Merge the email-service to version 2.2
authorSunghyun Kwon <sh0701.kwon@samsung.com>
Thu, 20 Feb 2014 05:58:45 +0000 (14:58 +0900)
committerSunghyun Kwon <sh0701.kwon@samsung.com>
Thu, 20 Feb 2014 05:58:45 +0000 (14:58 +0900)
Change-Id: I26816a6b43c134a80e64c6051f8e1205df672ff7
Signed-off-by: Sunghyun Kwon <sh0701.kwon@samsung.com>
108 files changed:
CMakeLists.txt
email-api/CMakeLists.txt
email-api/email-api-account.c
email-api/email-api-etc.c
email-api/email-api-init.c
email-api/email-api-mail.c
email-api/email-api-mailbox.c
email-api/email-api-network.c
email-api/email-api-rule.c
email-api/email-api-smime.c
email-api/include/email-api-account.h
email-api/include/email-api-etc.h
email-api/include/email-api-init.h
email-api/include/email-api-mail.h
email-api/include/email-api-mailbox.h
email-api/include/email-api-network.h
email-api/include/email-api-smime.h
email-common-use/CMakeLists.txt
email-common-use/email-convert.c
email-common-use/email-utilities.c
email-common-use/include/email-debug-log.h
email-common-use/include/email-errors.h
email-common-use/include/email-internal-types.h
email-common-use/include/email-types.h
email-common-use/include/email-utilities.h
email-core/CMakeLists.txt
email-core/email-core-account.c
email-core/email-core-alarm.c
email-core/email-core-api.c [deleted file]
email-core/email-core-cert.c
email-core/email-core-event.c
email-core/email-core-imap-idle.c
email-core/email-core-imap-mailbox.c
email-core/email-core-mail.c
email-core/email-core-mailbox-sync.c
email-core/email-core-mailbox.c
email-core/email-core-mime.c
email-core/email-core-mm-callbacks.c
email-core/email-core-signal.c
email-core/email-core-smime.c
email-core/email-core-smtp.c
email-core/email-core-sound.c
email-core/email-core-task-manager.c
email-core/email-core-tasks.c
email-core/email-core-utils.c
email-core/email-device/email-device.c
email-core/email-device/include/email-device.h
email-core/email-network/email-network.c
email-core/email-network/include/email-network.h
email-core/email-storage/email-storage.c
email-core/email-storage/include/email-storage.h
email-core/include/email-core-account.h
email-core/include/email-core-alarm.h
email-core/include/email-core-api.h [deleted file]
email-core/include/email-core-event.h
email-core/include/email-core-imap-mailbox.h
email-core/include/email-core-mail.h
email-core/include/email-core-mailbox-sync.h
email-core/include/email-core-mailbox.h
email-core/include/email-core-mime.h
email-core/include/email-core-signal.h
email-core/include/email-core-smtp.h
email-core/include/email-core-sound.h
email-core/include/email-core-utils.h
email-daemon/CMakeLists.txt
email-daemon/email-daemon-account.c
email-daemon/email-daemon-auto-poll.c
email-daemon/email-daemon-emn.c
email-daemon/email-daemon-etc.c
email-daemon/email-daemon-init.c
email-daemon/email-daemon-mail.c
email-daemon/email-daemon-mailbox.c
email-daemon/include/email-daemon-auto-poll.h
email-daemon/include/email-daemon-init.h
email-daemon/include/email-daemon.h
email-daemon/main.c
email-ipc/email-activation/email-dbus-activation.c
email-ipc/email-activation/include/email-dbus-activation.h
email-ipc/email-ipc-api.c
email-ipc/email-ipc-api/email-ipc-param-list.c
email-ipc/email-ipc-api/include/email-ipc-api-info.h
email-ipc/email-ipc-proxy.c
email-ipc/email-ipc-stub.c
email-ipc/email-proxy/email-proxy-main.c
email-ipc/email-proxy/email-proxy-socket.c
email-ipc/email-proxy/include/email-proxy-socket.h
email-ipc/email-socket/email-ipc-socket.c
email-ipc/email-stub/email-stub-main.c
email-ipc/email-stub/email-stub-socket.c
email-ipc/email-stub/email-stub-task-manager.c
email-ipc/email-stub/email-stub-task.c
email-ipc/include/email-ipc.h
email-service.pc.in
email-service.rule
email-service_PG.h
packaging/email-service.changes [deleted file]
packaging/email-service.manifest [deleted file]
packaging/email-service.spec
packaging/email.service
res/email-service.sql
utilities/CMakeLists.txt
utilities/test-application/include/testapp-utility.h
utilities/test-application/main.c
utilities/test-application/testapp-account.c
utilities/test-application/testapp-mail.c
utilities/test-application/testapp-mailbox.c
utilities/test-application/testapp-others.c
utilities/test-application/testapp-utility.c

index 4e34ff1..de6dd71 100755 (executable)
@@ -57,7 +57,8 @@ CONFIGURE_FILE(email-service.pc.in email-service.pc @ONLY)
 INSTALL(FILES ${CMAKE_BINARY_DIR}/email-service.pc DESTINATION ${LIB_INSTALL_DIR}/pkgconfig)
 
 # LICENSE file
-INSTALL(FILES ${CMAKE_SOURCE_DIR}/LICENSE.BSD DESTINATION /usr/share/license/email-service/LICENSE)
+INSTALL(FILES ${CMAKE_SOURCE_DIR}/LICENSE.BSD DESTINATION /usr/share/license RENAME email-service)
+
 INSTALL(FILES ${CMAKE_SOURCE_DIR}/email-service.rule DESTINATION /opt/etc/smack/accesses.d/)
 
 INSTALL(DIRECTORY ${CMAKE_SOURCE_DIR}/res/ DESTINATION /opt/usr/data/email/res/image FILES_MATCHING PATTERN "*.png")
index e2296f1..eea919f 100755 (executable)
@@ -27,7 +27,6 @@ SET(API-SRCS
        ${CMAKE_SOURCE_DIR}/email-api/email-api-rule.c
        ${CMAKE_SOURCE_DIR}/email-api/email-api-mailbox.c
        ${CMAKE_SOURCE_DIR}/email-api/email-api-init.c
-       ${CMAKE_SOURCE_DIR}/email-api/email-api-smime.c
        ${CMAKE_SOURCE_DIR}/email-api/email-api-etc.c
 )
 
@@ -71,10 +70,48 @@ SET(EMAIL-API-HEADERS
        ${CMAKE_SOURCE_DIR}/email-api/include/email-api-network.h
        ${CMAKE_SOURCE_DIR}/email-api/include/email-api-rule.h
        ${CMAKE_SOURCE_DIR}/email-api/include/email-api-etc.h
-       ${CMAKE_SOURCE_DIR}/email-api/include/email-api-smime.h
        ${CMAKE_SOURCE_DIR}/email-common-use/include/email-types.h
        ${CMAKE_SOURCE_DIR}/email-common-use/include/email-errors.h
 )
 
 INSTALL(FILES ${EMAIL-API-HEADERS} DESTINATION include/email-service)
 
+##########################################################
+# Define Email SMIME API   
+##########################################################
+
+SET(SMIME-API-LIB "email-smime-api")
+SET(SMIME-API-SRCS 
+       ${CMAKE_SOURCE_DIR}/email-api/email-api-smime.c
+)
+
+INCLUDE_DIRECTORIES(
+       ${CMAKE_SOURCE_DIR}/email-api/include
+)
+
+INCLUDE(FindPkgConfig)
+pkg_check_modules(smime_api_pkgs REQUIRED glib-2.0 dlog) 
+
+FOREACH(flag ${smime_api_pkgs_CFLAGS})
+       SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag}")
+ENDFOREACH(flag)
+
+SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${EXTRA_CFLAGS}")
+
+SET(CMAKE_EXE_LINKER_FLAGS "-Wl,--as-needed")
+
+ADD_LIBRARY(${SMIME-API-LIB} SHARED ${SMIME-API-SRCS})
+
+TARGET_LINK_LIBRARIES(${SMIME-API-LIB} ${api_pkgs_LDFLAGS} email-ipc email-storage email-smime)
+
+SET_TARGET_PROPERTIES(${SMIME-API-LIB} PROPERTIES SOVERSION ${VERSION_MAJOR})
+SET_TARGET_PROPERTIES(${SMIME-API-LIB} PROPERTIES VERSION ${VERSION})
+
+INSTALL(TARGETS ${SMIME-API-LIB} DESTINATION ${LIB_INSTALL_DIR} COMPONENT RuntimeLibraries)
+
+SET(SMIME-EMAIL-API-HEADERS
+       ${CMAKE_SOURCE_DIR}/email-api/include/email-api-smime.h
+)
+
+INSTALL(FILES ${SMIME-EMAIL-API-HEADERS} DESTINATION include/email-service)
+
index 5f88002..5bc0ebc 100755 (executable)
 /* API - Adds the Email Account */
 EXPORT_API int email_add_account(email_account_t* account)
 {
-       EM_DEBUG_FUNC_BEGIN("account[%p]", account);
+       EM_DEBUG_API_BEGIN ("account[%p]", account);
        char* local_account_stream = NULL;
        int size = 0;
        int err = EMAIL_ERROR_NONE;
        int ret_from_ipc = EMAIL_ERROR_NONE;
        HIPC_API hAPI = NULL;
 
-       if ( !account )  {
+       if (account == NULL || account->user_email_address == NULL || account->incoming_server_user_name == NULL || account->incoming_server_address == NULL||
+               account->outgoing_server_user_name == NULL || account->outgoing_server_address == NULL)  {
                EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
                return EMAIL_ERROR_INVALID_PARAM;
        }
@@ -98,14 +99,14 @@ FINISH_OFF:
        if(hAPI)
                emipc_destroy_email_api(hAPI);
 
-       EM_DEBUG_FUNC_END("ERROR CODE [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 
 EXPORT_API int email_free_account(email_account_t** account_list, int count)
 {
-       EM_DEBUG_FUNC_BEGIN("account_list[%p], count[%d]", account_list, count);
+       EM_DEBUG_FUNC_BEGIN ("account_list[%p] count[%d]", account_list, count); /* use only debugging */
 
        /*  default variable */
        int err = EMAIL_ERROR_NONE;
@@ -140,7 +141,7 @@ EXPORT_API int email_free_account(email_account_t** account_list, int count)
        }
 
 FINISH_OFF:
-       EM_DEBUG_FUNC_END("ERROR CODE [%d]", err);
+       EM_DEBUG_FUNC_END ("err[%d]", err);
        return err;
 }
 
@@ -148,7 +149,7 @@ FINISH_OFF:
 /* API - Delete  the Email Account */
 EXPORT_API int email_delete_account(int account_id)
 {
-       EM_DEBUG_FUNC_BEGIN("account_id[%d]", account_id);
+       EM_DEBUG_API_BEGIN ("account_id[%d]", account_id);
 
        int ret = 0;
        int err = EMAIL_ERROR_NONE;
@@ -181,14 +182,14 @@ EXPORT_API int email_delete_account(int account_id)
        emipc_destroy_email_api(hAPI);
 
        hAPI = NULL;
-       EM_DEBUG_FUNC_END("RETURN VALUE [%d], ERROR CODE [%d]", ret, err);
+       EM_DEBUG_API_END ("ret[%d] err[%d]", ret, err);
        return err;
 }
 
 /* API - Update  the Email Account */
 EXPORT_API int email_update_account(int account_id, email_account_t* new_account)
 {
-       EM_DEBUG_FUNC_BEGIN("account_id[%d], new_account[%p]", account_id, new_account);
+       EM_DEBUG_API_BEGIN ("account_id[%d] new_account[%p]", account_id, new_account);
 
        int ret = 0;
        int size = 0;
@@ -241,14 +242,14 @@ FINISH_OFF:
        emipc_destroy_email_api(hAPI);
        hAPI = NULL;
 
-       EM_DEBUG_FUNC_END("RETURN VALUE [%d], ERROR CODE [%d]", ret, err);
+       EM_DEBUG_API_END ("ret[%d] err[%d]", ret, err);
        return err;
 }
 
 /* API - Update  the Email Account */
 EXPORT_API int email_update_account_with_validation(int account_id, email_account_t* new_account)
 {
-       EM_DEBUG_FUNC_BEGIN("account_id[%d], new_account[%p]", account_id, new_account);
+       EM_DEBUG_API_BEGIN ("account_id[%d] new_account[%p]", account_id, new_account);
 
        int ret = 0;
        int size = 0;
@@ -300,7 +301,7 @@ EXPORT_API int email_update_account_with_validation(int account_id, email_accoun
        emipc_destroy_email_api(hAPI);
        hAPI = NULL;
 
-       EM_DEBUG_FUNC_END("RETURN VALUE [%d], ERROR CODE [%d]", ret, err);
+       EM_DEBUG_API_END ("ret[%d] err[%d]", ret, err);
        return err;
 }
 
@@ -308,7 +309,7 @@ EXPORT_API int email_update_account_with_validation(int account_id, email_accoun
 /* API - Get the account Information based on the account ID */
 EXPORT_API int email_get_account(int account_id, int pulloption, email_account_t** account)
 {
-       EM_DEBUG_FUNC_BEGIN();
+       EM_DEBUG_FUNC_BEGIN ("account_id[%d] pulloption[%d]", account_id, pulloption);
        int ret = 0;
        int err = EMAIL_ERROR_NONE;
        emstorage_account_tbl_t *account_tbl = NULL;
@@ -316,17 +317,32 @@ EXPORT_API int email_get_account(int account_id, int pulloption, email_account_t
        EM_IF_NULL_RETURN_VALUE(account_id, EMAIL_ERROR_INVALID_PARAM);
        EM_IF_NULL_RETURN_VALUE(account, EMAIL_ERROR_INVALID_PARAM);
 
+#ifdef __FEATURE_ACCESS_CONTROL__
+       err = em_check_db_privilege_by_pid(getpid());
+       if (err == EMAIL_ERROR_PERMISSION_DENIED) {
+               EM_DEBUG_LOG("permission denied");
+               goto FINISH_OFF;
+       }
+#endif
+
        if (pulloption == GET_FULL_DATA)
                pulloption = EMAIL_ACC_GET_OPT_FULL_DATA;
 
-       if (pulloption & EMAIL_ACC_GET_OPT_PASSWORD) {
-               pulloption = pulloption & (~(EMAIL_ACC_GET_OPT_PASSWORD));      /*  disable password -Can't obtain password by MAPI */
-               EM_DEBUG_LOG("change pulloption : disable password");
-       }
-
        if (!emstorage_get_account_by_id(account_id, pulloption, &account_tbl, true, &err)) {
-               EM_DEBUG_EXCEPTION("emstorage_get_account_by_id failed - %d", err);
-               goto FINISH_OFF;
+               if (err != EMAIL_ERROR_SECURED_STORAGE_FAILURE) {
+                       EM_DEBUG_EXCEPTION("emstorage_get_account_by_id failed - %d", err);
+                       goto FINISH_OFF;
+               }
+
+               if (pulloption & EMAIL_ACC_GET_OPT_PASSWORD) {
+                       pulloption = pulloption & (~(EMAIL_ACC_GET_OPT_PASSWORD));      /*  disable password -Can't obtain password by MAPI */
+                       EM_DEBUG_LOG("change pulloption : disable password");
+               }
+
+               if (!emstorage_get_account_by_id(account_id, pulloption, &account_tbl, true, &err)) {
+                       EM_DEBUG_EXCEPTION("emstorage_get_account_by_id failed - %d", err);
+                       goto FINISH_OFF;
+               }
        }
 
        *account = em_malloc(sizeof(email_account_t));
@@ -344,13 +360,13 @@ FINISH_OFF:
        if (account_tbl)
                emstorage_free_account(&account_tbl, 1, NULL);
 
-       EM_DEBUG_FUNC_END();
+       EM_DEBUG_FUNC_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_get_account_list(email_account_t** account_list, int* count)
 {
-       EM_DEBUG_FUNC_BEGIN();
+       EM_DEBUG_FUNC_BEGIN ();
 
        int err = EMAIL_ERROR_NONE, i = 0;
        emstorage_account_tbl_t *temp_account_tbl = NULL;
@@ -358,6 +374,14 @@ EXPORT_API int email_get_account_list(email_account_t** account_list, int* count
        EM_IF_NULL_RETURN_VALUE(account_list, EMAIL_ERROR_INVALID_PARAM);
        EM_IF_NULL_RETURN_VALUE(count, EMAIL_ERROR_INVALID_PARAM);
 
+#ifdef __FEATURE_ACCESS_CONTROL__
+       err = em_check_db_privilege_by_pid(getpid());
+       if (err == EMAIL_ERROR_PERMISSION_DENIED) {
+               EM_DEBUG_LOG("permission denied");
+               goto FINISH_OFF;
+       }
+#endif
+
        if (!emstorage_get_account_list(count, &temp_account_tbl , true, false, &err)) {
                EM_DEBUG_EXCEPTION("emstorage_get_account_list failed [%d]", err);
 
@@ -368,6 +392,7 @@ EXPORT_API int email_get_account_list(email_account_t** account_list, int* count
                *account_list = em_malloc(sizeof(email_account_t) * (*count));
                if(!*account_list) {
                        EM_DEBUG_EXCEPTION("allocation failed [%d]", err);
+                       err = EMAIL_ERROR_OUT_OF_MEMORY;
                        goto FINISH_OFF;
                }
                memset((void*)*account_list, 0, sizeof(email_account_t) * (*count));
@@ -380,14 +405,14 @@ FINISH_OFF:
 
        if(temp_account_tbl)
                emstorage_free_account(&temp_account_tbl, (*count), NULL);
-       EM_DEBUG_FUNC_END("err[%d]", err);
+       EM_DEBUG_FUNC_END ("err[%d]", err);
        return err;
 
 }
 
 EXPORT_API int email_validate_account(int account_id, int *handle)
 {
-       EM_DEBUG_FUNC_BEGIN("account_id[%d], handle[%p]", account_id, handle);
+       EM_DEBUG_API_BEGIN ("account_id[%d] handle[%p]", account_id, handle);
 
        int ret = 0;
        int err = EMAIL_ERROR_NONE;
@@ -421,20 +446,24 @@ EXPORT_API int email_validate_account(int account_id, int *handle)
        emipc_destroy_email_api(hAPI);
 
        hAPI = NULL;
-       EM_DEBUG_FUNC_END("err[%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 
 }
 
 EXPORT_API int email_validate_account_ex(email_account_t* account, int *handle)
 {
-       EM_DEBUG_FUNC_BEGIN("account[%p]", account);
+       EM_DEBUG_API_BEGIN ("account[%p]", account);
        char* local_account_stream = NULL;
        int ret = -1;
        int size = 0;
        int err = EMAIL_ERROR_NONE;
 
-       EM_IF_NULL_RETURN_VALUE(account, false);
+       if (account == NULL || account->user_email_address == NULL || account->incoming_server_user_name == NULL || account->incoming_server_address == NULL||
+               account->outgoing_server_user_name == NULL || account->outgoing_server_address == NULL)  {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
 
        /* create account information */
        HIPC_API hAPI = emipc_create_email_api(_EMAIL_API_VALIDATE_ACCOUNT_EX);
@@ -464,19 +493,23 @@ EXPORT_API int email_validate_account_ex(email_account_t* account, int *handle)
        emipc_destroy_email_api(hAPI);
        hAPI = NULL;
 
-       EM_DEBUG_FUNC_END("err[%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_add_account_with_validation(email_account_t* account, int *handle)
 {
-       EM_DEBUG_FUNC_BEGIN("account[%p]", account);
+       EM_DEBUG_API_BEGIN ("account[%p]", account);
        char* local_account_stream = NULL;
        int ret = -1;
        int size = 0;
        int err = EMAIL_ERROR_NONE;
 
-       EM_IF_NULL_RETURN_VALUE(account, false);
+       if (account == NULL || account->user_email_address == NULL || account->incoming_server_user_name == NULL || account->incoming_server_address == NULL||
+               account->outgoing_server_user_name == NULL || account->outgoing_server_address == NULL)  {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
 
        if(emstorage_check_duplicated_account(account, true, &err) == false) {
                EM_DEBUG_EXCEPTION("emstorage_check_duplicated_account failed (%d) ", err);
@@ -511,14 +544,15 @@ EXPORT_API int email_add_account_with_validation(email_account_t* account, int *
        emipc_destroy_email_api(hAPI);
        hAPI = NULL;
 
-       EM_DEBUG_FUNC_END("err[%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 
 EXPORT_API int email_backup_accounts_into_secure_storage(const char *file_name)
 {
-       EM_DEBUG_FUNC_BEGIN("file_name[%s]", file_name);
+       EM_DEBUG_API_BEGIN ("file_name[%p]", file_name);
+
        int ret = 0;
        int err = EMAIL_ERROR_NONE;
 
@@ -552,13 +586,13 @@ EXPORT_API int email_backup_accounts_into_secure_storage(const char *file_name)
        emipc_destroy_email_api(hAPI);
 
        hAPI = NULL;
-       EM_DEBUG_FUNC_END("err[%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_restore_accounts_from_secure_storage(const char * file_name)
 {
-       EM_DEBUG_FUNC_BEGIN("file_name[%s]", file_name);
+       EM_DEBUG_API_BEGIN ("file_name[%p]", file_name);
        int ret = 0;
        int err = EMAIL_ERROR_NONE;
 
@@ -592,15 +626,16 @@ EXPORT_API int email_restore_accounts_from_secure_storage(const char * file_name
        emipc_destroy_email_api(hAPI);
 
        hAPI = NULL;
-       EM_DEBUG_FUNC_END("err[%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_get_password_length_of_account(const int account_id, int *password_length)
 {
-       EM_DEBUG_FUNC_BEGIN("account_id[%d], password_length[%p]", account_id, password_length);
+       EM_DEBUG_API_BEGIN ("account_id[%d] password_length[%p]", account_id, password_length);
        int ret = 0;
        int err = EMAIL_ERROR_NONE;
+       int password_type = 1;
 
        if (account_id <= 0 || password_length == NULL)  {
                EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
@@ -618,6 +653,12 @@ EXPORT_API int email_get_password_length_of_account(const int account_id, int *p
                EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
        }
 
+       /* password type */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&password_type, sizeof(int))) {
+               EM_DEBUG_EXCEPTION(" emipc_add_parameter account_id  failed ");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+       }
+
        if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
                EM_DEBUG_EXCEPTION(" emipc_execute_proxy_api failed ");
                EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_IPC_SOCKET_FAILURE);
@@ -630,13 +671,13 @@ EXPORT_API int email_get_password_length_of_account(const int account_id, int *p
        emipc_destroy_email_api(hAPI);
 
        hAPI = NULL;
-       EM_DEBUG_FUNC_END("*password_length[%d]", *password_length);
+       EM_DEBUG_API_END ("*password_length[%d]", *password_length);
        return err;
 }
 
 EXPORT_API int email_query_server_info(const char* domain_name, email_server_info_t **result_server_info)
 {
-       EM_DEBUG_FUNC_BEGIN("domain_name [%s], result_server_info [%p]", domain_name, result_server_info);
+       EM_DEBUG_API_BEGIN ("domain_name[%p] result_server_info[%p]", domain_name, result_server_info);
        int err = EMAIL_ERROR_NONE;
 
        if (!domain_name || !result_server_info)  {
@@ -647,14 +688,14 @@ EXPORT_API int email_query_server_info(const char* domain_name, email_server_inf
 
        err = emcore_query_server_info(domain_name, result_server_info);
 
-       EM_DEBUG_FUNC_END("err[%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 
 EXPORT_API int email_free_server_info(email_server_info_t **result_server_info)
 {
-       EM_DEBUG_FUNC_BEGIN("result_server_info [%p]", result_server_info);
+       EM_DEBUG_API_BEGIN ("result_server_info[%p]", result_server_info);
        int err = EMAIL_ERROR_NONE;
 
        if (!result_server_info)  {
@@ -665,14 +706,16 @@ EXPORT_API int email_free_server_info(email_server_info_t **result_server_info)
 
        err = emcore_free_server_info(result_server_info);
 
-       EM_DEBUG_FUNC_END("ret[%d]", err);
+       EM_DEBUG_API_END ("ret[%d]", err);
        return err;
 }
 
 EXPORT_API int email_update_notification_bar(int account_id)
 {
-       EM_DEBUG_FUNC_BEGIN("account_id [%d]", account_id);
+       EM_DEBUG_API_BEGIN("account_id [%d]", account_id);
        int err = EMAIL_ERROR_NONE;
+       int total_mail_count = 0;
+       int unread_mail_count = 0;
 
        if (account_id == 0)  {
                EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
@@ -690,6 +733,17 @@ EXPORT_API int email_update_notification_bar(int account_id)
                EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
        }
 
+       /* total_mail_count */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&total_mail_count, sizeof(int))) {
+               EM_DEBUG_EXCEPTION(" emipc_add_parameter account_id  failed");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+       }
+
+       /* unread_mail_count */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&unread_mail_count, sizeof(int))) {
+               EM_DEBUG_EXCEPTION(" emipc_add_parameter account_id  failed");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+       }
        if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
                EM_DEBUG_EXCEPTION(" emipc_execute_proxy_api failed ");
                EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_IPC_SOCKET_FAILURE);
@@ -699,40 +753,40 @@ EXPORT_API int email_update_notification_bar(int account_id)
        emipc_destroy_email_api(hAPI);
 
        hAPI = NULL;
-       EM_DEBUG_FUNC_END("ret[%d]", err);
+       EM_DEBUG_API_END ("ret[%d]", err);
        return err;
 }
 
 
 EXPORT_API int email_clear_all_notification_bar()
 {
-       EM_DEBUG_FUNC_BEGIN();
+       EM_DEBUG_FUNC_BEGIN ();
        int err = EMAIL_ERROR_NONE;
 
        err = emcore_clear_all_notifications();
 
-       EM_DEBUG_FUNC_END("ret[%d]", err);
+       EM_DEBUG_FUNC_END ("ret[%d]", err);
        return err;
 }
 
 EXPORT_API int email_save_default_account_id(int input_account_id)
 {
-       EM_DEBUG_FUNC_BEGIN("input_account_id [%d]", input_account_id);
+       EM_DEBUG_API_BEGIN ("input_account_id [%d]", input_account_id);
        int err = EMAIL_ERROR_NONE;
 
        err = emcore_save_default_account_id(input_account_id);
 
-       EM_DEBUG_FUNC_END("ret[%d]", err);
+       EM_DEBUG_API_END ("ret[%d]", err);
        return err;
 }
 
 EXPORT_API int email_load_default_account_id(int *output_account_id)
 {
-       EM_DEBUG_FUNC_BEGIN("output_account_id [%p]", output_account_id);
+       EM_DEBUG_FUNC_BEGIN ("output_account_id[%p]", output_account_id);
        int err = EMAIL_ERROR_NONE;
 
        err = emcore_load_default_account_id(output_account_id);
 
-       EM_DEBUG_FUNC_END("ret[%d]", err);
+       EM_DEBUG_FUNC_END ("ret[%d]", err);
        return err;
 }
index 258dd6a..4c5a1cd 100755 (executable)
@@ -40,7 +40,7 @@
 
 EXPORT_API int email_show_user_message(int id, email_action_t action, int error_code)
 {
-       EM_DEBUG_FUNC_BEGIN("id [%d], action [%d], error_code [%d]", id, action, error_code);
+       EM_DEBUG_API_BEGIN ("id[%d] action[%d] error_code[%d]", id, action, error_code);
        int err = EMAIL_ERROR_NONE;
 
        if(id < 0 || action < 0) {
@@ -78,13 +78,13 @@ EXPORT_API int email_show_user_message(int id, email_action_t action, int error_
        emipc_destroy_email_api(hAPI);
        hAPI = NULL;
 
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_parse_mime_file(char *eml_file_path, email_mail_data_t **output_mail_data, email_attachment_data_t **output_attachment_data, int *output_attachment_count)
 {
-       EM_DEBUG_FUNC_BEGIN("eml_file_path : [%s], output_mail_data : [%p], output_attachment_data : [%p]", eml_file_path, output_mail_data, output_attachment_data);
+       EM_DEBUG_API_BEGIN ("eml_file_path[%p] output_mail_data[%p] output_attachment_data[%p]", eml_file_path, output_mail_data, output_attachment_data);
        int err = EMAIL_ERROR_NONE;
 
        EM_IF_NULL_RETURN_VALUE(eml_file_path, EMAIL_ERROR_INVALID_PARAM);
@@ -92,22 +92,24 @@ EXPORT_API int email_parse_mime_file(char *eml_file_path, email_mail_data_t **ou
        if (!emcore_parse_mime_file_to_mail(eml_file_path, output_mail_data, output_attachment_data, output_attachment_count, &err) || !*output_mail_data)
                EM_DEBUG_EXCEPTION("emcore_parse_mime_file_to_mail failed [%d]", err);
 
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_write_mime_file(email_mail_data_t *input_mail_data, email_attachment_data_t *input_attachment_data, int input_attachment_count, char **output_file_path)
 {
-       EM_DEBUG_FUNC_BEGIN("input_mail_data : [%p], input_attachment_data : [%p], input_attachment_count : [%d]", input_mail_data, input_attachment_data, input_attachment_count);
+       EM_DEBUG_API_BEGIN ("input_mail_data[%p] input_attachment_data[%p] input_attachment_count[%d]", input_mail_data, input_attachment_data, input_attachment_count);
 
-       int err = EMAIL_ERROR_NONE;
-       int size = 0;
+       int   err = EMAIL_ERROR_NONE;
+       int   size = 0;
+       int  *ret_nth_value = 0;
        char *p_output_file_path = NULL;
        char *mail_data_stream = NULL;
        char *attachment_data_list_stream = NULL;
        HIPC_API hAPI = NULL;
 
        EM_IF_NULL_RETURN_VALUE(input_mail_data, EMAIL_ERROR_INVALID_PARAM);
+       EM_IF_NULL_RETURN_VALUE(output_file_path, EMAIL_ERROR_INVALID_PARAM);
 
        hAPI = emipc_create_email_api(_EMAIL_API_WRITE_MIME_FILE);
        if (!hAPI) {
@@ -137,13 +139,13 @@ EXPORT_API int email_write_mime_file(email_mail_data_t *input_mail_data, email_a
        }
 
        if (*output_file_path && (size = EM_SAFE_STRLEN(*output_file_path)) > 0) {
-               EM_DEBUG_LOG("output_file_path : [%s] size : [%d]", *output_file_path, size);
+               EM_DEBUG_LOG_SEC("output_file_path : [%s] size : [%d]", *output_file_path, size);
                size = size + 1;
        } else {
                size = 0;
        }
 
-       if (!emipc_add_dynamic_parameter(hAPI, ePARAMETER_IN, *output_file_path, size)) {
+       if (!emipc_add_parameter(hAPI, ePARAMETER_IN, *output_file_path, size)) {
                EM_DEBUG_EXCEPTION("emipc_add_dynamic_parameter failed");
                err = EMAIL_ERROR_OUT_OF_MEMORY;
                goto FINISH_OFF;
@@ -155,37 +157,43 @@ EXPORT_API int email_write_mime_file(email_mail_data_t *input_mail_data, email_a
                goto FINISH_OFF;
        }
 
-       size = emipc_get_parameter_length(hAPI, ePARAMETER_OUT, 0);
-       if (size > 0) {
-               p_output_file_path = (char *)em_malloc(size);
-               if (p_output_file_path == NULL) {
-                       err = EMAIL_ERROR_OUT_OF_MEMORY;
-                       goto FINISH_OFF;
-               }
-
-               if ((err = emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, size, p_output_file_path)) != EMAIL_ERROR_NONE) {
-                       EM_DEBUG_EXCEPTION("emipc_get_parameter failed : [%d]", err);
-                       goto FINISH_OFF;
+       if ((ret_nth_value = (int*)emipc_get_nth_parameter_data(hAPI, ePARAMETER_OUT, 0))) {
+               err = *ret_nth_value;
+
+               if (err == EMAIL_ERROR_NONE) {
+                       size = emipc_get_parameter_length(hAPI, ePARAMETER_OUT, 1);
+                       if (size > 0) {
+                               p_output_file_path = (char *)em_malloc(size);
+                               if (p_output_file_path == NULL) {
+                                       err = EMAIL_ERROR_OUT_OF_MEMORY;
+                                       goto FINISH_OFF;
+                               }
+
+                               if ((err = emipc_get_parameter(hAPI, ePARAMETER_OUT, 1, size, p_output_file_path)) != EMAIL_ERROR_NONE) {
+                                       EM_DEBUG_EXCEPTION("emipc_get_parameter failed : [%d]", err);
+                                       goto FINISH_OFF;
+                               }
+                       }
                }
        }
-       
-       *output_file_path = p_output_file_path; 
+
+       EM_SAFE_FREE(*output_file_path);
+       *output_file_path = EM_SAFE_STRDUP(p_output_file_path); 
 
 FINISH_OFF:
 
        if (hAPI)
                emipc_destroy_email_api(hAPI);
 
-       if (err != EMAIL_ERROR_NONE)
-               EM_SAFE_FREE(p_output_file_path);
+       EM_SAFE_FREE(p_output_file_path);
 
-       EM_DEBUG_FUNC_END("err : [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_delete_parsed_data(email_mail_data_t *input_mail_data)
 {
-       EM_DEBUG_FUNC_BEGIN("mail_data : [%p]", input_mail_data);
+       EM_DEBUG_API_BEGIN ("mail_data[%p]", input_mail_data);
        int err = EMAIL_ERROR_NONE;
 
        EM_IF_NULL_RETURN_VALUE(input_mail_data, EMAIL_ERROR_INVALID_PARAM);
@@ -193,13 +201,13 @@ EXPORT_API int email_delete_parsed_data(email_mail_data_t *input_mail_data)
        if (!emcore_delete_parsed_data(input_mail_data, &err))
                EM_DEBUG_EXCEPTION("emcore_delete_parsed_data failed [%d]", err);
 
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_get_mime_entity(char *mime_path, char **mime_entity)
 {
-       EM_DEBUG_FUNC_BEGIN("mime_path : [%s]", mime_path);
+       EM_DEBUG_API_BEGIN ("mime_path[%p]", mime_path);
        int err = EMAIL_ERROR_NONE;
 
        EM_IF_NULL_RETURN_VALUE(mime_path, EMAIL_ERROR_INVALID_PARAM);
@@ -207,7 +215,7 @@ EXPORT_API int email_get_mime_entity(char *mime_path, char **mime_entity)
        if (!emcore_get_mime_entity(mime_path, mime_entity, &err)) 
                EM_DEBUG_EXCEPTION("emcore_get_mime_entity failed [%d]", err);
 
-       EM_DEBUG_FUNC_END();
+       EM_DEBUG_API_END ();
        return err;
 }
 
index 0adc2c3..cfb2aa9 100755 (executable)
 #include "email-storage.h"
 #include "email-ipc.h"
 #include "email-core-task-manager.h"
+#include "email-utilities.h"
 #include <sqlite3.h>
 
 
 EXPORT_API int email_open_db(void)
 {
-       EM_DEBUG_FUNC_BEGIN();
+       EM_DEBUG_API_BEGIN ();
        int error  = EMAIL_ERROR_NONE;
        
+#ifdef __FEATURE_ACCESS_CONTROL__
+       error = em_check_db_privilege_by_pid(getpid());
+       if (error == EMAIL_ERROR_PERMISSION_DENIED) {
+               EM_DEBUG_EXCEPTION ("permission denied");
+               return error;
+       }
+#endif
+
        if (emstorage_db_open(&error) == NULL)
                EM_DEBUG_EXCEPTION("emstorage_db_open failed [%d]", error);
-
        
-       EM_DEBUG_FUNC_END("error [%d]", error);
+       EM_DEBUG_API_END ("err[%d]", error);
 
        return error;   
 }
 
 EXPORT_API int email_close_db(void)
 {
-       EM_DEBUG_FUNC_BEGIN();
+       EM_DEBUG_API_BEGIN ();
        int error  = EMAIL_ERROR_NONE;
 
        if ( !emstorage_db_close(&error)) 
                EM_DEBUG_EXCEPTION("emstorage_db_close failed [%d]", error);
 
-       EM_DEBUG_FUNC_END("error [%d]", error);
+       EM_DEBUG_API_END ("err[%d]", error);
        return error;   
 }
 
 
 EXPORT_API int email_service_begin(void)
 {
-       EM_DEBUG_FUNC_BEGIN();
+       EM_DEBUG_API_BEGIN ();
        int ret = -1;
 
        signal(SIGPIPE, SIG_IGN); /* to ignore signal 13(SIGPIPE) */
@@ -77,19 +85,19 @@ EXPORT_API int email_service_begin(void)
 
        emcore_init_task_handler_array();
 
-       EM_DEBUG_FUNC_END("err[%d]", ret);
+       EM_DEBUG_API_END ("err[%d]", ret);
        return ret;
 }
 
 
 EXPORT_API int email_service_end(void)
 {
-       EM_DEBUG_FUNC_BEGIN();
+       EM_DEBUG_API_BEGIN ();
        int ret = -1;
        
        ret = emipc_finalize_proxy();
-       if (ret != EMAIL_ERROR_NONE)
-               EM_DEBUG_FUNC_END("err[%d]", ret);
+
+       EM_DEBUG_API_END ("err[%d]", ret);
        
        return ret;
 }
@@ -99,20 +107,28 @@ EXPORT_API int email_service_end(void)
 
 EXPORT_API int email_init_storage(void)
 {
-       EM_DEBUG_FUNC_BEGIN();
+       EM_DEBUG_API_BEGIN ();
        int error  = EMAIL_ERROR_NONE;
        
+#ifdef __FEATURE_ACCESS_CONTROL__
+       error = em_check_db_privilege_by_pid(getpid());
+       if (error == EMAIL_ERROR_PERMISSION_DENIED) {
+               EM_DEBUG_LOG("permission denied");
+               return error;
+       }
+#endif
+
        if (!emstorage_create_table(EMAIL_CREATE_DB_CHECK, &error))  {
                EM_DEBUG_EXCEPTION("emstorage_create_table failed [%d]", error);
        }
 
-       EM_DEBUG_FUNC_END("error[%d]", error);
+       EM_DEBUG_API_END ("err[%d]", error);
        return error;
 }
 
 EXPORT_API int email_ping_service(void)
 {
-       EM_DEBUG_FUNC_BEGIN();
+       EM_DEBUG_API_BEGIN ();
        int error  = EMAIL_ERROR_NONE;
        HIPC_API hAPI = emipc_create_email_api(_EMAIL_API_PING_SERVICE);
 
@@ -129,6 +145,6 @@ EXPORT_API int email_ping_service(void)
 
        hAPI = NULL;
 
-       EM_DEBUG_FUNC_END("err[%d]", error);
+       EM_DEBUG_API_END ("err[%d]", error);
        return error;
 }
index 1c29e5b..579f082 100755 (executable)
@@ -43,7 +43,9 @@
 #include "email-core-account.h"
 #include "email-core-task-manager.h"
 #include "email-storage.h"
+#include "email-core-signal.h"
 #include "email-utilities.h"
+#include "email-core-smime.h"
 #include "db-util.h"
 
 #define  DIR_SEPERATOR_CH '/'
@@ -54,7 +56,7 @@
 
 EXPORT_API int email_add_mail(email_mail_data_t *input_mail_data, email_attachment_data_t *input_attachment_data_list, int input_attachment_count, email_meeting_request_t* input_meeting_request, int input_from_eas)
 {
-       EM_DEBUG_FUNC_BEGIN("input_mail_data[%p], input_attachment_data_list[%p], input_attachment_count [%d], input_meeting_request [%p], input_from_eas [%d]", input_mail_data, input_attachment_data_list, input_attachment_count, input_meeting_request, input_from_eas);
+       EM_DEBUG_API_BEGIN ("input_mail_data[%p] input_attachment_data_list[%p] input_attachment_count[%d] input_meeting_request[%p] input_from_eas[%d]", input_mail_data, input_attachment_data_list, input_attachment_count, input_meeting_request, input_from_eas);
 
        EM_IF_NULL_RETURN_VALUE(input_mail_data,               EMAIL_ERROR_INVALID_PARAM);
        EM_IF_NULL_RETURN_VALUE(input_mail_data->account_id,   EMAIL_ERROR_INVALID_PARAM);
@@ -66,13 +68,27 @@ EXPORT_API int email_add_mail(email_mail_data_t *input_mail_data, email_attachme
        }
 
        int       err = EMAIL_ERROR_NONE;
+       int      *ret_nth_value = NULL;
        int       size = 0;
+       char     *rfc822_file = NULL;
        char     *mail_data_stream = NULL;
        char     *attachment_data_list_stream  = NULL;
        char     *meeting_request_stream = NULL;
        HIPC_API  hAPI = NULL;
        
        if(input_from_eas == 0) { /* native emails */
+               if ((input_mail_data->smime_type != EMAIL_SMIME_NONE) && (input_mail_data->mailbox_type != EMAIL_MAILBOX_TYPE_DRAFT)) {
+                       if (!emcore_make_rfc822_file(input_mail_data, input_attachment_data_list, input_attachment_count, &rfc822_file, &err)) {
+                               EM_DEBUG_EXCEPTION("emcore_make_rfc822_file failed [%d]", err);
+                               goto FINISH_OFF;
+                       }
+               
+                       input_mail_data->file_path_mime_entity = EM_SAFE_STRDUP(emcore_set_mime_entity(rfc822_file));
+                       
+                       emstorage_delete_file(rfc822_file, NULL);
+                       EM_SAFE_FREE(rfc822_file);      
+               }
+
                hAPI = emipc_create_email_api(_EMAIL_API_ADD_MAIL);
 
                if(!hAPI) {
@@ -127,16 +143,30 @@ EXPORT_API int email_add_mail(email_mail_data_t *input_mail_data, email_attachme
                }
 
                /* get result from service */
-               err = *((int*)emipc_get_nth_parameter_data(hAPI, ePARAMETER_OUT, 0));
-               if(err == EMAIL_ERROR_NONE) {
-                       /* result mail_id */
-                       input_mail_data->mail_id = *((int*)emipc_get_nth_parameter_data(hAPI, ePARAMETER_OUT, 1));
-                       /* result thread_id */
-                       input_mail_data->thread_id = *((int*)emipc_get_nth_parameter_data(hAPI, ePARAMETER_OUT, 2));
+               if ((ret_nth_value = (int*)emipc_get_nth_parameter_data(hAPI, ePARAMETER_OUT, 0))) {
+                       err = *ret_nth_value;
+                       
+                       if (err == EMAIL_ERROR_NONE) {
+                               if ((ret_nth_value = (int *)emipc_get_nth_parameter_data(hAPI, ePARAMETER_OUT, 1))) {
+                                       input_mail_data->mail_id = *ret_nth_value;
+                               } else {
+                                       err = EMAIL_ERROR_IPC_SOCKET_FAILURE;
+                                       goto FINISH_OFF;
+                               }
+                               
+                               if ((ret_nth_value = (int *)emipc_get_nth_parameter_data(hAPI, ePARAMETER_OUT, 2))) {
+                                       input_mail_data->thread_id = *ret_nth_value;
+                               } else {
+                                       err = EMAIL_ERROR_IPC_SOCKET_FAILURE;
+                                       goto FINISH_OFF;
+                               }
+                       }
+               } else {
+                       err = EMAIL_ERROR_IPC_SOCKET_FAILURE;
+                       goto FINISH_OFF;
                }
-       } 
-       else { /* take care of mails from eas */
-               err = emcore_add_mail(input_mail_data, input_attachment_data_list, input_attachment_count, input_meeting_request, input_from_eas);
+       } else { /* take care of mails from eas */
+               err = emcore_add_mail(input_mail_data, input_attachment_data_list, input_attachment_count, input_meeting_request, input_from_eas, false);
                if(err != EMAIL_ERROR_NONE) {
                        EM_DEBUG_EXCEPTION("emcore_add_mail failed [%d]", err);
                        goto FINISH_OFF;
@@ -147,14 +177,14 @@ FINISH_OFF:
        if(hAPI) 
                emipc_destroy_email_api(hAPI);
 
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 
 }
 
 EXPORT_API int email_add_read_receipt(int input_read_mail_id, int *output_receipt_mail_id)
 {
-       EM_DEBUG_FUNC_BEGIN("input_read_mail_id [%d], output_receipt_mail_id [%p]", input_read_mail_id, output_receipt_mail_id);
+       EM_DEBUG_API_BEGIN ("input_read_mail_id[%d] output_receipt_mail_id[%p]", input_read_mail_id, output_receipt_mail_id);
 
        EM_IF_NULL_RETURN_VALUE(output_receipt_mail_id, EMAIL_ERROR_INVALID_PARAM);
 
@@ -188,7 +218,7 @@ EXPORT_API int email_add_read_receipt(int input_read_mail_id, int *output_receip
 
        hAPI = NULL;
 
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
@@ -272,7 +302,7 @@ FINISH_OFF:
 
 EXPORT_API int email_update_mail(email_mail_data_t *input_mail_data, email_attachment_data_t *input_attachment_data_list, int input_attachment_count, email_meeting_request_t* input_meeting_request, int input_from_eas)
 {
-       EM_DEBUG_FUNC_BEGIN("input_mail_data[%p], input_attachment_data_list[%p], input_attachment_count [%d], input_meeting_request [%p], input_from_eas [%d]", input_mail_data, input_attachment_data_list, input_attachment_count, input_meeting_request, input_from_eas);
+       EM_DEBUG_API_BEGIN ("input_mail_data[%p] input_attachment_data_list[%p] input_attachment_count[%d] input_meeting_request[%p] input_from_eas[%d]", input_mail_data, input_attachment_data_list, input_attachment_count, input_meeting_request, input_from_eas);
 
        EM_IF_NULL_RETURN_VALUE(input_mail_data,               EMAIL_ERROR_INVALID_PARAM);
        EM_IF_NULL_RETURN_VALUE(input_mail_data->account_id,   EMAIL_ERROR_INVALID_PARAM);
@@ -373,13 +403,13 @@ FINISH_OFF:
 
        EM_SAFE_FREE(mail_data_stream);
 
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_update_mail_attribute(int input_account_id, int *input_mail_id_array, int input_mail_id_count, email_mail_attribute_type input_attribute_type, email_mail_attribute_value_t input_value)
 {
-       EM_DEBUG_FUNC_BEGIN("input_account_id[%d] input_mail_id_array[%p] input_mail_id_count[%d] input_attribute_type[%d]", input_account_id, input_mail_id_array, input_mail_id_count, input_attribute_type);
+       EM_DEBUG_API_BEGIN ("input_account_id[%d] input_mail_id_array[%p] input_mail_id_count[%d] input_attribute_type[%d]", input_account_id, input_mail_id_array, input_mail_id_count, input_attribute_type);
 
        int err = EMAIL_ERROR_NONE;
        task_parameter_EMAIL_SYNC_TASK_UPDATE_ATTRIBUTE task_parameter;
@@ -414,13 +444,13 @@ EXPORT_API int email_update_mail_attribute(int input_account_id, int *input_mail
 
 FINISH_OFF:
 
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_clear_mail_data()
 {
-       EM_DEBUG_FUNC_BEGIN();
+       EM_DEBUG_API_BEGIN ();
        int err = EMAIL_ERROR_NONE;
        
        HIPC_API hAPI = emipc_create_email_api(_EMAIL_API_CLEAR_DATA);  
@@ -436,14 +466,14 @@ EXPORT_API int email_clear_mail_data()
        if(hAPI)
                emipc_destroy_email_api(hAPI);
 
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 
 EXPORT_API int email_count_mail(email_list_filter_t *input_filter_list, int input_filter_count, int *output_total_mail_count, int *output_unseen_mail_count)
 {
-       EM_DEBUG_FUNC_BEGIN("input_filter_list[%p], input_filter_count [%d], output_total_mail_count[%p], output_unseen_mail_count[%p]", input_filter_list, input_filter_count, output_total_mail_count, output_unseen_mail_count);
+       EM_DEBUG_API_BEGIN ("input_filter_list[%p] input_filter_count[%d] output_total_mail_count[%p] output_unseen_mail_count[%p]", input_filter_list, input_filter_count, output_total_mail_count, output_unseen_mail_count);
        
        int total_count = 0;
        int unread = 0;
@@ -455,6 +485,14 @@ EXPORT_API int email_count_mail(email_list_filter_t *input_filter_list, int inpu
        EM_IF_NULL_RETURN_VALUE(output_total_mail_count, EMAIL_ERROR_INVALID_PARAM);
        EM_IF_NULL_RETURN_VALUE(output_unseen_mail_count, EMAIL_ERROR_INVALID_PARAM);
 
+#ifdef __FEATURE_ACCESS_CONTROL__
+       err = em_check_db_privilege_by_pid(getpid());
+       if (err == EMAIL_ERROR_PERMISSION_DENIED) {
+               EM_DEBUG_LOG("permission denied");
+               goto FINISH_OFF;
+       }
+#endif
+
        if( (err = emstorage_write_conditional_clause_for_getting_mail_list(input_filter_list, input_filter_count, NULL, 0, -1, -1, &conditional_clause_string)) != EMAIL_ERROR_NONE) {
                EM_DEBUG_EXCEPTION("emstorage_write_conditional_clause_for_getting_mail_list failed[%d]", err);
                goto FINISH_OFF;
@@ -470,14 +508,14 @@ EXPORT_API int email_count_mail(email_list_filter_t *input_filter_list, int inpu
 
 FINISH_OFF:
 
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 
 EXPORT_API int email_delete_mail(int input_mailbox_id, int *input_mail_ids, int input_num, int input_from_server)
 {
-       EM_DEBUG_FUNC_BEGIN("input_mailbox_id[%d], input_mail_ids[%p], input_num[%d], input_from_server[%d]", input_mailbox_id, input_mail_ids, input_num, input_from_server);
+       EM_DEBUG_API_BEGIN ("input_mailbox_id[%d] input_mail_ids[%p] input_num[%d] input_from_server[%d]", input_mailbox_id, input_mail_ids, input_num, input_from_server);
 
        int err = EMAIL_ERROR_NONE;
        HIPC_API hAPI = NULL;
@@ -544,14 +582,14 @@ FINISH_OFF:
        if(hAPI)
                emipc_destroy_email_api(hAPI);
 
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 
 EXPORT_API int email_delete_all_mails_in_mailbox(int input_mailbox_id, int input_from_server)
 {
-       EM_DEBUG_FUNC_BEGIN("input_mailbox_id[%d], input_from_server[%d]", input_mailbox_id, input_from_server);
+       EM_DEBUG_API_BEGIN ("input_mailbox_id[%d] input_from_server[%d]", input_mailbox_id, input_from_server);
 
        int err = EMAIL_ERROR_NONE;
        HIPC_API hAPI = NULL;
@@ -595,13 +633,13 @@ FINISH_OFF:
        if(hAPI)        
                emipc_destroy_email_api(hAPI);
        
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_add_attachment(int mail_id, email_attachment_data_t* attachment)
 {
-       EM_DEBUG_FUNC_BEGIN("mail_id[%d], attachment[%p]", mail_id, attachment);
+       EM_DEBUG_API_BEGIN ("mail_id[%d] attachment[%p]", mail_id, attachment);
        int err = EMAIL_ERROR_NONE;
        char *attchment_stream = NULL;
        int size = 0;
@@ -659,14 +697,14 @@ FINISH_OFF:
        if(hAPI)
                emipc_destroy_email_api(hAPI);
        
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
  }
 
 
 EXPORT_API int email_delete_attachment(int attachment_id)
 {
-       EM_DEBUG_FUNC_BEGIN("attachment_id[%d]", attachment_id);
+       EM_DEBUG_API_BEGIN ("attachment_id[%d]", attachment_id);
        int err = EMAIL_ERROR_NONE;
        HIPC_API hAPI = NULL;
        
@@ -700,6 +738,7 @@ FINISH_OFF:
        if(hAPI)
                emipc_destroy_email_api(hAPI);
 
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
@@ -709,14 +748,22 @@ FINISH_OFF:
 
 EXPORT_API int email_query_mails(char *conditional_clause_string, email_mail_data_t** mail_list,  int *result_count)
 {
-       EM_DEBUG_FUNC_BEGIN("conditional_clause_string [%s], mail_list [%p], result_count [%p]", conditional_clause_string, mail_list, result_count);
+       EM_DEBUG_API_BEGIN ("conditional_clause_string[%s] mail_list[%p] result_count[%p]", conditional_clause_string, mail_list, result_count);
 
        int err = EMAIL_ERROR_NONE;
-       emstorage_mail_tbl_t *result_mail_tbl;
+       emstorage_mail_tbl_t *result_mail_tbl = NULL;
        
        EM_IF_NULL_RETURN_VALUE(result_count, EMAIL_ERROR_INVALID_PARAM);
        EM_IF_NULL_RETURN_VALUE(conditional_clause_string, EMAIL_ERROR_INVALID_PARAM);
 
+#ifdef __FEATURE_ACCESS_CONTROL__
+       err = em_check_db_privilege_by_pid(getpid());
+       if (err == EMAIL_ERROR_PERMISSION_DENIED) {
+               EM_DEBUG_LOG("permission denied");
+               goto FINISH_OFF;
+       }
+#endif
+
        if (!emstorage_query_mail_tbl(conditional_clause_string, true, &result_mail_tbl, result_count, &err)) {
                EM_DEBUG_EXCEPTION("emstorage_query_mail_list failed [%d]", err);
 
@@ -729,29 +776,37 @@ EXPORT_API int email_query_mails(char *conditional_clause_string, email_mail_dat
        }
 
 FINISH_OFF:    
-       if(result_mail_tbl && !emstorage_free_mail(&result_mail_tbl, *result_count, &err))
-               EM_DEBUG_EXCEPTION("emstorage_free_mail failed [%d]", err);
+       if(result_mail_tbl && !emstorage_free_mail(&result_mail_tbl, *result_count, NULL))
+               EM_DEBUG_EXCEPTION("emstorage_free_mail failed");
 
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_query_mail_list(char *input_conditional_clause_string, email_mail_list_item_t** output_mail_list,  int *output_result_count)
 {
-       EM_DEBUG_FUNC_BEGIN("input_conditional_clause_string [%s], output_mail_list [%p], output_result_count [%p]", input_conditional_clause_string, output_mail_list, output_result_count);
+       EM_DEBUG_API_BEGIN ("input_conditional_clause_string[%s] output_mail_list[%p] output_result_count[%p]", input_conditional_clause_string, output_mail_list, output_result_count);
 
        int err = EMAIL_ERROR_NONE;
        
        EM_IF_NULL_RETURN_VALUE(input_conditional_clause_string, EMAIL_ERROR_INVALID_PARAM);
        EM_IF_NULL_RETURN_VALUE(output_result_count, EMAIL_ERROR_INVALID_PARAM);
 
+#ifdef __FEATURE_ACCESS_CONTROL__
+       err = em_check_db_privilege_by_pid(getpid());
+       if (err == EMAIL_ERROR_PERMISSION_DENIED) {
+               EM_DEBUG_LOG("permission denied");
+               goto FINISH_OFF;
+       }
+#endif
+
        if (!emstorage_query_mail_list(input_conditional_clause_string, true, output_mail_list, output_result_count, &err)) {
                EM_DEBUG_EXCEPTION("emstorage_query_mail_list failed [%d]", err);
                goto FINISH_OFF;
        }
 
 FINISH_OFF:    
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err [%d]", err);
        return err;
 }
 
@@ -761,7 +816,7 @@ FINISH_OFF:
     -----------------------------------------------------------*/
 EXPORT_API int email_get_attachment_data(int attachment_id, email_attachment_data_t** attachment)
 {
-       EM_DEBUG_FUNC_BEGIN("attachment_id[%d], attachment[%p]", attachment_id, attachment);
+       EM_DEBUG_API_BEGIN ("attachment_id[%d] attachment[%p]", attachment_id, attachment);
        
        int err = EMAIL_ERROR_NONE;
        int nSize = 0;
@@ -823,39 +878,47 @@ FINISH_OFF:
        if(hAPI)
                emipc_destroy_email_api(hAPI);
 
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 
 }
 
 EXPORT_API int email_get_attachment_data_list(int input_mail_id, email_attachment_data_t **output_attachment_data, int *output_attachment_count)
 {
-       EM_DEBUG_FUNC_BEGIN("input_mail_id[%d], output_attachment_data[%p], output_attachment_count[%p]", input_mail_id, output_attachment_data, output_attachment_count);
+       EM_DEBUG_API_BEGIN ("input_mail_id[%d] output_attachment_data[%p] output_attachment_count[%p]", input_mail_id, output_attachment_data, output_attachment_count);
        int err = EMAIL_ERROR_NONE;
        
+#ifdef __FEATURE_ACCESS_CONTROL__
+       err = em_check_db_privilege_by_pid(getpid());
+       if (err == EMAIL_ERROR_PERMISSION_DENIED) {
+               EM_DEBUG_LOG("permission denied");
+               return err;
+       }
+#endif
+
        if((err = emcore_get_attachment_data_list(input_mail_id, output_attachment_data, output_attachment_count)) != EMAIL_ERROR_NONE) {
                EM_DEBUG_EXCEPTION("emcore_get_attachment_data_list failed [%d]", err);
        }
 
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_free_attachment_data(email_attachment_data_t **attachment_data_list, int attachment_data_count)
 {
-       EM_DEBUG_FUNC_BEGIN("attachment_data_list[%p], attachment_data_count[%d]", attachment_data_list, attachment_data_count);        
+       EM_DEBUG_FUNC_BEGIN ("attachment_data_list[%p] attachment_data_count[%d]", attachment_data_list, attachment_data_count);        
        
        int err = EMAIL_ERROR_NONE;
 
        emcore_free_attachment_data(attachment_data_list, attachment_data_count, &err);
        
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_FUNC_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_get_mail_list_ex(email_list_filter_t *input_filter_list, int input_filter_count, email_list_sorting_rule_t *input_sorting_rule_list, int input_sorting_rule_count, int input_start_index, int input_limit_count, email_mail_list_item_t** output_mail_list, int *output_result_count)
 {
-       EM_DEBUG_FUNC_BEGIN("input_filter_list [%p], input_filter_count[%d], input_sorting_rule_list[%p], input_sorting_rule_count [%d], input_start_index [%d], input_limit_count [%d], output_mail_list [%p], output_result_count [%p]", input_filter_list, input_filter_count, input_sorting_rule_list, input_sorting_rule_count, input_start_index, input_limit_count, output_mail_list, output_result_count);
+       EM_DEBUG_FUNC_BEGIN ("input_filter_list[%p] input_filter_count[%d] input_sorting_rule_list[%p] input_sorting_rule_count[%d] input_start_index[%d] input_limit_count[%d] output_mail_list[%p] output_result_count[%p]", input_filter_list, input_filter_count, input_sorting_rule_list, input_sorting_rule_count, input_start_index, input_limit_count, output_mail_list, output_result_count);
 
        int err = EMAIL_ERROR_NONE;
        char *conditional_clause_string = NULL;
@@ -863,41 +926,50 @@ EXPORT_API int email_get_mail_list_ex(email_list_filter_t *input_filter_list, in
        EM_IF_NULL_RETURN_VALUE(output_mail_list, EMAIL_ERROR_INVALID_PARAM);
        EM_IF_NULL_RETURN_VALUE(output_result_count, EMAIL_ERROR_INVALID_PARAM);
 
+#ifdef __FEATURE_ACCESS_CONTROL__
+       err = em_check_db_privilege_by_pid(getpid());
+       if (err == EMAIL_ERROR_PERMISSION_DENIED) {
+               EM_DEBUG_LOG("permission denied");
+               goto FINISH_OFF;
+       }
+#endif
+
        if( (err = emstorage_write_conditional_clause_for_getting_mail_list(input_filter_list, input_filter_count, input_sorting_rule_list, input_sorting_rule_count, input_start_index, input_limit_count, &conditional_clause_string)) != EMAIL_ERROR_NONE) {
                EM_DEBUG_EXCEPTION("emstorage_write_conditional_clause_for_getting_mail_list failed[%d]", err);
                goto FINISH_OFF;
        }
 
-       EM_DEBUG_LOG("conditional_clause_string[%s].", conditional_clause_string);
+       EM_DEBUG_LOG_DEV ("conditional_clause_string[%s].", conditional_clause_string);
 
        if(!emstorage_query_mail_list(conditional_clause_string, true, output_mail_list, output_result_count, &err)) {
-               EM_DEBUG_EXCEPTION("emstorage_query_mail_list [%d]", err);
+               if (err != EMAIL_ERROR_MAIL_NOT_FOUND) /* there is no mail and it is definitely common */
+                       EM_DEBUG_EXCEPTION("emstorage_query_mail_list [%d]", err);
                goto FINISH_OFF;
        }
 
 FINISH_OFF:
        EM_SAFE_FREE(conditional_clause_string);
 
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_FUNC_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_free_list_filter(email_list_filter_t **input_filter_list, int input_filter_count)
 {
-       EM_DEBUG_FUNC_BEGIN("input_filter_list [%p], input_filter_count[%d]", input_filter_list, input_filter_count);
+       EM_DEBUG_FUNC_BEGIN ("input_filter_list[%p] input_filter_count[%d]", input_filter_list, input_filter_count);
        int err = EMAIL_ERROR_NONE;
 
        EM_IF_NULL_RETURN_VALUE(input_filter_list, EMAIL_ERROR_INVALID_PARAM);
 
        err = emstorage_free_list_filter(input_filter_list, input_filter_count);
 
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_FUNC_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_get_mails(int account_id , int mailbox_id, int thread_id, int start_index, int limit_count, email_sort_type_t sorting, email_mail_data_t** mail_list,  int* result_count)
 {
-       EM_DEBUG_FUNC_BEGIN();
+       EM_DEBUG_API_BEGIN ("account_id[%d] mailbox_id[%d] thread_id[%d]", account_id, mailbox_id, thread_id);
 
        int err = EMAIL_ERROR_NONE;
        emstorage_mail_tbl_t *mail_tbl_list = NULL;
@@ -909,6 +981,14 @@ EXPORT_API int email_get_mails(int account_id , int mailbox_id, int thread_id, i
                goto FINISH_OFF;
        }
 
+#ifdef __FEATURE_ACCESS_CONTROL__
+       err = em_check_db_privilege_by_pid(getpid());
+       if (err == EMAIL_ERROR_PERMISSION_DENIED) {
+               EM_DEBUG_LOG("permission denied");
+               goto FINISH_OFF;
+       }
+#endif
+
        if (!emstorage_get_mails(account_id, mailbox_id, NULL, thread_id, start_index, limit_count, sorting, true, &mail_tbl_list, result_count, &err))  {
                EM_DEBUG_EXCEPTION("emstorage_get_mails failed [%d]", err);
 
@@ -921,16 +1001,16 @@ EXPORT_API int email_get_mails(int account_id , int mailbox_id, int thread_id, i
        }
 
 FINISH_OFF:    
-       if(mail_tbl_list && !emstorage_free_mail(&mail_tbl_list, *result_count, &err))
-               EM_DEBUG_EXCEPTION("emstorage_free_mail failed [%d]", err);
+       if(mail_tbl_list && !emstorage_free_mail(&mail_tbl_list, *result_count, NULL))
+               EM_DEBUG_EXCEPTION("emstorage_free_mail failed");
 
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_get_mail_list(int account_id , int mailbox_id, int thread_id, int start_index, int limit_count, email_sort_type_t sorting, email_mail_list_item_t** mail_list,  int* result_count)
 {
-       EM_DEBUG_FUNC_BEGIN();
+       EM_DEBUG_API_BEGIN ("account_id[%d] mailbox_id[%d] thread_id[%d]", account_id, mailbox_id, thread_id);
 
        int err = EMAIL_ERROR_NONE;
        
@@ -941,6 +1021,14 @@ EXPORT_API int email_get_mail_list(int account_id , int mailbox_id, int thread_i
                return EMAIL_ERROR_INVALID_PARAM;
        }
 
+#ifdef __FEATURE_ACCESS_CONTROL__
+       err = em_check_db_privilege_by_pid(getpid());
+       if (err == EMAIL_ERROR_PERMISSION_DENIED) {
+               EM_DEBUG_LOG("permission denied");
+               goto FINISH_OFF;
+       }
+#endif
+
        if (!emstorage_get_mail_list(account_id, mailbox_id, NULL, thread_id, start_index, limit_count, 0, NULL, sorting, true, mail_list, result_count, &err))  {
                EM_DEBUG_EXCEPTION("emstorage_get_mail_list failed [%d]", err);
 
@@ -948,14 +1036,14 @@ EXPORT_API int email_get_mail_list(int account_id , int mailbox_id, int thread_i
        }
 
 FINISH_OFF:    
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_get_mail_by_address(int account_id , int mailbox_id, email_email_address_list_t* addr_list,
                                                                        int start_index, int limit_count, int search_type, const char *search_value, email_sort_type_t sorting, email_mail_list_item_t** mail_list,  int* result_count)
 {
-       EM_DEBUG_FUNC_BEGIN();
+       EM_DEBUG_API_BEGIN ("account_id[%d] mailbox_id[%d]", account_id, mailbox_id);
        int err = EMAIL_ERROR_NONE;
 
        email_mail_list_item_t* mail_list_item = NULL;
@@ -969,6 +1057,14 @@ EXPORT_API int email_get_mail_by_address(int account_id , int mailbox_id, email_
                return err;
        }
 
+#ifdef __FEATURE_ACCESS_CONTROL__
+       err = em_check_db_privilege_by_pid(getpid());
+       if (err == EMAIL_ERROR_PERMISSION_DENIED) {
+               EM_DEBUG_LOG("permission denied");
+               goto FINISH_OFF;
+       }
+#endif
+
        if (!emstorage_get_mail_list(account_id, mailbox_id, addr_list, EMAIL_LIST_TYPE_NORMAL, start_index, limit_count, search_type, search_value, sorting, true, &mail_list_item, result_count, &err)) {
                EM_DEBUG_EXCEPTION("emstorage_get_mail_list failed [%d]", err);
 
@@ -978,18 +1074,26 @@ EXPORT_API int email_get_mail_by_address(int account_id , int mailbox_id, email_
        *mail_list = mail_list_item;
 
 FINISH_OFF:
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_get_thread_information_by_thread_id(int thread_id, email_mail_data_t** thread_info)
 {
-       EM_DEBUG_FUNC_BEGIN();
+       EM_DEBUG_API_BEGIN ("thread_id[%d]", thread_id);
        int err = EMAIL_ERROR_NONE;
        emstorage_mail_tbl_t *mail_table_data = NULL;
        
        EM_IF_NULL_RETURN_VALUE(thread_info, EMAIL_ERROR_INVALID_PARAM);
 
+#ifdef __FEATURE_ACCESS_CONTROL__
+       err = em_check_db_privilege_by_pid(getpid());
+       if (err == EMAIL_ERROR_PERMISSION_DENIED) {
+               EM_DEBUG_LOG("permission denied");
+               goto FINISH_OFF;
+       }
+#endif
+
        if (!emstorage_get_thread_information(thread_id, &mail_table_data , true, &err)) {
                EM_DEBUG_EXCEPTION("emstorage_get_thread_information  failed [%d]", err);
                goto FINISH_OFF;
@@ -1002,22 +1106,30 @@ EXPORT_API int email_get_thread_information_by_thread_id(int thread_id, email_ma
 
 FINISH_OFF:    
 
-       if(mail_table_data && !emstorage_free_mail(&mail_table_data, 1, &err)) 
-               EM_DEBUG_EXCEPTION("emstorage_free_mail failed [%d]", err);
+       if(mail_table_data && !emstorage_free_mail(&mail_table_data, 1, NULL))
+               EM_DEBUG_EXCEPTION("emstorage_free_mail failed");
 
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_get_thread_information_ex(int thread_id, email_mail_list_item_t** thread_info)
 {
-       EM_DEBUG_FUNC_BEGIN();
+       EM_DEBUG_API_BEGIN ("thread_id[%d]", thread_id);
        int err = EMAIL_ERROR_NONE;
        emstorage_mail_tbl_t *mail_table_data = NULL;
        email_mail_list_item_t *temp_thread_info = NULL;
        
        EM_IF_NULL_RETURN_VALUE(thread_info, EMAIL_ERROR_INVALID_PARAM);
 
+#ifdef __FEATURE_ACCESS_CONTROL__
+       err = em_check_db_privilege_by_pid(getpid());
+       if (err == EMAIL_ERROR_PERMISSION_DENIED) {
+               EM_DEBUG_LOG("permission denied");
+               goto FINISH_OFF;
+       }
+#endif
+
        if (!emstorage_get_thread_information(thread_id, &mail_table_data , true, &err)) {
                EM_DEBUG_EXCEPTION("emstorage_get_thread_information -- failed [%d]", err);
                goto FINISH_OFF;
@@ -1038,6 +1150,7 @@ EXPORT_API int email_get_thread_information_ex(int thread_id, email_mail_list_it
        EM_SAFE_STRNCPY(temp_thread_info->preview_text            , mail_table_data->preview_text, MAX_PREVIEW_TEXT_LENGTH);
        temp_thread_info->mail_id                                 = mail_table_data->mail_id;
        temp_thread_info->mailbox_id                              = mail_table_data->mailbox_id;
+       temp_thread_info->mailbox_type                            = mail_table_data->mailbox_type;
        temp_thread_info->account_id                              = mail_table_data->account_id;
        temp_thread_info->date_time                               = mail_table_data->date_time;
        temp_thread_info->body_download_status                    = mail_table_data->body_download_status;
@@ -1059,19 +1172,27 @@ FINISH_OFF:
        if(mail_table_data)
                emstorage_free_mail(&mail_table_data, 1, NULL);
 
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_get_mail_data(int input_mail_id, email_mail_data_t **output_mail_data)
 {
-       EM_DEBUG_FUNC_BEGIN();
+       EM_DEBUG_API_BEGIN ("input_mail_id[%d]", input_mail_id);
        int err = EMAIL_ERROR_NONE;
        
+#ifdef __FEATURE_ACCESS_CONTROL__
+       err = em_check_db_privilege_by_pid(getpid());
+       if (err == EMAIL_ERROR_PERMISSION_DENIED) {
+               EM_DEBUG_LOG("permission denied");
+               return err;
+       }
+#endif
+
        if ( ((err = emcore_get_mail_data(input_mail_id, output_mail_data)) != EMAIL_ERROR_NONE) || !output_mail_data) 
                EM_DEBUG_EXCEPTION("emcore_get_mail_data failed [%d]", err);    
                
-       EM_DEBUG_FUNC_END("err [%d]", err);     
+       EM_DEBUG_API_END ("err[%d]", err);      
        return err;
 }
 
@@ -1082,14 +1203,14 @@ EXPORT_API int email_get_mail_data(int input_mail_id, email_mail_data_t **output
 
 EXPORT_API int email_modify_seen_flag(int *mail_ids, int num, int seen_flag, int onserver)
 {
-       EM_DEBUG_FUNC_BEGIN("mail_ids[%p], num[%d],seen_flag[%d], on_server [ %d]", mail_ids, num, seen_flag, onserver);
-       EM_DEBUG_FUNC_END("EMAIL_ERROR_NOT_IMPLEMENTED");
+       EM_DEBUG_API_BEGIN ("mail_ids[%p] num[%d] seen_flag[%d] on_server[%d]", mail_ids, num, seen_flag, onserver);
+       EM_DEBUG_API_END ("EMAIL_ERROR_NOT_IMPLEMENTED");
        return EMAIL_ERROR_NOT_IMPLEMENTED;
 }
 
 EXPORT_API int email_set_flags_field(int account_id, int *mail_ids, int num, email_flags_field_type field_type, int value, int onserver)
 {
-       EM_DEBUG_FUNC_BEGIN("account_id [%d], mail_ids[%p], num[%d], field_type [%d], seen_flag[%d], on_server [ %d]", account_id, mail_ids, num, field_type, value, onserver);
+       EM_DEBUG_API_BEGIN ("account_id[%d] mail_ids[%p] num[%d] field_type[%d] seen_flag[%d] on_server[%d]", account_id, mail_ids, num, field_type, value, onserver);
        
        int err = EMAIL_ERROR_NONE;
 
@@ -1163,7 +1284,7 @@ FINISH_OFF:
        if(hAPI)
                emipc_destroy_email_api(hAPI);
 
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
@@ -1173,7 +1294,7 @@ FINISH_OFF:
     -----------------------------------------------------------*/
 EXPORT_API int email_move_mail_to_mailbox(int *mail_ids, int num, int input_target_mailbox_id)
 {
-       EM_DEBUG_FUNC_BEGIN("mail_ids[%p], num [%d], input_target_mailbox_id[%d]",  mail_ids, num, input_target_mailbox_id);
+       EM_DEBUG_API_BEGIN ("mail_ids[%p] num[%d] input_target_mailbox_id[%d]",  mail_ids, num, input_target_mailbox_id);
        
        int err = EMAIL_ERROR_NONE;
        HIPC_API hAPI = NULL;
@@ -1233,14 +1354,14 @@ FINISH_OFF:
        if(hAPI)
                emipc_destroy_email_api(hAPI);
 
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 
 EXPORT_API int  email_move_all_mails_to_mailbox(int input_source_mailbox_id, int input_target_mailbox_id)
 {
-       EM_DEBUG_FUNC_BEGIN("input_source_mailbox_id[%d] , input_target_mailbox_id[%d]",  input_source_mailbox_id, input_target_mailbox_id);
+       EM_DEBUG_API_BEGIN ("input_source_mailbox_id[%d] input_target_mailbox_id[%d]", input_source_mailbox_id, input_target_mailbox_id);
        
        int err = EMAIL_ERROR_NONE;
        HIPC_API hAPI = NULL;
@@ -1286,13 +1407,13 @@ FINISH_OFF:
        if(hAPI)
                emipc_destroy_email_api(hAPI);
        
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_move_mails_to_mailbox_of_another_account(int input_source_mailbox_id, int *input_mail_id_array, int input_mail_id_count, int input_target_mailbox_id, int *output_task_id)
 {
-       EM_DEBUG_FUNC_BEGIN("input_source_mailbox_id[%d] input_mail_id_array[%p] input_mail_id_count[%d] input_target_mailbox_id[%d] output_task_id[%p]",  input_source_mailbox_id, input_mail_id_array, input_mail_id_count, input_target_mailbox_id, output_task_id);
+       EM_DEBUG_API_BEGIN ("input_source_mailbox_id[%d] input_mail_id_array[%p] input_mail_id_count[%d] input_target_mailbox_id[%d] output_task_id[%p]",  input_source_mailbox_id, input_mail_id_array, input_mail_id_count, input_target_mailbox_id, output_task_id);
 
        int err = EMAIL_ERROR_NONE;
        task_parameter_EMAIL_ASYNC_TASK_MOVE_MAILS_TO_MAILBOX_OF_ANOTHER_ACCOUNT task_parameter;
@@ -1315,16 +1436,16 @@ EXPORT_API int email_move_mails_to_mailbox_of_another_account(int input_source_m
 
 FINISH_OFF:
 
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
  
 EXPORT_API int email_free_mail_data(email_mail_data_t** mail_list, int count)
 {
-       EM_DEBUG_FUNC_BEGIN("mail_list[%p], count[%d]", mail_list, count);
+       EM_DEBUG_FUNC_BEGIN ("mail_list[%p] count[%d]", mail_list, count);
        int err = EMAIL_ERROR_NONE;
        emcore_free_mail_data_list(mail_list, count);
-       EM_DEBUG_FUNC_END("err [%d]", err);     
+       EM_DEBUG_FUNC_END ("err[%d]", err);     
        return err;
 }
 
@@ -1333,7 +1454,7 @@ EXPORT_API int email_free_mail_data(email_mail_data_t** mail_list, int count)
 
 EXPORT_API int email_cancel_sending_mail(int mail_id)
 {
-       EM_DEBUG_FUNC_BEGIN("Mail ID [ %d]", mail_id);
+       EM_DEBUG_API_BEGIN ("mail_id[%d]", mail_id);
        EM_IF_NULL_RETURN_VALUE(mail_id, EMAIL_ERROR_INVALID_PARAM);
        
        int err = EMAIL_ERROR_NONE;
@@ -1419,14 +1540,14 @@ FINISH_OFF:
        if(mail_data)
                emcore_free_mail_data_list(&mail_data, 1);
 
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 
 }
 
-EXPORT_API int email_retry_sending_mail( int mail_id, int timeout_in_sec)
+EXPORT_API int email_retry_sending_mail(int mail_id, int timeout_in_sec)
 {
-       EM_DEBUG_FUNC_BEGIN();
+       EM_DEBUG_API_BEGIN ("mail_id[%d]",mail_id);
        
        int err = EMAIL_ERROR_NONE;
 
@@ -1473,18 +1594,18 @@ FINISH_OFF:
        if(hAPI)
                emipc_destroy_email_api(hAPI);
 
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 
 }
 
 EXPORT_API int email_get_max_mail_count(int *Count)
 {
-       EM_DEBUG_FUNC_BEGIN();
+       EM_DEBUG_API_BEGIN ();
        int err = EMAIL_ERROR_NONE;
        EM_IF_NULL_RETURN_VALUE(Count, EMAIL_ERROR_INVALID_PARAM);
        *Count = emstorage_get_max_mail_count();
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
@@ -1493,7 +1614,7 @@ EXPORT_API int email_get_max_mail_count(int *Count)
 /* for setting application,disk usage of email in KB */
 EXPORT_API int email_get_disk_space_usage(unsigned long *total_size)
 {
-       EM_DEBUG_FUNC_BEGIN("total_size[%p]", total_size);
+       EM_DEBUG_API_BEGIN ("total_size[%p]", total_size);
        int err = EMAIL_ERROR_NONE;
 
        EM_IF_NULL_RETURN_VALUE(total_size, EMAIL_ERROR_INVALID_PARAM);
@@ -1504,13 +1625,13 @@ EXPORT_API int email_get_disk_space_usage(unsigned long *total_size)
                goto FINISH_OFF;
        }
 FINISH_OFF :   
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_get_address_info_list(int mail_id, email_address_info_list_t** address_info_list)
 {
-       EM_DEBUG_FUNC_BEGIN("mail_id[%d], address_info_list[%p]", mail_id, address_info_list);
+       EM_DEBUG_FUNC_BEGIN ("mail_id[%d] address_info_list[%p]", mail_id, address_info_list);
 
        int err = EMAIL_ERROR_NONE;
 
@@ -1523,6 +1644,14 @@ EXPORT_API int email_get_address_info_list(int mail_id, email_address_info_list_
                return err;
        }
        
+#ifdef __FEATURE_ACCESS_CONTROL__
+       err = em_check_db_privilege_by_pid(getpid());
+       if (err == EMAIL_ERROR_PERMISSION_DENIED) {
+               EM_DEBUG_LOG("permission denied");
+               goto FINISH_OFF;
+       }
+#endif
+
        if ( !emcore_get_mail_address_info_list(mail_id, &temp_address_info_list, &err) ) {
                EM_DEBUG_EXCEPTION("emcore_get_mail_address_info_list failed [%d]", err);
 
@@ -1537,33 +1666,57 @@ EXPORT_API int email_get_address_info_list(int mail_id, email_address_info_list_
 FINISH_OFF:
        if ( temp_address_info_list )
                emstorage_free_address_info_list(&temp_address_info_list);
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_FUNC_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_free_address_info_list(email_address_info_list_t **address_info_list)
 {
-       EM_DEBUG_FUNC_BEGIN("address_info_list[%p]", address_info_list);
+       EM_DEBUG_FUNC_BEGIN ("address_info_list[%p]", address_info_list);
 
        int err = EMAIL_ERROR_NONE;
 
        if ( (err = emstorage_free_address_info_list(address_info_list)) != EMAIL_ERROR_NONE ) {
                EM_DEBUG_EXCEPTION("address_info_list[%p] free failed.", address_info_list);
        }
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_FUNC_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_get_structure(const char*encoded_string, void **struct_var, email_convert_struct_type_e type)
 {
-       EM_DEBUG_FUNC_BEGIN("encoded_string[%s], struct_var[%p], type[%d]", encoded_string, struct_var, type);
-       EM_DEBUG_FUNC_END("err [%d]", EMAIL_ERROR_NOT_IMPLEMENTED);
+       EM_DEBUG_API_BEGIN ("encoded_string[%s] struct_var[%p] type[%d]", encoded_string, struct_var, type);
+       EM_DEBUG_API_END ("err[%d]", EMAIL_ERROR_NOT_IMPLEMENTED);
        return EMAIL_ERROR_NOT_IMPLEMENTED;
 }
 
+EXPORT_API int email_query_meeting_request(char *input_conditional_clause_string, email_meeting_request_t **output_meeting_req, int *output_count)
+{
+       EM_DEBUG_API_BEGIN ("input_conditional_clause_string[%s] output_meeting_req[%p] output_count[%p]", input_conditional_clause_string, output_meeting_req, output_count);
+       int err = EMAIL_ERROR_NONE;
+
+       EM_IF_NULL_RETURN_VALUE(input_conditional_clause_string, EMAIL_ERROR_INVALID_PARAM);
+       EM_IF_NULL_RETURN_VALUE(output_count, EMAIL_ERROR_INVALID_PARAM);
+
+#ifdef __FEATURE_ACCESS_CONTROL__
+       err = em_check_db_privilege_by_pid(getpid());
+       if (err == EMAIL_ERROR_PERMISSION_DENIED) {
+               EM_DEBUG_LOG("permission denied");
+               return err;
+       }
+#endif
+
+       if ((err = emstorage_query_meeting_request(input_conditional_clause_string, output_meeting_req, output_count, true)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emstorage_query_meeting_request failed [%d]", err);
+       }
+
+       EM_DEBUG_API_END ("err[%d]", err);
+       return err;
+}
+
 EXPORT_API int email_get_meeting_request(int mail_id, email_meeting_request_t **meeting_req)
 {
-       EM_DEBUG_FUNC_BEGIN("mail_id[%d],meeting_req[%p]",  mail_id, meeting_req);
+       EM_DEBUG_API_BEGIN ("mail_id[%d] meeting_req[%p]", mail_id, meeting_req);
 
        int err = EMAIL_ERROR_NONE;
 
@@ -1576,8 +1729,16 @@ EXPORT_API int email_get_meeting_request(int mail_id, email_meeting_request_t **
                return err;
        }
        
+#ifdef __FEATURE_ACCESS_CONTROL__
+       err = em_check_db_privilege_by_pid(getpid());
+       if (err == EMAIL_ERROR_PERMISSION_DENIED) {
+               EM_DEBUG_LOG("permission denied");
+               goto FINISH_OFF;
+       }
+#endif
+
        if ( !emstorage_get_meeting_request(mail_id, &temp_meeting_req, 1, &err) ) {
-               EM_DEBUG_EXCEPTION("emstorage_get_meeting_request -- Failed [%d]", err);
+               EM_DEBUG_EXCEPTION("emstorage_get_meeting_request failed[%d]", err);
 
                goto FINISH_OFF;
        }
@@ -1586,13 +1747,13 @@ EXPORT_API int email_get_meeting_request(int mail_id, email_meeting_request_t **
                *meeting_req = temp_meeting_req;
 
 FINISH_OFF:
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_free_meeting_request(email_meeting_request_t** meeting_req, int count)
 {
-       EM_DEBUG_FUNC_BEGIN("meeting_req[%p], count[%d]", meeting_req, count);
+       EM_DEBUG_FUNC_BEGIN ("meeting_req[%p] count[%d]", meeting_req, count);
        if( !meeting_req || !*meeting_req ) {
                EM_DEBUG_EXCEPTION("NULL PARAM");
                return EMAIL_ERROR_INVALID_PARAM;
@@ -1605,15 +1766,14 @@ EXPORT_API int email_free_meeting_request(email_meeting_request_t** meeting_req,
 
        EM_SAFE_FREE(*meeting_req);
 
-       EM_DEBUG_FUNC_END();
+       EM_DEBUG_FUNC_END ();
        return EMAIL_ERROR_NONE;
 }
 
 EXPORT_API int email_move_thread_to_mailbox(int thread_id, int target_mailbox_id, int move_always_flag)
 {
-       EM_DEBUG_FUNC_BEGIN("thread_id[%d], target_mailbox_id[%d], move_always_flag[%d]", thread_id, target_mailbox_id, move_always_flag);
+       EM_DEBUG_API_BEGIN ("thread_id[%d] target_mailbox_id[%d] move_always_flag[%d]", thread_id, target_mailbox_id, move_always_flag);
        int err = EMAIL_ERROR_NONE;
-       
 
        EM_IF_NULL_RETURN_VALUE(target_mailbox_id, EMAIL_ERROR_INVALID_PARAM);
        
@@ -1659,13 +1819,13 @@ FINISH_OFF:
        if(hAPI)
                emipc_destroy_email_api(hAPI);
 
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_delete_thread(int thread_id, int delete_always_flag)
 {
-       EM_DEBUG_FUNC_BEGIN("thread_id[%d], delete_always_flag[%d]", thread_id, delete_always_flag);
+       EM_DEBUG_API_BEGIN ("thread_id[%d] delete_always_flag[%d]", thread_id, delete_always_flag);
        int err = EMAIL_ERROR_NONE;
 
        HIPC_API hAPI = emipc_create_email_api(_EMAIL_API_DELETE_THREAD);
@@ -1703,13 +1863,13 @@ FINISH_OFF:
        if(hAPI)
                emipc_destroy_email_api(hAPI);
 
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_modify_seen_flag_of_thread(int thread_id, int seen_flag, int on_server)
 {
-       EM_DEBUG_FUNC_BEGIN("thread_id[%d], seen_flag[%d], on_server[%d]", thread_id, seen_flag, on_server);
+       EM_DEBUG_API_BEGIN ("thread_id[%d] seen_flag[%d] on_server[%d]", thread_id, seen_flag, on_server);
        int err = EMAIL_ERROR_NONE;
        HIPC_API hAPI = emipc_create_email_api(_EMAIL_API_MODIFY_SEEN_FLAG_OF_THREAD);
 
@@ -1752,13 +1912,13 @@ EXPORT_API int email_modify_seen_flag_of_thread(int thread_id, int seen_flag, in
 FINISH_OFF:
        if(hAPI)
                emipc_destroy_email_api(hAPI);
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_expunge_mails_deleted_flagged(int input_mailbox_id, int input_on_server, int *output_handle)
 {
-       EM_DEBUG_FUNC_BEGIN("input_mailbox_id[%d], input_on_server[%d], output_handle[%p]", input_mailbox_id, input_on_server, output_handle);
+       EM_DEBUG_API_BEGIN ("input_mailbox_id[%d] input_on_server[%d] output_handle[%p]", input_mailbox_id, input_on_server, output_handle);
        int err = EMAIL_ERROR_NONE;
        int return_value = 0;
        HIPC_API hAPI = NULL;
@@ -1850,6 +2010,7 @@ FINISH_OFF:
                emstorage_free_mailbox(&mailbox_tbl_data, 1, NULL);
        }
 
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
+
index 94edec3..ccd01cf 100755 (executable)
@@ -35,6 +35,7 @@
 #include "email-convert.h"
 #include "email-storage.h"
 #include "email-core-utils.h"
+#include "email-core-signal.h"
 #include "email-utilities.h"
 #include "email-ipc.h"
 #include "db-util.h"
@@ -43,7 +44,7 @@
 
 EXPORT_API int email_add_mailbox(email_mailbox_t* new_mailbox, int on_server, int *handle)
 {
-       EM_DEBUG_FUNC_BEGIN();
+       EM_DEBUG_API_BEGIN ();
 
        int size = 0;
        int err = EMAIL_ERROR_NONE;
@@ -77,6 +78,8 @@ EXPORT_API int email_add_mailbox(email_mailbox_t* new_mailbox, int on_server, in
                as_noti_data.add_mailbox.account_id    = new_mailbox->account_id;
                as_noti_data.add_mailbox.mailbox_alias = new_mailbox->alias;
                as_noti_data.add_mailbox.mailbox_path  = new_mailbox->mailbox_name;
+               as_noti_data.add_mailbox.eas_data      = new_mailbox->eas_data;
+               as_noti_data.add_mailbox.eas_data_length = new_mailbox->eas_data_length;
 
                if ( em_send_notification_to_active_sync_engine(ACTIVE_SYNC_NOTI_ADD_MAILBOX, &as_noti_data) == false) {
                        EM_DEBUG_EXCEPTION("em_send_notification_to_active_sync_engine failed.");
@@ -113,7 +116,6 @@ EXPORT_API int email_add_mailbox(email_mailbox_t* new_mailbox, int on_server, in
                }
 
                emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);
-               EM_DEBUG_LOG(" >>>>> error VALUE [%d]", err);
        
                if(handle) {
                        emipc_get_parameter(hAPI, ePARAMETER_OUT, 1, sizeof(int), handle);
@@ -130,13 +132,13 @@ EXPORT_API int email_add_mailbox(email_mailbox_t* new_mailbox, int on_server, in
 FINISH_OFF:
        EM_SAFE_FREE(local_mailbox_stream);
 
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_rename_mailbox(int input_mailbox_id, char *input_mailbox_name, char *input_mailbox_alias, int input_on_server, int *output_handle)
 {
-       EM_DEBUG_FUNC_BEGIN("input_mailbox_id [%d], input_mailbox_name [%p], input_mailbox_alias [%p], input_on_server [%d], output_handle [%p]", input_mailbox_id, input_mailbox_name, input_mailbox_alias, input_on_server, output_handle);
+       EM_DEBUG_API_BEGIN ("input_mailbox_id[%d] input_mailbox_name[%p] input_mailbox_alias[%p] input_on_server[%d] output_handle[%p]", input_mailbox_id, input_mailbox_name, input_mailbox_alias, input_on_server, output_handle);
 
        int err = EMAIL_ERROR_NONE;
        email_account_server_t account_server_type;
@@ -175,6 +177,8 @@ EXPORT_API int email_rename_mailbox(int input_mailbox_id, char *input_mailbox_na
                as_noti_data.rename_mailbox.mailbox_id    = input_mailbox_id;
                as_noti_data.rename_mailbox.mailbox_name  = input_mailbox_name;
                as_noti_data.rename_mailbox.mailbox_alias = input_mailbox_alias;
+               as_noti_data.rename_mailbox.eas_data        = NULL;
+               as_noti_data.rename_mailbox.eas_data_length = 0;
 
                if ( em_send_notification_to_active_sync_engine(ACTIVE_SYNC_NOTI_RENAME_MAILBOX, &as_noti_data) == false) {
                        EM_DEBUG_EXCEPTION("em_send_notification_to_active_sync_engine failed.");
@@ -214,6 +218,8 @@ EXPORT_API int email_rename_mailbox(int input_mailbox_id, char *input_mailbox_na
                }
 
                emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);
+               if (output_handle)
+                       emipc_get_parameter(hAPI, ePARAMETER_OUT, 1, sizeof(int), output_handle);
 
                EM_DEBUG_LOG("error VALUE [%d]", err);
                emipc_destroy_email_api(hAPI);
@@ -222,7 +228,108 @@ FINISH_OFF:
        if (mailbox_tbl)
                emstorage_free_mailbox(&mailbox_tbl, 1, NULL);
 
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
+       return err;
+}
+
+EXPORT_API int email_rename_mailbox_ex(int input_mailbox_id, char *input_mailbox_name, char *input_mailbox_alias, void *input_eas_data, int input_eas_data_length, int input_on_server, int *output_handle)
+{
+       EM_DEBUG_API_BEGIN ("input_mailbox_id[%d] input_mailbox_name[%p] input_mailbox_alias[%p] input_eas_data[%p] input_eas_data_length[%d] input_on_server[%d] output_handle[%p]", input_mailbox_id, input_mailbox_name, input_mailbox_alias, input_eas_data, input_eas_data_length, input_on_server, output_handle);
+
+       int err = EMAIL_ERROR_NONE;
+       email_account_server_t account_server_type;
+       HIPC_API hAPI = NULL;
+       ASNotiData as_noti_data;
+       emstorage_mailbox_tbl_t *mailbox_tbl = NULL;
+
+       EM_IF_NULL_RETURN_VALUE(input_mailbox_id,    EMAIL_ERROR_INVALID_PARAM);
+       EM_IF_NULL_RETURN_VALUE(input_mailbox_name,  EMAIL_ERROR_INVALID_PARAM);
+       EM_IF_NULL_RETURN_VALUE(input_mailbox_alias, EMAIL_ERROR_INVALID_PARAM);
+
+       if ((err = emstorage_get_mailbox_by_id(input_mailbox_id, &mailbox_tbl)) != EMAIL_ERROR_NONE || !mailbox_tbl) {
+               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_id failed. [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       /*  check account bind type and branch off  */
+       if ( em_get_account_server_type_by_account_id(mailbox_tbl->account_id, &account_server_type, false, &err) == false ) {
+               EM_DEBUG_EXCEPTION("em_get_account_server_type_by_account_id failed[%d]", err);
+               err = EMAIL_ERROR_ACTIVE_SYNC_NOTI_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       if ( account_server_type == EMAIL_SERVER_TYPE_ACTIVE_SYNC && input_on_server) {
+               int as_handle;
+
+               if ( em_get_handle_for_activesync(&as_handle, &err) == false ) {
+                       EM_DEBUG_EXCEPTION("em_get_handle_for_activesync failed[%d].", err);
+                       err = EMAIL_ERROR_ACTIVE_SYNC_NOTI_FAILURE;
+                       goto FINISH_OFF;
+               }
+
+               /*  noti to active sync */
+               as_noti_data.rename_mailbox.handle          = as_handle;
+               as_noti_data.rename_mailbox.account_id      = mailbox_tbl->account_id;
+               as_noti_data.rename_mailbox.mailbox_id      = input_mailbox_id;
+               as_noti_data.rename_mailbox.mailbox_name    = input_mailbox_name;
+               as_noti_data.rename_mailbox.mailbox_alias   = input_mailbox_alias;
+               as_noti_data.rename_mailbox.eas_data        = input_eas_data;
+               as_noti_data.rename_mailbox.eas_data_length = input_eas_data_length;
+
+               if ( em_send_notification_to_active_sync_engine(ACTIVE_SYNC_NOTI_RENAME_MAILBOX, &as_noti_data) == false) {
+                       EM_DEBUG_EXCEPTION("em_send_notification_to_active_sync_engine failed.");
+                       err = EMAIL_ERROR_ACTIVE_SYNC_NOTI_FAILURE;
+                       goto FINISH_OFF;
+               }
+
+               if(output_handle)
+                       *output_handle = as_handle;
+       }
+       else {
+               hAPI = emipc_create_email_api(_EMAIL_API_RENAME_MAILBOX_EX);
+
+               if(!emipc_add_parameter(hAPI, ePARAMETER_IN, &input_mailbox_id, sizeof(int))) {
+                       EM_DEBUG_EXCEPTION(" emipc_add_parameter for input_mailbox_id failed");
+                       EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+               }
+
+               if(!emipc_add_parameter(hAPI, ePARAMETER_IN, input_mailbox_name, EM_SAFE_STRLEN(input_mailbox_name)+1 )) {
+                       EM_DEBUG_EXCEPTION(" emipc_add_parameter for input_mailbox_path failed");
+                       EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+               }
+
+               if(!emipc_add_parameter(hAPI, ePARAMETER_IN, input_mailbox_alias, EM_SAFE_STRLEN(input_mailbox_alias)+1 )) {
+                       EM_DEBUG_EXCEPTION(" emipc_add_parameter for input_mailbox_alias failed");
+                       EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+               }
+
+               if(!emipc_add_parameter(hAPI, ePARAMETER_IN, input_eas_data, input_eas_data_length )) {
+                       EM_DEBUG_EXCEPTION(" emipc_add_parameter for input_eas_data failed");
+                       EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+               }
+
+               if(!emipc_add_parameter(hAPI, ePARAMETER_IN, &input_on_server, sizeof(int))) {
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+                       EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+               }
+
+               if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed");
+                       EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_IPC_SOCKET_FAILURE);
+               }
+
+               emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);
+               if (output_handle)
+                       emipc_get_parameter(hAPI, ePARAMETER_OUT, 1, sizeof(int), output_handle);
+
+               EM_DEBUG_LOG("error VALUE [%d]", err);
+               emipc_destroy_email_api(hAPI);
+       }
+FINISH_OFF:
+       if (mailbox_tbl)
+               emstorage_free_mailbox(&mailbox_tbl, 1, NULL);
+
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
@@ -231,7 +338,7 @@ FINISH_OFF:
 
 EXPORT_API int email_delete_mailbox(int input_mailbox_id, int input_on_server, int *output_handle)
 {
-       EM_DEBUG_FUNC_BEGIN("input_mailbox_id[%d] input_on_server[%d] output_handle[%p]", input_mailbox_id, input_on_server, output_handle);
+       EM_DEBUG_API_BEGIN ("input_mailbox_id[%d] input_on_server[%d] output_handle[%p]", input_mailbox_id, input_on_server, output_handle);
        
        int err = EMAIL_ERROR_NONE;
        email_account_server_t account_server_type;
@@ -312,13 +419,13 @@ FINISH_OFF:
                emstorage_free_mailbox(&mailbox_tbl, 1, NULL);
        }
 
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_delete_mailbox_ex(int input_account_id, int *input_mailbox_id_array, int input_mailbox_id_count, int input_on_server, int *output_handle)
 {
-       EM_DEBUG_FUNC_BEGIN("input_account_id [%d] input_mailbox_id_array[%p] input_mailbox_id_count[%d] input_on_server[%d] output_handle[%p]", input_mailbox_id_array, input_mailbox_id_array, input_mailbox_id_count, input_on_server, output_handle);
+       EM_DEBUG_API_BEGIN ("input_account_id[%d] input_mailbox_id_array[%p] input_mailbox_id_count[%d] input_on_server[%d] output_handle[%p]", input_mailbox_id_array, input_mailbox_id_array, input_mailbox_id_count, input_on_server, output_handle);
        int err = EMAIL_ERROR_NONE;
        email_account_server_t account_server_type;
        task_parameter_EMAIL_ASYNC_TASK_DELETE_MAILBOX_EX task_parameter;
@@ -376,13 +483,13 @@ EXPORT_API int email_delete_mailbox_ex(int input_account_id, int *input_mailbox_
 
 FINISH_OFF:
 
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_set_mailbox_type(int input_mailbox_id, email_mailbox_type_e input_mailbox_type)
 {
-       EM_DEBUG_FUNC_BEGIN("input_mailbox_id [%d], input_mailbox_type [%d]", input_mailbox_id, input_mailbox_type);
+       EM_DEBUG_API_BEGIN ("input_mailbox_id[%d] input_mailbox_type[%d]", input_mailbox_id, input_mailbox_type);
        int err = EMAIL_ERROR_NONE;
 
        EM_IF_NULL_RETURN_VALUE(input_mailbox_id, EMAIL_ERROR_INVALID_PARAM);
@@ -408,17 +515,16 @@ EXPORT_API int email_set_mailbox_type(int input_mailbox_id, email_mailbox_type_e
 
        emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);
 
-       EM_DEBUG_LOG("error VALUE [%d]", err);
        emipc_destroy_email_api(hAPI);
        hAPI = NULL;
 
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_set_local_mailbox(int input_mailbox_id, int input_is_local_mailbox)
 {
-       EM_DEBUG_FUNC_BEGIN("input_mailbox_id [%d], input_is_local_mailbox [%d]", input_mailbox_id, input_is_local_mailbox);
+       EM_DEBUG_API_BEGIN ("input_mailbox_id[%d] input_is_local_mailbox[%d]", input_mailbox_id, input_is_local_mailbox);
        int err = EMAIL_ERROR_NONE;
 
        EM_IF_NULL_RETURN_VALUE(input_mailbox_id, EMAIL_ERROR_INVALID_PARAM);
@@ -444,17 +550,16 @@ EXPORT_API int email_set_local_mailbox(int input_mailbox_id, int input_is_local_
 
        emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);
 
-       EM_DEBUG_LOG("error VALUE [%d]", err);
        emipc_destroy_email_api(hAPI);
        hAPI = NULL;
 
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_get_sync_mailbox_list(int account_id, email_mailbox_t** mailbox_list, int* count)
 {
-       EM_DEBUG_FUNC_BEGIN();
+       EM_DEBUG_API_BEGIN ();
        int mailbox_count = 0;
        int err = EMAIL_ERROR_NONE ;
        int i = 0;
@@ -488,14 +593,14 @@ EXPORT_API int email_get_sync_mailbox_list(int account_id, email_mailbox_t** mai
        FINISH_OFF:
        if (mailbox_tbl_list != NULL)
                emstorage_free_mailbox(&mailbox_tbl_list, mailbox_count, NULL);
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 
 EXPORT_API int email_get_mailbox_list(int account_id, int mailbox_sync_type, email_mailbox_t** mailbox_list, int* count)
 {
-       EM_DEBUG_FUNC_BEGIN();  
+       EM_DEBUG_API_BEGIN ();  
 
        int mailbox_count = 0;
        emstorage_mailbox_tbl_t* mailbox_tbl_list = NULL; 
@@ -506,6 +611,14 @@ EXPORT_API int email_get_mailbox_list(int account_id, int mailbox_sync_type, ema
        EM_IF_ACCOUNT_ID_NULL(account_id, EMAIL_ERROR_INVALID_PARAM);
        EM_IF_NULL_RETURN_VALUE(count, EMAIL_ERROR_INVALID_PARAM);
 
+#ifdef __FEATURE_ACCESS_CONTROL__
+       err = em_check_db_privilege_by_pid(getpid());
+       if (err == EMAIL_ERROR_PERMISSION_DENIED) {
+               EM_DEBUG_LOG("permission denied");
+               goto FINISH_OFF;
+       }
+#endif
+
        if (!emstorage_get_mailbox_list(account_id, mailbox_sync_type, EMAIL_MAILBOX_SORT_BY_NAME_ASC, &mailbox_count, &mailbox_tbl_list, true, &err))  {
                EM_DEBUG_EXCEPTION("emstorage_get_mailbox failed [%d]", err);
 
@@ -531,7 +644,7 @@ FINISH_OFF:
        if (mailbox_tbl_list != NULL)
                emstorage_free_mailbox(&mailbox_tbl_list, mailbox_count, NULL);
 
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err [%d]", err);
        return err;
 }
 
@@ -539,7 +652,7 @@ FINISH_OFF:
 
 EXPORT_API int email_get_mailbox_list_ex(int account_id, int mailbox_sync_type, int with_count, email_mailbox_t** mailbox_list, int* count)
 {
-       EM_DEBUG_FUNC_BEGIN();  
+       EM_DEBUG_FUNC_BEGIN (); 
 
        int mailbox_count = 0;
        emstorage_mailbox_tbl_t* mailbox_tbl_list = NULL; 
@@ -550,6 +663,14 @@ EXPORT_API int email_get_mailbox_list_ex(int account_id, int mailbox_sync_type,
        EM_IF_ACCOUNT_ID_NULL(account_id, EMAIL_ERROR_INVALID_PARAM);
        EM_IF_NULL_RETURN_VALUE(count, EMAIL_ERROR_INVALID_PARAM);
 
+#ifdef __FEATURE_ACCESS_CONTROL__
+       err = em_check_db_privilege_by_pid(getpid());
+       if (err == EMAIL_ERROR_PERMISSION_DENIED) {
+               EM_DEBUG_LOG("permission denied");
+               goto FINISH_OFF;
+       }
+#endif
+
        if (!emstorage_get_mailbox_list_ex(account_id, mailbox_sync_type, with_count, &mailbox_count, &mailbox_tbl_list, true, &err))  {        
                EM_DEBUG_EXCEPTION("emstorage_get_mailbox_list_ex failed [%d]", err);
 
@@ -577,16 +698,62 @@ FINISH_OFF:
        if (mailbox_tbl_list != NULL)
                emstorage_free_mailbox(&mailbox_tbl_list, mailbox_count, NULL);
 
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_FUNC_END ("err[%d]", err);
        return err;
 }
 
+EXPORT_API int email_get_mailbox_list_by_keyword(int account_id, char *keyword, email_mailbox_t** mailbox_list, int* count)
+{
+       EM_DEBUG_API_BEGIN ();
+
+       int mailbox_count = 0;
+       emstorage_mailbox_tbl_t* mailbox_tbl_list = NULL;
+       int err = EMAIL_ERROR_NONE;
+       int i = 0;
+
+       EM_IF_NULL_RETURN_VALUE(mailbox_list, EMAIL_ERROR_INVALID_PARAM);
+       EM_IF_NULL_RETURN_VALUE(count, EMAIL_ERROR_INVALID_PARAM);
+
+#ifdef __FEATURE_ACCESS_CONTROL__
+       err = em_check_db_privilege_by_pid(getpid());
+       if (err == EMAIL_ERROR_PERMISSION_DENIED) {
+               EM_DEBUG_LOG("permission denied");
+               goto FINISH_OFF;
+       }
+#endif
+
+       if (!emstorage_get_mailbox_by_keyword(account_id, keyword, &mailbox_tbl_list, &mailbox_count, true, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_keyword failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (mailbox_count > 0) {
+               if (!(*mailbox_list = em_malloc(sizeof(email_mailbox_t) * mailbox_count))) {
+                       EM_DEBUG_EXCEPTION("malloc failed for mailbox_list");
+                       err= EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+
+               for (i = 0; i < mailbox_count; i++)
+                       em_convert_mailbox_tbl_to_mailbox(mailbox_tbl_list + i, (*mailbox_list) + i);
+       } else
+               *mailbox_list = NULL;
 
-/* sowmya.kr, 05-Apr-2010, new MAPI*/
+       if (count)
+               *count = mailbox_count;
+
+FINISH_OFF:
+
+       if (mailbox_tbl_list != NULL)
+               emstorage_free_mailbox(&mailbox_tbl_list, mailbox_count, NULL);
+
+       EM_DEBUG_API_END ("err[%d]", err);
+       return err;
+}
 
 EXPORT_API int email_get_mailbox_by_mailbox_type(int account_id, email_mailbox_type_e mailbox_type,  email_mailbox_t** mailbox)
 {
-       EM_DEBUG_FUNC_BEGIN();
+       EM_DEBUG_FUNC_BEGIN ();
        
        int err = EMAIL_ERROR_NONE;
        email_mailbox_t* curr_mailbox = NULL;
@@ -595,9 +762,17 @@ EXPORT_API int email_get_mailbox_by_mailbox_type(int account_id, email_mailbox_t
        EM_IF_NULL_RETURN_VALUE(mailbox, EMAIL_ERROR_INVALID_PARAM);    
        EM_IF_NULL_RETURN_VALUE(account_id, EMAIL_ERROR_INVALID_PARAM)  ;
 
-
        if(mailbox_type < EMAIL_MAILBOX_TYPE_INBOX || mailbox_type > EMAIL_MAILBOX_TYPE_USER_DEFINED)
                return EMAIL_ERROR_INVALID_PARAM;
+
+#ifdef __FEATURE_ACCESS_CONTROL__
+       err = em_check_db_privilege_by_pid(getpid());
+       if (err == EMAIL_ERROR_PERMISSION_DENIED) {
+               EM_DEBUG_LOG("permission denied");
+               goto FINISH_OFF;
+       }
+#endif
+
        if (!emstorage_get_mailbox_by_mailbox_type(account_id, mailbox_type, &local_mailbox, true, &err))  {
                EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_mailbox_type failed [%d]", err);
 
@@ -614,13 +789,13 @@ FINISH_OFF:
 
        if(local_mailbox)
                emstorage_free_mailbox(&local_mailbox, 1, NULL);
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_FUNC_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_get_mailbox_by_mailbox_id(int input_mailbox_id, email_mailbox_t** output_mailbox)
 {
-       EM_DEBUG_FUNC_BEGIN();
+       EM_DEBUG_API_BEGIN ();
 
        int err = EMAIL_ERROR_NONE;
        email_mailbox_t* curr_mailbox = NULL;
@@ -628,6 +803,14 @@ EXPORT_API int email_get_mailbox_by_mailbox_id(int input_mailbox_id, email_mailb
 
        EM_IF_NULL_RETURN_VALUE(output_mailbox, EMAIL_ERROR_INVALID_PARAM);
 
+#ifdef __FEATURE_ACCESS_CONTROL__
+       err = em_check_db_privilege_by_pid(getpid());
+       if (err == EMAIL_ERROR_PERMISSION_DENIED) {
+               EM_DEBUG_LOG("permission denied");
+               return err;
+       }
+#endif
+
        if ( (err = emstorage_get_mailbox_by_id(input_mailbox_id, &local_mailbox)) != EMAIL_ERROR_NONE) {
                EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_id failed [%d]", err);
                return err;
@@ -643,13 +826,13 @@ EXPORT_API int email_get_mailbox_by_mailbox_id(int input_mailbox_id, email_mailb
 
        emstorage_free_mailbox(&local_mailbox, 1, &err);
 
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_set_mail_slot_size(int account_id, int mailbox_id, int new_slot_size)
 {
-       EM_DEBUG_FUNC_BEGIN("account_id[%d], mailbox_id[%d], new_slot_size[%d]", account_id, mailbox_id, new_slot_size);
+       EM_DEBUG_API_BEGIN ("account_id[%d] mailbox_id[%d] new_slot_size[%d]", account_id, mailbox_id, new_slot_size);
 
        int err = EMAIL_ERROR_NONE;
 
@@ -694,32 +877,38 @@ EXPORT_API int email_set_mail_slot_size(int account_id, int mailbox_id, int new_
                hAPI = NULL;
                
        }
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_stamp_sync_time_of_mailbox(int input_mailbox_id)
 {
-       EM_DEBUG_FUNC_BEGIN("input_mailbox_id [%d]", input_mailbox_id);
+       EM_DEBUG_API_BEGIN ("input_mailbox_id[%d]", input_mailbox_id);
 
        int err = EMAIL_ERROR_NONE;
 
        EM_IF_NULL_RETURN_VALUE(input_mailbox_id, EMAIL_ERROR_INVALID_PARAM);
 
+#ifdef __FEATURE_ACCESS_CONTROL__
+       err = em_check_db_privilege_by_pid(getpid());
+       if (err == EMAIL_ERROR_PERMISSION_DENIED) {
+               EM_DEBUG_LOG("permission denied");
+               return err;
+       }
+#endif
+
        err = emstorage_stamp_last_sync_time_of_mailbox(input_mailbox_id, 1);
 
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_free_mailbox(email_mailbox_t** mailbox_list, int count)
 {
-       EM_DEBUG_FUNC_BEGIN("mailbox_list[%p], count[%d]", mailbox_list, count);
+       EM_DEBUG_FUNC_BEGIN ("mailbox_list[%p] count[%d]", mailbox_list, count);
        int err = EMAIL_ERROR_NONE;
 
        if (count <= 0 || !mailbox_list || !*mailbox_list) {
-               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
-               err = EMAIL_ERROR_INVALID_PARAM;
                goto FINISH_OFF;
        }
 
@@ -729,13 +918,14 @@ EXPORT_API int email_free_mailbox(email_mailbox_t** mailbox_list, int count)
        for (i = 0; i < count; i++)  {
                EM_SAFE_FREE(p[i].mailbox_name);
                EM_SAFE_FREE(p[i].alias);
+               EM_SAFE_FREE(p[i].eas_data);
        }
 
        EM_SAFE_FREE(p);
        *mailbox_list = NULL;
 
 FINISH_OFF:
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_FUNC_END ("err[%d]", err);
        return err;
 
 }
index d87a049..1054660 100755 (executable)
 #include "email-convert.h"
 #include "email-api-mailbox.h"
 #include "email-types.h"
+#include "email-core-signal.h"
 #include "email-utilities.h"
 #include "email-ipc.h"
 #include "email-storage.h"
 
 
-
-
 EXPORT_API int email_send_mail(int mail_id, int *handle)
 {
-       EM_DEBUG_FUNC_BEGIN("mail_id[%d], handle[%p]", mail_id, handle);
+       EM_DEBUG_API_BEGIN ("mail_id[%d] handle[%p]", mail_id, handle);
        
        int err = EMAIL_ERROR_NONE;
        emstorage_mail_tbl_t* mail_table_data = NULL;
@@ -137,13 +136,13 @@ FINISH_OFF:
 
        emstorage_free_mail(&mail_table_data, 1, NULL);
 
-       EM_DEBUG_FUNC_END("err [%d]", err);  
+       EM_DEBUG_API_END ("err[%d]", err);  
        return err;     
 }
 
 EXPORT_API int email_send_mail_with_downloading_attachment_of_original_mail(int input_mail_id, int *output_handle)
 {
-       EM_DEBUG_FUNC_BEGIN("input_mail_id[%d], output_handle[%p]", input_mail_id, output_handle);
+       EM_DEBUG_API_BEGIN ("input_mail_id[%d] output_handle[%p]", input_mail_id, output_handle);
 
        int err = EMAIL_ERROR_NONE;
        emstorage_mail_tbl_t* mail_table_data = NULL;
@@ -218,13 +217,13 @@ FINISH_OFF:
 
        emstorage_free_mail(&mail_table_data, 1, NULL);
 
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_schedule_sending_mail(int input_mail_id, time_t input_scheduled_time)
 {
-       EM_DEBUG_FUNC_BEGIN("mail_id[%d], input_time[%d]", input_mail_id, input_scheduled_time);
+       EM_DEBUG_API_BEGIN ("mail_id[%d] input_time[%d]", input_mail_id, input_scheduled_time);
 
        int err = EMAIL_ERROR_NONE;
        emstorage_mail_tbl_t* mail_table_data = NULL;
@@ -290,13 +289,13 @@ FINISH_OFF:
 
        emstorage_free_mail(&mail_table_data, 1, NULL);
 
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_send_saved(int account_id, int *handle)
 {
-       EM_DEBUG_FUNC_BEGIN("account_id[%d], handle[%p]", account_id, handle);
+       EM_DEBUG_API_BEGIN ("account_id[%d] handle[%p]", account_id, handle);
        
        char* pOptionStream = NULL;
        int err = EMAIL_ERROR_NONE;
@@ -327,13 +326,13 @@ EXPORT_API int email_send_saved(int account_id, int *handle)
        hAPI = NULL;
        EM_SAFE_FREE(pOptionStream);
 
-       EM_DEBUG_FUNC_END("err [%d]", err);  
+       EM_DEBUG_API_END ("err[%d]", err);  
        return err;
 }
 
 EXPORT_API int email_sync_header(int input_account_id, int input_mailbox_id, int *handle)
 {
-       EM_DEBUG_FUNC_BEGIN("input_account_id[%d], input_mailbox_id[%d] handle[%p]", input_account_id, input_mailbox_id, handle);
+       EM_DEBUG_API_BEGIN ("input_account_id[%d] input_mailbox_id[%d] handle[%p]", input_account_id, input_mailbox_id, handle);
        int err = EMAIL_ERROR_NONE;     
        /* int total_count = 0; */
        
@@ -410,14 +409,14 @@ FINISH_OFF:
        emipc_destroy_email_api(hAPI);
        hAPI = NULL;
 
-       EM_DEBUG_FUNC_END("err [%d]", err);  
+       EM_DEBUG_API_END ("err[%d]", err);  
        return err;
 }
 
 
 EXPORT_API int email_sync_header_for_all_account(int *handle)
 {
-       EM_DEBUG_FUNC_BEGIN("handle[%p]", handle);
+       EM_DEBUG_API_BEGIN ("handle[%p]", handle);
        char* mailbox_stream = NULL;
        int err = EMAIL_ERROR_NONE;     
        HIPC_API hAPI = NULL;
@@ -505,13 +504,13 @@ FINISH_OFF:
        if ( account_tbl_array )
                emstorage_free_account(&account_tbl_array, account_count, NULL);
        
-       EM_DEBUG_FUNC_END("err [%d]", err);  
+       EM_DEBUG_API_END ("err[%d]", err);  
        return err;
 }
 
 EXPORT_API int email_download_body(int mail_id, int with_attachment, int *handle)
 {
-       EM_DEBUG_FUNC_BEGIN("mail_id[%d],with_attachment[%d]", mail_id, with_attachment);
+       EM_DEBUG_API_BEGIN ("mail_id[%d] with_attachment[%d]", mail_id, with_attachment);
        int err = EMAIL_ERROR_NONE;
        emstorage_mail_tbl_t* mail_table_data = NULL;
        int account_id = 0;
@@ -612,7 +611,7 @@ FINISH_OFF:
                emstorage_free_mail(&mail_table_data, 1, &err);
        }
 
-       EM_DEBUG_FUNC_END("err [%d]", err);  
+       EM_DEBUG_API_END ("err[%d]", err);  
        return err;
 
 }
@@ -622,7 +621,7 @@ FINISH_OFF:
 
 EXPORT_API int email_download_attachment(int mail_id, int nth, int *handle)
 {
-       EM_DEBUG_FUNC_BEGIN("mail_id[%d], nth[%d], handle[%p]", mail_id, nth, handle);
+       EM_DEBUG_API_BEGIN ("mail_id[%d] nth[%d] handle[%p]", mail_id, nth, handle);
        char* mailbox_stream = NULL;
        int err = EMAIL_ERROR_NONE;
        emstorage_mail_tbl_t* mail_table_data = NULL;
@@ -722,7 +721,7 @@ FINISH_OFF:
                emstorage_free_mail(&mail_table_data, 1, &err);
        }
 
-       EM_DEBUG_FUNC_END("err [%d]", err);  
+       EM_DEBUG_API_END ("err[%d]", err);  
        return err;
        
 }
@@ -730,7 +729,7 @@ FINISH_OFF:
 
 EXPORT_API int email_cancel_job(int input_account_id, int input_handle, email_cancelation_type input_cancel_type)
 {
-       EM_DEBUG_FUNC_BEGIN("input_account_id [%d], input_handle [%d], input_cancel_type [%d]", input_account_id, input_handle, input_cancel_type);
+       EM_DEBUG_API_BEGIN ("input_account_id[%d] input_handle[%d] input_cancel_type[%d]", input_account_id, input_handle, input_cancel_type);
        int err = EMAIL_ERROR_NONE;
        email_account_server_t account_server_type;
        HIPC_API hAPI = NULL;
@@ -850,7 +849,7 @@ FINISH_OFF:
        if (account_list)
                emstorage_free_account(&account_list, account_count, NULL);
                
-       EM_DEBUG_FUNC_END("err [%d]", err);  
+       EM_DEBUG_API_END ("err[%d]", err);  
        return err;
 }
 
@@ -858,24 +857,24 @@ FINISH_OFF:
 
 EXPORT_API int email_get_pending_job(email_action_t action, int account_id, int mail_id, email_event_status_type_t * status)
 {
-       EM_DEBUG_FUNC_BEGIN("action[%d], account_id[%d], mail_id[%d], status[%p]", action, account_id, mail_id, status);
+       EM_DEBUG_API_BEGIN ("action[%d] account_id[%d] mail_id[%d] status[%p]", action, account_id, mail_id, status);
        int err = EMAIL_ERROR_NOT_SUPPORTED;
-       EM_DEBUG_FUNC_END("err [%d]", err);  
+       EM_DEBUG_API_END ("err[%d]", err);  
        return err;
 
 }
 
 EXPORT_API int email_get_network_status(int* on_sending, int* on_receiving)
 {
-       EM_DEBUG_FUNC_BEGIN("on_sending[%p], on_receiving[%p]", on_sending, on_receiving);
+       EM_DEBUG_API_BEGIN ("on_sending[%p] on_receiving[%p]", on_sending, on_receiving);
        int err = EMAIL_ERROR_NOT_SUPPORTED;
-       EM_DEBUG_FUNC_END("err [%d]", err);  
+       EM_DEBUG_API_END ("err[%d]", err);  
        return err;
 }
 
 EXPORT_API int email_get_task_information(email_task_information_t **output_task_information, int *output_task_information_count)
 {
-       EM_DEBUG_FUNC_BEGIN("output_task_information[%p] output_task_information_count[%p]", output_task_information, output_task_information_count);
+       EM_DEBUG_API_BEGIN ("output_task_information[%p] output_task_information_count[%p]", output_task_information, output_task_information_count);
        int err = EMAIL_ERROR_NONE;
        int task_information_stream_length = 0;
        HIPC_API hAPI = NULL;
@@ -912,6 +911,7 @@ EXPORT_API int email_get_task_information(email_task_information_t **output_task
 
                        emipc_get_parameter(hAPI, ePARAMETER_OUT, 1, task_information_stream_length, task_information_stream);
                        em_convert_byte_stream_to_task_information(task_information_stream, task_information_stream_length, output_task_information, output_task_information_count);
+                       EM_SAFE_FREE(task_information_stream); /*prevent 18951*/
                }
 
                if(!output_task_information) {
@@ -925,15 +925,13 @@ FINISH_OFF:
        if(hAPI)
                emipc_destroy_email_api(hAPI);
 
-       EM_SAFE_FREE(task_information_stream); /*prevent 51266*/
-
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_sync_imap_mailbox_list(int account_id, int *handle)
 {
-       EM_DEBUG_FUNC_BEGIN();
+       EM_DEBUG_API_BEGIN ();
 
        int err = EMAIL_ERROR_NONE;
 
@@ -962,13 +960,13 @@ EXPORT_API int email_sync_imap_mailbox_list(int account_id, int *handle)
        emipc_destroy_email_api(hAPI);
        hAPI = NULL;
 
-       EM_DEBUG_FUNC_END("err [%d]", err);  
+       EM_DEBUG_API_END ("err[%d]", err);  
        return err;
 }
 
 EXPORT_API int email_search_mail_on_server(int input_account_id, int input_mailbox_id, email_search_filter_t *input_search_filter_list, int input_search_filter_count, int *output_handle)
 {
-       EM_DEBUG_FUNC_BEGIN("input_account_id [%d], input_mailbox_id [%d], input_search_filter_list [%p], input_search_filter_count [%d], output_handle [%p]", input_account_id, input_mailbox_id, input_search_filter_list, input_search_filter_count, output_handle);
+       EM_DEBUG_API_BEGIN ("input_account_id[%d] input_mailbox_id[%d] input_search_filter_list[%p] input_search_filter_count[%d] output_handle[%p]", input_account_id, input_mailbox_id, input_search_filter_list, input_search_filter_count, output_handle);
 
        int       err = EMAIL_ERROR_NONE;
        int       return_value = 0;
@@ -1037,7 +1035,7 @@ EXPORT_API int email_search_mail_on_server(int input_account_id, int input_mailb
 
                EM_PROXY_IF_NULL_RETURN_VALUE(stream_for_search_filter_list, hAPI, EMAIL_ERROR_NULL_VALUE);
 
-               if(!emipc_add_parameter(hAPI, ePARAMETER_IN, stream_for_search_filter_list, stream_size_for_search_filter_list)) {
+               if(!emipc_add_dynamic_parameter(hAPI, ePARAMETER_IN, stream_for_search_filter_list, stream_size_for_search_filter_list)) { /*prevent 18950*/
                        EM_DEBUG_EXCEPTION("emipc_add_parameter failed  ");
                        err = EMAIL_ERROR_IPC_PROTOCOL_FAILURE;
                        goto FINISH_OFF;
@@ -1065,13 +1063,13 @@ FINISH_OFF:
                hAPI = NULL;
        }
 
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_clear_result_of_search_mail_on_server(int input_account_id)
 {
-       EM_DEBUG_FUNC_BEGIN("input_account_id [%d]", input_account_id);
+       EM_DEBUG_API_BEGIN ("input_account_id[%d]", input_account_id);
 
        int       err = EMAIL_ERROR_NONE;
        int       return_value = 0;
@@ -1138,6 +1136,58 @@ FINISH_OFF:
                hAPI = NULL;
        }
 
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
+       return err;
+}
+
+EXPORT_API int email_query_smtp_mail_size_limit(int account_id, int *handle)
+{
+       EM_DEBUG_API_BEGIN ("account_id[%d] handle[%p]", account_id, handle);
+       int err = EMAIL_ERROR_NONE;
+       email_account_server_t account_server_type;
+       HIPC_API hAPI = NULL;
+
+       if (account_id <= 0) {
+               EM_DEBUG_EXCEPTION("account_id is not valid");
+               err= EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (em_get_account_server_type_by_account_id(account_id, &account_server_type, false, &err) == false ) {
+               EM_DEBUG_EXCEPTION("em_get_account_server_type_by_account_id failed[%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (account_server_type != EMAIL_SERVER_TYPE_ACTIVE_SYNC) {
+               hAPI = emipc_create_email_api(_EMAIL_API_QUERY_SMTP_MAIL_SIZE_LIMIT);
+
+               if (!hAPI ) {
+                       EM_DEBUG_EXCEPTION ("INVALID PARAM: hAPI NULL");
+                       return EMAIL_ERROR_NULL_VALUE;
+               }
+
+               /*account_id */
+               if (!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&account_id, sizeof(int))) {
+                       EM_DEBUG_EXCEPTION("email_query_smtp_mail_size_limit--Add Param mail_id failed");
+                       EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+               }
+
+               if (emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("email_query_smtp_mail_size_limit--emipc_execute_proxy_api failed  ");
+                       EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_IPC_CRASH);
+               }
+
+               emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);
+               if (err == EMAIL_ERROR_NONE) {
+                       if(handle)
+                               emipc_get_parameter(hAPI, ePARAMETER_OUT, 1, sizeof(int), handle);
+               }
+       }
+
+FINISH_OFF:
+       emipc_destroy_email_api(hAPI);
+       hAPI = (HIPC_API)NULL;
+
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
index f4a71eb..34a61f7 100755 (executable)
 
 EXPORT_API int email_get_rule(int filter_id, email_rule_t** filtering_set)
 {
-       EM_DEBUG_FUNC_BEGIN("filter_id[%d], filtering_set[%p]", filter_id, filtering_set);
+       EM_DEBUG_API_BEGIN ("filter_id[%d] filtering_set[%p]", filter_id, filtering_set);
 
        int err = 0;
 
        EM_IF_NULL_RETURN_VALUE(filtering_set, EMAIL_ERROR_INVALID_PARAM);
        EM_IF_NULL_RETURN_VALUE(filter_id, EMAIL_ERROR_INVALID_PARAM);
 
+#ifdef __FEATURE_ACCESS_CONTROL__
+       err = em_check_db_privilege_by_pid(getpid());
+       if (err == EMAIL_ERROR_PERMISSION_DENIED) {
+               EM_DEBUG_LOG("permission denied");
+               goto FINISH_OFF;
+       }
+#endif
+
        if (!emstorage_get_rule_by_id(filter_id, (emstorage_rule_tbl_t**)filtering_set, true, &err))  {
                EM_DEBUG_EXCEPTION("emstorage_get_rule_by_id failed [%d]", err);
 
@@ -54,14 +62,14 @@ EXPORT_API int email_get_rule(int filter_id, email_rule_t** filtering_set)
                err = EMAIL_ERROR_NONE;
 
 FINISH_OFF:
-       EM_DEBUG_FUNC_END("error value [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 
 EXPORT_API int email_get_rule_list(email_rule_t** filtering_set, int* count)
 {
-       EM_DEBUG_FUNC_BEGIN();
+       EM_DEBUG_API_BEGIN ();
        
        int err = EMAIL_ERROR_NONE;
        int is_completed = 0;
@@ -69,6 +77,14 @@ EXPORT_API int email_get_rule_list(email_rule_t** filtering_set, int* count)
        EM_IF_NULL_RETURN_VALUE(filtering_set, EMAIL_ERROR_INVALID_PARAM);
        EM_IF_NULL_RETURN_VALUE(count, EMAIL_ERROR_INVALID_PARAM);
 
+#ifdef __FEATURE_ACCESS_CONTROL__
+       err = em_check_db_privilege_by_pid(getpid());
+       if (err == EMAIL_ERROR_PERMISSION_DENIED) {
+               EM_DEBUG_LOG("permission denied");
+               goto FINISH_OFF;
+       }
+#endif
+
        *count = 1000;
        
        if (!emstorage_get_rule(0, 0, 0, count, &is_completed, (emstorage_rule_tbl_t**)filtering_set, true, &err))  {
@@ -79,23 +95,29 @@ EXPORT_API int email_get_rule_list(email_rule_t** filtering_set, int* count)
        } else
                err = EMAIL_ERROR_NONE;
 
-
 FINISH_OFF:
-       
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 
 }
 
 EXPORT_API int email_add_rule(email_rule_t* filtering_set)
 {
-       EM_DEBUG_FUNC_BEGIN("filtering_set[%p]", filtering_set);
+       EM_DEBUG_API_BEGIN ("filtering_set[%p]", filtering_set);
        
        int size = 0;
+       int *ret_nth_param = NULL;
        int err = EMAIL_ERROR_NONE;
        char* stream = NULL;
        
        EM_IF_NULL_RETURN_VALUE(filtering_set, EMAIL_ERROR_INVALID_PARAM);
 
+       if (filtering_set->account_id < 0 || filtering_set->target_mailbox_id < 0) {
+               EM_DEBUG_EXCEPTION("Invalid Param : account_id[%d], target_mailbox_id[%d]",
+                               filtering_set->account_id, filtering_set->target_mailbox_id);
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
        /* make rule info */
        HIPC_API hAPI = emipc_create_email_api(_EMAIL_API_ADD_RULE);    
        EM_IF_NULL_RETURN_VALUE(hAPI, EMAIL_ERROR_NULL_VALUE);
@@ -114,20 +136,28 @@ EXPORT_API int email_add_rule(email_rule_t* filtering_set)
        }
        
        /* get reult form service */
-       err = *((int*)emipc_get_nth_parameter_data(hAPI, ePARAMETER_OUT, 0));
-       if (err == EMAIL_ERROR_NONE) {
-               filtering_set->filter_id = *((int*)emipc_get_nth_parameter_data(hAPI, ePARAMETER_OUT, 1));
-       }       
+       if ((ret_nth_param = (int*)emipc_get_nth_parameter_data(hAPI, ePARAMETER_OUT, 0))) {
+               err = *ret_nth_param;
+
+               if (err == EMAIL_ERROR_NONE) {
+                       if ((ret_nth_param = (int *)emipc_get_nth_parameter_data(hAPI, ePARAMETER_OUT, 1)))
+                               filtering_set->filter_id = *ret_nth_param;
+                       else
+                               err = EMAIL_ERROR_IPC_SOCKET_FAILURE;
+               }
+       } else {
+               err = EMAIL_ERROR_IPC_SOCKET_FAILURE;
+       }
 
        emipc_destroy_email_api(hAPI);
        hAPI = NULL;
-       EM_DEBUG_FUNC_END("error value [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_update_rule(int filter_id, email_rule_t* new_set)
 {
-       EM_DEBUG_FUNC_BEGIN("filter_id[%d], new_set[%p]", filter_id, new_set);
+       EM_DEBUG_API_BEGIN ("filter_id[%d] new_set[%p]", filter_id, new_set);
        
        int size = 0;
        char* stream =  NULL;
@@ -166,7 +196,7 @@ EXPORT_API int email_update_rule(int filter_id, email_rule_t* new_set)
        emipc_destroy_email_api(hAPI);
 
        hAPI = NULL;
-       EM_DEBUG_FUNC_END("error value [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
@@ -175,7 +205,7 @@ EXPORT_API int email_update_rule(int filter_id, email_rule_t* new_set)
 
 EXPORT_API int email_delete_rule(int filter_id)
 {
-       EM_DEBUG_FUNC_BEGIN("filter_id[%d]", filter_id);
+       EM_DEBUG_API_BEGIN ("filter_id[%d]", filter_id);
        
        int err = EMAIL_ERROR_NONE;
                
@@ -200,13 +230,13 @@ EXPORT_API int email_delete_rule(int filter_id)
        emipc_destroy_email_api(hAPI);
 
        hAPI = NULL;
-       EM_DEBUG_FUNC_END("error value [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_free_rule (email_rule_t** filtering_set, int count)
 {
-       EM_DEBUG_FUNC_BEGIN();
+       EM_DEBUG_FUNC_BEGIN ();
        int err = EMAIL_ERROR_NONE, i;  
 
        EM_IF_NULL_RETURN_VALUE(filtering_set, EMAIL_ERROR_INVALID_PARAM);
@@ -222,13 +252,13 @@ EXPORT_API int email_free_rule (email_rule_t** filtering_set, int count)
                EM_SAFE_FREE(p); *filtering_set = NULL;
        }
        
-       EM_DEBUG_FUNC_END("error value [%d]", err);
+       EM_DEBUG_FUNC_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_apply_rule(int filter_id)
 {
-       EM_DEBUG_FUNC_BEGIN("filter_id[%d]", filter_id);
+       EM_DEBUG_API_BEGIN ("filter_id[%d]", filter_id);
        
        int err = EMAIL_ERROR_NONE;
                
@@ -252,6 +282,6 @@ EXPORT_API int email_apply_rule(int filter_id)
        emipc_destroy_email_api(hAPI);
 
        hAPI = NULL;
-       EM_DEBUG_FUNC_END("error value [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
index ade7f9c..96708dc 100755 (executable)
 #include "email-core-account.h"
 #include "email-core-cert.h"
 #include "email-core-smime.h"
+#include "email-core-signal.h"
 #include "email-ipc.h"
 
 EXPORT_API int email_add_certificate(char *certificate_path, char *email_address)
 {
-       EM_DEBUG_FUNC_BEGIN("Certificate path : [%s]", certificate_path);
+       EM_DEBUG_API_BEGIN ();
+       EM_DEBUG_FUNC_BEGIN_SEC("certificate_path[%s]", certificate_path);
        int result_from_ipc = 0;
        int err = EMAIL_ERROR_NONE;
        
@@ -62,13 +64,13 @@ EXPORT_API int email_add_certificate(char *certificate_path, char *email_address
        }
 
        if (!emipc_add_parameter(hAPI, ePARAMETER_IN, certificate_path, EM_SAFE_STRLEN(certificate_path)+1)) {
-               EM_DEBUG_EXCEPTION("emipc_add_parameter certificate_path[%s] failed", certificate_path);
+               EM_DEBUG_EXCEPTION_SEC("emipc_add_parameter certificate_path[%s] failed", certificate_path);
                err = EMAIL_ERROR_NULL_VALUE;
                goto FINISH_OFF;
        }
 
        if (!emipc_add_parameter(hAPI, ePARAMETER_IN, email_address, EM_SAFE_STRLEN(email_address)+1)) {
-               EM_DEBUG_EXCEPTION("emipc_add_parameter certificate_path[%s] failed", email_address);
+               EM_DEBUG_EXCEPTION_SEC("emipc_add_parameter certificate_path[%s] failed", email_address);
                err = EMAIL_ERROR_NULL_VALUE;
                goto FINISH_OFF;
        }
@@ -91,13 +93,14 @@ FINISH_OFF:
        if (hAPI)
                emipc_destroy_email_api(hAPI);
 
-       EM_DEBUG_FUNC_END("ERROR CODE [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_delete_certificate(char *email_address)
 {
-       EM_DEBUG_FUNC_BEGIN("Eamil_address : [%s]", email_address);
+       EM_DEBUG_API_BEGIN ();
+       EM_DEBUG_FUNC_BEGIN_SEC("email_address[%s]", email_address);
        int result_from_ipc = 0;
        int err = EMAIL_ERROR_NONE;
        
@@ -114,7 +117,7 @@ EXPORT_API int email_delete_certificate(char *email_address)
        }
 
        if (!emipc_add_parameter(hAPI, ePARAMETER_IN, email_address, EM_SAFE_STRLEN(email_address)+1)) {
-               EM_DEBUG_EXCEPTION("emipc_add_parameter email_address[%s] failed", email_address);
+               EM_DEBUG_EXCEPTION_SEC("emipc_add_parameter email_address[%s] failed", email_address);
                err = EMAIL_ERROR_NULL_VALUE;
                goto FINISH_OFF;
        }
@@ -137,19 +140,28 @@ FINISH_OFF:
        if (hAPI)
                emipc_destroy_email_api(hAPI);
 
-       EM_DEBUG_FUNC_END("ERROR CODE [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_get_certificate(char *email_address, email_certificate_t **certificate)
 {
-       EM_DEBUG_FUNC_BEGIN();
+       EM_DEBUG_API_BEGIN ();
        int err = EMAIL_ERROR_NONE;
        char temp_email_address[130] = {0, };
        emstorage_certificate_tbl_t *cert = NULL;
        
        EM_IF_NULL_RETURN_VALUE(email_address, EMAIL_ERROR_INVALID_PARAM);
        EM_IF_NULL_RETURN_VALUE(certificate, EMAIL_ERROR_INVALID_PARAM);
+
+#ifdef __FEATURE_ACCESS_CONTROL__
+       err = em_check_db_privilege_by_pid(getpid());
+       if (err == EMAIL_ERROR_PERMISSION_DENIED) {
+               EM_DEBUG_LOG("permission denied");
+               return err;
+       }
+#endif
+
        SNPRINTF(temp_email_address, sizeof(temp_email_address), "<%s>", email_address);
        
        if (!emstorage_get_certificate_by_email_address(temp_email_address, &cert, false, 0, &err)) {
@@ -162,16 +174,18 @@ EXPORT_API int email_get_certificate(char *email_address, email_certificate_t **
                return err;
        }       
        
-       EM_DEBUG_FUNC_END("ERROR CODE [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_get_decrypt_message(int mail_id, email_mail_data_t **output_mail_data, email_attachment_data_t **output_attachment_data, int *output_attachment_count)
 {
-       EM_DEBUG_FUNC_BEGIN("mail_id : [%d]", mail_id);
+       EM_DEBUG_API_BEGIN ("mail_id[%d]", mail_id);
        int err = EMAIL_ERROR_NONE;
        int p_output_attachment_count = 0;
+        int i = 0;
        char *decrypt_filepath = NULL;
+        char *search = NULL;
        email_mail_data_t *p_output_mail_data = NULL;
        email_attachment_data_t *p_output_attachment_data = NULL;
        emstorage_account_tbl_t *p_account_tbl = NULL;
@@ -184,6 +198,14 @@ EXPORT_API int email_get_decrypt_message(int mail_id, email_mail_data_t **output
                goto FINISH_OFF;
        }
 
+#ifdef __FEATURE_ACCESS_CONTROL__
+       err = em_check_db_privilege_by_pid(getpid());
+       if (err == EMAIL_ERROR_PERMISSION_DENIED) {
+               EM_DEBUG_LOG("permission denied");
+               goto FINISH_OFF;
+       }
+#endif
+
        if ((err = emcore_get_mail_data(mail_id, &p_output_mail_data)) != EMAIL_ERROR_NONE) {
                EM_DEBUG_EXCEPTION("emcore_get_mail_data failed");
                goto FINISH_OFF;
@@ -199,13 +221,21 @@ EXPORT_API int email_get_decrypt_message(int mail_id, email_mail_data_t **output
                goto FINISH_OFF;
        }
 
-       if (p_output_attachment_count != 1 || !p_output_attachment_data) {
-               EM_DEBUG_EXCEPTION("This is not the encrypted mail");
-               err = EMAIL_ERROR_INVALID_PARAM;
-               goto FINISH_OFF;
-       }
+        for (i = 0; i < p_output_attachment_count; i++) {
+                EM_DEBUG_LOG("mime_type : [%s]", p_output_attachment_data[i].attachment_mime_type);
+                if (p_output_attachment_data[i].attachment_mime_type && (search = strcasestr(p_output_attachment_data[i].attachment_mime_type, "PKCS7-MIME"))) {
+                        EM_DEBUG_LOG("Found the encrypt file");
+                        break;
+                }
+        }
 
-       if (!emcore_smime_set_decrypt_message(p_output_attachment_data->attachment_path, p_account_tbl->certificate_path, &decrypt_filepath, &err)) {
+        if (!search) {
+                EM_DEBUG_EXCEPTION("No have a decrypt file");
+                err = EMAIL_ERROR_INVALID_PARAM;
+                goto FINISH_OFF;
+        }
+
+       if (!emcore_smime_set_decrypt_message(p_output_attachment_data[i].attachment_path, p_account_tbl->certificate_path, &decrypt_filepath, &err)) {
                EM_DEBUG_EXCEPTION("emcore_smime_set_decrypt_message failed");
                goto FINISH_OFF;
        }
@@ -216,6 +246,17 @@ EXPORT_API int email_get_decrypt_message(int mail_id, email_mail_data_t **output
                goto FINISH_OFF;
        }
 
+       (*output_mail_data)->subject                 = EM_SAFE_STRDUP(p_output_mail_data->subject);
+       (*output_mail_data)->date_time               = p_output_mail_data->date_time;
+       (*output_mail_data)->full_address_return     = EM_SAFE_STRDUP(p_output_mail_data->full_address_return);
+       (*output_mail_data)->email_address_recipient = EM_SAFE_STRDUP(p_output_mail_data->email_address_recipient);
+       (*output_mail_data)->email_address_sender    = EM_SAFE_STRDUP(p_output_mail_data->email_address_sender);
+       (*output_mail_data)->full_address_reply      = EM_SAFE_STRDUP(p_output_mail_data->full_address_reply);
+       (*output_mail_data)->full_address_from       = EM_SAFE_STRDUP(p_output_mail_data->full_address_from);
+       (*output_mail_data)->full_address_to         = EM_SAFE_STRDUP(p_output_mail_data->full_address_to);
+       (*output_mail_data)->full_address_cc         = EM_SAFE_STRDUP(p_output_mail_data->full_address_cc);
+       (*output_mail_data)->full_address_bcc        = EM_SAFE_STRDUP(p_output_mail_data->full_address_bcc);
+
 FINISH_OFF:
 
        if (p_account_tbl)
@@ -227,13 +268,13 @@ FINISH_OFF:
        if (p_output_attachment_data)
                email_free_attachment_data(&p_output_attachment_data, p_output_attachment_count);
 
-       EM_DEBUG_FUNC_END("ERROR CODE [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_verify_signature(int mail_id, int *verify)
 {
-       EM_DEBUG_FUNC_BEGIN("mail_id : [%d]", mail_id);
+       EM_DEBUG_API_BEGIN ("mail_id[%d]", mail_id);
        int result_from_ipc = 0;
        int err = EMAIL_ERROR_NONE;
        int p_verify = 0;
@@ -274,13 +315,38 @@ FINISH_OFF:
        if (verify != NULL)
                *verify = p_verify;
 
-       EM_DEBUG_FUNC_END("ERROR CODE [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
+       return err;
+}
+
+EXPORT_API int email_verify_signature_ex(email_mail_data_t *input_mail_data, email_attachment_data_t *input_attachment_data, int input_attachment_count, int *verify)
+{
+       EM_DEBUG_API_BEGIN ();
+
+       if (!input_mail_data || !input_attachment_data || input_attachment_count <= 0) {
+               EM_DEBUG_EXCEPTION("Invalid parameter");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       int count = 0;
+       int err = EMAIL_ERROR_NONE;
+
+       for (count = 0; count < input_attachment_count ; count++) {
+               if (input_attachment_data[count].attachment_mime_type && strcasestr(input_attachment_data[count].attachment_mime_type, "SIGNATURE"))
+                       break;
+       }
+
+       if (!emcore_verify_signature(input_attachment_data[count].attachment_path, input_mail_data->file_path_mime_entity, verify, &err)) 
+               EM_DEBUG_EXCEPTION("emcore_verify_signature failed");
+
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_verify_certificate(char *certificate_path, int *verify)
 {
-       EM_DEBUG_FUNC_BEGIN("certificate : [%s]", certificate_path);
+       EM_DEBUG_API_BEGIN ();
+       EM_DEBUG_FUNC_BEGIN_SEC("certificate_path[%s]", certificate_path);
        int err = EMAIL_ERROR_NONE;
        int result_from_ipc = 0;
        int p_verify = 0;
@@ -298,7 +364,7 @@ EXPORT_API int email_verify_certificate(char *certificate_path, int *verify)
        }
 
        if (!emipc_add_parameter(hAPI, ePARAMETER_IN, certificate_path, EM_SAFE_STRLEN(certificate_path)+1)) {
-               EM_DEBUG_EXCEPTION("emipc_add_paramter failed : [%s]", certificate_path);
+               EM_DEBUG_EXCEPTION_SEC("emipc_add_paramter failed : [%s]", certificate_path);
                err = EMAIL_ERROR_NULL_VALUE;
                goto FINISH_OFF;
        }
@@ -324,14 +390,14 @@ FINISH_OFF:
        if (verify != NULL)
                *verify = p_verify;
 
-       EM_DEBUG_FUNC_END("ERROR CODE [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 /*
 EXPORT_API int email_check_ocsp_status(char *email_address, char *response_url, unsigned *handle)
 {
-       EM_DEBUG_FUNC_BEGIN("email_address : [%s], response_url : [%s], handle : [%p]", email_address, response_url, handle);
+       EM_DEBUG_FUNC_BEGIN_SEC("email_address : [%s], response_url : [%s], handle : [%p]", email_address, response_url, handle);
 
        EM_IF_NULL_RETURN_VALUE(email_address, EMAIL_ERROR_INVALID_PARAM);
 
@@ -366,7 +432,8 @@ EXPORT_API int email_check_ocsp_status(char *email_address, char *response_url,
 */
 EXPORT_API int email_validate_certificate(int account_id, char *email_address, unsigned *handle)
 {
-       EM_DEBUG_FUNC_BEGIN("account_id : [%d], email_address : [%s], handle : [%p]", account_id, email_address, handle);
+       EM_DEBUG_API_BEGIN ("account_id[%d]", account_id);
+       EM_DEBUG_FUNC_BEGIN_SEC("account_id[%d] email_address[%s] handle[%p]", account_id, email_address, handle);
        
        EM_IF_NULL_RETURN_VALUE(account_id, EMAIL_ERROR_INVALID_PARAM);
        EM_IF_NULL_RETURN_VALUE(email_address, EMAIL_ERROR_INVALID_PARAM);
@@ -411,13 +478,14 @@ EXPORT_API int email_validate_certificate(int account_id, char *email_address, u
 
 FINISH_OFF:
 
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_get_resolve_recipients(int account_id, char *email_address, unsigned *handle)
 {
-       EM_DEBUG_FUNC_BEGIN("account_id : [%d], email_address : [%s], handle : [%p]", account_id, email_address, handle);
+       EM_DEBUG_API_BEGIN ("account_id[%d]", account_id);
+       EM_DEBUG_FUNC_BEGIN_SEC("account_id[%d] email_address[%s] handle[%p]", account_id, email_address, handle);
        
        EM_IF_NULL_RETURN_VALUE(account_id, EMAIL_ERROR_INVALID_PARAM);
        EM_IF_NULL_RETURN_VALUE(email_address, EMAIL_ERROR_INVALID_PARAM);
@@ -462,15 +530,15 @@ EXPORT_API int email_get_resolve_recipients(int account_id, char *email_address,
 
 FINISH_OFF:
 
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
 
 EXPORT_API int email_free_certificate(email_certificate_t **certificate, int count)
 {
-       EM_DEBUG_FUNC_BEGIN("certificate[%p], count[%d]", certificate, count);
+       EM_DEBUG_API_BEGIN ("certificate[%p] count[%d]", certificate, count);
        int err = EMAIL_ERROR_NONE;
        emcore_free_certificate(certificate, count, &err);
-       EM_DEBUG_FUNC_END("err [%d]", err);
+       EM_DEBUG_API_END ("err[%d]", err);
        return err;
 }
index 3c7b78b..98c545c 100755 (executable)
 *      account->outgoing_server_need_authentication           = 1;
 *      account->outgoing_server_user_name           = strdup("tom@gmail.com");
 *      account->sending_password       = strdup("password");
+*      account->auto_resend_times        = 0;
 *      account->pop_before_smtp        = 0;
 *      account->incoming_server_requires_apop                   = 0;
-*      account->flag1                  = 2;
-*      account->flag2                  = 1;
+*      account->incoming_server_authentication_method                   = 0;
 *      account->is_preset_account         = 1;
 *      account->logo_icon_path         = strdup("Logo Icon Path");
 *      account->options.priority = 3;
@@ -158,7 +158,6 @@ extern "C" {
 #endif /* __cplusplus */
 
 /**
-
  * @fn email_add_account(email_account_t* account)
  * @brief      Create a new email account.This function is invoked when user wants to add new email account
  *
@@ -171,7 +170,6 @@ extern "C" {
 EXPORT_API int email_add_account(email_account_t* account);
 
 /**
-
  * @fn email_delete_account(int account_id)
  * @brief       Delete a email account.This function is invoked when user wants to delete an existing email account
  *
@@ -184,7 +182,6 @@ EXPORT_API int email_add_account(email_account_t* account);
 EXPORT_API int email_delete_account(int account_id);
 
 /**
-
  * @fn email_update_account(int account_id, email_account_t* new_account)
  * @brief      Change the information of a email account.This function is getting invoked when user wants to change some information of existing email account.
  *
@@ -199,7 +196,6 @@ EXPORT_API int email_delete_account(int account_id);
 EXPORT_API int email_update_account(int account_id, email_account_t* new_account);
 
 /**
-
  * @fn email_update_account_with_validation(int account_id, email_account_t* new_account)
  * @brief      Change the information of a email account.This function is getting invoked when user wants to change some information of existing email account.
  *
@@ -214,7 +210,6 @@ EXPORT_API int email_update_account(int account_id, email_account_t* new_account
 EXPORT_API int email_update_account_with_validation(int account_id, email_account_t* new_account);
 
 /**
-
  * @fn  email_get_account(int account_id, int pulloption, email_account_t** account)
  * @brief      Get an email account by ID. This function is getting invoked when user wants to get the account informantion based on account id and option (GET_FULL_DATA/WITHOUT_OPTION/ONLY_OPTION).<br>
  *                     Memory for account information will be allocated to 3rd param(account). The allocated memory should be freed by email_free_account().
@@ -227,11 +222,9 @@ EXPORT_API int email_update_account_with_validation(int account_id, email_accoun
  * @see email_account_t
  * @remarks N/A
  */
-
 EXPORT_API int email_get_account(int account_id, int pulloption, email_account_t** account);
 
 /**
-
  * @fn email_get_account_list(email_account_t** account_list, int* count);
  * @brief      Get Account List.This function is getting invoked when user wants to get all account information based on the count of accounts provided by user.<br>
  *                     Memory for account information will be allocated to 3rd param(account). The allocated memory should be freed by email_free_account().
@@ -245,8 +238,7 @@ EXPORT_API int email_get_account(int account_id, int pulloption, email_account_t
  */
 EXPORT_API int email_get_account_list(email_account_t** account_list, int* count);
 
- /**
-
+/**
  * @fn   email_free_account(email_account_t** account_list, int count);
  * @brief      Free allocated memory.This function is getting invoked when user wants to delete all account information.
  *
@@ -261,7 +253,6 @@ EXPORT_API int email_free_account(email_account_t** account_list, int count);
 
 
 /**
-
  * @fn email_validate_account(int account_id, int *handle)
  * @brief      Validate account.This function is getting invoked  after adding one account to validate it.If account is not validated then user should retry once again to add the account .
  *
@@ -275,10 +266,21 @@ EXPORT_API int email_free_account(email_account_t** account_list, int count);
  */
 EXPORT_API int email_validate_account(int account_id, int *handle) DEPRECATED; /* Will be replaced with email_validate_account_ex */
 
+/**
+ * @fn email_validate_account_ex(email_account_t* account, int *handle)
+ * @brief      Validate account.This function is getting invoked after adding one account to validate it.If account is not validated then user should retry once again to add the account .
+ *
+ * @param[in] account  Specifies the account structure
+ * @param[out] handle  Specifies the sending handle.
+ * @remarks N/A
+ * @exception EMAIL_ERROR_INVALID_PARAM - Invalid argument
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @see                email_account_t
+ * @remarks N/A
+ */
 EXPORT_API int email_validate_account_ex(email_account_t* account, int *handle);
 
 /**
-
  * @fn email_add_account_with_validation(email_account_t* account, int *handle)
  * @brief      Add an account when the account is validated. This function is getting invoked when user want to validate an account. If account is not validated then user should retry once again to add the account.<br>
  *              Validation is executed without saving an account to DB
@@ -292,7 +294,6 @@ EXPORT_API int email_add_account_with_validation(email_account_t* account, int *
 
 
 /**
-
  * @fn email_backup_accounts_into_secure_storage(const char *file_name)
  * @brief      Back up information of all accounts into secure storage.
  *          This function is getting invoked when user want to backup account information safely.
@@ -304,7 +305,6 @@ EXPORT_API int email_add_account_with_validation(email_account_t* account, int *
 EXPORT_API int email_backup_accounts_into_secure_storage(const char *file_name);
 
 /**
-
  * @fn email_restore_accounts_from_secure_storage(const char *file_name)
  * @brief      Restore accounts from stored file in secure storage.
  *          This function is getting invoked when user want to restore accounts.
@@ -316,21 +316,20 @@ EXPORT_API int email_backup_accounts_into_secure_storage(const char *file_name);
 EXPORT_API int email_restore_accounts_from_secure_storage(const char * file_name);
 
 /**
-
  * @fn email_get_password_length_of_account(const int account_id, int *password_length)
  * @brief      Get password length of an account.
  *          This function is getting invoked when user want to know the length of an account.
  *
  * @param[in] account_id    Specifies the account id
- * @param[out] handle          Specifies the password length.
+ * @param[in] password_type Specifies the password type
+ * @param[out] password_length         Specifies the password length.
  * @remarks N/A
  * @return This function returns true on success or false on failure.
  */
-EXPORT_API int email_get_password_length_of_account(const int account_id, int *password_length);
+EXPORT_API int email_get_password_length_of_account(int account_id, int *password_length);
 
 
 /**
-
  * @fn email_query_server_info(const char* domain_name, email_server_info_t **result_server_info)
  * @brief      Query email server information.
  *          This function is getting invoked when user want to get email server information.
@@ -343,7 +342,6 @@ EXPORT_API int email_get_password_length_of_account(const int account_id, int *p
 EXPORT_API int email_query_server_info(const char* domain_name, email_server_info_t **result_server_info);
 
 /**
-
  * @fn email_free_server_info(email_server_info_t **result_server_info)
  * @brief      Free email_server_info_t.
  *          This function is getting invoked when user want to free email_server_info_t.
@@ -355,7 +353,6 @@ EXPORT_API int email_query_server_info(const char* domain_name, email_server_inf
 EXPORT_API int email_free_server_info(email_server_info_t **result_server_info);
 
 /**
-
  * @fn email_update_notification_bar(int account_id)
  * @brief      Update notifications on notification bar.
  *          This function is getting invoked when user want to update notification bar.
@@ -367,7 +364,6 @@ EXPORT_API int email_free_server_info(email_server_info_t **result_server_info);
 EXPORT_API int email_update_notification_bar(int account_id);
 
 /**
-
  * @fn email_clear_all_notification_bar()
  * @brief      Clear all notification on notification bar.
  *          This function is getting invoked when user want to clear notification bar.
@@ -379,7 +375,6 @@ EXPORT_API int email_clear_all_notification_bar();
 
 
 /**
-
  * @fn email_save_default_account_id()
  * @brief      Save default account id to vconf storage.
  *          This function is getting invoked when user want to save default account id.
@@ -390,7 +385,6 @@ EXPORT_API int email_clear_all_notification_bar();
 EXPORT_API int email_save_default_account_id(int input_account_id);
 
 /**
-
  * @fn email_load_default_account_id()
  * @brief      Load default account id to vconf storage.
  *          This function is getting invoked when user want to load default account id.
index f397fd9..4d6d2e5 100755 (executable)
@@ -52,9 +52,7 @@ extern "C" {
 #include "email-types.h"
 
 /**
-
-
- * @fn email_show_user_message(void)
+ * @fn email_show_user_message
  * @brief      This function show user message.
  *
  * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
@@ -64,12 +62,56 @@ extern "C" {
  */
 EXPORT_API int email_show_user_message(int id, email_action_t action, int error_code);
 
+/**
+ * @fn email_parse_mime_file
+ * @brief      This function parse mime file
+ * @param[in]  eml_file_path
+ * @param[out] output_mail_data
+ * @param[out] output_attachment_data
+ * @param[out] output_attachment_count
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @exception  none
+ * @see
+ * @remarks N/A
+ */
 EXPORT_API int email_parse_mime_file(char *eml_file_path, email_mail_data_t **output_mail_data, email_attachment_data_t **output_attachment_data, int *output_attachment_count);
 
+/**
+ * @fn email_write_mime_file
+ * @brief      This function create mime file from input data
+ * @param[in]  input_mail_data
+ * @param[in]  input_attachment_data
+ * @param[in]  input_attachment_count
+ * @param[out] output_file_path
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @exception  none
+ * @see
+ * @remarks N/A
+ */
 EXPORT_API int email_write_mime_file(email_mail_data_t *input_mail_data, email_attachment_data_t *input_attachment_data, int input_attachment_count, char **output_file_path);
 
+/**
+ * @fn email_delete_parsed_data
+ * @brief      This function delete parsed files of mime
+ * @param[in]  input_mail_data
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @exception  none
+ * @see
+ * @remarks N/A
+ */
 EXPORT_API int email_delete_parsed_data(email_mail_data_t *input_mail_data);
 
+
+/**
+ * @fn email_get_mime_entity
+ * @brief      This function get mime entity
+ * @param[in]  mime_path
+ * @param[out] mime_entity
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @exception  none
+ * @see
+ * @remarks N/A
+ */
 EXPORT_API int email_get_mime_entity(char *mime_path, char **mime_entity);
 #ifdef __cplusplus
 }
index 96ee737..6e2ffe1 100755 (executable)
@@ -45,7 +45,7 @@
  * @author     Kyuho Jo <kyuho.jo@samsung.com>
  * @author     Sunghyun Kwon <sh0701.kwon@samsung.com>
  * @version    0.1
- * @brief              This file contains the data structures and interfaces of Email FW Initialization provided by
+ * @brief      This file contains the data structures and interfaces of Email FW Initialization provided by
  *                     email-service .
  *@{
  *@code
@@ -97,8 +97,6 @@ extern "C" {
 #endif /* __cplusplus */
 
 /**
-
-
  * @fn email_init_storage(void)
  * @brief      Create all tables for email.
  *
@@ -110,8 +108,6 @@ extern "C" {
 EXPORT_API int email_init_storage(void);
 
 /**
-
-
  * @fn email_open_db(void)
  * @brief This function Open the email DB and register busy handler
  *
@@ -124,8 +120,6 @@ EXPORT_API int email_open_db(void);
 
 
 /**
-
-
  * @fn email_close_db(void)
  * @brief      This function closes the connection of  the email DB
  *
@@ -137,8 +131,6 @@ EXPORT_API int email_open_db(void);
 EXPORT_API int email_close_db(void);
 
 /**
-
-
  * @fn email_service_begin(void)
  * @brief      Does the IPC Proxy Initialization by the Application which used the Email FW API's
  *
@@ -150,8 +142,6 @@ EXPORT_API int email_close_db(void);
 EXPORT_API int email_service_begin(void);
 
 /**
-
-
  * @fn email_service_end(void)
  * @brief      This function does the IPC Proxy Finaization by the Application which used the Email FW API's
  *
@@ -162,6 +152,17 @@ EXPORT_API int email_service_begin(void);
  */
 EXPORT_API int email_service_end(void);
 
+/**
+ * @fn email_ping_service(void)
+ * @brief      This function check email-service process is running or not
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @exception  none
+ * @see        none
+ * @remarks N/A
+ */
+EXPORT_API int email_ping_service(void);
+
 #ifdef __cplusplus
 }
 #endif /* __cplusplus */
index 57ee6de..212cd81 100755 (executable)
@@ -24,9 +24,7 @@
 #define __EMAIL_API_MAIL_H__
 
 #include "email-types.h"
-
 #include <time.h>
-
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <unistd.h>
  *
  * This file contains the data structures and interfaces needed for application,
  * to interact with email-service.
- * @file               email-api-mail.h
+ * @file       email-api-mail.h
  * @author     Kyuho Jo <kyuho.jo@samsung.com>
  * @author     Sunghyun Kwon <sh0701.kwon@samsung.com>
  * @version    0.1
- * @brief              This file contains the data structures and interfaces of Messages provided by
+ * @brief      This file contains the data structures and interfaces of Messages provided by
  *                     email-service .
  */
 
@@ -202,18 +200,17 @@ extern "C" {
  */
 EXPORT_API int email_add_mail(email_mail_data_t *input_mail_data, email_attachment_data_t *input_attachment_data_list, int input_attachment_count, email_meeting_request_t* input_meeting_request, int input_from_eas);
 
- /**
-
-  * @fn email_add_read_receipt(int input_read_mail_id,  int *output_handle)
-  * @brief     Add a read receipt mail. This function is invoked when user receives a mail with read report enable and wants to send a read report for the same.
-  *
-  * @return    This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
-  * @param[in]  input_read_mail_id     Specifies the id of mail which has been read.
-  * @param[out] output_receipt_mail_id Specifies the receipt mail id .
-  * @exception none
-  * @see
-  * @remarks N/A
-  */
+/**
+ * @fn email_add_read_receipt(int input_read_mail_id,  int *output_handle)
+ * @brief      Add a read receipt mail. This function is invoked when user receives a mail with read report enable and wants to send a read report for the same.
+ *
+ * @return     This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in]  input_read_mail_id      Specifies the id of mail which has been read.
+ * @param[out] output_receipt_mail_id  Specifies the receipt mail id .
+ * @exception none
+ * @see
+ * @remarks N/A
+ */
 EXPORT_API int email_add_read_receipt(int input_read_mail_id, int *output_receipt_mail_id);
 
 /**
@@ -295,6 +292,20 @@ EXPORT_API int email_add_read_receipt(int input_read_mail_id, int *output_receip
  */
 EXPORT_API int email_update_mail(email_mail_data_t *input_mail_data, email_attachment_data_t *input_attachment_data_list, int input_attachment_count, email_meeting_request_t* input_meeting_request, int input_from_eas);
 
+/**
+ * @fn email_update_mail_attribute(int input_account_id, int *input_mail_id_array, int input_mail_id_count, email_mail_attribute_type input_attribute_type, email_mail_attribute_value_t input_value)
+ * @brief      This function update individual attribute of mail data.
+ *
+ * @return     This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in]  input_account_id        Specifies the id of account.
+ * @param[in]  input_mail_id_array Specify the array list if mail id
+ * @param[in]  input_mail_id_count Specify the count of mail id array
+ * @param[in]  input_attribute_type Specify the attribute type which to update
+ * @param[in]  input_value Specify the value of attribute
+ * @exception none
+ * @see
+ * @remarks N/A
+ */
 EXPORT_API int email_update_mail_attribute(int input_account_id, int *input_mail_id_array, int input_mail_id_count, email_mail_attribute_type input_attribute_type, email_mail_attribute_value_t input_value);
 
 /**
@@ -434,7 +445,6 @@ EXPORT_API int email_delete_mail(int input_mailbox_id, int *input_mail_ids, int
 EXPORT_API int email_delete_all_mails_in_mailbox(int input_mailbox_id, int input_from_server);
 
 /**
-
  *  @fn email_clear_mail_data()
  * @brief      delete email data from storage. This API will be used by the Settings Application
  *
@@ -460,7 +470,6 @@ EXPORT_API int  email_clear_mail_data();
 
 
 /**
-
  * @fn email_add_attachment(int mail_id, email_attachment_data_t* attachment)
  * @brief      Append a attachment to email.This function is invoked when user wants to add attachment to existing mail.
  *
@@ -498,7 +507,6 @@ EXPORT_API int email_add_attachment(int mail_id, email_attachment_data_t* attach
 
 
 /**
-
  * @fn email_delete_attachment(int mail_id, const char * attachment_id)
  * @brief      delete a attachment from email.This function is invoked when user wants to delete a attachment from existing mailbased on mail Id and attachment Id
  *
@@ -524,7 +532,6 @@ EXPORT_API int email_add_attachment(int mail_id, email_attachment_data_t* attach
 EXPORT_API int email_delete_attachment(int attachment_id);
 
 /**
-
  * @fn email_get_attachment_data(int mail_id, const char* attachment_id, email_attachment_data_t** attachment)
  * @brief      Get a mail attachment.This function is invoked when user wants to get the attachment information based on attachment id for the specified mail Id.
  *
@@ -564,10 +571,21 @@ EXPORT_API int email_delete_attachment(int attachment_id);
  */
 EXPORT_API int email_get_attachment_data(int attachment_id, email_attachment_data_t** attachment);
 
+/**
+ * @fn email_get_attachment_data_list(int input_mail_id, email_attachment_data_t **output_attachment_data, int *output_attachment_count)
+ * @brief      Get a list of mail attachment.This function is invoked when user wants to get the information of attachment list based on mail id.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] input_mail_id            Specifies the mail ID.
+ * @param[out] output_attachment_data  The returned attachment list is save here.
+ * @param[out] output_attachment_count The returned count of attachment list.
+ * @exception  none
+ * @see                email_attachment_data_t
+ * @remarks N/A
+ */
 EXPORT_API int email_get_attachment_data_list(int input_mail_id, email_attachment_data_t **output_attachment_data, int *output_attachment_count);
 
 /**
-
  * @fn email_free_attachment_data(email_attachment_data_t **attachment_data_list, int attachment_data_count)
  * @brief      Free allocated memroy for email attachment.
  *
@@ -610,13 +628,12 @@ EXPORT_API int email_get_attachment_data_list(int input_mail_id, email_attachmen
  */
 EXPORT_API int email_free_attachment_data(email_attachment_data_t **attachment_data_list, int attachment_data_count);
 
-/* -----------------------------------------------------------
-                                             Mail Information API
-    -----------------------------------------------------------*/
+/*-----------------------------------------------------------
+                                       Mail Information API
+  -----------------------------------------------------------*/
 
 
 /**
-
  * @fn email_query_mails(char *conditional_clause_string, email_mail_data_t** mail_list,  int *result_count)
  * @brief                          Query the mail list information from DB based on the mailbox name.
  *
@@ -649,14 +666,13 @@ EXPORT_API int email_free_attachment_data(email_attachment_data_t **attachment_d
  *                     free(mail_list);
  *             }
  *
- *     }
+ *     }
  * @endcode
  * @remarks N/A
  */
 EXPORT_API int email_query_mails(char *conditional_clause_string, email_mail_data_t** mail_list,  int *result_count);
 
 /**
-
  * @fn email_query_mail_list(char *input_conditional_clause_string, email_mail_list_item_t** output_mail_list,  int *output_result_count)
  * @brief Query the mail list information from DB.
  *
@@ -696,7 +712,6 @@ EXPORT_API int email_query_mails(char *conditional_clause_string, email_mail_dat
 EXPORT_API int email_query_mail_list(char *input_conditional_clause_string, email_mail_list_item_t** output_mail_list,  int *output_result_count);
 
 /**
-
  * @fn email_get_mail_data(int input_mail_id, email_mail_data_t **output_mail_data)
  * @brief      Get a mail by its mail id. This function is invoked when user wants to get a mail based on mail id existing in DB.
  *
@@ -735,7 +750,6 @@ EXPORT_API int email_get_mail_data(int input_mail_id, email_mail_data_t **output
 
 
 /**
-
  * @fn email_free_mail_data(email_mail_data_t** mail_list, int count)
  * @brief      Free allocated memroy for emails.
  *
@@ -765,12 +779,11 @@ EXPORT_API int email_get_mail_data(int input_mail_id, email_mail_data_t **output
  */
 EXPORT_API int email_free_mail_data(email_mail_data_t** mail_list, int count);
 
-/* -----------------------------------------------------------
-                                             Mail Flag API
-    -----------------------------------------------------------*/
+/*-----------------------------------------------------------
+                                       Mail Flag API
+  -----------------------------------------------------------*/
 
 /**
-
  * @fn email_set_flags_field(int *mail_ids, int num, email_flags_field_type field_type, int value, int onserver)
  * @brief      Change email flags field.
  *             If the incoming_server_type is EMAIL_SERVER_TYPE_POP3 then from_server value will be 0
@@ -810,15 +823,13 @@ EXPORT_API int email_free_mail_data(email_mail_data_t** mail_list, int count);
  * @endcode
  * @remarks N/A
  */
-
 EXPORT_API int email_set_flags_field(int account_id, int *mail_ids, int num, email_flags_field_type field_type, int value, int onserver);
 
 /* -----------------------------------------------------------
-                                             Mail Move API
-    -----------------------------------------------------------*/
+                                       Mail Move API
+   -----------------------------------------------------------*/
 
 /**
-
  * @fn email_move_mail_to_mailbox(int *mail_ids, int num, int input_target_mailbox_id)
  * @brief      Move a email to another mailbox.
  *
@@ -853,7 +864,6 @@ EXPORT_API int email_set_flags_field(int account_id, int *mail_ids, int num, ema
  */
 EXPORT_API int email_move_mail_to_mailbox(int *mail_ids, int num, int input_target_mailbox_id);
 
-
 /**
  * @fn email_move_all_mails_to_mailbox(int input_source_mailbox_id, int input_target_mailbox_id)
  * @brief      Move all email to another mailbox.
@@ -913,7 +923,6 @@ EXPORT_API int email_move_mails_to_mailbox_of_another_account(int input_source_m
 
 
 /**
-
  * @fn email_get_mail_list_ex(email_list_filter_t *input_filter_list, int input_filter_count, email_list_sorting_rule_t *input_sorting_rule_list, int input_sorting_rule_count, int input_start_index, int input_limit_count, email_mail_list_item_t** output_mail_list, int *output_result_count)
  * @brief      Get the Mail List information from DB.
  *
@@ -1010,10 +1019,20 @@ EXPORT_API int email_move_mails_to_mailbox_of_another_account(int input_source_m
  */
 EXPORT_API int email_get_mail_list_ex(email_list_filter_t *input_filter_list, int input_filter_count, email_list_sorting_rule_t *input_sorting_rule_list, int input_sorting_rule_count, int input_start_index, int input_limit_count, email_mail_list_item_t** output_mail_list, int *output_result_count);
 
+/**
+ * @fn email_free_list_filter(email_list_filter_t **input_filter_list, int input_filter_count)
+ * @brief      Free allocated memroy for filers.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] input_filter_list        Specifies the pointer of filter structure.
+ * @param[in] input_filter_count       Specifies the count of filter.
+ * @exception          none
+ * @see                        email_list_filter_t
+ * @remarks N/A
+ */
 EXPORT_API int email_free_list_filter(email_list_filter_t **input_filter_list, int input_filter_count);
 
 /**
-
  * @fn email_get_mails(int account_id , int mailbox_id, int thread_id, int start_index, int limit_count, email_sort_type_t sorting, email_mail_data_t** mail_list,  int* result_count)
  * @brief      Get the Mail List information from DB based on the mailbox name.
  *
@@ -1063,7 +1082,6 @@ EXPORT_API int email_free_list_filter(email_list_filter_t **input_filter_list, i
 EXPORT_API int email_get_mails(int account_id , int mailbox_id, int thread_id, int start_index, int limit_count, email_sort_type_t sorting, email_mail_data_t** mail_list,  int* result_count);
 
 /**
-
  * @fn email_get_mail_list(int account_id, int mailbox_id, int thread_id, int start_index, int limit_count, email_sort_type_t sorting, email_mail_list_item_t** mail_list,  int* result_count)
  * @brief      Get the Mail List information from DB based on the mailbox name.
  *
@@ -1114,7 +1132,6 @@ EXPORT_API int email_get_mails(int account_id , int mailbox_id, int thread_id, i
 EXPORT_API int email_get_mail_list(int account_id, int mailbox_id, int thread_id, int start_index, int limit_count, email_sort_type_t sorting, email_mail_list_item_t** mail_list,  int* result_count);
 
 /**
-
  * @fn         email_get_mail_by_address(int account_id, int mailbox_id, email_email_address_list_t* addr_list,
                                                                        int start_index, int limit_count, email_sort_type_t sorting, email_mail_list_item_t** mail_list,  int* result_count)
  * @brief      Get the Mail List information from the DB based on the mailbox name account_id and sender address.
@@ -1140,7 +1157,6 @@ EXPORT_API int email_get_mail_by_address(int account_id , int mailbox_id, email_
                                                                        int start_index, int limit_count, int search_type, const char *search_value, email_sort_type_t sorting, email_mail_list_item_t** mail_list,  int* result_count);
 
 /**
-
  * @fn email_get_thread_information_by_thread_id(int thread_id, email_mail_data_t** thread_info)
  * @brief      Get the thread information for specific thread from DB based on the mailbox name.
  *
@@ -1175,12 +1191,9 @@ EXPORT_API int email_get_mail_by_address(int account_id , int mailbox_id, email_
  * @endcode
  * @remarks N/A
  */
-
-
 EXPORT_API int email_get_thread_information_by_thread_id(int thread_id, email_mail_data_t** thread_info);
 
 /**
-
  * @fn email_get_thread_information_ex(int thread_id, email_mail_list_item_t** thread_info)
  * @brief      Get the Mail List information for specific thread from DB based on the mailbox name.
  *
@@ -1217,10 +1230,7 @@ EXPORT_API int email_get_thread_information_by_thread_id(int thread_id, email_ma
  */
 EXPORT_API int email_get_thread_information_ex(int thread_id, email_mail_list_item_t** thread_info);
 
-
-
 /**
-
  * @fn email_retry_sending_mail( int mail_id, int timeout_in_sec)
  * @brief      Retry mail send
  *
@@ -1249,10 +1259,18 @@ EXPORT_API int email_get_thread_information_ex(int thread_id, email_mail_list_it
  */
 EXPORT_API int email_retry_sending_mail(int mail_id, int timeout_in_sec);
 
+/**
+ * @fn email_create_db_full()
+ * @brief      Create db and fill with dummy data
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @exception          none
+ * @see                                none
+ * @remarks N/A
+ */
 EXPORT_API int email_create_db_full();
 
 /**
-
  * @fn email_cancel_sending_mail( int mail_id)
  * @brief      Callback function for cm popup. We set the status as EMAIL_MAIL_STATUS_SEND_CANCELED
  *
@@ -1279,8 +1297,7 @@ EXPORT_API int email_create_db_full();
  */
 EXPORT_API int email_cancel_sending_mail(int mail_id) ;
 
- /**
-
+/**
  * @fn email_get_disk_space_usage(unsigned long *total_size)
  * @brief      Gets the total disk usage of emails in KB.
  *
@@ -1305,7 +1322,6 @@ EXPORT_API int email_cancel_sending_mail(int mail_id) ;
 EXPORT_API int email_get_disk_space_usage(unsigned long *total_size);
 
 /**
-
  * @fn         email_get_address_info_list(int mail_id, email_address_info_list_t** address_info_list)
  * @brief      Get the address info list. The address info list contains from, to, cc, bcc addresses and their display name, contact id and etc. (see email_address_info_list_t)
  *                     Each GList (from, to, cc, bcc) is the list of email_address_info_t data.
@@ -1361,7 +1377,6 @@ EXPORT_API int email_get_disk_space_usage(unsigned long *total_size);
 EXPORT_API int email_get_address_info_list(int mail_id, email_address_info_list_t** address_info_list);
 
 /**
-
  * @fn email_free_address_info_list(email_address_info_list_t **address_info_list)
  * @brief      Free the address info list allocated by email_get_address_info_list(). This function will free the memory which is allocated to address_info_list itself.
  *
@@ -1373,7 +1388,6 @@ EXPORT_API int email_get_address_info_list(int mail_id, email_address_info_list_
 EXPORT_API int email_free_address_info_list(email_address_info_list_t **address_info_list);
 
 /**
-
  * @fn email_get_structure(const char*encoded_string, void **struct_var, email_convert_struct_type_e type)
  * @brief      This function returns the structure of the type which is indicated by 'type' variable. This function will allocate new memory to 'struct_var' for structure.<br>
  *                     Some notifications such as NOTI_DOWNLOAD_NEW_MAIL are published with string parameter. The string contains various values that might be divided by delimiter.<br>
@@ -1390,6 +1404,21 @@ EXPORT_API int email_get_structure(const char*encoded_string, void **struct_var,
 /**
 
  * @fn email_get_meeting_request(int mail_id, email_meeting_request_t **meeting_req)
+ * @brief      Query the information of meeting request.
+ *                     The information of meeting request is corresponding to only one mail.
+ *                     For this reason, the information of meeting request can be added by using email_add_message_with_meeting_request() with a matched mail information.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success. This function returns EMAIL_ERROR_DATA_NOT_FOUND if there isn't a matched mail. Otherwise it returns error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] input_conditional_clause_string  Specifies the where clause string.
+ * @param[out] output_meeting_req      Specifies the Pointer to the structure email_meeting_request_t.
+ * @param[out] output_count    Specifies the number of meeting request returned.
+ * @exception  none
+ * @see        email_meeting_request_t
+ */
+EXPORT_API int email_query_meeting_request(char *input_conditional_clause_string, email_meeting_request_t **output_meeting_req, int *output_count);
+
+/**
+ * @fn email_get_meeting_request(int mail_id, email_meeting_request_t **meeting_req)
  * @brief      Get the information of meeting request.  The information of meeting request is based on Mail Id. <br>
  *                     The information of meeting request is corresponding to only one mail.
  *                     For this reason, the information of meeting request can be added by using email_add_message_with_meeting_request() with a matched mail information.
@@ -1402,9 +1431,7 @@ EXPORT_API int email_get_structure(const char*encoded_string, void **struct_var,
  */
 EXPORT_API int email_get_meeting_request(int mail_id, email_meeting_request_t **meeting_req);
 
-
 /**
-
  * @fn email_free_meeting_request(email_meeting_request_t** meeting_req, int count)
  * @brief      Free the meeting request allocated by email_get_meeting_request() or alloacted to add. This function will free the memory which is allocated to meeting_req (= *meeting_req) itself.
  *
@@ -1416,12 +1443,55 @@ EXPORT_API int email_get_meeting_request(int mail_id, email_meeting_request_t **
  */
 EXPORT_API int email_free_meeting_request(email_meeting_request_t** meeting_req, int count);
 
+/**
+ * @fn email_move_thread_to_mailbox(int thread_id, int target_mailbox_id, int move_always_flag)
+ * @brief      Move a thread of mails to target mailbox.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] thread_id        Specifies the thread id to move
+ * @param[in] target_mailbox_id        Specifies the mailbox id which move in
+ * @param[in] move_always_flag Specify move always flag
+ * @exception none
+ * @see
+ */
 EXPORT_API int email_move_thread_to_mailbox(int thread_id, int target_mailbox_id, int move_always_flag);
 
+/**
+ * @fn email_delete_thread(int thread_id, int delete_always_flag)
+ * @brief      delete a thread of mails.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] thread_id        Specifies the thread id to delete
+ * @param[in] delete_always_flag Specify delete always flag
+ * @exception none
+ * @see
+ */
 EXPORT_API int email_delete_thread(int thread_id, int delete_always_flag);
 
+/**
+ * @fn email_modify_seen_flag_of_thread(int thread_id, int seen_flag, int on_server)
+ * @brief      Modify seen flags of thread
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] thread_id        Specifies the thread id to modify
+ * @param[in] seen_flag Specify seem flag
+ * @param[in] on_server Specify to sync with server
+ * @exception none
+ * @see
+ */
 EXPORT_API int email_modify_seen_flag_of_thread(int thread_id, int seen_flag, int on_server);
 
+/**
+ * @fn email_expunge_mails_deleted_flagged(int input_mailbox_id, int input_on_server, int *output_handle)
+ * @brief      Delete mails which flagged to delete
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] input_mailbox_id Specifies the id of mailbox
+ * @param[in] input_on_server Specify to sync with server
+ * @param[out] output_handle Specify the handle of task
+ * @exception none
+ * @see
+ */
 EXPORT_API int email_expunge_mails_deleted_flagged(int input_mailbox_id, int input_on_server, int *output_handle);
 
 #ifdef __cplusplus
index aefe23b..0a7b7bb 100755 (executable)
@@ -164,6 +164,25 @@ EXPORT_API int email_add_mailbox(email_mailbox_t *new_mailbox, int on_server, in
 EXPORT_API int email_rename_mailbox(int input_mailbox_id, char *input_mailbox_name, char *input_mailbox_alias, int input_on_server, int *output_handle);
 
 /**
+ * @fn int email_rename_mailbox_ex(int input_mailbox_id, char *input_mailbox_name, char *input_mailbox_alias, void *input_eas_data, int input_eas_data_length, int input_on_server, int *output_handle);
+ * @brief      Change mailbox name. This function is invoked when user wants to change the name of existing mail box.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code(refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] input_mailbox_id Specifies the id of the mailbox.
+ * @param[in] input_mailbox_name       Specifies the name of the mailbox.
+ * @param[in] input_mailbox_alias      Specifies the alias of the mailbox.
+ * @param[in] input_eas_data           Specifies the eas data.
+ * @param[in] input_eas_data_length    Specifies the length of eas data.
+ * @param[in] input_on_server  Specifies the moving mailbox on server.
+ * @param[out] output_handle   Specifies the handle to manage tasks.
+ *
+ * @exception see email-errors.h
+ * @see        email_mailbox_t, email_mailbox_type_e
+ * @remarks N/A
+ */
+EXPORT_API int email_rename_mailbox_ex(int input_mailbox_id, char *input_mailbox_name, char *input_mailbox_alias, void *input_eas_data, int input_eas_data_length, int input_on_server, int *output_handle);
+
+/**
  * @fn int email_delete_mailbox(int input_mailbox_id, int input_on_server, int *output_handle)
  * @brief      Delete a mailbox or mailbox.This function deletes the existing mailbox for specified account based on the option on_server.
  *             If the on_server is true then it deletes mailbox from server as well as locally.
@@ -178,6 +197,21 @@ EXPORT_API int email_rename_mailbox(int input_mailbox_id, char *input_mailbox_na
  */
 EXPORT_API int email_delete_mailbox(int input_mailbox_id, int input_on_server, int *output_handle);
 
+/**
+ * @fn int email_delete_mailbox_ex(int input_account_id, int *input_mailbox_id_array, int input_mailbox_id_count, int input_on_server, int *output_handle);
+ * @brief      Delete a mailbox or mailbox.This function deletes the existing mailbox for specified account based on the option on_server.
+ *             If the on_server is true then it deletes mailbox from server as well as locally.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code(refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] input_account_id         Specifies the id of account.
+ * @param[in] input_mailbox_id_array   Specifies the mailbox array for deleting.
+ * @param[in] input_mailbox_id_count   Specifies the count of mailbox for deleting.
+ * @param[in] input_on_server  Specifies the deleting mailbox on server.
+ * @param[out] output_handle   Specifies the sending handle.
+ * @exception  see email-errors.h
+ * @see        email_mailbox_t
+ * @remarks N/A
+ */
 EXPORT_API int email_delete_mailbox_ex(int input_account_id, int *input_mailbox_id_array, int input_mailbox_id_count, int input_on_server, int *output_handle);
 
 /**
@@ -249,9 +283,38 @@ EXPORT_API int email_set_local_mailbox(int input_mailbox_id, int input_is_local_
  */
 EXPORT_API int email_get_mailbox_list(int account_id, int mailbox_sync_type, email_mailbox_t** mailbox_list, int* count);
 
+/**
+ * @fn email_get_mailbox_list_ex(int account_id, int mailbox_sync_type, int with_count, email_mailbox_t** mailbox_list, int* count)
+ * @brief      Extend the email_get_mailbox_list_ex function.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code(refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] account_id               Specifies the account ID.
+ * @param[in] mailbox_sync_type                Specifies the sync type.
+ * @param[in] with_count                specifies the count of mailbox.
+ * @param[out] mailbox_list    Specifies the pointer of mailbox structure pointer.(possibly NULL)
+ * @param[out] count                   The mailbox count is saved here.(possibly 0)
+ * @exception          none
+ * @see        email_mailbox_t
+ * @remarks N/A
+ */
 EXPORT_API int email_get_mailbox_list_ex(int account_id, int mailbox_sync_type, int with_count, email_mailbox_t** mailbox_list, int* count);
 
 /**
+ * @fn email_get_mailbox_list_by_keyworkd(int account_id, char *keyword , email_mailbox_t** mailbox_list, int* count)
+ * @brief      Get the mailbox list to using keywork.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code(refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] account_id               Specifies the account ID.
+ * @param[in] keywork          Specifies the specified keyworkd for searching.
+ * @param[out] mailbox_list    Specifies the pointer of mailbox structure pointer.(possibly NULL)
+ * @param[out] count                   The mailbox count is saved here.(possibly 0)
+ * @exception          none
+ * @see        email_mailbox_t
+ * @remarks N/A
+ */
+EXPORT_API int email_get_mailbox_list_by_keyword(int account_id, char *keyword, email_mailbox_t** mailbox_list, int* count);
+
+/**
  * @fn email_get_mailbox_by_mailbox_type(int account_id, email_mailbox_type_e mailbox_type,  email_mailbox_t** mailbox)
  * @brief      Get mailbox by mailbox_type.This function is invoked when user wants to know the mailbox information by mailbox_type for the given account.
  *
index 47519e1..77f3e16 100755 (executable)
@@ -177,8 +177,30 @@ extern "C" {
  */
 EXPORT_API int email_send_mail(int mail_id,    int *handle);
 
+/**
+ * @fn email_send_mail_with_downloading_attachment_of_original_mail(int input_mail_id, int *output_handle)
+ * @brief      Send a mail. This function is invoked when user wants to send the mail, not been downloaded the attachment.
+ *
+ * @return     This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] input_mail_id    Specifies the mail ID.
+ * @param[out] handle          Specifies the sending handle.
+ * @exception  none
+ * @see        email_mailbox_t and email_option_t
+ * @remarks N/A
+ */
 EXPORT_API int email_send_mail_with_downloading_attachment_of_original_mail(int input_mail_id, int *output_handle);
 
+/**
+ * @fn email_schedule_sending_mail(int input_mail_id, time_t input_time)
+ * @brief      Send a mail. This function is invoked when user wants to send the scheduled mail.
+ *
+ * @return     This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] input_mail_id    Specifies the mail ID.
+ * @param[out] input_time      Specifies the scheduled time.
+ * @exception  none
+ * @see        email_mailbox_t and email_option_t
+ * @remarks N/A
+ */
 EXPORT_API int email_schedule_sending_mail(int input_mail_id, time_t input_time);
 
 
@@ -258,7 +280,6 @@ EXPORT_API int email_download_attachment(int mail_id, int nth, int *handle);
  * @see        none
  * @remarks N/A
  */
-
 EXPORT_API int email_cancel_job(int input_account_id, int input_handle, email_cancelation_type input_cancel_type);
 
 EXPORT_API int email_get_pending_job(email_action_t action, int account_id, int mail_id, email_event_status_type_t * status) DEPRECATED;
@@ -324,8 +345,35 @@ EXPORT_API int email_sync_imap_mailbox_list(int account_id, int *handle);
  */
 EXPORT_API int email_search_mail_on_server(int input_account_id, int input_mailbox_id, email_search_filter_t *input_search_filter_list, int input_search_filter_count, int *output_handle);
 
+/**
+
+ * @fn email_clear_result_of_search_mail_on_server(int input_account_id)
+ * @brief      Delete the temporarily downloaded mails on local storage.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] account_id       Specifies the Account ID
+ * @exception          none
+ * @see email_search_filter_t,
+ * @code
+ * @endcode
+ * @remarks N/A
+ */
 EXPORT_API int email_clear_result_of_search_mail_on_server(int input_account_id);
 
+/**
+
+ * @fn email_query_smtp_mail_size_limit(int account_id)
+ * @brief      query maximum mail size limit from smtp server
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] account_id       Specifies the Account ID
+ * @exception          none
+ * @code
+ * @endcode
+ * @remarks N/A
+ */
+EXPORT_API int email_query_smtp_mail_size_limit(int account_id, int *handle);
+
 #ifdef __cplusplus
 }
 #endif /* __cplusplus */
index 5188cd3..fc66834 100755 (executable)
 extern "C" {
 #endif /* __cplusplus */
 
+/**
+
+ * @fn email_add_certificate(char *certificate_path, char *email_address)
+ * @brief       Store infomations of public certificate in database.
+ *
+ * @param[in] certificate_path         File path of public certificate.
+ * @param[in] email_address            Keyword for searching the certificate information
+ * @exception  none
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @see
+ * @remarks N/A
+ */
 EXPORT_API int email_add_certificate(char *certificate_path, char *email_address);
 
+/**
+
+ * @fn email_delete_certificate(char *email_address)
+ * @brief       Delete infomations of public certificate in database.
+ *
+ * @param[in] email_address            Keyword for deleting the certificate information
+ * @exception  none
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @see
+ * @remarks N/A
+ */
 EXPORT_API int email_delete_certificate(char *email_address);
 
+/**
+
+ * @fn email_get_certificate(char *email_address, email_certificate_t **certificate)
+ * @brief       Get infomations of public certificate in database.
+ *
+ * @param[in] email_address            Keyword for geting the certificate information
+ * @param[out] certificate              Specifies the certificate
+ * @exception  none
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @see
+ * @remarks N/A
+ */
 EXPORT_API int email_get_certificate(char *email_address, email_certificate_t **certificate);
 
+/**
+
+ * @fn email_get_decrypt_message(int mail_id, email_mail_data_t **output_mail_data, email_attachment_data_t **output_attachment_data, int *output_attachment_count);
+
+ * @brief       Get the decrypted message 
+ * @param[in] mail_id                  Specifies the mail_id
+ * @param[out] output_mail_data                Specifies the mail_data 
+ * @param[out] output_attachment_data  Specifies the mail_attachment_data
+ * @param[out] output_attachment_count Specifies the count of attachment
+ * @exception  none
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @see
+ * @remarks N/A
+ */
 EXPORT_API int email_get_decrypt_message(int mail_id, email_mail_data_t **output_mail_data, email_attachment_data_t **output_attachment_data, int *output_attachment_count);
 
+/**
+
+ * @fn email_verify_signature(int mail_id, int *verify);
+
+ * @brief       Verify the signed mail 
+ * @param[in] mail_id          Specifies the mail_id
+ * @param[out] verify          Specifies verify [false : failed verify, true : success the verification]
+ * @exception  none
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @see
+ * @remarks N/A
+ */
 EXPORT_API int email_verify_signature(int mail_id, int *verify);
 
+EXPORT_API int email_verify_signature_ex(email_mail_data_t *input_mail_data, email_attachment_data_t *input_attachment_data, int input_attachment_count, int *verify);
+
+/**
+
+ * @fn email_verify_certificate(char *certificate_path, int *verify);
+
+ * @brief       Verify the certificate 
+ * @param[in] certificate_path Specifies the path of certificate
+ * @param[out] verify          Specifies verify [false : failed verify, true : success the verification]
+ * @exception  none
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @see
+ * @remarks N/A
+ */
 EXPORT_API int email_verify_certificate(char *certificate_path, int *verify);
 
+/**
+
+ * @fn email_get_resolve_recipients(int account_id, char *email_address, unsigned *handle);
+
+ * @brief       Get the certificate at the server [Using exchange server] 
+ * @param[in] account_id       Specifies an account_id
+ * @param[in] email_address    Specifies email address for getting certificate
+ * @param[out] handle          Specifies the handle for stopping 
+ * @exception  none
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @see
+ * @remarks N/A
+ */
 EXPORT_API int email_get_resolve_recipients(int account_id, char *email_address, unsigned *handle);
 
+/**
+
+ * @fn email_validate_certificate(int account_id, char *email_address, unsigned *handle);
+
+ * @brief       Verfiy the certificate to the server [Using exchange server] 
+ * @param[in] account_id       Specifies an account_id
+ * @param[in] email_address    Specifies email address for validating certificate
+ * @param[out] handle          Specifies the handle for stopping 
+ * @exception  none
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @see
+ * @remarks N/A
+ */
 EXPORT_API int email_validate_certificate(int account_id, char *email_address, unsigned *handle);
 
+/**
+
+ * @fn email_free_certificate(email_certificate_t **certificate, int count);
+
+ * @brief       Free the memory of certificate 
+ * @param[in] certificate      Specifies the certificate
+ * @param[in] count            Specifies the count of certificates
+ * @exception  none
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @see
+ * @remarks N/A
+ */
 EXPORT_API int email_free_certificate(email_certificate_t **certificate, int count);
 
 #ifdef __cplusplus
index 1602e50..0f777b2 100755 (executable)
@@ -28,7 +28,7 @@ INCLUDE_DIRECTORIES(
 )
 
 INCLUDE(FindPkgConfig)
-pkg_check_modules(common_pkgs REQUIRED glib-2.0 dlog dbus-1 vconf contacts-service2 uw-imap-toolkit) 
+pkg_check_modules(common_pkgs REQUIRED glib-2.0 dlog dbus-1 vconf contacts-service2 uw-imap-toolkit security-server
 
 FOREACH(flag ${common_pkgs_CFLAGS})
        SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag}")
index 340b678..f9437e5 100755 (executable)
@@ -67,13 +67,22 @@ INTERNAL_FUNC int em_convert_account_to_account_tbl(email_account_t *account, em
        account_tbl->account_id                               = account->account_id;
        account_tbl->keep_mails_on_pop_server_after_download  = account->keep_mails_on_pop_server_after_download;
        account_tbl->auto_download_size                       = account->auto_download_size;
+       account_tbl->peak_interval                            = account->peak_interval;
+       account_tbl->peak_days                                = account->peak_days;
+       account_tbl->peak_start_time                          = account->peak_start_time;
+       account_tbl->peak_end_time                            = account->peak_end_time;
+
+
        account_tbl->outgoing_server_use_same_authenticator   = account->outgoing_server_use_same_authenticator;
+       account_tbl->auto_resend_times                        = account->auto_resend_times;
        account_tbl->pop_before_smtp                          = account->pop_before_smtp;
        account_tbl->incoming_server_requires_apop            = account->incoming_server_requires_apop;
+       account_tbl->incoming_server_authentication_method    = account->incoming_server_authentication_method;
        account_tbl->logo_icon_path                           = EM_SAFE_STRDUP(account->logo_icon_path);
 
        account_tbl->user_data                                = em_memdup(account->user_data, account->user_data_length);
        account_tbl->user_data_length                         = account->user_data_length;
+       account_tbl->roaming_option                           = account->roaming_option;
 
        account_tbl->options.priority                         = account->options.priority;
        account_tbl->options.keep_local_copy                  = account->options.keep_local_copy;
@@ -98,6 +107,7 @@ INTERNAL_FUNC int em_convert_account_to_account_tbl(email_account_t *account, em
        account_tbl->certificate_path                         = EM_SAFE_STRDUP(account->certificate_path);
        account_tbl->cipher_type                              = account->cipher_type;
        account_tbl->digest_type                              = account->digest_type;
+       account_tbl->outgoing_server_size_limit               = account->outgoing_server_size_limit;
 
 
        EM_DEBUG_FUNC_END();
@@ -131,12 +141,19 @@ INTERNAL_FUNC int em_convert_account_tbl_to_account(emstorage_account_tbl_t *acc
        account->account_id                               = account_tbl->account_id;
        account->keep_mails_on_pop_server_after_download  = account_tbl->keep_mails_on_pop_server_after_download;
        account->auto_download_size                       = account_tbl->auto_download_size;
+       account->peak_interval                            = account_tbl->peak_interval;
+       account->peak_days                                = account_tbl->peak_days;
+       account->peak_start_time                          = account_tbl->peak_start_time;
+       account->peak_end_time                            = account_tbl->peak_end_time;
        account->outgoing_server_use_same_authenticator   = account_tbl->outgoing_server_use_same_authenticator;
        account->pop_before_smtp                          = account_tbl->pop_before_smtp;
+       account->auto_resend_times                        = account_tbl->auto_resend_times;
        account->incoming_server_requires_apop            = account_tbl->incoming_server_requires_apop;
+       account->incoming_server_authentication_method    = account_tbl->incoming_server_authentication_method;
        account->logo_icon_path                           = EM_SAFE_STRDUP(account_tbl->logo_icon_path);
-       account->user_data                     = em_memdup(account_tbl->user_data, account_tbl->user_data_length);
-       account->user_data_length              = account_tbl->user_data_length;
+       account->user_data                                = em_memdup(account_tbl->user_data, account_tbl->user_data_length);
+       account->user_data_length                         = account_tbl->user_data_length;
+       account->roaming_option                           = account_tbl->roaming_option;
        account->options.priority                         = account_tbl->options.priority;
        account->options.keep_local_copy                  = account_tbl->options.keep_local_copy;
        account->options.req_delivery_receipt             = account_tbl->options.req_delivery_receipt;
@@ -160,6 +177,7 @@ INTERNAL_FUNC int em_convert_account_tbl_to_account(emstorage_account_tbl_t *acc
        account->certificate_path                         = EM_SAFE_STRDUP(account_tbl->certificate_path);
        account->cipher_type                              = account_tbl->cipher_type;
        account->digest_type                              = account_tbl->digest_type;
+       account->outgoing_server_size_limit               = account_tbl->outgoing_server_size_limit;
 
        EM_DEBUG_FUNC_END();
        return ret;
@@ -183,6 +201,16 @@ INTERNAL_FUNC int em_convert_mailbox_to_mailbox_tbl(email_mailbox_t *mailbox, em
        mailbox_tbl->no_select                  = mailbox->no_select;
        mailbox_tbl->last_sync_time             = mailbox->last_sync_time;
        mailbox_tbl->deleted_flag               = mailbox->deleted_flag;
+       mailbox_tbl->eas_data_length            = mailbox->eas_data_length;
+
+       if ((mailbox->eas_data_length>0) && mailbox->eas_data) {
+               if ((mailbox_tbl->eas_data = em_malloc(mailbox->eas_data_length)) == NULL) {
+                       EM_DEBUG_EXCEPTION("em_malloc failed");
+                       return 0; /*prevent 53448*/
+               }
+               memcpy(mailbox_tbl->eas_data, mailbox->eas_data, mailbox->eas_data_length);
+       }
+
 
        EM_DEBUG_FUNC_END();
        return ret;
@@ -206,6 +234,15 @@ INTERNAL_FUNC int em_convert_mailbox_tbl_to_mailbox(emstorage_mailbox_tbl_t *mai
        mailbox->no_select                  = mailbox_tbl->no_select;
        mailbox->last_sync_time             = mailbox_tbl->last_sync_time;
        mailbox->deleted_flag               = mailbox_tbl->deleted_flag;
+       mailbox->eas_data_length            = mailbox_tbl->eas_data_length;
+
+       if ((mailbox_tbl->eas_data_length >0) && mailbox_tbl->eas_data) {
+               if ((mailbox->eas_data = em_malloc(mailbox_tbl->eas_data_length)) == NULL) {
+                       EM_DEBUG_EXCEPTION("em_malloc failed");
+                       return 0; /*prevent 53445*/
+               }
+               memcpy(mailbox->eas_data, mailbox_tbl->eas_data, mailbox_tbl->eas_data_length);
+       }
 
        EM_DEBUG_FUNC_END();
        return ret;
@@ -281,6 +318,10 @@ INTERNAL_FUNC int em_convert_mail_tbl_to_mail_data(emstorage_mail_tbl_t *mail_ta
                temp_mail_data[i].digest_type             = mail_table_data[i].digest_type;
                temp_mail_data[i].smime_type              = mail_table_data[i].smime_type;
                temp_mail_data[i].scheduled_sending_time  = mail_table_data[i].scheduled_sending_time;
+               temp_mail_data[i].remaining_resend_times  = mail_table_data[i].remaining_resend_times;
+               temp_mail_data[i].tag_id                  = mail_table_data[i].tag_id;
+               temp_mail_data[i].replied_time            = mail_table_data[i].replied_time;
+               temp_mail_data[i].forwarded_time          = mail_table_data[i].forwarded_time;
                temp_mail_data[i].eas_data_length         = mail_table_data[i].eas_data_length;
                if(mail_table_data[i].eas_data_length && mail_table_data[i].eas_data) {
                        if((temp_mail_data[i].eas_data = em_malloc(mail_table_data[i].eas_data_length)) == NULL) {
@@ -378,6 +419,10 @@ INTERNAL_FUNC int   em_convert_mail_data_to_mail_tbl(email_mail_data_t *mail_dat
                temp_mail_tbl[i].digest_type             = mail_data[i].digest_type;
                temp_mail_tbl[i].smime_type              = mail_data[i].smime_type;
                temp_mail_tbl[i].scheduled_sending_time  = mail_data[i].scheduled_sending_time;
+               temp_mail_tbl[i].remaining_resend_times  = mail_data[i].remaining_resend_times;
+               temp_mail_tbl[i].tag_id                  = mail_data[i].tag_id;
+               temp_mail_tbl[i].replied_time            = mail_data[i].replied_time;
+               temp_mail_tbl[i].forwarded_time          = mail_data[i].forwarded_time;
                temp_mail_tbl[i].eas_data_length         = mail_data[i].eas_data_length;
                if(mail_data[i].eas_data_length && mail_data[i].eas_data) {
                        if((temp_mail_tbl[i].eas_data = em_malloc(mail_data[i].eas_data_length)) == NULL) {
@@ -615,8 +660,8 @@ static int fetch_string_from_stream(char *input_stream, int *input_output_stream
        return EMAIL_ERROR_NONE;
 }
                                     /* divide struct at binary field (void* user_data)*/
-#define EMAIL_ACCOUNT_FMT   "S(" "isiii" "is" ")" "B" "S(" "issss"  "isiss" "iiiii" "isiss" "iii"\
-                                 "$(" "iiiii" "iisii" "iisi" ")" "iiisii" ")"
+#define EMAIL_ACCOUNT_FMT   "S(" "isiii" "isi" ")" "B" "S(" "issss"  "isiss" "iiiii" "iiiii" "isiss" "iii"\
+                                 "$(" "iiiii" "iisii" "iisi" ")" "iiiiisii" ")"
 
 
 INTERNAL_FUNC char* em_convert_account_to_byte_stream(email_account_t* account, int *stream_len)
@@ -628,6 +673,10 @@ INTERNAL_FUNC char* em_convert_account_to_byte_stream(email_account_t* account,
        tpl_bin tb;
 
        tn = tpl_map(EMAIL_ACCOUNT_FMT, account, &tb, &(account->user_data_length));
+       if (!tn) {
+               EM_DEBUG_EXCEPTION("tpl_map failed");
+               return NULL;
+       }
        tb.sz = account->user_data_length;
        tb.addr = account->user_data;
        tpl_pack(tn, 0);
@@ -654,6 +703,10 @@ INTERNAL_FUNC void em_convert_byte_stream_to_account(char *stream, int stream_le
        tpl_bin tb;
 
        tn = tpl_map(EMAIL_ACCOUNT_FMT, account, &tb, &(account->user_data_length));
+       if (!tn) {
+               EM_DEBUG_EXCEPTION("tpl_map failed");
+               return;
+       }
        tpl_load(tn, TPL_MEM, stream, stream_len);
        tpl_unpack(tn, 0);
        tpl_free(tn);
@@ -665,7 +718,7 @@ INTERNAL_FUNC void em_convert_byte_stream_to_account(char *stream, int stream_le
 }
 
 #define EMAIL_MAIL_DATA_FMT  "S(" "iiiis" "iisss" "issss" "sssss" "sisss"\
-                            "icccc" "cccii" "iiiii" "iisii" "iiii)B"
+                            "icccc" "cccii" "iiiii" "iisii" "iiiii" "iii)B"
 
 INTERNAL_FUNC char* em_convert_mail_data_to_byte_stream(email_mail_data_t *mail_data, int *stream_len)
 {
@@ -678,7 +731,11 @@ INTERNAL_FUNC char* em_convert_mail_data_to_byte_stream(email_mail_data_t *mail_
 
        EM_DEBUG_LOG("eas_data_length[%d]", mail_data->eas_data_length); /*prevent 44369*/
 
-       tn      = tpl_map(EMAIL_MAIL_DATA_FMT, mail_data, &tb);
+       tn = tpl_map(EMAIL_MAIL_DATA_FMT, mail_data, &tb);
+       if (!tn) {
+               EM_DEBUG_EXCEPTION("tpl_map failed");
+               return NULL;
+       }
        tb.sz   = mail_data->eas_data_length;
        tb.addr = mail_data->eas_data;
        tpl_pack(tn, 0);
@@ -739,17 +796,20 @@ INTERNAL_FUNC char* em_convert_attachment_data_to_byte_stream(email_attachment_d
                return NULL;
        }
 
-
        email_attachment_data_t cur = {0};
        tpl_node *tn = NULL;
 
        /* tpl_map adds value at 2nd param addr to packing buffer iterately */
        /* 2nd param value (not addr via pointer) should be modified at each iteration */
        tn = tpl_map(EMAIL_ATTACHMENT_DATA_FMT, &cur);
+       if (!tn) {
+               EM_DEBUG_EXCEPTION("tpl_map failed");
+               return NULL;
+       }
        int i=0;
        for( ; i < attachment_count ; i++ ) {
-               memcpy(&cur, attachment+i, sizeof(cur)); /* copy data to cur : swallow copy */
-               tpl_pack(tn, 1);                        /* pack data at &cur: deep copy */
+               memcpy(&cur, attachment + i, sizeof(email_attachment_data_t));
+               tpl_pack(tn, 1);                       
        }
 
        /* write data to buffer */
@@ -777,6 +837,10 @@ INTERNAL_FUNC void em_convert_byte_stream_to_attachment_data(char *stream, int s
        email_attachment_data_t cur = {0};
        tpl_node *tn = NULL;
        tn = tpl_map(EMAIL_ATTACHMENT_DATA_FMT, &cur);
+       if (!tn) {
+               EM_DEBUG_EXCEPTION("tpl_map failed");
+               return;
+       }
        tpl_load(tn, TPL_MEM, stream, stream_len);
 
        /* tpl does not return the size of variable-length array, but we need variable-length array */
@@ -787,8 +851,11 @@ INTERNAL_FUNC void em_convert_byte_stream_to_attachment_data(char *stream, int s
        while( tpl_unpack(tn, 1) > 0) {
                email_attachment_data_t* pdata = (email_attachment_data_t*) em_malloc(sizeof(email_attachment_data_t));
                memcpy(pdata, &cur, sizeof(email_attachment_data_t)); /* copy unpacked data to list item */
+               pdata->attachment_name          = EM_SAFE_STRDUP(cur.attachment_name);
+               pdata->attachment_path          = EM_SAFE_STRDUP(cur.attachment_path);
+               pdata->attachment_mime_type     = EM_SAFE_STRDUP(cur.attachment_mime_type);
                head = g_list_prepend(head, pdata);                   /* add it to list */
-               memset(&cur, 0, sizeof(email_attachment_data_t));     /* initialize variable, used for unpacking */
+               memset(&cur, 0, sizeof(email_attachment_data_t));    /* initialize variable, used for unpacking */
                count++;
        }
        tpl_free(tn);
@@ -814,7 +881,7 @@ INTERNAL_FUNC void em_convert_byte_stream_to_attachment_data(char *stream, int s
 }
 
 
-#define EMAIL_MAILBOX_FMT  "S(" "isisi" "iiiii" "i" ")"
+#define EMAIL_MAILBOX_FMT  "S(" "isisi" "iiiii" "iiii" ")B"
 
 INTERNAL_FUNC char* em_convert_mailbox_to_byte_stream(email_mailbox_t *mailbox_data, int *stream_len)
 {
@@ -823,15 +890,26 @@ INTERNAL_FUNC char* em_convert_mailbox_to_byte_stream(email_mailbox_t *mailbox_d
        EM_IF_NULL_RETURN_VALUE(stream_len, NULL);
 
        tpl_node *tn = NULL;
+       tpl_bin tb;
 
-       tn = tpl_map(EMAIL_MAILBOX_FMT, mailbox_data);
+       EM_DEBUG_LOG("eas_data_length[%d]", mailbox_data->eas_data_length);
+
+       tn = tpl_map(EMAIL_MAILBOX_FMT, mailbox_data, &tb);
+       if (!tn) {
+               EM_DEBUG_EXCEPTION("tpl_map failed");
+               return NULL;
+       }
+       tb.sz   = mailbox_data->eas_data_length;
+       tb.addr = mailbox_data->eas_data;
        tpl_pack(tn, 0);
 
        /* write account to buffer */
        void *buf = NULL;
        size_t len = 0;
        tpl_dump(tn, TPL_MEM, &buf, &len);
-       tpl_free(tn);
+
+       if(tn)
+               tpl_free(tn);
 
        *stream_len = len;
        EM_DEBUG_FUNC_END("serialized len: %d", len);
@@ -846,11 +924,26 @@ INTERNAL_FUNC void em_convert_byte_stream_to_mailbox(char *stream, int stream_le
        EM_NULL_CHECK_FOR_VOID(mailbox_data);
 
        tpl_node *tn = NULL;
+       tpl_bin tb;
 
-       tn = tpl_map(EMAIL_MAILBOX_FMT, mailbox_data);
+       tn = tpl_map(EMAIL_MAILBOX_FMT, mailbox_data, &tb);
+       if (!tn) {
+               EM_DEBUG_EXCEPTION("tpl_map failed");
+               return;
+       }
        tpl_load(tn, TPL_MEM, stream, stream_len);
        tpl_unpack(tn, 0);
-       tpl_free(tn);
+
+       if(mailbox_data->eas_data_length <= 0 || tb.addr == NULL) {
+               EM_DEBUG_LOG("No eas data. eas_data_length[%d] addr[%p]", mailbox_data->eas_data_length, tb.addr);
+       }
+       else {
+               EM_DEBUG_LOG("eas_data_length[%d] addr[%p]", mailbox_data->eas_data_length, tb.addr);
+               mailbox_data->eas_data = tb.addr;
+       }
+
+       if(tn)
+               tpl_free(tn);
 
        EM_DEBUG_FUNC_END("deserialized len %d", stream_len);
 }
@@ -866,6 +959,10 @@ INTERNAL_FUNC char* em_convert_option_to_byte_stream(email_option_t* option, int
        tpl_node *tn = NULL;
 
        tn = tpl_map(EMAIL_OPTION_FMT, option);
+       if (!tn) {
+               EM_DEBUG_EXCEPTION("tpl_map failed");
+               return NULL;
+       }
        tpl_pack(tn, 0);
 
        /* write account to buffer */
@@ -888,6 +985,10 @@ INTERNAL_FUNC void em_convert_byte_stream_to_option(char *stream, int stream_len
        tpl_node *tn = NULL;
 
        tn = tpl_map(EMAIL_OPTION_FMT, option);
+       if (!tn) {
+               EM_DEBUG_EXCEPTION("tpl_map failed");
+               return;
+       }
        tpl_load(tn, TPL_MEM, stream, stream_len);
        tpl_unpack(tn, 0);
        tpl_free(tn);
@@ -896,7 +997,7 @@ INTERNAL_FUNC void em_convert_byte_stream_to_option(char *stream, int stream_len
 }
 
 
-#define EMAIL_RULE_FMT "S(" "iiisi" "iii" ")"
+#define EMAIL_RULE_FMT "S(" "iisis" "siiii" ")"
 
 INTERNAL_FUNC char* em_convert_rule_to_byte_stream(email_rule_t *rule, int *stream_len)
 {
@@ -907,6 +1008,10 @@ INTERNAL_FUNC char* em_convert_rule_to_byte_stream(email_rule_t *rule, int *stre
        tpl_node *tn = NULL;
 
        tn = tpl_map(EMAIL_RULE_FMT, rule);
+       if (!tn) {
+               EM_DEBUG_EXCEPTION("tpl_map failed");
+               return NULL;
+       }
        tpl_pack(tn, 0);
 
        /* write account to buffer */
@@ -929,6 +1034,10 @@ INTERNAL_FUNC void em_convert_byte_stream_to_rule(char *stream, int stream_len,
        tpl_node *tn = NULL;
 
        tn = tpl_map(EMAIL_RULE_FMT, rule);
+       if (!tn) {
+               EM_DEBUG_EXCEPTION("tpl_map failed");
+               return;
+       }
        tpl_load(tn, TPL_MEM, stream, stream_len);
        tpl_unpack(tn, 0);
        tpl_free(tn);
@@ -962,6 +1071,10 @@ INTERNAL_FUNC char* em_convert_meeting_req_to_byte_stream(email_meeting_request_
                                                &tb[3],
                                                &meeting_req->time_zone.daylight_bias
                                );
+       if (!tn) {
+               EM_DEBUG_EXCEPTION("tpl_map failed");
+               return NULL;
+       }
        tb[0].sz = tb[1].sz = tb[2].sz = tb[3].sz = sizeof(struct tm);
        tb[0].addr = &meeting_req->start_time;
        tb[1].addr = &meeting_req->end_time;
@@ -1007,6 +1120,10 @@ INTERNAL_FUNC void em_convert_byte_stream_to_meeting_req(char *stream, int strea
                                                &tb[3],
                                                &meeting_req->time_zone.daylight_bias
                                );
+       if (!tn) {
+               EM_DEBUG_EXCEPTION("tpl_map failed");
+               return;
+       }
        tpl_load(tn, TPL_MEM, stream, stream_len);
        tpl_unpack(tn, 0);
        tpl_free(tn);
@@ -1168,6 +1285,10 @@ INTERNAL_FUNC char* em_convert_task_information_to_byte_stream(email_task_inform
        int i = 0;
 
        tn = tpl_map(EMAIL_JOB_INFORMATION_FMT, &cur);
+       if (!tn) {
+               EM_DEBUG_EXCEPTION("tpl_map failed");
+               return NULL;
+       }
 
        for( ; i < input_task_information_count ; i++ ) {
                memcpy(&cur, input_task_information + i, sizeof(email_task_information_t));
@@ -1199,6 +1320,10 @@ INTERNAL_FUNC void em_convert_byte_stream_to_task_information(char *input_stream
        GList *head = NULL;
 
        tn = tpl_map(EMAIL_JOB_INFORMATION_FMT, &cur);
+       if (!tn) {
+               EM_DEBUG_EXCEPTION("tpl_map failed");
+               return;
+       }
        tpl_load(tn, TPL_MEM, input_stream, input_stream_len);
 
        while( tpl_unpack(tn, 1) > 0) {
index fe52ddb..b5f36f5 100755 (executable)
@@ -36,6 +36,7 @@
 #include <malloc.h>
 #include <pthread.h>
 #include <regex.h>
+#include <security-server.h>
 
 #include "c-client.h"
 
@@ -47,7 +48,7 @@ INTERNAL_FUNC void* em_malloc(int len)
 {
        /* EM_DEBUG_LOG("Memory allocation size[%d] bytes", len); */
        if (len <= 0) {
-               EM_DEBUG_EXCEPTION("len should be positive.[%d]", len);
+               EM_DEBUG_LOG ("len should be positive.[%d]", len);
                return NULL;
        }
 
@@ -63,7 +64,7 @@ INTERNAL_FUNC void* em_memdup(void* src, int len)
 {
        /* EM_DEBUG_LOG("Memory allocation size[%d] bytes", len); */
        if (len <= 0) {
-               EM_DEBUG_EXCEPTION("len should be positive.[%d]", len);
+               EM_DEBUG_LOG ("len should be positive.[%d]", len);
                return NULL;
        }
 
@@ -225,6 +226,12 @@ INTERNAL_FUNC char* em_replace_all_string(char *source_string, char *old_string,
                EM_DEBUG_EXCEPTION("calloc failed");
                return NULL;
        }
+
+       if (!strstr(source_string, old_string)) {
+               memcpy(result_buffer, source_string, src_len);
+               return result_buffer;
+       }
+
        realloc_len = src_len + 1;
 
        for (i = 0; i < src_len && source_string[i] != '\0';) {
@@ -254,7 +261,7 @@ INTERNAL_FUNC char* em_replace_all_string(char *source_string, char *old_string,
        else
                result_buffer[realloc_len-1] = '\0';
 
-       EM_DEBUG_FUNC_END("result_buffer : %s", result_buffer);
+       EM_DEBUG_FUNC_END();
        return result_buffer;
 }
 
@@ -349,7 +356,7 @@ INTERNAL_FUNC void em_flush_memory()
 
 INTERNAL_FUNC int em_get_file_name_from_file_path(char *input_source_file_path, char **output_file_name)
 {
-       EM_DEBUG_FUNC_BEGIN("input_source_file_path[%s], output_file_name [%p]", input_source_file_path, output_file_name);
+       EM_DEBUG_FUNC_BEGIN_SEC("input_source_file_path[%s], output_file_name [%p]", input_source_file_path, output_file_name);
        int   err = EMAIL_ERROR_NONE;
        int   pos_on_string = 0;
        int   file_name_length = 0;
@@ -380,7 +387,7 @@ INTERNAL_FUNC int em_get_file_name_from_file_path(char *input_source_file_path,
                memcpy(file_name_string, start_pos_of_file_name, file_name_length);
        }
 
-       EM_DEBUG_LOG("file_name_string [%s] pos_on_string [%d] file_name_length [%d]", file_name_string, pos_on_string, file_name_length);
+       EM_DEBUG_LOG_SEC("file_name_string [%s] pos_on_string [%d] file_name_length [%d]", file_name_string, pos_on_string, file_name_length);
 
        *output_file_name = EM_SAFE_STRDUP(file_name_string);
 
@@ -391,7 +398,7 @@ FINISH_OFF:
 
 INTERNAL_FUNC int em_get_file_name_and_extension_from_file_path(char *input_source_file_path, char **output_file_name, char **output_extension)
 {
-       EM_DEBUG_FUNC_BEGIN("input_source_file_path[%s], output_file_name [%p], output_extension [%p]", input_source_file_path, output_file_name, output_extension);
+       EM_DEBUG_FUNC_BEGIN_SEC("input_source_file_path[%s], output_file_name [%p], output_extension [%p]", input_source_file_path, output_file_name, output_extension);
        int   err = EMAIL_ERROR_NONE;
        int   pos_on_string = 0;
        int   file_name_length = 0;
@@ -436,7 +443,7 @@ INTERNAL_FUNC int em_get_file_name_and_extension_from_file_path(char *input_sour
                memcpy(extension_string, dot_pos_of_file_path + 1, extention_length);
        }
 
-       EM_DEBUG_LOG("*file_name_string [%s] pos_on_string [%d]", file_name_string, pos_on_string);
+       EM_DEBUG_LOG_SEC("*file_name_string [%s] pos_on_string [%d]", file_name_string, pos_on_string);
 
        *output_file_name = EM_SAFE_STRDUP(file_name_string);
        *output_extension = EM_SAFE_STRDUP(extension_string);
@@ -448,7 +455,7 @@ FINISH_OFF:
 
 INTERNAL_FUNC char *em_get_extension_from_file_path(char *source_file_path, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("source_file_path[%s]", source_file_path);
+       EM_DEBUG_FUNC_BEGIN_SEC("source_file_path[%s]", source_file_path);
        int err = EMAIL_ERROR_NONE, pos_on_string = 0;
        char *extension = NULL;
 
@@ -587,20 +594,20 @@ FINISH_OFF:
 #define EMAIL_ALIAS_WITHOUT_BRACKET_RGEX       "([[:space:]]*\"[^\"]*\")?"EMAIL_ADDR_WITHOUT_BRACKET_RGEX
 #define EMAIL_ALIAS_LIST_WITHOUT_BRACKET_RGEX  "("EMAIL_ALIAS_WITHOUT_BRACKET_RGEX"[;,])*"EMAIL_ADDR_WITHOUT_BRACKET_RGEX"[;,]?[[:space:]]*$"
 
-INTERNAL_FUNC int em_verify_email_address(char *address, int without_bracket, int *err_code)
+INTERNAL_FUNC int em_verify_email_address(char *address, int without_bracket)
 {
-       EM_DEBUG_FUNC_BEGIN("address[%s] without_bracket[%d]", address, without_bracket);
+       EM_DEBUG_FUNC_BEGIN_SEC("address[%s] without_bracket[%d]", address, without_bracket);
 
        /*  this following code verfies the email alias string using reg. exp. */
        regex_t alias_list_regex = {0};
-       int ret = false, error = EMAIL_ERROR_NONE;
+       int error = EMAIL_ERROR_NONE;
        char *reg_rule = NULL;
+       int alias_len = 0;
+       regmatch_t *pmatch = NULL;
 
        if(!address || EM_SAFE_STRLEN(address) == 0) {
                EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
-               if (err_code)
-                       *err_code = EMAIL_ERROR_INVALID_PARAM;
-               return false;
+               return EMAIL_ERROR_INVALID_PARAM;
        }
 
        if(without_bracket)
@@ -608,54 +615,52 @@ INTERNAL_FUNC int em_verify_email_address(char *address, int without_bracket, in
        else
                reg_rule = EMAIL_ALIAS_LIST_RGEX;
 
-       if (regcomp(&alias_list_regex, reg_rule, REG_ICASE | REG_EXTENDED)) {
+       if (regcomp (&alias_list_regex, reg_rule, REG_ICASE | REG_EXTENDED) != 0) {
                EM_DEBUG_EXCEPTION("email alias regex unrecognized");
-               if (err_code)
-                       *err_code = EMAIL_ERROR_UNKNOWN;
-               return false;
+               error = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
        }
 
-       int alias_len = EM_SAFE_STRLEN(address) + 1;
-       regmatch_t pmatch[alias_len];
-
-       bzero(pmatch, alias_len);
+       alias_len = EM_SAFE_STRLEN(address) + 1;
+       pmatch = (regmatch_t *) em_malloc (alias_len * sizeof (regmatch_t));
+       if (!pmatch) {
+               EM_DEBUG_EXCEPTION("em_malloc error");
+               goto FINISH_OFF;
+       }
 
-       if (regexec(&alias_list_regex, address, alias_len, pmatch, 0) == REG_NOMATCH)
-               EM_DEBUG_LOG("failed :[%s]", address);
-       else {
-               EM_DEBUG_LOG("success :[%s]", address);
-               ret = true;
+       if (regexec (&alias_list_regex, address, alias_len, pmatch, 0) == REG_NOMATCH) {
+               EM_DEBUG_LOG_SEC("failed :[%s]", address);
+               error = EMAIL_ERROR_INVALID_ADDRESS;
+               goto FINISH_OFF;
        }
 
+FINISH_OFF:
        regfree(&alias_list_regex);
+       EM_SAFE_FREE (pmatch);
 
-       if (err_code)
-               *err_code = error;
-
-       EM_DEBUG_FUNC_END("ret [%d]", ret);
-       return ret;
+       EM_DEBUG_FUNC_END("err [%d]", error);
+       return error;
 }
 
-INTERNAL_FUNC int em_verify_email_address_of_mail_data(email_mail_data_t *mail_data, int without_bracket, int *err_code)
+INTERNAL_FUNC int em_verify_email_address_of_mail_data (email_mail_data_t *mail_data, int without_bracket)
 {
        EM_DEBUG_FUNC_BEGIN("mail_data[%p] without_bracket[%d]", mail_data, without_bracket);
        char *address_array[4] = { mail_data->full_address_from, mail_data->full_address_to, mail_data->full_address_cc, mail_data->full_address_bcc};
-       int  ret = false, err = EMAIL_ERROR_NONE, i;
+       int  err = EMAIL_ERROR_NONE, i;
 
        /* check for email_address validation */
        for (i = 0; i < 4; i++) {
                if (address_array[i] && address_array[i][0] != 0) {
-                       if (!em_verify_email_address(address_array[i] , without_bracket, &err)) {
-                               err = EMAIL_ERROR_INVALID_ADDRESS;
-                               EM_DEBUG_EXCEPTION("Invalid Email Address [%d][%s]", i, address_array[i]);
+                       err = em_verify_email_address (address_array[i] , without_bracket);
+                       if (err != EMAIL_ERROR_NONE) {
+                               EM_DEBUG_EXCEPTION_SEC("em_verify_email_address error[%d] idx[%d] addr[%s]", err, i, address_array[i]);
                                goto FINISH_OFF;
                        }
                }
        }
-       ret = true;
 FINISH_OFF:
-       EM_DEBUG_FUNC_END("ret [%d]", ret);
-       return ret;
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
 }
 
 INTERNAL_FUNC int em_verify_email_address_of_mail_tbl(emstorage_mail_tbl_t *input_mail_tbl, int input_without_bracket)
@@ -667,9 +672,8 @@ INTERNAL_FUNC int em_verify_email_address_of_mail_tbl(emstorage_mail_tbl_t *inpu
        /* check for email_address validation */
        for (i = 0; i < 4; i++) {
                if (address_array[i] && address_array[i][0] != 0) {
-                       if (!em_verify_email_address(address_array[i] , input_without_bracket, &err)) {
-                               err = EMAIL_ERROR_INVALID_ADDRESS;
-                               EM_DEBUG_EXCEPTION("Invalid Email Address [%d][%s]", i, address_array[i]);
+                       if ((err = em_verify_email_address (address_array[i] , input_without_bracket)) != EMAIL_ERROR_NONE) {
+                               EM_DEBUG_EXCEPTION_SEC("em_verify_email_address error[%d] idx[%d] addr[%s]", err, i, address_array[i]);
                                goto FINISH_OFF;
                        }
                }
@@ -929,221 +933,181 @@ FINISH_OFF:
        return ret;
 }
 
-INTERNAL_FUNC int em_send_notification_to_active_sync_engine(int subType, ASNotiData *data)
+INTERNAL_FUNC int em_check_socket_privilege_by_pid(int pid)
 {
-       EM_DEBUG_FUNC_BEGIN("subType [%d], data [%p]", subType, data);
+       EM_DEBUG_FUNC_BEGIN("pid [%d]", pid);
+       int smack_ret = 0;
 
-       DBusConnection     *connection;
-       DBusMessage        *signal = NULL;
-       DBusError           error;
-       int                 i = 0;
+       smack_ret = security_server_check_privilege_by_pid(pid, "email-service::write", "rw");
+       if (smack_ret == SECURITY_SERVER_API_ERROR_ACCESS_DENIED) {
+               EM_DEBUG_EXCEPTION("SECURITY_SERVER_API_ERROR_ACCESS_DENIED");
+               return EMAIL_ERROR_PERMISSION_DENIED;
+       }
 
-       dbus_error_init (&error);
-       connection = dbus_bus_get(DBUS_BUS_SYSTEM, &error);
+       EM_DEBUG_FUNC_END();
+       return EMAIL_ERROR_NONE;
+}
 
-       if(connection == NULL)
-               goto FINISH_OFF;
+INTERNAL_FUNC int em_check_db_privilege_by_pid(int pid)
+{
+       EM_DEBUG_FUNC_BEGIN("pid [%d]", pid);
+       int smack_ret = 0;
 
-       signal = dbus_message_new_signal("/User/Email/ActiveSync", EMAIL_ACTIVE_SYNC_NOTI, "email");
+       smack_ret = security_server_check_privilege_by_pid(pid, "email-service::db", "rw");
+       if (smack_ret == SECURITY_SERVER_API_ERROR_ACCESS_DENIED) {
+               EM_DEBUG_EXCEPTION("SECURITY_SERVER_API_ERROR_ACCESS_DENIED");
+               return EMAIL_ERROR_PERMISSION_DENIED;
+       }
 
-       dbus_message_append_args(signal, DBUS_TYPE_INT32, &subType, DBUS_TYPE_INVALID);
-       switch ( subType ) {
-               case ACTIVE_SYNC_NOTI_SEND_MAIL:
-                       EM_DEBUG_LOG("handle:[%d]", data->send_mail.handle);
-                       EM_DEBUG_LOG("account_id:[%d]", data->send_mail.account_id);
-                       EM_DEBUG_LOG("mail_id:[%d]", data->send_mail.mail_id);
+       EM_DEBUG_FUNC_END();
+       return EMAIL_ERROR_NONE;
+}
 
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->send_mail.handle), DBUS_TYPE_INVALID);
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->send_mail.account_id), DBUS_TYPE_INVALID);
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->send_mail.mail_id), DBUS_TYPE_INVALID);
-                       break;
-               case ACTIVE_SYNC_NOTI_SEND_SAVED:                               /*  publish a send notification to ASE (active sync engine) */
-                       EM_DEBUG_EXCEPTION("Not support yet : subType[ACTIVE_SYNC_NOTI_SEND_SAVED]", subType);
-                       break;
-               case ACTIVE_SYNC_NOTI_SEND_REPORT:
-                       EM_DEBUG_EXCEPTION("Not support yet : subType[ACTIVE_SYNC_NOTI_SEND_REPORT]", subType);
-                       break;
-               case ACTIVE_SYNC_NOTI_SYNC_HEADER:
-                       EM_DEBUG_LOG("handle:[%d]", data->sync_header.handle);
-                       EM_DEBUG_LOG("account_id:[%d]", data->sync_header.account_id);
-                       EM_DEBUG_LOG("mailbox_id:[%d]", data->sync_header.mailbox_id);
-
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->sync_header.handle ), DBUS_TYPE_INVALID);
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->sync_header.account_id ), DBUS_TYPE_INVALID);
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->sync_header.mailbox_id ), DBUS_TYPE_INVALID);
-                       break;
-               case ACTIVE_SYNC_NOTI_DOWNLOAD_BODY:                    /*  publish a download body notification to ASE */
-                       EM_DEBUG_LOG("handle:[%d]", data->download_body.handle);
-                       EM_DEBUG_LOG("account_id:[%d]", data->download_body.account_id);
-                       EM_DEBUG_LOG("mail_id:[%d]", data->download_body.mail_id);
-                       EM_DEBUG_LOG("with_attachment:[%d]", data->download_body.with_attachment);
-
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->download_body.handle  ), DBUS_TYPE_INVALID);
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->download_body.account_id  ), DBUS_TYPE_INVALID);
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->download_body.mail_id ), DBUS_TYPE_INVALID);
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->download_body.with_attachment  ), DBUS_TYPE_INVALID);
-                       break;
-               case ACTIVE_SYNC_NOTI_DOWNLOAD_ATTACHMENT:
-                       EM_DEBUG_LOG("handle:[%d]", data->download_attachment.handle);
-                       EM_DEBUG_LOG("account_id:[%d]", data->download_attachment.account_id );
-                       EM_DEBUG_LOG("mail_id:[%d]", data->download_attachment.mail_id);
-                       EM_DEBUG_LOG("with_attachment:[%d]", data->download_attachment.attachment_order );
-
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->download_attachment.handle  ), DBUS_TYPE_INVALID);
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->download_attachment.account_id  ), DBUS_TYPE_INVALID);
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->download_attachment.mail_id ), DBUS_TYPE_INVALID);
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->download_attachment.attachment_order), DBUS_TYPE_INVALID);
-                       break;
-               case ACTIVE_SYNC_NOTI_VALIDATE_ACCOUNT:
-                       EM_DEBUG_EXCEPTION("Not support yet : subType[ACTIVE_SYNC_NOTI_VALIDATE_ACCOUNT]", subType);
-                       break;
-               case ACTIVE_SYNC_NOTI_CANCEL_JOB:
-                       EM_DEBUG_LOG("account_id:[%d]",       data->cancel_job.account_id );
-                       EM_DEBUG_LOG("handle to cancel:[%d]", data->cancel_job.handle);
-                       EM_DEBUG_LOG("cancel_type:[%d]",      data->cancel_job.cancel_type);
-
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->cancel_job.account_id  ), DBUS_TYPE_INVALID);
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->cancel_job.handle  ), DBUS_TYPE_INVALID);
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->cancel_job.cancel_type  ), DBUS_TYPE_INVALID);
-                       break;
-               case ACTIVE_SYNC_NOTI_SEARCH_ON_SERVER:
-                       EM_DEBUG_LOG("account_id:[%d]",          data->search_mail_on_server.account_id );
-                       EM_DEBUG_LOG("mailbox_id:[%d]",        data->search_mail_on_server.mailbox_id );
-                       EM_DEBUG_LOG("search_filter_count:[%d]", data->search_mail_on_server.search_filter_count );
-                       EM_DEBUG_LOG("handle to cancel:[%d]",    data->search_mail_on_server.handle);
-
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->search_mail_on_server.account_id), DBUS_TYPE_INVALID);
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->search_mail_on_server.mailbox_id), DBUS_TYPE_INVALID);
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->search_mail_on_server.search_filter_count), DBUS_TYPE_INVALID);
-                       for(i = 0; i < data->search_mail_on_server.search_filter_count; i++) {
-                               dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->search_mail_on_server.search_filter_list[i].search_filter_type), DBUS_TYPE_INVALID);
-                               switch(data->search_mail_on_server.search_filter_list[i].search_filter_type) {
-                                       case EMAIL_SEARCH_FILTER_TYPE_MESSAGE_NO       :
-                                       case EMAIL_SEARCH_FILTER_TYPE_UID              :
-                                       case EMAIL_SEARCH_FILTER_TYPE_SIZE_LARSER      :
-                                       case EMAIL_SEARCH_FILTER_TYPE_SIZE_SMALLER     :
-                                       case EMAIL_SEARCH_FILTER_TYPE_FLAGS_ANSWERED   :
-                                       case EMAIL_SEARCH_FILTER_TYPE_FLAGS_DELETED    :
-                                       case EMAIL_SEARCH_FILTER_TYPE_FLAGS_DRAFT      :
-                                       case EMAIL_SEARCH_FILTER_TYPE_FLAGS_FLAGED     :
-                                       case EMAIL_SEARCH_FILTER_TYPE_FLAGS_RECENT     :
-                                       case EMAIL_SEARCH_FILTER_TYPE_FLAGS_SEEN       :
-                                               dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->search_mail_on_server.search_filter_list[i].search_filter_key_value.integer_type_key_value), DBUS_TYPE_INVALID);
-                                               break;
-
-                                       case EMAIL_SEARCH_FILTER_TYPE_BCC              :
-                                       case EMAIL_SEARCH_FILTER_TYPE_CC               :
-                                       case EMAIL_SEARCH_FILTER_TYPE_FROM             :
-                                       case EMAIL_SEARCH_FILTER_TYPE_KEYWORD          :
-                                       case EMAIL_SEARCH_FILTER_TYPE_SUBJECT          :
-                                       case EMAIL_SEARCH_FILTER_TYPE_TO               :
-                                       case EMAIL_SEARCH_FILTER_TYPE_MESSAGE_ID       :
-                                               dbus_message_append_args(signal, DBUS_TYPE_STRING, &(data->search_mail_on_server.search_filter_list[i].search_filter_key_value.string_type_key_value), DBUS_TYPE_INVALID);
-                                               break;
-
-                                       case EMAIL_SEARCH_FILTER_TYPE_SENT_DATE_BEFORE :
-                                       case EMAIL_SEARCH_FILTER_TYPE_SENT_DATE_ON     :
-                                       case EMAIL_SEARCH_FILTER_TYPE_SENT_DATE_SINCE  :
-                                               dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->search_mail_on_server.search_filter_list[i].search_filter_key_value.time_type_key_value), DBUS_TYPE_INVALID);
-                                               break;
-                                       default :
-                                               EM_DEBUG_EXCEPTION("Invalid filter type [%d]", data->search_mail_on_server.search_filter_list[i].search_filter_type);
-                                               break;
-                               }
-                       }
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->search_mail_on_server.handle), DBUS_TYPE_INVALID);
-                       break;
 
-               case ACTIVE_SYNC_NOTI_CLEAR_RESULT_OF_SEARCH_ON_SERVER :
-                       EM_DEBUG_LOG("account_id:[%d]",          data->clear_result_of_search_mail_on_server.account_id );
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->search_mail_on_server.account_id), DBUS_TYPE_INVALID);
-                       break;
+/* thread with task queue generic functions */
 
-               case ACTIVE_SYNC_NOTI_EXPUNGE_MAILS_DELETED_FLAGGED :
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->expunge_mails_deleted_flagged.account_id), DBUS_TYPE_INVALID);
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->expunge_mails_deleted_flagged.mailbox_id), DBUS_TYPE_INVALID);
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->expunge_mails_deleted_flagged.on_server), DBUS_TYPE_INVALID);
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->expunge_mails_deleted_flagged.handle), DBUS_TYPE_INVALID);
-                       break;
+pthread_mutex_t g_mu = PTHREAD_MUTEX_INITIALIZER;
 
-               case ACTIVE_SYNC_NOTI_RESOLVE_RECIPIENT :
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->get_resolve_recipients.account_id), DBUS_TYPE_INVALID);
-                       dbus_message_append_args(signal, DBUS_TYPE_STRING, &(data->get_resolve_recipients.email_address), DBUS_TYPE_INVALID);
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->get_resolve_recipients.handle), DBUS_TYPE_INVALID);
-                       break;
+email_thread_handle_t* em_thread_create (void *(*thread_exit)(void*), void *arg)
+{
+       pthread_mutex_lock(&g_mu);
 
-               case ACTIVE_SYNC_NOTI_VALIDATE_CERTIFICATE :
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->validate_certificate.account_id), DBUS_TYPE_INVALID);
-                       dbus_message_append_args(signal, DBUS_TYPE_STRING, &(data->validate_certificate.email_address), DBUS_TYPE_INVALID);
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->validate_certificate.handle), DBUS_TYPE_INVALID);
-                       break;
+       email_thread_handle_t* thd_handle = (email_thread_handle_t*) calloc (1,sizeof (email_thread_handle_t));
+       if (!thd_handle) {
+               EM_DEBUG_EXCEPTION ("out of memory");
+               goto FINISH_OFF;
+       }
 
-               case ACTIVE_SYNC_NOTI_ADD_MAILBOX :
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->add_mailbox.account_id), DBUS_TYPE_INVALID);
-                       dbus_message_append_args(signal, DBUS_TYPE_STRING, &(data->add_mailbox.mailbox_path), DBUS_TYPE_INVALID);
-                       dbus_message_append_args(signal, DBUS_TYPE_STRING, &(data->add_mailbox.mailbox_alias), DBUS_TYPE_INVALID);
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->add_mailbox.handle), DBUS_TYPE_INVALID);
-                       break;
+       thd_handle->q = g_queue_new ();
+       if (!thd_handle->q) {
+               EM_DEBUG_EXCEPTION ("g_queue_new failed");
+               goto FINISH_OFF;
+       }
+       g_queue_init (thd_handle->q);
 
-               case ACTIVE_SYNC_NOTI_RENAME_MAILBOX :
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->rename_mailbox.account_id), DBUS_TYPE_INVALID);
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->rename_mailbox.mailbox_id), DBUS_TYPE_INVALID);
-                       dbus_message_append_args(signal, DBUS_TYPE_STRING, &(data->rename_mailbox.mailbox_name), DBUS_TYPE_INVALID);
-                       dbus_message_append_args(signal, DBUS_TYPE_STRING, &(data->rename_mailbox.mailbox_alias), DBUS_TYPE_INVALID);
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->rename_mailbox.handle), DBUS_TYPE_INVALID);
-                       break;
+       int ret = pthread_mutex_init (&thd_handle->mu, NULL);
+       if (ret == -1) {
+               EM_DEBUG_EXCEPTION ("pthread_mutex_init failed [%d]", errno);
+               goto FINISH_OFF;
+       }
 
-               case ACTIVE_SYNC_NOTI_DELETE_MAILBOX :
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->delete_mailbox.account_id), DBUS_TYPE_INVALID);
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->delete_mailbox.mailbox_id), DBUS_TYPE_INVALID);
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->delete_mailbox.handle), DBUS_TYPE_INVALID);
-                       break;
+       ret = pthread_cond_init (&thd_handle->cond, NULL);
+       if (ret == -1) {
+               EM_DEBUG_EXCEPTION ("pthread_cond_init failed [%d]", errno);
+               goto FINISH_OFF;
+       }
 
-               case ACTIVE_SYNC_NOTI_DELETE_MAILBOX_EX :
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->delete_mailbox_ex.account_id), DBUS_TYPE_INVALID);
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->delete_mailbox_ex.mailbox_id_count), DBUS_TYPE_INVALID);
-                       for(i = 0; i <data->delete_mailbox_ex.mailbox_id_count; i++)
-                               dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->delete_mailbox_ex.mailbox_id_array[i]), DBUS_TYPE_INVALID);
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->delete_mailbox_ex.handle), DBUS_TYPE_INVALID);
-                       break;
+       thd_handle->thread_exit     = thread_exit;
+       thd_handle->thread_exit_arg = arg;
 
-               case ACTIVE_SYNC_NOTI_SEND_MAIL_WITH_DOWNLOADING_OF_ORIGINAL_MAIL:
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->send_mail_with_downloading_attachment_of_original_mail.handle), DBUS_TYPE_INVALID);
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->send_mail_with_downloading_attachment_of_original_mail.mail_id), DBUS_TYPE_INVALID);
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->send_mail_with_downloading_attachment_of_original_mail.account_id), DBUS_TYPE_INVALID);
-                       break;
+       pthread_mutex_unlock (&g_mu);
+       return thd_handle;
 
-               case ACTIVE_SYNC_NOTI_SCHEDULE_SENDING_MAIL:
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->schedule_sending_mail.handle), DBUS_TYPE_INVALID);
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->schedule_sending_mail.account_id), DBUS_TYPE_INVALID);
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->schedule_sending_mail.mail_id), DBUS_TYPE_INVALID);
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->schedule_sending_mail.scheduled_time), DBUS_TYPE_INVALID);
-                       break;
+FINISH_OFF:
+       pthread_mutex_unlock (&g_mu);
+       em_thread_destroy (thd_handle);
+       return NULL;
+}
 
-               case ACTIVE_SYNC_NOTI_CANCEL_SENDING_MAIL:
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->cancel_sending_mail.handle), DBUS_TYPE_INVALID);
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->cancel_sending_mail.account_id  ), DBUS_TYPE_INVALID);
-                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->cancel_sending_mail.mail_id), DBUS_TYPE_INVALID);
-                       break;
+void em_thread_destroy (email_thread_handle_t* thd_handle)
+{
+       if (!thd_handle) return;
 
-               default:
-                       EM_DEBUG_EXCEPTION("Invalid Notification type of Active Sync : subType[%d]", subType);
-                       return FAILURE;
+       if (!g_queue_is_empty (thd_handle->q)) {
+               EM_DEBUG_EXCEPTION ("delete q item routine here");
        }
 
-       if(!dbus_connection_send (connection, signal, NULL)) {
-               EM_DEBUG_EXCEPTION("dbus_connection_send is failed");
-               return FAILURE;
-       } else
-               EM_DEBUG_LOG("dbus_connection_send is successful");
+       pthread_mutex_destroy (&thd_handle->mu);
+       pthread_cond_destroy (&thd_handle->cond);
 
-       dbus_connection_flush(connection);
+       EM_SAFE_FREE (thd_handle);
+}
 
-FINISH_OFF:
+typedef struct {
+       void *(*thread_func)(void*);    /* thread main function */
+       void *(*destroy)(void*);                /* destroyer function */
+       void *arg;
+       email_thread_handle_t *thd_handle;
+} worker_handle_t;
 
-       if(signal)
-               dbus_message_unref(signal);
+static void* worker_func (void* arg)
+{
+       if (!arg) {
+               EM_DEBUG_EXCEPTION ("PARAMETER NULL");
+               return NULL;
+       }
+       /* first task is passed by arg */
+       worker_handle_t* warg = (worker_handle_t*) arg;
+       email_thread_handle_t *thd_handle = warg->thd_handle;
 
-       EM_DEBUG_FUNC_END();
-       return true;
+       if (!thd_handle) {
+               EM_DEBUG_EXCEPTION ("PARAMETER NULL");
+               return NULL;
+       }
+
+       /* consume task in queue and exit */
+       do {
+               /* running thread main function */
+               if (warg->thread_func)
+                       (warg->thread_func) (warg->arg); 
+               if (warg->destroy)
+                       (warg->destroy) (warg->arg);
+               EM_SAFE_FREE (warg);
+
+               /* if there is a pending job */
+               pthread_mutex_lock (&thd_handle->mu);
+               warg = g_queue_pop_head (thd_handle->q);
+               if (!warg) {
+                       thd_handle->running = 0;
+                       pthread_mutex_unlock (&thd_handle->mu);
+                       (thd_handle->thread_exit) (thd_handle->thread_exit_arg);
+                       return NULL;
+               }
+               pthread_mutex_unlock (&thd_handle->mu);
+       } while (1);
+
+       return NULL;
+}
+
+void em_thread_run (email_thread_handle_t *thd_handle, void *(*thread_func)(void*), void *(*destroy)(void*), void* arg)
+{
+       if(!thd_handle || !thread_func) {
+               EM_DEBUG_EXCEPTION ("invalid param");
+               return;
+       }
+
+       worker_handle_t *worker_handle = (worker_handle_t*) calloc (1, sizeof (worker_handle_t));
+       if (!worker_handle) {
+               EM_DEBUG_EXCEPTION ("out of memory");
+               return;
+       }
+       worker_handle->thread_func = thread_func;
+       worker_handle->arg  = arg;
+       worker_handle->thd_handle = thd_handle;
+
+       pthread_mutex_lock (&thd_handle->mu);
+
+       /* adding task to queue */
+       if (thd_handle->running) {
+               g_queue_push_tail (thd_handle->q, worker_handle);               
+       }
+       else {
+               thd_handle->running = 1;
+               pthread_t tid = 0;
+               int err = pthread_create (&tid, NULL, worker_func, worker_handle);
+               if (err < 0 )
+                       EM_DEBUG_EXCEPTION ("pthread_create failed [%d]", errno);
+               thd_handle->tid = tid;
+       }
+       pthread_mutex_unlock (&thd_handle->mu);
 }
+
+void em_thread_join (email_thread_handle_t *thd_handle)
+{
+       int err = pthread_join (thd_handle->tid, NULL);
+       if (err < 0) {
+               EM_DEBUG_EXCEPTION ("pthread_join failed [%d]", errno);
+       }
+}
+
+
index b568293..21820d4 100755 (executable)
@@ -45,6 +45,8 @@ extern "C"
 #include <errno.h>
 
 #define __FEATURE_DEBUG_LOG__
+#define __FEATURE_LOG_FOR_LIFE_CYCLE_OF_FUNCTION__
+#define __FEATURE_LOG_FOR_DEBUG_LOG_DEV__
 
 #ifdef  __FEATURE_DEBUG_LOG__
 
@@ -57,15 +59,43 @@ extern "C"
 
 #define        EM_DEBUG_LOG(format, arg...)        SLOGD(format, ##arg)
 #define        EM_DEBUG_EXCEPTION(format, arg...)  SLOGE("[EXCEPTION!] " format "\n", ##arg)
+
+#ifdef _SECURE_LOG
+#undef _SECURE_LOG
+#endif
+
+#ifdef _SECURE_LOG
+#define        EM_DEBUG_LOG_SEC(format, arg...)        SECURE_SLOGD(format, ##arg)
+#define        EM_DEBUG_EXCEPTION_SEC(format, arg...)  SECURE_SLOGE("[EXCEPTION!] " format "\n", ##arg)
+#define        EM_DEBUG_FUNC_BEGIN_SEC(format, arg...) EM_DEBUG_LOG_SEC("BEGIN - "format, ##arg)
+#else
+#define        EM_DEBUG_LOG_SEC(format, arg...)        SLOGD(format, ##arg)
+#define        EM_DEBUG_EXCEPTION_SEC(format, arg...)  SLOGE("[EXCEPTION!] " format "\n", ##arg)
+#define        EM_DEBUG_FUNC_BEGIN_SEC(format, arg...) EM_DEBUG_LOG("BEGIN - "format, ##arg)
+#endif
+
 #ifdef  _DEBUG_MIME_PARSE_
-#define EM_DEBUG_LOG_MIME(format, arg...)   EM_DEBUG_LOG(format, ##arg)
+#define EM_DEBUG_LOG_MIME(format, arg...)   EM_DEBUG_LOG_SEC(format, ##arg)
 #else   /*  _DEBUG_MIME_PARSE */
 #define EM_DEBUG_LOG_MIME(format, arg...)
 #endif /*  _DEBUG_MIME_PARSE */
 
+#ifdef __FEATURE_LOG_FOR_LIFE_CYCLE_OF_FUNCTION__
 #define        EM_DEBUG_FUNC_BEGIN(format, arg...) EM_DEBUG_LOG("BEGIN - "format, ##arg)
 #define        EM_DEBUG_FUNC_END(format, arg...)   EM_DEBUG_LOG("END - "format, ##arg)
+#else /* __FEATURE_LOG_FOR_LIFE_CYCLE_OF_FUNCTION__ */
+#define        EM_DEBUG_FUNC_BEGIN(format, arg...)
+#define        EM_DEBUG_FUNC_END(format, arg...)
+#undef EM_DEBUG_FUNC_BEGIN_SEC
+#define        EM_DEBUG_FUNC_BEGIN_SEC(format, arg...)
+#endif
+
+#ifdef __FEATURE_LOG_FOR_DEBUG_LOG_DEV__
+#define        EM_DEBUG_LOG_DEV(format, arg...) EM_DEBUG_LOG("[DEV] " format, ##arg)
+#else /* __FEATURE_LOG_FOR_DEBUG_LOG_DEV__ */
+#define        EM_DEBUG_LOG_DEV(format, arg...)
+#endif
+
 #define        EM_DEBUG_LINE                       EM_DEBUG_LOG("FUNC[%s : %d]", __FUNCTION__, __LINE__)
 #define EM_DEBUG_DB_EXEC(eval, expr, X)     if (eval) { EM_DEBUG_LOG X; expr;} else {;}
 
@@ -75,7 +105,27 @@ extern "C"
                                FILE *fp_error = NULL;\
                                fp_error = fopen(EM_DEBUG_ERROR_FILE_PATH, "a");\
                                if(fp_error) {\
-                                       fprintf(fp_error, "[%s() :%s:%d] " format "\n", \
+                                       char now_time_string[30] = {0,}; \
+                                       time_t now = time(NULL); \
+                                       strftime(now_time_string, 20, "%Y.%m.%d %H:%M:%S", localtime(&now)); \
+                                       fprintf(fp_error, "[%s][%s() :%s:%d] " format "\n",\
+                                               now_time_string, \
+                                               __FUNCTION__, (rindex(__FILE__, '/')? rindex(__FILE__,'/')+1 : __FILE__ ),\
+                                               __LINE__, ##arg); \
+                                       fclose(fp_error);\
+                               }\
+                       }
+#define EM_DEBUG_ALARM_LOG_FILE_PATH         "/opt/usr/data/email/.email_data/.alarm.log"
+#define EM_DEBUG_ALARM_LOG(format, arg...)   \
+                       {\
+                               FILE *fp_error = NULL;\
+                               fp_error = fopen(EM_DEBUG_ALARM_LOG_FILE_PATH, "a");\
+                               if(fp_error) {\
+                                       char now_time_string[30] = {0,}; \
+                                       time_t now = time(NULL); \
+                                       strftime(now_time_string, 20, "%Y.%m.%d %H:%M:%S", localtime(&now)); \
+                                       fprintf(fp_error, "[%s][%s() :%s:%d] " format "\n",\
+                                               now_time_string, \
                                                __FUNCTION__, (rindex(__FILE__, '/')? rindex(__FILE__,'/')+1 : __FILE__ ),\
                                                __LINE__, ##arg); \
                                        fclose(fp_error);\
@@ -146,6 +196,9 @@ extern "C"
 
 #endif /* __FEATURE_DEBUG_LOG__ */
 
+/* Use it in api function */
+#define        EM_DEBUG_API_BEGIN(format, arg...) EM_DEBUG_LOG("BEGIN - "format, ##arg)
+#define        EM_DEBUG_API_END(format, arg...)   EM_DEBUG_LOG("END - "format, ##arg)
 
 #define EM_NULL_CHECK_FOR_VOID(expr)   \
        {\
@@ -178,8 +231,8 @@ extern "C"
 
 #define EM_SAFE_FREE(expr)      \
        ({\
-               if (expr ) {\
-                       free(expr);\
+               if (expr) {\
+                       free (expr);\
                        expr = NULL;\
                }\
        })
@@ -228,13 +281,18 @@ extern "C"
 
 #define EM_IF_ACCOUNT_ID_NULL(expr, ret) {\
                if (expr <= 0) {\
-                       EM_DEBUG_EXCEPTION ("EM_IF_ACCOUNT_ID_NULL: Account ID [ %d ]  ", expr);\
+                       EM_DEBUG_EXCEPTION_SEC ("EM_IF_ACCOUNT_ID_NULL: Account ID [ %d ]  ", expr);\
                        return ret;\
                }\
        }
 
 
-#define EM_STRERROR(err) ({ char buf[128]; strerror_r(err, buf, sizeof(buf));})
+#define ERRNO_BUF_SIZE         64
+
+#define EM_STRERROR(errno_buf) ({\
+                                       strerror_r(errno, errno_buf, sizeof(errno_buf));\
+                                       errno_buf;\
+                               })
 
 
 #ifdef  __cplusplus
index 05975ed..2a5247e 100755 (executable)
@@ -70,6 +70,7 @@
 #define EMAIL_ERROR_DB_FAILURE                          -1029    /*  database operation failed */
 #define EMAIL_ERROR_SECURED_STORAGE_FAILURE             -2100    /*  Error from secured storage */
 #define EMAIL_ERROR_GCONF_FAILURE                       -1058    /*  The error occurred on accessing Gconf */
+#define EMAIL_ERROR_FILE                                -1059    /* file related error */
 
 /* Error codes for network */
 #define EMAIL_ERROR_SOCKET_FAILURE                      -1031    /*  socket operation failed */
 #define EMAIL_ERROR_LOGIN_FAILURE                       -1035    /*  login failed */
 #define EMAIL_ERROR_LOGIN_ALLOWED_EVERY_15_MINS         -1600    /*  "login allowed only every 15 minutes" */
 #define EMAIL_ERROR_TOO_MANY_LOGIN_FAILURE              -1601    /*  "Too many login failure" */
+#define EMAIL_ERROR_XOAUTH_BAD_REQUEST                  -1602    /*  "{"status":"400"..." */
+#define EMAIL_ERROR_XOAUTH_INVALID_UNAUTHORIZED         -1603    /*  "{"status":"401"..." */
+#define EMAIL_ERROR_XOAUTH_INVALID_GRANT                -1604    /*  "error" : "invalid_grant" */
+
 
 /* Error codes for functionality */
 #define EMAIL_ERROR_NOT_IMPLEMENTED                     -1047    /*  The function is not implemented yet*/
 #define EMAIL_ERROR_SCAN_NOT_SUPPORTED                  -1037    /* The server doesn't support 'scan mailbox' */
 
 #define EMAIL_ERROR_SMTP_SEND_FAILURE                   -1063    /* SMTP send failed */
+#define EMAIL_ERROR_SMTP_SEND_FAILURE_BY_OVERSIZE       -1073    /* SMTP send failed by too large mail size*/
 
 #define EMAIL_ERROR_POP3_DELE_FAILURE                   -1100    /* Failed to run the command 'Dele' on POP server */
 #define EMAIL_ERROR_POP3_UIDL_FAILURE                   -1101    /* Failed to run the command 'Uidl' on POP server */
 /* Error codes for account */
 #define EMAIL_ERROR_ACCOUNT_IS_QUARANTINED              -5001
 #define EMAIL_ERROR_ACCOUNT_IS_BLOCKED                  -5002
+#define EMAIL_ERROR_ACCOUNT_SYNC_IS_DISALBED            -5003
 
 /* Error codes for mails */
 #define EMAIL_ERROR_MAIL_NOT_FOUND_ON_SERVER            -1055    /*  The expected mail is not found in server */
 /* Error codes for attachment */
 #define EMAIL_ERROR_ATTACHMENT_SIZE_EXCEED_POLICY_LIMIT -7001
 
-/* Error codes for MDM */
+/* Error codes for Other Module */
 #define EMAIL_ERROR_MDM_SERVICE_FAILURE                 -7100
 #define EMAIL_ERROR_MDM_RESTRICTED_MODE                 -7101
+#define EMAIL_ERROR_NOTI                                -7110
 
 /* Etc */
 #define EMAIL_ERROR_ALREADY_INITIALIZED                 -7321
 #define EMAIL_ERROR_ALREADY_EXISTS                      -1023    /*  data duplicated */
 #define EMAIL_ERROR_INPROPER_RESPONSE_FROM_MSG_SERVICE  -1323
 
+/* smack */
+#define EMAIL_ERROR_NO_SMACK_RULE                       -1710    /*  No smack rule exist for file access */
+#define EMAIL_ERROR_PERMISSION_DENIED                   -1720    /*  Failed to check privilege */
+
 /* Not used */
 #define EMAIL_ERROR_INVALID_USER                        -1003    /*  invalid user ID was given. - Invalid user or password */
 #define EMAIL_ERROR_INVALID_PASSWORD                    -1004    /*  invalid password was given. - Invalid user or password */
 #define EMAIL_ERROR_PROFILE_FAILURE                     -1030    /*  no proper profile was found */
 #define EMAIL_ERROR_NO_MMC_INSERTED                     -1209
 #define EMAIL_ERROR_VALIDATE_ACCOUNT                    -1208
+#define EMAIL_ERROR_VALIDATE_ACCOUNT_OF_SMTP            -1215
 #define EMAIL_ERROR_NETWORK_TOO_BUSY                    -1027    /*  Network is busy */
 #define EMAIL_ERROR_DISCONNECTED                        -1034    /*  connection was disconnected */
 #define EMAIL_ERROR_MAIL_LOCKED                         -1049    /*  The mail was locked */
index 9e207b9..dc2c43f 100755 (executable)
@@ -45,10 +45,11 @@ extern "C"
 
 /* ----------------------------------------------------------------------------- */
 /*  Feature definitions */
+/* #define __FEATURE_USING_ACCOUNT_SVC_FOR_ACCOUNT_MANAGEMENT__ */
 #define __FEATURE_USING_ACCOUNT_SVC_FOR_SYNC_STATUS__
 #define __FEATURE_BACKUP_ACCOUNT__
 #define __FEATURE_MOVE_TO_OUTBOX_FIRST__
-/*  #define __FEATURE_PARTIAL_BODY_FOR_POP3__ */
+/*  #define __FEATURE_PARTIAL_BODY_FOR_POP3__*/
 /*  #define __FEATURE_KEEP_CONNECTION__  */
 /*  #define __FEATURE_DRM__ */
 #define __FEATURE_PARTIAL_BODY_DOWNLOAD__
@@ -72,7 +73,16 @@ extern "C"
 #define __FEATURE_DRIVING_MODE__
 #define __FEATURE_DELETE_MAILBOX_RECURSIVELY__
 #define __FEATURE_RENAME_MAILBOX_RECURSIVELY__
+#define __FEATURE_AUTO_RETRY_SEND__
+/*  #define __FEATURE_SMTP_VALIDATION__  */
+/*  #define FEATURE_CORE_DEBUG  */
+/*  #define FEATURE_USE_GMIME  */
+/* #define __FEATURE_BLOCKING_MODE__ */
 #define __FEATURE_BODY_SEARCH__
+/* #define __FEATURE_USE_APPSYNC__ */
+/* #define __FEATURE_ACCESS_CONTROL__ */
+/* #define __FEATURE_IMAP_QUOTA__ */
+
 
 /* ----------------------------------------------------------------------------- */
 /*  Macro */
@@ -92,18 +102,19 @@ extern "C"
 #define EMAIL_ATTACHMENT_MAX_COUNT          512
 #define DOWNLOAD_MAX_BUFFER_SIZE            8000
 #define LOCAL_MAX_BUFFER_SIZE               1000000
-#define IMAP_MAX_COMMAND_LENGTH             1000
+#define IMAP_MAX_COMMAND_LENGTH             2000
 #define DOWNLOAD_NOTI_INTERVAL_PERCENT      5         /*  notify every 5% */
 #define DOWNLOAD_NOTI_INTERVAL_SIZE         51200     /*  notify every 50k */
 #define MAX_PATH                            4096      /* /usr/src/linux-2.4.20-8/include/linux/limits.h */
 #define DATETIME_LENGTH                     16
 #define MAIL_ID_STRING_LENGTH               10
 #define MAILBOX_ID_STRING_LENGTH            10
-#define        EMAIL_LIMITATION_FREE_SPACE         (5) /*  This value is 5MB */
+#define        EMAIL_LIMITATION_FREE_SPACE         (5)       /* This value means 5MB */
 #define EMAIL_MAIL_MAX_COUNT                5000
 #define HTML_EXTENSION_STRING               ".htm"
 #define MAX_PATH_HTML                       256
 #define MAX_ACTIVE_TASK                     10
+#define AUTO_RESEND_INTERVAL                1200      /* 20 minutes */
 
 #define DIR_SEPERATOR                       "/"
 
@@ -123,6 +134,8 @@ extern "C"
 
 #define SHM_FILE_FOR_DB_LOCK                "/.email_shm_db_lock"
 
+#define ACCOUNT_PASSWORD_SS_GROUP_ID        "secure-storage::email-service"
+
 #define NATIVE_EMAIL_APPLICATION_PKG        "com.samsung.email"
 #define NATIVE_EMAIL_DOMAIN                 "email"
 
@@ -172,9 +185,9 @@ extern "C"
 #define THREAD_SELF()                             pthread_self()
 #define THREAD_DETACH(tv)                         pthread_detach(tv)
 #define INITIALIZE_CRITICAL_SECTION(cs)           {EM_DEBUG_LOG("INITIALIZE_CRITICAL_SECTION "#cs); pthread_mutex_init(&cs, NULL); }
-#define ENTER_CRITICAL_SECTION(cs)                {EM_DEBUG_LOG("ENTER_CRITICAL_SECTION "#cs); pthread_mutex_lock(&cs); }
-#define TRY_ENTER_CRITICAL_SECTION(cs)            {EM_DEBUG_LOG("TRY_ENTER_CRITICAL_SECTION "#cs); pthread_mutex_trylock(&cs); }
-#define LEAVE_CRITICAL_SECTION(cs)                {EM_DEBUG_LOG("LEAVE_CRITICAL_SECTION "#cs); pthread_mutex_unlock(&cs); }
+#define ENTER_CRITICAL_SECTION(cs)                {pthread_mutex_lock(&cs); }
+#define TRY_ENTER_CRITICAL_SECTION(cs)            {pthread_mutex_trylock(&cs); }
+#define LEAVE_CRITICAL_SECTION(cs)                {pthread_mutex_unlock(&cs); }
 #define DELETE_CRITICAL_SECTION(cs)               {EM_DEBUG_LOG("DELETE_CRITICAL_SECTION "#cs); pthread_mutex_destroy(&cs); }
 
 #define INITIALIZE_CONDITION_VARIABLE(cv)         {EM_DEBUG_LOG("INITIALIZE_CONDITION_VARIABLE "#cv); pthread_cond_init(&cv, NULL); } 
@@ -182,30 +195,34 @@ extern "C"
 #define WAKE_CONDITION_VARIABLE(cv)               {EM_DEBUG_LOG("WAKE_CONDITION_VARIABLE "#cv); pthread_cond_signal(&cv); } 
 #define DELETE_CONDITION_VARIABLE(cv)             {EM_DEBUG_LOG("DELETE_CONDITION_VARIABLE "#cv); pthread_cond_destroy(&cv); } 
 
-#define INITIALIZE_RECURSIVE_CRITICAL_SECTION(cs) { EM_DEBUG_LOG("INITIALIZE_RECURSIVE_CRITICAL_SECTION "#cs);  \
-                                                   if (cs == NULL) {pthread_mutex_lock(&_send_event_available_lock); pthread_mutexattr_t attr; cs = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t));\
+#define INITIALIZE_RECURSIVE_CRITICAL_SECTION(cs) {EM_DEBUG_LOG("INITIALIZE_RECURSIVE_CRITICAL_SECTION "#cs);\
+                                                   if (cs == NULL) {pthread_mutexattr_t attr; cs = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t));\
                                                    pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE_NP);\
-                                                   pthread_mutex_init(cs, &attr);pthread_mutexattr_destroy(&attr); pthread_mutex_unlock(&_send_event_available_lock);}}
-#define ENTER_RECURSIVE_CRITICAL_SECTION(cs)      {EM_DEBUG_LOG("ENTER_RECURSIVE_CRITICAL_SECTION "#cs); if(cs) pthread_mutex_lock(cs);}
-#define TRY_ENTER_RECURSIVE_CRITICAL_SECTION(cs)  {EM_DEBUG_LOG("TRY_ENTER_RECURSIVE_CRITICAL_SECTION "#cs); if(cs)  pthread_mutex_trylock(cs);}
-#define LEAVE_RECURSIVE_CRITICAL_SECTION(cs)      {EM_DEBUG_LOG("LEAVE_RECURSIVE_CRITICAL_SECTION "#cs); if(cs) pthread_mutex_unlock(cs);}
+                                                   pthread_mutex_init(cs, &attr); pthread_mutexattr_destroy(&attr);}}
+#define ENTER_RECURSIVE_CRITICAL_SECTION(cs)      {if(cs) pthread_mutex_lock(cs);}
+#define TRY_ENTER_RECURSIVE_CRITICAL_SECTION(cs)  {if(cs)  pthread_mutex_trylock(cs);}
+#define LEAVE_RECURSIVE_CRITICAL_SECTION(cs)      {if(cs) pthread_mutex_unlock(cs);}
 #define DELETE_RECURSIVE_CRITICAL_SECTION(cs)     {EM_DEBUG_LOG("DELETE_RECURSIVE_CRITICAL_SECTION "#cs); if(cs) pthread_mutex_destroy(cs);}
 typedef pthread_t thread_t;
 
-#define SMTP_RESPONSE_OK                       250
-#define SMTP_RESPONSE_READY                    354
-#define SMTP_RESPONSE_CONNECTION_BROKEN 421
-#define SMTP_RESPONSE_WANT_AUTH                    505
-#define SMTP_RESPONSE_WANT_AUTH2           530
-#define SMTP_RESPONSE_UNAVAIL              550
+#define SMTP_RESPONSE_OK                   250
+#define SMTP_RESPONSE_READY                354
+#define SMTP_RESPONSE_CONNECTION_BROKEN    421
+#define SMTP_RESPONSE_WANT_AUTH            505
+#define SMTP_RESPONSE_WANT_AUTH2           530
+#define SMTP_RESPONSE_UNAVAIL              550
+#define SMTP_RESPONSE_EXCEED_SIZE_LIMIT    552
 
 #define VCONF_KEY_LATEST_MAIL_ID        "db/private/email-service/latest_mail_id"
 #define VCONF_KEY_DEFAULT_ACCOUNT_ID    "db/private/email-service/default_account_id"
 #define VCONF_KEY_NOTI_PRIVATE_ID       "db/private/email-service/noti_private_id"
 
+#define VCONF_KEY_TOPMOST_WINDOW        "db/private/com.samsung.email/is_topmost_window"
+
 #define OUTMODE  "wb"
 #define INMODE   "rb"
 #define READMODE "r"
+#define WRITEMODE "w"
 
 #define TYPEPKCS7_SIGN 10      
 #define TYPEPKCS7_MIME 11
@@ -213,12 +230,11 @@ typedef pthread_t thread_t;
 #define INLINE_ATTACHMENT    1
 #define ATTACHMENT           2
 
-#define EMAIL_ALARM_CLASS_SCHEDULED_SENDING   1
-#define EMAIL_ALARM_CLASS_NEW_MAIL_ALERT      2
-#define EMAIL_ALARM_CLASS_AUTO_POLLING        3
-
 #define EVENT_QUEUE_MAX 32
 
+#define EMAIL_LAUNCHED_BY_UNKNOWN_METHOD  0
+#define EMAIL_LAUNCHED_BY_DBUS_ACTIVATION 1
+
 /* __FEATURE_LOCAL_ACTIVITY__ supported
 #define BULK_OPERATION_COUNT              50
 #define ALL_ACTIVITIES                    0
@@ -282,10 +298,19 @@ enum
        EXTENSION_P7M    = 10
 };
 
+typedef enum {
+       EMAIL_ALARM_CLASS_SCHEDULED_SENDING   = 1,
+       EMAIL_ALARM_CLASS_NEW_MAIL_ALERT      = 2,
+       EMAIL_ALARM_CLASS_AUTO_POLLING        = 3,
+       EMAIL_ALARM_CLASS_AUTO_RESEND         = 4
+} email_alarm_class_t;
+
+
 /*  event information */
 typedef struct
 {
        int                        account_id;         /*  in general, account id */
+       int                        handle;
        email_event_type_t         type;
        email_event_status_type_t  status;
        char                      *event_param_data_1; /*  in general, mailbox name (exception in emcore_send_mail, emcore_send_saved_mail it is email_option_t **/
@@ -340,6 +365,8 @@ typedef struct
        int                    has_archived_mails;         /**< Specifies the archived mails.*/
        int                    mail_slot_size;             /**< Specifies how many mails can be stored in local mailbox.*/
        int                    no_select;                  /**< Specifies the 'no_select' attribute from xlist.*/
+       int                    eas_data_length;            /**< Specifies the length of eas_data. */
+       char                  *eas_data;                   /**< Specifies the data for eas engine. */
        void                  *user_data;                  /**< Specifies the internal data.*/
        void                  *mail_stream;                /**< Specifies the internal data.*/
 } email_internal_mailbox_t;
@@ -377,7 +404,6 @@ typedef struct {
        thread_t           thread_id;
 } email_active_task_t;
 
-
 typedef void (*email_event_callback)(int total, int done, int status, int account_id, int mail_id, int handle, void *user_data, int error);
 
 /* ----------------------------------------------------------------------------- */
index 6edf1eb..0ffecde 100755 (executable)
@@ -64,6 +64,7 @@ extern "C"
 #define MAX_PREVIEW_TEXT_LENGTH           512
 #define STRING_LENGTH_FOR_DISPLAY         100
 #define MEETING_REQ_OBJECT_ID_LENGTH      256
+#define EMAIL_NO_LIMITED_RETRY_COUNT      -1
 
 #define ALL_ACCOUNT                       0
 #define NEW_ACCOUNT_ID                    0xFFFFFFFE
@@ -135,11 +136,26 @@ extern "C"
 #define DEPRECATED                        __attribute__((deprecated))
 #endif
 
-#define VCONF_VIP_NOTI_RINGTONE_PATH          "db/private/email-service/noti_ringtone_path"            
-#define VCONF_VIP_NOTI_REP_TYPE               "db/private/email-service/noti_rep_type"                 
-#define VCONF_VIP_NOTI_NOTIFICATION_TICKER    "db/private/email-service/noti_notification_ticker"      
-#define VCONF_VIP_NOTI_DISPLAY_CONTENT_TICKER "db/private/email-service/noti_display_content_ticker"   
-#define VCONF_VIP_NOTI_BADGE_TICKER           "db/private/email-service/noti_badge_ticker"             
+#define VCONF_VIP_NOTI_RINGTONE_PATH                 "db/private/email-service/noti_ringtone_path"
+#define VCONF_VIP_NOTI_REP_TYPE                      "db/private/email-service/noti_rep_type"
+#define VCONF_VIP_NOTI_NOTIFICATION_TICKER           "db/private/email-service/noti_notification_ticker"
+#define VCONF_VIP_NOTI_DISPLAY_CONTENT_TICKER        "db/private/email-service/noti_display_content_ticker"
+#define VCONF_VIP_NOTI_BADGE_TICKER                  "db/private/email-service/noti_badge_ticker"
+#define VCONF_VIP_NOTI_VIBRATION_STATUS_BOOL         "db/private/email-service/noti_vip_vibration_status"
+#define VCONF_VIP_NOTI_USE_DEFAULT_RINGTONE_BOOL     "db/private/email-service/noti_vip_use_default_ringtone"
+#define VCONF_EMAIL_NOTI_VIBRATION_STATUS_BOOL       "db/private/email-service/noti_vibration_status"
+#define VCONF_EMAIL_NOTI_USE_DEFAULT_RINGTONE_BOOL   "db/private/email-service/noti_use_default_ringtone"
+
+
+#define EMAIL_PEAK_DAYS_SUNDAY            0x01
+#define EMAIL_PEAK_DAYS_MONDAY            0x02
+#define EMAIL_PEAK_DAYS_TUEDAY            0x04
+#define EMAIL_PEAK_DAYS_WEDDAY            0x08
+#define EMAIL_PEAK_DAYS_THUDAY            0x10
+#define EMAIL_PEAK_DAYS_FRIDAY            0x20
+#define EMAIL_PEAK_DAYS_SATDAY            0x40
+
+#define PRIORITY_SENDER_TAG_ID            -30000
 
 /*****************************************************************************/
 /*  Enumerations                                                             */
@@ -189,6 +205,7 @@ enum {
        _EMAIL_API_DELETE_MAILBOX                            = 0x01200001,
        _EMAIL_API_SET_MAIL_SLOT_SIZE                        = 0x01200007,
        _EMAIL_API_RENAME_MAILBOX                            = 0x01200008,
+       _EMAIL_API_RENAME_MAILBOX_EX                         = 0x0120000B,
        _EMAIL_API_SET_MAILBOX_TYPE                          = 0x01200009,
        _EMAIL_API_SET_LOCAL_MAILBOX                         = 0x0120000A,
 
@@ -204,6 +221,7 @@ enum {
        _EMAIL_API_SEND_MAIL_CANCEL_JOB                      = 0x01300017,
        _EMAIL_API_SEARCH_MAIL_ON_SERVER                     = 0x01300019,
        _EMAIL_API_CLEAR_RESULT_OF_SEARCH_MAIL_ON_SERVER     = 0x0130001A,
+       _EMAIL_API_QUERY_SMTP_MAIL_SIZE_LIMIT                = 0x0130001B,
 
        /* Rule */
        _EMAIL_API_ADD_RULE                                  = 0x01400000,
@@ -223,7 +241,7 @@ enum {
        _EMAIL_API_UPDATE_NOTIFICATION_BAR_FOR_UNREAD_MAIL   = 0x01500001,
        _EMAIL_API_SHOW_USER_MESSAGE                         = 0x01500002,
        _EMAIL_API_WRITE_MIME_FILE                           = 0x01500003,
-       _EMAIL_API_GET_TASK_INFORMATION                       = 0x01500004,
+       _EMAIL_API_GET_TASK_INFORMATION                      = 0x01500004,
 
        /* Smime */
        _EMAIL_API_ADD_CERTIFICATE                           = 0x01600000,
@@ -354,11 +372,14 @@ typedef enum
        NOTI_SYNC_IMAP_MAILBOX_LIST_FAIL,
        NOTI_SYNC_IMAP_MAILBOX_LIST_CANCEL,
 
-       NOTI_DELETE_MAIL_START        = 12300,
+       NOTI_DELETE_MAIL_START        = 12400,
        NOTI_DELETE_MAIL_FINISH,
        NOTI_DELETE_MAIL_FAIL,
        NOTI_DELETE_MAIL_CANCEL,
 
+       NOTI_QUERY_SMTP_MAIL_SIZE_LIMIT_FINISH  = 12500,
+       NOTI_QUERY_SMTP_MAIL_SIZE_LIMIT_FAIL,
+
        /* To be added more */
 } email_noti_on_network_event;
 
@@ -406,9 +427,9 @@ typedef enum
 typedef enum
 {
        EMAIL_FILTER_FROM                = 1,          /**< Specifies the filtering of sender.*/
-       EMAIL_FILTER_SUBJECT,                          /**< Specifies the filtering of email subject.*/
-       EMAIL_FILTER_BODY,                             /**< Specifies the filterinf of email body.*/
-       EMAIL_PRIORITY_SENDER,                         /**< Specifies the priority sender of email. */
+       EMAIL_FILTER_SUBJECT             = 2,          /**< Specifies the filtering of email subject.*/
+       EMAIL_FILTER_BODY                = 4,          /**< Specifies the filterinf of email body.*/
+       EMAIL_PRIORITY_SENDER            = 8,          /**< Specifies the priority sender of email. */
 } email_rule_type_t;
 
 
@@ -447,6 +468,7 @@ typedef enum
        EMAIL_MAIL_STATUS_SEND_CANCELED,               /**< The mail is a canceled mail.*/
        EMAIL_MAIL_STATUS_SEND_WAIT,                   /**< The mail is a mail to be send .*/
        EMAIL_MAIL_STATUS_SEND_SCHEDULED,              /**< The mail is a scheduled mail to be send later.*/
+       EMAIL_MAIL_STATUS_SEND_DELAYED,                /**< The mail is a delayed mail to be send later.*/
 } email_mail_status_t;
 
 /**
@@ -505,6 +527,8 @@ typedef enum
        EMAIL_MEETING_RESPONSE_DECLINE             = 3, /**< The response is decline */
        EMAIL_MEETING_RESPONSE_REQUEST             = 4, /**< The response is request */
        EMAIL_MEETING_RESPONSE_CANCEL              = 5, /**< The response is cancellation */
+       EMAIL_MEETING_RESPONSE_PROPOSE_NEW_TIME_TENTATIVE,
+       EMAIL_MEETING_RESPONSE_PROPOSE_NEW_TIME_DECLINE
 } email_meeting_response_t;
 
 typedef enum
@@ -531,6 +555,7 @@ typedef enum
        EMAIL_ACTION_EXPUNGE_MAILS_DELETED_FLAGGED = 32,
        EMAIL_ACTION_SEARCH_ON_SERVER              = 33,
        EMAIL_ACTION_MOVE_MAILBOX                  = 34,
+       EMAIL_ACTION_SENDING_MAIL                  = 35,
        EMAIL_ACTION_NUM,
 } email_action_t;
 
@@ -739,6 +764,7 @@ typedef enum
        EMAIL_EVENT_SEARCH_ON_SERVER                = 21,
        EMAIL_EVENT_RENAME_MAILBOX_ON_IMAP_SERVER   = 22,
        EMAIL_EVENT_VALIDATE_ACCOUNT_EX             = 23,
+       EMAIL_EVENT_QUERY_SMTP_MAIL_SIZE_LIMIT      = 24,
 
        EMAIL_EVENT_ADD_MAIL                        = 10001,       /*  Deprecated */
        EMAIL_EVENT_UPDATE_MAIL_OLD                 = 10002,       /*  Deprecated */
@@ -1036,33 +1062,39 @@ typedef enum {
        EMAIL_MAIL_ATTRIBUTE_CC                      = 14,  /* string type */
        EMAIL_MAIL_ATTRIBUTE_BCC                     = 15,  /* string type */
        EMAIL_MAIL_ATTRIBUTE_BODY_DOWNLOAD_STATUS    = 16,  /* integer type */
-       EMAIL_MAIL_ATTRIBUTE_FILE_PATH_PLAIN         = 17,  /* string type */
-       EMAIL_MAIL_ATTRIBUTE_FILE_PATH_HTML          = 18,  /* string type */
-       EMAIL_MAIL_ATTRIBUTE_FILE_SIZE               = 19,  /* integer type */
-       EMAIL_MAIL_ATTRIBUTE_FLAGS_SEEN_FIELD        = 20,  /* integer type */
-       EMAIL_MAIL_ATTRIBUTE_FLAGS_DELETED_FIELD     = 21,  /* integer type */
-       EMAIL_MAIL_ATTRIBUTE_FLAGS_FLAGGED_FIELD     = 22,  /* integer type */
-       EMAIL_MAIL_ATTRIBUTE_FLAGS_ANSWERED_FIELD    = 23,  /* integer type */
-       EMAIL_MAIL_ATTRIBUTE_FLAGS_RECENT_FIELD      = 24,  /* integer type */
-       EMAIL_MAIL_ATTRIBUTE_FLAGS_DRAFT_FIELD       = 25,  /* integer type */
-       EMAIL_MAIL_ATTRIBUTE_FLAGS_FORWARDED_FIELD   = 26,  /* integer type */
-       EMAIL_MAIL_ATTRIBUTE_DRM_STATUS              = 27,  /* integer type */
-       EMAIL_MAIL_ATTRIBUTE_PRIORITY                = 28,  /* integer type */
-       EMAIL_MAIL_ATTRIBUTE_SAVE_STATUS             = 29,  /* integer type */
-       EMAIL_MAIL_ATTRIBUTE_LOCK_STATUS             = 30,  /* integer type */
-       EMAIL_MAIL_ATTRIBUTE_REPORT_STATUS           = 31,  /* integer type */
-       EMAIL_MAIL_ATTRIBUTE_ATTACHMENT_COUNT        = 32,  /* integer type */
-       EMAIL_MAIL_ATTRIBUTE_INLINE_CONTENT_COUNT    = 33,  /* integer type */
-       EMAIL_MAIL_ATTRIBUTE_THREAD_ID               = 34,  /* integer type */
-       EMAIL_MAIL_ATTRIBUTE_THREAD_ITEM_COUNT       = 35,  /* integer type */
-       EMAIL_MAIL_ATTRIBUTE_PREVIEW_TEXT            = 36,  /* string type */
-       EMAIL_MAIL_ATTRIBUTE_MEETING_REQUEST_STATUS  = 37,  /* integer type */
-       EMAIL_MAIL_ATTRIBUTE_MESSAGE_CLASS           = 38,  /* integer type */
-       EMAIL_MAIL_ATTRIBUTE_DIGEST_TYPE             = 39,  /* integer type */
-       EMAIL_MAIL_ATTRIBUTE_SMIME_TYPE              = 40,  /* integer type */
-       EMAIL_MAIL_ATTRIBUTE_SCHEDULED_SENDING_TIME  = 41,  /* integer type */
-       EMAIL_MAIL_ATTRIBUTE_EAS_DATA_LENGTH_TYPE    = 42,  /* integer type */
-       EMAIL_MAIL_ATTRIBUTE_EAS_DATA_TYPE           = 43,  /* binary type */
+       EMAIL_MAIL_ATTRIBUTE_MAIL_SIZE               = 17,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_FILE_PATH_PLAIN         = 18,  /* string type */
+       EMAIL_MAIL_ATTRIBUTE_FILE_PATH_HTML          = 19,  /* string type */
+       EMAIL_MAIL_ATTRIBUTE_FILE_SIZE               = 20,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_FLAGS_SEEN_FIELD        = 21,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_FLAGS_DELETED_FIELD     = 22,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_FLAGS_FLAGGED_FIELD     = 23,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_FLAGS_ANSWERED_FIELD    = 24,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_FLAGS_RECENT_FIELD      = 25,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_FLAGS_DRAFT_FIELD       = 26,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_FLAGS_FORWARDED_FIELD   = 27,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_DRM_STATUS              = 28,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_PRIORITY                = 29,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_SAVE_STATUS             = 30,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_LOCK_STATUS             = 31,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_REPORT_STATUS           = 32,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_ATTACHMENT_COUNT        = 33,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_INLINE_CONTENT_COUNT    = 34,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_THREAD_ID               = 35,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_THREAD_ITEM_COUNT       = 36,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_PREVIEW_TEXT            = 37,  /* string type */
+       EMAIL_MAIL_ATTRIBUTE_MEETING_REQUEST_STATUS  = 38,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_MESSAGE_CLASS           = 39,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_DIGEST_TYPE             = 40,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_SMIME_TYPE              = 41,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_SCHEDULED_SENDING_TIME  = 42,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_REMAINING_RESEND_TIMES  = 43,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_TAG_ID                  = 44,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_REPLIED_TIME            = 45,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_FORWARDED_TIME          = 46,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_RECIPIENT_ADDRESS       = 47,  /* string type */
+       EMAIL_MAIL_ATTRIBUTE_EAS_DATA_LENGTH_TYPE    = 48,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_EAS_DATA_TYPE           = 49,  /* binary type */
        EMAIL_MAIL_ATTRIBUTE_END                         
 } email_mail_attribute_type;
 
@@ -1072,6 +1104,11 @@ typedef enum {
 } email_mail_text_attribute_type;
 
 typedef enum {
+       EMAIL_MAIL_ATTACH_ATTRIBUTE_ATTACHMENT_NAME = 1,
+       EMAIL_MAIL_ATTCH_ATTRIBUTE_END
+} email_mail_attach_attribute_type;
+
+typedef enum {
        EMAIL_MAIL_ATTRIBUTE_VALUE_TYPE_NONE         = 0,
        EMAIL_MAIL_ATTRIBUTE_VALUE_TYPE_INTEGER      = 1,
        EMAIL_MAIL_ATTRIBUTE_VALUE_TYPE_STRING       = 2,
@@ -1113,6 +1150,7 @@ typedef enum {
        EMAIL_MESSAGE_CLASS_REPORT_READ_REPORT                                  = 0x20000000,
        EMAIL_MESSAGE_CLASS_REPORT_NON_DELIVERY_RECEIPT                         = 0x40000000,
        EMAIL_MESSAGE_CLASS_REPORT_DELIVERY_RECEIPT                             = 0x80000000,
+       EMAIL_MESSAGE_CLASS_CALENDAR_FORWARD                                                        = 0x04000000
 } email_message_class; 
 
 typedef enum{
@@ -1135,6 +1173,22 @@ typedef enum {
        DIGEST_TYPE_MD5,
 } email_digest_type;
 
+typedef enum {
+       EMAIL_AUTHENTICATION_METHOD_NO_AUTH          = 0,
+       EMAIL_AUTHENTICATION_METHOD_DEFAULT          = 1,
+       EMAIL_AUTHENTICATION_METHOD_XOAUTH2          = 2,
+} email_authentication_method_t;
+
+typedef enum {
+       EMAIL_ROAMING_OPTION_RESTRICTED_BACKGROUND_TASK  = 0,
+       EMAIL_ROAMING_OPTION_UNRESTRICTED                = 1,
+} email_roaming_option_t;
+
+typedef enum {
+       EMAIL_GET_INCOMING_PASSWORD_LENGTH = 1,
+       EMAIL_GET_OUTGOING_PASSWORD_LENGTH
+} email_get_password_length_type;
+
 /*****************************************************************************/
 /*  Data Structures                                                          */
 /*****************************************************************************/
@@ -1179,59 +1233,67 @@ typedef struct
 typedef struct
 {
        /* General account information */
-       int                          account_id;                               /**< Account id  */
-       char                        *account_name;                             /**< Account name */
-       int                          account_svc_id;                           /**< AccountSvc priv data: Specifies id from account-svc */
-       int                          sync_status;                              /**< Sync Status. SYNC_STATUS_FINISHED, SYNC_STATUS_SYNCING, SYNC_STATUS_HAVE_NEW_MAILS */
-       int                          sync_disabled;                            /**< If this attriube is set as true, email-service will not synchronize this account. */
-       int                          default_mail_slot_size;
-       char                        *logo_icon_path;                           /**< account logo icon (used by account svc and email app) */
-       void                        *user_data;                                /**< binary user data */
-       int                                          user_data_length;                         /**< user data length */
+       int                             account_id;                               /**< Account id  */
+       char                           *account_name;                             /**< Account name */
+       int                             account_svc_id;                           /**< AccountSvc priv data: Specifies id from account-svc */
+       int                             sync_status;                              /**< Sync Status. SYNC_STATUS_FINISHED, SYNC_STATUS_SYNCING, SYNC_STATUS_HAVE_NEW_MAILS */
+       int                             sync_disabled;                            /**< If this attriube is set as true, email-service will not synchronize this account. */
+       int                             default_mail_slot_size;
+       char                           *logo_icon_path;                           /**< account logo icon (used by account svc and email app) */
+       email_roaming_option_t          roaming_option;                           /**< roaming option */
+       void                           *user_data;                                /**< binary user data */
+       int                                             user_data_length;                         /**< user data length */
 
        /* User information */
-       char                            *user_display_name;                        /**< User's display */
-       char                            *user_email_address;                       /**< User's email address */
-       char                        *reply_to_address;                         /**< Email address for reply */
-       char                        *return_address;                           /**< Email address for error from server*/
+       char                           *user_display_name;                        /**< User's display */
+       char                           *user_email_address;                       /**< User's email address */
+       char                           *reply_to_address;                         /**< Email address for reply */
+       char                           *return_address;                           /**< Email address for error from server*/
 
        /* Configuration for incoming server */
-       email_account_server_t       incoming_server_type;                     /**< Incoming server type */
-       char                        *incoming_server_address;                  /**< Incoming server address */
-       int                          incoming_server_port_number;              /**< Incoming server port number */
-       char                        *incoming_server_user_name;                /**< Incoming server user name */
-       char                        *incoming_server_password;                 /**< Incoming server password */
-       int                          incoming_server_secure_connection;        /**< Does incoming server requires secured connection? */
+       email_account_server_t          incoming_server_type;                     /**< Incoming server type */
+       char                           *incoming_server_address;                  /**< Incoming server address */
+       int                             incoming_server_port_number;              /**< Incoming server port number */
+       char                           *incoming_server_user_name;                /**< Incoming server user name */
+       char                           *incoming_server_password;                 /**< Incoming server password */
+       int                             incoming_server_secure_connection;        /**< Does incoming server requires secured connection? */
+       email_authentication_method_t   incoming_server_authentication_method;    /**< Incoming server authentication method */
 
        /* Options for incoming server */
-       email_imap4_retrieval_mode_t retrieval_mode;                           /**< Retrieval mode : EMAIL_IMAP4_RETRIEVAL_MODE_NEW or EMAIL_IMAP4_RETRIEVAL_MODE_ALL */
-       int                          keep_mails_on_pop_server_after_download;  /**< Keep mails on POP server after download */
-       int                          check_interval;                           /**< Specifies the interval for checking new mail periodically */
-       int                          auto_download_size;                       /**< Specifies the size for auto download in bytes. -1 means entire mails body */
+       email_imap4_retrieval_mode_t    retrieval_mode;                           /**< Retrieval mode : EMAIL_IMAP4_RETRIEVAL_MODE_NEW or EMAIL_IMAP4_RETRIEVAL_MODE_ALL */
+       int                             keep_mails_on_pop_server_after_download;  /**< Keep mails on POP server after download */
+       int                             check_interval;                           /**< Specifies the interval for checking new mail periodically */
+       int                             auto_download_size;                       /**< Specifies the size for auto download in bytes. -1 means entire mails body */
+       int                             peak_interval;                            /**< Specifies the interval for checking new mail periodically of peak schedule */
+       int                             peak_days;                                /**< Specifies the weekdays of peak schedule */
+       int                             peak_start_time;                          /**< Specifies the start time of peak schedule */
+       int                             peak_end_time;                            /**< Specifies the end time of peak schedule */
 
        /* Configuration for outgoing server */
-       email_account_server_t       outgoing_server_type;                     /**< Outgoing server type */
-       char                                    *outgoing_server_address;                  /**< Outgoing server address */
-       int                                              outgoing_server_port_number;              /**< Outgoing server port number */
-       char                                    *outgoing_server_user_name;                /**< Outgoing server user name */
-       char                                    *outgoing_server_password;                 /**< Outgoing server password */
-       int                                      outgoing_server_secure_connection;        /**< Does outgoing server requires secured connection? */
-       int                                      outgoing_server_need_authentication;      /**< Does outgoing server requires authentication? */
-       int                                      outgoing_server_use_same_authenticator;   /**< Use same authenticator for outgoing server */
+       email_account_server_t          outgoing_server_type;                     /**< Outgoing server type */
+       char                                       *outgoing_server_address;                  /**< Outgoing server address */
+       int                                                 outgoing_server_port_number;              /**< Outgoing server port number */
+       char                                       *outgoing_server_user_name;                /**< Outgoing server user name */
+       char                                       *outgoing_server_password;                 /**< Outgoing server password */
+       int                                         outgoing_server_secure_connection;        /**< Does outgoing server requires secured connection? */
+       int                                         outgoing_server_need_authentication;      /**< Does outgoing server requires authentication? */
+       int                                         outgoing_server_use_same_authenticator;   /**< Use same authenticator for outgoing server - email_authentication_method_t - */
 
 
        /* Options for outgoing server */
-       email_option_t                   options;
+       email_option_t                      options;
+       int                             auto_resend_times;                        /**< Auto retry count for sending a email */
+       int                            outgoing_server_size_limit;                /** Mail size limitation for SMTP sending*/
 
        /* Authentication Options */
-       int                              pop_before_smtp;                          /**< POP before SMTP Authentication */
-       int                          incoming_server_requires_apop;            /**< APOP authentication */
+       int                                 pop_before_smtp;                          /**< POP before SMTP Authentication */
+       int                             incoming_server_requires_apop;            /**< APOP authentication */
 
        /* S/MIME Options */
-       email_smime_type             smime_type;                               /**< Specifies the smime type 0=Normal 1=Clear signed 2=encrypted 3=Signed + encrypted */
-       char                        *certificate_path;                         /**< Specifies the certificate path of private*/
-       email_cipher_type            cipher_type;                              /**< Specifies the encryption algorithm*/
-       email_digest_type            digest_type;                              /**< Specifies the digest algorithm*/
+       email_smime_type                smime_type;                               /**< Specifies the smime type 0=Normal 1=Clear signed 2=encrypted 3=Signed + encrypted */
+       char                           *certificate_path;                         /**< Specifies the certificate path of private*/
+       email_cipher_type               cipher_type;                              /**< Specifies the encryption algorithm*/
+       email_digest_type               digest_type;                              /**< Specifies the digest algorithm*/
 } email_account_t;
 
 /**
@@ -1335,8 +1397,12 @@ typedef struct
        email_digest_type     digest_type;             /**< Specifies the digest algorithm*/
        email_smime_type      smime_type;              /**< Specifies the SMIME type. */
        time_t                scheduled_sending_time;  /**< Specifies the scheduled sending time.*/
+       int                   remaining_resend_times;  /**< Specifies the remaining resend times.*/
+       int                   tag_id;                  /**< Specifies the data for filtering. */
+       time_t                replied_time;            /**< Specifies the time of replied. */
+       time_t                forwarded_time;          /**< Specifies the time of forwarded. */
        int                   eas_data_length;         /**< Specifies the length of eas_data. */
-       char                 *eas_data;                /**< Specifies the data for eas engine. */
+       void                 *eas_data;                /**< Extended Application Specific data. */
 } email_mail_data_t;
 
 /**
@@ -1347,11 +1413,13 @@ typedef struct
        int                   mail_id;                                            /**< Specifies the mail id.*/
        int                   account_id;                                         /**< Specifies the account id.*/
        int                   mailbox_id;                                         /**< Specifies the mailbox id.*/
+       email_mailbox_type_e  mailbox_type;                                       /**< Specifies the mailbox type of the mail. */
        char                  full_address_from[STRING_LENGTH_FOR_DISPLAY];       /**< Specifies the full from email address.*/
        char                  email_address_sender[MAX_EMAIL_ADDRESS_LENGTH];     /**< Specifies the sender email address.*/
        char                  email_address_recipient[STRING_LENGTH_FOR_DISPLAY]; /**< Specifies the recipients email address.*/
        char                  subject[STRING_LENGTH_FOR_DISPLAY];                 /**< Specifies the subject.*/
        int                   body_download_status;                               /**< Specifies the text donwloaded or not.*/
+       int                   mail_size;                                          /**< Specifies the mail size. */
        time_t                date_time;                                          /**< Specifies the date time.*/
        char                  flags_seen_field;                                   /**< Specifies the seen flags*/
        char                  flags_deleted_field;                                /**< Specifies the deleted flags*/
@@ -1374,8 +1442,10 @@ typedef struct
        int                   message_class;                                      /**< Specifies the message class */ /* email_message_class */
        email_smime_type      smime_type;                                         /**< Specifies the smime type */ /* email_smime_type */
        time_t                scheduled_sending_time;                             /**< Specifies the scheduled sending time.*/
+       int                   remaining_resend_times;                             /**< Specifies the remaining resend times.*/
+       int                   tag_id;                                             /**< Specifies the data for filtering */
        int                   eas_data_length;                                    /**< Specifies the length of eas_data. */
-       char                 *eas_data;                                           /**< Specifies the data for eas engine. */
+       void                 *eas_data;                                           /**< Extended Application Specific data. */
 } email_mail_list_item_t;
 
 /**
@@ -1385,8 +1455,10 @@ typedef struct
 {
        int                  account_id;          /**< Specifies the account ID.*/
        int                  filter_id;           /**< Specifies the filtering ID.*/
+       char                *filter_name;         /**< Specifies the filtering name. */
        email_rule_type_t    type;                /**< Specifies the filtering type.*/
-       char                *value;               /**< Specifies the filtering value.*/
+       char                *value;               /**< Specifies the filtering value : subject. */
+       char                *value2;              /**< Specifies the filtering value2 : sender address. */
        email_rule_action_t  faction;             /**< Specifies the action type for filtering.*/
        int                  target_mailbox_id;   /**< Specifies the mail box if action type means move.*/
        int                  flag1;               /**< Specifies the activation.*/
@@ -1497,6 +1569,8 @@ typedef struct
        int                   no_select;                  /**< Specifies the 'no_select' attribute from xlist.*/
        time_t                last_sync_time;
        int                   deleted_flag;               /**< Specifies whether mailbox is deleted.*/
+       int                   eas_data_length;            /**< Specifies the length of eas_data. */
+       void                 *eas_data;                   /**< Specifies the data for eas engine. */
 } email_mailbox_t;
 
 typedef struct
@@ -1570,10 +1644,18 @@ typedef struct {
        email_mail_attribute_value_t           key_value;
 } email_list_filter_rule_fts_t;
 
+typedef struct {
+       email_list_filter_rule_type_t          rule_type;
+       email_mail_attach_attribute_type       target_attribute;
+       email_mail_attribute_value_t           key_value;
+       email_list_filter_case_sensitivity_t   case_sensitivity;
+} email_list_filter_rule_attach_t;
+
 typedef enum {
        EMAIL_LIST_FILTER_ITEM_RULE                     = 0,
        EMAIL_LIST_FILTER_ITEM_RULE_FTS                 = 1,
-       EMAIL_LIST_FILTER_ITEM_OPERATOR                 = 2,
+       EMAIL_LIST_FILTER_ITEM_RULE_ATTACH              = 2,
+       EMAIL_LIST_FILTER_ITEM_OPERATOR                 = 3,
 } email_list_filter_item_type_t;
 
 typedef enum {
@@ -1589,6 +1671,7 @@ typedef struct {
        union {
                email_list_filter_rule_t           rule;
                email_list_filter_rule_fts_t       rule_fts;
+               email_list_filter_rule_attach_t    rule_attach;
                email_list_filter_operator_type_t  operator_type;
        } list_filter_item;
 
@@ -1596,12 +1679,16 @@ typedef struct {
 
 typedef enum {
        EMAIL_SORT_ORDER_ASCEND                             = 0,
-       EMAIL_SORT_ORDER_DESCEND                            = 1
+       EMAIL_SORT_ORDER_DESCEND                            = 1,
+       EMAIL_SORT_ORDER_TO_CCBCC                           = 2,
+       EMAIL_SORT_ORDER_TO_CC_BCC                          = 3,
+       EMAIL_SORT_ORDER_TO_CCBCC_ALL                       = 4
 } email_list_filter_sort_order_t;
 
 
 typedef struct {
        email_mail_attribute_type              target_attribute;
+       email_mail_attribute_value_t           key_value;
        bool                                   force_boolean_check;
        email_list_filter_sort_order_t         sort_order;
 } email_list_sorting_rule_t;
@@ -1614,6 +1701,34 @@ typedef struct {
        email_event_status_type_t              status;
 } email_task_information_t;
 
+typedef enum {
+       EMAIL_MESSAGE_CONTEXT_VOICE_MESSAGE                 = 1,
+       EMAIL_MESSAGE_CONTEXT_VIDEO_MESSAGE                 = 2,
+       EMAIL_MESSAGE_CONTEXT_FAX_MESSAGE                   = 3,
+       EMAIL_MESSAGE_CONTEXT_X_EMPTY_CALL_CAPTURE_MESSAGE  = 4,
+       EMAIL_MESSAGE_CONTEXT_X_NUMBER_MESSAGE              = 5,
+       EMAIL_MESSAGE_CONTEXT_X_VOICE_INFOTAINMENT_MESSAGE  = 6
+} email_message_context_t;
+
+typedef enum {
+       EMAIL_MESSAGE_SENSITIVITY_PRIVATE                   = 1,
+       EMAIL_MESSAGE_SENSITIVITY_CONFIDENTIAL              = 2,
+       EMAIL_MESSAGE_SENSITIVITY_PERSONAL                  = 3
+} email_message_sensitivity_t;
+
+typedef struct {
+       email_message_context_t                message_context;
+       int                                    content_length;     /* Content-Duration for audio/video or X-Content-Pages for fax */
+       email_message_sensitivity_t            sensitivity;
+} email_vvm_specific_data_t;
+
+typedef struct {
+       char *quota_root;
+       char *resource_name;
+       int   usage;
+       int   limits;
+} email_quota_resource_t;
+
 /*****************************************************************************/
 /*  For Active Sync                                                          */
 /*****************************************************************************/
@@ -1747,6 +1862,8 @@ typedef union
                int                     account_id;
                char                   *mailbox_path;
                char                   *mailbox_alias;
+               void                   *eas_data;
+               int                     eas_data_length;
        } add_mailbox;
 
        struct _rename_mailbox
@@ -1756,6 +1873,8 @@ typedef union
                int                     mailbox_id;
                char                   *mailbox_name;
                char                   *mailbox_alias;
+               void                   *eas_data;
+               int                     eas_data_length;
        } rename_mailbox;
 
        struct _delete_mailbox
index 0472528..9a9ebf5 100755 (executable)
@@ -53,8 +53,8 @@ INTERNAL_FUNC char* em_get_extension_from_file_path(char *source_file_path, int
 INTERNAL_FUNC int   em_get_encoding_type_from_file_path(const char *input_file_path, char **output_encoding_type);
 INTERNAL_FUNC int   em_get_content_type_from_extension_string(const char *extension_string, int *err_code);
 
-INTERNAL_FUNC int   em_verify_email_address(char *address, int without_bracket, int *err_code);
-INTERNAL_FUNC int   em_verify_email_address_of_mail_data(email_mail_data_t *mail_data, int without_bracket, int *err_code);
+INTERNAL_FUNC int   em_verify_email_address(char *address, int without_bracket);
+INTERNAL_FUNC int   em_verify_email_address_of_mail_data(email_mail_data_t *mail_data, int without_bracket);
 INTERNAL_FUNC int   em_verify_email_address_of_mail_tbl(emstorage_mail_tbl_t *input_mail_tbl, int input_without_bracket);
 
 INTERNAL_FUNC int   em_find_pos_stripped_subject_for_thread_view(char *subject, char *stripped_subject, int stripped_subject_buffer_size);
@@ -68,6 +68,24 @@ extern        char* strcasestr(__const char *__haystack, __const char *__needle)
 INTERNAL_FUNC int   em_get_account_server_type_by_account_id(int account_id, email_account_server_t* account_server_type, int flag, int *error);
 
 INTERNAL_FUNC int   em_get_handle_for_activesync(int *handle, int *error);
-INTERNAL_FUNC int   em_send_notification_to_active_sync_engine(int subType, ASNotiData *data);
+INTERNAL_FUNC int   em_check_socket_privilege_by_pid(int pid);
+INTERNAL_FUNC int   em_check_db_privilege_by_pid(int pid);
+
+/* thread handle definition */
+typedef struct {
+       GQueue *q;
+       pthread_mutex_t mu;
+       pthread_cond_t cond;
+       int running;
+       pthread_t tid;
+       void *(*thread_exit)(void*);
+       void *thread_exit_arg;
+} email_thread_handle_t;
+
+INTERNAL_FUNC email_thread_handle_t* em_thread_create ();
+INTERNAL_FUNC void em_thread_destroy (email_thread_handle_t* th);
+INTERNAL_FUNC void em_thread_run (email_thread_handle_t *th, void *(*thread_func)(void*), void *(*destroy)(void*), void* arg);
+INTERNAL_FUNC void em_thread_join (email_thread_handle_t *th);
+
 
 #endif /* __EMAIL_UTILITIES_H__ */
index 096c00f..7e0efaf 100755 (executable)
@@ -31,7 +31,7 @@ INCLUDE_DIRECTORIES(
 
 
 INCLUDE(FindPkgConfig)
-pkg_check_modules(storage_pkgs REQUIRED glib-2.0 dlog vconf dbus-1)
+pkg_check_modules(device_pkgs REQUIRED glib-2.0 dlog vconf pmapi dbus-1)
 
 set(EXTRA_CFLAGS "")
 FOREACH(flag ${device_pkgs_CFLAGS})
@@ -42,12 +42,12 @@ SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${EXTRA_CFLAGS}")
 
 #message(">>> extra_cflags ${EXTRA_CFLAGS}")
 #message(">>> result ${CMAKE_C_FLAGS}")
-
+#message(">>> ld flag ${device_pkgs_LDFLAGS}")
 
 SET(CMAKE_EXE_LINKER_FLAGS "-Wl,--as-needed")
 
 ADD_LIBRARY(${DEVICE-LIB} SHARED ${DEVICE-SRCS})
-TARGET_LINK_LIBRARIES(${DEVICE-LIB} ${device_LDFLAGS} ${BASE-LIB})
+TARGET_LINK_LIBRARIES(${DEVICE-LIB} ${device_pkgs_LDFLAGS} ${BASE-LIB})
 SET_TARGET_PROPERTIES(${DEVICE-LIB} PROPERTIES SOVERSION ${VERSION_MAJOR})
 SET_TARGET_PROPERTIES(${DEVICE-LIB} PROPERTIES VERSION ${VERSION})
 
@@ -132,6 +132,50 @@ SET_TARGET_PROPERTIES(${NETWORK-LIB} PROPERTIES VERSION ${VERSION})
 INSTALL(TARGETS ${NETWORK-LIB} DESTINATION ${LIB_INSTALL_DIR} COMPONENT RuntimeLibraries)
 
 ##########################################################
+# Define Core-sound lib
+##########################################################
+
+SET(CORE-SOUND-LIB "email-core-sound")
+SET(CORE-SOUND-SRCS 
+       ${CMAKE_SOURCE_DIR}/email-core/email-core-sound.c
+)
+
+INCLUDE_DIRECTORIES(
+       ${CMAKE_SOURCE_DIR}/email-common-use/include
+       ${CMAKE_SOURCE_DIR}/email-daemon/include/
+       ${CMAKE_SOURCE_DIR}/email-core/include
+       ${CMAKE_SOURCE_DIR}/email-core/email-storage/include
+)
+
+
+INCLUDE(FindPkgConfig)
+pkg_check_modules(core_sound_pkgs REQUIRED glib-2.0 dlog dbus-1 gthread-2.0 
+                       vconf vconf-internal-keys mm-player mm-session feedback 
+                       alarm-service notification badge)
+
+set(EXTRA_CFLAGS "")
+FOREACH(flag ${core_sound_pkgs_CFLAGS})
+       SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag}")
+ENDFOREACH(flag)
+
+SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${EXTRA_CFLAGS}")
+
+#message(">> core extra raw: ${core_sound_pkgs_CFLAGS}")
+#message(">> core extra : ${EXTRA_CFLAGS}")
+#message(">> core result: ${CMAKE_C_FLAGS}")
+
+SET(CMAKE_EXE_LINKER_FLAGS "-Wl,--as-needed")
+
+ADD_LIBRARY(${CORE-SOUND-LIB} SHARED ${CORE-SOUND-SRCS})
+
+TARGET_LINK_LIBRARIES(${CORE-SOUND-LIB} ${core_sound_pkgs_LDFLAGS} ${STORAGE-LIB} ${CORE-LIB})
+
+SET_TARGET_PROPERTIES(${CORE-SOUND-LIB} PROPERTIES SOVERSION ${VERSION_MAJOR})
+SET_TARGET_PROPERTIES(${CORE-SOUND-LIB} PROPERTIES VERSION ${VERSION})
+
+INSTALL(TARGETS ${CORE-SOUND-LIB} DESTINATION lib COMPONENT RuntimeLibraries)
+
+##########################################################
 # Define Core lib
 ##########################################################
 
@@ -144,16 +188,13 @@ SET(CORE-SRCS
        ${CMAKE_SOURCE_DIR}/email-core/email-core-mail.c
        ${CMAKE_SOURCE_DIR}/email-core/email-core-mm-callbacks.c
        ${CMAKE_SOURCE_DIR}/email-core/email-core-utils.c
-       ${CMAKE_SOURCE_DIR}/email-core/email-core-api.c
        ${CMAKE_SOURCE_DIR}/email-core/email-core-smtp.c
        ${CMAKE_SOURCE_DIR}/email-core/email-core-timer.c
        ${CMAKE_SOURCE_DIR}/email-core/email-core-imap-idle.c
        ${CMAKE_SOURCE_DIR}/email-core/email-core-global.c
        ${CMAKE_SOURCE_DIR}/email-core/email-core-account.c
        ${CMAKE_SOURCE_DIR}/email-core/email-core-mime.c
-       ${CMAKE_SOURCE_DIR}/email-core/email-core-smime.c
-       ${CMAKE_SOURCE_DIR}/email-core/email-core-cert.c
-       ${CMAKE_SOURCE_DIR}/email-core/email-core-sound.c
+#      ${CMAKE_SOURCE_DIR}/email-core/email-core-sound.c
        ${CMAKE_SOURCE_DIR}/email-core/email-core-task-manager.c
        ${CMAKE_SOURCE_DIR}/email-core/email-core-tasks.c
        ${CMAKE_SOURCE_DIR}/email-core/email-core-signal.c
@@ -162,7 +203,6 @@ SET(CORE-SRCS
 
 INCLUDE_DIRECTORIES(
        ${CMAKE_SOURCE_DIR}/email-common-use/include
-       ${CMAKE_SOURCE_DIR}/email-daemon/include/
        ${CMAKE_SOURCE_DIR}/email-core/include
        ${CMAKE_SOURCE_DIR}/email-core/email-storage/include
        ${CMAKE_SOURCE_DIR}/email-core/email-network/include
@@ -171,7 +211,7 @@ INCLUDE_DIRECTORIES(
 
 
 INCLUDE(FindPkgConfig)
-pkg_check_modules(core_pkgs REQUIRED glib-2.0 drm-client dlog dbus-1 gthread-2.0 uw-imap-toolkit vconf vconf-internal-keys contacts-service2 secure-storage openssl accounts-svc mm-player mm-session feedback alarm-service notification libcurl libxml-2.0 cert-svc cert-svc-vcore badge capi-appfw-application)
+pkg_check_modules(core_pkgs REQUIRED glib-2.0 drm-client dlog dbus-1 gthread-2.0 uw-imap-toolkit vconf vconf-internal-keys contacts-service2 secure-storage openssl accounts-svc mm-player mm-session feedback alarm-service notification libcurl libxml-2.0 cert-svc cert-svc-vcore badge capi-appfw-application icu-i18n)
 
 set(EXTRA_CFLAGS "")
 FOREACH(flag ${core_pkgs_CFLAGS})
@@ -203,11 +243,48 @@ SET(CMAKE_EXE_LINKER_FLAGS "-Wl,--as-needed")
 
 ADD_LIBRARY(${CORE-LIB} SHARED ${CORE-SRCS})
 
-TARGET_LINK_LIBRARIES(${CORE-LIB} ${core_pkgs_LDFLAGS} ${STORAGE-LIB} ${NETWORK-LIB} ${DEVICE-LIB})
+TARGET_LINK_LIBRARIES(${CORE-LIB} ${core_pkgs_LDFLAGS} ${STORAGE-LIB} ${NETWORK-LIB} ${DEVICE-LIB} ${CORE-SOUND-LIB})
 
 SET_TARGET_PROPERTIES(${CORE-LIB} PROPERTIES SOVERSION ${VERSION_MAJOR})
 SET_TARGET_PROPERTIES(${CORE-LIB} PROPERTIES VERSION ${VERSION})
 
 INSTALL(TARGETS ${CORE-LIB} DESTINATION ${LIB_INSTALL_DIR} COMPONENT RuntimeLibraries)
 
+##########################################################
+# Define smime lib
+##########################################################
+
+SET(SMIME-LIB "email-smime")
+SET(SMIME-SRCS 
+       ${CMAKE_SOURCE_DIR}/email-core/email-core-smime.c
+       ${CMAKE_SOURCE_DIR}/email-core/email-core-cert.c
+)
+
+INCLUDE_DIRECTORIES(
+       ${CMAKE_SOURCE_DIR}/email-common-use/include
+       ${CMAKE_SOURCE_DIR}/email-core/include
+       ${CMAKE_SOURCE_DIR}/email-core/email-storage/include
+)
+
+
+INCLUDE(FindPkgConfig)
+pkg_check_modules(smime_pkgs REQUIRED glib-2.0 dlog cert-svc cert-svc-vcore)
+
+set(EXTRA_CFLAGS "")
+FOREACH(flag ${smime_pkgs_CFLAGS})
+       SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag}")
+ENDFOREACH(flag)
+
+SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${EXTRA_CFLAGS}")
+
+SET(CMAKE_EXE_LINKER_FLAGS "-Wl,--as-needed")
+
+ADD_LIBRARY(${SMIME-LIB} SHARED ${SMIME-SRCS})
+TARGET_LINK_LIBRARIES(${SMIME-LIB} ${smime_pkgs_LDFLAGS} ${BASE-LIB})
+SET_TARGET_PROPERTIES(${SMIME-LIB} PROPERTIES SOVERSION ${VERSION_MAJOR})
+SET_TARGET_PROPERTIES(${SMIME-LIB} PROPERTIES VERSION ${VERSION})
+
+INSTALL(TARGETS ${SMIME-LIB} DESTINATION ${LIB_INSTALL_DIR} COMPONENT RuntimeLibraries)
+
+
 
index f790de2..31149dc 100755 (executable)
@@ -35,6 +35,7 @@
 #include <time.h>
 #include <sys/types.h>
 #include <vconf.h>
+#include <curl/curl.h>
 
 #include "email-convert.h"
 #include "email-types.h"
@@ -137,9 +138,9 @@ FINISH_OFF:
 }
 
 
-INTERNAL_FUNC int emcore_validate_account_with_account_info(email_account_t *account, int *err_code)
+INTERNAL_FUNC int emcore_validate_account_with_account_info(email_account_t *account, email_event_type_t event_type, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("account[%p], err_code[%p], incoming_server_address [%s]", account, err_code, account->incoming_server_address);
+       EM_DEBUG_FUNC_BEGIN_SEC("account[%p], err_code[%p], incoming_server_address [%s]", account, err_code, account->incoming_server_address);
 
        int ret = false;
        int err = EMAIL_ERROR_NONE;
@@ -147,109 +148,99 @@ INTERNAL_FUNC int emcore_validate_account_with_account_info(email_account_t *acc
        SENDSTREAM *stream = NULL;
        MAILSTREAM *tmp_stream = NULL;
 
-       if (!emcore_check_thread_status())  {
+       if (!emcore_check_thread_status()) {
                err = EMAIL_ERROR_CANCELLED;
                goto FINISH_OFF;
        }
 
-       if (!emnetwork_check_network_status(&err))  {
+       if (!emnetwork_check_network_status(&err)) {
                EM_DEBUG_EXCEPTION("emnetwork_check_network_status failed [%d]", err);
                goto FINISH_OFF;
        }
        EM_DEBUG_LOG("Network available");
 
-       if (!emcore_check_thread_status())  {
+       if (!emcore_check_thread_status()) {
                err = EMAIL_ERROR_CANCELLED;
                goto FINISH_OFF;
        }
 
-       if (!emcore_get_empty_session(&session))  {
+       if (!emcore_get_empty_session(&session)) {
                EM_DEBUG_EXCEPTION("emcore_get_empty_session failed...");
                err = EMAIL_ERROR_SESSION_NOT_FOUND;
                goto FINISH_OFF;
        }
 
-#ifdef _SMTP_ACCOUNT_VALIDATION_
-       /* validate connection for smt */
-       EM_DEBUG_LOG("Validate connection for SMTP");
+       /* validate connection for pop3/imap */
+       EM_DEBUG_LOG("Validate connection for POP3/IMAP4");
+       if (EMAIL_ERROR_NONE == err) {
+               if (!emcore_check_thread_status()) {
+                       err = EMAIL_ERROR_CANCELLED;
+                       goto FINISH_OFF;
+               }
+
+               if (!emcore_connect_to_remote_mailbox_with_account_info(account, 0, (void **)&tmp_stream, &err) || !tmp_stream) {
+                       EM_DEBUG_LOG("emcore_connect_to_remote_mailbox failed [%d]", err);
+                       if (EMAIL_ERROR_AUTHENTICATE == err || EMAIL_ERROR_LOGIN_FAILURE == err) {      /*  wrong password or etc */
+                               EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed : Login or Authentication failed - %d", err);
+                       } else if (EMAIL_ERROR_CONNECTION_FAILURE != err) {
+                               /* err = EMAIL_ERROR_VALIDATE_ACCOUNT */
+                       }
+                       goto FINISH_OFF;
+               }
+       }
+
+#ifdef __FEATURE_SMTP_VALIDATION__
+       /* validate connection for SMTP */
+       EM_DEBUG_LOG("Validate connection for SMTP server");
 
        if (!emcore_check_thread_status()) {
                err = EMAIL_ERROR_CANCELLED;
                goto FINISH_OFF;
        }
-       if (!emcore_connect_to_remote_mailbox_with_account_info(account, (char *)ENCODED_PATH_SMTP, (void **)&stream, &err) || !stream)  {
-               EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed 1 - %d", err);
-               if (EMAIL_ERROR_AUTHENTICATE == err || EMAIL_ERROR_LOGIN_FAILURE == err) {      /*  wrong password or etc */
-                       EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed  :  Login or Authentication fail 1- %d", err);
+
+       if (!emcore_connect_to_remote_mailbox_with_account_info(account, EMAIL_CONNECT_FOR_SENDING, (void **)&stream, &err) || !stream) {
+               EM_DEBUG_LOG("emcore_connect_to_remote_mailbox failed [%d]", err);
+               if (EMAIL_ERROR_AUTHENTICATE == err || EMAIL_ERROR_LOGIN_FAILURE == err) {
+                       /* Wrong password or etc */
+                       EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed [%d]", err);
+                       err = EMAIL_ERROR_VALIDATE_ACCOUNT_OF_SMTP;
                        goto FINISH_OFF;
                }
 
-               if (account->outgoing_server_secure_connection == 0x01) /*  0x01 == ss */ {
-                       /*  retry with tl */
-                       EM_DEBUG_LOG("Retry with TLS");
-                       account->outgoing_server_secure_connection = 0x02;      /*  0x02 == tl */
-                       if (!emcore_check_thread_status())  {
+               if (account->outgoing_server_secure_connection == 0x01) /*  0x01 == SSL */ {
+                       if (!emcore_check_thread_status()) {
                                err = EMAIL_ERROR_CANCELLED;
                                goto FINISH_OFF;
                        }
 
-                   if (!emcore_connect_to_remote_mailbox_with_account_info(account, (char *)ENCODED_PATH_SMTP, (void **)&stream, &err) || !stream)  {
-                               EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed 2 - %d", err);
-                               if (EMAIL_ERROR_AUTHENTICATE == err || EMAIL_ERROR_LOGIN_FAILURE == err) {      /*  wrong password or etc */
-                                       EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed  :  Login or Authentication fail 2 - %d", err);
-                               }
-                               else if (EMAIL_ERROR_CONNECTION_FAILURE != err) {
-                                       err = EMAIL_ERROR_VALIDATE_ACCOUNT;
-                               }
-                               account->outgoing_server_secure_connection = 0x01;      /*  restore to the previous value */
-                               goto FINISH_OFF;
-                   }
+                       EM_DEBUG_LOG("Retry with TLS");
+                       account->outgoing_server_secure_connection = 0x02;      /*  0x02 == TLS */
 
-                       if (!emcore_check_thread_status())  {
-                               err = EMAIL_ERROR_CANCELLED;
+                       if (!emcore_connect_to_remote_mailbox_with_account_info(account, EMAIL_CONNECT_FOR_SENDING, (void **)&stream, &err) || !stream) {
+                               EM_DEBUG_LOG("emcore_connect_to_remote_mailbox failed [%d]", err);
+                               err = EMAIL_ERROR_VALIDATE_ACCOUNT_OF_SMTP;
+                               account->outgoing_server_secure_connection = 0x01;      /*  restore to the previous value */
                                goto FINISH_OFF;
                        }
 
-                       /*  save outgoing_server_secure_connection = 0x02 (tls) to the d */
-                       if (!emstorage_update_account(account_id, (emstorage_account_tbl_t  *)account, true, &err)) {
-                               EM_DEBUG_EXCEPTION("emstorage_update_account failed - %d", err);
-                               account->outgoing_server_secure_connection = 0x01;      /*  restore to the previous value */
-                               err = EMAIL_ERROR_VALIDATE_ACCOUNT;
+                       if (!emcore_check_thread_status()) {
+                               err = EMAIL_ERROR_CANCELLED;
                                goto FINISH_OFF;
                        }
                }
                else {
                        if (EMAIL_ERROR_CONNECTION_FAILURE != err)
-                               err = EMAIL_ERROR_VALIDATE_ACCOUNT;
+                               err = EMAIL_ERROR_VALIDATE_ACCOUNT_OF_SMTP;
                        goto FINISH_OFF;
                }
        }
-#endif
-
-       /* validate connection for pop3/ima */
-       EM_DEBUG_LOG("Validate connection for POP3/IMAP4");
-       if (EMAIL_ERROR_NONE == err) {
-               if (!emcore_check_thread_status())  {
-                       err = EMAIL_ERROR_CANCELLED;
-                       goto FINISH_OFF;
-               }
+#endif /* __FEATURE_SMTP_VALIDATION__ */
 
-                if (!emcore_connect_to_remote_mailbox_with_account_info(account, 0, (void **)&tmp_stream, &err) || !tmp_stream)
-                {
-                       EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed - %d", err);
-                       if (EMAIL_ERROR_AUTHENTICATE == err || EMAIL_ERROR_LOGIN_FAILURE == err) {      /*  wrong password or etc */
-                               EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed : Login or Authentication failed - %d", err);
-                       }
-                       else if (EMAIL_ERROR_CONNECTION_FAILURE != err) {
-                               /* err = EMAIL_ERROR_VALIDATE_ACCOUNT */
-                       }
-                       goto FINISH_OFF;
+       if (!emcore_check_thread_status()) {
+               if (event_type == EMAIL_EVENT_VALIDATE_AND_CREATE_ACCOUNT || event_type == EMAIL_EVENT_VALIDATE_ACCOUNT_EX) {
+                       if (!emcore_delete_account(account->account_id, NULL))
+                               EM_DEBUG_EXCEPTION("emdaemon_delete_account failed [%d]", account->account_id);
                }
-       }
-
-       if (!emcore_check_thread_status())  {
-               if (!emcore_delete_account(account->account_id, NULL))
-                       EM_DEBUG_EXCEPTION("emdaemon_delete_account failed [%d]", account->account_id);
                err = EMAIL_ERROR_CANCELLED;
                goto FINISH_OFF;
        }
@@ -261,7 +252,7 @@ FINISH_OFF:
                smtp_close(stream);
 
        if (tmp_stream)
-               emcore_close_mailbox(0 , tmp_stream);
+               tmp_stream = mail_close (tmp_stream);
 
        if (err_code != NULL)
                *err_code = err;
@@ -281,8 +272,7 @@ INTERNAL_FUNC int emcore_validate_account(int account_id, int *err_code)
        email_account_t *ref_account = NULL;
 
 
-       if (account_id <= 0)
-    {
+       if (account_id <= 0) {
                EM_DEBUG_EXCEPTION("account_id[%p]", account_id);
                err = EMAIL_ERROR_INVALID_PARAM;
                goto FINISH_OFF;
@@ -290,7 +280,7 @@ INTERNAL_FUNC int emcore_validate_account(int account_id, int *err_code)
 
        ref_account = emcore_get_account_reference(account_id);
 
-       if (ref_account && emcore_validate_account_with_account_info(ref_account, &err) == false) {
+       if (ref_account && emcore_validate_account_with_account_info(ref_account, EMAIL_EVENT_VALIDATE_ACCOUNT, &err) == false) {
                EM_DEBUG_EXCEPTION("emcore_validate_account_with_account_info failed (%d)", err);
                goto FINISH_OFF;
        }
@@ -392,8 +382,10 @@ INTERNAL_FUNC int emcore_delete_account(int account_id, int *err_code)
        }
        
        if (!emstorage_delete_account(account_id, false, &err))  {
-               EM_DEBUG_EXCEPTION("emstorage_delete_account failed [%d]", err);
-               goto FINISH_OFF;
+               if(err != EMAIL_ERROR_SYSTEM_FAILURE) {
+                       EM_DEBUG_EXCEPTION("emstorage_delete_account failed [%d]", err);
+                       goto FINISH_OFF;
+               }
        }
 
 #ifdef __FEATURE_KEEP_CONNECTION__
@@ -408,8 +400,10 @@ INTERNAL_FUNC int emcore_delete_account(int account_id, int *err_code)
 
        /*  delete all mailboxes */
        if (!emstorage_delete_mailbox(account_id, -1, 0, false, &err))  {
-               EM_DEBUG_EXCEPTION("emstorage_delete_mailbox failed - %d", err);
-               goto FINISH_OFF;
+               if(err != EMAIL_ERROR_MAILBOX_NOT_FOUND) {
+                       EM_DEBUG_EXCEPTION("emstorage_delete_mailbox failed - %d", err);
+                       goto FINISH_OFF;
+               }
        }
 
        /*  delete local imap sync mailbox from imap mailbox table */
@@ -419,7 +413,7 @@ INTERNAL_FUNC int emcore_delete_account(int account_id, int *err_code)
        }
 
        emcore_display_unread_in_badge();
-       emcore_delete_notification_by_account(account_id);
+       emcore_delete_notification_by_account(account_id, true);
        emcore_init_account_reference();
 
        ret = true;
@@ -430,15 +424,15 @@ FINISH_OFF:
                        err = EMAIL_ERROR_DB_FAILURE;
                        ret = false;
                }
-               if (!emcore_notify_storage_event(NOTI_ACCOUNT_DELETE, account_id, 0, NULL, 0))
-                       EM_DEBUG_EXCEPTION(" emcore_notify_storage_event[ NOTI_ACCOUNT_DELETE] : Notification Failed >>> ");
+               if (!emcore_notify_storage_event (NOTI_ACCOUNT_DELETE, account_id, 0, NULL, 0))
+                       EM_DEBUG_EXCEPTION (" emcore_notify_storage_event[ NOTI_ACCOUNT_DELETE] : Notification Failed >>> ");
 
        }
        else {  /*  ROLLBACK TRANSACTION; */
                if (!before_tr_begin && emstorage_rollback_transaction(NULL, NULL, NULL) == false)
                        err = EMAIL_ERROR_DB_FAILURE;
-               if (!emcore_notify_storage_event(NOTI_ACCOUNT_DELETE_FAIL, account_id, err, NULL, 0))
-                       EM_DEBUG_EXCEPTION(" emcore_notify_storage_event[ NOTI_ACCOUNT_DELETE] : Notification Failed >>> ");
+               if (!emcore_notify_storage_event (NOTI_ACCOUNT_DELETE_FAIL, account_id, err, NULL, 0))
+                       EM_DEBUG_EXCEPTION (" emcore_notify_storage_event[ NOTI_ACCOUNT_DELETE] : Notification Failed >>> ");
        }
 
        if (err_code)
@@ -482,11 +476,6 @@ INTERNAL_FUNC int emcore_create_account(email_account_t *account, int *err_code)
        account->account_id = 0;
 
        /* Temporarily code - begin */
-       if (account->auto_download_size == 0) {
-               account->auto_download_size = PARTIAL_BODY_SIZE_IN_BYTES;
-               EM_DEBUG_LOG("account->auto_download_size [%d]", account->auto_download_size);
-       }
-
        if (account->default_mail_slot_size == 0) {
                account->default_mail_slot_size = 50;
                EM_DEBUG_LOG("account->default_mail_slot_size [%d]", account->default_mail_slot_size);
@@ -494,11 +483,10 @@ INTERNAL_FUNC int emcore_create_account(email_account_t *account, int *err_code)
        /* Temporarily code - end */
 
        /* check for email address validation */
-       EM_DEBUG_LOG("account->user_email_address[%s]", account->user_email_address);
+       EM_DEBUG_LOG_SEC("account->user_email_address[%s]", account->user_email_address);
        if (account->user_email_address) {
-               if (!em_verify_email_address(account->user_email_address, true, &err)) {
-                       err = EMAIL_ERROR_INVALID_ADDRESS;
-                       EM_DEBUG_EXCEPTION("Invalid Email Address");
+               if ((err = em_verify_email_address (account->user_email_address, true)) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("em_verify_email_address error [%d]", err);
                        goto FINISH_OFF;
                }
        }
@@ -600,24 +588,27 @@ INTERNAL_FUNC int emcore_create_account(email_account_t *account, int *err_code)
                /* 1. create default local mailbox
                *    (Inbox, Draft, Outbox, Sentbox) */
                for (i = 0; i < MAILBOX_COUNT; i++) {
-               EM_DEBUG_LOG("g_default_mbox_name [%d/%d] is [%s]", i, MAILBOX_COUNT, g_default_mbox_name[i]);
-                       local_mailbox.account_id = temp_account_tbl->account_id;
-                       local_mailbox.mailbox_name  = g_default_mbox_name[i];
-                       local_mailbox.mailbox_type      = g_default_mbox_type[i];
-                       if (local_mailbox.mailbox_type == EMAIL_MAILBOX_TYPE_INBOX) {
+                       EM_DEBUG_LOG_SEC("g_default_mbox_name [%d/%d] is [%s]", i, MAILBOX_COUNT, g_default_mbox_name[i]);
+                       local_mailbox.account_id      = temp_account_tbl->account_id;
+                       local_mailbox.mailbox_name    = EM_SAFE_STRDUP(g_default_mbox_name[i]);
+                       local_mailbox.alias           = EM_SAFE_STRDUP(g_default_mbox_alias[i]);
+                       local_mailbox.mailbox_type        = g_default_mbox_type[i];
+                       local_mailbox.mail_slot_size  = temp_account_tbl->default_mail_slot_size;
+                       local_mailbox.eas_data        = NULL;
+                       local_mailbox.eas_data_length = 0;
+
+                       if (local_mailbox.mailbox_type == EMAIL_MAILBOX_TYPE_INBOX)
                                local_mailbox.local = EMAIL_MAILBOX_FROM_SERVER;
-                       }
-                       else {
+                       else
                                local_mailbox.local = EMAIL_MAILBOX_FROM_LOCAL;
-                       }
-                       local_mailbox.alias = g_default_mbox_alias[i];
-                       local_mailbox.mail_slot_size = temp_account_tbl->default_mail_slot_size;
 
                        if (!emcore_create_mailbox(&local_mailbox, 0, &err))  {
-                               EM_DEBUG_EXCEPTION("emcore_create failed - %d", err);
+                               EM_DEBUG_EXCEPTION("emcore_create failed [%d]", err);
+                               emcore_free_mailbox(&local_mailbox);
                                goto FINISH_OFF;
                        }
                        
+                       emcore_free_mailbox(&local_mailbox);
                }
        }
 
@@ -703,11 +694,6 @@ INTERNAL_FUNC int emcore_init_account_reference()
 FINISH_OFF: 
        if (account_tbl_array)
                emstorage_free_account(&account_tbl_array, count, NULL);
-       
-       if (err != EMAIL_ERROR_NONE && account_list && i > 0) {
-               g_account_list = account_list;
-               emcore_free_account_reference();
-       }
 
        EM_DEBUG_FUNC_END("err [%d]", err);
        return err;
@@ -798,11 +784,34 @@ INTERNAL_FUNC void emcore_free_account(email_account_t *account)
        EM_DEBUG_FUNC_END();
 }
 
+INTERNAL_FUNC int emcore_duplicate_account_members(const email_account_t *input_account, email_account_t *output_account_dup)
+{
+       memcpy(output_account_dup, input_account , sizeof(email_account_t));
+
+       output_account_dup->account_name                             = EM_SAFE_STRDUP(input_account->account_name);
+       output_account_dup->incoming_server_address                  = EM_SAFE_STRDUP(input_account->incoming_server_address);
+       output_account_dup->user_email_address                       = EM_SAFE_STRDUP(input_account->user_email_address);
+       output_account_dup->incoming_server_user_name                = EM_SAFE_STRDUP(input_account->incoming_server_user_name);
+       output_account_dup->incoming_server_password                 = EM_SAFE_STRDUP(input_account->incoming_server_password);
+       output_account_dup->outgoing_server_address                  = EM_SAFE_STRDUP(input_account->outgoing_server_address);
+       output_account_dup->outgoing_server_user_name                = EM_SAFE_STRDUP(input_account->outgoing_server_user_name);
+       output_account_dup->outgoing_server_password                 = EM_SAFE_STRDUP(input_account->outgoing_server_password);
+       output_account_dup->user_display_name                        = EM_SAFE_STRDUP(input_account->user_display_name);
+       output_account_dup->reply_to_address                         = EM_SAFE_STRDUP(input_account->reply_to_address);
+       output_account_dup->return_address                           = EM_SAFE_STRDUP(input_account->return_address);
+       output_account_dup->logo_icon_path                           = EM_SAFE_STRDUP(input_account->logo_icon_path);
+       output_account_dup->user_data                                = em_memdup(input_account->user_data, input_account->user_data_length);
+       output_account_dup->options.display_name_from                = EM_SAFE_STRDUP(input_account->options.display_name_from);
+       output_account_dup->options.signature                        = EM_SAFE_STRDUP(input_account->options.signature);
+       output_account_dup->certificate_path                         = EM_SAFE_STRDUP(input_account->certificate_path);
+
+       return EMAIL_ERROR_NONE;
+}
+
 
 INTERNAL_FUNC void emcore_duplicate_account(const email_account_t *account, email_account_t **account_dup, int *err_code)
 {
        EM_DEBUG_FUNC_BEGIN("account[%p]", account);
-       email_account_t *temp_account = NULL;
 
        if(!account || !account_dup) { /*prevent 40514*/
                EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
@@ -817,25 +826,7 @@ INTERNAL_FUNC void emcore_duplicate_account(const email_account_t *account, emai
                return;
        }
 
-       memcpy(*account_dup, account , sizeof(email_account_t));
-       temp_account = *account_dup;
-
-       temp_account->account_name                             = EM_SAFE_STRDUP(account->account_name);
-       temp_account->incoming_server_address                  = EM_SAFE_STRDUP(account->incoming_server_address);
-       temp_account->user_email_address                       = EM_SAFE_STRDUP(account->user_email_address);
-       temp_account->incoming_server_user_name                = EM_SAFE_STRDUP(account->incoming_server_user_name);
-       temp_account->incoming_server_password                 = EM_SAFE_STRDUP(account->incoming_server_password);
-       temp_account->outgoing_server_address                  = EM_SAFE_STRDUP(account->outgoing_server_address);
-       temp_account->outgoing_server_user_name                = EM_SAFE_STRDUP(account->outgoing_server_user_name);
-       temp_account->outgoing_server_password                 = EM_SAFE_STRDUP(account->outgoing_server_password);
-       temp_account->user_display_name                        = EM_SAFE_STRDUP(account->user_display_name);
-       temp_account->reply_to_address                         = EM_SAFE_STRDUP(account->reply_to_address);
-       temp_account->return_address                           = EM_SAFE_STRDUP(account->return_address);
-       temp_account->logo_icon_path                           = EM_SAFE_STRDUP(account->logo_icon_path);
-       temp_account->user_data                                = em_memdup(account->user_data, account->user_data_length);
-       temp_account->options.display_name_from                = EM_SAFE_STRDUP(account->options.display_name_from);
-       temp_account->options.signature                        = EM_SAFE_STRDUP(account->options.signature);
-       temp_account->certificate_path                         = EM_SAFE_STRDUP(account->certificate_path);
+       emcore_duplicate_account_members(account, *account_dup);
 
        if (err_code != NULL)
                *err_code = EMAIL_ERROR_NONE;
@@ -882,8 +873,8 @@ INTERNAL_FUNC int emcore_get_account_reference_list(email_account_t **account_li
        p = g_account_list;
        for (i = 0; i < countOfAccounts; i++)  {
                accountRef = (*account_list) + i;
-               memcpy(accountRef, p->account , sizeof(email_account_t));
-               EM_DEBUG_LOG("Result account id[%d], name[%s]", accountRef->account_id, accountRef->account_name);
+               emcore_duplicate_account_members(p->account, accountRef);
+               EM_DEBUG_LOG_SEC("Result account id[%d], name[%s]", accountRef->account_id, accountRef->account_name);
                p = p->next;
        }
 
@@ -993,7 +984,7 @@ FINISH_OFF:
 
 INTERNAL_FUNC int emcore_backup_accounts(const char *file_path, int *error_code)
 {
-       EM_DEBUG_FUNC_BEGIN("file_path [%s], error_code [%p]", file_path, error_code);
+       EM_DEBUG_FUNC_BEGIN_SEC("file_path [%s], error_code [%p]", file_path, error_code);
        int local_error_code = EMAIL_ERROR_NONE, local_error_code_2 = EMAIL_ERROR_NONE, ret_code = false;
        int select_num, i, target_buff_length = 0;
        char *target_buffer = NULL;
@@ -1060,7 +1051,7 @@ FINISH_OFF:
 
 INTERNAL_FUNC int emcore_restore_accounts(const char *file_path, int *error_code)
 {
-       EM_DEBUG_FUNC_BEGIN("file_path [%s], error_code [%p]", file_path, error_code);
+       EM_DEBUG_FUNC_BEGIN_SEC("file_path [%s], error_code [%p]", file_path, error_code);
        int local_error_code = EMAIL_ERROR_NONE, ret_code = false, buffer_length = 0, read_length = 0;
        int account_count = 0, i = 0, account_stream_length = 0;
        char *temp_buffer = NULL, *account_stream = NULL, *buffer_ptr = NULL;
@@ -1086,7 +1077,10 @@ INTERNAL_FUNC int emcore_restore_accounts(const char *file_path, int *error_code
                        }
                }
 
-               EM_SAFE_FREE(account_list);
+               if(account_list) {
+                       emcore_free_account_list(&account_list, account_count, NULL);
+                       account_list = NULL;
+               }
        }
 
        if (ssm_getinfo(file_path, &sfi, SSM_FLAG_SECRET_OPERATION, NULL) < 0) {
@@ -1150,6 +1144,10 @@ INTERNAL_FUNC int emcore_restore_accounts(const char *file_path, int *error_code
        }
        ret_code = true;        
 FINISH_OFF: 
+       if(account_list) {
+               emcore_free_account_list(&account_list, account_count, NULL);
+               account_list = NULL;
+       }
        emcore_free_account(&temp_account);
        EM_SAFE_FREE(account_stream);
        EM_SAFE_FREE(temp_buffer);
@@ -1164,7 +1162,7 @@ FINISH_OFF:
 
 INTERNAL_FUNC int emcore_query_server_info(const char* domain_name, email_server_info_t **result_server_info)
 {
-       EM_DEBUG_FUNC_BEGIN("domain_name [%s], result_server_info [%p]", domain_name, result_server_info);
+       EM_DEBUG_FUNC_BEGIN_SEC("domain_name [%s], result_server_info [%p]", domain_name, result_server_info);
        int ret_code = EMAIL_ERROR_NONE;
 
        EM_DEBUG_FUNC_END("ret_code [%d]", ret_code);
@@ -1219,7 +1217,10 @@ static int _recover_from_invalid_default_account_id(int *output_account_id)
        }
 
        if(!emstorage_get_account_list(&account_count, &result_account_list, false, false, &ret_code) || !result_account_list) {
-               EM_DEBUG_EXCEPTION("emstorage_get_account_list() failed [%d]", ret_code);
+               if (ret_code == EMAIL_ERROR_ACCOUNT_NOT_FOUND)
+                       EM_DEBUG_LOG ("no account found");                      
+               else
+                       EM_DEBUG_EXCEPTION ("emstorage_get_account_list() failed [%d]", ret_code);
                *output_account_id = 0;
                goto FINISH_OFF;
        }
@@ -1228,7 +1229,7 @@ static int _recover_from_invalid_default_account_id(int *output_account_id)
                *output_account_id = result_account_list[0].account_id;
        }
 
-       EM_DEBUG_LOG("output_account_id [%d]", *output_account_id);
+       EM_DEBUG_LOG_DEV ("output_account_id [%d]", *output_account_id);
 
 FINISH_OFF:
 
@@ -1261,17 +1262,23 @@ INTERNAL_FUNC int emcore_load_default_account_id(int *output_account_id)
 
        if (*output_account_id != 0) {
                if (!emstorage_get_account_by_id(*output_account_id, EMAIL_ACC_GET_OPT_DEFAULT, &result_account, false, &ret_code)) {
-                       EM_DEBUG_EXCEPTION("emstorage_get_account_by_id() failed [%d]", ret_code);
-                       if(ret_code == EMAIL_ERROR_ACCOUNT_NOT_FOUND)
+                       if (ret_code == EMAIL_ERROR_ACCOUNT_NOT_FOUND) {
+                               EM_DEBUG_LOG ("no account found account_id[%d]", *output_account_id);
                                *output_account_id = 0;
-                       else
+                       }
+                       else {
+                               EM_DEBUG_EXCEPTION ("emstorage_get_account_by_id() failed account_id[%d] err[%d]", *output_account_id, ret_code);
                                goto FINISH_OFF;
+                       }
                }
        }
 
        if (*output_account_id == 0) {
-               if ( (ret_code = _recover_from_invalid_default_account_id(output_account_id)) != EMAIL_ERROR_NONE) {
-                       EM_DEBUG_EXCEPTION("_recover_from_invalid_default_account() failed [%d]", ret_code);
+               if ((ret_code = _recover_from_invalid_default_account_id (output_account_id)) != EMAIL_ERROR_NONE) {
+                       if (ret_code == EMAIL_ERROR_ACCOUNT_NOT_FOUND)
+                               EM_DEBUG_LOG ("no account found");
+                       else 
+                               EM_DEBUG_EXCEPTION("_recover_from_invalid_default_account() failed [%d]", ret_code);
                        *output_account_id = 0;
                }
        }
@@ -1333,19 +1340,17 @@ INTERNAL_FUNC int emcore_update_sync_status_of_account(int input_account_id, ema
                }
 
                err_from_account_svc = account_connect();
-               EM_DEBUG_LOG("account_connect returns [%d]", err_from_account_svc);
-
-               EM_DEBUG_LOG("account_tbl_data->account_svc_id [%d]", account_tbl_data->account_svc_id);
+               EM_DEBUG_LOG_DEV("account_connect returns [%d]", err_from_account_svc);
 
                if (input_set_operator == SET_TYPE_SET)
                        err_from_account_svc = account_update_sync_status_by_id(account_tbl_data->account_svc_id, ACCOUNT_SYNC_STATUS_RUNNING);
                else if(input_set_operator == SET_TYPE_MINUS)
                        err_from_account_svc = account_update_sync_status_by_id(account_tbl_data->account_svc_id, ACCOUNT_SYNC_STATUS_IDLE);
 
-               EM_DEBUG_LOG("account_update_sync_status_by_id returns [%d]", err_from_account_svc);
+               EM_DEBUG_LOG("account_update_sync_status_by_id returns [%d] by id[%d]", err_from_account_svc, account_tbl_data->account_svc_id); 
 
                err_from_account_svc = account_disconnect();
-               EM_DEBUG_LOG("account_disconnect returns [%d]", err_from_account_svc);
+               EM_DEBUG_LOG_DEV("account_disconnect returns [%d]", err_from_account_svc); 
        }
 #endif /* __FEATURE_USING_ACCOUNT_SVC_FOR_SYNC_STATUS__ */
 
@@ -1361,3 +1366,235 @@ FINISH_OFF:
        EM_DEBUG_FUNC_END("err [%d]", err);
        return err;
 }
+
+#define GOOGLE_PIM_SYNC_GET_TOKEN_URL "https://accounts.google.com/o/oauth2/token"
+#define GOOGLE_PIM_SYNC_CLIENT_ID     "233916860221.apps.googleusercontent.com"
+#define GOOGLE_PIM_SYNC_CLIENT_SECRET "dI8wRLGMJ16Ioxfl8KaujmuU"
+#define CALCURL_TIMEOUT               30
+
+int emcore_curl_progress_callback(void *p, double dtot, double dnow, double utot, double unow)
+{
+       EM_DEBUG_LOG("%0.0lf %0.0lf %0.0lf %0.0lf", dtot, dnow, utot, unow);
+       return 0;
+}
+
+size_t emcore_curl_write_callback(char* data, size_t size, size_t nmemb, void* target)
+{
+       EM_DEBUG_FUNC_BEGIN("data[%p] size[%d] nmemb[%d] target[%p]", data, size, nmemb, target);
+       int last_pos = 0;
+       char **result_string = (char**)target;
+       size_t received_length = size * nmemb;
+
+       if (*result_string == NULL) {
+               EM_DEBUG_LOG("received_length[%d]", received_length);
+               *result_string = em_malloc(received_length + 1);
+       }
+       else {
+               int new_buffer_length = 0;
+               last_pos = EM_SAFE_STRLEN(*result_string);
+               new_buffer_length = last_pos + received_length + 1;
+               EM_DEBUG_LOG("new_buffer_length[%d]", new_buffer_length);
+               *result_string = realloc(*result_string, new_buffer_length);
+       }
+
+       if (*result_string == NULL) {
+               EM_DEBUG_EXCEPTION("memory allocation failed");
+               received_length = 0;
+               goto FINISH_OFF;
+       }
+
+       memcpy(*result_string + last_pos, data, received_length);
+       /*EM_DEBUG_LOG("result_string[%s]", *result_string);*/
+
+FINISH_OFF:
+       EM_DEBUG_FUNC_END("received_length [%d]", received_length);
+       return received_length;
+}
+
+static int emcore_get_xoauth2_access_token(char *input_refresh_token, char **output_access_token)
+{
+       EM_DEBUG_FUNC_BEGIN("input_refresh_token [%p] output_access_token [%p]", input_refresh_token, output_access_token);
+       int err = EMAIL_ERROR_NONE;
+
+       CURL *curl = NULL;
+       CURLcode curl_ressult_code;
+       char *result_string = NULL;
+       char *pos = NULL;
+       char *savepos = NULL;
+       char *access_token = NULL;
+       long response_code;
+       double speed_upload, total_time, download_size;
+
+       if(input_refresh_token == NULL || output_access_token == NULL) {
+               EM_DEBUG_EXCEPTION("curl_easy_init() failed");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       curl = curl_easy_init();
+       if (NULL == curl) {
+               EM_DEBUG_EXCEPTION("curl_easy_init() failed");
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       char buf[1024] = {0};
+       snprintf(buf, sizeof(buf),
+                               "client_id=%s&"
+                               "client_secret=%s&"
+                               "refresh_token=%s&"
+                               "grant_type=refresh_token",
+                               GOOGLE_PIM_SYNC_CLIENT_ID,
+                               GOOGLE_PIM_SYNC_CLIENT_SECRET,
+                               input_refresh_token);
+       curl_easy_setopt(curl, CURLOPT_URL, GOOGLE_PIM_SYNC_GET_TOKEN_URL);
+       curl_easy_setopt(curl, CURLOPT_POST, 1);
+       curl_easy_setopt(curl, CURLOPT_POSTFIELDS, buf);
+       curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
+       curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, CALCURL_TIMEOUT);
+       curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
+       curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
+       curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, emcore_curl_progress_callback);
+       curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, emcore_curl_write_callback);
+       curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)&result_string);
+       curl_easy_setopt(curl, CURLOPT_HEADER, true);
+
+       curl_ressult_code = curl_easy_perform(curl);
+
+       EM_DEBUG_LOG("CURLcode: %d (%s)", curl_ressult_code, curl_easy_strerror(curl_ressult_code));
+
+       if (0 == curl_ressult_code) {
+               curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
+               curl_easy_getinfo(curl, CURLINFO_SPEED_UPLOAD,  &speed_upload);
+               curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME,    &total_time);
+               curl_easy_getinfo(curl, CURLINFO_SIZE_DOWNLOAD, &download_size);
+
+               EM_DEBUG_LOG("Speed: %.3f bytes/sec during %.3f seconds", speed_upload, total_time);
+               EM_DEBUG_LOG("response code = %ld , length = %.3f", response_code, download_size);
+       }
+
+       if (result_string == NULL) {
+               EM_DEBUG_EXCEPTION("Getting result string failed");
+               err = EMAIL_ERROR_XOAUTH_BAD_REQUEST;
+               goto FINISH_OFF;
+       }
+
+       if(strstr(result_string, "error")) {
+               if(strstr(result_string, "\"invalid_grant\""))
+                       err = EMAIL_ERROR_XOAUTH_INVALID_GRANT;
+               else
+                       err = EMAIL_ERROR_XOAUTH_BAD_REQUEST;
+               goto FINISH_OFF;
+       }
+
+       pos = strstr(result_string, "\"access_token\" : \"");
+
+       if(!pos) {
+               err = EMAIL_ERROR_XOAUTH_BAD_REQUEST;
+               goto FINISH_OFF;
+       }
+
+       pos = pos + strlen("\"access_token\" : \"");
+
+       access_token = strtok_r(pos, "\"", &savepos);
+
+       if(access_token) {
+               *output_access_token = EM_SAFE_STRDUP(access_token);
+
+               if(*output_access_token == NULL) {
+                       EM_DEBUG_EXCEPTION("strdup failed");
+                       err = EMAIL_ERROR_SYSTEM_FAILURE;
+                       goto FINISH_OFF;
+               }
+       }
+
+FINISH_OFF:
+
+       EM_SAFE_FREE(result_string);
+
+       if(curl)
+               curl_easy_cleanup(curl);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC int emcore_refresh_xoauth2_access_token(int input_account_id)
+{
+       EM_DEBUG_FUNC_BEGIN("input_account_id [%d]", input_account_id);
+       int err = EMAIL_ERROR_NONE;
+       int new_password_string_length = 0;
+       char *access_token = NULL;
+       char *refresh_token = NULL;
+       char *new_access_token = NULL;
+       char *new_password_string = NULL;
+       char *saveptr = NULL;
+       email_account_t *ref_account = NULL;
+
+
+       ref_account = emcore_get_account_reference(input_account_id);
+
+       if(ref_account == NULL) {
+               EM_DEBUG_EXCEPTION("emcore_get_account_reference() failed");
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+
+       access_token = EM_SAFE_STRDUP(strtok_r(ref_account->incoming_server_password, "\001", &saveptr));
+
+       if(access_token == NULL) {
+               EM_DEBUG_EXCEPTION("invalid token string.");
+               err = EMAIL_ERROR_XOAUTH_BAD_REQUEST;
+               goto FINISH_OFF;
+       }
+
+       EM_DEBUG_LOG_SEC("access_token [%s]", access_token);
+
+       refresh_token = EM_SAFE_STRDUP(strtok_r(NULL, "\001", &saveptr));
+
+       if(refresh_token == NULL) {
+               EM_DEBUG_EXCEPTION("invalid token string.");
+               err = EMAIL_ERROR_XOAUTH_BAD_REQUEST;
+               goto FINISH_OFF;
+       }
+
+       EM_DEBUG_LOG_SEC("refresh_token [%s]", refresh_token);
+
+       if((err = emcore_get_xoauth2_access_token(refresh_token, &new_access_token)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emcore_get_xoauth2_access_token() failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       new_password_string_length = EM_SAFE_STRLEN(new_access_token) + EM_SAFE_STRLEN(refresh_token) + 2;
+
+       new_password_string = em_malloc(new_password_string_length);
+       if(new_password_string == NULL) {
+               EM_DEBUG_EXCEPTION("em_malloc() failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       SNPRINTF(new_password_string, new_password_string_length, "%s\001%s", new_access_token, refresh_token);
+
+       if((err = emstorage_update_account_password(input_account_id, new_password_string, new_password_string)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emstorage_update_account_password() failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       emcore_init_account_reference();
+
+FINISH_OFF:
+
+       EM_SAFE_FREE(access_token);
+       EM_SAFE_FREE(refresh_token);
+       EM_SAFE_FREE(new_access_token);
+       EM_SAFE_FREE(new_password_string);
+
+       if(ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+       
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
index 2600288..4181890 100755 (executable)
-/*\r
-*  email-service\r
-*\r
-* Copyright (c) 2013 Samsung Electronics Co., Ltd. All rights reserved.\r
-*\r
-* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>\r
-*\r
-* Licensed under the Apache License, Version 2.0 (the "License");\r
-* you may not use this file except in compliance with the License.\r
-* You may obtain a copy of the License at\r
-*\r
-* http://www.apache.org/licenses/LICENSE-2.0\r
-*\r
-* Unless required by applicable law or agreed to in writing, software\r
-* distributed under the License is distributed on an "AS IS" BASIS,\r
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-* See the License for the specific language governing permissions and\r
-* limitations under the License.\r
-*\r
-*/\r
-\r
-\r
-/******************************************************************************\r
- * File :  email-core-alarm.c\r
- * Desc :  Alarm Management\r
- *\r
- * Auth :  Kyuho Jo\r
- *\r
- * History :\r
- *    2013.01.28  :  created\r
- *****************************************************************************/\r
-#include <stdio.h>\r
-#include <stdlib.h>\r
-#include <string.h>\r
-#include <time.h>\r
-#include <sys/types.h>\r
-#include <vconf.h>\r
-#include <glib.h>\r
-#include <alarm.h>\r
-\r
-#include "email-convert.h"\r
-#include "email-types.h"\r
-#include "email-daemon.h"\r
-#include "email-debug-log.h"\r
-#include "email-storage.h"\r
-#include "email-network.h"\r
-#include "email-utilities.h"\r
-#include "email-core-utils.h"\r
-#include "email-core-global.h"\r
-#include "email-core-alarm.h"\r
-
-#ifdef __FEATURE_USE_APPSYNC__\r
+/*
+*  email-service
+*
+* Copyright (c) 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+*/
+
+
+/******************************************************************************
+ * File :  email-core-alarm.c
+ * Desc :  Alarm Management
+ *
+ * Auth :  Kyuho Jo
+ *
+ * History :
+ *    2013.01.28  :  created
+ *****************************************************************************/
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include <sys/types.h>
+#include <vconf.h>
+#include <glib.h>
+#include <alarm.h>
+
+#include "email-convert.h"
+#include "email-types.h"
+#include "email-daemon.h"
+#include "email-debug-log.h"
+#include "email-storage.h"
+#include "email-network.h"
+#include "email-device.h"
+#include "email-utilities.h"
+#include "email-core-utils.h"
+#include "email-core-global.h"
+#include "email-core-alarm.h"
+
+#ifdef __FEATURE_USE_APPSYNC__
 #include <appsync.h>
-#endif\r
-\r
-\r
-#define EMAIL_ALARM_DESTINATION "email-service-0"\r
-\r
-GList *alarm_data_list = NULL;\r
-\r
-INTERNAL_FUNC int emcore_get_alarm_data_by_alarm_id(alarm_id_t input_alarm_id, email_alarm_data_t **output_alarm_data)\r
-{\r
-       EM_DEBUG_FUNC_BEGIN("input_alarm_id [%d] output_alarm_data [%p]", input_alarm_id, output_alarm_data);\r
-       int err = EMAIL_ERROR_NONE;\r
-       GList *index = g_list_first(alarm_data_list);\r
-       email_alarm_data_t *alarm_data = NULL;\r
-\r
-       if (output_alarm_data == NULL) {\r
-               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");\r
-               err = EMAIL_ERROR_INVALID_PARAM;\r
-               goto FINISH_OFF;\r
-       }\r
-\r
-       while(index) {\r
-               alarm_data = index->data;\r
-               if(alarm_data->alarm_id == input_alarm_id) {\r
-                       break;\r
-               }\r
-               index = g_list_next(index);\r
-       }\r
-\r
-       if(alarm_data)\r
-               *output_alarm_data = alarm_data;\r
-       else\r
-               err = EMAIL_ERROR_ALARM_DATA_NOT_FOUND;\r
-\r
-FINISH_OFF:\r
-\r
-       EM_DEBUG_FUNC_END("err [%d]", err);\r
-       return err;\r
-}\r
-\r
-INTERNAL_FUNC int emcore_get_alarm_data_by_reference_id(int input_class_id, int input_reference_id, email_alarm_data_t **output_alarm_data)\r
-{\r
-       EM_DEBUG_FUNC_BEGIN("input_class_id [%d] input_reference_id [%d] output_alarm_data [%p]", input_class_id, input_reference_id, output_alarm_data);\r
-       int err = EMAIL_ERROR_NONE;\r
-       GList *index = g_list_first(alarm_data_list);\r
-       email_alarm_data_t *alarm_data = NULL;\r
-\r
-       if (output_alarm_data == NULL) {\r
-               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");\r
-               err = EMAIL_ERROR_INVALID_PARAM;\r
-               goto FINISH_OFF;\r
-       }\r
-\r
-       while(index) {\r
-               alarm_data = index->data;\r
-               if(alarm_data->class_id == input_class_id && alarm_data->reference_id == input_reference_id) {\r
-                       EM_DEBUG_LOG("found");\r
-                       break;\r
-               }\r
-               index = g_list_next(index);\r
-       }\r
-\r
-       if(index)\r
-               *output_alarm_data = alarm_data;\r
-       else\r
-               err = EMAIL_ERROR_ALARM_DATA_NOT_FOUND;\r
-\r
-FINISH_OFF:\r
-\r
-       EM_DEBUG_FUNC_END("err [%d]", err);\r
-       return err;\r
-}\r
-\r
-\r
-static int emcore_add_alarm_data_to_alarm_data_list(alarm_id_t input_alarm_id, int input_class_id, int input_reference_id, time_t input_trigger_at_time, int (*input_alarm_callback)(int, void *), void *user_data)\r
-{\r
-       EM_DEBUG_FUNC_BEGIN("input_alarm_id [%d] input_class_id[%d] input_reference_id[%d] input_trigger_at_time[%d] input_alarm_callback [%p] user_data[%p]", input_alarm_id, input_class_id, input_reference_id, input_trigger_at_time, input_alarm_callback, user_data);\r
-       int err = EMAIL_ERROR_NONE;\r
-       email_alarm_data_t *alarm_data = NULL;\r
-\r
-       if (input_alarm_id == 0 || input_trigger_at_time == 0 || input_alarm_callback == NULL) {\r
-               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");\r
-               err = EMAIL_ERROR_INVALID_PARAM;\r
-               goto FINISH_OFF;\r
-       }\r
-\r
-       alarm_data = em_malloc(sizeof(email_alarm_data_t));\r
-\r
-       if(alarm_data == NULL) {\r
-               EM_DEBUG_EXCEPTION("EMAIL_ERROR_OUT_OF_MEMORY");\r
-               err = EMAIL_ERROR_OUT_OF_MEMORY;\r
-               goto FINISH_OFF;\r
-       }\r
-       alarm_data->alarm_id        = input_alarm_id;\r
-       alarm_data->class_id        = input_class_id;\r
-       alarm_data->reference_id    = input_reference_id;\r
-       alarm_data->trigger_at_time = input_trigger_at_time;\r
-       alarm_data->alarm_callback  = input_alarm_callback;\r
-       alarm_data->user_data       = user_data;\r
-\r
-       alarm_data_list = g_list_append(alarm_data_list, (gpointer)alarm_data);\r
-\r
-FINISH_OFF:\r
-\r
-       EM_DEBUG_FUNC_END("err [%d]", EMAIL_ERROR_NONE);\r
-       return EMAIL_ERROR_NONE;\r
-}\r
-\r
-static int emcore_remove_alarm(email_alarm_data_t *input_alarm_data)\r
-{\r
-       EM_DEBUG_FUNC_BEGIN("input_alarm_data [%p]", input_alarm_data);\r
-\r
-       int ret = ALARMMGR_RESULT_SUCCESS;\r
-       int err = EMAIL_ERROR_NONE;\r
-\r
-       EM_DEBUG_LOG("alarm_id [%d]", input_alarm_data->alarm_id);\r
-       if ((ret = alarmmgr_remove_alarm(input_alarm_data->alarm_id)) != ALARMMGR_RESULT_SUCCESS) {\r
-               EM_DEBUG_EXCEPTION("delete of alarm id failed [%d]", ret);\r
-               err = EMAIL_ERROR_SYSTEM_FAILURE;\r
-       }\r
-\r
-       EM_DEBUG_FUNC_END("err [%d]", err);\r
-       return EMAIL_ERROR_NONE;\r
-}\r
-\r
-INTERNAL_FUNC int emcore_delete_alram_data_from_alarm_data_list(email_alarm_data_t *input_alarm_data)\r
-{\r
-       EM_DEBUG_FUNC_BEGIN("input_alarm_data [%p]", input_alarm_data);\r
-       int err = EMAIL_ERROR_NONE;\r
-\r
-       if ((err = emcore_remove_alarm(input_alarm_data)) != EMAIL_ERROR_NONE) {\r
-               EM_DEBUG_EXCEPTION("emcore_remove_alarm failed[%d]", err);\r
-       }\r
-\r
-       alarm_data_list = g_list_remove(alarm_data_list, input_alarm_data);\r
-\r
-       EM_DEBUG_FUNC_END("err [%d]", EMAIL_ERROR_NONE);\r
-       return EMAIL_ERROR_NONE;\r
-}\r
-\r
-INTERNAL_FUNC int emcore_delete_alram_data_by_reference_id(int input_class_id, int input_reference_id)\r
-{\r
-       EM_DEBUG_FUNC_BEGIN("input_class_id[%d] input_reference_id[%d]", input_class_id, input_reference_id);\r
-       int err = EMAIL_ERROR_NONE;\r
-       email_alarm_data_t *alarm_data = NULL;\r
-\r
-       if ((err = emcore_get_alarm_data_by_reference_id(input_class_id, input_reference_id, &alarm_data)) != EMAIL_ERROR_NONE) {\r
-               EM_DEBUG_EXCEPTION("emcore_remove_alarm failed[%d]", err);\r
-               goto FINISH_OFF;\r
-       }\r
-\r
-       if ((err = emcore_delete_alram_data_from_alarm_data_list(alarm_data)) != EMAIL_ERROR_NONE) {\r
-               EM_DEBUG_EXCEPTION("emcore_delete_alram_data_from_alarm_data_list failed[%d]", err);\r
-       }\r
-FINISH_OFF:\r
-       EM_DEBUG_FUNC_END("err [%d]", EMAIL_ERROR_NONE);\r
-       return EMAIL_ERROR_NONE;\r
-}\r
-\r
-static int default_alarm_callback(int input_timer_id, void *user_parameter)\r
-{\r
-       EM_DEBUG_FUNC_BEGIN("input_timer_id [%d] user_parameter [%p]", input_timer_id, user_parameter);\r
-       int err = EMAIL_ERROR_NONE;\r
-       email_alarm_data_t *alarm_data = NULL;\r
-\r
-       if ((err = emcore_get_alarm_data_by_alarm_id(input_timer_id, &alarm_data)) != EMAIL_ERROR_NONE || alarm_data == NULL) {\r
-               EM_DEBUG_EXCEPTION("emcore_get_alarm_data_by_alarm_id failed [%d]", err);\r
-               goto FINISH_OFF;\r
-       }\r
-\r
-       if ((err = alarm_data->alarm_callback(input_timer_id, user_parameter)) != EMAIL_ERROR_NONE) {\r
-               EM_DEBUG_EXCEPTION("alarm_callback failed [%d]", err);\r
-               goto FINISH_OFF;\r
-       }\r
-\r
-       emcore_delete_alram_data_from_alarm_data_list(alarm_data);\r
-       EM_SAFE_FREE(alarm_data);\r
-\r
-FINISH_OFF:\r
-\r
-\r
-       EM_DEBUG_FUNC_END("err [%d]", err);\r
-       return err;\r
-}\r
-\r
-INTERNAL_FUNC int emcore_init_alarm_data_list()\r
-{\r
-       EM_DEBUG_FUNC_BEGIN();\r
-       int ret = ALARMMGR_RESULT_SUCCESS;\r
-       int err = EMAIL_ERROR_NONE;\r
-       alarm_data_list = NULL;\r
-\r
-       if ((ret = alarmmgr_init(EMAIL_ALARM_DESTINATION)) != ALARMMGR_RESULT_SUCCESS) {\r
-               EM_DEBUG_EXCEPTION("alarmmgr_init failed [%d]",ret);\r
-               err = EMAIL_ERROR_SYSTEM_FAILURE;\r
-               goto FINISH_OFF;\r
-       }\r
-\r
-       if ((ret = alarmmgr_set_cb(default_alarm_callback, NULL)) != ALARMMGR_RESULT_SUCCESS) {\r
-               EM_DEBUG_EXCEPTION("alarmmgr_set_cb() failed [%d]", ret);\r
-               err = EMAIL_ERROR_SYSTEM_FAILURE;\r
-               goto FINISH_OFF;\r
-       }\r
-\r
-FINISH_OFF:\r
-\r
-       EM_DEBUG_FUNC_END("err [%d]", err);\r
-       return err;\r
-}\r
-\r
-INTERNAL_FUNC int emcore_add_alarm(time_t input_trigger_at_time, int input_class_id, int input_reference_id, int (*input_alarm_callback)(int, void *), void *input_user_data)\r
-{\r
-       EM_DEBUG_FUNC_BEGIN("input_trigger_at_time[%d] input_class_id[%d] input_reference_id[%d] input_alarm_callback[%p] input_user_data[%p]", input_trigger_at_time, input_class_id, input_reference_id, input_alarm_callback, input_user_data);\r
-\r
-       int err = EMAIL_ERROR_NONE;\r
-       int ret = 0;\r
-       time_t alarm_interval = 0;\r
-       time_t current_time = 0;\r
-       alarm_id_t alarm_id = 0;\r
-\r
-       time(&current_time);\r
-\r
-       alarm_interval = input_trigger_at_time - current_time;\r
-\r
-       /* old style */
-#ifdef __FEATURE_USE_APPSYNC__\r
-       if(input_class_id == EMAIL_ALARM_CLASS_AUTO_POLLING) {\r
-               if ((ret = appsync_daemon_schedule_after_delay(alarm_interval, 0, &alarm_id)) != APPSYNC_ERROR_NONE) {\r
-                       EM_DEBUG_EXCEPTION("appsync_daemon_schedule_after_delay failed [%d]",ret);\r
-                       err = EMAIL_ERROR_SYSTEM_FAILURE;\r
-                       goto FINISH_OFF;\r
-               }\r
-       }\r
+#endif
+
+
+INTERNAL_FUNC GList *alarm_data_list = NULL;
+
+INTERNAL_FUNC int emcore_get_alarm_data_by_alarm_id(alarm_id_t input_alarm_id, email_alarm_data_t **output_alarm_data)
+{
+       EM_DEBUG_FUNC_BEGIN("input_alarm_id [%d] output_alarm_data [%p]", input_alarm_id, output_alarm_data);
+       int err = EMAIL_ERROR_NONE;
+       GList *index = g_list_first(alarm_data_list);
+       email_alarm_data_t *alarm_data = NULL;
+
+       if (output_alarm_data == NULL) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       while(index) {
+               alarm_data = index->data;
+               if(alarm_data->alarm_id == input_alarm_id) {
+                       break;
+               }
+               index = g_list_next(index);
+       }
+
+       if(alarm_data)
+               *output_alarm_data = alarm_data;
+       else
+               err = EMAIL_ERROR_ALARM_DATA_NOT_FOUND;
+
+FINISH_OFF:
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC int emcore_get_alarm_data_by_reference_id(email_alarm_class_t input_class_id, int input_reference_id, email_alarm_data_t **output_alarm_data)
+{
+       EM_DEBUG_FUNC_BEGIN("input_class_id [%d] input_reference_id [%d] output_alarm_data [%p]", input_class_id, input_reference_id, output_alarm_data);
+       int err = EMAIL_ERROR_NONE;
+       GList *index = g_list_first(alarm_data_list);
+       email_alarm_data_t *alarm_data = NULL;
+
+       if (output_alarm_data == NULL) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       while(index) {
+               alarm_data = index->data;
+               if(alarm_data->class_id == input_class_id && alarm_data->reference_id == input_reference_id) {
+                       EM_DEBUG_LOG("found");
+                       break;
+               }
+               index = g_list_next(index);
+       }
+
+       if(index)
+               *output_alarm_data = alarm_data;
+       else
+               err = EMAIL_ERROR_ALARM_DATA_NOT_FOUND;
+
+FINISH_OFF:
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC int emcore_check_alarm_by_class_id(email_alarm_class_t input_class_id)
+{
+       EM_DEBUG_FUNC_BEGIN("input_class_id [%d]", input_class_id);
+       int err = EMAIL_ERROR_NONE;
+       GList *index = g_list_first(alarm_data_list);
+       email_alarm_data_t *alarm_data = NULL;
+
+       while(index) {
+               alarm_data = index->data;
+               if(alarm_data->class_id == input_class_id) {
+                       EM_DEBUG_LOG("found");
+                       break;
+               }
+               index = g_list_next(index);
+       }
+
+       if(!index)
+               err = EMAIL_ERROR_ALARM_DATA_NOT_FOUND;
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+static int emcore_add_alarm_data_to_alarm_data_list(alarm_id_t input_alarm_id, email_alarm_class_t input_class_id, int input_reference_id, time_t input_trigger_at_time, int (*input_alarm_callback)(int, void *), void *user_data)
+{
+       EM_DEBUG_FUNC_BEGIN("input_alarm_id [%d] input_class_id[%d] input_reference_id[%d] input_trigger_at_time[%d] input_alarm_callback [%p] user_data[%p]", input_alarm_id, input_class_id, input_reference_id, input_trigger_at_time, input_alarm_callback, user_data);
+       int err = EMAIL_ERROR_NONE;
+       email_alarm_data_t *alarm_data = NULL;
+
+       if (input_alarm_id == 0 || input_trigger_at_time == 0 || input_alarm_callback == NULL) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       alarm_data = em_malloc(sizeof(email_alarm_data_t));
+
+       if(alarm_data == NULL) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_OUT_OF_MEMORY");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+       alarm_data->alarm_id        = input_alarm_id;
+       alarm_data->class_id        = input_class_id;
+       alarm_data->reference_id    = input_reference_id;
+       alarm_data->trigger_at_time = input_trigger_at_time;
+       alarm_data->alarm_callback  = input_alarm_callback;
+       alarm_data->user_data       = user_data;
+
+       alarm_data_list = g_list_append(alarm_data_list, (gpointer)alarm_data);
+
+FINISH_OFF:
+
+       EM_DEBUG_FUNC_END("err [%d]", EMAIL_ERROR_NONE);
+       return EMAIL_ERROR_NONE;
+}
+
+static int emcore_remove_alarm(email_alarm_data_t *input_alarm_data)
+{
+       EM_DEBUG_FUNC_BEGIN("input_alarm_data [%p]", input_alarm_data);
+
+       int ret = ALARMMGR_RESULT_SUCCESS;
+       int err = EMAIL_ERROR_NONE;
+
+       EM_DEBUG_LOG("alarm_id [%d]", input_alarm_data->alarm_id);
+       if ((ret = alarmmgr_remove_alarm(input_alarm_data->alarm_id)) != ALARMMGR_RESULT_SUCCESS) {
+               EM_DEBUG_EXCEPTION ("alarmmgr_remove_alarm failed [%d]", ret);
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+       }
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC int emcore_delete_alram_data_from_alarm_data_list(email_alarm_data_t *input_alarm_data)
+{
+       EM_DEBUG_FUNC_BEGIN("input_alarm_data [%p]", input_alarm_data);
+       int err = EMAIL_ERROR_NONE;
+
+       if ((err = emcore_remove_alarm(input_alarm_data)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION ("emcore_remove_alarm failed [%d]", err);
+       }
+
+       alarm_data_list = g_list_remove(alarm_data_list, input_alarm_data);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC int emcore_delete_alram_data_by_reference_id(email_alarm_class_t input_class_id, int input_reference_id)
+{
+       EM_DEBUG_FUNC_BEGIN("input_class_id[%d] input_reference_id[%d]", input_class_id, input_reference_id);
+       int err = EMAIL_ERROR_NONE;
+       email_alarm_data_t *alarm_data = NULL;
+
+       if ((err = emcore_get_alarm_data_by_reference_id(input_class_id, input_reference_id, &alarm_data)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_LOG ("emcore_remove_alarm return [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if ((err = emcore_delete_alram_data_from_alarm_data_list(alarm_data)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_LOG ("emcore_delete_alram_data_from_alarm_data_list return [%d]", err);
+       }
+
+FINISH_OFF:
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC int emcore_add_alarm(time_t input_trigger_at_time, email_alarm_class_t input_class_id, int input_reference_id, int (*input_alarm_callback)(int, void *), void *input_user_data)
+{
+       EM_DEBUG_FUNC_BEGIN("input_trigger_at_time[%d] input_class_id[%d] input_reference_id[%d] input_alarm_callback[%p] input_user_data[%p]", input_trigger_at_time, input_class_id, input_reference_id, input_alarm_callback, input_user_data);
+
+       int err = EMAIL_ERROR_NONE;
+       int ret = 0;
+       time_t alarm_interval = 0;
+       time_t current_time = 0;
+       alarm_id_t alarm_id = 0;
+
+       time(&current_time);
+
+       alarm_interval = input_trigger_at_time - current_time;
+
+       EM_DEBUG_ALARM_LOG("alarm_interval [%d]", (int)alarm_interval);
+
+#ifdef __FEATURE_USE_APPSYNC__
+       if(input_class_id == EMAIL_ALARM_CLASS_AUTO_POLLING) {
+               if ((ret = appsync_daemon_schedule_after_delay(alarm_interval, 0, &alarm_id)) != APPSYNC_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("appsync_daemon_schedule_after_delay failed [%d]",ret);
+                       err = EMAIL_ERROR_SYSTEM_FAILURE;
+                       goto FINISH_OFF;
+               }
+       }
        else
 #endif
-       {\r
-               if ((ret = alarmmgr_add_alarm(ALARM_TYPE_VOLATILE, alarm_interval, ALARM_REPEAT_MODE_ONCE, EMAIL_ALARM_DESTINATION, &alarm_id)) != ALARMMGR_RESULT_SUCCESS) {\r
-                       EM_DEBUG_EXCEPTION("alarmmgr_add_alarm failed [%d]",ret);\r
-                       err = EMAIL_ERROR_SYSTEM_FAILURE;\r
-                       goto FINISH_OFF;\r
-               }\r
-       }\r
-\r
-       if((err = emcore_add_alarm_data_to_alarm_data_list(alarm_id, input_class_id, input_reference_id, input_trigger_at_time, input_alarm_callback, input_user_data)) != EMAIL_ERROR_NONE) {\r
-               EM_DEBUG_EXCEPTION("emcore_add_alarm_data_to_alarm_data_list failed [%d]", err);\r
-               goto FINISH_OFF;\r
-       }\r
-\r
-FINISH_OFF:\r
-\r
-       EM_DEBUG_FUNC_END("err [%d]", err);\r
-       return err;\r
-}\r
+       {
+               if ((ret = alarmmgr_add_alarm(ALARM_TYPE_VOLATILE, alarm_interval, ALARM_REPEAT_MODE_ONCE, EMAIL_ALARM_DESTINATION, &alarm_id)) != ALARMMGR_RESULT_SUCCESS) {
+                       EM_DEBUG_EXCEPTION("alarmmgr_add_alarm failed [%d]",ret);
+                       err = EMAIL_ERROR_SYSTEM_FAILURE;
+                       goto FINISH_OFF;
+               }
+       }
+
+       if((err = emcore_add_alarm_data_to_alarm_data_list(alarm_id, input_class_id, input_reference_id, input_trigger_at_time, input_alarm_callback, input_user_data)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emcore_add_alarm_data_to_alarm_data_list failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+FINISH_OFF:
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
diff --git a/email-core/email-core-api.c b/email-core/email-core-api.c
deleted file mode 100755 (executable)
index d23e468..0000000
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
-*  email-service
-*
-* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
-* 
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*
-*/
-
-
-/******************************************************************************
- * File :  email-core-api.h
- * Desc :  Mail Engine API
- *
- * Auth : 
- *
- * History : 
- *    2006.08.16  :  created
- *****************************************************************************/
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
-
-#include "c-client.h"
-#include "email-core-global.h"
-#include "email-network.h"
-#include "email-core-event.h"
-#include "email-core-mailbox.h"
-#include "email-core-utils.h"
-#include "email-core-alarm.h"
-#include "email-debug-log.h"
-
-extern void *
-pop3_parameters(long function, void *value);
-extern void *
-imap_parameters(long function, void *value);
-
-
-
-/* initialize mail core */
-INTERNAL_FUNC int emcore_init(int *err_code)
-{
-       EM_DEBUG_FUNC_BEGIN();
-
-       if (err_code != NULL) {
-               *err_code = EMAIL_ERROR_NONE;
-       }
-
-       mail_link(&imapdriver);  /*  link in the imap driver  */
-       mail_link(&pop3driver);  /*  link in the pop3 driver  */
-
-       mail_link(&unixdriver);  /*  link in the unix driver  */
-       mail_link(&dummydriver); /*  link in the dummy driver  */
-
-       ssl_onceonlyinit();
-
-       auth_link(&auth_md5);    /*  link in the md5 authenticator  */
-       auth_link(&auth_pla);    /*  link in the pla authenticator  */
-       auth_link(&auth_log);    /*  link in the log authenticator  */
-
-       /* Disabled to authenticate with plain text */
-       mail_parameters(NIL, SET_DISABLEPLAINTEXT, (void *) 2);
-
-       /* Set max trials for login */
-       imap_parameters(SET_MAXLOGINTRIALS, (void *)1);
-       pop3_parameters(SET_MAXLOGINTRIALS, (void *)1);
-       smtp_parameters(SET_MAXLOGINTRIALS, (void *)1);
-
-       mail_parameters(NIL, SET_SSLCERTIFICATEQUERY, (void *)emnetwork_callback_ssl_cert_query);
-       mail_parameters(NIL, SET_SSLCAPATH, (void *)SSL_CERT_DIRECTORY);
-
-       /* Set time out in second */
-       mail_parameters(NIL, SET_OPENTIMEOUT  , (void *)50);
-       mail_parameters(NIL, SET_READTIMEOUT  , (void *)180);
-       mail_parameters(NIL, SET_WRITETIMEOUT , (void *)180);
-       mail_parameters(NIL, SET_CLOSETIMEOUT , (void *)30);
-
-       emcore_init_alarm_data_list();
-
-       if (err_code)
-               *err_code = EMAIL_ERROR_NONE;
-
-    return true;
-}
-
index c0891b1..7247b4e 100755 (executable)
@@ -75,7 +75,7 @@ static int emcore_get_certificate_type(char *extension, int *err_code)
        }
        
        while(supported_file_type[index]) {
-               EM_DEBUG_LOG("certificate extension[%d]:[%s]", index, supported_file_type[index]);
+               EM_DEBUG_LOG_SEC("certificate extension[%d]:[%s]", index, supported_file_type[index]);
                if (strcasecmp(extension, supported_file_type[index]) == 0) {
                        switch (index) {
                        case 0:
@@ -113,7 +113,7 @@ FINISH_OFF:
 /*     
 static GList *emcore_make_glist_from_string(char *email_address_list)
 {
-       EM_DEBUG_FUNC_BEGIN("email_address list : [%s]", email_address_list);
+       EM_DEBUG_FUNC_BEGIN_SEC("email_address list : [%s]", email_address_list);
        int index = 0;
        const gchar seperator = 0x01;
        GList *email_list = NULL;
@@ -175,7 +175,7 @@ FINISH_OFF:
 #if 0
 INTERNAL_FUNC int emcore_load_PFX_file(char *certificate, char *password, EVP_PKEY **pri_key, X509 **cert, STACK_OF(X509) **ca, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("Certificate path : [%s], password : [%s]", certificate, password);
+       EM_DEBUG_FUNC_BEGIN_SEC("Certificate path : [%s], password : [%s]", certificate, password);
 
        int err = EMAIL_ERROR_NONE;
        int ret = false;
@@ -185,7 +185,7 @@ INTERNAL_FUNC int emcore_load_PFX_file(char *certificate, char *password, EVP_PK
        OpenSSL_add_all_algorithms();
        ERR_load_crypto_strings();
        if (!(fp = fopen(certificate, "rb"))) {
-               EM_DEBUG_EXCEPTION("fopen failed : [%s]", certificate);
+               EM_DEBUG_EXCEPTION_SEC("fopen failed : [%s]", certificate);
                err = EMAIL_ERROR_SYSTEM_FAILURE;
                goto FINISH_OFF;
        }
@@ -222,7 +222,7 @@ FINISH_OFF:
 
 INTERNAL_FUNC int emcore_load_PFX_file(char *certificate, EVP_PKEY **pri_key, X509 **cert, STACK_OF(X509) **ca, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("certificate : [%s]", certificate);
+       EM_DEBUG_FUNC_BEGIN_SEC("certificate : [%s]", certificate);
        int err = EMAIL_ERROR_NONE;
        int ret = false;
        size_t key_size = 0;
@@ -295,7 +295,7 @@ INTERNAL_FUNC int emcore_load_PFX_file(char *certificate, EVP_PKEY **pri_key, X5
                goto FINISH_OFF;
        }
 
-       EM_DEBUG_LOG("key_size : [%d], private_key : [%s]", key_size, private_key);
+       EM_DEBUG_LOG_DEV("key_size : [%d], private_key : [%s]", key_size, private_key);
 
        /* Convert char to pkey */
        bio_mem = BIO_new(BIO_s_mem());
@@ -347,7 +347,7 @@ FINISH_OFF:
 
 INTERNAL_FUNC int emcore_add_public_certificate(char *public_cert_path, char *save_name, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("Path [%s], filename [%s]", public_cert_path, save_name);
+       EM_DEBUG_FUNC_BEGIN_SEC("Path [%s], filename [%s]", public_cert_path, save_name);
        int err = EMAIL_ERROR_NONE;     
        int ret = false;
        int validity = 0;
@@ -465,6 +465,8 @@ INTERNAL_FUNC int emcore_add_public_certificate(char *public_cert_path, char *sa
        ret = true;
 
 FINISH_OFF:
+
+       emstorage_delete_file(temp_file, NULL);
        
        emstorage_free_certificate(&cert, 1, NULL);
 
@@ -499,7 +501,7 @@ INTERNAL_FUNC int emcore_delete_public_certificate(char *email_address, int *err
        }
 
        if (remove(certificate->filepath) < 0) {
-               EM_DEBUG_EXCEPTION("remove failed : [%s]", certificate->filepath);
+               EM_DEBUG_EXCEPTION_SEC("remove failed : [%s]", certificate->filepath);
                goto FINISH_OFF;
        }
 
@@ -524,7 +526,7 @@ FINISH_OFF:
 
 INTERNAL_FUNC int emcore_verify_signature(char *p7s_file_path, char *mime_entity, int *validity, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("path : [%s], mime_entity : [%s]", p7s_file_path, mime_entity);
+       EM_DEBUG_FUNC_BEGIN_SEC("path : [%s], mime_entity : [%s]", p7s_file_path, mime_entity);
        int ret = false;
        int err = EMAIL_ERROR_NONE;
        int t_validity = 0;
index 97f32c0..74fc387 100755 (executable)
 *
 */
 
-
-
-/******************************************************************************
- * File :  email-core-event_data.h
- * Desc :  Mail Engine Event
- *
- * Auth :
- *
- * History :
- *    2006.08.16  :  created
- *****************************************************************************/
 #include <stdio.h>
 #include <glib.h>
 #include <malloc.h>
 #include "email-debug-log.h"
 
 
-#ifdef __FEATURE_PARTIAL_BODY_DOWNLOAD__
+/*-----------------------------------------------------------------------------
+ * Receving Event Queue
+ *---------------------------------------------------------------------------*/
+INTERNAL_FUNC thread_t g_srv_thread;
+INTERNAL_FUNC pthread_cond_t  _event_available_signal = PTHREAD_COND_INITIALIZER;
+INTERNAL_FUNC pthread_mutex_t *_event_queue_lock = NULL;
+INTERNAL_FUNC pthread_mutex_t *_event_handle_map_lock = NULL;
 
-/*[h.gahlaut] - All static variable declaration for partial body download thread are done here */
+INTERNAL_FUNC GQueue *g_event_que;
+INTERNAL_FUNC int g_event_loop = 1;
+INTERNAL_FUNC int handle_map[EVENT_QUEUE_MAX] = {0,};
+INTERNAL_FUNC int recv_thread_run = 0;
 
-#define TOTAL_PARTIAL_BODY_EVENTS 100
+static void fail_status_notify(email_event_t *event_data, int error);
+static int emcore_get_new_handle(void);
 
-static email_event_partial_body_thd g_partial_body_thd_event_que[TOTAL_PARTIAL_BODY_EVENTS];
 
-static int g_partial_body_thd_next_event_idx = 0;                      /* Index of Next Event to be processed in the queue*/
-static int g_partial_body_thd_loop = 1;                                                /* Variable to make a continuos while loop */
-static int g_partial_body_thd_queue_empty = true;                      /* Variable to determine if event queue is empty.True means empty*/
-static int g_partial_body_thd_queue_full = false;                      /* Variable to determine if event queue is full. True means full*/
-static int g_pb_thd_local_activity_continue = true;                    /* Variable to control local activity sync */
-int g_pbd_thd_state = false;                                                           /* false :  thread is sleeping , true :  thread is working */
+/*-----------------------------------------------------------------------------
+ * Sending Event Queue
+ *---------------------------------------------------------------------------*/
+INTERNAL_FUNC thread_t g_send_srv_thread;
+INTERNAL_FUNC pthread_cond_t  _send_event_available_signal = PTHREAD_COND_INITIALIZER;
+INTERNAL_FUNC pthread_mutex_t *_send_event_queue_lock = NULL;
+INTERNAL_FUNC pthread_mutex_t *_send_event_handle_map_lock = NULL;
 
-static pthread_mutex_t _partial_body_thd_event_queue_lock = PTHREAD_MUTEX_INITIALIZER; /* Mutex to protect event queue */
-static pthread_cond_t  _partial_body_thd_cond = PTHREAD_COND_INITIALIZER;                              /* Condition variable on which partial body thread is waiting  */
-thread_t g_partial_body_thd ;                                                          /* Determines if thread is created or not. Non Null means thread is created */
+INTERNAL_FUNC GQueue *g_send_event_que;
+INTERNAL_FUNC int g_send_event_loop = 1;
+INTERNAL_FUNC int send_handle_map[EVENT_QUEUE_MAX] = {0,};
+INTERNAL_FUNC int send_thread_run = 0;
 
-email_event_partial_body_thd g_partial_body_bulk_dwd_que[BULK_PARTIAL_BODY_DOWNLOAD_COUNT];
-static int g_partial_body_bulk_dwd_next_event_idx = 0;         /* Index of Next Event to be processed in the queue*/
-static int g_partial_body_bulk_dwd_queue_empty = true;
+static int emcore_get_new_send_handle(void);
 
-static pthread_mutex_t _state_variables_lock;
+/*-----------------------------------------------------------------------------
+ * Partial Body Event Queue
+ *---------------------------------------------------------------------------*/
 
-/*[h.gahlaut] - All static function declaration for partial body download thread are done here */
+#ifdef __FEATURE_PARTIAL_BODY_DOWNLOAD__
 
-static int emcore_retrieve_partial_body_thread_event(email_event_partial_body_thd *partial_body_thd_event, int *error_code);
-static int emcore_copy_partial_body_thd_event(email_event_partial_body_thd *src, email_event_partial_body_thd *dest, int *error_code);
-static void emcore_pb_thd_set_local_activity_continue(int flag);
-static int emcore_set_pbd_thd_state(int flag);
-static int emcore_clear_bulk_pbd_que(int *err_code);
-int emcore_mail_partial_body_download(email_event_partial_body_thd *pbd_event, int *error_code);
+INTERNAL_FUNC thread_t g_partial_body_thd ;                                                            /* Determines if thread is created or not. Non Null means thread is created */
+INTERNAL_FUNC pthread_mutex_t _partial_body_thd_event_queue_lock = PTHREAD_MUTEX_INITIALIZER;  /* Mutex to protect event queue */
+INTERNAL_FUNC pthread_cond_t  _partial_body_thd_cond = PTHREAD_COND_INITIALIZER;                               /* Condition variable on which partial body thread is waiting  */
+INTERNAL_FUNC pthread_mutex_t _state_variables_lock;
 
-#endif
+INTERNAL_FUNC email_event_partial_body_thd g_partial_body_thd_event_que[TOTAL_PARTIAL_BODY_EVENTS];
+INTERNAL_FUNC int g_partial_body_thd_next_event_idx = 0;                       /* Index of Next Event to be processed in the queue*/
+INTERNAL_FUNC int g_partial_body_thd_loop = 1;                                         /* Variable to make a continuos while loop */
+INTERNAL_FUNC int g_partial_body_thd_queue_empty = true;                       /* Variable to determine if event queue is empty.True means empty*/
+INTERNAL_FUNC int g_partial_body_thd_queue_full = false;                       /* Variable to determine if event queue is full. True means full*/
+INTERNAL_FUNC int g_pb_thd_local_activity_continue = true;                     /* Variable to control local activity sync */
+INTERNAL_FUNC int g_pbd_thd_state = false;                                                             /* false :  thread is sleeping , true :  thread is working */
 
-#ifdef ENABLE_IMAP_IDLE_THREAD
-extern int g_imap_idle_thread_alive;
-extern int imap_idle_thread;
-#endif /* ENABLE_IMAP_IDLE_THREAD */
-INTERNAL_FUNC int g_client_count = 0;
-INTERNAL_FUNC int g_client_run = 0 ;
+INTERNAL_FUNC email_event_partial_body_thd g_partial_body_bulk_dwd_que[BULK_PARTIAL_BODY_DOWNLOAD_COUNT];
+static int g_partial_body_bulk_dwd_next_event_idx = 0;         /* Index of Next Event to be processed in the queue*/
+INTERNAL_FUNC int g_partial_body_bulk_dwd_queue_empty = true;
 
-#ifdef __FEATURE_LOCAL_ACTIVITY__
-INTERNAL_FUNC int g_local_activity_run = 0;
-INTERNAL_FUNC int g_save_local_activity_run = 0;
-#endif
+static int emcore_copy_partial_body_thd_event(email_event_partial_body_thd *src, email_event_partial_body_thd *dest, int *error_code);
+static int emcore_clear_bulk_pbd_que(int *err_code);
 
+#endif
 
+/*-----------------------------------------------------------------------------
+ * Unused
+ *---------------------------------------------------------------------------*/
 typedef struct EVENT_CALLBACK_ELEM
 {
        email_event_callback callback;
@@ -115,53 +118,19 @@ typedef struct EVENT_CALLBACK_ELEM
        struct EVENT_CALLBACK_ELEM *next;
 } EVENT_CALLBACK_LIST;
 
-static pthread_mutex_t _event_available_lock = PTHREAD_MUTEX_INITIALIZER;
-static pthread_cond_t  _event_available_signal = PTHREAD_COND_INITIALIZER;
-static pthread_mutex_t *_event_callback_table_lock = NULL;
-static pthread_mutex_t *_event_queue_lock = NULL;
 static EVENT_CALLBACK_LIST *_event_callback_table[EMAIL_ACTION_NUM];           /*  array of singly-linked list for event callbacks */
+INTERNAL_FUNC pthread_mutex_t *_event_callback_table_lock = NULL;
 
-void *thread_func_branch_command(void *arg);
-
-static email_event_t g_event_que[EVENT_QUEUE_MAX];
-
-int send_thread_run = 0;
-int recv_thread_run = 0;
-
-static pthread_mutex_t _send_event_available_lock = PTHREAD_MUTEX_INITIALIZER;
-static pthread_mutex_t *_send_event_queue_lock = NULL;  /*  MUST BE "recursive" */
-static pthread_cond_t  _send_event_available_signal = PTHREAD_COND_INITIALIZER;
-static thread_t g_send_srv_thread;
-static thread_t g_srv_thread;
-
-static email_event_t g_send_event_que[EVENT_QUEUE_MAX];
-static int g_send_event_que_idx = 1;
-static int g_send_event_loop = 1;
-static int g_send_active_que = 0;
-static int g_event_que_idx = 1;
-static int g_event_loop = 1;
-static int g_active_que = 0;
-static int g_sending_busy_cnt = 0;
-static int g_receiving_busy_cnt = 0;
-
-
-INTERNAL_FUNC int emcore_get_current_thread_type()
-{
-       EM_DEBUG_FUNC_BEGIN();
-       thread_t thread_id = THREAD_SELF();
-       int thread_type = -1;
-
-       if (thread_id == g_srv_thread)
-               thread_type = _SERVICE_THREAD_TYPE_RECEIVING;
-       else if (thread_id == g_send_srv_thread)
-               thread_type = _SERVICE_THREAD_TYPE_SENDING;
-#ifdef __FEATURE_PARTIAL_BODY_DOWNLOAD__
-       else if (thread_id == g_partial_body_thd)
-               thread_type = _SERVICE_THREAD_TYPE_PBD;
+#ifdef __FEATURE_LOCAL_ACTIVITY__
+INTERNAL_FUNC int g_local_activity_run = 0;
+INTERNAL_FUNC int g_save_local_activity_run = 0;
+static int event_handler_EMAIL_EVENT_LOCAL_ACTIVITY(int account_id, int *error);
 #endif
-       EM_DEBUG_FUNC_END("thread_type [%d]", thread_type);
-       return thread_type;
-}
+
+#ifdef ENABLE_IMAP_IDLE_THREAD
+extern int g_imap_idle_thread_alive;
+extern int imap_idle_thread;
+#endif /* ENABLE_IMAP_IDLE_THREAD */
 
 static int is_gdk_lock_needed()
 {
@@ -171,114 +140,6 @@ static int is_gdk_lock_needed()
        return false;
 }
 
-static void _sending_busy_ref(void)
-{
-       g_sending_busy_cnt++;
-}
-
-static void _sending_busy_unref(void)
-{
-       g_sending_busy_cnt--;
-}
-
-static void _receiving_busy_ref(void)
-{
-       g_receiving_busy_cnt++;
-}
-
-static void _receiving_busy_unref(void)
-{
-       g_receiving_busy_cnt--;
-}
-
-static void waiting_status_notify(email_event_t *event_data, int queue_idx)
-{
-       EM_DEBUG_FUNC_BEGIN("event_data[%p], queue_idx[%d]", event_data, queue_idx);
-
-       int account_id = event_data->account_id;
-       int mail_id = event_data->event_param_data_4;           /*  NOT ALWAYS */
-
-       switch (event_data->type)  {
-               case EMAIL_EVENT_SEND_MAIL:
-                       emcore_execute_event_callback(EMAIL_ACTION_SEND_MAIL, 0, 0, EMAIL_SEND_WAITING, account_id, mail_id, queue_idx, EMAIL_ERROR_NONE);
-                       break;
-
-               case EMAIL_EVENT_SYNC_HEADER:
-                       emcore_execute_event_callback(EMAIL_ACTION_SYNC_HEADER, 0, 0, EMAIL_LIST_WAITING, account_id, 0, queue_idx, EMAIL_ERROR_NONE);
-                       break;
-
-               case EMAIL_EVENT_SYNC_HEADER_OMA:
-                       emcore_execute_event_callback(EMAIL_ACTION_SYNC_HEADER_OMA, 0, 0, EMAIL_LIST_WAITING, account_id, 0, queue_idx, EMAIL_ERROR_NONE);
-                       break;
-
-               case EMAIL_EVENT_DOWNLOAD_BODY:
-                       emcore_execute_event_callback(EMAIL_ACTION_DOWNLOAD_BODY, 0, 0, EMAIL_DOWNLOAD_WAITING, account_id, mail_id, queue_idx, EMAIL_ERROR_NONE);
-                       break;
-
-#ifdef __FEATURE_SYNC_CLIENT_TO_SERVER__
-               case EMAIL_EVENT_SYNC_MAIL_FLAG_TO_SERVER:
-                       emcore_execute_event_callback(EMAIL_ACTION_SYNC_MAIL_FLAG_TO_SERVER, 0, 0, EMAIL_SYNC_WAITING, account_id, mail_id, queue_idx, EMAIL_ERROR_NONE);
-                       break;
-#endif
-
-               case EMAIL_EVENT_DOWNLOAD_ATTACHMENT:
-                       emcore_execute_event_callback(EMAIL_ACTION_DOWNLOAD_ATTACHMENT, 0, 0, EMAIL_DOWNLOAD_WAITING, account_id, mail_id, queue_idx, EMAIL_ERROR_NONE);
-                       break;
-
-               case EMAIL_EVENT_DELETE_MAIL:
-               case EMAIL_EVENT_DELETE_MAIL_ALL:
-                       emcore_execute_event_callback(EMAIL_ACTION_DELETE_MAIL, 0, 0, EMAIL_DELETE_WAITING, account_id, 0, queue_idx, EMAIL_ERROR_NONE);
-                       break;
-
-               case EMAIL_EVENT_VALIDATE_ACCOUNT:
-                       emcore_execute_event_callback(EMAIL_ACTION_VALIDATE_ACCOUNT, 0, 0, EMAIL_VALIDATE_ACCOUNT_WAITING, account_id, 0, queue_idx, EMAIL_ERROR_NONE);
-                       break;
-
-               case EMAIL_EVENT_VALIDATE_AND_CREATE_ACCOUNT:
-                       emcore_execute_event_callback(EMAIL_ACTION_VALIDATE_AND_CREATE_ACCOUNT, 0, 0, EMAIL_VALIDATE_ACCOUNT_WAITING, account_id, 0, queue_idx, EMAIL_ERROR_NONE);
-                       break;
-
-               case EMAIL_EVENT_VALIDATE_ACCOUNT_EX:
-                       emcore_execute_event_callback(EMAIL_ACTION_VALIDATE_ACCOUNT_EX, 0, 0, EMAIL_VALIDATE_ACCOUNT_WAITING, account_id, 0, queue_idx, EMAIL_ERROR_NONE);
-                       break;
-
-               case EMAIL_EVENT_MOVE_MAIL:
-                       emcore_execute_event_callback(EMAIL_ACTION_MOVE_MAIL, 0, 0, EMAIL_LIST_WAITING, account_id, 0, queue_idx, EMAIL_ERROR_NONE);
-                       break;
-
-               case EMAIL_EVENT_CREATE_MAILBOX:
-                       emcore_execute_event_callback(EMAIL_ACTION_CREATE_MAILBOX, 0, 0, EMAIL_LIST_WAITING, account_id, 0, queue_idx, EMAIL_ERROR_NONE);
-                       break;
-
-               case EMAIL_EVENT_VALIDATE_AND_UPDATE_ACCOUNT:
-                       emcore_execute_event_callback(EMAIL_ACTION_VALIDATE_AND_UPDATE_ACCOUNT, 0, 0, EMAIL_VALIDATE_ACCOUNT_WAITING, account_id, 0, queue_idx, EMAIL_ERROR_NONE);
-                       break;
-
-               case EMAIL_EVENT_UPDATE_MAIL:
-                       break;
-
-               case EMAIL_EVENT_SET_MAIL_SLOT_SIZE:
-                       emcore_execute_event_callback(EMAIL_ACTION_SET_MAIL_SLOT_SIZE, 0, 0, EMAIL_SET_SLOT_SIZE_WAITING, account_id, 0, queue_idx, EMAIL_ERROR_NONE);
-                       break;
-
-               case EMAIL_EVENT_EXPUNGE_MAILS_DELETED_FLAGGED:
-                       emcore_execute_event_callback(EMAIL_ACTION_EXPUNGE_MAILS_DELETED_FLAGGED, 0, 0, EMAIL_EXPUNGE_MAILS_DELETED_FLAGGED_WAITING, account_id, event_data->event_param_data_4, queue_idx, EMAIL_ERROR_NONE);
-                       break;
-
-               case EMAIL_EVENT_SEARCH_ON_SERVER:
-                       emcore_execute_event_callback(EMAIL_ACTION_SEARCH_ON_SERVER, 0, 0, EMAIL_SYNC_WAITING, account_id, 0, queue_idx, EMAIL_ERROR_NONE);
-                       break;
-
-               case EMAIL_EVENT_RENAME_MAILBOX_ON_IMAP_SERVER:
-                       /* emcore_execute_event_callback(EMAIL_ACTION_CREATE_MAILBOX, 0, 0, EMAIL_LIST_WAITING, account_id, 0, queue_idx, EMAIL_ERROR_NONE); */
-                       break;
-
-               default:
-                       break;
-       }
-       EM_DEBUG_FUNC_END();
-}
-
 static void fail_status_notify(email_event_t *event_data, int error)
 {
        EM_DEBUG_FUNC_BEGIN();
@@ -380,7 +241,7 @@ static void fail_status_notify(email_event_t *event_data, int error)
 }
 
 
-static void emcore_initialize_event_callback_table()
+INTERNAL_FUNC void emcore_initialize_event_callback_table()
 {
        ENTER_RECURSIVE_CRITICAL_SECTION(_event_callback_table_lock);
 
@@ -454,7 +315,7 @@ int emcore_unregister_event_callback(email_action_t action, email_event_callback
                        else
                                _event_callback_table[action] = node->next;
 
-                       free(node);
+                       EM_SAFE_FREE(node);
 
                        ret = true;
                        break;
@@ -486,7 +347,7 @@ void emcore_execute_event_callback(email_action_t action, int total, int done, i
 
        while (node != NULL)  {
                if (node->callback != NULL)
-                       node->callback(total, done, status, account_id, mail_id, (handle == -1 ? emcore_get_active_queue_idx()  :  handle), node->event_data, error);
+                       node->callback(total, done, status, account_id, mail_id, handle, node->event_data, error);
                node = node->next;
        }
 
@@ -502,106 +363,75 @@ INTERNAL_FUNC int emcore_insert_event(email_event_t *event_data, int *handle, in
 {
        EM_DEBUG_FUNC_BEGIN("event_data[%p], handle[%p], err_code[%p]", event_data, handle, err_code);
 
-       if (!event_data)  {
+       if (!event_data) {
                EM_DEBUG_EXCEPTION("Invalid Parameter");
                if (err_code != NULL)
                        *err_code = EMAIL_ERROR_INVALID_PARAM;
                return false;
        }
 
-       if (!g_srv_thread)  {
+       if (!g_srv_thread) {
                EM_DEBUG_EXCEPTION("email-service is not ready");
                if (err_code != NULL)
                        *err_code = EMAIL_ERROR_LOAD_ENGINE_FAILURE;
                return false;
        }
 
-       int ret = true;
+       int ret = false;
        int error = EMAIL_ERROR_NONE;
+       int q_length = 0;
+       int new_handle = 0;
 
        ENTER_RECURSIVE_CRITICAL_SECTION(_event_queue_lock);
 
-       if (!g_event_que[g_event_que_idx].type)  {      /*  if current buffer has not event, insert event data to current buffer  */
-               EM_DEBUG_LOG("Current buffer has not a event. [%d]", g_event_que_idx);
-               memcpy(g_event_que+g_event_que_idx, event_data, sizeof(email_event_t));
-               g_event_que[g_event_que_idx].status = EMAIL_EVENT_STATUS_WAIT;
-               waiting_status_notify(event_data, g_event_que_idx);
-               if (handle)
-                       *handle = g_event_que_idx;
-       }
-       else  { /*  if current buffer has event, find the empty buffer */
-               EM_DEBUG_LOG("Current buffer has a event. [%d]", g_event_que_idx);
-               int i, j = g_event_que_idx + 1;
-
-               for (i = 1; i < EVENT_QUEUE_MAX; i++, j++)  {
-                       if (j >= EVENT_QUEUE_MAX)
-                               j = 1;
-
-                       if (!g_event_que[j].type)
-                                       break;
-               }
+       if (g_event_que)
+               q_length = g_queue_get_length(g_event_que);
 
-               if (i < EVENT_QUEUE_MAX)  {
-                       EM_DEBUG_LOG("I found available buffer. [%d]", g_event_que + j);
-                       memcpy(g_event_que+j, event_data, sizeof(email_event_t));
-                       g_event_que[j].status = EMAIL_EVENT_STATUS_WAIT;
-                       waiting_status_notify(event_data, j);
+       EM_DEBUG_LOG("Q Length : [%d]", q_length);
 
-                       if (handle)
-                               *handle = j;
-               }
-               else  {
-                       EM_DEBUG_EXCEPTION("event que is full...");
-                       error = EMAIL_ERROR_EVENT_QUEUE_FULL;
-                       ret = false;
+       if (q_length > EVENT_QUEUE_MAX) {
+               EM_DEBUG_EXCEPTION("event que is full...");
+               error = EMAIL_ERROR_EVENT_QUEUE_FULL;
+               ret = false;
+       } else {
+               new_handle = emcore_get_new_handle();
+
+               if (new_handle) {
+                       event_data->status = EMAIL_EVENT_STATUS_WAIT;
+                       event_data->handle = new_handle;
+                       g_queue_push_tail(g_event_que, event_data);
+                       WAKE_CONDITION_VARIABLE(_event_available_signal);
+                       ret = true;
                }
        }
 
        LEAVE_RECURSIVE_CRITICAL_SECTION(_event_queue_lock);
 
-       if (ret == true)  {
-               event_data->event_param_data_1 = NULL;          /*  MUST BE - to prevent double-free */
-
-               switch (event_data->type)  {
-                       case EMAIL_EVENT_SEND_MAIL:
-                       case EMAIL_EVENT_SEND_MAIL_SAVED:
-                               _sending_busy_ref();
-                               break;
-
-                       case EMAIL_EVENT_SYNC_HEADER:
-                       case EMAIL_EVENT_DOWNLOAD_BODY:
-                       case EMAIL_EVENT_DOWNLOAD_ATTACHMENT:
-                       case EMAIL_EVENT_SYNC_MAIL_FLAG_TO_SERVER:
-                       case EMAIL_EVENT_SYNC_FLAGS_FIELD_TO_SERVER:
-                       case EMAIL_EVENT_ISSUE_IDLE:
-                       case EMAIL_EVENT_SYNC_IMAP_MAILBOX:
-                       case EMAIL_EVENT_VALIDATE_ACCOUNT:
-                       case EMAIL_EVENT_VALIDATE_AND_CREATE_ACCOUNT:
-                       case EMAIL_EVENT_VALIDATE_ACCOUNT_EX:
-                       case EMAIL_EVENT_SAVE_MAIL:
-                       case EMAIL_EVENT_MOVE_MAIL:
-                       case EMAIL_EVENT_DELETE_MAIL:
-                       case EMAIL_EVENT_DELETE_MAIL_ALL:
-                       case EMAIL_EVENT_SYNC_HEADER_OMA:
-                       case EMAIL_EVENT_CREATE_MAILBOX:
-                       case EMAIL_EVENT_DELETE_MAILBOX:
-                       case EMAIL_EVENT_VALIDATE_AND_UPDATE_ACCOUNT:
-                       case EMAIL_EVENT_SET_MAIL_SLOT_SIZE:
-                       case EMAIL_EVENT_UPDATE_MAIL:
-                       case EMAIL_EVENT_EXPUNGE_MAILS_DELETED_FLAGGED:
-                       case EMAIL_EVENT_SEARCH_ON_SERVER:
-                       case EMAIL_EVENT_RENAME_MAILBOX_ON_IMAP_SERVER:
-                               _receiving_busy_ref();
-                               break;
-                       default:
-                               break;
-               }
+       if (handle)
+               *handle = new_handle;
 
-               ENTER_CRITICAL_SECTION(_event_available_lock);
-               WAKE_CONDITION_VARIABLE(_event_available_signal);
-               LEAVE_CRITICAL_SECTION(_event_available_lock);
-       }
+       switch (event_data->type)  {
+               case EMAIL_EVENT_DOWNLOAD_ATTACHMENT:
+               case EMAIL_EVENT_SYNC_MAIL_FLAG_TO_SERVER:
+               case EMAIL_EVENT_SYNC_FLAGS_FIELD_TO_SERVER:
+               case EMAIL_EVENT_VALIDATE_ACCOUNT:
+               case EMAIL_EVENT_VALIDATE_AND_CREATE_ACCOUNT:
+               case EMAIL_EVENT_VALIDATE_ACCOUNT_EX:
+               case EMAIL_EVENT_SAVE_MAIL:
+               case EMAIL_EVENT_MOVE_MAIL:
+               case EMAIL_EVENT_DELETE_MAIL:
+               case EMAIL_EVENT_DELETE_MAIL_ALL:
+               case EMAIL_EVENT_CREATE_MAILBOX:
+               case EMAIL_EVENT_DELETE_MAILBOX:
+               case EMAIL_EVENT_VALIDATE_AND_UPDATE_ACCOUNT:
+               case EMAIL_EVENT_SET_MAIL_SLOT_SIZE:
+               case EMAIL_EVENT_UPDATE_MAIL:
+               case EMAIL_EVENT_EXPUNGE_MAILS_DELETED_FLAGGED:
+               case EMAIL_EVENT_SEARCH_ON_SERVER:
+               case EMAIL_EVENT_RENAME_MAILBOX_ON_IMAP_SERVER:
+                       break;
 
+               default:
 #ifdef __FEATURE_PARTIAL_BODY_DOWNLOAD__
        {
                int is_local_activity_event_inserted = false;
@@ -614,50 +444,67 @@ INTERNAL_FUNC int emcore_insert_event(email_event_t *event_data, int *handle, in
                }
        }
 #endif
+               break;
+       }
 
-       if (err_code != NULL)
+       if (err_code) {
+               EM_DEBUG_LOG("ERR [%d]", error);
                *err_code = error;
+       }
 
-       EM_DEBUG_LOG("Finish with [%d]", ret);
        return ret;
 }
 
 /* get a event from event_data queue */
-static int emcore_retrieve_event(email_event_t *event_data, int *err_code)
+INTERNAL_FUNC int emcore_retrieve_event(email_event_t **event_data, int *err_code)
 {
        EM_DEBUG_FUNC_BEGIN("event_data[%p], err_code[%p]", event_data, err_code);
 
        int ret = false;
        int error = EMAIL_ERROR_NONE;
+       int q_length = 0;
+       email_event_t *poped = NULL;
+       email_event_t *head_event = NULL;
 
-       ENTER_RECURSIVE_CRITICAL_SECTION(_event_queue_lock);
+       if (g_event_que)
+               q_length = g_queue_get_length(g_event_que);
 
-       /*  get a event_data if this queue is not empty */
-       if (g_event_que[g_event_que_idx].type)  {
-               memcpy(event_data, g_event_que+g_event_que_idx, sizeof(email_event_t));
+       EM_DEBUG_LOG("Q Length : [%d]", q_length);
 
-               if (event_data->status != EMAIL_EVENT_STATUS_WAIT)  {   /*  EMAIL_EVENT_STATUS_CANCELED */
-                       memset(g_event_que+g_event_que_idx, 0x00, sizeof(email_event_t));
-                       g_active_que = 0;
+       if (!q_length) {
+               error = EMAIL_ERROR_EVENT_QUEUE_EMPTY;
+               EM_DEBUG_LOG("QUEUE is empty");
+               goto FINISH_OFF;
+       }
+
+       while (1) {
+               head_event = (email_event_t *)g_queue_peek_head(g_event_que);
+               if (!head_event) {
+                       error = EMAIL_ERROR_EVENT_QUEUE_EMPTY;
+                       EM_DEBUG_LOG_DEV ("QUEUE is empty");
+                       break;
                }
-               else  {
-                       EM_DEBUG_LINE;
-                       g_event_que[g_event_que_idx].status = EMAIL_EVENT_STATUS_STARTED;
-                       g_active_que = g_event_que_idx;
+               if (head_event->status != EMAIL_EVENT_STATUS_WAIT) {
+                       EM_DEBUG_LOG("EVENT STATUS [%d]", head_event->status);
+                       poped = g_queue_pop_head(g_event_que);
+                       if (poped) {
+                               emcore_return_handle(poped->handle);
+                               emcore_free_event(poped);
+                               EM_SAFE_FREE(poped);
+                       } else {
+                               error = EMAIL_ERROR_EVENT_QUEUE_EMPTY;
+                               EM_DEBUG_LOG("QUEUE is empty");
+                               break;
+                       }
+               } else {
+                       head_event->status = EMAIL_EVENT_STATUS_STARTED;
+                       *event_data = head_event;
                        ret = true;
+                       break;
                }
-
-               if (++g_event_que_idx >= EVENT_QUEUE_MAX)
-                       g_event_que_idx = 1;
-
-               EM_DEBUG_LOG("g_event_que[%d].type [%d]", g_active_que, g_event_que[g_active_que].type);
-       }
-       else  {
-               g_active_que = 0;
-               error = EMAIL_ERROR_EVENT_QUEUE_EMPTY;
        }
 
-       LEAVE_RECURSIVE_CRITICAL_SECTION(_event_queue_lock);
+FINISH_OFF:
 
        if (err_code != NULL)
                *err_code = error;
@@ -667,1685 +514,417 @@ static int emcore_retrieve_event(email_event_t *event_data, int *err_code)
 }
 
 /* check that event_data loop is continuous */
-static int emcore_event_loop_continue()
+INTERNAL_FUNC int emcore_event_loop_continue(void)
 {
-    return g_event_loop;
+       return g_event_loop;
 }
 
-
-
 INTERNAL_FUNC int emcore_insert_event_for_sending_mails(email_event_t *event_data, int *handle, int *err_code)
 {
        EM_DEBUG_FUNC_BEGIN("event_data[%p], handle[%p], err_code[%p]", event_data, handle, err_code);
 
-       if (!event_data)  {
-               EM_DEBUG_EXCEPTION("\t event_data[%p], handle[%p]", event_data, handle);
-
+       if (!event_data) {
+               EM_DEBUG_EXCEPTION("Invalid Parameter");
                if (err_code != NULL)
                        *err_code = EMAIL_ERROR_INVALID_PARAM;
                return false;
        }
 
-       int ret = true;
+       if (!g_send_srv_thread) {
+               EM_DEBUG_EXCEPTION("email-service is not ready");
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_LOAD_ENGINE_FAILURE;
+               return false;
+       }
+
+       int ret = false;
        int error = EMAIL_ERROR_NONE;
+       int q_length = 0;
+       int new_handle = 0;
 
        ENTER_RECURSIVE_CRITICAL_SECTION(_send_event_queue_lock);
 
-       if (!g_send_event_que[g_send_event_que_idx].type)  {
-               /* if current buffer has not event_data, insert event_data data to current buffer */
-               EM_DEBUG_LOG("Current buffer has not a event_data. [%d]", g_send_event_que_idx);
-               memcpy(g_send_event_que+g_send_event_que_idx, event_data, sizeof(email_event_t));
-
-               g_send_event_que[g_send_event_que_idx].status = EMAIL_EVENT_STATUS_WAIT;
-
-               if (handle)
-                       *handle = g_send_event_que_idx;
-       }
-       else  {
-               /* if current buffer has event_data, find the empty buffer */
-               EM_DEBUG_LOG("Current buffer has a event_data. [%d]", g_send_event_que_idx);
-               int i, j = g_send_event_que_idx + 1;
-
-               for (i = 1; i < EVENT_QUEUE_MAX; i++, j++)  {
-                       if (j >= EVENT_QUEUE_MAX)
-                               j = 1;
+       if (g_send_event_que)
+               q_length = g_queue_get_length(g_send_event_que);
 
-                       if (!g_send_event_que[j].type)
-                                       break;
-                       }
+       EM_DEBUG_LOG("SEND Q Length : [%d]", q_length);
 
-               if (i < EVENT_QUEUE_MAX)  {
-                       EM_DEBUG_LOG("I found available buffer. [%d]", j);
-                       memcpy(g_send_event_que+j, event_data, sizeof(email_event_t));
-                       g_send_event_que[j].status = EMAIL_EVENT_STATUS_WAIT;
-                       if (handle) *handle = j;
-               }
-               else  {
-                       EM_DEBUG_EXCEPTION("event_data queue is full...");
-                       error = EMAIL_ERROR_EVENT_QUEUE_FULL;
-                       ret = false;
+       if (q_length > EVENT_QUEUE_MAX) {
+               EM_DEBUG_EXCEPTION("send event que is full...");
+               error = EMAIL_ERROR_EVENT_QUEUE_FULL;
+               ret = false;
+       } else {
+               new_handle = emcore_get_new_send_handle();
+
+               if (new_handle) {
+                       event_data->status = EMAIL_EVENT_STATUS_WAIT;
+                       event_data->handle = new_handle;
+                       g_queue_push_tail(g_send_event_que, event_data);
+                       WAKE_CONDITION_VARIABLE(_send_event_available_signal);
+                       ret = true;
                }
        }
 
        LEAVE_RECURSIVE_CRITICAL_SECTION(_send_event_queue_lock);
 
-       if (ret == true)  {
-               ENTER_CRITICAL_SECTION(_send_event_available_lock);
-               WAKE_CONDITION_VARIABLE(_send_event_available_signal);
-               LEAVE_CRITICAL_SECTION(_send_event_available_lock);
-       }
-
        if (handle)
-       EM_DEBUG_LOG("emcore_insert_event_for_sending_mails-handle[%d]", *handle);
+               *handle = new_handle;
 
        if (err_code != NULL)
                *err_code = error;
 
-       /* EM_DEBUG_FUNC_BEGIN(); */
+       EM_DEBUG_LOG("Finish with [%d]", ret);
        return ret;
 }
 
 
-static int emcore_retrieve_send_event(email_event_t *event_data, int *err_code)
+INTERNAL_FUNC int emcore_retrieve_send_event(email_event_t **event_data, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN();
+       EM_DEBUG_FUNC_BEGIN("event_data[%p], err_code[%p]", event_data, err_code);
 
        int ret = false;
        int error = EMAIL_ERROR_NONE;
+       int q_length = 0;
+       email_event_t *poped = NULL;
+       email_event_t *head_event = NULL;
 
-       ENTER_RECURSIVE_CRITICAL_SECTION(_send_event_queue_lock);
-/* get a event_data if this queue is not empty */
-       if (g_send_event_que[g_send_event_que_idx].type)  {
-               memcpy(event_data, g_send_event_que+g_send_event_que_idx, sizeof(email_event_t));
-
-               if (event_data->status != EMAIL_EVENT_STATUS_WAIT) {
-                       memset(g_send_event_que+g_send_event_que_idx, 0x00, sizeof(email_event_t));
-                       g_send_active_que = 0;
-               }
-               else  {
-                       g_send_event_que[g_send_event_que_idx].status = EMAIL_EVENT_STATUS_STARTED;
-                       EM_DEBUG_LOG("g_send_event_que_idx[%d]", g_send_event_que_idx);
-                       g_send_active_que = g_send_event_que_idx;
-
-                       ret = true;
-               }
+       if (g_send_event_que);
+               q_length = g_queue_get_length(g_send_event_que);
 
-               if (++g_send_event_que_idx >= EVENT_QUEUE_MAX)
-                       g_send_event_que_idx = 1;
+       EM_DEBUG_LOG("SEND Q Length : [%d]", q_length);
 
-                       EM_DEBUG_LOG("\t g_send_event_que[%d].type = %d", g_send_active_que, g_send_event_que[g_send_active_que].type);
+       if (!q_length) {
+               error = EMAIL_ERROR_EVENT_QUEUE_EMPTY;
+               EM_DEBUG_LOG_DEV("SEND QUEUE is empty"); 
+               goto FINISH_OFF;
        }
-       else  {
-                       EM_DEBUG_LOG("\t send event_data queue is empty...");
-                       g_send_active_que = 0;
+
+       while(1) {
+               head_event = (email_event_t *)g_queue_peek_head(g_send_event_que);
+               if (!head_event) {
                        error = EMAIL_ERROR_EVENT_QUEUE_EMPTY;
+                       EM_DEBUG_LOG("SEND QUEUE is empty");
+                       break;
+               }
+               if (head_event->status != EMAIL_EVENT_STATUS_WAIT) {
+                       EM_DEBUG_LOG("EVENT STATUS [%d]", head_event->status);
+                       poped = g_queue_pop_head(g_send_event_que);
+                       if (poped) {
+                               emcore_return_send_handle(poped->handle);
+                               emcore_free_event(poped);
+                               EM_SAFE_FREE(poped);
+                       } else {
+                               error = EMAIL_ERROR_EVENT_QUEUE_EMPTY;
+                               EM_DEBUG_LOG("SEND QUEUE is empty");
+                               break;
+                       }
+               } else {
+                       head_event->status = EMAIL_EVENT_STATUS_STARTED;
+                       *event_data = head_event;
+                       ret = true;
+                       break;
+               }
        }
 
-       LEAVE_RECURSIVE_CRITICAL_SECTION(_send_event_queue_lock);
+FINISH_OFF:
 
        if (err_code != NULL)
                *err_code = error;
 
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
        return ret;
 }
 
-
-void* thread_func_branch_command_for_sending_mails(void *arg)
+/* finish api event_data loop */
+INTERNAL_FUNC int emcore_send_event_loop_stop(int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN();
-       int err = EMAIL_ERROR_NONE;
-       email_event_t event_data;
-       email_session_t *session = NULL;
+    EM_DEBUG_FUNC_BEGIN();
 
-       if (!emstorage_open(&err))  {
-               EM_DEBUG_EXCEPTION("\t emstorage_open falied - %d", err);
-               return NULL;
-       }
+       if (err_code != NULL)
+               *err_code = EMAIL_ERROR_NONE;
 
-       while (g_send_event_loop) {
-               if (!emcore_get_empty_session(&session))
-                       EM_DEBUG_EXCEPTION("\t SEND THREAD emcore_get_empty_session failed...");
+       if (!g_send_srv_thread)          {
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_UNKNOWN;
+               return false;
+       }
 
-               if (!emcore_retrieve_send_event(&event_data, NULL))  {
-                       EM_DEBUG_LOG(">>>> waiting for send event_data>>>>>>>>>");
-#ifdef __FEATURE_LOCAL_ACTIVITY__
-                       if (send_thread_run && g_save_local_activity_run) {
-                               emstorage_account_tbl_t *account_list = NULL;
-                               int count = 0, i;
-                               if (!emstorage_get_account_list(&count, &account_list, true, true, &err)) {
-                                       EM_DEBUG_LOG("\t emstorage_get_account_list failed - %d", err);
-                               }
-                               else {
-                                       for (i = 0; i < count; i++) {
-                                               if (emcore_save_local_activity_sync(account_list[i].account_id, &err)) {
-                                                       EM_DEBUG_LOG("Found local activity...!");
-                                                       EM_DEBUG_LOG("Resetting g_save_local_activity_run ");
-                                                       g_save_local_activity_run = 0;
-                                                       emcore_clear_session(session);
-                                               }
-                                       }
+       /* stop event_data loop */
+       g_send_event_loop = 0;
 
-                                       emstorage_free_account(&account_list, count, &err);
+       emcore_cancel_all_send_mail_thread(err_code);
 
-                                       if (!g_save_local_activity_run) {
-                                               continue;
-                                       }
-                               }
-                       }
-#endif
-                       send_thread_run = 0;
+       WAKE_CONDITION_VARIABLE(_send_event_available_signal);          /*  MUST BE HERE */
 
-                       ENTER_CRITICAL_SECTION(_send_event_available_lock);
-                       SLEEP_CONDITION_VARIABLE(_send_event_available_signal, _send_event_available_lock);
-                       LEAVE_CRITICAL_SECTION(_send_event_available_lock);
-               }
-               else {
-                       EM_DEBUG_LOG(">>>>>>>>>>>>>>Got SEND event_data>>>>>>>>>>>>>>>>");
-                       send_thread_run = 1;
-                       g_client_run = 1;
+       /* wait for thread finished */
+       THREAD_JOIN(g_send_srv_thread);
 
-                       if (!emnetwork_check_network_status( &err))  {
-                               EM_DEBUG_EXCEPTION("emnetwork_check_network_status failed [%d]", err);
+       g_queue_free(g_send_event_que);
 
-                               emcore_show_user_message(event_data.event_param_data_4, EMAIL_ACTION_SEND_MAIL, err);
-                               if (!emcore_notify_network_event(NOTI_SEND_FAIL, event_data.account_id, NULL , event_data.event_param_data_4, err))
-                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_SEND_FAIL] Failed >>>> ");
-                               goto FINISH_OFF;
-                       }
+       g_send_srv_thread = 0;
 
-                       switch (event_data.type)  {
+       DELETE_RECURSIVE_CRITICAL_SECTION(_send_event_queue_lock);
+       DELETE_RECURSIVE_CRITICAL_SECTION(_send_event_handle_map_lock);
+       DELETE_CONDITION_VARIABLE(_send_event_available_signal);
 
-                               case EMAIL_EVENT_SEND_MAIL:
-                                       emdevice_set_dimming_on_off(false, NULL);
-
-                                       if (!emcore_send_mail(event_data.event_param_data_4, &err))
-                                               EM_DEBUG_EXCEPTION("emcore_send_mail failed [%d]", err);
-
-                                       emdevice_set_dimming_on_off(true, NULL);
-                                       break;
-
-                               case EMAIL_EVENT_SEND_MAIL_SAVED:  /* send mails to been saved in off-line mode */
-                                       emdevice_set_dimming_on_off(false, NULL);
-
-                                       if (!emcore_send_saved_mail(event_data.account_id, event_data.event_param_data_3, &err))
-                                               EM_DEBUG_EXCEPTION("emcore_send_saved_mail failed - %d", err);
-
-                                       emdevice_set_dimming_on_off(true, NULL);
-                                       break;
-
-#ifdef __FEATURE_LOCAL_ACTIVITY__
-
-                               case EMAIL_EVENT_LOCAL_ACTIVITY: {
-                                       emdevice_set_dimming_on_off(false, NULL);
-                                       emstorage_activity_tbl_t *local_activity = NULL;
-                                       int activity_id_count = 0;
-                                       int activity_chunk_count = 0;
-                                       int *activity_id_list = NULL;
-                                       int i = 0;
-
-                                       if (false == emstorage_get_activity_id_list(event_data.account_id, &activity_id_list, &activity_id_count, ACTIVITY_SAVEMAIL, ACTIVITY_DELETEMAIL_SEND, true, &err)) {
-                                               EM_DEBUG_EXCEPTION("emstorage_get_activity_id_list failed [%d]", err);
-                                       }
-                                       else {
-                                               for (i = 0; i < activity_id_count; ++i) {
-                                                       if ((false == emstorage_get_activity(event_data.account_id, activity_id_list[i], &local_activity, &activity_chunk_count, true,  &err)) || (NULL == local_activity) || (0 == activity_chunk_count)) {
-                                                               EM_DEBUG_EXCEPTION(" emstorage_get_activity Failed [ %d] or local_activity is NULL [%p] or activity_chunk_count is 0[%d]", err, local_activity, activity_chunk_count);
-                                                       }
-                                                       else {
-                                                               EM_DEBUG_LOG("Found local activity type - %d", local_activity[0].activity_type);
-                                                               switch (local_activity[0].activity_type) {
-                                                                       case ACTIVITY_SAVEMAIL:  {
-                                                                               if (!emcore_sync_mail_from_client_to_server(event_data.account_id, local_activity[0].mail_id, &err)) {
-                                                                                       EM_DEBUG_EXCEPTION("emcore_sync_mail_from_client_to_server failed - %d ", err);
-                                                                               }
-                                                                       }
-                                                                       break;
-
-                                                                       case ACTIVITY_DELETEMAIL_SEND:                          /* New Activity Type Added for Race Condition and Crash Fix */ {
-                                                                               if (!emcore_delete_mail(local_activity[0].account_id,
-                                                                                                                               &local_activity[0].mail_id,
-                                                                                                                               EMAIL_DELETE_FOR_SEND_THREAD,
-                                                                                                                               true,
-                                                                                                                               EMAIL_DELETED_BY_COMMAND,
-                                                                                                                               false,
-                                                                                                                               &err))  {
-                                                                                       EM_DEBUG_LOG("\t emcore_delete_mail failed - %d", err);
-                                                                               }
-                                                                       }
-                                                                       break;
-
-                                                                       default:  {
-                                                                               EM_DEBUG_LOG(">>>> No such Local Activity Handled by this thread [ %d ] >>> ", local_activity[0].activity_type);
-                                                                       }
-                                                                       break;
-                                                               }
-
-                                                               emstorage_free_local_activity(&local_activity, activity_chunk_count, NULL);
-
-                                                               if (g_save_local_activity_run == 1) {
-                                                                       EM_DEBUG_LOG(" Network event_data found.. Local sync Stopped..! ");
-                                                                       break;
-                                                               }
-                                                       }
-
-                                               }
-                                               if (false == emstorage_free_activity_id_list(activity_id_list, &err)) {
-                                                       EM_DEBUG_LOG("emstorage_free_activity_id_list failed");
-                                               }
-                                       }
-
-                                       emdevice_set_dimming_on_off(true, NULL);
-                               }
-                               break;
-#endif /* __FEATURE_LOCAL_ACTIVITY__ */
-                               default:
-                                       EM_DEBUG_LOG("Others not supported by Send Thread..! [%d]", event_data.type);
-                                       break;
-                       }
-
-                       ENTER_RECURSIVE_CRITICAL_SECTION(_send_event_queue_lock);
-                       memset(g_send_event_que+g_send_active_que, 0x00, sizeof(email_event_t));
-                       LEAVE_RECURSIVE_CRITICAL_SECTION(_send_event_queue_lock);
-
-FINISH_OFF:
-                       ;
-               }
-               emcore_clear_session(session);
-       }
-
-       if (!emstorage_close(&err))
-               EM_DEBUG_EXCEPTION("emstorage_close falied [%d]", err);
-
-       EM_DEBUG_FUNC_END("err [%d]", err);
-       return NULL;
-}
-
-
-int event_handler_EMAIL_EVENT_SYNC_HEADER(int input_account_id, int input_mailbox_id, int handle_to_be_published, int *error)
-{
-       EM_DEBUG_FUNC_BEGIN("input_account_id [%d], input_mailbox_id [%d], handle_to_be_published [%d], error[%p]", input_account_id, input_mailbox_id, handle_to_be_published, error);
-
-       int err = EMAIL_ERROR_NONE, sync_type = 0, ret = false;
-       int mailbox_count = 0, account_count = 0;
-       int counter, account_index;
-       int unread = 0, total_unread = 0;
-       emcore_uid_list *uid_list = NULL;
-       emstorage_account_tbl_t *account_tbl_array = NULL;
-       emstorage_mailbox_tbl_t *mailbox_tbl_target = NULL, *mailbox_tbl_list = NULL;
-#ifndef __FEATURE_KEEP_CONNECTION__
-       MAILSTREAM *stream = NULL;
-#endif
-       char mailbox_id_param_string[10] = {0,};
-       char *input_mailbox_id_str = NULL;
-
-       if (input_mailbox_id == 0)
-               sync_type = EMAIL_SYNC_ALL_MAILBOX;
-       else {
-               if (!emstorage_get_mailbox_by_id(input_mailbox_id, &mailbox_tbl_target) || !mailbox_tbl_target) {
-                       EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_id failed [%d]", err);
-                       goto FINISH_OFF;
-               }
-       }
-       if(mailbox_tbl_target)
-               SNPRINTF(mailbox_id_param_string, 10, "%d", mailbox_tbl_target->mailbox_id);
-
-       input_mailbox_id_str = (input_mailbox_id == 0)? NULL: mailbox_id_param_string;
-
-       if (!emcore_notify_network_event(NOTI_DOWNLOAD_START, input_account_id, input_mailbox_id_str, handle_to_be_published, 0))
-               EM_DEBUG_EXCEPTION("emcore_notify_network_event [ NOTI_DOWNLOAD_START] Failed >>>> ");
-
-       if (!emnetwork_check_network_status(&err)) {
-               EM_DEBUG_EXCEPTION("emnetwork_check_network_status failed [%d]", err);
-
-               if (!emcore_notify_network_event(NOTI_DOWNLOAD_FAIL, input_account_id, input_mailbox_id_str, handle_to_be_published, err))
-                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_FAIL] Failed >>>> ");
-       }
-       else {
-               if (sync_type != EMAIL_SYNC_ALL_MAILBOX) {      /* Sync only particular mailbox */
-
-                       if ((err = emcore_update_sync_status_of_account(input_account_id, SET_TYPE_SET, SYNC_STATUS_SYNCING)) != EMAIL_ERROR_NONE)
-                               EM_DEBUG_EXCEPTION("emcore_update_sync_status_of_account failed [%d]", err);
-
-                       if (!emcore_sync_header(mailbox_tbl_target, NULL, &uid_list, &unread, &err)) {
-                               EM_DEBUG_EXCEPTION("emcore_sync_header failed [%d]", err);
-                               if (!emcore_notify_network_event(NOTI_DOWNLOAD_FAIL, mailbox_tbl_target->account_id, mailbox_id_param_string, handle_to_be_published, err))
-                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [NOTI_DOWNLOAD_FAIL] Failed >>>> ");
-                       }
-                       else {
-                               EM_DEBUG_LOG("emcore_sync_header succeeded [%d]", err);
-                               if (!emcore_notify_network_event(NOTI_DOWNLOAD_FINISH, mailbox_tbl_target->account_id, mailbox_id_param_string, handle_to_be_published, 0))
-                                       EM_DEBUG_EXCEPTION("emcore_notify_network_event [NOTI_DOWNLOAD_FINISH] Failed >>>> ");
-                       }
-
-                       total_unread += unread;
-
-                       if (total_unread > 0 && (err = emcore_update_sync_status_of_account(input_account_id, SET_TYPE_UNION, SYNC_STATUS_HAVE_NEW_MAILS)) != EMAIL_ERROR_NONE)
-                               EM_DEBUG_EXCEPTION("emcore_update_sync_status_of_account failed [%d]", err);
-
-                       if (!emcore_finalize_sync(input_account_id, &err))
-                               EM_DEBUG_EXCEPTION("emcore_finalize_sync failed [%d]", err);
-               }
-               else /*  All Foder */ {
-                       EM_DEBUG_LOG(">>>> SYNC ALL MAILBOX ");
-                       /*  Sync of all mailbox */
-
-                       if (input_account_id == ALL_ACCOUNT) {
-                               if ((err = emcore_update_sync_status_of_account(ALL_ACCOUNT, SET_TYPE_SET, SYNC_STATUS_SYNCING)) != EMAIL_ERROR_NONE)
-                                       EM_DEBUG_EXCEPTION("emcore_update_sync_status_of_account failed [%d]", err);
-
-                               if (!emstorage_get_account_list(&account_count, &account_tbl_array , true, false, &err)) {
-                                       EM_DEBUG_EXCEPTION("emstorage_get_account_list failed [ %d ] ", err);
-                                       if (!emcore_notify_network_event(NOTI_DOWNLOAD_FAIL, input_account_id, NULL,  handle_to_be_published, err))
-                                               EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_FAIL] Failed >>>> ");
-                                       goto FINISH_OFF;
-                               }
-                       }
-                       else {
-                               EM_DEBUG_LOG("Sync all mailbox of an account[%d].", input_account_id);
-
-                               if ((err = emcore_update_sync_status_of_account(input_account_id, SET_TYPE_SET, SYNC_STATUS_SYNCING)) != EMAIL_ERROR_NONE)
-                                       EM_DEBUG_EXCEPTION("emcore_update_sync_status_of_account failed [%d]", err);
-
-                               if (!emstorage_get_account_by_id(input_account_id, EMAIL_ACC_GET_OPT_DEFAULT, &account_tbl_array, true, &err)) {
-                                       EM_DEBUG_EXCEPTION("emstorage_get_account_by_id failed [ %d ] ", err);
-                                       if (!emcore_notify_network_event(NOTI_DOWNLOAD_FAIL, input_account_id, input_mailbox_id_str, handle_to_be_published, err))
-                                               EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_FAIL] Failed >>>> ");
-                                       goto FINISH_OFF;
-                               }
-                               account_count = 1;
-                       }
-
-                       for (account_index = 0 ; account_index < account_count; account_index++) {
-                               if (account_tbl_array[account_index].incoming_server_type == EMAIL_SERVER_TYPE_ACTIVE_SYNC) {
-                                       EM_DEBUG_LOG("account[%d] is for ActiveSync. Skip  ", account_index);
-                                       continue;
-                               }
-
-                               if (!emstorage_get_mailbox_list(account_tbl_array[account_index].account_id, 0, EMAIL_MAILBOX_SORT_BY_TYPE_ASC, &mailbox_count, &mailbox_tbl_list, true, &err) || mailbox_count <= 0) {
-                                       EM_DEBUG_EXCEPTION("emstorage_get_mailbox failed [%d]", err);
-
-                                       if (!emcore_notify_network_event(NOTI_DOWNLOAD_FAIL, account_tbl_array[account_index].account_id, input_mailbox_id_str, handle_to_be_published, err))
-                                               EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_FAIL] Failed >>>> ");
-
-                                       continue;
-                               }
-
-                               EM_DEBUG_LOG("emcore_get_mailbox_list_to_be_sync returns [%d] mailboxes", mailbox_count);
-
-                               if (mailbox_count > 0) {
-#ifndef __FEATURE_KEEP_CONNECTION__
-                                       if (account_tbl_array[account_index].incoming_server_type == EMAIL_SERVER_TYPE_IMAP4) {
-                                               memset(mailbox_id_param_string, 0, 10);
-                                               SNPRINTF(mailbox_id_param_string, 10, "%d", mailbox_tbl_list[0].mailbox_id);
-                                               if (!emcore_connect_to_remote_mailbox(account_tbl_array[account_index].account_id, mailbox_tbl_list[0].mailbox_id, (void **)&stream, &err))  {
-                                                       EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed [%d]", err);
-                                                       if (err == EMAIL_ERROR_LOGIN_FAILURE)
-                                                               EM_DEBUG_EXCEPTION("EMAIL_ERROR_LOGIN_FAILURE ");
-                                                       /* continue; */
-                                                       if (!emcore_notify_network_event(NOTI_DOWNLOAD_FAIL, account_tbl_array[account_index].account_id, mailbox_id_param_string,  handle_to_be_published, err))
-                                                               EM_DEBUG_EXCEPTION(" emcore_notify_network_event [NOTI_DOWNLOAD_FAIL] Failed >>>> ");
-                                                       continue;
-                                               }
-                                               EM_DEBUG_LOG("emcore_connect_to_remote_mailbox returns [%d] : ", err);
-                                       }
-                                       else
-                                               stream = NULL;
-#endif
-                               }
-
-                               for (counter = 0; counter < mailbox_count; counter++) {
-
-                                       EM_DEBUG_LOG("maiblox_name [%s], mailbox_id [%d], mailbox_type [%d]", mailbox_tbl_list[counter].mailbox_name, mailbox_tbl_list[counter].mailbox_id, mailbox_tbl_list[counter].mailbox_type);
-
-                                       if ( mailbox_tbl_list[counter].mailbox_type == EMAIL_MAILBOX_TYPE_ALL_EMAILS
-                                                       || mailbox_tbl_list[counter].mailbox_type == EMAIL_MAILBOX_TYPE_TRASH
-                                               /*|| mailbox_tbl_list[counter].mailbox_type == EMAIL_MAILBOX_TYPE_SPAMBOX */)
-                                               EM_DEBUG_LOG("Skipped for all emails or trash");
-                                       else if (!mailbox_tbl_list[counter].local_yn) {
-                                               EM_DEBUG_LOG("[%s] Syncing...", mailbox_tbl_list[counter].mailbox_name);
-#ifdef __FEATURE_KEEP_CONNECTION__
-                                               if (!emcore_sync_header((mailbox_tbl_list + counter) , NULL, &uid_list, &unread, &err)) {
-#else /*  __FEATURE_KEEP_CONNECTION__ */
-                                               if (!emcore_sync_header((mailbox_tbl_list + counter) , (void *)stream, &uid_list, &unread, &err)) {
-#endif /*  __FEATURE_KEEP_CONNECTION__ */
-                                                       EM_DEBUG_EXCEPTION("emcore_sync_header for %s(mailbox_id = %d) failed [%d]", mailbox_tbl_list[counter].mailbox_name, mailbox_tbl_list[counter].mailbox_id, err);
-
-#ifndef __FEATURE_KEEP_CONNECTION__
-                                                       if (err == EMAIL_ERROR_CONNECTION_BROKEN || err == EMAIL_ERROR_NO_SUCH_HOST || err == EMAIL_ERROR_SOCKET_FAILURE || err == EMAIL_ERROR_LOGIN_FAILURE)
-                                                               stream = NULL;    /*  Don't retry to connect for broken connection. It might cause crash.  */
-#endif /*  __FEATURE_KEEP_CONNECTION__ */
-                                                       memset(mailbox_id_param_string, 0, 10);
-                                                       SNPRINTF(mailbox_id_param_string, 10, "%d", mailbox_tbl_list[counter].mailbox_id);
-                                                       if (!emcore_notify_network_event(NOTI_DOWNLOAD_FAIL, account_tbl_array[account_index].account_id, mailbox_id_param_string,  handle_to_be_published, err))
-                                                               EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_FAIL] Failed >>>> ");
-
-                                                       break;
-                                               }
-                                       }
-                                       total_unread  += unread;
-                               }
-
-                               EM_DEBUG_LOG("Sync for account_id(%d) is completed....!", account_tbl_array[account_index].account_id);
-                               if ((err == EMAIL_ERROR_NONE) && !emcore_notify_network_event(NOTI_DOWNLOAD_FINISH, account_tbl_array[account_index].account_id, NULL, handle_to_be_published, 0))
-                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_FINISH] Failed >>>> ");
-
-                               if ((total_unread > 0) && (err = emcore_update_sync_status_of_account(account_tbl_array[account_index].account_id, SET_TYPE_UNION, SYNC_STATUS_HAVE_NEW_MAILS)) != EMAIL_ERROR_NONE)
-                                       EM_DEBUG_EXCEPTION("emcore_update_sync_status_of_account failed [%d]", err);
-
-                               if (!emcore_finalize_sync(account_tbl_array[account_index].account_id, &err))
-                                       EM_DEBUG_EXCEPTION("emcore_finalize_sync failed [%d]", err);
-#ifndef __FEATURE_KEEP_CONNECTION__
-                               if (stream)  {
-                                       emcore_close_mailbox(0, stream);
-                                       stream = NULL;
-                               }
-#endif
-                               if (mailbox_tbl_list) {
-                                       emstorage_free_mailbox(&mailbox_tbl_list, mailbox_count, NULL);
-                                       mailbox_tbl_list = NULL;
-                                       mailbox_count = 0;
-                               }
-                       }
-               }
-
-               ret = true;
-
-FINISH_OFF:
-
-#ifndef __FEATURE_KEEP_CONNECTION__
-               if (stream)
-                       emcore_close_mailbox(0, stream);
-#endif
-               if(mailbox_tbl_target)
-                       emstorage_free_mailbox(&mailbox_tbl_target, 1, NULL);
-
-               if (mailbox_tbl_list)
-                       emstorage_free_mailbox(&mailbox_tbl_list, mailbox_count, NULL);
-
-               if (account_tbl_array)
-                       emstorage_free_account(&account_tbl_array, account_count, NULL);
-       }
-
-       EM_DEBUG_FUNC_END();
-       return ret;
-}
-
-int event_handler_EMAIL_EVENT_VALIDATE_AND_CREATE_ACCOUNT(email_account_t *account, int handle_to_be_published, int *error)
-{
-       EM_DEBUG_FUNC_BEGIN("account [%p]", account);
-       int err, ret = false;
-
-       if(!account) {
-               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
-               err = EMAIL_ERROR_INVALID_PARAM;
-               goto FINISH_OFF;
-       }
-
-       EM_DEBUG_LOG("incoming_server_address  :  %s", account->incoming_server_address);
-
-       if (!emnetwork_check_network_status(&err)) {
-               emcore_delete_account_from_unvalidated_account_list(account->account_id);
-               EM_DEBUG_EXCEPTION("emnetwork_check_network_status failed [%d]", err);
-               if (!emcore_notify_network_event(NOTI_VALIDATE_AND_CREATE_ACCOUNT_FAIL, account->account_id, NULL,  handle_to_be_published, err))
-                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_VALIDATE_ACCOUNT_FAIL] Failed >>>> ");
-               goto FINISH_OFF;
-       }
-       else {
-               EM_DEBUG_LOG("incoming_server_address : %s", account->incoming_server_address);
-
-               if (!emcore_validate_account_with_account_info(account, &err)) {
-                       emcore_delete_account_from_unvalidated_account_list(account->account_id);
-                       EM_DEBUG_EXCEPTION("emcore_validate_account_with_account_info failed err :  %d", err);
-                       if (err == EMAIL_ERROR_CANCELLED) {
-                               EM_DEBUG_EXCEPTION(" notify  :  NOTI_VALIDATE_AND_CREATE_ACCOUNT_CANCEL ");
-                               if (!emcore_notify_network_event(NOTI_VALIDATE_AND_CREATE_ACCOUNT_CANCEL, account->account_id, NULL,  handle_to_be_published, err))
-                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_VALIDATE_AND_CREATE_ACCOUNT_CANCEL] Failed");
-                               goto FINISH_OFF;
-                       }
-                       else
-                               goto FINISH_OFF;
-               }
-               else {
-                       emcore_delete_account_from_unvalidated_account_list(account->account_id);
-
-                       if (emcore_create_account(account, &err) == false)       {
-                               EM_DEBUG_EXCEPTION(" emdaemon_create_account failed - %d", err);
-                               goto FINISH_OFF;
-                       }
-
-                       emcore_init_account_reference();
-
-                       EM_DEBUG_LOG("incoming_server_type [%d]", account->incoming_server_type);
-
-                       if ((EMAIL_SERVER_TYPE_IMAP4 == account->incoming_server_type)) {
-                               if (!emcore_sync_mailbox_list(account->account_id, "", handle_to_be_published, &err))  {
-                                       EM_DEBUG_EXCEPTION("emcore_get_mailbox_list_to_be_sync failed [%d]", err);
-                                       /*  delete account whose mailbox couldn't be obtained from server */
-                                       emcore_delete_account(account->account_id, NULL);
-                                       goto FINISH_OFF;
-                               }
-                       }
-
-                       EM_DEBUG_LOG("validating and creating an account are succeeded for account id  [%d]  err [%d]", account->account_id, err);
-                       if (!emcore_notify_network_event(NOTI_VALIDATE_AND_CREATE_ACCOUNT_FINISH, account->account_id, NULL,  handle_to_be_published, err))
-                               EM_DEBUG_EXCEPTION("emcore_notify_network_event [ NOTI_VALIDATE_ACCOUNT_FINISH] Success");
-               }
-       }
-
-       ret = true;
-
-FINISH_OFF:
-       if (ret == false && err != EMAIL_ERROR_CANCELLED && account) {
-               if (!emcore_notify_network_event(NOTI_VALIDATE_AND_CREATE_ACCOUNT_FAIL, account->account_id, NULL,  handle_to_be_published, err))
-                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_VALIDATE_AND_CREATE_ACCOUNT_FAIL] Failed");
-       }
-
-       if (error)
-               *error = err;
-
-       EM_DEBUG_FUNC_END();
-       return ret;
-}
-
-int event_handler_EMAIL_EVENT_VALIDATE_ACCOUNT_EX(email_account_t *input_account, int input_handle_to_be_published)
-{
-       EM_DEBUG_FUNC_BEGIN("input_account [%p]", input_account);
-       int err = EMAIL_ERROR_NONE;
-
-       if(!input_account) {
-               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
-               err = EMAIL_ERROR_INVALID_PARAM;
-               goto FINISH_OFF;
-       }
-
-       EM_DEBUG_LOG("incoming_server_address [%s]", input_account->incoming_server_address);
-
-       if (!emnetwork_check_network_status(&err)) {
-               emcore_delete_account_from_unvalidated_account_list(input_account->account_id);
-               EM_DEBUG_EXCEPTION("emnetwork_check_network_status failed [%d]", err);
-               if (!emcore_notify_network_event(NOTI_VALIDATE_AND_CREATE_ACCOUNT_FAIL, input_account->account_id, NULL, input_handle_to_be_published, err))
-                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_VALIDATE_ACCOUNT_FAIL] Failed >>>> ");
-               goto FINISH_OFF;
-       }
-       else {
-               EM_DEBUG_LOG("incoming_server_address : %s", input_account->incoming_server_address);
-
-               if (!emcore_validate_account_with_account_info(input_account, &err)) {
-                       emcore_delete_account_from_unvalidated_account_list(input_account->account_id);
-
-                       EM_DEBUG_EXCEPTION("emcore_validate_account_with_account_info failed err :  %d", err);
-
-                       if (err == EMAIL_ERROR_CANCELLED) {
-                               EM_DEBUG_EXCEPTION(" notify  :  NOTI_VALIDATE_ACCOUNT_CANCEL ");
-                               if (!emcore_notify_network_event(NOTI_VALIDATE_ACCOUNT_CANCEL, input_account->account_id, NULL, input_handle_to_be_published, err))
-                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_VALIDATE_ACCOUNT_CANCEL] Failed");
-                               goto FINISH_OFF;
-                       }
-                       else
-                               goto FINISH_OFF;
-               }
-               else {
-                       emcore_delete_account_from_unvalidated_account_list(input_account->account_id);
-
-                       EM_DEBUG_LOG("validating an account are succeeded for account id  [%d]  err [%d]", input_account->account_id, err);
-                       if (!emcore_notify_network_event(NOTI_VALIDATE_ACCOUNT_FINISH, input_account->account_id, NULL, input_handle_to_be_published, err))
-                               EM_DEBUG_EXCEPTION("emcore_notify_network_event [ NOTI_VALIDATE_ACCOUNT_FINISH] Success");
-               }
-       }
-
-FINISH_OFF:
-       if (err != EMAIL_ERROR_NONE && err != EMAIL_ERROR_CANCELLED && input_account) {
-               if (!emcore_notify_network_event(NOTI_VALIDATE_ACCOUNT_FAIL, input_account->account_id, NULL, input_handle_to_be_published, err))
-                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_VALIDATE_ACCOUNT_FAIL] Failed");
-       }
-
-       EM_DEBUG_FUNC_END("err[%d]", err);
-       return err;
-}
-
-int event_handler_EMAIL_EVENT_VALIDATE_AND_UPDATE_ACCOUNT(int account_id, email_account_t *new_account_info, int handle_to_be_published, int *error)
-{
-       EM_DEBUG_FUNC_BEGIN("account_id [%d], new_account_info [%p]", account_id, new_account_info);
-       int err, ret = false;
-       emstorage_account_tbl_t *old_account_tbl = NULL, *new_account_tbl = NULL;
-
-       if (!new_account_info) {
-               EM_DEBUG_EXCEPTION("Invalid Parameter");
-               err = EMAIL_ERROR_INVALID_PARAM;
-               goto FINISH_OFF;
-       }
-
-       if (!emnetwork_check_network_status(&err))  {
-               EM_DEBUG_EXCEPTION("emnetwork_check_network_status failed [%d]", err);
-
-               if (!emcore_notify_network_event(NOTI_VALIDATE_AND_UPDATE_ACCOUNT_FAIL, new_account_info->account_id, NULL,  handle_to_be_published, err))
-                       EM_DEBUG_EXCEPTION("emcore_notify_network_event [ NOTI_VALIDATE_AND_UPDATE_ACCOUNT_FAIL] Failed >>>> ");
-               goto FINISH_OFF;
-       }
-       else  {
-               EM_DEBUG_LOG("incoming_server_address: (%s)", new_account_info->incoming_server_address);
-
-               if (!emcore_validate_account_with_account_info(new_account_info, &err)) {
-                       EM_DEBUG_EXCEPTION("emcore_validate_account_with_account_info() failed err :  %d", err);
-                       if (err == EMAIL_ERROR_CANCELLED) {
-                               EM_DEBUG_EXCEPTION(" notify  :  NOTI_VALIDATE_AND_CREATE_ACCOUNT_CANCEL ");
-                               if (!emcore_notify_network_event(NOTI_VALIDATE_AND_UPDATE_ACCOUNT_CANCEL, new_account_info->account_id, NULL,  handle_to_be_published, err))
-                                       EM_DEBUG_EXCEPTION("emcore_notify_network_event [ NOTI_VALIDATE_AND_UPDATE_ACCOUNT_CANCEL] Failed");
-                               goto FINISH_OFF;
-                       }
-                       else {
-                               goto FINISH_OFF;
-                       }
-               }
-               else {
-                       if (!emstorage_get_account_by_id(account_id, WITHOUT_OPTION, &old_account_tbl, true, &err)) {
-                               EM_DEBUG_EXCEPTION("emstorage_get_account_by_id failed [%d]", err);
-                               /* goto FINISH_OFF; */
-                       }
-
-                       new_account_tbl = em_malloc(sizeof(emstorage_account_tbl_t));
-                       if (!new_account_tbl) {
-                               EM_DEBUG_EXCEPTION("allocation failed [%d]", err);
-                               goto FINISH_OFF;
-                       }
-
-                       em_convert_account_to_account_tbl(new_account_info, new_account_tbl);
-
-                       if (emstorage_update_account(account_id, new_account_tbl, true, &err)) {
-                               emcore_init_account_reference();
-                       }
-
-                       EM_DEBUG_LOG("validating and updating an account are succeeded for account id [%d], err [%d]", new_account_info->account_id, err);
-                       if (!emcore_notify_network_event(NOTI_VALIDATE_AND_UPDATE_ACCOUNT_FINISH, new_account_info->account_id, NULL,  handle_to_be_published, err))
-                               EM_DEBUG_EXCEPTION(" emcore_notify_network_event [NOTI_VALIDATE_AND_UPDATE_ACCOUNT_FINISH] Success");
-               }
-       }
-
-       ret = true;
-
-FINISH_OFF:
-       if (old_account_tbl)
-               emstorage_free_account(&old_account_tbl, 1, NULL);
-       if (new_account_tbl)
-               emstorage_free_account(&new_account_tbl, 1, NULL);
-
-       if (ret == false && err != EMAIL_ERROR_CANCELLED && new_account_info) {
-               if (!emcore_notify_network_event(NOTI_VALIDATE_AND_UPDATE_ACCOUNT_FAIL, new_account_info->account_id, NULL,  handle_to_be_published, err))
-                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_VALIDATE_AND_CREATE_ACCOUNT_FAIL] Failed");
-       }
-
-       if (error)
-               *error = err;
-
-       EM_DEBUG_FUNC_END();
-       return ret;
-}
-
-int event_handler_EMAIL_EVENT_SET_MAIL_SLOT_SIZE(int account_id, int mailbox_id, int new_slot_size, int handle_to_be_published, int *error)
-{
-       EM_DEBUG_FUNC_BEGIN();
-
-       emcore_set_mail_slot_size(account_id, mailbox_id, new_slot_size, error);
-
-       EM_DEBUG_FUNC_END();
-       return true;
-}
-
-static int event_handler_EMAIL_EVENT_EXPUNGE_MAILS_DELETED_FLAGGED(int input_account_id, int input_mailbox_id)
-{
-       EM_DEBUG_FUNC_BEGIN("input_account_id [%d], input_mailbox_id [%d]", input_account_id, input_mailbox_id);
-       int err = EMAIL_ERROR_NONE;
-
-       if ( (err = emcore_expunge_mails_deleted_flagged_from_remote_server(input_account_id, input_mailbox_id)) != EMAIL_ERROR_NONE) {
-               EM_DEBUG_EXCEPTION("emcore_expunge_mails_deleted_flagged_from_remote_server failed [%d]", err);
-               goto FINISH_OFF;
-       }
-
-       if ( (err = emcore_expunge_mails_deleted_flagged_from_local_storage(input_mailbox_id)) != EMAIL_ERROR_NONE) {
-               EM_DEBUG_EXCEPTION("emcore_expunge_mails_deleted_flagged_from_local_storage failed [%d]", err);
-               goto FINISH_OFF;
-       }
-
-FINISH_OFF:
-
-       EM_DEBUG_FUNC_END("err [%d]", err);
-       return err;
-}
-
-#ifdef __FEATURE_LOCAL_ACTIVITY__
-int event_handler_EMAIL_EVENT_LOCAL_ACTIVITY(int account_id, int *error)
-{
-       EM_DEBUG_FUNC_BEGIN();
-
-       int err = EMAIL_ERROR_NONE;
-       email_mailbox_t mailbox;
-       emstorage_activity_tbl_t *local_activity = NULL;
-       int activity_id_count = 0;
-       int activity_chunk_count = 0;
-       int *activity_id_list = NULL;
-       int i = 0;
-
-       if (!emnetwork_check_network_status(&err))
-               EM_DEBUG_EXCEPTION("emnetwork_check_network_status failed [%d]", err);
-       else {
-               if (false == emstorage_get_activity_id_list(account_id, &activity_id_list, &activity_id_count, ACTIVITY_DELETEMAIL, ACTIVITY_COPYMAIL, true, &err)) {
-                       EM_DEBUG_EXCEPTION("emstorage_get_activity_id_list failed [%d]", err);
-               }
-               else {
-                       for (i = 0; i < activity_id_count; ++i) {
-                               if ((false == emstorage_get_activity(account_id , activity_id_list[i], &local_activity, &activity_chunk_count, true,  &err)) || (NULL == local_activity) || (0 == activity_chunk_count))
-                                       EM_DEBUG_EXCEPTION(" emstorage_get_activity Failed [ %d] or local_activity is NULL [%p] or activity_chunk_count is 0[%d]", err, local_activity, activity_chunk_count);
-                               else {
-                                       EM_DEBUG_LOG("Found local activity type - %d", local_activity[0].activity_type);
-                                       switch (local_activity[0].activity_type) {
-                                               case ACTIVITY_MODIFYFLAG:  {
-                                                       if (emcore_sync_flag_with_server(local_activity[0].mail_id , &err))  {
-                                                               if (!emcore_delete_activity(&local_activity[0], &err))
-                                                                       EM_DEBUG_EXCEPTION(">>>>>>Local Activity [ACTIVITY_MODIFYFLAG] [%d] ", err);
-                                                       }
-                                               }
-                                               break;
-
-                                               case ACTIVITY_DELETEMAIL:
-                                               case ACTIVITY_MOVEMAIL:
-                                               case ACTIVITY_MODIFYSEENFLAG:
-                                               case ACTIVITY_COPYMAIL:  {
-
-                                                       int j = 0, k = 0;
-                                                       int total_mail_ids = activity_chunk_count;
-
-                                                       int *mail_id_list = NULL;
-
-                                                       mail_id_list = (int *)em_malloc(sizeof(int) * total_mail_ids);
-
-                                                       if (NULL == mail_id_list) {
-                                                               EM_DEBUG_EXCEPTION("malloc failed... ");
-                                                               break;
-                                                       }
-
-                                                       do {
-
-                                                               for (j = 0; j < BULK_OPERATION_COUNT && (k < total_mail_ids); ++j, ++k)
-                                                                       mail_id_list[j] = local_activity[k].mail_id;
-
-                                                               switch (local_activity[k-1].activity_type) {
-                                                                       case ACTIVITY_DELETEMAIL:  {
-                                                                               if (!emcore_delete_mail(local_activity[k-1].account_id,
-                                                                                                                               mail_id_list,
-                                                                                                                               j,
-                                                                                                                               EMAIL_DELETE_LOCAL_AND_SERVER,
-                                                                                                                               EMAIL_DELETED_BY_COMMAND,
-                                                                                                                               false,
-                                                                                                                               &err))
-                                                                                       EM_DEBUG_LOG("\t emcore_delete_mail failed - %d", err);
-                                                                       }
-                                                                       break;
-
-                                                                       case ACTIVITY_MOVEMAIL:  {
-                                                                               if (!emcore_move_mail_on_server_ex(local_activity[k-1].account_id ,
-                                                                                                                                                  local_activity[k-1].src_mbox,
-                                                                                                                                                  mail_id_list,
-                                                                                                                                                  j,
-                                                                                                                                                  local_activity[k-1].dest_mbox,
-                                                                                                                                                  &err))
-                                                                                       EM_DEBUG_LOG("\t emcore_move_mail_on_server_ex failed - %d", err);
-                                                                       }
-                                                                       break;
-                                                                       case ACTIVITY_MODIFYSEENFLAG:  {
-                                                                               int seen_flag = atoi(local_activity[0].src_mbox);
-                                                                               if (!emcore_sync_seen_flag_with_server_ex(mail_id_list, j , seen_flag , &err)) /* local_activity[0].src_mbox points to the seen flag */
-                                                                                       EM_DEBUG_EXCEPTION("\t emcore_sync_seen_flag_with_server_ex failed - %d", err);
-                                                                       }
-                                                                       break;
-                                                               }
-
-                                                       } while (k < total_mail_ids);
-
-                                                       EM_SAFE_FREE(mail_id_list);
-                                               }
-
-                                               break;
-
-                                               default:
-                                                       EM_DEBUG_LOG(">>>> No such Local Activity Handled by this thread [ %d ] >>> ", local_activity[0].activity_type);
-                                               break;
-                                       }
-
-                                       emstorage_free_local_activity(&local_activity, activity_chunk_count, NULL);
-
-                                       if (g_local_activity_run == 1) {
-                                               EM_DEBUG_LOG(" Network event_data found.. Local sync Stopped..! ");
-                                               break;
-                                       }
-                               }
-                       }
-               }
-       }
-       if (activity_id_list) {
-               if (false == emstorage_free_activity_id_list(activity_id_list, &err))
-                       EM_DEBUG_EXCEPTION("emstorage_free_activity_id_list failed");
-       }
-
-       if (error)
-               *error = err;
-
-       EM_DEBUG_FUNC_END();
-
-       return true;
-}
-#endif /* __FEATURE_LOCAL_ACTIVITY__ */
-
-int event_handler_EMAIL_EVENT_DOWNLOAD_BODY(int account_id, int mail_id, int option, int handle_to_be_published, int *error)
-{
-       EM_DEBUG_FUNC_BEGIN();
-
-       int err = EMAIL_ERROR_NONE;
-       email_mailbox_t mailbox;
-
-       memset(&mailbox, 0x00, sizeof(mailbox));
-       mailbox.account_id = account_id;
-
-       if (!emnetwork_check_network_status(&err))  {
-               EM_DEBUG_EXCEPTION("emnetwork_check_network_status failed [%d]", err);
-
-               emcore_notify_network_event(NOTI_DOWNLOAD_BODY_FAIL, mail_id, NULL, handle_to_be_published, err);
-       }
-       else  {
-               if (!emcore_download_body_multi_sections_bulk(NULL,
-                       mailbox.account_id,
-                       mail_id,
-                       option >> 1,            /*  0 :  silent, 1 :  verbose */
-                       option & 0x01,          /*  0 :  without attachments, 1 :  with attachments */
-                       NO_LIMITATION,
-                       handle_to_be_published,
-                       &err))
-                       EM_DEBUG_EXCEPTION("emcore_download_body_multi_sections_bulk failed - %d", err);
-       }
-
-       if (error)
-               *error = err;
-
-       EM_DEBUG_FUNC_END();
-       return true;
-}
-
-int event_handler_EMAIL_EVENT_DOWNLOAD_ATTACHMENT(int account_id, int mail_id, int attachment_no, int handle_to_be_published, int *error)
-{
-       EM_DEBUG_FUNC_BEGIN();
-
-       int err = EMAIL_ERROR_NONE;
-
-       EM_DEBUG_LOG("attachment_no is %d", attachment_no);
-
-       if (!emnetwork_check_network_status(&err))  {
-               EM_DEBUG_EXCEPTION("emnetwork_check_network_status failed [%d]", err);
-               emcore_notify_network_event(NOTI_DOWNLOAD_ATTACH_FAIL, mail_id, NULL, attachment_no, err);
-       }
-       else  {
-
-#ifdef __ATTACHMENT_OPTI__
-               if (!emcore_download_attachment_bulk(account_id, mail_id, attachment_no, &err))
-                       EM_DEBUG_EXCEPTION("\t emcore_download_attachment failed [%d]", err);
-#else
-               if (!emcore_download_attachment(account_id, mail_id, attachment_no, &err))
-                       EM_DEBUG_EXCEPTION("\t emcore_download_attachment failed [%d]", err);
-#endif
-       }
-
-       if (error)
-               *error = err;
-
-       EM_DEBUG_FUNC_END();
-       return true;
-}
-
-int event_handler_EMAIL_EVENT_SYNC_FLAGS_FIELD_TO_SERVER(int mail_ids[], int num, email_flags_field_type field_type, int value, int *error)
-{
-       EM_DEBUG_FUNC_BEGIN();
-
-       int err = EMAIL_ERROR_NONE;
-
-       if (!emnetwork_check_network_status(&err))
-               EM_DEBUG_EXCEPTION("dnet_init failed [%d]", err);
-       else if (!emcore_sync_flags_field_with_server(mail_ids, num, field_type, value, &err))
-               EM_DEBUG_EXCEPTION("emcore_sync_flags_field_with_server failed [%d]", err);
-
-       if (error)
-               *error = err;
-
-       EM_DEBUG_FUNC_END();
-       return true;
-}
-
-int event_handler_EMAIL_EVENT_VALIDATE_ACCOUNT(int account_id, int handle_to_be_published, int *error)
-{
-       EM_DEBUG_FUNC_BEGIN();
-
-       int err = EMAIL_ERROR_NONE;
-
-       if (!emnetwork_check_network_status(&err))  {
-               EM_DEBUG_EXCEPTION("emnetwork_check_network_status failed [%d]", err);
-
-               if (!emcore_notify_network_event(NOTI_VALIDATE_ACCOUNT_FAIL, account_id, NULL,  handle_to_be_published, err))
-                       EM_DEBUG_EXCEPTION("emcore_notify_network_event [ NOTI_VALIDATE_ACCOUNT_FAIL] Failed >>>>");
-       }
-       else  {
-
-               if (!emcore_validate_account(account_id, &err)) {
-                       EM_DEBUG_EXCEPTION("emcore_validate_account failed account id  :  %d  err :  %d", account_id, err);
-
-                       if (err == EMAIL_ERROR_CANCELLED) {
-                               EM_DEBUG_EXCEPTION("notify  :  NOTI_VALIDATE_ACCOUNT_CANCEL ");
-                               if (!emcore_notify_network_event(NOTI_VALIDATE_ACCOUNT_CANCEL, account_id, NULL,  handle_to_be_published, err))
-                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_VALIDATE_ACCOUNT_CANCEL] Failed >>>> ");
-                       }
-                       else {
-                               if (!emcore_notify_network_event(NOTI_VALIDATE_ACCOUNT_FAIL, account_id, NULL,  handle_to_be_published, err))
-                                       EM_DEBUG_EXCEPTION("emcore_notify_network_event [ NOTI_VALIDATE_ACCOUNT_FAIL] Failed >>>> ");
-                       }
-               }
-               else {
-                       email_account_t *account_ref = NULL;
-                       account_ref = emcore_get_account_reference(account_id);
-
-                       if (account_ref) {
-                               EM_DEBUG_LOG("account_ref->incoming_server_type[%d]", account_ref->incoming_server_type);
-                               if ( EMAIL_SERVER_TYPE_IMAP4 == account_ref->incoming_server_type ) {
-                                       if (!emcore_check_thread_status())
-                                               err = EMAIL_ERROR_CANCELLED;
-                                       else if (!emcore_sync_mailbox_list(account_id, "", handle_to_be_published, &err))
-                                               EM_DEBUG_EXCEPTION("\t emcore_get_mailbox_list_to_be_sync falied - %d", err);
-                               }
-
-                               if (err > 0) {
-                                       EM_DEBUG_EXCEPTION("emcore_validate_account succeeded account id  :  %d  err :  %d", account_id, err);
-                                       if (!emcore_notify_network_event(NOTI_VALIDATE_ACCOUNT_FINISH, account_id, NULL,  handle_to_be_published, err))
-                                               EM_DEBUG_EXCEPTION("emcore_notify_network_event [ NOTI_VALIDATE_ACCOUNT_FINISH] Success >>>>");
-                               }
-
-                               emcore_free_account(account_ref);
-                               EM_SAFE_FREE(account_ref);
-                       }
-               }
-       }
-
-       if (error)
-               *error = err;
-
-       EM_DEBUG_FUNC_END();
-       return true;
-}
-
-int event_handler_EMAIL_EVENT_UPDATE_MAIL(email_mail_data_t *input_mail_data, email_attachment_data_t *input_attachment_data_list, int input_attachment_count, email_meeting_request_t* input_meeting_request, int input_from_eas, int handle_to_be_published)
-{
-       EM_DEBUG_FUNC_BEGIN("input_mail_data[%p], input_attachment_data_list[%p], input_attachment_count[%d], input_meeting_request[%p], input_from_eas[%d]", input_mail_data, input_attachment_data_list, input_attachment_count, input_meeting_request, input_from_eas);
-       int err = EMAIL_ERROR_NONE;
-
-       if ( (err = emcore_update_mail(input_mail_data, input_attachment_data_list, input_attachment_count, input_meeting_request, input_from_eas)) != EMAIL_ERROR_NONE)
-               EM_DEBUG_EXCEPTION("emcore_update_mail failed [%d]", err);
-
-       if(input_mail_data)
-               emcore_free_mail_data_list(&input_mail_data, 1);
-
-       if(input_attachment_data_list)
-               emcore_free_attachment_data(&input_attachment_data_list, input_attachment_count, NULL);
-
-       if(input_meeting_request)
-               emstorage_free_meeting_request(input_meeting_request);
-
-       EM_DEBUG_FUNC_END("err [%d", err);
-       return err;
-}
-int event_handler_EMAIL_EVENT_SAVE_MAIL(int input_account_id, int input_mail_id, int input_handle_to_be_published)
-{
-       EM_DEBUG_FUNC_BEGIN("input_account_id [%d] input_mail_id [%d] input_handle_to_be_published [%d]", input_account_id, input_mail_id, input_handle_to_be_published);
-       int err = EMAIL_ERROR_NONE;
-
-       err = emcore_sync_mail_from_client_to_server(input_mail_id);
-
-       EM_DEBUG_FUNC_END("err [%d]", err);
-       return err;
-}
-
-int event_handler_EMAIL_EVENT_MOVE_MAIL(int account_id, int *mail_ids, int mail_id_count, int dest_mailbox_id, int src_mailbox_id, int handle_to_be_published, int *error)
-{
-       EM_DEBUG_FUNC_BEGIN();
-       int err = EMAIL_ERROR_NONE, ret = false;
-       email_account_t *account_ref = NULL;
-
-       if (!(account_ref = emcore_get_account_reference(account_id))) {
-               EM_DEBUG_EXCEPTION("emcore_get_account_reference failed [%d]", account_id);
-               err = EMAIL_ERROR_INVALID_ACCOUNT;
-               goto FINISH_OFF;
-       }
-
-       /* Move mail local */
-       /*
-       if (!emcore_mail_move(mail_ids, mail_id_count, dest_mailbox.mailbox_name, EMAIL_MOVED_BY_COMMAND, 0, &err)) {
-               EM_DEBUG_EXCEPTION("emcore_mail_move failed [%d]", err);
-               goto FINISH_OFF;
-       }
-       */
-
-       if (account_ref->incoming_server_type == EMAIL_SERVER_TYPE_IMAP4) {
-               /* Move mail on server */
-               if (!emnetwork_check_network_status(&err))
-                       EM_DEBUG_EXCEPTION("emnetwork_check_network_status failed [%d]", err);
-               else {
-#ifdef __FEATURE_BULK_DELETE_MOVE_UPDATE_REQUEST_OPTI__
-                       if (!emcore_move_mail_on_server_ex(account_id , src_mailbox_id, mail_ids, mail_id_count, dest_mailbox_id, &err))
-                               EM_DEBUG_EXCEPTION("emcore_move_mail_on_server_ex failed - %d", err);
-#else
-                       if (!emcore_move_mail_on_server(account_id , src_mailbox_id, mail_ids, mail_id_count, dest_mailbox_id, &err))
-                               EM_DEBUG_EXCEPTION("\t emcore_move_mail_on_server failed - %d", err);
-#endif
-               }
-       }
-
-       ret = true;
-FINISH_OFF:
-       EM_SAFE_FREE(mail_ids); /*prevent 33693*/
-
-       if (account_ref) {
-               emcore_free_account(account_ref);
-               EM_SAFE_FREE(account_ref);
-       }
-
-       if (error)
-               *error = err;
-
-       EM_DEBUG_FUNC_END();
-       return ret;
-}
-
-int event_handler_EMAIL_EVENT_DELETE_MAILBOX(int mailbox_id, int on_server, int recursive, int handle_to_be_published, int *error)
-{
-       EM_DEBUG_FUNC_BEGIN("mailbox_id[%d] on_server[%d] recursive[%d] handle_to_be_published[%d] error[%p]",  mailbox_id, on_server, recursive, handle_to_be_published, error);
-       int err = EMAIL_ERROR_NONE;
-
-       if (!emnetwork_check_network_status(&err))
-               EM_DEBUG_EXCEPTION("emnetwork_check_network_status failed [%d]", err);
-       else  {
-               if (( err = emcore_delete_mailbox(mailbox_id, on_server, recursive)) != EMAIL_ERROR_NONE)
-                       EM_DEBUG_EXCEPTION("emcore_delete failed [%d]", err);
-       }
-
-       if (error)
-               *error = err;
+       if (err_code != NULL)
+               *err_code = EMAIL_ERROR_NONE;
 
-       EM_DEBUG_FUNC_END();
        return true;
 }
 
-int event_handler_EMAIL_EVENT_CREATE_MAILBOX(int account_id, char *mailbox_name, char *mailbox_alias, int mailbox_type, int on_server, int handle_to_be_published, int *error)
+/* finish api event_data loop */
+INTERNAL_FUNC int emcore_stop_event_loop(int *err_code)
 {
        EM_DEBUG_FUNC_BEGIN();
-       int err = EMAIL_ERROR_NONE;
-       email_mailbox_t mailbox;
-
-       memset(&mailbox, 0x00, sizeof(mailbox));
 
-       mailbox.account_id = account_id;
-       mailbox.mailbox_name = mailbox_name;
-       mailbox.alias = mailbox_alias;
-       mailbox.mailbox_type = mailbox_type;
+       if (err_code != NULL)
+               *err_code = EMAIL_ERROR_NONE;
 
-       if (!emnetwork_check_network_status(&err))  {
-               EM_DEBUG_EXCEPTION("emnetwork_check_network_status failed [%d]", err);
-       }
-       else  {
-               if (!emcore_create_mailbox(&mailbox, on_server, &err))
-                       EM_DEBUG_EXCEPTION("emcore_create failed - %d", err);
+       if (!g_srv_thread) {
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_UNKNOWN;
+               return false;
        }
 
+       /* stop event_data loop */
+       g_event_loop = 0;
 
-       if (error)
-               *error = err;
+       /* pthread_kill(g_srv_thread, SIGINT); */
+       emcore_cancel_all_thread(err_code);
 
-       EM_DEBUG_FUNC_END();
-       return true;
-}
+       WAKE_CONDITION_VARIABLE(_event_available_signal);
 
-int event_handler_EMAIL_EVENT_SYNC_MAIL_FLAG_TO_SERVER(int mail_id, int *error)
-{
-       EM_DEBUG_FUNC_BEGIN("mail_id [%d], error [%p]", mail_id, error);
+       /* wait for thread finished */
+       THREAD_JOIN(g_srv_thread);
 
-       int err = EMAIL_ERROR_NONE;
+       g_queue_free(g_event_que);
 
-       if (!emnetwork_check_network_status(&err))
-               EM_DEBUG_EXCEPTION("emnetwork_check_network_status failed [%d]", err);
-       else {
-               if (!emcore_sync_flag_with_server(mail_id, &err))
-                       EM_DEBUG_EXCEPTION("emcore_sync_flag_with_server failed [%d]", err);
-#ifdef __FEATURE_LOCAL_ACTIVITY__
-               else {
-                       emstorage_activity_tbl_t new_activity;
-                       memset(&new_activity, 0x00, sizeof(emstorage_activity_tbl_t));
-                       new_activity.activity_type = ACTIVITY_MODIFYFLAG;
-                       new_activity.account_id    = event_data.account_id;
-                       new_activity.mail_id       = event_data.event_param_data_4;
-                       new_activity.dest_mbox     = NULL;
-                       new_activity.server_mailid = NULL;
-                       new_activity.src_mbox      = NULL;
-
-                       if (!emcore_delete_activity(&new_activity, &err))
-                               EM_DEBUG_EXCEPTION(">>>>>>Local Activity [ACTIVITY_MODIFYFLAG] [%d] ", err);
-               }
-#endif /*  __FEATURE_LOCAL_ACTIVITY__ */
-       }
+       g_srv_thread = 0;
 
-       if (error)
-               *error = err;
+       DELETE_RECURSIVE_CRITICAL_SECTION(_event_queue_lock);
+       DELETE_RECURSIVE_CRITICAL_SECTION(_event_handle_map_lock);
+       DELETE_RECURSIVE_CRITICAL_SECTION(_event_callback_table_lock);
+       DELETE_CONDITION_VARIABLE(_event_available_signal);
 
+       if (err_code != NULL)
+               *err_code = EMAIL_ERROR_NONE;
        EM_DEBUG_FUNC_END();
        return true;
 }
 
-int event_handler_EMAIL_EVENT_DELETE_MAIL_ALL(int input_account_id, int input_mailbox_id, int input_from_server, int *error)
-{
-       EM_DEBUG_FUNC_BEGIN("input_account_id [%d] input_mailbox_id [%d], input_from_server [%d], error [%p]", input_account_id, input_mailbox_id, input_from_server, error);
-       int err = EMAIL_ERROR_NONE;
-
-       if (!emcore_delete_all_mails_of_mailbox(input_account_id, input_mailbox_id, input_from_server, &err))
-               EM_DEBUG_EXCEPTION("emcore_delete_all_mails_of_mailbox failed [%d]", err);
-
-       if (error)
-               *error = err;
-
-       EM_DEBUG_FUNC_END("err [%d]", err);
-       return true;
-}
-
-int event_handler_EMAIL_EVENT_DELETE_MAIL(int account_id, int *mail_id_list, int mail_id_count, int *error)
+/* check thread status
+* 0 : stop job 1 : continue job
+*/
+INTERNAL_FUNC int emcore_check_thread_status()
 {
        EM_DEBUG_FUNC_BEGIN();
-       int err = EMAIL_ERROR_NONE;
-       int ret = false;
-       email_account_t *account_ref = NULL;
 
-       if (!(account_ref = emcore_get_account_reference(account_id))) {
-               EM_DEBUG_EXCEPTION("emcore_get_account_reference failed [%d]", account_id);
-               err = EMAIL_ERROR_INVALID_ACCOUNT;
-               goto FINISH_OFF;
-       }
+       int ret = false;
+       int q_length = 0;
+       email_event_t *active_event = NULL;
 
-       if (!emcore_delete_mail(account_id, mail_id_list, mail_id_count, EMAIL_DELETE_FROM_SERVER, EMAIL_DELETED_BY_COMMAND, false, &err)) {
-               EM_DEBUG_EXCEPTION("emcore_delete_mail failed [%d]", err);
-               goto FINISH_OFF;
-       }
+       ENTER_RECURSIVE_CRITICAL_SECTION(_event_queue_lock);
 
-       ret = true;
-FINISH_OFF:
+       if (g_event_que)
+               q_length = g_queue_get_length(g_event_que);
 
-       if (account_ref) {
-               emcore_free_account(account_ref);
-               EM_SAFE_FREE(account_ref);
+       if (q_length) {
+               active_event = (email_event_t *)g_queue_peek_head(g_event_que);
+               if (active_event) {
+                       if (active_event->status == EMAIL_EVENT_STATUS_STARTED)
+                               ret = true;
+                       else
+                               ret = false;
+               }
+       } else {
+               EM_DEBUG_LOG("Rcv Queue is empty [%d]", q_length);
+               ret = true;
        }
 
-       if (error)
-               *error = err;
-
-       EM_DEBUG_FUNC_END();
+       LEAVE_RECURSIVE_CRITICAL_SECTION(_event_queue_lock);
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
        return ret;
 }
 
-int event_hanlder_EMAIL_EVENT_SYNC_HEADER_OMA(int account_id, char *maibox_name, int handle_to_be_published, int *error)
-{
-       EM_DEBUG_FUNC_BEGIN();
-       int err = EMAIL_ERROR_NONE;
-
-       if (!emnetwork_check_network_status(&err))  {
-               EM_DEBUG_EXCEPTION("emnetwork_check_network_status failed [%d]", err);
-               if (!emcore_notify_network_event(NOTI_DOWNLOAD_FAIL, account_id, maibox_name,  0, err))
-                       EM_DEBUG_EXCEPTION("emcore_notify_network_event [NOTI_DOWNLOAD_FAIL] Failed");
-       }
-       else  {
-               EM_DEBUG_LOG("Sync of all mailbox");
-               if (!emcore_sync_mailbox_list(account_id, "", handle_to_be_published, &err))
-                       EM_DEBUG_EXCEPTION("emcore_sync_mailbox_list failed [%d]", err);
-       }
-
-       if (error)
-               *error = err;
-
-       EM_DEBUG_FUNC_END();
-       return true;
-}
-
-int event_handler_EMAIL_EVENT_SEARCH_ON_SERVER(int account_id, int mailbox_id, char *criteria, int handle_to_be_published, int *error)
+/* cancel a job  */
+INTERNAL_FUNC int emcore_cancel_thread(int handle, void *arg, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("account_id : [%d], mailbox_id : [%d], criteria : [%s]", account_id, mailbox_id, criteria);
+       EM_DEBUG_FUNC_BEGIN("handle[%d], arg[%p], err_code[%p]", handle, arg, err_code);
 
+       int ret = false;
        int err = EMAIL_ERROR_NONE;
+       int found = 0;
        int i = 0;
-       int mail_id = 0;
-       int thread_id = 0;
-       char temp_uid_string[20] = {0,};
-
-       emcore_uid_list uid_elem;
-       emstorage_mailbox_tbl_t *search_mailbox = NULL;
-       emstorage_mail_tbl_t *new_mail_tbl_data = NULL;
-
-       MAILSTREAM *stream = NULL;
-       MESSAGECACHE *mail_cache_element = NULL;
-       ENVELOPE *env = NULL;
-       emstorage_mailbox_tbl_t* local_mailbox = NULL;
-       char mailbox_id_param_string[10] = {0,};
-
-       if (account_id < 0 || mailbox_id == 0) {
-               EM_DEBUG_EXCEPTION("Invalid parameter");
-               err = EMAIL_ERROR_INVALID_PARAM;
-               goto FINISH_OFF;
-       }
-
-       if ( (err = emstorage_get_mailbox_by_id(mailbox_id, &local_mailbox)) != EMAIL_ERROR_NONE || !local_mailbox) {
-               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_id failed [%d]", err);
-               goto FINISH_OFF;
-       }
-
-       SNPRINTF(mailbox_id_param_string, 10, "%d", local_mailbox->mailbox_id);
-
-       if (!emcore_notify_network_event(NOTI_SEARCH_ON_SERVER_START, account_id, mailbox_id_param_string, handle_to_be_published, 0))
-               EM_DEBUG_EXCEPTION("emcore_notify_network_event [NOTI_SEARCH_ON_SERVER_START] failed >>>>");
-
-       if (!emnetwork_check_network_status(&err)) {
-               EM_DEBUG_EXCEPTION("emnetwork_check_network_status failed [%d]", err);
-               if (!emcore_notify_network_event(NOTI_SEARCH_ON_SERVER_FAIL, account_id, mailbox_id_param_string,  0, err))
-                       EM_DEBUG_EXCEPTION("emcore_notify_network_event [NOTI_DOWNLOAD_FAIL] Failed");
-               goto FINISH_OFF;
-       }
-
-       if (!emcore_connect_to_remote_mailbox(account_id, mailbox_id, (void **)&stream, &err)) {
-               EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed");
-               if (!emcore_notify_network_event(NOTI_SEARCH_ON_SERVER_FAIL, account_id, mailbox_id_param_string, handle_to_be_published, err))
-                       EM_DEBUG_EXCEPTION("emcore_notify_network_event [NOTI_SEARCH_ON_SERVER_FAIL] Failed >>>>");
-               goto FINISH_OFF;
-       }
-
-       if (!mail_search_full(stream, NIL, mail_criteria(criteria), SE_FREE)) {
-               EM_DEBUG_EXCEPTION("mail_search failed");
-               if (!emcore_notify_network_event(NOTI_SEARCH_ON_SERVER_FAIL, account_id, mailbox_id_param_string, handle_to_be_published, err))
-                       EM_DEBUG_EXCEPTION("emcore_notify_network_event [NOTI_SEARCH_ON_SERVER_FAIL] Failed >>>>");
-               goto FINISH_OFF;
-       }
+       int q_length = 0;
+       email_event_t *found_elm = NULL;
+       email_event_t *pop_elm = NULL;
 
-       for (i = 1; i <= stream->nmsgs; ++i) {
-               mail_cache_element = mail_elt(stream, i);
-               if (mail_cache_element->searched) {
-                       env = mail_fetchstructure_full(stream, i, NULL, FT_PEEK);
-
-                       memset(&uid_elem, 0x00, sizeof(uid_elem));
-
-                       uid_elem.msgno = mail_cache_element->msgno;
-                       SNPRINTF(temp_uid_string, 20, "%4lu", mail_cache_element->private.uid);
-                       uid_elem.uid = temp_uid_string;
-                       uid_elem.flag.seen = mail_cache_element->seen;
-
-                       if (!emcore_make_mail_tbl_data_from_envelope(stream, env, &uid_elem, &new_mail_tbl_data, &err) || !new_mail_tbl_data) {
-                               EM_DEBUG_EXCEPTION("emcore_make_mail_tbl_data_from_envelope failed [%d]", err);
-                               if (!emcore_notify_network_event(NOTI_SEARCH_ON_SERVER_FAIL, account_id, mailbox_id_param_string, handle_to_be_published, err))
-                                       EM_DEBUG_EXCEPTION("emcore_notify_network_event [NOTI_SEARCH_ON_SERVER_FAIL] Failed >>>>");
-                               goto FINISH_OFF;
-                       }
-
-                       search_mailbox = em_malloc(sizeof(emstorage_mailbox_tbl_t));
-                       if (search_mailbox == NULL) {
-                               EM_DEBUG_EXCEPTION("em_malloc failed");
-                               err = EMAIL_ERROR_OUT_OF_MEMORY;
-                               if (!emcore_notify_network_event(NOTI_SEARCH_ON_SERVER_FAIL, account_id, mailbox_id_param_string, handle_to_be_published, err))
-                                       EM_DEBUG_EXCEPTION("emcore_notify_network_event [NOTI_SEARCH_ON_SERVER_FAIL] Failed >>>>");
-                               goto FINISH_OFF;
-                       }
-
-                       search_mailbox->account_id = account_id;
-                       search_mailbox->mailbox_id = mailbox_id;
-                       search_mailbox->mailbox_name = EM_SAFE_STRDUP(EMAIL_SEARCH_RESULT_MAILBOX_NAME);
-                       search_mailbox->mailbox_type = EMAIL_MAILBOX_TYPE_SEARCH_RESULT;
-
-                       if ((err = emcore_add_mail_to_mailbox(search_mailbox, new_mail_tbl_data, &mail_id, &thread_id)) != EMAIL_ERROR_NONE) {
-                               EM_DEBUG_EXCEPTION("emcore_add_mail_to_mailbox failed [%d]", err);
-                               if (!emcore_notify_network_event(NOTI_SEARCH_ON_SERVER_FAIL, account_id, mailbox_id_param_string, handle_to_be_published, err))
-                                       EM_DEBUG_EXCEPTION("emcore_notify_network_event [NOTI_SEARCH_ON_SERVER_FAIL] Failed >>>>");
-                               goto FINISH_OFF;
-                       }
-                       memset(mailbox_id_param_string, 0, 10);
-                       SNPRINTF(mailbox_id_param_string, 10, "%d", search_mailbox->mailbox_id);
-                       if (!emcore_notify_storage_event(NOTI_MAIL_ADD, account_id, mail_id, mailbox_id_param_string, thread_id)) {
-                               EM_DEBUG_EXCEPTION("emcore_notify_storage_event [NOTI_MAIL_ADD] failed");
-                       }
-
-                       if (new_mail_tbl_data) {
-                               emstorage_free_mail(&new_mail_tbl_data, 1, NULL);
-                               new_mail_tbl_data = NULL;
-                       }
-               }
-       }
-
-       if (err == EMAIL_ERROR_NONE && !emcore_notify_network_event(NOTI_SEARCH_ON_SERVER_FINISH, account_id, NULL, handle_to_be_published, 0))
-               EM_DEBUG_EXCEPTION("emcore_notify_network_event[NOTI_SEARCH_ON_SERVER_FINISH] Failed >>>>>");
-
-FINISH_OFF:
-
-       if (search_mailbox != NULL)
-               emstorage_free_mailbox(&search_mailbox, 1, NULL);
-
-       if (new_mail_tbl_data)
-               emstorage_free_mail(&new_mail_tbl_data, 1, NULL);
-
-       if (local_mailbox)
-               emstorage_free_mailbox(&local_mailbox, 1, NULL);
-
-       if (error)
-               *error = err;
-
-       EM_DEBUG_FUNC_END();
-       return true;
-}
-
-static int event_handler_EMAIL_EVENT_RENAME_MAILBOX_ON_IMAP_SERVER(int input_account_id, int input_mailbox_id, char *input_old_mailbox_path, char *input_new_mailbox_path, char *input_new_mailbox_alias, int handle_to_be_published)
-{
-       EM_DEBUG_FUNC_BEGIN("input_account_id [%d], input_mailbox_id [%d], input_old_mailbox_path %s], input_new_mailbox_path [%s], input_new_mailbox_alias [%s], handle_to_be_published [%d]", input_account_id, input_mailbox_id, input_old_mailbox_path, input_new_mailbox_path, input_new_mailbox_alias, handle_to_be_published);
-       int err = EMAIL_ERROR_NONE;
+       ENTER_RECURSIVE_CRITICAL_SECTION(_event_queue_lock);
 
+       if (g_event_que)
+               q_length = g_queue_get_length(g_event_que);
 
-       if (err == EMAIL_ERROR_NONE) {
-               if ((err = emcore_rename_mailbox(input_mailbox_id, input_new_mailbox_path, input_new_mailbox_alias, true, true, handle_to_be_published)) != EMAIL_ERROR_NONE) {
-                       EM_DEBUG_EXCEPTION("emcore_rename_mailbox failed [%d]", err);
+       for (i = 0; i < q_length; i++) {
+               found_elm = (email_event_t *)g_queue_peek_nth(g_event_que, i);
+               if (found_elm->handle == handle) {
+                       EM_DEBUG_LOG("Found Queue element[%d] with handle[%d]", i, handle);
+                       found = 1;
+                       break;
                }
        }
 
-       EM_DEBUG_FUNC_END("err [%d]", err);
-       return err;
-}
-
-void* thread_func_branch_command(void *arg)
-{
-       EM_DEBUG_FUNC_BEGIN();
-
-       int err = EMAIL_ERROR_NONE;
-       int is_storage_full = false;
-       int noti_id = 0;
-       email_event_t event_data;
-       email_session_t *session = NULL;
-       emstorage_account_tbl_t *account_tbl = NULL;
-       int handle_to_be_published = 0;
-
-       if (!emstorage_open(&err))  {
-               EM_DEBUG_EXCEPTION("emstorage_open falied [%d]", err);
-               return false;
-       }
-
-       /* check that event_data loop is continuous */
-       while (emcore_event_loop_continue())  {
-               if (!emcore_get_empty_session(&session))
-                       EM_DEBUG_EXCEPTION("emcore_get_empty_session failed...");
-
-               /* get a event_data from event_data queue */
-               if (!emcore_retrieve_event(&event_data, NULL))  {       /*  no event_data pending */
-                       EM_DEBUG_LOG("For handle g_event_que[g_event_que_idx].type [%d], g_event_que_idx [%d]", g_event_que[g_event_que_idx].type, g_event_que_idx);
-#ifdef ENABLE_IMAP_IDLE_THREAD
-                       if ( !emnetwork_check_network_status(&err))  {
-                               EM_DEBUG_LOG(">>>> Data Networking ON ");
-                               if (g_client_run) {
-                                       if (g_imap_idle_thread_alive) {
-                                               /* emcore_kill_imap_idle_thread(NULL); */
-                                               /* emcore_create_imap_idle_thread(NULL); */
-                                       }
-                                       else {
-                                               if (!send_thread_run)
-                                                       emcore_create_imap_idle_thread(event_data.account_id, NULL);
-                                       }
-                               }
-                       }
-#endif /*  ENABLE_IMAP_IDLE_THREAD */
-#ifdef __FEATURE_LOCAL_ACTIVITY__
-                       /*  Local activity sync */
-                       if (g_client_run && g_local_activity_run) {
-                               emstorage_account_tbl_t *account_list = NULL;
-                               int count = 0, i;
-                               if (!emstorage_get_account_list(&count, &account_list, true, true, &err))
-                                       EM_DEBUG_EXCEPTION("emstorage_get_account_list failed [%d]", err);
-                               else {
-                                       for (i = 0; i < count; i++) {
-                                               if (emcore_local_activity_sync(account_list[i].account_id, &err)) {
-                                                       EM_DEBUG_LOG("Found local activity...!");
-                                                       EM_DEBUG_LOG("Resetting g_local_activity_run ");
-                                                       g_local_activity_run = 0;
-                                                       emcore_clear_session(session);
-                                               }
-                                       }
-
-                                       emstorage_free_account(&account_list, count, &err);
-
-                                       if (!g_local_activity_run)
-                                               continue;
-                               }
-                       }
-#endif
-
-                       recv_thread_run = 0;
-
-                       ENTER_CRITICAL_SECTION(_event_available_lock);
-                       SLEEP_CONDITION_VARIABLE(_event_available_signal, _event_available_lock);
-                       EM_DEBUG_LOG("Wake up by _event_available_signal");
-                       LEAVE_CRITICAL_SECTION(_event_available_lock);
-               }
-               else  {
-                       EM_DEBUG_LOG(">>>>>>>>>>>>>>> Got event_data !!! <<<<<<<<<<<<<<<");
-                       EM_DEBUG_LOG("For handle g_event_que_idx - %d", g_event_que_idx);
-
-                       if (g_event_que_idx == 1)
-                               handle_to_be_published = 31;
-                       else
-                               handle_to_be_published = g_event_que_idx - 1 ;
-
-                       EM_DEBUG_LOG("Handle to be Published  [%d]", handle_to_be_published);
-                       recv_thread_run = 1;
-                       g_client_run = 1;
-
-                       /*  Handling storage full */
-                       is_storage_full = false;
-                       if (event_data.type == EMAIL_EVENT_SYNC_HEADER || event_data.type == EMAIL_EVENT_SYNC_HEADER_OMA ||
-                               event_data.type == EMAIL_EVENT_DOWNLOAD_BODY || event_data.type == EMAIL_EVENT_DOWNLOAD_ATTACHMENT) {
-                               if (emcore_is_storage_full(&err) == true) {
-                                       EM_DEBUG_EXCEPTION("Storage is full");
-                                       switch (event_data.type) {
-                                               case EMAIL_EVENT_SYNC_HEADER:
-                                               case EMAIL_EVENT_SYNC_HEADER_OMA:
-                                                       noti_id = NOTI_DOWNLOAD_FAIL;
-                                                       break;
-                                               case EMAIL_EVENT_DOWNLOAD_BODY:
-                                                       noti_id = NOTI_DOWNLOAD_BODY_FAIL;
-                                                       break;
-                                               case EMAIL_EVENT_DOWNLOAD_ATTACHMENT:
-                                                       noti_id = NOTI_DOWNLOAD_ATTACH_FAIL;
-                                                       break;
-                                               default:
-                                                       break;
-                                       }
-
-                                       if (!emcore_notify_network_event(noti_id, event_data.account_id, NULL,  handle_to_be_published, err))
-                                               EM_DEBUG_EXCEPTION(" emcore_notify_network_event [NOTI_DOWNLOAD_FAIL] Failed >>>> ");
-                                       is_storage_full = true;
-                               }
-                       }
-
-                       emdevice_set_dimming_on_off(false, NULL);
-
-                       if (event_data.account_id > 0) {
-                               if (!emstorage_get_account_by_id(event_data.account_id, EMAIL_ACC_GET_OPT_DEFAULT, &account_tbl, false, &err)) {
-                                       EM_DEBUG_EXCEPTION("emstorage_get_account_by_id [%d]", err);
-                               }
-                       }
-
-                       if (account_tbl)
-                               EM_DEBUG_LOG("account_id : [%d], sync_disabled : [%d]", event_data.account_id, account_tbl->sync_disabled);
-
-                       if (!account_tbl || account_tbl->sync_disabled == 0) {
-                               switch (event_data.type)  {
-                                       case EMAIL_EVENT_SYNC_IMAP_MAILBOX:  /*  get imap mailbox list  */
-                                               if (!emcore_sync_mailbox_list(event_data.account_id, event_data.event_param_data_3, handle_to_be_published, &err))
-                                                       EM_DEBUG_EXCEPTION("emcore_sync_mailbox_list failed [%d]", err);
-                                               EM_SAFE_FREE(event_data.event_param_data_3);
-                                               break;
+       if (found) {
+               if (found_elm->status == EMAIL_EVENT_STATUS_WAIT) {
+                       fail_status_notify(found_elm, EMAIL_ERROR_CANCELLED);
 
-                                       case EMAIL_EVENT_SYNC_HEADER:  /*  synchronize mail header  */
-                                               if (is_storage_full == false)
-                                                       event_handler_EMAIL_EVENT_SYNC_HEADER(event_data.account_id, event_data.event_param_data_5, handle_to_be_published,  &err);
-                                               break;
-
-                                       case EMAIL_EVENT_SYNC_HEADER_OMA:  /*  synchronize mail header for OMA */
-                                               if (is_storage_full == false)
-                                                       event_hanlder_EMAIL_EVENT_SYNC_HEADER_OMA(event_data.account_id, event_data.event_param_data_1, handle_to_be_published, &err);
-                                               EM_SAFE_FREE(event_data.event_param_data_1);
-                                               break;
-
-                                       case EMAIL_EVENT_DOWNLOAD_BODY:  /*  download mail body  */
-                                               if (is_storage_full == false)
-                                                       event_handler_EMAIL_EVENT_DOWNLOAD_BODY(event_data.account_id, (int)event_data.event_param_data_4, (int)event_data.event_param_data_3, handle_to_be_published, &err);
-                                               event_data.event_param_data_3 = NULL;           /*  MUST BE */
-                                               break;
-
-                                       case EMAIL_EVENT_DOWNLOAD_ATTACHMENT:  /*  download attachment */
-                                               if (is_storage_full == false)
-                                                       event_handler_EMAIL_EVENT_DOWNLOAD_ATTACHMENT(event_data.account_id, (int)event_data.event_param_data_4, event_data.event_param_data_5, handle_to_be_published, &err);
-                                               break;
+                       switch (found_elm->type) {
 
-                                       case EMAIL_EVENT_SYNC_FLAGS_FIELD_TO_SERVER:  /*  Sync flags field */
-                                               event_handler_EMAIL_EVENT_SYNC_FLAGS_FIELD_TO_SERVER((int*)event_data.event_param_data_3, event_data.event_param_data_4 , event_data.event_param_data_5, event_data.event_param_data_6, &err);
-                                               EM_SAFE_FREE(event_data.event_param_data_3);
-                                               break;
+                               case EMAIL_EVENT_SEND_MAIL:
+                               case EMAIL_EVENT_SEND_MAIL_SAVED:
+                                       EM_DEBUG_LOG("EMAIL_EVENT_SEND_MAIL or EMAIL_EVENT_SEND_MAIL_SAVED");
+                                       if (!emcore_notify_network_event(NOTI_SEND_CANCEL, found_elm->account_id, NULL , found_elm->event_param_data_4, err))
+                                               EM_DEBUG_EXCEPTION("emcore_notify_network_event [ NOTI_SEND_CANCEL] Failed >>>>");
+                                       break;
 
-                                       case EMAIL_EVENT_DELETE_MAIL:  /*  delete mails */
-                                               event_handler_EMAIL_EVENT_DELETE_MAIL(event_data.account_id, (int*)event_data.event_param_data_3, event_data.event_param_data_4, &err);
-                                               EM_SAFE_FREE(event_data.event_param_data_3);
-                                               break;
+                               case EMAIL_EVENT_DOWNLOAD_BODY:
+                                       EM_DEBUG_LOG("EMAIL_EVENT_DOWNLOAD_BODY");
+                                       if (!emcore_notify_network_event(NOTI_DOWNLOAD_BODY_CANCEL, found_elm->account_id, NULL , found_elm->event_param_data_4, err))
+                                               EM_DEBUG_EXCEPTION("emcore_notify_network_event [ NOTI_DOWNLOAD_BODY_CANCEL] Failed >>>>");
+                                       break;
 
-                                       case EMAIL_EVENT_DELETE_MAIL_ALL:  /*  delete all mails */
-                                               event_handler_EMAIL_EVENT_DELETE_MAIL_ALL(event_data.account_id, event_data.event_param_data_4, (int)event_data.event_param_data_5, &err);
-                                               break;
-#ifdef __FEATURE_SYNC_CLIENT_TO_SERVER__
-                                       case EMAIL_EVENT_SYNC_MAIL_FLAG_TO_SERVER:
-                                               event_handler_EMAIL_EVENT_SYNC_MAIL_FLAG_TO_SERVER((int)event_data.event_param_data_4, &err);
-                                               break;
-#endif
+                               case EMAIL_EVENT_DOWNLOAD_ATTACHMENT:
+                                       EM_DEBUG_LOG("EMAIL_EVENT_DOWNLOAD_ATTACHMENT");
+                                       if (!emcore_notify_network_event(NOTI_DOWNLOAD_ATTACH_CANCEL, found_elm->event_param_data_4, NULL , found_elm->event_param_data_5, err))
+                                               EM_DEBUG_EXCEPTION("emcore_notify_network_event [ NOTI_DOWNLOAD_ATTACH_CANCEL] Failed >>>>");
+                                       break;
 
-                                       case EMAIL_EVENT_CREATE_MAILBOX:
-                                               event_handler_EMAIL_EVENT_CREATE_MAILBOX(event_data.account_id, event_data.event_param_data_1, event_data.event_param_data_2, GPOINTER_TO_INT(event_data.event_param_data_3), event_data.event_param_data_4, handle_to_be_published, &err);
-                                               EM_SAFE_FREE(event_data.event_param_data_1);
-                                               EM_SAFE_FREE(event_data.event_param_data_2);
-                                               break;
+                               case EMAIL_EVENT_SYNC_HEADER:
+                               case EMAIL_EVENT_SYNC_HEADER_OMA:
+                               case EMAIL_EVENT_SYNC_MAIL_FLAG_TO_SERVER:
+                               case EMAIL_EVENT_SYNC_FLAGS_FIELD_TO_SERVER:
+                                       EM_DEBUG_LOG("EMAIL_EVENT_SYNC_HEADER, EMAIL_EVENT_DOWNLOAD_ATTACHMENT");
+                                       break;
 
-                                       case EMAIL_EVENT_DELETE_MAILBOX:
-                                               event_handler_EMAIL_EVENT_DELETE_MAILBOX(event_data.event_param_data_4, event_data.event_param_data_5, event_data.event_param_data_6,handle_to_be_published, &err);
-                                               break;
+                               case EMAIL_EVENT_VALIDATE_ACCOUNT:
+                                       EM_DEBUG_LOG("validate account waiting: cancel account id[%d]", found_elm->account_id);
+                                       if (!emcore_notify_network_event(NOTI_VALIDATE_ACCOUNT_CANCEL, found_elm->account_id, NULL , found_elm->event_param_data_4, err))
+                                               EM_DEBUG_EXCEPTION("emcore_notify_network_event [ NOTI_VALIDATE_ACCOUNT_CANCEL] Failed >>>>");
+                                       break;
 
-                                       case EMAIL_EVENT_SAVE_MAIL:
-                                               err = event_handler_EMAIL_EVENT_SAVE_MAIL(event_data.account_id, event_data.event_param_data_4, handle_to_be_published);
-                                               break;
+                               case EMAIL_EVENT_DELETE_MAIL:
+                               case EMAIL_EVENT_DELETE_MAIL_ALL:
+                               case EMAIL_EVENT_SYNC_IMAP_MAILBOX:
+                               case EMAIL_EVENT_SAVE_MAIL:
+                               case EMAIL_EVENT_MOVE_MAIL:
+                               case EMAIL_EVENT_CREATE_MAILBOX:
+                               case EMAIL_EVENT_DELETE_MAILBOX:
+                               case EMAIL_EVENT_SET_MAIL_SLOT_SIZE:
+                               case EMAIL_EVENT_SEARCH_ON_SERVER:
+                               case EMAIL_EVENT_RENAME_MAILBOX_ON_IMAP_SERVER:
+                                       EM_DEBUG_LOG("EMAIL_EVENT_DELETE_MAIL, EMAIL_EVENT_SYNC_IMAP_MAILBOX");
+                                       break;
 
-                                       case EMAIL_EVENT_MOVE_MAIL:
-                                               event_handler_EMAIL_EVENT_MOVE_MAIL(event_data.account_id, (int  *)event_data.event_param_data_3, event_data.event_param_data_4, event_data.event_param_data_5, event_data.event_param_data_8, handle_to_be_published, &err);
-                                               event_data.event_param_data_3 = NULL; /*prevent 33693*/
-                                               break;
+                               default:
+                                       break;
+                       }
 
-                                       case EMAIL_EVENT_VALIDATE_ACCOUNT:
-                                               event_handler_EMAIL_EVENT_VALIDATE_ACCOUNT(event_data.account_id, handle_to_be_published, &err);
-                                               break;
+                       pop_elm = (email_event_t *)g_queue_pop_nth(g_event_que, i);
+                       if (pop_elm) {
+                               emcore_return_handle(pop_elm->handle);
+                               emcore_free_event(pop_elm);
+                               EM_SAFE_FREE(pop_elm);
+                       } else {
+                               EM_DEBUG_LOG("Failed to g_queue_pop_nth [%d] element", i);
+                       }
+               } else {
+                       switch (found_elm->type) {
 
-                                       case EMAIL_EVENT_VALIDATE_AND_CREATE_ACCOUNT: {
-                                                       email_account_t *account = (email_account_t *)event_data.event_param_data_1;
-                                                       event_handler_EMAIL_EVENT_VALIDATE_AND_CREATE_ACCOUNT(account, handle_to_be_published, &err);
-                                                       if(account) {
-                                                               emcore_free_account(account);
-                                                               EM_SAFE_FREE(account);
-                                                       }
-                                               }
-                                               break;
+                               case EMAIL_EVENT_SYNC_HEADER:
+                                       EM_DEBUG_LOG("EMAIL_EVENT_SYNC_HEADER");
+                                       if (!emcore_notify_network_event(NOTI_DOWNLOAD_CANCEL, found_elm->account_id, NULL , found_elm->event_param_data_4, err))
+                                               EM_DEBUG_EXCEPTION("emcore_notify_network_event [ NOTI_DOWNLOAD_CANCEL] Failed >>>>");
+                                       if ((err = emcore_update_sync_status_of_account(found_elm->account_id, SET_TYPE_MINUS, SYNC_STATUS_SYNCING)) != EMAIL_ERROR_NONE)
+                                               EM_DEBUG_EXCEPTION("emcore_update_sync_status_of_account failed [%d]", err);
+                                       break;
 
-                                       case EMAIL_EVENT_VALIDATE_ACCOUNT_EX: {
-                                                       email_account_t *account = (email_account_t *)event_data.event_param_data_1;
-                                                       err = event_handler_EMAIL_EVENT_VALIDATE_ACCOUNT_EX(account, handle_to_be_published);
-                                                       if(account) {
-                                                               emcore_free_account(account);
-                                                               EM_SAFE_FREE(account);
-                                                       }
-                                               }
-                                               break;
+                               case EMAIL_EVENT_DOWNLOAD_ATTACHMENT:
+                                       EM_DEBUG_LOG("EMAIL_EVENT_DOWNLOAD_ATTACHMENT");
+                                       if (!emcore_notify_network_event(NOTI_DOWNLOAD_ATTACH_CANCEL, found_elm->event_param_data_4, NULL , found_elm->event_param_data_5, err))
+                                               EM_DEBUG_EXCEPTION("emcore_notify_network_event [ NOTI_DOWNLOAD_ATTACH_CANCEL] Failed >>>>");
+                                       break;
 
-                                       case EMAIL_EVENT_VALIDATE_AND_UPDATE_ACCOUNT: {
-                                                       email_account_t *account = (email_account_t *)event_data.event_param_data_1;
-                                                       event_handler_EMAIL_EVENT_VALIDATE_AND_UPDATE_ACCOUNT(event_data.account_id, account, handle_to_be_published, &err);
-                                                       emcore_free_account(account);
-                                                       EM_SAFE_FREE(account);
-                                               }
-                                               break;
+                               default:
+                                       break;
+                       }
+                       found_elm->status = EMAIL_EVENT_STATUS_CANCELED;
+               }
 
-                                       case EMAIL_EVENT_UPDATE_MAIL:
-                                               event_handler_EMAIL_EVENT_UPDATE_MAIL((email_mail_data_t*)event_data.event_param_data_1, (email_attachment_data_t*)event_data.event_param_data_2, event_data.event_param_data_4, (email_meeting_request_t*)event_data.event_param_data_3, event_data.event_param_data_5, handle_to_be_published);
+               ret = true;
+       }
 
-                                               event_data.event_param_data_1 = NULL;
-                                               event_data.event_param_data_2 = NULL;
-                                               event_data.event_param_data_3 = NULL;
-                                               break;
+       LEAVE_RECURSIVE_CRITICAL_SECTION(_event_queue_lock);
 
-                                       case EMAIL_EVENT_SET_MAIL_SLOT_SIZE:
-                                               event_handler_EMAIL_EVENT_SET_MAIL_SLOT_SIZE(event_data.account_id, event_data.event_param_data_4, event_data.event_param_data_5, handle_to_be_published, &err);
-                                               break;
+       if (err_code != NULL)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
 
-                                       case EMAIL_EVENT_EXPUNGE_MAILS_DELETED_FLAGGED:
-                                               err = event_handler_EMAIL_EVENT_EXPUNGE_MAILS_DELETED_FLAGGED(event_data.account_id, event_data.event_param_data_4);
-                                               break;
+/* cancel all job  */
+INTERNAL_FUNC int emcore_cancel_all_thread(int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("err_code[%p]", err_code);
 
-       #ifdef __FEATURE_LOCAL_ACTIVITY__
-                                       case EMAIL_EVENT_LOCAL_ACTIVITY:
-                                               event_handler_EMAIL_EVENT_LOCAL_ACTIVITY(event_data.account_id, &err);
-                                               break;
-       #endif /* __FEATURE_LOCAL_ACTIVITY__*/
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       int q_length = 0;
+       int i = 0;
+       email_event_t *pop_elm = NULL;
 
-                                       case EMAIL_EVENT_SEARCH_ON_SERVER:
-                                               event_handler_EMAIL_EVENT_SEARCH_ON_SERVER(event_data.account_id, event_data.event_param_data_4, (char *)event_data.event_param_data_1, handle_to_be_published, &err);
-                                               EM_SAFE_FREE(event_data.event_param_data_1);
-                                               break;
+       ENTER_RECURSIVE_CRITICAL_SECTION(_event_queue_lock);
 
-                                       case EMAIL_EVENT_RENAME_MAILBOX_ON_IMAP_SERVER:
-                                               err = event_handler_EMAIL_EVENT_RENAME_MAILBOX_ON_IMAP_SERVER(event_data.account_id, event_data.event_param_data_4, (char*)event_data.event_param_data_1, (char*)event_data.event_param_data_2, (char*)event_data.event_param_data_3, handle_to_be_published);
-                                               EM_SAFE_FREE(event_data.event_param_data_1);
-                                               EM_SAFE_FREE(event_data.event_param_data_2);
-                                               EM_SAFE_FREE(event_data.event_param_data_3);
-                                               break;
+       if (g_event_que);
+               q_length = g_queue_get_length(g_event_que);
 
-                                       default:
-                                               break;
-                               }
-                       }
+       for (i = 0; i < q_length; i++) {
+               pop_elm = (email_event_t *)g_queue_peek_nth(g_event_que, i);
 
-                       if (account_tbl) {
-                               emstorage_free_account(&account_tbl, 1, NULL);
-                               account_tbl = NULL;
-                       }
+               if (pop_elm->status == EMAIL_EVENT_STATUS_WAIT) {
 
-                       if (!emcore_notify_response_to_api(event_data.type, handle_to_be_published, err))
-                               EM_DEBUG_EXCEPTION("emcore_notify_response_to_api failed");
+                       fail_status_notify(pop_elm, EMAIL_ERROR_CANCELLED);
 
-                       emdevice_set_dimming_on_off(true, NULL);
-                       em_flush_memory();
+                       switch (pop_elm->type) {
 
-                       switch (event_data.type)  {
                                case EMAIL_EVENT_SEND_MAIL:
                                case EMAIL_EVENT_SEND_MAIL_SAVED:
-                                       _sending_busy_unref();
+                                       EM_DEBUG_LOG("EMAIL_EVENT_SEND_MAIL or EMAIL_EVENT_SEND_MAIL_SAVED");
+                                       if (!emcore_notify_network_event(NOTI_SEND_CANCEL, pop_elm->account_id, NULL , pop_elm->event_param_data_4, err))
+                                               EM_DEBUG_EXCEPTION("emcore_notify_network_event [ NOTI_SEND_CANCEL] Failed >>>>");
+                                       break;
+
+                               case EMAIL_EVENT_DOWNLOAD_BODY:
+                                       EM_DEBUG_LOG("EMAIL_EVENT_DOWNLOAD_BODY");
+                                       if (!emcore_notify_network_event(NOTI_DOWNLOAD_BODY_CANCEL, pop_elm->account_id, NULL , pop_elm->event_param_data_4, err))
+                                               EM_DEBUG_EXCEPTION("emcore_notify_network_event [ NOTI_SEND_CANCEL] Failed >>>>");
                                        break;
 
                                case EMAIL_EVENT_SYNC_HEADER:
                                case EMAIL_EVENT_SYNC_HEADER_OMA:
-                               case EMAIL_EVENT_DOWNLOAD_BODY:
                                case EMAIL_EVENT_DOWNLOAD_ATTACHMENT:
                                case EMAIL_EVENT_SYNC_MAIL_FLAG_TO_SERVER:
                                case EMAIL_EVENT_SYNC_FLAGS_FIELD_TO_SERVER:
+                                       EM_DEBUG_LOG("EMAIL_EVENT_SYNC_HEADER, EMAIL_EVENT_DOWNLOAD_ATTACHMENT");
+                                       break;
+
+                               case EMAIL_EVENT_VALIDATE_ACCOUNT:
+                                       EM_DEBUG_LOG("validate account waiting: cancel account id[%d]", pop_elm->account_id);
+                                       if (!emcore_notify_network_event(NOTI_VALIDATE_ACCOUNT_CANCEL, pop_elm->account_id, NULL , pop_elm->event_param_data_4, err))
+                                               EM_DEBUG_EXCEPTION("emcore_notify_network_event [ NOTI_VALIDATE_ACCOUNT_CANCEL] Failed >>>>");
+                                       break;
+
                                case EMAIL_EVENT_DELETE_MAIL:
                                case EMAIL_EVENT_DELETE_MAIL_ALL:
-                               case EMAIL_EVENT_VALIDATE_ACCOUNT:
                                case EMAIL_EVENT_SYNC_IMAP_MAILBOX:
                                case EMAIL_EVENT_SAVE_MAIL:
                                case EMAIL_EVENT_MOVE_MAIL:
@@ -2354,472 +933,561 @@ void* thread_func_branch_command(void *arg)
                                case EMAIL_EVENT_SET_MAIL_SLOT_SIZE:
                                case EMAIL_EVENT_SEARCH_ON_SERVER:
                                case EMAIL_EVENT_RENAME_MAILBOX_ON_IMAP_SERVER:
-                                       _receiving_busy_unref();
+                                       EM_DEBUG_LOG("EMAIL_EVENT_DELETE_MAIL, EMAIL_EVENT_SYNC_IMAP_MAILBOX");
                                        break;
 
                                default:
                                        break;
                        }
 
-                       event_data.type = 0;
+                       pop_elm = (email_event_t *)g_queue_pop_nth(g_event_que, i);
+                       if (pop_elm) {
+                               emcore_return_handle(pop_elm->handle);
+                               emcore_free_event(pop_elm);
+                               EM_SAFE_FREE(pop_elm);
+                               i--;
+                       }
+                       if (g_event_que)
+                               q_length = g_queue_get_length(g_event_que);
 
-                       ENTER_RECURSIVE_CRITICAL_SECTION(_event_queue_lock);
-                       memset(g_event_que+g_active_que, 0x00, sizeof(email_event_t));
-                       LEAVE_RECURSIVE_CRITICAL_SECTION(_event_queue_lock);
+               } else {
+                       pop_elm->status = EMAIL_EVENT_STATUS_CANCELED;
                }
-
-               emcore_clear_session(session);
        }
+       LEAVE_RECURSIVE_CRITICAL_SECTION(_event_queue_lock);
 
-       if (!emstorage_close(&err))
-               EM_DEBUG_EXCEPTION("emstorage_close falied [%d]", err);
+       ret = true;
 
+       if (err_code != NULL)
+               *err_code = err;
        EM_DEBUG_FUNC_END();
-       return SUCCESS;
+       return ret;
 }
-/*Send event_data loop*/
-INTERNAL_FUNC int emcore_start_event_loop_for_sending_mails(int *err_code)
+
+/* check thread status
+* 0 : stop job 1 : continue job
+*/
+INTERNAL_FUNC int emcore_check_send_mail_thread_status(void)
 {
        EM_DEBUG_FUNC_BEGIN();
-       int thread_error = -1;
 
-       if (err_code != NULL)
-               *err_code = EMAIL_ERROR_NONE;
+       int ret = false;
+       int q_length = 0;
+       email_event_t *active_event = NULL;
 
-       memset(&g_send_event_que, 0x00, sizeof(g_send_event_que));
+       ENTER_RECURSIVE_CRITICAL_SECTION(_send_event_queue_lock);
 
-       if (g_send_srv_thread)  {
-               EM_DEBUG_EXCEPTION("\t send service thread is already running...");
-               if (err_code != NULL)
-                       *err_code = EMAIL_ERROR_UNKNOWN;
-               return true;
+       if (g_send_event_que)
+               q_length = g_queue_get_length(g_send_event_que);
+
+       if (q_length) {
+               active_event = (email_event_t *)g_queue_peek_head(g_send_event_que);
+               if (active_event) {
+                       if (active_event->status == EMAIL_EVENT_STATUS_STARTED)
+                               ret = true;
+                       else
+                               ret = false;
+               }
+       } else {
+               EM_DEBUG_LOG("Send Queue is empty [%d]", q_length);
+               ret = true;
        }
 
-       g_send_event_que_idx = 1;
-       g_send_event_loop = 1;
-       g_send_active_que = 0;
+       LEAVE_RECURSIVE_CRITICAL_SECTION(_send_event_queue_lock);
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
 
-       /* initialize lock */
-       /*  INITIALIZE_CRITICAL_SECTION(_send_event_available_lock); */
-       INITIALIZE_RECURSIVE_CRITICAL_SECTION(_send_event_queue_lock);
-       INITIALIZE_CONDITION_VARIABLE(_send_event_available_signal);
+INTERNAL_FUNC int emcore_cancel_all_threads_of_an_account(int account_id)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int error_code = EMAIL_ERROR_NONE;
+       int i = 0;
+       int q_length = 0;
+       email_event_t *found_elm = NULL;
+       email_event_t *pop_elm = NULL;
 
-       /* create thread */
-       THREAD_CREATE_JOINABLE(g_send_srv_thread, thread_func_branch_command_for_sending_mails, thread_error);
+       ENTER_RECURSIVE_CRITICAL_SECTION(_event_queue_lock);
 
-       if (thread_error != 0) {
-               EM_DEBUG_EXCEPTION("cannot make thread...");
-               if (err_code != NULL)
-                       *err_code = EMAIL_ERROR_UNKNOWN;
-               return FAILURE;
-       }
+       if (g_event_que)
+               q_length = g_queue_get_length(g_event_que);
 
-       if (err_code != NULL)
-               *err_code = EMAIL_ERROR_NONE;
-       EM_DEBUG_FUNC_END();
-       return SUCCESS;
-}
+       for (i = 0; i < q_length; i++) {
+               found_elm = (email_event_t *)g_queue_peek_nth(g_event_que, i);
+               if (found_elm->account_id == account_id || found_elm->account_id == ALL_ACCOUNT) {
+                       EM_DEBUG_LOG("Found Queue element[%d]", i);
 
-/* finish api event_data loop */
-INTERNAL_FUNC int emcore_send_event_loop_stop(int *err_code)
-{
-    EM_DEBUG_FUNC_BEGIN();
+                       if (found_elm->status == EMAIL_EVENT_STATUS_WAIT) {
+                               fail_status_notify(found_elm, EMAIL_ERROR_CANCELLED);
 
-       if (err_code != NULL)
-               *err_code = EMAIL_ERROR_NONE;
+                               switch (found_elm->type) {
 
-       if (!g_send_srv_thread)          {
-               if (err_code != NULL)
-                       *err_code = EMAIL_ERROR_UNKNOWN;
-               return false;
-       }
+                                       case EMAIL_EVENT_SEND_MAIL:
+                                       case EMAIL_EVENT_SEND_MAIL_SAVED:
+                                               EM_DEBUG_LOG("EMAIL_EVENT_SEND_MAIL or EMAIL_EVENT_SEND_MAIL_SAVED");
+                                               if (!emcore_notify_network_event(NOTI_SEND_CANCEL, found_elm->account_id, NULL , found_elm->event_param_data_4, error_code))
+                                                       EM_DEBUG_EXCEPTION("emcore_notify_network_event [ NOTI_SEND_CANCEL] Failed >>>>");
+                                               break;
 
-    /* stop event_data loop */
-    g_send_event_loop = 0;
+                                       case EMAIL_EVENT_DOWNLOAD_BODY:
+                                               EM_DEBUG_LOG("EMAIL_EVENT_DOWNLOAD_BODY");
+                                               if (!emcore_notify_network_event(NOTI_DOWNLOAD_BODY_CANCEL, found_elm->account_id, NULL , found_elm->event_param_data_4, error_code))
+                                                       EM_DEBUG_EXCEPTION("emcore_notify_network_event [ NOTI_SEND_CANCEL] Failed >>>>");
+                                               break;
 
-       emcore_cancel_send_mail_thread(g_send_active_que, NULL, err_code);
-       ENTER_CRITICAL_SECTION(_send_event_available_lock);
-       WAKE_CONDITION_VARIABLE(_send_event_available_signal);          /*  MUST BE HERE */
-       LEAVE_CRITICAL_SECTION(_send_event_available_lock);
+                                       case EMAIL_EVENT_SYNC_HEADER:
+                                       case EMAIL_EVENT_SYNC_HEADER_OMA:
+                                       case EMAIL_EVENT_DOWNLOAD_ATTACHMENT:
+                                       case EMAIL_EVENT_SYNC_MAIL_FLAG_TO_SERVER:
+                                       case EMAIL_EVENT_SYNC_FLAGS_FIELD_TO_SERVER:
+                                               EM_DEBUG_LOG("EMAIL_EVENT_SYNC_HEADER, EMAIL_EVENT_DOWNLOAD_ATTACHMENT");
+                                               break;
 
-       /* wait for thread finished */
-       THREAD_JOIN(g_send_srv_thread);
+                                       case EMAIL_EVENT_VALIDATE_ACCOUNT:
+                                               EM_DEBUG_LOG("validate account waiting: cancel account id[%d]", found_elm->account_id);
+                                               if (!emcore_notify_network_event(NOTI_VALIDATE_ACCOUNT_CANCEL, found_elm->account_id, NULL , found_elm->event_param_data_4, error_code))
+                                                       EM_DEBUG_EXCEPTION("emcore_notify_network_event [ NOTI_VALIDATE_ACCOUNT_CANCEL] Failed >>>>");
+                                               break;
 
-       g_send_srv_thread = 0;
+                                       case EMAIL_EVENT_DELETE_MAIL:
+                                       case EMAIL_EVENT_DELETE_MAIL_ALL:
+                                       case EMAIL_EVENT_SYNC_IMAP_MAILBOX:
+                                       case EMAIL_EVENT_SAVE_MAIL:
+                                       case EMAIL_EVENT_MOVE_MAIL:
+                                       case EMAIL_EVENT_CREATE_MAILBOX:
+                                       case EMAIL_EVENT_DELETE_MAILBOX:
+                                       case EMAIL_EVENT_SET_MAIL_SLOT_SIZE:
+                                       case EMAIL_EVENT_SEARCH_ON_SERVER:
+                                       case EMAIL_EVENT_RENAME_MAILBOX_ON_IMAP_SERVER:
+                                               EM_DEBUG_LOG("EMAIL_EVENT_DELETE_MAIL, EMAIL_EVENT_SYNC_IMAP_MAILBOX");
+                                               break;
 
-       DELETE_RECURSIVE_CRITICAL_SECTION(_send_event_queue_lock);
-       DELETE_CRITICAL_SECTION(_send_event_available_lock);
-       DELETE_CONDITION_VARIABLE(_send_event_available_signal);
+                                       default:
+                                               break;
+                               }
 
-       g_send_event_que_idx = 1;
-       g_send_active_que = 0;
+                               pop_elm = g_queue_pop_nth(g_event_que, i);
+                               if (pop_elm) {
+                                       emcore_return_handle(pop_elm->handle);
+                                       emcore_free_event(pop_elm);
+                                       EM_SAFE_FREE(pop_elm);
+                                       i--;
+                               } else {
+                                       EM_DEBUG_LOG("Failed to g_queue_pop_nth [%d] element", i);
+                               }
+                               if (g_event_que)
+                                       q_length = g_queue_get_length(g_event_que);
 
-       if (err_code != NULL)
-               *err_code = EMAIL_ERROR_NONE;
+                       } else {
+                               found_elm->status = EMAIL_EVENT_STATUS_CANCELED;
+                       }
+               }
+       }
 
-    return true;
+       LEAVE_RECURSIVE_CRITICAL_SECTION(_event_queue_lock);
+
+       EM_DEBUG_FUNC_END();
+       return error_code;
 }
 
-/* start api event_data loop */
-INTERNAL_FUNC int emcore_start_event_loop(int *err_code)
+
+/* cancel send mail job  */
+INTERNAL_FUNC int emcore_cancel_send_mail_thread(int handle, void *arg, int *err_code)
 {
-    EM_DEBUG_FUNC_BEGIN();
-       int thread_error;
+       EM_DEBUG_FUNC_BEGIN("handle[%d], arg[%p], err_code[%p]", handle, arg, err_code);
 
-       if (err_code != NULL)
-               *err_code = EMAIL_ERROR_NONE;
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       int found = 0;
+       int i = 0;
+       int q_length = 0;
+       email_event_t *found_elm = NULL;
+       email_event_t *pop_elm = NULL;
 
-    memset(&g_event_que, 0x00, sizeof(g_event_que));
+       ENTER_RECURSIVE_CRITICAL_SECTION(_send_event_queue_lock);
 
-       if (g_srv_thread) {
-               EM_DEBUG_EXCEPTION("service thread is already running...");
-               if (err_code != NULL)
-                       *err_code = EMAIL_ERROR_UNKNOWN;
-               return true;
+       if (g_send_event_que)
+               q_length = g_queue_get_length(g_send_event_que);
+
+       for (i = 0; i < q_length; i++) {
+               found_elm = (email_event_t *)g_queue_peek_nth(g_send_event_que, i);
+               if (found_elm->handle == handle) {
+                       EM_DEBUG_LOG("Found Send Queue element[%d] with handle[%d]", i, handle);
+                       found = 1;
+                       break;
+               }
        }
 
-       g_event_que_idx = 1;
-       g_event_loop = 1;
-       g_active_que = 0;
+       if (found) {
+               if (found_elm->status == EMAIL_EVENT_STATUS_WAIT) {
+                       fail_status_notify(found_elm, EMAIL_ERROR_CANCELLED);
 
-    /* initialize lock */
-       INITIALIZE_RECURSIVE_CRITICAL_SECTION(_event_queue_lock);
-       INITIALIZE_RECURSIVE_CRITICAL_SECTION(_event_callback_table_lock);
+                       switch (found_elm->type) {
+                               case EMAIL_EVENT_SEND_MAIL:
+                               case EMAIL_EVENT_SEND_MAIL_SAVED:
+                                       found_elm->status = EMAIL_EVENT_STATUS_CANCELED;
+                                       if (!emcore_notify_network_event(NOTI_SEND_CANCEL, found_elm->account_id, NULL, found_elm->event_param_data_4, err))
+                                               EM_DEBUG_EXCEPTION("emcore_notify_network_event [NOTI_SEND_CANCEL] Failed >>>>");
+                                       break;
+                               default:
+                                       break;
+                       }
 
-       emcore_initialize_event_callback_table();
+                       pop_elm = (email_event_t *)g_queue_pop_nth(g_send_event_que, i);
+                       if (pop_elm) {
+                               emcore_return_send_handle(pop_elm->handle);
+                               emcore_free_event(pop_elm);
+                               EM_SAFE_FREE(pop_elm);
+                       } else {
+                               EM_DEBUG_LOG("Failed to g_queue_pop_nth [%d] element", i);
+                       }
+               } else {
+                       found_elm->status = EMAIL_EVENT_STATUS_CANCELED;
+               }
 
-    /* create thread */
-       THREAD_CREATE(g_srv_thread, thread_func_branch_command, NULL, thread_error);
+               ret = true;
+       }
 
-       if (thread_error != 0) {
-        EM_DEBUG_EXCEPTION("cannot create thread");
-               if (err_code != NULL)
-                       *err_code = EMAIL_ERROR_SYSTEM_FAILURE;
-        return FAILURE;
-    }
+       LEAVE_RECURSIVE_CRITICAL_SECTION(_send_event_queue_lock);
 
        if (err_code != NULL)
-               *err_code = EMAIL_ERROR_NONE;
-
-    return false;
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
 }
 
-/* finish api event_data loop */
-INTERNAL_FUNC int emcore_stop_event_loop(int *err_code)
+INTERNAL_FUNC int emcore_cancel_all_send_mail_thread(int *err_code)
 {
-    EM_DEBUG_FUNC_BEGIN();
+       EM_DEBUG_FUNC_BEGIN("err_code[%p]", err_code);
 
-       if (err_code != NULL)
-               *err_code = EMAIL_ERROR_NONE;
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       int q_length = 0;
+       int i = 0;
+       email_event_t *pop_elm = NULL;
 
-       if (!g_srv_thread)  {
-               if (err_code != NULL)
-                       *err_code = EMAIL_ERROR_UNKNOWN;
-               return false;
-       }
+       ENTER_RECURSIVE_CRITICAL_SECTION(_send_event_queue_lock);
 
-    /* stop event_data loop */
-    g_event_loop = 0;
+       if (g_send_event_que)
+               q_length = g_queue_get_length(g_send_event_que);
 
-       /*      pthread_kill(g_srv_thread, SIGINT); */
-       emcore_cancel_thread(g_active_que, NULL, err_code);
+       for (i = 0; i < q_length; i++) {
+               pop_elm = (email_event_t *)g_queue_peek_nth(g_send_event_que, i);
 
-       ENTER_CRITICAL_SECTION(_event_available_lock);
-       WAKE_CONDITION_VARIABLE(_event_available_signal);
-       LEAVE_CRITICAL_SECTION(_event_available_lock);
+               if (pop_elm->status == EMAIL_EVENT_STATUS_WAIT) {
 
-       /* wait for thread finished */
-       THREAD_JOIN(g_srv_thread);
+                       fail_status_notify(pop_elm, EMAIL_ERROR_CANCELLED);
 
-       g_srv_thread = 0;
+                       switch (pop_elm->type) {
+                               case EMAIL_EVENT_SEND_MAIL:
+                               case EMAIL_EVENT_SEND_MAIL_SAVED:
+                                       pop_elm->status = EMAIL_EVENT_STATUS_CANCELED;
+                                       if (!emcore_notify_network_event(NOTI_SEND_CANCEL, pop_elm->account_id, NULL, pop_elm->event_param_data_4, err))
+                                               EM_DEBUG_EXCEPTION("emcore_notify_network_event [NOTI_SEND_CANCEL] Failed >>>>");
+                                       break;
+                               default:
+                                       break;
+                       }
 
-       DELETE_RECURSIVE_CRITICAL_SECTION(_event_queue_lock);
-       DELETE_CRITICAL_SECTION(_event_available_lock);
-       DELETE_CONDITION_VARIABLE(_event_available_signal);
-       DELETE_RECURSIVE_CRITICAL_SECTION(_event_callback_table_lock);
+                       pop_elm = (email_event_t *)g_queue_pop_nth(g_send_event_que, i);
+                       if (pop_elm) {
+                               emcore_return_send_handle(pop_elm->handle);
+                               emcore_free_event(pop_elm);
+                               EM_SAFE_FREE(pop_elm);
+                               i--;
+                       }
 
-       g_event_que_idx = 1;
-       g_active_que = 0;
+                       if (g_send_event_que)
+                               q_length = g_queue_get_length(g_send_event_que);
 
-       if (err_code != NULL)
-               *err_code = EMAIL_ERROR_NONE;
-       EM_DEBUG_FUNC_END();
-    return true;
-}
+               } else {
+                       pop_elm->status = EMAIL_EVENT_STATUS_CANCELED;
+               }
+       }
+       LEAVE_RECURSIVE_CRITICAL_SECTION(_send_event_queue_lock);
 
+       ret = true;
 
-int emcore_get_active_queue_idx()
-{
-       return g_send_active_que;
+       if (err_code != NULL)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
 }
 
-/* check thread status
-* 0 : stop job 1 : continue job
-*/
-INTERNAL_FUNC int emcore_check_thread_status()
+INTERNAL_FUNC int emcore_get_task_information(email_task_information_t **output_task_information, int *output_task_information_count)
 {
-       if (g_active_que <= 0)
-               return true;
+       EM_DEBUG_FUNC_BEGIN("output_task_information[%p] output_task_information_count[%p]", output_task_information, output_task_information_count);
+       int err = EMAIL_ERROR_NONE;
+       int i = 0;
+       int index = 0;
+       int q_length = 0;
+       email_task_information_t *task_information = NULL;
+       email_event_t *elm = NULL;
 
-       return (g_event_que[g_active_que].status == EMAIL_EVENT_STATUS_STARTED);
-}
+       if (output_task_information == NULL || output_task_information_count == NULL) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
 
-/* cancel a job  */
-INTERNAL_FUNC int emcore_cancel_thread(int handle, void *arg, int *err_code)
-{
-       EM_DEBUG_FUNC_BEGIN("handle[%d], arg[%p], err_code[%p]", handle, arg, err_code);
+       if (g_event_que)
+               q_length = g_queue_get_length(g_event_que);
 
-       int ret = false;
-       int err = EMAIL_ERROR_NONE;
+       if (!q_length) {
+               err = EMAIL_ERROR_DATA_NOT_FOUND;
+               goto FINISH_OFF;
+       }
 
-       if (handle <= 0 || handle > (EVENT_QUEUE_MAX - 1))  {
-               EM_DEBUG_EXCEPTION("handle[%d], arg[%p]", handle, arg);
-               err = EMAIL_ERROR_INVALID_PARAM;
+       if ((task_information = em_malloc(sizeof(email_task_information_t) * q_length)) == NULL) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_OUT_OF_MEMORY");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
                goto FINISH_OFF;
        }
 
-       ENTER_RECURSIVE_CRITICAL_SECTION(_event_queue_lock);
+       for (i = 0; i < q_length; i++) {
+               elm = (email_event_t *)g_queue_peek_nth(g_event_que, i);
+               if(elm->type != EMAIL_EVENT_NONE && elm->status != EMAIL_EVENT_STATUS_CANCELED) {
+                       task_information[index].handle     = elm->handle;
+                       task_information[index].account_id = elm->account_id;
+                       task_information[index].type       = elm->type;
+                       task_information[index].status     = elm->status;
+                       index++;
+               }
+       }
+
+       *output_task_information_count = q_length;
+       *output_task_information       = task_information;
+
+FINISH_OFF:
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC int emcore_free_event(email_event_t *event_data)
+{
+       EM_DEBUG_FUNC_BEGIN("event_data [%p]", event_data);
+       if(!event_data) 
+               return EMAIL_ERROR_INVALID_PARAM;
+
+       switch(event_data->type) {
+               case EMAIL_EVENT_SYNC_IMAP_MAILBOX:
+                       EM_SAFE_FREE(event_data->event_param_data_3);
+                       break;
+
+               case EMAIL_EVENT_SYNC_HEADER:  /* synchronize mail header  */
+                       break;
 
-       EM_DEBUG_LOG("status[%d], type[%d], handle[%d]", g_event_que[handle].status, g_event_que[handle].type, handle);
+               case EMAIL_EVENT_SYNC_HEADER_OMA:  /*  synchronize mail header for OMA */
+                       EM_SAFE_FREE(event_data->event_param_data_1);
+                       break;
 
-       if (g_event_que[handle].status == EMAIL_EVENT_STATUS_WAIT)  {
-               fail_status_notify(&g_event_que[handle], EMAIL_ERROR_CANCELLED);
+               case EMAIL_EVENT_DOWNLOAD_BODY:  /*  download mail body  */
+                       break;
 
-               switch (g_event_que[handle].type)  {
-                       case EMAIL_EVENT_SEND_MAIL:
-                       case EMAIL_EVENT_SEND_MAIL_SAVED:
-                               EM_DEBUG_LOG("EMAIL_EVENT_SEND_MAIL or EMAIL_EVENT_SEND_MAIL_SAVED");
-                               _sending_busy_unref();
-                               if (!emcore_notify_network_event(NOTI_SEND_CANCEL, g_event_que[handle].account_id, NULL , g_event_que[handle].event_param_data_4, err))
-                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_SEND_CANCEL] Failed >>>> ");
-                               break;
-                       case EMAIL_EVENT_DOWNLOAD_BODY:
-                               EM_DEBUG_LOG("EMAIL_EVENT_DOWNLOAD_BODY");
-                               _receiving_busy_unref();
-                               if (!emcore_notify_network_event(NOTI_DOWNLOAD_BODY_CANCEL, g_event_que[handle].account_id, NULL , g_event_que[handle].event_param_data_4, err))
-                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_SEND_CANCEL] Failed >>>> ");
-                               break;
+               case EMAIL_EVENT_DOWNLOAD_ATTACHMENT:  /*  download attachment */
+                       break;
 
-                       case EMAIL_EVENT_SYNC_HEADER:
-                       case EMAIL_EVENT_SYNC_HEADER_OMA:
-                       case EMAIL_EVENT_DOWNLOAD_ATTACHMENT:
-                       case EMAIL_EVENT_SYNC_MAIL_FLAG_TO_SERVER:
-                       case EMAIL_EVENT_SYNC_FLAGS_FIELD_TO_SERVER:
-                               EM_DEBUG_LOG("EMAIL_EVENT_SYNC_HEADER, EMAIL_EVENT_DOWNLOAD_ATTACHMENT");
-                               _receiving_busy_unref();
-                               break;
+               case EMAIL_EVENT_SYNC_FLAGS_FIELD_TO_SERVER:  /*  Sync flags field */
+                       EM_SAFE_FREE(event_data->event_param_data_3);
+                       break;
 
-                       case EMAIL_EVENT_VALIDATE_ACCOUNT:
-                               EM_DEBUG_LOG(" validate account waiting  :  cancel acc id  :  %d", g_event_que[handle].account_id);
-                               _receiving_busy_unref();
-                               if (!emcore_notify_network_event(NOTI_VALIDATE_ACCOUNT_CANCEL, g_event_que[handle].account_id, NULL , g_event_que[handle].event_param_data_4, err))
-                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_VALIDATE_ACCOUNT_CANCEL] Failed >>>> ");
-                               break;
+               case EMAIL_EVENT_DELETE_MAIL:  /*  delete mails */
+                       EM_SAFE_FREE(event_data->event_param_data_3);
+                       break;
 
-                       case EMAIL_EVENT_DELETE_MAIL:
-                       case EMAIL_EVENT_DELETE_MAIL_ALL:
-                       case EMAIL_EVENT_SYNC_IMAP_MAILBOX:
-                       case EMAIL_EVENT_SAVE_MAIL:
-                       case EMAIL_EVENT_MOVE_MAIL:
-                       case EMAIL_EVENT_CREATE_MAILBOX:
-                       case EMAIL_EVENT_DELETE_MAILBOX:
-                       case EMAIL_EVENT_SET_MAIL_SLOT_SIZE:
-                       case EMAIL_EVENT_SEARCH_ON_SERVER:
-                       case EMAIL_EVENT_RENAME_MAILBOX_ON_IMAP_SERVER:
-                               EM_DEBUG_LOG("EMAIL_EVENT_DELETE_MAIL, EMAIL_EVENT_SYNC_IMAP_MAILBOX");
-                               _receiving_busy_unref();
-                               break;
-                       default:
-                               break;
-               }
-       }
+               case EMAIL_EVENT_DELETE_MAIL_ALL:  /*  delete all mails */
+                       break;
 
-       memset(g_event_que+handle, 0x00, sizeof(email_event_t));
-       g_event_que[handle].status = EMAIL_EVENT_STATUS_CANCELED;
+#ifdef __FEATURE_SYNC_CLIENT_TO_SERVER__
+               case EMAIL_EVENT_SYNC_MAIL_FLAG_TO_SERVER:
+                       break;
+#endif
 
-       LEAVE_RECURSIVE_CRITICAL_SECTION(_event_queue_lock);
+               case EMAIL_EVENT_CREATE_MAILBOX:
+                       emcore_free_mailbox((email_mailbox_t*)event_data->event_param_data_1);
+                       EM_SAFE_FREE(event_data->event_param_data_1);
+                       break;
 
-       ret = true;
+               case EMAIL_EVENT_DELETE_MAILBOX:
+                       break;
 
-FINISH_OFF:
-       if (err_code != NULL)
-               *err_code = err;
-       EM_DEBUG_FUNC_END();
-       return ret;
-}
+               case EMAIL_EVENT_SAVE_MAIL:
+                       break;
 
-/* check thread status
-* 0 : stop job 1 : continue job
-*/
-int emcore_check_send_mail_thread_status()
-{
-       EM_DEBUG_FUNC_BEGIN();
+               case EMAIL_EVENT_MOVE_MAIL:
+                       EM_SAFE_FREE(event_data->event_param_data_3);
+                       break;
 
-       if (g_send_active_que <= 0)
-               return true;
-       EM_DEBUG_LOG("g_send_event_que[g_send_active_que[%d]].status[%d]", g_send_active_que, g_send_event_que[g_send_active_que].status);
-       EM_DEBUG_FUNC_END();
-       return (g_send_event_que[g_send_active_que].status == EMAIL_EVENT_STATUS_STARTED);
-}
+               case EMAIL_EVENT_VALIDATE_ACCOUNT:
+                       break;
 
-INTERNAL_FUNC int emcore_cancel_all_threads_of_an_account(int account_id)
-{
-       EM_DEBUG_FUNC_BEGIN();
-       int error_code = EMAIL_ERROR_NONE;
-       int i, event_count = EVENT_QUEUE_MAX, exit_flag = 0, sleep_count = 0;
-
-       for (i = 0 ; i < event_count; i++) {
-               if (g_event_que[i].type && g_event_que[i].status != EMAIL_EVENT_STATUS_UNUSED) {
-                       EM_DEBUG_LOG("There is a live thread. %d", i);
-                       if (g_event_que[i].account_id == account_id || g_event_que[i].account_id == ALL_ACCOUNT) {
-                               EM_DEBUG_LOG("And it is for account %d", g_event_que[i].account_id);
-                               emcore_cancel_thread(i, NULL, &error_code);
-                       }
-               }
-       }
+               case EMAIL_EVENT_VALIDATE_AND_CREATE_ACCOUNT:
+                       emcore_free_account((email_account_t *)event_data->event_param_data_1);
+                       EM_SAFE_FREE(event_data->event_param_data_1);
 
-       while (exit_flag == 0 && sleep_count < 30) {
-               EM_DEBUG_LOG("Sleeping...");
-               usleep(100000);
-               EM_DEBUG_LOG("Wake up!");
-               sleep_count++;
-               exit_flag = 1;
-               for (i = 0 ; i < event_count; i++) {
-                       if (g_event_que[i].type && g_event_que[i].status != EMAIL_EVENT_STATUS_UNUSED) {
-                               EM_DEBUG_LOG("There is still a live thread. %d", i);
-                               if (g_event_que[i].account_id == account_id || g_event_que[i].account_id == ALL_ACCOUNT) {
-                                       EM_DEBUG_LOG("And it is for account %d. So, I should sleep for a while.", g_event_que[i].account_id);
-                                       exit_flag = 0;
-                               }
-                       }
-               }
-       }
+                       break;
 
-       EM_DEBUG_LOG("Sleep count %d", sleep_count);
+               case EMAIL_EVENT_VALIDATE_ACCOUNT_EX:
+                       emcore_free_account((email_account_t *)event_data->event_param_data_1);
+                       EM_SAFE_FREE(event_data->event_param_data_1);
+                       break;
 
-       if (sleep_count >= 30)
-               error_code = EMAIL_ERROR_CANNOT_STOP_THREAD;
-       else
-               error_code = EMAIL_ERROR_NONE;
-       EM_DEBUG_FUNC_END();
-       return error_code;
-}
+               case EMAIL_EVENT_VALIDATE_AND_UPDATE_ACCOUNT:
+                       emcore_free_account((email_account_t *)event_data->event_param_data_1);
+                       EM_SAFE_FREE(event_data->event_param_data_1);
+                       break;
 
+               case EMAIL_EVENT_UPDATE_MAIL: {
+                               email_mail_data_t* input_mail_data = (email_mail_data_t*) event_data->event_param_data_1;
+                               email_attachment_data_t* input_attachment_data_list = (email_attachment_data_t*) event_data->event_param_data_2;
+                               email_meeting_request_t* input_meeting_request = (email_meeting_request_t*) event_data->event_param_data_3;
+                               int input_attachment_count = event_data->event_param_data_4;
+                               emcore_free_mail_data_list(&input_mail_data, 1);
+                               emcore_free_attachment_data(&input_attachment_data_list, input_attachment_count, NULL);
+                               emstorage_free_meeting_request(input_meeting_request);                          
+                       }
+                       break;
 
-/* cancel send mail job  */
-INTERNAL_FUNC int emcore_cancel_send_mail_thread(int handle, void *arg, int *err_code)
-{
-       EM_DEBUG_FUNC_BEGIN("handle[%d], arg[%p], err_code[%p]", handle, arg, err_code);
+               case EMAIL_EVENT_SET_MAIL_SLOT_SIZE:
+                       break;
 
-       int ret = false;
-       int err = EMAIL_ERROR_NONE;
+               case EMAIL_EVENT_EXPUNGE_MAILS_DELETED_FLAGGED:
+                       break;
 
-       if (handle <= 0 || handle > (EVENT_QUEUE_MAX - 1))  {
-               EM_DEBUG_EXCEPTION("handle[%d], arg[%p]", handle, arg);
-               err = EMAIL_ERROR_INVALID_PARAM;
-               goto FINISH_OFF;
-       }
+#ifdef __FEATURE_LOCAL_ACTIVITY__
+               case EMAIL_EVENT_LOCAL_ACTIVITY:
+                       break;
+#endif /* __FEATURE_LOCAL_ACTIVITY__*/
 
-       ENTER_RECURSIVE_CRITICAL_SECTION(_send_event_queue_lock);
+               case EMAIL_EVENT_SEARCH_ON_SERVER:
+                       EM_SAFE_FREE(event_data->event_param_data_1);
+                       break;
 
-       EM_DEBUG_LOG("event_data.status[%d], handle[%d]", g_send_event_que[handle].status, handle);
+               case EMAIL_EVENT_RENAME_MAILBOX_ON_IMAP_SERVER:
+                       EM_SAFE_FREE(event_data->event_param_data_1);
+                       EM_SAFE_FREE(event_data->event_param_data_2);
+                       EM_SAFE_FREE(event_data->event_param_data_3);
+                       break;
 
-       if (g_send_event_que[handle].status == EMAIL_EVENT_STATUS_WAIT)  {
-               fail_status_notify(&g_send_event_que[handle], EMAIL_ERROR_CANCELLED);
 
-               switch (g_send_event_que[handle].type)  {
-                       case EMAIL_EVENT_SEND_MAIL:
-                       case EMAIL_EVENT_SEND_MAIL_SAVED:
-                               _sending_busy_unref();
-                               g_send_event_que[handle].status = EMAIL_EVENT_STATUS_CANCELED;
-                               if (!emcore_notify_network_event(NOTI_SEND_CANCEL, g_send_event_que[handle].account_id, NULL , g_send_event_que[handle].event_param_data_4, err))
-                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_SEND_CANCEL] Failed >>>> ");
-                               break;
-                       default:
-                               break;
-               }
-       }
+               case EMAIL_EVENT_SEND_MAIL:
+                       break;
 
-       EM_DEBUG_LOG("send_mail_cancel");
-       memset(g_send_event_que+handle, 0x00, sizeof(email_event_t));
-       g_send_event_que[handle].status = EMAIL_EVENT_STATUS_CANCELED;
+               case EMAIL_EVENT_SEND_MAIL_SAVED:
+                       EM_SAFE_FREE(event_data->event_param_data_3);
+                       break;
 
-       EM_DEBUG_LOG("event_data.status[%d], handle[%d]", g_send_event_que[handle].status, handle);
+               case EMAIL_EVENT_QUERY_SMTP_MAIL_SIZE_LIMIT:
+                       break;
 
+#ifdef __FEATURE_LOCAL_ACTIVITY__
+               case EMAIL_EVENT_LOCAL_ACTIVITY: {
+               break;
+#endif /* __FEATURE_LOCAL_ACTIVITY__ */
 
-       LEAVE_RECURSIVE_CRITICAL_SECTION(_send_event_queue_lock);
+               default : /*free function is not implemented*/
+                       EM_DEBUG_EXCEPTION("event %d is NOT freed, possibly memory leaks", event_data->type);   
+       }
 
-       ret = true;
+       event_data->event_param_data_1 = event_data->event_param_data_2 = event_data->event_param_data_3 = NULL;
 
-FINISH_OFF:
-       if (err_code != NULL)
-               *err_code = err;
-       EM_DEBUG_FUNC_END("ret [%d]", ret);
-       return ret;
+       EM_DEBUG_FUNC_END();
+       return true;
 }
 
-INTERNAL_FUNC int emcore_get_task_information(email_task_information_t **output_task_information, int *output_task_information_count)
+static int emcore_get_new_handle(void)
 {
-       EM_DEBUG_FUNC_BEGIN("output_task_information[%p] output_task_information_count[%p]", output_task_information, output_task_information_count);
-       int err = EMAIL_ERROR_NONE;
+       EM_DEBUG_FUNC_BEGIN();
        int i = 0;
-       int count = 0;
-       int index = 0;
-       email_task_information_t *task_information = NULL;
+       int ret_handle = 0;
 
-       if (output_task_information == NULL || output_task_information_count == NULL) {
-               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
-               err = EMAIL_ERROR_INVALID_PARAM;
-               goto FINISH_OFF;
+       ENTER_RECURSIVE_CRITICAL_SECTION(_event_handle_map_lock);
+       for (i = 0; i < EVENT_QUEUE_MAX; i++) {
+               if (handle_map[i] == 0) {
+                       handle_map[i] = 1;
+                       break;
+               }
        }
+       LEAVE_RECURSIVE_CRITICAL_SECTION(_event_handle_map_lock);
 
-       for(i = 0; i < EVENT_QUEUE_MAX; i++) {
-               if(g_event_que[i].type != EMAIL_EVENT_NONE && g_event_que[i].status != EMAIL_EVENT_STATUS_CANCELED)
-                       count++;
+       if (i < EVENT_QUEUE_MAX) {
+               ret_handle = i+1;
+               EM_DEBUG_LOG("New handle [%d]", ret_handle);
+       }
+       else {
+               ret_handle = 0;
+               EM_DEBUG_EXCEPTION ("there is no available handle");
        }
 
-       if(count != 0) {
-               if((task_information = em_malloc(sizeof(email_task_information_t) * count)) == NULL) {
-                       EM_DEBUG_EXCEPTION("EMAIL_ERROR_OUT_OF_MEMORY");
-                       err = EMAIL_ERROR_OUT_OF_MEMORY;
-                       goto FINISH_OFF;
-               }
+       EM_DEBUG_FUNC_END();
 
-               for(i = 0; i < EVENT_QUEUE_MAX; i++) {
-                       if(g_event_que[i].type != EMAIL_EVENT_NONE && g_event_que[i].status != EMAIL_EVENT_STATUS_CANCELED) {
-                               task_information[index].handle     = i;
-                               task_information[index].account_id = g_event_que[i].account_id;
-                               task_information[index].type       = g_event_que[i].type;
-                               task_information[index].status     = g_event_que[i].status;
-                               index++;
-                       }
+       return ret_handle;
+}
+
+static int emcore_get_new_send_handle(void)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int i = 0;
+       int ret_handle = 0;
+
+       ENTER_RECURSIVE_CRITICAL_SECTION(_send_event_handle_map_lock);
+       for (i = 0; i < EVENT_QUEUE_MAX; i++) {
+               if (send_handle_map[i] == 0) {
+                       send_handle_map[i] = 1;
+                       break;
                }
        }
+       LEAVE_RECURSIVE_CRITICAL_SECTION(_send_event_handle_map_lock);
+
+       if (i < EVENT_QUEUE_MAX) {
+               ret_handle = i+1;
+               EM_DEBUG_LOG("New send handle [%d]", ret_handle);
+       }
        else {
-               err = EMAIL_ERROR_DATA_NOT_FOUND;
+               ret_handle = 0;
+               EM_DEBUG_LOG("there is no available send handle");
        }
 
-       *output_task_information_count = count;
-       *output_task_information       = task_information;
+       EM_DEBUG_FUNC_END();
 
-FINISH_OFF:
+       return ret_handle;
+}
 
-       EM_DEBUG_FUNC_END("err [%d]", err);
-       return err;
+INTERNAL_FUNC int emcore_return_handle(int handle)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int ret = false;
+
+       ENTER_RECURSIVE_CRITICAL_SECTION(_event_handle_map_lock);
+       if (handle > 0 && handle <= EVENT_QUEUE_MAX) {
+               handle_map[handle-1] = 0;
+               ret = true;
+               EM_DEBUG_LOG("handle [%d] is returned", handle);
+       }
+       LEAVE_RECURSIVE_CRITICAL_SECTION(_event_handle_map_lock);
+
+       EM_DEBUG_FUNC_END();
+
+       return ret;
 }
 
-INTERNAL_FUNC int emcore_free_event(email_event_t *event_data)
+INTERNAL_FUNC int emcore_return_send_handle(int handle)
 {
-       EM_DEBUG_FUNC_BEGIN("event_data [%p]", event_data);
+       EM_DEBUG_FUNC_BEGIN();
+       int ret = false;
 
-       if(event_data) {
-               EM_SAFE_FREE(event_data->event_param_data_1);
-               EM_SAFE_FREE(event_data->event_param_data_2);
-               EM_SAFE_FREE(event_data->event_param_data_3);
+       ENTER_RECURSIVE_CRITICAL_SECTION(_send_event_handle_map_lock);
+       if (handle > 0 && handle <= EVENT_QUEUE_MAX) {
+               send_handle_map[handle-1] = 0;
+               ret = true;
+               EM_DEBUG_LOG("send handle [%d] is returned", handle);
        }
+       LEAVE_RECURSIVE_CRITICAL_SECTION(_send_event_handle_map_lock);
 
        EM_DEBUG_FUNC_END();
-       return true;
+
+       return ret;
 }
 
 #ifdef __FEATURE_KEEP_CONNECTION__
@@ -2840,7 +1508,7 @@ INTERNAL_FUNC int emcore_get_pbd_thd_state()
        return pbd_thd_state;
 }
 
-static int emcore_set_pbd_thd_state(int flag)
+INTERNAL_FUNC int emcore_set_pbd_thd_state(int flag)
 {
        ENTER_CRITICAL_SECTION(_state_variables_lock);
        g_pbd_thd_state = flag;
@@ -2880,7 +1548,7 @@ static int emcore_clear_bulk_pbd_que(int *err_code)
        return ret;
 }
 
-static void emcore_pb_thd_set_local_activity_continue(int flag)
+INTERNAL_FUNC void emcore_pb_thd_set_local_activity_continue(int flag)
 {
        EM_DEBUG_FUNC_BEGIN("flag [%d]", flag);
 
@@ -2896,8 +1564,7 @@ static void emcore_pb_thd_set_local_activity_continue(int flag)
        EM_DEBUG_FUNC_END();
 }
 
-static
-int emcore_pb_thd_can_local_activity_continue()
+INTERNAL_FUNC int emcore_pb_thd_can_local_activity_continue()
 {
        EM_DEBUG_FUNC_BEGIN();
 
@@ -3135,7 +1802,7 @@ INTERNAL_FUNC int emcore_insert_partial_body_thread_event(email_event_partial_bo
 
 /* h.gahlaut :  Return true only if event_data is retrieved successfully */
 
-static int emcore_retrieve_partial_body_thread_event(email_event_partial_body_thd *partial_body_thd_event, int *error_code)
+INTERNAL_FUNC int emcore_retrieve_partial_body_thread_event(email_event_partial_body_thd *partial_body_thd_event, int *error_code)
 {
        EM_DEBUG_FUNC_BEGIN();
 
@@ -3162,7 +1829,6 @@ static int emcore_retrieve_partial_body_thread_event(email_event_partial_body_th
                        if (false == emcore_free_partial_body_thd_event(g_partial_body_thd_event_que + index, &error))
                                EM_DEBUG_EXCEPTION("emcore_free_partial_body_thd_event_cell failed [%d]", error);
                        else {
-
                                g_partial_body_thd_queue_full = false;
                                g_partial_body_thd_next_event_idx = ++index;
 
@@ -3193,189 +1859,6 @@ static int emcore_retrieve_partial_body_thread_event(email_event_partial_body_th
 
 }
 
-gpointer partial_body_download_thread(gpointer data)
-{
-       EM_DEBUG_FUNC_BEGIN();
-
-       int err = EMAIL_ERROR_NONE;
-       email_session_t *session = NULL;
-       email_event_partial_body_thd partial_body_thd_event;
-
-       EM_DEBUG_LOG(" ************ PB THREAD ID IS ALIVE. ID IS [%d] ********************" , THREAD_SELF());
-
-       /* Open connection with DB */
-
-       if (false == emstorage_open(&err))  {
-               EM_DEBUG_EXCEPTION("emstorage_open failed [%d]", err);
-               return false;
-       }
-
-       /* Start the continuous loop */
-
-       while (g_partial_body_thd_loop) {
-               /*  Get an empty session  */
-               /*  TODO :  Mutex should be used in session APIs */
-
-               if (false == emcore_get_empty_session(&session))
-                       EM_DEBUG_EXCEPTION("emcore_get_empty_session failed...");
-               else {  /* Get and Event from the Partial Body thread Event Queue */
-                       memset(&partial_body_thd_event, 0x00, sizeof(email_event_partial_body_thd));
-
-                       if (false == emcore_retrieve_partial_body_thread_event(&partial_body_thd_event, &err)) {
-                               if (EMAIL_ERROR_EVENT_QUEUE_EMPTY != err)
-                                       EM_DEBUG_EXCEPTION("emcore_retrieve_partial_body_thread_event failed [%d]", err);
-                               else {
-                                       EM_DEBUG_LOG(" partial body thread event_data queue is empty.");
-
-                                       /*  Flush the que before starting local activity sync to clear the events in queue which are less than 10 in count  */
-                                       if (!g_partial_body_bulk_dwd_queue_empty) {
-                                               partial_body_thd_event.event_type = 0;
-                                               partial_body_thd_event.account_id = g_partial_body_bulk_dwd_que[0].account_id;
-                                               partial_body_thd_event.mailbox_id = g_partial_body_bulk_dwd_que[0].mailbox_id;
-                                               partial_body_thd_event.mailbox_name = EM_SAFE_STRDUP(g_partial_body_bulk_dwd_que[0].mailbox_name);
-
-                                               if (false == emcore_mail_partial_body_download(&partial_body_thd_event, &err))
-                                                       EM_DEBUG_EXCEPTION("emcore_mail_partial_body_download from event_data queue failed [%d]", err);
-
-                                               emcore_pb_thd_set_local_activity_continue(true);
-                                       }
-
-                                       if (true == emcore_pb_thd_can_local_activity_continue()) {
-                                               /*Check for local Activities */
-                                               int is_local_activity_event_inserted = false;
-
-                                               if (false == emcore_partial_body_thd_local_activity_sync(&is_local_activity_event_inserted, &err)) {
-                                                       EM_DEBUG_EXCEPTION("emcore_partial_body_thd_local_activity_sync failed [%d]", err);
-                                               }
-                                               else {
-                                                       if (true == is_local_activity_event_inserted) {
-                                                               emcore_pb_thd_set_local_activity_continue(false);
-
-                                                               emcore_clear_session(session);
-                                                               continue;
-                                                       }
-                                               }
-                                       }
-
-                                       EM_DEBUG_LOG(" Partial Body Thread is going to sleep");
-
-                                       emcore_set_pbd_thd_state(false);
-
-                                       ENTER_CRITICAL_SECTION(_partial_body_thd_event_queue_lock);
-                                       SLEEP_CONDITION_VARIABLE(_partial_body_thd_cond, _partial_body_thd_event_queue_lock);
-                                       LEAVE_CRITICAL_SECTION(_partial_body_thd_event_queue_lock);
-
-                                       EM_DEBUG_LOG(" Partial Body Thread wakes up ");
-
-                                       emcore_set_pbd_thd_state(true);
-                               }
-
-                       }
-                       else {
-                               EM_DEBUG_LOG(" Event Received from Partial Body Event Queue ");
-
-                               /* Since all events are network operations dnet init and sleep control is
-                               done before entering switch block*/
-
-                               emdevice_set_dimming_on_off(false, NULL);
-
-                               if (!emnetwork_check_network_status( &err))  {
-                                       EM_DEBUG_EXCEPTION("emnetwork_check_network_status failed [%d]", err);;
-                               }
-                               else {
-                                       /*  Process events  */
-                                       EM_DEBUG_LOG("partial_body_thd_event.account_id[%d]", partial_body_thd_event.account_id);
-
-                                       switch (partial_body_thd_event.event_type) {
-                                               case EMAIL_EVENT_BULK_PARTIAL_BODY_DOWNLOAD:  {
-                                                       if (false == emcore_mail_partial_body_download(&partial_body_thd_event, &err)) {
-                                                               EM_DEBUG_EXCEPTION("emcore_mail_partial_body_download from event_data queue failed [%d]", err);
-                                                       }
-                                                       break;
-                                               }
-                                               case EMAIL_EVENT_LOCAL_ACTIVITY_SYNC_BULK_PBD:  {
-                                                       partial_body_thd_event.event_type = 0;
-
-                                                       /* Both the checks below make sure that before starting local activity there is no new/pending event_data in
-                                                       *   g_partial_body_thd_event_que and g_partial_body_bulk_dwd_que */
-                                                       if (false == emcore_is_partial_body_thd_que_empty())
-                                                               break;
-                                                       if (!g_partial_body_bulk_dwd_queue_empty)
-                                                               break;
-
-                                                       if (false == emcore_mail_partial_body_download(&partial_body_thd_event, &err))
-                                                               EM_DEBUG_EXCEPTION("emcore_mail_partial_body_download from activity table failed [%d]", err);
-                                                       break;
-                                               }
-                                               default:
-                                                       EM_DEBUG_EXCEPTION(" Warning :  Default case entered. This should not happen ");
-                                                       break;
-                                       }
-                               }
-
-                               if (false == emcore_free_partial_body_thd_event(&partial_body_thd_event, &err))
-                                       EM_DEBUG_EXCEPTION("emcore_free_partial_body_thd_event_cell failed [%d]", err);
-
-                               emdevice_set_dimming_on_off(true, NULL);
-                      }
-
-                      emcore_clear_session(session);
-              }
-       }
-
-       /* If something is added to end thread in future for any case then if thread is holding any resources
-       define a function emcore_partial_body_thd_loop_stop to release resources and call it
-       here to end thread */
-       return SUCCESS;
-}
-
-INTERNAL_FUNC int emcore_start_thread_for_downloading_partial_body(int *err_code)
-{
-       EM_DEBUG_FUNC_BEGIN();
-
-       int i = 0, thread_error = -1;
-
-       /* Clear Partial Body Event Queue*/
-       memset(&g_partial_body_thd_event_que, 0x00, sizeof(g_partial_body_thd_event_que));
-
-       for (i = 0; i < TOTAL_PARTIAL_BODY_EVENTS; ++i) {
-               g_partial_body_thd_event_que[i].mailbox_name = NULL;
-        g_partial_body_thd_event_que[i].mailbox_id = 0;
-    }
-
-       if (g_partial_body_thd)  {
-               EM_DEBUG_EXCEPTION("partial body thread is already running...");
-               if (err_code != NULL)
-                       *err_code = EMAIL_ERROR_UNKNOWN;
-
-               return true;
-       }
-
-       g_partial_body_thd_next_event_idx = 0;
-       g_partial_body_thd_loop = 1;
-       g_partial_body_thd_queue_empty = true;
-       g_partial_body_thd_queue_full = false;
-
-       INITIALIZE_CONDITION_VARIABLE(_partial_body_thd_cond);
-
-       /* create thread */
-       /* THREAD_CREATE_JOINABLE(g_partial_body_thd, partial_body_download_thread, thread_error); */
-       THREAD_CREATE(g_partial_body_thd, partial_body_download_thread, NULL, thread_error);
-
-       if (thread_error != 0) {
-               EM_DEBUG_EXCEPTION("cannot make thread...");
-               if (err_code != NULL)
-                       *err_code = EMAIL_ERROR_UNKNOWN;
-               return FAILURE;
-       }
-
-       if (err_code != NULL)
-               *err_code = EMAIL_ERROR_NONE;
-
-       return false;
-
-}
-
 /*Function to flush the bulk partial body download queue [santosh.br@samsung.com]*/
 static int emcore_partial_body_bulk_flush(int *error_code)
 {
@@ -3392,7 +1875,7 @@ static int emcore_partial_body_bulk_flush(int *error_code)
        stream = (MAILSTREAM *)tmp_stream;
 
        /*  Call bulk download here */
-       if (false == emcore_download_bulk_partial_mail_body(stream, g_partial_body_bulk_dwd_que, g_partial_body_bulk_dwd_next_event_idx, &error)) {
+       if (false == emcore_download_bulk_partial_mail_body (stream, g_partial_body_bulk_dwd_que, g_partial_body_bulk_dwd_next_event_idx, &error)) {
                EM_DEBUG_EXCEPTION(" emcore_download_bulk_partial_mail_body failed.. [%d]", error);
                goto FINISH_OFF;
        }
@@ -3400,8 +1883,7 @@ static int emcore_partial_body_bulk_flush(int *error_code)
        ret = true;
 FINISH_OFF:
 
-       emcore_close_mailbox(0, stream);
-       stream = NULL;
+       stream = mail_close (stream);
 
        g_partial_body_bulk_dwd_next_event_idx = 0;
        g_partial_body_bulk_dwd_queue_empty = true;
@@ -3418,26 +1900,24 @@ FINISH_OFF:
 
 
 /* Function to pass UID list and Data for bulk partial body download [santosh.br@samsung.com]/[h.gahlaut@samsung.com] */
-INTERNAL_FUNC int emcore_mail_partial_body_download(email_event_partial_body_thd *pbd_event, int *error_code)
+INTERNAL_FUNC int emcore_mail_partial_body_download (email_event_partial_body_thd *pbd_event, int *error_code)
 {
        EM_DEBUG_FUNC_BEGIN();
        int error = EMAIL_ERROR_NONE;
-       int num_activity = 0;
        int ret = false;
        int count = 0;
        int i = 0, m = 0;
        MAILSTREAM *stream = NULL;
-       void *tmp_stream = NULL;
        email_event_partial_body_thd *activity_data_list = NULL;
        int *mailbox_list = NULL;
+       int *account_list = NULL;
 
-       if (NULL == pbd_event)
-    {
+       if (NULL == pbd_event) {
            EM_DEBUG_EXCEPTION("Invalid Parameter pbd_event [%p] ", pbd_event);
 
            error = EMAIL_ERROR_INVALID_PARAM;
            goto FINISH_OFF;
-    }
+       }
 
        /*Check if the event_data is to flush the event_data que array */
        if (EMAIL_EVENT_BULK_PARTIAL_BODY_DOWNLOAD == pbd_event->event_type) {
@@ -3467,7 +1947,8 @@ INTERNAL_FUNC int emcore_mail_partial_body_download(email_event_partial_body_thd
                        }
                }
                /*Add the event_data to the download que array */
-               if (false == emcore_copy_partial_body_thd_event(pbd_event, g_partial_body_bulk_dwd_que+(g_partial_body_bulk_dwd_next_event_idx), &error))
+               if (false == emcore_copy_partial_body_thd_event (pbd_event, 
+                                 g_partial_body_bulk_dwd_que+(g_partial_body_bulk_dwd_next_event_idx), &error))
                        EM_DEBUG_EXCEPTION("\t Partial Body thread emcore_copy_partial_body_thd_event failed - %d", error);
                else {
                        g_partial_body_bulk_dwd_queue_empty = false;
@@ -3476,7 +1957,7 @@ INTERNAL_FUNC int emcore_mail_partial_body_download(email_event_partial_body_thd
                }
        }
        else if (pbd_event->activity_type) {
-               int *account_list = NULL;
+
                int account_count = 0;
 
                EM_DEBUG_LOG("Event is coming from local activity.");
@@ -3499,20 +1980,22 @@ INTERNAL_FUNC int emcore_mail_partial_body_download(email_event_partial_body_thd
                                int k = 0;
                                int activity_count = 0;
 
-                               if (!emcore_connect_to_remote_mailbox(account_list[m], mailbox_list[i], (void **)&tmp_stream, &error))  {
+                               if (!emcore_connect_to_remote_mailbox(account_list[m], mailbox_list[i], (void **)&stream, &error)) {
                                        EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed [%d]", error);
-                                       stream = NULL;
+                                       stream = mail_close (stream);
                                        goto FINISH_OFF;
                                }
 
-                               stream = (MAILSTREAM *)tmp_stream;
+                               if (false == emstorage_get_pbd_activity_data(account_list[m], mailbox_list[i], &activity_data_list, &activity_count,  false, &error))
+                                       EM_DEBUG_EXCEPTION(" emstorage_get_pbd_activity_data failed.. [%d]", error);
 
+                               /* it is duplicated with emstorage_get_pbd_activity_data
                                if (false == emstorage_get_mailbox_pbd_activity_count(account_list[m], mailbox_list[i], &activity_count, false, &error)) {
                                        EM_DEBUG_EXCEPTION(" emstorage_get_mailbox_pbd_activity_count failed.. [%d]", error);
                                        continue;
                                }
-
-                               if (activity_count > 0) {
+                               */
+                               if (activity_count>0 && activity_data_list) {
                                        int temp_error = EMAIL_ERROR_NONE;
                                        int j = 0;
                                        int iter = 0;
@@ -3520,6 +2003,7 @@ INTERNAL_FUNC int emcore_mail_partial_body_download(email_event_partial_body_thd
                                        int num = BULK_PARTIAL_BODY_DOWNLOAD_COUNT;
                                        int index = 0;
 
+/*
                                        if (false == emstorage_get_pbd_activity_data(account_list[j], mailbox_list[i], &activity_data_list, &num_activity,  false, &error))
                                                EM_DEBUG_EXCEPTION(" emstorage_get_pbd_activity_data failed.. [%d]", error);
 
@@ -3527,9 +2011,9 @@ INTERNAL_FUNC int emcore_mail_partial_body_download(email_event_partial_body_thd
                                                EM_DEBUG_EXCEPTION(" activity_data_list is null..");
                                                continue;
                                        }
-
-                                       remainder = num_activity%BULK_PARTIAL_BODY_DOWNLOAD_COUNT;
-                                       iter = num_activity/BULK_PARTIAL_BODY_DOWNLOAD_COUNT + ((num_activity%BULK_PARTIAL_BODY_DOWNLOAD_COUNT) ? 1  :  0);
+*/
+                                       remainder = activity_count%BULK_PARTIAL_BODY_DOWNLOAD_COUNT;
+                                       iter = activity_count/BULK_PARTIAL_BODY_DOWNLOAD_COUNT + ((activity_count%BULK_PARTIAL_BODY_DOWNLOAD_COUNT) ? 1  :  0);
 
                                        for (j = 0; j < iter; j++) {
                                                if ((iter == (j+1)) && (remainder != 0))
@@ -3541,28 +2025,26 @@ INTERNAL_FUNC int emcore_mail_partial_body_download(email_event_partial_body_thd
                                                        temp_error = EMAIL_ERROR_NO_RESPONSE;
                                                }
 
-                                               for (k = 0; k < num; k++) {
-                                                       if (activity_data_list[index + k].activity_type)
-                                                               emcore_free_partial_body_thd_event(activity_data_list + index + k, &error);
-                                                       else
-                                                               break;
-                                               }
                                                index += num;
 
-                                               if (false == emcore_is_partial_body_thd_que_empty()) {
-                                                       ret = true;
-                                                       goto FINISH_OFF;                /* Stop Local Activity Sync */
-                                               }
                                                if (EMAIL_ERROR_NO_RESPONSE == temp_error) {
                                                        temp_error = EMAIL_ERROR_NONE;
                                                        break;
                                                }
                                        }
+
+                                       for (k = 0; k < activity_count; k++)
+                                               emcore_free_partial_body_thd_event(activity_data_list + k, &error);
+                                       EM_SAFE_FREE(activity_data_list);
+
+                                       /*check: empty check required?*/
+                                       if (false == emcore_is_partial_body_thd_que_empty()) {
+                                               ret = true;
+                                               goto FINISH_OFF;                /* Stop Local Activity Sync */
+                                       }
                                }
                        }
-                       emcore_close_mailbox(0, stream);
-                       stream = NULL;
-                       tmp_stream = NULL;
+                       stream = mail_close (stream);
                }
 
                /* After completing one cycle of local activity sync ,
@@ -3588,20 +2070,10 @@ INTERNAL_FUNC int emcore_mail_partial_body_download(email_event_partial_body_thd
 FINISH_OFF:
 
        EM_SAFE_FREE(mailbox_list);
+       EM_SAFE_FREE(account_list);
+       stream = mail_close (stream);
 
-       if (activity_data_list) {
-               for (i = 0; i < num_activity; i++) {
-                       if (activity_data_list[i].activity_type)
-                               emcore_free_partial_body_thd_event(activity_data_list + i, &error);
-                       else
-                               break;
-               }
-       }
-
-       emcore_close_mailbox(0, stream);
-       stream = NULL;
-
-       if (NULL != error_code)
+       if (error_code)
                *error_code = error;
        EM_DEBUG_FUNC_END("ret [%d]", ret);
        return ret;
index 441a5ad..fdbc3fe 100755 (executable)
@@ -167,7 +167,7 @@ int emcore_imap_idle_loop_start(email_mailbox_t *mailbox_list,  int num, int *er
                                if (temp && FD_ISSET(temp->hold_connection, &readfds)) {
                                        if (!emcore_imap_idle_parse_response_stream(temp, &err)) {
                                                EM_DEBUG_EXCEPTION(">>>> emcore_imap_idle_loop_start 6 ");
-                                               emcore_close_mailbox(temp->account_id, temp->mail_stream);
+                                               temp->mail_stream = mail_close (temp->mail_stream);
                                                EM_DEBUG_EXCEPTION(">>>> emcore_imap_idle_loop_start 7 ");
                                                goto FINISH_OFF;
                                        }
@@ -193,13 +193,13 @@ int emcore_imap_idle_loop_start(email_mailbox_t *mailbox_list,  int num, int *er
                                        sprintf(cmd, "%s DONE\015\012", tag);
 
                                        if (!imap_local->netstream || !net_sout(imap_local->netstream, cmd, (int)EM_SAFE_STRLEN(cmd))) {
-                                               EM_DEBUG_EXCEPTION("network error - failed to DONE on Mailbox - %s ", temp->name);
+                                               EM_DEBUG_EXCEPTION_SEC("network error - failed to DONE on Mailbox - %s ", temp->name);
                                        }
                                        else {
                                                while (imap_local->netstream) {
-                                               p = net_getline(imap_local->netstream);
-                                               EM_DEBUG_EXCEPTION("p =[%s]", p);
-                                                       emcore_close_mailbox(temp->account_id, temp->mail_stream);
+                                                       p = net_getline(imap_local->netstream);
+                                                       EM_DEBUG_EXCEPTION("p =[%s]", p);
+                                                       temp->mail_stream = mail_close (temp->mail_stream);
                                                        break;
                                            }
                                        }
@@ -329,20 +329,21 @@ int emcore_imap_idle_insert_sync_event(email_mailbox_t *mailbox, int *err_code)
        int ret = false;
        int err = EMAIL_ERROR_NONE;
        int handle;
+       email_event_t *event_data = NULL;
        
        if (!mailbox || mailbox->account_id <= 0) {
                EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
                err = EMAIL_ERROR_INVALID_PARAM;
                goto FINISH_OFF;
        }
-       email_event_t event_data = { 0 };
 
-       event_data.type               = EMAIL_EVENT_SYNC_HEADER;
-       event_data.event_param_data_1 = mailbox ? EM_SAFE_STRDUP(mailbox->mailbox_name)  :  NULL;
-       event_data.event_param_data_3 = NULL;
-       event_data.account_id         = mailbox->account_id;
+       event_data = em_malloc(sizeof(email_event_t));
+       event_data->type               = EMAIL_EVENT_SYNC_HEADER;
+       event_data->event_param_data_1 = mailbox ? EM_SAFE_STRDUP(mailbox->mailbox_name) : NULL;
+       event_data->event_param_data_3 = NULL;
+       event_data->account_id         = mailbox->account_id;
                        
-       if (!emcore_insert_event(&event_data, &handle, &err)) {
+       if (!emcore_insert_event(event_data, &handle, &err)) {
                EM_DEBUG_EXCEPTION("emcore_insert_event failed [%d]", err);
                goto FINISH_OFF;
        }
@@ -351,8 +352,14 @@ int emcore_imap_idle_insert_sync_event(email_mailbox_t *mailbox, int *err_code)
 
 FINISH_OFF:
 
+       if (ret == false && event_data) {
+               emcore_free_event(event_data);
+               EM_SAFE_FREE(event_data);
+       }
+
        if (err_code)
                *err_code = err;
+
        EM_DEBUG_FUNC_END("ret [%d]", ret);
        return ret;
 }
@@ -413,7 +420,7 @@ static int emcore_imap_idle_connect_and_idle_on_mailbox(email_mailbox_t *mailbox
 
        /* Send IDLE command */
        if (!imap_local->netstream || !net_sout(imap_local->netstream, cmd, (int)EM_SAFE_STRLEN(cmd))) {
-               EM_DEBUG_EXCEPTION("network error - failed to IDLE on Mailbox - %s ", mailbox->mailbox_name);
+               EM_DEBUG_EXCEPTION_SEC("network error - failed to IDLE on Mailbox - %s ", mailbox->mailbox_name);
                err = EMAIL_ERROR_IMAP4_IDLE_FAILURE;
                goto FINISH_OFF;
        }
@@ -445,7 +452,7 @@ FINISH_OFF:
                mailbox->hold_connection = socket_id; /* holds connection continuously on the given socket_id */
        }
        else if (mail_stream)
-               emcore_close_mailbox(mailbox->account_id, mail_stream);
+               mail_stream = mail_close (mail_stream);
 
        if (ref_account) {
                emcore_free_account(ref_account);
@@ -492,7 +499,7 @@ static int emcore_imap_idle_parse_response_stream(email_mailbox_t *mailbox, int
                        }
                        else  { 
                                if (!emcore_imap_idle_insert_sync_event(mailbox, &err))
-                                       EM_DEBUG_EXCEPTION("Syncing mailbox %s failed with err_code [%d]", mailbox->mailbox_name, err);
+                                       EM_DEBUG_EXCEPTION_SEC("Syncing mailbox %s failed with err_code [%d]", mailbox->mailbox_name, err);
                                EM_SAFE_FREE(p);        
                                break;
                        }
index b012933..aa3b5c8 100755 (executable)
@@ -36,7 +36,6 @@
 #include <vconf.h>
 #include "email-core-global.h"
 #include "email-core-utils.h"
-#include "c-client.h"
 #include "email-storage.h"
 #include "email-utilities.h"
 #include "email-network.h"
@@ -46,7 +45,9 @@
 #include "email-core-mailbox-sync.h"
 #include "email-core-account.h" 
 #include "email-core-signal.h"
+
 #include "lnx_inc.h"
+#include "c-client.h"
 
 #include "email-debug-log.h"
 
@@ -109,7 +110,7 @@ INTERNAL_FUNC int emcore_remove_overflowed_mails(emstorage_mailbox_tbl_t *intput
        
        if (!emstorage_get_overflowed_mail_id_list(intput_mailbox_tbl->account_id, intput_mailbox_tbl->mailbox_id, intput_mailbox_tbl->mail_slot_size, &mail_id_list, &mail_id_list_count, true, &err)) {
                if (err == EMAIL_ERROR_MAIL_NOT_FOUND) {
-                       EM_DEBUG_LOG("There are enough slot in intput_mailbox_tbl [%s]", intput_mailbox_tbl->mailbox_name);
+                       EM_DEBUG_LOG_SEC("There are enough slot in intput_mailbox_tbl [%s]", intput_mailbox_tbl->mailbox_name);
                        err = EMAIL_ERROR_NONE;
                        ret = true;
                }
@@ -252,7 +253,7 @@ FINISH_OFF:
 
 static int emcore_get_mailbox_connection_path(int account_id, char *mailbox_name, char **path, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("account_id [%d], mailbox_name[%s], err_code[%p]", account_id, mailbox_name, err_code);
+       EM_DEBUG_FUNC_BEGIN_SEC("account_id [%d], mailbox_name[%s], err_code[%p]", account_id, mailbox_name, err_code);
        email_account_t *ref_account = NULL;
        size_t path_len = 0;
        int ret = false;
@@ -290,7 +291,7 @@ static int emcore_get_mailbox_connection_path(int account_id, char *mailbox_name
                strncat(*path + 1, "/ssl", path_len-(EM_SAFE_STRLEN(*path)-1));
        }
        if (ref_account->incoming_server_secure_connection & 0x02)
-               strncat(*path + 1, "/tls", path_len-(EM_SAFE_STRLEN(*path)-1));
+               strncat(*path + 1, "/tls/force_tls_v1_0", path_len-(EM_SAFE_STRLEN(*path)-1));
        else
                strncat(*path + 1, "/notls", path_len-(EM_SAFE_STRLEN(*path)-1));
 
@@ -315,6 +316,63 @@ FINISH_OFF:
        return 1;
 }
 
+static void emcore_find_mailbox_diff_between_local_and_remote (email_internal_mailbox_t *remote_box_list, 
+                                               int remote_box_count, emstorage_mailbox_tbl_t *local_box_list, int local_box_count, 
+                                               GList** remote_box_only, GList** local_box_only)
+{
+       if ( !remote_box_only || !local_box_only ) {
+               return ;
+       }
+       int i = 0;
+       GList *remote_head = NULL;
+       GList *local_head  = NULL;
+       GList *remote_p    = NULL;
+       GList *local_p     = NULL;
+
+       EM_DEBUG_LOG ("remote_box_count[%d] local_box_count[%d]", remote_box_count, local_box_count);
+
+       if (local_box_count == 0) {
+               for (i=0 ; i<remote_box_count ; i++) {
+                       *remote_box_only = g_list_prepend (*remote_box_only, remote_box_list+i);
+                       *local_box_only = NULL;
+               }
+               return;
+       }
+
+       for (i=0; i<remote_box_count; i++)
+               remote_head = g_list_prepend (remote_head, remote_box_list+i);
+
+       for (i=0; i<local_box_count; i++)
+               local_head = g_list_prepend (local_head, local_box_list+i);
+
+       int matched = false;
+       for (remote_p = remote_head; remote_p ; remote_p = g_list_next (remote_p)) {
+               matched = false ; /* initialized not matched for each iteration */
+               email_internal_mailbox_t *remote_box = (email_internal_mailbox_t *) g_list_nth_data (remote_p, 0);
+               EM_DEBUG_LOG_DEV ("remote [%s]",  remote_box->mailbox_name );
+               /* find matching mailbox in local box */
+               for (local_p = local_head; local_p ; local_p = g_list_next(local_p)) {
+                       emstorage_mailbox_tbl_t *local_box = (emstorage_mailbox_tbl_t *) g_list_nth_data (local_p, 0);
+                       /* if match found */
+                       EM_DEBUG_LOG_DEV ("vs local [%s]", local_box->mailbox_name);
+                       if (!EM_SAFE_STRCMP (remote_box->mailbox_name, local_box->mailbox_name)) {
+                               /* It is unnecessary to compare the matched box in the next iteration, so remove it from local_box*/
+                               local_head = g_list_delete_link (local_head, local_p);                          
+                               matched = true;
+                               break;
+                       }
+               }
+               /* if matching not found, add it to remote box */
+               if (matched == false) {
+                       EM_DEBUG_LOG ("New box: name[%s] alias[%s]", remote_box->mailbox_name, remote_box->alias);
+                       *remote_box_only = g_list_prepend (*remote_box_only, remote_box);
+               }
+       }
+
+       /* local_head contains unmatched local box */
+       *local_box_only = local_head;
+}
+
 INTERNAL_FUNC int emcore_sync_mailbox_list(int account_id, char *mailbox_name, int handle, int *err_code)
 {
        EM_DEBUG_FUNC_BEGIN("account_id[%d], mailbox_name[%p], handle[%d], err_code[%p]", account_id, mailbox_name, handle, err_code);
@@ -323,7 +381,12 @@ INTERNAL_FUNC int emcore_sync_mailbox_list(int account_id, char *mailbox_name, i
        int err = EMAIL_ERROR_NONE;
        int status = EMAIL_DOWNLOAD_FAIL;
        MAILSTREAM *stream = NULL;
-       email_internal_mailbox_t *mailbox_list = NULL;
+       email_internal_mailbox_t *mailbox_list = NULL;   /* mailbox list from imap server */
+       /* mailbox list from DB */
+       emstorage_mailbox_tbl_t *local_mailbox_list = NULL;
+       int local_mailbox_count = 0;
+       GList *remote_box_only = NULL;
+       GList *local_box_only  = NULL;
        email_account_t *ref_account = NULL;
        void *tmp_stream = NULL;
        char *mbox_path = NULL;
@@ -393,141 +456,168 @@ INTERNAL_FUNC int emcore_sync_mailbox_list(int account_id, char *mailbox_name, i
        
        /*  download mailbox list */
        if (!emcore_download_mailbox_list(stream, mailbox_name, &mailbox_list, &count, &err))  {
-               EM_DEBUG_EXCEPTION("emcore_download_mailbox_list failed - %d", err);
+               EM_DEBUG_EXCEPTION("emcore_download_mailbox_list failed [%d]", err);
                goto FINISH_OFF;
        }
 
+       /* get all mailboxes which is previously synced */
+       if (!emstorage_get_mailbox_list (account_id, EMAIL_MAILBOX_FROM_SERVER, EMAIL_MAILBOX_SORT_BY_NAME_ASC,\
+                                                        &local_mailbox_count, &local_mailbox_list, 1, &err)) {
+               if (err != EMAIL_ERROR_MAILBOX_NOT_FOUND) {
+                       EM_DEBUG_EXCEPTION("emstorage_get_mailbox_list error [%d]", err);
+               }
+               else
+                       EM_DEBUG_LOG ("mailbox not found");
+       }
+
        if (!emcore_check_thread_status())  {
                err = EMAIL_ERROR_CANCELLED;
                goto FINISH_OFF;
        }
        
-       for (i = 0; i < count; i++) {
+       emcore_find_mailbox_diff_between_local_and_remote (mailbox_list, count, local_mailbox_list, local_mailbox_count,
+                                                                                       &remote_box_only, &local_box_only);
+
+       /* for remote_box_only, add new mailbox to DB */
+       GList *p = remote_box_only;
+       for (; p; p = g_list_next (p)) {
+               email_internal_mailbox_t *new_mailbox = (email_internal_mailbox_t *) g_list_nth_data (p, 0);
+
                if (!emcore_check_thread_status())  {
                        EM_DEBUG_LOG("emcore_check_thread_status - cancelled");
                        err = EMAIL_ERROR_CANCELLED;
                        goto FINISH_OFF;
                }
-               if (mailbox_list[i].mailbox_name) {
-                       EM_DEBUG_LOG("mailbox name - %s", mailbox_list[i].mailbox_name);
-                       mailbox_list[i].mail_slot_size = ref_account->default_mail_slot_size;
 
-                       if(mailbox_list[i].mailbox_type == EMAIL_MAILBOX_TYPE_NONE)
-                               emcore_bind_mailbox_type(mailbox_list + i);
+               if (!new_mailbox->mailbox_name) {
+                       continue;
+               }
+
+               /* EM_DEBUG_LOG_SEC ("mailbox name [%s]", new_mailbox->mailbox_name); */
+               new_mailbox->mail_slot_size = ref_account->default_mail_slot_size;
 
-                       if (mailbox_list[i].mailbox_type <= EMAIL_MAILBOX_TYPE_ALL_EMAILS) {    /* if result mailbox type is duplicated,  */
-                               if (mailbox_type_list[mailbox_list[i].mailbox_type] != -1) {
-                                       EM_DEBUG_LOG("Mailbox type [%d] of [%s] is duplicated", mailbox_list[i].mailbox_type, mailbox_list[i].mailbox_name);
-                                       mailbox_list[i].mailbox_type = EMAIL_MAILBOX_TYPE_USER_DEFINED; /* ignore latest one  */
-                               }
-                               else
-                                       mailbox_type_list[mailbox_list[i].mailbox_type] = i;
+               if (new_mailbox->mailbox_type == EMAIL_MAILBOX_TYPE_NONE)
+                       emcore_bind_mailbox_type (new_mailbox);
+
+               if (new_mailbox->mailbox_type <= EMAIL_MAILBOX_TYPE_ALL_EMAILS) {       /* if result mailbox type is duplicated,  */
+                       if (mailbox_type_list[new_mailbox->mailbox_type] != -1) {
+                               EM_DEBUG_LOG_SEC ("Mailbox type [%d] of [%s] is duplicated", new_mailbox->mailbox_type, new_mailbox->mailbox_name);
+                               new_mailbox->mailbox_type = EMAIL_MAILBOX_TYPE_USER_DEFINED; /* ignore latest one  */
                        }
+                       else
+                               mailbox_type_list[new_mailbox->mailbox_type] = 1;
+               }
 
-                       EM_DEBUG_LOG("mailbox type [%d]", mailbox_list[i].mailbox_type);
-                       if(!emcore_set_sync_imap_mailbox(mailbox_list + i, 1, &err)) {
-                               EM_DEBUG_EXCEPTION("emcore_set_sync_imap_mailbox failed [%d]", err);
+               /* make box variable to be added in DB */
+               emstorage_mailbox_tbl_t mailbox_tbl = {0};
+               mailbox_tbl.mailbox_id     = new_mailbox->mailbox_id;
+               mailbox_tbl.account_id     = new_mailbox->account_id;
+               mailbox_tbl.local_yn       = 0;
+               mailbox_tbl.deleted_flag   = 0;
+               mailbox_tbl.mailbox_type   = new_mailbox->mailbox_type;
+               mailbox_tbl.mailbox_name   = new_mailbox->mailbox_name;
+               mailbox_tbl.mail_slot_size = new_mailbox->mail_slot_size;
+               mailbox_tbl.no_select      = new_mailbox->no_select;
+
+               /* Get the Alias Name after Parsing the Full mailbox Path */
+               if (new_mailbox->alias == NULL)
+                       new_mailbox->alias = emcore_get_alias_of_mailbox ((const char *)new_mailbox->mailbox_name);
+
+               if (new_mailbox->alias) {
+                       mailbox_tbl.alias = new_mailbox->alias;
+                       mailbox_tbl.modifiable_yn = 1; 
+                       mailbox_tbl.total_mail_count_on_server = 0;
+                               
+                       if (!emstorage_add_mailbox (&mailbox_tbl, true, &err)) {
+                               EM_DEBUG_EXCEPTION ("emstorage_add_mailbox error [%d]", err);
                                goto FINISH_OFF;
                        }
-
+                       EM_DEBUG_LOG_SEC ("MAILBOX ADDED: mailbox_name [%s] alias [%s] mailbox_type [%d]", new_mailbox->mailbox_name,\
+                                                               new_mailbox->alias, mailbox_tbl.mailbox_type);
                }
        }
 
+       /* delete all local boxes and mails */
+       p = local_box_only;
+       for (; p; p = g_list_next (p)) {
+               emstorage_mailbox_tbl_t *del_box = (emstorage_mailbox_tbl_t *) g_list_nth_data (p, 0);
+               if (!emstorage_delete_mail_by_mailbox (del_box->account_id, del_box->mailbox_id, 1, &err)) {
+                       EM_DEBUG_EXCEPTION ("emstorage_delete_mail_by_mailbox error [%d] account_id [%d] mailbox_name [%s]",\
+                                                       err, del_box->account_id, del_box->mailbox_name);
+               }
+               if (!emstorage_delete_mailbox (del_box->account_id, EMAIL_MAILBOX_FROM_SERVER, del_box->mailbox_id, 1, &err)) {
+                       EM_DEBUG_EXCEPTION ("emstorage_delete_mail_by_mailbox error [%d] account_id [%d] mailbox_name [%s]",\
+                                                       err, del_box->account_id, del_box->mailbox_name);
+               }
+               EM_DEBUG_LOG_SEC ("MAILBOX REMOVED: mailbox_name[%s] mailbox_id[%d]", del_box->mailbox_name, del_box->mailbox_id);
+       }
 
        for (counter = EMAIL_MAILBOX_TYPE_INBOX; counter <= EMAIL_MAILBOX_TYPE_OUTBOX; counter++) {
-               /* if (!emstorage_get_mailbox_name_by_mailbox_type(account_id, counter, &mailbox_name_for_mailbox_type, false, &err))  */
                if (mailbox_type_list[counter] == -1) {
-                       /* EM_DEBUG_EXCEPTION("emstorage_get_mailbox_name_by_mailbox_type failed - %d", err); */
-                       /* if (EMAIL_ERROR_MAILBOX_NOT_FOUND == err)     */
-                       /* { */
-                               emstorage_mailbox_tbl_t mailbox_tbl;
-                               
-                               memset(&mailbox_tbl, 0x00, sizeof(mailbox_tbl));
-                               
-                               mailbox_tbl.account_id = account_id;
-                               mailbox_tbl.mailbox_id = 0;
-                               mailbox_tbl.local_yn = 1; 
-                               mailbox_tbl.mailbox_type = counter;
-                               mailbox_tbl.deleted_flag =  0;
-                               mailbox_tbl.modifiable_yn = 1; 
-                               mailbox_tbl.total_mail_count_on_server = 0;
-                               mailbox_tbl.mail_slot_size = ref_account->default_mail_slot_size;
-                               
-                               switch (counter) {
-                                       case EMAIL_MAILBOX_TYPE_SENTBOX:
-                                               mailbox_tbl.mailbox_name = EMAIL_SENTBOX_NAME;
-                                               mailbox_tbl.alias = EMAIL_SENTBOX_DISPLAY_NAME;
-                                               break;
-                                               
-                                       case EMAIL_MAILBOX_TYPE_TRASH:
-                                               mailbox_tbl.mailbox_name = EMAIL_TRASH_NAME;
-                                               mailbox_tbl.alias = EMAIL_TRASH_DISPLAY_NAME;
-                                               break;
-
-                                   case EMAIL_MAILBOX_TYPE_DRAFT:
-                                               mailbox_tbl.mailbox_name = EMAIL_DRAFTBOX_NAME;
-                                               mailbox_tbl.alias = EMAIL_DRAFTBOX_DISPLAY_NAME;
-                                               break;
-                                               
-                                       case EMAIL_MAILBOX_TYPE_SPAMBOX:
-                                               mailbox_tbl.mailbox_name = EMAIL_SPAMBOX_NAME;
-                                               mailbox_tbl.alias = EMAIL_SPAMBOX_DISPLAY_NAME;
-                                               break;
-                                               
-                                       case EMAIL_MAILBOX_TYPE_OUTBOX:
-                                               mailbox_tbl.mailbox_name = EMAIL_OUTBOX_NAME;
-                                               mailbox_tbl.alias = EMAIL_OUTBOX_DISPLAY_NAME;
-                                               break;
-
-                                       default: 
-                                               mailbox_tbl.mailbox_name = EMAIL_INBOX_NAME;
-                                               mailbox_tbl.alias = EMAIL_INBOX_DISPLAY_NAME;
-                                               break;
+                       int err2 = EMAIL_ERROR_NONE;
+                       emstorage_mailbox_tbl_t mailbox_tbl;
+                       emstorage_mailbox_tbl_t *result_mailbox_tbl = NULL;
+
+                       if(emstorage_get_mailbox_by_mailbox_type(account_id, counter, &result_mailbox_tbl, true, &err2)) {
+                               if(result_mailbox_tbl) {
+                                       emstorage_free_mailbox(&result_mailbox_tbl, 1, NULL);
+                                       continue;
                                }
+                       }
 
-                               if (!emstorage_add_mailbox(&mailbox_tbl, true, &err)) {
-                                       EM_DEBUG_EXCEPTION("emstorage_add_mailbox failed - %d", err);
-                                       goto FINISH_OFF;
-                               }
-                               
-                       /* }     */
-                       /* else */
-                       /* { */
-                       /*  */
-                       /*      goto FINISH_OFF; */
-                       /* } */
-                       
-               }
-               EM_SAFE_FREE(mailbox_name_for_mailbox_type);
-       }
+                       memset(&mailbox_tbl, 0x00, sizeof(mailbox_tbl));
+
+                       mailbox_tbl.account_id = account_id;
+                       mailbox_tbl.mailbox_id = 0;
+                       mailbox_tbl.local_yn = 1;
+                       mailbox_tbl.mailbox_type = counter;
+                       mailbox_tbl.deleted_flag =  0;
+                       mailbox_tbl.modifiable_yn = 1;
+                       mailbox_tbl.total_mail_count_on_server = 0;
+                       mailbox_tbl.mail_slot_size = ref_account->default_mail_slot_size;
+
+                       switch (counter) {
+                               case EMAIL_MAILBOX_TYPE_SENTBOX:
+                                       mailbox_tbl.mailbox_name = EMAIL_SENTBOX_NAME;
+                                       mailbox_tbl.alias = EMAIL_SENTBOX_DISPLAY_NAME;
+                                       break;
+
+                               case EMAIL_MAILBOX_TYPE_TRASH:
+                                       mailbox_tbl.mailbox_name = EMAIL_TRASH_NAME;
+                                       mailbox_tbl.alias = EMAIL_TRASH_DISPLAY_NAME;
+                                       break;
+
+                               case EMAIL_MAILBOX_TYPE_DRAFT:
+                                       mailbox_tbl.mailbox_name = EMAIL_DRAFTBOX_NAME;
+                                       mailbox_tbl.alias = EMAIL_DRAFTBOX_DISPLAY_NAME;
+                                       break;
+
+                               case EMAIL_MAILBOX_TYPE_SPAMBOX:
+                                       mailbox_tbl.mailbox_name = EMAIL_SPAMBOX_NAME;
+                                       mailbox_tbl.alias = EMAIL_SPAMBOX_DISPLAY_NAME;
+                                       break;
+
+                               case EMAIL_MAILBOX_TYPE_OUTBOX:
+                                       mailbox_tbl.mailbox_name = EMAIL_OUTBOX_NAME;
+                                       mailbox_tbl.alias = EMAIL_OUTBOX_DISPLAY_NAME;
+                                       break;
+
+                               default:
+                                       mailbox_tbl.mailbox_name = EMAIL_INBOX_NAME;
+                                       mailbox_tbl.alias = EMAIL_INBOX_DISPLAY_NAME;
+                                       break;
+                       }
 
-       emstorage_mailbox_tbl_t *local_mailbox_list = NULL;
-       int select_num = 0;
-       i = 0;
-       email_mailbox_t mailbox;
-
-       if (emstorage_get_mailbox_by_modifiable_yn(account_id, 0 /* modifiable_yn */, &select_num, &local_mailbox_list, true, &err)) {
-               if (local_mailbox_list) {
-                       for (i = 0; i < select_num; i++) {
-                               EM_DEBUG_LOG(">>> MailBox needs to be Deleted[ %s ] ", local_mailbox_list[i].mailbox_name);
-                               mailbox.account_id = local_mailbox_list[i].account_id;
-                               mailbox.mailbox_name = local_mailbox_list[i].mailbox_name;
-                               mailbox.mailbox_id = local_mailbox_list[i].mailbox_id;
-                               if (!emcore_delete_mailbox_all(&mailbox, &err)) {
-                                       EM_DEBUG_EXCEPTION(" emcore_delete_all of Mailbox [%s] Failed ", mailbox.mailbox_name);
-                                       emstorage_free_mailbox(&local_mailbox_list, select_num, NULL); 
-                                       local_mailbox_list = NULL;
-                                       goto FINISH_OFF;
-                               }
+                       if (!emstorage_add_mailbox(&mailbox_tbl, true, &err)) {
+                               EM_DEBUG_EXCEPTION("emstorage_add_mailbox failed - %d", err);
+                               goto FINISH_OFF;
                        }
-                       emstorage_free_mailbox(&local_mailbox_list, select_num, NULL); 
-                       local_mailbox_list = NULL;
                }
+               EM_SAFE_FREE(mailbox_name_for_mailbox_type);
        }
-
        if (!emstorage_set_all_mailbox_modifiable_yn(account_id, 0, true, &err)) {
-                       EM_DEBUG_EXCEPTION(" >>>> emstorage_set_all_mailbox_modifiable_yn Failed [ %d ]", err);
-                       goto FINISH_OFF;
+               EM_DEBUG_EXCEPTION(" >>>> emstorage_set_all_mailbox_modifiable_yn Failed [ %d ]", err);
+               goto FINISH_OFF;
        }
        
        if (!emcore_check_thread_status())  {
@@ -560,10 +650,19 @@ FINISH_OFF:
        }
 
        if (stream) 
-               emcore_close_mailbox(account_id, stream);
+               stream = mail_close (stream);
        
        if (mailbox_list) 
-               emcore_free_internal_mailbox(&mailbox_list, count, NULL);
+               emcore_free_internal_mailbox (&mailbox_list, count, NULL);
+
+       if (local_mailbox_list) 
+               emstorage_free_mailbox (&local_mailbox_list, local_mailbox_count, NULL);
+
+       if (local_box_only) 
+               g_list_free (local_box_only);
+
+       if (remote_box_only)
+               g_list_free (remote_box_only);
 
        if (err_code != NULL)
                *err_code = err;
@@ -579,16 +678,16 @@ int emcore_download_mailbox_list(void *mail_stream,
 {
        EM_DEBUG_FUNC_BEGIN("mail_stream [%p], mailbox_name [%p], mailbox_list [%p], count [%p], err_code [%p]", mail_stream, mailbox_name, mailbox_list, count, err_code);
 
-    MAILSTREAM *stream = mail_stream;
-    email_callback_holder_t holder;
-    char *pattern = NULL;
-    char *reference = NULL;
-    int   err = EMAIL_ERROR_NONE;
-    int   ret = false;
+       MAILSTREAM *stream = mail_stream;
+       email_callback_holder_t holder;
+       char *pattern = NULL;
+       char *reference = NULL;
+       int   err = EMAIL_ERROR_NONE;
+       int   ret = false;
 
        if (!stream || !mailbox_list || !count) {
-        err = EMAIL_ERROR_INVALID_PARAM;
-        goto FINISH_OFF;
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
        }
        
        memset(&holder, 0x00, sizeof(holder));
@@ -608,18 +707,18 @@ int emcore_download_mailbox_list(void *mail_stream,
                reference = EM_SAFE_STRDUP(stream->original_mailbox);
 
        pattern        = "*";
-    stream->sparep = &holder;
+       stream->sparep = &holder;
 
        /*  imap command : tag LIST reference * */
-    /*  see callback function mm_list */
-       mail_list(stream, reference, pattern);
+       /*  see callback function mm_list */
+       mail_list (stream, reference, pattern);
 
-    stream->sparep = NULL;
+       stream->sparep = NULL;
 
        EM_SAFE_FREE(reference);
 
-    *count        = holder.num;
-    *mailbox_list = (email_internal_mailbox_t*)holder.data;
+       *count        = holder.num;
+       *mailbox_list = (email_internal_mailbox_t*) holder.data;
 
        ret = true;
 
@@ -631,344 +730,74 @@ FINISH_OFF:
 }
 
 /* description
- *    check whether this imap mailbox is synchronous mailbox
+ *    create a new imap mailbox
  * arguments
- *    mailbox  :  imap mailbox to be checked
- *    synchronous  :   boolean variable to be synchronous (1 : sync 0 : non-sync)
+ *    new_mailbox  :  imap mailbox to be created
  * return
  *    succeed  :  1
  *    fail  :  0
  */
-int emcore_check_sync_imap_mailbox(email_mailbox_t *mailbox, int *synchronous, int *err_code)
+INTERNAL_FUNC int emcore_create_imap_mailbox(email_mailbox_t *mailbox, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN();
-       
-       EM_DEBUG_LOG("\t mailbox[%p], synchronous[%p], err_code[%p]", mailbox, synchronous, err_code);
-       
-       if (err_code) {
-               *err_code = EMAIL_ERROR_NONE;
-       }
-
-       if (!mailbox || !synchronous) {
-               EM_DEBUG_EXCEPTION("\t mailbox[%p], synchronous[%p]", mailbox, synchronous);
-               
-               if (err_code != NULL)
-                       *err_code = EMAIL_ERROR_INVALID_PARAM;
-               return false;
-       }
-       
+       MAILSTREAM *stream = NULL;
+       char *long_enc_path = NULL;
+       void *tmp_stream = NULL;
        int ret = false;
        int err = EMAIL_ERROR_NONE;
-       emstorage_mailbox_tbl_t *imap_mailbox_tbl = NULL;
 
-       if (!emstorage_get_mailbox_by_name(mailbox->account_id, 0, mailbox->mailbox_name, &imap_mailbox_tbl, true, &err))  {
-               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_name failed - %d", err);
+       EM_DEBUG_FUNC_BEGIN();
+
+       if (!mailbox) {
+               err = EMAIL_ERROR_INVALID_PARAM;
                goto FINISH_OFF;
        }
-       
-       *synchronous = imap_mailbox_tbl ? 1  :  0;
-       
-       ret = true;
-       
-FINISH_OFF: 
-       if (imap_mailbox_tbl != NULL)
-               emstorage_free_mailbox(&imap_mailbox_tbl, 1, NULL);
-       
-       if (err_code != NULL)
-               *err_code = err;
-       
-       return ret;
-}
 
+       /* connect mail server */
+       stream = NULL;
+       if (!emcore_connect_to_remote_mailbox(mailbox->account_id, 0, (void **)&tmp_stream, &err)) {
+               EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed [%d]", err);
+               goto FINISH_OFF;
+       }
 
-/* description
- *    set sync imap mailbox
- * arguments
- *    mailbox_list  :  imap mailbox to be synced
- *    syncronous  :  0-sync 1 : non-sync
- * return
- *    succeed  :  1
- *    fail  :  0
- */
+       stream = (MAILSTREAM *) tmp_stream;
 
-INTERNAL_FUNC int emcore_set_sync_imap_mailbox(email_internal_mailbox_t *mailbox, int synchronous, int *err_code)
-{
-       EM_DEBUG_FUNC_BEGIN("mailbox[%p], synchronous[%d], err_code[%p]", mailbox, synchronous, err_code);
-       
-       if (!mailbox)  {
-               EM_DEBUG_EXCEPTION("mailbox[%p], synchronous[%d]", mailbox, synchronous);
-               if (err_code != NULL)
-                       *err_code = EMAIL_ERROR_INVALID_PARAM;
-               return false;
+       /* encode mailbox name by UTF7, and rename to full path (ex : {mail.test.com}child_mailbox) */
+       if (!emcore_get_long_encoded_path(mailbox->account_id, mailbox->mailbox_name, '/', &long_enc_path, &err)) {
+               EM_DEBUG_EXCEPTION("emcore_get_long_encoded_path failed [%d]", err);
+               goto FINISH_OFF;
        }
-       
-       int ret = false;
-       int err = EMAIL_ERROR_NONE;
-       emstorage_mailbox_tbl_t *imap_mailbox_tbl_item = NULL;
-       emstorage_mailbox_tbl_t mailbox_tbl = { 0, };
-       emcore_uid_list *uid_list = NULL;
-       emstorage_read_mail_uid_tbl_t *downloaded_uids = NULL;
-       MAILSTREAM *stream = mailbox->mail_stream;
-       int mailbox_renamed = 0;
-       int j = 0;
-       int i = 0;
-       int temp = 0;
-       IMAPLOCAL *imap_local = NULL;
-       char cmd[128] = { 0 , }, tag[32] = { 0 , }, *p = NULL;
-               
-       if (synchronous) {              
-               /* if synchcronous, insert imap mailbox to db */
-               if (emstorage_get_mailbox_by_name(mailbox->account_id, 0, mailbox->mailbox_name, &imap_mailbox_tbl_item, true, &err))  {        
-                       /* mailbox already exists */
-                       /* mailbox Found, Do set the modifiable_yn = 1 */
-                       EM_DEBUG_LOG("mailbox already exists and setting modifiable_yn to 1");
-                       if (!emstorage_update_mailbox_modifiable_yn(mailbox->account_id, 0, mailbox->mailbox_name, 1, true, &err)) {
-                               EM_DEBUG_EXCEPTION(" emstorage_update_mailbox_modifiable_yn Failed [ %d ] ", err);
-                               goto JOB_ERROR;
-                       }
-               }
-               else {
-                       if (err != EMAIL_ERROR_MAILBOX_NOT_FOUND) {
-                               EM_DEBUG_EXCEPTION(">>>>.>>>>>Getting mailbox failed>>>>>>>>>>>>>>");
-                               /* This is error scenario so finish the job */
-                               goto JOB_ERROR;
-                       }
-                       else {
-                               /* This is not error scenario - mailbox is either new/renamed mailbox and needs to be added/modfied in DB */
-                               /* Now check if mailbox is renamed */
-                               EM_DEBUG_LOG(">>>>>>>>>>>>>>>>>>>>>>>MAILBOX NEW OR RENAMED");
-                               if (stream) {
-                                       imap_local = ((MAILSTREAM *)stream)->local;
-                                       EM_DEBUG_LINE;
-                                       sprintf(tag, "%08lx", 0xffffffff & (((MAILSTREAM *)stream)->gensym++));
-                                       EM_DEBUG_LINE;
-                                       sprintf(cmd, "%s SELECT %s\015\012", tag, mailbox->mailbox_name);
-                                       EM_DEBUG_LINE;
 
-                               }
-                               
-                               /* select the mailbox and get its UID */
-                               if (!imap_local || !imap_local->netstream || !net_sout(imap_local->netstream, cmd, (int)EM_SAFE_STRLEN(cmd))) {
-                                       EM_DEBUG_EXCEPTION("network error - failed to IDLE on Mailbox [%s]", mailbox->mailbox_name);
-                                       /*
-                                       err = EMAIL_ERROR_CONNECTION_BROKEN;
-                                       if(imap_local)
-                                               imap_local->netstream = NULL;
-                                       mailbox->mail_stream = NULL;
-                                       goto JOB_ERROR;
-                                       */
-                               }
-                               else {
-                                       EM_DEBUG_LOG("Get response for select call");
-                                       while (imap_local->netstream) {
-                                       p = net_getline(imap_local->netstream);
-                                               EM_DEBUG_LOG("p =[%s]", p);
-                                               if (!strncmp(p, "+", 1)) {
-                                                       ret = 1;
-                                                       break;
-                                               }
-                                               else if (!strncmp(p, "*", 1)) {
-                                               EM_SAFE_FREE(p); 
-                                               continue;
-                                               }
-                                               else {
-                                                       ret = 0;
-                                                       break;
-                                               }
-                               }
-                                       EM_SAFE_FREE(p); 
-                                       EM_DEBUG_LINE;
-                                       /* check if OK or BAD response comes. */
-                                       /* if response is OK the try getting UID list. */
-                                       if (!strncmp((char *)imap_local->reply.key, "OK", strlen("OK")))  {
-                                               EM_DEBUG_LOG(">>>>>>>>>>Select success on %s mailbox", mailbox->mailbox_name);
-                                               if (!imap4_mailbox_get_uids(stream, &uid_list, &err)) {
-                                                       EM_DEBUG_EXCEPTION("imap4_mailbox_get_uids failed - %d", err);
-                                                       EM_SAFE_FREE(uid_list);
-                                               }
-                                               else {
-                                                       if (!emstorage_get_downloaded_list(mailbox->account_id, 0, &downloaded_uids, &j, true, &err)) {
-                                                               EM_DEBUG_EXCEPTION("emstorage_get_downloaded_list failed [%d]", err);
-                                               
-                                                               downloaded_uids = NULL;
-                                                       }
-                                                       else /* Prevent Defect - 28497 */ {
-                                                               emcore_uid_list *uid_elem = uid_list;
-                                                               emcore_uid_list *next_uid_elem = NULL;
-                                                               if (uid_elem) {
-                                                                       for (i = j; (i > 0 && !mailbox_renamed); i--)  {
-                                                                               if (uid_elem) {
-                                                                                       next_uid_elem = uid_elem->next;
-                                                                                       if (uid_elem->uid && downloaded_uids[i - 1].s_uid && !strcmp(uid_elem->uid, downloaded_uids[i - 1].s_uid)) {
-                                                                                               temp = i-1;
-                                                                                               mailbox_renamed = 1;
-                                                                                               break;
-                                                                                       }
-                                                                                       EM_SAFE_FREE(uid_elem->uid);
-                                                                                       uid_elem = next_uid_elem;
-                                                                               }
-                                                                       }
-                                                               }
-                                                       }
-                                               }
-                                       } /* mailbox selected */
-                               }       
-
-                               if (mailbox_renamed) /* renamed mailbox */ {
-                                       EM_DEBUG_LOG("downloaded_uids[temp].mailbox_name [%s]", downloaded_uids[temp].mailbox_name);
-
-                                       mailbox_renamed = 0;
-
-                                       memset(&mailbox_tbl, 0, sizeof(emstorage_mailbox_tbl_t));
-
-                                       mailbox_tbl.account_id = mailbox->account_id;
-                                       mailbox_tbl.local_yn = 0;
-                                       mailbox_tbl.mailbox_name = mailbox->mailbox_name;
-                                       mailbox_tbl.mailbox_type = mailbox->mailbox_type;
-
-                                       /* Get the Alias Name after parsing the Full mailbox Path */
-                                       if(mailbox->alias == NULL)
-                                               mailbox->alias = emcore_get_alias_of_mailbox((const char *)mailbox->mailbox_name);
-                                       
-                                       mailbox_tbl.alias = mailbox->alias;
-                                       mailbox_tbl.deleted_flag  = 1;
-                                       mailbox_tbl.modifiable_yn = 1;
-                                       mailbox_tbl.total_mail_count_on_server = 0;
-                                       
-                                       /* if non synchronous, delete imap mailbox from db */
-                                       if (!emstorage_update_mailbox(mailbox->account_id, 0, downloaded_uids[temp].mailbox_id, &mailbox_tbl, true, &err)) {
-                                               EM_DEBUG_EXCEPTION(" emstorage_update_mailbox Failed [%d] ", err);
-                                               goto JOB_ERROR;
-                                       }
-                                       
-                               }
-                               else /* Its a Fresh Mailbox */ {
-                                       memset(&mailbox_tbl, 0, sizeof(emstorage_mailbox_tbl_t));
-
-                                       mailbox_tbl.mailbox_id     = mailbox->mailbox_id;
-                                       mailbox_tbl.account_id     = mailbox->account_id;
-                                       mailbox_tbl.local_yn       = 0;
-                                       mailbox_tbl.deleted_flag   = 0;
-                                       mailbox_tbl.mailbox_type   = mailbox->mailbox_type;
-                                       mailbox_tbl.mailbox_name   = mailbox->mailbox_name;
-                                       mailbox_tbl.mail_slot_size = mailbox->mail_slot_size;
-                                       mailbox_tbl.no_select      = mailbox->no_select;
-
-                                       /* Get the Alias Name after Parsing the Full mailbox Path */
-                                       if(mailbox->alias == NULL)
-                                       mailbox->alias = emcore_get_alias_of_mailbox((const char *)mailbox->mailbox_name);
-
-                                       if (mailbox->alias) {
-                                               EM_DEBUG_LOG("mailbox->alias [%s] ", mailbox->alias);
-
-                                               mailbox_tbl.alias = mailbox->alias;
-                                               mailbox_tbl.modifiable_yn = 1; 
-                                               mailbox_tbl.total_mail_count_on_server = 0;
-                                                       
-                                               EM_DEBUG_LOG("mailbox_tbl.mailbox_type - %d", mailbox_tbl.mailbox_type);
-
-                                               if (!emstorage_add_mailbox(&mailbox_tbl, true, &err)) {
-                                                       EM_DEBUG_EXCEPTION("emstorage_add_mailbox failed - %d", err);
-                                                       goto JOB_ERROR;
-                                               }
-                                       }
-                               }
-                       }
-               }
+       /* create mailbox */
+       if (!mail_create(stream, long_enc_path)) {
+               EM_DEBUG_EXCEPTION("mail_create failed");
+               err = EMAIL_ERROR_IMAP4_CREATE_FAILURE;
+               goto FINISH_OFF;
        }
 
-       /* set sync db mailbox */
-       mailbox->synchronous = synchronous;
-       
-       ret = true;
-       
-JOB_ERROR:
-
-       if (downloaded_uids) 
-               emstorage_free_read_mail_uid(&downloaded_uids, j, NULL);
-
-       if (imap_mailbox_tbl_item)
-               emstorage_free_mailbox(&imap_mailbox_tbl_item, 1, NULL);
-
-       if (err_code)
-               *err_code = err;
-       
-       return ret;
-}
-
-/* description
- *    create a new imap mailbox
- * arguments
- *    new_mailbox  :  imap mailbox to be created
- * return
- *    succeed  :  1
- *    fail  :  0
- */
-INTERNAL_FUNC int emcore_create_imap_mailbox(email_mailbox_t *mailbox, int *err_code)
-{
-    MAILSTREAM *stream = NULL;
-    char *long_enc_path = NULL;
-    void *tmp_stream = NULL;
-    int ret = false;
-    int err = EMAIL_ERROR_NONE;
-
-    EM_DEBUG_FUNC_BEGIN();
-
-    if (!mailbox) {
-        err = EMAIL_ERROR_INVALID_PARAM;
-        goto FINISH_OFF;
-    }
-
-    /* connect mail server */
-    stream = NULL;
-    if (!emcore_connect_to_remote_mailbox(mailbox->account_id, 0, (void **)&tmp_stream, &err)) {
-       EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed [%d]", err);
-        goto FINISH_OFF;
-    }
-
-    stream = (MAILSTREAM *)tmp_stream;
-
-    /* encode mailbox name by UTF7, and rename to full path (ex : {mail.test.com}child_mailbox) */
-    if (!emcore_get_long_encoded_path(mailbox->account_id, mailbox->mailbox_name, '/', &long_enc_path, &err)) {
-       EM_DEBUG_EXCEPTION("emcore_get_long_encoded_path failed [%d]", err);
-        goto FINISH_OFF;
-    }
-
-    /* create mailbox */
-    if (!mail_create(stream, long_enc_path)) {
-       EM_DEBUG_EXCEPTION("mail_create failed");
-        err = EMAIL_ERROR_IMAP4_CREATE_FAILURE;
-        goto FINISH_OFF;
-    }
-
-       emcore_close_mailbox(0, stream);
-       stream = NULL;
-
-    EM_SAFE_FREE(long_enc_path);
+       EM_SAFE_FREE(long_enc_path);
 
-    ret = true;
+       ret = true;
 
 FINISH_OFF:
-    if (stream){
-               emcore_close_mailbox(0, stream);
-               stream = NULL;
-    }
+       if (stream) {
+               stream = mail_close (stream);
+       }
 
-    EM_SAFE_FREE(long_enc_path);
+       EM_SAFE_FREE(long_enc_path);
 
-    if (mailbox) {
+       if (mailbox) {
                if (err == EMAIL_ERROR_NONE) {
-                       if(!emcore_notify_network_event(NOTI_ADD_MAILBOX_FINISH, mailbox->account_id, mailbox->mailbox_name, 0, 0))
-                       EM_DEBUG_EXCEPTION("emcore_notify_network_event[NOTI_ADD_MAILBOX_FINISH] failed");
+                       if (!emcore_notify_network_event (NOTI_ADD_MAILBOX_FINISH, mailbox->account_id, mailbox->mailbox_name, 0, 0))
+                               EM_DEBUG_EXCEPTION("emcore_notify_network_event[NOTI_ADD_MAILBOX_FINISH] failed");
                }
-               else if (!emcore_notify_network_event(NOTI_ADD_MAILBOX_FAIL, mailbox->account_id, mailbox->mailbox_name, 0, err))
+               else if (!emcore_notify_network_event (NOTI_ADD_MAILBOX_FAIL, mailbox->account_id, mailbox->mailbox_name, 0, err))
                        EM_DEBUG_EXCEPTION("emcore_notify_network_event[NOTI_ADD_MAILBOX_FAIL] failed");
-    }
+       }
 
-    if (err_code)
-        *err_code = err;
+       if (err_code)
+               *err_code = err;
 
-    return ret;
+       return ret;
 }
 
 
@@ -1029,17 +858,13 @@ INTERNAL_FUNC int emcore_delete_imap_mailbox(int input_mailbox_id, int *err_code
                goto FINISH_OFF;
        }
 
-       emcore_close_mailbox(0, stream);
-       stream = NULL;
-
        EM_SAFE_FREE(long_enc_path);
 
        ret = true;
 
 FINISH_OFF:
        if (stream) {
-               emcore_close_mailbox(0, stream);
-               stream = NULL;
+               stream = mail_close (stream);
        }
 
        if (ref_account) {
@@ -1136,10 +961,122 @@ FINISH_OFF:
        }
 
        if (stream) {
-               emcore_close_mailbox(0, stream);
-               stream = NULL;
+               stream = mail_close (stream);
        }
 
        EM_DEBUG_FUNC_END("err [%d]", err);
        return err;
 }
+
+
+#ifdef __FEATURE_IMAP_QUOTA__
+
+quota_t callback_for_get_quota_root(MAILSTREAM *stream, unsigned char *mailbox, STRINGLIST *quota_root_list)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       quota_t ret_quota;
+       EM_DEBUG_FUNC_END();
+       return ret_quota;
+}
+
+quota_t callback_for_get_quota(MAILSTREAM *stream, unsigned char *quota_root, QUOTALIST *quota_list)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       quota_t ret_quota;
+       EM_DEBUG_FUNC_END();
+       return ret_quota;
+}
+
+
+INTERNAL_FUNC int emcore_register_quota_callback()
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int err = EMAIL_ERROR_NONE;
+
+       mail_parameters(NULL, SET_QUOTAROOT, callback_for_get_quota_root); /* set callback function for handling quota root message */
+       mail_parameters(NULL, SET_QUOTA,     callback_for_get_quota);      /* set callback function for handling quota message */
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC int emcore_get_quota_root(int input_mailbox_id, email_quota_resource_t *output_list_of_resource_limits)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mailbox_id[%d], output_list_of_resource_limits[%p]", input_mailbox_id, output_list_of_resource_limits);
+       int err = EMAIL_ERROR_NONE;
+       MAILSTREAM *stream = NULL;
+       email_account_t *ref_account = NULL;
+       emstorage_mailbox_tbl_t *mailbox_tbl = NULL;
+
+       if ((err = emstorage_get_mailbox_by_id(input_mailbox_id, &mailbox_tbl)) != EMAIL_ERROR_NONE || !mailbox_tbl) {
+               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_id failed. [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       ref_account = emcore_get_account_reference(mailbox_tbl->account_id);
+
+       if (!ref_account || ref_account->incoming_server_type != EMAIL_SERVER_TYPE_IMAP4) {
+               EM_DEBUG_EXCEPTION("Invalid account information");
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+
+       /* connect mail server */
+       if (!emcore_connect_to_remote_mailbox(mailbox_tbl->account_id, 0, (void **)&stream, &err)) {
+               EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       imap_getquotaroot(stream, mailbox_tbl->mailbox_name);
+
+FINISH_OFF:
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC int emcore_get_quota(int input_mailbox_id, char *input_quota_root, email_quota_resource_t *output_list_of_resource_limits)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mailbox_id[%d] input_quota_root[%p] output_list_of_resource_limits[%p]", input_mailbox_id, input_quota_root, output_list_of_resource_limits);
+       int err = EMAIL_ERROR_NONE;
+       MAILSTREAM *stream = NULL;
+       email_account_t *ref_account = NULL;
+       emstorage_mailbox_tbl_t *mailbox_tbl = NULL;
+
+       if ((err = emstorage_get_mailbox_by_id(input_mailbox_id, &mailbox_tbl)) != EMAIL_ERROR_NONE || !mailbox_tbl) {
+               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_id failed. [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       ref_account = emcore_get_account_reference(mailbox_tbl->account_id);
+
+       if (!ref_account || ref_account->incoming_server_type != EMAIL_SERVER_TYPE_IMAP4) {
+               EM_DEBUG_EXCEPTION("Invalid account information");
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+
+       /* connect mail server */
+       if (!emcore_connect_to_remote_mailbox(mailbox_tbl->account_id, 0, (void **)&stream, &err)) {
+               EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       imap_getquota(stream, input_quota_root);
+
+FINISH_OFF:
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC int emcore_set_quota(int input_mailbox_id, char *input_quota_root, email_quota_resource_t *input_list_of_resource_limits)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mailbox_id[%d] input_quota_root[%p] output_list_of_resource_limits[%p]", input_mailbox_id, input_quota_root, input_list_of_resource_limits);
+       int err = EMAIL_ERROR_NONE;
+       /* TODO : set quota using the function 'imap_setquota' */
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+#endif /* __FEATURE_IMAP_QUOTA__ */
index 2697943..c27f48f 100755 (executable)
@@ -42,6 +42,8 @@
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <unistd.h>
+#include <glib.h>
+#include <glib/gstdio.h>
 
 #include <vconf.h> 
 #include <contacts.h>
 #include "email-convert.h"
 #include "email-debug-log.h"
 
+#ifdef __FEATURE_USE_GMIME__
+#include "email-core-gmime.h"
+#endif /* __FEATURE_USE_GMIME__ */
+
 #ifdef __FEATURE_DRM__
 #include <drm_client.h>
 #endif /* __FEATURE_DRM__ */
@@ -144,7 +150,7 @@ static void _print_stringlist(STRINGLIST *stringlist)
        }
 }
 
-static void _print_body(BODY *body, int recursive)
+void _print_body(BODY *body, int recursive)
 {
        EM_DEBUG_LOG(" ========================================================== ");
        
@@ -157,7 +163,7 @@ static void _print_body(BODY *body, int recursive)
                
                _print_parameter(body->parameter);
                
-               EM_DEBUG_LOG("body->id[%s]", body->id);
+               EM_DEBUG_LOG_SEC("body->id[%s]", body->id);
                EM_DEBUG_LOG("body->description[%s]", body->description);
                
                EM_DEBUG_LOG("body->disposition.type[%s]", body->disposition.type);
@@ -169,7 +175,7 @@ static void _print_body(BODY *body, int recursive)
                
                _print_stringlist(body->language);
                
-               EM_DEBUG_LOG("body->location[%s]", body->location);
+               EM_DEBUG_LOG_SEC("body->location[%s]", body->location);
        
                EM_DEBUG_LOG("body->mime.offset[%ld]", body->mime.offset);
                EM_DEBUG_LOG("body->mime.text.data[%s]", body->mime.text.data);
@@ -263,8 +269,7 @@ static int pop3_mail_delete(MAILSTREAM *stream, int msgno, int *err_code)
        ret = true;
 
 FINISH_OFF: 
-       if (p)
-               free(p);
+       EM_SAFE_FREE(p);
        
        if (err_code)
                *err_code = err;
@@ -473,7 +478,7 @@ INTERNAL_FUNC int emcore_move_mail_on_server_ex(int account_id, int src_mailbox_
                EM_DEBUG_LOG("calling mail_copy_full FODLER MAIL COPY ");
                /*  [h.gahlaut] Break the set of mail_ids into comma separated strings of given length  */
                /*  Length is decided on the basis of remaining keywords in the Query to be formed later on in emstorage_get_id_set_from_mail_ids  */
-               /*  Here about 90 bytes are required for fixed keywords in the query-> SELECT local_uid, s_uid from mail_read_mail_uid_tbl where local_uid in (....) ORDER by s_uid  */
+               /*  Here about 90 bytes are required for fixed keywords in the query-> SELECT local_uid, server_uid from mail_read_mail_uid_tbl where local_uid in (....) ORDER by server_uid  */
                /*  So length of comma separated strings which will be filled in (.....) in above query can be maximum QUERY_SIZE - 90  */
                
                if (false == emcore_form_comma_separated_strings(mail_ids, num, QUERY_SIZE - 90, &string_list, &string_count, &err_code))   {
@@ -545,8 +550,9 @@ INTERNAL_FUNC int emcore_move_mail_on_server_ex(int account_id, int src_mailbox_
        ret = true;
 
 FINISH_OFF: 
-       emcore_close_mailbox(0, stream);
-       stream = NULL;
+       emcore_free_comma_separated_strings(&string_list, &string_count); /*prevent 17958*/
+
+       stream = mail_close (stream);
 
        if (ref_account) {
                emcore_free_account(ref_account);
@@ -623,7 +629,11 @@ int emcore_delete_mails_from_imap4_server(int mail_ids[], int num, int from_serv
        }
 
        if (!mail_tbl_data || mail_tbl_data->account_id <= 0 || mail_tbl_data->mailbox_id <= 0) {
-               EM_DEBUG_EXCEPTION("mail_tbl_data [%p]", mail_tbl_data);
+               if(mail_tbl_data)
+                       EM_DEBUG_EXCEPTION("mail_tbl_data->account_id[%d] mail_tbl_data->mailbox_id[%d]", mail_tbl_data->account_id, mail_tbl_data->mailbox_id);
+               else
+                       EM_DEBUG_EXCEPTION("mail_tbl_data [%p]", mail_tbl_data);
+
                goto FINISH_OFF;
        }
 
@@ -634,7 +644,7 @@ int emcore_delete_mails_from_imap4_server(int mail_ids[], int num, int from_serv
 
        /*  [h.gahlaut] Break the set of mail_ids into comma separated strings of given length  */
        /*  Length is decided on the basis of remaining keywords in the Query to be formed later on in emstorage_get_id_set_from_mail_ids  */
-       /*  Here about 90 bytes are required for fixed keywords in the query-> SELECT local_uid, s_uid from mail_read_mail_uid_tbl where local_uid in (....) ORDER by s_uid  */
+       /*  Here about 90 bytes are required for fixed keywords in the query-> SELECT local_uid, server_uid from mail_read_mail_uid_tbl where local_uid in (....) ORDER by server_uid  */
        /*  So length of comma separated strings which will be filled in (.....) in above query can be maximum QUERY_SIZE - 90  */
 
        if (false == emcore_form_comma_separated_strings(mail_ids, num, QUERY_SIZE - 90, &string_list, &string_count, &err)) {
@@ -870,6 +880,11 @@ int emcore_delete_mails_from_imap4_server(int mail_ids[], int num, int from_serv
 
 FINISH_OFF: 
        EM_SAFE_FREE(p);
+       EM_SAFE_FREE(id_set); /*prevent 17954*/
+       
+       if (stream)  {
+               stream = mail_close (stream);
+       }
        
        emcore_free_comma_separated_strings(&string_list, &string_count);
 
@@ -931,7 +946,6 @@ static int imap4_send_command(MAILSTREAM *stream, imap4_cmd_t cmd_type, int *err
                /*  receive response */
                if (!(p = net_getline(imaplocal->netstream))) {
                        EM_DEBUG_EXCEPTION("net_getline failed...");
-                       
                        err = EMAIL_ERROR_INVALID_RESPONSE;             /* EMAIL_ERROR_UNKNOWN; */
                        goto FINISH_OFF;
                }
@@ -967,7 +981,7 @@ FINISH_OFF:
 
 int emcore_get_mail_contact_info_with_update(email_mail_contact_info_t *contact_info, char *full_address, int mail_id, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("contact_info[%p], full_address[%s], mail_id[%d], err_code[%p]", contact_info, full_address, mail_id, err_code);
+       EM_DEBUG_FUNC_BEGIN_SEC("contact_info[%p], full_address[%s], mail_id[%d], err_code[%p]", contact_info, full_address, mail_id, err_code);
        
        int ret = false;
        int err = EMAIL_ERROR_NONE;
@@ -1005,7 +1019,7 @@ int emcore_get_mail_contact_info_with_update(email_mail_contact_info_t *contact_
        }
 
        em_skip_whitespace(full_address , &address);
-       EM_DEBUG_LOG("address[address][%s]", address);  
+       EM_DEBUG_LOG_SEC("address[address][%s]", address);
 
 
        /*  ',' -> "%2C" */
@@ -1021,12 +1035,12 @@ int emcore_get_mail_contact_info_with_update(email_mail_contact_info_t *contact_
                        p[i] = ',';
                i++;
        }
-       EM_DEBUG_LOG("  2  converted address %s ", p);
+       EM_DEBUG_LOG_SEC("  2  converted address %s ", p);
 
        rfc822_parse_adrlist(&addr, p, NULL);
 
        EM_SAFE_FREE(p);
-       EM_DEBUG_LOG("  3  full_address  %s ", full_address);
+       EM_DEBUG_LOG_SEC("  3  full_address  %s ", full_address);
 
        if (!addr) {
                EM_DEBUG_EXCEPTION("rfc822_parse_adrlist failed...");
@@ -1062,7 +1076,7 @@ int emcore_get_mail_contact_info_with_update(email_mail_contact_info_t *contact_
                email_address = g_strdup_printf("%s@%s", addr->mailbox ? addr->mailbox  :  "", addr->host ? addr->host  :  "");
                
                EM_DEBUG_LOG(" addr->personal[%s]", addr->personal);
-               EM_DEBUG_LOG(" email_address[%s]", email_address);
+               EM_DEBUG_LOG_SEC(" email_address[%s]", email_address);
        
                is_searched = false;
                EM_DEBUG_LOG(" >>>>> emcore_get_mail_contact_info - 10");
@@ -1070,7 +1084,7 @@ int emcore_get_mail_contact_info_with_update(email_mail_contact_info_t *contact_
                if (emcore_get_mail_display_name(email_address, &contact_display_name_from_contact_info, &err) && err == EMAIL_ERROR_NONE) {
                        contact_display_name = contact_display_name_from_contact_info;
 
-                       EM_DEBUG_LOG(">>> contact_name[%s]", contact_display_name);
+                       EM_DEBUG_LOG_SEC(">>> contact_name[%s]", contact_display_name);
                        /*  Make display name string */
                        is_searched = true;
 
@@ -1113,7 +1127,7 @@ int emcore_get_mail_contact_info_with_update(email_mail_contact_info_t *contact_
                                }
                                snprintf(contact_name + contact_name_len, contact_name_buffer_size - contact_name_len, "%s", temp_string);
                                contact_name_len += contact_display_name_len;
-                               EM_DEBUG_LOG("new contact_name >>>>> %s ", contact_name);
+                               EM_DEBUG_LOG_SEC("new contact_name >>>>> %s ", contact_name);
                        }
                }
                else {
@@ -1145,8 +1159,8 @@ int emcore_get_mail_contact_info_with_update(email_mail_contact_info_t *contact_
                        contact_info->storage_type = -1;
 
                        /*  Make display name string */
-                       EM_DEBUG_LOG("contact_display_name : [%s]", contact_display_name);
-                       EM_DEBUG_LOG("email_address : [%s]", email_address);
+                       EM_DEBUG_LOG_SEC("contact_display_name : [%s]", contact_display_name);
+                       EM_DEBUG_LOG_SEC("email_address : [%s]", email_address);
 
                        /*  if mail_id is 0, return only contact info without saving contact info to DB */
                        if (mail_id == 0 || (contact_name_len == 0))             {      /*  save only the first address information - 09-SEP-2010 */
@@ -1176,7 +1190,7 @@ int emcore_get_mail_contact_info_with_update(email_mail_contact_info_t *contact_
                                
                                snprintf(contact_name + contact_name_len, contact_name_buffer_size - contact_name_len, "%s", temp_string);
                                contact_name_len += contact_display_name_len;
-                               EM_DEBUG_LOG("new contact_name >>>>> %s ", contact_name);
+                               EM_DEBUG_LOG_SEC("new contact_name >>>>> %s ", contact_name);
                        }
                }
 
@@ -1186,7 +1200,7 @@ int emcore_get_mail_contact_info_with_update(email_mail_contact_info_t *contact_
                                EM_SAFE_STRCAT(temp_emailaddr, email_address);
                                if (addr->next != NULL)
                                        EM_SAFE_STRCAT(temp_emailaddr, ", ");
-                               EM_DEBUG_LOG(">>>> TEMP EMail Address [ %s ] ", temp_emailaddr);
+                               EM_DEBUG_LOG_SEC(">>>> TEMP EMail Address [ %s ] ", temp_emailaddr);
                        }
                        else {  /*  save only the first address information - 09-SEP-2010 */
                                if (is_saved == 0) {
@@ -1197,7 +1211,7 @@ int emcore_get_mail_contact_info_with_update(email_mail_contact_info_t *contact_
                                        if (addr->next != NULL)
                                                EM_SAFE_STRCAT(temp_emailaddr, ", ");
                                        */
-                                       EM_DEBUG_LOG(">>>> TEMP EMail Address [ %s ] ", temp_emailaddr);
+                                       EM_DEBUG_LOG_SEC(">>>> TEMP EMail Address [ %s ] ", temp_emailaddr);
                                }
                        }
                }
@@ -1439,23 +1453,23 @@ static int emcore_sync_address_info(email_address_type_t address_type, char *ful
 
                SNPRINTF(email_address, MAX_EMAIL_ADDRESS_LENGTH, "%s@%s", addr->mailbox ? addr->mailbox  :  "", addr->host ? addr->host  :  "");
  
-               EM_DEBUG_LOG("Search a contact  :  address[%s]", email_address);
+               EM_DEBUG_LOG_SEC("Search a contact  :  address[%s]", email_address);
 
                is_search = false;
 
                if (emcore_get_mail_display_name(email_address, &contact_display_name_from_contact_info, &error) && error == EMAIL_ERROR_NONE) {
-                       EM_DEBUG_LOG(">>> contact display name[%s]", contact_display_name_from_contact_info);
+                       EM_DEBUG_LOG_SEC(">>> contact display name[%s]", contact_display_name_from_contact_info);
 
                        is_search = true;
                }
-               else
+               else if (error != EMAIL_ERROR_DATA_NOT_FOUND)
                        EM_DEBUG_EXCEPTION("emcore_get_mail_display_name - Not found contact record(if err is -203) or error [%d]", error);
 
                if (is_search == true) {
                        p_address_info->contact_id = contact_index;             
                        p_address_info->storage_type = -1;                              
                        p_address_info->display_name = contact_display_name_from_contact_info;
-                       EM_DEBUG_LOG("display_name from contact[%s]", p_address_info->display_name);
+                       EM_DEBUG_LOG_SEC("display_name from contact[%s]", p_address_info->display_name);
                }
                else {
                        /*  if contact doesn't exist, use alias or email address as display name */
@@ -1481,22 +1495,22 @@ static int emcore_sync_address_info(email_address_type_t address_type, char *ful
                        else
                                p_address_info->display_name = EM_SAFE_STRDUP(alias);
 
-                       EM_DEBUG_LOG("display_name from email [%s]", p_address_info->display_name);
+                       EM_DEBUG_LOG_SEC("display_name from email [%s]", p_address_info->display_name);
                }
                
                p_address_info->address = EM_SAFE_STRDUP(email_address);
                p_address_info->address_type = address_type;
 
-               EM_DEBUG_LOG("email address[%s]", p_address_info->address);
+               EM_DEBUG_LOG_SEC("email address[%s]", p_address_info->address);
 
                *address_info_list = g_list_append(*address_info_list, p_address_info);
                p_address_info = NULL;
 
-               EM_DEBUG_LOG("after append");
+               EM_DEBUG_LOG_DEV ("after append");
 
                alias = NULL;
 
-               EM_DEBUG_LOG("next address[%p]", addr->next);
+               EM_DEBUG_LOG_DEV ("next address[%p]", addr->next);
 
                /*  next address */
                addr = addr->next;
@@ -1506,7 +1520,11 @@ static int emcore_sync_address_info(email_address_type_t address_type, char *ful
        
 FINISH_OFF: 
 
-       EM_SAFE_FREE(address);
+       EM_SAFE_FREE(address);
+
+       if (addr) {
+               mail_free_address(&addr);
+       }
        
        if (err_code != NULL)
                *err_code = error;      
@@ -1592,10 +1610,10 @@ INTERNAL_FUNC GList *emcore_get_recipients_list(GList *old_recipients_list, char
                
                SNPRINTF(email_address, MAX_EMAIL_ADDRESS_LENGTH, "%s@%s", addr->mailbox ? addr->mailbox : "", addr->host ? addr->host : "");
 
-               EM_DEBUG_LOG("Search a contact : address[%s]", email_address);
+               EM_DEBUG_LOG_SEC("Search a contact : address[%s]", email_address);
 
                if (emcore_get_mail_display_name(email_address, &display_name, &err) && err == EMAIL_ERROR_NONE) {
-                       EM_DEBUG_LOG(">>> contact display name[%s]", display_name);
+                       EM_DEBUG_LOG_SEC(">>> contact display name[%s]", display_name);
                        is_search = true;
                } else {
                        EM_DEBUG_LOG("emcore_get_mail_display_name - Not found contact record(if err is -203) or error [%d]", err);
@@ -1603,7 +1621,7 @@ INTERNAL_FUNC GList *emcore_get_recipients_list(GList *old_recipients_list, char
 
                if (is_search) {
                        temp_recipients_list->display_name = display_name;
-                       EM_DEBUG_LOG("display_name from contact[%s]", temp_recipients_list->display_name);
+                       EM_DEBUG_LOG_SEC("display_name from contact[%s]", temp_recipients_list->display_name);
                } else {
                        if (addr->personal != NULL) {
                                tokens = g_strsplit(addr->personal, "%2C", -1);
@@ -1620,11 +1638,11 @@ INTERNAL_FUNC GList *emcore_get_recipients_list(GList *old_recipients_list, char
                        else
                                temp_recipients_list->display_name = EM_SAFE_STRDUP(alias);
 
-                       EM_DEBUG_LOG("display_name from contact[%s]", temp_recipients_list->display_name);
+                       EM_DEBUG_LOG_SEC("display_name from contact[%s]", temp_recipients_list->display_name);
                }
 
                temp_recipients_list->address = EM_SAFE_STRDUP(email_address);
-               EM_DEBUG_LOG("email address[%s]", temp_recipients_list->address);
+               EM_DEBUG_LOG_SEC("email address[%s]", temp_recipients_list->address);
 
                EM_SAFE_FREE(display_name);
                EM_DEBUG_LOG("next address[%p]", addr->next);
@@ -1692,11 +1710,8 @@ INTERNAL_FUNC int emcore_get_mail_address_info_list(int mail_id, email_address_i
        }       
        memset(p_address_info_list, 0x00, sizeof(email_address_info_list_t));   
 
-       if ((contact_error = contacts_connect2()) == CONTACTS_ERROR_NONE)        {              
-               EM_DEBUG_LOG("Open Contact Service Success");   
-       }       
-       else     {              
-               EM_DEBUG_EXCEPTION("contact_db_service_connect failed [%d]", contact_error);            
+       if ((contact_error = contacts_connect2 ()) != CONTACTS_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("contacts_connect2 failed [%d]", contact_error);             
                err = EMAIL_ERROR_DB_FAILURE;
                goto FINISH_OFF;
        }
@@ -1710,10 +1725,8 @@ INTERNAL_FUNC int emcore_get_mail_address_info_list(int mail_id, email_address_i
        if (mail->full_address_bcc && emcore_sync_address_info(EMAIL_ADDRESS_TYPE_BCC, mail->full_address_bcc, &p_address_info_list->bcc, &err))
                failed = false;
 
-       if ((contact_error = contacts_disconnect2()) == CONTACTS_ERROR_NONE)
-               EM_DEBUG_LOG("Close Contact Service Success");
-       else
-               EM_DEBUG_EXCEPTION("Close Contact Service Fail [%d]", contact_error);
+       if ((contact_error = contacts_disconnect2 ()) != CONTACTS_ERROR_NONE)
+               EM_DEBUG_EXCEPTION("contacts_connect2 failed [%d]", contact_error);
 
        if (failed == false)
                ret = true;
@@ -1778,14 +1791,6 @@ FINISH_OFF:
 }
 
 
-/* internal function */
-void emcore_free_body_sharep(void **p)
-{
-       EM_DEBUG_FUNC_BEGIN();
-       EM_SAFE_FREE(*p);
-       EM_DEBUG_FUNC_END();
-}
-
 int emcore_check_drm(emstorage_attachment_tbl_t *input_attachment_tb_data)
 {
        EM_DEBUG_FUNC_BEGIN();
@@ -1860,13 +1865,14 @@ INTERNAL_FUNC int emcore_get_attachment_info(int attachment_id, email_attachment
                goto FINISH_OFF;
        }
        
-       (*attachment)->attachment_id = attachment_id;
-       (*attachment)->attachment_name = attachment_tbl->attachment_name; attachment_tbl->attachment_name = NULL;
-       (*attachment)->attachment_size = attachment_tbl->attachment_size;
-       (*attachment)->save_status = attachment_tbl->attachment_save_status;
-       (*attachment)->attachment_path = attachment_tbl->attachment_path; attachment_tbl->attachment_path = NULL;
-       (*attachment)->drm_status = attachment_tbl->attachment_drm_type;
+       (*attachment)->attachment_id         = attachment_id;
+       (*attachment)->attachment_name       = attachment_tbl->attachment_name; attachment_tbl->attachment_name = NULL;
+       (*attachment)->attachment_size       = attachment_tbl->attachment_size;
+       (*attachment)->save_status           = attachment_tbl->attachment_save_status;
+       (*attachment)->attachment_path       = attachment_tbl->attachment_path; attachment_tbl->attachment_path = NULL;
+       (*attachment)->drm_status            = attachment_tbl->attachment_drm_type;
        (*attachment)->inline_content_status = attachment_tbl->attachment_inline_content_status;
+       (*attachment)->attachment_mime_type  = attachment_tbl->attachment_mime_type; attachment_tbl->attachment_mime_type = NULL;
 
        ret = true;
 
@@ -1936,6 +1942,7 @@ INTERNAL_FUNC int emcore_get_attachment_data_list(int input_mail_id, email_attac
                        temp_attachment_data->save_status           = attachment_tbl_list[i].attachment_save_status;
                        temp_attachment_data->drm_status            = attachment_tbl_list[i].attachment_drm_type;
                        temp_attachment_data->inline_content_status = attachment_tbl_list[i].attachment_inline_content_status;
+                       temp_attachment_data->attachment_mime_type  = attachment_tbl_list[i].attachment_mime_type; attachment_tbl_list[i].attachment_mime_type = NULL;
                }
        }
        
@@ -1976,13 +1983,14 @@ INTERNAL_FUNC int emcore_download_attachment(int account_id, int mail_id, int nt
        struct attachment_info *ai = NULL;
        struct _m_content_info *cnt_info = NULL;
        void *tmp_stream = NULL;
-       char *s_uid = NULL, buf[1024];
+       char *server_uid = NULL, buf[1024];
        int msg_no = 0;
        emstorage_attachment_tbl_t *attachment_list = NULL;
        int current_attachment_no = 0;
        int attachment_count_to_be_downloaded = 0;              /*  how many attachments should be downloaded */
        int i = 0;
        int server_mbox_id = 0;
+       int decoded_attachment_size = 0;
 
        if (!emcore_check_thread_status())  {
                err = EMAIL_ERROR_CANCELLED;
@@ -1994,7 +2002,6 @@ INTERNAL_FUNC int emcore_download_attachment(int account_id, int mail_id, int nt
        /*  get mail from mail table. */
        if (!emstorage_get_mail_by_id(mail_id, &mail, true, &err) || !mail)  {
                EM_DEBUG_EXCEPTION("emstorage_get_mail_by_id failed [%d]", err);
-
                goto FINISH_OFF;
        }
 
@@ -2009,7 +2016,6 @@ INTERNAL_FUNC int emcore_download_attachment(int account_id, int mail_id, int nt
                attachment_count_to_be_downloaded = EMAIL_ATTACHMENT_MAX_COUNT;
                if ( (err = emstorage_get_attachment_list(mail_id, true, &attachment_list, &attachment_count_to_be_downloaded)) != EMAIL_ERROR_NONE ){
                        EM_DEBUG_EXCEPTION("emstorage_get_attachment_list failed [%d]", err);
-
                        goto FINISH_OFF;
                }
        }
@@ -2027,10 +2033,15 @@ INTERNAL_FUNC int emcore_download_attachment(int account_id, int mail_id, int nt
                goto FINISH_OFF;
        }
        
-       account_id              = mail->account_id;
-       s_uid                   = EM_SAFE_STRDUP(mail->server_mail_id);
+       account_id      = mail->account_id;
+       server_uid      = EM_SAFE_STRDUP(mail->server_mail_id);
        server_mbox_id  = mail->mailbox_id;
 
+       if (attachment_count_to_be_downloaded == 1 && attachment_list) {
+               if (!emcore_notify_network_event(NOTI_DOWNLOAD_ATTACH_START, mail_id, attachment_list[0].attachment_name, nth, 0))
+                       EM_DEBUG_EXCEPTION("emcore_notify_network_event [ NOTI_DOWNLOAD_ATTACH_START] Failed >>>>");
+       }
+
        /*  open mail server. */
        if (!emcore_connect_to_remote_mailbox(account_id, server_mbox_id, (void **)&tmp_stream, &err) || !tmp_stream)  {
                EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed [%d]", err);
@@ -2056,6 +2067,12 @@ INTERNAL_FUNC int emcore_download_attachment(int account_id, int mail_id, int nt
                        goto FINISH_OFF;
                }
                
+               /*free cnt_info before reusing*/
+               if (cnt_info)  {
+                       emcore_free_content_info(cnt_info);
+                       EM_SAFE_FREE(cnt_info);
+               }
+               
                if (!(cnt_info = em_malloc(sizeof(struct _m_content_info))))  {
                        EM_DEBUG_EXCEPTION("malloc failed...");
                        err = EMAIL_ERROR_OUT_OF_MEMORY;
@@ -2072,14 +2089,14 @@ INTERNAL_FUNC int emcore_download_attachment(int account_id, int mail_id, int nt
 #endif
 
                /*  set sparep(member of BODY) memory free function. */
-               mail_parameters(stream, SET_FREEBODYSPAREP, emcore_free_body_sharep);
+               mail_parameters(stream, SET_FREEBODYSPAREP, emcore_free_body_sparep);
                
                if (!emcore_check_thread_status()) {
                        err = EMAIL_ERROR_CANCELLED;
                        goto FINISH_OFF;
                }
 
-               msg_no = s_uid? atoi(s_uid): 0;
+               msg_no = server_uid? atoi(server_uid): 0;
 
                /*  get body structure. */
                /*  don't free mbody because mbody is freed in closing mail_stream. */
@@ -2094,7 +2111,7 @@ INTERNAL_FUNC int emcore_download_attachment(int account_id, int mail_id, int nt
                }
 
                /*  set body fetch section. */
-               if (emcore_set_fetch_body_section(mbody, false, NULL,  &err) < 0) {
+               if (emcore_set_fetch_body_section(mbody, false, NULL, NULL, &err) < 0) {
                        EM_DEBUG_EXCEPTION("emcore_set_fetch_body_section failed [%d]", err);
                        goto FINISH_OFF;
                }
@@ -2118,7 +2135,7 @@ INTERNAL_FUNC int emcore_download_attachment(int account_id, int mail_id, int nt
 
                /*  select target attachment information. */
                for (ai = cnt_info->file ; ai; ai = ai->next) {
-                       EM_DEBUG_LOG("[in loop] name[%s] save[%s] no[%d]", ai->save, ai->name, cnt_info->file_no);
+                       EM_DEBUG_LOG_SEC("[in loop] name[%s] save[%s] no[%d]", ai->save, ai->name, cnt_info->file_no);
                        if (--cnt_info->file_no == 0)
                                break;
                }
@@ -2145,8 +2162,9 @@ INTERNAL_FUNC int emcore_download_attachment(int account_id, int mail_id, int nt
 
                        EM_SAFE_FREE(ai->save);
 
-                       EM_DEBUG_LOG("ai->size [%d]", ai->size);
-                       attachment->attachment_size = ai->size;
+                       emcore_get_file_size(buf, &decoded_attachment_size, NULL);
+                       EM_DEBUG_LOG("decoded_attachment_size [%d]", decoded_attachment_size);
+                       attachment->attachment_size = decoded_attachment_size;
                        attachment->attachment_path = EM_SAFE_STRDUP(buf);
 
                        /*  update attachment information. */
@@ -2174,36 +2192,33 @@ INTERNAL_FUNC int emcore_download_attachment(int account_id, int mail_id, int nt
                        goto FINISH_OFF;
                }
        
-               if (cnt_info)  {
-                       emcore_free_content_info(cnt_info);
-                       cnt_info = NULL;
-               }
                EM_DEBUG_LOG(" >>>>>> Attachment Downloading [%d / %d] completed", i+1, attachment_count_to_be_downloaded);
        }
 
-       if (stream)  {
-               emcore_close_mailbox(0, stream);
-               stream = NULL;
-       }
-       
        ret = true;
        
 FINISH_OFF:
-       if (stream)
-               emcore_close_mailbox(account_id, stream);
+       if (stream)  {
+               stream = mail_close (stream);
+       }
+
        if (attachment_list)
                emstorage_free_attachment(&attachment_list, attachment_count_to_be_downloaded, NULL);
-       if (cnt_info)
+       if (cnt_info) {
                emcore_free_content_info(cnt_info);
+               EM_SAFE_FREE(cnt_info);
+       }
        if (mail)
                emstorage_free_mail(&mail, 1, NULL);
 
-       EM_SAFE_FREE(s_uid);
+       EM_SAFE_FREE(server_uid);
 
        if (ret == true)
                emcore_notify_network_event(NOTI_DOWNLOAD_ATTACH_FINISH, mail_id, NULL, nth, 0);
-       else
-               emcore_notify_network_event(NOTI_DOWNLOAD_ATTACH_FAIL, mail_id, NULL, nth, err);
+       else {
+               if (err != EMAIL_ERROR_CANCELLED)
+                       emcore_notify_network_event(NOTI_DOWNLOAD_ATTACH_FAIL, mail_id, NULL, nth, err);
+       }
 
        if (err_code != NULL)
                *err_code = err;
@@ -2243,7 +2258,7 @@ INTERNAL_FUNC int emcore_download_attachment_bulk(int account_id, int mail_id, i
        email_file_list *pFileListMMc = NULL;
        email_file_list *pFileList = NULL;
 #endif /*  SUPPORT_EXTERNAL_MEMORY */
-       
+       int decoded_attachment_size = 0;
        
        memset(buf, 0x00, 512);
        /* CID FIX 31230 */
@@ -2414,7 +2429,10 @@ INTERNAL_FUNC int emcore_download_attachment_bulk(int account_id, int mail_id, i
                        goto FINISH_OFF;
                }
 
-               attachment->attachment = EM_SAFE_STRDUP(buf);
+               emcore_get_file_size(buf, &decoded_attachment_size, NULL);
+               EM_DEBUG_LOG("decoded_attachment_size [%d]", decoded_attachment_size);
+               attachment->attachment_size = decoded_attachment_size;
+               attachment->attachment_path = EM_SAFE_STRDUP(buf);
                /*  update attachment information. */
                if (!emstorage_change_attachment_field(mail_id, UPDATE_SAVENAME, attachment, true, &err)) {
                        EM_DEBUG_EXCEPTION("emstorage_change_attachment_field failed [%d]", err);
@@ -2425,7 +2443,7 @@ INTERNAL_FUNC int emcore_download_attachment_bulk(int account_id, int mail_id, i
 #ifdef __FEATURE_DRM__
                if (emcore_check_drm(attachment)) {
                        /*  is drm */
-                       if (drm_svc_register_file(attachment->attachment) == DRM_RESULT_SUCCESS)
+                       if (drm_svc_register_file(attachment->attachment_path) == DRM_RESULT_SUCCESS)
                                EM_DEBUG_LOG("drm_svc_register_file success");
                        else
                                EM_DEBUG_EXCEPTION("drm_svc_register_file fail");
@@ -2447,8 +2465,9 @@ INTERNAL_FUNC int emcore_download_attachment_bulk(int account_id, int mail_id, i
 
        EM_SAFE_FREE(savefile);
 
-       emcore_close_mailbox(0, stream);
-       stream = NULL;
+       if (stream)  {
+               stream = mail_close (stream);
+       }
 
        if (attachment_list) 
                emstorage_free_attachment(&attachment_list, attachment_count_to_be_downloaded, NULL);
@@ -2456,11 +2475,9 @@ INTERNAL_FUNC int emcore_download_attachment_bulk(int account_id, int mail_id, i
        if (mail) 
                emstorage_free_mail(&mail, 1, NULL);
 
-       if (s_uid)
-               free(s_uid);
+       EM_SAFE_FREE(s_uid);
 
-       if (server_mbox)
-               free(server_mbox);server_mbox = NULL;
+       EM_SAFE_FREE(server_mbox);
 
        if (ret == true)
                emcore_notify_network_event(NOTI_DOWNLOAD_ATTACH_FINISH, mail_id, NULL, attachment_no, 0);
@@ -2474,9 +2491,11 @@ INTERNAL_FUNC int emcore_download_attachment_bulk(int account_id, int mail_id, i
 }
 #endif
 
-INTERNAL_FUNC int emcore_download_body_multi_sections_bulk(void *mail_stream, int account_id, int mail_id, int verbose, int with_attach, int limited_size, int event_handle , int *err_code)
+INTERNAL_FUNC int emcore_download_body_multi_sections_bulk (void *mail_stream, int account_id, 
+                         int mail_id, int verbose, int with_attach, int limited_size, int event_handle , int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("mail_stream[%p], account_id[%d], mail_id[%d], verbose[%d], with_attach[%d], event_handle [ %d ] ", mail_stream, account_id, mail_id, verbose, with_attach, event_handle);
+       EM_DEBUG_FUNC_BEGIN("mail_stream[%p], account_id[%d], mail_id[%d], verbose[%d], with_attach[%d], event_handle [%d]", 
+                                                 mail_stream, account_id, mail_id, verbose, with_attach, event_handle);
 
        int ret = false;
        int err = EMAIL_ERROR_NONE;
@@ -2486,26 +2505,27 @@ INTERNAL_FUNC int emcore_download_body_multi_sections_bulk(void *mail_stream, in
        MAILSTREAM *stream = NULL;
        BODY *mbody = NULL;
        PARTLIST *section_list = NULL;
-       email_internal_mailbox_t mailbox = { 0 };
+       email_internal_mailbox_t mailbox = {0};
        emstorage_mail_tbl_t *mail = NULL;
-       emstorage_attachment_tbl_t attachment = {0, 0, NULL, };
+       emstorage_attachment_tbl_t attachment = {0};
        email_account_t *ref_account = NULL;
        struct attachment_info *ai = NULL;
        struct _m_content_info *cnt_info = NULL;
-       void *tmp_stream = NULL;
-       char *s_uid = NULL, buf[512];
+       void *tmp_stream = NULL; 
+       char *s_uid = NULL; 
+       char buf[512] = {0};
        int msgno = 0, attachment_num = 1, local_attachment_count = 0, local_inline_content_count = 0;
        int iActualSize = 0;
-       char html_body[MAX_PATH] = {0};
+       char html_body[MAX_PATH] = {0};
        emcore_uid_list *uid_list = NULL;
 #ifdef CHANGE_HTML_BODY_TO_ATTACHMENT
        int html_changed = 0;
 #endif
 
        if (mail_id < 1)  {
-               EM_DEBUG_EXCEPTION("mail_stream[%p], account_id[%d], mail_id[%d], verbose[%d], with_attach[%d]", mail_stream, account_id, mail_id, verbose, with_attach);
+               EM_DEBUG_EXCEPTION("mail_stream[%p], account_id[%d], mail_id[%d], verbose[%d], with_attach[%d]", 
+                                                              mail_stream, account_id, mail_id, verbose, with_attach);
                err = EMAIL_ERROR_INVALID_PARAM;
-               
                if (err_code != NULL)
                        *err_code = err;
 
@@ -2519,7 +2539,6 @@ INTERNAL_FUNC int emcore_download_body_multi_sections_bulk(void *mail_stream, in
 
        if (!emstorage_get_mail_by_id(mail_id, &mail, true, &err) || !mail)  {
                EM_DEBUG_EXCEPTION("emstorage_get_mail_by_id failed [%d]", err);
-
                goto FINISH_OFF;
        }
        
@@ -2530,7 +2549,6 @@ INTERNAL_FUNC int emcore_download_body_multi_sections_bulk(void *mail_stream, in
        }
        
        s_uid                             = EM_SAFE_STRDUP(mail->server_mail_id);
-
        attachment.account_id             = mail->account_id;
        attachment.mail_id                = mail->mail_id;
        attachment.mailbox_id             = mail->mailbox_id;
@@ -2571,10 +2589,9 @@ INTERNAL_FUNC int emcore_download_body_multi_sections_bulk(void *mail_stream, in
                attachment.attachment_save_status = 1;          /*  all attachments should be downloaded in the case of POP3 */
 
                mailbox.account_id = account_id;
-               mailbox.mail_stream = stream;
 
                /*  download all uids from server. */
-               if (!emcore_download_uid_all(&mailbox, &uid_list, NULL, NULL, 0, EM_CORE_GET_UIDS_FOR_NO_DELETE, &err))  {
+               if (!emcore_download_uid_all (stream, &mailbox, &uid_list, NULL, NULL, 0, EM_CORE_GET_UIDS_FOR_NO_DELETE, &err))  {
                        EM_DEBUG_EXCEPTION("emcore_download_uid_all failed [%d]", err);
                        goto FINISH_OFF;
                }
@@ -2613,12 +2630,32 @@ INTERNAL_FUNC int emcore_download_body_multi_sections_bulk(void *mail_stream, in
                
                /*  save message into tempfile */
                /*  parsing mime from stream. */
+#ifdef __FEATURE_USE_GMIME__
+               char sock_buf[1024] = {0, };
+               int fd = 0;
+               char *tmp_path = emcore_mime_get_save_file_name(&err);
+               EM_DEBUG_LOG ("tmp_path[%s]", tmp_path);
+               fd = open(tmp_path, O_WRONLY|O_CREAT, 0644);
+               if (fd < 0) {
+                       EM_DEBUG_EXCEPTION("open error [%d]:  holder is a filename that will be saved.", errno);
+               }
+
+               while(emcore_mime_get_line_from_sock((void *)stream, sock_buf, 1024, &err)) {
+                       if (write(fd, sock_buf, EM_SAFE_STRLEN(sock_buf)) != EM_SAFE_STRLEN(sock_buf)) {
+                               EM_DEBUG_EXCEPTION("write failed");
+                       }
+               }
+               close(fd);
+
+               emcore_gmime_parse_mime(tmp_path, cnt_info, &err);
 
+               g_remove(tmp_path);
+#else
                if (!emcore_parse_mime(stream, 0, cnt_info,  &err))  {
                        EM_DEBUG_EXCEPTION("emcore_parse_mime failed [%d]", err);
                        goto FINISH_OFF;
                }
-               
+#endif /* __FEATURE_USE_GMIME__ */
                FINISH_OFF_IF_CANCELED;
        }
        else  { /*  in IMAP case, both text and attachment list are downloaded in this call. */
@@ -2631,7 +2668,7 @@ INTERNAL_FUNC int emcore_download_body_multi_sections_bulk(void *mail_stream, in
                int uid = s_uid? atoi(s_uid):0; /*prevent 39118*/
 
                /*  set sparep(member of BODY) memory free function  */
-               mail_parameters(stream, SET_FREEBODYSPAREP, emcore_free_body_sharep);
+               mail_parameters(stream, SET_FREEBODYSPAREP, emcore_free_body_sparep);
 
                /*  get body strucutre. */
                /*  don't free mbody because mbody is freed in closing mail_stream. */
@@ -2655,7 +2692,7 @@ INTERNAL_FUNC int emcore_download_body_multi_sections_bulk(void *mail_stream, in
                                if (only_body_download == true) {
                                        if (((body->id) && EM_SAFE_STRLEN(body->id) > 1) || (body->location))
                                                is_attachment = 0;
-                                       else if (body->disposition.type)  {     /*  "attachment" or "inline" or etc... */
+                                       else if (body->disposition.type)      /*  "attachment" or "inline" or etc... */
                                                PARAMETER *param = body->disposition.parameter;
 
                                                while (param)  {
@@ -2663,7 +2700,7 @@ INTERNAL_FUNC int emcore_download_body_multi_sections_bulk(void *mail_stream, in
 
                                                        if (!strcasecmp(param->attribute, "filename"))  {       /* attribute is "filename" */
                                                                strncpy(filename, param->value, MAX_PATH);
-                                                               EM_DEBUG_LOG(">>>>> FILENAME [%s] ", filename);
+                                                               EM_DEBUG_LOG_SEC(">>>>> FILENAME [%s] ", filename);
                                                                break;
                                                        }
                                                        param = param->next;
@@ -2694,7 +2731,7 @@ INTERNAL_FUNC int emcore_download_body_multi_sections_bulk(void *mail_stream, in
                }
 
                /*  set body fetch section. */
-               if (emcore_set_fetch_body_section(mbody, true, &iActualSize, &err) < 0) {
+               if (emcore_set_fetch_body_section(mbody, true, NULL, &iActualSize, &err) < 0) {
                        EM_DEBUG_EXCEPTION("emcore_set_fetch_body_section failed [%d]", err);
                        goto FINISH_OFF;
                }
@@ -2741,8 +2778,9 @@ INTERNAL_FUNC int emcore_download_body_multi_sections_bulk(void *mail_stream, in
                        goto FINISH_OFF;
                }
 
+               EM_SAFE_FREE(mail->file_path_plain);
                mail->file_path_plain = EM_SAFE_STRDUP(buf);
-               EM_DEBUG_LOG("mail->file_path_plain [%s]", mail->file_path_plain);
+               EM_DEBUG_LOG_SEC("mail->file_path_plain [%s]", mail->file_path_plain);
        }
        
        if (cnt_info->text.html)  {
@@ -2751,7 +2789,11 @@ INTERNAL_FUNC int emcore_download_body_multi_sections_bulk(void *mail_stream, in
                        goto FINISH_OFF;
                }
                
-               if (cnt_info->text.plain_charset != NULL) {
+               if (cnt_info->text.html_charset != NULL) {
+                       memcpy(html_body, cnt_info->text.html_charset, EM_SAFE_STRLEN(cnt_info->text.html_charset));
+                       strcat(html_body, HTML_EXTENSION_STRING);
+               }
+               else if (cnt_info->text.plain_charset != NULL) {
                        memcpy(html_body, cnt_info->text.plain_charset, EM_SAFE_STRLEN(cnt_info->text.plain_charset));
                        strcat(html_body, HTML_EXTENSION_STRING);
                }
@@ -2767,17 +2809,20 @@ INTERNAL_FUNC int emcore_download_body_multi_sections_bulk(void *mail_stream, in
                        EM_DEBUG_EXCEPTION("emstorage_move_file failed [%d]", err);
                        goto FINISH_OFF;
                }
+               EM_SAFE_FREE(mail->file_path_html);
                mail->file_path_html = EM_SAFE_STRDUP(buf);
        }
        
-       if (ref_account->incoming_server_type == EMAIL_SERVER_TYPE_POP3 && limited_size != NO_LIMITATION && limited_size < pop3_body_size)
+       if (ref_account->incoming_server_type == EMAIL_SERVER_TYPE_POP3 && limited_size != NO_LIMITATION && 
+                                                                                     limited_size < pop3_body_size)
                mail->body_download_status = EMAIL_BODY_DOWNLOAD_STATUS_PARTIALLY_DOWNLOADED;
        else
                mail->body_download_status = EMAIL_BODY_DOWNLOAD_STATUS_FULLY_DOWNLOADED;
 
        /* Update local_preview_text */
-       if ((err = emcore_get_preview_text_from_file(mail->file_path_plain, mail->file_path_html, MAX_PREVIEW_TEXT_LENGTH, &(mail->preview_text))) != EMAIL_ERROR_NONE) {
-               EM_DEBUG_EXCEPTION("emcore_get_preview_text_from_file failedi : [%d]", err);
+       if ((err = emcore_get_preview_text_from_file (mail->file_path_plain, mail->file_path_html, 
+                                             MAX_PREVIEW_TEXT_LENGTH, &mail->preview_text)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emcore_get_preview_text_from_file error [%d]", err);
        }
        
 #ifdef CHANGE_HTML_BODY_TO_ATTACHMENT
@@ -2802,13 +2847,14 @@ INTERNAL_FUNC int emcore_download_body_multi_sections_bulk(void *mail_stream, in
                EM_DEBUG_LOG("attachment.attachment_id[%d]", attachment.attachment_id);
                EM_DEBUG_LOG("attachment.attachment_size[%d]", attachment.attachment_size);
                EM_DEBUG_LOG("attachment.attachment_path[%s]", attachment.attachment_path);
-               EM_DEBUG_LOG("attachment.attachment_name[%s]", attachment.attachment_name);
+               EM_DEBUG_LOG_SEC("attachment.attachment_name[%s]", attachment.attachment_name);
                EM_DEBUG_LOG("attachment.attachment_drm_type[%d]", attachment.attachment_drm_type);
                EM_DEBUG_LOG("attachment.attachment_inline_content_status[%d]", attachment.attachment_inline_content_status);
 
                if (ai->type == 1)
                        local_inline_content_count++;
-               local_attachment_count++;
+               else
+                       local_attachment_count++;
 
                if (ai->save)  {
                        /*  in POP3 case, rename temporary file to real file. */
@@ -2853,13 +2899,15 @@ INTERNAL_FUNC int emcore_download_body_multi_sections_bulk(void *mail_stream, in
                                goto FINISH_OFF;
                        }
 
-                       free(ai->save); ai->save = EM_SAFE_STRDUP(buf);
+                       EM_SAFE_FREE(ai->save); 
+                       ai->save = EM_SAFE_STRDUP(buf);
 
                        attachment.attachment_path = ai->save;
 
 #ifdef __FEATURE_DRM__
                        if (emcore_check_drm(&attachment)) /*  is drm content ?*/ {
-                               if (drm_process_request(DRM_REQUEST_TYPE_REGISTER_FILE, attachment.attachment_path, NULL) != DRM_RETURN_SUCCESS)
+                               if (drm_process_request(DRM_REQUEST_TYPE_REGISTER_FILE, attachment.attachment_path, NULL) 
+                                                                                              != DRM_RETURN_SUCCESS)
                                        EM_DEBUG_EXCEPTION("drm_process_request : register file fail");
                                mail->DRM_status = attachment.attachment_drm_type;
                        }
@@ -2904,8 +2952,8 @@ INTERNAL_FUNC int emcore_download_body_multi_sections_bulk(void *mail_stream, in
                                attch_info->attachment_size = ai->size;
                                if (!emstorage_update_attachment(attch_info, true, &err)) {
                                        EM_DEBUG_EXCEPTION("emstorage_update_attachment failed [%d]", err);
-
-                                               goto FINISH_OFF;
+                                       emstorage_free_attachment(&attch_info, 1, NULL); /*prevent 17956*/
+                                       goto FINISH_OFF;
                                }
                        }
 
@@ -2977,6 +3025,7 @@ INTERNAL_FUNC int emcore_download_body_multi_sections_bulk(void *mail_stream, in
        if (!emstorage_change_mail_text_field(mail_id, mail_text, false, &err)) {
                EM_DEBUG_EXCEPTION("emstorage_change_mail_text_field failed [%d]", err);
                emstorage_rollback_transaction(NULL, NULL, NULL); /*  ROLLBACK TRANSACTION; */
+               emstorage_free_mail_text(&mail_text, 1, NULL); /*prevent 17957*/
                goto FINISH_OFF;
        }
 
@@ -2999,12 +3048,6 @@ INTERNAL_FUNC int emcore_download_body_multi_sections_bulk(void *mail_stream, in
                }
 #endif
                
-               if (!mail_stream)  {
-                       if (stream != NULL)  {
-                               emcore_close_mailbox(0, stream);
-                               stream = NULL;
-                       }
-               }
        }
 
        FINISH_OFF_IF_CANCELED;
@@ -3018,6 +3061,11 @@ FINISH_OFF:
                EM_SAFE_FREE(ref_account);
        }
 
+       /* note that local stream should be freed here*/
+       if (mail_stream == NULL && stream != NULL)  {
+               stream = mail_close (stream);
+       }
+
        multi_part_body_size = 0;
        _pop3_received_body_size = 0;
        _pop3_last_notified_body_size = 0;
@@ -3029,8 +3077,10 @@ FINISH_OFF:
        _imap4_total_body_size = 0;
        _imap4_download_noti_interval_value = 0;
        
-       if (cnt_info)
+       if (cnt_info) {
                emcore_free_content_info(cnt_info);
+               EM_SAFE_FREE(cnt_info);
+       }
        if (mail)
                emstorage_free_mail(&mail, 1, NULL);
        EM_SAFE_FREE(s_uid);
@@ -3057,7 +3107,7 @@ void emcore_mail_copyuid(MAILSTREAM *stream, char *mailbox,
        EM_DEBUG_FUNC_BEGIN();
        char  old_server_uid[129];
 
-       EM_DEBUG_LOG("mailbox name - %s", mailbox);
+       EM_DEBUG_LOG_SEC("mailbox name - %s", mailbox);
        EM_DEBUG_LOG("first sequence number source- %ld", sourceset->first);
        EM_DEBUG_LOG("last sequence number last- %ld", sourceset->last);
        EM_DEBUG_LOG("first sequence number dest - %ld", destset->first);
@@ -3241,33 +3291,89 @@ FINISH_OFF:
        return ret;
 }
 
+email_thread_handle_t *del_thd = NULL;
+
+static void* del_dir (void* arg)
+{
+       char* buf = (char*) arg;
+       int err = EMAIL_ERROR_NONE;
+       if (!emstorage_delete_dir (buf, &err))  {
+               EM_DEBUG_EXCEPTION ("emstorage_delete_dir failed [%d]", err);
+       }
+       return NULL;
+}
+
+static void* free_buf (void* arg)
+{
+       EM_SAFE_FREE (arg);
+       return NULL;
+}
+
+int pipefd[2] = {0}; /* defined in main.c */
+pthread_mutex_t mu_del_account = PTHREAD_MUTEX_INITIALIZER;
+
+static void* del_exit (void* arg)
+{
+       emcore_send_signal_for_del_account (EMAIL_SIGNAL_FILE_DELETED);
+       EM_DEBUG_LOG ("publish all file deleted");
+       return NULL;
+}
+
+INTERNAL_FUNC int *emcore_init_pipe_for_del_account ()
+{
+       int err = pipe(pipefd);
+       if (err<0) {
+               EM_DEBUG_EXCEPTION ("pipe error [%d]", errno);
+               return NULL;
+       }
+       return pipefd;
+}
+
+INTERNAL_FUNC void emcore_send_signal_for_del_account (int signal)
+{
+       pthread_mutex_lock (&mu_del_account);
+       write(pipefd[1], (char*) &signal, sizeof (signal));
+       pthread_mutex_unlock (&mu_del_account);
+}
+
 int emcore_delete_all_mails_of_acount(int input_account_id)
 {
        EM_DEBUG_FUNC_BEGIN("input_account_id [%d]");
 
        int   err = EMAIL_ERROR_NONE;
-       char  buf[512] = { 0, };
+       char*  buf = NULL;
 
        /* emstorage_delete_mail_by_account is available only locally */
        if (!emstorage_delete_mail_by_account(input_account_id, false, &err))  {
-               EM_DEBUG_EXCEPTION("emstorage_delete_mail_by_account failed [%d]", err);
-               goto FINISH_OFF;
+               if(err != EMAIL_ERROR_MAIL_NOT_FOUND) {
+                       EM_DEBUG_EXCEPTION("emstorage_delete_mail_by_account failed [%d]", err);
+                       goto FINISH_OFF;
+               }
        }
 
        if (!emstorage_delete_attachment_all_on_db(input_account_id, NULL, false, &err))  {
-               EM_DEBUG_EXCEPTION("emstorage_delete_attachment_all_on_db failed [%d]", err);
-               goto FINISH_OFF;
+               if(err != EMAIL_ERROR_MAIL_NOT_FOUND) {
+                       EM_DEBUG_EXCEPTION("emstorage_delete_attachment_all_on_db failed [%d]", err);
+                       goto FINISH_OFF;
+               }
        }
 
        /*  delete mail contents from filesystem */
+       buf = em_malloc (512);
+       if (!buf) {
+               EM_DEBUG_EXCEPTION("em_malloc failed");
+               goto FINISH_OFF;
+       }
+
        if (!emstorage_get_save_name(input_account_id, 0, 0, NULL, buf, &err))  {
                EM_DEBUG_EXCEPTION("emstorage_get_save_name failed [%d]", err);
                goto FINISH_OFF;
        }
 
-       if (!emstorage_delete_dir(buf, &err))  {
-               EM_DEBUG_EXCEPTION("emstorage_delete_dir failed [%d]", err);
-       }
+       if (!del_thd) 
+               del_thd = em_thread_create (del_exit, NULL);
+
+       em_thread_run (del_thd, del_dir, free_buf, buf);
 
        /*  delete meeting request */
        if (!emstorage_delete_meeting_request(input_account_id, 0, 0, false, &err))  {
@@ -3364,11 +3470,9 @@ INTERNAL_FUNC int emcore_delete_mails_from_local_storage(int account_id, int *ma
        /* Updating Thread informations */
        /* Thread information should be updated as soon as possible. */
        for(i = 0; i < num; i++) {
-               if (result_mail_list[i].thread_item_count > 1)  {
-                       if (!emstorage_update_latest_thread_mail(account_id, result_mail_list[i].thread_id, 0, 0, false,  &err)) {
-                               EM_DEBUG_EXCEPTION("emstorage_update_latest_thread_mail failed [%d]", err);
-                               goto FINISH_OFF;
-                       }
+               if (!emstorage_update_latest_thread_mail(account_id, result_mail_list[i].thread_id, 0, 0, false,  &err)) {
+                       EM_DEBUG_EXCEPTION("emstorage_update_latest_thread_mail failed [%d]", err);
+                       goto FINISH_OFF;
                }
        }
        if (!emcore_notify_storage_event(NOTI_MAIL_DELETE_FINISH, account_id, noti_param_1, noti_param_string, noti_param_2))
@@ -3502,9 +3606,8 @@ FINISH_OFF:
        if (mail_tbl_data != NULL)
                emstorage_free_mail(&mail_tbl_data, 1, NULL);
 
-       if (stream)              {
-               emcore_close_mailbox(0, stream);
-               stream = NULL;
+       if (stream)  {
+               stream = mail_close (stream);
        }
 
        if (mailbox_data.user_data != NULL) {
@@ -3518,7 +3621,7 @@ FINISH_OFF:
 
 INTERNAL_FUNC int emcore_get_mail_msgno_by_uid(email_account_t *account, email_internal_mailbox_t *mailbox, char *uid, int *msgno, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("account[%p], mailbox[%p], uid[%s], msgno[%p], err_code[%p]", account, mailbox, uid, msgno, err_code);
+       EM_DEBUG_FUNC_BEGIN_SEC("account[%p], mailbox[%p], uid[%s], msgno[%p], err_code[%p]", account, mailbox, uid, msgno, err_code);
 
        int ret = false;
        int err = EMAIL_ERROR_NONE;
@@ -3526,7 +3629,7 @@ INTERNAL_FUNC int emcore_get_mail_msgno_by_uid(email_account_t *account, email_i
        emcore_uid_list *uid_list = NULL;
        
        if (!account || !mailbox || !uid || !msgno)  {
-               EM_DEBUG_EXCEPTION("account[%p], mailbox[%p], uid[%s], msgno[%p]", account, mailbox, uid, msgno);
+               EM_DEBUG_EXCEPTION_SEC("account[%p], mailbox[%p], uid[%s], msgno[%p]", account, mailbox, uid, msgno);
                err = EMAIL_ERROR_INVALID_PARAM;
                goto FINISH_OFF;
        }
@@ -3731,7 +3834,7 @@ FINISH_OFF:
  *    succeed  :  1
  *    fail  :  0
  */
-INTERNAL_FUNC int emcore_mail_add_attachment(int mail_id, email_attachment_data_t *attachment, int *err_code)
+INTERNAL_FUNC int emcore_add_attachment(int mail_id, email_attachment_data_t *attachment, int *err_code)
 {
        EM_DEBUG_FUNC_BEGIN("mail_id[%d], attachment[%p], err_code[%p]", mail_id, attachment, err_code);
        
@@ -3768,6 +3871,7 @@ INTERNAL_FUNC int emcore_mail_add_attachment(int mail_id, email_attachment_data_
        attachment_tbl.attachment_save_status           = attachment->save_status;
        attachment_tbl.attachment_drm_type              = attachment->drm_status;
        attachment_tbl.attachment_inline_content_status = attachment->inline_content_status;
+       attachment_tbl.attachment_mime_type             = attachment->attachment_mime_type;
 
        /*  BEGIN TRANSACTION; */
        if (!emstorage_begin_transaction(NULL, NULL, &err)) {
@@ -3858,7 +3962,7 @@ FINISH_OFF2:
 }
 
 
-INTERNAL_FUNC int emcore_mail_add_attachment_data(int input_mail_id, email_attachment_data_t *input_attachment_data)
+INTERNAL_FUNC int emcore_add_attachment_data(int input_mail_id, email_attachment_data_t *input_attachment_data)
 {
        EM_DEBUG_FUNC_BEGIN("input_mail_id[%d], input_attachment_data[%p]", input_mail_id, input_attachment_data);
 
@@ -3890,6 +3994,7 @@ INTERNAL_FUNC int emcore_mail_add_attachment_data(int input_mail_id, email_attac
        attachment_tbl.attachment_save_status           = input_attachment_data->save_status;
        attachment_tbl.attachment_drm_type              = input_attachment_data->drm_status;
        attachment_tbl.attachment_inline_content_status = input_attachment_data->inline_content_status;
+       attachment_tbl.attachment_mime_type             = input_attachment_data->attachment_mime_type;
        
        /*  BEGIN TRANSACTION; */
        if (!emstorage_begin_transaction(NULL, NULL, &err)) {
@@ -4074,6 +4179,7 @@ static int emcore_mail_update_attachment_data(int input_mail_id, email_attachmen
        attachment_tbl.attachment_save_status           = input_attachment_data->save_status;
        attachment_tbl.attachment_drm_type              = input_attachment_data->drm_status;
        attachment_tbl.attachment_inline_content_status = input_attachment_data->inline_content_status;
+       attachment_tbl.attachment_mime_type             = input_attachment_data->attachment_mime_type;
        attachment_tbl.attachment_id                    = input_attachment_data->attachment_id;
 
        if (!input_attachment_data->inline_content_status) {
@@ -4136,31 +4242,35 @@ static int emcore_mail_compare_filename_of_attachment_data(int input_mail_id, in
 {
        EM_DEBUG_FUNC_BEGIN("input_mail_id[%d], input_attachment_a_id[%d], input_attachment_b_data[%p], result[%p]", input_mail_id, input_attachment_a_id, input_attachment_b_data, result);
 
-       EM_IF_NULL_RETURN_VALUE(input_attachment_b_data, false);
-       EM_IF_NULL_RETURN_VALUE(result, false);
+       if (!input_attachment_b_data || !result) {
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
 
-       int err, err_2, ret = EMAIL_ERROR_NONE;
+       int err = EMAIL_ERROR_NONE;
        emstorage_attachment_tbl_t *attachment_a_tbl = NULL;
 
        if (!emstorage_get_attachment(input_attachment_a_id, &attachment_a_tbl, 1, &err)) {
-               EM_DEBUG_EXCEPTION("emstorage_get_attachment failed [%d]", err);
+               if (err == EMAIL_ERROR_ATTACHMENT_NOT_FOUND)
+                       EM_DEBUG_LOG ("no attachment found");
+               else
+                       EM_DEBUG_EXCEPTION ("emstorage_get_attachment failed [%d]", err);
+
+               *result = 1; /* matching attachment file is not found */
 
                goto FINISH_OFF;
        }
 
        if (attachment_a_tbl->attachment_name && input_attachment_b_data->attachment_name) {
-               EM_DEBUG_LOG("attachment_a_tbl->attachment_name [%s], input_attachment_b_data->name [%s]", attachment_a_tbl->attachment_name, input_attachment_b_data->attachment_name);
+               EM_DEBUG_LOG_SEC("attachment_a_tbl->attachment_name [%s], input_attachment_b_data->name [%s]", attachment_a_tbl->attachment_name, input_attachment_b_data->attachment_name);
                *result = strcmp(attachment_a_tbl->attachment_name, input_attachment_b_data->attachment_name);
        }
 
-       ret = true;
-
 FINISH_OFF: 
 
        if (attachment_a_tbl)
-               emstorage_free_attachment(&attachment_a_tbl, 1, &err_2);
+               emstorage_free_attachment(&attachment_a_tbl, 1, NULL);
        EM_DEBUG_FUNC_END("*result [%d]", *result);
-       return ret;
+       return err;
 }
 
 
@@ -4186,6 +4296,7 @@ INTERNAL_FUNC int emcore_mail_copy(int mail_id, email_mailbox_t *dst_mailbox, in
        char buf[512];
        int count = EMAIL_ATTACHMENT_MAX_COUNT;
        char *mailbox_name = NULL;
+       char *stripped_text = NULL;
 
        if (!emstorage_get_mail_by_id(mail_id, &mail, true, &err) || !mail)  {
                EM_DEBUG_EXCEPTION("emstorage_get_mail_by_id failed [%d]", err);
@@ -4231,6 +4342,7 @@ INTERNAL_FUNC int emcore_mail_copy(int mail_id, email_mailbox_t *dst_mailbox, in
                        goto FINISH_OFF;
                }
 
+               EM_SAFE_FREE(mail->file_path_plain);
                mail->file_path_plain = EM_SAFE_STRDUP(buf);
        }
 
@@ -4259,6 +4371,7 @@ INTERNAL_FUNC int emcore_mail_copy(int mail_id, email_mailbox_t *dst_mailbox, in
                        goto FINISH_OFF;
                }
 
+               EM_SAFE_FREE(mail->file_path_html); /*valgrind*/
                mail->file_path_html = EM_SAFE_STRDUP(buf);
        }
 
@@ -4368,7 +4481,6 @@ INTERNAL_FUNC int emcore_mail_copy(int mail_id, email_mailbox_t *dst_mailbox, in
 
 #ifdef __FEATURE_BODY_SEARCH__
        /* Insert mail_text to DB */
-       char *stripped_text = NULL;
        emstorage_mailbox_tbl_t *output_mailbox;
        if (!emcore_strip_mail_body_from_file(mail, &stripped_text, &err) || stripped_text == NULL) {
                EM_DEBUG_EXCEPTION("emcore_strip_mail_body_from_file failed [%d]", err);
@@ -4491,7 +4603,7 @@ INTERNAL_FUNC int emcore_move_mail(int mail_ids[], int mail_ids_count, int dst_m
 
 
        for (i = 0; i < mail_ids_count; i++) {
-               if (!emstorage_update_latest_thread_mail(account_id, mail_list[i].thread_id, 0, 0, true, &err))
+               if (!emstorage_update_latest_thread_mail(account_id, mail_list[i].thread_id, 0, 0, false, &err))
                        EM_DEBUG_EXCEPTION("emstorage_update_latest_thread_mail failed [%d]", err);
        }
 
@@ -4613,7 +4725,8 @@ INTERNAL_FUNC int emcore_move_mail_on_server(int account_id, int src_mailbox_id,
        }
 
 FINISH_OFF:
-       if (stream) emcore_close_mailbox(account_id, stream);
+       if (stream) 
+               stream = mail_close (stream);
 
        if (ref_account) {
                emcore_free_account(ref_account);
@@ -4677,7 +4790,7 @@ static int emcore_copy_mail_to_another_account_on_local_storeage(int input_mail_
        mail_data->thread_id         = 0;
        mail_data->thread_item_count = 0;
 
-       if((err = emcore_add_mail(mail_data, attachment_data, attachment_count, NULL, false)) != EMAIL_ERROR_NONE) {
+       if((err = emcore_add_mail(mail_data, attachment_data, attachment_count, NULL, false, true)) != EMAIL_ERROR_NONE) {
                EM_DEBUG_EXCEPTION("emcore_add_mail failed [%d]", err);
                goto FINISH_OFF;
        }
@@ -4687,7 +4800,7 @@ static int emcore_copy_mail_to_another_account_on_local_storeage(int input_mail_
 FINISH_OFF:
        if (mail_data) {
                emcore_free_mail_data(mail_data);
-               free(mail_data);                /* prevent 34648 */
+               EM_SAFE_FREE (mail_data); /* prevent 34648 */
        }
 
        if (attachment_data)
@@ -4836,14 +4949,19 @@ INTERNAL_FUNC int emcore_update_mail(email_mail_data_t *input_mail_data, email_a
 {
        EM_DEBUG_FUNC_BEGIN("input_mail_data[%p], input_attachment_data_list[%p], input_attachment_count[%d], input_meeting_request[%p], input_from_eas[%d]", input_mail_data, input_attachment_data_list, input_attachment_count, input_meeting_request, input_from_eas);
 
-       char                   filename_buf[1024]         = {0, };
-       char                  *body_text_file_name        = NULL;
-       int                    i                          = 0;
-       int                    err                        = EMAIL_ERROR_NONE;
-       int                    local_inline_content_count = 0;
-       emstorage_mail_tbl_t  *converted_mail_tbl_data    = NULL;
-       email_meeting_request_t *meeting_req = NULL;
+       char                   filename_buf[1024]          = {0, };
+       char                   mailbox_id_param_string[10] = {0, };
+       char                  *body_text_file_name         = NULL;
+       int                    i                           = 0;
+       int                    err                         = EMAIL_ERROR_NONE;
+       int                    local_inline_content_count  = 0;
+       emstorage_mail_tbl_t  *converted_mail_tbl_data     = NULL;
+       email_meeting_request_t *meeting_req               = NULL;
        struct stat            st_buf;
+       int ori_attachment_count                           = 0;
+       int *temp_attachment_id_array                      = NULL;
+       email_attachment_data_t *ori_attachment_data_list  = NULL;
+
 
        if (!input_mail_data || (input_attachment_count && !input_attachment_data_list) || (!input_attachment_count &&input_attachment_data_list))  {
                EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
@@ -4854,7 +4972,7 @@ INTERNAL_FUNC int emcore_update_mail(email_mail_data_t *input_mail_data, email_a
        if(input_from_eas == 0) {
                if (input_mail_data->file_path_plain)  {
                        if (stat(input_mail_data->file_path_plain, &st_buf) < 0)  {
-                               EM_DEBUG_EXCEPTION("input_mail_data->file_path_plain, stat(\"%s\") failed...", input_mail_data->file_path_plain);
+                               EM_DEBUG_EXCEPTION_SEC("input_mail_data->file_path_plain, stat(\"%s\") failed...", input_mail_data->file_path_plain);
                                err = EMAIL_ERROR_FILE_NOT_FOUND;
                                goto FINISH_OFF;
                        }
@@ -4862,7 +4980,7 @@ INTERNAL_FUNC int emcore_update_mail(email_mail_data_t *input_mail_data, email_a
                
                if (input_mail_data->file_path_html)  {
                        if (stat(input_mail_data->file_path_html, &st_buf) < 0)  {
-                               EM_DEBUG_EXCEPTION("input_mail_data->file_path_html, stat(\"%s\") failed...", input_mail_data->file_path_html);
+                               EM_DEBUG_EXCEPTION_SEC("input_mail_data->file_path_html, stat(\"%s\") failed...", input_mail_data->file_path_html);
                                err = EMAIL_ERROR_FILE_NOT_FOUND;
                                goto FINISH_OFF;
                        }
@@ -4927,14 +5045,31 @@ INTERNAL_FUNC int emcore_update_mail(email_mail_data_t *input_mail_data, email_a
 
        if (input_attachment_data_list && input_attachment_count)  {
                int i = 0;
+               int j = 0;
                int compare_result = 1;
                email_attachment_data_t *temp_attachment_data = NULL;
+                               
+               if ((err = emcore_get_attachment_data_list(input_mail_data->mail_id, &ori_attachment_data_list, &ori_attachment_count)) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("emcore_get_attachment_data_list failed : [%d]", err);
+               }
 
+               if (ori_attachment_count > 0) { /* prevent 33415 */
+                       temp_attachment_id_array = em_malloc (sizeof(int) * ori_attachment_count);
+                       if (temp_attachment_id_array == NULL) {
+                               EM_DEBUG_EXCEPTION("em_malloc failed");
+                               err = EMAIL_ERROR_OUT_OF_MEMORY;
+                               goto FINISH_OFF2;
+                       }
+               }
+       
                for(i = 0; i < input_attachment_count; i++) {
                        temp_attachment_data = input_attachment_data_list + i;
-                       if ( (err = emcore_mail_compare_filename_of_attachment_data(input_mail_data->mail_id, temp_attachment_data->attachment_id, temp_attachment_data, &compare_result)) != EMAIL_ERROR_NONE) {
-                               EM_DEBUG_EXCEPTION("emcore_mail_compare_filename_of_attachment_data failed [%d]", err);
-                               compare_result = 1;
+                       if ( (err = emcore_mail_compare_filename_of_attachment_data(input_mail_data->mail_id, \
+                               temp_attachment_data->attachment_id, temp_attachment_data, &compare_result)) != EMAIL_ERROR_NONE) {
+                               if (err == EMAIL_ERROR_ATTACHMENT_NOT_FOUND)                                            
+                                       EM_DEBUG_LOG ("no attachment found");
+                               else
+                                       EM_DEBUG_EXCEPTION ("emcore_mail_compare_filename_of_attachment_data failed [%d]", err);
                        }
        
                        if (compare_result == 0) {
@@ -4943,18 +5078,18 @@ INTERNAL_FUNC int emcore_update_mail(email_mail_data_t *input_mail_data, email_a
                                        EM_DEBUG_EXCEPTION("emcore_mail_update_attachment_data failed [%d]", err);
                                        goto FINISH_OFF2;
                                }
+                               temp_attachment_id_array[i] = temp_attachment_data->attachment_id;
                        }
                        else {
                                EM_DEBUG_LOG("save names are different");
                                if(temp_attachment_data->attachment_id > 0) {
                                        if (!emcore_delete_mail_attachment(temp_attachment_data->attachment_id, &err)) {
                                                EM_DEBUG_EXCEPTION("emcore_delete_mail_attachment failed [%d]", err);
-                                               goto FINISH_OFF2;
                                        }
                                }
 
-                               if ( (err = emcore_mail_add_attachment_data(input_mail_data->mail_id, temp_attachment_data)) != EMAIL_ERROR_NONE)  {
-                                       EM_DEBUG_EXCEPTION("emcore_mail_add_attachment failed [%d]", err);
+                               if ( (err = emcore_add_attachment_data(input_mail_data->mail_id, temp_attachment_data)) != EMAIL_ERROR_NONE)  {
+                                       EM_DEBUG_EXCEPTION("emcore_add_attachment failed [%d]", err);
                                        goto FINISH_OFF2;
                                }
                        }
@@ -4962,9 +5097,26 @@ INTERNAL_FUNC int emcore_update_mail(email_mail_data_t *input_mail_data, email_a
                        if (temp_attachment_data->inline_content_status)
                                local_inline_content_count++;
                }
+
+               for (i = 0; i < ori_attachment_count; i++) {
+                       temp_attachment_data = ori_attachment_data_list + i;
+                       compare_result = 0;
+                       for (j = 0; j < input_attachment_count; j++) {
+                               if (temp_attachment_id_array[j] != temp_attachment_data->attachment_id) 
+                                       continue;               
+                               
+                               compare_result = 1;                     
+                       }
+
+                       if (!compare_result) {
+                               if (!emcore_delete_mail_attachment(temp_attachment_data->attachment_id, &err)) {
+                                       EM_DEBUG_EXCEPTION("emcore_delete_mail_attachment failed [%d]", err);
+                               }
+                       }
+               }
        }
        
-       input_mail_data->attachment_count     = input_attachment_count;
+       input_mail_data->attachment_count     = input_attachment_count - local_inline_content_count;
        input_mail_data->inline_content_count = local_inline_content_count;
 
        if (!input_mail_data->date_time) {
@@ -5015,6 +5167,7 @@ INTERNAL_FUNC int emcore_update_mail(email_mail_data_t *input_mail_data, email_a
 
        if (!emstorage_change_mail_text_field(input_mail_data->mail_id, mail_text, false, &err)) {
                EM_DEBUG_EXCEPTION("emstorage_change_mail_text_field failed [%d]", err);
+               emstorage_free_mail_text(&mail_text, 1, NULL); /*prevent 17955*/
                goto FINISH_OFF;
        }
 
@@ -5064,8 +5217,10 @@ FINISH_OFF:
                        err = EMAIL_ERROR_DB_FAILURE;
                }
 
-               if (input_mail_data->meeting_request_status && !emcore_notify_storage_event(NOTI_MAIL_UPDATE, input_mail_data->account_id, input_mail_data->mail_id, NULL, UPDATE_MEETING))
-                       EM_DEBUG_EXCEPTION(" emcore_notify_storage_event failed [ NOTI_MAIL_UPDATE : UPDATE_MEETING_RESPONSE ] >>>> ");
+               SNPRINTF(mailbox_id_param_string, 10, "%d", input_mail_data->mailbox_id);
+
+               if (!emcore_notify_storage_event(NOTI_MAIL_UPDATE, input_mail_data->account_id, input_mail_data->mail_id, mailbox_id_param_string, input_mail_data->meeting_request_status?UPDATE_MEETING:UPDATE_MAIL))
+                       EM_DEBUG_EXCEPTION(" emcore_notify_storage_event failed [NOTI_MAIL_UPDATE] ");
        }
        else {
                /*  ROLLBACK TRANSACTION; */
@@ -5076,6 +5231,10 @@ FINISH_OFF:
 FINISH_OFF2:
 
        EM_SAFE_FREE(body_text_file_name);
+       EM_SAFE_FREE(temp_attachment_id_array);
+
+       if (ori_attachment_data_list)
+               emcore_free_attachment_data(&ori_attachment_data_list, ori_attachment_count, NULL);
 
        if(meeting_req)
                emstorage_free_meeting_request(meeting_req);
@@ -5375,7 +5534,7 @@ INTERNAL_FUNC int emcore_sync_flag_with_server(int mail_id, int *err_code)
 FINISH_OFF: 
        
        if (stream)
-               emcore_close_mailbox(account_id, stream);
+               stream = mail_close (stream);
 
        if (mail)
                emstorage_free_mail(&mail, 1, NULL);
@@ -5416,7 +5575,7 @@ INTERNAL_FUNC int emcore_sync_seen_flag_with_server(int mail_ids[], int num, int
        int mail_id = 0;
        int i = 0;
 
-       memset(&mailbox, 0x00, sizeof(email_mailbox_t));
+       memset(&mailbox, 0x00, sizeof(email_internal_mailbox_t)); /*prevent 20575*/
 
        mail_id = mail_ids[0];
 
@@ -5504,8 +5663,10 @@ INTERNAL_FUNC int emcore_sync_seen_flag_with_server(int mail_ids[], int num, int
 
 FINISH_OFF:
        
-       if (stream) emcore_close_mailbox(account_id, stream);
-       if (mail) emstorage_free_mail(&mail, 1, NULL);
+       if (stream) 
+               stream = mail_close (stream);
+       if (mail) 
+               emstorage_free_mail(&mail, 1, NULL);
 
        if (ref_account) {
                emcore_free_account(ref_account);
@@ -5522,10 +5683,8 @@ INTERNAL_FUNC void emcore_free_mail_data_list(email_mail_data_t **mail_list, int
 {
        EM_DEBUG_FUNC_BEGIN("count[%d]", count);
        
-       if (count <= 0 || !mail_list || !*mail_list)  {
-               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");                        
+       if (count <= 0 || !mail_list || !*mail_list) 
                return;
-       }
                
        email_mail_data_t* p = *mail_list;
        int i;
@@ -5905,8 +6064,8 @@ FINISH_OFF:
        if (false == ret)
                emcore_free_uid_range_set(&uid_range_set);
 
-       emcore_close_mailbox(0, stream);
-       stream = NULL;
+       if (stream)
+               stream = mail_close (stream);
 
        if (temp_account) {
                emcore_free_account(temp_account);
@@ -5934,13 +6093,17 @@ static int emcore_mail_move_by_filter_rule(int account_id, int mailbox_id, int m
        emstorage_mailbox_tbl_t *dst_mailbox_tbl = NULL;
        emstorage_mail_tbl_t *mail_tbl = NULL;
        
-       if ((account_id < 0) && !mailbox_id && !filter_info) {
+       if ((account_id < 0) && !filter_info) {
                EM_DEBUG_EXCEPTION("Invalid parameter");
                err = EMAIL_ERROR_INVALID_PARAM;
                return err;
        }
 
-       if (!emstorage_filter_mails_by_rule(account_id, mailbox_id, mailbox_type, filter_info, &filter_mail_id_list, &filter_mail_id_count, &err)) {
+        if (filter_info->rule_id > 0 && !emstorage_update_tag_id(filter_info->rule_id, 0, &err)) {
+                EM_DEBUG_EXCEPTION("emstorage_update_tag_id failed : [%d]", err);
+        }
+
+       if (!emstorage_filter_mails_by_rule(account_id, mailbox_id, mailbox_type, false, filter_info, &filter_mail_id_list, &filter_mail_id_count, &err)) {
                EM_DEBUG_EXCEPTION("emstorage_filter_mails_by_rule failed [%d]", err);
                goto FINISH_OFF;
        }
@@ -5970,29 +6133,31 @@ static int emcore_mail_move_by_filter_rule(int account_id, int mailbox_id, int m
                        EM_DEBUG_EXCEPTION("emcore_notify_storage_event failed [ NOTI_MAIL_MOVE ] >>>> ");
        }
 
-       /* Move the mails on server */
-       if ((err = emstorage_get_mailbox_by_id(mailbox_id, &dst_mailbox_tbl)) != EMAIL_ERROR_NONE || !dst_mailbox_tbl) {
-               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_id failed : [%d]", err);
-               goto FINISH_OFF;
-       }
-
-       for (mail_id_index = 0; mail_id_index < filter_mail_id_count; mail_id_index++) {
-               if (!emstorage_get_mail_by_id(filter_mail_id_list[mail_id_index], &mail_tbl, false, &err)) {
-                       EM_DEBUG_EXCEPTION("emstorage_get_mail_by_id failed : [%d]", err);
-                       goto FINISH_OFF;
-               }
-
-               if ((err = emstorage_get_mailbox_by_id(mail_tbl->mailbox_id, &src_mailbox_tbl)) != EMAIL_ERROR_NONE) {
+       if (filter_info->action_type != EMAIL_FILTER_MOVE) {
+               /* Move the mails on server */
+               if ((err = emstorage_get_mailbox_by_id(mailbox_id, &dst_mailbox_tbl)) != EMAIL_ERROR_NONE || !dst_mailbox_tbl) {
                        EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_id failed : [%d]", err);
                        goto FINISH_OFF;
                }
 
-               if (!emcore_move_mail_on_server(account_id, src_mailbox_tbl->mailbox_id, filter_mail_id_list, filter_mail_id_count, dst_mailbox_tbl->mailbox_name, &err)) {
-                       EM_DEBUG_EXCEPTION("emcore_move_mail_on_server failed : [%d]", err);
-                       goto FINISH_OFF;
-               }
+               for (mail_id_index = 0; mail_id_index < filter_mail_id_count; mail_id_index++) {
+                       if (!emstorage_get_mail_by_id(filter_mail_id_list[mail_id_index], &mail_tbl, false, &err)) {
+                               EM_DEBUG_EXCEPTION("emstorage_get_mail_by_id failed : [%d]", err);
+                               goto FINISH_OFF;
+                       }
 
-               emstorage_free_mailbox(&src_mailbox_tbl, 1, NULL); /*prevent 46750*/
+                       if ((err = emstorage_get_mailbox_by_id(mail_tbl->mailbox_id, &src_mailbox_tbl)) != EMAIL_ERROR_NONE) {
+                               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_id failed : [%d]", err);
+                               goto FINISH_OFF;
+                       }
+
+                       if (!emcore_move_mail_on_server(account_id, src_mailbox_tbl->mailbox_id, filter_mail_id_list, filter_mail_id_count, dst_mailbox_tbl->mailbox_name, &err)) {
+                               EM_DEBUG_EXCEPTION("emcore_move_mail_on_server failed : [%d]", err);
+                               goto FINISH_OFF;
+                       }
+
+                       emstorage_free_mailbox(&src_mailbox_tbl, 1, NULL); /*prevent 46750*/
+               }
        }
 
 FINISH_OFF:    
@@ -6028,12 +6193,10 @@ INTERNAL_FUNC int emcore_mail_filter_by_rule(email_rule_t *filter_info, int *err
 
        switch (filter_info->faction) {
        case EMAIL_FILTER_MOVE :
-               if ((err = emstorage_get_mailbox_by_id(filter_info->target_mailbox_id, &spam_mailbox)) != EMAIL_ERROR_NONE) {
-                       EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_id for id[%d] failed : [%d]", filter_info->target_mailbox_id, err);
-                       goto FINISH_OFF;
-               }
+               if (filter_info->type != EMAIL_PRIORITY_SENDER)
+                       break;
 
-               if ((err = emcore_mail_move_by_filter_rule(filter_info->account_id, spam_mailbox->mailbox_id, spam_mailbox->mailbox_type, (emstorage_rule_tbl_t *)filter_info)) != EMAIL_ERROR_NONE) {
+               if ((err = emcore_mail_move_by_filter_rule(filter_info->account_id, 0, 0, (emstorage_rule_tbl_t *)filter_info)) != EMAIL_ERROR_NONE) {
                        EM_DEBUG_EXCEPTION("emcore_mail_move_by_filter_rule failed : [%d]", err);
                        goto FINISH_OFF;
                }
index dfcebcc..a9c3ae0 100755 (executable)
@@ -31,6 +31,7 @@
 #include <string.h>
 #include <ctype.h>
 #include <vconf.h>
+#include <unicode/ucsdet.h>
 
 #include "email-internal-types.h"
 
@@ -60,6 +61,7 @@
 
 #define MAX_CHARSET_VALUE 256
 
+static int g_current_sync_account_id = 0;
 static char g_append_uid_rsp[129]; /* added for getting server response  */
 
 extern void imap_parse_body_structure (MAILSTREAM *stream, BODY *body, unsigned char **txtptr, IMAPPARSEDREPLY *reply);
@@ -307,12 +309,12 @@ int pop3_mailbox_get_uids(MAILSTREAM *stream, emcore_uid_list** uid_list, int *e
                }
 
                if (*response == '+') {         /*  "+OK" */
-                       free(response); response = NULL;
+                       EM_SAFE_FREE (response);
                        continue;
                }
 
                if (*response == '.') {
-                       free(response); response = NULL;
+                       EM_SAFE_FREE (response);
                        break;
                }
 
@@ -338,14 +340,13 @@ int pop3_mailbox_get_uids(MAILSTREAM *stream, emcore_uid_list** uid_list, int *e
                        goto FINISH_OFF;
                }
 
-               free(response); response = NULL;
+               EM_SAFE_FREE (response);
        }
 
        ret = true;
 
 FINISH_OFF:
-       if (response  != NULL)
-               free(response);
+       EM_SAFE_FREE(response);
 
        if (err_code  != NULL)
                *err_code = err;
@@ -409,6 +410,7 @@ int imap4_mailbox_get_uids(MAILSTREAM *stream, emcore_uid_list** uid_list, int *
                int seen = 0;
                int forwarded = 0;
                int draft = 0;
+               int flagged = 0;
                /*  receive response */
                if (!(response = net_getline(imaplocal->netstream))) {
                        EM_DEBUG_EXCEPTION("net_getline failed...");
@@ -422,7 +424,7 @@ int imap4_mailbox_get_uids(MAILSTREAM *stream, emcore_uid_list** uid_list, int *
 
                if (!strncmp(response, tag, EM_SAFE_STRLEN(tag))) {
                        if (!strncmp(response + EM_SAFE_STRLEN(tag) + 1, "OK", 2)) {
-                               free(response); response = NULL;
+                               EM_SAFE_FREE (response);
                                break;
                        }
                        else {          /*  'NO' or 'BAD' */
@@ -437,6 +439,7 @@ int imap4_mailbox_get_uids(MAILSTREAM *stream, emcore_uid_list** uid_list, int *
 
                                seen = strstr(p, "\\Seen") ? 1  :  0;
                                draft = strstr(p, "\\Draft") ? 1  :  0;
+                               flagged = strstr(p, "\\Flagged") ? 1  :  0;
                                forwarded = strstr(p, "$Forwarded") ? 1  :  0;
 
                                if ((p = strstr(p, "UID "))) {
@@ -458,6 +461,7 @@ int imap4_mailbox_get_uids(MAILSTREAM *stream, emcore_uid_list** uid_list, int *
                                        uid_elem->flag.seen = seen;
                                        uid_elem->flag.draft = draft;
                                        uid_elem->flag.forwarded = forwarded;
+                                       uid_elem->flag.flagged = flagged;
                                        if (*uid_list  != NULL)
                                                uid_elem->next = *uid_list;             /*  prepend new data to list */
 
@@ -631,7 +635,7 @@ int imap4_mailbox_get_uids_by_timestamp(MAILSTREAM *stream, emcore_uid_list** ui
 
                if (!strncmp(response, tag, EM_SAFE_STRLEN(tag))) {
                        if (!strncmp(response + EM_SAFE_STRLEN(tag) + 1, "OK", 2)) {
-                               free(response); response = NULL;
+                               EM_SAFE_FREE (response);
                                break;
                        }
                        else {  /*  'NO' or 'BAD' */
@@ -676,8 +680,7 @@ int imap4_mailbox_get_uids_by_timestamp(MAILSTREAM *stream, emcore_uid_list** ui
        ret = true;
 
 FINISH_OFF:
-       if (response  != NULL)
-               free(response);
+       EM_SAFE_FREE (response);
 
        if (err_code  != NULL)
                *err_code = err;
@@ -687,7 +690,7 @@ FINISH_OFF:
 }
 
 #define PARSE_BUFFER_LENGTH 4096
-static int emcore_parse_header(char *rfc822_header, int *req_read_receipt, int *priority, int *err_code)
+static int emcore_parse_header(char *rfc822_header, char **subject, char **from, int *req_read_receipt, int *priority, int *err_code)
 {
        EM_DEBUG_FUNC_BEGIN("rfc822_header[%p], req_read_receipt[%p], priority[%p], err_code[%p]", rfc822_header, req_read_receipt, priority,  err_code);
 
@@ -701,6 +704,7 @@ static int emcore_parse_header(char *rfc822_header, int *req_read_receipt, int *
 
        char buf[PARSE_BUFFER_LENGTH];
        int len, i, j;
+       int subject_flag = 0;
 
        EM_DEBUG_LOG("Buffer length [%d]", PARSE_BUFFER_LENGTH);
 
@@ -719,10 +723,11 @@ static int emcore_parse_header(char *rfc822_header, int *req_read_receipt, int *
                        j = 0;
 
                        /*  parsing data */
-                       em_upper_string(buf);
+                       EM_DEBUG_LOG_DEV("buf:%s", buf);
 
                        /*  disposition_notification_to */
                        if (buf[0] == 'D' && buf[11] == '-' && buf[12] == 'N' && buf[24] == '-' && buf[25] == 'T') {
+                               em_upper_string(buf);
                                if (req_read_receipt)
                                        *req_read_receipt = 1;
                                memset(buf, 0x00, PARSE_BUFFER_LENGTH);
@@ -731,6 +736,7 @@ static int emcore_parse_header(char *rfc822_header, int *req_read_receipt, int *
 
                        /*  x-priority */
                        if (buf[0] == 'X' && buf[2] == 'P' && buf[9] == 'Y'){
+                               em_upper_string(buf);
                                size_t len_2 = EM_SAFE_STRLEN(buf);
                                if (len_2 >= 12){
                                        buf[len_2 - 2] = '\0';
@@ -742,6 +748,7 @@ static int emcore_parse_header(char *rfc822_header, int *req_read_receipt, int *
 
                        /*  x-msmail-priority */
                        if (buf[0] == 'X' && buf[2] == 'M' && buf[9] == 'P' && buf[16] == 'Y'){
+                               em_upper_string(buf);
                                if (strstr(buf, "HIGH"))
                                        *priority = 1;
                                if (strstr(buf, "NORMAL"))
@@ -752,6 +759,64 @@ static int emcore_parse_header(char *rfc822_header, int *req_read_receipt, int *
                                continue;
                        }
 
+                       /* subject */
+                       if (subject) {
+                               if (buf[0] != ' ' && buf[0] != '\t') {
+                                       subject_flag = 0;
+                               }
+
+                               if (buf[0] == 'S' && buf[1] == 'u' && buf[2] == 'b') {
+                                       char *deli = NULL;
+                                       char *r = NULL;
+
+                                       deli = strstr(buf, ":");
+                                       r = strstr(buf, "\r\n");
+                                       if (r) *r = '\0';
+
+                                       if (deli) {
+                                               *subject = g_strdup(deli+1);
+                                               EM_DEBUG_LOG_DEV("subject:%s", *subject);
+                                       }
+
+                                       subject_flag = 1;
+                               }
+
+                               if (subject_flag && (buf[0] == ' ' || buf[0] == '\t')) {
+                                       char *subject_add = NULL;
+                                       char *tmp = NULL;
+                                       char *r = NULL;
+
+                                       r = strstr(buf, "\r\n");
+                                       if (r) *r = '\0';
+
+                                       subject_add = g_strdup(buf+1);
+
+                                       tmp = *subject;
+                                       *subject = g_strconcat(*subject, "\t", subject_add, NULL);
+                                       EM_SAFE_FREE(tmp);
+                                       EM_SAFE_FREE(subject_add);
+
+                                       EM_DEBUG_LOG_DEV("subject:%s", *subject);
+                               }
+                       }
+
+                       /* From */
+                       if (from) {
+                               if (buf[0] == 'F' && buf[1] == 'r' && buf[2] == 'o') {
+                                       char *deli = NULL;
+                                       char *r = NULL;
+
+                                       deli = strstr(buf, ":");
+                                       r = g_strrstr(buf, "<");
+                                       if (r) *r = '\0';
+
+                                       if (deli) {
+                                               *from = g_strdup(deli+1);
+                                               EM_DEBUG_LOG_DEV("from:%s", *from);
+                                       }
+                               }
+                       }
+
                        memset(buf, 0x00, PARSE_BUFFER_LENGTH);
                        continue;
                }
@@ -771,7 +836,7 @@ static int emcore_parse_header(char *rfc822_header, int *req_read_receipt, int *
 }
 
 
-static int emcore_get_mail_extra_info(MAILSTREAM *stream, int msgno, int *req_read_receipt, int *priority, int *err_code)
+static int emcore_get_mail_extra_info(MAILSTREAM *stream, int msgno, char **subject, char **from, int *req_read_receipt, int *priority, int *err_code)
 {
        EM_PROFILE_BEGIN(emCoreMailGetExtraInfo);
        EM_DEBUG_FUNC_BEGIN("stream[%p], msgno[%d], req_read_receipt[%p], priority[%p], err_code[%p]", stream, msgno, req_read_receipt, priority, err_code);
@@ -805,7 +870,7 @@ static int emcore_get_mail_extra_info(MAILSTREAM *stream, int msgno, int *req_re
                goto FINISH_OFF;
        }
 
-       if (!emcore_parse_header(rfc822_header, req_read_receipt, priority, &err)) {
+       if (!emcore_parse_header(rfc822_header, subject, from, req_read_receipt, priority, &err)) {
                EM_DEBUG_EXCEPTION("emcore_parse_header falied - %d", err);
                goto FINISH_OFF;
        }
@@ -821,6 +886,11 @@ FINISH_OFF:
        return ret;
 }
 
+#define EMAIL_SYNC_STATUS_NOT_EXIST_ON_SERVER  0
+#define EMAIL_SYNC_STATUS_EXIST_ON_SERVER      1
+#define EMAIL_SYNC_STATUS_SEEN_FLAG_CHANGED    2
+#define EMAIL_SYNC_STATUS_FLAG_CHANGED         3
+
 static int emcore_get_uids_to_download(MAILSTREAM *stream, email_account_t *account, emstorage_mailbox_tbl_t *input_mailbox_tbl, int limit_count, emcore_uid_list** uid_list, int *uids, int retrieve_mode ,  int *err_code)
 {
        EM_PROFILE_BEGIN(emCoreGetUidsDownload);
@@ -830,7 +900,7 @@ static int emcore_get_uids_to_download(MAILSTREAM *stream, email_account_t *acco
        int err = EMAIL_ERROR_NONE;
 
        emstorage_read_mail_uid_tbl_t *downloaded_uids = NULL;
-       int i = 0, j = 0, uid_count = 0, uid_to_be_downloaded_count = 0;
+       int i = 0, downloaded_uid_count = 0, uid_count = 0, uid_to_be_downloaded_count = 0;
        emcore_uid_list *uid_elem = NULL;
        emcore_uid_list *head_uid_elem = NULL, *end =  NULL;
        emcore_uid_list *next_uid_elem = NULL;
@@ -858,24 +928,23 @@ static int emcore_get_uids_to_download(MAILSTREAM *stream, email_account_t *acco
                        EM_DEBUG_EXCEPTION("imap4_mailbox_get_uids failed [%d]", err);
                        if (err  != EMAIL_ERROR_MAIL_NOT_FOUND_ON_SERVER)
                                goto FINISH_OFF;
-           }
+               }
        }
 
        if (!emstorage_get_downloaded_list(input_mailbox_tbl->account_id,
-        (account->incoming_server_type == EMAIL_SERVER_TYPE_POP3) ? 0 : input_mailbox_tbl->mailbox_id,
-        &downloaded_uids, &j, true, &err)) {
+               (account->incoming_server_type == EMAIL_SERVER_TYPE_POP3) ? 0 : input_mailbox_tbl->mailbox_id,
+               &downloaded_uids, &downloaded_uid_count, true, &err)) {
                EM_DEBUG_EXCEPTION("emstorage_get_downloaded_list failed [%d]", err);
-
                goto FINISH_OFF;
        }
-       EM_DEBUG_LOG("Number of Mails in Downloaded Table [%d]", j);
+       EM_DEBUG_LOG("Number of Mails in Downloaded Table [%d]", downloaded_uid_count);
 
        uid_elem = *uid_list;
        uid_count = 0;
 
        if(!uid_elem) { /* If there is no mail in the input_mailbox_tbl, remove all mails in the input_mailbox_tbl */
-               for (i = 0; i < j; i++) {
-                       downloaded_uids[i].reserved = 0;
+               for (i = 0; i < downloaded_uid_count; i++) {
+                       downloaded_uids[i].sync_status = EMAIL_SYNC_STATUS_NOT_EXIST_ON_SERVER;
                }
        }
 
@@ -884,11 +953,9 @@ static int emcore_get_uids_to_download(MAILSTREAM *stream, email_account_t *acco
        while (uid_elem) {
                next_uid_elem = uid_elem->next;
 
-               if ((account->retrieval_mode == EMAIL_IMAP4_RETRIEVAL_MODE_NEW) && (uid_elem->flag.seen != 0)){         /*  already seen */
-                       if (uid_elem->uid)
-                               free(uid_elem->uid);
-
-                       free(uid_elem);
+               if ((account->retrieval_mode == EMAIL_IMAP4_RETRIEVAL_MODE_NEW) && (uid_elem->flag.seen != 0)) {                /*  already seen */
+                       EM_SAFE_FREE (uid_elem->uid);
+                       EM_SAFE_FREE (uid_elem);
                }
                else {
                        int to_be_downloaded = 1;
@@ -898,9 +965,22 @@ static int emcore_get_uids_to_download(MAILSTREAM *stream, email_account_t *acco
                                to_be_downloaded = 0;
                        }
                        else{
-                               for (i = j; i > 0; i--) {
-                                       if (downloaded_uids[i - 1].reserved == 0 && !strcmp(uid_elem->uid, downloaded_uids[i - 1].s_uid)) {
-                                               downloaded_uids[i - 1].reserved = uid_elem->flag.seen ? 2 : 1;
+                               for (i = downloaded_uid_count; i > 0; i--) {
+                                       if (downloaded_uids[i - 1].sync_status == EMAIL_SYNC_STATUS_NOT_EXIST_ON_SERVER && !EM_SAFE_STRCMP(uid_elem->uid, downloaded_uids[i - 1].server_uid)) {
+                                               /* The mail exists on server and local storage, so it should not be downloaded, just check seen flag */
+                                               if(downloaded_uids[i - 1].flags_seen_field != uid_elem->flag.seen ||
+                                                               downloaded_uids[i - 1].flags_flagged_field != uid_elem->flag.flagged) {
+                                                       if(downloaded_uids[i - 1].flags_seen_field != uid_elem->flag.seen) {
+                                                               downloaded_uids[i - 1].sync_status = EMAIL_SYNC_STATUS_FLAG_CHANGED;
+                                                               downloaded_uids[i - 1].flags_seen_field = uid_elem->flag.seen;
+                                                       }
+                                                       if (downloaded_uids[i - 1].flags_flagged_field != uid_elem->flag.flagged) {
+                                                               downloaded_uids[i - 1].sync_status = EMAIL_SYNC_STATUS_FLAG_CHANGED;
+                                                               downloaded_uids[i - 1].flags_flagged_field = uid_elem->flag.flagged;
+                                                       }
+                                               } else {
+                                                       downloaded_uids[i - 1].sync_status = EMAIL_SYNC_STATUS_EXIST_ON_SERVER;
+                                               }
                                                to_be_downloaded = 0;
                                                break;
                                        }
@@ -930,9 +1010,8 @@ static int emcore_get_uids_to_download(MAILSTREAM *stream, email_account_t *acco
 
                        }
                        else {
-                               if (uid_elem->uid)
-                                       free(uid_elem->uid);
-                               free(uid_elem);
+                               EM_SAFE_FREE (uid_elem->uid);
+                               EM_SAFE_FREE (uid_elem);
                        }
 
                        uid_count++;
@@ -944,11 +1023,11 @@ static int emcore_get_uids_to_download(MAILSTREAM *stream, email_account_t *acco
        EM_PROFILE_END(emCoreGetUidsDownloadWhilwLoop);
        EM_PROFILE_BEGIN(emCoreGetUidsDownloadForLoop);
 
-       for (i = 0; i < j; i++) {
-               /*  EM_DEBUG_LOG("input_mailbox_tbl[%s] reserved[%d]", input_mailbox_tbl->name, downloaded_uids[i].reserved); */
-               if (downloaded_uids[i].reserved == 0) {         /*  deleted on server */
-                       if (!emstorage_get_maildata_by_servermailid(input_mailbox_tbl->mailbox_id, downloaded_uids[i].s_uid, &mail, true, &err)){
-                               EM_DEBUG_EXCEPTION("emstorage_get_maildata_by_servermailid for uid[%s] Failed [%d] \n ", downloaded_uids[i].s_uid, err);
+       for (i = 0; i < downloaded_uid_count; i++) {
+               /*  EM_DEBUG_LOG("input_mailbox_tbl[%s] sync_status[%d]", input_mailbox_tbl->name, downloaded_uids[i].sync_status); */
+               if (downloaded_uids[i].sync_status == EMAIL_SYNC_STATUS_NOT_EXIST_ON_SERVER) {          /*  deleted on server */
+                       if (!emstorage_get_maildata_by_servermailid(input_mailbox_tbl->mailbox_id, downloaded_uids[i].server_uid, &mail, true, &err)){
+                               EM_DEBUG_EXCEPTION("emstorage_get_maildata_by_servermailid for uid[%s] Failed [%d] \n ", downloaded_uids[i].server_uid, err);
                                if (err == EMAIL_ERROR_MAIL_NOT_FOUND){
                                        continue;
                                }
@@ -963,26 +1042,27 @@ static int emcore_get_uids_to_download(MAILSTREAM *stream, email_account_t *acco
                                emcore_display_unread_in_badge();
                        }
 
-                       if (!emstorage_remove_downloaded_mail(input_mailbox_tbl->account_id, input_mailbox_tbl->mailbox_name, downloaded_uids[i].s_uid, true, &err)) {   /*  remove uid from uid list */
+                       if (!emstorage_remove_downloaded_mail(input_mailbox_tbl->account_id, input_mailbox_tbl->mailbox_name, downloaded_uids[i].server_uid, true, &err)) {   /*  remove uid from uid list */
                                EM_DEBUG_EXCEPTION("emstorage_remove_downloaded_mail failed - %d", err);
-
                                /* goto FINISH_OFF; */
                        }
 
                }
-               else if (account->incoming_server_type == EMAIL_SERVER_TYPE_IMAP4 && downloaded_uids[i].reserved == 1) {
-                       /*  unseen on server */
-                       if  (!emstorage_get_mail_by_id(downloaded_uids[i].local_uid, &mail, true, &err)){
-                               EM_DEBUG_EXCEPTION("emstorage_get_mail_by_id failed for [%d] - [%d]", downloaded_uids[i].local_uid, err);
-                               continue;
-                       }
+               else if (account->incoming_server_type == EMAIL_SERVER_TYPE_IMAP4) {
+                       /* set seen flag of downloaded mail */
+                       if (downloaded_uids[i].sync_status == EMAIL_SYNC_STATUS_FLAG_CHANGED) {
+                               if (!emcore_set_flags_field(downloaded_uids[i].account_id, &(downloaded_uids[i].local_uid), 1, EMAIL_FLAGS_FLAGGED_FIELD, downloaded_uids[i].flags_flagged_field, &err)) {
+                                       EM_DEBUG_EXCEPTION("emcore_set_flags_field failed [%d]", err);
+                               }
 
-                       if (mail) {
-                               if (mail->body_download_status && mail->flags_seen_field){
-                                       EM_DEBUG_LOG("Set flag as seen on server");
-                                       mail_setflag_full(stream, downloaded_uids[i].s_uid, "\\Seen", ST_UID);
+                               if (!emcore_set_flags_field(downloaded_uids[i].account_id, &(downloaded_uids[i].local_uid), 1, EMAIL_FLAGS_SEEN_FIELD, downloaded_uids[i].flags_seen_field, &err)) {
+                                       EM_DEBUG_EXCEPTION("emcore_set_flags_field failed [%d]", err);
                                }
+                               else
+                                       emcore_display_unread_in_badge();
                        }
+
+
                }
                if (mail != NULL)
                        emstorage_free_mail(&mail, 1, NULL);
@@ -1002,7 +1082,7 @@ FINISH_OFF:
        }
 
        if (downloaded_uids != NULL)
-               emstorage_free_read_mail_uid(&downloaded_uids, j, NULL);
+               emstorage_free_read_mail_uid(&downloaded_uids, downloaded_uid_count, NULL);
 
        if (mail != NULL)
                emstorage_free_mail(&mail, 1, NULL);
@@ -1018,7 +1098,7 @@ FINISH_OFF:
 /* insert received mail UID to read mail uid table */
 static int emcore_add_read_mail_uid(emstorage_mailbox_tbl_t *input_maibox_data, char *server_mailbox_name, int mail_id, char *uid, int rfc822_size, int rule_id, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("input_maibox_data[%p], server_mailbox_name[%s], uid[%s], rfc822_size[%d], rule_id[%d], err_code[%p]", input_maibox_data, server_mailbox_name, uid, rfc822_size, rule_id, err_code);
+       EM_DEBUG_FUNC_BEGIN_SEC("input_maibox_data[%p], server_mailbox_name[%s], uid[%s], rfc822_size[%d], rule_id[%d], err_code[%p]", input_maibox_data, server_mailbox_name, uid, rfc822_size, rule_id, err_code);
 
        int ret = false;
        int err = EMAIL_ERROR_NONE;
@@ -1054,9 +1134,8 @@ static int emcore_add_read_mail_uid(emstorage_mailbox_tbl_t *input_maibox_data,
        else
                read_mail_uid.mailbox_name = mailbox_tbl->mailbox_name;
 
-       read_mail_uid.s_uid = uid;
-       read_mail_uid.data1 = rfc822_size;
-       read_mail_uid.flag = rule_id;
+       read_mail_uid.server_uid = uid;
+       read_mail_uid.rfc822_size = rfc822_size;
 
        if (!emstorage_add_downloaded_mail(&read_mail_uid, false, &err)) {
                EM_DEBUG_EXCEPTION("emstorage_add_downloaded_mail failed [%d]", err);
@@ -1093,7 +1172,7 @@ int emcore_add_mail_text(emstorage_mailbox_tbl_t *input_maibox_data, emstorage_m
                goto FINISH_OFF;
        }
 
-       mail_text.mail_id = input_new_mail_tbl_data->mail_id;
+       mail_text.mail_id    = input_new_mail_tbl_data->mail_id;
        mail_text.account_id = input_maibox_data->account_id;
        mail_text.mailbox_id = input_maibox_data->mailbox_id;
 
@@ -1111,6 +1190,8 @@ int emcore_add_mail_text(emstorage_mailbox_tbl_t *input_maibox_data, emstorage_m
 
 FINISH_OFF:
 
+       EM_SAFE_FREE(mail_text.body_text);
+
        if (err_code)
                *err_code = err;
 
@@ -1119,7 +1200,7 @@ FINISH_OFF:
 }
 #endif
 
-int emcore_add_mail_to_mailbox(emstorage_mailbox_tbl_t *input_maibox_data, emstorage_mail_tbl_t *input_new_mail_tbl_data, int *output_mail_id, int *output_thread_id)
+INTERNAL_FUNC int emcore_add_mail_to_mailbox(emstorage_mailbox_tbl_t *input_maibox_data, emstorage_mail_tbl_t *input_new_mail_tbl_data, int *output_mail_id, int *output_thread_id)
 {
        EM_DEBUG_FUNC_BEGIN("input_maibox_data[%p], input_new_mail_tbl_data[%p], uid_elem[%p], output_mail_id[%p], output_thread_id[%p]", mail_stream, input_maibox_data, input_new_mail_tbl_data, output_mail_id, output_thread_id);
 
@@ -1202,31 +1283,28 @@ FINISH_OFF:
        return err;
 }
 
-int emcore_check_rule(const char *input_full_address_from, const char *input_subject, emstorage_rule_tbl_t *rule, int rule_len, int *matched, int *err_code)
+int emcore_check_rule(const char *input_full_address_from, const char *input_subject, emstorage_rule_tbl_t *rule, int rule_count, int *priority_sender, int *blocked, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("input_full_address_from [%p], input_subject [%p], rule [%p], rule_len [%d], matched [%p], err_code [%p]", input_full_address_from, input_subject, rule, rule_len, matched, err_code);
+       EM_DEBUG_FUNC_BEGIN("input_full_address_from [%p], input_subject [%p], rule [%p], rule_count [%d], priority_sender [%p], blocked [%p], err_code [%p]", input_full_address_from, input_subject, rule, rule_count, priority_sender, blocked, err_code);
 
-       int ret = false, err = EMAIL_ERROR_NONE, i;
+       int ret = false, err = EMAIL_ERROR_NONE, i = 0;
        size_t len = 0;
-       char *src = NULL;       /*  string which will be compared with rules */
        char *from_address = NULL;
        char *p_input_full_address_from = NULL;
        ADDRESS *addr = NULL;
 
-       if (!matched || !input_full_address_from || !input_subject) {
+       if (!input_full_address_from ) { /*input_subject could be null*/
                EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
                err = EMAIL_ERROR_INVALID_PARAM;
-               goto FINISH_OFF;
+               return ret; /*prevent 54914*/
        }
 
-       *matched = -1;
-
        p_input_full_address_from = strdup((char *)input_full_address_from);
 
        rfc822_parse_adrlist(&addr, p_input_full_address_from, NULL);
 
        if(addr) {
-               EM_DEBUG_LOG("rule : full_address_from[%s], addr->mailbox[%s], addr->host[%s]", p_input_full_address_from, addr->mailbox, addr->host);
+               EM_DEBUG_LOG_SEC("rule : full_address_from[%s], addr->mailbox[%s], addr->host[%s]", p_input_full_address_from, addr->mailbox, addr->host);
 
                if (addr->mailbox)
                        len = EM_SAFE_STRLEN(addr->mailbox);
@@ -1248,55 +1326,71 @@ int emcore_check_rule(const char *input_full_address_from, const char *input_sub
                goto FINISH_OFF;
        }
 
-       for (i = 0; i < rule_len; i++) {
-               if (!(rule + i)) {
-                       EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
-                       err = EMAIL_ERROR_INVALID_PARAM;
-                       goto FINISH_OFF;
-               }
+       for (i = 0; i < rule_count ; i++) {
 
-               EM_DEBUG_LOG("rule[%d].flag1(rule id[%d]) is %d", i, rule[i].rule_id, rule[i].flag1);
+               EM_DEBUG_LOG("rule[%d]: rule_id[%d], flag1[%d], action_type[%d]", i, rule[i].rule_id, rule[i].flag1, rule[i].action_type);
 
-               if (rule[i].flag1){
-                       /*  'ON' */
-                       EM_DEBUG_LOG("rule[%d].flag2(rule id[%d]) is %d", i, rule[i].rule_id, rule[i].flag2);
-                       switch (rule[i].type) {
-                               case EMAIL_FILTER_FROM:
-                                       src = from_address;
-                                       break;
-                               case EMAIL_FILTER_SUBJECT:
-                                       src = (char*)input_subject;
-                                       break;
-                               case EMAIL_FILTER_BODY:
-                                       err = EMAIL_ERROR_NOT_SUPPORTED;
-                                       goto FINISH_OFF;
-                                       break;
-                       }
-                       EM_DEBUG_LOG("rule src[%s], value[%s]\n", src, rule[i].value);
+               if (!rule[i].flag1) { /*flag1 means "OFF(0)/ON(1)"*/
+                       continue;
+               }
 
-                       if (src && rule[i].value) {
-                           if (RULE_TYPE_INCLUDES == rule[i].flag2) {
-                                       if (strstr(src, rule[i].value)) {
-                                               *matched = i;
-                                               break;
+               switch (rule[i].action_type) {
+               case EMAIL_FILTER_DELETE :
+                       EM_DEBUG_LOG("Not support action type");
+                       break;
+
+               case EMAIL_FILTER_BLOCK :
+                       if (rule[i].type == EMAIL_FILTER_SUBJECT) {
+                               if (input_subject && rule[i].value) {
+                                       if (RULE_TYPE_INCLUDES == rule[i].flag2) {
+                                               if (strcasestr(input_subject, rule[i].value))
+                                                       *blocked = true;
                                        }
+                                       else if (RULE_TYPE_EXACTLY == rule[i].flag2) {
+                                               if (!strcasecmp(input_subject, rule[i].value))
+                                                       *blocked = true;
+                                       }      
                                }
-                               else if (RULE_TYPE_EXACTLY == rule[i].flag2) {
-                                       if (!strcmp(src, rule[i].value)) {
-                                               *matched = i;
-                                               break;
+                       }
+
+                       if (rule[i].type == EMAIL_FILTER_FROM) {
+                               if (from_address && rule[i].value2) {
+                                       if (RULE_TYPE_INCLUDES == rule[i].flag2) {
+                                               if (strcasestr(from_address, rule[i].value2))
+                                                       *blocked = true;
+                                       }
+                                       else if (RULE_TYPE_EXACTLY == rule[i].flag2) {
+                                               if (!strcasecmp(from_address, rule[i].value2))
+                                                       *blocked = true;
                                        }
                                }
                        }
+               
+                       break;
+
+               default:
+                       if (rule[i].type != EMAIL_PRIORITY_SENDER)
+                               break;
+
+                       if (from_address && rule[i].value2) {
+                               if (RULE_TYPE_INCLUDES == rule[i].flag2) {
+                                       if (strcasestr(from_address, rule[i].value2))
+                                               *priority_sender = 1;
+                               }      
+                               else if (RULE_TYPE_EXACTLY == rule[i].flag2) {
+                                       if (!strcasecmp(from_address, rule[i].value2)) 
+                                               *priority_sender = 1;
+                               }       
+                       }
+                       break;
                }
-               else
-                       EM_DEBUG_LOG("Invald src or rule[i].value");
        }
        ret = true;
 
-       EM_DEBUG_LOG("i [%d], matched [%d]", i, *matched);
 FINISH_OFF:
 
+       EM_DEBUG_LOG("blocked [%d], priority_sender [%d]", *blocked, *priority_sender);
+
        EM_SAFE_FREE(from_address);
        EM_SAFE_FREE(p_input_full_address_from);
 
@@ -1310,76 +1404,7 @@ FINISH_OFF:
        return ret;
 }
 
-static int emcore_get_utf8_address(char **dest, ADDRESS *address, int *err_code)
-{
-       EM_DEBUG_FUNC_BEGIN("dest[%p], address[%p], err_code[%p]", dest, address, err_code);
-
-       if (!dest || !address)  {
-               EM_DEBUG_EXCEPTION("dest[%p], address[%p]", dest, address);
-               if (err_code != NULL)
-                       *err_code = EMAIL_ERROR_INVALID_PARAM;
-               return false;
-       }
-
-       int ret = false;
-       int err = EMAIL_ERROR_NONE;
-
-       gchar *concatenated = NULL;
-       gchar *utf8_address = NULL;
-       gchar *temp = NULL;
-       char *nickname = NULL;
-
-       while (address)  {
-               EM_DEBUG_LOG("address->mailbox[%s], address->host[%s]", address->mailbox, address->host);
-               if (!address->mailbox || !address->host) {
-                       address = address->next;
-                       continue;
-               }
-               EM_DEBUG_LOG("address->mailbox[%p]", address->personal);
-               if (address->personal)  {
-                       if (!(nickname = emcore_decode_rfc2047_text(address->personal, &err)))  {
-                               EM_DEBUG_EXCEPTION("emcore_decode_rfc2047_text failed - %d", err);
-                               goto FINISH_OFF;
-                       }
-                       EM_DEBUG_LOG("nickname[%s]", nickname);
-                       if (*nickname != '\0')
-                               utf8_address = g_strdup_printf("\"%s\" <%s@%s>", nickname, address->mailbox ? address->mailbox : "", address->host ? address->host : "");
-                       else
-                               utf8_address = g_strdup_printf("<%s@%s>", address->mailbox ? address->mailbox : "", address->host ? address->host : "");
-
-                       EM_SAFE_FREE(nickname);
-               }
-               else
-                       utf8_address = g_strdup_printf("<%s@%s>", address->mailbox ? address->mailbox : "", address->host ? address->host : "");
-
-               EM_DEBUG_LOG("utf8_address[%s]", utf8_address);
-
-               if (concatenated != NULL)  {
-                       temp = concatenated;
-                       concatenated = g_strdup_printf("%s; %s", temp, utf8_address);
-                       g_free(temp);
-               }
-               else
-                       concatenated = g_strdup(utf8_address);
-
-               g_free(utf8_address);
-               utf8_address = NULL;
-
-               address = address->next;
-       }
-
-       *dest = concatenated;
-
-       ret = true;
-
-FINISH_OFF:
-       EM_SAFE_FREE(nickname);
-       EM_DEBUG_FUNC_END("ret[%d]", ret);
-       return ret;
-}
-
-
-int emcore_make_mail_tbl_data_from_envelope(MAILSTREAM *mail_stream, ENVELOPE *input_envelope, emcore_uid_list *input_uid_elem, emstorage_mail_tbl_t **output_mail_tbl_data,  int *err_code)
+INTERNAL_FUNC int emcore_make_mail_tbl_data_from_envelope(int account_id, MAILSTREAM *mail_stream, ENVELOPE *input_envelope, emcore_uid_list *input_uid_elem, emstorage_mail_tbl_t **output_mail_tbl_data,  int *err_code)
 {
        EM_PROFILE_BEGIN(emCoreParseEnvelope);
        EM_DEBUG_FUNC_BEGIN("input_envelope[%p], input_uid_elem [%p], output_mail_tbl_data[%p],  err_code[%p]", input_envelope, input_uid_elem, output_mail_tbl_data, err_code);
@@ -1392,6 +1417,16 @@ int emcore_make_mail_tbl_data_from_envelope(MAILSTREAM *mail_stream, ENVELOPE *i
        struct tm             temp_time_info;
        MESSAGECACHE         *mail_cache_element = NULL;
        emstorage_mail_tbl_t *temp_mail_tbl_data = NULL;
+       email_account_t      *account_ref = NULL;
+       char *rfc822_subject = NULL;
+       char *rfc822_from = NULL;
+
+       account_ref = emcore_get_account_reference(account_id);
+       if (!account_ref) {
+               EM_DEBUG_EXCEPTION("emcore_get_account_reference failed - %d", account_id);
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
 
        if (!output_mail_tbl_data) {
                EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
@@ -1399,6 +1434,12 @@ int emcore_make_mail_tbl_data_from_envelope(MAILSTREAM *mail_stream, ENVELOPE *i
                goto FINISH_OFF;
        }
 
+       if (!input_envelope) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
        if (!(temp_mail_tbl_data = em_malloc(sizeof(emstorage_mail_tbl_t)))) {
                EM_DEBUG_EXCEPTION("em_malloc failed...");
                err = EMAIL_ERROR_OUT_OF_MEMORY;
@@ -1411,9 +1452,32 @@ int emcore_make_mail_tbl_data_from_envelope(MAILSTREAM *mail_stream, ENVELOPE *i
                goto FINISH_OFF;
        }
 
-       if (!emcore_get_mail_extra_info(mail_stream, input_uid_elem->msgno, &req_read_receipt, &priority, &err)) {
-               EM_DEBUG_EXCEPTION("emcore_get_mail_extra_info failed [%d]", err);
-               goto FINISH_OFF;
+       if (g_strrstr(account_ref->incoming_server_address, "outlook.com")) {
+               if (!emcore_get_mail_extra_info(mail_stream, input_uid_elem->msgno, &rfc822_subject, &rfc822_from, &req_read_receipt, &priority, &err)) {
+                       EM_DEBUG_EXCEPTION("emcore_get_mail_extra_info failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+       } else {
+               if (!emcore_get_mail_extra_info(mail_stream, input_uid_elem->msgno, NULL, NULL, &req_read_receipt, &priority, &err)) {
+                       EM_DEBUG_EXCEPTION("emcore_get_mail_extra_info failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+       }
+
+       if (rfc822_subject) {
+               EM_SAFE_FREE(input_envelope->subject);
+               input_envelope->subject = g_strdup(rfc822_subject);
+               EM_DEBUG_LOG("rfc822_subject:%s", input_envelope->subject);
+               EM_SAFE_FREE(rfc822_subject);
+       }
+
+       if (rfc822_from) {
+               if (input_envelope->from) {
+                       EM_SAFE_FREE(input_envelope->from->personal);
+                       input_envelope->from->personal = g_strdup(rfc822_from);
+                       EM_DEBUG_LOG("rfc822_from:%s", input_envelope->from->personal);
+               }
+               EM_SAFE_FREE(rfc822_from);
        }
 
        if (input_envelope->subject) {
@@ -1427,27 +1491,25 @@ int emcore_make_mail_tbl_data_from_envelope(MAILSTREAM *mail_stream, ENVELOPE *i
                        goto FINISH_OFF;
                }
 
-               EM_DEBUG_LOG("full_address_from[%s]", temp_mail_tbl_data->full_address_from);
+               EM_DEBUG_LOG_SEC("full_address_from[%s]", temp_mail_tbl_data->full_address_from);
        }
 
        if (input_envelope->to) {
-               EM_DEBUG_LOG("input_envelope->to");
                if (!emcore_get_utf8_address(&temp_mail_tbl_data->full_address_to, input_envelope->to, &err)) {
                        EM_DEBUG_EXCEPTION("emcore_get_utf8_address failed [%d]", err);
                        goto FINISH_OFF;
                }
 
-               EM_DEBUG_LOG("full_address_to[%s]", temp_mail_tbl_data->full_address_to);
+               EM_DEBUG_LOG_SEC("full_address_to[%s]", temp_mail_tbl_data->full_address_to);
        }
 
        if (input_envelope->cc) {
-               EM_DEBUG_LOG("input_envelope->cc");
                if (!emcore_get_utf8_address(&temp_mail_tbl_data->full_address_cc, input_envelope->cc, &err)) {
                        EM_DEBUG_EXCEPTION("emcore_get_utf8_address failed [%d]", err);
                        goto FINISH_OFF;
                }
 
-               EM_DEBUG_LOG("full_address_cc [%s]", temp_mail_tbl_data->full_address_cc);
+               EM_DEBUG_LOG_SEC("full_address_cc [%s]", temp_mail_tbl_data->full_address_cc);
        }
 
        if (input_envelope->bcc) {
@@ -1456,7 +1518,7 @@ int emcore_make_mail_tbl_data_from_envelope(MAILSTREAM *mail_stream, ENVELOPE *i
                        goto FINISH_OFF;
                }
 
-               EM_DEBUG_LOG("full_address_bcc [%s]", temp_mail_tbl_data->full_address_bcc);
+               EM_DEBUG_LOG_SEC("full_address_bcc [%s]", temp_mail_tbl_data->full_address_bcc);
        }
 
        if (input_envelope->reply_to) {
@@ -1465,7 +1527,7 @@ int emcore_make_mail_tbl_data_from_envelope(MAILSTREAM *mail_stream, ENVELOPE *i
                        goto FINISH_OFF;
                }
 
-               EM_DEBUG_LOG("full_address_reply [%s]\n", temp_mail_tbl_data->full_address_reply);
+               EM_DEBUG_LOG_SEC("full_address_reply [%s]\n", temp_mail_tbl_data->full_address_reply);
        }
 
        if (input_envelope->return_path) {
@@ -1473,7 +1535,7 @@ int emcore_make_mail_tbl_data_from_envelope(MAILSTREAM *mail_stream, ENVELOPE *i
                        EM_DEBUG_EXCEPTION("emcore_get_utf8_address failed [%d]", err);
                        goto FINISH_OFF;
                }
-               EM_DEBUG_LOG("full_address_return[%s]", temp_mail_tbl_data->full_address_return);
+               EM_DEBUG_LOG_SEC("full_address_return[%s]", temp_mail_tbl_data->full_address_return);
        }
 
        temp_mail_tbl_data->message_id            = EM_SAFE_STRDUP(input_envelope->message_id);
@@ -1516,6 +1578,7 @@ int emcore_make_mail_tbl_data_from_envelope(MAILSTREAM *mail_stream, ENVELOPE *i
        temp_mail_tbl_data->eas_data_length       = 0;
        temp_mail_tbl_data->eas_data              = NULL;
 
+       temp_mail_tbl_data->account_id            = account_id;
        emcore_fill_address_information_of_mail_tbl(temp_mail_tbl_data);
 
        *output_mail_tbl_data = temp_mail_tbl_data;
@@ -1528,6 +1591,11 @@ FINISH_OFF:
        if (ret != true)
                EM_SAFE_FREE(temp_mail_tbl_data);
 
+       if (account_ref) {
+               emcore_free_account(account_ref);
+               EM_SAFE_FREE(account_ref);
+       }
+
        if (err_code  != NULL)
                *err_code = err;
 
@@ -1536,10 +1604,17 @@ FINISH_OFF:
        return ret;
 }
 
-INTERNAL_FUNC int emcore_sync_header(emstorage_mailbox_tbl_t *input_mailbox_tbl, void *stream_recycle, emcore_uid_list **input_uid_list, int *unread_mail, int *err_code)
+INTERNAL_FUNC int emcore_sync_header (emstorage_mailbox_tbl_t *input_mailbox_tbl, void **stream, 
+                                     emcore_uid_list **input_uid_list, int *mail_count, int *unread_mail, int *err_code)
 {
        EM_PROFILE_BEGIN(emCoreSyncHeader);
        EM_DEBUG_FUNC_BEGIN("input_mailbox_tbl[%p], input_uid_list [%p], err_code[%p]", input_mailbox_tbl, input_uid_list, err_code);
+       if (!stream) {
+               EM_DEBUG_EXCEPTION ("NULL stream");
+               if (err_code)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
 
        int ret = false;
        int err = EMAIL_ERROR_NONE, err_2 = EMAIL_ERROR_NONE;
@@ -1554,8 +1629,7 @@ INTERNAL_FUNC int emcore_sync_header(emstorage_mailbox_tbl_t *input_mailbox_tbl,
        emstorage_mailbox_tbl_t *destination_mailbox = NULL;
 
        ENVELOPE *env = NULL;
-       int account_id = 0, mail_id = 0, rule_len = 1000, total = 0, unread = 0, i = 0, percentage  = 0, thread_id = -1;
-       void *stream = NULL;
+       int account_id = 0, mail_id = 0, rule_count = 1000, total = 0, unread = 0, i = 0, percentage  = 0, thread_id = -1;
        char *uid_range = NULL;
        char mailbox_id_param_string[10] = {0,};
 
@@ -1566,6 +1640,7 @@ INTERNAL_FUNC int emcore_sync_header(emstorage_mailbox_tbl_t *input_mailbox_tbl,
        }
 
        account_id = input_mailbox_tbl->account_id;
+       g_current_sync_account_id = account_id;
        account_ref = emcore_get_account_reference(account_id);
        if (!account_ref) {
                EM_DEBUG_EXCEPTION("emcore_get_account_reference failed - %d", account_id);
@@ -1587,22 +1662,17 @@ INTERNAL_FUNC int emcore_sync_header(emstorage_mailbox_tbl_t *input_mailbox_tbl,
        }
 #endif /* __FEATURE_SUPPORT_SYNC_STATE_ON_NOTI_BAR__ */
 
-#ifndef        __FEATURE_KEEP_CONNECTION__
-       /*  h.gahlaut :  Recycling of stream is taken care internally in emcore_connect_to_remote_mailbox so no need of this code here */
-       if (stream_recycle)
-               stream = stream_recycle; /*  set stream for recycling connection. */
-#endif
-
-       if (!emcore_connect_to_remote_mailbox(account_id, input_mailbox_tbl->mailbox_id, (void **)&stream, &err) || !stream){
+       if (!emcore_connect_to_remote_mailbox(account_id, input_mailbox_tbl->mailbox_id, (void **)stream, &err) || !*stream){
                EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed - %d", err);
                status = EMAIL_LIST_CONNECTION_FAIL;
+               err = EMAIL_ERROR_CONNECTION_FAILURE;
                goto FINISH_OFF;
        }
 
        FINISH_OFF_IF_CANCELED;
 
        /*  save total mail count on server to DB */
-       if (!emstorage_update_mailbox_total_count(account_id, input_mailbox_tbl->mailbox_id, ((MAILSTREAM *)stream)->nmsgs, 1, &err)){
+       if (!emstorage_update_mailbox_total_count(account_id, input_mailbox_tbl->mailbox_id, ((MAILSTREAM *)*stream)->nmsgs, 1, &err)){
                EM_DEBUG_EXCEPTION("emstorage_update_mailbox_total_count failed [%d]", err);
 
                goto FINISH_OFF;
@@ -1622,11 +1692,14 @@ INTERNAL_FUNC int emcore_sync_header(emstorage_mailbox_tbl_t *input_mailbox_tbl,
                        else if (!opt_ref->block_subject)
                                type = EMAIL_FILTER_FROM;
 
-                       if (!emstorage_get_rule(ALL_ACCOUNT, type, 0, &rule_len, &is_completed, &rule, true, &err) || !rule)
-                               EM_DEBUG_EXCEPTION("emstorage_get_rule failed - %d", err);
+                       if (!emstorage_get_rule(ALL_ACCOUNT, type, 0, &rule_count, &is_completed, &rule, true, &err) || !rule) {
+                               if ( err != EMAIL_ERROR_FILTER_NOT_FOUND )
+                                       EM_DEBUG_EXCEPTION ("emstorage_get_rule error [%d]", err);
+                       }
                }
                download_limit_count = input_mailbox_tbl->mail_slot_size;
-               if (!emcore_get_uids_to_download(stream, account_ref, input_mailbox_tbl, download_limit_count,  &uid_list, &total, EMAIL_SYNC_LATEST_MAILS_FIRST, &err)){
+               if (!emcore_get_uids_to_download(*stream, account_ref, input_mailbox_tbl, download_limit_count, &uid_list, 
+                                                                         &total, EMAIL_SYNC_LATEST_MAILS_FIRST, &err)){
                        EM_DEBUG_EXCEPTION("emcore_get_uids_to_download failed [%d]", err);
                        uid_list = NULL;
                        goto FINISH_OFF;
@@ -1645,7 +1718,7 @@ INTERNAL_FUNC int emcore_sync_header(emstorage_mailbox_tbl_t *input_mailbox_tbl,
 #ifdef  __FEATURE_HEADER_OPTIMIZATION__
                /* g.shyamakshi@samsung.com : Bulk fetch of headers only if the recieving server type is IMAP */
 
-               EM_DEBUG_LOG("((MAILSTREAM *)stream)->nmsgs [%d]", ((MAILSTREAM *)stream)->nmsgs);
+               EM_DEBUG_LOG("((MAILSTREAM *)stream)->nmsgs [%d]", ((MAILSTREAM *)*stream)->nmsgs);
                EM_DEBUG_LOG("uid_list [%p]", uid_list);
                if (account_ref->incoming_server_type == EMAIL_SERVER_TYPE_IMAP4 && uid_list  != NULL){
                        emcore_uid_list *uid_list_prev = NULL;
@@ -1710,121 +1783,131 @@ INTERNAL_FUNC int emcore_sync_header(emstorage_mailbox_tbl_t *input_mailbox_tbl,
                                }
                        }
 
-                       /* h.gahlaut :  [Start] */
-                       /* Adding this check here to check if application has called cancel job. */
-                       /* This checking should be done because fetching 50 headers will take time  */
                        FINISH_OFF_IF_CANCELED;
 
                        EM_DEBUG_LOG("index [%d]", index);
 
-                       /*  h.gahlaut :  [End] */
                        uid_elem = uid_list;
-                       if (stream && uid_elem){
+                       if (*stream && uid_elem){
                                EM_DEBUG_LOG("msgno : %d", uid_elem->msgno);
-                               ((MAILSTREAM *)stream)->nmsgs = uid_elem->msgno;
+                               ((MAILSTREAM *)*stream)->nmsgs = uid_elem->msgno;
                        }
                        else{
                                EM_DEBUG_LOG("Uid List Null");
                        }
                        EM_DEBUG_LOG("Calling ... mail_fetch_fast. uid_range [%s]", uid_range);
-                       mail_fetch_fast(stream, uid_range, FT_UID | FT_PEEK | FT_NEEDENV);
+                       mail_fetch_fast(*stream, uid_range, FT_UID | FT_PEEK | FT_NEEDENV);
                        EM_SAFE_FREE(uid_range);
                }
 #endif
 
                /*  h.gahlaut@samsung.com :  Clear the event queue of partial body download thread before starting fetching new headers  */
-#ifndef __PARTIAL_BODY_FOR_POP3__
+#ifndef __FEATURE_PARTIAL_BODY_FOR_POP3__
                if (account_ref->incoming_server_type == EMAIL_SERVER_TYPE_IMAP4){
-#endif /*  __PARTIAL_BODY_FOR_POP3__ */
+#endif /*  __FEATURE_PARTIAL_BODY_FOR_POP3__ */
                        /*  Partial body download feature is only for IMAP accounts  */
                        if (false == emcore_clear_partial_body_thd_event_que(&err))
                                EM_DEBUG_LOG("emcore_clear_partial_body_thd_event_que failed [%d]", err);
-#ifndef __PARTIAL_BODY_FOR_POP3__
+#ifndef __FEATURE_PARTIAL_BODY_FOR_POP3__
                }
-#endif /*  __PARTIAL_BODY_FOR_POP3__ */
+#endif /*  __FEATURE_PARTIAL_BODY_FOR_POP3__ */
                while (uid_elem) {
                        EM_PROFILE_BEGIN(emCoreSyncHeaderEachMail);
                        EM_DEBUG_LOG("mail_fetchstructure_full  :  uid_elem->msgno[%d]", uid_elem->msgno);
 
                        env = NULL;
 
-                       if (uid_elem->msgno > ((MAILSTREAM *)stream)->nmsgs)
-                               EM_DEBUG_EXCEPTION("Warnings! msgno[%d] can't be greater than nmsgs[%d]. It might cause crash.", uid_elem->msgno, ((MAILSTREAM *)stream)->nmsgs);
+                       if (uid_elem->msgno > ((MAILSTREAM *)*stream)->nmsgs)
+                               EM_DEBUG_LOG ("WARN: msgno[%d] can't be greater than nmsgs[%d].", uid_elem->msgno, 
+                                                                                       ((MAILSTREAM *)*stream)->nmsgs);
                        else{
 
 #ifdef __FEATURE_HEADER_OPTIMIZATION__
                                if (account_ref->incoming_server_type == EMAIL_SERVER_TYPE_IMAP4) /* Fetch env from cache in case of IMAP */
-                                       env = mail_fetchstructure_full(stream, uid_elem->msgno, NULL, FT_PEEK, 0);
+                                       env = mail_fetchstructure_full (*stream, uid_elem->msgno, NULL, FT_PEEK, 0);
                                else /* Fetch header from network in case of POP */
-                                       env = mail_fetchstructure_full(stream, uid_elem->msgno, NULL, FT_PEEK, 1);
+                                       env = mail_fetchstructure_full (*stream, uid_elem->msgno, NULL, FT_PEEK, 1);
 #else
-                               env = mail_fetchstructure_full(stream, uid_elem->msgno, NULL, FT_PEEK);
+                               env = mail_fetchstructure_full (*stream, uid_elem->msgno, NULL, FT_PEEK);
 #endif
                        }
                        FINISH_OFF_IF_CANCELED;
 
                        if (env != NULL) {
-                               int matched = -1;
+                               int searched_mail_id = 0;
+                               int blocked = false;
+                               int priority_sender = false;
 
-                               if (!emcore_make_mail_tbl_data_from_envelope(stream, env, uid_elem, &new_mail_tbl_data, &err) || !new_mail_tbl_data) {
+                               if (!emcore_make_mail_tbl_data_from_envelope (account_id, *stream, env, uid_elem, 
+                                                                     &new_mail_tbl_data, &err) || !new_mail_tbl_data) {
                                        EM_DEBUG_EXCEPTION("emcore_make_mail_tbl_data_from_envelope failed [%d]", err);
-                                       goto FINISH_OFF;
+                                       goto CONTINUE_NEXT;
                                }
 
-                               if (rule && !emcore_check_rule(new_mail_tbl_data->full_address_from, new_mail_tbl_data->subject, rule, rule_len, &matched, &err)) {
+                               /* Check message_id for duplicated mail in sentbox */
+                               if ((input_mailbox_tbl->mailbox_type == EMAIL_MAILBOX_TYPE_SENTBOX) && (emstorage_check_and_update_server_uid_by_message_id(new_mail_tbl_data->account_id, input_mailbox_tbl->mailbox_type, new_mail_tbl_data->message_id, new_mail_tbl_data->server_mail_id, &searched_mail_id) == EMAIL_ERROR_NONE)) {
+                                       EM_DEBUG_LOG("Existed the duplicated mail : message_id[%s]", new_mail_tbl_data->message_id);
+
+                                       if (!emcore_add_read_mail_uid(input_mailbox_tbl, input_mailbox_tbl->mailbox_name, searched_mail_id, new_mail_tbl_data->server_mail_id, new_mail_tbl_data->mail_size, 0, &err)) {
+                                               EM_DEBUG_EXCEPTION("emcore_add_read_mail_uid failed");
+                                       }
+
+                                       goto CONTINUE_NEXT;
+                               }
+
+                               if (rule && !emcore_check_rule(new_mail_tbl_data->full_address_from, new_mail_tbl_data->subject, rule, rule_count, &priority_sender, &blocked, &err)) {
                                        EM_DEBUG_EXCEPTION("emcore_check_rule failed [%d]", err);
-                                       goto FINISH_OFF;
                                }
 
-                               if (matched >= 0) {     /*  add filtered mails to SPAMBOX */
+                               if(destination_mailbox) /* cleanup before reusing */
+                                       emstorage_free_mailbox(&destination_mailbox, 1, NULL);
+
+                               if (priority_sender)
+                                       new_mail_tbl_data->tag_id = PRIORITY_SENDER_TAG_ID;
+
+                               if (blocked) {
                                        EM_DEBUG_LOG("mail[%d] added to spambox", mail_id);
-                                       switch (rule->action_type) {
-                                       case EMAIL_FILTER_MOVE :
-                                               if ( (err = emstorage_get_mailbox_by_id(rule->target_mailbox_id, &destination_mailbox)) != EMAIL_ERROR_NONE) {
-                                                       EM_DEBUG_LOG("emstorage_get_mailbox_by_id failed : [%d]", err);
-                                               }       
-                                               break;
-                                       case EMAIL_FILTER_BLOCK :
-                                               if (!emstorage_get_mailbox_by_mailbox_type(account_id, EMAIL_MAILBOX_TYPE_SPAMBOX, &destination_mailbox, false, &err)) {
-                                                       EM_DEBUG_LOG("emstorage_get_mailbox_by_mailbox_type failed [%d]", err);
-                                               }
-                                               break;
-                                       default:
-                                               break;
+                                       if (!emstorage_get_mailbox_by_mailbox_type(account_id, EMAIL_MAILBOX_TYPE_SPAMBOX, 
+                                                                                  &destination_mailbox, false, &err)) {
+                                               EM_DEBUG_LOG("emstorage_get_mailbox_by_mailbox_type failed [%d]", err);
                                        }
+                               }
 
-                                       if (destination_mailbox) {
-                                               if ((err = emcore_add_mail_to_mailbox(destination_mailbox, new_mail_tbl_data, &mail_id, &thread_id)) != EMAIL_ERROR_NONE) {
-                                                       EM_DEBUG_EXCEPTION("emcore_add_mail_to_mailbox falied [%d]", err);
-                                                       goto FINISH_OFF;
-                                               }
-                               
-                                               if (account_ref->incoming_server_type == EMAIL_SERVER_TYPE_IMAP4) {
-                                                       if (!emcore_move_mail_on_server(account_id, input_mailbox_tbl->mailbox_id,  &mail_id, 1, destination_mailbox->mailbox_name, &err)){
-                                                               EM_DEBUG_EXCEPTION("emcore_move_mail_on_server falied [%d]", err);
-                                                               goto FINISH_OFF;
-                                                       }
+                               if (destination_mailbox) {
+                                       if ((err = emcore_add_mail_to_mailbox(destination_mailbox, new_mail_tbl_data, &mail_id, 
+                                                                                    &thread_id)) != EMAIL_ERROR_NONE) {
+                                               EM_DEBUG_EXCEPTION("emcore_add_mail_to_mailbox falied [%d]", err);
+                                               goto CONTINUE_NEXT;
+                                       }
+                       
+                                       if (account_ref->incoming_server_type == EMAIL_SERVER_TYPE_IMAP4) {
+                                               if (!emcore_move_mail_on_server(account_id, input_mailbox_tbl->mailbox_id,  &mail_id, 
+                                                                           1, destination_mailbox->mailbox_name, &err)){
+                                                       EM_DEBUG_EXCEPTION("emcore_move_mail_on_server falied [%d]", err);
+                                                       goto CONTINUE_NEXT;
                                                }
                                        }
                                } else {
                                        /*  add mails to specified mail box */
-                                       EM_DEBUG_LOG("mail[%d] moved to input_mailbox_tbl [%s]", mail_id, input_mailbox_tbl->mailbox_name);
-                                       if ( (err = emcore_add_mail_to_mailbox(input_mailbox_tbl, new_mail_tbl_data, &mail_id, &thread_id)) != EMAIL_ERROR_NONE) {
+                                       EM_DEBUG_LOG_SEC("mail[%d] moved to input_mailbox_tbl [%s]", mail_id, input_mailbox_tbl->mailbox_name);
+                                       if ( (err = emcore_add_mail_to_mailbox (input_mailbox_tbl, new_mail_tbl_data, 
+                                                                          &mail_id, &thread_id)) != EMAIL_ERROR_NONE) {
                                                EM_DEBUG_EXCEPTION("emcore_add_mail_to_mailbox falied [%d]", err);
-                                               goto FINISH_OFF;
+                                               goto CONTINUE_NEXT;
                                        }
 
                                        /*h.gahlaut :  Start partial body dowload using partial body thread only for IMAP accounts*/
-#ifndef __PARTIAL_BODY_FOR_POP3__
+#ifndef __FEATURE_PARTIAL_BODY_FOR_POP3__
                                        if (account_ref->incoming_server_type == EMAIL_SERVER_TYPE_IMAP4) {
-#endif /*  __PARTIAL_BODY_FOR_POP3__ */
+#endif /*  __FEATURE_PARTIAL_BODY_FOR_POP3__ */
                                                if (account_ref->auto_download_size != 0) {
-                                                       if (false == emcore_initiate_pbd(stream, account_id, mail_id, uid_elem->uid, input_mailbox_tbl->mailbox_id, &err))
+                                                       if (false == emcore_initiate_pbd (*stream, account_id, mail_id, uid_elem->uid, 
+                                                                                  input_mailbox_tbl->mailbox_id, &err))
                                                                EM_DEBUG_LOG("Partial body download initiation failed [%d]", err);
                                                }
-#ifndef __PARTIAL_BODY_FOR_POP3__
+#ifndef __FEATURE_PARTIAL_BODY_FOR_POP3__
                                        }
-#endif /*  __PARTIAL_BODY_FOR_POP3__ */
+#endif /*  __FEATURE_PARTIAL_BODY_FOR_POP3__ */
 /*
                                        if (!uid_elem->flag.seen && input_mailbox_tbl->mailbox_type != EMAIL_MAILBOX_TYPE_SPAMBOX)
                                                emcore_add_notification_for_unread_mail(new_mail_tbl_data);
@@ -1835,11 +1918,13 @@ INTERNAL_FUNC int emcore_sync_header(emstorage_mailbox_tbl_t *input_mailbox_tbl,
                                                unread++;
 
                                        percentage = ((i+1) * 100) / total ;
-                                       EM_DEBUG_LOG("Header Percentage Completed [%d] : [%d/%d]  mail_id [%d]", percentage, i+1, total, mail_id);
+                                       EM_DEBUG_LOG("Header Percentage Completed [%d] : [%d/%d]  mail_id [%d]", percentage, i+1, 
+                                                                                                        total, mail_id);
                                        SNPRINTF(mailbox_id_param_string, 10, "%d", input_mailbox_tbl->mailbox_id);
 
-                                       if (!emcore_notify_storage_event(NOTI_MAIL_ADD, account_id, mail_id, mailbox_id_param_string, thread_id))
-                                               EM_DEBUG_EXCEPTION("emcore_notify_storage_event [NOTI_MAIL_ADD] failed");
+                                       if (!emcore_notify_storage_event (NOTI_MAIL_ADD, account_id, mail_id, 
+                                                                                    mailbox_id_param_string, thread_id))
+                                               EM_DEBUG_EXCEPTION ("emcore_notify_storage_event [NOTI_MAIL_ADD] failed");
                                }
 
 #ifdef __FEATURE_BLOCKING_MODE__
@@ -1848,12 +1933,13 @@ INTERNAL_FUNC int emcore_sync_header(emstorage_mailbox_tbl_t *input_mailbox_tbl,
 
                                blocking_mode = emcore_get_blocking_mode_status();
                                if (!blocking_mode) {
-                                       if ((err = emcore_check_blocking_mode(new_mail_tbl_data->email_address_sender, &blocking_mode)) != EMAIL_ERROR_NONE) {
-                                               EM_DEBUG_EXCEPTION("emcore_check_blocking_mode failed : [%d]", err);
+                                       if ((err = emcore_check_blocking_mode (new_mail_tbl_data->email_address_sender, 
+                                                                                &blocking_mode)) != EMAIL_ERROR_NONE) {
+                                               EM_DEBUG_EXCEPTION ("emcore_check_blocking_mode failed : [%d]", err);
                                        }
 
                                        if (blocking_mode)
-                                               emcore_set_blocking_mode_status(blocking_mode); 
+                                               emcore_set_blocking_mode_status (blocking_mode);        
                                }
 #endif /* __FEATURE_BLOCKING_MODE__ */
 
@@ -1877,14 +1963,15 @@ INTERNAL_FUNC int emcore_sync_header(emstorage_mailbox_tbl_t *input_mailbox_tbl,
 
                                /*  Release for envelope is not required and it may cause crash. Don't free the memory for envelope here. */
                                /*  Envelope data will be freed by garbage collector in mail_close_full */
-                               if (new_mail_tbl_data){
-                                       emstorage_free_mail(&new_mail_tbl_data, 1, NULL);
-                                       new_mail_tbl_data = NULL;
-                               }
 
                                FINISH_OFF_IF_CANCELED;
                        }
 
+CONTINUE_NEXT:
+                       if (new_mail_tbl_data){
+                               emstorage_free_mail(&new_mail_tbl_data, 1, NULL);
+                               new_mail_tbl_data = NULL;
+                       }
                        uid_elem = uid_elem->next;
                        i++;
                        EM_PROFILE_END(emCoreSyncHeaderEachMail);
@@ -1895,7 +1982,11 @@ INTERNAL_FUNC int emcore_sync_header(emstorage_mailbox_tbl_t *input_mailbox_tbl,
        ret = true;
 FINISH_OFF:
 
-       *unread_mail = unread;
+       if (mail_count != NULL)
+               *mail_count = total;
+
+       if (unread_mail != NULL)
+               *unread_mail = unread;
 
        if (account_ref) {
                emcore_free_account(account_ref);
@@ -1905,7 +1996,7 @@ FINISH_OFF:
        if (!emcore_remove_overflowed_mails(input_mailbox_tbl, &err_2))
                EM_DEBUG_EXCEPTION("emcore_remove_overflowed_mails failed - %d", err_2);
 
-       if (input_mailbox_tbl)
+       if (ret && input_mailbox_tbl)
                emstorage_stamp_last_sync_time_of_mailbox(input_mailbox_tbl->mailbox_id, 1);
 
 #ifdef __FEATURE_SUPPORT_SYNC_STATE_ON_NOTI_BAR__
@@ -1921,28 +2012,23 @@ FINISH_OFF:
                emcore_free_uids(uid_list, NULL);
                /*  uid_list point to the same memory with input_mailbox_tbl->user_data.  */
                /*  input_mailbox_tbl->user_data should be set NULL if uid_list is freed */
-               *input_uid_list = NULL;
+               if (input_uid_list && *input_uid_list)
+                       *input_uid_list = NULL;
        }
 
        EM_SAFE_FREE(uid_range);
 
-       if (rule  != NULL)
-               emstorage_free_rule(&rule, rule_len, NULL);
+       if(destination_mailbox)
+               emstorage_free_mailbox(&destination_mailbox, 1, NULL);
 
-#ifdef __FEATURE_KEEP_CONNECTION__
-       if (stream  != NULL) {
-#else /*  __FEATURE_KEEP_CONNECTION__   */
-       if (stream  != NULL && stream_recycle == NULL)  {
-#endif /*  __FEATURE_KEEP_CONNECTION__  */
-               emcore_close_mailbox(0, stream);
-               stream = NULL;
-       }
+       if (rule  != NULL)
+               emstorage_free_rule(&rule, rule_count, NULL);
 
-       if (err_code  != NULL)
+       if (err_code)
                *err_code = err;
 
        EM_PROFILE_END(emCoreSyncHeader);
-       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       EM_DEBUG_FUNC_END("ret [%d], err [%d]", ret, err);
        return ret;
 }
 
@@ -1967,7 +2053,7 @@ emcore_uid_list *__ReverseList(emcore_uid_list *uid_list)
 
 
 
-int emcore_download_uid_all(email_internal_mailbox_t *mailbox, emcore_uid_list** uid_list, int *total, emstorage_read_mail_uid_tbl_t *downloaded_uids, int count, emcore_get_uids_for_delete_t for_delete, int *err_code)
+int emcore_download_uid_all(MAILSTREAM *mail_stream, email_internal_mailbox_t *mailbox, emcore_uid_list** uid_list, int *total, emstorage_read_mail_uid_tbl_t *downloaded_uids, int count, emcore_get_uids_for_delete_t for_delete, int *err_code)
 {
        EM_DEBUG_FUNC_BEGIN("mailbox[%p], uid_list[%p], total[%p], downloaded_uids[%p], count[%d], for_delete[%d], err_code[%p]", mailbox, uid_list, total, downloaded_uids, count, for_delete, err_code);
 
@@ -1996,7 +2082,7 @@ int emcore_download_uid_all(email_internal_mailbox_t *mailbox, emcore_uid_list**
                goto FINISH_OFF;
        }
 
-       if (!mailbox->mail_stream) {
+       if (!mail_stream) {
                if (!emcore_connect_to_remote_mailbox(mailbox->account_id, mailbox->mailbox_id, (void **)&tmp_stream, &err)){
                        EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed...");
 
@@ -2006,7 +2092,7 @@ int emcore_download_uid_all(email_internal_mailbox_t *mailbox, emcore_uid_list**
                stream = (MAILSTREAM *)tmp_stream;
        }
        else
-               stream = mailbox->mail_stream;
+               stream = mail_stream;
 
        if (ref_account->incoming_server_type == EMAIL_SERVER_TYPE_POP3) {              /*  POP3 */
                POP3LOCAL *pop3local = NULL;
@@ -2051,7 +2137,7 @@ int emcore_download_uid_all(email_internal_mailbox_t *mailbox, emcore_uid_list**
 
                        /*  replied success "+OK" */
                        if (*p == '+') {
-                               free(p); p = NULL;
+                               EM_SAFE_FREE (p);
                                continue;
                        }
 
@@ -2085,8 +2171,7 @@ int emcore_download_uid_all(email_internal_mailbox_t *mailbox, emcore_uid_list**
                        if (downloaded_uids) {
                                int i;
                                for (i = 0; i < count; ++i) {
-                                       if (!strcmp(uid_elem->uid, downloaded_uids[i].s_uid)) {
-                                               downloaded_uids[i].flag = 1;
+                                       if (!strcmp(uid_elem->uid, downloaded_uids[i].server_uid)) {
                                                break;
                                        }
                                }
@@ -2106,7 +2191,7 @@ int emcore_download_uid_all(email_internal_mailbox_t *mailbox, emcore_uid_list**
                        if (total)
                                ++(*total);
 
-                       free(p); p = NULL;
+                       EM_SAFE_FREE (p);
                }
        }
        else {          /*  IMAP */
@@ -2150,13 +2235,13 @@ int emcore_download_uid_all(email_internal_mailbox_t *mailbox, emcore_uid_list**
                        /*  check that reply is reply to our command */
                        /*  format  :  "* 9 FETCH (UID 68)" */
                        if (!strstr(p, "FETCH (FLAGS")) {
-                               free(p); p = NULL;
+                               EM_SAFE_FREE (p);
                                continue;
                        }
 
                        if (for_delete == EM_CORE_GET_UIDS_FOR_NO_DELETE) {
                                if ((ref_account->retrieval_mode == EMAIL_IMAP4_RETRIEVAL_MODE_NEW) && (strstr(p, "\\Seen"))) {
-                                       free(p); p = NULL;
+                                       EM_SAFE_FREE (p);
                                        continue;
                                }
                        }
@@ -2214,10 +2299,9 @@ int emcore_download_uid_all(email_internal_mailbox_t *mailbox, emcore_uid_list**
                        if (downloaded_uids) {
                                int i;
                                for (i = 0; i < count; ++i) {
-                                       if (uid_elem->uid && !strcmp(uid_elem->uid, downloaded_uids[i].s_uid)) {
-                                               downloaded_uids[i].flag = 1;
-                                               free(uid_elem->uid);
-                                               free(uid_elem); uid_elem = NULL;
+                                       if (uid_elem->uid && !strcmp(uid_elem->uid, downloaded_uids[i].server_uid)) {
+                                               EM_SAFE_FREE (uid_elem->uid);
+                                               EM_SAFE_FREE (uid_elem);
                                                break;
                                        }
                                }
@@ -2240,7 +2324,7 @@ int emcore_download_uid_all(email_internal_mailbox_t *mailbox, emcore_uid_list**
                                        ++(*total);
                        }
 
-                       free(p); p = NULL;
+                       EM_SAFE_FREE (p);
                }
        }
 
@@ -2248,14 +2332,12 @@ int emcore_download_uid_all(email_internal_mailbox_t *mailbox, emcore_uid_list**
 
 FINISH_OFF:
        if (uid_elem && ret == false)
-               free(uid_elem);
+               EM_SAFE_FREE (uid_elem);
 
-       if (p)
-               free(p);
+       EM_SAFE_FREE (p);
 
-       if (mailbox && !mailbox->mail_stream) {
-               emcore_close_mailbox(0, stream);
-               stream = NULL;
+       if (!mail_stream && stream) {
+               stream = mail_close (stream);
        }
 
        if (ref_account) {
@@ -2345,14 +2427,14 @@ int emcore_download_imap_msgno(email_internal_mailbox_t *mailbox, char *uid, int
                /*  check that reply is reply to our command */
                /*  format :  "* SEARCH 68", if not found, "* SEARCH" */
                if (!strstr(p, "SEARCH ") || (p[9] < '0' || p[9] > '9')) {
-                       free(p); p = NULL;
+                       EM_SAFE_FREE (p);
                        continue;
                }
 
                if (msgno)
                        *msgno = atoi(p+9);
 
-               free(p); p = NULL;
+               EM_SAFE_FREE (p);
 
                ret = true;
        }
@@ -2361,13 +2443,11 @@ int emcore_download_imap_msgno(email_internal_mailbox_t *mailbox, char *uid, int
                err = EMAIL_ERROR_MAIL_NOT_FOUND;
 
 FINISH_OFF:
-       if (p)
-               free(p);
+       EM_SAFE_FREE (p);
+
+       if (mailbox && !mailbox->mail_stream)
+               stream = mail_close (stream);
 
-       if (mailbox && !mailbox->mail_stream){
-               emcore_close_mailbox(0, stream);
-               stream = NULL;
-       }
 
        if (ref_account) {
                emcore_free_account(ref_account);
@@ -2476,9 +2556,8 @@ int emcore_free_uids(emcore_uid_list *uid_list, int *err_code)
        while (uid_list) {
                p = uid_list;
                uid_list = uid_list->next;
-               EM_SAFE_FREE(p->uid);
-               free(p);
-               p = NULL;
+               EM_SAFE_FREE (p->uid);
+               EM_SAFE_FREE (p);
        }
 
        ret = true;
@@ -2491,6 +2570,86 @@ FINISH_OFF:
        return ret;
 }
 
+INTERNAL_FUNC char *emcore_guess_charset(char *source_string)
+{
+       EM_DEBUG_FUNC_BEGIN("source - %s", source_string);
+
+       UErrorCode err = U_ZERO_ERROR;
+       UCharsetDetector* detector = NULL;
+       const UCharsetMatch** match = NULL;
+       int count = 0;
+       int i = 0;
+       int confidence = 0;
+       int most_confidence = 0;
+       const char *detected_charset = NULL;
+       char *uscdet_result_charset = NULL;
+
+       char *ret = NULL;
+       email_account_t *account_ref = NULL;
+       SIZEDTEXT source_text;
+       CHARSET *result_charset = NULL;
+       source_text.data = (unsigned char*)source_string;
+       source_text.size = EM_SAFE_STRLEN(source_string);
+       result_charset   = (CHARSET*)utf8_infercharset(&source_text);
+
+       if(result_charset) {
+               EM_DEBUG_LOG_SEC("return_charset->name [%s]", result_charset->name);
+               return EM_SAFE_STRDUP(result_charset->name);
+       }
+
+       detector = ucsdet_open(&err);
+       if(U_FAILURE(err))
+               EM_DEBUG_LOG("ucsdet_open failed");
+
+       ucsdet_setText(detector, source_string, EM_SAFE_STRLEN(source_string), &err);
+       if(U_FAILURE(err))
+               EM_DEBUG_LOG("ucsdet_setText failed");
+
+       match = ucsdet_detectAll(detector, &count, &err);
+       if(U_FAILURE(err))
+               EM_DEBUG_LOG("ucsdet_detectAll failed");
+
+       for (i = 0 ; i < count ; i++) {
+               confidence = ucsdet_getConfidence(match[i], &err);
+               if(U_FAILURE(err))
+                       EM_DEBUG_LOG("ucsdet_getConfidence failed");
+
+               if(U_FAILURE(err))
+                       EM_DEBUG_LOG("ucsdet_getName failed");
+
+               if (most_confidence < confidence) {
+                       most_confidence = confidence;
+                       detected_charset = ucsdet_getName(match[i], &err);
+               }
+               EM_DEBUG_LOG_DEV("UCSDET DETECTED CHARSET:%s, %d", ucsdet_getName(match[i], &err), confidence);
+       }
+
+       if (detected_charset)
+               uscdet_result_charset = EM_SAFE_STRDUP(detected_charset);
+
+       ucsdet_close(detector);
+
+       if (uscdet_result_charset)
+               return uscdet_result_charset;
+
+       account_ref = emcore_get_account_reference(g_current_sync_account_id);
+       if (!account_ref) {
+               EM_DEBUG_EXCEPTION("emcore_get_account_reference failed - %d",
+                               g_current_sync_account_id);
+               return NULL;
+       }
+
+       if (g_str_has_suffix(account_ref->user_email_address, ".ru")) {
+               ret = EM_SAFE_STRDUP("windows-1251");
+       }
+
+       if (account_ref) {
+               emcore_free_account(account_ref);
+               EM_SAFE_FREE(account_ref);
+       }
+
+       return ret;
+}
 
 #ifdef __FEATURE_SYNC_CLIENT_TO_SERVER__
 /* callback for GET_APPENDUID - shasikala.p */
@@ -2509,22 +2668,22 @@ INTERNAL_FUNC int emcore_sync_mail_from_client_to_server(int mail_id)
 {
        EM_DEBUG_FUNC_BEGIN("mail_id [%d]", mail_id);
 
-       int                             err                  = EMAIL_ERROR_NONE;
-       int                             len                  = 0;
-       int                             read_size            = 0;
-       int                             attachment_tbl_count = 0;
-       char                           *fname                = NULL;
-       char                           *long_enc_path        = NULL;
-       char                           *data                 = NULL;
-       char                            set_flags[100]       = { 0, };
-       ENVELOPE                       *envelope             = NULL;
-       FILE                           *fp                   = NULL;
-       STRING                          str;
-       MAILSTREAM                     *stream               = NULL;
-       email_account_t                *account_ref          = NULL;
-       emstorage_mail_tbl_t           *mail_table_data      = NULL;
-       emstorage_attachment_tbl_t     *attachment_tbl_data  = NULL;
-       emstorage_mailbox_tbl_t        *mailbox_tbl          = NULL;
+       int                         err                  = EMAIL_ERROR_NONE;
+       int                         len                  = 0;
+       int                         read_size            = 0;
+       int                         attachment_tbl_count = 0;
+       char                       *fname                = NULL;
+       char                       *long_enc_path        = NULL;
+       char                       *data                 = NULL;
+       char                        set_flags[100]       = {0,};
+       ENVELOPE                   *envelope             = NULL;
+       FILE                       *fp                   = NULL;
+       STRING                     str;
+       MAILSTREAM                 *stream               = NULL;
+       email_account_t            *account_ref          = NULL;
+       emstorage_mail_tbl_t       *mail_table_data      = NULL;
+       emstorage_attachment_tbl_t *attachment_tbl_data  = NULL;
+       emstorage_mailbox_tbl_t    *mailbox_tbl          = NULL;
 
        /*  get a mail from mail table */
        if (!emstorage_get_mail_by_id(mail_id, &mail_table_data, true, &err)) {
@@ -2552,7 +2711,7 @@ INTERNAL_FUNC int emcore_sync_mail_from_client_to_server(int mail_id)
        }
 
        if (mailbox_tbl->local_yn) {
-               EM_DEBUG_EXCEPTION("The mailbox [%s] is not on server.", mailbox_tbl->mailbox_name);
+               EM_DEBUG_EXCEPTION_SEC("The mailbox [%s] is not on server.", mailbox_tbl->mailbox_name);
                err = EMAIL_ERROR_INVALID_MAILBOX;
                goto FINISH_OFF;
        }
@@ -2596,11 +2755,10 @@ INTERNAL_FUNC int emcore_sync_mail_from_client_to_server(int mail_id)
        }
 
        if (fname)
-               EM_DEBUG_LOG("Composed file name [%s] and file size [%d]", fname, len);
+               EM_DEBUG_LOG_SEC("Composed file name [%s] and file size [%d]", fname, len);
 
        rewind(fp);
 
-       stream = NULL;
        if (!emcore_connect_to_remote_mailbox(mail_table_data->account_id, 0, (void **)&stream, &err)){
            EM_DEBUG_EXCEPTION("emcore_move_mail_on_server failed :  Mailbox open[%d]", err);
            goto FINISH_OFF;
@@ -2643,6 +2801,12 @@ INTERNAL_FUNC int emcore_sync_mail_from_client_to_server(int mail_id)
                goto FINISH_OFF;
        }
 
+       /* Update mail_data tbl */
+       if (!emstorage_update_server_uid(mail_table_data->server_mail_id, g_append_uid_rsp, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_update_server_uid failed : [%d]", err);
+               emstorage_rollback_transaction(NULL, NULL, NULL);
+               goto FINISH_OFF;
+       }
 
 FINISH_OFF:
 
@@ -2691,10 +2855,8 @@ FINISH_OFF:
                EM_SAFE_FREE(fname);
        }
 
-       if (stream){
-               emcore_close_mailbox(0, stream);
-               stream = NULL;
-       }
+       if (stream)
+               stream = mail_close (stream);
 
        EM_DEBUG_FUNC_END("err [%d]", err);
        return err;
@@ -2798,8 +2960,9 @@ static int emcore_parse_bodystructure(void *stream, IMAPPARSEDREPLY *reply_from_
 
        int err = EMAIL_ERROR_NONE;
 
-       if (!stream || !reply_from_server || !bodystructure) {
-               EM_DEBUG_EXCEPTION("Invalid paramter");
+       if (!stream || !reply_from_server || !bodystructure || !cnt_info || !body || !total_mail_size) {
+               EM_DEBUG_EXCEPTION("Invalid paramter stream[%p] reply_from_server[%p] bodystructure[%p] cnt_info[%p] body[%p] total_mail_size[%p]", 
+                                       stream, reply_from_server, bodystructure, cnt_info, body, total_mail_size);
                err = EMAIL_ERROR_INVALID_PARAM;
                return err;
        }
@@ -2813,13 +2976,16 @@ static int emcore_parse_bodystructure(void *stream, IMAPPARSEDREPLY *reply_from_
        /* Get the body strcuture string */
        bodystructure_start = strstr(bodystructure, "BODYSTRUCTURE (");
        if (!bodystructure_start) {
-               EM_DEBUG_EXCEPTION("Invalid bodystructure");
+               EM_DEBUG_EXCEPTION("Invalid bodystructure :[%s]", bodystructure);
                err = EMAIL_ERROR_INVALID_PARAM;
                goto FINISH_OFF;
        }
 
        bodystructure_start = bodystructure_start + strlen("BODYSTRUCTURE");
        bodystructure_string = strdup(bodystructure_start);
+       char* ptr = bodystructure_string;
+
+       EM_DEBUG_LOG_DEV("BODYSTRUCTURE:%s", bodystructure_string);
 
        /* Parse the bodystructure string */
        p_body = mail_newbody();
@@ -2829,10 +2995,14 @@ static int emcore_parse_bodystructure(void *stream, IMAPPARSEDREPLY *reply_from_
                goto FINISH_OFF;
        }
 
+       /* valgrind : free body->sparep */
+       mail_parameters(stream, SET_FREEBODYSPAREP, emcore_free_body_sparep);
+
+       /*imap_parse_body_structure changes param pointer*/
        imap_parse_body_structure(stream, p_body, (unsigned char **)&bodystructure_string, reply_from_server);
 
        /* Get the total mail size */
-       if (emcore_set_fetch_body_section(p_body, false, &p_total_mail_size, &err) < 0) {
+       if (emcore_set_fetch_body_section(p_body, true, &p_total_mail_size, NULL, &err) < 0) {
                EM_DEBUG_EXCEPTION("emcore_set_fetch_body_section failed:[%d]", err);
                goto FINISH_OFF;
        }
@@ -2852,24 +3022,19 @@ static int emcore_parse_bodystructure(void *stream, IMAPPARSEDREPLY *reply_from_
 
 FINISH_OFF:
 
-//     EM_SAFE_FREE(bodystructure_string);
+       EM_SAFE_FREE(ptr);
 
        if (err != EMAIL_ERROR_NONE) {
-               if (p_cnt_info)
+               if (p_cnt_info) {
                        emcore_free_content_info(p_cnt_info);
-
-               if (body)
+                       EM_SAFE_FREE(p_cnt_info);
+               }
+               if (p_body)
                        mail_free_body(&p_body);
        } else {
-               if (cnt_info)
-                       *cnt_info = p_cnt_info;
-
-               if (body)
-                       *body = p_body;
-
-               if (total_mail_size)
-                       *total_mail_size = p_total_mail_size;
-
+               *cnt_info = p_cnt_info;
+               *body = p_body;
+               *total_mail_size = p_total_mail_size;
        }
 
        EM_DEBUG_FUNC_END("Err:[%d]", err);
@@ -2950,7 +3115,7 @@ FINISH_OFF:
 
 static int emcore_parse_html_part_for_partial_body(char *start_header, char *boundary_string, char *bufsendforparse, char *text_html, int body_size)
 {
-       EM_DEBUG_FUNC_BEGIN("start_header [%s], boundary_string [%s], bufsendforparse [%s], text_html [%s], body_size [%d]", start_header, boundary_string, bufsendforparse, text_html, body_size);
+       EM_DEBUG_FUNC_BEGIN("start_header [%p], boundary_string [%s], bufsendforparse [%s], text_html [%s], body_size [%d]", start_header, boundary_string, bufsendforparse, text_html, body_size);
 
        int   err = EMAIL_ERROR_NONE;
        int   html_uidno = 0;
@@ -2994,7 +3159,7 @@ static int emcore_parse_html_part_for_partial_body(char *start_header, char *bou
        if (txt_html != NULL){
                txt_html += 4; /*  txt_html points at html content */
                start = txt_html;
-               char multipart_boundary[100] = {0};
+               char multipart_boundary[1600] = {0};
                char *multipart_related_boundry = NULL;
                char *multipart_related_boundry_end = NULL;
                if (iEncodingHeader == 1)
@@ -3008,7 +3173,9 @@ static int emcore_parse_html_part_for_partial_body(char *start_header, char *bou
                while (bufsendforparse < multipart_related_boundry && *multipart_related_boundry != LF && *multipart_related_boundry != NULL_CHAR)
                        multipart_related_boundry -= 1;
 
-               multipart_related_boundry  += 1;
+               if ((multipart_related_boundry_end - multipart_related_boundry) > 1600)
+                       return false;
+
                memcpy(multipart_boundary, multipart_related_boundry, multipart_related_boundry_end - multipart_related_boundry);
 
                if (strcmp(multipart_boundary, boundary_string) == 0)
@@ -3054,7 +3221,7 @@ static int emcore_parse_html_part_for_partial_body(char *start_header, char *bou
                        if (emcore_decode_body_text(text_html, end - txt_html, enc_type , &dec_len, &err) < 0)
                                EM_DEBUG_EXCEPTION("emcore_decode_body_text failed [%d]", err);
                }
-       else if ((temp_enc1 = (char *)strcasestr(start_header, "Content-transfer-encoding:")) && (temp_enc1 < end)){ /*prevent 27448*/
+               else if ((temp_enc1 = (char *)strcasestr(start_header, "Content-transfer-encoding:")) && (temp_enc1 < end)){ /*prevent 27448*/
                        if (temp_enc1)
                                start_header = temp_enc1;
 
@@ -3239,6 +3406,7 @@ static void emcore_free_email_image_data(email_image_data **image_data, int coun
        int i = 0;
 
        for (i = 0; i < count; i++) {
+               EM_SAFE_FREE(p[i].image_file_name);
                EM_SAFE_FREE(p[i].text_image);
                EM_SAFE_FREE(p[i].content_id);
                EM_SAFE_FREE(p[i].mime_type);
@@ -3282,14 +3450,8 @@ static int emcore_parse_image_part_for_partial_body(char *header_start_string, c
 
        EM_DEBUG_LOG("Content-type: image");
 
-       while ((image_boundary > bufsendforparse) && (*image_boundary != LF)) {
+       while (bufsendforparse < image_boundary && image_boundary && *image_boundary != LF)
                image_boundary--;
-       }
-
-       if (image_boundary <= bufsendforparse) {
-               EM_DEBUG_CRITICAL_EXCEPTION("== bufsendforparse ==");
-               EM_DEBUG_CRITICAL_EXCEPTION("%s", bufsendforparse);
-       }
 
        image_boundary++;
 
@@ -3300,7 +3462,7 @@ static int emcore_parse_image_part_for_partial_body(char *header_start_string, c
                return false;
        }
 
-       if (image_boundary != NULL && image_boundary_end != NULL)
+       if (image_boundary  != NULL && image_boundary_end != NULL)
                memcpy(temp_image_boundary, image_boundary, image_boundary_end-image_boundary);
 
        if ((char *)strcasestr((const char *)temp_image_boundary, "Content-type:") == NULL)
@@ -3317,9 +3479,10 @@ static int emcore_parse_image_part_for_partial_body(char *header_start_string, c
                }
 
                emcore_get_content_type_from_mime_string(start_header, &(image_data[i].mime_type));
+               EM_DEBUG_LOG("image_data[i].mime_type : [%s]", image_data[i].mime_type);
 
                if ((strcasestr(p, "Content-Disposition: attachment")) || (!strcasestr(p, "Content-ID: <"))){
-                       EM_DEBUG_EXCEPTION(" Body has attachment no need to parse ");
+                       EM_DEBUG_LOG("Body has attachment no need to parse ");
                        end = NULL;
                        multiple_image = NULL;
                }
@@ -3330,8 +3493,8 @@ static int emcore_parse_image_part_for_partial_body(char *header_start_string, c
                        char *cid = NULL;
                        char *temp_name = NULL;
                        char *decoded_filename = NULL;
-
-                       memset(image_data[i].image_file_name, 0, 100);
+                       
+                       image_data[i].image_file_name = NULL;
 
                        if(!start_header) { /*prevent 27449*/
                                EM_DEBUG_EXCEPTION("start_header NULL");
@@ -3345,31 +3508,42 @@ static int emcore_parse_image_part_for_partial_body(char *header_start_string, c
                        temp_name = strstr(txt_image, "name=");
                        if (temp_name  != NULL){
                                temp_image = temp_name;
-                               if (*(temp_image+5) == '"')
-                                       temp_image = temp_image+5;
+                               if (*(temp_image + 5) == '"') {
+                                       temp_image = temp_image + 5;
+                                       temp_name = temp_name + 6 ;
+                               } else {
+                                       temp_image = temp_image + 5;
+                                       temp_name = temp_name + 5;
+                               }
 
                                while (*temp_image  != CR){
                                        temp_image++;
-                                       memcpy(image_data[i].image_file_name+ch_image, temp_image, 1);
                                        ch_image++;
                                }
-
-                               if ((*(temp_name+4) == '=') && (*(temp_name+5) == '\"'))
-                                       image_data[i].image_file_name[ch_image-2] = '\0';
-
-                               if ((*(temp_name+4) == '=') && (*(temp_name+5) != '\"'))
-                                       image_data[i].image_file_name[ch_image-1] = '\0';
+                               
+                               if (ch_image > 0) {
+                                       image_data[i].image_file_name = em_malloc(ch_image);
+                                       if (image_data[i].image_file_name == NULL) {
+                                               EM_DEBUG_EXCEPTION("em_malloc failed");
+                                               return false;
+                                       }
+                                       if (*(temp_image - 1) == '"') {
+                                               memcpy(image_data[i].image_file_name, temp_name, ch_image - 2);
+                                       } else {
+                                               memcpy(image_data[i].image_file_name, temp_name, ch_image - 1);
+                                       }
+                               }                               
 
                                decoded_filename = emcore_decode_rfc2047_text(image_data[i].image_file_name, &err);
                                if(decoded_filename) {
-                                       memset(image_data[i].image_file_name, 0, 100);
+                                       memset(image_data[i].image_file_name, 0, ch_image);
                                        memcpy(image_data[i].image_file_name, decoded_filename, EM_SAFE_STRLEN(decoded_filename));
                                        EM_SAFE_FREE(decoded_filename);
                                }
                        }
 
                        if (((temp_cid1 = (char *)strcasestr((const char *)start_header, "Content-ID: <")) != NULL)){
-                               if (temp_cid1){
+                               if (temp_cid1) {
                                        cid = temp_cid1;
                                        temp_image = temp_cid1;
                                }
@@ -3385,8 +3559,14 @@ static int emcore_parse_image_part_for_partial_body(char *header_start_string, c
                                else
                                        EM_DEBUG_EXCEPTION("em_malloc() failed");
 
-                               if (image_data[i].image_file_name[0] == '\0')
+                               if (image_data[i].image_file_name == NULL) {
+                                       image_data[i].image_file_name = em_malloc((cid_end - cid) + 1);
+                                       if (image_data[i].image_file_name == NULL) {
+                                               EM_DEBUG_EXCEPTION("em_malloc failed");
+                                               return false;
+                                       }
                                        memcpy(image_data[i].image_file_name, cid, cid_end - cid);
+                               }
                        }
 
                        txt_image = strstr(txt_image, CRLF_STRING CRLF_STRING);
@@ -3403,8 +3583,10 @@ static int emcore_parse_image_part_for_partial_body(char *header_start_string, c
                                        end = txt_image + body_size - (txt_image-bufsendforparse);
                                }
                                else{
+                                       EM_DEBUG_LOG("This image is fully downloaded");
                                        boundarylen = EM_SAFE_STRLEN(p_boundary_string);
                                        end -= 2;
+                                       image_data[i].fully_downloaded = 1;
                                }
 
                                if ((temp_enc1 = (char *)strcasestr((const char *)start_header, "Content-transfer-encoding:"))  != NULL){ /*prevent 27449*/
@@ -3483,11 +3665,11 @@ static int emcore_find_boundary_string_of_the_part(const char *whole_string, con
 
                do{
                        boundary_cur--;
-               } while (whole_string < boundary_cur && *boundary_cur != LF && *boundary_cur != NULL_CHAR);
+               } while (whole_string <= boundary_cur && *boundary_cur != LF && *boundary_cur != NULL_CHAR);
 
                boundary_cur++;
 
-               if(boundary_end > boundary_cur && boundary_cur > whole_string) {
+               if(boundary_end > boundary_cur && boundary_cur >= whole_string) {
                        EM_DEBUG_LOG("boundary_end - boundary_cur + 15 [%d]", boundary_end - boundary_cur + 15);
                        boundary_string = em_malloc(boundary_end - boundary_cur + 15);
                        if(!boundary_string) {
@@ -3596,9 +3778,15 @@ static int emcore_parse_body_for_imap(char *body_str, int body_size, struct _m_c
                                } else {
                                        EM_DEBUG_LOG(" Content-type: multipart/alternative ");
                                        boundary_start = strstr(temp_alternative_plain_header, "--");
-                                       if(!boundary_start) goto FINISH_OFF; /*prevent 37946 */
+                                       if(!boundary_start) { /*prevent 37946 */
+                                               err = EMAIL_ERROR_INVALID_DATA; 
+                                               goto FINISH_OFF; 
+                                       }
                                        boundary_end = strcasestr(boundary_start, "Content-type:");
-                                       if(!boundary_end) goto FINISH_OFF; /*prevent 37946 */
+                                       if(!boundary_end) { /*prevent 37946 */
+                                               err = EMAIL_ERROR_INVALID_DATA;
+                                               goto FINISH_OFF;
+                                       }
 
                                        boundary_string = em_malloc(boundary_end - (boundary_start + strlen("--")));
                                        if (boundary_string == NULL) {
@@ -3615,9 +3803,15 @@ static int emcore_parse_body_for_imap(char *body_str, int body_size, struct _m_c
 
                if (no_alternative_part_flag) {
                        boundary_start = strstr(p_body_str, "--");
-                       if(!boundary_start) goto FINISH_OFF; /*prevent 37946 */
+                       if(!boundary_start) { /*prevent 37946 */
+                               err = EMAIL_ERROR_INVALID_DATA; 
+                               goto FINISH_OFF; 
+                       }
                        boundary_end = strcasestr(boundary_start, "Content-type:");
-                       if(!boundary_end) goto FINISH_OFF; /*prevent 37946 */
+                       if(!boundary_end) { /*prevent 37946 */
+                               err = EMAIL_ERROR_INVALID_DATA; 
+                               goto FINISH_OFF; 
+                       }
 
                        boundary_string = em_malloc(boundary_end - (boundary_start + strlen("--")));
                        if (boundary_string == NULL) {
@@ -3630,7 +3824,12 @@ static int emcore_parse_body_for_imap(char *body_str, int body_size, struct _m_c
                }
 
                if (boundary_string && boundary_end) { /*prevent 37946 */
-                       EM_DEBUG_LOG("boundary_string : [%s]", boundary_string);
+                       /* EM_DEBUG_LOG("boundary_string : [%s]", boundary_string); */
+                       char *next_boundary_start = NULL;
+                       next_boundary_start = (char *)strcasestr(boundary_end, boundary_string);
+
+                       /*if (next_boundary_start)
+                               boundary_end = next_boundary_start;*/
 
                        if (((start_header = (char *)strcasestr(boundary_end, "Content-Type: text/html"))  != NULL) && (no_html  != 1) &&(((char *)strcasestr(boundary_end, "Content-Type: message/rfc822")) == NULL) &&
                                (((char *)strcasestr(boundary_end, "Content-Type: text/rfc822-headers")) == NULL))
@@ -3661,7 +3860,6 @@ static int emcore_parse_body_for_imap(char *body_str, int body_size, struct _m_c
                                        err = EMAIL_ERROR_OUT_OF_MEMORY;
                                        goto FINISH_OFF;
                                }
-
                                emcore_parse_image_part_for_partial_body(boundary_end, start_header, boundary_string, p_body_str, image_data, body_size);
                        }
                }
@@ -3729,7 +3927,7 @@ static int emcore_download_bulk_partial_mail_body_for_imap(MAILSTREAM *stream, i
        /* For constructing UID list which is having 10 UID or less at a time */
        for (j = 0, stSectionNo = pbd_event; (stSectionNo  != NULL && j < item_count); j++)
        {
-               EM_DEBUG_LOG("pbd_event[%d].account_id [%d], mail_id [%d], server_mail_id [%d], activity_id [%d]", \
+               EM_DEBUG_LOG_SEC("pbd_event[%d].account_id [%d], mail_id [%d], server_mail_id [%d], activity_id [%d]", \
                        j, stSectionNo[j].account_id, stSectionNo[j].mail_id, stSectionNo[j].server_mail_id, stSectionNo[j].activity_id);
 
                if (i32_index >= UID_RANGE_STRING_LENGTH){
@@ -3760,6 +3958,9 @@ static int emcore_download_bulk_partial_mail_body_for_imap(MAILSTREAM *stream, i
 
        if (!imap_response || !reply_from_server ){
                EM_DEBUG_EXCEPTION(" Invalid response from emcore_get_response_from_server");
+               for( i = 0 ; i< item_count ; i++ )
+                       emcore_delete_pbd_activity(pbd_event[i].account_id, pbd_event[i].mail_id, pbd_event[i].activity_id, &err);
+
                goto FINISH_OFF;
        }
 
@@ -3768,6 +3969,18 @@ static int emcore_download_bulk_partial_mail_body_for_imap(MAILSTREAM *stream, i
                total_attachment_size = 0;
                attachment_num = 0;
 
+               if( !(imap_response[i].header) ) continue;
+
+               if (body) {
+                       mail_free_body(&body);
+                       body = NULL;
+               }
+
+               if (cnt_info) {
+                       emcore_free_content_info(cnt_info);
+                       EM_SAFE_FREE(cnt_info);
+               }
+
                err = emcore_parse_bodystructure(stream, reply_from_server, imap_response[i].header, &body, &cnt_info, &total_mail_size);
                if (err != EMAIL_ERROR_NONE || !body) {
                        EM_DEBUG_EXCEPTION("emcore_parse_bodystructure failed : [%d]", err);
@@ -3785,7 +3998,7 @@ static int emcore_download_bulk_partial_mail_body_for_imap(MAILSTREAM *stream, i
                }
 
                /* Start to parse the body */
-               EM_DEBUG_LOG("Start partial body");
+               EM_DEBUG_LOG("Start partial body of server_mail_id %d", imap_response[i].uid_no);
 
                /* Check the body download status and body size */
                SNPRINTF(uid_string, sizeof(uid_string), "%ld", imap_response[i].uid_no);
@@ -3808,7 +4021,7 @@ static int emcore_download_bulk_partial_mail_body_for_imap(MAILSTREAM *stream, i
 
                EM_DEBUG_LOG("total_mail_size:[%d], total_attachment_size:[%d], attachment_num:[%d]", total_mail_size, total_attachment_size, attachment_num);
                mail->mail_size            = total_mail_size;
-               mail->attachment_count     = attachment_num + inline_attachment_num;
+               mail->attachment_count     = attachment_num;
                mail->inline_content_count = inline_attachment_num;
 
                if (imap_response[i].body_len == 0) {
@@ -3816,27 +4029,37 @@ static int emcore_download_bulk_partial_mail_body_for_imap(MAILSTREAM *stream, i
                        continue;
                }
 
+               /*free the plain, html, and image_data before reusing*/
+               if (image_data) 
+                       emcore_free_email_image_data(&image_data, IMAGE_DISPLAY_PARTIAL_BODY_COUNT);
+
+               EM_SAFE_FREE(text_plain);
+               EM_SAFE_FREE(text_html);
+
                if ((err = emcore_parse_body_for_imap(imap_response[i].body, imap_response[i].body_len, cnt_info, body->encoding, &text_plain, &text_html, &image_data)) != EMAIL_ERROR_NONE) {
                        EM_DEBUG_EXCEPTION("emcore_parse_body_for_imap failed");
                        goto FINISH_OFF;
                }
 
-               memset(buf, 0x00, sizeof(buf));
+               int text_plain_len = EM_SAFE_STRLEN(text_plain);
+               if (text_plain_len > 0) {
+                       memset(buf, 0x00, sizeof(buf));
 
-               if (!emstorage_create_dir(pbd_event[temp_count].account_id, mail->mail_id, 0, &err))
-                       EM_DEBUG_EXCEPTION("emstorage_create_dir failed [%d]", err);
+                       if (!emstorage_create_dir(pbd_event[temp_count].account_id, mail->mail_id, 0, &err))
+                               EM_DEBUG_EXCEPTION("emstorage_create_dir failed [%d]", err);
 
-               if (!emstorage_get_save_name(pbd_event[temp_count].account_id, mail->mail_id, 0, cnt_info->text.plain_charset ? cnt_info->text.plain_charset : "UTF-8", buf, &err))
-                       EM_DEBUG_EXCEPTION("emstorage_get_save_name failed [%d]", err);
+                       if (!emstorage_get_save_name(pbd_event[temp_count].account_id, mail->mail_id, 0, cnt_info->text.plain_charset ? cnt_info->text.plain_charset : "UTF-8", buf, &err))
+                               EM_DEBUG_EXCEPTION("emstorage_get_save_name failed [%d]", err);
 
-               if (!emstorage_create_file(text_plain, EM_SAFE_STRLEN(text_plain), buf, &err))
-                       EM_DEBUG_EXCEPTION("emstorage_create_file failed [%d]", err);
+                       if (!emstorage_create_file(text_plain, text_plain_len, buf, &err))
+                               EM_DEBUG_EXCEPTION("emstorage_create_file failed [%d]", err);
 
-               mail->file_path_plain = EM_SAFE_STRDUP(buf);
-               EM_DEBUG_LOG("mail->file_path_plain [%s]", mail->file_path_plain);
+                       mail->file_path_plain = EM_SAFE_STRDUP(buf);
+                       EM_DEBUG_LOG_SEC("mail->file_path_plain [%s]", mail->file_path_plain);
+               }
 
                if (image_data != NULL && image_data[0].text_image != NULL && image_data[0].text_image[0] != NULL_CHAR) {
-                       char *result_string_of_replcaing = NULL;
+                       char *result_string_of_replacing = NULL;
                        int store_file = 0;
                        int content_index = 0;
 
@@ -3853,43 +4076,51 @@ static int emcore_download_bulk_partial_mail_body_for_imap(MAILSTREAM *stream, i
                                /* EM_SAFE_STRNCPY(temp_data_html, text_html, text_html); */
 
                        do {
-                               if (!emstorage_create_dir(pbd_event[temp_count].account_id, mail->mail_id, 0, &err))
-                                       EM_DEBUG_EXCEPTION("emstorage_create_dir failed [%d]", err);
-
-                               if (!emstorage_get_save_name(pbd_event[temp_count].account_id, mail->mail_id, 0, image_data[store_file].image_file_name, buf, &err))
-                                       EM_DEBUG_EXCEPTION("emstorage_get_save_name failed [%d]", err);
-
-                               if (!emstorage_create_file(image_data[store_file].text_image, image_data[store_file].dec_len, buf, &err))
-                                       EM_DEBUG_EXCEPTION("emstorage_create_file failed [%d]", err);
-
-                               if (mail->body_download_status  != EMAIL_BODY_DOWNLOAD_STATUS_PARTIALLY_DOWNLOADED){
-                                       memset(&attachment_tbl, 0x00, sizeof(emstorage_attachment_tbl_t));
-                                       attachment_tbl.mail_id                          = mail->mail_id;
-                                       attachment_tbl.account_id                       = pbd_event[temp_count].account_id;
-                                       attachment_tbl.mailbox_id                       = pbd_event[temp_count].mailbox_id;
-                                       attachment_tbl.attachment_name                  = image_data[store_file].image_file_name;
-                                       attachment_tbl.attachment_size                  = image_data[store_file].dec_len;
-                                       attachment_tbl.attachment_path                  = buf;
-                                       attachment_tbl.attachment_save_status           = 1;
-                                       attachment_tbl.attachment_inline_content_status = 1; /*  set to 1 for inline image */
-                                       attachment_tbl.attachment_mime_type             = image_data[store_file].mime_type;
-                                       if (!emstorage_add_attachment (&attachment_tbl, false, false, &err))
-                                               EM_DEBUG_EXCEPTION("emstorage_add_attachment failed - %d", err);
+                               if(image_data[store_file].fully_downloaded == 1) {
+                                       if (!emstorage_create_dir(pbd_event[temp_count].account_id, mail->mail_id, 0, &err))
+                                               EM_DEBUG_EXCEPTION("emstorage_create_dir failed [%d]", err);
+
+                                       if (!emstorage_get_save_name(pbd_event[temp_count].account_id, mail->mail_id, 0, image_data[store_file].image_file_name, buf, &err))
+                                               EM_DEBUG_EXCEPTION("emstorage_get_save_name failed [%d]", err);
+
+                                       if (image_data[store_file].dec_len>0)
+                                               if (!emstorage_create_file(image_data[store_file].text_image, image_data[store_file].dec_len, buf, &err))
+                                                       EM_DEBUG_EXCEPTION("emstorage_create_file failed [%d]", err);
+
+                                       if (mail->body_download_status != EMAIL_BODY_DOWNLOAD_STATUS_PARTIALLY_DOWNLOADED){
+                                               memset(&attachment_tbl, 0x00, sizeof(emstorage_attachment_tbl_t));
+                                               attachment_tbl.mail_id                          = mail->mail_id;
+                                               attachment_tbl.account_id                       = pbd_event[temp_count].account_id;
+                                               attachment_tbl.mailbox_id                       = pbd_event[temp_count].mailbox_id;
+                                               attachment_tbl.attachment_name                  = image_data[store_file].image_file_name;
+                                               attachment_tbl.attachment_size                  = image_data[store_file].dec_len;
+                                               attachment_tbl.attachment_path                  = buf;
+                                               attachment_tbl.attachment_save_status           = 1;
+                                               attachment_tbl.attachment_inline_content_status = 1; /* set to 1 for inline image */
+                                               attachment_tbl.attachment_mime_type             = image_data[store_file].mime_type;
+                                               EM_DEBUG_LOG("mime_type : [%s]", image_data[store_file].mime_type);
+                                               if (!emstorage_add_attachment (&attachment_tbl, false, false, &err))
+                                                       EM_DEBUG_EXCEPTION("emstorage_add_attachment failed - %d", err);
+                                       }
                                }
 
                                store_file++;
-                       } while (image_data[store_file].text_image  != NULL && image_data[store_file].text_image[0]  != NULL_CHAR && (store_file < IMAGE_DISPLAY_PARTIAL_BODY_COUNT));
+                       } while (image_data[store_file].text_image != NULL && image_data[store_file].text_image[0] != NULL_CHAR && (store_file < IMAGE_DISPLAY_PARTIAL_BODY_COUNT));
 
                        while (image_data[content_index].text_image  != NULL && image_data[content_index].text_image[0]  != NULL_CHAR &&
-                                 image_data[content_index].content_id && image_data[content_index].content_id[0]  != NULL_CHAR && (content_index < IMAGE_DISPLAY_PARTIAL_BODY_COUNT)){   /*  Finding CID in HTML and replacing with image name. */
-                               result_string_of_replcaing = em_replace_string((char *)temp_data_html, (char *)image_data[content_index].content_id, (char *)image_data[content_index].image_file_name);
-
-                               EM_SAFE_STRNCPY(temp_data_html, result_string_of_replcaing, EM_SAFE_STRLEN(result_string_of_replcaing));
-                               EM_SAFE_FREE(result_string_of_replcaing);
-
-                               if (strstr(temp_data_html, image_data[content_index].content_id)  != NULL)
-                                       continue; /*  Replace content id on HTML with same file name one more time. */
+                                 image_data[content_index].content_id && image_data[content_index].content_id[0]  != NULL_CHAR && (content_index < IMAGE_DISPLAY_PARTIAL_BODY_COUNT)){
+                               /*  Finding CID in HTML and replacing with image name. */
+                               if(image_data[content_index].fully_downloaded == 1) {
+                                       result_string_of_replacing = em_replace_string((char *)temp_data_html, (char *)image_data[content_index].content_id, (char *)image_data[content_index].image_file_name);
+                                       if (result_string_of_replacing) {
+                                               memset(temp_data_html, 0x00, imap_response[i].body_len + 1);
+                                               strncpy(temp_data_html, result_string_of_replacing, strlen(result_string_of_replacing));
+                                               EM_SAFE_FREE (result_string_of_replacing);
+                                       }
 
+                                       if (strstr(temp_data_html, image_data[content_index].content_id)  != NULL)
+                                               continue; /*  Replace content id on HTML with same file name one more time. */
+                               }
                                content_index++;
                        }
 
@@ -3921,21 +4152,18 @@ static int emcore_download_bulk_partial_mail_body_for_imap(MAILSTREAM *stream, i
                        if (!emstorage_get_save_name(pbd_event[temp_count].account_id, mail->mail_id, 0, html_body, buf, &err))
                                EM_DEBUG_EXCEPTION("emstorage_get_save_name failed [%d]", err);
 
-                       if (!emstorage_create_file(text_html, EM_SAFE_STRLEN(text_html), buf, &err))
-                               EM_DEBUG_EXCEPTION("emstorage_create_file failed [%d]", err);
+                       int text_html_len = EM_SAFE_STRLEN(text_html);
+                       if (text_html_len>0)
+                               if (!emstorage_create_file(text_html, EM_SAFE_STRLEN(text_html), buf, &err))
+                                       EM_DEBUG_EXCEPTION("emstorage_create_file failed [%d]", err);
 
                        mail->file_path_html = EM_SAFE_STRDUP(buf);
 
-                       /* free the plain, html, image data */
-                       EM_SAFE_FREE(text_plain);
-                       EM_SAFE_FREE(text_html);
-                       if (image_data)
-                               emcore_free_email_image_data(&image_data, IMAGE_DISPLAY_PARTIAL_BODY_COUNT);
-
                }
 
                mail->body_download_status = (total_mail_size - total_attachment_size < input_download_size) ? 1 : 2;
-               EM_DEBUG_LOG("mail->body_download_status [%d]", mail->body_download_status);
+               EM_DEBUG_LOG("total_mail_size[%d] total_attachment_size[%d] input_download_size[%d]", total_mail_size, total_attachment_size, input_download_size);
+               EM_DEBUG_LOG("mail_id [%d] body_download_status [%d]", mail->mail_id, mail->body_download_status);
 
                /* Get preview text */
                if ( (err = emcore_get_preview_text_from_file(mail->file_path_plain, mail->file_path_html, MAX_PREVIEW_TEXT_LENGTH, &(mail->preview_text))) != EMAIL_ERROR_NONE)
@@ -4004,8 +4232,10 @@ FINISH_OFF:
        if (image_data)
                emcore_free_email_image_data(&image_data, IMAGE_DISPLAY_PARTIAL_BODY_COUNT);
 
-       if (cnt_info)
+       if (cnt_info) {
                emcore_free_content_info(cnt_info);
+               EM_SAFE_FREE(cnt_info);
+       }
 
        if (body)
                mail_free_body(&body);
@@ -4033,7 +4263,7 @@ INTERNAL_FUNC int emcore_download_bulk_partial_mail_body_for_pop3(MAILSTREAM *st
        }
 
        for (i = 0; i < item_count; i++) {
-               EM_DEBUG_LOG("pbd_event[%d].account_id [%d], mail_id [%d], server_mail_id [%d], activity_id [%d]", \
+               EM_DEBUG_LOG_SEC("pbd_event[%d].account_id [%d], mail_id [%d], server_mail_id [%d], activity_id [%d]", \
                        i, pbd_event[i].account_id, pbd_event[i].mail_id, pbd_event[i].server_mail_id, pbd_event[i].activity_id);
 
                if (!emcore_download_body_multi_sections_bulk(stream, pbd_event[i].account_id, pbd_event[i].mail_id, false, false, input_download_size, 0 , &err)){
@@ -4108,7 +4338,6 @@ static void emcore_free_email_partial_buffer(email_partial_buffer **partial_buff
        EM_DEBUG_FUNC_BEGIN("count : [%d]", item_count);
 
        if (item_count <= 0 || !partial_buffer || !*partial_buffer) {
-               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
                return;
        }
 
@@ -4128,80 +4357,109 @@ static email_partial_buffer *emcore_get_response_from_server (NETSTREAM *nstream
 {
        EM_DEBUG_FUNC_BEGIN();
 
-       if (!nstream || !tag || !reply){
+       if (!nstream || !tag || !reply || item_count <= 0) {
                EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
                return NIL;
        }
 
-       email_partial_buffer *retPartialBuffer = NULL;
+       email_partial_buffer *server_response = NULL;
        IMAPPARSEDREPLY *ret_reply = NULL;
-       char *pre_content = NULL;
-       char *pline = NULL;
-       char *p_uid = NULL;
-       char *p = NULL;
+
+       char *cur_line = NULL;
+       char *full_line = NULL;
+       char *tmp = NULL;
+
        int body_size = 0;
-       int header_len = 0;
        int count = 0;
        int ret = false;
-       int header_start = false;
 
-       retPartialBuffer = (email_partial_buffer *)em_malloc(sizeof(email_partial_buffer) * item_count);
-       if (NULL == retPartialBuffer){
+       char *p_uid = NULL;
+       char *p_bodystructure = NULL;
+       char *p_bodystructure_end = NULL;
+       char *p_body_text = NULL;
+
+       server_response = (email_partial_buffer *)em_malloc(sizeof(email_partial_buffer) * item_count);
+       if (NULL == server_response) {
                EM_DEBUG_EXCEPTION("em_malloc failed");
                return NIL;
        }
 
-       while (nstream){
-               if (!(pline = net_getline(nstream))) {
+       while (nstream) {
+
+               if (!(cur_line = net_getline(nstream))) {
                        EM_DEBUG_EXCEPTION("net_getline failed...");
                        goto FINISH_OFF;
                }
 
-               /* Search the start of header */
-               if (strcasestr(pline, "BODYSTRUCTURE") != NULL) {
-                       header_len = EM_SAFE_STRLEN(pline);
-                       header_start = true;
-                       count++;
-               }
+               if (count < item_count) {
+                       tmp = full_line;
+                       if (tmp)
+                               full_line = g_strconcat(tmp, cur_line, NULL);
+                       else
+                               full_line = g_strdup(cur_line);
 
-               /* Search the end of header */
-               if ((p = strcasestr(pline, "BODY[TEXT]")) != NULL && header_len > 0) {
-                       /* Get the header content */
-                       retPartialBuffer[count - 1].header_len = (p - pline) + EM_SAFE_STRLEN(pre_content);
-                       retPartialBuffer[count - 1].header = em_malloc(retPartialBuffer[count - 1].header_len + 1);
-                       if (retPartialBuffer[count - 1].header == NULL) {
-                               EM_DEBUG_EXCEPTION("em_malloc failed");
-                               goto FINISH_OFF;
-                       }
+                       EM_SAFE_FREE(cur_line);
+                       EM_SAFE_FREE(tmp);
 
-                       if (pre_content != NULL)
-                               SNPRINTF(retPartialBuffer[count - 1].header, retPartialBuffer[count - 1].header_len, "%s%s", pre_content, pline);
-                       else
-                               SNPRINTF(retPartialBuffer[count - 1].header, retPartialBuffer[count - 1].header_len, "%s", pline);
-
-                       /* Get the body content */
-                       p += strlen("BODY[TEXT]<0> {");
-                       body_size = atoi(p);
-                       retPartialBuffer[count - 1].body_len = (body_size > input_download_size) ? input_download_size : body_size ;
-                       retPartialBuffer[count - 1].body = em_malloc(retPartialBuffer[count - 1].body_len + 1);
-                       if (retPartialBuffer[count - 1].body == NULL) {
-                               EM_DEBUG_EXCEPTION("em_malloc failed");
-                               goto FINISH_OFF;
-                       }
+                       p_bodystructure = strcasestr(full_line, "BODYSTRUCTURE");
+                       p_bodystructure_end = strcasestr(full_line, "BODY[TEXT]");
 
-                       if (net_getbuffer(nstream, retPartialBuffer[count - 1].body_len, retPartialBuffer[count - 1].body) <= 0) {
-                               EM_DEBUG_EXCEPTION("net_getbuffer failed");
-                               goto FINISH_OFF;
-                       }
+                       /* check whether full header is received */
+                       if (p_bodystructure && p_bodystructure_end) {
 
-                       header_start = false;
-               }
+                               /* get UID */
+                               if ((p_uid = strcasestr(full_line, "UID")) != NULL) {
+                                       p_uid = p_uid + strlen("UID ");
+                                       server_response[count].uid_no = atol(p_uid);
+                               }
 
-               if (header_start)
-                       pre_content = EM_SAFE_STRDUP(pline);
+                               /* get BODYSTRUCTURE */
+                               server_response[count].header_len = p_bodystructure_end - p_bodystructure;
+                               server_response[count].header = em_malloc(server_response[count].header_len + 1);
+                               if (server_response[count].header == NULL) {
+                                       EM_DEBUG_EXCEPTION("em_malloc failed");
+                                       goto FINISH_OFF;
+                               }
+                               SNPRINTF(server_response[count].header, server_response[count].header_len, "%s", p_bodystructure);
+                               /*EM_DEBUG_LOG("BODYSTRUCTURE(%d)[%s]", server_response[count].header_len, server_response[count].header);*/
 
-               if (0 == strncmp(pline, tag, EM_SAFE_STRLEN(tag))) {
+                               /* get BODY size & text */
+                               p_body_text = strcasestr(full_line, "BODY[TEXT]<0> {");
+                               if (!p_body_text) {
+                                       EM_DEBUG_EXCEPTION("can't find BODY[TEXT] size");
+                                       goto FINISH_OFF;
+                               }
 
+                               p_body_text += strlen("BODY[TEXT]<0> {");
+                               body_size = atoi(p_body_text);
+                               server_response[count].body_len = (body_size > input_download_size) ? input_download_size : body_size;
+                               server_response[count].body = em_malloc(server_response[count].body_len + 1);
+                               if (server_response[count].body == NULL) {
+                                       EM_DEBUG_EXCEPTION("em_malloc failed");
+                                       goto FINISH_OFF;
+                               }
+
+                               if (net_getbuffer(nstream, server_response[count].body_len, server_response[count].body) <= 0) {
+                                       EM_DEBUG_EXCEPTION("net_getbuffer failed");
+                                       goto FINISH_OFF;
+                               }
+                               /*EM_DEBUG_LOG("BODYSTR(%d)[%s]", server_response[count].body_len, server_response[count].body);*/
+
+                               EM_SAFE_FREE(full_line);
+                               count++;
+                               p_bodystructure = NULL;
+                               p_bodystructure_end = NULL;
+                               continue;
+                       } else {
+                               /* not a full header, accumulate into buffer util get the end of header */
+                               p_bodystructure = NULL;
+                               p_bodystructure_end = NULL;
+                               continue;
+                       }
+               }
+
+               /* get tag and result */
+               if (strncmp(cur_line, tag, EM_SAFE_STRLEN(tag)) == 0) {
                        ret_reply = em_malloc(sizeof(IMAPPARSEDREPLY));
                        if (!ret_reply){
                                EM_DEBUG_EXCEPTION("em_malloc failed");
@@ -4211,48 +4469,39 @@ static email_partial_buffer *emcore_get_response_from_server (NETSTREAM *nstream
                        if(reply)
                                *reply = ret_reply;
 
-                       if (0 == strncmp(pline + EM_SAFE_STRLEN(tag) + 1, "OK", 2)) {
+                       if (strncmp(cur_line + EM_SAFE_STRLEN(tag) + 1, "OK", 2) == 0) {
                                ret_reply->line = (unsigned char*)EM_SAFE_STRDUP(tag);
                                ret_reply->tag  = (unsigned char*)EM_SAFE_STRDUP(tag);
                                ret_reply->key  = (unsigned char*)strdup("OK");
                                ret_reply->text = (unsigned char*)strdup("Success");
-                               EM_SAFE_FREE(pline);
+                               ret = true;
                                break;
-                       }
-                       else {
-                               EM_DEBUG_EXCEPTION("Tagged Response not OK. IMAP4 Response -> [%s]", pline);
+                       } else {
+                               EM_DEBUG_EXCEPTION("Tagged Response not OK. IMAP4 Response -> [%s]", cur_line);
                                ret_reply->line = (unsigned char*)EM_SAFE_STRDUP(tag);
                                ret_reply->tag  = (unsigned char*)EM_SAFE_STRDUP(tag);
                                ret_reply->key  = (unsigned char*)strdup("NO");
                                ret_reply->text = (unsigned char*)strdup("Fail");
-
                                goto FINISH_OFF;
-
                        }
                }
 
-               if ((p_uid = strcasestr(pline, "UID")) != NULL) {
-                       p_uid = p_uid + strlen("UID ");
-
-                       retPartialBuffer[count - 1].uid_no = atol(p_uid);
-               }
-
-               EM_SAFE_FREE(pline);
+               EM_SAFE_FREE(cur_line);
        }
 
-       ret = true;
-
 FINISH_OFF:
 
-       EM_SAFE_FREE(pline);
-       EM_SAFE_FREE(pre_content);
+       EM_SAFE_FREE(tmp);
+       EM_SAFE_FREE(cur_line);
+       EM_SAFE_FREE(full_line);
 
-       if (!ret) {
-               emcore_free_email_partial_buffer(&retPartialBuffer, item_count);
+       if (!ret || count != item_count ) {
+               EM_DEBUG_EXCEPTION("emcore_get_response_from_server may be failed ret[%d] count[%d]", ret, count);
+               emcore_free_email_partial_buffer(&server_response, item_count);
        }
 
-       EM_DEBUG_FUNC_END("retPartialBuffer [%p]", retPartialBuffer);
-       return retPartialBuffer;
+       EM_DEBUG_FUNC_END("server_response [%p]", server_response);
+       return server_response;
 }
 
 #endif /*  __FEATURE_PARTIAL_BODY_DOWNLOAD__ */
index ffa078d..9525bcd 100755 (executable)
@@ -333,59 +333,73 @@ INTERNAL_FUNC int emcore_create_mailbox(email_mailbox_t *new_mailbox, int on_ser
        EM_DEBUG_FUNC_BEGIN("new_mailbox[%p], err_code[%p]", new_mailbox, err_code);
        int ret = false;
        int err = EMAIL_ERROR_NONE;
-       emstorage_mailbox_tbl_t local_mailbox;
+       emstorage_mailbox_tbl_t *local_mailbox = NULL;
+       email_account_t *account_ref = NULL;
+       char *enc_mailbox_name = NULL;
        
        if (new_mailbox == NULL || new_mailbox->mailbox_name == NULL)  {
                err = EMAIL_ERROR_INVALID_PARAM;
                goto FINISH_OFF;
        }
 
-       if  (on_server) {
+       account_ref = emcore_get_account_reference(new_mailbox->account_id);
+       if (!account_ref) {
+               EM_DEBUG_EXCEPTION("Invalid account_id [%d]", new_mailbox->account_id);
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+
+
+       /* converting UTF-8 to UTF-7 except EAS */
+       if (account_ref->incoming_server_type != EMAIL_SERVER_TYPE_ACTIVE_SYNC) {
+               if (!emcore_get_encoded_mailbox_name(new_mailbox->mailbox_name, &enc_mailbox_name, &err)) {
+                       EM_DEBUG_EXCEPTION("emcore_get_encoded_mailbox_name failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+               EM_SAFE_FREE(new_mailbox->mailbox_name);
+               new_mailbox->mailbox_name = enc_mailbox_name;
+       }
+
+       if (on_server) {
                /* Create a mailbox from Sever */
                if (!emcore_create_imap_mailbox(new_mailbox, &err)) {
-                       EM_DEBUG_EXCEPTION(">>>>> mailbox Creation in Server FAILED >>> ");
+                       EM_DEBUG_EXCEPTION("Creating a mailbox on server failed.");
                        goto FINISH_OFF;
                }
                else
-                       EM_DEBUG_LOG(">>>>> mailbox Creation in Server SUCCESS >>> ");  
-       }
-
-       memset(&local_mailbox, 0x00, sizeof(emstorage_mailbox_tbl_t));
-       EM_DEBUG_LOG("box name[%s] local yn[%d] mailbox_type[%d]", new_mailbox->mailbox_name, local_mailbox.local_yn, new_mailbox->mailbox_type);
-
-       /* add local mailbox into local mailbox table */
-       local_mailbox.mailbox_id = new_mailbox->mailbox_id;
-       local_mailbox.account_id = new_mailbox->account_id;
-       local_mailbox.local_yn = new_mailbox->local;
-       local_mailbox.mailbox_name = new_mailbox->mailbox_name;
-       local_mailbox.alias = new_mailbox->alias;
-       local_mailbox.mailbox_type = new_mailbox->mailbox_type;
-       local_mailbox.unread_count = 0;
-       local_mailbox.total_mail_count_on_local = 0;
-       local_mailbox.total_mail_count_on_server = 0;
-       emcore_get_default_mail_slot_count(local_mailbox.account_id, &local_mailbox.mail_slot_size);
-
-       if (strncmp(new_mailbox->mailbox_name, EMAIL_INBOX_NAME, EM_SAFE_STRLEN(EMAIL_INBOX_NAME))    == 0 || 
-               strncmp(new_mailbox->mailbox_name, EMAIL_DRAFTBOX_NAME, EM_SAFE_STRLEN(EMAIL_DRAFTBOX_NAME)) == 0 ||
-               strncmp(new_mailbox->mailbox_name, EMAIL_OUTBOX_NAME, EM_SAFE_STRLEN(EMAIL_OUTBOX_NAME)) == 0 || 
-               strncmp(new_mailbox->mailbox_name, EMAIL_SENTBOX_NAME, EM_SAFE_STRLEN(EMAIL_SENTBOX_NAME))  == 0)
-               local_mailbox.modifiable_yn = 0;                        /*  can be deleted/modified */
-       else
-               local_mailbox.modifiable_yn = 1;
+                       EM_DEBUG_LOG("Creating a mailbox on server succeeded.");
+       }
 
+       local_mailbox = em_malloc(sizeof(emstorage_mailbox_tbl_t)); /*prevent 60604*/
 
-       if (!emstorage_add_mailbox(&local_mailbox, true, &err))  {
+       if(local_mailbox == NULL) {
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       em_convert_mailbox_to_mailbox_tbl(new_mailbox, local_mailbox);
+
+       emcore_get_default_mail_slot_count(local_mailbox->account_id, &(local_mailbox->mail_slot_size));
+
+       if (!emstorage_add_mailbox(local_mailbox, true, &err))  {
                EM_DEBUG_EXCEPTION("emstorage_add_mailbox failed [%d]", err);
                goto FINISH_OFF;
        }
 
-       new_mailbox->mailbox_id = local_mailbox.mailbox_id;
+       new_mailbox->mailbox_id = local_mailbox->mailbox_id;
        ret = true;
-       
-FINISH_OFF: 
+
+FINISH_OFF:
+
+       if(local_mailbox)
+               emstorage_free_mailbox(&local_mailbox, 1, NULL);
+
        if (err_code)
                *err_code = err;
        
+       emcore_free_account(account_ref);
+       EM_SAFE_FREE(account_ref);
+
        return ret;
 }
 
@@ -528,13 +542,14 @@ FINISH_OFF:
        return ret;
 }
 
-INTERNAL_FUNC int emcore_rename_mailbox(int input_mailbox_id, char *input_new_mailbox_name, char *input_new_mailbox_alias, int input_on_server, int input_recursive, int handle_to_be_published)
+INTERNAL_FUNC int emcore_rename_mailbox(int input_mailbox_id, char *input_new_mailbox_name, char *input_new_mailbox_alias, void *input_eas_data, int input_eas_data_length, int input_on_server, int input_recursive, int handle_to_be_published)
 {
-       EM_DEBUG_FUNC_BEGIN("input_mailbox_id[%d] input_new_mailbox_name[%p] input_new_mailbox_alias[%p] input_on_server[%d] input_recursive[%d] handle_to_be_published[%d]", input_mailbox_id, input_new_mailbox_name, input_new_mailbox_alias, input_on_server, input_recursive, handle_to_be_published);
+       EM_DEBUG_FUNC_BEGIN("input_mailbox_id[%d] input_new_mailbox_name[%p] input_new_mailbox_alias[%p] input_eas_data[%p] input_eas_data_length[%d] input_on_server[%d] input_recursive[%d] handle_to_be_published[%d]", input_mailbox_id, input_new_mailbox_name, input_new_mailbox_alias, input_eas_data, input_eas_data_length, input_on_server, input_recursive, handle_to_be_published);
 
        int err = EMAIL_ERROR_NONE;
        int i = 0;
        int mailbox_count = 0;
+       email_account_t *account_ref = NULL;
        emstorage_mailbox_tbl_t *target_mailbox = NULL;
        emstorage_mailbox_tbl_t *target_mailbox_array = NULL;
        char *renamed_mailbox_name = NULL;
@@ -551,7 +566,14 @@ INTERNAL_FUNC int emcore_rename_mailbox(int input_mailbox_id, char *input_new_ma
                goto FINISH_OFF;
        }
 
-       EM_DEBUG_LOG("target_mailbox->mailbox_name [%s]", target_mailbox->mailbox_name);
+       account_ref = emcore_get_account_reference(target_mailbox->account_id);
+
+       if (account_ref == NULL) {
+               EM_DEBUG_EXCEPTION("emcore_get_account_reference failed.");
+               goto FINISH_OFF;
+       }
+
+       EM_DEBUG_LOG_SEC("target_mailbox->mailbox_name [%s]", target_mailbox->mailbox_name);
        old_mailbox_name = EM_SAFE_STRDUP(target_mailbox->mailbox_name);
 
        if (input_on_server) {
@@ -566,7 +588,7 @@ INTERNAL_FUNC int emcore_rename_mailbox(int input_mailbox_id, char *input_new_ma
        }
 
 #ifdef __FEATURE_RENAME_MAILBOX_RECURSIVELY__
-       if(input_recursive) {
+       if(account_ref->incoming_server_type != EMAIL_SERVER_TYPE_ACTIVE_SYNC && input_recursive) {
                /* Getting children mailbox list */
                if(!emstorage_get_child_mailbox_list(target_mailbox->account_id, target_mailbox->mailbox_name, &mailbox_count, &target_mailbox_array, false,&err)) {
                        EM_DEBUG_EXCEPTION("emstorage_get_child_mailbox_list failed. [%d]", err);
@@ -585,22 +607,22 @@ INTERNAL_FUNC int emcore_rename_mailbox(int input_mailbox_id, char *input_new_ma
                target_mailbox       = NULL;
        }
 
-       /* Remove mailboxes */
+       /* Rename mailboxes */
        for(i = 0; i < mailbox_count ; i++) {
-               EM_DEBUG_LOG("Rename mailbox_id [%d] mailbox_name [%s]", target_mailbox_array[i].mailbox_id, target_mailbox_array[i].mailbox_name);
+               EM_DEBUG_LOG_SEC("Rename mailbox_id [%d] mailbox_name [%s]", target_mailbox_array[i].mailbox_id, target_mailbox_array[i].mailbox_name);
 
                if(input_mailbox_id == target_mailbox_array[i].mailbox_id) {
-                       if ((err = emstorage_rename_mailbox(target_mailbox_array[i].mailbox_id, input_new_mailbox_name, input_new_mailbox_alias, true)) != EMAIL_ERROR_NONE) {
+                       if ((err = emstorage_rename_mailbox(target_mailbox_array[i].mailbox_id, input_new_mailbox_name, input_new_mailbox_alias, input_eas_data, input_eas_data_length, true)) != EMAIL_ERROR_NONE) {
                                EM_DEBUG_EXCEPTION("emstorage_rename_mailbox failed [%d]", err);
                                goto FINISH_OFF;
                        }
                }
                else {
-                       EM_DEBUG_LOG("target_mailbox_array[i].mailbox_name[%s] old_mailbox_name[%s] input_new_mailbox_name [%s]", target_mailbox_array[i].mailbox_name, old_mailbox_name, input_new_mailbox_name);
+                       EM_DEBUG_LOG_SEC("target_mailbox_array[i].mailbox_name[%s] old_mailbox_name[%s] input_new_mailbox_name [%s]", target_mailbox_array[i].mailbox_name, old_mailbox_name, input_new_mailbox_name);
                        renamed_mailbox_name = em_replace_string(target_mailbox_array[i].mailbox_name, old_mailbox_name, input_new_mailbox_name);
-                       EM_DEBUG_LOG("renamed_mailbox_name[%s]", renamed_mailbox_name);
+                       EM_DEBUG_LOG_SEC("renamed_mailbox_name[%s]", renamed_mailbox_name);
 
-                       if ((err = emstorage_rename_mailbox(target_mailbox_array[i].mailbox_id, renamed_mailbox_name, target_mailbox_array[i].alias, true)) != EMAIL_ERROR_NONE) {
+                       if ((err = emstorage_rename_mailbox(target_mailbox_array[i].mailbox_id, renamed_mailbox_name, target_mailbox_array[i].alias, NULL, 0, true)) != EMAIL_ERROR_NONE) {
                                EM_DEBUG_EXCEPTION("emstorage_rename_mailbox failed [%d]", err);
                                goto FINISH_OFF;
                        }
@@ -613,6 +635,11 @@ FINISH_OFF:
        EM_SAFE_FREE(renamed_mailbox_name);
        EM_SAFE_FREE(old_mailbox_name);
 
+       if (account_ref) {
+               emcore_free_account(account_ref);
+               EM_SAFE_FREE(account_ref);
+       }
+
        if (target_mailbox)
                emstorage_free_mailbox(&target_mailbox, 1, NULL);
 
@@ -622,24 +649,24 @@ FINISH_OFF:
        return err;
 }
 
-extern int try_auth;
-extern int try_auth_smtp;
-
 #ifdef __FEATURE_KEEP_CONNECTION__
 extern long smtp_send(SENDSTREAM *stream, char *command, char *args);
 #endif /* __FEATURE_KEEP_CONNECTION__ */
 
-INTERNAL_FUNC int emcore_connect_to_remote_mailbox_with_account_info(email_account_t *account, int input_mailbox_id, void **result_stream, int *err_code)
+INTERNAL_FUNC int emcore_connect_to_remote_mailbox_with_account_info (email_account_t *account, 
+                                        int input_mailbox_id, void **result_stream, /*either MAILSTREAM or SENDSTREAM*/ 
+                                        int *err_code)
 {
        EM_PROFILE_BEGIN(emCoreMailboxOpen);
-       EM_DEBUG_FUNC_BEGIN("account[%p], input_mailbox_id[%d], mail_stream[%p], err_code[%p]", account, input_mailbox_id, result_stream, err_code);
+       EM_DEBUG_FUNC_BEGIN("account[%p], input_mailbox_id[%d], mail_stream[%p], err_code[%p]", account, input_mailbox_id,
+                                                                                              result_stream, err_code);
        
        int ret = false;
        int error = EMAIL_ERROR_NONE;
        email_session_t *session = NULL;
        char *mbox_path = NULL;
-       void *reusable_stream = NULL;
        int is_connection_for = _SERVICE_THREAD_TYPE_NONE;
+       int connection_retry_count = 0;
        emstorage_mailbox_tbl_t* mailbox = NULL;
        char *mailbox_name = NULL;
 
@@ -666,41 +693,38 @@ INTERNAL_FUNC int emcore_connect_to_remote_mailbox_with_account_info(email_accou
        if(connection_info) {
                if (is_connection_for == _SERVICE_THREAD_TYPE_RECEIVING) {
                        if(connection_info->receiving_server_stream_status == EMAIL_STREAM_STATUS_CONNECTED)
-                               reusable_stream = connection_info->receiving_server_stream;
+                               *result_stream = connection_info->receiving_server_stream;
                }
                else {
                        if(connection_info->sending_server_stream_status == EMAIL_STREAM_STATUS_CONNECTED)
-                               reusable_stream = connection_info->sending_server_stream;
+                               *result_stream = connection_info->sending_server_stream;
                }
        }
        
-       if (reusable_stream != NULL)
+       if (*result_stream)
                EM_DEBUG_LOG("Stream reuse desired");
-#else
-       reusable_stream = *result_stream;
 #endif
 
        session->error = EMAIL_ERROR_NONE;
-       emcore_set_network_error(EMAIL_ERROR_NONE);             /*  set current network error as EMAIL_ERROR_NONE before network operation */
+       emcore_set_network_error (EMAIL_ERROR_NONE);    /* set current network error as EMAIL_ERROR_NONE before network operation */
        
        if (input_mailbox_id == EMAIL_CONNECT_FOR_SENDING) {
                mailbox_name = EM_SAFE_STRDUP(ENCODED_PATH_SMTP);
        }
        else if (input_mailbox_id == 0) {
                mailbox_name = NULL;
-       }else {
-               if ( (error = emstorage_get_mailbox_by_id(input_mailbox_id, &mailbox)) != EMAIL_ERROR_NONE || !mailbox) {
+       }
+       else {
+               if ((error = emstorage_get_mailbox_by_id (input_mailbox_id, &mailbox)) != EMAIL_ERROR_NONE || !mailbox) {
                        EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_id failed [%d]", error);
                        goto FINISH_OFF;
                }
-               mailbox_name = EM_SAFE_STRDUP(mailbox->mailbox_name);
+               mailbox_name = EM_SAFE_STRDUP (mailbox->mailbox_name);
        }
 
        if (is_connection_for == _SERVICE_THREAD_TYPE_RECEIVING) {      
                /*  open pop3/imap server */
-               MAILSTREAM *mail_stream = NULL;
-               
-               if (!emcore_get_long_encoded_path_with_account_info(account, mailbox_name, '/', &mbox_path, &error)) {
+               if (!emcore_get_long_encoded_path_with_account_info (account, mailbox_name, '/', &mbox_path, &error)) {
                        EM_DEBUG_EXCEPTION("emcore_get_long_encoded_path failed - %d", error);
                        session->error = error;
                        goto FINISH_OFF;
@@ -708,34 +732,45 @@ INTERNAL_FUNC int emcore_connect_to_remote_mailbox_with_account_info(email_accou
                
                EM_DEBUG_LOG("open mail connection to mbox_path [%s]", mbox_path);
                
-               try_auth = 0;           /*  ref_account->receiving_auth ? 1  :  0  */
                session->auth = 0; /*  ref_account->receiving_auth ? 1  :  0 */
-               
-               if (!(mail_stream = mail_open(reusable_stream, mbox_path, IMAP_2004_LOG))) {    
+
+               if (!(*result_stream = mail_open (*result_stream, mbox_path, IMAP_2004_LOG))) { 
                        EM_DEBUG_EXCEPTION("mail_open failed. session->error[%d], session->network[%d]", session->error, session->network);
+                       *result_stream = mail_close (*result_stream);
                        
-                       if ((session->error == EMAIL_ERROR_UNKNOWN) || (session->error == EMAIL_ERROR_NONE))
-                               session->error = EMAIL_ERROR_CONNECTION_FAILURE;
+                       if(account->account_id > 0 && (session->network == EMAIL_ERROR_XOAUTH_BAD_REQUEST || session->network == EMAIL_ERROR_XOAUTH_INVALID_UNAUTHORIZED)) {
+                               if((error = emcore_refresh_xoauth2_access_token (account->account_id)) != EMAIL_ERROR_NONE) {
+                                       EM_DEBUG_EXCEPTION("emcore_refresh_xoauth2_access_token failed. [%d]", error);
+                               }
+                               else {
+                                       while (*result_stream == NULL && connection_retry_count < 5) {
+                                               sleep(3); /* wait for updating access token */
+                                               if (!(*result_stream = mail_open (*result_stream, mbox_path, IMAP_2004_LOG))) {
+                                                       EM_DEBUG_LOG("mail_open failed. session->error[%d], session->network[%d]", session->error, session->network);
+                                               }
+                                               connection_retry_count++;
+                                               EM_DEBUG_LOG ("connection_retry_count [%d]", connection_retry_count);
+                                       }
+                               }
+                       }
                        
-                       error = session->error;
-
-#ifdef __FEATURE_KEEP_CONNECTION__
-                       /* Since mail_open failed Reset the global stream pointer as it is a dangling pointer now */
-#endif /*  __FEATURE_KEEP_CONNECTION__ */
-                       goto FINISH_OFF;
+                       if (*result_stream == NULL) { /* Finally, connection failed */
+                               if (session->error == EMAIL_ERROR_UNKNOWN || session->error == EMAIL_ERROR_NONE)
+                                       session->error = EMAIL_ERROR_CONNECTION_FAILURE;
+                               error = session->error;
+                               goto FINISH_OFF;
+                       }
                }
-               *result_stream = mail_stream;
        }
        else {  
                /*  open smtp server */
-               SENDSTREAM *send_stream = NULL;
                char *host_list[2] = {NULL, NULL};
 
 #ifdef __FEATURE_KEEP_CONNECTION__
-               if (reusable_stream != NULL) {
+               if (*result_stream) {
                        int send_ret = 0;
                        /* Check whether connection is avaiable */
-                       send_stream     = reusable_stream;
+                       send_stream = *result_stream;
                        /*
                        send_ret = smtp_send(send_stream, "RSET", 0);
                        
@@ -746,8 +781,8 @@ INTERNAL_FUNC int emcore_connect_to_remote_mailbox_with_account_info(email_accou
                        */
                }
 #endif
-               if(!send_stream) {
-                       if (!emcore_get_long_encoded_path_with_account_info(account, mailbox_name, 0, &mbox_path, &error)) {
+               if (!*result_stream) {
+                       if (!emcore_get_long_encoded_path_with_account_info (account, mailbox_name, 0, &mbox_path, &error)) {
                                EM_DEBUG_EXCEPTION(" emcore_get_long_encoded_path failed - %d", error);
                                session->error = error;
                                goto FINISH_OFF;
@@ -755,24 +790,44 @@ INTERNAL_FUNC int emcore_connect_to_remote_mailbox_with_account_info(email_accou
                                
                        EM_DEBUG_LOG("open SMTP connection to mbox_path [%s]", mbox_path);
                        
-                       try_auth_smtp = account->outgoing_server_need_authentication ? 1  :  0;
                        session->auth = account->outgoing_server_need_authentication ? 1  :  0;
                        
                        host_list[0] = mbox_path;
-                       
-                       if (!(send_stream = smtp_open(host_list, 1))) {
-                               EM_DEBUG_EXCEPTION("smtp_open failed... : current outgoing_server_secure_connection[%d] session->error[%d] session->network[%d]",
-                                       account->outgoing_server_secure_connection, session->error, session->network);
-                               if (session->network != EMAIL_ERROR_NONE)
-                                       session->error = session->network;
-                               if ((session->error == EMAIL_ERROR_UNKNOWN) || (session->error == EMAIL_ERROR_NONE))
-                                       session->error = EMAIL_ERROR_CONNECTION_FAILURE;
-                               
-                               error = session->error;
-                               goto FINISH_OFF;
+
+                       if (!(*result_stream = smtp_open (host_list, 1))) {
+                               EM_DEBUG_EXCEPTION_SEC("smtp_open error : outgoing_server_secure_connection[%d] "
+                                               "session->error[%d] session->network[%d]",
+                                          account->outgoing_server_secure_connection, session->error, session->network);
+
+                               if (account->account_id > 0 && (session->network == EMAIL_ERROR_XOAUTH_BAD_REQUEST || 
+                                                         session->network == EMAIL_ERROR_XOAUTH_INVALID_UNAUTHORIZED)) {
+                                       *result_stream = smtp_close (*result_stream);
+                                       if((error = emcore_refresh_xoauth2_access_token (account->account_id)) != EMAIL_ERROR_NONE) {
+                                               EM_DEBUG_EXCEPTION ("emcore_refresh_xoauth2_access_token failed. [%d]", error);
+                                               if ((session->error == EMAIL_ERROR_UNKNOWN) || (session->error == EMAIL_ERROR_NONE))
+                                                       session->error = EMAIL_ERROR_CONNECTION_FAILURE;
+                                               error = session->error;
+                                               goto FINISH_OFF;
+                                       }
+
+                                       sleep(2); /* wait for updating access token */
+
+                                       if (!(*result_stream = smtp_open (host_list, 1))) {
+                                               if (session->network != EMAIL_ERROR_NONE)
+                                                       session->error = session->network;
+                                               if ((session->error == EMAIL_ERROR_UNKNOWN) || (session->error == EMAIL_ERROR_NONE))
+                                                       session->error = EMAIL_ERROR_CONNECTION_FAILURE;
+
+                                               error = session->error;
+                                               goto FINISH_OFF;
+                                       }
+                               }
+                               else {
+                                       error = EMAIL_ERROR_CONNECTION_FAILURE;
+                                       goto FINISH_OFF;
+                               }
                        }
                }
-               *result_stream = send_stream;
        }
        
        ret = true;
@@ -805,7 +860,6 @@ FINISH_OFF:
 #endif
 
        EM_SAFE_FREE(mbox_path);
-
        EM_SAFE_FREE(mailbox_name);
 
        if (mailbox) {
@@ -864,8 +918,7 @@ INTERNAL_FUNC void emcore_close_mailbox_receiving_stream()
        EM_DEBUG_FUNC_BEGIN("recv_thread_run [%d]", recv_thread_run);
        if (!recv_thread_run) {
                ENTER_CRITICAL_SECTION(_close_stream_lock);
-               mail_close(g_receiving_thd_stream);
-               g_receiving_thd_stream = NULL;
+               g_receiving_thd_stream = mail_close (g_receiving_thd_stream);
                prev_acc_id_recv_thd = 0;
                LEAVE_CRITICAL_SECTION(_close_stream_lock);
        }
@@ -877,8 +930,7 @@ INTERNAL_FUNC void emcore_close_mailbox_partial_body_stream()
        EM_DEBUG_FUNC_BEGIN();
        if (false == emcore_get_pbd_thd_state()) {
                EM_DEBUG_LOG("emcore_get_pbd_thd_state returned false");
-               mail_close(g_partial_body_thd_stream);
-               g_partial_body_thd_stream = NULL;
+               g_partial_body_thd_stream = mail_close (g_partial_body_thd_stream);
                prev_acc_id_pb_thd = 0;
        }
        EM_DEBUG_FUNC_END();
@@ -948,6 +1000,7 @@ FINISH_OFF:
        if (err_code)
                *err_code = error;
        
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
        return ret;
 }
 #endif  /*  __FEATURE_KEEP_CONNECTION__ */
@@ -957,7 +1010,6 @@ INTERNAL_FUNC int emcore_close_mailbox(int account_id, void *mail_stream)
        EM_DEBUG_FUNC_BEGIN("account_id[%d], mail_stream[%p]", account_id, mail_stream);
        
        if (!mail_stream)  {
-               EM_DEBUG_EXCEPTION("Invalid parameter");
                return false;
        }
        
@@ -1008,13 +1060,11 @@ INTERNAL_FUNC void emcore_free_mailbox(email_mailbox_t *mailbox)
 {
        EM_DEBUG_FUNC_BEGIN();
 
-       if (!mailbox)  {
-               EM_DEBUG_EXCEPTION("INVALID_PARAM");
-               return;
-       }
-       
+       if (!mailbox) return;
+
        EM_SAFE_FREE(mailbox->mailbox_name);
        EM_SAFE_FREE(mailbox->alias);
+       EM_SAFE_FREE(mailbox->eas_data);
        
        EM_DEBUG_FUNC_END();
 }
@@ -1045,7 +1095,7 @@ INTERNAL_FUNC int emcore_free_internal_mailbox(email_internal_mailbox_t **mailbo
                        EM_SAFE_FREE(p[i].alias);
                }
                /* EM_DEBUG_LOG("p [%p]", p); */
-               free(p);
+               EM_SAFE_FREE (p);
                *mailbox_list = NULL;
        }
 
@@ -1089,7 +1139,7 @@ INTERNAL_FUNC int  emcore_send_mail_event(email_mailbox_t *mailbox, int mail_id
        int ret = false;
        int err = EMAIL_ERROR_NONE;
        int handle; 
-       email_event_t event_data;
+       email_event_t *event_data = NULL;
 
        if (!mailbox || mailbox->account_id <= 0) {
                EM_DEBUG_LOG(" mailbox[%p]", mailbox);
@@ -1097,22 +1147,29 @@ INTERNAL_FUNC int  emcore_send_mail_event(email_mailbox_t *mailbox, int mail_id
                err = EMAIL_ERROR_INVALID_PARAM;
                goto FINISH_OFF;
        }
-       memset(&event_data, 0x00, sizeof(email_event_t));
 
-       event_data.type = EMAIL_EVENT_SEND_MAIL;
-       event_data.account_id = mailbox->account_id;
-       event_data.event_param_data_4 = mail_id;
-       event_data.event_param_data_1 = NULL;
-       event_data.event_param_data_5 = mailbox->mailbox_id;
+       event_data = em_malloc(sizeof(email_event_t));
+       event_data->type = EMAIL_EVENT_SEND_MAIL;
+       event_data->account_id = mailbox->account_id;
+       event_data->event_param_data_4 = mail_id;
+       event_data->event_param_data_1 = NULL;
+       event_data->event_param_data_5 = mailbox->mailbox_id;
                        
-       if (!emcore_insert_event_for_sending_mails(&event_data, &handle, &err))  {
+       if (!emcore_insert_event_for_sending_mails(event_data, &handle, &err))  {
                EM_DEBUG_LOG(" emcore_insert_event failed - %d", err);
                goto FINISH_OFF;
        }
        emcore_add_transaction_info(mail_id , handle , &err);
 
        ret = true;
+
 FINISH_OFF: 
+
+       if (ret == false && event_data) {
+               emcore_free_event(event_data);
+               EM_SAFE_FREE(event_data);
+       }
+
        if (err_code)
                *err_code = err;
        
@@ -1213,11 +1270,7 @@ INTERNAL_FUNC int emcore_local_activity_sync(int account_id, int *err_code)
        int err         = 0;
        int handle = 0;
        int ret = false;
-       email_event_t event_data;
-
-
-       memset(&event_data, 0x00, sizeof(email_event_t));
-       
+       email_event_t *event_data = NULL;
 
        EM_IF_NULL_RETURN_VALUE(err_code, false);
 
@@ -1235,9 +1288,10 @@ INTERNAL_FUNC int emcore_local_activity_sync(int account_id, int *err_code)
        EM_DEBUG_LOG(">>> emdaemon_sync_local_activity 5 ");
 
        if (activity_count > 0) {
-               event_data.type = EMAIL_EVENT_LOCAL_ACTIVITY;
-               event_data.account_id  = account_id;
-               if (!emcore_insert_event(&event_data, &handle, &err))  {
+               event_data = em_malloc(sizeof(email_event_t));
+               event_data->type = EMAIL_EVENT_LOCAL_ACTIVITY;
+               event_data->account_id  = account_id;
+               if (!emcore_insert_event(event_data, &handle, &err))  {
                        EM_DEBUG_LOG(" emcore_insert_event failed - %d", err);
                        goto FINISH_OFF;
                }
@@ -1245,8 +1299,13 @@ INTERNAL_FUNC int emcore_local_activity_sync(int account_id, int *err_code)
                ret = true;
        }
 
-       FINISH_OFF: 
-               
+FINISH_OFF:
+
+       if (ret == false && event_data) {
+               emcore_free_event(event_data);
+               EM_SAFE_FREE(event_data);
+       }
+
        if (activity_id_list)
                emstorage_free_activity_id_list(activity_id_list, &err); 
        
@@ -1266,12 +1325,10 @@ INTERNAL_FUNC int emcore_save_local_activity_sync(int account_id, int *err_code)
        emstorage_activity_tbl_t *local_activity = NULL;
        int *activity_id_list = NULL;
        int activity_count = 0;
-       int err         = 0;
+       int err = EMAIL_ERROR_NONE;
        int ret = false;
        int handle = 0;
-       email_event_t event_data;
-
-       memset(&event_data, 0x00, sizeof(email_event_t));
+       email_event_t *event_data = NULL;
 
        EM_IF_NULL_RETURN_VALUE(err_code, false);
 
@@ -1288,9 +1345,10 @@ INTERNAL_FUNC int emcore_save_local_activity_sync(int account_id, int *err_code)
 
        
        if (activity_count > 0) {
-               event_data.type = EMAIL_EVENT_LOCAL_ACTIVITY;
-               event_data.account_id  = account_id;
-               if (!emcore_insert_event_for_sending_mails(&event_data, &handle, &err))  {
+               event_data = em_malloc(sizeof(email_event_t));
+               event_data->type = EMAIL_EVENT_LOCAL_ACTIVITY;
+               event_data->account_id  = account_id;
+               if (!emcore_insert_event_for_sending_mails(event_data, &handle, &err)) {
                        EM_DEBUG_LOG(" emcore_insert_event failed - %d", err);
                        goto FINISH_OFF;
                }       
@@ -1298,8 +1356,12 @@ INTERNAL_FUNC int emcore_save_local_activity_sync(int account_id, int *err_code)
                ret = true;
        }
 
+FINISH_OFF:
 
-       FINISH_OFF: 
+       if (ret == false && event_data) {
+               emcore_free_event(event_data);
+               EM_SAFE_FREE(event_data);
+       }
 
        if (local_activity)
                emstorage_free_local_activity(&local_activity, activity_count, NULL); 
@@ -1311,7 +1373,6 @@ INTERNAL_FUNC int emcore_save_local_activity_sync(int account_id, int *err_code)
                *err_code = err;
        
        return ret;
-
 }
 
 #endif
index 5b9d0b3..5c0b09e 100755 (executable)
@@ -39,6 +39,7 @@
 #include <ctype.h>
 #include <sys/stat.h>
 #include <sys/time.h>
+#include <glib.h>
 #include "email-internal-types.h"
 #include "lnx_inc.h"
 #include "email-utilities.h"
@@ -50,6 +51,7 @@
 #include "email-core-event.h"
 #include "email-core-account.h"
 #include "email-core-signal.h"
+#include "email-core-mailbox-sync.h"
 #include "email-debug-log.h"
 
 #define MIME_MESG_IS_SOCKET
@@ -85,6 +87,8 @@
 #define CONTENT_REPORT_TYPE  9
 #define CONTENT_ID           10
 #define CONTENT_LOCATION     11
+#define CONTENT_SMIME_TYPE   12
+#define CONTENT_PROTOCOL     13
 
 #define GRAB_TYPE_TEXT       1 /*  retrieve text and attachment name */
 #define GRAB_TYPE_ATTACHMENT 2 /*  retrieve only attachmen */
 /*  MIME Header Parameter (Content-Type, Content-Disposition, ... */
 struct _parameter {
        char                            *name;                  /*  parameter name */
-       char                            *value;                 /*  parameter valu */
+       char                            *value;                 /*  parameter value */
        struct _parameter       *next;                  /*  next paramete */
 };
 
-/*  Content-Dispositio */
+/*  Content-Disposition */
 struct _disposition {
        char                            *type;                  /*  "inline" "attachment */
        struct _parameter       *parameter;             /*  "filename", .. */
 };
 
-/*  RFC822 Heade */
+/*  RFC822 Header */
 struct _rfc822header {
-       char                            *return_path;   /*  error return pat */
+       char                            *return_path;   /*  error return path */
        char                            *received;
        char                            *date;
        char                            *from;
@@ -176,50 +180,53 @@ struct _rfc822header {
 
 /*  MIME Part Header */
 struct _m_part_header {
-       char                            *type;                  /*  text, image, audio, video, application, multipart, message */
-       char                            *subtype;               /*  plain, html, jpeg, .. */
-       char                            *encoding;              /*  encoding typ */
-       struct _parameter       *parameter;             /*  content-type parameter  :  "boundary" "charset" .. */
-       char                            *desc;                  /*  descriptio */
-       char                            *disp_type;             /*  disposition type  :  "inline" "attachment", */
-       struct _parameter       *disp_parameter;    /*  disposition parameter  :  "filename", .. */
-       char                            *content_id;    /*  content id  :  it is inline  */
-       char                            *content_location;      /*  content location  :  "inline" location  */
+       char                            *type;                      /* text, image, audio, video, application, multipart, message */
+       char                            *subtype;                   /* plain, html, jpeg, .. */
+       char                            *encoding;                  /* encoding typ */
+       struct _parameter       *parameter;                 /* content-type parameter  :  "boundary" "charset" .. */
+       char                            *desc;                      /* description */
+       char                            *disp_type;                 /* disposition type  :  "inline" "attachment", */
+       struct _parameter       *disp_parameter;    /* disposition parameter  :  "filename", .. */
+       char                            *content_id;        /* content id  :  it is inline  */
+       char                            *content_location;      /* content location  :  "inline" location  */
 };
 
 /*  MIME Message Header */
 struct _m_mesg_header {
-       char                            *version;               /*  MIME Versio */
-       struct _m_part_header  *part_header;    /*  MIME Part Heade */
+       char                               *version;          /* MIME Version */
+       struct _m_part_header  *part_header;      /* MIME Part Header */
+       /* char                   *message_context; */  /* Message-Context : Voice-message, Video-message, Fax-message... */
+       /* int                     content_duration; */ /* Content-Duration */
+       /* int                     x_content_pages;  */ /* X-Content-Pages */
+       /* char                   *sensitivity; */     /* Sensitivity */
 };
 
 /*  MIME Multipart Body linked list */
 typedef struct _m_body _m_body_t;
 struct _m_part{
-       _m_body_t                       *body;                  /*  part bod */
-       struct _m_part          *next;                  /*  the next found par */
+       _m_body_t              *body;             /* part body */
+       struct _m_part         *next;             /* the next found part */
 };
 
 /*  MIME Multipart Body */
 struct _m_body {
-       struct _m_part_header *part_header;     /*  MIME Part Heade */
-       struct _m_part                  nested;                 /*  nested structure if contain multipar */
-       char                            *text;                  /*  text if not contain multipar */
-       int                                             size;                   /*  text size if not contain multipar */
-       char                            *holdingfile;
+       struct _m_part_header  *part_header;      /* MIME Part Header */
+       struct _m_part          nested;           /* nested structure if contain multipart */
+       char                   *text;             /* text if not contain multipart */
+       int                     size;             /* text size if not contain multipart */
+       char                   *holdingfile;
 };
 
 /*  MIME Message */
 struct _m_mesg {
-       struct _rfc822header  *rfc822header;    /*  RFC822 Heade */
-       struct _m_mesg_header *header;                  /*  MIME Message Heade */
-       struct _m_part          nested;                 /*  nested structure if contain multipar */
-       char                            *text;                  /*  text if not contain multipar */
-       int                                             size;                   /*  text size if not contain multipar */
+       struct _rfc822header    *rfc822header;    /* RFC822 Header */
+       struct _m_mesg_header   *header;          /* MIME Message Header */
+       struct _m_part           nested;          /* nested structure if contain multipart */
+       char                    *text;            /* text if not contain multipart */
+       int                      size;            /* text size if not contain multipart */
 };
 /* ---------------------------------------------------------------------- */
 /*  Global variable */
-static bool next_decode_string = false;
 static int  eml_data_count = 0;
 
 /* ---------------------------------------------------------------------- */
@@ -238,8 +245,8 @@ extern int multi_part_body_size;
 extern bool only_body_download;
 
 /* ---------------------------------------------------------------------- */
-static BODY **g_inline_list = NULL;
-static int g_inline_count = 0;
+__thread BODY **g_inline_list = NULL;
+__thread int g_inline_count = 0;
 
 /*  Function Declaration */
 
@@ -274,8 +281,6 @@ void emcore_mime_free_rfc822_header(struct _rfc822header *rfc822header);
 void emcore_mime_free_part(struct _m_part *part);
 void emcore_mime_free_part_body(struct _m_body *body);
 void emcore_mime_free_mime(struct _m_mesg *mmsg);
-char *emcore_mime_get_line_from_sock(void *stream, char *buf, int size, int *err_code);
-char *emcore_mime_get_save_file_name(int *err_code);
 
 /*  get content data and save buffer or fil */
 /*  mode - 1 :  get the only siz */
@@ -338,7 +343,6 @@ char *em_split_file_path(char *str)
 
        if (temp_cid == NULL) {
                EM_DEBUG_EXCEPTION(">>>> File Path Doesnot contain end line for CID ");
-               next_decode_string = true;
                EM_SAFE_FREE(buf);
                return temp_str;
        }
@@ -347,7 +351,6 @@ char *em_split_file_path(char *str)
 
        if (!strstr(temp_cid_data, delims)) {
                EM_DEBUG_EXCEPTION(">>>> File Path Doesnot contain @ ");
-               next_decode_string = true;
                EM_SAFE_FREE(buf);
                EM_SAFE_FREE(temp_cid_data);
                return temp_str;
@@ -355,10 +358,9 @@ char *em_split_file_path(char *str)
        else            {
                result = strstr(temp_str, delims);
                if (result != NULL) {
-                       next_decode_string = false;
                        *result = '\0';
                        result++;
-                       EM_DEBUG_LOG("content_id is [ %s ]", content_id);
+                       EM_DEBUG_LOG_SEC("content_id is [ %s ]", content_id);
 
                        if (strcasestr(content_id, ".bmp") || strcasestr(content_id, ".jpeg") || strcasestr(content_id, ".png") ||
                                        strcasestr(content_id, ".jpg") || strcasestr(content_id, ".gif"))
@@ -368,7 +370,6 @@ char *em_split_file_path(char *str)
                }
                else {
                        EM_DEBUG_EXCEPTION(">>>> File Path Doesnot contain end line for CID ");
-                       next_decode_string = true;
                        EM_SAFE_FREE(buf);
                        EM_SAFE_FREE(temp_cid_data);
                        return temp_str;
@@ -535,7 +536,7 @@ int emcore_parse_mime(void *stream, int is_file, struct _m_content_info *cnt_inf
        /*  2. parse body */
        EM_DEBUG_LOG(">>>>>> 2. parse body");
        if (mmsg && mmsg->header && mmsg->header->part_header && mmsg->header->part_header->parameter)  {
-               EM_DEBUG_LOG("name[%s]", mmsg->header->part_header->parameter->name);
+               EM_DEBUG_LOG_SEC("name[%s]", mmsg->header->part_header->parameter->name);
                EM_DEBUG_LOG("value[%s]", mmsg->header->part_header->parameter->value);
                EM_DEBUG_LOG("next  :  %p", mmsg->header->part_header->parameter->next);
        }
@@ -548,7 +549,7 @@ int emcore_parse_mime(void *stream, int is_file, struct _m_content_info *cnt_inf
        /*  3. free memory */
        EM_DEBUG_LOG(">>>>>> 3. free memory");
        if (mmsg && mmsg->header && mmsg->header->part_header && mmsg->header->part_header->parameter)  {
-               EM_DEBUG_LOG("name[%s]", mmsg->header->part_header->parameter->name);
+               EM_DEBUG_LOG_SEC("name[%s]", mmsg->header->part_header->parameter->name);
                EM_DEBUG_LOG("value[%s]", mmsg->header->part_header->parameter->value);
                EM_DEBUG_LOG("next  :  %p", mmsg->header->part_header->parameter->next);
        }
@@ -573,8 +574,7 @@ int emcore_mime_parse_header(void *stream, int is_file, struct _rfc822header **r
                if (err_code != NULL)
                        *err_code = EMAIL_ERROR_CANCELLED;
                        return false;
-               }
-
+       }
 
        if ((is_file == 0 && !emcore_mime_get_line_from_sock(stream, buf, MIME_LINE_LEN, err_code)) ||
                (is_file == 1 && !emcore_get_line_from_file(stream, buf, MIME_LINE_LEN, err_code)))  {
@@ -608,7 +608,6 @@ int emcore_mime_parse_header(void *stream, int is_file, struct _rfc822header **r
                                EM_SAFE_FREE(name);
                        }
 
-                       /* EM_DEBUG_FUNC_BEGIN() */
                        if ((pTemp = strtok(buf, ":")) == NULL)
                                break;
 
@@ -627,29 +626,43 @@ int emcore_mime_parse_header(void *stream, int is_file, struct _rfc822header **r
                if (!name)
                        break;
 
-               EM_DEBUG_LOG("> name[%s]", name);
+               EM_DEBUG_LOG_SEC("> name[%s]", name);
                EM_DEBUG_LOG("> value[%s]", value);
 
-               /*  MIME Part Heade */
+               /*  MIME Part Header */
                if (memcmp(name, "CONTENT-", 8) == 0 && value)  {
-                       EM_DEBUG_LINE;
                        emcore_mime_set_part_header_value(&tmp_header->part_header, name, value, err_code);
 
                        if (tmp_header->part_header && tmp_header->part_header->parameter)      {
-                               EM_DEBUG_LOG("name[%s]", tmp_header->part_header->parameter->name);
+                               EM_DEBUG_LOG_SEC("name[%s]", tmp_header->part_header->parameter->name);
                                EM_DEBUG_LOG("value[%s]", tmp_header->part_header->parameter->value);
                                EM_DEBUG_LOG("next  :  %p", tmp_header->part_header->parameter->next);
                        }
 
-                       /*  MIME Version Heade */
+                       /*  MIME Version Header */
                }
                else if (memcmp(name, "MIME-VERSION", 12) == 0)  {
                        /* EM_DEBUG_FUNC_BEGIN() */
                        /*  ignored because we need only contents information */
                        /*  tmp_header->version = EM_SAFE_STRDUP(value) */
-
-                       /*  RFC822 Heade */
+                       /*  RFC822 Header */
+               }
+               /*
+               else if (strncmp(name, "MESSAGE-CONTEXT", strlen("MESSAGE-CONTEXT")) == 0) {
+                       em_upper_string(value);
+                       tmp_header->message_context = EM_SAFE_STRDUP(value);
+               }
+               else if (strncmp(name, "CONTENT-DURATION", strlen("CONTENT-DURATION")) == 0) {
+                       tmp_header->content_duration = atoi(value);
+               }
+               else if (strncmp(name, "X-CONTENT-PAGES", strlen("X-CONTENT-PAGES")) == 0) {
+                       tmp_header->x_content_pages = atoi(value);
                }
+               else if (strncmp(name, "SENSITIVITY", strlen("SENSITIVITY")) == 0) {
+                       em_upper_string(value);
+                       tmp_header->sensitivity = EM_SAFE_STRDUP(value);
+               }
+               */
                else  {
                        /*  in socket stream case, ignored because we need only contents information */
                        if (is_file == 1)
@@ -819,8 +832,8 @@ int emcore_mime_parse_body(void *stream, int is_file, struct _m_mesg *mmsg, stru
                        }
 
                        /*  after finishing body parsing, make stream empty to get next mail. (get line from sock or file until '.' is read */
-                       if (end_of_parsing == true && err != EMAIL_ERROR_NO_MORE_DATA)
-                               emcore_mime_flush_receiving_buffer(stream, is_file, NULL, NULL, NULL, err_code);
+                       if (end_of_parsing && err != EMAIL_ERROR_NO_MORE_DATA)
+                               emcore_mime_flush_receiving_buffer(stream, is_file, NULL, NULL, NULL, NULL);
 
                        break;
 
@@ -839,7 +852,7 @@ int emcore_mime_parse_body(void *stream, int is_file, struct _m_mesg *mmsg, stru
                                if (attachment_name == NULL)
                                        attachment_name = emcore_mime_get_header_value(mmsg->header->part_header, CONTENT_NAME, err_code);
 
-                               EM_DEBUG_LOG("attachment_name : [%s]", attachment_name);
+                               EM_DEBUG_LOG_SEC("attachment_name : [%s]", attachment_name);
 
                                cnt_info->file = em_malloc(sizeof(struct attachment_info));
                                if (cnt_info->file) {
@@ -851,6 +864,7 @@ int emcore_mime_parse_body(void *stream, int is_file, struct _m_mesg *mmsg, stru
                                        }
                                        cnt_info->file->save = holder;
                                        cnt_info->file->size = size;
+                               cnt_info->file->attachment_mime_type = EM_SAFE_STRDUP(content_type);
                                        cnt_info->file->next = NULL;
                                }
                                break;
@@ -907,12 +921,13 @@ int emcore_mime_parse_part(void *stream, int is_file, struct _m_part_header *par
        char buf[MIME_LINE_LEN] = {0x00, };
        char boundary[BOUNDARY_LEN] = {0x00, };
        char boundary_end[BOUNDARY_LEN] = {0x00, };
-       char mime_type_buffer[128] = { 0, };
+       char temp_inline_attachment_name[20] = {0x00, };
        char *boundary_str = NULL;
        char *content_type = NULL;
        char *content_encoding = NULL;
        char *holder = NULL;
        char *attachment_name = NULL;
+       char *content_id = NULL;
        char *content_disposition = NULL;
        char *pTemp = NULL;
        int type = 0;
@@ -921,6 +936,7 @@ int emcore_mime_parse_part(void *stream, int is_file, struct _m_part_header *par
        int size = 0, local_err_code = EMAIL_ERROR_NONE;
        int is_skip = false;
        int result = 0;
+       int inline_attach_index = 0;
 
        boundary_str = emcore_mime_get_header_value(parent_header, CONTENT_BOUNDARY, err_code);
 
@@ -1045,6 +1061,7 @@ int emcore_mime_parse_part(void *stream, int is_file, struct _m_part_header *par
                        default:
                                EM_DEBUG_LOG("default");
                                attachment_name = NULL;
+                               content_id = NULL;
                                content_disposition = NULL;
 
                                if (type == TYPE_MESSAGE)
@@ -1062,13 +1079,21 @@ int emcore_mime_parse_part(void *stream, int is_file, struct _m_part_header *par
                                /*  first check inline content */
                                /*  if the content id or content location exis */
                                content_disposition = emcore_mime_get_header_value(tmp_body->part_header, CONTENT_DISPOSITION, err_code);
-                               EM_DEBUG_LOG("content_disposition : [%s]", content_disposition);
+                               EM_DEBUG_LOG_SEC("content_disposition : [%s]", content_disposition);
 
-                               attachment_name = emcore_mime_get_header_value(tmp_body->part_header, CONTENT_ID, err_code);
-                               EM_DEBUG_LOG("content_id : [%s]", attachment_name);
+                               content_id = emcore_mime_get_header_value(tmp_body->part_header, CONTENT_ID, err_code);
+                               EM_DEBUG_LOG_SEC("content_id : [%s]", content_id);
 
-                               if (attachment_name) {
-                                       if (emcore_search_string_from_file(cnt_info->text.html, attachment_name, &result) == EMAIL_ERROR_NONE && result) {
+                               if (content_id) {
+                                       if (emcore_search_string_from_file(cnt_info->text.html, content_id, NULL, &result) == EMAIL_ERROR_NONE && result) {
+
+                                               SNPRINTF(temp_inline_attachment_name, sizeof(temp_inline_attachment_name), "image_%d", ++inline_attach_index);
+                                               attachment_name = temp_inline_attachment_name;  
+
+                                               if (emcore_search_string_from_file(cnt_info->text.html, content_id, attachment_name, &result) != EMAIL_ERROR_NONE) {
+                                                       EM_DEBUG_EXCEPTION("emcore_search_string_from file failed");
+                                               }
+                                               
                                                content_disposition_type = INLINE_ATTACHMENT;
                                        } else if (!strcasecmp(content_disposition ? content_disposition : "", "attachment")) {
                                                attachment_name = emcore_mime_get_header_value(tmp_body->part_header, CONTENT_NAME, err_code);
@@ -1091,12 +1116,15 @@ int emcore_mime_parse_part(void *stream, int is_file, struct _m_part_header *par
                                                content_disposition_type = ATTACHMENT;
 
                                        } else if (!strcasecmp(content_disposition ? content_disposition : "", "inline")) {
-                                               attachment_name = emcore_mime_get_header_value(tmp_body->part_header, CONTENT_NAME, err_code);
 
-                                               if (!attachment_name)
-                                                       attachment_name = emcore_mime_get_header_value(tmp_body->part_header, CONTENT_FILENAME, err_code);
+                                               SNPRINTF(temp_inline_attachment_name, sizeof(temp_inline_attachment_name), "image_%d", ++inline_attach_index);
+                                               attachment_name = temp_inline_attachment_name;  
 
-                                               content_disposition_type = INLINE_ATTACHMENT;
+                                               if (emcore_search_string_from_file(cnt_info->text.html, content_id, attachment_name, &result) != EMAIL_ERROR_NONE) {
+                                                       EM_DEBUG_EXCEPTION("emcore_search_string_from file failed");
+                                               } else {
+                                                       content_disposition_type = INLINE_ATTACHMENT;
+                                               }
                                        } else if (strstr(content_type ? content_type : "", "PKCS7")) {
                                                attachment_name = emcore_mime_get_header_value(tmp_body->part_header, CONTENT_NAME, err_code);
                                                EM_DEBUG_LOG_MIME(">> attachment = [%s]", attachment_name ? attachment_name  :  NIL);
@@ -1117,7 +1145,7 @@ int emcore_mime_parse_part(void *stream, int is_file, struct _m_part_header *par
                                        return false;
                                }
 
-                               EM_DEBUG_LOG("attachment_name : [%s]", attachment_name);
+                               EM_DEBUG_LOG_SEC("attachment_name : [%s]", attachment_name);
                                /*  get content and content information */
                                if (content_disposition_type != ATTACHMENT && content_disposition_type != INLINE_ATTACHMENT)  { /*  text */
                                        /*  get content by buffer */
@@ -1154,10 +1182,7 @@ int emcore_mime_parse_part(void *stream, int is_file, struct _m_part_header *par
                                                        EM_DEBUG_LOG(" cnt_info->text.plain [%s]", cnt_info->text.plain);
                                                }
                                        } else {
-                                               if (holder) {
-                                                       free(holder);
-                                                       holder = NULL;
-                                               }
+                                               EM_SAFE_FREE (holder);                                          
                                        }
                                } else {                /*  attachment */
                                        EM_DEBUG_LOG("attachment_name is not NULL. It's a attachment");
@@ -1178,10 +1203,8 @@ int emcore_mime_parse_part(void *stream, int is_file, struct _m_part_header *par
 
                                        file->name                 = EM_SAFE_STRDUP(attachment_name);
                                        file->content_id           = EM_SAFE_STRDUP(tmp_body->part_header->content_id);
-                                       if(tmp_body->part_header->type && tmp_body->part_header->subtype) {
-                                               SNPRINTF(mime_type_buffer, 128, "%s/%s", tmp_body->part_header->type, tmp_body->part_header->subtype);
-                                               file->attachment_mime_type = EM_SAFE_STRDUP(mime_type_buffer);
-                                       }
+                                       file->attachment_mime_type = EM_SAFE_STRDUP(content_type);
+                                       
 
                                        /*  check if the current file is target file */
                                        if ((cnt_info->grab_type & GRAB_TYPE_ATTACHMENT) || file->type == INLINE_ATTACHMENT)  {
@@ -1214,6 +1237,8 @@ int emcore_mime_parse_part(void *stream, int is_file, struct _m_part_header *par
                                                EM_DEBUG_LOG("end_of_parsing [%d], err_code [%d]", end_of_parsing, *err_code);
 
                                        file->size = size;
+                                        file->attachment_mime_type = strdup(content_type);
+                                        file->save_status = end_of_parsing;
 
                                        if (strstr(content_type, APPLICATION_STR))  {
                                                pTemp = content_type + EM_SAFE_STRLEN(APPLICATION_STR);
@@ -1287,7 +1312,7 @@ int emcore_mime_parse_part(void *stream, int is_file, struct _m_part_header *par
 /*  set RFC822 Heade */
 int emcore_mime_set_rfc822_header_value(struct _rfc822header **header, char *name, char *value, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("header[%p], name[%s], value[%s], err_code[%p]", header, name, value, err_code);
+       EM_DEBUG_FUNC_BEGIN_SEC("header[%p], name[%s], value[%s], err_code[%p]", header, name, value, err_code);
 
        char **p = NULL;
        char *t = NULL;
@@ -1335,6 +1360,8 @@ int emcore_mime_set_rfc822_header_value(struct _rfc822header **header, char *nam
                return false;
        }
 
+        em_trim_left(value);
+
        if (!*p)
                *p = EM_SAFE_STRDUP(value);
        else  { /*  Long Header */
@@ -1351,7 +1378,7 @@ int emcore_mime_set_rfc822_header_value(struct _rfc822header **header, char *nam
 /*  set MIME Part Heade */
 int emcore_mime_set_part_header_value(struct _m_part_header **header, char *name, char *value, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("header[%p], name[%s], value[%s], err_code[%p]", header, name, value, err_code);
+       EM_DEBUG_FUNC_BEGIN_SEC("header[%p], name[%s], value[%s], err_code[%p]", header, name, value, err_code);
 
        if (!name || !value) {
                EM_DEBUG_EXCEPTION("Invalid parameter");
@@ -1372,6 +1399,7 @@ int emcore_mime_set_part_header_value(struct _m_part_header **header, char *name
        }
 
        em_upper_string(name);
+       
        em_trim_left(value);
        em_trim_right(value);
 
@@ -1385,24 +1413,25 @@ int emcore_mime_set_part_header_value(struct _m_part_header **header, char *name
                if (strncmp(name, "CONTENT-TYPE", strlen("CONTENT-TYPE")) == 0)  {
                        p_val = strtok(value, ";");
 
-                       if (p_val)  {
+                       if (p_val) {
                                if (!(*header)->type)  {   /*  Content-Type */
                                        em_upper_string(p_val);
                                        (*header)->type = EM_SAFE_STRDUP(p_val);
                                }
-                               else  {   /*  Content-Type Parameter (format :  "name =value" */
+
+                               /*  Content-Type Parameter (format :  "name =value" */
+                               do {
                                        if (emcore_mime_get_param_from_str(p_val, &p, err_code))
                                                emcore_mime_add_param_to_list(&((*header)->parameter), p, err_code);
                                        else /* name= CRLF value */ {
                                                struct _parameter *t = (*header)->parameter;
                                                while (t && t->next) {
+                                                       EM_DEBUG_LOG_SEC("name : [%s]", t->name);
+                                                       EM_DEBUG_LOG("value : [%s]", t->value);
                                                        t = t->next;
                                                }
 
-                                               EM_DEBUG_LOG("name : [%s]", t->name);
-                                               EM_DEBUG_LOG("value : [%s]", t->value);
-
-                                               if (t->value == NULL) {
+                                               if (t && t->name) {
                                                        char *pointer = NULL;
 
                                                        if (EM_SAFE_STRLEN(p_val) > 0)  {
@@ -1417,21 +1446,27 @@ int emcore_mime_set_part_header_value(struct _m_part_header **header, char *name
                                                                int err = EMAIL_ERROR_NONE;
                                                                char *utf8_text = NULL;
 
-                                                               if (!(utf8_text = emcore_decode_rfc2047_text(p_val, &err)))
+                                                               if (!(utf8_text = emcore_decode_rfc2047_text(p_val, &err))) {
                                                                        EM_DEBUG_EXCEPTION("emcore_decode_rfc2047_text failed [%d]", err);
+                                                                       continue; /*prevent 53050*/
+                                                               }
                                                                EM_DEBUG_LOG("utf8_text : [%s]", utf8_text);
-                                                               t->value = EM_SAFE_STRDUP(utf8_text);
+
+                                                               if (t->value == NULL) {
+                                                                       EM_DEBUG_LOG("value is NULL");
+                                                                       t->value = EM_SAFE_STRDUP(utf8_text);
+                                                               } else {
+                                                                       EM_DEBUG_LOG("value is not NULL");
+                                                                       t->value = realloc(t->value, strlen(t->value) + EM_SAFE_STRLEN(utf8_text) + 1); 
+                                                                       strcpy((t->value + strlen(utf8_text)), utf8_text);
+                                                               }
+               
+                                                               EM_DEBUG_LOG("value : [%s]", t->value); 
+                                                               EM_SAFE_FREE (utf8_text);
                                                        }
                                                }
                                        }
-
-                               }
-
-                               /*  repeatedly get paramete */
-                               while ((p_val = strtok(NULL, ";")))  {
-                                       if (emcore_mime_get_param_from_str(p_val, &p, err_code))
-                                               emcore_mime_add_param_to_list(&((*header)->parameter), p, err_code);
-                               }
+                               } while ((p_val = strtok(NULL, ";"))); 
                        }
                }
                else if (strncmp(name, "CONTENT-TRANSFER-ENCODING", strlen("CONTENT-TRANSFER-ENCODING")) == 0)  {
@@ -1493,9 +1528,13 @@ int emcore_mime_get_param_from_str(char *str, struct _parameter **param, int *er
 
        *param = NULL;
 
-       /*  Parameter Check */
        if (!(p = strchr(str, '=')))    return false;
 
+       if (*(p+1) == '?') {
+               EM_DEBUG_LOG("The parameter is invalid : [%s]", str);
+               return false;
+       }
+
        *p = '\0';
 
        p_name = str;
@@ -1624,6 +1663,16 @@ char *emcore_mime_get_header_value(struct _m_part_header *header, int type, int
                case CONTENT_LOCATION:
                        return header->content_location;
 
+               case CONTENT_SMIME_TYPE:
+                       name = "SMIME-TYPE";
+                       p = header->parameter;
+                       break;
+
+               case CONTENT_PROTOCOL:
+                       name = "PROTOCOL";
+                       p = header->parameter;
+                       break;
+
                default:
                        return NULL;
        }
@@ -1673,14 +1722,18 @@ INTERNAL_FUNC int emcore_decode_body_text(char *enc_buf, int enc_len, int enc_ty
        if (content)  {
                if (enc_len < *dec_len) {
                        EM_DEBUG_EXCEPTION("Decoded length is too big to store it");
-                       return -1;
+                       EM_SAFE_FREE(content);
+                       if(err_code) *err_code = EMAIL_ERROR_INVALID_DATA;
+                       return EMAIL_ERROR_INVALID_DATA;
                }
                memcpy(enc_buf, content, *dec_len);
                enc_buf[*dec_len] = '\0';
                EM_SAFE_FREE(content);
        }
        EM_DEBUG_FUNC_END();
-       return 0;
+
+       if(err_code) *err_code = EMAIL_ERROR_NONE;
+       return EMAIL_ERROR_NONE;
 }
 
 /*  1. if boundary is NULL, contnent has not multipart */
@@ -1692,7 +1745,7 @@ INTERNAL_FUNC int emcore_decode_body_text(char *enc_buf, int enc_len, int enc_ty
 /*         SAVE_TYPE_FILE   :  content is saved to temporary file (holder is file name */
 int emcore_mime_get_content_data(void *stream, int is_file, int is_text, char *boundary_str, char *content_encoding, int *end_of_parsing, int mode, char **holder, int *size, void *callback, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("stream[%p], is_file[%d], boundary_str[%s], content_encoding[%s], end_of_parsing[%p], mode[%d], holder[%p], size[%p], callback[%p], err_code[%p]", stream, is_file, boundary_str, content_encoding, end_of_parsing, mode, holder, size, callback, err_code);
+       EM_DEBUG_FUNC_BEGIN_SEC("stream[%p], is_file[%d], boundary_str[%s], content_encoding[%s], end_of_parsing[%p], mode[%d], holder[%p], size[%p], callback[%p], err_code[%p]", stream, is_file, boundary_str, content_encoding, end_of_parsing, mode, holder, size, callback, err_code);
 
        int encoding = ENC7BIT;
        int error = EMAIL_ERROR_NONE, ret = false;
@@ -1921,39 +1974,35 @@ char *emcore_mime_get_line_from_sock(void *stream, char *buf, int size, int *err
                return NULL;
        }
 
-       if (!pop3_reply((MAILSTREAM *)stream))  { /*  if TRUE, check respons */
-               EM_DEBUG_LOG("p_pop3local->response 1[%s]", p_pop3local->response);
+       if (!pop3_reply((MAILSTREAM *)stream))  { /*  if TRUE, check response */
+               EM_DEBUG_LOG_DEV("p_pop3local->response 1[%s]", p_pop3local->response);
                if (p_pop3local->response) {
                        if (*p_pop3local->response == '.' && EM_SAFE_STRLEN(p_pop3local->response) == 1)  {
-                               free(p_pop3local->response);
-                               p_pop3local->response = NULL;
+                               EM_SAFE_FREE (p_pop3local->response);
                                if (err_code != NULL)
                                        *err_code = EMAIL_ERROR_NO_MORE_DATA;
                                EM_DEBUG_FUNC_END("end of response");
                                return NULL;
                        }
-                       EM_DEBUG_LOG("Not end of response");
+                       EM_DEBUG_LOG_DEV("Not end of response");
                        strncpy(buf, p_pop3local->response, size-1);
                        strncat(buf, CRLF_STRING, size-(EM_SAFE_STRLEN(buf) + 1));
 
-                       free(p_pop3local->response);
-                       p_pop3local->response = NULL;
-
+                       EM_SAFE_FREE (p_pop3local->response);
                        goto FINISH_OFF;
                }
        }
 
-       EM_DEBUG_LOG("p_pop3local->response 2[%s]", p_pop3local->response);
+       EM_DEBUG_LOG_DEV("p_pop3local->response 2[%s]", p_pop3local->response);
        if (p_pop3local->response)
-       {
+       {
                /*  if response isn't NULL, check whether this response start with '+' */
                /*  if the first character is '+', return error because this response is normal data */
                strncpy(buf, p_pop3local->response, size-1);
                strncat(buf, CRLF_STRING, size-(EM_SAFE_STRLEN(buf)+1));
-               free(p_pop3local->response); p_pop3local->response = NULL;
+               EM_SAFE_FREE (p_pop3local->response);
                goto FINISH_OFF;
-       }
-       else  {
+       } else {
                EM_DEBUG_EXCEPTION("p_pop3local->response is null. network error... ");
                if (err_code != NULL)
                        *err_code = EMAIL_ERROR_INVALID_RESPONSE;
@@ -1969,8 +2018,8 @@ FINISH_OFF:
                last_notified_percentage = (double)_pop3_last_notified_body_size / (double)_pop3_total_body_size *100.0;
                received_percentage      = (double)_pop3_received_body_size / (double)_pop3_total_body_size *100.0;
 
-               EM_DEBUG_LOG("_pop3_received_body_size = %d, _pop3_total_body_size = %d", _pop3_received_body_size, _pop3_total_body_size);
-               EM_DEBUG_LOG("received_percentage = %d, last_notified_percentage = %d", received_percentage, last_notified_percentage);
+               EM_DEBUG_LOG_DEV("_pop3_received_body_size = %d, _pop3_total_body_size = %d", _pop3_received_body_size, _pop3_total_body_size);
+               EM_DEBUG_LOG_DEV("received_percentage = %d, last_notified_percentage = %d", received_percentage, last_notified_percentage);
 
                if (received_percentage > last_notified_percentage + 5) {
                        if (!emcore_notify_network_event(NOTI_DOWNLOAD_BODY_START, _pop3_receiving_mail_id, "dummy-file", _pop3_total_body_size, _pop3_received_body_size))
@@ -1990,9 +2039,9 @@ void emcore_mime_free_param(struct _parameter *param)
        EM_DEBUG_FUNC_BEGIN();
        while (p) {
                t = p->next;
-               EM_SAFE_FREE(p->name);
-               EM_SAFE_FREE(p->value);
-               free(p);p = NULL;
+               EM_SAFE_FREE (p->name);
+               EM_SAFE_FREE (p->value);
+               EM_SAFE_FREE (p);
                p = t;
        }
        EM_DEBUG_FUNC_END();
@@ -2002,14 +2051,16 @@ void emcore_mime_free_part_header(struct _m_part_header *header)
 {
        EM_DEBUG_FUNC_BEGIN();
        if (!header) return ;
-       EM_SAFE_FREE(header->type);
+       EM_SAFE_FREE (header->type);
        if (header->parameter) emcore_mime_free_param(header->parameter);
-       EM_SAFE_FREE(header->subtype);
-       EM_SAFE_FREE(header->encoding);
-       EM_SAFE_FREE(header->desc);
-       EM_SAFE_FREE(header->disp_type);
+       EM_SAFE_FREE (header->subtype);
+       EM_SAFE_FREE (header->encoding);
+       EM_SAFE_FREE (header->desc);
+       EM_SAFE_FREE (header->disp_type);
+       EM_SAFE_FREE (header->content_id);
+       EM_SAFE_FREE (header->content_location);
        if (header->disp_parameter) emcore_mime_free_param(header->disp_parameter);
-       free(header); header = NULL;
+       EM_SAFE_FREE (header);
        EM_DEBUG_FUNC_END();
 }
 
@@ -2017,9 +2068,9 @@ void emcore_mime_free_message_header(struct _m_mesg_header *header)
 {
        EM_DEBUG_FUNC_BEGIN();
        if (!header) return ;
-       EM_SAFE_FREE(header->version);
+       EM_SAFE_FREE (header->version);
        if (header->part_header) emcore_mime_free_part_header(header->part_header);
-       free(header); header = NULL;
+       EM_SAFE_FREE (header);
        EM_DEBUG_FUNC_END();
 }
 
@@ -2027,17 +2078,17 @@ void emcore_mime_free_rfc822_header(struct _rfc822header *header)
 {
        EM_DEBUG_FUNC_BEGIN();
        if (!header) return ;
-       EM_SAFE_FREE(header->return_path);
-       EM_SAFE_FREE(header->received);
-       EM_SAFE_FREE(header->reply_to);
-       EM_SAFE_FREE(header->date);
-       EM_SAFE_FREE(header->from);
-       EM_SAFE_FREE(header->subject);
-       EM_SAFE_FREE(header->sender);
-       EM_SAFE_FREE(header->to);
-       EM_SAFE_FREE(header->cc);
-       EM_SAFE_FREE(header->bcc);
-       free(header); header = NULL;
+       EM_SAFE_FREE (header->return_path);
+       EM_SAFE_FREE (header->received);
+       EM_SAFE_FREE (header->reply_to);
+       EM_SAFE_FREE (header->date);
+       EM_SAFE_FREE (header->from);
+       EM_SAFE_FREE (header->subject);
+       EM_SAFE_FREE (header->sender);
+       EM_SAFE_FREE (header->to);
+       EM_SAFE_FREE (header->cc);
+       EM_SAFE_FREE (header->bcc);
+       EM_SAFE_FREE (header);
        EM_DEBUG_FUNC_END();
 }
 
@@ -2049,7 +2100,7 @@ void emcore_mime_free_part_body(struct _m_body *body)
        EM_SAFE_FREE(body->text);
        if (body->nested.body) emcore_mime_free_part_body(body->nested.body);
        if (body->nested.next) emcore_mime_free_part(body->nested.next);
-       free(body); body = NULL;
+       EM_SAFE_FREE (body);
        EM_DEBUG_FUNC_END();
 }
 
@@ -2059,7 +2110,7 @@ void emcore_mime_free_part(struct _m_part *part)
        if (!part) return ;
        if (part->body) emcore_mime_free_part_body(part->body);
        if (part->next) emcore_mime_free_part(part->next);
-       free(part);part = NULL;
+       EM_SAFE_FREE (part);
        EM_DEBUG_FUNC_END();
 }
 
@@ -2073,7 +2124,7 @@ void emcore_mime_free_mime(struct _m_mesg *mmsg)
        if (mmsg->nested.body) emcore_mime_free_part_body(mmsg->nested.body);
        if (mmsg->nested.next) emcore_mime_free_part(mmsg->nested.next);
        EM_SAFE_FREE(mmsg->text);
-       free(mmsg); mmsg = NULL;
+       EM_SAFE_FREE (mmsg);
        EM_DEBUG_FUNC_END();
 }
 
@@ -2086,16 +2137,17 @@ void emcore_free_content_info(struct _m_content_info *cnt_info)
        EM_SAFE_FREE(cnt_info->text.plain);
        EM_SAFE_FREE(cnt_info->text.plain_charset);
        EM_SAFE_FREE(cnt_info->text.html);
+       EM_SAFE_FREE(cnt_info->text.html_charset);
        while (cnt_info->file) {
                p = cnt_info->file->next;
                EM_SAFE_FREE(cnt_info->file->name);
                EM_SAFE_FREE(cnt_info->file->save);
                EM_SAFE_FREE(cnt_info->file->attachment_mime_type);
                EM_SAFE_FREE(cnt_info->file->content_id);
-               free(cnt_info->file); cnt_info->file = NULL;
+               EM_SAFE_FREE(cnt_info->file); 
                cnt_info->file = p;
        }
-       free(cnt_info);cnt_info = NULL;
+
        EM_DEBUG_FUNC_END();
 }
 
@@ -2274,7 +2326,7 @@ PARTLIST* emcore_get_body_full(MAILSTREAM *stream, int msg_uid, BODY *body, stru
                                        EM_DEBUG_LOG("Encoding - %d  Section No - %s ", ai->encoding, ai->section);
 #endif
 
-                                       EM_DEBUG_LOG("Type[%d], Name[%s], Path[%s] ", ai->type, ai->name, ai->save);
+                                       EM_DEBUG_LOG_SEC("Type[%d], Name[%s], Path[%s] ", ai->type, ai->name, ai->save);
                                        if (body->type == TYPEAPPLICATION)  {
                                                if (!strcasecmp(body->subtype, MIME_SUBTYPE_DRM_OBJECT))
                                                        ai->drm = EMAIL_ATTACHMENT_DRM_OBJECT;
@@ -2452,6 +2504,12 @@ static int emcore_write_response_into_file(char *filename, char *write_mode, cha
 
                case ENCBASE64:
                        decoded = (char *)rfc822_base64((unsigned char *)encoded, encoded_len, &decoded_len);
+                       if (!decoded) {
+                               gsize dlen = 0;
+                               EM_DEBUG_LOG("rfc822_base64 decode failed");
+                               decoded = (char *)g_base64_decode(encoded, &dlen);
+                               decoded_len = (unsigned long)dlen;
+                       }
                        break;
 
                default:  {
@@ -2471,10 +2529,10 @@ static int emcore_write_response_into_file(char *filename, char *write_mode, cha
 
        if (decoded != NULL)  {
                EM_DEBUG_LOG("Decoded Length [%d] " , decoded_len);
-               EM_DEBUG_LOG("filename [%s] " , filename);
+               EM_DEBUG_LOG_SEC("filename [%s] " , filename);
 
                if (!(fp = fopen(filename, write_mode)))  {
-                       EM_DEBUG_EXCEPTION("fopen failed - %s", filename);
+                       EM_DEBUG_EXCEPTION_SEC("fopen failed - %s", filename);
                        error = EMAIL_ERROR_SYSTEM_FAILURE; /*prevent 28347*/
                        goto FINISH_OFF;
                }
@@ -2499,7 +2557,7 @@ static int emcore_write_response_into_file(char *filename, char *write_mode, cha
                                                memset(body_inline_id, 0x00, 512);
 
                                                if (body_inline->id && EM_SAFE_STRLEN(body_inline->id) > 0) { /*prevent 27454*/
-                                                       EM_DEBUG_LOG("body_inline->id - %s", body_inline->id);
+                                                       EM_DEBUG_LOG_SEC("body_inline->id - %s", body_inline->id);
                                                        EM_DEBUG_LOG("param - %p param1 - %p", param, param1);
                                                        decoded_content_id = strstr(decoded, "cid:");
 
@@ -2508,7 +2566,7 @@ static int emcore_write_response_into_file(char *filename, char *write_mode, cha
                                                        else
                                                                memcpy(body_inline_id, body_inline->id , EM_SAFE_STRLEN(body_inline->id));
 
-                                                       EM_DEBUG_LOG("Inline body_inline_id [%s]  ", body_inline_id);
+                                                       EM_DEBUG_LOG_SEC("Inline body_inline_id [%s]  ", body_inline_id);
 
                                                        if ((param || param1) && 0 == strncmp(body_inline_id , decoded_content_id + strlen("cid:"), EM_SAFE_STRLEN(body_inline_id))) {
                                                                EM_DEBUG_LOG(" Inline CID Found ");
@@ -2523,7 +2581,7 @@ static int emcore_write_response_into_file(char *filename, char *write_mode, cha
                                                                        /*  Content ID will be replaced with its file name in html */
                                                                        memcpy(html_cid_path, decoded_content_id , strlen("cid:") + EM_SAFE_STRLEN(body_inline_id));
 
-                                                                       EM_DEBUG_LOG("Replacing %s with %s ", html_cid_path, save_file_name);
+                                                                       EM_DEBUG_LOG_SEC("Replacing %s with %s ", html_cid_path, save_file_name);
                                                                        if ((decoded_temp = em_replace_string(decoded, html_cid_path, save_file_name))) {
                                                                                EM_SAFE_FREE(decoded);
                                                                                decoded = decoded_temp;
@@ -2594,7 +2652,7 @@ FINISH_OFF:
 }
 
 
-static BODY *emcore_select_body_structure_from_section_list(PARTLIST *section_list,  char *section)
+static BODY *emcore_select_body_structure_from_section_list(PARTLIST *section_list, char *section)
 {
        PARTLIST *temp = section_list;
        BODY *body = NULL;
@@ -2614,7 +2672,8 @@ static BODY *emcore_select_body_structure_from_section_list(PARTLIST *section_li
 static int imap_mail_write_body_to_file(MAILSTREAM *stream, int account_id, int mail_id, int is_attachment, char *filepath, int uid, char *section, int encoding, int *decoded_total, char *section_subtype, int *err_code)
 {
        EM_PROFILE_BEGIN(imapMailWriteBodyToFile);
-       EM_DEBUG_FUNC_BEGIN("stream[%p], filepath[%s], uid[%d], section[%s], encoding[%d], decoded_total[%p], err_code[%p]", stream, filepath, uid, section, encoding, decoded_total, err_code);
+       EM_DEBUG_FUNC_BEGIN_SEC("stream[%p], filepath[%s], uid[%d], section[%s], encoding[%d], decoded_total[%p], err_code[%p]",
+                       stream, filepath, uid, section, encoding, decoded_total, err_code);
 
        int ret = false;
        int err = EMAIL_ERROR_NONE;
@@ -2628,58 +2687,60 @@ static int imap_mail_write_body_to_file(MAILSTREAM *stream, int account_id, int
        char server_uid[129] = { 0, };
        char *filename = NULL;
        int server_response_yn = 0;
-       int write_flag = false;
        unsigned char encoded[DOWNLOAD_MAX_BUFFER_SIZE] = {0, };
        unsigned char test_buffer[LOCAL_MAX_BUFFER_SIZE] = {0, };
        int flag_first_write = true;
-
-       if (!stream || !filepath || !section)  {
-               EM_DEBUG_EXCEPTION("stream[%p], filepath[%s], uid[%d], section[%s], encoding[%d], decoded_total[%p]", stream, filepath, uid, section, encoding, decoded_total);
+       int preline_len = 0;
+       int nskip = 0;
+       char *concat_encoded = NULL;
+       char *new_response = NULL;
+       char *tag_position = NULL;
+
+       if (!stream || !filepath || !section) {
+               EM_DEBUG_EXCEPTION_SEC("stream[%p], filepath[%s], uid[%d], section[%s], encoding[%d], decoded_total[%p]",
+                               stream, filepath, uid, section, encoding, decoded_total);
                err = EMAIL_ERROR_INVALID_PARAM;
                goto FINISH_OFF;
        }
 
        FINISH_OFF_IF_CANCELED;
 
-       if (!(fp = fopen(filepath, "wb+")))  {
-               EM_DEBUG_EXCEPTION("fopen failed - %s", filepath);
-               err = EMAIL_ERROR_SYSTEM_FAILURE;               /* EMAIL_ERROR_UNKNOWN */
+       if (!(fp = fopen(filepath, "wb+"))) {
+               EM_DEBUG_EXCEPTION_SEC("fopen failed - %s", filepath);
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
                goto FINISH_OFF;
        }
 
        imaplocal = stream->local;
 
-       if (!imaplocal->netstream)  {
+       if (!imaplocal->netstream) {
                EM_DEBUG_EXCEPTION("invalid IMAP4 stream detected... %p", imaplocal->netstream);
                err = EMAIL_ERROR_INVALID_STREAM;
                goto FINISH_OFF;
        }
 
-       EM_DEBUG_LOG(" next_decode_string = false  ");
-       next_decode_string = false;
-
        memset(tag, 0x00, sizeof(tag));
        memset(command, 0x00, sizeof(command));
 
        SNPRINTF(tag, sizeof(tag), "%08lx", 0xffffffff & (stream->gensym++));
        SNPRINTF(command, sizeof(command), "%s UID FETCH %d BODY.PEEK[%s]\015\012", tag, uid, section);
-
        EM_DEBUG_LOG("[IMAP4] >>> [%s]", command);
 
-       /*  send command  :  get msgno/uid for all messag */
-       if (!net_sout(imaplocal->netstream, command, (int)EM_SAFE_STRLEN(command)))  {
+       /* send command : get msgno/uid for all message */
+       if (!net_sout(imaplocal->netstream, command, (int)EM_SAFE_STRLEN(command))) {
                EM_DEBUG_EXCEPTION("net_sout failed...");
                err = EMAIL_ERROR_CONNECTION_BROKEN;
                goto FINISH_OFF;
        }
 
-       while (imaplocal->netstream)  {
-               char *p = NULL;
-               char *s = NULL;
+       char *p_stream = NULL;
+       char *p_content = NULL;
 
-               if (!emcore_check_thread_status())  {
+       while (imaplocal->netstream) {
+
+               if (!emcore_check_thread_status()) {
                        EM_DEBUG_LOG("Canceled...");
-                       /*      Is it realy required ? It might cause crashes.
+                       /* Is it realy required ? It might cause crashes.
                        if (imaplocal->netstream)
                                net_close (imaplocal->netstream);
                        */
@@ -2688,8 +2749,8 @@ static int imap_mail_write_body_to_file(MAILSTREAM *stream, int account_id, int
                        goto FINISH_OFF;
                }
 
-               /*  receive respons */
-               if (!(response = net_getline(imaplocal->netstream)))  {
+               /* receive response */
+               if (!(response = net_getline(imaplocal->netstream))) {
                        EM_DEBUG_EXCEPTION("net_getline failed...");
                        err = EMAIL_ERROR_INVALID_RESPONSE;
                        goto FINISH_OFF;
@@ -2698,54 +2759,57 @@ static int imap_mail_write_body_to_file(MAILSTREAM *stream, int account_id, int
                EM_DEBUG_LOG("recv[%s]", response);
 #endif
 
-               write_flag = false;
-               if (response[0] == '*' && !server_response_yn)  {               /*  start of respons */
-
-                       if ((p = strstr(response, "BODY[")) /* || (p = strstr(s + 1, "BODY["))*/) {
+               /* start of response */
+               if (response[0] == '*' && !server_response_yn) {
+                       p_stream = strstr(response, "BODY[");
+                       if (p_stream) {
                                server_response_yn = 1;
-                               p += strlen("BODY[");
-                               s = p;
+                               p_stream += strlen("BODY[");
+                               p_content = p_stream;
 
-                               while (*s != ']')
-                                       s++;
+                               while (*p_content != ']')
+                                       p_content++;
 
-                               *s = '\0';
+                               *p_content = '\0';
 
-                               if (strcmp(section, p))  {
+                               /* check correct section */
+                               if (strcmp(section, p_stream)) {
+                                       EM_DEBUG_LOG("Invalid response of section");
                                        err = EMAIL_ERROR_INVALID_RESPONSE;
                                        goto FINISH_OFF;
                                }
 
-                               if ((p = strstr(s+1, " {")))  {
-                                       p += strlen(" {");
-                                       s = p;
+                               /* get body size */
+                               p_stream = strstr(p_content+1, " {");
+                               if (p_stream) {
+                                       p_stream += strlen(" {");
+                                       p_content = p_stream;
 
-                                       while (isdigit(*s))
-                                               s++;
+                                       while (isdigit(*p_content))
+                                               p_content++;
 
-                                       *s = '\0';
+                                       *p_content = '\0';
 
-                                       body_size = atoi(p);
-                               }
-                               else {  /*  no body length is replied */
-                                       if ((p = strstr(s+1, " \""))) { /*  seek the termination of double quot */
+                                       body_size = atoi(p_stream);
+                               } else {        /* no body length is replied */
+                                       /* seek the termination of double quot */
+                                       p_stream = strstr(p_content+1, " \"");
+                                       if (p_stream) {
                                                char *t = NULL;
-                                               p += strlen(" \"");
-                                               if ((t = strstr(p, "\""))) {
-                                                       body_size = t - p;
+                                               p_stream += strlen(" \"");
+                                               t = strstr(p_stream, "\"");
+                                               if (t) {
+                                                       body_size = t - p_stream;
                                                        *t = '\0';
-                                                       EM_DEBUG_LOG("Body  :  start[%p] end[%p]  :  body[%s]", p, t, p);
-                                                       /*  need to decod */
+                                                       EM_DEBUG_LOG("Body : start[%p] end[%p] : body[%s]", p_stream, t, p_stream);
+                                                       /* need to decode */
                                                        EM_SAFE_FREE(response);
-                                                       response = EM_SAFE_STRDUP(p);
-                                                       write_flag = true;
-                                               }
-                                               else {
+                                                       response = EM_SAFE_STRDUP(p_stream);
+                                               } else {
                                                        err = EMAIL_ERROR_INVALID_RESPONSE;
                                                        goto FINISH_OFF;
                                                }
-                                       }
-                                       else {
+                                       } else {
                                                err = EMAIL_ERROR_INVALID_RESPONSE;
                                                goto FINISH_OFF;
                                        }
@@ -2759,47 +2823,86 @@ static int imap_mail_write_body_to_file(MAILSTREAM *stream, int account_id, int
                                parse_file_path_to_filename(filepath, &file_id);
 
                                filename = file_id;
-                               sprintf(server_uid, "%d", uid);
+                               snprintf(server_uid, sizeof(server_uid), "%d", uid);
 
-                               EM_DEBUG_LOG("file_id [%s]", file_id);
-                               EM_DEBUG_LOG("filename [%p]-[%s]", filename, filename);
+                               EM_DEBUG_LOG_SEC("file_id [%s]", file_id);
+                               EM_DEBUG_LOG_SEC("filename [%p]-[%s]", filename, filename);
                                EM_DEBUG_LOG("body_size [%d]", body_size);
                                EM_DEBUG_LOG("server_uid [%s]", server_uid);
                                EM_DEBUG_LOG("mail_id [%d]", mail_id);
 
+                               if (!emcore_check_thread_status()) {
+                                       EM_DEBUG_LOG("Canceled...");
+                                       imaplocal->netstream = NULL;
+                                       err = EMAIL_ERROR_CANCELLED;
+                                       goto FINISH_OFF;
+                               }
+
                                if (is_attachment) {
                                        EM_DEBUG_LOG("Attachment number [%d]", is_attachment);
                                        if (!emcore_notify_network_event(NOTI_DOWNLOAD_ATTACH_START, mail_id, filename, is_attachment, 0))
-                                               EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_ATTACH_START] Failed >>>> ");
-                                       _imap4_download_noti_interval_value =  body_size *DOWNLOAD_NOTI_INTERVAL_PERCENT / 100;
+                                               EM_DEBUG_EXCEPTION("emcore_notify_network_event [ NOTI_DOWNLOAD_ATTACH_START] Failed >>>>");
+                                       _imap4_download_noti_interval_value = body_size * DOWNLOAD_NOTI_INTERVAL_PERCENT / 100;
                                        _imap4_total_body_size = body_size;
-                               }
-                               else {
+                               } else {
                                        if (multi_part_body_size) {
                                                EM_DEBUG_LOG("Multipart body size is [%d]", multi_part_body_size);
                                                if (!emcore_notify_network_event(NOTI_DOWNLOAD_MULTIPART_BODY, mail_id, filename, multi_part_body_size, 0))
-                                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_BODY_START] Failed >>>> ");
-                                               _imap4_download_noti_interval_value =  multi_part_body_size *DOWNLOAD_NOTI_INTERVAL_PERCENT / 100;
+                                                       EM_DEBUG_EXCEPTION("emcore_notify_network_event [ NOTI_DOWNLOAD_BODY_START] Failed >>>>");
+                                               _imap4_download_noti_interval_value =  multi_part_body_size * DOWNLOAD_NOTI_INTERVAL_PERCENT / 100;
                                                /*  _imap4_total_body_size should be set before calling this functio */
                                                /* _imap4_total_body_size */
-                                       }
-                                       else {
+                                       } else {
                                                if (!emcore_notify_network_event(NOTI_DOWNLOAD_BODY_START, mail_id, filename, body_size, 0))
-                                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_BODY_START] Failed >>>>");
-                                               _imap4_download_noti_interval_value =  body_size *DOWNLOAD_NOTI_INTERVAL_PERCENT / 100;
+                                                       EM_DEBUG_EXCEPTION("emcore_notify_network_event [ NOTI_DOWNLOAD_BODY_START] Failed >>>>");
+                                               _imap4_download_noti_interval_value =  body_size * DOWNLOAD_NOTI_INTERVAL_PERCENT / 100;
                                                _imap4_total_body_size = body_size;
                                        }
                                }
+
                                if (_imap4_download_noti_interval_value > DOWNLOAD_NOTI_INTERVAL_SIZE) {
                                        _imap4_download_noti_interval_value = DOWNLOAD_NOTI_INTERVAL_SIZE;
                                }
-                               if (body_size < DOWNLOAD_MAX_BUFFER_SIZE) {
-                                       if (net_getbuffer (imaplocal->netstream, (long)body_size, (char *)encoded) <= 0) {
+
+                               /* remove new lines */
+                               do {
+                                       EM_SAFE_FREE(response);
+                                       if (!(response = net_getline(imaplocal->netstream))) {
+                                               EM_DEBUG_EXCEPTION("net_getline failed...");
+                                               err = EMAIL_ERROR_INVALID_RESPONSE;
+                                               goto FINISH_OFF;
+                                       }
+
+                                       EM_DEBUG_LOG("response:%s", response);
+                                       if (EM_SAFE_STRLEN(response) == 0) {
+                                               EM_DEBUG_LOG("Skip newline !!");
+                                               nskip++;
+                                       } else {
+                                               new_response = g_strconcat(response, "\r\n", NULL);
+                                               EM_SAFE_FREE(response);
+                                               break;
+                                       }
+                               } while(1);
+
+                               preline_len = EM_SAFE_STRLEN(new_response);
+                               EM_DEBUG_LOG("preline_len : %d", preline_len);
+
+                               if (body_size - preline_len - nskip*2 <= 0)
+                                       continue;
+
+                               if (body_size - preline_len - nskip*2 < DOWNLOAD_MAX_BUFFER_SIZE) {
+                                       memset(encoded, 0x00, sizeof(encoded));
+                                       if (net_getbuffer(imaplocal->netstream, body_size - preline_len - nskip*2, (char *)encoded) <= 0) {
                                                EM_DEBUG_EXCEPTION("net_getbuffer failed...");
                                                err = EMAIL_ERROR_NO_RESPONSE;
                                                goto FINISH_OFF;
                                        }
 
+                                       concat_encoded = g_strconcat(new_response, encoded, NULL);
+                                       memset(encoded, 0x00, sizeof(encoded));
+                                       memcpy(encoded, concat_encoded, EM_SAFE_STRLEN(concat_encoded));
+                                       EM_SAFE_FREE(concat_encoded);
+                                       EM_SAFE_FREE(new_response);
                                        if (!emcore_write_response_into_file(filepath, "wb+", (char *)encoded, encoding, section_subtype, account_id, mail_id, &err)) {
                                                EM_DEBUG_EXCEPTION("write_response_into_file failed [%d]", err);
                                                goto FINISH_OFF;
@@ -2807,142 +2910,142 @@ static int imap_mail_write_body_to_file(MAILSTREAM *stream, int account_id, int
 
                                        total = EM_SAFE_STRLEN((char *)encoded);
                                        EM_DEBUG_LOG("total = %d", total);
-                                       EM_DEBUG_LOG("write_response_into_file successful %s.....", filename);
-
-                                       if (((_imap4_last_notified_body_size  + _imap4_download_noti_interval_value) <=  _imap4_received_body_size)
-                                                               || (_imap4_received_body_size >= _imap4_total_body_size))               /*  100  */ {
-                                               /*  In some situation, total_encoded_len includes the length of dummy bytes. So it might be greater than body_size */
-                                               int gap = 0;
-                                               if (total > body_size)
-                                                       gap = total - body_size;
-                                               _imap4_received_body_size -= gap;
-                                               _imap4_last_notified_body_size = _imap4_received_body_size;
-
-                                               if(body_size > 0)
-                                                       EM_DEBUG_LOG("DOWNLOADING STATUS NOTIFY  :  Encoded[%d] / [%d] = %d %% Completed. -- Total Decoded[%d]", total, body_size, 100*total/body_size, total);
-
-                                               if(_imap4_total_body_size > 0)
-                                                       EM_DEBUG_LOG("DOWNLOADING STATUS NOTIFY  :  Total[%d] / [%d] = %d %% Completed.", _imap4_received_body_size, _imap4_total_body_size, 100*_imap4_received_body_size/_imap4_total_body_size);
-
-                                               if (is_attachment) {
-                                                       if (_imap4_total_body_size && !emcore_notify_network_event(NOTI_DOWNLOAD_ATTACH_START, mail_id, filename, is_attachment, 100 *_imap4_received_body_size / _imap4_total_body_size))
-                                                               EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_ATTACH_START] Failed >>>> ");
+                                       EM_DEBUG_LOG_SEC("write_response_into_file successful %s.....", filename);
+
+                                       /*  In some situation, total_encoded_len includes the length of dummy bytes. So it might be greater than body_size */
+
+                                       _imap4_received_body_size += total;
+                                       _imap4_last_notified_body_size = _imap4_received_body_size;
+
+                                       EM_DEBUG_LOG("DOWNLOADING STATUS NOTIFY : received_body[%d] / total_body[%d] = %d %% Completed.",
+                                                       _imap4_received_body_size, _imap4_total_body_size, 100*_imap4_received_body_size/_imap4_total_body_size);
+
+                                       if (is_attachment) {
+                                               if (_imap4_total_body_size && !emcore_notify_network_event(NOTI_DOWNLOAD_ATTACH_START, mail_id, filename, is_attachment, 100 *total/body_size))
+                                                       EM_DEBUG_EXCEPTION("emcore_notify_network_event [ NOTI_DOWNLOAD_ATTACH_START] Failed >>>>");
+                                       } else {
+                                               if (multi_part_body_size) {
+                                                       if (!emcore_notify_network_event(NOTI_DOWNLOAD_MULTIPART_BODY, mail_id, filename, _imap4_total_body_size, _imap4_received_body_size))
+                                                               EM_DEBUG_EXCEPTION("emcore_notify_network_event [ NOTI_DOWNLOAD_BODY_START] Failed >>>>");
+                                               } else {
+                                                       if (!emcore_notify_network_event(NOTI_DOWNLOAD_BODY_START, mail_id, filename, _imap4_total_body_size, _imap4_received_body_size))
+                                                               EM_DEBUG_EXCEPTION("emcore_notify_network_event [ NOTI_DOWNLOAD_BODY_START] Failed >>>>");
                                                }
-                                               else {
-                                                       if (multi_part_body_size) {
-                                                               if (!emcore_notify_network_event(NOTI_DOWNLOAD_MULTIPART_BODY, mail_id, filename, _imap4_total_body_size, _imap4_received_body_size))
-                                                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_BODY_START] Failed >>>> ");
-                                                       }
-                                                       else {
-                                                               if (!emcore_notify_network_event(NOTI_DOWNLOAD_BODY_START, mail_id, filename, _imap4_total_body_size, _imap4_received_body_size))
-                                                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_BODY_START] Failed >>>>");
-                                                       }
-                                               }       /*  if (is_attachment) .. else .. */
                                        }
-                               }
-                               else {
-                                       int temp_body_size = body_size;
+                               } else {
+                                       int remain_body_size = body_size - preline_len - nskip*2;
                                        int x = 0;
-
-                                       if (encoding == ENCBASE64)
-                                               x = (sizeof(encoded)/78) *78; /*  to solve base64 decoding pro */
-                                       else
-                                               x = sizeof(encoded)-1;
+                                       int nsize = 0;
+                                       total += preline_len + nskip*2;
+                                       _imap4_received_body_size += preline_len + nskip*2;
 
                                        memset(test_buffer, 0x00, sizeof(test_buffer));
-                                       while (temp_body_size && (total <body_size)) {
+
+                                       while (remain_body_size > 0 && (total < body_size)) {
 
                                                memset(test_buffer, 0x00, sizeof(test_buffer));
-                                               while ((total != body_size) && temp_body_size && ((EM_SAFE_STRLEN((char *)test_buffer) + x) < sizeof(test_buffer))) {
+
+                                               if (encoding == ENCBASE64)
+                                                       x = (sizeof(encoded)/preline_len)*preline_len; /* to solve base64 decoding pro */
+                                               else
+                                                       x = sizeof(encoded)-1;
+
+                                               if (new_response) {
+                                                       strncat((char *)test_buffer, (char *)new_response, preline_len);
+                                                       EM_SAFE_FREE(new_response);
+                                               }
+
+                                               while (remain_body_size > 0 && (total < body_size) && ((EM_SAFE_STRLEN((char *)test_buffer) + x) < sizeof(test_buffer))) {
+
                                                        memset(encoded, 0x00, sizeof(encoded));
 
-                                                       if (net_getbuffer (imaplocal->netstream, (long)x, (char *)encoded) <= 0) {
+                                                       if (net_getbuffer(imaplocal->netstream, (long)x, (char *)encoded) <= 0) {
                                                                EM_DEBUG_EXCEPTION("net_getbuffer failed...");
                                                                err = EMAIL_ERROR_NO_RESPONSE;
                                                                goto FINISH_OFF;
                                                        }
 
-                                                       temp_body_size = temp_body_size - x;
-                                                       strncat((char *)test_buffer, (char *)encoded, EM_SAFE_STRLEN((char *)encoded));
-                                                       total = total + x;
-                                                       _imap4_received_body_size += EM_SAFE_STRLEN((char *)encoded);
-
-                                                       if ( !(temp_body_size/x) && temp_body_size%x)
-                                                               x = temp_body_size%x;
-
-                                                       if (((_imap4_last_notified_body_size  + _imap4_download_noti_interval_value) <=  _imap4_received_body_size)
-                                                               || (_imap4_received_body_size >= _imap4_total_body_size))               /*  100  */ {
-                                                               /*  In some situation, total_encoded_len includes the length of dummy bytes. So it might be greater than body_size */
-                                                               int gap = 0;
+                                                       nsize = EM_SAFE_STRLEN((char *)encoded);
+                                                       remain_body_size = remain_body_size - nsize;
+                                                       strncat((char *)test_buffer, (char *)encoded, nsize);
+                                                       total = total + nsize;
+                                                       _imap4_received_body_size += nsize;
+                                                       EM_DEBUG_LOG("nsize : %d", nsize);
+                                                       EM_DEBUG_LOG("remain_body_size : %d", remain_body_size);
+                                                       EM_DEBUG_LOG("total : %d", total);
+                                                       EM_DEBUG_LOG("imap_received_body_size : %d", _imap4_received_body_size);
+
+                                                       if (!(remain_body_size/x) && remain_body_size%x)
+                                                               x = remain_body_size%x;
+
+                                                       /* notify event every 5% increase */
+                                                       if (((_imap4_last_notified_body_size + _imap4_download_noti_interval_value) <= _imap4_received_body_size)
+                                                               || (_imap4_received_body_size >= _imap4_total_body_size)) {
+
+                                                               /*  In some situation, total_encoded_len includes the length of dummy bytes.
+                                                                * So it might be greater than body_size */
                                                                if (total > body_size)
-                                                                       gap = total - body_size;
-                                                               _imap4_received_body_size -= gap;
+                                                                       _imap4_received_body_size = body_size;
+
                                                                _imap4_last_notified_body_size = _imap4_received_body_size;
 
-                                                               /* EM_DEBUG_LOG("DOWNLOADING STATUS NOTIFY  :  Encoded[%d] / [%d] = %d %% Completed. -- Total Decoded[%d]", total, body_size, 100*total/body_size, total) */
-                                                               EM_DEBUG_LOG("DOWNLOADING STATUS NOTIFY  :  Total[%d] / [%d] = %d %% Completed.", _imap4_received_body_size, _imap4_total_body_size, 100*_imap4_received_body_size/_imap4_total_body_size);
+                                                               if (!emcore_check_thread_status()) {
+                                                                       EM_DEBUG_LOG("Canceled...");
+                                                                       imaplocal->netstream = NULL;
+                                                                       err = EMAIL_ERROR_CANCELLED;
+                                                                       goto FINISH_OFF;
+                                                               }
+
+                                                               EM_DEBUG_LOG("DOWNLOADING STATUS NOTIFY : Total[%d] / [%d] = %d %% Completed.\n", total, body_size, 100*total/body_size);
 
                                                                if (is_attachment) {
-                                                                       if (!emcore_notify_network_event(NOTI_DOWNLOAD_ATTACH_START, mail_id, filename, is_attachment, 100 *_imap4_received_body_size / _imap4_total_body_size))
-                                                                               EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_ATTACH_START] Failed >>>> ");
-                                                               }
-                                                               else {
+                                                                       if (!emcore_notify_network_event(NOTI_DOWNLOAD_ATTACH_START, mail_id, filename, is_attachment, 100*total/body_size))
+                                                                               EM_DEBUG_EXCEPTION("emcore_notify_network_event [ NOTI_DOWNLOAD_ATTACH_START] Failed >>>>");
+                                                               } else {
                                                                        if (multi_part_body_size) {
                                                                                /* EM_DEBUG_LOG("DOWNLOADING..........  :  Multipart body size is [%d]", multi_part_body_size) */
                                                                        if (!emcore_notify_network_event(NOTI_DOWNLOAD_MULTIPART_BODY, mail_id, filename, _imap4_total_body_size, _imap4_received_body_size))
-                                                                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_BODY_START] Failed >>>> ");
-                                                                       }
-                                                                       else {
+                                                                                       EM_DEBUG_EXCEPTION("emcore_notify_network_event [ NOTI_DOWNLOAD_BODY_START] Failed >>>>");
+                                                                       } else {
                                                                                if (!emcore_notify_network_event(NOTI_DOWNLOAD_BODY_START, mail_id, filename, _imap4_total_body_size, _imap4_received_body_size))
-                                                                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_BODY_START] Failed >>>>");
+                                                                                       EM_DEBUG_EXCEPTION("emcore_notify_network_event [ NOTI_DOWNLOAD_BODY_START] Failed >>>>");
                                                                        }
-                                                               }       /*  if (is_attachment) .. else .. */
+                                                               }
                                                        }
+                                               }
 
-
-               }
-
-                                                       if (flag_first_write == true) {
-                                                               if (!emcore_write_response_into_file(filepath, "wb+", (char *)test_buffer, encoding, section_subtype, account_id, mail_id, &err)) {
-                                                                       EM_DEBUG_EXCEPTION("write_response_into_file %s failed [%d]", filepath, err);
-                                                                       goto FINISH_OFF;
-                                                               }
-                                                               flag_first_write = false;
+                                               if (flag_first_write == true) {
+                                                       if (!emcore_write_response_into_file(filepath, "wb+", (char *)test_buffer, encoding, section_subtype, account_id, mail_id, &err)) {
+                                                               EM_DEBUG_EXCEPTION_SEC("write_response_into_file %s failed [%d]", filepath, err);
+                                                               goto FINISH_OFF;
                                                        }
-                                                       else {
-                                                               if (!emcore_write_response_into_file(filepath, "ab+", (char *)test_buffer, encoding, section_subtype, account_id, mail_id, &err)) /*  append */ {
-                                                                       EM_DEBUG_EXCEPTION("write_response_into_file %s failed [%d]", filepath, err);
-                                                                       goto FINISH_OFF;
-                                                               }
+                                                       flag_first_write = false;
+                                               } else {
+                                                       if (!emcore_write_response_into_file(filepath, "ab+", (char *)test_buffer, encoding, section_subtype, account_id, mail_id, &err)) /*  append */ {
+                                                               EM_DEBUG_EXCEPTION_SEC("write_response_into_file %s failed [%d]", filepath, err);
+                                                               goto FINISH_OFF;
                                                        }
-                                                       EM_DEBUG_LOG("%d has been written", EM_SAFE_STRLEN((char *)test_buffer));
-                                                       /*  notif */
                                                }
+                                               EM_DEBUG_LOG("%d has been written", EM_SAFE_STRLEN((char *)test_buffer));
+                                       }
                                }
-
-                       }
-                       else  {
+                       } else {
                                err = EMAIL_ERROR_INVALID_RESPONSE;
                                goto FINISH_OFF;
                        }
-
                }
-               else if (!strncmp(response, tag, EM_SAFE_STRLEN(tag)))  {               /*  end of respons */
-                       if (!strncmp(response + EM_SAFE_STRLEN(tag) + 1, "OK", 2))  {
+               else if ((tag_position = g_strrstr(response, tag))) /*  end of response */ {
+                       if (!strncmp(tag_position + EM_SAFE_STRLEN(tag) + 1, "OK", 2)) {
                                EM_SAFE_FREE(response);
-                       }
-                       else  {         /*  'NO' or 'BAD */
+                       } else  {               /* 'NO' or 'BAD */
                                err = EMAIL_ERROR_IMAP4_FETCH_UID_FAILURE;
                                goto FINISH_OFF;
                        }
-
                        break;
                }
-               else if (!strcmp(response, ")"))  {
-                       /*  The end of response which contains body informatio */
-                       write_flag = false;
+               else if (!strcmp(response, ")")) {
+                       /*  The end of response which contains body information */
                }
-
        }       /*  while (imaplocal->netstream)  */
 
        if (decoded_total != NULL)
@@ -2957,7 +3060,7 @@ FINISH_OFF:
        if (fp != NULL)
                fclose(fp);
 
-       if (ret == false) {     /*  delete temp fil */
+       if (ret == false) {     /* delete temp file */
                struct stat temp_file_stat;
                if (filepath &&  stat(filepath, &temp_file_stat) == 0)
                        remove(filepath);
@@ -2976,27 +3079,29 @@ static int emcore_get_body_part_imap_full(MAILSTREAM *stream, int msg_uid, int a
        EM_DEBUG_FUNC_BEGIN("stream[%p], msg_uid[%d], body[%p], cnt_info[%p], err_code[%p]", stream, msg_uid, section_list, cnt_info, err_code);
 
        int err = EMAIL_ERROR_NONE;
-       char sections[IMAP_MAX_COMMAND_LENGTH] = { 0, };
+       char sections[IMAP_MAX_COMMAND_LENGTH] = {0,};
        IMAPLOCAL *imaplocal = NULL;
-       char tag[16] = { 0, }, command[IMAP_MAX_COMMAND_LENGTH] = { 0, };
-       char section[16] = {0};
+       char tag[16] = {0,};
+       char command[IMAP_MAX_COMMAND_LENGTH] = {0,};
+       char section[16] = {0,};
        char *response = NULL;
        BODY *body = NULL;
        int server_response_yn = 0;
        int body_size = 0;
        char *buf = NULL;
-       char filename[512] = {0, };
-       int return_value = 0 ;
+       char filename[512] = {0,};
+       int return_value = 0;
        int encoding = 0;
-       unsigned char encoded[DOWNLOAD_MAX_BUFFER_SIZE] = {0};
-       unsigned char test_buffer[LOCAL_MAX_BUFFER_SIZE] = {0};
+       unsigned char encoded[DOWNLOAD_MAX_BUFFER_SIZE] = {0,};
+       unsigned char test_buffer[LOCAL_MAX_BUFFER_SIZE] = {0,};
        struct attachment_info *ai = NULL;
        int i = 0;
        int total = 0;
        int flag_first_write = 1;
-       int imap4_total_body_download_progress = 0, progress = 0;
+       int imap4_total_body_download_progress = 0;
+       char *tag_position = NULL;
 
-       if (!(imaplocal = stream->local) || !imaplocal->netstream || !section_list || !cnt_info)  {
+       if (!(imaplocal = stream->local) || !imaplocal->netstream || !section_list || !cnt_info) {
                EM_DEBUG_EXCEPTION("invalid IMAP4 stream detected...");
                err = EMAIL_ERROR_INVALID_PARAM;
                return_value = -1;
@@ -3011,70 +3116,62 @@ static int emcore_get_body_part_imap_full(MAILSTREAM *stream, int msg_uid, int a
                        body = temp->body;
                        if (body->sparep != NULL)  {
                                snprintf(sections, sizeof(sections), "BODY.PEEK[%s]", (char *)body->sparep);
-                       }
-                       else {
+                       } else {
                                EM_DEBUG_EXCEPTION("body->sparep can not be null. ");
                                return_value = -1;
                                goto FINISH_OFF;
-
                        }
-               }
-               else {
+               } else {
                        while (temp != NULL) {
-                               char t[64] = {0};
+                               char t[64] = {0,};
                                body = temp->body;
 
-                               if ((body->type == TYPETEXT)  || (body->id != NULL) || ((body->disposition.type != NULL) && ((body->disposition.type[0] == 'i') || (body->disposition.type[0] == 'I')))) {
-                                       snprintf(t, sizeof(t), "BODY.PEEK[%s] ", (char *)body->sparep);         /*  body parts seperated by period */
-                                       strcat(sections, t);
+                               if ((body->type == TYPETEXT) || (body->id != NULL) || ((body->disposition.type != NULL) && ((body->disposition.type[0] == 'i') || (body->disposition.type[0] == 'I')))) {
+                                       snprintf(t, sizeof(t), "BODY.PEEK[%s] ", (char *)body->sparep);         /* body parts seperated by period */
+                                       if (EM_SAFE_STRLEN(sections) + EM_SAFE_STRLEN(t) < sizeof(sections))
+                                               strcat(sections, t);
+                                       else {
+                                               EM_DEBUG_EXCEPTION("Too many body parts. IMAP command may cross 2000bytes.");
+                                               break;
+                                       }
                                }
                                temp = (PARTLIST *)temp->next;
                        }
                }
        }
 
-       if ((EM_SAFE_STRLEN(sections) == (sizeof(sections)-1)) || (EM_SAFE_STRLEN(sections) == 0)) {
-                       EM_DEBUG_EXCEPTION(" Too many body parts or nil. IMAP command may cross 1000bytes.");
-                       return_value = -1;
-                       goto FINISH_OFF;
-               }
-
        if (sections[EM_SAFE_STRLEN(sections)-1] == ' ') {
                sections[EM_SAFE_STRLEN(sections)-1] = '\0';
        }
 
        EM_DEBUG_LOG("sections <%s>", sections);
-
        SNPRINTF(tag, sizeof(tag), "%08lx", 0xffffffff & (stream->gensym++));
        SNPRINTF(command, sizeof(command), "%s UID FETCH %d (%s)\015\012", tag, msg_uid, sections);
-       EM_DEBUG_LOG("command %s", command);
-
-       if (EM_SAFE_STRLEN(command) == (sizeof(command)-1)) {
-               EM_DEBUG_EXCEPTION("Too many body parts. IMAP command will fail.");
-               return_value = -1;
-               goto FINISH_OFF;
-       }
+       EM_DEBUG_LOG("command <%s>", command);
 
-       /*  send command  :  get msgno/uid for all message */
-       if (!net_sout(imaplocal->netstream, command, (int)EM_SAFE_STRLEN(command)))  {
+       /* send command : get msgno/uid for all message */
+       if (!net_sout(imaplocal->netstream, command, (int)EM_SAFE_STRLEN(command))) {
                EM_DEBUG_EXCEPTION("net_sout failed...");
                err = EMAIL_ERROR_CONNECTION_BROKEN;
                return_value = -1;
                goto FINISH_OFF;
        }
-       while (imaplocal->netstream)  {
 
-               /*  receive respons */
-               if (!(response = net_getline(imaplocal->netstream)))  {
+       while (imaplocal->netstream) {
+
+               /*  receive response */
+               if (!(response = net_getline(imaplocal->netstream))) {
                        EM_DEBUG_EXCEPTION("net_getline failed...");
                        err = EMAIL_ERROR_INVALID_RESPONSE;
                        return_value = -1;
                        goto FINISH_OFF;
                }
 
+               EM_DEBUG_LOG("response :%s", response);
+
                if (strstr(response, "BODY[")) {
 
-                       if (!server_response_yn)                /*  start of response */ {
+                       if (!server_response_yn) { /* start of response */
                                if (response[0] != '*') {
                                        err = EMAIL_ERROR_INVALID_RESPONSE;
                                        EM_DEBUG_EXCEPTION("Start of response doesn't contain *");
@@ -3088,15 +3185,15 @@ static int emcore_get_body_part_imap_full(MAILSTREAM *stream, int msg_uid, int a
                        total = 0;
                        memset(encoded, 0x00, sizeof(encoded));
 
-                       if (emcore_get_section_body_size(response, section, &body_size)<0) {
+                       if (emcore_get_section_body_size(response, section, &body_size) < 0) {
                                EM_DEBUG_EXCEPTION("emcore_get_section_body_size failed [%d]", err);
                                err = EMAIL_ERROR_INVALID_RESPONSE;
                                return_value = -1;
                                goto FINISH_OFF;
                        }
-                       EM_DEBUG_LOG("body_size-%d", body_size);
+                       EM_DEBUG_LOG("section :%s, body_size :%d", section, body_size);
 
-                       /*  get body from seciton_list */
+                       /* get body from seciton_list */
                        if ((body = emcore_select_body_structure_from_section_list(section_list, section)) == NULL) {
                                EM_DEBUG_EXCEPTION("emcore_select_body_structure_from_section_list failed [%d]", err);
                                err = EMAIL_ERROR_INVALID_RESPONSE;
@@ -3110,15 +3207,15 @@ static int emcore_get_body_part_imap_full(MAILSTREAM *stream, int msg_uid, int a
                                goto FINISH_OFF;
                        }*/
 
-                       if (!emcore_get_temp_file_name(&buf, &err))  {
+                       if (!emcore_get_temp_file_name(&buf, &err)) {
                                EM_DEBUG_EXCEPTION("emcore_get_temp_file_name failed [%d]", err);
                                goto FINISH_OFF;
                        }
 
-                       EM_DEBUG_LOG("buf :  %s", buf);
+                       EM_DEBUG_LOG("temp filename :%s", buf);
 
                        /*  notifying UI start */
-                       /*  parse_file_path_to_filename(buf, &file_id);                 */
+                       /*  parse_file_path_to_filename(buf, &file_id);            */
                        /*  EM_DEBUG_LOG(">>>> filename - %p >>>>>>", file_id) */
 
                        if (body->type == TYPETEXT && body->subtype && (!body->disposition.type || (body->disposition.type && (body->disposition.type[0] == 'i' || body->disposition.type[0] == 'I')))) {
@@ -3128,20 +3225,18 @@ static int emcore_get_body_part_imap_full(MAILSTREAM *stream, int msg_uid, int a
                                        cnt_info->text.plain = buf;
 
                                PARAMETER *param = NULL;
-
                                param = body->parameter;
 
-                               while (param)  {
-                                       if (!strcasecmp(param->attribute, "CHARSET"))  {
+                               while (param) {
+                                       if (!strcasecmp(param->attribute, "CHARSET")) {
                                                cnt_info->text.plain_charset = EM_SAFE_STRDUP(param->value);
                                                break;
                                        }
                                        param = param->next;
                                }
-                       }
-                       else if (body->subtype && (body->id || body->location || body->disposition.type)) { /*prevent 23712*/ /*refactoring : body->subtype*/
+                       } else if (body->subtype && (body->id || body->location || body->disposition.type)) { /*prevent 23712*/ /*refactoring : body->subtype*/
 
-                               if (emcore_get_file_pointer(body, false, filename, cnt_info , &err)<0) {
+                               if (emcore_get_file_pointer(body, false, filename, cnt_info , &err) < 0) {
                                        EM_DEBUG_EXCEPTION("emcore_get_file_pointer failed [%d]", err);
                                        goto FINISH_OFF;
                                }
@@ -3149,12 +3244,12 @@ static int emcore_get_body_part_imap_full(MAILSTREAM *stream, int msg_uid, int a
                                /* Search info from attachment list followed by inline attachment list */
 
                                ai = cnt_info->file;
-                               EM_DEBUG_LOG("ai - %p ", (ai));
+                               EM_DEBUG_LOG("ai - %p", (ai));
 
                                /* For Inline content append to the end */
                                for (i = 1; ai; ai = ai->next, i++) {
                                        if (ai->save == NULL && (ai->content_id != NULL && EM_SAFE_STRCMP(ai->content_id, body->id) == 0)) {
-                                               EM_DEBUG_LOG("Found matching details ");
+                                               EM_DEBUG_LOG("Found matching details");
                                                ai->save = buf;
                                                break;
                                        }
@@ -3165,27 +3260,24 @@ static int emcore_get_body_part_imap_full(MAILSTREAM *stream, int msg_uid, int a
 
                        if (cnt_info->grab_type == GRAB_TYPE_ATTACHMENT) {
                                if (!emcore_notify_network_event(NOTI_DOWNLOAD_ATTACH_START, mail_id, buf, cnt_info->file_no, 0))
-                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_ATTACH_START] Failed >>>> ");
+                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [NOTI_DOWNLOAD_ATTACH_START] Failed >>>>");
 
-                               _imap4_download_noti_interval_value =  body_size *DOWNLOAD_NOTI_INTERVAL_PERCENT / 100;
+                               _imap4_download_noti_interval_value =  body_size * DOWNLOAD_NOTI_INTERVAL_PERCENT / 100;
                                _imap4_total_body_size = body_size;
-                       }
-                       else {
+                       } else {
                                if (multi_part_body_size) {
                                        EM_DEBUG_LOG("Multipart body size is [%d]", multi_part_body_size);
                                        if (!emcore_notify_network_event(NOTI_DOWNLOAD_MULTIPART_BODY, mail_id, buf, multi_part_body_size, 0))
                                                EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_BODY_START] Failed >>>> ");
 
-                                       _imap4_download_noti_interval_value =  multi_part_body_size *DOWNLOAD_NOTI_INTERVAL_PERCENT / 100;
-                               }
-                               else {
+                                       _imap4_download_noti_interval_value =  multi_part_body_size * DOWNLOAD_NOTI_INTERVAL_PERCENT / 100;
+                               } else {
                                        if (!emcore_notify_network_event(NOTI_DOWNLOAD_BODY_START, mail_id, buf, body_size, 0))
                                                EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_BODY_START] Failed >>>> ");
 
-                                       _imap4_download_noti_interval_value =  body_size *DOWNLOAD_NOTI_INTERVAL_PERCENT / 100;
+                                       _imap4_download_noti_interval_value =  body_size * DOWNLOAD_NOTI_INTERVAL_PERCENT / 100;
                                        _imap4_total_body_size = body_size;
                                }
-
                        }
 
                        if (_imap4_download_noti_interval_value > DOWNLOAD_NOTI_INTERVAL_SIZE) {
@@ -3196,75 +3288,60 @@ static int emcore_get_body_part_imap_full(MAILSTREAM *stream, int msg_uid, int a
                        /* notifying UI end */
 
                        if (body_size < DOWNLOAD_MAX_BUFFER_SIZE) {
-                               if (net_getbuffer (imaplocal->netstream, (long)body_size, (char *)encoded) <= 0) {
+                               if (net_getbuffer(imaplocal->netstream, (long)body_size, (char *)encoded) <= 0) {
                                        EM_DEBUG_EXCEPTION("net_getbuffer failed...");
                                        err = EMAIL_ERROR_NO_RESPONSE;
                                        return_value = -1;
                                        goto FINISH_OFF;
                                }
+
                                if (!emcore_write_response_into_file(buf, "wb+", (char *)encoded, encoding, body->subtype, account_id, mail_id, &err)) {
                                        EM_DEBUG_EXCEPTION("write_response_into_file failed [%d]", err);
                                        return_value = -1;
                                        goto FINISH_OFF;
                                }
 
+                               total = EM_SAFE_STRLEN((char *)encoded);
+                               _imap4_received_body_size = _imap4_received_body_size + EM_SAFE_STRLEN((char *)encoded);
+
                                EM_DEBUG_LOG("total = %d", total);
                                EM_DEBUG_LOG("write_response_into_file successful %s.....", buf);
 
-                               total = _imap4_received_body_size = EM_SAFE_STRLEN((char *)encoded);
-
                                EM_DEBUG_LOG("_imap4_last_notified_body_size [%d]", _imap4_last_notified_body_size);
                                EM_DEBUG_LOG("_imap4_download_noti_interval_value [%d]", _imap4_download_noti_interval_value);
                                EM_DEBUG_LOG("_imap4_received_body_size [%d]", _imap4_received_body_size);
                                EM_DEBUG_LOG("_imap4_total_body_size [%d] ", _imap4_total_body_size);
 
-                               if (((_imap4_last_notified_body_size  + _imap4_download_noti_interval_value) <=  _imap4_received_body_size)
-                                       || (_imap4_received_body_size >= _imap4_total_body_size))               /*  100  */ {
-                                       /*  In some situation, total_encoded_len includes the length of dummy bytes. So it might be greater than body_size */
-                                       int gap = 0;
-
-                                       if (total > body_size)
-                                               gap = total - body_size;
-                                       _imap4_received_body_size -= gap;
-                                       _imap4_last_notified_body_size = _imap4_received_body_size;
-                                       if (_imap4_total_body_size)
-                                               imap4_total_body_download_progress = 100*_imap4_received_body_size/_imap4_total_body_size;
-                                       else
-                                               imap4_total_body_download_progress = _imap4_received_body_size;
+                               /* In some situation, total_encoded_len includes the length of dummy bytes.
+                                * So it might be greater than body_size */
 
-                                       EM_DEBUG_LOG("3  :  body_size %d", body_size);
+                               _imap4_last_notified_body_size = _imap4_received_body_size;
 
-                                       if (body_size)
-                                               progress = 100*total/body_size;
-                                       else
-                                               progress = body_size;
+                               if (_imap4_total_body_size)
+                                       imap4_total_body_download_progress = 100*_imap4_received_body_size/_imap4_total_body_size;
+                               else
+                                       imap4_total_body_download_progress = _imap4_received_body_size;
 
-                                       EM_DEBUG_LOG("DOWNLOADING STATUS NOTIFY  :  Encoded[%d] / [%d] = %d %% Completed. -- Total Decoded[%d]", total, body_size, progress, total);
-                                       EM_DEBUG_LOG("DOWNLOADING STATUS NOTIFY  :  Total[%d] / [%d] = %d %% Completed.", _imap4_received_body_size, _imap4_total_body_size, imap4_total_body_download_progress);
+                               EM_DEBUG_LOG("DOWNLOADING STATUS NOTIFY :Total[%d] / [%d] = %d %% Completed.", _imap4_received_body_size, _imap4_total_body_size, imap4_total_body_download_progress);
 
-                                       if (cnt_info->grab_type == GRAB_TYPE_ATTACHMENT) {
-                                               if (!emcore_notify_network_event(NOTI_DOWNLOAD_ATTACH_START, mail_id, buf, cnt_info->file_no, imap4_total_body_download_progress))
-                                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_ATTACH_START] Failed >>>> ");
+                               if (cnt_info->grab_type == GRAB_TYPE_ATTACHMENT) {
+                                       if (!emcore_notify_network_event(NOTI_DOWNLOAD_ATTACH_START, mail_id, buf, cnt_info->file_no, imap4_total_body_download_progress))
+                                               EM_DEBUG_EXCEPTION("emcore_notify_network_event [NOTI_DOWNLOAD_ATTACH_START] Failed >>>>");
+                               } else {
+                                       if (multi_part_body_size) {
+                                               /* EM_DEBUG_LOG("DOWNLOADING..........  :  Multipart body size is [%d]", multi_part_body_size) */
+                                               if (!emcore_notify_network_event(NOTI_DOWNLOAD_MULTIPART_BODY, mail_id, buf, _imap4_total_body_size, _imap4_received_body_size))
+                                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [NOTI_DOWNLOAD_BODY_START] Failed >>>>");
+                                       } else {
+                                               if (!emcore_notify_network_event(NOTI_DOWNLOAD_BODY_START, mail_id, buf, _imap4_total_body_size, _imap4_received_body_size))
+                                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [NOTI_DOWNLOAD_BODY_START] Failed >>>>");
                                        }
-                                       else {
-                                                       if (multi_part_body_size) {
-                                                               /* EM_DEBUG_LOG("DOWNLOADING..........  :  Multipart body size is [%d]", multi_part_body_size) */
-                                                       if (!emcore_notify_network_event(NOTI_DOWNLOAD_MULTIPART_BODY, mail_id, buf, _imap4_total_body_size, _imap4_received_body_size))
-                                                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_BODY_START] Failed >>>> ");
-                                                       }
-                                                       else {
-                                                       if (!emcore_notify_network_event(NOTI_DOWNLOAD_BODY_START, mail_id, buf, _imap4_total_body_size, _imap4_received_body_size))
-                                                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_BODY_START] Failed >>>>");
-                                                       }
-                                       }       /*  if (is_attachment) .. else .. */
                                }
-
-                               EM_DEBUG_LOG("4");
-
-                       }
-                       else {
-                               int temp_body_size = body_size;
+                       } else {
+                               int remain_body_size = body_size;
                                int x = 0;
+                               int nsize = 0;
+                               total = 0;
 
                                if (encoding == ENCBASE64)
                                        x = (sizeof(encoded)/78) *78; /*  to solve base64 decoding pro */
@@ -3272,10 +3349,10 @@ static int emcore_get_body_part_imap_full(MAILSTREAM *stream, int msg_uid, int a
                                        x = sizeof(encoded)-1;
 
                                memset(test_buffer, 0x00, sizeof(test_buffer));
-                               while (temp_body_size && (total <body_size)) {
+                               while (remain_body_size && (total <body_size)) {
 
                                        memset(test_buffer, 0x00, sizeof(test_buffer));
-                                       while ((total != body_size) && temp_body_size && ((EM_SAFE_STRLEN((char *)test_buffer) + x) < sizeof(test_buffer))) {
+                                       while ((total != body_size) && remain_body_size && ((EM_SAFE_STRLEN((char *)test_buffer) + x) < sizeof(test_buffer))) {
                                                memset(encoded, 0x00, sizeof(encoded));
 
                                                if (net_getbuffer (imaplocal->netstream, (long)x, (char *)encoded) <= 0) {
@@ -3285,15 +3362,16 @@ static int emcore_get_body_part_imap_full(MAILSTREAM *stream, int msg_uid, int a
                                                        goto FINISH_OFF;
                                                }
 
-                                               temp_body_size = temp_body_size - x;
-                                               strncat((char *)test_buffer, (char *)encoded, EM_SAFE_STRLEN((char *)encoded));
-                                               total = total + x;
-                                               _imap4_received_body_size += EM_SAFE_STRLEN((char *)encoded);
+                                               nsize = EM_SAFE_STRLEN((char *)encoded);
+                                               remain_body_size = remain_body_size - nsize;
+                                               strncat((char *)test_buffer, (char *)encoded, nsize);
+                                               total = total + nsize;
+                                               _imap4_received_body_size += nsize;
 
                                                EM_DEBUG_LOG("total = %d", total);
 
-                                               if ( !(temp_body_size/x) && temp_body_size%x)
-                                                       x = temp_body_size%x;
+                                               if (!(remain_body_size/x) && remain_body_size%x)
+                                                       x = remain_body_size%x;
 
                                                EM_DEBUG_LOG(" _imap4_last_notified_body_size - %d ", _imap4_last_notified_body_size);
                                                EM_DEBUG_LOG(" _imap4_download_noti_interval_value - %d ", _imap4_download_noti_interval_value);
@@ -3301,40 +3379,35 @@ static int emcore_get_body_part_imap_full(MAILSTREAM *stream, int msg_uid, int a
                                                EM_DEBUG_LOG(" _imap4_received_body_size - %d ", _imap4_received_body_size);
                                                EM_DEBUG_LOG(" _imap4_total_body_size - %d ", _imap4_total_body_size);
 
-                                               if (_imap4_total_body_size)
-                                                       imap4_total_body_download_progress = 100*_imap4_received_body_size/_imap4_total_body_size;
-                                               else
-                                                       imap4_total_body_download_progress = _imap4_received_body_size;
-
-                                               if (((_imap4_last_notified_body_size  + _imap4_download_noti_interval_value) <=  _imap4_received_body_size)
-                                                       || (_imap4_received_body_size >= _imap4_total_body_size))               /*  100  */ {
-                                                       /*  In some situation, total_encoded_len includes the length of dummy bytes. So it might be greater than body_size */
-                                                       int gap = 0;
-                                                       if (total > body_size)
-                                                               gap = total - body_size;
-                                                       _imap4_received_body_size -= gap;
+                                               if (((_imap4_last_notified_body_size + _imap4_download_noti_interval_value) <=  _imap4_received_body_size)
+                                                       || (_imap4_received_body_size >= _imap4_total_body_size)) {
+                                                       /*  In some situation, total_encoded_len includes the length of dummy bytes.
+                                                        * So it might be greater than body_size */
+
+                                                       if (_imap4_received_body_size > _imap4_total_body_size)
+                                                               _imap4_received_body_size = _imap4_total_body_size;
                                                        _imap4_last_notified_body_size = _imap4_received_body_size;
 
-                                                       progress = 100*total/body_size; /*prevent 40023*/
+                                                       if (_imap4_total_body_size)
+                                                               imap4_total_body_download_progress = 100*_imap4_received_body_size/_imap4_total_body_size;
+                                                       else
+                                                               imap4_total_body_download_progress = _imap4_received_body_size;
 
-                                                       EM_DEBUG_LOG("DOWNLOADING STATUS NOTIFY  :  Encoded[%d] / [%d] = %d %% Completed. -- Total Decoded[%d]", total, body_size, progress, total);
-                                                       EM_DEBUG_LOG("DOWNLOADING STATUS NOTIFY  :  Total[%d] / [%d] = %d %% Completed.", _imap4_received_body_size, _imap4_total_body_size, imap4_total_body_download_progress);
+                                                       EM_DEBUG_LOG("DOWNLOADING STATUS NOTIFY :Total[%d] / [%d] = %d %% Completed.", _imap4_received_body_size, _imap4_total_body_size, imap4_total_body_download_progress);
 
                                                        if (cnt_info->grab_type == GRAB_TYPE_ATTACHMENT) {
                                                                if (!emcore_notify_network_event(NOTI_DOWNLOAD_ATTACH_START, mail_id, buf, cnt_info->file_no, imap4_total_body_download_progress))
-                                                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_ATTACH_START] Failed >>>> ");
-                                                       }
-                                                       else {
+                                                                       EM_DEBUG_EXCEPTION("emcore_notify_network_event [NOTI_DOWNLOAD_ATTACH_START] Failed >>>>");
+                                                       } else {
                                                                if (multi_part_body_size) {
                                                                        /* EM_DEBUG_LOG("DOWNLOADING..........  :  Multipart body size is [%d]", multi_part_body_size) */
                                                                        if (!emcore_notify_network_event(NOTI_DOWNLOAD_MULTIPART_BODY, mail_id, buf, _imap4_total_body_size, _imap4_received_body_size))
-                                                                               EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_BODY_START] Failed >>>> ");
-                                                               }
-                                                               else {
+                                                                               EM_DEBUG_EXCEPTION("emcore_notify_network_event [NOTI_DOWNLOAD_BODY_START] Failed >>>>");
+                                                               } else {
                                                                        if (!emcore_notify_network_event(NOTI_DOWNLOAD_BODY_START, mail_id, buf, _imap4_total_body_size, _imap4_received_body_size))
-                                                                               EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_BODY_START] Failed >>>>");
+                                                                               EM_DEBUG_EXCEPTION("emcore_notify_network_event [NOTI_DOWNLOAD_BODY_START] Failed >>>>");
                                                                }
-                                                       }       /*  if (is_attachment) .. else .. */
+                                                       }
                                                }
                                        }
 
@@ -3345,8 +3418,7 @@ static int emcore_get_body_part_imap_full(MAILSTREAM *stream, int msg_uid, int a
                                                        goto FINISH_OFF;
                                                }
                                                flag_first_write = 0;
-                                       }
-                                       else {
+                                       } else {
                                                if (!emcore_write_response_into_file(buf, "ab+", (char *)test_buffer, encoding, body->subtype, account_id, mail_id, &err)) /*  append */ {
                                                        EM_DEBUG_EXCEPTION("write_response_into_file %s failed [%d]", buf, err);
                                                        return_value = -1;
@@ -3357,23 +3429,20 @@ static int emcore_get_body_part_imap_full(MAILSTREAM *stream, int msg_uid, int a
                                }
                        }
                }
-               else if (!strncmp(response, tag, EM_SAFE_STRLEN(tag)))  /*  end of respons */ {
-                       if (!strncmp(response + EM_SAFE_STRLEN(tag) + 1, "OK", 2))
+               else if ((tag_position = g_strrstr(response, tag))) /*  end of response */ {
+                       if (!strncmp(tag_position + EM_SAFE_STRLEN(tag) + 1, "OK", 2)) {
                                EM_SAFE_FREE(response);
-                       else                    /*  'NO' or 'BAD */ {
+                       } else  {               /* 'NO' or 'BAD */
                                err = EMAIL_ERROR_IMAP4_FETCH_UID_FAILURE;
                                return_value = -1;
                                goto FINISH_OFF;
                        }
-
                        break;
                }
-               else if (!strcmp(response, ")"))  {
-
+               else if (!strcmp(response, ")")) {
                }
 
-               free(response);
-               response = NULL;
+               EM_SAFE_FREE (response);
        }
 
        return_value = 0;
@@ -3440,13 +3509,14 @@ static int _modify_file_name_string_for_duplicated_inline_content(char *input_so
                SNPRINTF(temp_file_name, MAX_PATH, "%s_", file_name);
 
        EM_SAFE_STRCPY(input_source_file_name, temp_file_name);
+       EM_DEBUG_LOG_SEC("temp_file_name [%s]", temp_file_name);
 
 FINISH_OFF:
 
        EM_SAFE_FREE(file_name);
        EM_SAFE_FREE(extension);
 
-       EM_DEBUG_FUNC_END("err [%d], temp_file_name [%s]", err, temp_file_name);
+       EM_DEBUG_FUNC_END("err [%d]", err);
        return err;
 }
 
@@ -3482,6 +3552,7 @@ static int emcore_get_file_pointer(BODY *body, bool input_check_duplicated_file_
                        char charset_string[512];
 
                        if (emcore_get_attribute_value_of_body_part(param, "CHARSET", charset_string, 512, false, &error)) {
+                               EM_SAFE_FREE(cnt_info->text.plain_charset); /*valgrind*/
                                cnt_info->text.plain_charset = EM_SAFE_STRDUP(charset_string);
                                memcpy(output_file_name_string, cnt_info->text.plain_charset, EM_SAFE_STRLEN(cnt_info->text.plain_charset));
                        }
@@ -3525,7 +3596,7 @@ static int emcore_get_file_pointer(BODY *body, bool input_check_duplicated_file_
                                attachment_file_name[len - 1] = '\0';
                        decoded_filename = emcore_decode_rfc2047_text(attachment_file_name, &error);
                }
-               EM_DEBUG_LOG("attachment_file_name [%s]", attachment_file_name);
+               EM_DEBUG_LOG_SEC("attachment_file_name [%s]", attachment_file_name);
                if (decoded_filename != NULL)
                        memcpy(output_file_name_string, decoded_filename, EM_SAFE_STRLEN(decoded_filename));
                else
@@ -3559,8 +3630,8 @@ FINISH_OFF:
 
        if (err)
                *err = error;
-
-       EM_DEBUG_FUNC_END("output_file_name_string[%s], error [%d]", output_file_name_string, error);
+       EM_DEBUG_LOG_SEC("output_file_name_string[%s]", output_file_name_string);
+       EM_DEBUG_FUNC_END("error [%d]", error);
        return SUCCESS;
 }
 
@@ -3613,24 +3684,24 @@ static int emcore_get_section_body_size(char *response, char *section, int *body
        char *p = NULL;
        char *s = NULL;
        int size = 0;
-       if ((p = strstr(response, "BODY[")) /* || (p = strstr(s + 1, "BODY["))*/) {
 
-                               p += strlen("BODY[");
-                               s = p;
+       if ((p = strstr(response, "BODY[")) /* || (p = strstr(s + 1, "BODY["))*/) {
 
-                               while (*s != ']')
-                                       s++;
+               p += strlen("BODY[");
+               s = p;
 
-                               *s = '\0';
+               while (*s != ']')
+                       s++;
 
-                               strcpy(section, p);
+               *s = '\0';
+               strcpy(section, p);
 
                /* if (strcmp(section, p)) {
                                        err = EMAIL_ERROR_INVALID_RESPONSE;
                                        goto FINISH_OFF;
                }*/
                p = strstr(s+1, " {");
-               if (p)  {
+               if (p) {
                        p += strlen(" {");
                        s = p;
 
@@ -3647,19 +3718,17 @@ static int emcore_get_section_body_size(char *response, char *section, int *body
                        2. file_id
                        3. bodysize
                        */
-
-               }
-               else  {
+               } else {
                        return FAILURE;
                }
-       }
-       else  {
+       } else {
                return FAILURE;
        }
+
        return SUCCESS;
 }
 
-
+/*
 static char *em_parse_filename(char *filename)
 {
        EM_DEBUG_FUNC_BEGIN("filename [%p] ", filename);
@@ -3686,11 +3755,12 @@ static char *em_parse_filename(char *filename)
     else
                sprintf(parsed_filename + EM_SAFE_STRLEN(parsed_filename), "%s%s", result, ".jpeg");
 
-       EM_DEBUG_LOG(">>> FileName [ %s ] ", result);
-
-       EM_DEBUG_FUNC_END("parsed_filename [%s] ", parsed_filename);
+       EM_DEBUG_LOG_SEC(">>> FileName [ %s ] ", result);
+       EM_DEBUG_LOG_SEC("parsed_filename [%s] ", parsed_filename);
+       EM_DEBUG_FUNC_END();
        return parsed_filename;
 }
+*/
 
 #define CONTENT_TYPE_STRING_IN_MIME_HEAEDER "Content-Type:"
 
@@ -3733,10 +3803,8 @@ INTERNAL_FUNC int emcore_get_content_type_from_mime_string(char *input_mime_stri
                if(temp_content_type_end && *temp_content_type_end == ';') {
                        if(temp_content_type_end - temp_content_type_start < 256) {
                                memcpy(result_content_type, temp_content_type_start, temp_content_type_end - temp_content_type_start);
-                               EM_DEBUG_LOG("result_content_type [%s]", result_content_type);
-                               *output_content_type = EM_SAFE_STRDUP(result_content_type);
-                               em_trim_left(*output_content_type);
-
+                               EM_DEBUG_LOG_SEC("result_content_type [%s]", result_content_type);
+                               *output_content_type = EM_SAFE_STRDUP(em_trim_left(result_content_type));
                        }
                        else {
                                EM_DEBUG_EXCEPTION("temp_content_type_end - temp_content_type_start [%d]", temp_content_type_end - temp_content_type_start);
@@ -3752,6 +3820,74 @@ FINISH_OFF:
        return err;
 }
 
+INTERNAL_FUNC int emcore_get_utf8_address(char **dest, ADDRESS *address, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("dest[%p], address[%p], err_code[%p]", dest, address, err_code);
+
+       if (!dest || !address)  {
+               EM_DEBUG_EXCEPTION("dest[%p], address[%p]", dest, address);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+
+       gchar *concatenated = NULL;
+       gchar *utf8_address = NULL;
+       gchar *temp = NULL;
+       char *nickname = NULL;
+
+       while (address)  {
+               EM_DEBUG_LOG_SEC("address->mailbox[%s], address->host[%s]", address->mailbox, address->host);
+               if (!address->mailbox || !address->host) {
+                       address = address->next;
+                       continue;
+               }
+               EM_DEBUG_LOG_DEV("address->mailbox[%p]", address->personal); 
+               if (address->personal)  {
+                       if (!(nickname = emcore_decode_rfc2047_text(address->personal, &err)))  {
+                               EM_DEBUG_EXCEPTION("emcore_decode_rfc2047_text failed - %d", err);
+                               goto FINISH_OFF;
+                       }
+                       EM_DEBUG_LOG_DEV("nickname[%s]", nickname);
+                       if (*nickname != '\0')
+                               utf8_address = g_strdup_printf("\"%s\" <%s@%s>", nickname, address->mailbox ? address->mailbox : "", address->host ? address->host : "");
+                       else
+                               utf8_address = g_strdup_printf("<%s@%s>", address->mailbox ? address->mailbox : "", address->host ? address->host : "");
+
+                       EM_SAFE_FREE(nickname);
+               }
+               else
+                       utf8_address = g_strdup_printf("<%s@%s>", address->mailbox ? address->mailbox : "", address->host ? address->host : "");
+
+               EM_DEBUG_LOG_DEV("utf8_address[%s]", utf8_address);
+
+               if (concatenated != NULL)  {
+                       temp = concatenated;
+                       concatenated = g_strdup_printf("%s; %s", temp, utf8_address);
+                       g_free(temp);
+               }
+               else
+                       concatenated = g_strdup(utf8_address);
+
+               g_free(utf8_address);
+               utf8_address = NULL;
+
+               address = address->next;
+       }
+
+       *dest = concatenated;
+
+       ret = true;
+
+FINISH_OFF:
+       EM_SAFE_FREE(nickname);
+       EM_DEBUG_FUNC_END("ret[%d]", ret);
+       return ret;
+}
+
 #define SUBTYPE_STRING_LENGTH 128
 
 INTERNAL_FUNC int emcore_get_content_type_from_mail_bodystruct(BODY *input_body, int input_buffer_length, char *output_content_type)
@@ -3804,7 +3940,7 @@ INTERNAL_FUNC int emcore_get_content_type_from_mail_bodystruct(BODY *input_body,
                        break;
        }
 
-       EM_DEBUG_LOG("output_content_type [%s]", output_content_type);
+       EM_DEBUG_LOG_SEC("output_content_type [%s]", output_content_type);
 
 FINISH_OFF:
 
@@ -3814,7 +3950,7 @@ FINISH_OFF:
 
 INTERNAL_FUNC int emcore_get_attribute_value_of_body_part(PARAMETER *input_param, char *atribute_name, char *output_value, int output_buffer_length, int with_rfc2047_text, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("input_param [%p], atribute_name [%s], output_buffer_length [%d], with_rfc2047_text [%d]", input_param, atribute_name, output_buffer_length, with_rfc2047_text);
+       EM_DEBUG_FUNC_BEGIN_SEC("input_param [%p], atribute_name [%s], output_buffer_length [%d], with_rfc2047_text [%d]", input_param, atribute_name, output_buffer_length, with_rfc2047_text);
        PARAMETER *temp_param = input_param;
        char *decoded_value = NULL, *result_value = NULL;
        int ret = false, err = EMAIL_ERROR_NONE;
@@ -3892,7 +4028,6 @@ static int emcore_get_body_part_imap(MAILSTREAM *stream, int account_id, int mai
        char *decoded_filename = NULL;
        int is_attachment = 0;
        int o_data_len = 0;
-       char *filename_temp = NULL;
        char charset_value_buffer[512] = { 0, };
        char content_type_buffer[512] = { 0, };
 /*  { is_pb */
@@ -3923,21 +4058,16 @@ static int emcore_get_body_part_imap(MAILSTREAM *stream, int account_id, int mai
        }
 
        if (is_pbd) {
-               if (!emcore_get_temp_file_name(&o_data, &err) || !o_data)  {
-                       EM_DEBUG_EXCEPTION("emcore_get_temp_file_name failed [%d]", err);
-                       if (err_code != NULL)
-                               *err_code = err;
-                       return FAILURE;
-               }
-
-
-               if (body->subtype[0] == 'P')  { /*  Sub type is PLAIN_TEX */
-                       if (cnt_info->text.plain != NULL)
-                               EM_SAFE_FREE(o_data);
-               }
-
                if (body->type == TYPETEXT && body->subtype &&
                        (!body->disposition.type || (body->disposition.type && (body->disposition.type[0] == 'i' || body->disposition.type[0] == 'I')))) {
+
+                       if (!emcore_get_temp_file_name(&o_data, &err) || !o_data)  {
+                               EM_DEBUG_EXCEPTION("emcore_get_temp_file_name failed [%d]", err);
+                               if (err_code != NULL)
+                                       *err_code = err;
+                               return FAILURE;
+                       }
+
                        if (body->subtype[0] == 'H')    /*  HTM */
                                cnt_info->text.html = o_data;
                        else
@@ -3946,8 +4076,9 @@ static int emcore_get_body_part_imap(MAILSTREAM *stream, int account_id, int mai
                        memset(charset_value_buffer, 0, 512);
 
                        if (emcore_get_attribute_value_of_body_part(body->parameter, "CHARSET", charset_value_buffer, 512, true, &err)) {
+                               EM_SAFE_FREE(cnt_info->text.plain_charset);
                                cnt_info->text.plain_charset = EM_SAFE_STRDUP(charset_value_buffer);
-                               EM_DEBUG_LOG(">>>>> CHARSET [%s] ", filename);
+                               EM_DEBUG_LOG_SEC(">>>>> CHARSET [%s] ", filename);
                        }
                }
        } /*  is_pbd */
@@ -3968,7 +4099,7 @@ static int emcore_get_body_part_imap(MAILSTREAM *stream, int account_id, int mai
                                                strncpy(filename, decoded_filename, MAX_PATH);
                                                EM_SAFE_FREE(decoded_filename);
                                        }
-                                       EM_DEBUG_LOG(">>>>> FILENAME [%s] ", filename);
+                                       EM_DEBUG_LOG_SEC(">>>>> FILENAME [%s] ", filename);
                                        extcheck = strchr(filename, '.');
 
                                        if (extcheck)
@@ -3977,7 +4108,7 @@ static int emcore_get_body_part_imap(MAILSTREAM *stream, int account_id, int mai
                                                if (body->subtype) {
                                                        strcat(filename, ".");
                                                        strcat(filename, body->subtype);
-                                                       EM_DEBUG_LOG(">>>>> FILENAME Identified the Extension [%s] ", filename);
+                                                       EM_DEBUG_LOG_SEC(">>>>> FILENAME Identified the Extension [%s] ", filename);
                                                }
                                                else
                                                        EM_DEBUG_EXCEPTION("UnKnown Extesnsion  : _ (");
@@ -4002,7 +4133,7 @@ static int emcore_get_body_part_imap(MAILSTREAM *stream, int account_id, int mai
                                        decoded_filename = emcore_decode_rfc2047_text(param->value, &err);
                                        strncpy(filename, decoded_filename, MAX_PATH);
                                        EM_SAFE_FREE(decoded_filename);
-                                       EM_DEBUG_LOG(">>>>> FILENAME [%s] ", filename);
+                                       EM_DEBUG_LOG_SEC(">>>>> FILENAME [%s] ", filename);
                                        break;
                                }
 
@@ -4029,7 +4160,7 @@ static int emcore_get_body_part_imap(MAILSTREAM *stream, int account_id, int mai
                decoded_filename = emcore_decode_rfc2047_text(body->location, &err);
                strncpy(filename, decoded_filename, MAX_PATH);
                EM_SAFE_FREE(decoded_filename);
-               EM_DEBUG_LOG("body->location [%s]", body->location);
+               EM_DEBUG_LOG_SEC("body->location [%s]", body->location);
        }
        else if (is_pbd && (strncmp(body->subtype, "RFC822", strlen("RFC822")) == 0) && (cnt_info->grab_type == 0 || (cnt_info->grab_type & GRAB_TYPE_ATTACHMENT))) {
                EM_DEBUG_LOG("Beause subtype is RFC822. This is ttachment");
@@ -4103,7 +4234,7 @@ static int emcore_get_body_part_imap(MAILSTREAM *stream, int account_id, int mai
                is_attachment = 1;
 
                if (emcore_get_attribute_value_of_body_part(body->disposition.parameter, "filename", filename, MAX_PATH, true, &err))
-                       EM_DEBUG_LOG(">>>>> FILENAME [%s] ", filename);
+                       EM_DEBUG_LOG_SEC(">>>>> FILENAME [%s] ", filename);
 
                if (!*filename)  {      /*  If the part has no filename, it may be report ms */
                        if ((body->disposition.type[0] == 'i' || body->disposition.type[0] == 'I') && body->parameter && body->parameter->attribute && strcasecmp(body->parameter->attribute, "NAME"))
@@ -4112,7 +4243,7 @@ static int emcore_get_body_part_imap(MAILSTREAM *stream, int account_id, int mai
                                char *extcheck = NULL;
 
                                if (emcore_get_attribute_value_of_body_part(body->parameter, "NAME", filename, MAX_PATH, true, &err))
-                                       EM_DEBUG_LOG("NAME [%s] ", filename);
+                                       EM_DEBUG_LOG_SEC("NAME [%s] ", filename);
 
                                extcheck = strchr(filename, '.');
 
@@ -4124,7 +4255,7 @@ static int emcore_get_body_part_imap(MAILSTREAM *stream, int account_id, int mai
                                                        strcat(filename, ".");
                                                        strcat(filename, body->subtype);
                                                }
-                                               EM_DEBUG_LOG(">>>>> FILENAME Identified the Extension [%s] ", filename);
+                                               EM_DEBUG_LOG_SEC(">>>>> FILENAME Identified the Extension [%s] ", filename);
                                        }
                                        else
                                                EM_DEBUG_EXCEPTION("UnKnown Extesnsion  : _ (");
@@ -4139,18 +4270,39 @@ static int emcore_get_body_part_imap(MAILSTREAM *stream, int account_id, int mai
                                is_attachment = 0;
                }
        }
+       else {
+               char *attr_upper = NULL;
+               char *decoded_value = NULL;
+               PARAMETER *param = body->parameter;
+               if (param) {
+                       do {
+                               EM_DEBUG_LOG_DEV("BODY-PARAM-ATTRIBUTE:%s", param->attribute);
+                               EM_DEBUG_LOG_DEV("BODY-PARAM-VALUE:%s", param->value);
+
+                               attr_upper = g_ascii_strup(param->attribute, -1);
+                               if (g_strcmp0(attr_upper, "NAME") == 0) {
+                                       decoded_value = emcore_decode_rfc2047_text(param->value, &err);
+                                       if (decoded_value) strncpy(filename, decoded_value, MAX_PATH);
+                                       break;
+                               }
+                               param = param->next;
+                       } while(param);
+               }
+
+               if (!decoded_value)
+                       strncpy(filename, "unknown", MAX_PATH);
+
+               EM_SAFE_FREE(attr_upper);
+               EM_SAFE_FREE(decoded_value);
+       }
 
        /* if (!is_pbd) */ {
-               EM_DEBUG_LOG("filename [%s]", filename);
+               EM_DEBUG_LOG_SEC("filename [%s]", filename);
                if (*filename)  {
                        decoded_filename = emcore_decode_rfc2047_text(filename, &err);
                        strncpy(filename, decoded_filename, MAX_PATH);
                        EM_SAFE_FREE(decoded_filename);
-                       filename_temp = em_parse_filename(filename);
-                       if (filename_temp) {
-                               strncpy(filename, filename_temp, MAX_PATH);
-                               EM_DEBUG_LOG("filename [%s]", filename);
-                       }
+                       EM_DEBUG_LOG_SEC("filename [%s]", filename);
                }
        }
        EM_DEBUG_LOG("is_attachment [%d]", is_attachment);
@@ -4158,7 +4310,8 @@ static int emcore_get_body_part_imap(MAILSTREAM *stream, int account_id, int mai
        if (!is_attachment)  {  /*  Text or RFC822 Message */
                EM_DEBUG_LOG("Multipart is not attachment, body->type = %d", body->type);
                EM_DEBUG_LOG("grab_type : [%d]", cnt_info->grab_type);
-               if ((cnt_info->grab_type & GRAB_TYPE_TEXT) && (body->type == TYPEMESSAGE || body->type == TYPETEXT || body->type == TYPEIMAGE))  {
+               if (((cnt_info->grab_type & GRAB_TYPE_TEXT) && (body->type == TYPEMESSAGE || body->type == TYPETEXT || body->type == TYPEIMAGE)) ||
+                        (cnt_info->grab_type & GRAB_TYPE_ATTACHMENT))  {
                        if (is_pbd)
                                return SUCCESS;
                        else {  /*  fetch body */
@@ -4171,8 +4324,8 @@ static int emcore_get_body_part_imap(MAILSTREAM *stream, int account_id, int mai
                                        EM_DEBUG_EXCEPTION("imap_mail_write_body_to_file failed [%d]", err);
                                        if(err == EMAIL_ERROR_INVALID_STREAM) {
                                                email_session_t *session = NULL;
-                                               emcore_get_current_session(&session);
-                                               err = session->error;
+                                               if (emcore_get_current_session(&session) && session)
+                                                       err = session->error;
                                        }
                                        goto FINISH_OFF;
                                }
@@ -4187,8 +4340,11 @@ static int emcore_get_body_part_imap(MAILSTREAM *stream, int account_id, int mai
                                else  {
                                        cnt_info->text.plain = o_data;
                                        memset(charset_value_buffer, 0, 512);
-                                       if (emcore_get_attribute_value_of_body_part(body->parameter, "CHARSET", charset_value_buffer, 512, true, &err))
+                                       /*check: cnt_info->text.plain_charset is malloc'd twice */
+                                       if (emcore_get_attribute_value_of_body_part(body->parameter, "CHARSET", charset_value_buffer, 512, true, &err)) {
+                                               EM_SAFE_FREE(cnt_info->text.plain_charset);
                                                cnt_info->text.plain_charset = EM_SAFE_STRDUP(charset_value_buffer);
+                                       }
                                }
                                break;
                        case TYPEIMAGE:
@@ -4232,7 +4388,7 @@ static int emcore_get_body_part_imap(MAILSTREAM *stream, int account_id, int mai
                                        if ( (err = emcore_get_content_type_from_mail_bodystruct(body, 512, content_type_buffer) ) == EMAIL_ERROR_NONE)
                                                (*ai)->attachment_mime_type = EM_SAFE_STRDUP(content_type_buffer);
 
-                                       EM_DEBUG_LOG("name[%s], size[%d], save[%s], content_id[%s], content_type_buffer [%s]", cnt_info->file->name, cnt_info->file->size, cnt_info->file->save, content_type_buffer);
+                                       EM_DEBUG_LOG_SEC("name[%s], size[%d], save[%s], content_type_buffer [%s]", cnt_info->file->name, cnt_info->file->size, cnt_info->file->save, content_type_buffer);
 #ifdef __ATTACHMENT_OPTI__
                                        (*ai)->encoding = body->encoding;
                                        if (body->sparep)
@@ -4292,7 +4448,7 @@ static int emcore_get_body_part_imap(MAILSTREAM *stream, int account_id, int mai
                dec_len = body->size.bytes;
 
                if (body->id)
-                       EM_DEBUG_LOG("BODY ID [ %s ]", body->id);
+                       EM_DEBUG_LOG_SEC("BODY ID [ %s ]", body->id);
                else
                        EM_DEBUG_LOG("BODY ID IS NULL");
 
@@ -4303,7 +4459,7 @@ static int emcore_get_body_part_imap(MAILSTREAM *stream, int account_id, int mai
                        (((body->id) || (body->location)) && (cnt_info->grab_type & GRAB_TYPE_TEXT))  /*  Is it inline contents  */
                )  {
                        /*  fetch attachment */
-                       EM_DEBUG_LOG("attachment (enc)  :  %s %ld bytes", filename, body->size.bytes);
+                       EM_DEBUG_LOG_SEC("attachment (enc)  :  %s %ld bytes", filename, body->size.bytes);
                        EM_DEBUG_LOG(">>>>> ONLY BODY DOWNLOAD [ %d ] ", only_body_download);
 
                        if (only_body_download == false) {
@@ -4321,7 +4477,7 @@ static int emcore_get_body_part_imap(MAILSTREAM *stream, int account_id, int mai
                        }
                }
 
-               EM_DEBUG_LOG("attachment (dec)  :  %s %d bytes", filename, dec_len);
+               EM_DEBUG_LOG_SEC("attachment (dec)  :  %s %d bytes", filename, dec_len);
 
                /*  add attachment info to content inf */
                if (!(*ai = em_malloc(sizeof(struct attachment_info))))  {
@@ -4555,10 +4711,10 @@ INTERNAL_FUNC int emcore_get_body_structure(MAILSTREAM *stream, int msg_uid, BOD
        return SUCCESS;
 }
 
-int emcore_set_fetch_part_section(BODY *body, char *section_pfx, int section_subno, int enable_inline_list, int *total_mail_size, int *err_code);
+int emcore_set_fetch_part_section(BODY *body, char *section_pfx, int section_subno, int enable_inline_list, int *total_mail_size, int *total_body_size, int *err_code);
 
 /* set body section to be fetched */
-INTERNAL_FUNC int emcore_set_fetch_body_section(BODY *body, int enable_inline_list, int *total_mail_size, int *err_code)
+INTERNAL_FUNC int emcore_set_fetch_body_section(BODY *body, int enable_inline_list, int *total_mail_size, int *total_body_size, int *err_code)
 {
        EM_DEBUG_FUNC_BEGIN("body[%p], err_code[%p]", body, err_code);
 
@@ -4570,17 +4726,17 @@ INTERNAL_FUNC int emcore_set_fetch_body_section(BODY *body, int enable_inline_li
        }
 
 //     body->id = cpystr("1"); /*  top level body */
-       EM_DEBUG_LOG("body->id : [%s]", body->id);
+       EM_DEBUG_LOG_SEC("body->id : [%s]", body->id);
 
        if (enable_inline_list) {
                g_inline_count = 0;
                EM_SAFE_FREE(g_inline_list);
        }
 
-       emcore_set_fetch_part_section(body, (char *)NULL, 0, enable_inline_list, total_mail_size, err_code);
+       emcore_set_fetch_part_section(body, (char *)NULL, 0, enable_inline_list, total_mail_size, total_body_size, err_code);
 
        if (body && body->id)
-               EM_DEBUG_LOG(">>>>> FILE NAME [%s] ", body->id);
+               EM_DEBUG_LOG_SEC(">>>>> FILE NAME [%s] ", body->id);
        else
                EM_DEBUG_LOG(">>>>> BODY NULL ");
 
@@ -4589,9 +4745,9 @@ INTERNAL_FUNC int emcore_set_fetch_body_section(BODY *body, int enable_inline_li
 }
 
 /* set part section of body to be fetched */
-int emcore_set_fetch_part_section(BODY *body, char *section_pfx, int section_subno, int enable_inline_list, int *total_mail_size, int *err_code)
+int emcore_set_fetch_part_section(BODY *body, char *section_pfx, int section_subno, int enable_inline_list, int *total_mail_size, int *total_body_size, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("body[%p], section_pfx[%s], section_subno[%d], err_code[%p]", body, section_pfx, section_subno, err_code);
+       EM_DEBUG_FUNC_BEGIN("body[%p], section_pfx[%s], section_subno[%d], enable_inline_list[%d], total_mail_size[%p] err_code[%p]", body, section_pfx, section_subno, enable_inline_list, total_mail_size, err_code);
 
        PART *part = NULL;
        char section[64] = {0x00, };
@@ -4607,7 +4763,7 @@ int emcore_set_fetch_part_section(BODY *body, char *section_pfx, int section_sub
                }
 
                for (section_subno = 0, part = body->nested.part; part; part = part->next)
-                       emcore_set_fetch_part_section(&part->body, section, section_subno++, enable_inline_list, total_mail_size, err_code);
+                       emcore_set_fetch_part_section(&part->body, section, section_subno++, enable_inline_list, total_mail_size, total_body_size, err_code);
        }
        else  {
                if (!section_pfx) /* dummy prefix if top level */
@@ -4633,21 +4789,27 @@ int emcore_set_fetch_part_section(BODY *body, char *section_pfx, int section_sub
                        EM_DEBUG_LOG("Update g_inline_list with inline count [%d]", g_inline_count);
                }
 
-               /*  if ((total_mail_size != NULL) && !(body->disposition.type && (body->disposition.type[0] == 'a' || body->disposition.type[0] == 'A')) */
                if (total_mail_size != NULL) {
                        *total_mail_size = *total_mail_size + (int)body->size.bytes;
                        EM_DEBUG_LOG("body->size.bytes [%d]", body->size.bytes);
+                       EM_DEBUG_LOG("total_mail_size [%d]", *total_mail_size);
+               }
+
+               if ((total_body_size != NULL) && !(body->disposition.type && (body->disposition.type[0] == 'a' || body->disposition.type[0] == 'A'))) {
+                       *total_body_size = *total_body_size + (int)body->size.bytes;
+                       EM_DEBUG_LOG("body->size.bytes [%d]", body->size.bytes);
+                       EM_DEBUG_LOG("total_mail_size [%d]", *total_body_size);
                }
 
                /* encapsulated message ? */
                if ((body->type == TYPEMESSAGE) && !strcasecmp(body->subtype, "RFC822") && (body = ((MESSAGE *)body->nested.msg)->body))  {
                        if (body->type == TYPEMULTIPART) {
                                section[0] = '\0';
-                               emcore_set_fetch_part_section(body, section, section_subno-1, enable_inline_list, total_mail_size, err_code);
+                               emcore_set_fetch_part_section(body, section, section_subno-1, enable_inline_list, total_mail_size, total_body_size, err_code);
                        }
                        else  {         /*  build encapsulation prefi */
                                SNPRINTF(section, sizeof(section), "%s%d.", section_pfx, section_subno);
-                               emcore_set_fetch_part_section(body, section, 0, enable_inline_list, total_mail_size, err_code);
+                               emcore_set_fetch_part_section(body, section, 0, enable_inline_list, total_mail_size, total_body_size, err_code);
                        }
                }
                else  {
@@ -4816,7 +4978,10 @@ static char *emcore_decode_rfc2047_word(char *encoded_word, int *err_code)
                                        charset = NULL;
                                }
 
-                               current = end + 2;      /*  skip '?=' */
+                               if( *(end + 2) == ' ')
+                                       current = end + 3;      /*  skip '?= ' */
+                               else
+                                       current = end + 2;      /*  skip '?=' */
                        }
                        else {
                                /*  unencoded text      */
@@ -4830,8 +4995,37 @@ static char *emcore_decode_rfc2047_word(char *encoded_word, int *err_code)
                }
                else {
                        /*  unencoded text      */
+                       char *tmp_buffer = NULL;
+                       char *charset_guess = emcore_guess_charset(current);
                        length = EM_SAFE_STRLEN(current);
-                       strncat(buffer, current, length);
+
+                       if (charset_guess) {
+                               SIZEDTEXT extra_src = { NULL, 0 };
+                               SIZEDTEXT extra_dst = { NULL, 0 };
+                               extra_src.data = (unsigned char *)current;
+                               extra_src.size = length;
+                               if (!utf8_text(&extra_src, charset_guess, &extra_dst, 0)) {
+                                       EM_DEBUG_EXCEPTION("utf8_text falied...");
+                                       if (extra_src.data) {
+                                               tmp_buffer = buffer;
+                                               buffer = g_strconcat(tmp_buffer, (char *)extra_src.data, NULL);
+                                               EM_SAFE_FREE(tmp_buffer);
+                                       }
+                               } else {
+                                       if (extra_dst.data) {
+                                               tmp_buffer = buffer;
+                                               buffer = g_strconcat(tmp_buffer, (char *)extra_dst.data, NULL);
+                                               EM_SAFE_FREE(tmp_buffer);
+                                       }
+                               }
+
+                               EM_SAFE_FREE(charset_guess);
+                       } else {
+                               tmp_buffer = buffer;
+                               buffer = g_strconcat(tmp_buffer, current, NULL);
+                               EM_SAFE_FREE(tmp_buffer);
+                       }
+
                        current = current + length;
 #ifdef FEATURE_CORE_DEBUG
                        EM_DEBUG_LOG("4 - Buffer[%s]", buffer);
@@ -4879,23 +5073,26 @@ INTERNAL_FUNC char *emcore_decode_rfc2047_text(char *rfc2047_text, int *err_code
 
        char *text = NULL;
 
-       gchar **encoded_words = g_strsplit_set(rfc2047_text, " \t\r\n", -1);
+       gchar **encoded_words = g_strsplit_set(rfc2047_text, "\t\r\n", -1);
        gchar **decoded_words = g_new0(char *, g_strv_length(encoded_words) + 1);
 
-       /* EM_DEBUG_LOG("g_strv_length(encoded_words) [%d]", g_strv_length(encoded_words)); */
+       EM_DEBUG_LOG_DEV("rfc2047_text [%s]", rfc2047_text);
+       EM_DEBUG_LOG_DEV("g_strv_length(encoded_words) [%d]", g_strv_length(encoded_words));
 
        if (encoded_words != NULL)  {
                int i = 0;
 
                while (encoded_words[i] != NULL)  {
+                       EM_DEBUG_LOG_DEV("encoded_words[%d] [%s]", i, encoded_words[i]);
                        if (!(decoded_words[i] = emcore_decode_rfc2047_word(encoded_words[i], &err)))  {
                                EM_DEBUG_EXCEPTION("emcore_decode_rfc2047_word falied [%d]", err);
                                goto FINISH_OFF;
                        }
-
+                       EM_DEBUG_LOG_DEV("decoded_words[%d] [%s]", i, decoded_words[i]);
                        i++;
                }
-               text = g_strjoinv(" ", decoded_words);
+
+               text = g_strjoinv("", decoded_words);
        }
        else
                text = EM_SAFE_STRDUP(rfc2047_text);
@@ -4916,26 +5113,143 @@ FINISH_OFF:
        return text;
 }
 
+static int emcore_make_mail_data_from_m_mesg(email_mail_data_t *dst_mail_data, struct _m_mesg *mmsg)
+{
+        EM_DEBUG_FUNC_BEGIN();
+        int err = EMAIL_ERROR_NONE;
+
+        if (!mmsg || !dst_mail_data) {
+                EM_DEBUG_EXCEPTION("Invalid parameter");
+                err = EMAIL_ERROR_INVALID_PARAM;
+                return err;
+        }
+       
+       char *content_type = NULL;
+       char *mime_type = NULL;
+       char *encoded_subject = NULL;
+       struct tm temp_time_info;
+        ADDRESS *from = NULL;
+        ADDRESS *to = NULL;
+        ADDRESS *cc = NULL;
+        ADDRESS *bcc = NULL;
+       MESSAGECACHE mail_cache_element = {0, };
+
+       memset(&mail_cache_element, 0x00, sizeof(MESSAGECACHE));
+       memset((void *)&temp_time_info, 0, sizeof(struct tm));
+
+       if (mmsg->header)
+               content_type = emcore_mime_get_header_value(mmsg->header->part_header, CONTENT_TYPE, &err);
+
+        if (content_type) {
+                if (strcasestr(content_type, "PKCS7-MIME")) {
+                       mime_type = emcore_mime_get_header_value(mmsg->header->part_header, CONTENT_SMIME_TYPE, &err);
+
+                       if (mime_type && strcasestr(mime_type, "enveloped-data")) 
+                               dst_mail_data->smime_type = EMAIL_SMIME_ENCRYPTED;
+                       else
+                               dst_mail_data->smime_type = EMAIL_SMIME_SIGNED_AND_ENCRYPTED;
+               } else if (strcasestr(content_type, "SIGNED")) {
+                        dst_mail_data->smime_type = EMAIL_SMIME_SIGNED;
+               } else {
+                        dst_mail_data->smime_type = EMAIL_SMIME_NONE;
+               }
+        }
+
+       if (!mmsg->rfc822header) {
+                EM_DEBUG_LOG("This mail did not have envelop");
+                return err;
+        }
+
+        if (mmsg->rfc822header->date) {
+                EM_DEBUG_LOG("date : [%s]", mmsg->rfc822header->date);
+                mail_parse_date(&mail_cache_element, (unsigned char *)mmsg->rfc822header->date);
+        }
+
+        temp_time_info.tm_sec = mail_cache_element.seconds;
+        temp_time_info.tm_min = mail_cache_element.minutes - mail_cache_element.zminutes;
+        temp_time_info.tm_hour = mail_cache_element.hours - mail_cache_element.zhours;
+
+        if (mail_cache_element.hours - mail_cache_element.zhours < 0) {
+                temp_time_info.tm_mday = mail_cache_element.day - 1;
+                temp_time_info.tm_hour += 24;
+        } else
+                temp_time_info.tm_mday = mail_cache_element.day;
+
+        temp_time_info.tm_mon = mail_cache_element.month - 1;
+        temp_time_info.tm_year = mail_cache_element.year + 70;
+
+        dst_mail_data->date_time                   = timegm(&temp_time_info);
+
+        encoded_subject = emcore_decode_rfc2047_text(mmsg->rfc822header->subject, NULL);
+        dst_mail_data->subject                     = EM_SAFE_STRDUP(encoded_subject);
+
+        dst_mail_data->full_address_return         = EM_SAFE_STRDUP(mmsg->rfc822header->return_path);
+        dst_mail_data->email_address_recipient     = EM_SAFE_STRDUP(mmsg->rfc822header->received);
+        dst_mail_data->email_address_sender        = EM_SAFE_STRDUP(mmsg->rfc822header->sender);
+        dst_mail_data->full_address_reply          = EM_SAFE_STRDUP(mmsg->rfc822header->reply_to);
+
+        if (mmsg->rfc822header->from) {
+                rfc822_parse_adrlist(&from, mmsg->rfc822header->from, NULL);
+                if (!emcore_get_utf8_address(&dst_mail_data->full_address_from, from, &err)) {
+                        EM_DEBUG_EXCEPTION_SEC("emcore_get_utf8_address failed : [%d], [%s]", err, mmsg->rfc822header->from);
+                }    
+        }                    
+
+        if (mmsg->rfc822header->to) {
+                rfc822_parse_adrlist(&to, mmsg->rfc822header->to, NULL);
+                if (!emcore_get_utf8_address(&dst_mail_data->full_address_to, to, &err)) {
+                        EM_DEBUG_EXCEPTION_SEC("emcore_get_utf8_address failed : [%d], [%s]", err, mmsg->rfc822header->to);
+                }    
+        }                    
+
+        if (mmsg->rfc822header->cc) {
+                rfc822_parse_adrlist(&cc, mmsg->rfc822header->cc, NULL);
+                if (!emcore_get_utf8_address(&dst_mail_data->full_address_cc, cc, &err)) {
+                        EM_DEBUG_EXCEPTION_SEC("emcore_get_utf8_address failed : [%d], [%s]", err, mmsg->rfc822header->cc);
+                }    
+        }                    
+
+        if (mmsg->rfc822header->bcc) {
+                rfc822_parse_adrlist(&bcc, mmsg->rfc822header->bcc, NULL);
+                if (!emcore_get_utf8_address(&dst_mail_data->full_address_bcc, bcc, &err)) {
+                        EM_DEBUG_EXCEPTION_SEC("emcore_get_utf8_address failed : [%d], [%s]", err, mmsg->rfc822header->bcc);
+                }    
+        }     
+
+       EM_SAFE_FREE(encoded_subject);
+
+       if (from)
+               mail_free_address(&from);
+
+       if (to)
+               mail_free_address(&to);
+
+       if (cc)
+               mail_free_address(&cc);
+
+       if (bcc)
+               mail_free_address(&bcc);
+
+        EM_DEBUG_FUNC_END("err : [%d]", err);
+        return err;
+}
+
 INTERNAL_FUNC int emcore_make_mail_data_from_mime_data(struct _m_mesg *mmsg, struct _m_content_info *cnt_info, email_mail_data_t **output_mail_data, email_attachment_data_t **output_attachment_data, int *output_attachment_count, int *err_code)
 {
        EM_DEBUG_FUNC_BEGIN();
+       int i = 0;
        int ret = false;
+        int eml_mail_id = 0;
+       int attachment_num = 0;
        int err = EMAIL_ERROR_NONE;
        int local_attachment_count = 0;
        int local_inline_content_count = 0;
-       int attachment_num = 0;
-       int i = 0;
-       int eml_mail_id = 0;
        char buf[512];
        char html_body[MAX_PATH] = {0, };
-       struct tm temp_time_info;
-       struct timeval tv;
+        struct timeval tv;
        struct attachment_info *ai = NULL;
-       char *encoded_subject = NULL;
-       char *content_type = NULL;
        email_attachment_data_t *attachment = NULL;
        email_mail_data_t *p_mail_data = NULL;
-       MESSAGECACHE mail_cache_element = {0, };
 
        if (!mmsg || !cnt_info || !output_mail_data || !output_attachment_data) {
                EM_DEBUG_EXCEPTION("Invalid parameter");
@@ -4943,6 +5257,11 @@ INTERNAL_FUNC int emcore_make_mail_data_from_mime_data(struct _m_mesg *mmsg, str
                goto FINISH_OFF;
        }
 
+       /* Create rand mail id of eml */
+       gettimeofday(&tv, NULL);
+       srand(tv.tv_usec);
+       eml_mail_id = rand();
+
        p_mail_data = (email_mail_data_t *)em_malloc(sizeof(email_mail_data_t));
        if (p_mail_data == NULL) {
                EM_DEBUG_EXCEPTION("em_malloc failed");
@@ -4950,52 +5269,13 @@ INTERNAL_FUNC int emcore_make_mail_data_from_mime_data(struct _m_mesg *mmsg, str
                goto FINISH_OFF;
        }
 
-       memset(&mail_cache_element, 0x00, sizeof(MESSAGECACHE));
-       memset((void *)&temp_time_info, 0, sizeof(struct tm));
-
-       /* Create rand mail id of eml */
-       gettimeofday(&tv, NULL);
-       srand(tv.tv_usec);
-       eml_mail_id = rand();
-
        p_mail_data->mail_id = eml_mail_id;
        p_mail_data->account_id = EML_FOLDER;
+       p_mail_data->body_download_status = (*err_code != EMAIL_ERROR_NO_MORE_DATA) ? EMAIL_BODY_DOWNLOAD_STATUS_FULLY_DOWNLOADED : EMAIL_BODY_DOWNLOAD_STATUS_PARTIALLY_DOWNLOADED;
 
-       if (mmsg->header)
-               content_type = emcore_mime_get_header_value(mmsg->header->part_header, CONTENT_TYPE, &err);
-
-       if (content_type && strcasestr(content_type, "PKCS7-MIME")) /*prevent 50417*/
-               p_mail_data->smime_type = EMAIL_SMIME_ENCRYPTED;
-
-       if (mmsg->rfc822header->date)
-               mail_parse_date(&mail_cache_element, (unsigned char *)mmsg->rfc822header->date);
-
-       temp_time_info.tm_sec = mail_cache_element.seconds;
-       temp_time_info.tm_min = mail_cache_element.minutes - mail_cache_element.zminutes;
-       temp_time_info.tm_hour = mail_cache_element.hours - mail_cache_element.zhours;
-
-       if (mail_cache_element.hours - mail_cache_element.zhours < 0) {
-               temp_time_info.tm_mday = mail_cache_element.day - 1;
-               temp_time_info.tm_hour += 24;
-       } else
-               temp_time_info.tm_mday = mail_cache_element.day;
-
-       temp_time_info.tm_mon = mail_cache_element.month - 1;
-       temp_time_info.tm_year = mail_cache_element.year + 70;
-
-       encoded_subject = emcore_decode_rfc2047_text(mmsg->rfc822header->subject, NULL);
-
-       p_mail_data->date_time                   = timegm(&temp_time_info);
-       p_mail_data->full_address_return         = EM_SAFE_STRDUP(mmsg->rfc822header->return_path);
-       p_mail_data->email_address_recipient     = EM_SAFE_STRDUP(mmsg->rfc822header->received);
-       p_mail_data->full_address_from           = EM_SAFE_STRDUP(mmsg->rfc822header->from);
-       p_mail_data->subject                     = EM_SAFE_STRDUP(encoded_subject);
-       p_mail_data->email_address_sender        = EM_SAFE_STRDUP(mmsg->rfc822header->sender);
-       p_mail_data->full_address_to             = EM_SAFE_STRDUP(mmsg->rfc822header->to);
-       p_mail_data->full_address_cc             = EM_SAFE_STRDUP(mmsg->rfc822header->cc);
-       p_mail_data->full_address_bcc            = EM_SAFE_STRDUP(mmsg->rfc822header->bcc);
-       p_mail_data->full_address_reply          = EM_SAFE_STRDUP(mmsg->rfc822header->reply_to);
-       p_mail_data->body_download_status        = EMAIL_BODY_DOWNLOAD_STATUS_FULLY_DOWNLOADED;
+        if ((err = emcore_make_mail_data_from_m_mesg(p_mail_data, mmsg)) != EMAIL_ERROR_NONE) {
+                EM_DEBUG_EXCEPTION("emcore_make_mail_data_from_m_mesg failed : [%d]", err);
+        }
 
        EM_DEBUG_LOG("cnt_info->text.plain [%s], cnt_info->text.html [%s]", cnt_info->text.plain, cnt_info->text.html);
 
@@ -5017,10 +5297,9 @@ INTERNAL_FUNC int emcore_make_mail_data_from_mime_data(struct _m_mesg *mmsg, str
                }
 
                p_mail_data->file_path_plain = EM_SAFE_STRDUP(buf);
-               EM_DEBUG_LOG("mail_data->file_path_plain [%s]", p_mail_data->file_path_plain);
        }
 
-       if (cnt_info->text.html)  {
+       if (cnt_info->text.html) {
                if (!emstorage_create_dir(EML_FOLDER, eml_mail_id, 0, &err))  {
                        EM_DEBUG_EXCEPTION("emstorage_create_dir failed [%d]", err);
                        goto FINISH_OFF;
@@ -5041,10 +5320,10 @@ INTERNAL_FUNC int emcore_make_mail_data_from_mime_data(struct _m_mesg *mmsg, str
                        EM_DEBUG_EXCEPTION("emstorage_move_file failed [%d]", err);
                        goto FINISH_OFF;
                }
+
                p_mail_data->file_path_html = EM_SAFE_STRDUP(buf);
        }
 
-
        for (ai = cnt_info->file; ai; ai = ai->next, attachment_num++) {}
        EM_DEBUG_LOG("attachment_num : [%d]", attachment_num);
 
@@ -5057,29 +5336,32 @@ INTERNAL_FUNC int emcore_make_mail_data_from_mime_data(struct _m_mesg *mmsg, str
                }
 
                for (ai = cnt_info->file; ai; ai = ai->next, i++) {
-                       attachment[i].attachment_id          = 0;
+                       attachment[i].attachment_id          = i + 1;
                        attachment[i].attachment_size        = ai->size;
                        attachment[i].attachment_name        = EM_SAFE_STRDUP(ai->name);
                        attachment[i].drm_status             = ai->drm;
                        attachment[i].save_status            = 0;
                        attachment[i].inline_content_status  = ai->type == 1;
-                       attachment[i].attachment_mime_type   = ai->attachment_mime_type;
+                       attachment[i].attachment_mime_type   = EM_SAFE_STRDUP(ai->attachment_mime_type);
 #ifdef __ATTACHMENT_OPTI__
                        attachment[i].encoding               = ai->encoding;
                        attachment[i].section                = ai->section;
 #endif
                        EM_DEBUG_LOG("attachment[%d].attachment_id[%d]", i, attachment[i].attachment_id);
                        EM_DEBUG_LOG("attachment[%d].attachment_size[%d]", i, attachment[i].attachment_size);
-                       EM_DEBUG_LOG("attachment[%d].attachment_name[%s]", i, attachment[i].attachment_name);
+                       EM_DEBUG_LOG_SEC("attachment[%d].attachment_name[%s]", i, attachment[i].attachment_name);
                        EM_DEBUG_LOG("attachment[%d].drm_status[%d]", i, attachment[i].drm_status);
                        EM_DEBUG_LOG("attachment[%d].inline_content_status[%d]", i, attachment[i].inline_content_status);
+                        EM_DEBUG_LOG("attachment[%d].attachment_mime_type : [%s]", i, attachment[i].attachment_mime_type);
 
                        if (ai->type == 1)
                                local_inline_content_count ++;
-                       local_attachment_count++;
+                       else
+                               local_attachment_count++;
+
+                       if (ai->save) {
+             attachment[i].save_status = ai->save_status == EMAIL_BODY_DOWNLOAD_STATUS_PARTIALLY_DOWNLOADED ? EMAIL_BODY_DOWNLOAD_STATUS_PARTIALLY_DOWNLOADED : EMAIL_BODY_DOWNLOAD_STATUS_FULLY_DOWNLOADED;
 
-                       if (ai->save)  {
-                               attachment[i].save_status = 1;
                                if (ai->type == 1)  {           /*  it is inline content */
                                        if (!emstorage_create_dir(EML_FOLDER, eml_mail_id, 0, &err))  {
                                                EM_DEBUG_EXCEPTION("emstorage_create_dir failed [%d]", err);
@@ -5091,12 +5373,12 @@ INTERNAL_FUNC int emcore_make_mail_data_from_mime_data(struct _m_mesg *mmsg, str
                                        }
                                }
                                else  {
-                                       if (!emstorage_create_dir(EML_FOLDER, eml_mail_id, i, &err)) {
+                                       if (!emstorage_create_dir(EML_FOLDER, eml_mail_id, i + 1, &err)) {
                                                EM_DEBUG_EXCEPTION("emstorage_create_dir failed [%d]", err);
                                                goto FINISH_OFF;
                                        }
 
-                                       if (!emstorage_get_save_name(EML_FOLDER, eml_mail_id, i, attachment[i].attachment_name, buf, &err))  {
+                                       if (!emstorage_get_save_name(EML_FOLDER, eml_mail_id, i + 1, attachment[i].attachment_name, buf, &err))  {
                                                EM_DEBUG_EXCEPTION("emstorage_get_save_name failed [%d]", err);
                                                goto FINISH_OFF;
                                        }
@@ -5145,7 +5427,7 @@ FINISH_OFF:
                        *output_attachment_data = attachment;
 
                if (output_attachment_count)
-                       *output_attachment_count = local_attachment_count;
+                       *output_attachment_count = attachment_num;
        } else {
                if (p_mail_data) {
                        emcore_free_mail_data(p_mail_data);
@@ -5156,7 +5438,6 @@ FINISH_OFF:
                        emcore_free_attachment_data(&attachment, attachment_num, NULL);
        }
 
-       EM_SAFE_FREE(encoded_subject);
 
        if (err_code)
                *err_code = err;
@@ -5167,11 +5448,13 @@ FINISH_OFF:
 
 INTERNAL_FUNC int emcore_parse_mime_file_to_mail(char *eml_file_path, email_mail_data_t **output_mail_data, email_attachment_data_t **output_attachment_data, int *output_attachment_count, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("eml_file_path : [%s], output_mail_data : [%p]", eml_file_path, output_mail_data);
+       EM_DEBUG_FUNC_BEGIN_SEC("eml_file_path : [%s], output_mail_data : [%p]", eml_file_path, output_mail_data);
 
        int err = EMAIL_ERROR_NONE;
        int ret = false;
        int is_file = 1;
+       char buf[512];
+       char *mime_entity = NULL;
        FILE *eml_fp = NULL;
        struct _m_content_info *cnt_info = NULL;
        struct _m_mesg *mmsg = NULL;
@@ -5219,9 +5502,11 @@ INTERNAL_FUNC int emcore_parse_mime_file_to_mail(char *eml_file_path, email_mail
        }
 
        if (!emcore_mime_parse_body(eml_fp, is_file, mmsg, cnt_info, NULL, &err)) {
-               EM_DEBUG_EXCEPTION("emcore_mime_parse_body failed : [%d]", err);
-               err = EMAIL_ERROR_INVALID_DATA;
-               goto FINISH_OFF;
+               if (err != EMAIL_ERROR_NO_MORE_DATA) {
+                       EM_DEBUG_EXCEPTION("emcore_mime_parse_body failed : [%d]", err);
+                       err = EMAIL_ERROR_INVALID_DATA;
+                       goto FINISH_OFF;
+               }
        }
 
        if (!emcore_make_mail_data_from_mime_data(mmsg, cnt_info, output_mail_data, output_attachment_data, output_attachment_count, &err)) {
@@ -5230,6 +5515,25 @@ INTERNAL_FUNC int emcore_parse_mime_file_to_mail(char *eml_file_path, email_mail
 
        }
 
+       if ((*output_mail_data)->smime_type == EMAIL_SMIME_SIGNED) {
+               if (!emcore_get_mime_entity(eml_file_path, &mime_entity, &err)) {
+                       EM_DEBUG_EXCEPTION("emcore_get_mime_entity failed: [%d]", err);
+                       goto FINISH_OFF;
+               }
+               
+               if (!emstorage_get_save_name((*output_mail_data)->account_id, (*output_mail_data)->mail_id, 0, "mime_entity", buf, &err)) {
+                       EM_DEBUG_EXCEPTION("emstorage_get_save_name failed : [%d]", err);
+                       goto FINISH_OFF;
+               }
+       
+               if (!emstorage_move_file(mime_entity, buf, false, &err)) {
+                       EM_DEBUG_EXCEPTION("emstorage_move_file failed [%d]", err);
+                       goto FINISH_OFF;
+               }       
+
+               (*output_mail_data)->file_path_mime_entity = EM_SAFE_STRDUP(buf);
+       }
+
        ret = true;
 
 FINISH_OFF:
@@ -5240,8 +5544,12 @@ FINISH_OFF:
        if (mmsg)
                emcore_mime_free_mime(mmsg);
 
-       if (cnt_info)
+       if (cnt_info) {
                emcore_free_content_info(cnt_info);
+               EM_SAFE_FREE(cnt_info);
+       }
+
+       EM_SAFE_FREE(mime_entity);
 
        if (err_code)
                *err_code = err;
@@ -5296,7 +5604,7 @@ FINISH_OFF:
 
 INTERNAL_FUNC int emcore_get_mime_entity(char *mime_path, char **output_path, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("mime_path : [%s], output_path : [%p]", mime_path, *output_path);
+       EM_DEBUG_FUNC_BEGIN("mime_path : [%s], output_path : [%p]", mime_path, output_path);
        int ret = false;
        int err = EMAIL_ERROR_NONE;
        int is_file = 1;
@@ -5312,6 +5620,7 @@ INTERNAL_FUNC int emcore_get_mime_entity(char *mime_path, char **output_path, in
        FILE *fp_read = NULL;
        FILE *fp_write = NULL;
        struct _m_mesg *mmsg = NULL;
+       char errno_buf[ERRNO_BUF_SIZE] = {0};
 
        if (!mime_path) {
                EM_DEBUG_EXCEPTION("Invalid parameter");
@@ -5329,20 +5638,21 @@ INTERNAL_FUNC int emcore_get_mime_entity(char *mime_path, char **output_path, in
 
        fp_read = fopen(mime_path, "r");
        if (fp_read == NULL) {
-               EM_DEBUG_EXCEPTION("File open(read) is failed : filename [%s]", mime_path);
+               EM_DEBUG_EXCEPTION_SEC("File open(read) is failed : filename [%s]", mime_path);
                err = EMAIL_ERROR_SYSTEM_FAILURE;
                goto FINISH_OFF;
        }
 
        if (!emcore_mime_parse_header(fp_read, is_file, &mmsg->rfc822header, &mmsg->header, &err)) {
                EM_DEBUG_EXCEPTION("emcore_mime_parse_header failed : [%d]", err);
+               err = EMAIL_ERROR_INVALID_DATA;
                goto FINISH_OFF;
        }
 
        /* Parsing the mime header */
        content_type = emcore_mime_get_header_value(mmsg->header->part_header, CONTENT_TYPE, NULL);
-       EM_DEBUG_LOG("Content_type : [%s]", content_type);
-       if (strcasestr(content_type, "signed") == NULL) {
+       EM_DEBUG_LOG_SEC("Content_type : [%s]", content_type);
+       if (content_type && strcasestr(content_type, "signed")==NULL) {
                EM_DEBUG_EXCEPTION("Invalid parameter : No signed mail");
                err = EMAIL_ERROR_INVALID_PARAM;
                goto FINISH_OFF;
@@ -5357,7 +5667,7 @@ INTERNAL_FUNC int emcore_get_mime_entity(char *mime_path, char **output_path, in
 
        fp_write = fopen(mime_entity_path, "w");
        if (fp_write == NULL) {
-               EM_DEBUG_EXCEPTION("File open(write) is failed : filename [%s]", mime_entity_path);
+               EM_DEBUG_EXCEPTION_SEC("File open(write) is failed : filename [%s]", mime_entity_path);
                err = EMAIL_ERROR_SYSTEM_FAILURE;
                goto FINISH_OFF;
        }
@@ -5367,16 +5677,17 @@ INTERNAL_FUNC int emcore_get_mime_entity(char *mime_path, char **output_path, in
 
        while (TRUE) {
                if (!emcore_get_line_from_file((void *)fp_read, buf, MIME_LINE_LEN, &err)) {
-                       EM_DEBUG_EXCEPTION("emcore_mime_get_line_from_file failed [%d]", err);
                        if (err == EMAIL_ERROR_NO_MORE_DATA) {
                                EM_DEBUG_LOG("this mail is partial body");
                                end_mime_entity = ftell(fp_read);
                                if ( end_mime_entity < 0 ) {
-                                       EM_DEBUG_EXCEPTION("ftell failed [%s]", EM_STRERROR(errno));
+                                       EM_DEBUG_EXCEPTION("ftell failed [%s]", EM_STRERROR(errno_buf));
                                        goto FINISH_OFF;
                                }
+                                err = EMAIL_ERROR_NONE;
                                break;
                        }
+                       EM_DEBUG_EXCEPTION("emcore_mime_get_line_from_file failed [%d]", err);
                        goto FINISH_OFF;
                }
 
@@ -5385,13 +5696,13 @@ INTERNAL_FUNC int emcore_get_mime_entity(char *mime_path, char **output_path, in
                        if (search == 1) {
                                start_mime_entity = ftell(fp_read);
                                if( start_mime_entity < 0 ) { /*prevent 24473*/
-                                       EM_DEBUG_EXCEPTION("ftell failed [%s]", EM_STRERROR(errno));
+                                       EM_DEBUG_EXCEPTION("ftell failed [%s]", EM_STRERROR(errno_buf));
                                        goto FINISH_OFF;
                                }
                        } else if (search == 2) {
                                end_mime_entity = ftell(fp_read);
                                if( end_mime_entity < 0 ) { /*prevent 24473*/
-                                       EM_DEBUG_EXCEPTION("ftell failed [%s]", EM_STRERROR(errno));
+                                       EM_DEBUG_EXCEPTION("ftell failed [%s]", EM_STRERROR(errno_buf));
                                        goto FINISH_OFF;
                                }
                                break;
@@ -5461,6 +5772,7 @@ int emcore_decode_body_text_from_file(FILE *stream, char *boundary_str, int enco
        char *body = NULL;
        int modified_body_size = 0;
        char *modified_body = NULL;
+       char errno_buf[ERRNO_BUF_SIZE] = {0};
 
        if (boundary_str) {
                /*  if there boundary, this content is from current line to ending boundary */
@@ -5474,7 +5786,7 @@ int emcore_decode_body_text_from_file(FILE *stream, char *boundary_str, int enco
        start_location = ftell(stream);
        if(start_location < 0 ) { /*prevent 35555*/
                error = EMAIL_ERROR_INVALID_PARAM;
-               EM_DEBUG_EXCEPTION("ftell failed : %s", EM_STRERROR(errno));
+               EM_DEBUG_EXCEPTION("ftell failed : %s", EM_STRERROR(errno_buf));
                goto FINISH_OFF;
        }
 
@@ -5487,7 +5799,7 @@ int emcore_decode_body_text_from_file(FILE *stream, char *boundary_str, int enco
                        }
 
                        partial_body = 1;
-                       *end_of_parsing = 1;
+                       *end_of_parsing = 2;
                        break;
                }
 
@@ -5506,7 +5818,7 @@ int emcore_decode_body_text_from_file(FILE *stream, char *boundary_str, int enco
        end_location = ftell(stream);
        if(end_location < 0 ) { /*prevent 35555*/
                error = EMAIL_ERROR_INVALID_PARAM;
-               EM_DEBUG_EXCEPTION("ftell failed : %s", EM_STRERROR(errno));
+               EM_DEBUG_EXCEPTION("ftell failed : %s", EM_STRERROR(errno_buf));
                goto FINISH_OFF;
        }
 
@@ -5610,7 +5922,7 @@ int emcore_decode_body_text_from_sock(void *stream, char *boundary_str, int enco
 
                        EM_DEBUG_LOG("This mail is partial body");
 
-                       *end_of_parsing = 1;
+                       *end_of_parsing = 2;
 
                        error = EMAIL_ERROR_NONE;
 
@@ -5654,7 +5966,14 @@ int emcore_decode_body_text_from_sock(void *stream, char *boundary_str, int enco
                        }
 
                        if (result_buffer == NULL) {
-                               result_buffer      = strdup(buf); /*prevent 35499*/
+                               result_buffer = em_malloc(dec_len + 1);
+                               if (result_buffer == NULL) {
+                                       EM_DEBUG_EXCEPTION("em_malloc failed");
+                                       error = EMAIL_ERROR_OUT_OF_MEMORY;
+                                       goto FINISH_OFF;
+                               }
+
+                               memcpy(result_buffer, buf, dec_len); /*prevent 35499*/
                                result_buffer_size = dec_len;
                        }
 
index 1c39b6c..ed1c71c 100755 (executable)
@@ -153,7 +153,7 @@ INTERNAL_FUNC void mm_list(MAILSTREAM *stream, int delimiter, char *mailbox, lon
        else
                p[count].mailbox_name  = cpystr(enc_path);
 
-       EM_DEBUG_LOG("mailbox name [%s] mailbox_type [%d] no_select [%d]", p[count].mailbox_name, p[count].mailbox_type, p[count].no_select);
+       EM_DEBUG_LOG_SEC("mailbox name [%s] mailbox_type [%d] no_select [%d]", p[count].mailbox_name, p[count].mailbox_type, p[count].no_select);
 
        p[count].alias = emcore_get_alias_of_mailbox((const char *)enc_path);
        p[count].local = 0;
@@ -165,9 +165,10 @@ INTERNAL_FUNC void mm_list(MAILSTREAM *stream, int delimiter, char *mailbox, lon
        tmp = strstr(mailbox, "user=");
        if (tmp) {
                tmp = tmp+5;
-               for (s = tmp; *s != '/'; s++);
+               for (s = tmp; *s != '/' &&  *s != '}' && *s != '\0'; s++);
                *s = '\0';
-               p[count].account_id = atoi(tmp);
+               if(strlen(tmp) > 0)
+                       p[count].account_id = atoi(tmp);
        }
        EM_DEBUG_LOG("mm_list account_id %d ", p[count].account_id);
 
@@ -207,6 +208,8 @@ INTERNAL_FUNC void mm_login(NETMBX *mb, char *user, char *pwd, long trial)
        email_account_t *ref_account = NULL;
        char *username = NULL;
        char *password = NULL;
+       char *token    = NULL;
+       char *save_ptr = NULL;
 
        if (!mb->user[0])  {
                EM_DEBUG_EXCEPTION("invalid account_id...");
@@ -230,13 +233,23 @@ INTERNAL_FUNC void mm_login(NETMBX *mb, char *user, char *pwd, long trial)
 
        if (ref_account->incoming_server_password == NULL) {
                EM_SAFE_FREE(username);
-               EM_DEBUG_EXCEPTION("invalid password...");
+               EM_DEBUG_EXCEPTION("Empty password");
                goto FINISH_OFF;
        }
 
-       password = EM_SAFE_STRDUP(ref_account->incoming_server_password);
+       EM_DEBUG_LOG("incoming_server_authentication_method [%d]", ref_account->incoming_server_authentication_method);
 
-       if(EM_SAFE_STRLEN(username) > 0 && EM_SAFE_STRLEN(password) > 0) { /*prevent 34355*/
+       if(ref_account->incoming_server_authentication_method == EMAIL_AUTHENTICATION_METHOD_XOAUTH2) {
+
+               token = strtok_r(ref_account->incoming_server_password, "\001", &save_ptr);
+               EM_DEBUG_LOG_SEC("token [%s]", token);
+               password = EM_SAFE_STRDUP(token);
+       }
+       else {
+               password = EM_SAFE_STRDUP(ref_account->incoming_server_password);
+       }
+
+       if(EM_SAFE_STRLEN(username) > 0 && EM_SAFE_STRLEN(password) > 0) {
                strcpy(user, username);
                strcpy(pwd, password);
        }
@@ -298,6 +311,9 @@ INTERNAL_FUNC void mm_log(char *string, long errflg)
                        if (session) {
                                mm_get_error(string, &session->error);
                                EM_DEBUG_EXCEPTION("IMAP_TOOLKIT_LOG ERROR [%d]", session->error);
+                               if(session->error == EMAIL_ERROR_XOAUTH_BAD_REQUEST || session->error == EMAIL_ERROR_XOAUTH_INVALID_UNAUTHORIZED) {
+                                       session->network = session->error;
+                               }
                        }
                        
                        break;
@@ -420,6 +436,10 @@ INTERNAL_FUNC void mm_get_error(char *string, int *err_code)
                *err_code = EMAIL_ERROR_MAILBOX_NOT_FOUND;
        else if (strstr(string, "15 minute"))
                *err_code = EMAIL_ERROR_LOGIN_ALLOWED_EVERY_15_MINS;
+       else if (strstr(string, "\"status\":\"400"))
+               *err_code = EMAIL_ERROR_XOAUTH_BAD_REQUEST;
+       else if (strstr(string, "\"status\":\"401"))
+               *err_code = EMAIL_ERROR_XOAUTH_INVALID_UNAUTHORIZED;
        else
                *err_code = EMAIL_ERROR_UNKNOWN;
 }
index 50cb794..eaf9818 100755 (executable)
@@ -69,7 +69,7 @@ static int emcore_send_signal(enotitype_t notiType, int subType, int data1, int
        DBusConnection *connection;\r
        DBusMessage     *signal = NULL;\r
        DBusError          dbus_error;\r
-       dbus_uint32_t   error;\r
+       dbus_uint32_t   error = 0;\r
        const char       *nullString = "";\r
 \r
        ENTER_CRITICAL_SECTION(_dbus_noti_lock);\r
@@ -77,8 +77,9 @@ static int emcore_send_signal(enotitype_t notiType, int subType, int data1, int
        dbus_error_init (&dbus_error);\r
        connection = dbus_bus_get(DBUS_BUS_SYSTEM, &dbus_error);\r
 \r
-       if (connection == NULL) {\r
-               EM_DEBUG_LOG("dbus_bus_get is failed");\r
+       if (dbus_error_is_set (&dbus_error)) {\r
+               EM_DEBUG_EXCEPTION ("dbus_bus_get failed: [%s]", dbus_error.message);\r
+               dbus_error_free (&dbus_error);\r
                goto FINISH_OFF;\r
        }\r
 \r
@@ -140,10 +141,10 @@ static int emcore_send_signal(enotitype_t notiType, int subType, int data1, int
        }\r
 \r
        if (!dbus_connection_send(connection, signal, &error)) {\r
-               EM_DEBUG_LOG("dbus_connection_send is failed [%d]", error);\r
+               EM_DEBUG_EXCEPTION ("dbus_connection_send failed [%d]", error);\r
        }\r
        else {\r
-               EM_DEBUG_LOG("dbus_connection_send is successful");\r
+               EM_DEBUG_LOG_DEV ("dbus_connection_send done");\r
                ret = 1;\r
        }\r
 \r
@@ -163,6 +164,248 @@ FINISH_OFF:
 }\r
 \r
 \r
+\r
+INTERNAL_FUNC int em_send_notification_to_active_sync_engine(int subType, ASNotiData *data)\r
+{\r
+       EM_DEBUG_FUNC_BEGIN("subType [%d], data [%p]", subType, data);\r
+\r
+       DBusConnection     *connection;\r
+       DBusMessage        *signal = NULL;\r
+       DBusError           dbus_error;\r
+       int                 i = 0;\r
+       dbus_uint32_t   error = 0;\r
+       int ret = true;\r
+\r
+       ENTER_CRITICAL_SECTION(_dbus_noti_lock);\r
+\r
+       dbus_error_init (&dbus_error);\r
+       connection = dbus_bus_get(DBUS_BUS_SYSTEM, &dbus_error);\r
+       if (dbus_error_is_set (&dbus_error)) {\r
+               EM_DEBUG_EXCEPTION("dbus_bus_get failed: [%s]", dbus_error.message);\r
+               dbus_error_free (&dbus_error);\r
+               ret = false;\r
+               goto FINISH_OFF;\r
+       }\r
+\r
+       signal = dbus_message_new_signal("/User/Email/ActiveSync", EMAIL_ACTIVE_SYNC_NOTI, "email");\r
+\r
+       dbus_message_append_args(signal, DBUS_TYPE_INT32, &subType, DBUS_TYPE_INVALID);\r
+       switch ( subType ) {\r
+               case ACTIVE_SYNC_NOTI_SEND_MAIL:\r
+                       EM_DEBUG_LOG("handle:[%d]", data->send_mail.handle);\r
+                       EM_DEBUG_LOG("account_id:[%d]", data->send_mail.account_id);\r
+                       EM_DEBUG_LOG("mail_id:[%d]", data->send_mail.mail_id);\r
+\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->send_mail.handle), DBUS_TYPE_INVALID);\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->send_mail.account_id), DBUS_TYPE_INVALID);\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->send_mail.mail_id), DBUS_TYPE_INVALID);\r
+                       break;\r
+               case ACTIVE_SYNC_NOTI_SEND_SAVED:                               /*  publish a send notification to ASE (active sync engine) */\r
+                       EM_DEBUG_EXCEPTION("Not support yet : subType[ACTIVE_SYNC_NOTI_SEND_SAVED]", subType);\r
+                       break;\r
+               case ACTIVE_SYNC_NOTI_SEND_REPORT:\r
+                       EM_DEBUG_EXCEPTION("Not support yet : subType[ACTIVE_SYNC_NOTI_SEND_REPORT]", subType);\r
+                       break;\r
+               case ACTIVE_SYNC_NOTI_SYNC_HEADER:\r
+                       EM_DEBUG_LOG("handle:[%d]", data->sync_header.handle);\r
+                       EM_DEBUG_LOG("account_id:[%d]", data->sync_header.account_id);\r
+                       EM_DEBUG_LOG("mailbox_id:[%d]", data->sync_header.mailbox_id);\r
+\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->sync_header.handle ), DBUS_TYPE_INVALID);\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->sync_header.account_id ), DBUS_TYPE_INVALID);\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->sync_header.mailbox_id ), DBUS_TYPE_INVALID);\r
+                       break;\r
+               case ACTIVE_SYNC_NOTI_DOWNLOAD_BODY:                    /*  publish a download body notification to ASE */\r
+                       EM_DEBUG_LOG("handle:[%d]", data->download_body.handle);\r
+                       EM_DEBUG_LOG("account_id:[%d]", data->download_body.account_id);\r
+                       EM_DEBUG_LOG("mail_id:[%d]", data->download_body.mail_id);\r
+                       EM_DEBUG_LOG("with_attachment:[%d]", data->download_body.with_attachment);\r
+\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->download_body.handle  ), DBUS_TYPE_INVALID);\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->download_body.account_id  ), DBUS_TYPE_INVALID);\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->download_body.mail_id ), DBUS_TYPE_INVALID);\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->download_body.with_attachment  ), DBUS_TYPE_INVALID);\r
+                       break;\r
+               case ACTIVE_SYNC_NOTI_DOWNLOAD_ATTACHMENT:\r
+                       EM_DEBUG_LOG("handle:[%d]", data->download_attachment.handle);\r
+                       EM_DEBUG_LOG("account_id:[%d]", data->download_attachment.account_id );\r
+                       EM_DEBUG_LOG("mail_id:[%d]", data->download_attachment.mail_id);\r
+                       EM_DEBUG_LOG("with_attachment:[%d]", data->download_attachment.attachment_order );\r
+\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->download_attachment.handle  ), DBUS_TYPE_INVALID);\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->download_attachment.account_id  ), DBUS_TYPE_INVALID);\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->download_attachment.mail_id ), DBUS_TYPE_INVALID);\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->download_attachment.attachment_order), DBUS_TYPE_INVALID);\r
+                       break;\r
+               case ACTIVE_SYNC_NOTI_VALIDATE_ACCOUNT:\r
+                       EM_DEBUG_EXCEPTION("Not support yet : subType[ACTIVE_SYNC_NOTI_VALIDATE_ACCOUNT]", subType);\r
+                       break;\r
+               case ACTIVE_SYNC_NOTI_CANCEL_JOB:\r
+                       EM_DEBUG_LOG("account_id:[%d]",       data->cancel_job.account_id );\r
+                       EM_DEBUG_LOG("handle to cancel:[%d]", data->cancel_job.handle);\r
+                       EM_DEBUG_LOG("cancel_type:[%d]",      data->cancel_job.cancel_type);\r
+\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->cancel_job.account_id  ), DBUS_TYPE_INVALID);\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->cancel_job.handle  ), DBUS_TYPE_INVALID);\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->cancel_job.cancel_type  ), DBUS_TYPE_INVALID);\r
+                       break;\r
+               case ACTIVE_SYNC_NOTI_SEARCH_ON_SERVER:\r
+                       EM_DEBUG_LOG("account_id:[%d]",          data->search_mail_on_server.account_id );\r
+                       EM_DEBUG_LOG("mailbox_id:[%d]",        data->search_mail_on_server.mailbox_id );\r
+                       EM_DEBUG_LOG("search_filter_count:[%d]", data->search_mail_on_server.search_filter_count );\r
+                       EM_DEBUG_LOG("handle to cancel:[%d]",    data->search_mail_on_server.handle);\r
+\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->search_mail_on_server.account_id), DBUS_TYPE_INVALID);\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->search_mail_on_server.mailbox_id), DBUS_TYPE_INVALID);\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->search_mail_on_server.search_filter_count), DBUS_TYPE_INVALID);\r
+                       for(i = 0; i < data->search_mail_on_server.search_filter_count; i++) {\r
+                               dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->search_mail_on_server.search_filter_list[i].search_filter_type), DBUS_TYPE_INVALID);\r
+                               switch(data->search_mail_on_server.search_filter_list[i].search_filter_type) {\r
+                                       case EMAIL_SEARCH_FILTER_TYPE_MESSAGE_NO       :\r
+                                       case EMAIL_SEARCH_FILTER_TYPE_UID              :\r
+                                       case EMAIL_SEARCH_FILTER_TYPE_SIZE_LARSER      :\r
+                                       case EMAIL_SEARCH_FILTER_TYPE_SIZE_SMALLER     :\r
+                                       case EMAIL_SEARCH_FILTER_TYPE_FLAGS_ANSWERED   :\r
+                                       case EMAIL_SEARCH_FILTER_TYPE_FLAGS_DELETED    :\r
+                                       case EMAIL_SEARCH_FILTER_TYPE_FLAGS_DRAFT      :\r
+                                       case EMAIL_SEARCH_FILTER_TYPE_FLAGS_FLAGED     :\r
+                                       case EMAIL_SEARCH_FILTER_TYPE_FLAGS_RECENT     :\r
+                                       case EMAIL_SEARCH_FILTER_TYPE_FLAGS_SEEN       :\r
+                                               dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->search_mail_on_server.search_filter_list[i].search_filter_key_value.integer_type_key_value), DBUS_TYPE_INVALID);\r
+                                               break;\r
+\r
+                                       case EMAIL_SEARCH_FILTER_TYPE_BCC              :\r
+                                       case EMAIL_SEARCH_FILTER_TYPE_CC               :\r
+                                       case EMAIL_SEARCH_FILTER_TYPE_FROM             :\r
+                                       case EMAIL_SEARCH_FILTER_TYPE_KEYWORD          :\r
+                                       case EMAIL_SEARCH_FILTER_TYPE_SUBJECT          :\r
+                                       case EMAIL_SEARCH_FILTER_TYPE_TO               :\r
+                                       case EMAIL_SEARCH_FILTER_TYPE_MESSAGE_ID       :\r
+                                               dbus_message_append_args(signal, DBUS_TYPE_STRING, &(data->search_mail_on_server.search_filter_list[i].search_filter_key_value.string_type_key_value), DBUS_TYPE_INVALID);\r
+                                               break;\r
+\r
+                                       case EMAIL_SEARCH_FILTER_TYPE_SENT_DATE_BEFORE :\r
+                                       case EMAIL_SEARCH_FILTER_TYPE_SENT_DATE_ON     :\r
+                                       case EMAIL_SEARCH_FILTER_TYPE_SENT_DATE_SINCE  :\r
+                                               dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->search_mail_on_server.search_filter_list[i].search_filter_key_value.time_type_key_value), DBUS_TYPE_INVALID);\r
+                                               break;\r
+                                       default :\r
+                                               EM_DEBUG_EXCEPTION("Invalid filter type [%d]", data->search_mail_on_server.search_filter_list[i].search_filter_type);\r
+                                               break;\r
+                               }\r
+                       }\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->search_mail_on_server.handle), DBUS_TYPE_INVALID);\r
+                       break;\r
+\r
+               case ACTIVE_SYNC_NOTI_CLEAR_RESULT_OF_SEARCH_ON_SERVER :\r
+                       EM_DEBUG_LOG("account_id:[%d]",          data->clear_result_of_search_mail_on_server.account_id );\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->search_mail_on_server.account_id), DBUS_TYPE_INVALID);\r
+                       break;\r
+\r
+               case ACTIVE_SYNC_NOTI_EXPUNGE_MAILS_DELETED_FLAGGED :\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->expunge_mails_deleted_flagged.account_id), DBUS_TYPE_INVALID);\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->expunge_mails_deleted_flagged.mailbox_id), DBUS_TYPE_INVALID);\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->expunge_mails_deleted_flagged.on_server), DBUS_TYPE_INVALID);\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->expunge_mails_deleted_flagged.handle), DBUS_TYPE_INVALID);\r
+                       break;\r
+\r
+               case ACTIVE_SYNC_NOTI_RESOLVE_RECIPIENT :\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->get_resolve_recipients.account_id), DBUS_TYPE_INVALID);\r
+                       dbus_message_append_args(signal, DBUS_TYPE_STRING, &(data->get_resolve_recipients.email_address), DBUS_TYPE_INVALID);\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->get_resolve_recipients.handle), DBUS_TYPE_INVALID);\r
+                       break;\r
+\r
+               case ACTIVE_SYNC_NOTI_VALIDATE_CERTIFICATE :\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->validate_certificate.account_id), DBUS_TYPE_INVALID);\r
+                       dbus_message_append_args(signal, DBUS_TYPE_STRING, &(data->validate_certificate.email_address), DBUS_TYPE_INVALID);\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->validate_certificate.handle), DBUS_TYPE_INVALID);\r
+                       break;\r
+\r
+               case ACTIVE_SYNC_NOTI_ADD_MAILBOX :\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->add_mailbox.account_id), DBUS_TYPE_INVALID);\r
+                       dbus_message_append_args(signal, DBUS_TYPE_STRING, &(data->add_mailbox.mailbox_path), DBUS_TYPE_INVALID);\r
+                       dbus_message_append_args(signal, DBUS_TYPE_STRING, &(data->add_mailbox.mailbox_alias), DBUS_TYPE_INVALID);\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->add_mailbox.handle), DBUS_TYPE_INVALID);\r
+                       /* eas is not ready to use void array and length */\r
+                       dbus_message_append_args (signal, DBUS_TYPE_STRING, &(data->add_mailbox.eas_data), DBUS_TYPE_INVALID);\r
+/*                     dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->add_mailbox.eas_data_length), DBUS_TYPE_INVALID);\r
+                       if (data->add_mailbox.eas_data_length > 0) {\r
+                               dbus_message_append_args (signal, DBUS_TYPE_ARRAY,  DBUS_TYPE_INT32, &(data->add_mailbox.eas_data),\\r
+                                                                                               data->add_mailbox.eas_data_length,DBUS_TYPE_INVALID);\r
+                       } */\r
+                       break;\r
+\r
+               case ACTIVE_SYNC_NOTI_RENAME_MAILBOX :\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->rename_mailbox.account_id), DBUS_TYPE_INVALID);\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->rename_mailbox.mailbox_id), DBUS_TYPE_INVALID);\r
+                       dbus_message_append_args(signal, DBUS_TYPE_STRING, &(data->rename_mailbox.mailbox_name), DBUS_TYPE_INVALID);\r
+                       dbus_message_append_args(signal, DBUS_TYPE_STRING, &(data->rename_mailbox.mailbox_alias), DBUS_TYPE_INVALID);\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->rename_mailbox.handle), DBUS_TYPE_INVALID);\r
+                       /* eas is not ready to use void array and length */\r
+                       dbus_message_append_args (signal, DBUS_TYPE_STRING, &(data->rename_mailbox.eas_data), DBUS_TYPE_INVALID);\r
+/*                     dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->rename_mailbox.eas_data_length), DBUS_TYPE_INVALID);\r
+                       if (data->rename_mailbox.eas_data_length > 0) {\r
+                               dbus_message_append_args (signal, DBUS_TYPE_ARRAY,  DBUS_TYPE_INT32, &(data->rename_mailbox.eas_data),\\r
+                                                                                          data->rename_mailbox.eas_data_length, DBUS_TYPE_INVALID);\r
+                       }*/\r
+                       break;\r
+\r
+               case ACTIVE_SYNC_NOTI_DELETE_MAILBOX :\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->delete_mailbox.account_id), DBUS_TYPE_INVALID);\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->delete_mailbox.mailbox_id), DBUS_TYPE_INVALID);\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->delete_mailbox.handle), DBUS_TYPE_INVALID);\r
+                       break;\r
+\r
+               case ACTIVE_SYNC_NOTI_DELETE_MAILBOX_EX :\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->delete_mailbox_ex.account_id), DBUS_TYPE_INVALID);\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->delete_mailbox_ex.mailbox_id_count), DBUS_TYPE_INVALID);\r
+                       for(i = 0; i <data->delete_mailbox_ex.mailbox_id_count; i++)\r
+                               dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->delete_mailbox_ex.mailbox_id_array[i]), DBUS_TYPE_INVALID);\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->delete_mailbox_ex.handle), DBUS_TYPE_INVALID);\r
+                       break;\r
+\r
+               case ACTIVE_SYNC_NOTI_SEND_MAIL_WITH_DOWNLOADING_OF_ORIGINAL_MAIL:\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->send_mail_with_downloading_attachment_of_original_mail.handle), DBUS_TYPE_INVALID);\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->send_mail_with_downloading_attachment_of_original_mail.mail_id), DBUS_TYPE_INVALID);\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->send_mail_with_downloading_attachment_of_original_mail.account_id), DBUS_TYPE_INVALID);\r
+                       break;\r
+\r
+               case ACTIVE_SYNC_NOTI_SCHEDULE_SENDING_MAIL:\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->schedule_sending_mail.handle), DBUS_TYPE_INVALID);\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->schedule_sending_mail.account_id), DBUS_TYPE_INVALID);\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->schedule_sending_mail.mail_id), DBUS_TYPE_INVALID);\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->schedule_sending_mail.scheduled_time), DBUS_TYPE_INVALID);\r
+                       break;\r
+\r
+               case ACTIVE_SYNC_NOTI_CANCEL_SENDING_MAIL:\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->cancel_sending_mail.handle), DBUS_TYPE_INVALID);\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->cancel_sending_mail.account_id  ), DBUS_TYPE_INVALID);\r
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->cancel_sending_mail.mail_id), DBUS_TYPE_INVALID);\r
+                       break;\r
+\r
+               default:\r
+                       EM_DEBUG_EXCEPTION("Invalid Notification type of Active Sync : subType[%d]", subType);\r
+                       ret = false;\r
+                       goto FINISH_OFF;\r
+       }\r
+\r
+       if (!dbus_connection_send (connection, signal, &error)) {\r
+               EM_DEBUG_EXCEPTION ("dbus_connection_send failed [%d]", error);\r
+               ret = false;\r
+       }\r
+\r
+       /*dbus_connection_flush(connection);*/\r
+\r
+FINISH_OFF:\r
+\r
+       if(signal)\r
+               dbus_message_unref(signal);\r
+\r
+       LEAVE_CRITICAL_SECTION(_dbus_noti_lock);\r
+       EM_DEBUG_FUNC_END();\r
+       return ret;\r
+}\r
+\r
 INTERNAL_FUNC int emcore_notify_storage_event(email_noti_on_storage_event transaction_type, int data1, int data2 , char *data3, int data4)\r
 {\r
        EM_DEBUG_FUNC_BEGIN("transaction_type[%d], data1[%d], data2[%d], data3[%p], data4[%d]", transaction_type, data1, data2, data3, data4);\r
@@ -189,15 +432,16 @@ INTERNAL_FUNC int emcore_send_task_status_signal(email_task_type_t input_task_ty
        DBusConnection *connection;\r
        DBusMessage        *signal = NULL;\r
        DBusError           dbus_error;\r
-       dbus_uint32_t   error;\r
+       dbus_uint32_t   error = 0;\r
 \r
        ENTER_CRITICAL_SECTION(_dbus_noti_lock);\r
 \r
        dbus_error_init (&dbus_error);\r
        connection = dbus_bus_get(DBUS_BUS_SYSTEM, &dbus_error);\r
-\r
-       if (connection == NULL) {\r
-               EM_DEBUG_LOG("dbus_bus_get is failed");\r
+       if (dbus_error_is_set (&dbus_error)) {\r
+               EM_DEBUG_EXCEPTION("dbus_bus_get failed: [%s]", dbus_error.message);\r
+               dbus_error_free (&dbus_error);\r
+               err = EMAIL_ERROR_IPC_CONNECTION_FAILURE;\r
                goto FINISH_OFF;\r
        }\r
 \r
@@ -205,6 +449,7 @@ INTERNAL_FUNC int emcore_send_task_status_signal(email_task_type_t input_task_ty
 \r
        if (signal == NULL) {\r
                EM_DEBUG_EXCEPTION("dbus_message_new_signal is failed");\r
+               err = EMAIL_ERROR_IPC_CONNECTION_FAILURE;\r
                goto FINISH_OFF;\r
        }\r
        EM_DEBUG_LOG("Signal for task status has been created by dbus_message_new_signal");\r
@@ -216,10 +461,11 @@ INTERNAL_FUNC int emcore_send_task_status_signal(email_task_type_t input_task_ty
        dbus_message_append_args(signal, DBUS_TYPE_INT32, &input_param_2, DBUS_TYPE_INVALID);\r
 \r
        if (!dbus_connection_send(connection, signal, &error)) {\r
-               EM_DEBUG_LOG("dbus_connection_send is failed [%d]", error);\r
+               EM_DEBUG_EXCEPTION("dbus_connection_send failed: [%d]", error);\r
+               err = EMAIL_ERROR_IPC_CONNECTION_FAILURE;\r
        }\r
        else {\r
-               EM_DEBUG_LOG("dbus_connection_send is successful");\r
+               EM_DEBUG_LOG("dbus_connection_send done");\r
        }\r
 \r
 /*     EM_DEBUG_LOG("Before dbus_connection_flush");    */\r
index 7783144..bb9103a 100755 (executable)
@@ -130,13 +130,15 @@ static int get_x509_stack_of_recipient_certs(char *recipients, STACK_OF(X509) **
 
        int err = EMAIL_ERROR_NONE;
        int ret = false;        
+       int i = 0, j = 0;
        int cert_size = 0;
        char *temp_recipients = NULL;
-       char *token = NULL;
-       char *str = NULL;
+       char *email_address = NULL;
        char file_name[512] = {0, };
        const unsigned char *in_cert = NULL;
 
+       ADDRESS *token_address = NULL;
+
        X509 *x509_cert = NULL;
        STACK_OF(X509) *temp_recipient_certs = NULL;
 
@@ -150,21 +152,38 @@ static int get_x509_stack_of_recipient_certs(char *recipients, STACK_OF(X509) **
        }
 
        /* Initialize the variable */
-       context = cert_svc_cert_context_init();
        temp_recipient_certs = sk_X509_new_null();
 
        temp_recipients = EM_SAFE_STRDUP(recipients);
-       temp_recipients = em_replace_all_string(temp_recipients, ",", ";");     
-       token = strtok_r(temp_recipients, ";", &str);
 
-       do {
-               if (!emstorage_get_certificate_by_email_address(token, &cert, false, 0, &err)) {
+       for (i = 0, j = EM_SAFE_STRLEN(temp_recipients); i < j; i++)
+               if (temp_recipients[i] == ';') temp_recipients[i] = ',';
+
+       rfc822_parse_adrlist(&token_address, temp_recipients, NULL);
+
+       while (token_address) {
+               context = cert_svc_cert_context_init();
+               if (!context) { /*prevent 20162*/
+                       EM_DEBUG_EXCEPTION("cert_svc_cert_context_init failed");
+                       goto FINISH_OFF;                        
+               }
+
+               EM_DEBUG_LOG("email_address_mailbox : [%s], email_address_host : [%s]", token_address->mailbox, token_address->host);
+
+               email_address = g_strdup_printf("<%s@%s>", token_address->mailbox, token_address->host);
+               if (!emstorage_get_certificate_by_email_address(email_address, &cert, false, 0, &err)) {
                        EM_DEBUG_EXCEPTION("emstorage_get_certificate_by_email_address failed : [%d]", err);
                        goto FINISH_OFF;
                }
+
+               if (!cert) { /*prevent 20161*/
+                       EM_DEBUG_EXCEPTION("cert is NULL");
+                       goto FINISH_OFF;        
+               }
+
                
                SNPRINTF(file_name, sizeof(file_name), "%s", cert->filepath);
-               EM_DEBUG_LOG("file_name : [%s]", file_name);
+               EM_DEBUG_LOG_SEC("file_name : [%s]", file_name);
                err = cert_svc_load_file_to_context(context, file_name);
                if (err != CERT_SVC_ERR_NO_ERROR) {
                        EM_DEBUG_EXCEPTION("cert_svc_load_file_to_context failed : [%d]", err);
@@ -187,11 +206,16 @@ static int get_x509_stack_of_recipient_certs(char *recipients, STACK_OF(X509) **
                        goto FINISH_OFF;
                }
 
-               x509_cert = NULL;
+               cert_svc_cert_context_final(context);
                context = NULL;
+               
                emstorage_free_certificate(&cert, 1, NULL);
                cert = NULL;
-       } while ((token = strtok_r(NULL, ";", &str)));
+
+               x509_cert = NULL;
+
+               token_address = token_address->next;
+       }
 
        *output_recipient_certs = temp_recipient_certs;
 
@@ -200,23 +224,28 @@ static int get_x509_stack_of_recipient_certs(char *recipients, STACK_OF(X509) **
 FINISH_OFF:
 
        if (!ret) {
-               if (x509_cert)
-                       X509_free(x509_cert);
-
                if (temp_recipient_certs)
                        sk_X509_pop_free(temp_recipient_certs, X509_free);
+
+               if (x509_cert)
+                       X509_free(x509_cert);
        }
 
        if (cert)
                emstorage_free_certificate(&cert, 1, NULL);
 
-       cert_svc_cert_context_final(context);
+       if (context)
+               cert_svc_cert_context_final(context);
 
        EM_SAFE_FREE(temp_recipients);
+       EM_SAFE_FREE(email_address);
+       if (token_address)
+               mail_free_address(&token_address);
 
        if (err_code)
                *err_code = err;
 
+       EM_DEBUG_FUNC_END();
        return ret;
 }
 
@@ -278,7 +307,7 @@ FINISH_OFF:
 
 INTERNAL_FUNC int emcore_smime_set_signed_message(char *certificate, char *mime_entity, email_digest_type digest_type, char **file_path, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("certificate path : [%s], mime_entity : [%s]", certificate, mime_entity);
+       EM_DEBUG_FUNC_BEGIN_SEC("certificate path : [%s], mime_entity : [%s]", certificate, mime_entity);
        int err, ret = false;
        char temp_smime_filepath[512];
        X509 *cert = NULL;
@@ -294,11 +323,11 @@ INTERNAL_FUNC int emcore_smime_set_signed_message(char *certificate, char *mime_
        ERR_load_crypto_strings();
 
        SNPRINTF(temp_smime_filepath, sizeof(temp_smime_filepath), "%s%s%s", MAILTEMP, DIR_SEPERATOR, SMIME_SIGNED_FILE);
-       EM_DEBUG_LOG("attachment file path of smime : [%s]", temp_smime_filepath);
+       EM_DEBUG_LOG_SEC("attachment file path of smime : [%s]", temp_smime_filepath);
 
        smime_attachment = BIO_new_file(temp_smime_filepath, OUTMODE);
        if (!smime_attachment) {
-               EM_DEBUG_EXCEPTION("Cannot open output file %s", temp_smime_filepath);
+               EM_DEBUG_EXCEPTION_SEC("Cannot open output file %s", temp_smime_filepath);
                err = EMAIL_ERROR_SYSTEM_FAILURE;
                goto FINISH_OFF;
        }
@@ -374,7 +403,7 @@ INTERNAL_FUNC int emcore_smime_set_encrypt_message(char *recipient_list, char *m
        char temp_smime_filepath[512];
        int err = EMAIL_ERROR_NONE, ret = false;
 //     int flags = PKCS7_DETACHED | PKCS7_STREAM;
-       int flags = 0;
+       int flags = PKCS7_BINARY;
 
        CERT_CONTEXT *loaded_cert = NULL;
        STACK_OF(X509) *recipient_certs = NULL;
@@ -390,11 +419,11 @@ INTERNAL_FUNC int emcore_smime_set_encrypt_message(char *recipient_list, char *m
        loaded_cert = cert_svc_cert_context_init();
 
        SNPRINTF(temp_smime_filepath, sizeof(temp_smime_filepath), "%s%s%s", MAILTEMP, DIR_SEPERATOR, SMIME_ENCRYPT_FILE);
-       EM_DEBUG_LOG("attachment file path of smime : [%s]", temp_smime_filepath);
+       EM_DEBUG_LOG_SEC("attachment file path of smime : [%s]", temp_smime_filepath);
 
        smime_attachment = BIO_new_file(temp_smime_filepath, OUTMODE);
        if (!smime_attachment) {
-               EM_DEBUG_EXCEPTION("Cannot open output file %s", temp_smime_filepath);
+               EM_DEBUG_EXCEPTION_SEC("Cannot open output file %s", temp_smime_filepath);
                err = EMAIL_ERROR_SYSTEM_FAILURE;
                goto FINISH_OFF;
        }
@@ -453,15 +482,16 @@ FINISH_OFF:
 
 INTERNAL_FUNC int emcore_smime_set_signed_and_encrypt_message(char *recipient_list, char *certificate, char *mime_entity, email_cipher_type cipher_type, email_digest_type digest_type, char **file_path, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("certificate path : [%s], mime_entity : [%s]", recipient_list, mime_entity);
+       EM_DEBUG_FUNC_BEGIN_SEC("certificate path : [%s], mime_entity : [%s]", recipient_list, mime_entity);
        char temp_smime_filepath[512];
+       char temp_mime_entity_path[512];
        int err = EMAIL_ERROR_NONE, ret = false;
        int flags = PKCS7_DETACHED | PKCS7_PARTIAL | PKCS7_STREAM;
 
        STACK_OF(X509) *recipient_certs = NULL;
        STACK_OF(X509) *other_certs = NULL;
        BIO *bio_mime_entity = NULL, *bio_cert = NULL;
-       BIO *bio_signed_message = BIO_new(BIO_s_mem());
+       BIO *bio_signed_message = NULL;
        BIO *smime_attachment = NULL;
        PKCS7 *signed_message = NULL;
        PKCS7 *encrypt_message = NULL;
@@ -476,11 +506,11 @@ INTERNAL_FUNC int emcore_smime_set_signed_and_encrypt_message(char *recipient_li
        ERR_load_crypto_strings();
 
        SNPRINTF(temp_smime_filepath, sizeof(temp_smime_filepath), "%s%s%s", MAILTEMP, DIR_SEPERATOR, SMIME_ENCRYPT_FILE);
-       EM_DEBUG_LOG("attachment file path of smime : [%s]", temp_smime_filepath);
+       EM_DEBUG_LOG_SEC("attachment file path of smime : [%s]", temp_smime_filepath);
 
        smime_attachment = BIO_new_file(temp_smime_filepath, OUTMODE);
        if (!smime_attachment) {
-               EM_DEBUG_EXCEPTION("Cannot open output file %s", temp_smime_filepath);
+               EM_DEBUG_EXCEPTION_SEC("Cannot open output file %s", temp_smime_filepath);
                err = EMAIL_ERROR_SYSTEM_FAILURE;
                goto FINISH_OFF;
        }
@@ -519,12 +549,24 @@ INTERNAL_FUNC int emcore_smime_set_signed_and_encrypt_message(char *recipient_li
        }
 
        /* 6. Create signing message */
+       SNPRINTF(temp_mime_entity_path, sizeof(temp_mime_entity_path), "%s%smime_entity", MAILTEMP, DIR_SEPERATOR);
+       EM_DEBUG_LOG_SEC("attachment file path of smime : [%s]", temp_mime_entity_path);
+
+       bio_signed_message = BIO_new_file(temp_mime_entity_path, WRITEMODE);
+       if (!bio_signed_message) {
+               EM_DEBUG_EXCEPTION_SEC("Cannot open output file %s", temp_mime_entity_path);
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
        if (!SMIME_write_PKCS7(bio_signed_message, signed_message, bio_mime_entity, flags | SMIME_OLDMIME | SMIME_CRLFEOL)) {
                EM_DEBUG_EXCEPTION("SMIME_write_PKCS7 error");
                err = EMAIL_ERROR_SYSTEM_FAILURE;
                goto FINISH_OFF;
        }
 
+       BIO_free(bio_signed_message);
+
        /* Encrypting the mail */
        /* 1. Get the recipient certs */
        if (!get_x509_stack_of_recipient_certs(recipient_list, &recipient_certs, &err)) {
@@ -535,9 +577,16 @@ INTERNAL_FUNC int emcore_smime_set_signed_and_encrypt_message(char *recipient_li
        /* 2. Get cipher algorithm */
        cipher = emcore_get_cipher_algorithm(cipher_type);
        
-       flags = 0;
+       flags = PKCS7_BINARY;
 
        /* 3. Encrypt the signing message */    
+       bio_signed_message = BIO_new_file(temp_mime_entity_path, READMODE);
+       if (!bio_signed_message) {
+               EM_DEBUG_EXCEPTION_SEC("Cannot open output file %s", temp_mime_entity_path);
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
        encrypt_message = PKCS7_encrypt(recipient_certs, bio_signed_message, cipher, flags);
        if (encrypt_message == NULL) {
                EM_DEBUG_EXCEPTION("PKCS7_encrypt failed [%ld]", ERR_get_error());
@@ -559,6 +608,8 @@ FINISH_OFF:
        if (file_path && ret)
                *file_path = EM_SAFE_STRDUP(temp_smime_filepath);
 
+       emstorage_delete_file(temp_mime_entity_path, NULL);
+
        PKCS7_free(signed_message);
        PKCS7_free(encrypt_message);
        EVP_PKEY_free(private_key);
@@ -584,7 +635,7 @@ FINISH_OFF:
 
 INTERNAL_FUNC int emcore_smime_set_decrypt_message(char *encrypt_message, char *certificate, char **decrypt_message, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("encrypt_file : [%s], certificate : [%s]", encrypt_message, certificate);
+       EM_DEBUG_FUNC_BEGIN_SEC("encrypt_file : [%s], certificate : [%s]", encrypt_message, certificate);
        int ret = false;
        int err = EMAIL_ERROR_NONE;
        char temp_decrypt_filepath[512] = {0, };
@@ -614,11 +665,11 @@ INTERNAL_FUNC int emcore_smime_set_decrypt_message(char *encrypt_message, char *
 
        /* Initialize the output file for decrypted message */
        SNPRINTF(temp_decrypt_filepath, sizeof(temp_decrypt_filepath), "%s%s%s", MAILTEMP, DIR_SEPERATOR, DECRYPT_TEMP_FILE);
-       EM_DEBUG_LOG("attachment file path of smime : [%s]", temp_decrypt_filepath);
+       EM_DEBUG_LOG_SEC("attachment file path of smime : [%s]", temp_decrypt_filepath);
 
        out_buf = BIO_new_file(temp_decrypt_filepath, OUTMODE);
        if (!out_buf) {
-               EM_DEBUG_EXCEPTION("Cannot open output file %s", temp_decrypt_filepath);
+               EM_DEBUG_EXCEPTION_SEC("Cannot open output file %s", temp_decrypt_filepath);
                err = EMAIL_ERROR_SYSTEM_FAILURE;
                goto FINISH_OFF;
        }
@@ -740,98 +791,30 @@ FINISH_OFF:
 }
 */
 
-static char *emcore_set_mime_entity(char *mime_path)
-{
-       EM_DEBUG_FUNC_BEGIN("mime_path : [%s]", mime_path);
-       FILE *fp_read = NULL;
-       FILE *fp_write = NULL;
-       char *mime_entity = NULL;
-       char *mime_entity_path = NULL;
-       char temp_buffer[255] = {0,};
-       int err;
-       int searched = 0;
-
-       if (!emcore_get_temp_file_name(&mime_entity_path, &err))  {
-               EM_DEBUG_EXCEPTION(" em_core_get_temp_file_name failed[%d]", err);
-               goto FINISH_OFF;
-       }
-
-       /* get mime entity */
-       if (mime_path != NULL) {
-               fp_read = fopen(mime_path, "r");
-               if (fp_read == NULL) {
-                       EM_DEBUG_EXCEPTION("File open(read) is failed : filename [%s]", mime_path);
-                       goto FINISH_OFF;
-               }
-
-               fp_write = fopen(mime_entity_path, "w");
-               if (fp_write == NULL) {
-                       EM_DEBUG_EXCEPTION("File open(write) is failed : filename [%s]", mime_entity_path);
-                       goto FINISH_OFF;
-               }
-
-               fseek(fp_read, 0, SEEK_SET);
-               fseek(fp_write, 0, SEEK_SET);           
-
-               while (fgets(temp_buffer, 255, fp_read) != NULL) {
-                       mime_entity = strcasestr(temp_buffer, "content-type");
-                       if (mime_entity != NULL && !searched)
-                               searched = 1;
-
-                       if (searched) {
-                               EM_DEBUG_LOG("temp_buffer : %s", temp_buffer);
-                               fprintf(fp_write, "%s", temp_buffer);
-                       }
-               }
-       }       
-
-FINISH_OFF:
-       if (fp_read)
-               fclose(fp_read);
-
-       if (fp_write)
-               fclose(fp_write);
-
-       EM_SAFE_FREE(mime_entity);
-       EM_SAFE_FREE(mime_path);
-
-       EM_DEBUG_FUNC_END();
-       return mime_entity_path;
-}
-
 INTERNAL_FUNC int emcore_convert_mail_data_to_smime_data(emstorage_account_tbl_t *account_tbl_item, email_mail_data_t *input_mail_data, email_attachment_data_t *input_attachment_data_list, int input_attachment_count, email_mail_data_t **output_mail_data, email_attachment_data_t **output_attachment_data_list, int *output_attachment_count)
 {
        EM_DEBUG_FUNC_BEGIN("input_mail_data[%p], input_attachment_data_list [%p], input_attachment_count [%d], output_mail_data [%p], output_attachment_data_list [%p]", input_mail_data, input_attachment_data_list, input_attachment_count, output_mail_data, output_attachment_data_list);
 
-       int ret = false;
+       int i = 0, ret = false;
        int err = EMAIL_ERROR_NONE;
        int smime_type = EMAIL_SMIME_NONE;
        int address_length = 0;
        int attachment_count = input_attachment_count;
        int file_size = 0;
        char *name = NULL;
-       char *rfc822_file = NULL;
-       char *mime_entity = NULL;
        char *smime_file_path = NULL;
        char *other_certificate_list = NULL;
        email_attachment_data_t new_attachment_data = {0};
        email_attachment_data_t *new_attachment_list = NULL;
 
        /* Validating parameters */
-       
-       if (!input_mail_data || !(input_mail_data->account_id) || !(input_mail_data->mailbox_id)) {
+       if (!input_mail_data || !(input_mail_data->account_id) || !(input_mail_data->mailbox_id) 
+               || !output_attachment_count || !output_mail_data || !output_attachment_data_list ) { /*prevent#53051*/
                EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
                err = EMAIL_ERROR_INVALID_PARAM;
-               goto FINISH_OFF;
+               return ret;
        }
 
-       if (!emcore_make_rfc822_file(input_mail_data, input_attachment_data_list, attachment_count, &rfc822_file, &err))  {
-               EM_DEBUG_EXCEPTION("emcore_make_rfc822_file failed [%d]", err);
-               goto FINISH_OFF;
-       }
-
-       mime_entity = emcore_set_mime_entity(rfc822_file);
-
        smime_type = input_mail_data->smime_type;
        if (!smime_type) 
                smime_type = account_tbl_item->smime_type;
@@ -839,64 +822,61 @@ INTERNAL_FUNC int emcore_convert_mail_data_to_smime_data(emstorage_account_tbl_t
        /* Signed and Encrypt the message */
        switch (smime_type) {
        case EMAIL_SMIME_SIGNED:                        /* Clear signed message */
-               if (!emcore_smime_set_signed_message(account_tbl_item->certificate_path, mime_entity, account_tbl_item->digest_type, &smime_file_path, &err)) {
+               if (!emcore_smime_set_signed_message(account_tbl_item->certificate_path, input_mail_data->file_path_mime_entity, account_tbl_item->digest_type, &smime_file_path, &err)) {
                        EM_DEBUG_EXCEPTION("em_core_smime_set_clear_signed_message is failed : [%d]", err);
                        goto FINISH_OFF;
                }
        
-               EM_DEBUG_LOG("smime_file_path : %s", smime_file_path);  
+               EM_DEBUG_LOG_SEC("smime_file_path : %s", smime_file_path);
                name = strrchr(smime_file_path, '/');
 
                new_attachment_data.attachment_name = EM_SAFE_STRDUP(name + 1);
                new_attachment_data.attachment_path = EM_SAFE_STRDUP(smime_file_path);
+               new_attachment_data.attachment_mime_type = strdup("pkcs7-signature");
 
                attachment_count += 1;
 
                break;
        case EMAIL_SMIME_ENCRYPTED:                     /* Encryption message */
-               address_length = EM_SAFE_STRLEN(input_mail_data->full_address_to) + EM_SAFE_STRLEN(input_mail_data->full_address_cc) + EM_SAFE_STRLEN(input_mail_data->full_address_bcc);
+               address_length = EM_SAFE_STRLEN(input_mail_data->full_address_from) + EM_SAFE_STRLEN(input_mail_data->full_address_to) + EM_SAFE_STRLEN(input_mail_data->full_address_cc) + EM_SAFE_STRLEN(input_mail_data->full_address_bcc);
 
-               other_certificate_list = em_malloc(address_length + 3);
+               other_certificate_list = em_malloc(address_length + 4);
                
-               SNPRINTF(other_certificate_list, address_length + 2, "%s;%s;%s", input_mail_data->full_address_to, input_mail_data->full_address_cc, input_mail_data->full_address_bcc);
+               SNPRINTF(other_certificate_list, address_length + 2, "%s;%s;%s;%s", input_mail_data->full_address_from, input_mail_data->full_address_to, input_mail_data->full_address_cc, input_mail_data->full_address_bcc);
 
-               EM_DEBUG_LOG("to:[%s], cc:[%s], bcc:[%s]", input_mail_data->full_address_to, input_mail_data->full_address_cc, input_mail_data->full_address_bcc);
-               EM_DEBUG_LOG("length : [%d], email_address : [%s]", address_length, other_certificate_list);
-
-               if (!emcore_smime_set_encrypt_message(other_certificate_list, mime_entity, account_tbl_item->cipher_type, &smime_file_path, &err)) {
+               if (!emcore_smime_set_encrypt_message(other_certificate_list, input_mail_data->file_path_mime_entity, account_tbl_item->cipher_type, &smime_file_path, &err)) {
                        EM_DEBUG_EXCEPTION("emcore_smime_set_encrypt_message is failed : [%d]", err);
                        goto FINISH_OFF;
                }
 
-               EM_DEBUG_LOG("smime_file_path : %s", smime_file_path);  
+               EM_DEBUG_LOG_SEC("smime_file_path : %s", smime_file_path);
                name = strrchr(smime_file_path, '/');
 
                new_attachment_data.attachment_name = EM_SAFE_STRDUP(name + 1);
                new_attachment_data.attachment_path = EM_SAFE_STRDUP(smime_file_path);
+               new_attachment_data.attachment_mime_type = strdup("pkcs7-mime");
 
                attachment_count = 1;
 
                break;
        default:                        /* Signed and Encryption message */
-               address_length = EM_SAFE_STRLEN(input_mail_data->full_address_to) + EM_SAFE_STRLEN(input_mail_data->full_address_cc) + EM_SAFE_STRLEN(input_mail_data->full_address_bcc);
-
-               other_certificate_list = em_malloc(address_length + 3);
+               address_length = EM_SAFE_STRLEN(input_mail_data->full_address_from) + EM_SAFE_STRLEN(input_mail_data->full_address_to) + EM_SAFE_STRLEN(input_mail_data->full_address_cc) + EM_SAFE_STRLEN(input_mail_data->full_address_bcc);
 
-               SNPRINTF(other_certificate_list, address_length + 2, "%s;%s;%s", input_mail_data->full_address_to, input_mail_data->full_address_cc, input_mail_data->full_address_bcc);
-
-               EM_DEBUG_LOG("to:[%s], cc:[%s], bcc:[%s]", input_mail_data->full_address_to, input_mail_data->full_address_cc, input_mail_data->full_address_bcc);
-               EM_DEBUG_LOG("length : [%d], email_address : [%s]", address_length, other_certificate_list);
+               other_certificate_list = em_malloc(address_length + 4);
+               
+               SNPRINTF(other_certificate_list, address_length + 2, "%s;%s;%s;%s", input_mail_data->full_address_from, input_mail_data->full_address_to, input_mail_data->full_address_cc, input_mail_data->full_address_bcc);
 
-               if (!emcore_smime_set_signed_and_encrypt_message(other_certificate_list, account_tbl_item->certificate_path, mime_entity, account_tbl_item->cipher_type, account_tbl_item->digest_type, &smime_file_path, &err)) {
+               if (!emcore_smime_set_signed_and_encrypt_message(other_certificate_list, account_tbl_item->certificate_path, input_mail_data->file_path_mime_entity, account_tbl_item->cipher_type, account_tbl_item->digest_type, &smime_file_path, &err)) {
                        EM_DEBUG_EXCEPTION("em_core_smime_set_signed_and_encrypt_message is failed : [%d]", err);
                        goto FINISH_OFF;
                }
 
-               EM_DEBUG_LOG("smime_file_path : %s", smime_file_path);  
+               EM_DEBUG_LOG_SEC("smime_file_path : %s", smime_file_path);
                name = strrchr(smime_file_path, '/');
 
                new_attachment_data.attachment_name = EM_SAFE_STRDUP(name + 1);
                new_attachment_data.attachment_path = EM_SAFE_STRDUP(smime_file_path);
+               new_attachment_data.attachment_mime_type = strdup("pkcs7-mime");
 
                attachment_count = 1;
 
@@ -917,23 +897,46 @@ INTERNAL_FUNC int emcore_convert_mail_data_to_smime_data(emstorage_account_tbl_t
                goto FINISH_OFF;
        }
 
-       if (input_attachment_data_list != NULL)
-               new_attachment_list = input_attachment_data_list;
+       if (smime_type ==  EMAIL_SMIME_SIGNED) {
+               for (i = 0; i < input_attachment_count; i++) {
+                       new_attachment_list[i].attachment_id         = input_attachment_data_list[i].attachment_id;
+                       new_attachment_list[i].attachment_name       = EM_SAFE_STRDUP(input_attachment_data_list[i].attachment_name);
+                       new_attachment_list[i].attachment_path       = EM_SAFE_STRDUP(input_attachment_data_list[i].attachment_path);
+                       new_attachment_list[i].attachment_size       = input_attachment_data_list[i].attachment_size;
+                       new_attachment_list[i].mail_id               = input_attachment_data_list[i].mail_id;
+                       new_attachment_list[i].account_id            = input_attachment_data_list[i].account_id;
+                       new_attachment_list[i].mailbox_id            = input_attachment_data_list[i].mailbox_id;
+                       new_attachment_list[i].save_status           = input_attachment_data_list[i].save_status;
+                       new_attachment_list[i].drm_status            = input_attachment_data_list[i].drm_status;
+                       new_attachment_list[i].inline_content_status = input_attachment_data_list[i].inline_content_status;
+                       new_attachment_list[i].attachment_mime_type  = EM_SAFE_STRDUP(input_attachment_data_list[i].attachment_mime_type);
+               }
+       }
 
-       new_attachment_list[attachment_count-1] = new_attachment_data;
+       new_attachment_list[attachment_count - 1].attachment_id         = new_attachment_data.attachment_id;
+       new_attachment_list[attachment_count - 1].attachment_name       = EM_SAFE_STRDUP(new_attachment_data.attachment_name);
+       new_attachment_list[attachment_count - 1].attachment_path       = EM_SAFE_STRDUP(new_attachment_data.attachment_path);
+       new_attachment_list[attachment_count - 1].attachment_size       = new_attachment_data.attachment_size;
+       new_attachment_list[attachment_count - 1].mail_id               = new_attachment_data.mail_id;
+       new_attachment_list[attachment_count - 1].account_id            = new_attachment_data.account_id;
+       new_attachment_list[attachment_count - 1].mailbox_id            = new_attachment_data.mailbox_id;
+       new_attachment_list[attachment_count - 1].save_status           = new_attachment_data.save_status;
+       new_attachment_list[attachment_count - 1].drm_status            = new_attachment_data.drm_status;
+       new_attachment_list[attachment_count - 1].inline_content_status = new_attachment_data.inline_content_status;
+       new_attachment_list[attachment_count - 1].attachment_mime_type  = EM_SAFE_STRDUP(new_attachment_data.attachment_mime_type);
 
        input_mail_data->smime_type = smime_type;
-       input_mail_data->file_path_mime_entity = EM_SAFE_STRDUP(mime_entity);
        input_mail_data->digest_type = account_tbl_item->digest_type;
 
        ret = true;
 
 FINISH_OFF:    
-       if (output_attachment_count)
-               *output_attachment_count = attachment_count;
+
+       EM_SAFE_FREE(other_certificate_list);
+
+       *output_attachment_count = attachment_count;
        
-       if (output_attachment_data_list) 
-               *output_attachment_data_list = new_attachment_list;
+       *output_attachment_data_list = new_attachment_list;
 
        *output_mail_data = input_mail_data;
 
index 43dd9de..7414588 100755 (executable)
 #include <time.h>
 #include <unistd.h>
 #include <glib.h>
+#include <glib/gstdio.h>
 #include <alarm.h>
+#include <dlfcn.h>
+#include <ctype.h>
 
 #include "email-internal-types.h"
 #include "c-client.h"
 #include "email-core-global.h"
 #include "email-core-utils.h"
 #include "email-storage.h"
-#include "email-core-api.h"
 #include "email-core-smtp.h"
 #include "email-core-event.h"
 #include "email-core-mailbox.h"
@@ -60,6 +62,7 @@ static int emcore_get_report_mail_body(ENVELOPE *envelope, BODY **multipart_body
 #endif
 static int emcore_make_envelope_from_mail(emstorage_mail_tbl_t *input_mail_tbl_data, ENVELOPE **output_envelope);
 static int emcore_send_mail_smtp(SENDSTREAM *stream, ENVELOPE *env, char *data_file, int account_id, int mail_id,  int *err_code);
+char *emcore_generate_content_id_string(const char *hostname, int *err);
 
 /* Functions from uw-imap-toolkit */
 /* extern void *fs_get(size_t size); */
@@ -135,54 +138,78 @@ static char *emcore_find_img_tag(char *source_string)
 }
 
 #define CONTENT_ID_BUFFER_SIZE 512
-static char *emcore_replace_inline_image_path_with_content_id(char *source_string, BODY *html_body, int *err_code)
+static char *emcore_replace_inline_image_path_with_content_id(char *source_string, BODY *root_body, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("source_string[%p], html_body[%p], err_code[%p]", source_string, html_body, err_code);
+       EM_DEBUG_FUNC_BEGIN("source_string[%p], root_body[%p], err_code[%p]", source_string, root_body, err_code);
 
        int  err = EMAIL_ERROR_NONE;
-       char content_id_buffer[CONTENT_ID_BUFFER_SIZE], file_name_buffer[512], new_string[512], *result_string = NULL, *input_string = NULL;
+       char content_id_buffer[CONTENT_ID_BUFFER_SIZE] = {0,};
+       char file_name_buffer[512] = {0,};
+       char old_string[512] = {0,};
+       char new_string[512] = {0,};
+       char *result_string = NULL;
+       char *input_string = NULL;
        BODY *cur_body = NULL;
        PART *cur_part = NULL;
 
-       if (!source_string || !html_body) {
-               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+       if (!source_string || !root_body) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM [%p] [%p]", source_string, root_body);
                err = EMAIL_ERROR_INVALID_PARAM;
                goto FINISH_OFF;
        }
 
        input_string = EM_SAFE_STRDUP(source_string);
 
-       cur_part = html_body->nested.part;
-
-       while (cur_part) {
-               cur_body = &(cur_part->body);
-               result_string = NULL; /*prevent 37865*/
-               if (cur_body) {
-                       EM_DEBUG_LOG("Has body. id[%s]", cur_body->disposition.type);
-                       if (cur_body->disposition.type && cur_body->disposition.type[0] == 'i') {   /*  Is inline content? */
-                               EM_DEBUG_LOG("Has inline content");
-                               memset(content_id_buffer, 0, CONTENT_ID_BUFFER_SIZE);
-                               if (cur_body->id) {
-                                       EM_SAFE_STRNCPY(content_id_buffer, cur_body->id + 1, CONTENT_ID_BUFFER_SIZE - 1); /*  Removing <, > */
-                                       /* prevent 34413 */
-                                       char *last_bracket = rindex(content_id_buffer, '>');
-                                       *last_bracket = NULL_CHAR;
-
-                                       /* if (emcore_get_attribute_value_of_body_part(cur_body->parameter, "name", file_name_buffer, CONTENT_ID_BUFFER_SIZE, false, &err)) { */
-                                       if (emcore_get_attribute_value_of_body_part(cur_body->parameter, "name", file_name_buffer, CONTENT_ID_BUFFER_SIZE, true, &err)) {
-                                               EM_DEBUG_LOG("Content-ID[%s], filename[%s]", content_id_buffer, file_name_buffer);
-                                               SNPRINTF(new_string, CONTENT_ID_BUFFER_SIZE, "cid:%s", content_id_buffer);
-                                               result_string = em_replace_string(input_string, file_name_buffer, new_string);
+       cur_body = root_body;
+       if (root_body->type != TYPEMULTIPART) {
+               EM_DEBUG_EXCEPTION("Invalid related type : type[%d]", root_body->type);
+               err = EMAIL_ERROR_INVALID_DATA;
+               goto FINISH_OFF;
+       }
+
+       do {
+               cur_part = cur_body->nested.part;
+
+               if (strcasecmp(cur_body->subtype, "RELATED") == 0) {
+                       EM_DEBUG_LOG("Related part");
+                       while (cur_part) {
+                               cur_body = &(cur_part->body);
+
+                               if (cur_body->disposition.type && cur_body->disposition.type[0] == 'i') {   /*  Is inline content? */
+                                       EM_DEBUG_LOG("Has inline content");
+                                       memset(content_id_buffer, 0, CONTENT_ID_BUFFER_SIZE);
+                                       if (cur_body->id) {
+                                               EM_SAFE_STRNCPY(content_id_buffer, cur_body->id + 1, CONTENT_ID_BUFFER_SIZE - 1); /*  Removing <, > */
+                                               /* prevent 34413 */
+                                               char *last_bracket = rindex(content_id_buffer, '>');
+                                               *last_bracket = NULL_CHAR;
+
+                                               /* if (emcore_get_attribute_value_of_body_part(cur_body->parameter, "name", file_name_buffer, CONTENT_ID_BUFFER_SIZE, false, &err)) { */
+                                               if (emcore_get_attribute_value_of_body_part(cur_body->parameter, "name", file_name_buffer, CONTENT_ID_BUFFER_SIZE, true, &err)) {
+                                                       EM_DEBUG_LOG_SEC("Content-ID[%s], filename[%s]", content_id_buffer, file_name_buffer);
+                                                       SNPRINTF(new_string, CONTENT_ID_BUFFER_SIZE, "\"cid:%s\"", content_id_buffer);
+                                                       SNPRINTF(old_string, CONTENT_ID_BUFFER_SIZE, "\"%s\"", file_name_buffer);
+                                                       result_string = em_replace_string(input_string, old_string, new_string);
+                                               }
                                        }
                                }
+
+                               if (result_string) {
+                                       EM_SAFE_FREE(input_string);
+                                       input_string = result_string;
+                                       result_string = NULL;
+                               }
+
+                               cur_part = cur_part->next;
                        }
                }
-               if (result_string) {
-                       EM_SAFE_FREE(input_string);
-                       input_string = result_string;
-               }
-               cur_part = cur_part->next;
-       }
+
+               if (cur_part)
+                       cur_body = &(cur_part->body);
+               else 
+                       cur_body = NULL;
+
+       } while (cur_body);
 
        if (input_string)
                result_string = EM_SAFE_STRDUP(input_string);
@@ -196,22 +223,29 @@ FINISH_OFF:
        return result_string;
 }
 
-static int emcore_write_body(BODY *body, BODY *html_body, FILE *fp, int *err_code)
+static int emcore_write_body (BODY *body, BODY *root_body, FILE *fp)
 {
        EM_DEBUG_FUNC_BEGIN("fp[%d]", fp);
        char *file_path = NULL;
-       char buf[RFC822_STRING_BUFFER_SIZE + 1];
+       char buf[RFC822_STRING_BUFFER_SIZE + 1] = {0};
        char *img_tag_pos = NULL;
        char *p = NULL;
        char *replaced_string = NULL;
-       int fd, nread, nwrite, error = EMAIL_ERROR_NONE;
+       int fd = 0;
+       int nread = 0;
+       int nwrite = 0;
+       int error = EMAIL_ERROR_NONE;
        unsigned long len;
+       char *tmp_p = NULL;
+       char *tmp_file_path = NULL;
+       FILE *fp_html = NULL;
+       FILE *fp_write = NULL;
+       char *full_buf = NULL;
 
        file_path = body->sparep;
-
-       if (!file_path || EM_SAFE_STRLEN(file_path) == 0)  {
+       if (!file_path || EM_SAFE_STRLEN (file_path) == 0) {
                EM_DEBUG_LOG("There is no file path");
-               switch (body->encoding)  {
+               switch (body->encoding) {
                        case 0:
                                break;
                        default:
@@ -220,7 +254,7 @@ static int emcore_write_body(BODY *body, BODY *html_body, FILE *fp, int *err_cod
                                break;
                }
 
-               if (p)  {
+               if (p) {
                        EM_DEBUG_LOG("p[%s]", p);
                        fprintf(fp, "%s"CRLF_STRING CRLF_STRING, p);
                        EM_SAFE_FREE(p);
@@ -228,71 +262,141 @@ static int emcore_write_body(BODY *body, BODY *html_body, FILE *fp, int *err_cod
 
                EM_SAFE_FREE(body->sparep);
                EM_DEBUG_FUNC_END();
-               return true;
+               return error;
        }
 
-       EM_DEBUG_LOG("Opening a file[%s]", file_path);
-       fd = open(file_path, O_RDONLY);
+       if (body->type == TYPETEXT && body->subtype && toupper(body->subtype[0]) == 'H') {
+               EM_DEBUG_LOG ("HTML Part");
 
-       if (fd < 0) {
-               EM_DEBUG_EXCEPTION("open(\"%s\") failed...", file_path);
-               return false;
-       }
 
-       while (1) {
-               memset(&buf, 0x00, RFC822_STRING_BUFFER_SIZE + 1);
-               nread = read(fd, buf, (body->encoding == ENCBASE64 ? 57 : RFC822_READ_BLOCK_SIZE - 2));
+               struct stat st_buf;
+               unsigned int byte_read = 0;
 
-               if (nread <= 0)  {
-                       EM_DEBUG_LOG("Can't read anymore : nread[%d]", nread);
-                       break;
+               if (stat (file_path, &st_buf) < 0) {
+                       EM_DEBUG_EXCEPTION ("stat [%s] error [%d]", file_path, errno);
+                       error = EMAIL_ERROR_FILE ;
+                       goto FINISH_OFF;
                }
 
-               p = NULL;
-               len = nread;
+               if (!(fp_html = fopen (file_path, "r"))) {
+                       EM_DEBUG_EXCEPTION("fopen [%s] error [%d] ", file_path, errno);
+                       error = EMAIL_ERROR_FILE ;
+                       goto FINISH_OFF;
+               }
+
+               if (S_ISREG (st_buf.st_mode) && st_buf.st_size == 0) {
+                       EM_DEBUG_LOG ("file_path[%s] is empty size", file_path);
+                       error = EMAIL_ERROR_FILE ;
+                       goto FINISH_OFF;
+               }
+
+               if (!(full_buf = (char*) em_malloc (sizeof (char) * (st_buf.st_size + 1)))) {
+                       EM_DEBUG_EXCEPTION ("em_malloc failed");
+                       error = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
 
-               /* EM_DEBUG_LOG("body->type[%d], body->subtype[%c]", body->type, body->subtype[0]); */
+               byte_read = fread (full_buf, sizeof(char), st_buf.st_size, fp_html);
+
+               if (byte_read <= 0) {
+                       EM_SAFE_FREE (full_buf);
+                       if (ferror (fp_html)) {
+                               EM_DEBUG_EXCEPTION("fread [%s] error [%d]", file_path, errno);
+                               error = EMAIL_ERROR_FILE ;
+                               goto FINISH_OFF;
+                       }
+               } else {
+                       EM_DEBUG_LOG_DEV("==================================================");
+                       EM_DEBUG_LOG_DEV("fread : %s", full_buf);
+                       EM_DEBUG_LOG_DEV("==================================================");
 
-               if (body->type == TYPETEXT && (body->subtype && (body->subtype[0] == 'H' || body->subtype[0] == 'h'))) {
-                       EM_DEBUG_LOG("HTML Part");
-                       img_tag_pos = emcore_find_img_tag(buf);
+                       img_tag_pos = emcore_find_img_tag(full_buf);
 
                        if (img_tag_pos) {
-                               replaced_string = emcore_replace_inline_image_path_with_content_id(buf, html_body, &error);
+                               replaced_string = emcore_replace_inline_image_path_with_content_id(full_buf, root_body, &error);
                                if (replaced_string) {
                                        EM_DEBUG_LOG("emcore_replace_inline_image_path_with_content_id succeeded");
-                                       strcpy(buf, replaced_string);
-                                       nread = len = EM_SAFE_STRLEN(buf);
-                                       EM_DEBUG_LOG("buf[%s], nread[%d], len[%d]", buf, nread, len);
+                                       EM_DEBUG_LOG_DEV("==================================================");
+                                       EM_DEBUG_LOG_DEV("replaced_string : %s", replaced_string);
+                                       EM_DEBUG_LOG_DEV("==================================================");
+
+                                       if (!emcore_get_temp_file_name (&tmp_file_path, &error))  {
+                                               EM_DEBUG_EXCEPTION (" em_core_get_temp_file_name failed[%d]", error);
+                                               goto FINISH_OFF;
+                                       }
+                                       EM_DEBUG_LOG_DEV("tmp file path : %s", tmp_file_path);
+
+                                       fp_write = fopen (tmp_file_path, "w");
+                                       if (fp_write == NULL) {
+                                               EM_DEBUG_EXCEPTION_SEC ("fopen [%s] error [%d]", tmp_file_path, errno);
+                                               error = EMAIL_ERROR_FILE ;
+                                               goto FINISH_OFF;
+                                       }
+
+                                       if (fseek (fp_write, 0, SEEK_SET) < 0) {
+                                               EM_DEBUG_EXCEPTION("fseek failed : error [%d]", errno);
+                                               error = EMAIL_ERROR_FILE;
+                                               goto FINISH_OFF;
+                                       }
+
+                                       if (fprintf(fp_write, "%s", replaced_string) <= 0) {
+                                               EM_DEBUG_EXCEPTION("fprintf failed : error [%d]", errno);
+                                               error = EMAIL_ERROR_FILE;
+                                               goto FINISH_OFF;
+                                       }
+                       
+                                       file_path = tmp_file_path;
+                                       fclose(fp_write);
+                                       fp_write = NULL;
                                }
-                               else
-                                       EM_DEBUG_LOG("emcore_replace_inline_image_path_with_content_id failed[%d]", error);
                        }
                }
+       }
+
+       EM_DEBUG_LOG_DEV("Opening a file[%s]", file_path);
+
+       fd = open (file_path, O_RDONLY);
+       if (fd < 0) {
+               EM_DEBUG_EXCEPTION_SEC("open[%s] error [%d]", file_path, errno);
+               error = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       while (1) {
+               EM_SAFE_FREE (p);
+               memset(&buf, 0x00, RFC822_STRING_BUFFER_SIZE + 1);
+               nread = read(fd, buf, (body->encoding == ENCBASE64 ? 57 : RFC822_READ_BLOCK_SIZE - 2));
+
+               if (nread == 0)  {
+                       EM_DEBUG_LOG_DEV("Can't read anymore : nread[%d]", nread);
+                       break;
+               } else if (nread < 0) {
+                       EM_DEBUG_EXCEPTION ("read [%s] error [%d]", file_path, errno);
+                       error = EMAIL_ERROR_FILE;
+                       break;
+               } 
+
+               len = nread;
+
                /* EM_DEBUG_LOG("body->encoding[%d]", body->encoding); */
-//             if (body->subtype[0] != 'S' || body->subtype[0] != 's') {
                switch (body->encoding)  {
                        case ENCQUOTEDPRINTABLE:
-                               p = (char *)rfc822_8bit((unsigned char *)buf, (unsigned long)nread, (unsigned long *)&len);
+                               p = (char *) rfc822_8bit ((unsigned char *)buf, (unsigned long)nread, (unsigned long *)&len);
                                break;
                        case ENCBASE64:
-                               p = (char *)rfc822_binary((void *)buf, (unsigned long)nread, (unsigned long *)&len);
-                               break;
-                       default:
-                               buf[len] = '\0';
+                               tmp_p = g_base64_encode((guchar *)buf, (gsize)nread);
+                               p = g_strconcat(tmp_p, "\r\n", NULL);
+                               EM_SAFE_FREE(tmp_p);
+                               len = EM_SAFE_STRLEN(p);
                                break;
                }
-//             }
 
-               nwrite = fprintf(fp, "%s", (p ? p : buf));
-               if (nwrite != len)  {
-                       fclose(fp);
-                       close(fd);
-                       EM_SAFE_FREE(p);
-                       EM_DEBUG_EXCEPTION("fprintf failed nwrite[%d], len[%d]", nwrite, len);
-                       return false;
+               nwrite = fprintf (fp, "%s", (p? p:buf));
+               if (nwrite != len) {
+                       EM_DEBUG_EXCEPTION("fprintf error: nwrite[%d] len[%d] error[%d]", nwrite, len, errno);
+                       error = EMAIL_ERROR_FILE ;
+                       goto FINISH_OFF;
                }
-               EM_SAFE_FREE(p);
        }
 
        if (body->encoding == ENCQUOTEDPRINTABLE || body->encoding == ENCBASE64)
@@ -300,20 +404,27 @@ static int emcore_write_body(BODY *body, BODY *html_body, FILE *fp, int *err_cod
 
        fprintf(fp, CRLF_STRING);
 
-       if (body->sparep)  {
-               free(body->sparep);
-               body->sparep = NULL;
-       }
+FINISH_OFF: /* prevent 34226 */
 
+       /* cleanup local vars */
+       EM_SAFE_FREE (body->sparep);
        close(fd);
-
+       EM_SAFE_FREE (p);
+       if (tmp_file_path) 
+               g_remove(tmp_file_path);
+       if (fp_html) 
+               fclose (fp_html);
+       if (fp_write) 
+               fclose (fp_write);
+       EM_SAFE_FREE(full_buf);
+       EM_SAFE_FREE (replaced_string);
        EM_DEBUG_FUNC_END();
-       return true;
+       return error;
 }
 
-static int emcore_write_rfc822_body(BODY *body, BODY *html_body, FILE *fp, int *err_code)
+static int emcore_write_rfc822_body(BODY *body, BODY *root_body, FILE *fp, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("body[%p], html_body[%p], fp[%p], err_code[%p]", body, html_body, fp, err_code);
+       EM_DEBUG_FUNC_BEGIN("body[%p], fp[%p], err_code[%p]", body, fp, err_code);
 
        PARAMETER *param = NULL;
        PART *part = NULL;
@@ -322,7 +433,8 @@ static int emcore_write_rfc822_body(BODY *body, BODY *html_body, FILE *fp, int *
 
        switch (body->type)  {
                case TYPEMULTIPART:
-                       EM_DEBUG_LOG("body->type = TYPEMULTIPART");
+                       EM_DEBUG_LOG_DEV("body->type = TYPEMULTIPART");
+
                        part = body->nested.part;
 
                        for (param = body->parameter; param; param = param->next)  {
@@ -339,7 +451,7 @@ static int emcore_write_rfc822_body(BODY *body, BODY *html_body, FILE *fp, int *
 
                                fprintf(fp, "--%s"CRLF_STRING, bndry);
                                if (body->subtype[0] == 'S' || body->subtype[0] == 's') {
-                                       if (!emcore_write_body(body, html_body, fp, &error)) {
+                                       if ((error = emcore_write_body (body, root_body, fp)) != EMAIL_ERROR_NONE) {
                                                EM_DEBUG_EXCEPTION("emcore_write_body failed : [%d]", error);
                                                return false;
                                        }
@@ -348,32 +460,31 @@ static int emcore_write_rfc822_body(BODY *body, BODY *html_body, FILE *fp, int *
 
                                fprintf(fp, "%s"CRLF_STRING, buf);
 
-                               emcore_write_rfc822_body(&part->body, html_body, fp, err_code);
+                               emcore_write_rfc822_body(&part->body, root_body, fp, err_code);
                        } while ((part = part->next));
 
                        fprintf(fp, "--%s--"CRLF_STRING, bndry);
                        break;
 
-               default:  {
-                       EM_DEBUG_LOG("body->type is not TYPEMULTIPART");
+               default: 
+                       EM_DEBUG_LOG_DEV("body->type is not TYPEMULTIPART");
 
-                       if (!emcore_write_body(body, html_body, fp, &error)) {
+                       if ((error = emcore_write_body (body, root_body, fp)) != EMAIL_ERROR_NONE) {
                                EM_DEBUG_EXCEPTION("emcore_write_body failed : [%d]", error);
                                return false;
                        }
 
                        break;
-               }       /*  default: */
        }
        EM_DEBUG_FUNC_END();
        return true;
 }
 
-static int emcore_write_rfc822(ENVELOPE *env, BODY *body, BODY *html_body, email_mail_priority_t input_priority, email_mail_report_t input_report_flag, char **data, int *err_code)
+static int emcore_write_rfc822 (ENVELOPE *env, BODY *body, email_mail_priority_t input_priority, 
+                                                     email_mail_report_t input_report_flag, char **data)
 {
-       EM_DEBUG_FUNC_BEGIN("env[%p], body[%p], data[%p], err_code[%p]", env, body, data, err_code);
+       EM_DEBUG_FUNC_BEGIN("env[%p], body[%p], data[%p]", env, body, data);
 
-       int ret = false;
        int error = EMAIL_ERROR_NONE;
 
        FILE *fp = NULL;
@@ -386,7 +497,7 @@ static int emcore_write_rfc822(ENVELOPE *env, BODY *body, BODY *html_body, email
                error = EMAIL_ERROR_INVALID_PARAM;
                goto FINISH_OFF;
        }
-
+       
        srand(time(NULL));
 
        rfc822_encode_body_7bit(env, body); /*  if contents.text.data isn't NULL, the data will be encoded. */
@@ -400,7 +511,6 @@ static int emcore_write_rfc822(ENVELOPE *env, BODY *body, BODY *html_body, email
                goto FINISH_OFF;
        }
 
-
        RFC822BUFFER buf;
 
        /* write at start of buffer */
@@ -435,22 +545,22 @@ static int emcore_write_rfc822(ENVELOPE *env, BODY *body, BODY *html_body, email
                }
 
                g_strfreev(tokens);
-       } {
+       }
+
+       {
                gchar **tokens = g_strsplit(p, "To: undisclosed recipients: ;\015\012", 2);
                if (g_strv_length(tokens) > 1)
                        SNPRINTF(p, p_len, "%s%s", tokens[0], tokens[1]);
                g_strfreev(tokens);
        }
 
-
-       EM_DEBUG_LOG(" =============================================================================== "
+       EM_DEBUG_LOG_DEV(" =============================================================================== "
                LF_STRING"%s"LF_STRING
                " =============================================================================== ", p);
 
        if (EM_SAFE_STRLEN(p) > 2)
                *(p + EM_SAFE_STRLEN(p) - 2) = '\0';
 
-
        if (input_report_flag)  {
                char buf[512] = {0x00, };
 
@@ -509,15 +619,12 @@ static int emcore_write_rfc822(ENVELOPE *env, BODY *body, BODY *html_body, email
        fprintf(fp, "%s", p);
 
        if (body)  {
-               if (!emcore_write_rfc822_body(body, html_body, fp, &error))  {
+               if (!emcore_write_rfc822_body(body, body, fp, &error))  {
                        EM_DEBUG_EXCEPTION("emcore_write_rfc822_body failed[%d]", error);
                        goto FINISH_OFF;
                }
        }
 
-       ret = true;
-
-
 FINISH_OFF:
        if (fp != NULL)
                fclose(fp);
@@ -526,32 +633,33 @@ FINISH_OFF:
        emstorage_copy_file(fname, "/tmp/phone2pc.eml", false, NULL);
 #endif
 
-       if (ret == true)
+       if (error == EMAIL_ERROR_NONE)
                *data = fname;
-       else if (fname != NULL)  {
+       else if (fname != NULL) {
                remove(fname);
                EM_SAFE_FREE(fname);
        }
 
        EM_SAFE_FREE(p);
 
-       if (err_code != NULL)
-               *err_code = error;
        EM_DEBUG_FUNC_END();
-       return ret;
+       return error;
 }
 
-INTERNAL_FUNC int emcore_add_mail(email_mail_data_t *input_mail_data, email_attachment_data_t *input_attachment_data_list, int input_attachment_count, email_meeting_request_t *input_meeting_request, int input_from_eas)
+INTERNAL_FUNC int emcore_add_mail(email_mail_data_t *input_mail_data, email_attachment_data_t *input_attachment_data_list, int input_attachment_count, email_meeting_request_t *input_meeting_request, int input_from_eas, int move_flag)
 {
        EM_DEBUG_FUNC_BEGIN("input_mail_data[%p], input_attachment_data_list [%p], input_attachment_count [%d], input_meeting_request [%p], input_from_eas[%d]", input_mail_data, input_attachment_data_list, input_attachment_count, input_meeting_request, input_from_eas);
 
        int err = EMAIL_ERROR_NONE;
        int attachment_id = 0, thread_id = -1, thread_item_count = 0, latest_mail_id_in_thread = -1;
-       int i = 0, rule_len, rule_matched = -1, local_attachment_count = 0, local_inline_content_count = 0;
+       int i = 0, rule_len, priority_sender = 0, blocked = 0, local_attachment_count = 0, local_inline_content_count = 0;
        int mailbox_id_spam = 0, mailbox_id_target = 0;
-       char *ext = NULL;
+       int mail_smime_flag = 0;
        char name_buf[MAX_PATH] = {0x00, };
        char *body_text_file_name = NULL;
+       char *dl_error = NULL;
+       void *dl_handle = NULL;
+       int (*convert_mail_data_to_smime)(emstorage_account_tbl_t*, email_mail_data_t*, email_attachment_data_t*, int, email_mail_data_t**, email_attachment_data_t**, int*);
 
        int attachment_count = 0;
        email_mail_data_t *mail_data = NULL;
@@ -563,6 +671,7 @@ INTERNAL_FUNC int emcore_add_mail(email_mail_data_t *input_mail_data, email_atta
        emstorage_rule_tbl_t *rule = NULL;
        struct stat st_buf = { 0 };
        char mailbox_id_param_string[10] = {0,};
+       char errno_buf[ERRNO_BUF_SIZE] = {0};
 
 #ifdef __FEATURE_BODY_SEARCH__
        char *stripped_text = NULL;
@@ -587,10 +696,27 @@ INTERNAL_FUNC int emcore_add_mail(email_mail_data_t *input_mail_data, email_atta
        }
 
        if (input_from_eas == 0 && input_mail_data->smime_type && input_mail_data->mailbox_type != EMAIL_MAILBOX_TYPE_DRAFT) {
-               if (!emcore_convert_mail_data_to_smime_data(account_tbl_item, input_mail_data, input_attachment_data_list, input_attachment_count, &mail_data, &attachment_data_list, &attachment_count)) {
+               dl_handle = dlopen("libemail-smime-api.so.1", RTLD_LAZY);
+               if (!dl_handle) {
+                       EM_DEBUG_EXCEPTION("Open failed : [%s]", dl_handle);
+                       err = EMAIL_ERROR_INVALID_PATH;
+                       goto FINISH_OFF;
+               }
+               
+               dlerror();
+               convert_mail_data_to_smime = dlsym(dl_handle, "emcore_convert_mail_data_to_smime_data");
+               if ((dl_error = dlerror()) != NULL) {
+                       EM_DEBUG_EXCEPTION("Symbol open failed [%s]", err);
+                       err = EMAIL_ERROR_SYSTEM_FAILURE;
+                       goto FINISH_OFF;
+               }
+
+               if (!convert_mail_data_to_smime(account_tbl_item, input_mail_data, input_attachment_data_list, input_attachment_count, &mail_data, &attachment_data_list, &attachment_count)) {
                        EM_DEBUG_EXCEPTION("S/MIME failed");
                        goto FINISH_OFF;
                }
+               
+               mail_smime_flag = 1;
        } else {
                mail_data = input_mail_data;
                attachment_data_list = input_attachment_data_list;
@@ -604,7 +730,8 @@ INTERNAL_FUNC int emcore_add_mail(email_mail_data_t *input_mail_data, email_atta
                        !(input_mail_data->message_class & EMAIL_MESSAGE_CLASS_SMART_FORWARD) ) {
                if (mail_data->file_path_plain)  {
                        if (stat(mail_data->file_path_plain, &st_buf) < 0)  {
-                               EM_DEBUG_EXCEPTION("mail_data->file_path_plain, stat(\"%s\") failed...", mail_data->file_path_plain);
+                               EM_DEBUG_EXCEPTION_SEC("mail_data->file_path_plain, stat(\"%s\") failed...", mail_data->file_path_plain);
+                               EM_DEBUG_EXCEPTION("%s", EM_STRERROR(errno_buf));
                                err = EMAIL_ERROR_INVALID_MAIL;
                                goto FINISH_OFF;
                        }
@@ -612,7 +739,8 @@ INTERNAL_FUNC int emcore_add_mail(email_mail_data_t *input_mail_data, email_atta
 
                if (mail_data->file_path_html)  {
                        if (stat(mail_data->file_path_html, &st_buf) < 0)  {
-                               EM_DEBUG_EXCEPTION("mail_data->file_path_html, stat(\"%s\") failed...", mail_data->file_path_html);
+                               EM_DEBUG_EXCEPTION_SEC("mail_data->file_path_html, stat(\"%s\") failed...", mail_data->file_path_html);
+                               EM_DEBUG_EXCEPTION("%s", EM_STRERROR(errno_buf) );
                                err = EMAIL_ERROR_INVALID_MAIL;
                                goto FINISH_OFF;
                        }
@@ -634,11 +762,11 @@ INTERNAL_FUNC int emcore_add_mail(email_mail_data_t *input_mail_data, email_atta
                        input_mail_data->full_address_from = EM_SAFE_STRDUP(account_tbl_item->user_email_address);
 
                /* check for email_address validation */
-               if (!em_verify_email_address_of_mail_data(mail_data, false, &err)) {
+               if ((err = em_verify_email_address_of_mail_data (mail_data, false)) != EMAIL_ERROR_NONE) {
                        EM_DEBUG_EXCEPTION("em_verify_email_address_of_mail_data failed [%d]", err);
                        goto FINISH_OFF;
                }
-
+               
                if (mail_data->report_status & EMAIL_MAIL_REPORT_MDN)  {
                        /* check read-report mail */
                        if(!mail_data->full_address_to) { /* A report mail should have 'to' address */
@@ -656,36 +784,41 @@ INTERNAL_FUNC int emcore_add_mail(email_mail_data_t *input_mail_data, email_atta
                }
        }
        else {  /*  For Spam handling */
-               email_option_t *opt = &account_tbl_item->options;
-               EM_DEBUG_LOG("block_address [%d], block_subject [%d]", opt->block_address, opt->block_subject);
-
-               if (opt->block_address || opt->block_subject)  {
-                       int is_completed = false;
-                       int type = 0;
-
-                       if (!opt->block_address)
-                               type = EMAIL_FILTER_SUBJECT;
-                       else if (!opt->block_subject)
-                               type = EMAIL_FILTER_FROM;
-
-                       if (!emstorage_get_rule(ALL_ACCOUNT, type, 0, &rule_len, &is_completed, &rule, true, &err) || !rule)
-                               EM_DEBUG_LOG("No proper rules. emstorage_get_rule returns [%d]", err);
-               }
-
-               if (rule) {
-                       if (!emstorage_get_mailbox_id_by_mailbox_type(mail_data->account_id, EMAIL_MAILBOX_TYPE_SPAMBOX, &mailbox_id_spam, false, &err))  {
-                               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_name_by_mailbox_type failed [%d]", err);
-                               mailbox_id_spam = 0;
-                       }
+               if (mail_data->mailbox_type != EMAIL_MAILBOX_TYPE_OUTBOX) {
+                       email_option_t *opt = &account_tbl_item->options;
+                       EM_DEBUG_LOG("block_address [%d], block_subject [%d]", opt->block_address, opt->block_subject);
+
+                       if (opt->block_address || opt->block_subject)  {
+                               int is_completed = false;
+                               int type = 0;
+
+                               if (!opt->block_address)
+                                       type = EMAIL_FILTER_SUBJECT;
+                               else if (!opt->block_subject)
+                                       type = EMAIL_FILTER_FROM;
+
+                               if (!emstorage_get_rule(ALL_ACCOUNT, type, 0, &rule_len, &is_completed, &rule, true, &err) || !rule)
+                                       EM_DEBUG_LOG("No proper rules. emstorage_get_rule returns [%d]", err);
+                       
+                               if (rule && !emcore_check_rule(mail_data->full_address_from, mail_data->subject, rule, rule_len, &priority_sender, &blocked, &err)) {
+                                       EM_DEBUG_EXCEPTION("emcore_check_rule failed [%d]", err);
+                               }
+                       
+                               if (priority_sender)
+                                       mail_data->tag_id = PRIORITY_SENDER_TAG_ID;
+               
+                               if (blocked) {
+                                       EM_DEBUG_LOG("mail[%d] added to spambox", mail_data->mail_id);
+                                       if (!emstorage_get_mailbox_id_by_mailbox_type(mail_data->account_id, EMAIL_MAILBOX_TYPE_SPAMBOX, &mailbox_id_spam, false, &err))  {
+                                               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_name_by_mailbox_type failed [%d]", err);
+                                               mailbox_id_spam = 0;
+                                       }
 
-                       if (mailbox_id_spam && !emcore_check_rule(mail_data->full_address_from, mail_data->subject, rule, rule_len, &rule_matched, &err))  {
-                               EM_DEBUG_EXCEPTION("emcore_check_rule failed [%d]", err);
-                               goto FINISH_OFF;
+                                       if (mailbox_id_spam)
+                                               mailbox_id_target = mailbox_id_spam;
+                               }
                        }
-               }
-
-               if (rule_matched >= 0 && mailbox_id_spam)
-                       mailbox_id_target = mailbox_id_spam;
+               } 
        }
 
        if ((err = emstorage_get_mailbox_by_id(mailbox_id_target, (emstorage_mailbox_tbl_t**)&mailbox_tbl)) != EMAIL_ERROR_NONE) {
@@ -712,7 +845,7 @@ INTERNAL_FUNC int emcore_add_mail(email_mail_data_t *input_mail_data, email_atta
                }
 
                if (mail_data->file_path_plain) {
-                       EM_DEBUG_LOG("mail_data->file_path_plain [%s]", mail_data->file_path_plain);
+                       EM_DEBUG_LOG_SEC("mail_data->file_path_plain [%s]", mail_data->file_path_plain);
                        /* EM_SAFE_STRNCPY(body_text_file_name, "UTF-8", MAX_PATH); */
 
                        if ( (err = em_get_file_name_from_file_path(mail_data->file_path_plain, &body_text_file_name)) != EMAIL_ERROR_NONE) {
@@ -733,8 +866,8 @@ INTERNAL_FUNC int emcore_add_mail(email_mail_data_t *input_mail_data, email_atta
                                goto FINISH_OFF;
                        }
 
-                       if (!emstorage_move_file(mail_data->file_path_plain, name_buf, input_from_eas, &err)) {
-                               EM_DEBUG_EXCEPTION("emstorage_move_file failed [%d]", err);
+                       if (!emstorage_copy_file(mail_data->file_path_plain, name_buf, input_from_eas, &err)) {
+                               EM_DEBUG_EXCEPTION("emstorage_copy_file failed [%d]", err);
                                goto FINISH_OFF;
                        }
                        if (mail_data->body_download_status == EMAIL_BODY_DOWNLOAD_STATUS_NONE)
@@ -745,7 +878,7 @@ INTERNAL_FUNC int emcore_add_mail(email_mail_data_t *input_mail_data, email_atta
                }
 
                if (mail_data->file_path_html) {
-                       EM_DEBUG_LOG("mail_data->file_path_html [%s]", mail_data->file_path_html);
+                       EM_DEBUG_LOG_SEC("mail_data->file_path_html [%s]", mail_data->file_path_html);
                        /* EM_SAFE_STRNCPY(body_text_file_name, "UTF-8.htm", MAX_PATH); */
 
                        EM_SAFE_FREE(body_text_file_name);
@@ -767,8 +900,8 @@ INTERNAL_FUNC int emcore_add_mail(email_mail_data_t *input_mail_data, email_atta
                                goto FINISH_OFF;
                        }
 
-                       if (!emstorage_move_file(mail_data->file_path_html, name_buf, input_from_eas, &err))  {
-                               EM_DEBUG_EXCEPTION("emstorage_move_file failed [%d]", err);
+                       if (!emstorage_copy_file(mail_data->file_path_html, name_buf, input_from_eas, &err))  {
+                               EM_DEBUG_EXCEPTION("emstorage_copy_file failed [%d]", err);
                                goto FINISH_OFF;
                        }
 
@@ -781,15 +914,15 @@ INTERNAL_FUNC int emcore_add_mail(email_mail_data_t *input_mail_data, email_atta
        }
 
        if (mail_data->file_path_mime_entity) {
-               EM_DEBUG_LOG("mail_data->file_path_mime_entity [%s]", mail_data->file_path_mime_entity);
+               EM_DEBUG_LOG_SEC("mail_data->file_path_mime_entity [%s]", mail_data->file_path_mime_entity);
 
                if (!emstorage_get_save_name(mail_data->account_id, mail_data->mail_id, 0, "mime_entity", name_buf, &err)) {
                        EM_DEBUG_EXCEPTION("emstorage_get_save_name failed [%d]", err);
                        goto FINISH_OFF;
                }
 
-               if (!emstorage_move_file(mail_data->file_path_mime_entity, name_buf, input_from_eas, &err)) {
-                       EM_DEBUG_EXCEPTION("emstorage_move_file failed [%d]", err);
+               if (!emstorage_copy_file(mail_data->file_path_mime_entity, name_buf, input_from_eas, &err)) {
+                       EM_DEBUG_EXCEPTION("emstorage_copy_file failed [%d]", err);
                        goto FINISH_OFF;
                }
 
@@ -802,17 +935,24 @@ INTERNAL_FUNC int emcore_add_mail(email_mail_data_t *input_mail_data, email_atta
                mail_data->date_time = time(NULL);
        }
 
+       /* Generate message_id */
+       if (!input_from_eas) {
+               mail_data->message_id     = strdup(emcore_generate_content_id_string("com.samsung.slp.email", NULL));
+               mail_data->server_mail_id = strdup("0");
+       }
 
        mail_data->mailbox_id           = mailbox_id_target;
        mail_data->mailbox_type         = mailbox_tbl->mailbox_type;
        mail_data->server_mail_status   = !input_from_eas;
-       mail_data->save_status          = EMAIL_MAIL_STATUS_SAVED;
+       if(mail_data->save_status == EMAIL_MAIL_STATUS_NONE)
+               mail_data->save_status      = EMAIL_MAIL_STATUS_SAVED;
 
        /*  Getting attachment count */
        for (i = 0; i < attachment_count; i++) {
                if (attachment_data_list[i].inline_content_status== 1)
                        local_inline_content_count++;
-               local_attachment_count++;
+               else
+                       local_attachment_count++;
        }
 
        mail_data->inline_content_count = local_inline_content_count;
@@ -914,7 +1054,7 @@ INTERNAL_FUNC int emcore_add_mail(email_mail_data_t *input_mail_data, email_atta
                }
                /* if (input_from_eas == 0 || attachment_data_list[i].save_status) { */
                if (attachment_data_list[i].save_status) {
-                       if (!emstorage_copy_file(attachment_data_list[i].attachment_path, name_buf, input_from_eas, &err))  {
+                       if (!emstorage_copy_file(attachment_data_list[i].attachment_path, name_buf, input_from_eas, &err)) {
                                EM_DEBUG_EXCEPTION("emstorage_copy_file failed [%d]", err);
                                emstorage_rollback_transaction(NULL, NULL, NULL);
                                goto FINISH_OFF;
@@ -931,6 +1071,7 @@ INTERNAL_FUNC int emcore_add_mail(email_mail_data_t *input_mail_data, email_atta
                attachment_tbl.attachment_save_status           = attachment_data_list[i].save_status;
                attachment_tbl.attachment_drm_type              = attachment_data_list[i].drm_status;
                attachment_tbl.attachment_inline_content_status = attachment_data_list[i].inline_content_status;
+               attachment_tbl.attachment_mime_type             = attachment_data_list[i].attachment_mime_type;
 
                if (!emstorage_add_attachment(&attachment_tbl, 0, false, &err))  {
                        EM_DEBUG_EXCEPTION("emstorage_add_attachment failed [%d]", err);
@@ -938,7 +1079,10 @@ INTERNAL_FUNC int emcore_add_mail(email_mail_data_t *input_mail_data, email_atta
 
                        goto FINISH_OFF;
                }
-               attachment_data_list[i].attachment_id = attachment_tbl.attachment_id;
+
+               if (!mail_smime_flag) {
+                       attachment_data_list[i].attachment_id = attachment_tbl.attachment_id;
+               }
        }
 
 #ifdef __FEATURE_BODY_SEARCH__
@@ -973,7 +1117,7 @@ INTERNAL_FUNC int emcore_add_mail(email_mail_data_t *input_mail_data, email_atta
        if (!emcore_notify_storage_event(NOTI_MAIL_ADD, converted_mail_tbl->account_id, converted_mail_tbl->mail_id, mailbox_id_param_string, converted_mail_tbl->thread_id))
                EM_DEBUG_LOG("emcore_notify_storage_event [NOTI_MAIL_ADD] failed.");
 
-       if (account_tbl_item->incoming_server_type != EMAIL_SERVER_TYPE_ACTIVE_SYNC) {
+       if (account_tbl_item->incoming_server_type != EMAIL_SERVER_TYPE_ACTIVE_SYNC && !move_flag) {
                if (!emcore_remove_overflowed_mails(mailbox_tbl, &err)) {
                        if (err == EMAIL_ERROR_MAIL_NOT_FOUND || err == EMAIL_ERROR_NOT_SUPPORTED)
                                err = EMAIL_ERROR_NONE;
@@ -982,9 +1126,9 @@ INTERNAL_FUNC int emcore_add_mail(email_mail_data_t *input_mail_data, email_atta
                }
        }
 
-       if ( input_from_eas && (mail_data->flags_seen_field == 0)
-                               && mail_data->mailbox_type != EMAIL_MAILBOX_TYPE_TRASH
-                               && mail_data->mailbox_type != EMAIL_MAILBOX_TYPE_SPAMBOX) {
+       if ( input_from_eas && (mail_data->flags_seen_field == 0)) {
+//                             && mail_data->mailbox_type != EMAIL_MAILBOX_TYPE_TRASH
+//                             && mail_data->mailbox_type != EMAIL_MAILBOX_TYPE_SPAMBOX) {
                if ((err = emcore_update_sync_status_of_account(mail_data->account_id, SET_TYPE_SET, SYNC_STATUS_SYNCING | SYNC_STATUS_HAVE_NEW_MAILS)) != EMAIL_ERROR_NONE)
                                EM_DEBUG_LOG("emcore_update_sync_status_of_account failed [%d]", err);
 //             emcore_add_notification_for_unread_mail(converted_mail_tbl);
@@ -992,6 +1136,8 @@ INTERNAL_FUNC int emcore_add_mail(email_mail_data_t *input_mail_data, email_atta
        }
 
 FINISH_OFF:
+       if (dl_handle)
+               dlclose(dl_handle);
 
        EM_SAFE_FREE(body_text_file_name);
 
@@ -999,6 +1145,9 @@ FINISH_OFF:
        EM_SAFE_FREE(stripped_text);
 #endif
 
+       if (mail_smime_flag)
+               emcore_free_attachment_data(&attachment_data_list, attachment_count, NULL);
+
        if (account_tbl_item)
                emstorage_free_account(&account_tbl_item, 1, NULL);
 
@@ -1113,7 +1262,7 @@ INTERNAL_FUNC int emcore_add_read_receipt(int input_read_mail_id, int *output_re
        attachment_data->attachment_name = cpystr(p);
        */
 
-       if ( (err = emcore_add_mail(receipt_mail_data, attachment_data, attachment_count, NULL, 0)) != EMAIL_ERROR_NONE) {
+       if ( (err = emcore_add_mail(receipt_mail_data, attachment_data, attachment_count, NULL, 0, false)) != EMAIL_ERROR_NONE) {
                EM_DEBUG_EXCEPTION("emcore_add_mail failed [%d]", err);
                goto FINISH_OFF;
        }
@@ -1175,6 +1324,88 @@ FINISH_OFF:
        return ret;
 }
 
+INTERNAL_FUNC int emcore_query_mail_size_limit(int account_id, int handle, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], err_code[%p]", account_id, err_code);
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       SENDSTREAM *stream = NULL;
+       void *tmp_stream = NULL;
+       int mail_size_limit = -1;
+       email_account_t *ref_account = NULL;
+       sslstart_t stls = NULL;
+
+       if (account_id <= 0) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (!(ref_account = emcore_get_account_reference(account_id))) {
+               EM_DEBUG_EXCEPTION("emcore_get_account_reference failed [%d]", account_id);
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+
+       /*  if there is no security option, unset security. */
+       if (!ref_account->outgoing_server_secure_connection) {
+               stls = (sslstart_t)mail_parameters(NULL, GET_SSLSTART, NULL);
+               mail_parameters(NULL, SET_SSLSTART, NULL);
+       }
+
+       if (ref_account->pop_before_smtp != FALSE) {
+               if (!emcore_connect_to_remote_mailbox(account_id, 0, (void **)&tmp_stream, &err)) {
+                       EM_DEBUG_EXCEPTION(" POP before SMTP Authentication failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+       }
+
+       if (!emcore_connect_to_remote_mailbox(account_id, EMAIL_CONNECT_FOR_SENDING, (void **)&tmp_stream, &err)) {
+               EM_DEBUG_EXCEPTION(" emcore_connect_to_remote_mailbox failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       stream = (SENDSTREAM *)tmp_stream;
+
+       if (stream && stream->protocol.esmtp.ok) {
+               if (stream->protocol.esmtp.size.ok && stream->protocol.esmtp.size.limit > 0) {
+                       EM_DEBUG_LOG("Server size limit : %ld", stream->protocol.esmtp.size.limit);
+                       mail_size_limit = stream->protocol.esmtp.size.limit;
+               }
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+
+#ifndef __FEATURE_KEEP_CONNECTION__
+       if (stream)
+               smtp_close(stream);
+#endif /* __FEATURE_KEEP_CONNECTION__ */
+
+       if (stls)
+               mail_parameters(NULL, SET_SSLSTART, (void  *)stls);
+
+       if (ret == true) {
+               if (!emcore_notify_network_event(NOTI_QUERY_SMTP_MAIL_SIZE_LIMIT_FINISH, account_id, NULL, mail_size_limit, handle))
+                       EM_DEBUG_EXCEPTION("emcore_notify_network_event [NOTI_QUERY_SMTP_MAIL_SIZE_LIMIT_FINISH] Failed");
+       } else {
+               if (!emcore_notify_network_event(NOTI_QUERY_SMTP_MAIL_SIZE_LIMIT_FAIL, account_id, NULL, handle, err))
+                       EM_DEBUG_EXCEPTION("emcore_notify_network_event [NOTI_QUERY_SMTP_MAIL_SIZE_LIMIT_FAIL] Failed");
+       }
+
+       if (err_code != NULL)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END("ret [%d], err [%d]", ret, err);
+       return ret;
+}
+
 /*  send a mail */
 INTERNAL_FUNC int emcore_send_mail(int mail_id, int *err_code)
 {
@@ -1198,6 +1429,8 @@ INTERNAL_FUNC int emcore_send_mail(int mail_id, int *err_code)
        int sent_box = 0;
        emstorage_mailbox_tbl_t* local_mailbox = NULL;
        int dst_mailbox_id = 0;
+       int total_mail_size = 0;
+       int sent_flag = 0;
 
        if (!mail_id)  {
                EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
@@ -1319,6 +1552,18 @@ INTERNAL_FUNC int emcore_send_mail(int mail_id, int *err_code)
                goto FINISH_OFF;
        }
 
+       if (stream && stream->protocol.esmtp.ok) {
+               if (stream->protocol.esmtp.size.ok && stream->protocol.esmtp.size.limit > 0) {
+                       EM_DEBUG_LOG("Server size limit : %ld", stream->protocol.esmtp.size.limit);
+                       emcore_get_file_size(fpath, &total_mail_size, NULL);
+                       EM_DEBUG_LOG("mail size : %d", total_mail_size);
+                       if (total_mail_size > stream->protocol.esmtp.size.limit) {
+                               err = EMAIL_ERROR_SMTP_SEND_FAILURE_BY_OVERSIZE;
+                               goto FINISH_OFF;
+                       }
+               }
+       }
+
        /*  set request of delivery status. */
        EM_DEBUG_LOG("opt->req_delivery_receipt [%d]", opt->req_delivery_receipt);
        EM_DEBUG_LOG("mail_tbl_data->report_status [%d]", mail_tbl_data->report_status);
@@ -1332,14 +1577,18 @@ INTERNAL_FUNC int emcore_send_mail(int mail_id, int *err_code)
        }
 
        mail_tbl_data->save_status = EMAIL_MAIL_STATUS_SENDING;
+       emcore_show_user_message(mail_id, EMAIL_ACTION_SENDING_MAIL, EMAIL_ERROR_NONE);
 
        /*Update status save_status to DB*/
-       if (!emstorage_set_field_of_mails_with_integer_value(account_id, &mail_id, 1, "save_status", mail_tbl_data->save_status, false, &err))
+       if (!emstorage_set_field_of_mails_with_integer_value(account_id, &mail_id, 1, "save_status", mail_tbl_data->save_status, true, &err))
                EM_DEBUG_EXCEPTION("emstorage_set_field_of_mails_with_integer_value failed [%d]", err);
 
        /*  send mail to server. */
        if (!emcore_send_mail_smtp(stream, envelope, fpath, account_id, mail_id, &err)) {
                EM_DEBUG_EXCEPTION(" emcore_send_mail_smtp failed [%d]", err);
+               if (err == SMTP_RESPONSE_EXCEED_SIZE_LIMIT)
+                       err = EMAIL_ERROR_SMTP_SEND_FAILURE_BY_OVERSIZE;
+
 #ifndef __FEATURE_MOVE_TO_OUTBOX_FIRST__
                if (!emstorage_get_mailbox_by_mailbox_type(account_id, EMAIL_MAILBOX_TYPE_OUTBOX, &local_mailbox, false, &err))  {
                        EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_mailbox_type failed [%d]", err);
@@ -1352,6 +1601,8 @@ INTERNAL_FUNC int emcore_send_mail(int mail_id, int *err_code)
                if (!emcore_move_mail(&mail_id, 1, dst_mailbox_id, EMAIL_MOVED_BY_COMMAND, 0, NULL))
                        EM_DEBUG_EXCEPTION(" emcore_mail_move falied...");
 #endif
+               if (err > 0)
+                       err = EMAIL_ERROR_SMTP_SEND_FAILURE;
                goto FINISH_OFF;
        }
 
@@ -1368,7 +1619,6 @@ INTERNAL_FUNC int emcore_send_mail(int mail_id, int *err_code)
 #ifdef __FEATURE_SYNC_CLIENT_TO_SERVER__
 #ifdef __FEATURE_LOCAL_ACTIVITY__
                else if (ref_account->incoming_server_type == EMAIL_SERVER_TYPE_IMAP4) /* To be synced to Sent box only IMAP not for POP */ {
-
                        emstorage_activity_tbl_t new_activity;
                        int activityid = 0;
 
@@ -1410,16 +1660,33 @@ INTERNAL_FUNC int emcore_send_mail(int mail_id, int *err_code)
                }
 #endif
 #endif
-
                if (ref_account->incoming_server_type == EMAIL_SERVER_TYPE_IMAP4) {
                        emstorage_mailbox_tbl_t* src_mailbox = NULL;
+                       emstorage_mail_tbl_t *temp_mail = NULL;
+
                        if (!emstorage_get_mailbox_by_mailbox_type(account_id, EMAIL_MAILBOX_TYPE_OUTBOX, &src_mailbox, true, &err))  {
                                EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_mailbox_type failed [%d]", err);
                                goto FINISH_OFF;
                        }
 
-                       if (src_mailbox->local_yn)
-                               emcore_sync_mail_from_client_to_server(mail_id);
+                       EM_DEBUG_LOG("local_yn:[%d]", src_mailbox->local_yn);
+                       if (src_mailbox->local_yn) {
+                               if (!emcore_sync_header(local_mailbox, NULL, NULL, NULL, NULL, &err)) {
+                                       EM_DEBUG_EXCEPTION("emcore_sync_header failed");
+                               }
+
+                               if (!emstorage_get_maildata_by_servermailid(local_mailbox->mailbox_id, "0", &temp_mail, false, &err)) {
+                                       if (err != EMAIL_ERROR_MAIL_NOT_FOUND) {
+                                               EM_DEBUG_EXCEPTION("emstorage_get_maildata_by_servermailid failed : [%d]", err);
+                                               goto FINISH_OFF;
+                                       }
+                               }
+
+                               if (temp_mail) {
+                                       emcore_sync_mail_from_client_to_server(mail_id);
+                                       emstorage_free_mail(&temp_mail, 1, NULL);       
+                               }
+                       }
                        else {
                                if (!emcore_move_mail_on_server(account_id, src_mailbox->mailbox_id, &mail_id, 1, local_mailbox->mailbox_name, &err)) {
                                        EM_DEBUG_EXCEPTION(" emcore_move_mail_on_server falied [%d]", err);
@@ -1432,7 +1699,7 @@ INTERNAL_FUNC int emcore_send_mail(int mail_id, int *err_code)
                /* On Successful Mail sent remove the Draft flag */
                mail_tbl_data->flags_draft_field = 0;
 
-               if (!emstorage_set_field_of_mails_with_integer_value(account_id, &mail_id, 1, "flags_draft_field", mail_tbl_data->flags_draft_field, false, &err))
+               if (!emstorage_set_field_of_mails_with_integer_value(account_id, &mail_id, 1, "flags_draft_field", mail_tbl_data->flags_draft_field, true, &err))
                        EM_DEBUG_EXCEPTION("Failed to modify extra flag [%d]", err);
 
                sent_box = 1;
@@ -1447,9 +1714,9 @@ INTERNAL_FUNC int emcore_send_mail(int mail_id, int *err_code)
                EM_DEBUG_EXCEPTION("emcore_set_sent_contacts_log failed : [%d]", err);
        }
 
-       /*Update status save_status to DB*/
+       /*Update save_status */
        mail_tbl_data->save_status = EMAIL_MAIL_STATUS_SENT;
-       if (!emstorage_set_field_of_mails_with_integer_value(account_id, &mail_id, 1, "save_status", mail_tbl_data->save_status, false, &err))
+       if (!emstorage_set_field_of_mails_with_integer_value(account_id, &mail_id, 1, "save_status", mail_tbl_data->save_status, true, &err))
                EM_DEBUG_EXCEPTION("emstorage_set_field_of_mails_with_integer_value failed [%d]", err);
 
        if (!emcore_delete_transaction_info_by_mailId(mail_id))
@@ -1458,10 +1725,14 @@ INTERNAL_FUNC int emcore_send_mail(int mail_id, int *err_code)
        ret = true;
 
 FINISH_OFF:
+       if (ret == false && sent_flag == 0) {
+               emcore_show_user_message(mail_id, EMAIL_ACTION_SEND_MAIL, err);
+       }
+
        if (ret == false && err != EMAIL_ERROR_INVALID_PARAM && mail_tbl_data)  {
                if (err != EMAIL_ERROR_CANCELLED) {
                        mail_tbl_data->save_status = EMAIL_MAIL_STATUS_SEND_FAILURE;
-                       if (!emstorage_set_field_of_mails_with_integer_value(account_id, &mail_id, 1, "save_status", mail_tbl_data->save_status, false, &err2))
+                       if (!emstorage_set_field_of_mails_with_integer_value(account_id, &mail_id, 1, "save_status", mail_tbl_data->save_status, true, &err2))
                                EM_DEBUG_EXCEPTION("emstorage_set_field_of_mails_with_integer_value failed [%d]", err2);
                }
                else {
@@ -1469,7 +1740,7 @@ FINISH_OFF:
                                EM_DEBUG_LOG("EMAIL_MAIL_STATUS_SEND_CANCELED Already set for ");
                        else {
                                mail_tbl_data->save_status = EMAIL_MAIL_STATUS_SEND_CANCELED;
-                               if (!emstorage_set_field_of_mails_with_integer_value(account_id, &mail_id, 1, "save_status", mail_tbl_data->save_status, false, &err2))
+                               if (!emstorage_set_field_of_mails_with_integer_value(account_id, &mail_id, 1, "save_status", mail_tbl_data->save_status, true, &err2))
                                        EM_DEBUG_EXCEPTION("emstorage_set_field_of_mails_with_integer_value failed [%d]", err2);
                        }
                }
@@ -1496,7 +1767,7 @@ FINISH_OFF:
        if (fpath) {
                EM_DEBUG_LOG("REMOVE TEMP FILE  :  %s", fpath);
                remove(fpath);
-               free(fpath);
+               EM_SAFE_FREE (fpath);
        }
 
        if(local_mailbox)
@@ -1515,9 +1786,16 @@ FINISH_OFF:
                        EM_DEBUG_EXCEPTION("emcore_notify_network_event [NOTI_SEND_FAIL] Failed");
 #ifdef __FEATURE_SUPPORT_VALIDATION_SYSTEM__
                if(mail_tbl_data)
-               EM_VALIDATION_SYSTEM_LOG("INFO", mail_id, "Email Send End, %s -> %s, failed", mail_tbl_data->full_address_from, mail_tbl_data->full_address_to);
+                       EM_VALIDATION_SYSTEM_LOG("INFO", mail_id, "Email Send End, %s -> %s, failed", mail_tbl_data->full_address_from, mail_tbl_data->full_address_to);
 #endif
-               emcore_show_user_message(mail_id, EMAIL_ACTION_SEND_MAIL, err);
+
+               if (err != EMAIL_ERROR_SMTP_SEND_FAILURE_BY_OVERSIZE) {
+                       /* Add alarm for next sending mails */
+                       if( (err2 = emcore_create_alarm_for_auto_resend(AUTO_RESEND_INTERVAL)) != EMAIL_ERROR_NONE) {
+                               if (err2 != EMAIL_ERROR_MAIL_NOT_FOUND)
+                                       EM_DEBUG_EXCEPTION("emcore_create_alarm_for_auto_resend failed [%d]", err2);
+                       }
+               }
        }
 
        if (mail_tbl_data)
@@ -1537,6 +1815,7 @@ INTERNAL_FUNC int emcore_send_saved_mail(int account_id, char *input_mailbox_nam
 
        int ret = false;
        int err = EMAIL_ERROR_NONE;
+       int err2 = EMAIL_ERROR_NONE;
        int status = EMAIL_SEND_FAIL;
        int *mail_ids = NULL;
        int handle = 0;
@@ -1685,11 +1964,12 @@ INTERNAL_FUNC int emcore_send_saved_mail(int account_id, char *input_mailbox_nam
 
                if (!emcore_send_mail_smtp(stream, envelope, fpath, account_id, mail_ids[i], &err))  {
                        EM_DEBUG_EXCEPTION("emcore_send_mail_smtp failed [%d]", err);
+                       if (err == SMTP_RESPONSE_EXCEED_SIZE_LIMIT) err = EMAIL_ERROR_SMTP_SEND_FAILURE_BY_OVERSIZE;
 
                        searched_mail_tbl_data->save_status = EMAIL_MAIL_STATUS_SEND_FAILURE;
 
                        /*  update mail status to failure. */
-                       if (!emstorage_change_mail_field(mail_ids[i], UPDATE_EXTRA_FLAG, searched_mail_tbl_data, true, &err))
+                       if (!emstorage_change_mail_field(mail_ids[i], UPDATE_EXTRA_FLAG, searched_mail_tbl_data, true, &err2))
                                EM_DEBUG_EXCEPTION("emstorage_change_mail_field failed [%d]", err);
 
                        if (!emstorage_get_mailbox_by_mailbox_type(account_id, EMAIL_MAILBOX_TYPE_OUTBOX, &local_mailbox, true, &err))  {
@@ -1774,8 +2054,8 @@ FINISH_OFF:
                mail_free_envelope(&envelope);
 
        if (handle)  {
-               if (!emstorage_mail_search_end(handle, true, &err))
-                       EM_DEBUG_EXCEPTION("emstorage_mail_search_end failed [%d]", err);
+               if (!emstorage_mail_search_end(handle, true, &err2))
+                       EM_DEBUG_EXCEPTION("emstorage_mail_search_end failed [%d]", err2);
        }
 
        if (searched_mail_tbl_data)
@@ -1792,9 +2072,10 @@ FINISH_OFF:
        if(local_mailbox)
                emstorage_free_mailbox(&local_mailbox, 1, NULL);
 
-       if (ret == true)
+       if (ret == true) {
                mail_send_notify(EMAIL_SEND_FINISH, 0, 0, account_id, mail_ids[total], err);
-       else {
+               emcore_show_user_message(account_id, EMAIL_ACTION_SEND_MAIL, err);
+       } else {
                if(mail_ids) /* prevent 34385 */
                        mail_send_notify(status, 0, 0, account_id, mail_ids[total], err);
                emcore_show_user_message(account_id, EMAIL_ACTION_SEND_MAIL, err);
@@ -1810,7 +2091,7 @@ FINISH_OFF:
 
 static int emcore_send_mail_smtp(SENDSTREAM *stream, ENVELOPE *env, char *data_file, int account_id, int mail_id, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("stream[%p], env[%p], data_file[%s], account_id[%d], mail_id[%d], err_code[%p]", stream, env, data_file, account_id, mail_id, err_code);
+       EM_DEBUG_FUNC_BEGIN_SEC("stream[%p], env[%p], data_file[%s], account_id[%d], mail_id[%d], err_code[%p]", stream, env, data_file, account_id, mail_id, err_code);
        EM_PROFILE_BEGIN(profile_emcore_send_mail_smtp);
 
        int ret = false;
@@ -1983,9 +2264,10 @@ static int emcore_send_mail_smtp(SENDSTREAM *stream, ENVELOPE *env, char *data_f
        {
                char *data = NULL;
                int read_size, allocSize, dataSize, gMaxAllocSize = 40960; /*  40KB */
-
+               int total_fixed = 0;
                fseek(fp, 0, SEEK_END);
                total = ftell(fp);
+               total_fixed = total;
                fseek(fp, 0, SEEK_SET);
                EM_DEBUG_LOG("total size [%d]", total);
 
@@ -2023,7 +2305,6 @@ static int emcore_send_mail_smtp(SENDSTREAM *stream, ENVELOPE *env, char *data_f
                        }
                        sent += read_size;
 
-                       EM_DEBUG_LOG("before smtp_soutr_test");
                        if (!(send_ret = smtp_soutr_test(stream->netstream, data))) {
                                EM_SAFE_FREE(data);
                                EM_DEBUG_EXCEPTION("Failed to send the data ");
@@ -2031,11 +2312,14 @@ static int emcore_send_mail_smtp(SENDSTREAM *stream, ENVELOPE *env, char *data_f
                                goto FINISH_OFF;
                        }
                        else {
-                               sent_percent = (int) ((double)sent / (double)total * 100.0);
+                               sent_percent = (int) ((double)sent / (double)total_fixed * 100.0);
                                if (last_sent_percent + 5 <= sent_percent) {
+                                       double progress = (double)sent / (double)total_fixed;
                                        if (!emcore_notify_network_event(NOTI_SEND_START, account_id, NULL, mail_id, sent_percent))
                                                EM_DEBUG_EXCEPTION("emcore_notify_network_event [NOTI_SEND_START] Failed >>>>");
                                        last_sent_percent = sent_percent;
+
+                                       emcore_update_notification_for_send(account_id, mail_id, progress);
                                }
                                EM_DEBUG_LOG("Sent data Successfully. sent[%d] total[%d]", sent, total);
                        }
@@ -2153,9 +2437,10 @@ char *emcore_generate_content_id_string(const char *hostname, int *err)
 /*             else absolute path of file to be attached. */
 /*  data_len  :  length of data. if filename not NULL, ignored. */
 /*  file_name :  attahcment name. */
-static int attach_part(BODY *body, const unsigned char *data, int data_len, char *filename, char *content_sub_type, int is_inline, int *err_code)
+static int attach_part (BODY *body, const unsigned char *data, int data_len, 
+                                   char *filename, char *content_sub_type, int is_inline, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("body[%p], data[%s], data_len[%d], filename[%s], content_sub_type[%s], err_code[%p]", body, data, data_len, filename, content_sub_type, err_code);
+       EM_DEBUG_FUNC_BEGIN_SEC("body[%p], data[%s], data_len[%d], filename[%s], content_sub_type[%s], err_code[%p]", body, data, data_len, filename, content_sub_type, err_code);
 
        int        ret = false;
        int        error = EMAIL_ERROR_NONE;
@@ -2200,8 +2485,8 @@ static int attach_part(BODY *body, const unsigned char *data, int data_len, char
                goto FINISH_OFF;
        }
 
+       /* add it to the last */
        part->next = NULL;
-
        if (last_part)
                last_part->next = part;
        else
@@ -2224,7 +2509,7 @@ static int attach_part(BODY *body, const unsigned char *data, int data_len, char
                result_charset   = (CHARSET*)utf8_infercharset(&source_text);
 
                if(result_charset) {
-                       EM_DEBUG_LOG("return_charset->name [%s]", result_charset->name);
+                       EM_DEBUG_LOG_SEC("return_charset->name [%s]", result_charset->name);
                        encoded_file_name = (char*)g_convert (filename, -1, "UTF-8", result_charset->name, &bytes_read, &bytes_written, &glib_error);
                }
                else {
@@ -2240,7 +2525,7 @@ static int attach_part(BODY *body, const unsigned char *data, int data_len, char
                                encoded_file_name = (char*)g_convert (filename, -1, "UTF-8", "EUC-KR", &bytes_read, &bytes_written, &glib_error);
                }
 
-               EM_DEBUG_LOG("encoded_file_name [%s]", encoded_file_name);
+               EM_DEBUG_LOG_SEC("encoded_file_name [%s]", encoded_file_name);
 
                if(encoded_file_name == NULL)
                        encoded_file_name = strdup(filename);
@@ -2262,7 +2547,7 @@ static int attach_part(BODY *body, const unsigned char *data, int data_len, char
                                goto FINISH_OFF;
                        }
                        snprintf(encoded_file_name, EM_SAFE_STRLEN(result_file_name) + 15, "=?UTF-8?B?%s?=", result_file_name);
-                       EM_DEBUG_LOG("encoded_file_name [%s]", encoded_file_name);
+                       EM_DEBUG_LOG_SEC("encoded_file_name [%s]", encoded_file_name);
                }
 
                extension = em_get_extension_from_file_path(filename, NULL);
@@ -2449,7 +2734,7 @@ FINISH_OFF:
        return ret;
 }
 
-static PART *attach_mutipart_with_sub_type(BODY *parent_body, char *sub_type, int *err_code)
+static PART *attach_multipart_with_sub_type(BODY *parent_body, char *sub_type, int *err_code)
 {
        EM_DEBUG_FUNC_BEGIN("parent_body[%p], sub_type [%s], err_code[%p]", parent_body, sub_type, err_code);
 
@@ -2666,7 +2951,7 @@ static int emcore_make_envelope_from_mail(emstorage_mail_tbl_t *input_mail_tbl_d
                        if (input_mail_tbl_data->full_address_from) {
                                char *temp_address_string = NULL ;
                                em_skip_whitespace(input_mail_tbl_data->full_address_from , &temp_address_string);
-                               EM_DEBUG_LOG("address[temp_address_string][%s]", temp_address_string);
+                               EM_DEBUG_LOG_SEC("address[temp_address_string][%s]", temp_address_string);
                                rfc822_parse_adrlist(&envelope->from, temp_address_string, NULL);
                                EM_SAFE_FREE(temp_address_string);
                                temp_address_string = NULL ;
@@ -2705,8 +2990,8 @@ static int emcore_make_envelope_from_mail(emstorage_mail_tbl_t *input_mail_tbl_d
                }
        }
        else  {
-               if (!input_mail_tbl_data->full_address_from || !input_mail_tbl_data->full_address_to)  {
-                       EM_DEBUG_EXCEPTION("input_mail_tbl_data->full_address_from[%p], input_mail_tbl_data->full_address_to[%p]", input_mail_tbl_data->full_address_from, input_mail_tbl_data->full_address_to);
+               if (input_mail_tbl_data->full_address_from == NULL)  {
+                       EM_DEBUG_EXCEPTION("input_mail_tbl_data->full_address_from[%p]", input_mail_tbl_data->full_address_from);
                        error = EMAIL_ERROR_INVALID_MAIL;
                        goto FINISH_OFF;
                }
@@ -2727,14 +3012,14 @@ static int emcore_make_envelope_from_mail(emstorage_mail_tbl_t *input_mail_tbl_d
                        }
                }
                em_skip_whitespace(input_mail_tbl_data->full_address_from , &pAdd);
-               EM_DEBUG_LOG("address[pAdd][%s]", pAdd);
+               EM_DEBUG_LOG_SEC("address[pAdd][%s]", pAdd);
 
                rfc822_parse_adrlist(&envelope->from, pAdd, NULL);
                EM_SAFE_FREE(pAdd);
                pAdd = NULL;
 
                em_skip_whitespace(input_mail_tbl_data->full_address_return , &pAdd);
-               EM_DEBUG_LOG("address[pAdd][%s]", pAdd);
+               EM_DEBUG_LOG_SEC("address[pAdd][%s]", pAdd);
 
                rfc822_parse_adrlist(&envelope->return_path, pAdd, NULL);
                EM_SAFE_FREE(pAdd);
@@ -2766,16 +3051,19 @@ static int emcore_make_envelope_from_mail(emstorage_mail_tbl_t *input_mail_tbl_d
                }
        }
 
+       envelope->message_id = EM_SAFE_STRDUP(input_mail_tbl_data->message_id);
+       EM_DEBUG_LOG_SEC("message_id[%s]", envelope->message_id);
+
        em_skip_whitespace(input_mail_tbl_data->full_address_to , &pAdd);
-       EM_DEBUG_LOG("address[pAdd][%s]", pAdd);
+       EM_DEBUG_LOG_SEC("address[pAdd][%s]", pAdd);
 
        rfc822_parse_adrlist(&envelope->to, pAdd, NULL);
        EM_SAFE_FREE(pAdd);
        pAdd = NULL ;
 
-       EM_DEBUG_LOG("address[input_mail_tbl_data->full_address_cc][%s]", input_mail_tbl_data->full_address_cc);
+       EM_DEBUG_LOG_SEC("address[input_mail_tbl_data->full_address_cc][%s]", input_mail_tbl_data->full_address_cc);
        em_skip_whitespace(input_mail_tbl_data->full_address_cc , &pAdd);
-       EM_DEBUG_LOG("address[pAdd][%s]", pAdd);
+       EM_DEBUG_LOG_SEC("address[pAdd][%s]", pAdd);
 
        rfc822_parse_adrlist(&envelope->cc, pAdd, NULL);
        EM_SAFE_FREE(pAdd);
@@ -2800,11 +3088,14 @@ static int emcore_make_envelope_from_mail(emstorage_mail_tbl_t *input_mail_tbl_d
        char rfc822_date_string[DATE_STR_LENGTH] = { 0, };
        rfc822_date(rfc822_date_string);
 
+       EM_DEBUG_LOG("rfc822_date : [%s]", rfc822_date_string);
+
        if (!is_incomplete)  {
                char  localtime_string[DATE_STR_LENGTH] = { 0, };
-               strftime(localtime_string, 128, "%a, %e %b %Y %H : %M : %S ", localtime(&input_mail_tbl_data->date_time));
+               strftime(localtime_string, 128, "%a, %e %b %Y %H:%M:%S ", localtime(&input_mail_tbl_data->date_time));
+               EM_DEBUG_LOG("localtime string : [%s]", localtime_string);
                /* append last 5byes("+0900") */
-               g_strlcat(localtime_string, rfc822_date_string + (EM_SAFE_STRLEN(rfc822_date_string) -  5), DATE_STR_LENGTH);
+               g_strlcat(localtime_string, strchr(rfc822_date_string, '+'), DATE_STR_LENGTH);
                envelope->date = (unsigned char *)cpystr((const char *)localtime_string);
        }
        else {
@@ -2843,12 +3134,12 @@ INTERNAL_FUNC int emcore_make_rfc822_file_from_mail(emstorage_mail_tbl_t *input_
        int       error = EMAIL_ERROR_NONE;
        int       i = 0;
        ENVELOPE *envelope      = NULL;
+       BODY     *root_body     = NULL;
        BODY     *text_body     = NULL;
        BODY     *html_body     = NULL;
-       BODY     *root_body     = NULL;
-       PART     *part_for_html = NULL;
+       PART     *part_for_alternative = NULL;
+       PART     *part_for_related = NULL;
        PARAMETER *param = NULL;
-       PART     *part_for_text = NULL;
        char     *fname = NULL;
 
        if (!input_mail_tbl_data)  {
@@ -2868,34 +3159,39 @@ INTERNAL_FUNC int emcore_make_rfc822_file_from_mail(emstorage_mail_tbl_t *input_
                goto FINISH_OFF;
        }
 
-       EM_DEBUG_LOG("input_mail_tbl_data->file_path_plain[%s]", input_mail_tbl_data->file_path_plain);
-       EM_DEBUG_LOG("input_mail_tbl_data->file_path_html[%s]", input_mail_tbl_data->file_path_html);
-       EM_DEBUG_LOG("input_mail_tbl_data->file_path_mime_entity[%s]", input_mail_tbl_data->file_path_mime_entity);
+       EM_DEBUG_LOG_SEC("input_mail_tbl_data->file_path_plain[%s]", input_mail_tbl_data->file_path_plain);
+       EM_DEBUG_LOG_SEC("input_mail_tbl_data->file_path_html[%s]", input_mail_tbl_data->file_path_html);
+       EM_DEBUG_LOG_SEC("input_mail_tbl_data->file_path_mime_entity[%s]", input_mail_tbl_data->file_path_mime_entity);
        EM_DEBUG_LOG("input_mail_tbl_data->body->attachment_num[%d]", input_mail_tbl_data->attachment_count);
 
-       if ((input_mail_tbl_data->attachment_count > 0) || (input_mail_tbl_data->file_path_plain && input_mail_tbl_data->file_path_html))  {
-               EM_DEBUG_LOG("attachment_num [%d]", input_mail_tbl_data->attachment_count);
-
-               root_body = mail_newbody();
-
-               if (root_body == NULL)  {
-                       EM_DEBUG_EXCEPTION("mail_newbody failed...");
-                       error = EMAIL_ERROR_OUT_OF_MEMORY;
-                       goto FINISH_OFF;
-               }
+       root_body = mail_newbody();
+       if (root_body == NULL)  {
+               EM_DEBUG_EXCEPTION("mail_newbody failed...");
+               error = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
 
-               param = mail_newbody_parameter();
+       param = mail_newbody_parameter();
+       if (param == NULL) {
+               EM_DEBUG_EXCEPTION("mail_newbody_parameter failed...");
+               error = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
 
-               if (param == NULL) {
-                       EM_DEBUG_EXCEPTION("mail_newbody_parameter failed...");
-                       error = EMAIL_ERROR_OUT_OF_MEMORY;
-                       goto FINISH_OFF;
-               }
+       if (input_attachment_count > 0) {
+               /* handle the Multipart/mixed, Multipart/related and S/MIME */
+               EM_DEBUG_LOG("input_attachment_num [%d]", input_attachment_count);
+               EM_DEBUG_LOG("inline_attachment_num [%d]", input_mail_tbl_data->inline_content_count);
+               EM_DEBUG_LOG("attachment_num [%d]", input_mail_tbl_data->attachment_count);
 
                if (input_mail_tbl_data->smime_type == EMAIL_SMIME_NONE) {
-
-                       root_body->type               = TYPEMULTIPART;
-                       root_body->subtype            = strdup("MIXED");
+                       if (input_mail_tbl_data->attachment_count > 0) {
+                               root_body->type    = TYPEMULTIPART;
+                               root_body->subtype = strdup("MIXED");
+                       } else {
+                               root_body->type    = TYPEMULTIPART;
+                               root_body->subtype = strdup("RELATED");
+                       }
 
                        mail_free_body_parameter(&param);
                        param = NULL;
@@ -2932,7 +3228,6 @@ INTERNAL_FUNC int emcore_make_rfc822_file_from_mail(emstorage_mail_tbl_t *input_
                        input_attachment_count = 1;
 
                } else {
-
                        root_body->type    = TYPEAPPLICATION;
                        root_body->subtype = strdup("PKCS7-MIME");
 
@@ -2952,64 +3247,78 @@ INTERNAL_FUNC int emcore_make_rfc822_file_from_mail(emstorage_mail_tbl_t *input_
                root_body->size.bytes         = 0;
                root_body->parameter          = param;
 
-               if (input_mail_tbl_data->smime_type == EMAIL_SMIME_NONE && input_mail_tbl_data->file_path_plain && input_mail_tbl_data->file_path_html) {
-                       part_for_text = attach_mutipart_with_sub_type(root_body, "ALTERNATIVE", &error);
+               if (input_mail_tbl_data->smime_type == EMAIL_SMIME_NONE &&
+                                          (input_mail_tbl_data->file_path_plain && input_mail_tbl_data->file_path_html)) {
+                       /* Multipart/mixed -> multipart/related -> multipart/alternative  : has inline content and */
+                       /* Multipart/mixed -> Multipart/alternative */
 
-                       if (!part_for_text) {
-                               EM_DEBUG_EXCEPTION("attach_mutipart_with_sub_type [part_for_text] failed [%d]", error);
+                       if (input_mail_tbl_data->inline_content_count > 0 && (strcasecmp(root_body->subtype, "RELATED") != 0)) {
+                               part_for_related = attach_multipart_with_sub_type(root_body, "RELATED", &error);
+                               if (!part_for_related) {
+                                       EM_DEBUG_EXCEPTION("attach_multipart_with_sub_type [related] failed [%d]", error);
+                                       goto FINISH_OFF;
+                               }
+                       }
+
+                       if (part_for_related) 
+                               part_for_alternative = attach_multipart_with_sub_type(&(part_for_related->body), "ALTERNATIVE", &error);
+                       else 
+                               part_for_alternative = attach_multipart_with_sub_type(root_body, "ALTERNATIVE", &error);
+                       if (!part_for_alternative) {
+                               EM_DEBUG_EXCEPTION("attach_multipart_with_sub_type [alternative] failed [%d]", error);
                                goto FINISH_OFF;
                        }
 
-                       text_body = &part_for_text->body;
+                       if (strlen(input_mail_tbl_data->file_path_plain) > 0) {
+                               EM_DEBUG_LOG_SEC("file_path_plain[%s]", input_mail_tbl_data->file_path_plain);
 
-                       if (input_mail_tbl_data->file_path_plain && EM_SAFE_STRLEN(input_mail_tbl_data->file_path_plain) > 0) {
-                               EM_DEBUG_LOG("file_path_plain[%s]", input_mail_tbl_data->file_path_plain);
-                               if (!attach_part(text_body, (unsigned char *)input_mail_tbl_data->file_path_plain, 0, NULL, NULL, false, &error)) {
+                               text_body = &(part_for_alternative->body);
+                               if (!attach_part(text_body, (unsigned char *)input_mail_tbl_data->file_path_plain, 0, NULL, "plain", false, &error)) {
                                        EM_DEBUG_EXCEPTION("attach_part failed [%d]", error);
                                        goto FINISH_OFF;
                                }
                        }
 
-                       if (input_mail_tbl_data->file_path_html && EM_SAFE_STRLEN(input_mail_tbl_data->file_path_html) > 0) {
-                               EM_DEBUG_LOG("file_path_html[%s]", input_mail_tbl_data->file_path_html);
+                       if (strlen(input_mail_tbl_data->file_path_html) > 0) {
+                               EM_DEBUG_LOG_SEC("file_path_html[%s]", input_mail_tbl_data->file_path_html);
 
-                               part_for_html = attach_mutipart_with_sub_type(text_body, "RELATED", &error);
-                               if (!part_for_html) {
-                                       EM_DEBUG_EXCEPTION("attach_mutipart_with_sub_type [part_for_html] failed [%d]", error);
-                                       goto FINISH_OFF;
-                               }
-
-                               if (!attach_part(&(part_for_html->body) , (unsigned char *)input_mail_tbl_data->file_path_html, 0, NULL, "html", false, &error)) {
+                               html_body = &(part_for_alternative->body);
+                               if (!attach_part (html_body, (unsigned char *)input_mail_tbl_data->file_path_html, 0, NULL, "html", false, &error)) {
                                        EM_DEBUG_EXCEPTION("attach_part failed [%d]", error);
                                        goto FINISH_OFF;
                                }
                        }
-               } else if (input_mail_tbl_data->smime_type == EMAIL_SMIME_NONE && (input_mail_tbl_data->file_path_plain || input_mail_tbl_data->file_path_html)) {
+               } 
+               else if (input_mail_tbl_data->smime_type == EMAIL_SMIME_NONE && 
+                                          (input_mail_tbl_data->file_path_plain || input_mail_tbl_data->file_path_html)) {
                        if (input_mail_tbl_data->file_path_plain && EM_SAFE_STRLEN(input_mail_tbl_data->file_path_plain) > 0) {
-                               EM_DEBUG_LOG("file_path_plain[%s]", input_mail_tbl_data->file_path_plain);
-                               if (!attach_part(root_body, (unsigned char *)input_mail_tbl_data->file_path_plain, 0, NULL, NULL, false, &error)) {
+                               EM_DEBUG_LOG_SEC("file_path_plain[%s]", input_mail_tbl_data->file_path_plain);
+                               if (!attach_part (root_body, (unsigned char *) input_mail_tbl_data->file_path_plain, 0, 
+                                                                                        NULL, "plain", false, &error)) {
                                        EM_DEBUG_EXCEPTION("attach_part failed [%d]", error);
                                        goto FINISH_OFF;
                                }
                        }
 
                        if (input_mail_tbl_data->file_path_html && EM_SAFE_STRLEN(input_mail_tbl_data->file_path_html) > 0) {
-                               EM_DEBUG_LOG("file_path_html[%s]", input_mail_tbl_data->file_path_html);
-                               if (!attach_part(root_body, (unsigned char *)input_mail_tbl_data->file_path_html, 0, NULL, NULL, false, &error)) {
+                               EM_DEBUG_LOG_SEC("file_path_html[%s]", input_mail_tbl_data->file_path_html);
+                               if (!attach_part (root_body, (unsigned char *)input_mail_tbl_data->file_path_html, 0, 
+                                                                                         NULL, "html", false, &error)) {
                                        EM_DEBUG_EXCEPTION("attach_part failed [%d]", error);
                                        goto FINISH_OFF;
                                }
                        }
-               } else {
-                       EM_DEBUG_LOG("unkwon case");
+               }
+                else {
+                       EM_DEBUG_LOG("S/MIME type : [%d]", input_mail_tbl_data->smime_type);
                }
 
                if (input_mail_tbl_data->file_path_mime_entity && EM_SAFE_STRLEN(input_mail_tbl_data->file_path_mime_entity) > 0) {
-                       EM_DEBUG_LOG("file_path_mime_entity[%s]", input_mail_tbl_data->file_path_mime_entity);
+                       EM_DEBUG_LOG_SEC("file_path_mime_entity[%s]", input_mail_tbl_data->file_path_mime_entity);
                        root_body->sparep = EM_SAFE_STRDUP(input_mail_tbl_data->file_path_mime_entity);
                }
 
-               if (input_attachment_tbl && input_attachment_count)  {
+               if (input_attachment_tbl && input_attachment_count) {
                        emstorage_attachment_tbl_t *temp_attachment_tbl = NULL;
                        char *name = NULL;
                        BODY *body_to_attach = NULL;
@@ -3017,7 +3326,7 @@ INTERNAL_FUNC int emcore_make_rfc822_file_from_mail(emstorage_mail_tbl_t *input_
 
                        for(i = 0; i < input_attachment_count; i++) {
                                temp_attachment_tbl = input_attachment_tbl + i;
-                               EM_DEBUG_LOG("attachment_name[%s], attachment_path[%s]", temp_attachment_tbl->attachment_name, temp_attachment_tbl->attachment_path);
+                               EM_DEBUG_LOG_SEC("attachment_name[%s], attachment_path[%s]", temp_attachment_tbl->attachment_name, temp_attachment_tbl->attachment_path);
                                if (stat(temp_attachment_tbl->attachment_path, &st_buf) == 0)  {
                                        if (!temp_attachment_tbl->attachment_name)  {
                                                if (!emcore_get_file_name(temp_attachment_tbl->attachment_path, &name, &error))  {
@@ -3028,10 +3337,10 @@ INTERNAL_FUNC int emcore_make_rfc822_file_from_mail(emstorage_mail_tbl_t *input_
                                        else
                                                name = temp_attachment_tbl->attachment_name;
 
-                                       EM_DEBUG_LOG("name[%s]", name);
+                                       EM_DEBUG_LOG_SEC("name[%s]", name);
 
-                                       if (temp_attachment_tbl->attachment_inline_content_status && part_for_html)
-                                               body_to_attach = &(part_for_html->body);
+                                       if (temp_attachment_tbl->attachment_inline_content_status && part_for_related)
+                                               body_to_attach = &(part_for_related->body);
                                        else
                                                body_to_attach = root_body;
 
@@ -3044,29 +3353,51 @@ INTERNAL_FUNC int emcore_make_rfc822_file_from_mail(emstorage_mail_tbl_t *input_
                }
                text_body = NULL;
        }
-       else {
-               text_body = mail_newbody();
+       else if (input_mail_tbl_data->file_path_plain && input_mail_tbl_data->file_path_html) {
+               /* Handle the Multipart/alternative */
+               root_body->type    = TYPEMULTIPART;
+               root_body->subtype = strdup("ALTERNATIVE");
 
-               if (text_body == NULL)  {
-                       EM_DEBUG_EXCEPTION("mail_newbody failed...");
+               mail_free_body_parameter(&param);
+               param = NULL;
 
-                       error = EMAIL_ERROR_OUT_OF_MEMORY;
-                       goto FINISH_OFF;
+               root_body->contents.text.data = NULL;
+               root_body->contents.text.size = 0;
+               root_body->size.bytes         = 0;
+               root_body->parameter          = param;
+
+               if (strlen(input_mail_tbl_data->file_path_plain) > 0) {
+                       EM_DEBUG_LOG_SEC("file_path_plain[%s]", input_mail_tbl_data->file_path_plain);
+
+                       if (!attach_part(root_body, (unsigned char *)input_mail_tbl_data->file_path_plain, 0, NULL, "plain", false, &error)) {
+                               EM_DEBUG_EXCEPTION("attach_part failed [%d]", error);
+                               goto FINISH_OFF;
+                       }
                }
 
-               text_body->type = TYPETEXT;
-               text_body->encoding = ENC8BIT;
+               if (strlen(input_mail_tbl_data->file_path_html) > 0) {
+                       EM_DEBUG_LOG_SEC("file_path_html[%s]", input_mail_tbl_data->file_path_html);
+
+                       if (!attach_part (root_body, (unsigned char *)input_mail_tbl_data->file_path_html, 0, NULL, "html", false, &error)) {
+                               EM_DEBUG_EXCEPTION("attach_part failed [%d]", error);
+                               goto FINISH_OFF;
+                       }
+               }
+       }
+       else {
+               root_body->type = TYPETEXT;
+               root_body->encoding = ENC8BIT;
                if (input_mail_tbl_data->file_path_plain || input_mail_tbl_data->file_path_html)
-                       text_body->sparep = EM_SAFE_STRDUP(input_mail_tbl_data->file_path_plain ? input_mail_tbl_data->file_path_plain  :  input_mail_tbl_data->file_path_html);
+                       root_body->sparep = EM_SAFE_STRDUP(input_mail_tbl_data->file_path_plain ? input_mail_tbl_data->file_path_plain  :  input_mail_tbl_data->file_path_html);
                else
-                       text_body->sparep = NULL;
+                       root_body->sparep = NULL;
 
                if (input_mail_tbl_data->file_path_html != NULL && input_mail_tbl_data->file_path_html[0] != '\0')
-                       text_body->subtype = strdup("html");
-               if (text_body->sparep)
-                       text_body->size.bytes = EM_SAFE_STRLEN(text_body->sparep);
+                       root_body->subtype = strdup("html");
+               if (root_body->sparep)
+                       root_body->size.bytes = EM_SAFE_STRLEN(root_body->sparep);
                else
-                       text_body->size.bytes = 0;
+                       root_body->size.bytes = 0;
        }
 
 
@@ -3079,10 +3410,8 @@ INTERNAL_FUNC int emcore_make_rfc822_file_from_mail(emstorage_mail_tbl_t *input_
        if (file_path)  {
                EM_DEBUG_LOG("write rfc822 : file_path[%p]", file_path);
 
-               if (part_for_html)
-                       html_body = &(part_for_html->body);
-
-               if (!emcore_write_rfc822(envelope, root_body ? root_body : text_body, html_body, input_mail_tbl_data->priority, input_mail_tbl_data->report_status, &fname, &error))  {
+               if ((error = emcore_write_rfc822 (envelope, root_body, input_mail_tbl_data->priority, 
+                                                    input_mail_tbl_data->report_status, &fname)) != EMAIL_ERROR_NONE) {
                        EM_DEBUG_EXCEPTION("emcore_write_rfc822 failed [%d]", error);
                        goto FINISH_OFF;
                }
@@ -3121,7 +3450,6 @@ INTERNAL_FUNC int emcore_make_rfc822_file(email_mail_data_t *input_mail_tbl_data
        int       i                    = 0;
        ENVELOPE *envelope             = NULL;
        BODY     *text_body            = NULL;
-       BODY     *html_body            = NULL;
        BODY     *root_body            = NULL;
        PART     *part_for_html        = NULL;
        PART     *part_for_text        = NULL;
@@ -3177,7 +3505,7 @@ INTERNAL_FUNC int emcore_make_rfc822_file(email_mail_data_t *input_mail_tbl_data
                        if (input_mail_tbl_data->full_address_from) {
                                char *temp_address_string = NULL ;
                                em_skip_whitespace(input_mail_tbl_data->full_address_from , &temp_address_string);
-                               EM_DEBUG_LOG("address[temp_address_string][%s]", temp_address_string);
+                               EM_DEBUG_LOG_SEC("address[temp_address_string][%s]", temp_address_string);
                                rfc822_parse_adrlist(&envelope->from, temp_address_string, ref_account->outgoing_server_address);
                                EM_SAFE_FREE(temp_address_string);
                                temp_address_string = NULL ;
@@ -3237,14 +3565,14 @@ INTERNAL_FUNC int emcore_make_rfc822_file(email_mail_data_t *input_mail_tbl_data
                        }
                }
                        em_skip_whitespace(input_mail_tbl_data->full_address_from , &pAdd);
-               EM_DEBUG_LOG("address[pAdd][%s]", pAdd);
+               EM_DEBUG_LOG_SEC("address[pAdd][%s]", pAdd);
 
                rfc822_parse_adrlist(&envelope->from, pAdd, ref_account->outgoing_server_address);
                EM_SAFE_FREE(pAdd);
                        pAdd = NULL ;
 
                em_skip_whitespace(input_mail_tbl_data->full_address_return , &pAdd);
-               EM_DEBUG_LOG("address[pAdd][%s]", pAdd);
+               EM_DEBUG_LOG_SEC("address[pAdd][%s]", pAdd);
 
                rfc822_parse_adrlist(&envelope->return_path, pAdd, ref_account->outgoing_server_address);
                EM_SAFE_FREE(pAdd);
@@ -3277,15 +3605,15 @@ INTERNAL_FUNC int emcore_make_rfc822_file(email_mail_data_t *input_mail_tbl_data
        }
 
        em_skip_whitespace(input_mail_tbl_data->full_address_to , &pAdd);
-       EM_DEBUG_LOG("address[pAdd][%s]", pAdd);
+       EM_DEBUG_LOG_SEC("address[pAdd][%s]", pAdd);
 
        rfc822_parse_adrlist(&envelope->to, pAdd, ref_account->outgoing_server_address);
        EM_SAFE_FREE(pAdd);
        pAdd = NULL ;
 
-       EM_DEBUG_LOG("address[input_mail_tbl_data->full_address_cc][%s]", input_mail_tbl_data->full_address_cc);
+       EM_DEBUG_LOG_SEC("address[input_mail_tbl_data->full_address_cc][%s]", input_mail_tbl_data->full_address_cc);
        em_skip_whitespace(input_mail_tbl_data->full_address_cc , &pAdd);
-       EM_DEBUG_LOG("address[pAdd][%s]", pAdd);
+       EM_DEBUG_LOG_SEC("address[pAdd][%s]", pAdd);
 
        rfc822_parse_adrlist(&envelope->cc, pAdd, ref_account->outgoing_server_address);
        EM_SAFE_FREE(pAdd);
@@ -3324,8 +3652,8 @@ INTERNAL_FUNC int emcore_make_rfc822_file(email_mail_data_t *input_mail_tbl_data
        /*  check report input_mail_tbl_data */
 
        /* Non-report input_mail_tbl_data */
-       EM_DEBUG_LOG("input_mail_tbl_data->file_path_plain[%s]", input_mail_tbl_data->file_path_plain);
-       EM_DEBUG_LOG("input_mail_tbl_data->file_path_html[%s]", input_mail_tbl_data->file_path_html);
+       EM_DEBUG_LOG_SEC("input_mail_tbl_data->file_path_plain[%s]", input_mail_tbl_data->file_path_plain);
+       EM_DEBUG_LOG_SEC("input_mail_tbl_data->file_path_html[%s]", input_mail_tbl_data->file_path_html);
        EM_DEBUG_LOG("input_mail_tbl_data->body->attachment_num[%d]", input_mail_tbl_data->attachment_count);
 
        if (input_mail_tbl_data->file_path_plain) {
@@ -3364,17 +3692,17 @@ INTERNAL_FUNC int emcore_make_rfc822_file(email_mail_data_t *input_mail_tbl_data
                root_body->contents.text.size = 0;
                root_body->size.bytes         = 0;
 
-               part_for_text = attach_mutipart_with_sub_type(root_body, "ALTERNATIVE", &error);
+               part_for_text = attach_multipart_with_sub_type(root_body, "ALTERNATIVE", &error);
 
                if (!part_for_text) {
-                       EM_DEBUG_EXCEPTION("attach_mutipart_with_sub_type [part_for_text] failed [%d]", error);
+                       EM_DEBUG_EXCEPTION("attach_multipart_with_sub_type [part_for_text] failed [%d]", error);
                        goto FINISH_OFF;
                }
 
                text_body = &part_for_text->body;
 
                if (input_mail_tbl_data->file_path_plain && EM_SAFE_STRLEN(input_mail_tbl_data->file_path_plain) > 0)  {
-                       EM_DEBUG_LOG("file_path_plain[%s]", input_mail_tbl_data->file_path_plain);
+                       EM_DEBUG_LOG_SEC("file_path_plain[%s]", input_mail_tbl_data->file_path_plain);
                        if (!attach_part(text_body, (unsigned char *)temp_file_path_plain, 0, NULL, NULL, false, &error))  {
                                EM_DEBUG_EXCEPTION("attach_part failed [%d]", error);
                                goto FINISH_OFF;
@@ -3382,11 +3710,11 @@ INTERNAL_FUNC int emcore_make_rfc822_file(email_mail_data_t *input_mail_tbl_data
                }
 
                if (input_mail_tbl_data->file_path_html && EM_SAFE_STRLEN(input_mail_tbl_data->file_path_html) > 0)  {
-                       EM_DEBUG_LOG("file_path_html[%s]", input_mail_tbl_data->file_path_html);
+                       EM_DEBUG_LOG_SEC("file_path_html[%s]", input_mail_tbl_data->file_path_html);
 
-                       part_for_html = attach_mutipart_with_sub_type(text_body, "RELATED", &error);
+                       part_for_html = attach_multipart_with_sub_type(text_body, "RELATED", &error);
                        if (!part_for_html) {
-                               EM_DEBUG_EXCEPTION("attach_mutipart_with_sub_type [part_for_html] failed [%d]", error);
+                               EM_DEBUG_EXCEPTION("attach_multipart_with_sub_type [part_for_html] failed [%d]", error);
                                goto FINISH_OFF;
                        }
 
@@ -3404,7 +3732,7 @@ INTERNAL_FUNC int emcore_make_rfc822_file(email_mail_data_t *input_mail_tbl_data
 
                        for(i = 0; i < input_attachment_count; i++) {
                                temp_attachment_tbl = input_attachment_tbl + i;
-                               EM_DEBUG_LOG("attachment_name[%s], attachment_path[%s]", temp_attachment_tbl->attachment_name, temp_attachment_tbl->attachment_path);
+                               EM_DEBUG_LOG_SEC("attachment_name[%s], attachment_path[%s]", temp_attachment_tbl->attachment_name, temp_attachment_tbl->attachment_path);
                                if (stat(temp_attachment_tbl->attachment_path, &st_buf) == 0)  {
                                        if (!temp_attachment_tbl->attachment_name)  {
                                                if (!emcore_get_file_name(temp_attachment_tbl->attachment_path, &name, &error))  {
@@ -3414,7 +3742,7 @@ INTERNAL_FUNC int emcore_make_rfc822_file(email_mail_data_t *input_mail_tbl_data
                                        }
                                        else
                                                name = temp_attachment_tbl->attachment_name;
-                                       EM_DEBUG_LOG("name[%s]", name);
+                                       EM_DEBUG_LOG_SEC("name[%s]", name);
 
                                        if (temp_attachment_tbl->inline_content_status && part_for_html)
                                                body_to_attach = &(part_for_html->body);
@@ -3429,7 +3757,8 @@ INTERNAL_FUNC int emcore_make_rfc822_file(email_mail_data_t *input_mail_tbl_data
                        }
                }
                text_body = NULL;
-       } else  {
+       } 
+       else  {
                text_body = mail_newbody();
 
                if (text_body == NULL)  {
@@ -3455,12 +3784,8 @@ INTERNAL_FUNC int emcore_make_rfc822_file(email_mail_data_t *input_mail_tbl_data
        }
 
        if (file_path)  {
-               EM_DEBUG_LOG("write rfc822  :  file_path[%s]", file_path);
-
-               if (part_for_html)
-                       html_body = &(part_for_html->body);
-
-               if (!emcore_write_rfc822(envelope, root_body ? root_body  :  text_body, html_body, input_mail_tbl_data->priority, input_mail_tbl_data->report_status, &fname, &error))  {
+               if ((error = emcore_write_rfc822 (envelope, (root_body? root_body: text_body), input_mail_tbl_data->priority,
+                                                   input_mail_tbl_data->report_status, &fname)) != EMAIL_ERROR_NONE) {
                        EM_DEBUG_EXCEPTION("emcore_write_rfc822 failed [%d]", error);
                        goto FINISH_OFF;
                }
@@ -3693,7 +4018,7 @@ INTERNAL_FUNC int emcore_get_body_buff(char *file_path, char **buff)
                r_fp = fopen(file_path, "r");
 
        if (!r_fp) {
-               EM_DEBUG_EXCEPTION(" Filename %s failed to open", file_path);
+               EM_DEBUG_EXCEPTION_SEC(" Filename %s failed to open", file_path);
                goto FINISH_OFF;
        }
 
@@ -3706,7 +4031,7 @@ INTERNAL_FUNC int emcore_get_body_buff(char *file_path, char **buff)
        }
 
        if (ferror(r_fp)) {
-               EM_DEBUG_EXCEPTION("file read failed - %s", file_path);
+               EM_DEBUG_EXCEPTION_SEC("file read failed - %s", file_path);
                EM_SAFE_FREE(read_buff);
                goto FINISH_OFF;
        }
@@ -3866,15 +4191,14 @@ FINISH_OFF:
 
 /* Scheduled sending ------------------------------------------------ */
 
-
-static int emcore_sending_alarm_cb(int input_timer_id, void *user_parameter)
+static int emcore_sending_alarm_cb(int input_alarm_id, void *user_parameter)
 {
-       EM_DEBUG_FUNC_BEGIN("input_timer_id [%d] user_parameter [%p]", input_timer_id, user_parameter);
+       EM_DEBUG_FUNC_BEGIN("input_alarm_id [%d] user_parameter [%p]", input_alarm_id, user_parameter);
        int err = EMAIL_ERROR_NONE;
        int ret = 0;
        email_alarm_data_t *alarm_data = NULL;
 
-       if (((err = emcore_get_alarm_data_by_alarm_id(input_timer_id, &alarm_data)) != EMAIL_ERROR_NONE) || alarm_data == NULL) {
+       if (((err = emcore_get_alarm_data_by_alarm_id(input_alarm_id, &alarm_data)) != EMAIL_ERROR_NONE) || alarm_data == NULL) {
                EM_DEBUG_EXCEPTION("emcore_get_alarm_data_by_alarm_id failed [%d]", err);
                goto FINISH_OFF;
        }
@@ -3885,13 +4209,8 @@ static int emcore_sending_alarm_cb(int input_timer_id, void *user_parameter)
                goto FINISH_OFF;
        }
 
-       /* delete alarm info*/
-       emcore_delete_alram_data_from_alarm_data_list(alarm_data);
-
 FINISH_OFF:
 
-       EM_SAFE_FREE(alarm_data);
-
        EM_DEBUG_FUNC_END("err [%d]", err);
        return err;
 }
@@ -3909,11 +4228,12 @@ INTERNAL_FUNC int emcore_schedule_sending_mail(int input_mail_id, time_t input_t
                goto FINISH_OFF;
        }
 
-       /* set save_status as EMAIL_MAIL_STATUS_SEND_SCHEDULED */
+       /*
        if (!emstorage_set_field_of_mails_with_integer_value(mail_data->account_id, &(mail_data->mail_id), 1, "save_status", EMAIL_MAIL_STATUS_SEND_SCHEDULED, true, &err)) {
                EM_DEBUG_EXCEPTION("emstorage_set_field_of_mails_with_integer_value failed [%d]", err);
                goto FINISH_OFF;
        }
+       */
 
        if (!emstorage_set_field_of_mails_with_integer_value(mail_data->account_id, &(mail_data->mail_id), 1, "scheduled_sending_time", input_time_to_send, true, &err)) {
                EM_DEBUG_EXCEPTION("emstorage_set_field_of_mails_with_integer_value failed [%d]", err);
@@ -3934,3 +4254,181 @@ FINISH_OFF:
        return err;
 }
 /* Scheduled sending ------------------------------------------------ */
+
+#ifdef __FEATURE_AUTO_RETRY_SEND__
+
+static int emcore_auto_resend_cb(int input_alarm_id, void *user_parameter)
+{
+       EM_DEBUG_FUNC_BEGIN("input_alarm_id [%d] user_parameter [%p]", input_alarm_id, user_parameter);
+       int err = EMAIL_ERROR_NONE;
+       char *conditional_clause_string = NULL;
+       char *attribute_field_name = NULL;
+       email_list_filter_t filter_list[5];
+       email_mail_list_item_t *result_mail_list = NULL;
+       email_list_sorting_rule_t sorting_rule_list[2];
+       int filter_rule_count = 5;
+       int sorting_rule_count = 2;
+       int result_mail_count = 0;
+       int i = 0;
+
+       /* Get all mails have remaining resend counts in outbox with status 'EMAIL_MAIL_STATUS_SEND_FAILURE or EMAIL_MAIL_STATUS_SEND_WAIT' */
+       attribute_field_name = emcore_get_mail_field_name_by_attribute_type(EMAIL_MAIL_ATTRIBUTE_REMAINING_RESEND_TIMES);
+
+       memset(filter_list, 0 , sizeof(email_list_filter_t) * filter_rule_count);
+       memset(sorting_rule_list, 0 , sizeof(email_list_sorting_rule_t) * sorting_rule_count);
+
+       filter_list[0].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_RULE;
+       filter_list[0].list_filter_item.rule.target_attribute              = EMAIL_MAIL_ATTRIBUTE_REMAINING_RESEND_TIMES;
+       filter_list[0].list_filter_item.rule.rule_type                     = EMAIL_LIST_FILTER_RULE_GREATER_THAN;
+       filter_list[0].list_filter_item.rule.key_value.integer_type_value  = 0;
+
+       filter_list[1].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_OPERATOR;
+       filter_list[1].list_filter_item.operator_type                      = EMAIL_LIST_FILTER_OPERATOR_AND;
+
+       filter_list[2].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_RULE;
+       filter_list[2].list_filter_item.rule.target_attribute              = EMAIL_MAIL_ATTRIBUTE_MAILBOX_TYPE;
+       filter_list[2].list_filter_item.rule.rule_type                     = EMAIL_LIST_FILTER_RULE_EQUAL;
+       filter_list[2].list_filter_item.rule.key_value.integer_type_value  = EMAIL_MAILBOX_TYPE_OUTBOX;
+
+       filter_list[3].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_OPERATOR;
+       filter_list[3].list_filter_item.operator_type                      = EMAIL_LIST_FILTER_OPERATOR_AND;
+
+       filter_list[4].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_RULE;
+       filter_list[4].list_filter_item.rule.target_attribute              = EMAIL_MAIL_ATTRIBUTE_SAVE_STATUS;
+       filter_list[4].list_filter_item.rule.rule_type                     = EMAIL_LIST_FILTER_RULE_EQUAL;
+       filter_list[4].list_filter_item.rule.key_value.integer_type_value  = EMAIL_MAIL_STATUS_SEND_FAILURE;
+
+       sorting_rule_list[0].target_attribute                              = EMAIL_MAIL_ATTRIBUTE_ACCOUNT_ID;
+       sorting_rule_list[0].sort_order                                    = EMAIL_SORT_ORDER_ASCEND;
+
+       sorting_rule_list[1].target_attribute                              = EMAIL_MAIL_ATTRIBUTE_MAIL_ID;
+       sorting_rule_list[1].sort_order                                    = EMAIL_SORT_ORDER_ASCEND;
+
+       if( (err = emstorage_write_conditional_clause_for_getting_mail_list(filter_list, filter_rule_count, sorting_rule_list, sorting_rule_count, -1, -1, &conditional_clause_string)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emstorage_write_conditional_clause_for_getting_mail_list failed[%d]", err);
+               goto FINISH_OFF;
+       }
+
+       EM_DEBUG_LOG("conditional_clause_string[%s].", conditional_clause_string);
+
+       if(!emstorage_query_mail_list(conditional_clause_string, true, &result_mail_list, &result_mail_count, &err) && !result_mail_list) {
+               EM_DEBUG_LOG("There is no mails to be sent [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       /* Send mails in loop */
+
+       for(i = 0; i < result_mail_count; i++) {
+               if(!emcore_send_mail(result_mail_list[i].mail_id, &err)) {
+                       EM_DEBUG_EXCEPTION("emcore_send_mail failed [%d]", err);
+               }
+
+               if(attribute_field_name) {
+                       if(!emstorage_set_field_of_mails_with_integer_value(result_mail_list[i].account_id, &(result_mail_list[i].mail_id), 1, attribute_field_name, result_mail_list[i].remaining_resend_times - 1, true, &err)) {
+                               EM_DEBUG_EXCEPTION("emstorage_set_field_of_mails_with_integer_value failed [%d]", err);
+                       }
+               }
+       }
+
+FINISH_OFF:
+
+       EM_SAFE_FREE(result_mail_list);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC int emcore_create_alarm_for_auto_resend(int input_alarm_interval_in_second)
+{
+       EM_DEBUG_FUNC_BEGIN("input_alarm_interval_in_second[%d]", input_alarm_interval_in_second);
+       int err = EMAIL_ERROR_NONE;
+       time_t current_time;
+       time_t trigger_at_time;
+       char *conditional_clause_string = NULL;
+       char *attribute_field_name = NULL;
+       email_list_filter_t filter_list[5];
+       email_mail_list_item_t *result_mail_list = NULL;
+       email_list_sorting_rule_t sorting_rule_list[2];
+       int filter_rule_count = 5;
+       int sorting_rule_count = 2;
+       int result_mail_count = 0;
+
+       if(input_alarm_interval_in_second <= 0) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       /* Check whether the alarm is already existing */
+       if(emcore_check_alarm_by_class_id(EMAIL_ALARM_CLASS_AUTO_RESEND) == EMAIL_ERROR_NONE) {
+               /* already exist */
+               err = EMAIL_ERROR_ALREADY_EXISTS;
+               goto FINISH_OFF;
+       }
+       /* Get all mails have remaining resend counts in outbox with status 'EMAIL_MAIL_STATUS_SEND_FAILURE or EMAIL_MAIL_STATUS_SEND_WAIT' */
+       attribute_field_name = emcore_get_mail_field_name_by_attribute_type(EMAIL_MAIL_ATTRIBUTE_REMAINING_RESEND_TIMES);
+
+       memset(filter_list, 0 , sizeof(email_list_filter_t) * filter_rule_count);
+       memset(sorting_rule_list, 0 , sizeof(email_list_sorting_rule_t) * sorting_rule_count);
+
+       filter_list[0].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_RULE;
+       filter_list[0].list_filter_item.rule.target_attribute              = EMAIL_MAIL_ATTRIBUTE_REMAINING_RESEND_TIMES;
+       filter_list[0].list_filter_item.rule.rule_type                     = EMAIL_LIST_FILTER_RULE_GREATER_THAN;
+       filter_list[0].list_filter_item.rule.key_value.integer_type_value  = 0;
+
+       filter_list[1].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_OPERATOR;
+       filter_list[1].list_filter_item.operator_type                      = EMAIL_LIST_FILTER_OPERATOR_AND;
+
+       filter_list[2].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_RULE;
+       filter_list[2].list_filter_item.rule.target_attribute              = EMAIL_MAIL_ATTRIBUTE_MAILBOX_TYPE;
+       filter_list[2].list_filter_item.rule.rule_type                     = EMAIL_LIST_FILTER_RULE_EQUAL;
+       filter_list[2].list_filter_item.rule.key_value.integer_type_value  = EMAIL_MAILBOX_TYPE_OUTBOX;
+
+       filter_list[3].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_OPERATOR;
+       filter_list[3].list_filter_item.operator_type                      = EMAIL_LIST_FILTER_OPERATOR_AND;
+
+       filter_list[4].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_RULE;
+       filter_list[4].list_filter_item.rule.target_attribute              = EMAIL_MAIL_ATTRIBUTE_SAVE_STATUS;
+       filter_list[4].list_filter_item.rule.rule_type                     = EMAIL_LIST_FILTER_RULE_EQUAL;
+       filter_list[4].list_filter_item.rule.key_value.integer_type_value  = EMAIL_MAIL_STATUS_SEND_FAILURE;
+
+       sorting_rule_list[0].target_attribute                              = EMAIL_MAIL_ATTRIBUTE_ACCOUNT_ID;
+       sorting_rule_list[0].sort_order                                    = EMAIL_SORT_ORDER_ASCEND;
+
+       sorting_rule_list[1].target_attribute                              = EMAIL_MAIL_ATTRIBUTE_MAIL_ID;
+       sorting_rule_list[1].sort_order                                    = EMAIL_SORT_ORDER_ASCEND;
+
+       if( (err = emstorage_write_conditional_clause_for_getting_mail_list(filter_list, filter_rule_count, sorting_rule_list, sorting_rule_count, -1, -1, &conditional_clause_string)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emstorage_write_conditional_clause_for_getting_mail_list failed[%d]", err);
+               goto FINISH_OFF;
+       }
+
+       EM_DEBUG_LOG("conditional_clause_string[%s].", conditional_clause_string);
+
+       if(!emstorage_query_mail_list(conditional_clause_string, true, &result_mail_list, &result_mail_count, &err) && !result_mail_list) {
+               if (err == EMAIL_ERROR_MAIL_NOT_FOUND)
+                       EM_DEBUG_LOG ("no mail found");
+               else
+                       EM_DEBUG_EXCEPTION("emstorage_query_mail_list [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if(result_mail_count > 0) {
+               /* Add alarm */
+               time(&current_time);
+
+               trigger_at_time = current_time + input_alarm_interval_in_second;
+
+               if ((err = emcore_add_alarm(trigger_at_time, EMAIL_ALARM_CLASS_AUTO_RESEND, 0, emcore_auto_resend_cb, NULL)) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("emcore_add_alarm failed [%d]",err);
+                       goto FINISH_OFF;
+               }
+       }
+
+FINISH_OFF:
+       EM_SAFE_FREE(result_mail_list);
+       EM_SAFE_FREE(conditional_clause_string);
+       EM_DEBUG_FUNC_END("err[%d]", err);
+       return err;
+}
+#endif /* __FEATURE_AUTO_RETRY_SEND__ */
index 9af0486..5bf7f98 100755 (executable)
 #include "email-core-sound.h"
 #include "email-core-alarm.h"
 #include "email-utilities.h"
+#include "email-daemon.h"
 
 #define TIMER 30000   // 30 seconds
 #define HAPTIC_TEST_ITERATION 1
 #define EMAIL_ALARM_REFERENCE_ID_FOR_ALERT_TONE -1
 
-static MMHandleType email_mmhandle = 0;
-static int setting_noti_status = 0;
+static int emcore_get_alert_type(int vip_mode);
+static int emcore_alarm_timeout_cb_for_alert(int timer_id, void *user_parm);
+static int emcore_set_alarm_for_alert(int alert_time_in_minute);
+static void emcore_set_repetition_alarm(int repetition);
+static char * emcore_get_sound_file_path(int vip_mode);
 
-static char *filename;
 
-static pthread_mutex_t sound_mutex = PTHREAD_MUTEX_INITIALIZER;
-static pthread_cond_t sound_condition = PTHREAD_COND_INITIALIZER;
-static pthread_mutex_t mmhandle_mutex = PTHREAD_MUTEX_INITIALIZER;
-static thread_t g_alert_thread;
-
-void  emcore_set_repetition_alarm(int repetition);
-int   emcore_sound_mp_player_stop();
-bool  emcore_sound_mp_player_destory();
-void *start_alert_thread(void *arg);
-
-bool emcore_set_mp_filepath(const char *key)
-{
-       filename = vconf_get_str(key);
-       if (filename == NULL)
-               return false;
-
-       /* initialize the ringtone path */
-       if (vconf_set_str(VCONF_VIP_NOTI_RINGTONE_PATH, filename) != 0) {
-               EM_DEBUG_EXCEPTION("vconf_set_str failed");
-               return false;
-       }
-
-       return true;
-}
-
-int emcore_alert_sound_init()
-{
-       int ret = MM_ERROR_NONE;
-       if ((ret = mm_session_init(MM_SESSION_TYPE_NOTIFY)) != MM_ERROR_NONE) 
-               EM_DEBUG_EXCEPTION("mm_session_int failed");
-
-       return ret;
-}
-
-int emcore_alert_sound_filepath_init()
-{
-       filename = (char  *)em_malloc(MAX_PATH);
-       if (filename == NULL) {
-               EM_DEBUG_EXCEPTION("Memory malloc error");      
-               return false;
-       }
-
-       if (!emcore_set_mp_filepath(VCONFKEY_SETAPPL_NOTI_EMAIL_RINGTONE_PATH_STR)) {
-               /* TODO : Add code to set default ringtone path */
-               EM_DEBUG_EXCEPTION("emcore_set_mp_filepath failed.");
-               return false;
-       }
-
-       return true;
-}
-
-void emcore_global_noti_key_changed_cb(keynode_t *key_node, void *data)
+static int emcore_get_alert_type(int vip_mode)
 {
        EM_DEBUG_FUNC_BEGIN();
-       int err = EMAIL_ERROR_NONE;
+       int global_sound_status = 0;
+       int global_vibe_status = 0;
+       int email_vibe_status = 0;
+       int call_state = 0;
+       int alert_type = EMAIL_ALERT_TYPE_MUTE;
+       int voicerecoder_state = 0;
 
-       switch (vconf_keynode_get_type(key_node)) {
-       case VCONF_TYPE_INT:
-               if ((err = emcore_delete_alram_data_by_reference_id(EMAIL_ALARM_CLASS_NEW_MAIL_ALERT, EMAIL_ALARM_REFERENCE_ID_FOR_ALERT_TONE)) != EMAIL_ERROR_NONE) {
-                       EM_DEBUG_EXCEPTION("emcore_delete_alram_data_by_reference_id failed [%d]", err);
-               }
-               emcore_set_repetition_alarm(vconf_keynode_get_int(key_node));
-               break;
-       case VCONF_TYPE_STRING:
-               filename = vconf_keynode_get_str(key_node);
-               break;
-       default:
-               EM_DEBUG_EXCEPTION("Invalid key type");
-               break;
+       if (vconf_get_bool(VCONFKEY_SETAPPL_SOUND_STATUS_BOOL, &global_sound_status) != 0) {
+               EM_DEBUG_LOG("vconf_get_bool for VCONFKEY_SETAPPL_SOUND_STATUS_BOOL failed");
+               goto FINISH_OFF;
        }
 
-       EM_DEBUG_FUNC_END();
-}
-
-void emcore_email_noti_key_changed_cb(keynode_t *key_node, void *data)
-{
-       EM_DEBUG_FUNC_BEGIN();
-       int err = EMAIL_ERROR_NONE;
-
-       switch (vconf_keynode_get_type(key_node)) {
-       case VCONF_TYPE_INT:
-               if ((err = emcore_delete_alram_data_by_reference_id(EMAIL_ALARM_CLASS_NEW_MAIL_ALERT, EMAIL_ALARM_REFERENCE_ID_FOR_ALERT_TONE)) != EMAIL_ERROR_NONE) {
-                       EM_DEBUG_EXCEPTION("emcore_delete_alram_data_by_reference_id failed [%d]", err);
-               }
-
-               emcore_set_repetition_alarm(vconf_keynode_get_int(key_node));
-               break;
-       case VCONF_TYPE_STRING:
-               filename = vconf_keynode_get_str(key_node);
-               break;
-       default:
-               EM_DEBUG_EXCEPTION("Invalid key type");
-               break;
+       if (vconf_get_bool(VCONFKEY_SETAPPL_VIBRATION_STATUS_BOOL, &global_vibe_status) != 0) {
+               EM_DEBUG_LOG("vconf_get_bool for VCONFKEY_SETAPPL_VIBRATION_STATUS_BOOLfailed");
+               goto FINISH_OFF;
        }
-       EM_DEBUG_FUNC_END();
-}
 
-bool emcore_update_noti_status()
-{
-       EM_DEBUG_FUNC_BEGIN();
-       int ticker_noti = 0;
-
-       /* Get the priority noti ticker */
-       if (vconf_get_bool(VCONF_VIP_NOTI_NOTIFICATION_TICKER, &ticker_noti) != 0) {
-               EM_DEBUG_EXCEPTION("vconf_get_bool failed");
-               return false;
-       }
+       EM_DEBUG_LOG("global_sound_status [%d] global_vibe_status [%d]", global_sound_status, global_vibe_status);
 
-       EM_DEBUG_LOG("ticker_noti of vip : [%d]", ticker_noti);
+       if (global_sound_status || global_vibe_status) {
 
-       if (ticker_noti <= 0) {
-               /* Get the Global noti ticker */
-               if (vconf_get_bool(VCONFKEY_SETAPPL_STATE_TICKER_NOTI_EMAIL_BOOL, &ticker_noti) != 0) {
-                               EM_DEBUG_EXCEPTION("Not display the noti of email");
-                               return false;
+               if (vconf_get_int(VCONFKEY_VOICERECORDER_STATE, &voicerecoder_state) != 0) {
+                       EM_DEBUG_LOG("vconf_get_int for VCONFKEY_VOICERECORDER_STATE failed");
                }
+               EM_DEBUG_LOG("voicerecoder_state [%d]", voicerecoder_state);
 
-               EM_DEBUG_LOG("ticker_noti of global : [%d]", ticker_noti);
-
-               if (!ticker_noti) {
-                       EM_DEBUG_LOG("Not use the notification");
-                       setting_noti_status = SETTING_NOTI_STATUS_OFF;
-                       return true;
+               if (vconf_get_int(VCONFKEY_CALL_STATE, &call_state) != 0) {
+                       EM_DEBUG_LOG("vconf_get_int for VCONFKEY_CALL_STATE failed");
                }
+               EM_DEBUG_LOG("call_state [%d] ", call_state);
 
-               setting_noti_status = SETTING_NOTI_STATUS_GLOBAL;
-       } else {
-               setting_noti_status = SETTING_NOTI_STATUS_EMAIL;
-       }
-
-       EM_DEBUG_FUNC_END();
-       return true;
-}
-
-void emcore_noti_status_changed_cb(keynode_t *key_node, void *data)
-{
-       EM_DEBUG_FUNC_BEGIN();
-       if (!emcore_update_noti_status()) {
-               EM_DEBUG_EXCEPTION("emcore_update_noti_status failed");
-               return;
-       }
-       EM_DEBUG_FUNC_END();
-}
-
-bool emcore_noti_init(void *data)
-{
-       EM_DEBUG_FUNC_BEGIN();
-       struct appdata *ap = data;
-
-       if (!emcore_update_noti_status()) {
-               EM_DEBUG_EXCEPTION("emcore_update_noti_status failed");
-               return false;
-       }
-
-       /* Noti callback registration */
-       if (vconf_notify_key_changed(VCONFKEY_SETAPPL_NOTI_EMAIL_ALERT_REP_TYPE_INT, emcore_global_noti_key_changed_cb, ap) < 0) {
-               EM_DEBUG_EXCEPTION("Register failed : alert type");
-       }
-
-       if (vconf_notify_key_changed(VCONFKEY_SETAPPL_NOTI_EMAIL_RINGTONE_PATH_STR, emcore_global_noti_key_changed_cb, ap) < 0) {
-               EM_DEBUG_EXCEPTION("Register failed : Ringtone path");
-       }
-
-       if (vconf_notify_key_changed(VCONF_VIP_NOTI_REP_TYPE, emcore_email_noti_key_changed_cb, ap) < 0) {
-               EM_DEBUG_EXCEPTION("Register failed : alert type");
-       }
-
-       if (vconf_notify_key_changed(VCONF_VIP_NOTI_RINGTONE_PATH, emcore_email_noti_key_changed_cb, ap) < 0) {
-               EM_DEBUG_EXCEPTION("Register failed : Ringtone path");
-       }
-
-       if (vconf_notify_key_changed(VCONF_VIP_NOTI_NOTIFICATION_TICKER, emcore_noti_status_changed_cb, ap) < 0) {
-               EM_DEBUG_EXCEPTION("Register failed : Ringtone path");
-       }
-
-       if (vconf_notify_key_changed(VCONFKEY_SETAPPL_STATE_TICKER_NOTI_EMAIL_BOOL, emcore_noti_status_changed_cb, ap) < 0) {
-               EM_DEBUG_EXCEPTION("Register failed : Ringtone path");
-       }
-
-       EM_DEBUG_FUNC_END();
-       return true;
-}
-
-int emcore_alert_init()
-{
-       EM_DEBUG_FUNC_BEGIN();
-
-       int err = 0;
-       
-       if (!emcore_alert_sound_filepath_init()) {
-               EM_DEBUG_EXCEPTION("emcore_alert_sound_filepath_init failed");
-               return false;
-       }
-
-       if ((err = emcore_alert_sound_init()) != MM_ERROR_NONE) {
-               EM_DEBUG_EXCEPTION("emcore_alert_sound_init failed : [%d]", err);
-               return false;
-       }
-
-       if (!emcore_noti_init(NULL)) {
-               EM_DEBUG_EXCEPTION("emcore_noti_init failed");
-               return false;           
-       }
-
-       EM_DEBUG_FUNC_END();    
-       return true;
-}
-
-int emcore_mp_player_state_cb(int message, void *param, void *user_param)
-{
-       switch (message)
-       {
-               case MM_MESSAGE_ERROR:
-                       EM_DEBUG_LOG("Error is happened.");
-                       if (email_mmhandle) {
-                               emcore_sound_mp_player_destory();
+               if (vip_mode) {
+                       if (vconf_get_bool(VCONF_VIP_NOTI_VIBRATION_STATUS_BOOL, &email_vibe_status) != 0) {
+                               EM_DEBUG_EXCEPTION("vconf_get_bool failed");
+                               return EMAIL_ALERT_TYPE_NONE;
                        }
-                       break;
-               case MM_MESSAGE_BEGIN_OF_STREAM:
-                       EM_DEBUG_LOG("Play is started.");
-                       break;
-               case MM_MESSAGE_END_OF_STREAM:
-                       EM_DEBUG_LOG("End of stream.");
-                       ENTER_CRITICAL_SECTION(mmhandle_mutex);
-                       if (email_mmhandle)
-                       {                       
-                               emcore_sound_mp_player_stop();
-                               emcore_sound_mp_player_destory();
+               }
+               else {
+                       if (vconf_get_bool(VCONF_EMAIL_NOTI_VIBRATION_STATUS_BOOL, &email_vibe_status) != 0) {
+                               EM_DEBUG_EXCEPTION("vconf_get_bool failed");
+                               return EMAIL_ALERT_TYPE_NONE;
                        }
-                       LEAVE_CRITICAL_SECTION(mmhandle_mutex);
-                       break;
-               default: 
-                       EM_DEBUG_LOG("Message = %d", message);
-                       break;
-       }
-       return 1;
-}
-
-bool emcore_sound_mp_player_create() 
-{      
-       EM_DEBUG_FUNC_BEGIN();
-       int err = 0;
-       
-       if (email_mmhandle) {
-               EM_DEBUG_LOG("already create the handle");
-               return true;
-       }
-
-       if ((err = mm_player_create(&email_mmhandle)) != MM_ERROR_NONE) {
-               EM_DEBUG_EXCEPTION("mm_player create fail [%d]", err);
-               return false;
-       }       
-       EM_DEBUG_FUNC_END();
-       return true;
-}
-
-bool emcore_alert_create()
-{
-       EM_DEBUG_FUNC_BEGIN();
-
-#if 0  
-       /* Set the music file in alert */
-       if (!emcore_set_mp_filepath(VCONFKEY_SETAPPL_NOTI_EMAIL_RINGTONE_PATH_STR)) {
-               /* TODO : Add code to set default ringtone path */
-               EM_DEBUG_EXCEPTION("emcore_set_mp_filepath failed.");
-               return false;
-       }
-#endif 
-       EM_DEBUG_FUNC_END();
-       return true;
-}
-
-bool emcore_alert_destory()
-{
-       EM_DEBUG_FUNC_BEGIN();
-
-       /* Destroy the music player handle */
-       if (!emcore_sound_mp_player_destory()) {
-               EM_DEBUG_EXCEPTION("emcore_sound_mp_player_destory fail");
-               return false;
-       }                       
-       
-       EM_DEBUG_FUNC_END();
-       return true;
-}
-
-gboolean mp_player_timeout_cb(void *data)
-{
-       EM_DEBUG_FUNC_BEGIN();
-
-       ENTER_CRITICAL_SECTION(mmhandle_mutex); 
-       if (email_mmhandle)
-       {                       
-               emcore_sound_mp_player_stop();
-               emcore_sound_mp_player_destory();
-       }
-       LEAVE_CRITICAL_SECTION(mmhandle_mutex);
-       
-       EM_DEBUG_FUNC_END();
-       return false;
-}
-
-bool emcore_vibration_start()
-{
-       EM_DEBUG_FUNC_BEGIN();
-       int ret = false;
-       int error = FEEDBACK_ERROR_NONE;
-       int call_state = 0;
-
-       error = vconf_get_int(VCONFKEY_CALL_STATE, &call_state);
-       if (error == -1) {
-               EM_DEBUG_EXCEPTION("vconf_get_int failed");
-               goto FINISH_OFF;
-       }
-
-       error = feedback_initialize();
-       if (error != FEEDBACK_ERROR_NONE) {
-               EM_DEBUG_EXCEPTION("feedback_initialize failed : [%d]", error);
-               goto FINISH_OFF;
-       }
-
-       if (call_state > VCONFKEY_CALL_OFF && call_state < VCONFKEY_CALL_STATE_MAX) {   
-               error = feedback_play_type(FEEDBACK_TYPE_VIBRATION, FEEDBACK_PATTERN_EMAIL_ON_CALL);
-       } else {
-               error = feedback_play_type(FEEDBACK_TYPE_VIBRATION, FEEDBACK_PATTERN_EMAIL);
-       }
-
-       if (error != FEEDBACK_ERROR_NONE) {
-               EM_DEBUG_EXCEPTION("feedback_play failed : [%d]", error);
-               goto FINISH_OFF;
-       }
-
-       ret = true;
-
-FINISH_OFF:
-
-       error = feedback_deinitialize();
-       if (error != FEEDBACK_ERROR_NONE) {
-               EM_DEBUG_EXCEPTION("feedback_deinitialize failed : [%d]", error);
-       }
-       
-       EM_DEBUG_FUNC_END();
-       return ret;
-}
-
-int emcore_sound_mp_player_start(char *filepath)
-{
-       EM_DEBUG_FUNC_BEGIN();
-
-       int err = MM_ERROR_NONE;
-
-       mm_player_set_message_callback(email_mmhandle, emcore_mp_player_state_cb, (void  *)email_mmhandle);
-
-       EM_DEBUG_LOG("Before mm_player_set_attribute filepath = %s", filepath);
-       if ((err = mm_player_set_attribute(email_mmhandle, NULL, "sound_volume_type", MM_SOUND_VOLUME_TYPE_NOTIFICATION, "profile_uri", filepath, EM_SAFE_STRLEN(filepath), NULL)) != MM_ERROR_NONE)
-       {
-               EM_DEBUG_EXCEPTION("mm_player_set_attribute faile [ %d ] ", err);
-               return err;
-       }
-
-       EM_DEBUG_LOG("After mm_player_set_attribute");  
-
-       if ((err = mm_player_realize(email_mmhandle)) != MM_ERROR_NONE)
-       {
-               EM_DEBUG_EXCEPTION("mm_player_realize fail [%d]", err);
-               return err;
-       }
-
-       if ((err = mm_player_start(email_mmhandle)) != MM_ERROR_NONE)
-       {
-               EM_DEBUG_EXCEPTION("mm_player_start fail [%d]", err);
-               return err;
-       }
-
-       if ((err = g_timeout_add(TIMER, (GSourceFunc)mp_player_timeout_cb, NULL) <= 0))
-       {
-               EM_DEBUG_EXCEPTION("g_timeout_add - Failed to start timer");
-               return err;             
-       }
-       
-       EM_DEBUG_FUNC_END();
-       return err;
-}
-
-int emcore_sound_mp_player_stop()
-{
-       EM_DEBUG_FUNC_BEGIN();
-
-       int err = MM_ERROR_NONE;
-
-       if ((err = mm_player_stop(email_mmhandle)) != MM_ERROR_NONE)
-       {
-               EM_DEBUG_EXCEPTION("mm_player_stop fail [%d]", err);
-               return err;
-       }
-
-       if ((err = mm_player_unrealize(email_mmhandle)) != MM_ERROR_NONE)
-       {
-               EM_DEBUG_EXCEPTION("mm_player_unrealize [%d]", err);
-               return err;
-       }
-
-       EM_DEBUG_FUNC_END();
-       return err;
-}
-
-bool emcore_sound_mp_player_destory()
-{
-       EM_DEBUG_FUNC_BEGIN();
-
-       int err = MM_ERROR_NONE;
-
-       if ((err = mm_player_destroy(email_mmhandle)) != MM_ERROR_NONE) {
-               EM_DEBUG_EXCEPTION("mm_player_destory [%d]", err);
-               return false;
-       }
-
-       email_mmhandle = 0;
-
-       EM_DEBUG_FUNC_END();
-       return true;
-}      
-
-int get_vconf_data(int key, int *return_value)
-{
-       EM_DEBUG_FUNC_BEGIN();
-       int err = -1, value = 0;
-       
-       switch (key)
-       {
-               case EMAIL_SOUND_STATUS:
-                       err = vconf_get_bool(VCONFKEY_SETAPPL_SOUND_STATUS_BOOL, &value);
-                       EM_DEBUG_LOG("EMAIL_SOUND_STATUS[%d]", value);
-                       break;
-               case EMAIL_VIBE_STATUS:
-                       err = vconf_get_bool(VCONFKEY_SETAPPL_VIBRATION_STATUS_BOOL, &value);
-                       EM_DEBUG_LOG("EMAIL_VIBRATION_STATUS[%d]", value);
-                       break;
-               case EMAIL_ALERT_REP_TYPE:
-                       err = vconf_get_int(VCONFKEY_SETAPPL_NOTI_EMAIL_ALERT_REP_TYPE_INT, &value);
-                       EM_DEBUG_LOG("EMAIL_ALERT_REP_TYPE[%d]", value);
-                       break;
-               case EMAIL_ALERT_VOLUME:
-                       err = vconf_get_int(VCONFKEY_SETAPPL_NOTI_SOUND_VOLUME_INT, &value);
-                       EM_DEBUG_LOG("EMAIL_ALERT_VOLUME[%d]", value);
-                       break;
-               case EMAIL_ALERT_VIBE_STENGTH:
-                       err = vconf_get_int(VCONFKEY_SETAPPL_NOTI_VIBRATION_LEVEL_INT, &value);
-                       EM_DEBUG_LOG("EMAIL_ALERT_VIBE_STENGTH[%d]", value);
-                       break;
-               default: 
-               {
-                       EM_DEBUG_LOG("Uuknown request\n");
-                       return false;                   
                }
-       }
-       
-       if (err == -1)
-       {
-               EM_DEBUG_LOG("Vconf_get_int failed\n");
-               return false;
-       }
 
-       *return_value = value;
-       EM_DEBUG_FUNC_END();
-       return true;
-}
-
-int emcore_get_alert_type()
-{
-       EM_DEBUG_FUNC_BEGIN();
-       int sound_status = 0, vibe_status = 0;
-       int err;
-       int alert_type = -1;
+               EM_DEBUG_LOG("email_vibe_status [%d] ", email_vibe_status);
 
-       if (!(err = get_vconf_data(EMAIL_SOUND_STATUS, &sound_status))) {
-               EM_DEBUG_EXCEPTION("Don't get sound status");
-               return err;
-       }
-
-       if (!(err = get_vconf_data(EMAIL_VIBE_STATUS, &vibe_status)))
-       {
-               EM_DEBUG_EXCEPTION("Don't get vibration status");
-               return err;
+               if (voicerecoder_state == VCONFKEY_VOICERECORDER_RECORDING) {
+                       alert_type = EMAIL_ALERT_TYPE_VIB;
+                       EM_DEBUG_LOG("voice recorder is on recording...");
+               }
+               else if (call_state > VCONFKEY_CALL_OFF && call_state < VCONFKEY_CALL_STATE_MAX) {
+                       EM_DEBUG_LOG("Calling");
+#ifdef FEATURE_OPCO_DOCOMO
+                       alert_type = EMAIL_ALERT_TYPE_NONE;
+#else
+                       alert_type = EMAIL_ALERT_TYPE_VIB;
+#endif
+               }
+               else if (global_sound_status && email_vibe_status) {
+                       alert_type = EMAIL_ALERT_TYPE_MELODY_AND_VIB;
+               }
+               else if (global_sound_status) {
+                       alert_type = EMAIL_ALERT_TYPE_MELODY;
+               }
+               else if (global_vibe_status) {
+                       alert_type = EMAIL_ALERT_TYPE_VIB;
+               }
+               else {
+                       alert_type = EMAIL_ALERT_TYPE_MUTE;
+               }
        }
 
-       if (sound_status && vibe_status)
-               alert_type = EMAIL_ALERT_TYPE_MELODY_AND_VIB;
-       else if (sound_status)
-               alert_type = EMAIL_ALERT_TYPE_MELODY;
-       else if (vibe_status)
-               alert_type = EMAIL_ALERT_TYPE_VIB;
-       else
-               alert_type = EMAIL_ALERT_TYPE_MUTE;
-
+FINISH_OFF:
+       EM_DEBUG_FUNC_END("alert_type [%d]", alert_type);
        return alert_type;
 }
 
-
-INTERNAL_FUNC int emcore_start_thread_for_alerting_new_mails(int *err_code)
-{
-       EM_DEBUG_FUNC_BEGIN();
-
-       int thread_error;
-
-       if (err_code != NULL)
-               *err_code = EMAIL_ERROR_NONE;
-       
-       if (g_alert_thread)
-       {
-               EM_DEBUG_EXCEPTION("Alert service is already running...");
-               if (err_code != NULL)
-                       *err_code = EMAIL_ERROR_UNKNOWN;
-               
-               return 1;
-       }
-       
-       THREAD_CREATE(g_alert_thread, start_alert_thread, NULL, thread_error);
-       if (thread_error != 0)
-       {
-               EM_DEBUG_EXCEPTION("Cannot create alert thread");
-               if (err_code != NULL)
-                       *err_code = EMAIL_ERROR_SYSTEM_FAILURE;
-
-               return -1;
-       }
-               
-       if (err_code != NULL)
-               *err_code = EMAIL_ERROR_NONE;
-
-       return 0;
-}
-
-int emcore_alarm_timeout_cb_for_alert(int timer_id, void *user_parm)
+static int emcore_alarm_timeout_cb_for_alert(int timer_id, void *user_parm)
 {
        EM_DEBUG_FUNC_BEGIN();
 
@@ -595,7 +145,8 @@ int emcore_alarm_timeout_cb_for_alert(int timer_id, void *user_parm)
        EM_DEBUG_LOG(">>>> total_unread_count : [%d]\n", total_unread_count);
        
        if (total_unread_count) {
-               emcore_start_alert();
+               /* emdaemon_start_alert(); */
+               /* Alarm repetition disabled */
        }
 
        EM_DEBUG_FUNC_END();    
@@ -626,7 +177,7 @@ FINISH_OFF:
        return err;
 }
 
-void emcore_set_repetition_alarm(int repetition)
+static void emcore_set_repetition_alarm(int repetition)
 {
        EM_DEBUG_FUNC_BEGIN();
 
@@ -659,92 +210,134 @@ void emcore_set_repetition_alarm(int repetition)
        EM_DEBUG_FUNC_END();
 }
 
-void *start_alert_thread(void *arg)
+static char * emcore_get_sound_file_path(int vip_mode)
 {
-       EM_DEBUG_FUNC_BEGIN();
-       
-       int err = 0;
-       int repetition = 0;
+       EM_DEBUG_FUNC_BEGIN("vip_mode [%d]", vip_mode);
+       char *ret = NULL;
+       int   use_default_ring_tone = 0;
+
+       if (vip_mode) {
+               if (vconf_get_bool(VCONF_VIP_NOTI_USE_DEFAULT_RINGTONE_BOOL, &use_default_ring_tone) != 0)
+                       EM_DEBUG_LOG("vconf_get_bool for VCONF_VIP_NOTI_USE_DEFAULT_RINGTONE_BOOL failed");
 
-       if (!emcore_alert_init())
-       {
-               EM_DEBUG_EXCEPTION("Error : emcore_alert_init failed");
-               return 0;
+               EM_DEBUG_LOG("use_default_ring_tone [%d]", use_default_ring_tone);
+
+               if (use_default_ring_tone)
+                       ret = EM_SAFE_STRDUP(vconf_get_str(VCONFKEY_SETAPPL_NOTI_RINGTONE_DEFAULT_PATH_STR));
+               else
+                       ret = EM_SAFE_STRDUP(vconf_get_str(VCONF_VIP_NOTI_RINGTONE_PATH));
        }
+       else {
+               if (vconf_get_bool(VCONF_EMAIL_NOTI_USE_DEFAULT_RINGTONE_BOOL, &use_default_ring_tone) != 0)
+                       EM_DEBUG_LOG("vconf_get_bool for VCONF_EMAIL_NOTI_USE_DEFAULT_RINGTONE_BOOL failed");
 
-       while (1) {
-               if (!emcore_alert_create()) {
-                       EM_DEBUG_EXCEPTION("Error : emcore_alert_create failed");
-                       return 0;
-               }
+               EM_DEBUG_LOG("use_default_ring_tone [%d]", use_default_ring_tone);
 
-               err = get_vconf_data(EMAIL_ALERT_REP_TYPE, &repetition);
-               emcore_set_repetition_alarm(repetition);
-
-               ENTER_CRITICAL_SECTION(sound_mutex);
-               SLEEP_CONDITION_VARIABLE(sound_condition , sound_mutex);
-
-               switch (emcore_get_alert_type())
-               {
-                       case EMAIL_ALERT_TYPE_MELODY:
-                               if (!emcore_sound_mp_player_create()) {
-                                       EM_DEBUG_LOG("emcore_sound_mp_player_create failed : [%d]", email_mmhandle);
-                                       break;
-                               }
-                               emcore_sound_mp_player_start(filename);
-                               break;
-                       case EMAIL_ALERT_TYPE_VIB:
-                               emcore_vibration_start();
-                               break;
-                       case EMAIL_ALERT_TYPE_MELODY_AND_VIB:
-                               emcore_vibration_start();
-                               if (!emcore_sound_mp_player_create()) {
-                                       EM_DEBUG_LOG("emcore_sound_mp_player_create failed : [%d]", email_mmhandle);
-                                       break;
-                               }
-                               emcore_sound_mp_player_start(filename);
-                               break;
-                       case EMAIL_ALERT_TYPE_MUTE:
-                               EM_DEBUG_LOG("Alert type is mute!!");
-                               break;
-                       default: 
-                               EM_DEBUG_EXCEPTION("alert type is strange");
-                               emcore_alert_destory();
-                               break;
-               }
-               LEAVE_CRITICAL_SECTION(sound_mutex);
-               EM_DEBUG_LOG("Start FINISH");
+               if (use_default_ring_tone)
+                       ret = EM_SAFE_STRDUP(vconf_get_str(VCONFKEY_SETAPPL_NOTI_RINGTONE_DEFAULT_PATH_STR));
+               else
+                       ret = EM_SAFE_STRDUP(vconf_get_str(VCONFKEY_SETAPPL_NOTI_EMAIL_RINGTONE_PATH_STR));
        }
 
-       EM_DEBUG_FUNC_END();
-       return 0;
-}      
+       EM_DEBUG_FUNC_END("ret [%s]", ret);
+       return ret;
+}
 
-INTERNAL_FUNC void emcore_start_alert()
-{
-       EM_DEBUG_FUNC_BEGIN("setting_noti_status : [%d]", setting_noti_status);
 
-       int voicerecoder_state = 0;
+INTERNAL_FUNC int emcore_get_alert_policy(EMAIL_ALERT_TYPE *output_alert_type, char **output_alert_tone_path)
+{
+       EM_DEBUG_FUNC_BEGIN("output_alert_type [%p] output_alert_tone_path[%p]", output_alert_type, output_alert_tone_path);
 
-#ifdef __FEATURE_BLOCKING_MODE__
-       if (emcore_get_blocking_mode_status())
-               return;
-#endif /* __FEATURE_BLOCKING_MODE__ */
+       int err = EMAIL_ERROR_NONE;
+       int general_noti_status = false;
+       int vip_noti_status = false;
+       int vip_mail_count = 0;
+       int vip_unread_count = 0;
+       int vip_notification_mode = 0;
+       char *alert_tone_path = NULL;
+       EMAIL_ALERT_TYPE alert_type = EMAIL_ALERT_TYPE_NONE;
+
+       if (output_alert_type == NULL || output_alert_tone_path == NULL) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
 
-       if (setting_noti_status == SETTING_NOTI_STATUS_OFF)
-               return;
+       /* get general noti status */
+       if (vconf_get_bool(VCONFKEY_SETAPPL_STATE_TICKER_NOTI_EMAIL_BOOL, &general_noti_status) != 0) {
+               EM_DEBUG_EXCEPTION("vconf_get_int failed");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
 
-       /* skip sound alert when voice recording */
-       if (vconf_get_int(VCONFKEY_VOICERECORDER_STATE, &voicerecoder_state) != 0) {
+       /* get vip noti status */
+       if (vconf_get_bool(VCONF_VIP_NOTI_NOTIFICATION_TICKER, &vip_noti_status) != 0) {
                EM_DEBUG_EXCEPTION("vconf_get_int failed");
-       } else {
-               if (voicerecoder_state == VCONFKEY_VOICERECORDER_RECORDING) {
-                       EM_DEBUG_LOG("voice recoder is on recording");
-                       return;
+               err = EMAIL_ERROR_DATA_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+
+       if (!general_noti_status && !vip_noti_status) {
+               EM_DEBUG_LOG("both notification disabled");
+               goto FINISH_OFF;
+       }
+
+       if (vip_noti_status) {
+               if (!emcore_get_mail_count_by_query(ALL_ACCOUNT, EMAIL_MAILBOX_TYPE_INBOX, true, &vip_mail_count, &vip_unread_count, &err)) {
+                       EM_DEBUG_EXCEPTION("emcore_get_mail_count_by_query failed");
+                       err = EMAIL_ERROR_DATA_NOT_FOUND;
                }
        }
 
-       ENTER_CRITICAL_SECTION(sound_mutex);
-       WAKE_CONDITION_VARIABLE(sound_condition);
-       LEAVE_CRITICAL_SECTION(sound_mutex);
+       if (general_noti_status && !vip_noti_status) {
+               EM_DEBUG_LOG("GERNERAL NOTI MODE");
+               vip_notification_mode = 0;
+       }
+       else if (!general_noti_status && vip_noti_status) {
+               EM_DEBUG_LOG("VIP NOTI MODE");
+               if (err == EMAIL_ERROR_FILTER_NOT_FOUND) {
+                       EM_DEBUG_LOG("VIP filter not found");
+                       err = EMAIL_ERROR_DATA_NOT_FOUND;
+                       goto FINISH_OFF;
+               }
+               vip_notification_mode = 1;
+       }
+       else if (general_noti_status && vip_noti_status) {
+               if (err == EMAIL_ERROR_FILTER_NOT_FOUND) {
+                       EM_DEBUG_LOG("VIP filter not found");
+                       EM_DEBUG_LOG("GERNERAL NOTI MODE");
+                       vip_notification_mode = 0;
+               } else {
+                       //confusing..
+                       if (vip_unread_count > 0) {
+                               EM_DEBUG_LOG("VIP NOTI MODE");
+                               vip_notification_mode = 1;
+                       } else {
+                               EM_DEBUG_LOG("GERNERAL NOTI MODE");
+                               vip_notification_mode = 0;
+                       }
+               }
+       }
+
+       alert_type = emcore_get_alert_type(vip_notification_mode);
+       EM_DEBUG_LOG("alert_type [%d]", alert_type);
+
+
+
+       EM_DEBUG_LOG("vip_notification_mode [%d]", vip_notification_mode);
+
+       if (alert_type == EMAIL_ALERT_TYPE_MELODY_AND_VIB || alert_type == EMAIL_ALERT_TYPE_MELODY)
+               alert_tone_path = EM_SAFE_STRDUP(emcore_get_sound_file_path(vip_notification_mode));
+
+       *output_alert_type = alert_type;
+       if (alert_tone_path)
+               *output_alert_tone_path = alert_tone_path;
+
+       EM_DEBUG_LOG("alert_type [%d] alert_tone_path [%s]", alert_type, alert_tone_path);
+
+FINISH_OFF:
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+
+       return err;
 }
index 27f7e00..f3a1f7e 100755 (executable)
@@ -261,11 +261,10 @@ INTERNAL_FUNC int emcore_free_task_handler_array()
        int i = 0;\r
 \r
        for(i = 0; i < _task_handler_array_size; i++) {\r
-               free(_task_handler_array[i]);\r
+               EM_SAFE_FREE (_task_handler_array[i]);\r
        }\r
 \r
-       free(_task_handler_array);\r
-       _task_handler_array      = NULL;\r
+       EM_SAFE_FREE (_task_handler_array);\r
        _task_handler_array_size = 0;\r
 \r
        EM_DEBUG_FUNC_END();\r
@@ -566,14 +565,14 @@ FINISH_OFF :
 \r
 INTERNAL_FUNC int emcore_stop_task_manager_loop()\r
 {\r
-    EM_DEBUG_FUNC_BEGIN();\r
+       EM_DEBUG_FUNC_BEGIN();\r
 \r
-    int err = EMAIL_ERROR_NONE;\r
+       int err = EMAIL_ERROR_NONE;\r
 \r
-    /* TODO : cancel tasks */\r
+       /* TODO : cancel tasks */\r
 \r
-    /* stop event_data loop */\r
-    _task_manager_loop_availability = 0;\r
+       /* stop event_data loop */\r
+       _task_manager_loop_availability = 0;\r
 \r
        ENTER_CRITICAL_SECTION(_task_manager_loop_lock);\r
        WAKE_CONDITION_VARIABLE(_task_available_signal);\r
@@ -589,10 +588,10 @@ INTERNAL_FUNC int emcore_stop_task_manager_loop()
 \r
        /* Free _active_task_pool */\r
 \r
-//FINISH_OFF :\r
+       //FINISH_OFF :\r
 \r
        EM_DEBUG_FUNC_END("err [%d]", err);\r
-    return err;\r
+       return err;\r
 }\r
 \r
 INTERNAL_FUNC int emcore_add_task_to_task_table(email_task_type_t input_task_type, email_task_priority_t input_task_priority, char *input_task_parameter, int input_task_parameter_length, int *output_task_id)\r
index 71acfd1..019fa5d 100755 (executable)
@@ -569,14 +569,11 @@ INTERNAL_FUNC int email_decode_task_parameter_EMAIL_SYNC_TASK_UPDATE_ATTRIBUTE(c
 \r
 FINISH_OFF:\r
 \r
-       if(err != EMAIL_ERROR_NONE) /*prevent 50459*/\r
-               EM_SAFE_FREE(task_parameter);\r
-\r
        if(tn)\r
                tpl_free(tn);\r
 \r
        EM_DEBUG_FUNC_END("err [%d]", err);\r
-       return err;\r
+       return EMAIL_ERROR_NONE;\r
 }\r
 \r
 INTERNAL_FUNC void* task_handler_EMAIL_SYNC_TASK_UPDATE_ATTRIBUTE(void *input_param)\r
@@ -632,7 +629,7 @@ FINISH_OFF:
                EM_SAFE_FREE(task_param->value.string_type_value);\r
        }\r
 \r
-       free(task_param);\r
+       EM_SAFE_FREE (task_param);\r
 \r
 \r
        EM_DEBUG_FUNC_END("err [%d]", err);\r
index a15167a..ffcea51 100755 (executable)
@@ -36,6 +36,8 @@
 #include <ctype.h>
 #include <errno.h>
 #include <dlfcn.h>
+#include <libintl.h>
+#include <locale.h>
 #include <glib.h>
 #include <glib-object.h>
 #include <sys/time.h>
 #include <regex.h>
 #include <pthread.h>
 #include <notification.h>
+#include <notification_type.h>
 #include <badge.h>
+#include <drm_client_types.h>
+#include <drm_client.h>
 
 #include "email-types.h"
 #include "email-core-global.h"
 #include "email-core-account.h"
 #include "email-core-mailbox-sync.h"
 #include "email-core-mime.h"
-#include "email-core-sound.h"
 #include "email-core-signal.h"
+#include "email-core-sound.h"
+#include "email-daemon.h"
 #include "email-utilities.h"
 #include "email-convert.h"
 #include "email-internal-types.h"
+#include "email-device.h"
 
 #ifdef __FEATURE_DRIVING_MODE__
 #include <app_service.h>
@@ -94,7 +101,7 @@ typedef struct  _em_transaction_info_type_t {
 em_transaction_info_type_t  *g_transaction_info_list;
 
 static email_session_t g_session_list[SESSION_MAX] = { {0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0},};
-
+static notification_h g_sending_noti_handle = NULL;
 typedef struct emcore_account_list_t emcore_account_list_t;
 struct emcore_account_list_t {
        email_account_t *account;
@@ -111,17 +118,18 @@ INTERNAL_FUNC char *emcore_convert_mutf7_to_utf8(char *mailbox_name)
 int emcore_get_long_encoded_path_with_account_info(email_account_t *account, char *path, int delimiter, char **long_enc_path, int *err_code)
 {
        EM_PROFILE_BEGIN(emCorelongEncodedpath);
-       EM_DEBUG_FUNC_BEGIN("account[%p], path[%s], delimiter[%d], long_enc_path[%p], err_code[%p]", account, path, delimiter, long_enc_path, err_code);
+       EM_DEBUG_FUNC_BEGIN_SEC("account[%p], path[%s], delimiter[%d], long_enc_path[%p], err_code[%p]", account, path, delimiter, long_enc_path, err_code);
 
        int ret = false;
        int error = EMAIL_ERROR_NONE;
        char *p = NULL;
+       email_authentication_method_t authentication_method = 0;
 
        size_t long_enc_path_len = 0;
 
        if (path == NULL || (path && strncmp(path, ENCODED_PATH_SMTP, EM_SAFE_STRLEN(ENCODED_PATH_SMTP)) != 0)) {               /*  imap or pop3 */
-               EM_DEBUG_LOG("account->incoming_server_address[%p]", account->incoming_server_address);
-               EM_DEBUG_LOG("account->incoming_server_address[%s]", account->incoming_server_address);
+               EM_DEBUG_LOG_SEC("account->incoming_server_address[%p]", account->incoming_server_address);
+               EM_DEBUG_LOG_SEC("account->incoming_server_address[%s]", account->incoming_server_address);
 
                if (!account->incoming_server_address) {
                        EM_DEBUG_EXCEPTION("account->incoming_server_address is null");
@@ -129,7 +137,7 @@ int emcore_get_long_encoded_path_with_account_info(email_account_t *account, cha
                        goto FINISH_OFF;
                }
 
-               long_enc_path_len = EM_SAFE_STRLEN(account->incoming_server_address) + EM_SAFE_STRLEN(path) + 64; /*prevent 34357*/
+               long_enc_path_len = EM_SAFE_STRLEN(account->incoming_server_address) + EM_SAFE_STRLEN(path) + 256; /*prevent 34357*/
 
                *long_enc_path = em_malloc(long_enc_path_len);
                if (!*long_enc_path)  {
@@ -159,10 +167,10 @@ int emcore_get_long_encoded_path_with_account_info(email_account_t *account, cha
                        strncat(p, "/notls", long_enc_path_len-(EM_SAFE_STRLEN(p)+1));
                */
 
+               authentication_method = account->incoming_server_authentication_method;
+
                if (account->incoming_server_requires_apop) {
-                       EM_DEBUG_LOG("emcore_get_long_encoded_path - incoming_server_requires_apop - %d", account->incoming_server_requires_apop);
                        strncat(p, "/apop", long_enc_path_len-(EM_SAFE_STRLEN(p)+1));
-                       EM_DEBUG_LOG("long_enc_path - %s", p);
                }
        }
        else  {         /*  smtp */
@@ -185,39 +193,53 @@ int emcore_get_long_encoded_path_with_account_info(email_account_t *account, cha
                        account->outgoing_server_port_number,
                        "smtp");
 
-               if (account->outgoing_server_need_authentication) {
+               if (account->outgoing_server_need_authentication > 0) {
                        SNPRINTF(p + EM_SAFE_STRLEN(p), long_enc_path_len-(EM_SAFE_STRLEN(p)), "/user=%d", account->account_id);
+                       if (account->outgoing_server_need_authentication == EMAIL_AUTHENTICATION_METHOD_XOAUTH2)  {
+                               strncat(p, "/xoauth2", long_enc_path_len-(EM_SAFE_STRLEN(p)+1));
+                       }
                }
 
                if (account->outgoing_server_secure_connection & 0x01) {
-                       strncat(p, "/ssl", long_enc_path_len-(EM_SAFE_STRLEN(p)+1));
+                       strncat(p, "/ssl/force_tls_v1_0", long_enc_path_len-(EM_SAFE_STRLEN(p)+1));
                        /* strcat(p, "/tryssl"); */
                }
-               if (account->outgoing_server_secure_connection & 0x02)
-                       strncat(p, "/tls", long_enc_path_len-(EM_SAFE_STRLEN(p)+1));
+               else if (account->outgoing_server_secure_connection & 0x02)
+                       strncat(p, "/tls/force_tls_v1_0", long_enc_path_len-(EM_SAFE_STRLEN(p)+1));
                else
                        strncat(p, "/notls", long_enc_path_len-(EM_SAFE_STRLEN(p)+1));
+
+               authentication_method = account->outgoing_server_need_authentication;
+       }
+
+#ifdef FEATURE_CORE_DEBUG
+       strncat(p, "/debug", long_enc_path_len-(strlen("/debug")+1));
+#endif
+
+       /* Authentication method */
+       switch(authentication_method) {
+       case EMAIL_AUTHENTICATION_METHOD_DEFAULT:
+               strncat(p, "/needauth", long_enc_path_len-(EM_SAFE_STRLEN(p)+1));
+               break;
+       case EMAIL_AUTHENTICATION_METHOD_XOAUTH2:
+               strncat(p, "/xoauth2", long_enc_path_len-(EM_SAFE_STRLEN(p)+1));
+               break;
+       case EMAIL_AUTHENTICATION_METHOD_NO_AUTH:
+       default:
+               break;
        }
 
        if (path == NULL || (path && strncmp(path, ENCODED_PATH_SMTP, EM_SAFE_STRLEN(ENCODED_PATH_SMTP)) != 0)) {
                strncat(p, "}", long_enc_path_len-(EM_SAFE_STRLEN(p)+1));
 
                if (path != NULL) {
-                       char *enc_name = NULL;
-
-                       if (!emcore_get_encoded_mailbox_name(path, &enc_name, &error))  {
-                               EM_DEBUG_EXCEPTION("emcore_get_encoded_mailbox_name failed - %d", error);
-                               *long_enc_path = NULL;
-                               goto FINISH_OFF;
-                       }
-
-                       if (enc_name)  {
-                               strncat(p, enc_name, long_enc_path_len-(EM_SAFE_STRLEN(p)+1));
-                               EM_SAFE_FREE(enc_name);
-                       }
+                       strncat(p, path, long_enc_path_len-(EM_SAFE_STRLEN(p)+1));
                }
        }
 
+       if(*long_enc_path)
+               EM_DEBUG_LOG("long_enc_path [%s]", *long_enc_path);
+
        ret = true;
 
 FINISH_OFF:
@@ -268,7 +290,7 @@ FINISH_OFF:
 
 int emcore_get_encoded_mailbox_name(char *name, char **enc_name, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("name[%s], enc_name[%p], err_code[%p]", name, enc_name, err_code);
+       EM_DEBUG_FUNC_BEGIN_SEC("name[%s], enc_name[%p], err_code[%p]", name, enc_name, err_code);
 
        if (!name || !enc_name)  {
                if (err_code != NULL)
@@ -278,23 +300,71 @@ int emcore_get_encoded_mailbox_name(char *name, char **enc_name, int *err_code)
        }
 
        /* encoding mailbox name (Charset->UTF8->UTF7) */
+       char *last_slash = NULL;
+       char *last_word = NULL;
+       char *last_enc_word = NULL;
+       char *ret_enc_name = NULL;
+       int err = EMAIL_ERROR_NONE;
+       int ret = true;
 
-       *enc_name = em_malloc(EM_SAFE_STRLEN(name)+1);
-       if (*enc_name == NULL) {
-               EM_DEBUG_EXCEPTION("malloc failed...");
-               if (err_code != NULL)
-                       *err_code = EMAIL_ERROR_OUT_OF_MEMORY;
-               EM_DEBUG_FUNC_END();
-               return false;
+       last_slash = rindex(name, '/');
+       last_word = (last_slash)? last_slash+1 : name;
+       if (!last_word) {
+               EM_DEBUG_EXCEPTION("Wrong mailbox [%s]", name);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               ret = false;
+               goto FINISH_OFF;
+       }
+
+       /* convert the last mailbox folder to utf7 char */
+       last_enc_word = (char*)utf8_to_mutf7 ((unsigned char*)last_word);
+       if (!last_enc_word) {
+               EM_DEBUG_EXCEPTION("utf8_to_mutf7 failed");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               ret = false;
+               goto FINISH_OFF;
+       }
+
+       /* if last word of mailbox name is ASCII, use input */
+       if (!strcmp(last_enc_word, last_word)) {
+               EM_DEBUG_LOG_SEC("NOT UTF-8 [%s]", last_word);
+               ret_enc_name = strdup(name);
+               goto FINISH_OFF;
        }
+       
+       EM_DEBUG_LOG_SEC("UTF-7 [%s](%d)->[%s](%d)",last_word, strlen(last_word), last_enc_word, strlen(last_enc_word));
+
+       /* if last word of mailbox name is UTF-8, replace it */
+       /* it is not a subfolder */
+       if (!last_slash) { 
+               ret_enc_name = strdup(last_enc_word);
+       }
+       else { /* it is a subfolder */
+               /*temprarily NULL assigned*/
+               *last_slash = '\0';
+               int len = strlen(name) + 1 + strlen(last_enc_word); /* including '/' */
+               ret_enc_name = em_malloc(len + 1); /* NULL */
+               if (!ret_enc_name) {
+                       EM_DEBUG_EXCEPTION("malloc failed...");
+                       err = EMAIL_ERROR_OUT_OF_MEMORY;
+                       ret = false;
+                       goto FINISH_OFF;
+               }
 
-       strcpy(*enc_name, name);
+               snprintf(ret_enc_name, len+1, "%s/%s", name, last_enc_word);
+               *last_slash = '/';
+       }
+
+       EM_DEBUG_LOG_SEC("utf-7 encoding complete!! name[%s], enc_name[%s]", name, ret_enc_name);
 
+FINISH_OFF:
+       EM_SAFE_FREE(last_enc_word);
+       *enc_name = ret_enc_name;
        if (err_code != NULL)
-               *err_code = EMAIL_ERROR_NONE;
+               *err_code = err;
 
-       EM_DEBUG_FUNC_END();
-       return true;
+       EM_DEBUG_FUNC_END("result [%s]", *enc_name);
+       return ret;
 }
 
 int emcore_get_temp_file_name(char **filename, int *err_code)
@@ -342,7 +412,7 @@ FINISH_OFF:
 
 int emcore_get_file_name(char *path, char **filename, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("path[%s], filename[%p], err_code[%p]", path, filename, err_code);
+       EM_DEBUG_FUNC_BEGIN_SEC("path[%s], filename[%p], err_code[%p]", path, filename, err_code);
 
        int ret = false;
        int error = EMAIL_ERROR_NONE;
@@ -372,7 +442,7 @@ FINISH_OFF:
        return ret;
 }
 
-int emcore_get_file_size(char *path, int *size, int *err_code)
+INTERNAL_FUNC int emcore_get_file_size(char *path, int *size, int *err_code)
 {
        EM_DEBUG_FUNC_BEGIN("path[%s], size[%p], err_code[%p]", path, size, err_code);
 
@@ -406,7 +476,78 @@ FINISH_OFF:
        return ret;
 }
 
+INTERNAL_FUNC int emcore_check_drm_file(char *path, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("path[%s], err_code[%p]", path, err_code);
+
+       int ret = false;
+       int drm_ret = false;
+       int error = EMAIL_ERROR_NONE;
+       drm_bool_type_e isdrm;
+
+       if (path == NULL) {
+               EM_DEBUG_EXCEPTION("path[%p]", path);
+               error = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       drm_ret = drm_is_drm_file(path, &isdrm);
+       if (drm_ret != DRM_RETURN_SUCCESS || isdrm != DRM_TRUE) {
+               EM_DEBUG_LOG("file is not drm file");
+               error = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
 
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+INTERNAL_FUNC int emcore_check_drm_is_ringtone(char *ringtone_path, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("ringtone_path[%s], err_code[%p]", ringtone_path, err_code);
+
+       int ret = false;
+       int drm_ret = false;
+       int error = EMAIL_ERROR_NONE;
+
+       if (ringtone_path == NULL) {
+               EM_DEBUG_EXCEPTION("path[%p]", ringtone_path);
+               error = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       drm_bool_type_e allowed = DRM_UNKNOWN;
+       drm_action_allowed_data_s data;
+       memset(&data, 0x00, sizeof(drm_action_allowed_data_s));
+       strncpy(data.file_path, ringtone_path, strlen(ringtone_path));
+       data.data = (int)DRM_SETAS_RINGTONE;
+
+       drm_ret = drm_is_action_allowed(DRM_HAS_VALID_SETAS_STATUS, &data, &allowed);
+
+       if (drm_ret != DRM_RETURN_SUCCESS || allowed != DRM_TRUE) {
+               EM_DEBUG_LOG("fail to drm_is_action_allowed [0x%x]", drm_ret);
+               error = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       EM_DEBUG_LOG("allowed [DRM_TRUE]");
+       ret = true;
+
+FINISH_OFF:
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
 
 static int _emcore_check_host(char *host)
 {
@@ -457,7 +598,7 @@ int emcore_get_address_count(char *addr_str, int *count, int *err_code)
                                }
                        }
                        if ((!p_addr->mailbox) || (_emcore_check_host(p_addr->host) == 0)) {
-                               EM_DEBUG_EXCEPTION("\t invalid address : mailbox[%s], host[%s]\n", p_addr->mailbox, p_addr->host);
+                               EM_DEBUG_EXCEPTION_SEC("\t invalid address : mailbox[%s], host[%s]\n", p_addr->mailbox, p_addr->host);
 
                                error = EMAIL_ERROR_INVALID_ADDRESS;
                                /* goto FINISH_OFF; */
@@ -495,7 +636,7 @@ INTERNAL_FUNC int emcore_set_network_error(int err_code)
        return true;
 }
 
-int emcore_get_empty_session(email_session_t **session)
+INTERNAL_FUNC int emcore_get_empty_session(email_session_t **session)
 {
        EM_DEBUG_FUNC_BEGIN("session[%p]", session);
 
@@ -520,7 +661,7 @@ int emcore_get_empty_session(email_session_t **session)
        return (i != SESSION_MAX) ? true : false;
 }
 
-int emcore_clear_session(email_session_t *session)
+INTERNAL_FUNC int emcore_clear_session(email_session_t *session)
 {
        EM_DEBUG_FUNC_BEGIN();
 
@@ -530,7 +671,7 @@ int emcore_clear_session(email_session_t *session)
        return true;
 }
 
-int emcore_get_current_session(email_session_t **session)
+INTERNAL_FUNC int emcore_get_current_session(email_session_t **session)
 {
        EM_DEBUG_FUNC_BEGIN("session[%p]", session);
 
@@ -551,13 +692,13 @@ int emcore_get_current_session(email_session_t **session)
        return (i != SESSION_MAX) ? true : false;
 }
 
-int emcore_get_mail_count_by_query(int account_id, int priority_sender, int *total_mail, int *unread_mail, int *err_code)
+INTERNAL_FUNC int emcore_get_mail_count_by_query(int account_id, int mailbox_type, int priority_sender, int *total_mail, int *unread_mail, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN();
+       EM_DEBUG_FUNC_BEGIN("account_id : [%d], mailbox_type : [%d], priority_sender : [%d]", account_id, mailbox_type, priority_sender);
 
        int ret = false;
        int err = EMAIL_ERROR_NONE;
-       int i, count;
+       int i = 0;
        int type = EMAIL_PRIORITY_SENDER;
        int unread_count = 0;
        int total_count = 0;
@@ -570,74 +711,119 @@ int emcore_get_mail_count_by_query(int account_id, int priority_sender, int *tot
        int filter_count = 0;
        email_list_filter_t *filter_list = NULL;
 
+       /* Get rule list */
        if (priority_sender) {
-               /* Get rule list */
-               if (!emstorage_get_rule(ALL_ACCOUNT, type, 0, &rule_count, &is_completed, &rule, true, &err) || !rule) {
+               if (!emstorage_get_rule(ALL_ACCOUNT, type, 0, &rule_count, &is_completed, &rule, true, &err)) {
                        EM_DEBUG_EXCEPTION("emstorage_get_rule failed");
                        goto FINISH_OFF;
                }
-
-               /* Make query for searching unread mail */
-               if (account_id != ALL_ACCOUNT) {
-                       filter_count = (rule_count * 2) + 3;
-               } else {
-                       filter_count = (rule_count * 2) + 1;                              // 1 is unseen field.
-               }
-
-               filter_list = em_malloc(sizeof(email_list_filter_t) * filter_count);
-               if (filter_list == NULL) {
-                       EM_DEBUG_EXCEPTION("em_malloc failed");
-                       err = EMAIL_ERROR_OUT_OF_MEMORY;
+               if (err == EMAIL_ERROR_FILTER_NOT_FOUND) {
+                       EM_DEBUG_LOG("no rule found");
+                       ret = true;             /*it is not an error*/
                        goto FINISH_OFF;
                }
+       }
+
+       EM_DEBUG_LOG_DEV ("rule count [%d]", rule_count);
+
+       /* Make query for searching unread mail */
+       filter_count = 1;   /* unseen field requires one filter, "flags_seen_field = 0" */
+       
+       if (rule_count > 0 )
+               filter_count += (rule_count * 2) + 2; /* one rule requires two filters,"A" "OR", plus two more operator "(" and ")" */
 
-               for (i = 0, count = 0; i < filter_count - 1; i += 2, count++) {
-                       filter_list[i].list_filter_item_type                             = EMAIL_LIST_FILTER_ITEM_RULE;
-                       filter_list[i].list_filter_item.rule.rule_type                   = EMAIL_LIST_FILTER_RULE_INCLUDE;
-                       filter_list[i].list_filter_item.rule.target_attribute            = EMAIL_MAIL_ATTRIBUTE_FROM;
-                       filter_list[i].list_filter_item.rule.key_value.string_type_value = EM_SAFE_STRDUP(rule[count].value);
 
-                       filter_list[i+1].list_filter_item_type                           = EMAIL_LIST_FILTER_ITEM_OPERATOR;
-                       if (i == (filter_count - 2)) {
-                               filter_list[i+1].list_filter_item.operator_type          = EMAIL_LIST_FILTER_OPERATOR_AND;
-                       } else {
-                               filter_list[i+1].list_filter_item.operator_type          = EMAIL_LIST_FILTER_OPERATOR_OR;
+       if (account_id != ALL_ACCOUNT) {
+               filter_count += 2; /* two filters, "AND" "account_id = x" */
+       } 
+
+       if (mailbox_type)
+               filter_count += 2; /* two filters, "AND" "mailbox_type = x" */
+
+       filter_list = em_malloc(sizeof(email_list_filter_t) * filter_count);
+       if (filter_list == NULL) {
+               EM_DEBUG_EXCEPTION("em_malloc failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       int k = 0;        
+
+       /* priority sender only, convert one rule to two filters which is composed of from_address and or/and */
+       /* example: ( from_A OR from_B ) AND ... */
+       if (rule_count > 0) {
+               /* first, add left parenthesis to from address clause, "(" */
+               filter_list[0].list_filter_item_type                   = EMAIL_LIST_FILTER_ITEM_OPERATOR;
+               filter_list[0].list_filter_item.operator_type          = EMAIL_LIST_FILTER_OPERATOR_LEFT_PARENTHESIS;
+               
+               for (i = 0; i < rule_count; i++) {
+                       /*array at odd index(1, 3, 5,..) has rule values, "from_A" */
+                       k = i*2+1;
+                       filter_list[k].list_filter_item_type                             = EMAIL_LIST_FILTER_ITEM_RULE;
+                       filter_list[k].list_filter_item.rule.rule_type                   = EMAIL_LIST_FILTER_RULE_INCLUDE;
+                       filter_list[k].list_filter_item.rule.target_attribute            = EMAIL_MAIL_ATTRIBUTE_FROM;
+                       filter_list[k].list_filter_item.rule.key_value.string_type_value = EM_SAFE_STRDUP(rule[i].value2);
+
+                       /*array at even index(2, 4, 6,..) has either AND ,or OR*/
+                       if (i != (rule_count - 1)) { /*if it is not the last rule, "OR" */
+                               filter_list[++k].list_filter_item_type                 = EMAIL_LIST_FILTER_ITEM_OPERATOR;
+                               filter_list[k].list_filter_item.operator_type          = EMAIL_LIST_FILTER_OPERATOR_OR;
+
+                       } else { /* ")" "AND" */
+                               filter_list[++k].list_filter_item_type         = EMAIL_LIST_FILTER_ITEM_OPERATOR;
+                               filter_list[k].list_filter_item.operator_type  = EMAIL_LIST_FILTER_OPERATOR_RIGHT_PARENTHESIS; 
+
+                               filter_list[++k].list_filter_item_type         = EMAIL_LIST_FILTER_ITEM_OPERATOR;
+                               filter_list[k].list_filter_item.operator_type  = EMAIL_LIST_FILTER_OPERATOR_AND;
+                               k++;
                        }
                }
+       }
 
-               filter_list[i].list_filter_item_type                              = EMAIL_LIST_FILTER_ITEM_RULE;
-               filter_list[i].list_filter_item.rule.rule_type                    = EMAIL_LIST_FILTER_RULE_EQUAL;
-               filter_list[i].list_filter_item.rule.target_attribute             = EMAIL_MAIL_ATTRIBUTE_FLAGS_SEEN_FIELD;
-               filter_list[i].list_filter_item.rule.key_value.integer_type_value = 0;
+       /*rule value, unseen +1*/
+       filter_list[k].list_filter_item_type                              = EMAIL_LIST_FILTER_ITEM_RULE;
+       filter_list[k].list_filter_item.rule.rule_type                    = EMAIL_LIST_FILTER_RULE_EQUAL;
+       filter_list[k].list_filter_item.rule.target_attribute             = EMAIL_MAIL_ATTRIBUTE_FLAGS_SEEN_FIELD;
+       filter_list[k++].list_filter_item.rule.key_value.integer_type_value = 0;
 
-               if (account_id != ALL_ACCOUNT) {
-                       filter_list[i+1].list_filter_item_type                              = EMAIL_LIST_FILTER_ITEM_OPERATOR;
-                       filter_list[i+1].list_filter_item.operator_type                     = EMAIL_LIST_FILTER_OPERATOR_AND;
+       /*account_id requires two filters*/
+       if (account_id != ALL_ACCOUNT) {
+               /* odd index, logical operator */
+               filter_list[k].list_filter_item_type                              = EMAIL_LIST_FILTER_ITEM_OPERATOR;
+               filter_list[k++].list_filter_item.operator_type                   = EMAIL_LIST_FILTER_OPERATOR_AND;
 
-                       filter_list[i+2].list_filter_item_type                              = EMAIL_LIST_FILTER_ITEM_RULE;
-                       filter_list[i+2].list_filter_item.rule.rule_type                    = EMAIL_LIST_FILTER_RULE_EQUAL;
-                       filter_list[i+2].list_filter_item.rule.target_attribute             = EMAIL_MAIL_ATTRIBUTE_ACCOUNT_ID;
-                       filter_list[i+2].list_filter_item.rule.key_value.integer_type_value = account_id;
-               }
+               /* even index, rule value */
+               filter_list[k].list_filter_item_type                              = EMAIL_LIST_FILTER_ITEM_RULE;
+               filter_list[k].list_filter_item.rule.rule_type                    = EMAIL_LIST_FILTER_RULE_EQUAL;
+               filter_list[k].list_filter_item.rule.target_attribute             = EMAIL_MAIL_ATTRIBUTE_ACCOUNT_ID;
+               filter_list[k++].list_filter_item.rule.key_value.integer_type_value = account_id;
+       }
 
-               if ((err = emstorage_write_conditional_clause_for_getting_mail_list(filter_list, filter_count, NULL, 0, -1, -1, &conditional_clause_string)) != EMAIL_ERROR_NONE) {
-                       EM_DEBUG_EXCEPTION("emstorage_write_conditional_clause_for_getting_mail_list failed[%d]", err);
-                       goto FINISH_OFF;
-               }
+       /*mailbox_type requires two filters*/
+       if (mailbox_type) {
+               /* odd index, logical operator */
+               filter_list[k].list_filter_item_type                              = EMAIL_LIST_FILTER_ITEM_OPERATOR;
+               filter_list[k++].list_filter_item.operator_type                     = EMAIL_LIST_FILTER_OPERATOR_AND;
 
-               EM_DEBUG_LOG("conditional_clause_string[%s]", conditional_clause_string);
+               /* even index, rule value */
+               filter_list[k].list_filter_item_type                              = EMAIL_LIST_FILTER_ITEM_RULE;
+               filter_list[k].list_filter_item.rule.rule_type                    = EMAIL_LIST_FILTER_RULE_EQUAL;
+               filter_list[k].list_filter_item.rule.target_attribute             = EMAIL_MAIL_ATTRIBUTE_MAILBOX_TYPE;
+               filter_list[k++].list_filter_item.rule.key_value.integer_type_value = mailbox_type;
+       }
 
-               /* Search the mail of priority sender in DB */
-               if ((err = emstorage_query_mail_count(conditional_clause_string, true, &total_count, &unread_count)) != EMAIL_ERROR_NONE) {
-                       EM_DEBUG_EXCEPTION("emstorage_query_mail_count failed:[%d]", err);
-                       goto FINISH_OFF;
-               }
-       } else {
-               if (!emstorage_get_mail_count(account_id, 0, &total_count, &unread_count, true, &err))  {
-                       EM_DEBUG_EXCEPTION(" emstorage_get_mail_count failed - %d", err);
 
-                       goto FINISH_OFF;
-               }
+       if ((err = emstorage_write_conditional_clause_for_getting_mail_list(filter_list, filter_count, NULL, 0, -1, -1, &conditional_clause_string)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emstorage_write_conditional_clause_for_getting_mail_list failed[%d]", err);
+               goto FINISH_OFF;
+       }
+
+       EM_DEBUG_LOG_DEV ("conditional_clause_string[%s]", conditional_clause_string);
+
+       /* Search the mail of priority sender in DB */
+       if ((err = emstorage_query_mail_count(conditional_clause_string, true, &total_count, &unread_count)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emstorage_query_mail_count failed:[%d]", err);
+               goto FINISH_OFF;
        }
 
        ret = true;
@@ -664,6 +850,41 @@ FINISH_OFF:
        return ret;
 }
 
+INTERNAL_FUNC int emcore_display_badge_count(int count)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       /* Use badge API */
+       int err = EMAIL_ERROR_NONE;
+       badge_error_e badge_err = BADGE_ERROR_NONE;
+       bool exist;
+
+       if((badge_err = badge_is_existing("com.samsung.email", &exist)) != BADGE_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("badge_is_existing failed [%d]", badge_err);
+               err = EMAIL_ERROR_BADGE_API_FAILED;
+               goto FINISH_OFF;
+       }
+
+       if (!exist) {
+               /* create badge */
+               if((badge_err = badge_create("com.samsung.email", "/usr/bin/email-service")) != BADGE_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("badge_create failed [%d]", badge_err);
+                       err = EMAIL_ERROR_BADGE_API_FAILED;
+                       goto FINISH_OFF;
+               }
+       }
+
+       if((badge_err = badge_set_count("com.samsung.email", count)) != BADGE_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("badge_set_count failed [%d]", badge_err);
+               err = EMAIL_ERROR_BADGE_API_FAILED;
+               goto FINISH_OFF;
+       }
+
+FINISH_OFF:
+
+       EM_DEBUG_FUNC_END();
+       return err;
+}
+
 int emcore_display_unread_in_badge()
 {
        EM_DEBUG_FUNC_BEGIN();
@@ -672,79 +893,113 @@ int emcore_display_unread_in_badge()
        int err = EMAIL_ERROR_NONE;
        int total_unread_count = 0;
        int total_mail_count = 0;
-       int badge_ticker = 0;
-       int priority_sender = 0;
+       int unseen = 0;
+       int badge_status = false;
+       int general_noti_status = false;
+       int vip_noti_status = false;
+       int vip_mail_count = 0;
+       int vip_unread_count = 0;
+       int vip_notification_mode = 0;
+
+       /* get general noti status */
+       if (vconf_get_bool(VCONFKEY_SETAPPL_STATE_TICKER_NOTI_EMAIL_BOOL, &general_noti_status) != 0) {
+               EM_DEBUG_EXCEPTION("vconf_get_int failed");
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
 
+       /* get vip noti status */
+       if (vconf_get_bool(VCONF_VIP_NOTI_NOTIFICATION_TICKER, &vip_noti_status) != 0) {
+               EM_DEBUG_EXCEPTION("vconf_get_int failed");
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
 
-       /* Get the Global noti ticker */
-       if (vconf_get_bool(VCONFKEY_TICKER_NOTI_BADGE_EMAIL, &badge_ticker) != 0) {
-               EM_DEBUG_EXCEPTION("vconf_get_bool failed");
-               err = EMAIL_ERROR_GCONF_FAILURE;
+       if (!general_noti_status && !vip_noti_status) {
+               EM_DEBUG_LOG("both notification disabled");
+               ret = true;
                goto FINISH_OFF;
        }
 
-       /* Get the priority noti ticker */
-       if (!badge_ticker) {
-               if (vconf_get_bool(VCONF_VIP_NOTI_BADGE_TICKER, &badge_ticker) != 0) {
-                       EM_DEBUG_EXCEPTION("vconf_get_bool failed");
-                       err = EMAIL_ERROR_GCONF_FAILURE;
+       if (!emcore_get_mail_count_by_query(ALL_ACCOUNT, EMAIL_MAILBOX_TYPE_INBOX, 0, &total_mail_count, &total_unread_count, &err)) {
+               EM_DEBUG_EXCEPTION("emcore_get_mail_count_by_query failed");
+               goto FINISH_OFF;
+       }
+
+       if (vip_noti_status) {
+               if (!emcore_get_mail_count_by_query(ALL_ACCOUNT, EMAIL_MAILBOX_TYPE_INBOX, true, &vip_mail_count, &vip_unread_count, &err)) {
+                       EM_DEBUG_EXCEPTION("emcore_get_mail_count_by_query failed");
                        goto FINISH_OFF;
                }
+       }
 
-               if (!badge_ticker) {
-                       EM_DEBUG_LOG("Not display the badge");
+       if (general_noti_status && !vip_noti_status) {
+               EM_DEBUG_LOG("GERNERAL NOTI MODE");
+               vip_notification_mode = 0;
+               unseen = total_unread_count;
+       } else if (!general_noti_status && vip_noti_status) {
+               EM_DEBUG_LOG("VIP NOTI MODE");
+               if (err == EMAIL_ERROR_FILTER_NOT_FOUND) {
+                       EM_DEBUG_LOG("VIP filter not found");
                        ret = true;
                        goto FINISH_OFF;
+               } else {
+                       unseen = vip_unread_count;
+               }
+               vip_notification_mode = 1;
+       } else if (general_noti_status && vip_noti_status) {
+               if (err == EMAIL_ERROR_FILTER_NOT_FOUND) {
+                       EM_DEBUG_LOG("VIP filter not found");
+                       EM_DEBUG_LOG("GERNERAL NOTI MODE");
+                       vip_notification_mode = 0;
+                       unseen = total_unread_count;
+               } else {
+                       EM_DEBUG_LOG("VIP NOTI MODE");
+                       vip_notification_mode = 1;
+                       unseen = vip_unread_count;
                }
-
-               priority_sender = 1;
-       }
-
-       /* Get unread mail count */
-       if (!emcore_get_mail_count_by_query(ALL_ACCOUNT, priority_sender, &total_mail_count, &total_unread_count, &err)) {
-               EM_DEBUG_EXCEPTION("emcore_get_mail_count_by_query failed");
-               goto FINISH_OFF;
        }
 
-       /* Use badge API */
-       badge_error_e badge_err = BADGE_ERROR_NONE;
-       bool exist;
-
-       if((badge_err = badge_is_existing("com.samsung.email", &exist)) != BADGE_ERROR_NONE) {
-               EM_DEBUG_EXCEPTION("badge_is_existing failed [%d]", badge_err);
-               err = EMAIL_ERROR_BADGE_API_FAILED;
-               goto FINISH_OFF;
-       }
-       if (!exist) {
-               /* create badge */
-               if((badge_err = badge_create("com.samsung.email", "/usr/bin/email-service")) != BADGE_ERROR_NONE) {
-                       EM_DEBUG_EXCEPTION("badge_create failed [%d]", badge_err);
-                       err = EMAIL_ERROR_BADGE_API_FAILED;
+       if (vip_notification_mode) {
+               if (vconf_get_bool(VCONF_VIP_NOTI_BADGE_TICKER, &badge_status) != 0) {
+                       EM_DEBUG_EXCEPTION("vconf_get_bool failed");
+                       err = EMAIL_ERROR_GCONF_FAILURE;
+                       goto FINISH_OFF;
+               }
+       } else {
+               if (vconf_get_bool(VCONFKEY_TICKER_NOTI_BADGE_EMAIL, &badge_status) != 0) {
+                       EM_DEBUG_EXCEPTION("vconf_get_bool failed");
+                       err = EMAIL_ERROR_GCONF_FAILURE;
                        goto FINISH_OFF;
                }
        }
 
-       if((badge_err = badge_set_count("com.samsung.email", total_unread_count)) != BADGE_ERROR_NONE) {
-               EM_DEBUG_EXCEPTION("badge_set_count failed [%d]", badge_err);
-               err = EMAIL_ERROR_BADGE_API_FAILED;
+       if (!badge_status) {
+               EM_DEBUG_LOG("badge setting OFF");
+               ret = true;
                goto FINISH_OFF;
        }
 
-       if (total_unread_count <= 0)
+       if (unseen < 0)
                goto FINISH_OFF;
 
+       if ((err = emcore_display_badge_count(unseen)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emcore_display_badge_count failed : [%d]", err);
+               goto FINISH_OFF;
+       }
+       
        ret = true;
 
 FINISH_OFF:
-
+       
+       EM_DEBUG_FUNC_END();
        return ret;
 }
 
 static int emcore_layout_multi_noti(notification_h noti, int unread_mail, char *email_address, char *account_name)
 {
-       EM_DEBUG_FUNC_BEGIN();
+       EM_DEBUG_FUNC_BEGIN("unread_count %d", unread_mail);
        notification_error_e noti_err = NOTIFICATION_ERROR_NONE;
-       char modified_string[10];
 
        noti_err = notification_set_layout(noti, NOTIFICATION_LY_NOTI_EVENT_MULTIPLE);
        if (noti_err != NOTIFICATION_ERROR_NONE) {
@@ -752,21 +1007,13 @@ static int emcore_layout_multi_noti(notification_h noti, int unread_mail, char *
                goto FINISH_OFF;
        }
 
-       SNPRINTF(modified_string, sizeof(modified_string), "%d", unread_mail);
-
-       noti_err = notification_set_text(noti, NOTIFICATION_TEXT_TYPE_TITLE, "Email", NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+       noti_err = notification_set_text(noti, NOTIFICATION_TEXT_TYPE_TITLE, "Email", "IDS_EMAIL_OPT_EMAIL", NOTIFICATION_VARIABLE_TYPE_NONE);
        if (noti_err != NOTIFICATION_ERROR_NONE) {
                EM_DEBUG_EXCEPTION("notification_set_text TEXT_TYPE_TITLE failed");
                goto FINISH_OFF;
        }
 
-       noti_err = notification_set_text(noti, NOTIFICATION_TEXT_TYPE_EVENT_COUNT, modified_string, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
-       if (noti_err != NOTIFICATION_ERROR_NONE) {
-               EM_DEBUG_EXCEPTION("notification_set_text TEXT_TYPE_EVENT_COUNT failed");
-               goto FINISH_OFF;
-       }
-
-       noti_err = notification_set_text(noti, NOTIFICATION_TEXT_TYPE_CONTENT, "new emails", "IDS_EMAIL_BODY_NEW_EMAILS", NOTIFICATION_VARIABLE_TYPE_NONE);
+       noti_err = notification_set_text(noti, NOTIFICATION_TEXT_TYPE_CONTENT, "New email received", "IDS_EMAIL_BODY_PD_NEW_EMAILS_RECEIVED", NOTIFICATION_VARIABLE_TYPE_INT, unread_mail, NOTIFICATION_VARIABLE_TYPE_NONE);
        if (noti_err != NOTIFICATION_ERROR_NONE) {
                EM_DEBUG_EXCEPTION("notification_set_text TEXT_TYPE_CONTENT failed");
                goto FINISH_OFF;
@@ -790,13 +1037,25 @@ static int emcore_layout_multi_noti(notification_h noti, int unread_mail, char *
                goto FINISH_OFF;
        }
 
+       noti_err = notification_set_image(noti, NOTIFICATION_IMAGE_TYPE_ICON_FOR_INDICATOR, EMAIL_NOTI_ICON_PATH);
+       if (noti_err != NOTIFICATION_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("notification_set_image TYPE_ICON failed");
+               goto FINISH_OFF;
+       }
+
+       noti_err = notification_set_image(noti, NOTIFICATION_IMAGE_TYPE_ICON_FOR_LOCK, EMAIL_NOTI_ICON_PATH);
+       if (noti_err != NOTIFICATION_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("notification_set_image TYPE_ICON failed");
+               goto FINISH_OFF;
+       }
+
 FINISH_OFF:
 
        EM_DEBUG_FUNC_END("noti_err : [%d]", noti_err);
        return noti_err;
 }
 
-static int emcore_layout_single_noti(notification_h noti, char *account_name, char *display_sender, time_t time, char *subject)
+static int emcore_layout_single_noti(notification_h noti, char *account_name, int ids, char *display_sender, time_t time, char *subject)
 {
        EM_DEBUG_FUNC_BEGIN();
        notification_error_e noti_err = NOTIFICATION_ERROR_NONE;
@@ -807,7 +1066,11 @@ static int emcore_layout_single_noti(notification_h noti, char *account_name, ch
                goto FINISH_OFF;
        }
 
-       noti_err = notification_set_text(noti, NOTIFICATION_TEXT_TYPE_TITLE, "Email", NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+       if (ids)
+               noti_err = notification_set_text(noti, NOTIFICATION_TEXT_TYPE_TITLE, "Email", "IDS_COM_BODY_EMAIL", NOTIFICATION_VARIABLE_TYPE_NONE);
+       else
+               noti_err = notification_set_text(noti, NOTIFICATION_TEXT_TYPE_TITLE, "Email", "IDS_EMAIL_OPT_EMAIL", NOTIFICATION_VARIABLE_TYPE_NONE);
+
        if (noti_err != NOTIFICATION_ERROR_NONE) {
                EM_DEBUG_EXCEPTION("notification_set_text TEXT_TYPE_TITLE failed");
                goto FINISH_OFF;
@@ -819,7 +1082,11 @@ static int emcore_layout_single_noti(notification_h noti, char *account_name, ch
                goto FINISH_OFF;
        }
 
-       noti_err = notification_set_text(noti, NOTIFICATION_TEXT_TYPE_INFO_1, display_sender, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+       if (ids)
+               noti_err = notification_set_text(noti, NOTIFICATION_TEXT_TYPE_INFO_1, NULL, display_sender, NOTIFICATION_VARIABLE_TYPE_NONE);
+       else
+               noti_err = notification_set_text(noti, NOTIFICATION_TEXT_TYPE_INFO_1, display_sender, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+
        if (noti_err != NOTIFICATION_ERROR_NONE) {
                EM_DEBUG_EXCEPTION("notification_set_text TEXT_TYPE_INFO_1 failed");
                goto FINISH_OFF;
@@ -839,25 +1106,67 @@ static int emcore_layout_single_noti(notification_h noti, char *account_name, ch
                goto FINISH_OFF;
        }
 
-       noti_err = notification_set_image(noti, NOTIFICATION_IMAGE_TYPE_ICON, EMAIL_NOTI_ICON_PATH);
+       noti_err = notification_set_image(noti, NOTIFICATION_IMAGE_TYPE_ICON, EMAIL_NOTI_ICON_PATH);
+       if (noti_err != NOTIFICATION_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("notification_set_image TYPE_ICON failed");
+               goto FINISH_OFF;
+       }
+
+       noti_err = notification_set_image(noti, NOTIFICATION_IMAGE_TYPE_ICON_FOR_INDICATOR, EMAIL_NOTI_ICON_PATH);
+       if (noti_err != NOTIFICATION_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("notification_set_image TYPE_ICON failed");
+               goto FINISH_OFF;
+       }
+
+       noti_err = notification_set_image(noti, NOTIFICATION_IMAGE_TYPE_ICON_FOR_LOCK, EMAIL_NOTI_ICON_PATH);
+       if (noti_err != NOTIFICATION_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("notification_set_image TYPE_ICON failed");
+               goto FINISH_OFF;
+       }
+FINISH_OFF:
+
+       EM_DEBUG_FUNC_END("noti_err : [%d]", noti_err);
+       return noti_err;
+}
+
+INTERNAL_FUNC int emcore_add_notification(int account_id, int mail_id, int unread_mail_count, int input_play_alert_tone, int sending_error, unsigned long display)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d] mail_id[%d] unread_mail_count[%d] input_play_alert_tone[%d]", account_id, mail_id, unread_mail_count, input_play_alert_tone );
+       int err = EMAIL_ERROR_NONE;
+
+       EM_DEBUG_FUNC_END("ret [%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC int emcore_add_notification_for_send(int account_id, int mail_id, email_action_t action, int sending_error, unsigned long display)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id: %d, mail_id: %d, action:%d", account_id, mail_id, action );
+       int err = EMAIL_ERROR_NONE;
+
+       EM_DEBUG_FUNC_END("ret [%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC void emcore_update_notification_for_send(int account_id, int mail_id, double progress)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id: %d, mail_id: %d, progress: %f", account_id, mail_id, progress);
+
+       int private_id = 0;
+       char vconf_private_id[MAX_PATH] = {0, };
+       notification_error_e noti_err = NOTIFICATION_ERROR_NONE;
+
+       SNPRINTF(vconf_private_id, sizeof(vconf_private_id), "%s/%d", VCONF_KEY_NOTI_PRIVATE_ID, account_id);
+       if (vconf_get_int(vconf_private_id, &private_id) != 0) {
+               EM_DEBUG_EXCEPTION("vconf_get_int failed");
+       }
+
+       EM_DEBUG_LOG("Private_id = [%d]", private_id);
+       noti_err = notification_update_progress(g_sending_noti_handle, private_id, progress);
        if (noti_err != NOTIFICATION_ERROR_NONE) {
-               EM_DEBUG_EXCEPTION("notification_set_image TYPE_ICON failed");
-               goto FINISH_OFF;
+               EM_DEBUG_LOG("notification_update_progress failed [0x%x]", noti_err);
        }
 
-FINISH_OFF:
-
-       EM_DEBUG_FUNC_END("noti_err : [%d]", noti_err);
-       return noti_err;
-}
-
-static int emcore_add_notification(int account_id, int mail_id, email_action_t action)
-{
-       EM_DEBUG_FUNC_BEGIN();
-       int err = EMAIL_ERROR_NONE;
-
-       EM_DEBUG_FUNC_END("ret [%d]", err);
-       return err;
+       EM_DEBUG_FUNC_END();
 }
 
 INTERNAL_FUNC int emcore_show_user_message(int id, email_action_t action, int error)
@@ -865,13 +1174,11 @@ INTERNAL_FUNC int emcore_show_user_message(int id, email_action_t action, int er
        EM_DEBUG_FUNC_BEGIN("id[%d], action[%d], error[%d]", id, action, error);
 
        int ret = false;
+       int display = 0;
+       emstorage_mail_tbl_t *mail_table_data = NULL;
 
-       if (action == EMAIL_ACTION_SEND_MAIL && error != EMAIL_ERROR_CANCELLED) {
+       if ((action == EMAIL_ACTION_SEND_MAIL || action == EMAIL_ACTION_SENDING_MAIL) && error != EMAIL_ERROR_CANCELLED) {
        /*  In case email is cancelled using cancel button in Outbox there is no need to show Cancel/Retry Pop up */
-               emstorage_mail_tbl_t *mail_table_data = NULL;
-
-               if (error == 0) /*  error 0 means 'this is not error' */
-                       return true;
 
                if (id <= 0) {
                        EM_DEBUG_LOG("Invalid mail_id");
@@ -883,20 +1190,18 @@ INTERNAL_FUNC int emcore_show_user_message(int id, email_action_t action, int er
                        return false;
                }
 
-               if (emcore_add_notification(mail_table_data->account_id, id, action) != EMAIL_ERROR_NONE) {
+               if (emcore_add_notification_for_send(mail_table_data->account_id, id, action, error, display) != EMAIL_ERROR_NONE) {
                        EM_DEBUG_EXCEPTION("emcore_notification_set error");
-
-                       if (!emstorage_free_mail(&mail_table_data, 1, NULL))
-                               EM_DEBUG_EXCEPTION("emstorage_free_mail Failed");
-
-                       return false;
+                       goto FINISH_OFF;
                }
-
-               if (!emstorage_free_mail(&mail_table_data, 1, NULL))
-                       EM_DEBUG_EXCEPTION("emstorage_free_mail Failed");
-
                ret = true;
        }
+
+FINISH_OFF:
+
+       if (mail_table_data && !emstorage_free_mail(&mail_table_data, 1, NULL))
+               EM_DEBUG_EXCEPTION("emstorage_free_mail Failed");
+
        EM_DEBUG_FUNC_END("ret [%d]", ret);
        return ret;
 }
@@ -923,7 +1228,7 @@ int emcore_get_storage_status(void)
        return storage_status;
 }
 
-int emcore_is_storage_full(int *err_code)
+INTERNAL_FUNC int emcore_is_storage_full(int *err_code)
 {
        EM_DEBUG_FUNC_BEGIN();
 
@@ -938,10 +1243,11 @@ int emcore_is_storage_full(int *err_code)
        }
        else  {
                long i_free = (buf.f_bavail * buf.f_bsize) / (1024 * 1024);
-               EM_DEBUG_LOG("f_bfree[%d] f_bsize[%d]", buf.f_bavail, buf.f_bsize);
-               EM_DEBUG_LOG("Free space of storage is[%ld] MB.", i_free);
-               if (i_free < EMAIL_LIMITATION_FREE_SPACE)
+               EM_DEBUG_LOG_DEV("f_bavail[%d] f_bsize[%d]", buf.f_bavail, buf.f_bsize);
+               if (i_free < EMAIL_LIMITATION_FREE_SPACE) {
+                       EM_DEBUG_EXCEPTION("Not enough free space of storage [%ld] MB.", i_free);
                        err = EMAIL_ERROR_MAIL_MEMORY_FULL;
+               }
        }
 
        if (err == EMAIL_ERROR_MAIL_MEMORY_FULL)
@@ -971,7 +1277,7 @@ int emcore_calc_mail_size(email_mail_data_t *input_mail_data, email_attachment_d
 
        if (input_mail_data->file_path_plain != NULL) {
                if (stat(input_mail_data->file_path_plain, &st_buf) < 0)  {
-                       EM_DEBUG_EXCEPTION("input_mail_data->file_path_plain : stat(\"%s\") failed...", input_mail_data->file_path_plain);
+                       EM_DEBUG_EXCEPTION_SEC("input_mail_data->file_path_plain : stat(\"%s\") failed...", input_mail_data->file_path_plain);
                        err = EMAIL_ERROR_FILE_NOT_FOUND;
                        goto FINISH_OFF;
                }
@@ -982,7 +1288,7 @@ int emcore_calc_mail_size(email_mail_data_t *input_mail_data, email_attachment_d
 
        if (input_mail_data->file_path_html != NULL) {
                if (stat(input_mail_data->file_path_html, &st_buf) < 0) {
-                       EM_DEBUG_EXCEPTION("input_mail_data->file_path_html : stat(\"%s\") failed...", input_mail_data->file_path_html);
+                       EM_DEBUG_EXCEPTION_SEC("input_mail_data->file_path_html : stat(\"%s\") failed...", input_mail_data->file_path_html);
                        err = EMAIL_ERROR_FILE_NOT_FOUND;
                        goto FINISH_OFF;
                }
@@ -1023,6 +1329,11 @@ char *emcore_get_alias_of_mailbox(const char *mailbox_path)
        mailbox = g_strdup(mailbox_path);
        token_list = g_strsplit_set(mailbox, "/", -1);
 
+       if(token_list == NULL) {
+               EM_DEBUG_LOG("g_strsplit_set failed.");
+               return NULL;
+       }
+
        if (mailbox)
                g_free(mailbox);
 
@@ -1116,6 +1427,18 @@ void emcore_fill_address_information_of_mail_tbl(emstorage_mail_tbl_t *mail_data
        char *first_address = NULL;
        char *recipient     = NULL;
 
+       int i = 0;
+       int vector_len = 0;
+       char **vector;
+       char *recipient_self = NULL;
+
+       email_account_t *ref_account = NULL;
+
+       ref_account = emcore_get_account_reference(mail_data->account_id);
+       if (!ref_account)  {
+               EM_DEBUG_LOG("emcore_get_account_reference failed [%d]", mail_data->account_id);
+       }
+
        /*  sender alias & address */
        if (emcore_get_first_address(mail_data->full_address_from, &first_alias, &first_address) == true) {
                if (first_alias == NULL) {
@@ -1137,6 +1460,25 @@ void emcore_fill_address_information_of_mail_tbl(emstorage_mail_tbl_t *mail_data
        else if (mail_data->full_address_bcc != NULL)
                recipient = mail_data->full_address_bcc;
 
+       /* if full_address_to contains account address, set account address to email_address_recipient */
+       if (ref_account && mail_data->full_address_to &&
+                       g_strrstr(mail_data->full_address_to, ref_account->user_email_address)) {
+               vector = g_strsplit_set(mail_data->full_address_to, ";", -1);
+               vector_len = g_strv_length(vector);
+
+               for (i = 0; i < vector_len; i++) {
+                       if (g_strrstr(vector[i], ref_account->user_email_address)) {
+                               recipient_self = EM_SAFE_STRDUP(vector[i]);
+                               break;
+                       }
+               }
+               g_strfreev(vector);
+
+               if (recipient_self) {
+                       recipient = recipient_self;
+               }
+       }
+
        if (emcore_get_first_address(recipient, &first_alias, &first_address) == true) {
                if (first_alias == NULL)
                        mail_data->alias_recipient = EM_SAFE_STRDUP(first_address);
@@ -1145,6 +1487,13 @@ void emcore_fill_address_information_of_mail_tbl(emstorage_mail_tbl_t *mail_data
 
                mail_data->email_address_recipient = first_address;
        }
+
+       if (ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+
+       EM_SAFE_FREE(recipient_self);
        EM_DEBUG_FUNC_END();
 }
 
@@ -1172,6 +1521,7 @@ static struct email_attribute_info _mail_attribute_info_array[] = {
                {EMAIL_MAIL_ATTRIBUTE_CC, "full_address_cc", EMAIL_MAIL_ATTRIBUTE_VALUE_TYPE_STRING},
                {EMAIL_MAIL_ATTRIBUTE_BCC, "full_address_bcc", EMAIL_MAIL_ATTRIBUTE_VALUE_TYPE_STRING},
                {EMAIL_MAIL_ATTRIBUTE_BODY_DOWNLOAD_STATUS, "body_download_status", EMAIL_MAIL_ATTRIBUTE_VALUE_TYPE_INTEGER},
+               {EMAIL_MAIL_ATTRIBUTE_MAIL_SIZE, "mail_size", EMAIL_MAIL_ATTRIBUTE_VALUE_TYPE_INTEGER},
                {EMAIL_MAIL_ATTRIBUTE_FILE_PATH_PLAIN, "file_path_plain",EMAIL_MAIL_ATTRIBUTE_VALUE_TYPE_STRING},
                {EMAIL_MAIL_ATTRIBUTE_FILE_PATH_HTML,"file_path_html", EMAIL_MAIL_ATTRIBUTE_VALUE_TYPE_STRING},
                {EMAIL_MAIL_ATTRIBUTE_FILE_SIZE,"file_size", EMAIL_MAIL_ATTRIBUTE_VALUE_TYPE_INTEGER},
@@ -1197,6 +1547,11 @@ static struct email_attribute_info _mail_attribute_info_array[] = {
                {EMAIL_MAIL_ATTRIBUTE_DIGEST_TYPE,"digest_type", EMAIL_MAIL_ATTRIBUTE_VALUE_TYPE_INTEGER},
                {EMAIL_MAIL_ATTRIBUTE_SMIME_TYPE,"smime_type", EMAIL_MAIL_ATTRIBUTE_VALUE_TYPE_INTEGER},
                {EMAIL_MAIL_ATTRIBUTE_SCHEDULED_SENDING_TIME,"scheduled_sending_time", EMAIL_MAIL_ATTRIBUTE_VALUE_TYPE_TIME},
+               {EMAIL_MAIL_ATTRIBUTE_REMAINING_RESEND_TIMES,"remaining_resend_times", EMAIL_MAIL_ATTRIBUTE_VALUE_TYPE_INTEGER},
+               {EMAIL_MAIL_ATTRIBUTE_TAG_ID,"tag_id", EMAIL_MAIL_ATTRIBUTE_VALUE_TYPE_INTEGER},
+               {EMAIL_MAIL_ATTRIBUTE_REPLIED_TIME,"replied_time", EMAIL_MAIL_ATTRIBUTE_VALUE_TYPE_TIME},
+               {EMAIL_MAIL_ATTRIBUTE_FORWARDED_TIME,"forwarded_time", EMAIL_MAIL_ATTRIBUTE_VALUE_TYPE_TIME},
+               {EMAIL_MAIL_ATTRIBUTE_RECIPIENT_ADDRESS,"email_recipient_address", EMAIL_MAIL_ATTRIBUTE_VALUE_TYPE_STRING},
                {EMAIL_MAIL_ATTRIBUTE_EAS_DATA_LENGTH_TYPE,"eas_data_length", EMAIL_MAIL_ATTRIBUTE_VALUE_TYPE_INTEGER},
                {EMAIL_MAIL_ATTRIBUTE_EAS_DATA_TYPE,"eas_data", EMAIL_MAIL_ATTRIBUTE_VALUE_TYPE_BINARY}
 };
@@ -1210,7 +1565,7 @@ INTERNAL_FUNC char* emcore_get_mail_field_name_by_attribute_type(email_mail_attr
                return NULL;
        }
 
-       EM_DEBUG_FUNC_END("return [%s]", _mail_attribute_info_array[input_attribute_type].attribute_name);
+       EM_DEBUG_LOG_DEV("return [%s]", _mail_attribute_info_array[input_attribute_type].attribute_name);
        return _mail_attribute_info_array[input_attribute_type].attribute_name;
 }
 
@@ -1269,7 +1624,7 @@ FINISH_OFF:
 #ifdef __FEATURE_BODY_SEARCH__
 int emcore_strip_mail_body_from_file(emstorage_mail_tbl_t *mail, char **stripped_text, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("mail[%p]");
+       EM_DEBUG_FUNC_BEGIN("mail[%p]", mail);
 
        int ret = false;
        int err = EMAIL_ERROR_NONE;
@@ -1291,19 +1646,25 @@ int emcore_strip_mail_body_from_file(emstorage_mail_tbl_t *mail, char **stripped
 
        /* read file to buf & strip if html text */
        if (mail->file_path_html) {
+               if (mail->preview_text) {
+                       *stripped_text = EM_SAFE_STRDUP(mail->preview_text);
+                       ret = true;
+                       goto FINISH_OFF;
+               }
+
                if((err = em_get_encoding_type_from_file_path(mail->file_path_html, &encoding_type)) != EMAIL_ERROR_NONE) {
-                       EM_DEBUG_EXCEPTION("em_get_encoding_type_from_file_path failed [%s]", err);
+                       EM_DEBUG_EXCEPTION("em_get_encoding_type_from_file_path failed [%d]", err);
                        goto FINISH_OFF;
                }
 
                if (stat(mail->file_path_html, &st_buf) < 0) {
-                       EM_DEBUG_EXCEPTION("stat(\"%s\") failed...", mail->file_path_html);
+                       EM_DEBUG_EXCEPTION_SEC("stat(\"%s\") failed...", mail->file_path_html);
                        err = EMAIL_ERROR_FILE_NOT_FOUND;
                        goto FINISH_OFF;
                }
 
                if (!(fp_html = fopen(mail->file_path_html, "r"))) {
-                       EM_DEBUG_EXCEPTION("fopen failed [%s]", mail->file_path_html);
+                       EM_DEBUG_EXCEPTION_SEC("fopen failed [%s]", mail->file_path_html);
                        err = EMAIL_ERROR_SYSTEM_FAILURE;
                        goto FINISH_OFF;
                }
@@ -1325,12 +1686,12 @@ int emcore_strip_mail_body_from_file(emstorage_mail_tbl_t *mail, char **stripped
                if (byte_read <= 0) {
                        EM_SAFE_FREE(buf);
                        if (ferror(fp_html)) {
-                               EM_DEBUG_EXCEPTION("fread failed [%s]", mail->file_path_html);
+                               EM_DEBUG_EXCEPTION_SEC("fread failed [%s]", mail->file_path_html);
                                err = EMAIL_ERROR_SYSTEM_FAILURE;
                                goto FINISH_OFF;
                        }
                } else {
-                       if ((err = emcore_strip_HTML(buf)) != EMAIL_ERROR_NONE) {
+                       if ((err = emcore_strip_HTML(&buf)) != EMAIL_ERROR_NONE) {
                                EM_DEBUG_EXCEPTION("emcore_strip failed");
                                goto FINISH_OFF;
                        }
@@ -1339,19 +1700,19 @@ int emcore_strip_mail_body_from_file(emstorage_mail_tbl_t *mail, char **stripped
 
        if (!buf && mail->file_path_plain) {
                if ((err = em_get_encoding_type_from_file_path(mail->file_path_plain, &encoding_type)) != EMAIL_ERROR_NONE) {
-                       EM_DEBUG_EXCEPTION("em_get_encoding_type_from_file_path failed [%s]", err);
+                       EM_DEBUG_EXCEPTION("em_get_encoding_type_from_file_path failed [%d]", err);
                        goto FINISH_OFF;
                }
 
                memset(&st_buf, 0, sizeof(struct stat));
                if (stat(mail->file_path_plain, &st_buf) < 0) {
-                       EM_DEBUG_EXCEPTION("stat(\"%s\") failed...", mail->file_path_plain);
+                       EM_DEBUG_EXCEPTION_SEC("stat(\"%s\") failed...", mail->file_path_plain);
                        err = EMAIL_ERROR_INVALID_MAIL;
                        goto FINISH_OFF;
                }
 
                if (!(fp_plain = fopen(mail->file_path_plain, "r"))) {
-                       EM_DEBUG_EXCEPTION("fopen failed [%s]", mail->file_path_plain);
+                       EM_DEBUG_EXCEPTION_SEC("fopen failed [%s]", mail->file_path_plain);
                        err = EMAIL_ERROR_SYSTEM_FAILURE;
                        goto FINISH_OFF;
                }
@@ -1373,7 +1734,7 @@ int emcore_strip_mail_body_from_file(emstorage_mail_tbl_t *mail, char **stripped
                        EM_SAFE_FREE(buf);
                        err = EMAIL_ERROR_NULL_VALUE;
                        if (ferror(fp_plain)) {
-                               EM_DEBUG_EXCEPTION("fread failed [%s]", mail->file_path_plain);
+                               EM_DEBUG_EXCEPTION_SEC("fread failed [%s]", mail->file_path_plain);
                                err = EMAIL_ERROR_SYSTEM_FAILURE;
                        }
                        goto FINISH_OFF;
@@ -1398,20 +1759,14 @@ int emcore_strip_mail_body_from_file(emstorage_mail_tbl_t *mail, char **stripped
                        utf8_encoded_string = (char*)g_convert(buf, -1, "UTF-8", encoding_type, &byte_read, &byte_written, &glib_error);
 
                        if(utf8_encoded_string == NULL) {
-                               EM_DEBUG_EXCEPTION("g_convert failed : byte_read[%d], EM_SAFE_STRLEN : [%d]", byte_read, EM_SAFE_STRLEN(buf));
-                               EM_DEBUG_LOG("Error is G_CONVERT_ERROR_ILLEGAL_SEQUENCE");
-
                                if (!g_error_matches(glib_error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE)) {
-                                       EM_DEBUG_EXCEPTION("g_convert failed");
                                        *stripped_text = EM_SAFE_STRDUP(buf);
                                        goto FINISH_OFF;
                                }
-
                                EM_DEBUG_LOG("Extract the preview text, again");
 
                                utf8_encoded_string = (char *)g_convert(buf, byte_read, "UTF-8", encoding_type, &byte_read, &byte_written, &glib_error);
                                if (utf8_encoded_string == NULL) {
-                                       EM_DEBUG_EXCEPTION("g_convert failed : byte_read[%d]", byte_read);
                                        *stripped_text = EM_SAFE_STRDUP(buf);
                                        goto FINISH_OFF;
                                }
@@ -1474,7 +1829,7 @@ int emcore_get_preview_text_from_file(const char *input_plain_path, const char *
        if ( input_html_path ) { /*prevent 26249*/
                /*      get preview text from html file */
                if( (err = em_get_encoding_type_from_file_path(input_html_path, &encoding_type)) != EMAIL_ERROR_NONE) {
-                       EM_DEBUG_EXCEPTION("em_get_encoding_type_from_file_path failed [%s]", err);
+                       EM_DEBUG_EXCEPTION("em_get_encoding_type_from_file_path failed [%d]", err);
                        goto FINISH_OFF;
                }
 
@@ -1513,7 +1868,7 @@ int emcore_get_preview_text_from_file(const char *input_plain_path, const char *
                        }
                }
                else {
-                       if ( (err = emcore_strip_HTML(local_preview_text)) != EMAIL_ERROR_NONE) {
+                       if ( (err = emcore_strip_HTML(&local_preview_text)) != EMAIL_ERROR_NONE) {
                                EM_DEBUG_EXCEPTION("emcore_strip failed");
                                goto FINISH_OFF;
                        }
@@ -1523,7 +1878,7 @@ int emcore_get_preview_text_from_file(const char *input_plain_path, const char *
        if ( !local_preview_text && input_plain_path) { /*prevent 26249*/
                /*  get preview text from plain text file */
                if( (err = em_get_encoding_type_from_file_path(input_plain_path, &encoding_type)) != EMAIL_ERROR_NONE) {
-                       EM_DEBUG_EXCEPTION("em_get_encoding_type_from_file_path failed [%s]", err);
+                       EM_DEBUG_EXCEPTION("em_get_encoding_type_from_file_path failed [%d]", err);
                        goto FINISH_OFF;
                }
 
@@ -1582,22 +1937,15 @@ int emcore_get_preview_text_from_file(const char *input_plain_path, const char *
                        utf8_encoded_string = (char*)g_convert (local_preview_text, -1, "UTF-8", encoding_type, &byte_read, &byte_written, &glib_error);
 
                        if(utf8_encoded_string == NULL) {
-                               EM_DEBUG_EXCEPTION("g_convert failed : byte_read[%d], EM_SAFE_STRLEN : [%d]", byte_read, EM_SAFE_STRLEN(local_preview_text));
-                               EM_DEBUG_LOG("Error is G_CONVERT_ERROR_ILLEGAL_SEQUENCE");
-
                                if (!g_error_matches (glib_error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE)) {
-                                       EM_DEBUG_EXCEPTION("g_convert failed");
                                        goto FINISH_OFF;
                                }
-
                                EM_DEBUG_LOG("Extract the preview text, again");
 
                                utf8_encoded_string = (char *)g_convert(local_preview_text, byte_read, "UTF-8", encoding_type, &byte_read, &byte_written, &glib_error);
                                if (utf8_encoded_string == NULL) {
-                                       EM_DEBUG_EXCEPTION("g_convert failed : byte_read[%d]", byte_read);
                                        goto FINISH_OFF;
                                }
-
                        }
                        EM_SAFE_FREE(local_preview_text);
                        local_preview_text = utf8_encoded_string;
@@ -1605,9 +1953,14 @@ int emcore_get_preview_text_from_file(const char *input_plain_path, const char *
        }
 
 FINISH_OFF:
-
+/*
        if (local_preview_text != NULL)
                *output_preview_buffer = EM_SAFE_STRDUP(local_preview_text);
+*/
+       if (local_preview_text != NULL) {
+               EM_SAFE_FREE(*output_preview_buffer); /* valgrind */
+               *output_preview_buffer = EM_SAFE_STRDUP(local_preview_text);
+       }
 
        EM_SAFE_FREE(local_preview_text);
        EM_SAFE_FREE(encoding_type);
@@ -1809,48 +2162,75 @@ FINISH_OFF:
 }
 
 
-int emcore_strip_HTML(char *source_string)
+int reg_replace_new (char **input_source_text, char *input_old_pattern_string, char *input_new_string)
+{
+       char *replaced_str = NULL;
+       int error_code = EMAIL_ERROR_NONE;
+       GRegex *regex = NULL;
+       GError *error = NULL;
+
+       regex = g_regex_new(input_old_pattern_string, G_REGEX_RAW | G_REGEX_OPTIMIZE | G_REGEX_CASELESS, 0, &error);
+
+       if (!regex) {
+               EM_DEBUG_LOG("g_regex_new failed");
+               error_code = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       replaced_str = g_regex_replace_literal(regex, *input_source_text, strlen(*input_source_text), 0, input_new_string, 0, &error);
+
+       EM_SAFE_FREE(*input_source_text);
+
+       *input_source_text = replaced_str;
+
+FINISH_OFF:
+
+       g_regex_unref(regex);
+       return error_code;
+}
+
+
+int emcore_strip_HTML(char **source_string)
 {
        EM_DEBUG_FUNC_BEGIN("source_string [%p]", source_string);
 
        int result = EMAIL_ERROR_NONE;
 
        /* strip out CR, LF */
-       reg_replace(source_string, "(\r|\n)", "");
+       reg_replace_new(source_string, "(\r|\n)", "");
 
        /* strip out HEAD */
-       reg_replace(source_string, "<head[^>]*>.*<*/head>", "");
+       reg_replace_new(source_string, "<head[^>]*>.*<*/head>", "");
 
        /* strip out STYLE */
-       reg_replace(source_string, "<style[^>]*>.*<*/style>", "");
+       reg_replace_new(source_string, "<style[^>]*>.*<*/style>", "");
 
        /* strip out SCRIPT */
-       reg_replace(source_string, "<script[^>]*>.*<*/script>", "");
+       reg_replace_new(source_string, "<script[^>]*>.*<*/script>", "");
 
        /* strip out ALL TAG & comment */
-       reg_replace(source_string, "<[^>]*>", "");
+       reg_replace_new(source_string, "<[^>]*>", "");
 
        /* for remaining comment in some cases */
-       reg_replace(source_string, "-->", "");
+       reg_replace_new(source_string, "-->", "");
 
        /* strip out html entities */
-       reg_replace(source_string, "&(quot|#34|#034);", "\"");
-       reg_replace(source_string, "&(#35|#035);", "#");
-       reg_replace(source_string, "&(#36|#036);", "$");
-       reg_replace(source_string, "&(#37|#037);", "%");
-       reg_replace(source_string, "&(amp|#38|#038);", "&");
-       reg_replace(source_string, "&(lt|#60|#060);", "<");
-       reg_replace(source_string, "&(gt|#62|#062);", ">");
-       reg_replace(source_string, "&(#64|#064);", "@");
-       reg_replace(source_string, "&(lsquo|rsquo);", "'");
-       reg_replace(source_string, "&(ldquo|rdquo);", "\"");
-       reg_replace(source_string, "&sbquo;", ",");
-       reg_replace(source_string, "&(trade|#x2122);", "(TM)");
+       reg_replace_new(source_string, "&(quot|#34|#034);", "\"");
+       reg_replace_new(source_string, "&(#35|#035);", "#");
+       reg_replace_new(source_string, "&(#36|#036);", "$");
+       reg_replace_new(source_string, "&(#37|#037);", "%");
+       reg_replace_new(source_string, "&(amp|#38|#038);", "&");
+       reg_replace_new(source_string, "&(lt|#60|#060);", "<");
+       reg_replace_new(source_string, "&(gt|#62|#062);", ">");
+       reg_replace_new(source_string, "&(#64|#064);", "@");
+       reg_replace_new(source_string, "&(lsquo|rsquo);", "'");
+       reg_replace_new(source_string, "&(ldquo|rdquo);", "\"");
+       reg_replace_new(source_string, "&sbquo;", ",");
+       reg_replace_new(source_string, "&(trade|#x2122);", "(TM)");
 
        /* strip out all type of spaces */
-       reg_replace(source_string, "&(nbsp|#160);", " ");
-       reg_replace(source_string, "[[:space:]]", " ");
-       reg_replace(source_string, "  +", " ");
+       reg_replace_new(source_string, "&(nbsp|#160);", " ");
+       reg_replace_new(source_string, "  +", " ");
 
        EM_DEBUG_FUNC_END();
        return result;
@@ -1858,7 +2238,7 @@ int emcore_strip_HTML(char *source_string)
 
 INTERNAL_FUNC int emcore_send_noti_for_new_mail(int account_id, char *mailbox_name, char *subject, char *from, char *uid, char *datetime)
 {
-       EM_DEBUG_FUNC_BEGIN("mailbox_name(%s) subject(%s), from(%s), uid(%s), datetime(%s)", mailbox_name, subject, from, uid, datetime);
+       EM_DEBUG_FUNC_BEGIN_SEC("mailbox_name(%s) subject(%s), from(%s), uid(%s), datetime(%s)", mailbox_name, subject, from, uid, datetime);
        int error_code = EMAIL_ERROR_NONE;
        int param_length = 0;
        char *param_string = NULL;
@@ -1920,7 +2300,8 @@ int convert_app_err_to_email_err(int app_error)
        return err;
 }
 
-int emcore_start_driving_mode(int account_id) {
+INTERNAL_FUNC int emcore_start_driving_mode(int account_id)
+{
        EM_DEBUG_FUNC_BEGIN();
        
        int err = SERVICE_ERROR_NONE;
@@ -1985,74 +2366,6 @@ FINISH_OFF:
 }
 #endif /* __FEATURE_DRIVING_MODE__ */
 
-int emcore_update_notification_for_unread_mail(int account_id)
-{
-       EM_DEBUG_FUNC_BEGIN("acccount_id[%d]", account_id);
-       int ret = false;
-       int i, account_count = 0;
-       int err = EMAIL_ERROR_NONE;
-       emstorage_account_tbl_t *p_account_tbl = NULL;
-
-       if (!emstorage_get_account_list(&account_count, &p_account_tbl, true, false, &err)) {
-               EM_DEBUG_EXCEPTION("emstorage_get_account_list failed [%d]", err);
-               goto FINISH_OFF;
-       }
-
-       for (i = 0; i < account_count ; i++) {
-               if ((err = emcore_add_notification(p_account_tbl[i].account_id, 0, EMAIL_ACTION_NUM)) != EMAIL_ERROR_NONE) {
-                       EM_DEBUG_EXCEPTION("emcore_add_notification failed : [%d]", err);
-                       continue;
-               }
-       
-               if ((err = emcore_start_driving_mode(p_account_tbl[i].account_id)) != EMAIL_ERROR_NONE) {
-                       EM_DEBUG_EXCEPTION("emcore_start_driving_mode failed : [%d]", err);
-                       continue;
-               }
-       }
-
-       ret = true;
-
-FINISH_OFF:
-
-       if (p_account_tbl)
-               emstorage_free_account(&p_account_tbl, account_count, NULL);
-
-       EM_DEBUG_FUNC_END();
-       return ret;
-}
-
-INTERNAL_FUNC int emcore_finalize_sync(int account_id, int *error)
-{
-       EM_DEBUG_FUNC_BEGIN("account_id [%d], error [%p]", account_id, error);
-       int err = EMAIL_ERROR_NONE, ret = true, result_sync_status = SYNC_STATUS_FINISHED;
-
-       if ((err = emcore_update_sync_status_of_account(account_id, SET_TYPE_MINUS, SYNC_STATUS_SYNCING)) != EMAIL_ERROR_NONE)
-               EM_DEBUG_EXCEPTION("emcore_update_sync_status_of_account failed [%d]", err);
-
-       if (!emstorage_get_sync_status_of_account(ALL_ACCOUNT, &result_sync_status, &err))
-               EM_DEBUG_EXCEPTION("emstorage_get_sync_status_of_account failed [%d]", err);
-
-       if (result_sync_status == SYNC_STATUS_HAVE_NEW_MAILS) {
-               if (!emcore_update_notification_for_unread_mail(ALL_ACCOUNT))
-                       EM_DEBUG_EXCEPTION("emcore_update_notification_for_unread_mail failed");
-
-               if (!emcore_display_unread_in_badge())
-                       EM_DEBUG_EXCEPTION("emcore_display_unread_in_badge failed");
-
-               emcore_start_alert();
-
-#ifdef __FEATURE_BLOCKING_MODE__
-               emcore_set_blocking_mode_status(false);
-#endif /* __FEATURE_BLOCKING_MODE__ */
-
-               if ((err = emcore_update_sync_status_of_account(account_id, SET_TYPE_MINUS, SYNC_STATUS_HAVE_NEW_MAILS)) != EMAIL_ERROR_NONE)
-                       EM_DEBUG_EXCEPTION("emcore_update_sync_status_of_account failed [%d]", err);
-       }
-
-       EM_DEBUG_FUNC_END();
-       return ret;
-}
-
 INTERNAL_FUNC int emcore_clear_all_notifications()
 {
        int account_count = 0, i;
@@ -2065,7 +2378,7 @@ INTERNAL_FUNC int emcore_clear_all_notifications()
        }
 
        for(i = 0; i < account_count; i++) {
-               emcore_delete_notification_by_account(account_list[i].account_id);
+               emcore_delete_notification_by_account(account_list[i].account_id, true);
        }
 
 FINISH_OFF:
@@ -2079,7 +2392,7 @@ FINISH_OFF:
 
 #define EAS_EXECUTABLE_PATH "/usr/bin/eas-engine"
 
-INTERNAL_FUNC int emcore_delete_notification_by_account(int account_id)
+INTERNAL_FUNC int emcore_delete_notification_by_account(int account_id, int with_noti_tray)
 {
        EM_DEBUG_FUNC_BEGIN("account_id [%d]", account_id);
        int error_code = EMAIL_ERROR_NONE;
@@ -2503,7 +2816,7 @@ INTERNAL_FUNC void emcore_free_comma_separated_strings(char *** string_list, int
 
 int emcore_make_attachment_file_name_with_extension(char *source_file_name, char *sub_type, char *result_file_name, int result_file_name_buffer_length, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("source_file_name[%s], sub_type[%s], result_file_name_buffer_length[%d] ", source_file_name, sub_type, result_file_name_buffer_length);
+       EM_DEBUG_FUNC_BEGIN_SEC("source_file_name[%s], sub_type[%s], result_file_name_buffer_length[%d] ", source_file_name, sub_type, result_file_name_buffer_length);
        int ret = false, err = EMAIL_ERROR_NONE;
        char *extcheck = NULL;
        char attachment_file_name[MAX_PATH + 1] = { 0, };
@@ -2523,7 +2836,7 @@ int emcore_make_attachment_file_name_with_extension(char *source_file_name, char
                if (sub_type) {
                        strcat(attachment_file_name, ".");
                        strcat(attachment_file_name, sub_type);
-                       EM_DEBUG_LOG("attachment_file_name with extension[%s] ", attachment_file_name);
+                       EM_DEBUG_LOG_SEC("attachment_file_name with extension[%s] ", attachment_file_name);
                }
                else
                        EM_DEBUG_LOG("UnKnown Extesnsion");
@@ -2531,7 +2844,7 @@ int emcore_make_attachment_file_name_with_extension(char *source_file_name, char
        }
        memset(result_file_name, 0 , result_file_name_buffer_length);
        EM_SAFE_STRNCPY(result_file_name, attachment_file_name, result_file_name_buffer_length - 1);
-       EM_DEBUG_LOG("*result_file_name[%s]", result_file_name);
+       EM_DEBUG_LOG_SEC("*result_file_name[%s]", result_file_name);
        ret = true;
 
 FINISH_OFF:
@@ -2641,20 +2954,30 @@ INTERNAL_FUNC void emcore_free_rule(email_rule_t* rule)
        if (!rule)
                return;
 
+       EM_SAFE_FREE(rule->filter_name);
        EM_SAFE_FREE(rule->value);
+       EM_SAFE_FREE(rule->value2);
 
        EM_DEBUG_FUNC_END();
 }
 
-INTERNAL_FUNC int emcore_search_string_from_file(char *file_path, char *search_string, int *result)
+INTERNAL_FUNC void emcore_free_body_sparep(void **p)
 {
-       EM_DEBUG_FUNC_BEGIN("file_path : [%s], search_string : [%s]", file_path, search_string);
+       EM_DEBUG_FUNC_BEGIN();
+       EM_SAFE_FREE(*p);
+       EM_DEBUG_FUNC_END();
+}
+
+INTERNAL_FUNC int emcore_search_string_from_file(char *file_path, char *search_string, char *new_string, int *result)
+{
+       EM_DEBUG_FUNC_BEGIN_SEC("file_path : [%s], search_string : [%s]", file_path, search_string);
        int error = EMAIL_ERROR_NONE;
        int file_size = 0;
        int p_result = false;
        FILE *fp = NULL;
        char *buf = NULL;
        char *stripped = NULL;
+       char *modified_string = NULL;
 
        if (!search_string || !file_path || !result) {
                EM_DEBUG_EXCEPTION("Invalid parameter");
@@ -2674,7 +2997,7 @@ INTERNAL_FUNC int emcore_search_string_from_file(char *file_path, char *search_s
                goto FINISH_OFF;
        }
 
-       buf = em_malloc(file_size);
+       buf = em_malloc(file_size + 1);
        if (buf == NULL) {
                EM_DEBUG_EXCEPTION("em_malloc failed");
                error = EMAIL_ERROR_OUT_OF_MEMORY;
@@ -2689,8 +3012,30 @@ INTERNAL_FUNC int emcore_search_string_from_file(char *file_path, char *search_s
 
        /*prevent 35586*/
        stripped = em_replace_all_string(buf, CRLF_STRING, "");
-       if (strstr(stripped, search_string))
-               p_result = true;
+       if (stripped) {
+               if (new_string) {
+                       modified_string = em_replace_string(stripped, search_string, new_string);
+                       if (modified_string) {
+                               if (fp)
+                                       fclose(fp);
+       
+                               fp = fopen(file_path, "w");                     
+                               if (fp == NULL) {
+                                       EM_DEBUG_EXCEPTION("fopen failed");
+                                       error = EMAIL_ERROR_SYSTEM_FAILURE;
+                                       goto FINISH_OFF;
+                               }
+
+                               fprintf(fp, "%s", modified_string);                     
+
+                               p_result = true;        
+                       }
+
+               } else {
+                       if (strstr(stripped, search_string))
+                               p_result = true;
+               }
+       }
 
 FINISH_OFF:
        if(!p_result)
@@ -2703,6 +3048,7 @@ FINISH_OFF:
 
        EM_SAFE_FREE(buf);
        EM_SAFE_FREE(stripped);  /*prevent 35586*/
+       EM_SAFE_FREE(modified_string);
 
        EM_DEBUG_FUNC_END("error:[%d]", error);
        return error;
@@ -2710,7 +3056,7 @@ FINISH_OFF:
 
 INTERNAL_FUNC int emcore_load_query_from_file(char *file_path, char ***query_array, int *array_len)
 {
-       EM_DEBUG_FUNC_BEGIN("file_path : [%s], query_array : [%p]", file_path, *query_array);
+       EM_DEBUG_FUNC_BEGIN_SEC("file_path : [%s], query_array : [%p]", file_path, *query_array);
        int error = EMAIL_ERROR_NONE;
        int file_size = 0;
        int vector_len = 0;
@@ -2793,6 +3139,204 @@ FINISH_OFF:
        return error;
 }
 
+/* peak schedule */
+static int emcore_get_next_peak_start_time(emstorage_account_tbl_t *input_account_ref, time_t input_current_time, time_t *output_time)
+{
+       EM_DEBUG_FUNC_BEGIN("input_account_ref [%p] input_time[%d] output_time[%p]", input_account_ref, input_current_time, output_time);
+       int err = EMAIL_ERROR_NONE;
+       int wday = 1;
+       int day_count = 0;
+       int start_hour = 0;
+       int start_min  = 0;
+       struct tm *time_info;
+
+       if(output_time == NULL) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       time_info = localtime (&input_current_time);
+
+       EM_DEBUG_LOG("input time and date: %s", asctime(time_info));
+
+       wday = wday << time_info->tm_wday;
+
+       EM_DEBUG_LOG("wday[%d] peak_days[%d]", wday, input_account_ref->peak_days);
+
+       /* find next peak day */
+
+       if (wday & input_account_ref->peak_days) {
+               start_hour = input_account_ref->peak_start_time / 100;
+               start_min  = input_account_ref->peak_start_time % 100;
+               if (start_hour < time_info->tm_hour || (start_hour == time_info->tm_hour && start_min < time_info->tm_min)) {
+                       if(wday == EMAIL_PEAK_DAYS_SATDAY)
+                               wday = EMAIL_PEAK_DAYS_SUNDAY;
+                       else
+                               wday = wday << 1;
+                       day_count++;
+               }
+
+       }
+
+       while (!(wday & input_account_ref->peak_days) && day_count < 7){
+               EM_DEBUG_LOG("wday[%d] day_count[%d]", wday, day_count);
+               if(wday == EMAIL_PEAK_DAYS_SATDAY)
+                       wday = EMAIL_PEAK_DAYS_SUNDAY;
+               else
+                       wday = wday << 1;
+               day_count++;
+       }
+
+       EM_DEBUG_LOG("day_count[%d]", day_count);
+
+       if (day_count < 7) {
+               time_info->tm_mday += day_count; /* The other members of time_info will be interpreted or set by mktime */
+
+               time_info->tm_hour = input_account_ref->peak_start_time / 100;
+               time_info->tm_min  = input_account_ref->peak_start_time % 100;
+               time_info->tm_min  = 0;
+
+               *output_time = mktime(time_info);
+               EM_DEBUG_LOG("result_time: %s", asctime(time_info));
+       }
+
+FINISH_OFF:
+
+       EM_DEBUG_FUNC_END("err[%d]", err);
+       return err;
+}
+
+static int emcore_check_time_in_peak_schedule(emstorage_account_tbl_t *input_account_ref, time_t input_time, int *output_result)
+{
+       EM_DEBUG_FUNC_BEGIN("input_account_ref [%p] input_time[%d] output_result[%p]", input_account_ref, input_time, output_result);
+       int err = EMAIL_ERROR_NONE;
+       struct tm *time_info;
+       int wday = 1;
+       int result = 0;
+       int start_hour = 0;
+       int start_min  = 0;
+       int end_hour = 0;
+       int end_min  = 0;
+
+       if(input_account_ref == NULL || output_result == NULL) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       time_info = localtime (&input_time);
+
+       EM_DEBUG_LOG("input time and date: %s", asctime(time_info));
+
+       wday = wday << time_info->tm_wday;
+
+       EM_DEBUG_LOG("wday [%d]", wday);
+
+       if(wday & input_account_ref->peak_days) {
+               start_hour = input_account_ref->peak_start_time / 100;
+               start_min  = input_account_ref->peak_start_time % 100;
+
+               end_hour   = input_account_ref->peak_end_time / 100;
+               end_min    = input_account_ref->peak_end_time % 100;
+
+               EM_DEBUG_LOG("start_hour[%d] start_min[%d] end_hour[%d] end_min[%d]", start_hour, start_min, end_hour, end_min);
+
+               if(start_hour <= time_info->tm_hour && time_info->tm_hour <= end_hour) {
+                       if(time_info->tm_hour == end_hour) {
+                               if(time_info->tm_min < end_min)
+                                       result = 1;
+                       }
+                       else
+                               result = 1;
+               }
+       }
+
+       EM_DEBUG_LOG("result[%d]", result);
+       *output_result = result;
+
+FINISH_OFF:
+
+       EM_DEBUG_FUNC_END("err[%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC int emcore_calc_next_time_to_sync(int input_account_id, time_t input_current_time, time_t *output_time)
+{
+       EM_DEBUG_FUNC_BEGIN("input_account_id[%d] input_current_time[%d] output_time[%p]", input_account_id, input_current_time, output_time);
+       int err = EMAIL_ERROR_NONE;
+       emstorage_account_tbl_t *account = NULL;
+       time_t next_time = 0;
+       time_t next_peak_start_time = 0;
+       time_t result_time = 0;
+       int    is_time_in_peak_schedule = 0;
+
+       emstorage_get_account_by_id(input_account_id, EMAIL_ACC_GET_OPT_DEFAULT, &account, true, &err);
+       if (account == NULL) {
+               EM_DEBUG_EXCEPTION("emstorage_get_account_by_id failed [%d]",err);
+               goto FINISH_OFF;
+       }
+
+       if (account->peak_interval <= 0) {
+               /* peak schedule disabled */
+               if (account->check_interval > 0)
+                       result_time = input_current_time + (account->check_interval * 60);
+       }
+       else if(account->peak_days) {
+               /* peak schedule enabled */
+
+               /* if current time is in peak schedule */
+               emcore_check_time_in_peak_schedule(account, input_current_time, &is_time_in_peak_schedule);
+               EM_DEBUG_LOG("is_time_in_peak_schedule [%d]", is_time_in_peak_schedule);
+               if(is_time_in_peak_schedule) {
+                       /* if next time to sync is in peak schedule? */
+                       next_time = input_current_time + (account->peak_interval * 60);
+
+                       emcore_check_time_in_peak_schedule(account, next_time, &is_time_in_peak_schedule);
+                       if(is_time_in_peak_schedule) {
+                               /* create an alarm to sync in peak schedule*/
+                               result_time = next_time;
+                       }
+               }
+
+               if(result_time == 0) {
+                       /* if current time is not in peak schedule */
+                       if(next_time == 0)  {
+                               /* if normal sync schedule is set */
+                               if(account->check_interval) {
+                                       next_time = input_current_time + (account->check_interval * 60);
+                               }
+                       }
+                       emcore_get_next_peak_start_time(account, input_current_time, &next_peak_start_time);
+
+                       EM_DEBUG_LOG("next_time            : %s", ctime(&next_time));
+                       EM_DEBUG_LOG("next_peak_start_time : %s", ctime(&next_peak_start_time));
+
+                       /* if next time to sync is closer than next peak schedule start? */
+                       if(next_time && (next_time < next_peak_start_time)) {
+                               /* create an alarm to sync in check_interval */
+                               result_time = next_time;
+                       }
+                       /* else check_interval is zero or next peak schedule start is close than next check_interval */
+                       else {
+                               result_time = next_peak_start_time;
+                       }
+               }
+       }
+
+       *output_time = result_time;
+       EM_DEBUG_LOG("result_time : %s", ctime(&result_time));
+
+
+FINISH_OFF:
+       if(account) {
+               emstorage_free_account(&account, 1, NULL);
+       }
+
+       EM_DEBUG_FUNC_END("err[%d]", err);
+       return err;
+}
+
 static int convert_contact_err_to_email_err(int contact_err)
 {
        int err = EMAIL_ERROR_NONE;
@@ -2829,7 +3373,7 @@ static int convert_contact_err_to_email_err(int contact_err)
 
 int emcore_get_mail_contact_info(email_mail_contact_info_t *contact_info, char *full_address, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("contact_info[%p], full_address[%s], err_code[%p]", contact_info, full_address, err_code);
+       EM_DEBUG_FUNC_BEGIN_SEC("contact_info[%p], full_address[%s], err_code[%p]", contact_info, full_address, err_code);
        
        int ret = false;
        int err = EMAIL_ERROR_NONE;
@@ -2864,7 +3408,7 @@ int emcore_search_contact_info(const char *contact_uri, int address_property_id,
                goto FINISH_OFF;
        }
 
-       if ((contact_err = contacts_filter_add_str(filter, address_property_id, CONTACTS_MATCH_EXACTLY, address)) != CONTACTS_ERROR_NONE) {
+       if ((contact_err = contacts_filter_add_str(filter, address_property_id, CONTACTS_MATCH_FULLSTRING, address)) != CONTACTS_ERROR_NONE) {
                EM_DEBUG_EXCEPTION("contacts_filter_add_str failed");
                goto FINISH_OFF;
        }
@@ -2927,7 +3471,7 @@ int emcore_search_contact_info_by_address(const char *contact_uri, int property_
                goto FINISH_OFF;
        }
 
-       if ((contact_err = contacts_filter_add_str(filter, property_id, CONTACTS_MATCH_EXACTLY, address)) != CONTACTS_ERROR_NONE) {
+       if ((contact_err = contacts_filter_add_str(filter, property_id, CONTACTS_MATCH_FULLSTRING, address)) != CONTACTS_ERROR_NONE) {
                EM_DEBUG_EXCEPTION("contacts_filter_add_str failed");
                goto FINISH_OFF;
        }
@@ -2943,7 +3487,8 @@ int emcore_search_contact_info_by_address(const char *contact_uri, int property_
        }
 
        if ((contact_err = contacts_list_get_current_record_p(list, contacts_record)) != CONTACTS_ERROR_NONE) {
-               EM_DEBUG_EXCEPTION("contacts_list_get_current_record_p failed");
+               if (contact_err != CONTACTS_ERROR_NO_DATA) /* no matching record found */               
+                       EM_DEBUG_EXCEPTION ("contacts_list_get_current_record_p failed [%d]", contact_err);
                goto FINISH_OFF;
        }
 
@@ -2963,7 +3508,7 @@ FINISH_OFF:
 
 int emcore_set_contacts_log(int account_id, char *email_address, char *subject, time_t date_time, email_action_t action)
 {
-       EM_DEBUG_FUNC_BEGIN("account_id : [%d], address : [%p], subject : [%s], action : [%d], date_time : [%d]", account_id, email_address, subject, action, (int)date_time);
+       EM_DEBUG_FUNC_BEGIN_SEC("account_id : [%d], address : [%p], subject : [%s], action : [%d], date_time : [%d]", account_id, email_address, subject, action, (int)date_time);
        
        int err = EMAIL_ERROR_NONE;
        int contacts_error = CONTACTS_ERROR_NONE;
@@ -2991,8 +3536,8 @@ int emcore_set_contacts_log(int account_id, char *email_address, char *subject,
 
        /* Search contact person info */
        if ((contacts_error = emcore_search_contact_info_by_address(_contacts_person_email._uri, _contacts_person_email.email, email_address, 1, &person_record)) != CONTACTS_ERROR_NONE) {
-               EM_DEBUG_EXCEPTION("emcore_search_contact_info_by_address failed [%d]", contacts_error);
-               EM_DEBUG_LOG("Not match person");
+               if (contacts_error != CONTACTS_ERROR_NO_DATA) /* no matching record found */
+                       EM_DEBUG_EXCEPTION("emcore_search_contact_info_by_address failed [%d]", contacts_error);
        } else {
                /* Get person_id in contacts_person_email record  */
                if (person_record  && (contacts_error = contacts_record_get_int(person_record, _contacts_person_email.person_id, &person_id)) != CONTACTS_ERROR_NONE) {
@@ -3151,7 +3696,7 @@ FINISH_OFF:
 
 INTERNAL_FUNC int emcore_get_mail_display_name(char *email_address, char **contact_display_name, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("contact_name_value[%s], contact_display_name[%p]", email_address, contact_display_name);
+       EM_DEBUG_FUNC_BEGIN_SEC("contact_name_value[%s], contact_display_name[%p]", email_address, contact_display_name);
 
        int contact_err = 0;
        int ret = false;
@@ -3165,7 +3710,8 @@ INTERNAL_FUNC int emcore_get_mail_display_name(char *email_address, char **conta
        }
 
        if ((contact_err = emcore_search_contact_info_by_address(_contacts_contact_email._uri, _contacts_contact_email.email, email_address, 1, &record)) != CONTACTS_ERROR_NONE) {
-               EM_DEBUG_EXCEPTION("emcore_search_contact_info_by_address failed");
+               if (contact_err != CONTACTS_ERROR_NO_DATA) /* no matching record found */
+                       EM_DEBUG_EXCEPTION("emcore_search_contact_info_by_address failed [%d]", contact_err);
                goto FINISH_OFF;
        }
 /*
@@ -3221,20 +3767,7 @@ FINISH_OFF:
 #define ALLOWED_CONTACT_TYPE_CUSTOM    3
 
 static int blocking_mode_status = false;
-static int blocking_mode_of_setting = false;
-
-INTERNAL_FUNC bool emcore_init_blocking_mode_status()
-{
-       EM_DEBUG_FUNC_BEGIN("blocking_mode_of_setting : [%d]", blocking_mode_of_setting);
-
-       if (vconf_get_bool(VCONFKEY_SETAPPL_BLOCKINGMODE_NOTIFICATIONS, &blocking_mode_of_setting) != 0) {
-               EM_DEBUG_EXCEPTION("vconf_get_bool failed");
-               return false;
-       }
-
-       EM_DEBUG_FUNC_END();
-       return true;
-}
+INTERNAL_FUNC int blocking_mode_of_setting = false;
 
 INTERNAL_FUNC void emcore_set_blocking_mode_of_setting(int input_blocking_mode_of_setting)
 {
@@ -3291,7 +3824,8 @@ INTERNAL_FUNC int emcore_check_blocking_mode(char *sender_address, int *blocking
                EM_DEBUG_LOG("allowed_contact_type is ALL");
                /* Search the allowed contact type in contact DB */
                if ((contact_error = emcore_search_contact_info_by_address(_contacts_person_email._uri, _contacts_person_email.email, sender_address, 1, &record)) != CONTACTS_ERROR_NONE) {
-                       EM_DEBUG_EXCEPTION("emcore_search_contact_info_by_address failed : [%d]", contact_error);
+                       if (contact_error != CONTACTS_ERROR_NO_DATA) /* no matching record found */
+                               EM_DEBUG_EXCEPTION("emcore_search_contact_info_by_address failed [%d]", contact_error);
                        goto FINISH_OFF;
                }
 
@@ -3325,7 +3859,8 @@ INTERNAL_FUNC int emcore_check_blocking_mode(char *sender_address, int *blocking
                }       
 
                if ((contact_error = emcore_search_contact_info_by_address(_contacts_person_email._uri, _contacts_person_email.email, sender_address, 1, &record)) != CONTACTS_ERROR_NONE) {
-                       EM_DEBUG_EXCEPTION("emcore_search_contact_info_by_address failed : [%d]", contact_error);
+                       if (contact_error != CONTACTS_ERROR_NO_DATA) /* no matching record found */
+                               EM_DEBUG_EXCEPTION("emcore_search_contact_info_by_address failed [%d]", contact_error);
                        goto FINISH_OFF;
                }
 
@@ -3366,4 +3901,62 @@ FINISH_OFF :
 }
 
 #endif     /* __FEATURE_BLOCKING_MODE__ */
+
+INTERNAL_FUNC char *emcore_set_mime_entity(char *mime_path)
+{
+       EM_DEBUG_FUNC_BEGIN("mime_path : [%s]", mime_path);
+       FILE *fp_read = NULL;
+       FILE *fp_write = NULL;
+       char *mime_entity = NULL;
+       char *mime_entity_path = NULL;
+       char temp_buffer[255] = {0,};
+       int err;
+       int searched = 0;
+
+       if (!emcore_get_temp_file_name(&mime_entity_path, &err))  {
+               EM_DEBUG_EXCEPTION(" em_core_get_temp_file_name failed[%d]", err);
+               goto FINISH_OFF;
+       }
+
+       /* get mime entity */
+       if (mime_path != NULL) {
+               fp_read = fopen(mime_path, "r");
+               if (fp_read == NULL) {
+                       EM_DEBUG_EXCEPTION_SEC("File open(read) is failed : filename [%s]", mime_path);
+                       goto FINISH_OFF;
+               }
+
+               fp_write = fopen(mime_entity_path, "w");
+               if (fp_write == NULL) {
+                       EM_DEBUG_EXCEPTION_SEC("File open(write) is failed : filename [%s]", mime_entity_path);
+                       goto FINISH_OFF;
+               }
+
+               fseek(fp_read, 0, SEEK_SET);
+               fseek(fp_write, 0, SEEK_SET);           
+
+               while (fgets(temp_buffer, 255, fp_read) != NULL) {
+                       mime_entity = strcasestr(temp_buffer, "content-type");
+                       if (mime_entity != NULL && !searched)
+                               searched = 1;
+
+                       if (searched) {
+                               fprintf(fp_write, "%s", temp_buffer);
+                       }
+               }
+       }       
+
+FINISH_OFF:
+       if (fp_read)
+               fclose(fp_read);
+
+       if (fp_write)
+               fclose(fp_write);
+
+       EM_SAFE_FREE(mime_entity);
+
+       EM_DEBUG_FUNC_END();
+       return mime_entity_path;
+}
+
 /* EOF */
index 9af7104..ec1d671 100755 (executable)
@@ -25,7 +25,7 @@
 #include <stdlib.h>
 #include <time.h>
 #include <sys/types.h>
-
+#include "pmapi.h"
 #include "email-device.h"
 #include "email-debug-log.h"
 
 INTERNAL_FUNC int emdevice_set_sleep_on_off(int on, int *error_code)
 {
        EM_DEBUG_FUNC_BEGIN("on[%d], err_code[%p]", on, error_code);
+       int result_from_pm_api = 0;
+
+       if(on == 1) {
+               result_from_pm_api = pm_unlock_state(LCD_OFF, PM_SLEEP_MARGIN);
+               EM_DEBUG_LOG("pm_unlock_state() returns [%d]", result_from_pm_api);
+       }
+       else {
+               result_from_pm_api = pm_lock_state(LCD_OFF, STAY_CUR_STATE, 0);
+               EM_DEBUG_LOG("pm_lock_state() returns [%d]", result_from_pm_api);
+       }
+
        EM_DEBUG_FUNC_END();
        return true;
 }
index b4d056a..7bdd818 100755 (executable)
@@ -39,6 +39,10 @@ extern "C"
 
 #include "email-internal-types.h"
 
+#define DISPLAY_STATE_OFF 0
+#define DISPLAY_STATE_DIM 1
+#define DISPLAY_STATE_ON  2
+
 INTERNAL_FUNC int emdevice_set_sleep_on_off(int on, int *error_code);
 INTERNAL_FUNC int emdevice_set_dimming_on_off(int on, int *error_code);
 
index 5bb3783..c75100b 100755 (executable)
@@ -102,7 +102,7 @@ static int  _get_sim_status(int *sim_status)
        return EMAIL_ERROR_NONE;
 }
 
-static int _get_wifi_status(int *wifi_status)
+INTERNAL_FUNC int emnetwork_get_wifi_status(int *wifi_status)
 {
        EM_DEBUG_FUNC_BEGIN();
 
@@ -113,7 +113,7 @@ static int _get_wifi_status(int *wifi_status)
                return EMAIL_ERROR_INVALID_PARAM;
        }
 
-       if (vconf_get_int(VCONFKEY_WIFI_STATE, &value)  != 0) {
+       if (vconf_get_int(VCONFKEY_WIFI_STATE, &value) != 0) {
                EM_DEBUG_EXCEPTION("vconf_get_int failed");
                return EMAIL_ERROR_SYSTEM_FAILURE;
        }
@@ -142,8 +142,8 @@ INTERNAL_FUNC int emnetwork_check_network_status(int *err_code)
        if(network_status == 0) {
                EM_DEBUG_LOG("VCONFKEY_NETWORK_STATUS is 0");
 
-               if ( (err = _get_wifi_status(&wifi_status)) != EMAIL_ERROR_NONE) {
-                       EM_DEBUG_EXCEPTION("_get_wifi_status failed [%d]", err);
+               if ( (err = emnetwork_get_wifi_status(&wifi_status)) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("emnetwork_get_wifi_status failed [%d]", err);
                        goto FINISH_OFF;
                }
 
@@ -182,6 +182,33 @@ FINISH_OFF:
        return ret;
 }
 
+INTERNAL_FUNC int emnetwork_get_roaming_status(int *output_roaming_status)
+{
+       EM_DEBUG_FUNC_BEGIN("output_roaming_status [%p]", output_roaming_status);
+
+       int value;
+
+       if(!output_roaming_status) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       if (vconf_get_int(VCONFKEY_TELEPHONY_SVC_ROAM, &value)  != 0) {
+               EM_DEBUG_EXCEPTION("vconf_get_int failed");
+               return EMAIL_ERROR_SYSTEM_FAILURE;
+       }
+
+       /* VCONFKEY_TELEPHONY_SVC_ROAM or VCONFKEY_TELEPHONY_SVC_ROAM_OFF */
+       if(value == VCONFKEY_TELEPHONY_SVC_ROAM_ON)
+               *output_roaming_status = 1;
+       else
+               *output_roaming_status = 0;
+       *output_roaming_status = value;
+
+       EM_DEBUG_FUNC_END("output_roaming_status[%d]", *output_roaming_status);
+       return EMAIL_ERROR_NONE;
+}
+
 INTERNAL_FUNC long emnetwork_callback_ssl_cert_query(char *reason, char *host, char *cert)
 {
        EM_DEBUG_FUNC_BEGIN("reason[%s], host[%s], cert[%s]", reason, host, cert);
@@ -197,11 +224,6 @@ INTERNAL_FUNC long emnetwork_callback_ssl_cert_query(char *reason, char *host, c
 }
 
 /* ------ socket read/write handle ---------------------------------------- */
-int _g_canceled = 0;
-/*  TCPSTREAM = SENDSTREAM->netstream->stream; socket-id = TCPSTREAM->tcpsi, tcpso; */
-/*  sockid_in  = ((TCPSTREAM*)send_stream->netstream->stream)->tcpsi; */
-/*  sockid_out = ((TCPSTREAM*)send_stream->netstream->stream)->tcpso; */
-
 INTERNAL_FUNC long tcp_getbuffer_lnx(TCPSTREAM *stream, unsigned long size, char *s)
 {
        struct timeval tmout;
@@ -211,7 +233,7 @@ INTERNAL_FUNC long tcp_getbuffer_lnx(TCPSTREAM *stream, unsigned long size, char
        int max_timeout = 0;
        sockid = stream->tcpsi;
        maxfd = sockid + 1;
-/* EM_DEBUG_LOG("start sockid %d", sockid);    */
+       /* EM_DEBUG_LOG("start sockid %d", sockid); */
        if (sockid < 0) return 0;
 
        if (stream->ictr > 0) {
@@ -231,7 +253,6 @@ INTERNAL_FUNC long tcp_getbuffer_lnx(TCPSTREAM *stream, unsigned long size, char
 
                if (nleave <= 0) {
                        *p = '\0';
-                       /* EM_DEBUG_LOG("end"); */
                        return 1;
                }
        }
@@ -240,19 +261,6 @@ INTERNAL_FUNC long tcp_getbuffer_lnx(TCPSTREAM *stream, unsigned long size, char
        }
 
        while (nleave > 0) {
-#ifdef TEST_CANCEL_JOB
-               if (!emcore_check_thread_status()) {
-                       EM_DEBUG_EXCEPTION("thread canceled");
-                       tcp_abort(stream);
-                       goto JOB_CANCEL;
-               }
-#endif
-               /* if (_g_canceled){ */
-               /*      EM_DEBUG_LOG1("thread canceled\n"); */
-               /*      tcp_abort(stream); */
-               /*      return 0; */
-               /* } */
-
                tmout.tv_usec = 0;
                tmout.tv_sec = 1;
                FD_ZERO(&readfds);
@@ -278,7 +286,6 @@ INTERNAL_FUNC long tcp_getbuffer_lnx(TCPSTREAM *stream, unsigned long size, char
                nread = read(sockid, p, nleave);
                if (nread < 0) {
                        EM_DEBUG_EXCEPTION("socket read error");
-/*                     if (errno == EINTR) continue; */
                        tcp_abort(stream);
                        return 0;
                }
@@ -294,114 +301,7 @@ INTERNAL_FUNC long tcp_getbuffer_lnx(TCPSTREAM *stream, unsigned long size, char
        }
 
        *p = '\0';
-
-       if (_g_canceled) {
-               EM_DEBUG_EXCEPTION("thread canceled");
-               tcp_abort(stream);
-               return 0;
-       }
-
        return 1;
-/*     EM_DEBUG_LOG("end"); */
-#ifdef TEST_CANCEL_JOB
-JOB_CANCEL:
-       return 0;
-#endif
-}
-
-long tcp_getdata_lnx(TCPSTREAM *stream)
-{
-       struct timeval tmout;
-       fd_set readfds;
-       int nread, sret, sockid, maxfd;
-       int max_timeout = 0;
-       
-       sockid = stream->tcpsi;
-       maxfd = sockid + 1;
-       
-       /* EM_DEBUG_LOG("start sockid %d", sockid);     */
-       if (sockid < 0) return false;
-       
-       while (stream->ictr < 1)  {
-#ifdef TEST_CANCEL_JOB
-               if (!emcore_check_thread_status())  {
-                       EM_DEBUG_EXCEPTION("thread canceled...");
-                       tcp_abort(stream);
-                       goto JOB_CANCEL;
-               }
-#endif
-               
-               /* if (_g_canceled){ */
-               /*      EM_DEBUG_LOG1("thread canceled\n"); */
-               /*      tcp_abort(stream); */
-               /*      return 0; */
-               /* } */
-               
-               tmout.tv_usec = 0;/* 1000*10; */
-               tmout.tv_sec = 1;
-               
-               FD_ZERO(&readfds);
-               FD_SET(sockid, &readfds);
-               
-               sret = select(maxfd, &readfds, NULL, NULL, &tmout);
-               
-               if (sret < 0) {
-                       EM_DEBUG_LOG("select error[%d]", errno);
-                       
-                       tcp_abort(stream);
-                       return false;
-               }
-               else if (!sret) {
-                       if (max_timeout >= 50) {
-                               EM_DEBUG_EXCEPTION("max select timeout %d", max_timeout);
-                               
-                               emcore_set_network_error(EMAIL_ERROR_NO_RESPONSE);
-                               return false;
-                       }
-                       
-                       EM_DEBUG_EXCEPTION("%d select timeout", max_timeout);
-                       
-                       ++max_timeout;
-                       continue;
-               }
-               
-               if ((nread = read(sockid, stream->ibuf, BUFLEN)) < 0) {
-                       EM_DEBUG_EXCEPTION("socket read failed...");
-                       
-                       emcore_set_network_error(EMAIL_ERROR_SOCKET_FAILURE);
-                       
-                       /* if (errno == EINTR) contine; */
-                       tcp_abort(stream);
-                       return false;
-               }
-               
-               if (!nread) {
-                       EM_DEBUG_EXCEPTION("socket read no data...");
-                       
-                       emcore_set_network_error(EMAIL_ERROR_INVALID_RESPONSE);
-                       
-                       tcp_abort(stream);
-                       return false;
-               }
-               
-               stream->ictr = nread;
-               stream->iptr = stream->ibuf;
-       }
-       
-       if (_g_canceled) {
-               EM_DEBUG_EXCEPTION("\t thread canceled...\n");
-               
-               tcp_abort(stream);
-               return false;
-       }
-       
-       /* EM_DEBUG_LOG("end"); */
-       return true;
-       
-#ifdef TEST_CANCEL_JOB
-JOB_CANCEL:
-       return false;
-#endif
 }
 
 INTERNAL_FUNC long tcp_sout_lnx(TCPSTREAM *stream, char *string, unsigned long size)
@@ -410,26 +310,13 @@ INTERNAL_FUNC long tcp_sout_lnx(TCPSTREAM *stream, char *string, unsigned long s
        fd_set writefds;
        int sret, nwrite, maxfd, sockid;
        int max_timeout = 0;
-       
+
        sockid = stream->tcpso;
        maxfd = sockid + 1;
-/* EM_DEBUG_LOG("start sockid %d", sockid); */
+       /* EM_DEBUG_LOG("start sockid %d", sockid); */
        if (sockid < 0) return 0;
 
        while (size > 0) {
-#ifdef TEST_CANCEL_JOB
-               if (!emcore_check_thread_status()) {
-                       EM_DEBUG_EXCEPTION("thread canceled");
-                       tcp_abort(stream);
-                       goto JOB_CANCEL;
-               }
-#endif
-               /* if (_g_canceled){ */
-               /*      EM_DEBUG_LOG1("thread canceled"); */
-               /*      tcp_abort(stream); */
-               /*      return 0; */
-               /* } */
-
                tmout.tv_usec = 0;
                tmout.tv_sec = 1;
                FD_ZERO(&writefds);
@@ -469,18 +356,7 @@ INTERNAL_FUNC long tcp_sout_lnx(TCPSTREAM *stream, char *string, unsigned long s
                size -= nwrite;
        }
 
-       if (_g_canceled) {
-               EM_DEBUG_EXCEPTION("thread canceled");
-               tcp_abort(stream);
-               return 0;
-       }
-/* EM_DEBUG_LOG("end"); */
        return 1;
-
-#ifdef TEST_CANCEL_JOB
-JOB_CANCEL:
-       return 0;
-#endif
 }
 
 INTERNAL_FUNC long tcp_soutr_lnx(TCPSTREAM *stream, char *string)
index db56240..a5db10f 100755 (executable)
@@ -38,8 +38,11 @@ extern "C"
 
 #include "email-internal-types.h"
 
+INTERNAL_FUNC int emnetwork_check_network_status(int *err_code);
+INTERNAL_FUNC int emnetwork_get_roaming_status(int *output_roaming_status);
+INTERNAL_FUNC int emnetwork_get_wifi_status(int *wifi_status);
 INTERNAL_FUNC long emnetwork_callback_ssl_cert_query(char *reason, char *host, char *cert);
-INTERNAL_FUNC int  emnetwork_check_network_status(int *err_code);
+
 
 #ifdef __cplusplus
 }
index e2e6b29..21a14a4 100755 (executable)
@@ -62,6 +62,7 @@
 #include "email-types.h"
 #include "email-convert.h"
 #include "email-core-signal.h"
+#include "email-core-event.h"
 
 #define DB_STMT sqlite3_stmt *
 
 #define MAILBOX_NAME_LEN_IN_MAIL_READ_MAIL_UID_TBL      128
 #define S_UID_LEN_IN_MAIL_READ_MAIL_UID_TBL             128
 #define DATA2_LEN_IN_MAIL_READ_MAIL_UID_TBL             256
+#define FILTER_NAME_LEN_IN_MAIL_RULE_TBL                256
 #define VALUE_LEN_IN_MAIL_RULE_TBL                      256
+#define VALUE2_LEN_IN_MAIL_RULE_TBL                     256
 #define DEST_MAILBOX_LEN_IN_MAIL_RULE_TBL               128
 #define MAILBOX_NAME_LEN_IN_MAIL_ATTACHMENT_TBL         128
 #define ATTACHMENT_PATH_LEN_IN_MAIL_ATTACHMENT_TBL      256
 #define ATTACHMENT_NAME_LEN_IN_MAIL_ATTACHMENT_TBL      256
-#define CONTENT_ID_LEN_IN_MAIL_ATTACHMENT_TBL           256
 #define ATTACHMENT_MIME_TYPE_LEN_IN_MAIL_ATTACHMENT_TBL 128
 #define MAILBOX_LEN_IN_MAIL_TBL                         128
 #define SERVER_MAILBOX_LEN_IN_MAIL_TBL                  128
@@ -216,7 +218,7 @@ sqlite3 *emstorage_get_db_handle()
        ENTER_CRITICAL_SECTION(_db_handle_lock);
        for (i = 0; i < MAX_DB_CLIENT; i++) {
                if (pthread_equal(current_thread_id, _db_handle_list[i].thread_id)) {
-                       EM_DEBUG_LOG("found db handle at [%d]", i);
+                       EM_DEBUG_LOG_DEV("found db handle at [%d]", i);
                        result_db_handle = _db_handle_list[i].db_handle;
                        break;
                }
@@ -224,7 +226,7 @@ sqlite3 *emstorage_get_db_handle()
        LEAVE_CRITICAL_SECTION(_db_handle_lock);
 
        if (!result_db_handle)
-               EM_DEBUG_EXCEPTION("Can't find proper handle for [%d]", current_thread_id);
+               EM_DEBUG_LOG("no db_handle for [%d] found", current_thread_id);
 
        EM_DEBUG_FUNC_END();
        return result_db_handle;
@@ -300,10 +302,7 @@ int emstorage_reset_db_handle_list()
 
 sqlite3 *emstorage_get_db_connection()
 {
-       sqlite3 *tmp_db_handle = emstorage_get_db_handle();
-       if (NULL == tmp_db_handle)
-               tmp_db_handle = emstorage_db_open(NULL);
-       return tmp_db_handle;
+       return emstorage_db_open(NULL);
 }
 
 
@@ -347,6 +346,7 @@ int              shm_fd_for_generating_mail_id = 0;
 INTERNAL_FUNC int emstorage_shm_file_init(const char *shm_file_name)
 {
        EM_DEBUG_FUNC_BEGIN("shm_file_name [%p]", shm_file_name);
+       char errno_buf[ERRNO_BUF_SIZE] = {0};
 
        if(!shm_file_name) {
                EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
@@ -359,13 +359,13 @@ INTERNAL_FUNC int emstorage_shm_file_init(const char *shm_file_name)
                fchmod(fd, 0666);
                EM_DEBUG_LOG("** Create SHM FILE **");
                if (ftruncate(fd, sizeof(mmapped_t)) != 0) {
-                       EM_DEBUG_EXCEPTION("ftruncate failed: %s", strerror(errno));
+                       EM_DEBUG_EXCEPTION("ftruncate failed: %s", EM_STRERROR(errno_buf));
                        return EMAIL_ERROR_SYSTEM_FAILURE;
                }
 
                mmapped_t *m = (mmapped_t *)mmap(NULL, sizeof(mmapped_t), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
                if (m == MAP_FAILED) {
-                       EM_DEBUG_EXCEPTION("mmap failed: %s", strerror(errno));
+                       EM_DEBUG_EXCEPTION("mmap failed: %s", EM_STRERROR(errno_buf));
                        return EMAIL_ERROR_SYSTEM_FAILURE;
                }
 
@@ -379,7 +379,7 @@ INTERNAL_FUNC int emstorage_shm_file_init(const char *shm_file_name)
                pthread_mutexattr_destroy(&mattr);
        }
        else {
-               EM_DEBUG_EXCEPTION("shm_open failed: %s", strerror(errno));
+               EM_DEBUG_EXCEPTION("shm_open failed: %s", EM_STRERROR(errno_buf));
                return EMAIL_ERROR_SYSTEM_FAILURE;
        }
        close(fd);
@@ -390,13 +390,15 @@ INTERNAL_FUNC int emstorage_shm_file_init(const char *shm_file_name)
 int emstorage_shm_file_destroy(const char *shm_file_name)
 {
        EM_DEBUG_FUNC_BEGIN("shm_file_name [%p]", shm_file_name);
+       char errno_buf[ERRNO_BUF_SIZE] = {0};
+
        if(!shm_file_name) {
                EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
                return EMAIL_ERROR_INVALID_PARAM;
        }
 
        if (shm_unlink(shm_file_name) != 0)
-               EM_DEBUG_EXCEPTION("shm_unlink failed: %s", strerror(errno));
+               EM_DEBUG_EXCEPTION("shm_unlink failed: %s", EM_STRERROR(errno_buf));
        EM_DEBUG_FUNC_END();
        return EMAIL_ERROR_NONE;
 }
@@ -404,6 +406,7 @@ int emstorage_shm_file_destroy(const char *shm_file_name)
 static int _initialize_shm_mutex(const char *shm_file_name, int *param_shm_fd, mmapped_t **param_mapped)
 {
        EM_DEBUG_FUNC_BEGIN("shm_file_name [%p] param_shm_fd [%p], param_mapped [%p]", shm_file_name, param_shm_fd, param_mapped);
+       char errno_buf[ERRNO_BUF_SIZE] = {0};
 
        if(!shm_file_name || !param_shm_fd || !param_mapped) {
                EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
@@ -416,14 +419,14 @@ static int _initialize_shm_mutex(const char *shm_file_name, int *param_shm_fd, m
                if (!(*param_shm_fd)) { /*  open shm_file_name at first. Otherwise, the num of files in /proc/pid/fd will be increasing  */
                        *param_shm_fd = shm_open(shm_file_name, O_RDWR, 0);
                        if ((*param_shm_fd) == -1) {
-                               EM_DEBUG_EXCEPTION("FAIL: shm_open(): %s", strerror(errno));
+                               EM_DEBUG_EXCEPTION("FAIL: shm_open(): %s", EM_STRERROR(errno_buf));
                                return EMAIL_ERROR_SYSTEM_FAILURE;
                        }
                }
                mmapped_t *tmp = (mmapped_t *)mmap(NULL, sizeof(mmapped_t), PROT_READ|PROT_WRITE, MAP_SHARED, (*param_shm_fd), 0);
 
                if (tmp == MAP_FAILED) {
-                       EM_DEBUG_EXCEPTION("mmap failed: %s", strerror(errno));
+                       EM_DEBUG_EXCEPTION("mmap failed: %s", EM_STRERROR(errno_buf));
                        return EMAIL_ERROR_SYSTEM_FAILURE;
                }
                *param_mapped = tmp;
@@ -445,15 +448,16 @@ static int _timedlock_shm_mutex(mmapped_t **param_mapped, int sec)
        struct timespec abs_time;
        clock_gettime(CLOCK_REALTIME, &abs_time);
        abs_time.tv_sec += sec;
+       char errno_buf[ERRNO_BUF_SIZE] = {0};
 
        int err = pthread_mutex_timedlock(&((*param_mapped)->mutex), &abs_time);
 
        if (err == EOWNERDEAD) {
                err = pthread_mutex_consistent(&((*param_mapped)->mutex));
-               EM_DEBUG_EXCEPTION("Previous owner is dead with lock. Fix mutex : %s", EM_STRERROR(err));
+               EM_DEBUG_EXCEPTION("Previous owner is dead with lock. Fix mutex : %s", EM_STRERROR(errno_buf));
        }
        else if (err != 0) {
-               EM_DEBUG_EXCEPTION("ERROR : %s", EM_STRERROR(err));
+               EM_DEBUG_EXCEPTION("ERROR : %s", EM_STRERROR(errno_buf));
                return err;
        }
 
@@ -471,7 +475,6 @@ void _unlockshm_mutex(mmapped_t **param_mapped)
 
 
 static int _open_counter = 0;
-static int g_transaction = false;
 
 static int _get_password_file_name(int account_id, char *recv_password_file_name, char *send_password_file_name);
 static int _read_password_from_secure_storage(char *file_name, char **password);
@@ -511,15 +514,21 @@ enum
        CREATE_TABLE_MAIL_ATTACHMENT_TBL,
 #ifdef __FEATURE_PARTIAL_BODY_DOWNLOAD__
        CREATE_TABLE_MAIL_PARTIAL_BODY_ACTIVITY_TBL,
+#else
+       CREATE_TABLE_DUMMY_INDEX1,
 #endif
        CREATE_TABLE_MAIL_MEETING_TBL,
 #ifdef __FEATURE_LOCAL_ACTIVITY__
        CREATE_TABLE_MAIL_LOCAL_ACTIVITY_TBL,
+#else
+       CREATE_TABLE_DUMMY_INDEX2,
 #endif
        CREATE_TABLE_MAIL_CERTIFICATE_TBL,
        CREATE_TABLE_MAIL_TASK_TBL,
 #ifdef __FEATURE_BODY_SEARCH__
        CREATE_TABLE_MAIL_TEXT_TBL,
+#else
+       CREATE_TABLE_DUMMY_INDEX3,
 #endif
 
        /*CREATE INDEX*/
@@ -581,12 +590,13 @@ enum
 {
        ACCOUNT_ID_IDX_IN_MAIL_READ_MAIL_UID_TBL = 0,
        LOCAL_MAILBOX_ID_IDX_IN_MAIL_READ_MAIL_UID_TBL,
-       LOCAL_UID_IDX_IN_MAIL_READ_MAIL_UID_TBL,
        MAILBOX_NAME_IDX_IN_MAIL_READ_MAIL_UID_TBL,
-       S_UID_IDX_IN_MAIL_READ_MAIL_UID_TBL,
-       DATA1_IDX_IN_MAIL_READ_MAIL_UID_TBL,
-       DATA2_IDX_IN_MAIL_READ_MAIL_UID_TBL,
-       FLAG_IDX_IN_MAIL_READ_MAIL_UID_TBL,
+       LOCAL_UID_IDX_IN_MAIL_READ_MAIL_UID_TBL,
+       SERVER_UID_IDX_IN_MAIL_READ_MAIL_UID_TBL,
+       RFC822_SIZE_IDX_IN_MAIL_READ_MAIL_UID_TBL,
+       SYNC_STATUS_IDX_IN_MAIL_READ_MAIL_UID_TBL,
+       FLAGS_SEEN_FIELD_IDX_IN_MAIL_READ_MAIL_UID_TBL,
+       FLAGS_FLAGGED_FIELD_IDX_IN_MAIL_READ_MAIL_UID_TBL,
        IDX_NUM_IDX_IN_MAIL_READ_MAIL_UID_TBL,          /* unused */
 };
 
@@ -605,8 +615,10 @@ enum
 {
        ACCOUNT_ID_IDX_IN_MAIL_RULE_TBL = 0,
        RULE_ID_IDX_IN_MAIL_RULE_TBL,
+       FILTER_NAME_IDX_IN_MAIL_RULE_TBL,
        TYPE_IDX_IN_MAIL_RULE_TBL,
        VALUE_IDX_IN_MAIL_RULE_TBL,
+       VALUE2_IDX_IN_MAIL_RULE_TBL,
        ACTION_TYPE_IDX_IN_MAIL_RULE_TBL,
        TARGET_MAILBOX_ID_IDX_IN_MAIL_RULE_TBL,
        FLAG1_IDX_IN_MAIL_RULE_TBL,
@@ -663,6 +675,10 @@ enum
        DIGEST_TYPE_IDX_IN_MAIL_TBL,
        SMIME_TYPE_IDX_IN_MAIL_TBL,
        SCHEDULED_SENDING_TIME_IDX_IN_MAIL_TBL,
+       REMAINING_RESEND_TIMES_IDX_IN_MAIL_TBL,
+       TAG_ID_IDX_IN_MAIL_TBL,
+       REPLIED_TIME_IDX_IN_MAIL_TBL,
+       FORWARDED_TIME_IDX_IN_MAIL_TBL,
        EAS_DATA_LENGTH_IDX_IN_MAIL_TBL,
        EAS_DATA_IDX_IN_MAIL_TBL,
        FIELD_COUNT_OF_MAIL_TBL,  /* End of mail_tbl */
@@ -724,6 +740,7 @@ static char *g_test_query[] = {
                " retrieval_mode, "
                " incoming_server_port_number, "
                " incoming_server_secure_connection, "
+               " incoming_server_authentication_method,"
                " outgoing_server_type, "
                " outgoing_server_address, "
                " outgoing_server_port_number, "
@@ -736,11 +753,11 @@ static char *g_test_query[] = {
                " return_addr, "
                " account_id, "
                " keep_mails_on_pop_server_after_download, "
-               " flag1, "
-               " flag2, "
+               " auto_resend_times, "
+               " outgoing_server_size_limit, "
                " pop_before_smtp, "
-               " incoming_server_requires_apop"
-               ", logo_icon_path, "
+               " incoming_server_requires_apop,"
+               " logo_icon_path, "
                " is_preset_account, "
                " check_interval, "
                " priority, "
@@ -786,24 +803,26 @@ static char *g_test_query[] = {
                "SELECT  "
                "   account_id,  "
                "   mailbox_id,  "
-               "   local_uid,  "
                "   mailbox_name,  "
-               "   s_uid,  "
-               "   data1 ,  "
-               "   data2,  "
-               "   flag,  "
+               "   local_uid,  "
+               "   server_uid,  "
+               "   rfc822_size ,  "
+               "   sync_status,  "
+               "   flags_seen_field,  "
                "   idx_num "
                " FROM mail_read_mail_uid_tbl ",
                /*  4. select mail_rule_tbl */
                "SELECT "
                "   account_id, "
                "   rule_id, "
-               "       type, "
-               "       value, "
-               "       action_type, "
-               "       target_mailbox_id,      "
-               "       flag1, "
-               "       flag2 "
+               "   filter_name, "
+               "   type, "
+               "   value, "
+               "   value2, "
+               "   action_type, "
+               "   target_mailbox_id,  "
+               "   flag1, "
+               "   flag2 "
                " FROM mail_rule_tbl    ",
                /*  5. select mail_tbl */
                "SELECT"
@@ -947,6 +966,7 @@ static char *g_test_query[] = {
                NULL,
 };
 
+int _field_count_of_table[CREATE_TABLE_MAX] = { 0, };
 
 static int _get_table_field_data_char(char  **table, char *buf, int index)
 {
@@ -1311,6 +1331,45 @@ static int _bind_stmt_field_data_string(DB_STMT hStmt, int index, char *value, i
        return true;
 }
 
+/* destroy function for sqlite3_bind_text */
+void _bind_stmt_free_string(void* arg)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       char* p = (char*) arg;
+       EM_SAFE_FREE(p);
+       EM_DEBUG_FUNC_END();
+}
+
+static int _bind_stmt_field_data_nstring(DB_STMT hStmt, int index, char *value, int ucs2, int max_len)
+{
+       if ((hStmt == NULL) || (index < 0)) {
+               EM_DEBUG_EXCEPTION("index[%d], max_len[%d]", index, max_len);
+               return false;
+       }
+
+#ifdef _PRINT_STORAGE_LOG_
+       EM_DEBUG_LOG("hStmt = %p, index = %d, max_len = %d, value = [%s]", hStmt, index, max_len, value);
+#endif
+
+       int ret = 0;
+       if (value != NULL) {
+               if (strlen(value) <= max_len)
+                       ret = sqlite3_bind_text(hStmt, index+1, value, -1, SQLITE_STATIC);
+               else {
+                       char *buf = (char*)em_malloc(sizeof(char) * (max_len));
+                       snprintf(buf, max_len-1, "%s", value);
+                       ret = sqlite3_bind_text(hStmt, index+1, buf, -1, _bind_stmt_free_string);
+               }
+       } else
+               ret = sqlite3_bind_text(hStmt, index+1, "", -1, NULL);
+
+       if (ret != SQLITE_OK)  {
+               EM_DEBUG_EXCEPTION("sqlite3_bind_text fail [%d]", ret);
+               return false;
+       }
+       return true;
+}
+
 
 static int _bind_stmt_field_data_blob(DB_STMT hStmt, int index, void *blob, int blob_size)
 {
@@ -1418,8 +1477,6 @@ static void *_emstorage_open_once(int *err_code)
 
        _delete_temp_file(MAILTEMP);
 
-       g_transaction = false;
-
        if (!emstorage_create_table(EMAIL_CREATE_DB_NORMAL, &error)) {
                EM_DEBUG_EXCEPTION(" emstorage_create_table failed - %d", error);
                goto FINISH_OFF;
@@ -1454,7 +1511,7 @@ static int _delete_all_files_and_directories(int *err_code)
 
        if (!emstorage_delete_file(EMAIL_SERVICE_DB_FILE_PATH, &error)) {
                if (error != EMAIL_ERROR_FILE_NOT_FOUND) {
-                       EM_DEBUG_EXCEPTION("remove failed - %s", EMAIL_SERVICE_DB_FILE_PATH);
+                       EM_DEBUG_EXCEPTION_SEC("remove failed - %s", EMAIL_SERVICE_DB_FILE_PATH);
                        goto FINISH_OFF;
                }
        }
@@ -1508,17 +1565,16 @@ INTERNAL_FUNC int em_db_open(sqlite3 **sqlite_handle, int *err_code)
        int error = EMAIL_ERROR_NONE;
        int ret = false;
 
-       EM_DEBUG_LOG("*sqlite_handle[%p]", *sqlite_handle);
+       EM_DEBUG_LOG_DEV("*sqlite_handle[%p]", *sqlite_handle);
 
        if (*sqlite_handle)  { /*prevent 33351*/
-               EM_DEBUG_LOG(">>>>> DB Already Opened......");
+               EM_DEBUG_LOG_DEV(">>>>> DB Already Opened......");
                if (err_code != NULL)
                        *err_code = error;
                return true;
        }
 
        /*  db open */
-       EM_DEBUG_LOG("Open DB");
        EMSTORAGE_PROTECTED_FUNC_CALL(db_util_open(EMAIL_SERVICE_DB_FILE_PATH, sqlite_handle, DB_UTIL_REGISTER_HOOK_METHOD), rc);
        if (SQLITE_OK != rc) {
                EM_DEBUG_EXCEPTION("db_util_open fail:%d -%s", rc, sqlite3_errmsg(*sqlite_handle));
@@ -1546,10 +1602,9 @@ INTERNAL_FUNC int em_db_open(sqlite3 **sqlite_handle, int *err_code)
                else
                        goto FINISH_OFF;
        }
-       EM_DEBUG_LOG(">>>>> DB Handle : *sqlite_handle[%p]", *sqlite_handle);
 
+       EM_DEBUG_LOG_DEV(">>>>> Register DB Handle to busy handler: *sqlite_handle[%p]", *sqlite_handle);
        /* register busy handler */
-       EM_DEBUG_LOG(">>>>> Register busy handler.....");
        rc = sqlite3_busy_handler(*sqlite_handle, _callback_sqlite_busy_handler, NULL);  /*  Busy Handler registration, NULL is a parameter which will be passed to handler */
        if (SQLITE_OK != rc) {
                EM_DEBUG_EXCEPTION("sqlite3_busy_handler fail:%d -%s", rc, sqlite3_errmsg(*sqlite_handle));
@@ -1573,26 +1628,28 @@ FINISH_OFF:
 INTERNAL_FUNC sqlite3* emstorage_db_open(int *err_code)
 {
        EM_DEBUG_FUNC_BEGIN();
-#ifdef _MULTIPLE_DB_HANDLE
+
        sqlite3 *_db_handle = NULL;
-#endif
 
        int error = EMAIL_ERROR_NONE;
 
-       _initialize_shm_mutex(SHM_FILE_FOR_DB_LOCK, &shm_fd_for_db_lock, &mapped_for_db_lock);
+       _db_handle = emstorage_get_db_handle();
+
+       if( _db_handle == NULL) {
+               if (!em_db_open(&_db_handle, &error)) {
+                       EM_DEBUG_EXCEPTION("em_db_open failed[%d]", error);
+                       goto FINISH_OFF;
+               }
+               _initialize_shm_mutex(SHM_FILE_FOR_DB_LOCK, &shm_fd_for_db_lock, &mapped_for_db_lock);
 
 #ifdef __FEATURE_USE_SHARED_MUTEX_FOR_GENERATING_MAIL_ID__
-       _initialize_shm_mutex(SHM_FILE_FOR_MAIL_ID_LOCK, &shm_fd_for_generating_mail_id, &mapped_for_generating_mail_id);
+               _initialize_shm_mutex(SHM_FILE_FOR_MAIL_ID_LOCK, &shm_fd_for_generating_mail_id, &mapped_for_generating_mail_id);
 #endif /*__FEATURE_USE_SHARED_MUTEX_FOR_GENERATING_MAIL_ID__ */
 
-       if (!em_db_open(&_db_handle, &error)) {
-               EM_DEBUG_EXCEPTION("em_db_open failed[%d]", error);
-               goto FINISH_OFF;
+               emstorage_set_db_handle(_db_handle);
+               emstorage_initialize_field_count();
        }
 
-#ifdef _MULTIPLE_DB_HANDLE
-       emstorage_set_db_handle(_db_handle);
-#endif
 
 FINISH_OFF:
        if (err_code != NULL)
@@ -1657,9 +1714,9 @@ INTERNAL_FUNC int emstorage_open(int *err_code)
                goto FINISH_OFF;
        }
 
-
-       if (_open_counter++ == 0)
+       if (_open_counter++ == 0) {
                _emstorage_open_once(&error);
+       }
 
        ret = true;
 
@@ -1671,6 +1728,86 @@ FINISH_OFF:
        return ret;
 }
 
+static int emstorage_get_field_count_from_create_table_query(char *input_create_table_query, int *output_field_count)
+{
+       EM_DEBUG_FUNC_BEGIN("input_create_table_query[%d], output_field_count[%p]", input_create_table_query, output_field_count);
+       int err = EMAIL_ERROR_NONE;
+       int field_count = 0;
+       char *pos = NULL;
+
+       if(input_create_table_query == NULL || output_field_count == NULL) {
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       pos = input_create_table_query;
+
+       do {
+               field_count++;
+               if(pos == NULL || *pos == (char)0)
+                       break;
+               pos += 1;
+               pos = strchr(pos, ',');
+       } while(pos);
+
+       *output_field_count = field_count;
+
+       EM_DEBUG_LOG_DEV("field_count [%d]", field_count);
+
+FINISH_OFF:
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC int emstorage_initialize_field_count()
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int err = EMAIL_ERROR_NONE;
+       int query_len = 0;
+       char **create_table_query = NULL;
+
+       if(_field_count_of_table[CREATE_TABLE_MAIL_ACCOUNT_TBL] != 0) {
+               err = EMAIL_ERROR_ALREADY_INITIALIZED;
+               goto FINISH_OFF;
+       }
+
+       err = emcore_load_query_from_file(EMAIL_SERVICE_CREATE_TABLE_QUERY_FILE_PATH, &create_table_query, &query_len);
+       if (err != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emcore_load_sql_from_file failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       emstorage_get_field_count_from_create_table_query(create_table_query[CREATE_TABLE_MAIL_ACCOUNT_TBL], &(_field_count_of_table[CREATE_TABLE_MAIL_ACCOUNT_TBL]));
+       emstorage_get_field_count_from_create_table_query(create_table_query[CREATE_TABLE_MAIL_BOX_TBL], &(_field_count_of_table[CREATE_TABLE_MAIL_BOX_TBL]));
+       emstorage_get_field_count_from_create_table_query(create_table_query[CREATE_TABLE_MAIL_READ_MAIL_UID_TBL], &(_field_count_of_table[CREATE_TABLE_MAIL_READ_MAIL_UID_TBL]));
+       emstorage_get_field_count_from_create_table_query(create_table_query[CREATE_TABLE_MAIL_RULE_TBL], &(_field_count_of_table[CREATE_TABLE_MAIL_RULE_TBL]));
+       emstorage_get_field_count_from_create_table_query(create_table_query[CREATE_TABLE_MAIL_TBL], &(_field_count_of_table[CREATE_TABLE_MAIL_TBL]));
+       emstorage_get_field_count_from_create_table_query(create_table_query[CREATE_TABLE_MAIL_ATTACHMENT_TBL], &(_field_count_of_table[CREATE_TABLE_MAIL_ATTACHMENT_TBL]));
+       emstorage_get_field_count_from_create_table_query(create_table_query[CREATE_TABLE_MAIL_PARTIAL_BODY_ACTIVITY_TBL], &(_field_count_of_table[CREATE_TABLE_MAIL_PARTIAL_BODY_ACTIVITY_TBL]));
+       emstorage_get_field_count_from_create_table_query(create_table_query[CREATE_TABLE_MAIL_MEETING_TBL], &(_field_count_of_table[CREATE_TABLE_MAIL_MEETING_TBL]));
+#ifdef __FEATURE_LOCAL_ACTIVITY__
+       emstorage_get_field_count_from_create_table_query(create_table_query[CREATE_TABLE_MAIL_LOCAL_ACTIVITY_TBL], &(_field_count_of_table[CREATE_TABLE_MAIL_LOCAL_ACTIVITY_TBL]));
+#endif /* __FEATURE_LOCAL_ACTIVITY__ */
+       emstorage_get_field_count_from_create_table_query(create_table_query[CREATE_TABLE_MAIL_CERTIFICATE_TBL], &(_field_count_of_table[CREATE_TABLE_MAIL_CERTIFICATE_TBL]));
+       emstorage_get_field_count_from_create_table_query(create_table_query[CREATE_TABLE_MAIL_TASK_TBL], &(_field_count_of_table[CREATE_TABLE_MAIL_TASK_TBL]));
+       emstorage_get_field_count_from_create_table_query(create_table_query[CREATE_TABLE_MAIL_TEXT_TBL], &(_field_count_of_table[CREATE_TABLE_MAIL_TEXT_TBL]));
+FINISH_OFF:
+
+       if (create_table_query) {
+               int i = 0;
+               for (i = 0; i < query_len; i++) {
+                       if (create_table_query[i]) {
+                               EM_SAFE_FREE(create_table_query[i]);
+                       }
+               }
+               EM_SAFE_FREE(create_table_query);
+       }
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
 INTERNAL_FUNC int emstorage_create_table(emstorage_create_db_type_t type, int *err_code)
 {
        EM_DEBUG_FUNC_BEGIN();
@@ -1680,6 +1817,7 @@ INTERNAL_FUNC int emstorage_create_table(emstorage_create_db_type_t type, int *e
        int query_len = 0;
        char sql_query_string[QUERY_SIZE] = {0, };
        char **create_table_query = NULL;
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
 
        error = emcore_load_query_from_file(EMAIL_SERVICE_CREATE_TABLE_QUERY_FILE_PATH, &create_table_query, &query_len);
        if (error != EMAIL_ERROR_NONE) {
@@ -1693,11 +1831,10 @@ INTERNAL_FUNC int emstorage_create_table(emstorage_create_db_type_t type, int *e
                goto FINISH_OFF2;
        }
 
-       sqlite3 *local_db_handle = emstorage_get_db_connection();
        EM_DEBUG_LOG("local_db_handle = %p.", local_db_handle);
 
        char *sql;
-       char **result;
+       char **result = NULL;
 
        sql = "SELECT count(name) FROM sqlite_master WHERE name='mail_account_tbl';";
        EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql, &result, NULL, NULL, NULL), rc);
@@ -1725,7 +1862,6 @@ INTERNAL_FUNC int emstorage_create_table(emstorage_create_db_type_t type, int *e
                EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; }, ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
 
                EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, "END;", NULL, NULL, NULL), rc);
-
        } /*  mail_account_tbl */
        else if (type == EMAIL_CREATE_DB_CHECK)  {
                EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, g_test_query[CREATE_TABLE_MAIL_ACCOUNT_TBL], NULL, NULL, NULL), rc);
@@ -1733,7 +1869,7 @@ INTERNAL_FUNC int emstorage_create_table(emstorage_create_db_type_t type, int *e
        }
 
        sqlite3_free_table(result);
-
+       result = NULL;
 
        /*  2. create mail_box_tbl */
        sql = "SELECT count(name) FROM sqlite_master WHERE name='mail_box_tbl';";
@@ -1763,7 +1899,6 @@ INTERNAL_FUNC int emstorage_create_table(emstorage_create_db_type_t type, int *e
                        ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
 
                EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, "END;", NULL, NULL, NULL), rc);
-
        } /*  mail_box_tbl */
        else if (type == EMAIL_CREATE_DB_CHECK)  {
                rc = sqlite3_exec(local_db_handle, g_test_query[CREATE_TABLE_MAIL_BOX_TBL], NULL, NULL, NULL);
@@ -1771,6 +1906,7 @@ INTERNAL_FUNC int emstorage_create_table(emstorage_create_db_type_t type, int *e
                        ("SQL(%s) exec fail:%d -%s", g_test_query[CREATE_TABLE_MAIL_BOX_TBL], rc, sqlite3_errmsg(local_db_handle)));
        }
        sqlite3_free_table(result);
+       result = NULL;
 
        /*  3. create mail_read_mail_uid_tbl */
        sql = "SELECT count(name) FROM sqlite_master WHERE name='mail_read_mail_uid_tbl';";
@@ -1799,7 +1935,6 @@ INTERNAL_FUNC int emstorage_create_table(emstorage_create_db_type_t type, int *e
                EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
                        ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
                EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, "END;", NULL, NULL, NULL), rc);
-
        } /*  mail_read_mail_uid_tbl */
        else if (type == EMAIL_CREATE_DB_CHECK)  {
                EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, g_test_query[CREATE_TABLE_MAIL_READ_MAIL_UID_TBL], NULL, NULL, NULL), rc);
@@ -1807,7 +1942,7 @@ INTERNAL_FUNC int emstorage_create_table(emstorage_create_db_type_t type, int *e
                        ("SQL(%s) exec fail:%d -%s", g_test_query[CREATE_TABLE_MAIL_READ_MAIL_UID_TBL], rc, sqlite3_errmsg(local_db_handle)));
        }
        sqlite3_free_table(result);
-
+       result = NULL;
 
        /*  4. create mail_rule_tbl */
        sql = "SELECT count(name) FROM sqlite_master WHERE name='mail_rule_tbl';";
@@ -1829,7 +1964,6 @@ INTERNAL_FUNC int emstorage_create_table(emstorage_create_db_type_t type, int *e
                EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
                        ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
                EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, "END;", NULL, NULL, NULL), rc);
-
        } /*  mail_rule_tbl */
        else if (type == EMAIL_CREATE_DB_CHECK)  {
                EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, g_test_query[CREATE_TABLE_MAIL_RULE_TBL], NULL, NULL, NULL), rc);
@@ -1837,7 +1971,7 @@ INTERNAL_FUNC int emstorage_create_table(emstorage_create_db_type_t type, int *e
                        ("SQL(%s) exec fail:%d -%s", g_test_query[CREATE_TABLE_MAIL_RULE_TBL], rc, sqlite3_errmsg(local_db_handle)));
        }
        sqlite3_free_table(result);
-
+       result = NULL;
 
        /*  5. create mail_tbl */
        sql = "SELECT count(name) FROM sqlite_master WHERE name='mail_tbl';";
@@ -1876,7 +2010,6 @@ INTERNAL_FUNC int emstorage_create_table(emstorage_create_db_type_t type, int *e
                        ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
 
                EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, "END;", NULL, NULL, NULL), rc);
-
                /*  just one time call */
 /*             EFTSInitFTSIndex(FTS_EMAIL_IDX); */
        } /*  mail_tbl */
@@ -1886,7 +2019,7 @@ INTERNAL_FUNC int emstorage_create_table(emstorage_create_db_type_t type, int *e
                        ("SQL(%s) exec fail:%d -%s", g_test_query[CREATE_TABLE_MAIL_TBL], rc, sqlite3_errmsg(local_db_handle)));
        }
        sqlite3_free_table(result);
-
+       result = NULL;
 
        /*  6. create mail_attachment_tbl */
        sql = "SELECT count(name) FROM sqlite_master WHERE name='mail_attachment_tbl';";
@@ -1913,7 +2046,6 @@ INTERNAL_FUNC int emstorage_create_table(emstorage_create_db_type_t type, int *e
                EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
                        ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
                EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, "END;", NULL, NULL, NULL), rc);
-
        } /*  mail_attachment_tbl */
        else if (type == EMAIL_CREATE_DB_CHECK)  {
                EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, g_test_query[CREATE_TABLE_MAIL_ATTACHMENT_TBL], NULL, NULL, NULL), rc);
@@ -1921,6 +2053,7 @@ INTERNAL_FUNC int emstorage_create_table(emstorage_create_db_type_t type, int *e
                        ("SQL(%s) exec fail:%d -%s", g_test_query[CREATE_TABLE_MAIL_ATTACHMENT_TBL], rc, sqlite3_errmsg(local_db_handle)));
        }
        sqlite3_free_table(result);
+       result = NULL;
 
 #ifdef __FEATURE_PARTIAL_BODY_DOWNLOAD__
 
@@ -1943,7 +2076,6 @@ INTERNAL_FUNC int emstorage_create_table(emstorage_create_db_type_t type, int *e
                EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
                        ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
                EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, "END;", NULL, NULL, NULL), rc);
-
        } /*  mail_rule_tbl */
        else if (type == EMAIL_CREATE_DB_CHECK)  {
                EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, g_test_query[CREATE_TABLE_MAIL_PARTIAL_BODY_ACTIVITY_TBL], NULL, NULL, NULL), rc);
@@ -1951,6 +2083,7 @@ INTERNAL_FUNC int emstorage_create_table(emstorage_create_db_type_t type, int *e
                        ("SQL(%s) exec fail:%d -%s", g_test_query[CREATE_TABLE_MAIL_PARTIAL_BODY_ACTIVITY_TBL], rc, sqlite3_errmsg(local_db_handle)));
        }
        sqlite3_free_table(result);
+       result = NULL;
 
 #endif /*  __FEATURE_PARTIAL_BODY_DOWNLOAD__ */
 
@@ -1978,7 +2111,6 @@ INTERNAL_FUNC int emstorage_create_table(emstorage_create_db_type_t type, int *e
                EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
                        ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
                EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, "END;", NULL, NULL, NULL), rc);
-
        } /*  mail_contact_sync_tbl */
        else if (type == EMAIL_CREATE_DB_CHECK)  {
                EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, g_test_query[CREATE_TABLE_MAIL_MEETING_TBL], NULL, NULL, NULL), rc);
@@ -1986,6 +2118,7 @@ INTERNAL_FUNC int emstorage_create_table(emstorage_create_db_type_t type, int *e
                        ("SQL(%s) exec fail:%d -%s", g_test_query[CREATE_TABLE_MAIL_MEETING_TBL], rc, sqlite3_errmsg(local_db_handle)));
        }
        sqlite3_free_table(result);
+       result = NULL;
 
 #ifdef __FEATURE_LOCAL_ACTIVITY__
 
@@ -2008,7 +2141,6 @@ INTERNAL_FUNC int emstorage_create_table(emstorage_create_db_type_t type, int *e
                        EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
                                ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
                        EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, "END;", NULL, NULL, NULL), rc);
-
                } /*  mail_rule_tbl */
                else if (type == EMAIL_CREATE_DB_CHECK)  {
                        rc = sqlite3_exec(local_db_handle, g_test_query[CREATE_TABLE_MAIL_LOCAL_ACTIVITY_TBL], NULL, NULL, NULL);
@@ -2017,7 +2149,7 @@ INTERNAL_FUNC int emstorage_create_table(emstorage_create_db_type_t type, int *e
                                ("SQL(%s) exec fail:%d -%s", g_test_query[CREATE_TABLE_MAIL_LOCAL_ACTIVITY_TBL], rc, sqlite3_errmsg(local_db_handle)));
                }
                sqlite3_free_table(result);
-
+               result = NULL;
 #endif /*  __FEATURE_LOCAL_ACTIVITY__ */
        /*  create mail_certificate_tbl */
        sql = "SELECT count(name) FROM sqlite_master WHERE name='mail_certificate_tbl';";
@@ -2042,6 +2174,9 @@ INTERNAL_FUNC int emstorage_create_table(emstorage_create_db_type_t type, int *e
                EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; }, ("SQL(%s) exec fail:%d -%s", g_test_query[CREATE_TABLE_MAIL_CERTIFICATE_TBL], rc, sqlite3_errmsg(local_db_handle)));
        }
 
+       sqlite3_free_table(result);
+       result = NULL;
+
        /*  create mail_task_tbl */
        sql = "SELECT count(name) FROM sqlite_master WHERE name='mail_task_tbl';";
        EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql, &result, NULL, NULL, NULL), rc);
@@ -2068,6 +2203,9 @@ INTERNAL_FUNC int emstorage_create_table(emstorage_create_db_type_t type, int *e
                EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; }, ("SQL(%s) exec fail:%d -%s", g_test_query[CREATE_TABLE_MAIL_TASK_TBL], rc, sqlite3_errmsg(local_db_handle)));
        }
 
+       sqlite3_free_table(result);
+       result = NULL;
+
 #ifdef __FEATURE_BODY_SEARCH__
        /*  create mail_text_tbl */
        sql = "SELECT count(name) FROM sqlite_master WHERE name='mail_text_tbl';";
@@ -2091,13 +2229,18 @@ INTERNAL_FUNC int emstorage_create_table(emstorage_create_db_type_t type, int *e
                EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, g_test_query[CREATE_TABLE_MAIL_TEXT_TBL], NULL, NULL, NULL), rc);
                EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; }, ("SQL(%s) exec fail:%d -%s", g_test_query[CREATE_TABLE_MAIL_TEXT_TBL], rc, sqlite3_errmsg(local_db_handle)));
        }
-#endif
 
        sqlite3_free_table(result);
+       result = NULL;
+
+#endif
 
        ret = true;
 
 FINISH_OFF:
+
+       if(result) sqlite3_free_table(result);
+
        if (ret == true) {
                EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, "END;", NULL, NULL, NULL), rc);
        }
@@ -2134,7 +2277,6 @@ INTERNAL_FUNC int emstorage_query_mail_count(const char *input_conditional_claus
        int error = EMAIL_ERROR_NONE;
        DB_STMT hStmt = NULL;
        char sql_query_string[QUERY_SIZE] = {0, };
-       char err_msg[1024];
        char **result;
        sqlite3 *local_db_handle = NULL;
 
@@ -2154,11 +2296,11 @@ INTERNAL_FUNC int emstorage_query_mail_count(const char *input_conditional_claus
        if (output_total_mail_count)  {
                EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
                EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
-                       ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+                       ("sqlite3_prepare failed [%d] [%s]", rc, sql_query_string));
 
                EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
                EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
-                       ("sqlite3_step fail:%d", rc));
+                       ("sqlite3_step failed [%d] [%s]", rc, sql_query_string));
                _get_stmt_field_data_int(hStmt, output_total_mail_count, 0);
        }
 
@@ -2167,7 +2309,7 @@ INTERNAL_FUNC int emstorage_query_mail_count(const char *input_conditional_claus
 
                EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql_query_string, &result, NULL, NULL, NULL), rc);
                EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
-                       ("SQL(%s) sqlite3_get_table fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+                       ("sqlite3_get_table failed [%d] [%s]", rc, sql_query_string));
 
                *output_unseen_mail_count = atoi(result[1]);
                sqlite3_free_table(result);
@@ -2178,7 +2320,7 @@ FINISH_OFF:
        if (hStmt != NULL)  {
                rc = sqlite3_finalize(hStmt);
                if (rc != SQLITE_OK)  {
-                       EM_DEBUG_LOG("sqlite3_finalize failed [%d] : %s", rc, err_msg);
+                       EM_DEBUG_LOG("sqlite3_finalize failed [%d]", rc);
                        error = EMAIL_ERROR_DB_FAILURE;
                }
        }
@@ -2226,7 +2368,7 @@ INTERNAL_FUNC int emstorage_query_mail_id_list(const char *input_conditional_cla
 
        /*  to get mail list */
        if (count == 0) {
-               EM_DEBUG_EXCEPTION("No mail found...");
+               EM_DEBUG_LOG("No mail found...");
                error = EMAIL_ERROR_MAIL_NOT_FOUND;
                goto FINISH_OFF;
        }
@@ -2270,12 +2412,17 @@ INTERNAL_FUNC int emstorage_query_mail_list(const char *conditional_clause, int
        EM_PROFILE_BEGIN(emstorage_query_mail_list_func);
 
        int i = 0, count = 0, rc = -1, to_get_count = (result_mail_list)?0:1;
+       int sql_query_string_length = 0;
        int local_inline_content_count = 0, local_attachment_count = 0;
        int cur_query = 0, base_count = 0, col_index;
        int ret = false, error = EMAIL_ERROR_NONE;
        char *date_time_string = NULL;
-       char **result = NULL, sql_query_string[QUERY_SIZE] = {0, };
-       char *field_list = "mail_id, account_id, mailbox_id, full_address_from, email_address_sender, full_address_to, subject, body_download_status, flags_seen_field, flags_deleted_field, flags_flagged_field, flags_answered_field, flags_recent_field, flags_draft_field, flags_forwarded_field, DRM_status, priority, save_status, lock_status, attachment_count, inline_content_count, date_time, preview_text, thread_id, thread_item_count, meeting_request_status, message_class, smime_type, scheduled_sending_time, eas_data_length, eas_data ";
+       char **result = NULL;
+       char *field_mail_id = "mail_id";
+       char *field_all     = "mail_id, account_id, mailbox_id, mailbox_type, full_address_from, email_address_sender, full_address_to, subject, body_download_status, mail_size, flags_seen_field, flags_deleted_field, flags_flagged_field, flags_answered_field, flags_recent_field, flags_draft_field, flags_forwarded_field, DRM_status, priority, save_status, lock_status, attachment_count, inline_content_count, date_time, preview_text, thread_id, thread_item_count, meeting_request_status, message_class, smime_type, scheduled_sending_time, remaining_resend_times, tag_id, eas_data_length, eas_data ";
+       char *select_query_form = "SELECT %s FROM mail_tbl ";
+       char *target_field = NULL;
+       char *sql_query_string = NULL;
        email_mail_list_item_t *mail_list_item_from_tbl = NULL;
        sqlite3 *local_db_handle = emstorage_get_db_connection();
 
@@ -2286,49 +2433,61 @@ INTERNAL_FUNC int emstorage_query_mail_list(const char *conditional_clause, int
 
        /*  select clause */
        if (to_get_count) /*  count only */
-               cur_query += SNPRINTF_OFFSET(sql_query_string, cur_query, QUERY_SIZE, "SELECT mail_id FROM mail_tbl");
-       else /*  mail list in plain form */
-               cur_query += SNPRINTF_OFFSET(sql_query_string, cur_query, QUERY_SIZE, "SELECT %s FROM mail_tbl ", field_list);
+               target_field = field_mail_id;
+       else /* mail list in plain form */
+               target_field = field_all;
 
-       /* cur_query += SNPRINTF_OFFSET(sql_query_string, cur_query, QUERY_SIZE, conditional_clause); This code caused some crashes.*/
-       strncat(sql_query_string, conditional_clause, QUERY_SIZE - cur_query);
+       sql_query_string_length = EM_SAFE_STRLEN(select_query_form) + EM_SAFE_STRLEN(target_field) + EM_SAFE_STRLEN(conditional_clause);
 
-       EM_DEBUG_LOG("emstorage_query_mail_list : query[%s].", sql_query_string);
+       if(sql_query_string_length)
+               sql_query_string = em_malloc(sql_query_string_length);
 
-       /*  performing query            */
+       if(sql_query_string == NULL) {
+               EM_DEBUG_EXCEPTION("em_malloc failed...");
+               error = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       cur_query += SNPRINTF_OFFSET(sql_query_string, cur_query, sql_query_string_length, select_query_form, target_field);
+
+       strncat(sql_query_string, conditional_clause, sql_query_string_length - cur_query);
+
+       EM_DEBUG_LOG_DEV ("query[%s]", sql_query_string);
+
+       /*  performing query */
        EM_PROFILE_BEGIN(emstorage_query_mail_list_performing_query);
        EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql_query_string, &result, &count, 0, NULL), rc);
-       EM_DEBUG_DB_EXEC((SQLITE_OK != rc && -1 != rc), {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
-               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc && -1 != rc), {error = EMAIL_ERROR_DB_FAILURE; goto FINISH_OFF; },
+               ("sqlite3_get_table failed [%d] [%s]", rc, sql_query_string));
        EM_PROFILE_END(emstorage_query_mail_list_performing_query);
 
        if (!base_count)
-               base_count = ({ int i=0; char *tmp = field_list; for (i=0; tmp && *(tmp + 1); tmp = index(tmp + 1, ','), i++); i; });
+               base_count = ({ int i=0; char *tmp = field_all; for (i=0; tmp && *(tmp + 1); tmp = index(tmp + 1, ','), i++); i; });
 
        col_index = base_count;
 
-       EM_DEBUG_LOG("base_count [%d]", base_count);
+       EM_DEBUG_LOG_DEV("base_count [%d]", base_count);
 
        if (to_get_count) {
                /*  to get count */
                if (!count) {
-                       EM_DEBUG_EXCEPTION("No mail found...");
+                       EM_DEBUG_LOG_DEV ("No mail found...");
                        ret = false;
                        error= EMAIL_ERROR_MAIL_NOT_FOUND;
                        goto FINISH_OFF;
                }
-               EM_DEBUG_LOG("There are [%d] mails.", count);
+               EM_DEBUG_LOG_DEV ("There are [%d] mails.", count);
        }
        else {
                /*  to get mail list */
                if (!count) {
-                       EM_DEBUG_EXCEPTION("No mail found...");
+                       EM_DEBUG_LOG_DEV ("No mail found...");
                        ret = false;
                        error= EMAIL_ERROR_MAIL_NOT_FOUND;
                        goto FINISH_OFF;
                }
 
-               EM_DEBUG_LOG("There are [%d] mails.", count);
+               EM_DEBUG_LOG_DEV ("There are [%d] mails.", count);
                if (!(mail_list_item_from_tbl = (email_mail_list_item_t*)em_malloc(sizeof(email_mail_list_item_t) * count))) {
                        EM_DEBUG_EXCEPTION("malloc for mail_list_item_from_tbl failed...");
                        error = EMAIL_ERROR_OUT_OF_MEMORY;
@@ -2336,16 +2495,18 @@ INTERNAL_FUNC int emstorage_query_mail_list(const char *conditional_clause, int
                }
 
                EM_PROFILE_BEGIN(emstorage_query_mail_list_loop);
-               EM_DEBUG_LOG(">>>> DATA ASSIGN START >> ");
+               EM_DEBUG_LOG_DEV (">>>> DATA ASSIGN START >> ");
                for (i = 0; i < count; i++) {
                        _get_table_field_data_int(result, &(mail_list_item_from_tbl[i].mail_id), col_index++);
                        _get_table_field_data_int(result, &(mail_list_item_from_tbl[i].account_id), col_index++);
                        _get_table_field_data_int(result, &(mail_list_item_from_tbl[i].mailbox_id), col_index++);
+                       _get_table_field_data_int(result, (int*)&(mail_list_item_from_tbl[i].mailbox_type), col_index++);
                        _get_table_field_data_string_without_allocation(result, mail_list_item_from_tbl[i].full_address_from, STRING_LENGTH_FOR_DISPLAY, 1, col_index++);
                        _get_table_field_data_string_without_allocation(result, mail_list_item_from_tbl[i].email_address_sender, MAX_EMAIL_ADDRESS_LENGTH, 1, col_index++);
                        _get_table_field_data_string_without_allocation(result, mail_list_item_from_tbl[i].email_address_recipient, STRING_LENGTH_FOR_DISPLAY,  1, col_index++);
                        _get_table_field_data_string_without_allocation(result, mail_list_item_from_tbl[i].subject, STRING_LENGTH_FOR_DISPLAY, 1, col_index++);
                        _get_table_field_data_int(result, &(mail_list_item_from_tbl[i].body_download_status), col_index++);
+                       _get_table_field_data_int(result, &(mail_list_item_from_tbl[i].mail_size), col_index++);
                        _get_table_field_data_char(result, &(mail_list_item_from_tbl[i].flags_seen_field), col_index++);
                        _get_table_field_data_char(result, &(mail_list_item_from_tbl[i].flags_deleted_field), col_index++);
                        _get_table_field_data_char(result, &(mail_list_item_from_tbl[i].flags_flagged_field), col_index++);
@@ -2367,21 +2528,24 @@ INTERNAL_FUNC int emstorage_query_mail_list(const char *conditional_clause, int
                        _get_table_field_data_int(result, (int*)&(mail_list_item_from_tbl[i].message_class), col_index++);
                        _get_table_field_data_int(result, (int*)&(mail_list_item_from_tbl[i].smime_type), col_index++);
                        _get_table_field_data_int(result, (int*)&(mail_list_item_from_tbl[i].scheduled_sending_time), col_index++);
+                       _get_table_field_data_int(result, (int*)&(mail_list_item_from_tbl[i].remaining_resend_times), col_index++);
+                       _get_table_field_data_int(result, (int*)&(mail_list_item_from_tbl[i].tag_id), col_index++);
                        _get_table_field_data_int(result, (int*)&(mail_list_item_from_tbl[i].eas_data_length), col_index++);
                        _get_table_field_data_blob(result, (void**)&(mail_list_item_from_tbl[i].eas_data), mail_list_item_from_tbl[i].eas_data_length, col_index++);
 
-                       mail_list_item_from_tbl[i].attachment_count = ((local_attachment_count - local_inline_content_count)> 0) ? 1:0;
+                       mail_list_item_from_tbl[i].attachment_count = (local_attachment_count > 0) ? 1:0;
                }
-               EM_DEBUG_LOG(">>>> DATA ASSIGN END [count : %d] >> ", count);
+               EM_DEBUG_LOG_DEV(">>>> DATA ASSIGN END [count : %d] >> ", count);
                EM_PROFILE_END(emstorage_query_mail_list_loop);
        }
 
-       sqlite3_free_table(result);
-       result = NULL;
        ret = true;
 
 FINISH_OFF:
-       EM_DEBUG_LOG("COUNT [%d]", count);
+       EM_DEBUG_LOG("MAIL_COUNT [%d]", count);
+
+       if(result)
+               sqlite3_free_table(result);
 
        if (to_get_count)
                *result_count = count;
@@ -2397,10 +2561,11 @@ FINISH_OFF:
 
        EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
 
-       sqlite3_release_memory(-1);
+       sqlite3_db_release_memory(local_db_handle);
 
        _DISCONNECT_DB;
 
+       EM_SAFE_FREE(sql_query_string);
        EM_SAFE_FREE(date_time_string);
 
        if (err_code != NULL)
@@ -2416,9 +2581,8 @@ INTERNAL_FUNC int emstorage_query_mail_tbl(const char *conditional_clause, int t
 {
        EM_DEBUG_FUNC_BEGIN("conditional_clause[%s], result_mail_tbl[%p], result_count [%p], transaction[%d], err_code[%p]", conditional_clause, result_mail_tbl, result_count, transaction, err_code);
 
-       if (!conditional_clause) {
-               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
-
+       if (!conditional_clause || !result_mail_tbl || !result_count) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM: [%p] [%p] [%p]", conditional_clause, result_mail_tbl, result_mail_tbl);
                if (err_code != NULL)
                        *err_code = EMAIL_ERROR_INVALID_PARAM;
                return false;
@@ -2434,14 +2598,14 @@ INTERNAL_FUNC int emstorage_query_mail_tbl(const char *conditional_clause, int t
 
        SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT * FROM mail_tbl %s", conditional_clause);
 
-       EM_DEBUG_LOG("Query [%s]", sql_query_string);
+       EM_DEBUG_LOG_DEV ("Query[%s]", sql_query_string);
 
        EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql_query_string, &result, &count, 0, NULL), rc);
        EM_DEBUG_DB_EXEC((SQLITE_OK != rc && -1 != rc), {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
-               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+               ("sqlite3_get_table failed [%d] [%s]", rc, sql_query_string));
 
        if (!count) {
-               EM_DEBUG_EXCEPTION("No mail found...");
+               EM_DEBUG_LOG("No mail found...");
                ret = false;
                error= EMAIL_ERROR_MAIL_NOT_FOUND;
                goto FINISH_OFF;
@@ -2454,7 +2618,7 @@ INTERNAL_FUNC int emstorage_query_mail_tbl(const char *conditional_clause, int t
                goto FINISH_OFF;
        }
 
-       EM_DEBUG_LOG(">>>> DATA ASSIGN START >> ");
+       EM_DEBUG_LOG_DEV (">>>> DATA ASSIGN START >> ");
        for (i = 0; i < count; i++) {
                _get_table_field_data_int   (result, &(p_data_tbl[i].mail_id), col_index++);
                _get_table_field_data_int   (result, &(p_data_tbl[i].account_id), col_index++);
@@ -2504,27 +2668,12 @@ INTERNAL_FUNC int emstorage_query_mail_tbl(const char *conditional_clause, int t
                _get_table_field_data_int   (result, (int*)&(p_data_tbl[i].digest_type), col_index++);
                _get_table_field_data_int   (result, (int*)&(p_data_tbl[i].smime_type), col_index++);
                _get_table_field_data_int   (result, (int*)&(p_data_tbl[i].scheduled_sending_time), col_index++);
+               _get_table_field_data_int   (result, (int*)&(p_data_tbl[i].remaining_resend_times), col_index++);
+               _get_table_field_data_int   (result, (int*)&(p_data_tbl[i].tag_id), col_index++);
+               _get_table_field_data_int   (result, (int*)&(p_data_tbl[i].replied_time), col_index++);
+               _get_table_field_data_int   (result, (int*)&(p_data_tbl[i].forwarded_time), col_index++);
                _get_table_field_data_int   (result, (int*)&(p_data_tbl[i].eas_data_length), col_index++);
                _get_table_field_data_blob  (result, (void**)&(p_data_tbl[i].eas_data), p_data_tbl[i].eas_data_length, col_index++);
-               /*  check real body file... */
-               if (p_data_tbl[i].body_download_status) {
-                       struct stat buf;
-
-                       if (p_data_tbl[i].file_path_html && EM_SAFE_STRLEN(p_data_tbl[i].file_path_html) > 0) {
-                               if (stat(p_data_tbl[i].file_path_html, &buf) == -1) {
-                                       EM_DEBUG_LINE;
-                                       p_data_tbl[i].body_download_status = 0;
-                               }
-                       }
-                       else if (p_data_tbl[i].file_path_plain && EM_SAFE_STRLEN(p_data_tbl[i].file_path_plain) > 0) {
-                               if (stat(p_data_tbl[i].file_path_plain, &buf) == -1){
-                                       EM_DEBUG_LINE;
-                                       p_data_tbl[i].body_download_status = 0;
-                               }
-                       }
-                       else
-                               p_data_tbl[i].body_download_status = 0;
-               }
        }
 
        ret = true;
@@ -2533,17 +2682,18 @@ FINISH_OFF:
        if(result)
                sqlite3_free_table(result);
 
-       if (ret == true)  {
-               if (result_mail_tbl)
-                       *result_mail_tbl = p_data_tbl;
+       if (ret)  {
+               *result_mail_tbl = p_data_tbl;
                *result_count = count;
        }
-       else
-               EM_SAFE_FREE(p_data_tbl);
+       else {
+               *result_mail_tbl = NULL;
+               *result_count = 0;
+       }
 
        EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
 
-       sqlite3_release_memory(-1);
+       sqlite3_db_release_memory(local_db_handle);
 
        _DISCONNECT_DB;
 
@@ -2559,7 +2709,7 @@ INTERNAL_FUNC int emstorage_query_mail_text_tbl(const char *conditional_clause,
 {
        EM_DEBUG_FUNC_BEGIN("conditional_clause[%s], result_mail_text_tbl[%p], result_count [%p], transaction[%d], err_code[%p]", conditional_clause, result_mail_text_tbl, result_count, transaction, err_code);
 
-       if (!conditional_clause) {
+       if (!conditional_clause || !result_mail_text_tbl || !result_count) { /*prevent 50930*/
                EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
                if (err_code != NULL)
                        *err_code = EMAIL_ERROR_INVALID_PARAM;
@@ -2588,7 +2738,7 @@ INTERNAL_FUNC int emstorage_query_mail_text_tbl(const char *conditional_clause,
                ("SQL(%s) sqlite3_get_table fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
 
        if (!count) {
-               EM_DEBUG_EXCEPTION("No mail found...");
+               EM_DEBUG_LOG("No mail found...");
                ret = false;
                error= EMAIL_ERROR_MAIL_NOT_FOUND;
                goto FINISH_OFF;
@@ -2601,7 +2751,7 @@ INTERNAL_FUNC int emstorage_query_mail_text_tbl(const char *conditional_clause,
                goto FINISH_OFF;
        }
 
-       EM_DEBUG_LOG(">>>> DATA ASSIGN START >>");
+       EM_DEBUG_LOG_DEV (">>>> DATA ASSIGN START >>");
        for (i = 0; i < count; i++) {
                _get_table_field_data_int(result, &(p_data_tbl[i].mail_id), col_index++);
                _get_table_field_data_int(result, &(p_data_tbl[i].account_id), col_index++);
@@ -2615,7 +2765,7 @@ FINISH_OFF:
        if(result)
                sqlite3_free_table(result);
 
-       if (ret == true && result_mail_text_tbl && result_count) { /*prevent 50930*/
+       if (ret == true) {
                *result_mail_text_tbl = p_data_tbl;
                *result_count = count;
        }
@@ -2624,7 +2774,7 @@ FINISH_OFF:
 
        EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
 
-       sqlite3_release_memory(-1);
+       sqlite3_db_release_memory(local_db_handle);
 
        _DISCONNECT_DB;
 
@@ -2649,31 +2799,31 @@ INTERNAL_FUNC int emstorage_query_mailbox_tbl(const char *input_conditional_clau
        int total_count = 0;
        char **result;
        char sql_query_string[QUERY_SIZE] = {0, };
-       char *fields = "MBT.mailbox_id, MBT.account_id, local_yn, MBT.mailbox_name, MBT.mailbox_type, alias, deleted_flag, modifiable_yn, total_mail_count_on_server, has_archived_mails, mail_slot_size, no_select, last_sync_time ";
+       char *fields = "MBT.mailbox_id, MBT.account_id, local_yn, MBT.mailbox_name, MBT.mailbox_type, alias, deleted_flag, modifiable_yn, total_mail_count_on_server, has_archived_mails, mail_slot_size, no_select, last_sync_time, MBT.eas_data_length, MBT.eas_data ";
        emstorage_mailbox_tbl_t* p_data_tbl = NULL;
        sqlite3 *local_db_handle = emstorage_get_db_connection();
 
        EMSTORAGE_START_READ_TRANSACTION(input_transaction);
 
        if (input_get_mail_count == 0) {        /* without mail count */
-               col_index = 13;
+               col_index = 15;
                SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT %s FROM mail_box_tbl AS MBT %s %s", fields, input_conditional_clause, input_ordering_clause);
        }
        else {  /* with read count and total count */
-               col_index = 15;
-               SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT %s, total, read  FROM mail_box_tbl AS MBT LEFT OUTER JOIN (SELECT mailbox_id, count(mail_id) AS total, SUM(flags_seen_field) AS read FROM mail_tbl %s GROUP BY mailbox_id) AS MT ON MBT.mailbox_id = MT.mailbox_id %s %s", fields, input_conditional_clause, input_conditional_clause, input_ordering_clause);
+               col_index = 17;
+               SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT %s, total, read  FROM mail_box_tbl AS MBT LEFT OUTER JOIN (SELECT mailbox_id, count(mail_id) AS total, SUM(flags_seen_field) AS read FROM mail_tbl GROUP BY mailbox_id) AS MT ON MBT.mailbox_id = MT.mailbox_id %s %s", fields, input_conditional_clause, input_ordering_clause);
        }
 
-       EM_DEBUG_LOG("query[%s]", sql_query_string);
+       EM_DEBUG_LOG_DEV ("query[%s]", sql_query_string);
 
        EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql_query_string, &result, &count, NULL, NULL), rc);
        EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
-               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)))
+               ("sqlite3_get_table failed [%d] [%s]", rc, sql_query_string))
 
-       EM_DEBUG_LOG("result count [%d]", count);
+       EM_DEBUG_LOG_DEV ("result count [%d]", count);
 
        if(count == 0) {
-               EM_DEBUG_EXCEPTION("Can't find mailbox");
+               EM_DEBUG_LOG ("Can't find mailbox");
                error = EMAIL_ERROR_MAILBOX_NOT_FOUND;
                goto FINISH_OFF;
        }
@@ -2698,6 +2848,8 @@ INTERNAL_FUNC int emstorage_query_mailbox_tbl(const char *input_conditional_clau
                _get_table_field_data_int(result, &(p_data_tbl[i].mail_slot_size), col_index++);
                _get_table_field_data_int(result, &(p_data_tbl[i].no_select), col_index++);
                _get_table_field_data_int(result, (int*)&(p_data_tbl[i].last_sync_time), col_index++);
+               _get_table_field_data_int(result, (int*)&(p_data_tbl[i].eas_data_length), col_index++);
+               _get_table_field_data_blob(result, (void**)&(p_data_tbl[i].eas_data), p_data_tbl[i].eas_data_length, col_index++);
 
                if (input_get_mail_count == 1) {
                        _get_table_field_data_int(result, &(total_count), col_index++);
@@ -2715,12 +2867,12 @@ FINISH_OFF:
        if (error == EMAIL_ERROR_NONE)  {
                *output_mailbox_list = p_data_tbl;
                *output_mailbox_count = count;
-               EM_DEBUG_LOG("Mailbox Count [ %d]", count);
+               EM_DEBUG_LOG("Mailbox Count [%d]", count);
        }
 
        EMSTORAGE_FINISH_READ_TRANSACTION(input_transaction);
 
-       sqlite3_release_memory(-1);
+       sqlite3_db_release_memory(local_db_handle);
 
        _DISCONNECT_DB;
 
@@ -2733,20 +2885,22 @@ FINISH_OFF:
 INTERNAL_FUNC int emstorage_check_duplicated_account(email_account_t* account, int transaction, int *err_code)
 {
        EM_DEBUG_FUNC_BEGIN();
+       int rc = -1, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char **result;
+       int count;
+       char sql_query_string[QUERY_SIZE] = {0, };
+       sqlite3 *local_db_handle = NULL;
 
-       if (!account)  {
+       if (account == NULL || account->user_email_address == NULL || account->incoming_server_user_name == NULL || account->incoming_server_address == NULL||
+               account->outgoing_server_user_name == NULL || account->outgoing_server_address == NULL)  {
                if (err_code != NULL)
                        *err_code = EMAIL_ERROR_INVALID_PARAM;
                return false;
        }
 
-       int rc = -1, ret = false;
-       int error = EMAIL_ERROR_NONE;
-       char **result;
-       int count;
-       char sql_query_string[QUERY_SIZE] = {0, };
+       local_db_handle = emstorage_get_db_connection();
 
-       sqlite3 *local_db_handle = emstorage_get_db_connection();
        EMSTORAGE_START_READ_TRANSACTION(transaction);
 
        SNPRINTF(sql_query_string, sizeof(sql_query_string),
@@ -2775,11 +2929,11 @@ INTERNAL_FUNC int emstorage_check_duplicated_account(email_account_t* account, i
 
        if (count == 0) {       /*  not duplicated account */
                ret = true;
-               EM_DEBUG_LOG("NOT duplicated account: user_email_address[%s]", account->user_email_address);
+               EM_DEBUG_LOG_SEC("NOT duplicated account: user_email_address[%s]", account->user_email_address);
        }
        else {  /*  duplicated account */
                ret = false;
-               EM_DEBUG_LOG("The same account already exists. Duplicated account: user_email_address[%s]", account->user_email_address);
+               EM_DEBUG_LOG_SEC("The same account already exists. Duplicated account: user_email_address[%s]", account->user_email_address);
                error = EMAIL_ERROR_ALREADY_EXISTS;
        }
 
@@ -2816,8 +2970,9 @@ INTERNAL_FUNC int emstorage_get_account_count(int *count, int transaction, int *
        sqlite3 *local_db_handle = emstorage_get_db_connection();
        EMSTORAGE_START_READ_TRANSACTION(transaction);
        SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT COUNT(*) FROM mail_account_tbl");
-       EM_DEBUG_LOG("SQL STMT [ %s ]", sql_query_string);
-       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+       EM_DEBUG_LOG("SQL STMT [%s]", sql_query_string);
+       EMSTORAGE_PROTECTED_FUNC_CALL (sqlite3_prepare_v2 (local_db_handle, sql_query_string, 
+                                                          EM_SAFE_STRLEN (sql_query_string), &hStmt, NULL), rc);
        EM_DEBUG_LOG("Before sqlite3_prepare hStmt = %p", hStmt);
        EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
                ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
@@ -2886,10 +3041,10 @@ INTERNAL_FUNC int emstorage_get_account_list(int *select_num, emstorage_account_
        count = atoi(result[1]);
        sqlite3_free_table(result);
 
-       EM_DEBUG_LOG("count = %d", rc);
+       EM_DEBUG_LOG_DEV("count = %d", rc);
 
        if (count == 0) {
-               EM_DEBUG_EXCEPTION("no account found...");
+               EM_DEBUG_LOG("no account found...");
                error = EMAIL_ERROR_ACCOUNT_NOT_FOUND;
                ret = true;
                goto FINISH_OFF;
@@ -2898,7 +3053,7 @@ INTERNAL_FUNC int emstorage_get_account_list(int *select_num, emstorage_account_
 
        EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
 
-       EM_DEBUG_LOG("After sqlite3_prepare_v2 hStmt = %p", hStmt);
+       EM_DEBUG_LOG_DEV ("After sqlite3_prepare_v2 hStmt = %p", hStmt);
        EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
                ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
 
@@ -2932,6 +3087,7 @@ INTERNAL_FUNC int emstorage_get_account_list(int *select_num, emstorage_account_
                _get_stmt_field_data_int(hStmt, (int*)&(p_data_tbl[i].sync_status), field_index++);
                _get_stmt_field_data_int(hStmt, (int*)&(p_data_tbl[i].sync_disabled), field_index++);
                _get_stmt_field_data_int(hStmt, (int*)&(p_data_tbl[i].default_mail_slot_size), field_index++);
+               _get_stmt_field_data_int(hStmt, (int*)&(p_data_tbl[i].roaming_option), field_index++);
                _get_stmt_field_data_string(hStmt, &(p_data_tbl[i].user_display_name), 0, field_index++);
                _get_stmt_field_data_string(hStmt, &(p_data_tbl[i].user_email_address), 0, field_index++);
                _get_stmt_field_data_string(hStmt, &(p_data_tbl[i].reply_to_address), 0, field_index++);
@@ -2942,10 +3098,15 @@ INTERNAL_FUNC int emstorage_get_account_list(int *select_num, emstorage_account_
                _get_stmt_field_data_string(hStmt, &(p_data_tbl[i].incoming_server_user_name), 0, field_index++);
                _get_stmt_field_data_string(hStmt, &(p_data_tbl[i].incoming_server_password), 0, field_index++);
                _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].incoming_server_secure_connection), field_index++);
+               _get_stmt_field_data_int(hStmt, (int *)&(p_data_tbl[i].incoming_server_authentication_method), field_index++);
                _get_stmt_field_data_int(hStmt, (int*)&(p_data_tbl[i].retrieval_mode), field_index++);
                _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].keep_mails_on_pop_server_after_download), field_index++);
                _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].check_interval), field_index++);
                _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].auto_download_size), field_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].peak_interval), field_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].peak_days), field_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].peak_start_time), field_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].peak_end_time), field_index++);
                _get_stmt_field_data_int(hStmt, (int*)&(p_data_tbl[i].outgoing_server_type), field_index++);
                _get_stmt_field_data_string(hStmt, &(p_data_tbl[i].outgoing_server_address), 0, field_index++);
                _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].outgoing_server_port_number), field_index++);
@@ -2968,6 +3129,8 @@ INTERNAL_FUNC int emstorage_get_account_list(int *select_num, emstorage_account_
                _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].options.add_signature), field_index++);
                _get_stmt_field_data_string(hStmt, &(p_data_tbl[i].options.signature), 0, field_index++);
                _get_stmt_field_data_int(hStmt, (int*)&(p_data_tbl[i].options.add_my_address_to_bcc), field_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].auto_resend_times), field_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].outgoing_server_size_limit), field_index++);
                _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].pop_before_smtp), field_index++);
                _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].incoming_server_requires_apop), field_index++);
                _get_stmt_field_data_int(hStmt, (int *)&(p_data_tbl[i].smime_type), field_index++);
@@ -2975,7 +3138,8 @@ INTERNAL_FUNC int emstorage_get_account_list(int *select_num, emstorage_account_
                _get_stmt_field_data_int(hStmt, (int *)&(p_data_tbl[i].cipher_type), field_index++);
                _get_stmt_field_data_int(hStmt, (int *)&(p_data_tbl[i].digest_type), field_index++);
 
-               if (with_password == true) {
+               /* EAS passwd is not accessible */
+               if (with_password == true && p_data_tbl[i].incoming_server_type != EMAIL_SERVER_TYPE_ACTIVE_SYNC) {
                        /*  get password from the secure storage */
                        char recv_password_file_name[MAX_PW_FILE_NAME_LENGTH];
                        char send_password_file_name[MAX_PW_FILE_NAME_LENGTH];
@@ -3005,7 +3169,7 @@ INTERNAL_FUNC int emstorage_get_account_list(int *select_num, emstorage_account_
                }
 
                EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
-               EM_DEBUG_LOG("after sqlite3_step(), i = %d, rc = %d.", i,  rc);
+               EM_DEBUG_LOG_DEV("after sqlite3_step(), i = %d, rc = %d.", i,  rc);
                EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
                        ("sqlite3_step fail:%d", rc));
        }
@@ -3016,13 +3180,13 @@ FINISH_OFF:
        if (ret == true)  {
                *account_list = p_data_tbl;
                *select_num = count;
-               EM_DEBUG_LOG("COUNT : %d", count);
+               EM_DEBUG_LOG_DEV("COUNT : %d", count);
        }
        else if (p_data_tbl != NULL)
                emstorage_free_account(&p_data_tbl, count, NULL);
 
        if (hStmt != NULL)  {
-               EM_DEBUG_LOG("Before sqlite3_finalize hStmt = %p", hStmt);
+               EM_DEBUG_LOG_DEV("Before sqlite3_finalize hStmt = %p", hStmt);
 
                rc = sqlite3_finalize(hStmt);
                hStmt = NULL;
@@ -3045,7 +3209,7 @@ FINISH_OFF:
 
 INTERNAL_FUNC int emstorage_get_maildata_by_servermailid(int mailbox_id, char *server_mail_id, emstorage_mail_tbl_t** mail, int transaction, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("mailbox_id [%d], server_mail_id[%s], mail[%p], transaction[%d], err_code[%p]", mailbox_id, server_mail_id, mail, transaction, err_code);
+       EM_DEBUG_FUNC_BEGIN_SEC("mailbox_id [%d], server_mail_id[%s], mail[%p], transaction[%d], err_code[%p]", mailbox_id, server_mail_id, mail, transaction, err_code);
 
        int ret = false, error = EMAIL_ERROR_NONE, result_count;
        char conditional_clause[QUERY_SIZE] = {0, };
@@ -3396,7 +3560,7 @@ static int _get_password_file_name(int account_id, char *recv_password_file_name
 
 static int _read_password_from_secure_storage(char *file_name, char **password)
 {
-       EM_DEBUG_FUNC_BEGIN("file_name[%s], password[%p]", file_name, password);
+       EM_DEBUG_FUNC_BEGIN_SEC("file_name[%s]", file_name);
 
        if (!file_name || !password) {
                EM_DEBUG_EXCEPTION("Invalid Parameter");
@@ -3416,7 +3580,7 @@ static int _read_password_from_secure_storage(char *file_name, char **password)
        }
 
        buf_len = sfi.originSize;
-       EM_DEBUG_LOG("password buf_len[%d]", buf_len);
+       EM_DEBUG_LOG_DEV ("password buf_len[%d]", buf_len);
        if ((temp_password = (char *)malloc(buf_len + 1)) == NULL) {
                EM_DEBUG_EXCEPTION("malloc failed...");
                ret = EMAIL_ERROR_OUT_OF_MEMORY;
@@ -3430,7 +3594,7 @@ static int _read_password_from_secure_storage(char *file_name, char **password)
                goto FINISH_OFF;
        }
 
-       EM_DEBUG_LOG("password_file_name[%s], password[%s], originSize[%d], read len[%d]", file_name,  temp_password, sfi.originSize, read_len);
+       EM_DEBUG_LOG_DEV("password_file_name[%s], password[%s], originSize[%d], read len[%d]", file_name,  temp_password, sfi.originSize, read_len);
 
        *password = temp_password;
        temp_password = NULL;
@@ -3480,6 +3644,7 @@ INTERNAL_FUNC int emstorage_get_account_by_id(int account_id, int pulloption, em
                        "retrieval_mode,"
                        "incoming_server_port_number,"
                        "incoming_server_secure_connection,"
+                       "incoming_server_authentication_method,"
                        "outgoing_server_type,"
                        "outgoing_server_address,"
                        "outgoing_server_port_number,"
@@ -3492,7 +3657,13 @@ INTERNAL_FUNC int emstorage_get_account_by_id(int account_id, int pulloption, em
                        "account_id,"
                        "keep_mails_on_pop_server_after_download,"
                        "auto_download_size,"
+                       "peak_interval,"
+                       "peak_days,"
+                       "peak_start_time,"
+                       "peak_end_time,"
                        "outgoing_server_use_same_authenticator,"
+                       "auto_resend_times,"
+                       "outgoing_server_size_limit,"
                        "pop_before_smtp,"
                        "incoming_server_requires_apop,"
                        "logo_icon_path,"
@@ -3528,6 +3699,7 @@ INTERNAL_FUNC int emstorage_get_account_by_id(int account_id, int pulloption, em
                        "account_svc_id,"
                        "sync_disabled,"
                        "default_mail_slot_size,"
+                       "roaming_option,"
                        "smime_type,"
                        "certificate_path,"
                        "cipher_type,"
@@ -3575,6 +3747,7 @@ INTERNAL_FUNC int emstorage_get_account_by_id(int account_id, int pulloption, em
                _get_stmt_field_data_int(hStmt, (int*)&(p_data_tbl->retrieval_mode), col_index++);
                _get_stmt_field_data_int(hStmt, &(p_data_tbl->incoming_server_port_number), col_index++);
                _get_stmt_field_data_int(hStmt, &(p_data_tbl->incoming_server_secure_connection), col_index++);
+               _get_stmt_field_data_int(hStmt, (int*)&(p_data_tbl->incoming_server_authentication_method), col_index++);
                _get_stmt_field_data_int(hStmt, (int*)&(p_data_tbl->outgoing_server_type), col_index++);
                _get_stmt_field_data_string(hStmt, &(p_data_tbl->outgoing_server_address), 0, col_index++);
                _get_stmt_field_data_int(hStmt, &(p_data_tbl->outgoing_server_port_number), col_index++);
@@ -3587,7 +3760,13 @@ INTERNAL_FUNC int emstorage_get_account_by_id(int account_id, int pulloption, em
                _get_stmt_field_data_int(hStmt, &(p_data_tbl->account_id), col_index++);
                _get_stmt_field_data_int(hStmt, &(p_data_tbl->keep_mails_on_pop_server_after_download), col_index++);
                _get_stmt_field_data_int(hStmt, &(p_data_tbl->auto_download_size), col_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl->peak_interval), col_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl->peak_days), col_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl->peak_start_time), col_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl->peak_end_time), col_index++);
                _get_stmt_field_data_int(hStmt, &(p_data_tbl->outgoing_server_use_same_authenticator), col_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl->auto_resend_times), col_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl->outgoing_server_size_limit), col_index++);
                _get_stmt_field_data_int(hStmt, &(p_data_tbl->pop_before_smtp), col_index++);
                _get_stmt_field_data_int(hStmt, &(p_data_tbl->incoming_server_requires_apop), col_index++);
                _get_stmt_field_data_string(hStmt, &(p_data_tbl->logo_icon_path), 0, col_index++);
@@ -3603,23 +3782,23 @@ INTERNAL_FUNC int emstorage_get_account_by_id(int account_id, int pulloption, em
        if (pulloption & EMAIL_ACC_GET_OPT_PASSWORD) {
                /*  get password file name */
                if ((error = _get_password_file_name(p_data_tbl->account_id, recv_password_file_name, send_password_file_name)) != EMAIL_ERROR_NONE) {
-                       EM_DEBUG_EXCEPTION("_get_password_file_name failed. [%d]", error);
+                       EM_DEBUG_EXCEPTION("_get_password_file_name failed [%d]", error);
                        goto FINISH_OFF;
                }
 
                /*  read password from secure storage */
                if ((error = _read_password_from_secure_storage(recv_password_file_name, &(p_data_tbl->incoming_server_password))) < 0) {
-                       EM_DEBUG_EXCEPTION(" _read_password_from_secure_storage()  failed. [%d]", error);
+                       EM_DEBUG_EXCEPTION(" _read_password_from_secure_storage failed [%d]", error);
                        goto FINISH_OFF;
                }
 
-               EM_DEBUG_LOG("recv_password_file_name[%s], password[%s]", recv_password_file_name,  p_data_tbl->incoming_server_password);
+               EM_DEBUG_LOG_DEV ("recv_password_file_name[%s], password[%s]", recv_password_file_name,  p_data_tbl->incoming_server_password);
 
                if ((error = _read_password_from_secure_storage(send_password_file_name, &(p_data_tbl->outgoing_server_password))) < 0) {
-                       EM_DEBUG_EXCEPTION(" _read_password_from_secure_storage()  failed. [%d]", error);
+                       EM_DEBUG_EXCEPTION(" _read_password_from_secure_storage failed [%d]", error);
                        goto FINISH_OFF;
                }
-               EM_DEBUG_LOG("send_password_file_name[%s], password[%s]", send_password_file_name,  p_data_tbl->outgoing_server_password);
+               EM_DEBUG_LOG_DEV ("send_password_file_name[%s], password[%s]", send_password_file_name,  p_data_tbl->outgoing_server_password);
        }
 
        if (pulloption & EMAIL_ACC_GET_OPT_OPTIONS) {
@@ -3640,6 +3819,7 @@ INTERNAL_FUNC int emstorage_get_account_by_id(int account_id, int pulloption, em
                _get_stmt_field_data_int(hStmt, &(p_data_tbl->account_svc_id), col_index++);
                _get_stmt_field_data_int(hStmt, (int*)&(p_data_tbl->sync_disabled), col_index++);
                _get_stmt_field_data_int(hStmt, (int*)&(p_data_tbl->default_mail_slot_size), col_index++);
+               _get_stmt_field_data_int(hStmt, (int*)&(p_data_tbl->roaming_option), col_index++);
                _get_stmt_field_data_int(hStmt, (int *)&(p_data_tbl->smime_type), col_index++);
                _get_stmt_field_data_string(hStmt, &(p_data_tbl->certificate_path), 0, col_index++);
                _get_stmt_field_data_int(hStmt, (int *)&(p_data_tbl->cipher_type), col_index++);
@@ -3673,7 +3853,7 @@ FINISH_OFF:
        return ret;
 }
 
-INTERNAL_FUNC int emstorage_get_password_length_of_account(int account_id, int *password_length, int *err_code)
+INTERNAL_FUNC int emstorage_get_password_length_of_account(int account_id, int password_type, int *password_length, int *err_code)
 {
        EM_DEBUG_FUNC_BEGIN("account_id[%d], password_length[%p], err_code[%p]", account_id, password_length, err_code);
 
@@ -3698,14 +3878,26 @@ INTERNAL_FUNC int emstorage_get_password_length_of_account(int account_id, int *
        }
 
        /*  read password from secure storage */
-       if ((error = _read_password_from_secure_storage(recv_password_file_name, &temp_password)) < 0 || !temp_password) {
-               EM_DEBUG_EXCEPTION(" _read_password_from_secure_storage()  failed...");
+       if (password_type == EMAIL_GET_INCOMING_PASSWORD_LENGTH) {
+               if ((error = _read_password_from_secure_storage(recv_password_file_name, &temp_password)) < 0 || !temp_password) {
+                       EM_DEBUG_EXCEPTION(" _read_password_from_secure_storage()  failed...");
+                       goto FINISH_OFF;
+               }
+       } else if (password_type == EMAIL_GET_OUTGOING_PASSWORD_LENGTH) {
+               if ((error = _read_password_from_secure_storage(send_password_file_name, &temp_password)) < 0 || !temp_password) {
+                       EM_DEBUG_EXCEPTION(" _read_password_from_secure_storage()  failed...");
+                       goto FINISH_OFF;
+               }
+       } else {
+               EM_DEBUG_LOG("Invalid password type");
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
                goto FINISH_OFF;
        }
 
        *password_length = EM_SAFE_STRLEN(temp_password);
 
-       EM_DEBUG_LOG("recv_password_file_name[%s], *password_length[%d]", recv_password_file_name,  *password_length);
+       EM_DEBUG_LOG_SEC("recv_password_file_name[%s], *password_length[%d]", recv_password_file_name,  *password_length);
 
        ret = true;
 
@@ -3719,6 +3911,61 @@ FINISH_OFF:
        return ret;
 }
 
+INTERNAL_FUNC int emstorage_update_account_password(int input_account_id, char *input_incoming_server_password, char *input_outgoing_server_password)
+{
+       EM_DEBUG_FUNC_BEGIN("input_account_id[%d], input_incoming_server_password[%p], input_outgoing_server_password[%p]", input_account_id, input_incoming_server_password, input_outgoing_server_password);
+
+       int err = EMAIL_ERROR_NONE;
+       int err_from_ssm = 0;
+       char recv_password_file_name[MAX_PW_FILE_NAME_LENGTH];
+       char send_password_file_name[MAX_PW_FILE_NAME_LENGTH];
+
+       if(input_incoming_server_password == NULL || input_outgoing_server_password == NULL) {
+               EM_DEBUG_EXCEPTION_SEC("Invalid param");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       /*  get password file name */
+       if ((err = _get_password_file_name(input_account_id, recv_password_file_name, send_password_file_name)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("_get_password_file_name failed.");
+               goto FINISH_OFF;
+       }
+
+       EM_DEBUG_LOG_SEC("recv_password_file_name [%s] input_incoming_server_password [%s]", recv_password_file_name, input_incoming_server_password);
+       EM_DEBUG_LOG_SEC("send_password_file_name [%s] input_outgoing_server_password [%s]", send_password_file_name, input_outgoing_server_password);
+
+       if ((err_from_ssm = ssm_delete_file(recv_password_file_name,  SSM_FLAG_SECRET_OPERATION, NULL)) < 0) {
+               EM_DEBUG_EXCEPTION_SEC(" ssm_delete_file failed -recv password : file[%s]", recv_password_file_name);
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       /*  save passwords to the secure storage */
+       if ((err_from_ssm = ssm_write_buffer(input_incoming_server_password, EM_SAFE_STRLEN(input_incoming_server_password), recv_password_file_name, SSM_FLAG_SECRET_OPERATION, NULL)) < 0) {
+               EM_DEBUG_EXCEPTION_SEC(" ssm_write_buffer failed [%d] -recv incoming_server_password : file[%s]", err_from_ssm, recv_password_file_name);
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       if ((err_from_ssm = ssm_delete_file(send_password_file_name,  SSM_FLAG_SECRET_OPERATION, NULL)) < 0) {
+               EM_DEBUG_EXCEPTION_SEC(" ssm_delete_file failed -send password : file[%s]", send_password_file_name);
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       if ((err_from_ssm = ssm_write_buffer(input_outgoing_server_password, EM_SAFE_STRLEN(input_outgoing_server_password), send_password_file_name, SSM_FLAG_SECRET_OPERATION, NULL)) < 0) {
+               EM_DEBUG_EXCEPTION_SEC(" ssm_write_buffer failed [%d] -send password : file[%s]", err_from_ssm, send_password_file_name);
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+FINISH_OFF:
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
 INTERNAL_FUNC int emstorage_update_account(int account_id, emstorage_account_tbl_t* account_tbl, int transaction, int *err_code)
 {
        EM_DEBUG_FUNC_BEGIN("account_id[%d], account[%p], transaction[%d], err_code[%p]", account_id, account_tbl, transaction, err_code);
@@ -3735,8 +3982,6 @@ INTERNAL_FUNC int emstorage_update_account(int account_id, emstorage_account_tbl
 
        DB_STMT hStmt = NULL;
        char sql_query_string[QUERY_SIZE] = {0, };
-       char recv_password_file_name[MAX_PW_FILE_NAME_LENGTH];
-       char send_password_file_name[MAX_PW_FILE_NAME_LENGTH];
 
        sqlite3 *local_db_handle = emstorage_get_db_connection();
        EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
@@ -3751,6 +3996,7 @@ INTERNAL_FUNC int emstorage_update_account(int account_id, emstorage_account_tbl
                ", sync_status = ?"
                ", sync_disabled = ?"
                ", default_mail_slot_size = ?"
+               ", roaming_option = ?"
                ", user_display_name = ?"
                ", user_email_address = ?"
                ", reply_to_address = ?"
@@ -3760,10 +4006,15 @@ INTERNAL_FUNC int emstorage_update_account(int account_id, emstorage_account_tbl
                ", incoming_server_port_number = ?"
                ", incoming_server_user_name = ?"
                ", incoming_server_secure_connection = ?"
+               ", incoming_server_authentication_method = ?"
                ", retrieval_mode = ?"
                ", keep_mails_on_pop_server_after_download = ?"
                ", check_interval = ?"
                ", auto_download_size = ?"
+               ", peak_interval = ?"
+               ", peak_days = ?"
+               ", peak_start_time = ?"
+               ", peak_end_time = ?"
                ", outgoing_server_type = ?"
                ", outgoing_server_address = ?"
                ", outgoing_server_port_number = ?"
@@ -3785,6 +4036,8 @@ INTERNAL_FUNC int emstorage_update_account(int account_id, emstorage_account_tbl
                ", add_signature = ?"
                ", signature = ?"
                ", add_my_address_to_bcc = ?"
+               ", auto_resend_times = ?"
+               ", outgoing_server_size_limit = ?"
                ", pop_before_smtp = ?"
                ", incoming_server_requires_apop = ?"
                ", smime_type = ?"
@@ -3809,6 +4062,7 @@ INTERNAL_FUNC int emstorage_update_account(int account_id, emstorage_account_tbl
        _bind_stmt_field_data_int(hStmt, i++, account_tbl->sync_status);
        _bind_stmt_field_data_int(hStmt, i++, account_tbl->sync_disabled);
        _bind_stmt_field_data_int(hStmt, i++, account_tbl->default_mail_slot_size);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->roaming_option);
        _bind_stmt_field_data_string(hStmt, i++, (char *)account_tbl->user_display_name, 0, DISPLAY_NAME_LEN_IN_MAIL_ACCOUNT_TBL);
        _bind_stmt_field_data_string(hStmt, i++, (char *)account_tbl->user_email_address, 0, EMAIL_ADDR_LEN_IN_MAIL_ACCOUNT_TBL);
        _bind_stmt_field_data_string(hStmt, i++, (char *)account_tbl->reply_to_address, 0, REPLY_TO_ADDR_LEN_IN_MAIL_ACCOUNT_TBL);
@@ -3818,10 +4072,15 @@ INTERNAL_FUNC int emstorage_update_account(int account_id, emstorage_account_tbl
        _bind_stmt_field_data_int(hStmt, i++, account_tbl->incoming_server_port_number);
        _bind_stmt_field_data_string(hStmt, i++, (char *)account_tbl->incoming_server_user_name, 0, USER_NAME_LEN_IN_MAIL_ACCOUNT_TBL);
        _bind_stmt_field_data_int(hStmt, i++, account_tbl->incoming_server_secure_connection);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->incoming_server_authentication_method);
        _bind_stmt_field_data_int(hStmt, i++, account_tbl->retrieval_mode);
        _bind_stmt_field_data_int(hStmt, i++, account_tbl->keep_mails_on_pop_server_after_download);
        _bind_stmt_field_data_int(hStmt, i++, account_tbl->check_interval);
        _bind_stmt_field_data_int(hStmt, i++, account_tbl->auto_download_size);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->peak_interval);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->peak_days);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->peak_start_time);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->peak_end_time);
        _bind_stmt_field_data_int(hStmt, i++, account_tbl->outgoing_server_type);
        _bind_stmt_field_data_string(hStmt, i++, (char *)account_tbl->outgoing_server_address, 0, SENDING_SERVER_ADDR_LEN_IN_MAIL_ACCOUNT_TBL);
        _bind_stmt_field_data_int(hStmt, i++, account_tbl->outgoing_server_port_number);
@@ -3843,6 +4102,8 @@ INTERNAL_FUNC int emstorage_update_account(int account_id, emstorage_account_tbl
        _bind_stmt_field_data_int(hStmt, i++, account_tbl->options.add_signature);
        _bind_stmt_field_data_string(hStmt, i++, account_tbl->options.signature, 0, SIGNATURE_LEN_IN_MAIL_ACCOUNT_TBL);
        _bind_stmt_field_data_int(hStmt, i++, account_tbl->options.add_my_address_to_bcc);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->auto_resend_times);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->outgoing_server_size_limit);
        _bind_stmt_field_data_int(hStmt, i++, account_tbl->pop_before_smtp);
        _bind_stmt_field_data_int(hStmt, i++, account_tbl->incoming_server_requires_apop);
        _bind_stmt_field_data_int(hStmt, i++, account_tbl->smime_type);
@@ -3860,41 +4121,21 @@ INTERNAL_FUNC int emstorage_update_account(int account_id, emstorage_account_tbl
        /*  validate account existence */
        rc = sqlite3_changes(local_db_handle);
        if (rc == 0) {
-               EM_DEBUG_EXCEPTION(" no matched account found...");
-
+               EM_DEBUG_EXCEPTION ("no matched account found...");
                error = EMAIL_ERROR_ACCOUNT_NOT_FOUND;
                goto FINISH_OFF;
        }
 
-       /*  get password file name */
-       if ((error = _get_password_file_name(account_id, recv_password_file_name, send_password_file_name)) != EMAIL_ERROR_NONE) {
-               EM_DEBUG_EXCEPTION("_get_password_file_name failed.");
+       if((error = emstorage_update_account_password(account_id, account_tbl->incoming_server_password, account_tbl->outgoing_server_password)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emstorage_update_account_password failed [%d]", error);
                goto FINISH_OFF;
        }
 
-       /*  save passwords to the secure storage */
-       EM_DEBUG_LOG("save to the secure storage : recv_file[%s], recv_pass[%s], send_file[%s], send_pass[%s]", recv_password_file_name, account_tbl->incoming_server_password, send_password_file_name, account_tbl->outgoing_server_password);
-       if (account_tbl->incoming_server_password && (EM_SAFE_STRLEN(account_tbl->incoming_server_password) > 0)) {
-               if (ssm_write_buffer(account_tbl->incoming_server_password, EM_SAFE_STRLEN(account_tbl->incoming_server_password), recv_password_file_name, SSM_FLAG_SECRET_OPERATION, NULL) < 0) {
-                       EM_DEBUG_EXCEPTION(" ssm_write_buffer failed -recv incoming_server_password : file[%s]", recv_password_file_name);
-                       error = EMAIL_ERROR_SYSTEM_FAILURE;
-                       goto FINISH_OFF;
-               }
-       }
-
-       if (account_tbl->outgoing_server_password && (EM_SAFE_STRLEN(account_tbl->outgoing_server_password) > 0)) {
-               if (ssm_write_buffer(account_tbl->outgoing_server_password, EM_SAFE_STRLEN(account_tbl->outgoing_server_password), send_password_file_name, SSM_FLAG_SECRET_OPERATION, NULL) < 0) {
-                       EM_DEBUG_EXCEPTION(" ssm_write_buffer failed -send password : file[%s]", send_password_file_name);
-                       error = EMAIL_ERROR_SYSTEM_FAILURE;
-                       goto FINISH_OFF;
-               }
-       }
-
-       if (!emcore_notify_storage_event(NOTI_ACCOUNT_UPDATE, account_tbl->account_id, 0, NULL, 0))
-               EM_DEBUG_EXCEPTION(" emcore_notify_storage_event[ NOTI_ACCOUNT_UPDATE] : Notification Failed >>> ");
        ret = true;
 
 FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
 
        if (hStmt != NULL)  {
                EM_DEBUG_LOG(" Before sqlite3_finalize hStmt = %p", hStmt);
@@ -3906,9 +4147,10 @@ FINISH_OFF:
                }
        }
 
-       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
-
-       _DISCONNECT_DB;
+       if (error == EMAIL_ERROR_NONE) {
+               if (!emcore_notify_storage_event (NOTI_ACCOUNT_UPDATE, account_tbl->account_id, 0, NULL, 0))
+                       EM_DEBUG_EXCEPTION(" emcore_notify_storage_event[ NOTI_ACCOUNT_UPDATE] : Notification Failed >>> ");
+       }
 
        if (err_code != NULL)
                *err_code = error;
@@ -3919,7 +4161,7 @@ FINISH_OFF:
 
 INTERNAL_FUNC int emstorage_set_field_of_accounts_with_integer_value(int account_id, char *field_name, int value, int transaction)
 {
-       EM_DEBUG_FUNC_BEGIN("account_id[%d], field_name[%s], value[%d], transaction[%d]", account_id, field_name, value, transaction);
+       EM_DEBUG_FUNC_BEGIN_SEC("account_id[%d], field_name[%s], value[%d], transaction[%d]", account_id, field_name, value, transaction);
        int error = EMAIL_ERROR_NONE;
        int rc = 0;
        int result = 0;
@@ -3952,9 +4194,10 @@ FINISH_OFF:
        EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, result, error);
        _DISCONNECT_DB;
 
-       if (!emcore_notify_storage_event(NOTI_ACCOUNT_UPDATE, account_id, 0, field_name, value))
-               EM_DEBUG_EXCEPTION("emcore_notify_storage_event failed : NOTI_ACCOUNT_UPDATE [%s,%d]", field_name, value);
-
+       if (error == EMAIL_ERROR_NONE) {
+               if (!emcore_notify_storage_event (NOTI_ACCOUNT_UPDATE, account_id, 0, field_name, value))
+                       EM_DEBUG_EXCEPTION_SEC("emcore_notify_storage_event failed : NOTI_ACCOUNT_UPDATE [%s,%d]", field_name, value);
+       }
        EM_DEBUG_FUNC_END("error [%d]", error);
        return error;
 }
@@ -4026,7 +4269,9 @@ INTERNAL_FUNC int emstorage_update_sync_status_of_account(int account_id, email_
        if(set_operator != SET_TYPE_SET && account_id) {
                if(!emstorage_get_sync_status_of_account(account_id, &result_sync_status, &error)) {
                        EM_DEBUG_EXCEPTION("emstorage_get_sync_status_of_account failed [%d]", error);
-                       goto FINISH_OFF;
+                       if (err_code != NULL)
+                               *err_code = error;
+                       return false;
                }
                switch(set_operator) {
                        case SET_TYPE_UNION :
@@ -4064,16 +4309,17 @@ INTERNAL_FUNC int emstorage_update_sync_status_of_account(int account_id, email_
                goto FINISH_OFF;
        }
 
-       if (!emcore_notify_storage_event(NOTI_ACCOUNT_UPDATE_SYNC_STATUS, account_id, 0, NULL, 0))
-               EM_DEBUG_EXCEPTION("emcore_notify_storage_event[NOTI_ACCOUNT_UPDATE_SYNC_STATUS] : Notification failed");
        ret = true;
 
 FINISH_OFF:
-
        EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
-
        _DISCONNECT_DB;
 
+       if (error == EMAIL_ERROR_NONE) {
+               if (!emcore_notify_storage_event (NOTI_ACCOUNT_UPDATE_SYNC_STATUS, account_id, set_value, NULL, 0))
+                       EM_DEBUG_EXCEPTION("emcore_notify_storage_event[NOTI_ACCOUNT_UPDATE_SYNC_STATUS] : Notification failed");
+       }
+
        if (err_code != NULL)
                *err_code = error;
 
@@ -4136,6 +4382,7 @@ INTERNAL_FUNC int emstorage_add_account(emstorage_account_tbl_t* account_tbl, in
                "  , ? "  /*   sync_status */
                "  , ? "  /*   sync_disabled */
                "  , ? "  /*   default_mail_slot_size */
+               "  , ? "  /*   roaming_option */
                "  , ? "  /*   user_display_name */
                "  , ? "  /*   user_email_address */
                "  , ? "  /*   reply_to_address */
@@ -4146,10 +4393,15 @@ INTERNAL_FUNC int emstorage_add_account(emstorage_account_tbl_t* account_tbl, in
                "  , ? "  /*   incoming_server_user_name */
                "  , ? "  /*   incoming_server_password */
                "  , ? "  /*   incoming_server_secure_connection */
+               "  , ? "  /*   incoming_server_authentication_method */
                "  , ? "  /*   retrieval_mode */
                "  , ? "  /*   keep_mails_on_pop_server_after_download */
                "  , ? "  /*   check_interval */
                "  , ? "  /*   auto_download_size */
+               "  , ? "  /*   peak_interval */
+               "  , ? "  /*   peak_days */
+               "  , ? "  /*   peak_start_time */
+               "  , ? "  /*   peak_end_time */
                "  , ? "  /*   outgoing_server_type */
                "  , ? "  /*   outgoing_server_address */
                "  , ? "  /*   outgoing_server_port_number */
@@ -4172,6 +4424,8 @@ INTERNAL_FUNC int emstorage_add_account(emstorage_account_tbl_t* account_tbl, in
                "  , ? "  /*   add_signature */
                "  , ? "  /*   signature */
                "  , ? "  /*   add_my_address_to_bcc */
+               "  , ? "  /*   auto_resend_times */
+               "  , ? "  /*   outgoing_server_size_limit */
                "  , ? "  /*   pop_before_smtp */
                "  , ? "  /*   incoming_server_requires_apop */
                "  , ? "  /*   smime_type */
@@ -4196,6 +4450,7 @@ INTERNAL_FUNC int emstorage_add_account(emstorage_account_tbl_t* account_tbl, in
        _bind_stmt_field_data_int(hStmt, i++, account_tbl->sync_status);
        _bind_stmt_field_data_int(hStmt, i++, account_tbl->sync_disabled);
        _bind_stmt_field_data_int(hStmt, i++, account_tbl->default_mail_slot_size);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->roaming_option);
        _bind_stmt_field_data_string(hStmt, i++, (char *)account_tbl->user_display_name, 0, DISPLAY_NAME_LEN_IN_MAIL_ACCOUNT_TBL);
        _bind_stmt_field_data_string(hStmt, i++, (char *)account_tbl->user_email_address, 0, EMAIL_ADDR_LEN_IN_MAIL_ACCOUNT_TBL);
        _bind_stmt_field_data_string(hStmt, i++, (char *)account_tbl->reply_to_address, 0, REPLY_TO_ADDR_LEN_IN_MAIL_ACCOUNT_TBL);
@@ -4206,10 +4461,15 @@ INTERNAL_FUNC int emstorage_add_account(emstorage_account_tbl_t* account_tbl, in
        _bind_stmt_field_data_string(hStmt, i++, (char *)account_tbl->incoming_server_user_name, 0, USER_NAME_LEN_IN_MAIL_ACCOUNT_TBL);
        _bind_stmt_field_data_string(hStmt, i++, (char *)"", 0, PASSWORD_LEN_IN_MAIL_ACCOUNT_TBL);
        _bind_stmt_field_data_int(hStmt, i++, account_tbl->incoming_server_secure_connection);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->incoming_server_authentication_method);
        _bind_stmt_field_data_int(hStmt, i++, account_tbl->retrieval_mode);
        _bind_stmt_field_data_int(hStmt, i++, account_tbl->keep_mails_on_pop_server_after_download);
        _bind_stmt_field_data_int(hStmt, i++, account_tbl->check_interval);
        _bind_stmt_field_data_int(hStmt, i++, account_tbl->auto_download_size);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->peak_interval);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->peak_days);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->peak_start_time);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->peak_end_time);
        _bind_stmt_field_data_int(hStmt, i++, account_tbl->outgoing_server_type);
        _bind_stmt_field_data_string(hStmt, i++, (char *)account_tbl->outgoing_server_address, 0, SENDING_SERVER_ADDR_LEN_IN_MAIL_ACCOUNT_TBL);
        _bind_stmt_field_data_int(hStmt, i++, account_tbl->outgoing_server_port_number);
@@ -4232,6 +4492,8 @@ INTERNAL_FUNC int emstorage_add_account(emstorage_account_tbl_t* account_tbl, in
        _bind_stmt_field_data_int(hStmt, i++, account_tbl->options.add_signature);
        _bind_stmt_field_data_string(hStmt, i++, account_tbl->options.signature, 0, SIGNATURE_LEN_IN_MAIL_ACCOUNT_TBL);
        _bind_stmt_field_data_int(hStmt, i++, account_tbl->options.add_my_address_to_bcc);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->auto_resend_times);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->outgoing_server_size_limit);
        _bind_stmt_field_data_int(hStmt, i++, account_tbl->pop_before_smtp);
        _bind_stmt_field_data_int(hStmt, i++, account_tbl->incoming_server_requires_apop);
        _bind_stmt_field_data_int(hStmt, i++, account_tbl->smime_type);
@@ -4248,26 +4510,23 @@ INTERNAL_FUNC int emstorage_add_account(emstorage_account_tbl_t* account_tbl, in
 
 
        /*  save passwords to the secure storage */
-       EM_DEBUG_LOG("save to the secure storage : recv_file[%s], send_file[%s]", recv_password_file_name, send_password_file_name);
+       EM_DEBUG_LOG_SEC("save to the secure storage : recv_file[%s], send_file[%s]", recv_password_file_name, send_password_file_name);
        if ( (error_from_ssm = ssm_write_buffer(account_tbl->incoming_server_password, EM_SAFE_STRLEN(account_tbl->incoming_server_password), recv_password_file_name, SSM_FLAG_SECRET_OPERATION, NULL)) < 0) {
-               EM_DEBUG_EXCEPTION("ssm_write_buffer failed [%d] - recv password : file[%s]", error_from_ssm, recv_password_file_name);
+               EM_DEBUG_EXCEPTION_SEC("ssm_write_buffer failed [%d] - recv password : file[%s]", error_from_ssm, recv_password_file_name);
                error = EMAIL_ERROR_SYSTEM_FAILURE;
                goto FINISH_OFF;
        }
        if ( (error_from_ssm = ssm_write_buffer(account_tbl->outgoing_server_password, EM_SAFE_STRLEN(account_tbl->outgoing_server_password), send_password_file_name, SSM_FLAG_SECRET_OPERATION, NULL)) < 0) {
-               EM_DEBUG_EXCEPTION("ssm_write_buffer failed [%d] - send password : file[%s]", error_from_ssm, send_password_file_name);
+               EM_DEBUG_EXCEPTION_SEC("ssm_write_buffer failed [%d] - send password : file[%s]", error_from_ssm, send_password_file_name);
                error = EMAIL_ERROR_SYSTEM_FAILURE;
                goto FINISH_OFF;
        }
 
        ret = true;
 
-       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
-
-       if (!emcore_notify_storage_event(NOTI_ACCOUNT_ADD, account_tbl->account_id, 0, NULL, 0))
-               EM_DEBUG_EXCEPTION("emcore_notify_storage_event[NOTI_ACCOUNT_ADD] : Notification failed");
-
 FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
 
        if (hStmt != NULL)  {
                rc = sqlite3_finalize(hStmt);
@@ -4276,10 +4535,11 @@ FINISH_OFF:
                        error = EMAIL_ERROR_DB_FAILURE;
                }
        }
-       else
-               EM_DEBUG_LOG("hStmt is NULL!!!");
 
-       _DISCONNECT_DB;
+       if (error == EMAIL_ERROR_NONE) {
+               if (!emcore_notify_storage_event (NOTI_ACCOUNT_ADD, account_tbl->account_id, 0, NULL, 0))
+                       EM_DEBUG_EXCEPTION("emcore_notify_storage_event[NOTI_ACCOUNT_ADD] : Notification failed");
+       }
 
        if (err_code != NULL)
                *err_code = error;
@@ -4338,18 +4598,20 @@ INTERNAL_FUNC int emstorage_delete_account(int account_id, int transaction, int
 
                /*  delete from secure storage */
        if (ssm_delete_file(recv_password_file_name,  SSM_FLAG_SECRET_OPERATION, NULL) < 0) {
-               EM_DEBUG_EXCEPTION(" ssm_delete_file failed -recv password : file[%s]", recv_password_file_name);
+               EM_DEBUG_EXCEPTION_SEC(" ssm_delete_file failed -recv password : file[%s]", recv_password_file_name);
                error = EMAIL_ERROR_SYSTEM_FAILURE;
                goto FINISH_OFF;
        }
        if (ssm_delete_file(send_password_file_name,  SSM_FLAG_SECRET_OPERATION, NULL) < 0) {
-               EM_DEBUG_EXCEPTION(" ssm_delete_file failed -send password : file[%s]", send_password_file_name);
+               EM_DEBUG_EXCEPTION_SEC(" ssm_delete_file failed -send password : file[%s]", send_password_file_name);
                error = EMAIL_ERROR_SYSTEM_FAILURE;
                goto FINISH_OFF;
        }
        ret = true;
 
 FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
 
        if (hStmt != NULL)  {
                rc = sqlite3_finalize(hStmt);
@@ -4359,9 +4621,6 @@ FINISH_OFF:
                }
        }
 
-       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
-       _DISCONNECT_DB;
-
        if (err_code != NULL)
                *err_code = error;
 
@@ -4596,7 +4855,7 @@ INTERNAL_FUNC int emstorage_get_child_mailbox_list(int account_id, char *parent_
                return false;
        }
 
-       SNPRINTF(conditional_clause_string, sizeof(conditional_clause_string), "WHERE account_id = %d  AND UPPER(mailbox_name) LIKE UPPER('%s%%')", account_id, parent_mailbox_name);
+       sqlite3_snprintf(sizeof(conditional_clause_string), conditional_clause_string, "WHERE account_id = %d  AND UPPER(mailbox_name) LIKE UPPER('%q%%')", account_id, parent_mailbox_name);
        EM_DEBUG_LOG("conditional_clause_string", conditional_clause_string);
 
        if( (error = emstorage_query_mailbox_tbl(conditional_clause_string, " ORDER BY mailbox_name DESC ", 0, transaction, mailbox_list, select_num)) != EMAIL_ERROR_NONE) {
@@ -4699,11 +4958,11 @@ FINISH_OFF:
 
 INTERNAL_FUNC int emstorage_get_mailbox_by_name(int account_id, int local_yn, char *mailbox_name, emstorage_mailbox_tbl_t** result_mailbox, int transaction, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("account_id[%d], local_yn[%d], mailbox_name[%s], result_mailbox[%p], transaction[%d], err_code[%p]", account_id, local_yn, mailbox_name, result_mailbox, transaction, err_code);
+       EM_DEBUG_FUNC_BEGIN_SEC("account_id[%d], local_yn[%d], mailbox_name[%s], result_mailbox[%p], transaction[%d], err_code[%p]", account_id, local_yn, mailbox_name, result_mailbox, transaction, err_code);
        EM_PROFILE_BEGIN(profile_emstorage_get_mailbox_by_name);
 
        if (account_id < FIRST_ACCOUNT_ID || !mailbox_name || !result_mailbox)  {
-               EM_DEBUG_EXCEPTION(" account_id[%d], local_yn[%d], mailbox_name[%s], result_mailbox[%p]", account_id, local_yn, mailbox_name, result_mailbox);
+               EM_DEBUG_EXCEPTION_SEC(" account_id[%d], local_yn[%d], mailbox_name[%s], result_mailbox[%p]", account_id, local_yn, mailbox_name, result_mailbox);
 
                if (err_code != NULL)
                        *err_code = EMAIL_ERROR_INVALID_PARAM;
@@ -4714,14 +4973,6 @@ INTERNAL_FUNC int emstorage_get_mailbox_by_name(int account_id, int local_yn, ch
        int error = EMAIL_ERROR_NONE;
        int result_count = 0;
        char conditional_clause_string[QUERY_SIZE] = {0, };
-       char *replaced_mailbox_name = NULL;
-
-       if (strstr(mailbox_name, "'")) {
-               replaced_mailbox_name = em_replace_all_string(mailbox_name, "'", "''");
-               EM_DEBUG_LOG("replaced_mailbox_name : [%s]", replaced_mailbox_name);
-       } else {
-               replaced_mailbox_name = strdup(mailbox_name);
-       }
 
        if(strcmp(mailbox_name, EMAIL_SEARCH_RESULT_MAILBOX_NAME) == 0) {
                if (!(*result_mailbox = (emstorage_mailbox_tbl_t*)em_malloc(sizeof(emstorage_mailbox_tbl_t))))  {
@@ -4746,9 +4997,9 @@ INTERNAL_FUNC int emstorage_get_mailbox_by_name(int account_id, int local_yn, ch
        else {
 
                if (local_yn == -1)
-                       SNPRINTF(conditional_clause_string, sizeof(conditional_clause_string), "WHERE account_id = %d AND mailbox_name = '%s'", account_id, replaced_mailbox_name);
+                       sqlite3_snprintf(sizeof(conditional_clause_string), conditional_clause_string, "WHERE account_id = %d AND mailbox_name = '%q'", account_id, mailbox_name);
                else
-                       SNPRINTF(conditional_clause_string, sizeof(conditional_clause_string), "WHERE account_id = %d AND local_yn = %d AND mailbox_name = '%s'", account_id, local_yn, replaced_mailbox_name);
+                       sqlite3_snprintf(sizeof(conditional_clause_string), conditional_clause_string, "WHERE account_id = %d AND local_yn = %d AND mailbox_name = '%q'", account_id, local_yn, mailbox_name);
 
                EM_DEBUG_LOG("conditional_clause_string = [%s]", conditional_clause_string);
 
@@ -4762,8 +5013,6 @@ INTERNAL_FUNC int emstorage_get_mailbox_by_name(int account_id, int local_yn, ch
 
 FINISH_OFF:
 
-       EM_SAFE_FREE(replaced_mailbox_name);
-
        if (err_code != NULL)
                *err_code = error;
 
@@ -4772,99 +5021,38 @@ FINISH_OFF:
        return ret;
 }
 
-INTERNAL_FUNC int emstorage_get_mailbox_by_mailbox_type(int account_id, email_mailbox_type_e mailbox_type, emstorage_mailbox_tbl_t** mailbox_name, int transaction, int *err_code)
+INTERNAL_FUNC int emstorage_get_mailbox_by_mailbox_type(int account_id, email_mailbox_type_e mailbox_type, emstorage_mailbox_tbl_t **output_mailbox, int transaction, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("account_id[%d], mailbox_type[%d], mailbox_name[%p], transaction[%d], err_code[%p]", account_id, mailbox_type, mailbox_name, transaction, err_code);
-
-       if (account_id < FIRST_ACCOUNT_ID || (mailbox_type < EMAIL_MAILBOX_TYPE_INBOX || mailbox_type > EMAIL_MAILBOX_TYPE_USER_DEFINED) || !mailbox_name) {
-
-               EM_DEBUG_EXCEPTION(" account_id[%d], mailbox_type[%d], mailbox_name[%p]", account_id, mailbox_type, mailbox_name);
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], mailbox_type[%d], output_mailbox[%p], transaction[%d], err_code[%p]", account_id, mailbox_type, output_mailbox, transaction, err_code);
 
+       if (account_id < FIRST_ACCOUNT_ID || (mailbox_type < EMAIL_MAILBOX_TYPE_INBOX || mailbox_type > EMAIL_MAILBOX_TYPE_USER_DEFINED) || !output_mailbox) {
+               EM_DEBUG_EXCEPTION(" account_id[%d], mailbox_type[%d], output_mailbox[%p]", account_id, mailbox_type, output_mailbox);
                if (err_code != NULL)
                        *err_code = EMAIL_ERROR_INVALID_PARAM;
                return false;
        }
 
-       int rc, ret = false;
+       int ret = false;
        int error = EMAIL_ERROR_NONE;
-       emstorage_mailbox_tbl_t *p_data_tbl = NULL;
-       emstorage_account_tbl_t *account = NULL;
-       DB_STMT hStmt = NULL;
-       char sql_query_string[QUERY_SIZE] = {0,};
-       char *fields = "mailbox_id, account_id, local_yn, mailbox_name, mailbox_type, alias, deleted_flag, modifiable_yn, total_mail_count_on_server, has_archived_mails, mail_slot_size, no_select, last_sync_time ";
-
-       sqlite3 *local_db_handle = emstorage_get_db_connection();
-       EMSTORAGE_START_READ_TRANSACTION(transaction);
-
-       /* validate account */
-       /*  Check whether the account exists. */
-       if (!emstorage_get_account_by_id(account_id, EMAIL_ACC_GET_OPT_ACCOUNT_NAME,  &account, true, &error) || !account) {
-               EM_DEBUG_EXCEPTION(" emstorage_get_account_by_id failed - %d", error);
-               goto FINISH_OFF;
-       }
-
-       if (account)
-               emstorage_free_account(&account, 1, NULL);
-
-       SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT %s FROM mail_box_tbl WHERE account_id = %d AND mailbox_type = %d ", fields, account_id, mailbox_type);
-
-       EM_DEBUG_LOG("query = [%s]", sql_query_string);
-
-
-       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
-       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE; goto FINISH_OFF; }, ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
-
+       int result_count = 0;
+       emstorage_mailbox_tbl_t *result_mailbox = NULL;
+       char conditional_clause_string[QUERY_SIZE] = {0,};
 
-       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
-       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE; goto FINISH_OFF; }, ("sqlite3_step fail:%d", rc));
 
-       if (rc == SQLITE_DONE) {
-               EM_DEBUG_EXCEPTION(" no matched mailbox_name found...");
-               error = EMAIL_ERROR_MAILBOX_NOT_FOUND;
-               goto FINISH_OFF;
-       }
+       SNPRINTF(conditional_clause_string, QUERY_SIZE, "WHERE account_id = %d AND mailbox_type = %d ", account_id, mailbox_type);
 
+       EM_DEBUG_LOG("conditional_clause_string = [%s]", conditional_clause_string);
 
-       if (!(p_data_tbl = (emstorage_mailbox_tbl_t*)malloc(sizeof(emstorage_mailbox_tbl_t))))  {
-               EM_DEBUG_EXCEPTION(" malloc failed...");
-               error = EMAIL_ERROR_OUT_OF_MEMORY;
+       if( (error = emstorage_query_mailbox_tbl(conditional_clause_string, "", true, false, &result_mailbox, &result_count)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emstorage_query_mailbox_tbl failed [%d]", ret);
                goto FINISH_OFF;
        }
 
-       memset(p_data_tbl, 0x00, sizeof(emstorage_mailbox_tbl_t));
-
-       int col_index = 0;
-
-       _get_stmt_field_data_int(hStmt, &(p_data_tbl->mailbox_id), col_index++);
-       _get_stmt_field_data_int(hStmt, &(p_data_tbl->account_id), col_index++);
-       _get_stmt_field_data_int(hStmt, &(p_data_tbl->local_yn), col_index++);
-       _get_stmt_field_data_string(hStmt, &(p_data_tbl->mailbox_name), 0, col_index++);
-       _get_stmt_field_data_int(hStmt, (int*)&(p_data_tbl->mailbox_type), col_index++);
-       _get_stmt_field_data_string(hStmt, &(p_data_tbl->alias), 0, col_index++);
-       _get_stmt_field_data_int(hStmt, &(p_data_tbl->deleted_flag), col_index++);
-       _get_stmt_field_data_int(hStmt, &(p_data_tbl->modifiable_yn), col_index++);
-       _get_stmt_field_data_int(hStmt, &(p_data_tbl->total_mail_count_on_server), col_index++);
-       _get_stmt_field_data_int(hStmt, &(p_data_tbl->has_archived_mails), col_index++);
-       _get_stmt_field_data_int(hStmt, &(p_data_tbl->mail_slot_size), col_index++);
-       _get_stmt_field_data_int(hStmt, &(p_data_tbl->no_select), col_index++);
-       _get_stmt_field_data_int(hStmt, (int*)&(p_data_tbl->last_sync_time), col_index++);
-
        ret = true;
 
 FINISH_OFF:
        if (ret == true)
-               *mailbox_name = p_data_tbl;
-
-       if (hStmt != NULL)  {
-               rc = sqlite3_finalize(hStmt);
-               if (rc != SQLITE_OK)  {
-                       EM_DEBUG_EXCEPTION("sqlite3_finalize failed - %d", rc);
-                       error = EMAIL_ERROR_DB_FAILURE;
-               }
-       }
-
-       EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
-       _DISCONNECT_DB;
+               *output_mailbox = result_mailbox;
 
        if (err_code != NULL)
                *err_code = error;
@@ -4878,7 +5066,7 @@ INTERNAL_FUNC int emstorage_get_mailbox_by_id(int input_mailbox_id, emstorage_ma
        EM_DEBUG_FUNC_BEGIN("input_mailbox_id[%d], output_mailbox[%p]", input_mailbox_id, output_mailbox);
 
        if (input_mailbox_id <= 0 || !output_mailbox)  {
-               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM: input_mailbox_id[%d] output_mailbox[%p]", input_mailbox_id, output_mailbox);
                return  EMAIL_ERROR_INVALID_PARAM;
        }
 
@@ -4886,11 +5074,11 @@ INTERNAL_FUNC int emstorage_get_mailbox_by_id(int input_mailbox_id, emstorage_ma
        int  result_count = 0;
        char conditional_clause_string[QUERY_SIZE] = {0, };
 
-       SNPRINTF(conditional_clause_string, sizeof(conditional_clause_string), "WHERE mailbox_id = %d", input_mailbox_id);
+       SNPRINTF(conditional_clause_string, sizeof(conditional_clause_string), "WHERE MBT.mailbox_id = %d", input_mailbox_id);
 
        EM_DEBUG_LOG("conditional_clause_string = [%s]", conditional_clause_string);
 
-       if( (ret = emstorage_query_mailbox_tbl(conditional_clause_string, "", false, false, output_mailbox, &result_count)) != EMAIL_ERROR_NONE) {
+       if( (ret = emstorage_query_mailbox_tbl(conditional_clause_string, "", true, false, output_mailbox, &result_count)) != EMAIL_ERROR_NONE) {
                EM_DEBUG_EXCEPTION("emstorage_query_mailbox_tbl failed [%d]", ret);
                goto FINISH_OFF;
        }
@@ -4901,6 +5089,47 @@ FINISH_OFF:
        return ret;
 }
 
+INTERNAL_FUNC int emstorage_get_mailbox_by_keyword(int account_id, char *keyword, emstorage_mailbox_tbl_t** result_mailbox, int * result_count, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN_SEC("account_id[%d], keyword[%s], result_mailbox[%p], transaction[%d], err_code[%p]", account_id, keyword, result_mailbox, transaction, err_code);
+
+       if (account_id < 0 || !keyword || !result_mailbox) {
+               EM_DEBUG_EXCEPTION_SEC(" account_id[%d], keyword[%s], result_mailbox[%p]", account_id, keyword, result_mailbox);
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char conditional_clause_string[QUERY_SIZE] = {0, };
+
+       if (account_id == 0)
+               sqlite3_snprintf(sizeof(conditional_clause_string), conditional_clause_string,
+                               "WHERE alias LIKE \'%%%q%%\'", keyword);
+       else if (account_id > 0)
+               sqlite3_snprintf(sizeof(conditional_clause_string), conditional_clause_string,
+                               "WHERE account_id = %d AND alias LIKE \'%%%q%%\'", account_id, keyword);
+
+       EM_DEBUG_LOG("conditional_clause_string = [%s]", conditional_clause_string);
+
+       if ((error = emstorage_query_mailbox_tbl(conditional_clause_string, "", 0, transaction, result_mailbox, result_count)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emstorage_query_mailbox_tbl failed [%d]", error);
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
 INTERNAL_FUNC int emstorage_get_mailbox_id_by_mailbox_type(int account_id, email_mailbox_type_e mailbox_type, int *mailbox_id, int transaction, int *err_code)
 {
        EM_DEBUG_FUNC_BEGIN("account_id[%d], mailbox_type[%d], mailbox_id[%p], transaction[%d], err_code[%p]", account_id, mailbox_type, mailbox_id, transaction, err_code);
@@ -4955,6 +5184,8 @@ INTERNAL_FUNC int emstorage_get_mailbox_id_by_mailbox_type(int account_id, email
        ret = true;
 
 FINISH_OFF:
+       EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
+       _DISCONNECT_DB;
        if (hStmt != NULL)  {
                rc = sqlite3_finalize(hStmt);
                if (rc != SQLITE_OK)  {
@@ -4963,9 +5194,6 @@ FINISH_OFF:
                }
        }
 
-       EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
-       _DISCONNECT_DB;
-
        if (err_code != NULL)
                *err_code = error;
 
@@ -5108,6 +5336,7 @@ INTERNAL_FUNC int emstorage_update_mailbox_total_count(int account_id, int input
 
                if (err_code != NULL)
                        *err_code = EMAIL_ERROR_INVALID_PARAM;
+               EM_DEBUG_FUNC_END("ret [%d]", ret);
                return false;
        }
        sqlite3 *local_db_handle = emstorage_get_db_connection();
@@ -5151,6 +5380,7 @@ INTERNAL_FUNC int emstorage_update_mailbox(int account_id, int local_yn, int inp
 
                if (err_code != NULL)
                        *err_code = EMAIL_ERROR_INVALID_PARAM;
+               EM_DEBUG_FUNC_END("ret [%d]", EMAIL_ERROR_INVALID_PARAM);
                return false;
        }
 
@@ -5242,12 +5472,12 @@ FINISH_OFF:
 }
 
 
-INTERNAL_FUNC int emstorage_update_mailbox_type(int account_id, int local_yn, char *mailbox_name, email_mailbox_type_e new_mailbox_type, int transaction, int *err_code)
+INTERNAL_FUNC int emstorage_update_mailbox_type(int account_id, int local_yn, int input_mailbox_id, email_mailbox_type_e new_mailbox_type, int transaction, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("account_id[%d], local_yn[%d], mailbox_name[%s], new_mailbox_type[%d], transaction[%d], err_code[%p]", account_id, local_yn, mailbox_name, new_mailbox_type, transaction, err_code);
+       EM_DEBUG_FUNC_BEGIN_SEC("account_id[%d], local_yn[%d], input_mailbox_id[%d], new_mailbox_type[%d], transaction[%d], err_code[%p]", account_id, local_yn, input_mailbox_id, new_mailbox_type, transaction, err_code);
 
-       if (account_id < FIRST_ACCOUNT_ID || !mailbox_name)  {
-               EM_DEBUG_EXCEPTION(" account_id[%d], local_yn[%d], mailbox_name[%s]", account_id, local_yn, mailbox_name);
+       if (account_id < FIRST_ACCOUNT_ID)  {
+               EM_DEBUG_EXCEPTION_SEC(" account_id[%d], local_yn[%d], input_mailbox_id[%d]", account_id, local_yn, input_mailbox_id);
 
                if (err_code != NULL)
                        *err_code = EMAIL_ERROR_INVALID_PARAM;
@@ -5257,15 +5487,6 @@ INTERNAL_FUNC int emstorage_update_mailbox_type(int account_id, int local_yn, ch
        int rc, ret = false;
        int error = EMAIL_ERROR_NONE;
        char sql_query_string[QUERY_SIZE] = {0, };
-       char *replaced_mailbox_name = NULL;
-
-       if (strstr(mailbox_name, "'")) {
-               replaced_mailbox_name = em_replace_all_string(mailbox_name, "'", "''");
-       } else {
-               replaced_mailbox_name = strdup(mailbox_name);
-       }
-
-       EM_DEBUG_LOG("replaced_mailbox_name : [%s]", replaced_mailbox_name);
 
        sqlite3 *local_db_handle = emstorage_get_db_connection();
        EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
@@ -5283,19 +5504,19 @@ INTERNAL_FUNC int emstorage_update_mailbox_type(int account_id, int local_yn, ch
                        " mailbox_type = ?"
                        " WHERE account_id = %d"
                        " AND local_yn = %d"
-                       " AND mailbox_name = '%s'"
+                       " AND mailbox_id = '%d'"
                        , account_id
                        , local_yn
-                       , replaced_mailbox_name);
+                       , input_mailbox_id);
        }
        else {
                SNPRINTF(sql_query_string, sizeof(sql_query_string)-1,
                        "UPDATE mail_box_tbl SET"
                        " mailbox_type = ?"
                        " WHERE account_id = %d"
-                       " AND mailbox_name = '%s'"
+                       " AND mailbox_id = '%d'"
                        , account_id
-                       , replaced_mailbox_name);
+                       , input_mailbox_id);
        }
 
        EM_DEBUG_LOG("SQL(%s)", sql_query_string);
@@ -5332,9 +5553,9 @@ INTERNAL_FUNC int emstorage_update_mailbox_type(int account_id, int local_yn, ch
                        "UPDATE mail_tbl SET"
                        " mailbox_type = ?"
                        " WHERE account_id = %d"
-                       " AND mailbox_name = '%s'"
+                       " AND mailbox_id = '%d'"
                        , account_id
-                       , replaced_mailbox_name);
+                       , input_mailbox_id);
 
        EM_DEBUG_LOG("SQL[%s]", sql_query_string);
 
@@ -5366,8 +5587,6 @@ FINISH_OFF:
        EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
        _DISCONNECT_DB;
 
-       EM_SAFE_FREE(replaced_mailbox_name);
-
        if (hStmt_box_tbl != NULL)  {
                rc = sqlite3_finalize(hStmt_box_tbl);
                if (rc != SQLITE_OK)  {
@@ -5529,8 +5748,11 @@ FINISH_OFF:
        EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, result, err);
        _DISCONNECT_DB;
 
-       if (result && parameter_string && !emcore_notify_storage_event(NOTI_MAILBOX_FIELD_UPDATE, input_account_id, 0, parameter_string, input_value))
-               EM_DEBUG_EXCEPTION("emcore_notify_storage_event failed : NOTI_MAILBOX_FIELD_UPDATE [%s,%d]", input_field_name, input_value);
+       if (err == EMAIL_ERROR_NONE && parameter_string) {
+               if (!emcore_notify_storage_event (NOTI_MAILBOX_FIELD_UPDATE, input_account_id, 0, parameter_string, input_value))
+                       EM_DEBUG_EXCEPTION_SEC ("emcore_notify_storage_event failed : NOTI_MAILBOX_FIELD_UPDATE [%s,%d]", 
+                                                                                         input_field_name, input_value);
+       }
 
        EM_SAFE_FREE(mailbox_id_string_buffer);
        EM_SAFE_FREE(parameter_string);
@@ -5590,11 +5812,14 @@ INTERNAL_FUNC int emstorage_add_mailbox(emstorage_mailbox_tbl_t* mailbox_tbl, in
                ", ?"    /* has_archived_mails */
                ", ?"    /* mail_slot_size */
                ", ?"    /* no_select */
-               ", ? )");/* last_sync_time */
+               ", ?"    /* last_sync_time */
+               ", ?"    /* eas_data_length */
+               ", ?"    /* eas_data */
+               ")");
 
 
        EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
-       EM_DEBUG_LOG("After sqlite3_prepare hStmt = %p", hStmt);
+       EM_DEBUG_LOG_DEV ("After sqlite3_prepare hStmt = %p", hStmt);
        EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
                ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
 
@@ -5613,6 +5838,8 @@ INTERNAL_FUNC int emstorage_add_mailbox(emstorage_mailbox_tbl_t* mailbox_tbl, in
        _bind_stmt_field_data_int(hStmt, col_index++, mailbox_tbl->mail_slot_size);
        _bind_stmt_field_data_int(hStmt, col_index++, mailbox_tbl->no_select);
        _bind_stmt_field_data_int(hStmt, col_index++, current_time);
+       _bind_stmt_field_data_int(hStmt, col_index++, mailbox_tbl->eas_data_length);
+       _bind_stmt_field_data_blob(hStmt, col_index++, (void*)mailbox_tbl->eas_data, mailbox_tbl->eas_data_length);
 
 
        EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
@@ -5622,8 +5849,10 @@ INTERNAL_FUNC int emstorage_add_mailbox(emstorage_mailbox_tbl_t* mailbox_tbl, in
        ret = true;
 
 FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
        if (hStmt != NULL)  {
-               EM_DEBUG_LOG("before sqlite3_finalize hStmt = %p", hStmt);
+               EM_DEBUG_LOG_DEV ("before sqlite3_finalize hStmt = %p", hStmt);
 
                rc = sqlite3_finalize(hStmt);
                if (rc != SQLITE_OK)  {
@@ -5632,11 +5861,11 @@ FINISH_OFF:
                }
        }
 
-       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
-       _DISCONNECT_DB;
-
-       if (error == EMAIL_ERROR_NONE && !emcore_notify_storage_event(NOTI_MAILBOX_ADD, mailbox_tbl->account_id, mailbox_tbl->mailbox_id, mailbox_tbl->mailbox_name, mailbox_tbl->mailbox_type))
-               EM_DEBUG_EXCEPTION("emcore_notify_storage_event[ NOTI_MAILBOX_ADD] : Notification Failed");
+       if (error == EMAIL_ERROR_NONE) { 
+               if (!emcore_notify_storage_event (NOTI_MAILBOX_ADD, mailbox_tbl->account_id, mailbox_tbl->mailbox_id, 
+                                                                  mailbox_tbl->mailbox_name, mailbox_tbl->mailbox_type))
+                       EM_DEBUG_EXCEPTION ("emcore_notify_storage_event[ NOTI_MAILBOX_ADD] : Notification Failed");
+       }
 
        if (err_code != NULL)
                *err_code = error;
@@ -5737,8 +5966,8 @@ FINISH_OFF:
        _DISCONNECT_DB;
 
        if(error == EMAIL_ERROR_NONE) {
-               if (!emcore_notify_storage_event(NOTI_MAILBOX_DELETE, account_id, input_mailbox_id, NULL, 0))
-                       EM_DEBUG_EXCEPTION("emcore_notify_storage_event[ NOTI_MAILBOX_ADD] : Notification Failed");
+               if (!emcore_notify_storage_event (NOTI_MAILBOX_DELETE, account_id, input_mailbox_id, NULL, 0))
+                       EM_DEBUG_EXCEPTION ("emcore_notify_storage_event[ NOTI_MAILBOX_ADD] : Notification Failed");
        }
 
        if (err_code != NULL)
@@ -5769,6 +5998,7 @@ INTERNAL_FUNC int emstorage_free_mailbox(emstorage_mailbox_tbl_t** mailbox_list,
                for (; i < count; i++) {
                        EM_SAFE_FREE(p[i].mailbox_name);
                        EM_SAFE_FREE(p[i].alias);
+                       EM_SAFE_FREE(p[i].eas_data); /*valgrind*/
                }
 
                EM_SAFE_FREE(p); *mailbox_list = NULL;
@@ -5807,7 +6037,7 @@ INTERNAL_FUNC int emstorage_get_count_read_mail_uid(int account_id, char *mailbo
                replaced_mailbox_name = EM_SAFE_STRDUP(mailbox_name);
        }
 
-       EM_DEBUG_LOG("replaced_mailbox_name : [%s]", replaced_mailbox_name);
+       EM_DEBUG_LOG_SEC("replaced_mailbox_name : [%s]", replaced_mailbox_name);
 
 
        sqlite3 *local_db_handle = emstorage_get_db_connection();
@@ -5858,7 +6088,7 @@ INTERNAL_FUNC int emstorage_check_read_mail_uid(int account_id, char *mailbox_na
        char sql_query_string[QUERY_SIZE] = {0, };
        char *replaced_mailbox_name = NULL;
 
-       EM_DEBUG_LOG("replaced_mailbox_name : [%s]", replaced_mailbox_name);
+       EM_DEBUG_LOG_SEC("replaced_mailbox_name : [%s]", replaced_mailbox_name);
 
        sqlite3 *local_db_handle = emstorage_get_db_connection();
        EMSTORAGE_START_READ_TRANSACTION(transaction);
@@ -5870,13 +6100,13 @@ INTERNAL_FUNC int emstorage_check_read_mail_uid(int account_id, char *mailbox_na
                        replaced_mailbox_name = strdup(mailbox_name);
                }
 
-               SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT COUNT(*) FROM mail_read_mail_uid_tbl WHERE account_id = %d AND mailbox_name = '%s' AND s_uid = '%s' ", account_id, replaced_mailbox_name, uid);
+               SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT COUNT(*) FROM mail_read_mail_uid_tbl WHERE account_id = %d AND mailbox_name = '%s' AND server_uid = '%s' ", account_id, replaced_mailbox_name, uid);
        }
        else  {
-               SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT COUNT(*) FROM mail_read_mail_uid_tbl WHERE account_id = %d AND s_uid = '%s' ", account_id, uid);
+               SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT COUNT(*) FROM mail_read_mail_uid_tbl WHERE account_id = %d AND server_uid = '%s' ", account_id, uid);
        }
 
-       char **result;
+       char **result = NULL;
 
        EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql_query_string, &result, NULL, NULL, NULL), rc);
        EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
@@ -5916,7 +6146,7 @@ INTERNAL_FUNC int emstorage_get_downloaded_mail(int mail_id, emstorage_mail_tbl_
                return false;
        }
 
-       int rc, ret = false, temp_rule;
+       int rc, ret = false;
        int error = EMAIL_ERROR_NONE;
        DB_STMT hStmt = NULL;
        char sql_query_string[QUERY_SIZE] = {0, };
@@ -5948,11 +6178,11 @@ INTERNAL_FUNC int emstorage_get_downloaded_mail(int mail_id, emstorage_mail_tbl_
 
        _get_stmt_field_data_int(hStmt, &((*mail)->account_id), ACCOUNT_ID_IDX_IN_MAIL_READ_MAIL_UID_TBL);
        _get_stmt_field_data_int(hStmt, &((*mail)->mailbox_id), LOCAL_MAILBOX_ID_IDX_IN_MAIL_READ_MAIL_UID_TBL);
-       _get_stmt_field_data_int(hStmt, &((*mail)->mail_id), LOCAL_UID_IDX_IN_MAIL_READ_MAIL_UID_TBL);
        _get_stmt_field_data_string(hStmt, &((*mail)->server_mailbox_name), 0, MAILBOX_NAME_IDX_IN_MAIL_READ_MAIL_UID_TBL);
-       _get_stmt_field_data_string(hStmt, &((*mail)->server_mail_id), 0, S_UID_IDX_IN_MAIL_READ_MAIL_UID_TBL);
-       _get_stmt_field_data_int(hStmt, &((*mail)->mail_size), DATA1_IDX_IN_MAIL_READ_MAIL_UID_TBL);
-       _get_stmt_field_data_int(hStmt, &temp_rule, FLAG_IDX_IN_MAIL_READ_MAIL_UID_TBL);
+       _get_stmt_field_data_int(hStmt, &((*mail)->mail_id), LOCAL_UID_IDX_IN_MAIL_READ_MAIL_UID_TBL);
+       _get_stmt_field_data_string(hStmt, &((*mail)->server_mail_id), 0, SERVER_UID_IDX_IN_MAIL_READ_MAIL_UID_TBL);
+       _get_stmt_field_data_int(hStmt, &((*mail)->mail_size), RFC822_SIZE_IDX_IN_MAIL_READ_MAIL_UID_TBL);
+       _get_stmt_field_data_char(hStmt, &((*mail)->flags_seen_field), FLAGS_SEEN_FIELD_IDX_IN_MAIL_READ_MAIL_UID_TBL);
 
        (*mail)->server_mail_status = 1;
 
@@ -5983,7 +6213,7 @@ INTERNAL_FUNC int emstorage_get_downloaded_list(int account_id, int mailbox_id,
        EM_PROFILE_BEGIN(emStorageGetDownloadList);
        EM_DEBUG_FUNC_BEGIN("account_id[%d], mailbox_id[%d], read_mail_uid[%p], count[%p], transaction[%d], err_code[%p]", account_id, mailbox_id, read_mail_uid, count, transaction, err_code);
        if (account_id < FIRST_ACCOUNT_ID || !read_mail_uid || !count)  {
-               EM_DEBUG_EXCEPTION(" account_id[%d], mailbox_id[%s], read_mail_uid[%p], count[%p]", account_id, mailbox_id, read_mail_uid, count);
+               EM_DEBUG_EXCEPTION_SEC(" account_id[%d], mailbox_id[%s], read_mail_uid[%p], count[%p]", account_id, mailbox_id, read_mail_uid, count);
 
                if (err_code != NULL)
                        *err_code = EMAIL_ERROR_INVALID_PARAM;
@@ -6046,12 +6276,12 @@ INTERNAL_FUNC int emstorage_get_downloaded_list(int account_id, int mailbox_id,
        for (i = 0; i < *count; ++i)  {
                _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].account_id), ACCOUNT_ID_IDX_IN_MAIL_READ_MAIL_UID_TBL);
                _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].mailbox_id),LOCAL_MAILBOX_ID_IDX_IN_MAIL_READ_MAIL_UID_TBL);
-               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].local_uid), LOCAL_UID_IDX_IN_MAIL_READ_MAIL_UID_TBL);
                _get_stmt_field_data_string(hStmt, &(p_data_tbl[i].mailbox_name), 0, MAILBOX_NAME_IDX_IN_MAIL_READ_MAIL_UID_TBL);
-               _get_stmt_field_data_string(hStmt, &(p_data_tbl[i].s_uid), 0, S_UID_IDX_IN_MAIL_READ_MAIL_UID_TBL);
-               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].data1), DATA1_IDX_IN_MAIL_READ_MAIL_UID_TBL);
-               _get_stmt_field_data_string(hStmt, &(p_data_tbl[i].data2), 0, DATA2_IDX_IN_MAIL_READ_MAIL_UID_TBL);
-               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].flag), FLAG_IDX_IN_MAIL_READ_MAIL_UID_TBL);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].local_uid), LOCAL_UID_IDX_IN_MAIL_READ_MAIL_UID_TBL);
+               _get_stmt_field_data_string(hStmt, &(p_data_tbl[i].server_uid), 0, SERVER_UID_IDX_IN_MAIL_READ_MAIL_UID_TBL);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].rfc822_size), RFC822_SIZE_IDX_IN_MAIL_READ_MAIL_UID_TBL);
+               _get_stmt_field_data_char(hStmt, &(p_data_tbl[i].flags_seen_field), FLAGS_SEEN_FIELD_IDX_IN_MAIL_READ_MAIL_UID_TBL);
+               _get_stmt_field_data_char(hStmt, &(p_data_tbl[i].flags_flagged_field), FLAGS_FLAGGED_FIELD_IDX_IN_MAIL_READ_MAIL_UID_TBL);
 
                EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
                EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
@@ -6115,7 +6345,7 @@ INTERNAL_FUNC int emstorage_get_downloaded_mail_size(int account_id, char *mailb
                        replaced_mailbox_name = strdup(mailbox_name);
                }
 
-               EM_DEBUG_LOG("replaced_mailbox_name : [%s]", replaced_mailbox_name);
+               EM_DEBUG_LOG_SEC("replaced_mailbox_name : [%s]", replaced_mailbox_name);
 
                SNPRINTF(sql_query_string, sizeof(sql_query_string),
                        "SELECT IFNULL(MAX(data1), 0) FROM mail_read_mail_uid_tbl "
@@ -6123,7 +6353,7 @@ INTERNAL_FUNC int emstorage_get_downloaded_mail_size(int account_id, char *mailb
                        "AND mailbox_id = '%s' "
                        "AND local_uid = %d "
                        "AND mailbox_name = '%s' "
-                       "AND s_uid = '%s'",
+                       "AND server_uid = '%s'",
                        account_id, mailbox_id, local_uid, replaced_mailbox_name, uid);
        }
        else {
@@ -6132,7 +6362,7 @@ INTERNAL_FUNC int emstorage_get_downloaded_mail_size(int account_id, char *mailb
                        "WHERE account_id = %d "
                        "AND mailbox_id = '%s' "
                        "AND local_uid = %d "
-                       "AND s_uid = '%s'",
+                       "AND server_uid = '%s'",
                        account_id, mailbox_id, local_uid, uid);
        }
 
@@ -6147,7 +6377,7 @@ INTERNAL_FUNC int emstorage_get_downloaded_mail_size(int account_id, char *mailb
                ("sqlite3_step fail:%d", rc));
 
        if (rc == SQLITE_DONE) {
-               EM_DEBUG_EXCEPTION(" no matched mail found....");
+               EM_DEBUG_LOG("no matched mail found....");
                error = EMAIL_ERROR_MAIL_NOT_FOUND;
                goto FINISH_OFF;
        }
@@ -6211,14 +6441,15 @@ INTERNAL_FUNC int emstorage_add_downloaded_mail(emstorage_read_mail_uid_tbl_t* r
 
        SNPRINTF(sql_query_string, sizeof(sql_query_string),
                "INSERT INTO mail_read_mail_uid_tbl VALUES "
-               "( ?"
-               ", ?"
-               ", ?"
-               ", ?"
-               ", ?"
-               ", ?"
-               ", ?"
-               ", ?"
+               "( ?"  /* account_id */
+               ", ?"  /* mailbox_id */
+               ", ?"  /* mailbox_name */
+               ", ?"  /* local_uid */
+               ", ?"  /* server_uid */
+               ", ?"  /* rfc822_size */
+               ", ?"  /* sync_status */
+               ", ?"  /* flags_seen_field */
+               ", ?"  /* flags_flagged_field */
                ", ? )");
 
 
@@ -6234,21 +6465,19 @@ INTERNAL_FUNC int emstorage_add_downloaded_mail(emstorage_read_mail_uid_tbl_t* r
        EM_DEBUG_LOG("account_id VALUE [%d] ", read_mail_uid->account_id);
        EM_DEBUG_LOG("mailbox_id VALUE [%d] ", read_mail_uid->mailbox_id);
        EM_DEBUG_LOG("local_uid VALUE [%d] ", read_mail_uid->local_uid);
-       EM_DEBUG_LOG("mailbox_name VALUE [%s] ", read_mail_uid->mailbox_name);
-       EM_DEBUG_LOG("s_uid VALUE [%s] ", read_mail_uid->s_uid);
-       EM_DEBUG_LOG("data1 VALUE [%d] ", read_mail_uid->data1);
-       EM_DEBUG_LOG("data2 VALUE [%s] ", read_mail_uid->data2);
-       EM_DEBUG_LOG("flag VALUE [%d] ", read_mail_uid->flag);
+       EM_DEBUG_LOG_SEC("mailbox_name VALUE [%s] ", read_mail_uid->mailbox_name);
+       EM_DEBUG_LOG("server_uid VALUE [%s] ", read_mail_uid->server_uid);
+       EM_DEBUG_LOG("data1 VALUE [%d] ", read_mail_uid->rfc822_size);
        EM_DEBUG_LOG("rc VALUE [%d] ", rc);
 
        _bind_stmt_field_data_int(hStmt, ACCOUNT_ID_IDX_IN_MAIL_READ_MAIL_UID_TBL, read_mail_uid->account_id);
        _bind_stmt_field_data_int(hStmt, LOCAL_MAILBOX_ID_IDX_IN_MAIL_READ_MAIL_UID_TBL, read_mail_uid->mailbox_id);
        _bind_stmt_field_data_int(hStmt, LOCAL_UID_IDX_IN_MAIL_READ_MAIL_UID_TBL, read_mail_uid->local_uid);
        _bind_stmt_field_data_string(hStmt, MAILBOX_NAME_IDX_IN_MAIL_READ_MAIL_UID_TBL, (char *)read_mail_uid->mailbox_name, 0, MAILBOX_NAME_LEN_IN_MAIL_READ_MAIL_UID_TBL);
-       _bind_stmt_field_data_string(hStmt, S_UID_IDX_IN_MAIL_READ_MAIL_UID_TBL, (char *)read_mail_uid->s_uid, 0, S_UID_LEN_IN_MAIL_READ_MAIL_UID_TBL);
-       _bind_stmt_field_data_int(hStmt, DATA1_IDX_IN_MAIL_READ_MAIL_UID_TBL, read_mail_uid->data1);
-       _bind_stmt_field_data_string(hStmt, DATA2_IDX_IN_MAIL_READ_MAIL_UID_TBL, (char *)read_mail_uid->data2, 0, DATA2_LEN_IN_MAIL_READ_MAIL_UID_TBL);
-       _bind_stmt_field_data_int(hStmt, FLAG_IDX_IN_MAIL_READ_MAIL_UID_TBL, read_mail_uid->flag);
+       _bind_stmt_field_data_string(hStmt, SERVER_UID_IDX_IN_MAIL_READ_MAIL_UID_TBL, (char *)read_mail_uid->server_uid, 0, S_UID_LEN_IN_MAIL_READ_MAIL_UID_TBL);
+       _bind_stmt_field_data_int(hStmt, RFC822_SIZE_IDX_IN_MAIL_READ_MAIL_UID_TBL, read_mail_uid->rfc822_size);
+       _bind_stmt_field_data_int(hStmt, FLAGS_SEEN_FIELD_IDX_IN_MAIL_READ_MAIL_UID_TBL, read_mail_uid->flags_seen_field);
+       _bind_stmt_field_data_int(hStmt, FLAGS_FLAGGED_FIELD_IDX_IN_MAIL_READ_MAIL_UID_TBL, read_mail_uid->flags_flagged_field);
        _bind_stmt_field_data_int(hStmt, IDX_NUM_IDX_IN_MAIL_READ_MAIL_UID_TBL, rc);
 
 
@@ -6262,6 +6491,8 @@ INTERNAL_FUNC int emstorage_add_downloaded_mail(emstorage_read_mail_uid_tbl_t* r
        ret = true;
 
 FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
        if (hStmt != NULL)  {
                EM_DEBUG_LOG(" sqlite3_finalize hStmt = %p", hStmt);
 
@@ -6272,9 +6503,6 @@ FINISH_OFF:
                }
        }
 
-       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
-       _DISCONNECT_DB;
-
        if (err_code != NULL)
                *err_code = error;
 
@@ -6345,6 +6573,8 @@ INTERNAL_FUNC int emstorage_add_mail_text(emstorage_mail_text_tbl_t* mail_text,
        ret = true;
 
 FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
        if (hStmt != NULL) {
                EM_DEBUG_LOG(" sqlite3_finalize hStmt = %p", hStmt);
 
@@ -6355,9 +6585,6 @@ FINISH_OFF:
                }
        }
 
-       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
-       _DISCONNECT_DB;
-
        if (err_code != NULL)
                *err_code = error;
 
@@ -6391,17 +6618,17 @@ INTERNAL_FUNC int emstorage_change_read_mail_uid(int account_id, int mailbox_id,
                "UPDATE mail_read_mail_uid_tbl SET"
                "  account_id = ?"
                ", mailbox_id = ?"
-               ", local_uid  = ?"
                ", mailbox_name = ?"
-               ", s_uid = ?"
-               ", data1 = ?"
-               ", data2 = ?"
-               ", flag  = ?"
+               ", local_uid  = ?"
+               ", server_uid = ?"
+               ", rfc822_size = ?"
+               ", flags_seen_field  = ?"
+               ", flags_flagged_field  = ?"
                " WHERE account_id = ?"
                " AND mailbox_id  = ?"
                " AND local_uid   = ?"
                " AND mailbox_name= ?"
-               " AND s_uid = ?");
+               " AND server_uid = ?");
 
 
        EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
@@ -6414,12 +6641,12 @@ INTERNAL_FUNC int emstorage_change_read_mail_uid(int account_id, int mailbox_id,
 
        _bind_stmt_field_data_int(hStmt, i++, read_mail_uid->account_id);
        _bind_stmt_field_data_int(hStmt, i++, read_mail_uid->mailbox_id);
-       _bind_stmt_field_data_int(hStmt, i++, read_mail_uid->local_uid);
        _bind_stmt_field_data_string(hStmt, i++, (char*)read_mail_uid->mailbox_name, 0, MAILBOX_NAME_LEN_IN_MAIL_READ_MAIL_UID_TBL);
-       _bind_stmt_field_data_string(hStmt, i++, (char*)read_mail_uid->s_uid, 0, S_UID_LEN_IN_MAIL_READ_MAIL_UID_TBL);
-       _bind_stmt_field_data_int(hStmt, i++, read_mail_uid->data1);
-       _bind_stmt_field_data_string(hStmt, i++, (char*)read_mail_uid->data2, 0, DATA2_LEN_IN_MAIL_READ_MAIL_UID_TBL);
-       _bind_stmt_field_data_int(hStmt, i++, read_mail_uid->flag);
+       _bind_stmt_field_data_int(hStmt, i++, read_mail_uid->local_uid);
+       _bind_stmt_field_data_string(hStmt, i++, (char*)read_mail_uid->server_uid, 0, S_UID_LEN_IN_MAIL_READ_MAIL_UID_TBL);
+       _bind_stmt_field_data_int(hStmt, i++, read_mail_uid->rfc822_size);
+       _bind_stmt_field_data_int(hStmt, i++, read_mail_uid->flags_seen_field);
+       _bind_stmt_field_data_int(hStmt, i++, read_mail_uid->flags_flagged_field);
        _bind_stmt_field_data_int(hStmt, i++, account_id);
        _bind_stmt_field_data_int(hStmt, i++, mailbox_id);
        _bind_stmt_field_data_int(hStmt, i++, local_uid);
@@ -6434,6 +6661,8 @@ INTERNAL_FUNC int emstorage_change_read_mail_uid(int account_id, int mailbox_id,
        ret = true;
 
 FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
        if (hStmt != NULL)  {
                EM_DEBUG_LOG("sqlite3_finalize hStmt = %p", hStmt);
 
@@ -6445,9 +6674,6 @@ FINISH_OFF:
                }
        }
 
-       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
-       _DISCONNECT_DB;
-
        if (err_code != NULL)
                *err_code = error;
 
@@ -6457,10 +6683,10 @@ FINISH_OFF:
 
 INTERNAL_FUNC int emstorage_remove_downloaded_mail(int account_id, char *mailbox_name, char *uid, int transaction, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("account_id[%d], mailbox_name[%s], uid[%s], transaction[%d], err_code[%p]", account_id, mailbox_name, uid, transaction, err_code);
+       EM_DEBUG_FUNC_BEGIN_SEC("account_id[%d], mailbox_name[%s], uid[%s], transaction[%d], err_code[%p]", account_id, mailbox_name, uid, transaction, err_code);
 
        if (account_id < FIRST_ACCOUNT_ID)  {
-               EM_DEBUG_EXCEPTION(" account_id[%d], mailbox_name[%s], uid[%s]", account_id, mailbox_name, uid);
+               EM_DEBUG_EXCEPTION_SEC(" account_id[%d], mailbox_name[%s], uid[%s]", account_id, mailbox_name, uid);
 
                if (err_code != NULL)
                        *err_code = EMAIL_ERROR_INVALID_PARAM;
@@ -6489,7 +6715,7 @@ INTERNAL_FUNC int emstorage_remove_downloaded_mail(int account_id, char *mailbox
        }
 
        if (uid) {              /*  NULL means all mail */
-               SNPRINTF(sql_query_string+EM_SAFE_STRLEN(sql_query_string), sizeof(sql_query_string) - (1 + EM_SAFE_STRLEN(sql_query_string)), "AND s_uid='%s' ", uid);
+               SNPRINTF(sql_query_string+EM_SAFE_STRLEN(sql_query_string), sizeof(sql_query_string) - (1 + EM_SAFE_STRLEN(sql_query_string)), "AND server_uid='%s' ", uid);
        }
 
        EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
@@ -6500,12 +6726,11 @@ INTERNAL_FUNC int emstorage_remove_downloaded_mail(int account_id, char *mailbox
        ret = true;
 
 FINISH_OFF:
-
-       EM_SAFE_FREE(replaced_mailbox_name);
-
        EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
        _DISCONNECT_DB;
 
+       EM_SAFE_FREE(replaced_mailbox_name);
+
        if (err_code != NULL)
                *err_code = error;
 
@@ -6533,8 +6758,7 @@ INTERNAL_FUNC int emstorage_free_read_mail_uid(emstorage_read_mail_uid_tbl_t** r
 
                for (i = 0; i < count; i++)  {
                        EM_SAFE_FREE(p[i].mailbox_name);
-                       EM_SAFE_FREE(p[i].s_uid);
-                       EM_SAFE_FREE(p[i].data2);
+                       EM_SAFE_FREE(p[i].server_uid);
                }
 
                EM_SAFE_FREE(p); *read_mail_uid = NULL;
@@ -6634,7 +6858,7 @@ INTERNAL_FUNC int emstorage_get_rule(int account_id, int type, int start_idx, in
        }
 
        EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
-       EM_DEBUG_LOG("sqlite3_prepare hStmt = %p", hStmt);
+/*     EM_DEBUG_LOG("sqlite3_prepare hStmt = %p", hStmt); */
        EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
                ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
 
@@ -6652,8 +6876,9 @@ INTERNAL_FUNC int emstorage_get_rule(int account_id, int type, int start_idx, in
        sqlite3_free_table(result);
 
        if (count == 0)  {
-               EM_DEBUG_LOG(" no matched rule found...");
+               EM_DEBUG_LOG_DEV ("No matching rule found...");
                ret = true;
+               error = EMAIL_ERROR_FILTER_NOT_FOUND; /*there is no matched rule*/
                goto FINISH_OFF;
        }
 
@@ -6670,8 +6895,10 @@ INTERNAL_FUNC int emstorage_get_rule(int account_id, int type, int start_idx, in
        for (i = 0; i < count; i++)  {
                _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].account_id), ACCOUNT_ID_IDX_IN_MAIL_RULE_TBL);
                _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].rule_id), RULE_ID_IDX_IN_MAIL_RULE_TBL);
+               _get_stmt_field_data_string(hStmt, &(p_data_tbl[i].filter_name), 0, FILTER_NAME_IDX_IN_MAIL_RULE_TBL);
                _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].type), TYPE_IDX_IN_MAIL_RULE_TBL);
                _get_stmt_field_data_string(hStmt, &(p_data_tbl[i].value), 0, VALUE_IDX_IN_MAIL_RULE_TBL);
+               _get_stmt_field_data_string(hStmt, &(p_data_tbl[i].value2), 0, VALUE2_IDX_IN_MAIL_RULE_TBL);
                _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].action_type), ACTION_TYPE_IDX_IN_MAIL_RULE_TBL);
                _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].target_mailbox_id), TARGET_MAILBOX_ID_IDX_IN_MAIL_RULE_TBL);
                _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].flag1), FLAG1_IDX_IN_MAIL_RULE_TBL);
@@ -6696,7 +6923,7 @@ FINISH_OFF:
                emstorage_free_rule(&p_data_tbl, count, NULL); /* CID FIX */
 
        if (hStmt != NULL)  {
-               EM_DEBUG_LOG("  sqlite3_finalize hStmt = %p", hStmt);
+/*             EM_DEBUG_LOG("  sqlite3_finalize hStmt = %p", hStmt); */
 
                rc = sqlite3_finalize(hStmt);
                if (rc != SQLITE_OK)  {
@@ -6763,8 +6990,10 @@ INTERNAL_FUNC int emstorage_get_rule_by_id(int rule_id, emstorage_rule_tbl_t** r
        memset(p_data_tbl, 0x00, sizeof(emstorage_rule_tbl_t));
        _get_stmt_field_data_int(hStmt, &(p_data_tbl->account_id), ACCOUNT_ID_IDX_IN_MAIL_RULE_TBL);
        _get_stmt_field_data_int(hStmt, &(p_data_tbl->rule_id), RULE_ID_IDX_IN_MAIL_RULE_TBL);
+       _get_stmt_field_data_string(hStmt, &(p_data_tbl->filter_name), 0, FILTER_NAME_IDX_IN_MAIL_RULE_TBL);
        _get_stmt_field_data_int(hStmt, &(p_data_tbl->type), TYPE_IDX_IN_MAIL_RULE_TBL);
        _get_stmt_field_data_string(hStmt, &(p_data_tbl->value), 0, VALUE_IDX_IN_MAIL_RULE_TBL);
+       _get_stmt_field_data_string(hStmt, &(p_data_tbl->value2), 0, VALUE2_IDX_IN_MAIL_RULE_TBL);
        _get_stmt_field_data_int(hStmt, &(p_data_tbl->action_type), ACTION_TYPE_IDX_IN_MAIL_RULE_TBL);
        _get_stmt_field_data_int(hStmt, &(p_data_tbl->target_mailbox_id), TARGET_MAILBOX_ID_IDX_IN_MAIL_RULE_TBL);
        _get_stmt_field_data_int(hStmt, &(p_data_tbl->flag1), FLAG1_IDX_IN_MAIL_RULE_TBL);
@@ -6819,8 +7048,10 @@ INTERNAL_FUNC int emstorage_change_rule(int rule_id, emstorage_rule_tbl_t* new_r
 
        SNPRINTF(sql_query_string, sizeof(sql_query_string),
                "UPDATE mail_rule_tbl SET"
-               "  type = ?"
+               "  filter_name = ?"                
+               ", type = ?"
                ", value = ?"
+               ", value2 = ?"
                ", action_type = ?"
                ", target_mailbox_id = ?"
                ", flag1 = ?"
@@ -6836,8 +7067,10 @@ INTERNAL_FUNC int emstorage_change_rule(int rule_id, emstorage_rule_tbl_t* new_r
 
        int i = 0;
 
+       _bind_stmt_field_data_string(hStmt, i++, (char *)new_rule->filter_name, 0, FILTER_NAME_LEN_IN_MAIL_RULE_TBL);
        _bind_stmt_field_data_int(hStmt, i++, new_rule->type);
        _bind_stmt_field_data_string(hStmt, i++, (char *)new_rule->value, 0, VALUE_LEN_IN_MAIL_RULE_TBL);
+       _bind_stmt_field_data_string(hStmt, i++, (char *)new_rule->value2, 0, VALUE2_LEN_IN_MAIL_RULE_TBL);
        _bind_stmt_field_data_int(hStmt, i++, new_rule->action_type);
        _bind_stmt_field_data_int(hStmt, i++, new_rule->target_mailbox_id);
        _bind_stmt_field_data_int(hStmt, i++, new_rule->flag1);
@@ -6853,6 +7086,8 @@ INTERNAL_FUNC int emstorage_change_rule(int rule_id, emstorage_rule_tbl_t* new_r
        ret = true;
 
 FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
        if (hStmt != NULL)  {
                EM_DEBUG_LOG(" Before sqlite3_finalize hStmt = %p", hStmt);
 
@@ -6864,9 +7099,6 @@ FINISH_OFF:
                }
        }
 
-       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
-       _DISCONNECT_DB;
-
        if (err_code != NULL)
                *err_code = error;
 
@@ -6878,59 +7110,82 @@ INTERNAL_FUNC int emstorage_find_rule(emstorage_rule_tbl_t* rule, int transactio
 {
        EM_DEBUG_FUNC_BEGIN("rule[%p], transaction[%d], err_code[%p]", rule, transaction, err_code);
 
-       if (!rule) {            
-               if (rule != NULL)
-                       EM_DEBUG_EXCEPTION(" rule->account_id[%d]", rule->account_id);
-
+       if (!rule) {
+               EM_DEBUG_LOG("rule is NULL");
                if (err_code != NULL)
                        *err_code = EMAIL_ERROR_INVALID_PARAM;
                return false;
        }
 
        DB_STMT hStmt = NULL;
-       char sql_query_string[QUERY_SIZE] = {0, };
-
+       char sql_query_string[QUERY_SIZE] = {0,};
        int error = EMAIL_ERROR_NONE;
-       int rc, ret = false;
+       int rc = 0;
+       int ret = false;
 
        sqlite3 *local_db_handle = emstorage_get_db_connection();
        EMSTORAGE_START_READ_TRANSACTION(transaction);
 
-       SNPRINTF(sql_query_string, sizeof(sql_query_string),
-               "SELECT rule_id FROM mail_rule_tbl WHERE type = %d AND UPPER(value) = UPPER('%s')",
-               rule->type, rule->value);
+       switch(rule->action_type) {
+       case EMAIL_FILTER_MOVE:
+               if (rule->type == EMAIL_PRIORITY_SENDER) {
+                       sqlite3_snprintf(sizeof(sql_query_string), sql_query_string,
+                               "SELECT rule_id FROM mail_rule_tbl WHERE action_type = %d AND type = %d AND UPPER(value2) = UPPER(\'%q\')",
+                               rule->action_type, rule->type, rule->value2);
+               } else {
+                               sqlite3_snprintf(sizeof(sql_query_string), sql_query_string,
+                                       "SELECT rule_id FROM mail_rule_tbl WHERE action_type = %d AND type = %d AND UPPER(filter_name) = UPPER(\'%q\')", rule->action_type, rule->type, rule->filter_name);
+               }
+               break;
+       case EMAIL_FILTER_BLOCK:
+               if (rule->type == EMAIL_FILTER_FROM)
+                       sqlite3_snprintf(sizeof(sql_query_string), sql_query_string,
+                               "SELECT rule_id FROM mail_rule_tbl WHERE action_type = %d AND type = %d AND UPPER(value2) = UPPER(\'%q\')",
+                               rule->action_type, rule->type, rule->value2);
+               else if (rule->type == EMAIL_FILTER_SUBJECT)
+                       sqlite3_snprintf(sizeof(sql_query_string), sql_query_string,
+                               "SELECT rule_id FROM mail_rule_tbl WHERE action_type = %d AND type = %d AND UPPER(value) = UPPER(\'%q\')",
+                               rule->action_type, rule->type, rule->value);
+               else if (rule->type == (EMAIL_FILTER_SUBJECT | EMAIL_FILTER_FROM))
+                       sqlite3_snprintf(sizeof(sql_query_string), sql_query_string,
+                               "SELECT rule_id FROM mail_rule_tbl WHERE action_type = %d AND (type = %d AND UPPER(value) = UPPER(\'%q\')) OR (type = %d AND UPPER(value2) = UPPER(\'%q\'))",
+                               rule->action_type, EMAIL_FILTER_SUBJECT, rule->value, EMAIL_FILTER_FROM, rule->value2);
+               break;
 
+       default:
+               EM_DEBUG_EXCEPTION("Invalid parameter : rule->action_type[%d]", rule->action_type);
+               error = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+               break;
+       }
 
        EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
-       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE; goto FINISH_OFF;},
                ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
 
-
        EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
-       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE; goto FINISH_OFF;},
                ("sqlite3_step fail:%d", rc));
 
-       if (rc == SQLITE_DONE)  {
+       if (rc == SQLITE_DONE) {
                EM_DEBUG_EXCEPTION(" no matched rule found...");
                error = EMAIL_ERROR_FILTER_NOT_FOUND;
-               goto FINISH_OFF;
        }
 
-
        ret = true;
 
 FINISH_OFF:
-       if (hStmt != NULL)  {
+
+       if (hStmt != NULL) {
                EM_DEBUG_LOG("before sqlite3_finalize hStmt = %p", hStmt);
 
                rc = sqlite3_finalize(hStmt);
-               if (rc != SQLITE_OK)  {
+               if (rc != SQLITE_OK) {
                        EM_DEBUG_EXCEPTION(" sqlite3_finalize failed - %d", rc);
                        error = EMAIL_ERROR_DB_FAILURE;
                }
        }
 
-
        EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
        _DISCONNECT_DB;
 
@@ -6945,10 +7200,8 @@ INTERNAL_FUNC int emstorage_add_rule(emstorage_rule_tbl_t* rule, int transaction
 {
        EM_DEBUG_FUNC_BEGIN("rule[%p], transaction[%d], err_code[%p]", rule, transaction, err_code);
 
-       if (!rule)  {   /*  only global rule supported. */
-               if (rule != NULL)
-                       EM_DEBUG_EXCEPTION(" rule->account_id[%d]", rule->account_id);
-
+       if (!rule) {    /*  only global rule supported. */
+               EM_DEBUG_LOG("rule is NULL");
                if (err_code != NULL)
                        *err_code = EMAIL_ERROR_INVALID_PARAM;
                return false;
@@ -6985,8 +7238,10 @@ INTERNAL_FUNC int emstorage_add_rule(emstorage_rule_tbl_t* rule, int transaction
                "INSERT INTO mail_rule_tbl VALUES "
                "( ?"           /*  account id */
                ", ?"           /*  rule_id */
+               ", ?"           /*  filter_name */
                ", ?"           /*  type */
                ", ?"           /*  value */
+               ", ?"           /*  value2 */
                ", ?"           /*  action_type */
                ", ?"           /*  target_mailbox_id */
                ", ?"           /*  flag1 */
@@ -7001,8 +7256,10 @@ INTERNAL_FUNC int emstorage_add_rule(emstorage_rule_tbl_t* rule, int transaction
 
        _bind_stmt_field_data_int(hStmt, ACCOUNT_ID_IDX_IN_MAIL_RULE_TBL, rule->account_id);
        _bind_stmt_field_data_int(hStmt, RULE_ID_IDX_IN_MAIL_RULE_TBL, rule->rule_id);
+       _bind_stmt_field_data_string(hStmt, FILTER_NAME_IDX_IN_MAIL_RULE_TBL, (char*)rule->filter_name, 0, FILTER_NAME_LEN_IN_MAIL_RULE_TBL);
        _bind_stmt_field_data_int(hStmt, TYPE_IDX_IN_MAIL_RULE_TBL, rule->type);
        _bind_stmt_field_data_string(hStmt, VALUE_IDX_IN_MAIL_RULE_TBL, (char*)rule->value, 0, VALUE_LEN_IN_MAIL_RULE_TBL);
+       _bind_stmt_field_data_string(hStmt, VALUE2_IDX_IN_MAIL_RULE_TBL, (char*)rule->value2, 0, VALUE2_LEN_IN_MAIL_RULE_TBL);
        _bind_stmt_field_data_int(hStmt, ACTION_TYPE_IDX_IN_MAIL_RULE_TBL, rule->action_type);
        _bind_stmt_field_data_int(hStmt, TARGET_MAILBOX_ID_IDX_IN_MAIL_RULE_TBL, rule->target_mailbox_id);
        _bind_stmt_field_data_int(hStmt, FLAG1_IDX_IN_MAIL_RULE_TBL, rule->flag1);
@@ -7015,6 +7272,8 @@ INTERNAL_FUNC int emstorage_add_rule(emstorage_rule_tbl_t* rule, int transaction
        ret = true;
 
 FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
        if (hStmt != NULL)  {
                EM_DEBUG_LOG(" Before sqlite3_finalize hStmt = %p", hStmt);
 
@@ -7026,9 +7285,6 @@ FINISH_OFF:
                }
        }
 
-       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
-       _DISCONNECT_DB;
-
        if (err_code != NULL)
                *err_code = error;
 
@@ -7176,7 +7432,7 @@ INTERNAL_FUNC int emstorage_get_mail_count(int account_id, int mailbox_id, int *
                        SNPRINTF(sql_query_string + EM_SAFE_STRLEN(sql_query_string), sizeof(sql_query_string)-(EM_SAFE_STRLEN(sql_query_string)+1), " AND account_id = %d", account_id);
 
                if (mailbox_id) {
-                       SNPRINTF(sql_query_string + EM_SAFE_STRLEN(sql_query_string), sizeof(sql_query_string)-(EM_SAFE_STRLEN(sql_query_string)+1), " AND mailbox_id = '%d", mailbox_id);
+                       SNPRINTF(sql_query_string + EM_SAFE_STRLEN(sql_query_string), sizeof(sql_query_string)-(EM_SAFE_STRLEN(sql_query_string)+1), " AND mailbox_id = %d", mailbox_id);
                }
                else
                        SNPRINTF(sql_query_string + EM_SAFE_STRLEN(sql_query_string), sizeof(sql_query_string)-(EM_SAFE_STRLEN(sql_query_string)+1), " AND mailbox_type NOT IN (3, 5)");
@@ -7287,7 +7543,7 @@ INTERNAL_FUNC int emstorage_get_mail_field_by_id(int mail_id, int type, emstorag
                ("sqlite3_step fail:%d", rc));
 
        if (rc == SQLITE_DONE)  {
-               EM_DEBUG_EXCEPTION("no matched mail found...");
+               EM_DEBUG_LOG("no matched mail found...");
                error = EMAIL_ERROR_MAIL_NOT_FOUND;
                goto FINISH_OFF;
        }
@@ -7442,7 +7698,7 @@ INTERNAL_FUNC int emstorage_get_mail_field_by_multiple_mail_id(int mail_ids[], i
        }
 
        if (rc == SQLITE_DONE)  {
-               EM_DEBUG_EXCEPTION("no matched mail found...");
+               EM_DEBUG_LOG("no matched mail found...");
                error = EMAIL_ERROR_MAIL_NOT_FOUND;
                goto FINISH_OFF;
        }
@@ -7770,6 +8026,8 @@ INTERNAL_FUNC int emstorage_mail_search_result(int search_handle, emstorage_mail
                        _get_stmt_field_data_int   (hStmt, (int*)&(p_data_tbl->digest_type), DIGEST_TYPE_IDX_IN_MAIL_TBL);
                        _get_stmt_field_data_int   (hStmt, (int*)&(p_data_tbl->smime_type), SMIME_TYPE_IDX_IN_MAIL_TBL);
                        _get_stmt_field_data_int   (hStmt, (int*)&(p_data_tbl->scheduled_sending_time), SCHEDULED_SENDING_TIME_IDX_IN_MAIL_TBL);
+                       _get_stmt_field_data_int   (hStmt, (int*)&(p_data_tbl->remaining_resend_times), SCHEDULED_SENDING_TIME_IDX_IN_MAIL_TBL);
+                       _get_stmt_field_data_int   (hStmt, (int*)&(p_data_tbl->tag_id), TAG_ID_IDX_IN_MAIL_TBL);
                        _get_stmt_field_data_int   (hStmt, (int*)&(p_data_tbl->eas_data_length), EAS_DATA_LENGTH_IDX_IN_MAIL_TBL);
                        _get_stmt_field_data_blob   (hStmt, (void**)&(p_data_tbl->eas_data), EAS_DATA_IDX_IN_MAIL_TBL);
 
@@ -7785,7 +8043,8 @@ INTERNAL_FUNC int emstorage_mail_search_result(int search_handle, emstorage_mail
                                _get_stmt_field_data_string(hStmt, &(p_data_tbl->email_address_recipient), 1, EMAIL_ADDRESS_RECIPIENT_IDX_IN_MAIL_TBL);
                                _get_stmt_field_data_int   (hStmt, &(p_data_tbl->attachment_count), ATTACHMENT_COUNT_IDX_IN_MAIL_TBL);
                                _get_stmt_field_data_string(hStmt, &(p_data_tbl->preview_text), 1, PREVIEW_TEXT_IDX_IN_MAIL_TBL);
-
+                               _get_stmt_field_data_int   (hStmt, (int*)&(p_data_tbl->replied_time), REPLIED_TIME_IDX_IN_MAIL_TBL);
+                               _get_stmt_field_data_int   (hStmt, (int*)&(p_data_tbl->forwarded_time), FORWARDED_TIME_IDX_IN_MAIL_TBL);
                        }
 
                        if (p_data_tbl->body_download_status)  {
@@ -7955,6 +8214,10 @@ INTERNAL_FUNC int emstorage_change_mail(int mail_id, emstorage_mail_tbl_t* mail,
                ", preview_text = ?"
                ", smime_type = ?"
                ", scheduled_sending_time = ?"
+               ", remaining_resend_times = ?"
+               ", tag_id = ?"
+               ", replied_time = ?"
+               ", forwarded_time = ?"
                ", eas_data_length = ?"
                ", eas_data = ?"
                " WHERE mail_id = %d AND account_id != 0 "
@@ -7997,9 +8260,13 @@ INTERNAL_FUNC int emstorage_change_mail(int mail_id, emstorage_mail_tbl_t* mail,
        _bind_stmt_field_data_int   (hStmt, i++, mail->lock_status);
        _bind_stmt_field_data_string(hStmt, i++, (char *)mail->message_id, 0, MESSAGE_ID_LEN_IN_MAIL_TBL);
        _bind_stmt_field_data_int   (hStmt, i++, mail->report_status);
-       _bind_stmt_field_data_string(hStmt, i++, (char *)mail->preview_text, 1, PREVIEWBODY_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_nstring(hStmt, i++, (char *)mail->preview_text, 1, PREVIEWBODY_LEN_IN_MAIL_TBL);
        _bind_stmt_field_data_int   (hStmt, i++, mail->smime_type);
        _bind_stmt_field_data_int   (hStmt, i++, mail->scheduled_sending_time);
+       _bind_stmt_field_data_int   (hStmt, i++, mail->remaining_resend_times);
+       _bind_stmt_field_data_int   (hStmt, i++, mail->tag_id);
+       _bind_stmt_field_data_int   (hStmt, i++, mail->replied_time);
+       _bind_stmt_field_data_int   (hStmt, i++, mail->forwarded_time);
        _bind_stmt_field_data_int   (hStmt, i++, mail->eas_data_length);
        _bind_stmt_field_data_blob  (hStmt, i++, (void*)mail->eas_data, mail->eas_data_length);
 
@@ -8009,17 +8276,16 @@ INTERNAL_FUNC int emstorage_change_mail(int mail_id, emstorage_mail_tbl_t* mail,
 
        rc = sqlite3_changes(local_db_handle);
        if (rc == 0)  {
-               EM_DEBUG_EXCEPTION(" no matched mail found...");
+               EM_DEBUG_LOG(" no matched mail found...");
                error = EMAIL_ERROR_MAIL_NOT_FOUND;
                goto FINISH_OFF;
        }
-       SNPRINTF(mailbox_id_param_string, 10, "%d", mail->mailbox_id);
-       if (!emcore_notify_storage_event(NOTI_MAIL_UPDATE, mail->account_id, mail->mail_id, mailbox_id_param_string, 0))
-               EM_DEBUG_EXCEPTION(" emcore_notify_storage_event Failed [ NOTI_MAIL_UPDATE ] >>>> ");
 
        ret = true;
 
 FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
        if (hStmt != NULL)  {
                EM_DEBUG_LOG("Before sqlite3_finalize hStmt = %p", hStmt);
                rc = sqlite3_finalize(hStmt);
@@ -8029,8 +8295,12 @@ FINISH_OFF:
                }
        }
 
-       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
-       _DISCONNECT_DB;
+
+       if(error == EMAIL_ERROR_NONE && mail) {
+               SNPRINTF(mailbox_id_param_string, 10, "%d", mail->mailbox_id);
+               if (!emcore_notify_storage_event (NOTI_MAIL_UPDATE, mail->account_id, mail->mail_id, mailbox_id_param_string, 0))
+                       EM_DEBUG_EXCEPTION ("emcore_notify_storage_event failed [NOTI_MAIL_UPDATE]");
+       }
 
        if (err_code != NULL)
                *err_code = error;
@@ -8083,7 +8353,7 @@ FINISH_OFF:
 
 INTERNAL_FUNC int emstorage_set_field_of_mails_with_integer_value(int account_id, int mail_ids[], int mail_ids_count, char *field_name, int value, int transaction, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("account_id [%d], mail_ids[%p], mail_ids_count[%d], field_name[%s], value[%d], transaction[%d], err_code[%p]", account_id, mail_ids, mail_ids_count, field_name, value, transaction, err_code);
+       EM_DEBUG_FUNC_BEGIN_SEC("account_id [%d], mail_ids[%p], mail_ids_count[%d], field_name[%s], value[%d], transaction[%d], err_code[%p]", account_id, mail_ids, mail_ids_count, field_name, value, transaction, err_code);
        int i = 0;
        int error = EMAIL_ERROR_NONE;
        int rc = 0;
@@ -8117,8 +8387,9 @@ INTERNAL_FUNC int emstorage_set_field_of_mails_with_integer_value(int account_id
 
        if(!mail_id_string_buffer) {
                EM_DEBUG_EXCEPTION("em_malloc failed");
-               error = EMAIL_ERROR_OUT_OF_MEMORY;
-               goto FINISH_OFF;
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_OUT_OF_MEMORY;
+               return false;
        }
 
        for(i = 0; i < mail_ids_count; i++)
@@ -8132,8 +8403,10 @@ INTERNAL_FUNC int emstorage_set_field_of_mails_with_integer_value(int account_id
 
        if(!parameter_string) {
                EM_DEBUG_EXCEPTION("em_malloc failed");
-               error = EMAIL_ERROR_OUT_OF_MEMORY;
-               goto FINISH_OFF;
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_OUT_OF_MEMORY;
+               EM_SAFE_FREE (mail_id_string_buffer);
+               return false;
        }
 
        SNPRINTF(parameter_string, QUERY_SIZE, "%s%c%s", field_name, 0x01, mail_id_string_buffer);
@@ -8141,13 +8414,13 @@ INTERNAL_FUNC int emstorage_set_field_of_mails_with_integer_value(int account_id
        /* Write query string */
        SNPRINTF(sql_query_string, QUERY_SIZE, "UPDATE mail_tbl SET %s = %d WHERE mail_id in (%s) AND account_id = %d", field_name, value, mail_id_string_buffer, account_id);
 
-       EM_DEBUG_LOG("sql_query_string [%s]", sql_query_string);
+       EM_DEBUG_LOG_DEV ("sql_query_string [%s]", sql_query_string);
 
        /* Execute query */
        EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
        EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
        EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
-               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+               ("sqlite3_exec failed [%d] [%s]", rc, sql_query_string));
        if (sqlite3_changes(local_db_handle) == 0)
                EM_DEBUG_LOG("no mail matched...");
 
@@ -8157,8 +8430,10 @@ FINISH_OFF:
        EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
        _DISCONNECT_DB;
 
-       if (ret && parameter_string && !emcore_notify_storage_event(NOTI_MAIL_FIELD_UPDATE, account_id, target_mail_attribute_type, parameter_string, value))
-               EM_DEBUG_EXCEPTION("emcore_notify_storage_event failed : NOTI_MAIL_FIELD_UPDATE [%s,%d]", field_name, value);
+       if (error == EMAIL_ERROR_NONE && parameter_string) {
+               if (!emcore_notify_storage_event (NOTI_MAIL_FIELD_UPDATE, account_id, target_mail_attribute_type, parameter_string, value))
+                       EM_DEBUG_EXCEPTION_SEC ("emcore_notify_storage_event failed : NOTI_MAIL_FIELD_UPDATE [%s,%d]", field_name, value);
+       }
 
        EM_SAFE_FREE(mail_id_string_buffer);
        EM_SAFE_FREE(parameter_string);
@@ -8214,7 +8489,7 @@ INTERNAL_FUNC int emstorage_change_mail_text_field(int mail_id, emstorage_mail_t
 
                rc = sqlite3_changes(local_db_handle);
                if (rc == 0)  {
-                       EM_DEBUG_EXCEPTION(" no matched mail found...");
+                       EM_DEBUG_LOG(" no matched mail found...");
                        error = EMAIL_ERROR_MAIL_NOT_FOUND;
                        goto FINISH_OFF;
                }
@@ -8223,6 +8498,8 @@ INTERNAL_FUNC int emstorage_change_mail_text_field(int mail_id, emstorage_mail_t
        ret = true;
 
 FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
 
        if (hStmt != NULL) {
                rc = sqlite3_finalize(hStmt);
@@ -8233,9 +8510,6 @@ FINISH_OFF:
                hStmt = NULL;
        }
 
-       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
-       _DISCONNECT_DB;
-
        if (err_code != NULL)
                *err_code = error;
 
@@ -8312,7 +8586,7 @@ INTERNAL_FUNC int emstorage_change_mail_field(int mail_id, email_mail_change_typ
                        _bind_stmt_field_data_int(hStmt, i++, mail->flags_forwarded_field);
                        _bind_stmt_field_data_int(hStmt, i++, mail->DRM_status);
                        _bind_stmt_field_data_int(hStmt, i++, mail->attachment_count);
-                       _bind_stmt_field_data_string(hStmt, i++, (char *)mail->preview_text, 0, PREVIEWBODY_LEN_IN_MAIL_TBL);
+                       _bind_stmt_field_data_nstring(hStmt, i++, (char *)mail->preview_text, 0, PREVIEWBODY_LEN_IN_MAIL_TBL);
                        _bind_stmt_field_data_int(hStmt, i++, mail->meeting_request_status);
                        _bind_stmt_field_data_int(hStmt, i++, mail->message_class);
                        _bind_stmt_field_data_int(hStmt, i++, mail->digest_type);
@@ -8453,6 +8727,10 @@ INTERNAL_FUNC int emstorage_change_mail_field(int mail_id, email_mail_change_typ
                                ", digest_type = ?"
                                ", smime_type = ?"
                                ", scheduled_sending_time = ?"
+                               ", remaining_resend_times = ?"
+                               ", tag_id = ?"
+                               ", replied_time = ?"
+                               ", forwarded_time = ?"
                                ", eas_data_length = ?"
                                ", eas_data = ?"
                                " WHERE mail_id = %d AND account_id != 0"
@@ -8460,7 +8738,7 @@ INTERNAL_FUNC int emstorage_change_mail_field(int mail_id, email_mail_change_typ
 
 
                        EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
-                       EM_DEBUG_LOG(" before sqlite3_prepare hStmt = %p", hStmt);
+                       EM_DEBUG_LOG_DEV (" before sqlite3_prepare hStmt = %p", hStmt);
                        EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
                                ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
                        i = 0;
@@ -8488,7 +8766,7 @@ INTERNAL_FUNC int emstorage_change_mail_field(int mail_id, email_mail_change_typ
                        _bind_stmt_field_data_string(hStmt, i++, (char*)mail->file_path_html, 0, TEXT_2_LEN_IN_MAIL_TBL);
                        _bind_stmt_field_data_string(hStmt, i++, (char*)mail->file_path_mime_entity, 0, MIME_ENTITY_LEN_IN_MAIL_TBL);
                        _bind_stmt_field_data_int   (hStmt, i++, mail->mail_size);
-                       _bind_stmt_field_data_string(hStmt, i++, (char*)mail->preview_text, 1, PREVIEWBODY_LEN_IN_MAIL_TBL);
+                       _bind_stmt_field_data_nstring(hStmt, i++, (char*)mail->preview_text, 1, PREVIEWBODY_LEN_IN_MAIL_TBL);
                        _bind_stmt_field_data_int   (hStmt, i++, mail->body_download_status);
                        _bind_stmt_field_data_int   (hStmt, i++, mail->attachment_count);
                        _bind_stmt_field_data_int   (hStmt, i++, mail->inline_content_count);
@@ -8497,6 +8775,10 @@ INTERNAL_FUNC int emstorage_change_mail_field(int mail_id, email_mail_change_typ
                        _bind_stmt_field_data_int   (hStmt, i++, mail->digest_type);
                        _bind_stmt_field_data_int   (hStmt, i++, mail->smime_type);
                        _bind_stmt_field_data_int   (hStmt, i++, mail->scheduled_sending_time);
+                       _bind_stmt_field_data_int   (hStmt, i++, mail->remaining_resend_times);
+                       _bind_stmt_field_data_int   (hStmt, i++, mail->tag_id);
+                       _bind_stmt_field_data_int   (hStmt, i++, mail->replied_time);
+                       _bind_stmt_field_data_int   (hStmt, i++, mail->forwarded_time);
                        _bind_stmt_field_data_int   (hStmt, i++, mail->eas_data_length);
                        _bind_stmt_field_data_blob  (hStmt, i++, (void*)mail->eas_data, mail->eas_data_length);
                        break;
@@ -8596,7 +8878,7 @@ INTERNAL_FUNC int emstorage_change_mail_field(int mail_id, email_mail_change_typ
                        _bind_stmt_field_data_string(hStmt, i++, (char *)mail->file_path_html,  0, TEXT_2_LEN_IN_MAIL_TBL);
                        _bind_stmt_field_data_int(hStmt, i++, mail->attachment_count);
                        _bind_stmt_field_data_int(hStmt, i++, mail->inline_content_count);
-                       _bind_stmt_field_data_string(hStmt, i++, (char *)mail->preview_text,    0, PREVIEWBODY_LEN_IN_MAIL_TBL);
+                       _bind_stmt_field_data_nstring(hStmt, i++, (char *)mail->preview_text,    0, PREVIEWBODY_LEN_IN_MAIL_TBL);
 
                        break;
 
@@ -8637,8 +8919,7 @@ INTERNAL_FUNC int emstorage_change_mail_field(int mail_id, email_mail_change_typ
                        ("sqlite3_step fail:%d", rc));
                rc = sqlite3_changes(local_db_handle);
                if (rc == 0)  {
-                       EM_DEBUG_EXCEPTION(" no matched mail found...");
-
+                       EM_DEBUG_LOG(" no matched mail found...");
                        error = EMAIL_ERROR_MAIL_NOT_FOUND;
                        goto FINISH_OFF;
                }
@@ -8647,8 +8928,7 @@ INTERNAL_FUNC int emstorage_change_mail_field(int mail_id, email_mail_change_typ
        if (mail->account_id == 0) {
                emstorage_mail_tbl_t* mail_for_account_tbl = NULL;
                if (!emstorage_get_mail_field_by_id(mail_id, RETRIEVE_ACCOUNT, &mail_for_account_tbl, true, &error) || !mail_for_account_tbl) {
-                       EM_DEBUG_EXCEPTION(" emstorage_get_mail_field_by_id failed - %d", error);
-/*              */
+                       EM_DEBUG_EXCEPTION ("emstorage_get_mail_field_by_id error [%d]", error);
                        goto FINISH_OFF;
                }
                mail->account_id = mail_for_account_tbl->account_id;
@@ -8659,6 +8939,8 @@ INTERNAL_FUNC int emstorage_change_mail_field(int mail_id, email_mail_change_typ
        ret = true;
 
 FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
 
        if (hStmt != NULL)  {
                rc = sqlite3_finalize(hStmt);
@@ -8668,25 +8950,19 @@ FINISH_OFF:
                }
                hStmt = NULL;
        }
-
-       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
-       _DISCONNECT_DB;
-
-       /*h.gahlaut@samsung.com: Moving publication of notification after committing transaction to DB */
-
-       if (ret == true &&  move_flag != 1) {
-               if (!emstorage_get_mailbox_id_by_mailbox_type(mail->account_id, EMAIL_MAILBOX_TYPE_SENTBOX, &mailbox_id, false, &error))
-                       EM_DEBUG_EXCEPTION(" emstorage_get_mailbox_id_by_mailbox_type failed - %d", error);
+       if (error == EMAIL_ERROR_NONE &&  move_flag != 1 && transaction) {
+               if (!emstorage_get_mailbox_id_by_mailbox_type( mail->account_id, EMAIL_MAILBOX_TYPE_SENTBOX, &mailbox_id, false, &error))
+                       EM_DEBUG_EXCEPTION("emstorage_get_mailbox_id_by_mailbox_type error [%d]", error);
 
                if (mail->mailbox_id == mailbox_id) {
                        SNPRINTF(mailbox_id_param_string, 10, "%d", mail->mailbox_id);
-                       if (!emcore_notify_storage_event(NOTI_MAIL_UPDATE, mail->account_id, mail_id, mailbox_id_param_string, type))
-                               EM_DEBUG_EXCEPTION(" emcore_notify_storage_event Failed [ NOTI_MAIL_UPDATE ] >>>> ");
+                       if (!emcore_notify_storage_event (NOTI_MAIL_UPDATE, mail->account_id, mail_id, mailbox_id_param_string, type))
+                               EM_DEBUG_EXCEPTION ("emcore_notify_storage_event error [ NOTI_MAIL_UPDATE ] >>>> ");
                }
                else {
                        /* h.gahlaut@samsung.com: Jan 10, 2011 Publishing noti to refresh outbox when email sending status changes */
-                       if (!emcore_notify_storage_event(NOTI_MAIL_UPDATE, mail->account_id, mail_id, NULL, type))
-                               EM_DEBUG_EXCEPTION(" emcore_notify_storage_event Failed [ NOTI_MAIL_UPDATE ] ");
+                       if (!emcore_notify_storage_event (NOTI_MAIL_UPDATE, mail->account_id, mail_id, NULL, type))
+                               EM_DEBUG_EXCEPTION (" emcore_notify_storage_event error [ NOTI_MAIL_UPDATE ]");
                }
        }
 
@@ -8846,6 +9122,10 @@ INTERNAL_FUNC int emstorage_add_mail(emstorage_mail_tbl_t *mail_tbl_data, int ge
                ", ?" /*  digest_type */
                ", ?" /*  smime_type */
                ", ?" /*  scheduled_sending_time */
+               ", ?" /*  remaining_resend_times */
+               ", ?" /*  tag_id */
+               ", ?" /*  replied_time */
+               ", ?" /*  forwarded_time */
                ", ?" /*  eas_data_length */
                ", ?" /*  eas_data */
                ")");
@@ -8896,12 +9176,16 @@ INTERNAL_FUNC int emstorage_add_mail(emstorage_mail_tbl_t *mail_tbl_data, int ge
        _bind_stmt_field_data_int   (hStmt, INLINE_CONTENT_COUNT_IDX_IN_MAIL_TBL, mail_tbl_data->inline_content_count);
        _bind_stmt_field_data_int   (hStmt, THREAD_ID_IDX_IN_MAIL_TBL, mail_tbl_data->thread_id);
        _bind_stmt_field_data_int   (hStmt, THREAD_ITEM_COUNT_IDX_IN_MAIL_TBL, mail_tbl_data->thread_item_count);
-       _bind_stmt_field_data_string(hStmt, PREVIEW_TEXT_IDX_IN_MAIL_TBL, (char*)mail_tbl_data->preview_text, 1, PREVIEWBODY_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_nstring(hStmt, PREVIEW_TEXT_IDX_IN_MAIL_TBL, (char*)mail_tbl_data->preview_text, 1, PREVIEWBODY_LEN_IN_MAIL_TBL);
        _bind_stmt_field_data_int   (hStmt, MEETING_REQUEST_STATUS_IDX_IN_MAIL_TBL, mail_tbl_data->meeting_request_status);
        _bind_stmt_field_data_int   (hStmt, MESSAGE_CLASS_IDX_IN_MAIL_TBL, mail_tbl_data->message_class);
        _bind_stmt_field_data_int   (hStmt, DIGEST_TYPE_IDX_IN_MAIL_TBL, mail_tbl_data->digest_type);
        _bind_stmt_field_data_int   (hStmt, SMIME_TYPE_IDX_IN_MAIL_TBL, mail_tbl_data->smime_type);
        _bind_stmt_field_data_int   (hStmt, SCHEDULED_SENDING_TIME_IDX_IN_MAIL_TBL, mail_tbl_data->scheduled_sending_time);
+       _bind_stmt_field_data_int   (hStmt, REMAINING_RESEND_TIMES_IDX_IN_MAIL_TBL, mail_tbl_data->remaining_resend_times);
+       _bind_stmt_field_data_int   (hStmt, TAG_ID_IDX_IN_MAIL_TBL, mail_tbl_data->tag_id);
+       _bind_stmt_field_data_int   (hStmt, REPLIED_TIME_IDX_IN_MAIL_TBL, mail_tbl_data->replied_time);
+       _bind_stmt_field_data_int   (hStmt, FORWARDED_TIME_IDX_IN_MAIL_TBL, mail_tbl_data->forwarded_time);
        _bind_stmt_field_data_int   (hStmt, EAS_DATA_LENGTH_IDX_IN_MAIL_TBL, mail_tbl_data->eas_data_length);
        _bind_stmt_field_data_blob  (hStmt, EAS_DATA_IDX_IN_MAIL_TBL, (void*)mail_tbl_data->eas_data, mail_tbl_data->eas_data_length);
 
@@ -8911,6 +9195,8 @@ INTERNAL_FUNC int emstorage_add_mail(emstorage_mail_tbl_t *mail_tbl_data, int ge
        ret = true;
 
 FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
 
        if (hStmt != NULL)  {
                rc = sqlite3_finalize(hStmt);
@@ -8920,10 +9206,6 @@ FINISH_OFF:
                }
        }
 
-       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
-       _DISCONNECT_DB;
-
-
        if (err_code != NULL)
                *err_code = error;
 
@@ -8955,7 +9237,9 @@ INTERNAL_FUNC int emstorage_move_multiple_mails_on_db(int input_source_account_i
 
        if ((error = emstorage_get_mailbox_by_id(input_mailbox_id, &result_mailbox)) != EMAIL_ERROR_NONE || !result_mailbox) {
                EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_id failed. [%d]", error);
-               goto FINISH_OFF;
+               if (err_code != NULL)
+                       *err_code = error;
+               return false;
        }
 
        if (result_mailbox->mailbox_name) {
@@ -9186,7 +9470,7 @@ INTERNAL_FUNC int emstorage_delete_mail_by_account(int account_id, int transacti
 
        rc = sqlite3_changes(local_db_handle);
        if (rc == 0)  {
-               EM_DEBUG_EXCEPTION(" no mail found...");
+               EM_DEBUG_LOG(" no mail found...");
                error = EMAIL_ERROR_MAIL_NOT_FOUND;
        }
 
@@ -9200,7 +9484,7 @@ INTERNAL_FUNC int emstorage_delete_mail_by_account(int account_id, int transacti
 
        rc = sqlite3_changes(local_db_handle);
        if (rc == 0)  {
-               EM_DEBUG_EXCEPTION("no mail found...");
+               EM_DEBUG_LOG("No mail found...");
                error = EMAIL_ERROR_MAIL_NOT_FOUND;
        }
 
@@ -9215,21 +9499,22 @@ INTERNAL_FUNC int emstorage_delete_mail_by_account(int account_id, int transacti
 
        rc = sqlite3_changes(local_db_handle);
        if (rc == 0) {
-               EM_DEBUG_EXCEPTION("no mail found...");
+               EM_DEBUG_LOG("No mail found...");
                error = EMAIL_ERROR_MAIL_NOT_FOUND;
        }
 #endif
 
-       if (!emcore_notify_storage_event(NOTI_MAIL_DELETE_WITH_ACCOUNT, account_id, 0 , NULL, 0))
-               EM_DEBUG_EXCEPTION(" emcore_notify_storage_event Failed [ NOTI_MAIL_DELETE_ALL ]");
-
        ret = true;
 
 FINISH_OFF:
-
        EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
        _DISCONNECT_DB;
 
+       if (error == EMAIL_ERROR_NONE) {
+               if (!emcore_notify_storage_event (NOTI_MAIL_DELETE_WITH_ACCOUNT, account_id, 0 , NULL, 0))
+                       EM_DEBUG_EXCEPTION ("emcore_notify_storage_event Failed [ NOTI_MAIL_DELETE_ALL ]");
+       }
+
        if (err_code != NULL)
                *err_code = error;
 
@@ -9253,7 +9538,6 @@ INTERNAL_FUNC int emstorage_delete_mail_by_mailbox(int account_id, int mailbox_i
        char sql_query_string[QUERY_SIZE] = {0, };
 
        sqlite3 *local_db_handle = emstorage_get_db_connection();
-
        EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
 
        SNPRINTF(sql_query_string, sizeof(sql_query_string), "DELETE FROM mail_tbl WHERE account_id = %d AND mailbox_id = '%d'", account_id, mailbox_id);
@@ -9282,15 +9566,17 @@ INTERNAL_FUNC int emstorage_delete_mail_by_mailbox(int account_id, int mailbox_i
                ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
 #endif
 
-       if (!emcore_notify_storage_event(NOTI_MAIL_DELETE_ALL, account_id, mailbox_id , 0, 0))
-               EM_DEBUG_EXCEPTION(" emcore_notify_storage_event Failed [ NOTI_MAIL_DELETE_ALL ] >>>> ");
-
        ret = true;
 
 FINISH_OFF:
        EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
        _DISCONNECT_DB;
 
+       if (error == EMAIL_ERROR_NONE) {
+               if (!emcore_notify_storage_event(NOTI_MAIL_DELETE_ALL, account_id, mailbox_id , 0, 0))
+                       EM_DEBUG_EXCEPTION(" emcore_notify_storage_event Failed [ NOTI_MAIL_DELETE_ALL ] >>>> ");
+       }
+
        if (err_code != NULL)
                *err_code = error;
 
@@ -9346,17 +9632,14 @@ INTERNAL_FUNC int emstorage_free_mail(emstorage_mail_tbl_t** mail_list, int coun
 }
 
 #ifdef __FEATURE_BODY_SEARCH__
-INTERNAL_FUNC int emstorage_free_mail_text(emstorage_mail_text_tbl_t** mail_text_list, int count, int *err_code)
+INTERNAL_FUNC void emstorage_free_mail_text(emstorage_mail_text_tbl_t** mail_text_list, int count, int *err_code)
 {
        EM_DEBUG_FUNC_BEGIN("mail_text_list[%p], count[%d], err_code[%p]", mail_text_list, count, err_code);
 
        if (count > 0) {
                if ((mail_text_list == NULL) || (*mail_text_list == NULL)) {
-                       EM_DEBUG_EXCEPTION("mail_text_list[%p], count[%d]", mail_text_list, count);
-
-                       if (err_code)
-                               *err_code = EMAIL_ERROR_INVALID_PARAM;
-                       return false;
+                       EM_DEBUG_LOG("Nothing to free: mail_text_list[%p]", mail_text_list);
+                       return;
                }
 
                emstorage_mail_text_tbl_t *p = *mail_text_list;
@@ -9368,11 +9651,7 @@ INTERNAL_FUNC int emstorage_free_mail_text(emstorage_mail_text_tbl_t** mail_text
                EM_SAFE_FREE(*mail_text_list);
        }
 
-       if (err_code != NULL)
-               *err_code = EMAIL_ERROR_NONE;
-
        EM_DEBUG_FUNC_END();
-       return true;
 }
 #endif
 
@@ -9409,7 +9688,6 @@ INTERNAL_FUNC int emstorage_get_attachment_count(int mail_id, int *count, int tr
        ret = true;
 
 FINISH_OFF:
-
        EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
        _DISCONNECT_DB;
 
@@ -9487,8 +9765,8 @@ INTERNAL_FUNC int emstorage_get_attachment_list(int input_mail_id, int input_tra
                _get_stmt_field_data_int   (hStmt, &(p_data_tbl[i].attachment_drm_method), ATTACHMENT_DRM_METHOD_IDX_IN_MAIL_ATTACHMENT_TBL);
                _get_stmt_field_data_int   (hStmt, &(p_data_tbl[i].attachment_inline_content_status), ATTACHMENT_INLINE_CONTENT_STATUS_IDX_IN_MAIL_ATTACHMENT_TBL);
                _get_stmt_field_data_string(hStmt, &(p_data_tbl[i].attachment_mime_type), 0, ATTACHMENT_MIME_TYPE_IDX_IN_MAIL_ATTACHMENT_TBL);
-
                EM_DEBUG_LOG("attachment[%d].attachment_id : %d", i, p_data_tbl[i].attachment_id);
+               EM_DEBUG_LOG("attachment_mime_type : %s", p_data_tbl[i].attachment_mime_type);
                EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
                EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; }, ("sqlite3_step fail:%d", rc));
        }
@@ -9509,7 +9787,6 @@ FINISH_OFF:
        }
 
        EMSTORAGE_FINISH_READ_TRANSACTION(input_transaction);
-
        _DISCONNECT_DB;
 
        EM_DEBUG_FUNC_END("error [%d]", error);
@@ -9540,18 +9817,18 @@ INTERNAL_FUNC int emstorage_get_attachment(int attachment_id, emstorage_attachme
        sqlite3_stmt* hStmt = NULL;
 
        EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
-       EM_DEBUG_LOG(" before sqlite3_prepare hStmt = %p", hStmt);
+       EM_DEBUG_LOG_DEV (" before sqlite3_prepare hStmt = %p", hStmt);
 
        EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
-               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+               ("sqlite3_prepare failed [%d] [%s]", rc, sql_query_string));
 
 
        EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
        EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
-               ("sqlite3_step fail:%d", rc));
+               ("sqlite3_step failed [%d] [%s]", rc, sql_query_string));
 
        if (rc == SQLITE_DONE)  {
-               EM_DEBUG_EXCEPTION("no matched attachment found...");
+               EM_DEBUG_LOG ("no matched attachment found...");
                error = EMAIL_ERROR_ATTACHMENT_NOT_FOUND;
                goto FINISH_OFF;
        }
@@ -9587,11 +9864,11 @@ FINISH_OFF:
                *attachment = p_data_tbl;
 
        if (hStmt != NULL)  {
-               EM_DEBUG_LOG("Before sqlite3_finalize hStmt = %p", hStmt);
+               EM_DEBUG_LOG_DEV ("Before sqlite3_finalize hStmt = %p", hStmt);
 
                rc = sqlite3_finalize(hStmt);
                if (rc != SQLITE_OK)  {
-                       EM_DEBUG_EXCEPTION("sqlite3_finalize failed - %d", rc);
+                       EM_DEBUG_EXCEPTION("sqlite3_finalize failed [%d]", rc);
                        error = EMAIL_ERROR_DB_FAILURE;
                }
        }
@@ -9800,19 +10077,21 @@ FINISH_OFF:
 }
 
 
-INTERNAL_FUNC int emstorage_rename_mailbox(int input_mailbox_id, char *input_new_mailbox_name, char *input_new_mailbox_alias, int input_transaction)
+INTERNAL_FUNC int emstorage_rename_mailbox(int input_mailbox_id, char *input_new_mailbox_name, char *input_new_mailbox_alias, void *input_eas_data, int input_eas_data_length, int input_transaction)
 {
-       EM_DEBUG_FUNC_BEGIN("input_mailbox_id[%d], input_new_mailbox_name[%p], input_new_mailbox_alias [%p], input_transaction[%d]", input_mailbox_id, input_new_mailbox_name, input_new_mailbox_alias, input_transaction);
+       EM_DEBUG_FUNC_BEGIN("input_mailbox_id[%d] input_new_mailbox_name[%p] input_new_mailbox_alias[%p] input_eas_data[%p] input_eas_data_length[%d] input_transaction[%d]", input_mailbox_id, input_new_mailbox_name, input_new_mailbox_alias, input_eas_data, input_eas_data_length, input_transaction);
 
        int rc = 0;
        int ret = false;
        int error = EMAIL_ERROR_NONE;
-       char sql_query_string[QUERY_SIZE] = {0, };
-       sqlite3 *local_db_handle = NULL;
+       int field_idx = 0;
        int account_id = 0;
-       emstorage_mailbox_tbl_t *old_mailbox_data = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
        char *replaced_mailbox_name = NULL;
        char *replaced_alias = NULL;
+       sqlite3 *local_db_handle = NULL;
+       DB_STMT hStmt = NULL;
+       emstorage_mailbox_tbl_t *old_mailbox_data = NULL;
 
        if (input_mailbox_id <= 0 || !input_new_mailbox_name || !input_new_mailbox_alias)  {
                EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
@@ -9835,25 +10114,57 @@ INTERNAL_FUNC int emstorage_rename_mailbox(int input_mailbox_id, char *input_new
 
        if ((error = emstorage_get_mailbox_by_id(input_mailbox_id, &old_mailbox_data)) != EMAIL_ERROR_NONE) {
                EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_id failed [%d]", error);
-               goto FINISH_OFF;
+               EM_SAFE_FREE (replaced_mailbox_name);
+               EM_SAFE_FREE (replaced_alias);
+               return error;
        }
        account_id = old_mailbox_data->account_id;
 
        EMSTORAGE_START_WRITE_TRANSACTION(input_transaction, error);
 
-       SNPRINTF(sql_query_string, sizeof(sql_query_string),
-               "UPDATE mail_box_tbl SET"
-               " mailbox_name = '%s'"
-               ",alias = '%s'"
-               " WHERE mailbox_id = %d"
-               , replaced_mailbox_name
-               , replaced_alias
-               , input_mailbox_id);
+       if(input_eas_data && input_eas_data_length > 0) {
+               SNPRINTF(sql_query_string, sizeof(sql_query_string),
+                       "UPDATE mail_box_tbl SET"
+                       " mailbox_name = ?"
+                       ",alias = ?"
+                       ",eas_data = ?"
+                       ",eas_data_length = ?"
+                       " WHERE mailbox_id = ?");
 
-       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
 
-       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
-               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+               EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                       ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+               _bind_stmt_field_data_string(hStmt, field_idx++ , input_new_mailbox_name, 0, ATTACHMENT_NAME_LEN_IN_MAIL_ATTACHMENT_TBL);
+               _bind_stmt_field_data_string(hStmt, field_idx++ , input_new_mailbox_alias, 0, ATTACHMENT_PATH_LEN_IN_MAIL_ATTACHMENT_TBL);
+               _bind_stmt_field_data_blob  (hStmt, field_idx++ , input_eas_data, input_eas_data_length);
+               _bind_stmt_field_data_int   (hStmt, field_idx++ , input_eas_data_length);
+               _bind_stmt_field_data_int   (hStmt, field_idx++ , input_mailbox_id);
+       }
+       else {
+               SNPRINTF(sql_query_string, sizeof(sql_query_string),
+                               "UPDATE mail_box_tbl SET"
+                               " mailbox_name = ?"
+                               ",alias = ?"
+                               " WHERE mailbox_id = ?");
+
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+
+               EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                       ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+               _bind_stmt_field_data_string(hStmt, field_idx++ , input_new_mailbox_name, 0, ATTACHMENT_NAME_LEN_IN_MAIL_ATTACHMENT_TBL);
+               _bind_stmt_field_data_string(hStmt, field_idx++ , input_new_mailbox_alias, 0, ATTACHMENT_PATH_LEN_IN_MAIL_ATTACHMENT_TBL);
+               _bind_stmt_field_data_int   (hStmt, field_idx++ , input_mailbox_id);
+       }
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((SQLITE_FULL == rc), {error = EMAIL_ERROR_MAIL_MEMORY_FULL;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
 
        if (sqlite3_changes(local_db_handle) == 0)
                EM_DEBUG_LOG("no mail_meeting_tbl matched...");
@@ -9861,16 +10172,15 @@ INTERNAL_FUNC int emstorage_rename_mailbox(int input_mailbox_id, char *input_new
        ret = true;
 
 FINISH_OFF:
-
        EMSTORAGE_FINISH_WRITE_TRANSACTION(input_transaction, ret, error);
-
-       if (ret) {
-               if (!emcore_notify_storage_event(NOTI_MAILBOX_RENAME, account_id, input_mailbox_id, input_new_mailbox_name, 0))
-                       EM_DEBUG_EXCEPTION(" emcore_notify_storage_event Failed [ NOTI_MAILBOX_RENAME ] >>>> ");
+       _DISCONNECT_DB;
+       if (error == EMAIL_ERROR_NONE) {
+               if (!emcore_notify_storage_event (NOTI_MAILBOX_RENAME, account_id, input_mailbox_id, input_new_mailbox_name, 0))
+                       EM_DEBUG_EXCEPTION ("emcore_notify_storage_event Failed [ NOTI_MAILBOX_RENAME ] >>>> ");
        }
        else {
-               if (!emcore_notify_storage_event(NOTI_MAILBOX_RENAME_FAIL, account_id, input_mailbox_id, input_new_mailbox_name, error))
-                       EM_DEBUG_EXCEPTION(" emcore_notify_storage_event Failed [ NOTI_MAILBOX_RENAME_FAIL ] >>>> ");
+               if (!emcore_notify_storage_event (NOTI_MAILBOX_RENAME_FAIL, account_id, input_mailbox_id, input_new_mailbox_name, error))
+                       EM_DEBUG_EXCEPTION ("emcore_notify_storage_event Failed [ NOTI_MAILBOX_RENAME_FAIL ] >>>> ");
        }
 
        EM_SAFE_FREE(replaced_mailbox_name);
@@ -9879,7 +10189,13 @@ FINISH_OFF:
        if (old_mailbox_data)
                emstorage_free_mailbox(&old_mailbox_data, 1, NULL);
 
-       _DISCONNECT_DB;
+       if (hStmt != NULL)  {
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_EXCEPTION(" sqlite3_finalize failed - %d", rc);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
 
        EM_DEBUG_FUNC_END("error [%d]", error);
        return error;
@@ -9895,8 +10211,9 @@ INTERNAL_FUNC int emstorage_get_new_attachment_no(int *attachment_no, int *err_c
 
        if (!attachment_no)  {
                EM_DEBUG_EXCEPTION("Invalid attachment");
-               error = EMAIL_ERROR_INVALID_PARAM;
-               goto FINISH_OFF;
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
        }
 
        *attachment_no = -1;
@@ -10023,7 +10340,7 @@ INTERNAL_FUNC int emstorage_add_attachment(emstorage_attachment_tbl_t* attachmen
 */
        rc = sqlite3_changes(local_db_handle);
        if (rc == 0)  {
-               EM_DEBUG_EXCEPTION(" no matched mail found...");
+               EM_DEBUG_LOG(" no matched mail found...");
                error = EMAIL_ERROR_MAIL_NOT_FOUND;
                goto FINISH_OFF;
        }
@@ -10031,6 +10348,8 @@ INTERNAL_FUNC int emstorage_add_attachment(emstorage_attachment_tbl_t* attachmen
        ret = true;
 
 FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
        if (hStmt != NULL)  {
                rc = sqlite3_finalize(hStmt);
                if (rc != SQLITE_OK)  {
@@ -10039,9 +10358,6 @@ FINISH_OFF:
                }
        }
 
-       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
-       _DISCONNECT_DB;
-
        if (err_code != NULL)
        *err_code = error;
 
@@ -10060,8 +10376,9 @@ INTERNAL_FUNC int emstorage_update_attachment(emstorage_attachment_tbl_t* attach
 
        if (!attachment_tbl)  {
                EM_DEBUG_EXCEPTION(" attachment_tbl[%p] ", attachment_tbl);
-               error = EMAIL_ERROR_INVALID_PARAM;
-               goto FINISH_OFF;
+               if (err_code) 
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
        }
 
        sqlite3 *local_db_handle = emstorage_get_db_connection();
@@ -10121,7 +10438,7 @@ INTERNAL_FUNC int emstorage_update_attachment(emstorage_attachment_tbl_t* attach
 */
        rc = sqlite3_changes(local_db_handle);
        if (rc == 0)  {
-               EM_DEBUG_EXCEPTION(" no matched mail found...");
+               EM_DEBUG_LOG(" no matched mail found...");
                error = EMAIL_ERROR_MAIL_NOT_FOUND;
                goto FINISH_OFF;
        }
@@ -10129,6 +10446,8 @@ INTERNAL_FUNC int emstorage_update_attachment(emstorage_attachment_tbl_t* attach
        ret = true;
 
 FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
        if (hStmt != NULL)  {
                rc = sqlite3_finalize(hStmt);
                if (rc != SQLITE_OK)  {
@@ -10137,9 +10456,6 @@ FINISH_OFF:
                }
        }
 
-       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
-       _DISCONNECT_DB;
-
        if (err_code != NULL)
        *err_code = error;
 
@@ -10274,7 +10590,7 @@ INTERNAL_FUNC int emstorage_free_attachment(emstorage_attachment_tbl_t** attachm
 
        if (count > 0)  {
                if ((attachment_tbl_list == NULL) || (*attachment_tbl_list == NULL))  {
-                       EM_DEBUG_EXCEPTION(" attachment_tbl_list[%p], count[%d]", attachment_tbl_list, count);
+                       EM_DEBUG_LOG("Nothing to free: attachment_tbl_list[%p], count[%d]", attachment_tbl_list, count);
                        if (err_code != NULL)
                                *err_code = EMAIL_ERROR_INVALID_PARAM;
                        return false;
@@ -10309,15 +10625,6 @@ INTERNAL_FUNC int emstorage_begin_transaction(void *d1, void *d2, int *err_code)
        EM_PROFILE_BEGIN(emStorageBeginTransaction);
        int ret = true;
 
-       /*  wait for the trnasaction authority to be changed. */
-       while (g_transaction)  {
-               EM_DEBUG_LOG(">>>>>>>> Wait for the transaction authority to be changed");
-               usleep(50000);
-       }
-
-       /*  take the transaction authority. */
-       g_transaction = true;
-
        sqlite3 *local_db_handle = emstorage_get_db_connection();
        int rc;
        EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, "BEGIN immediate;", NULL, NULL, NULL), rc);
@@ -10326,7 +10633,6 @@ INTERNAL_FUNC int emstorage_begin_transaction(void *d1, void *d2, int *err_code)
 
        if (ret == false) {
                if (err_code != NULL) *err_code = EMAIL_ERROR_DB_FAILURE;
-               g_transaction = false;
        }
 
        EM_PROFILE_END(emStorageBeginTransaction);
@@ -10338,13 +10644,12 @@ INTERNAL_FUNC int emstorage_commit_transaction(void *d1, void *d2, int *err_code
 {
        EM_DEBUG_FUNC_BEGIN();
        int ret = true;
+       int rc;
+
        sqlite3 *local_db_handle = emstorage_get_db_connection();
 
-       int rc;
        EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, "END;", NULL, NULL, NULL), rc);
        EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {ret = false; }, ("SQL(END) exec error:%d -%s", rc, sqlite3_errmsg(local_db_handle)));
-       /*  release the transaction authority. */
-       g_transaction = false;
 
        if (ret == false && err_code != NULL)
                *err_code = EMAIL_ERROR_DB_FAILURE;
@@ -10361,13 +10666,9 @@ INTERNAL_FUNC int emstorage_rollback_transaction(void *d1, void *d2, int *err_co
        int rc;
 
        EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, "ROLLBACK;", NULL, NULL, NULL), rc);
-
        EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {ret = false; },
                ("SQL(ROLLBACK) exec error:%d -%s", rc, sqlite3_errmsg(local_db_handle)));
 
-       /*  release the transaction authority. */
-       g_transaction = false;
-
        if (ret == false && err_code != NULL)
                *err_code = EMAIL_ERROR_DB_FAILURE;
 
@@ -10489,7 +10790,7 @@ INTERNAL_FUNC char *emstorage_make_directory_path_from_file_path(char *file_name
        token = g_strsplit_set(file_name, delims, 1);
 
        if (token && token[0]) {
-               EM_DEBUG_LOG(">>>> Directory_name [ %s ]", token[0]);
+               EM_DEBUG_LOG_SEC(">>>> Directory_name [ %s ]", token[0]);
                result = EM_SAFE_STRDUP(token[0]);
        } else
                EM_DEBUG_LOG(">>>> No Need to create Directory");
@@ -10501,7 +10802,7 @@ INTERNAL_FUNC char *emstorage_make_directory_path_from_file_path(char *file_name
 
 INTERNAL_FUNC int emstorage_get_save_name(int account_id, int mail_id, int atch_id, char *fname, char *name_buf, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("account_id[%d], mail_id[%d], atch_id[%d], fname[%s], name_buf[%p], err_code[%p]", account_id, mail_id, atch_id, fname, name_buf, err_code);
+       EM_DEBUG_FUNC_BEGIN_SEC("account_id[%d], mail_id[%d], atch_id[%d], fname[%s], name_buf[%p], err_code[%p]", account_id, mail_id, atch_id, fname, name_buf, err_code);
        EM_PROFILE_BEGIN(profile_emstorage_get_save_name);
 
        int ret = false;
@@ -10534,17 +10835,17 @@ INTERNAL_FUNC int emstorage_get_save_name(int account_id, int mail_id, int atch_
 
        if (dir_name) {
                sprintf(create_dir, "%s%s%s", name_buf, DIR_SEPERATOR, dir_name);
-               EM_DEBUG_LOG(">>>>> DIR PATH [ %s ]", create_dir);
+               EM_DEBUG_LOG(">>>>> DIR PATH [%s]", create_dir);
                mkdir(create_dir, DIRECTORY_PERMISSION);
                EM_SAFE_FREE(dir_name);
        }
 
        if (fname) {
-               EM_DEBUG_LOG(">>>>> fname [ %s ]", fname);
+               EM_DEBUG_LOG_DEV(">>>>> fname [%s]", fname);
                sprintf(name_buf+EM_SAFE_STRLEN(name_buf), "%s%s", DIR_SEPERATOR, fname);
        }
 
-       EM_DEBUG_LOG(">>>>> name_buf [ %s ]", name_buf);
+       EM_DEBUG_LOG_SEC(">>>>> name_buf [%s]", name_buf);
 
        ret = true;
 
@@ -10595,9 +10896,10 @@ INTERNAL_FUNC int emstorage_create_dir(int account_id, int mail_id, int atch_id,
        EM_PROFILE_BEGIN(profile_emcore_save_create_dir);
        int ret = false;
        int error = EMAIL_ERROR_NONE;
-
        char buf[512];
        struct stat sbuf;
+       char errno_buf[ERRNO_BUF_SIZE] = {0};
+
        if (account_id >= FIRST_ACCOUNT_ID)  {
                SNPRINTF(buf, sizeof(buf), "%s%s%d", MAILHOME, DIR_SEPERATOR, account_id);
 
@@ -10611,8 +10913,10 @@ INTERNAL_FUNC int emstorage_create_dir(int account_id, int mail_id, int atch_id,
                else  {
                        if (mkdir(buf, DIRECTORY_PERMISSION) != 0) {
                                EM_DEBUG_EXCEPTION(" mkdir failed [%s]", buf);
-                               EM_DEBUG_EXCEPTION("mkdir failed l(Errno=%d)][ErrStr=%s]", errno, strerror(errno));
+                               EM_DEBUG_EXCEPTION("mkdir failed: %s", EM_STRERROR(errno_buf));
                                error = EMAIL_ERROR_SYSTEM_FAILURE;
+                               if(errno == 28)
+                                       error = EMAIL_ERROR_OUT_OF_MEMORY;
                                goto FINISH_OFF;
                        }
                }
@@ -10638,8 +10942,10 @@ INTERNAL_FUNC int emstorage_create_dir(int account_id, int mail_id, int atch_id,
                else  {
                        if (mkdir(buf, DIRECTORY_PERMISSION) != 0) {
                                EM_DEBUG_EXCEPTION(" mkdir failed [%s]", buf);
-                               EM_DEBUG_EXCEPTION("mkdir failed l (Errno=%d)][ErrStr=%s]", errno, strerror(errno));
+                               EM_DEBUG_EXCEPTION("mkdir failed: %s", strerror(errno));
                                error = EMAIL_ERROR_SYSTEM_FAILURE;
+                               if(errno == 28)
+                                       error = EMAIL_ERROR_OUT_OF_MEMORY;
                                goto FINISH_OFF;
                        }
                }
@@ -10667,6 +10973,8 @@ INTERNAL_FUNC int emstorage_create_dir(int account_id, int mail_id, int atch_id,
                        if (mkdir(buf, DIRECTORY_PERMISSION) != 0) {
                                EM_DEBUG_EXCEPTION(" mkdir failed [%s]", buf);
                                error = EMAIL_ERROR_SYSTEM_FAILURE;
+                               if(errno == 28)
+                                       error = EMAIL_ERROR_OUT_OF_MEMORY;
                                goto FINISH_OFF;
                        }
                }
@@ -10694,9 +11002,9 @@ INTERNAL_FUNC int emstorage_copy_file(char *src_file, char *dst_file, int sync_s
        int fp_src = 0;
        int fp_dst = 0;
        int nread = 0;
-       int nwritten = 0;
        char *buf =  NULL;
        int buf_size = 0;
+       char errno_buf[ERRNO_BUF_SIZE] = {0};
 
        if (!src_file || !dst_file)  {
                EM_DEBUG_EXCEPTION("src_file[%p], dst_file[%p]", src_file, dst_file);
@@ -10724,13 +11032,13 @@ INTERNAL_FUNC int emstorage_copy_file(char *src_file, char *dst_file, int sync_s
 
        if (buf) {
                if ((fp_src = open(src_file, O_RDONLY))<0) { /*prevent 24474*/
-                       EM_DEBUG_EXCEPTION(">>>> Source Fail open %s Failed [ %d ] - Error [ %s ]", src_file, errno, strerror(errno));
+                       EM_DEBUG_EXCEPTION(">>>> Source Fail open %s Failed: %s", src_file, EM_STRERROR(errno_buf));
                        error = EMAIL_ERROR_SYSTEM_FAILURE;
                        goto FINISH_OFF;
                }
 
-               if ((fp_dst = open(dst_file, O_CREAT | O_WRONLY, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH))<0) { /*prevent 24474*/
-                       EM_DEBUG_EXCEPTION(">>>> Destination Fail open %s Failed [ %d ] - Error [ %s ]", dst_file, errno, strerror(errno));
+               if ((fp_dst = open(dst_file, O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH))<0) { /*prevent 24474*/
+                       EM_DEBUG_EXCEPTION(">>>> Destination Fail open %s:  %s", dst_file, EM_STRERROR(errno_buf));
                        error = EMAIL_ERROR_SYSTEM_FAILURE;
                        goto FINISH_OFF;
                }
@@ -10738,12 +11046,30 @@ INTERNAL_FUNC int emstorage_copy_file(char *src_file, char *dst_file, int sync_s
                while ((nread = read(fp_src, buf, buf_size)) > 0) {
                        if (nread > 0 && nread <= buf_size)  {
                                EM_DEBUG_LOG("Nread Value [%d]", nread);
-                               if ((nwritten = write(fp_dst, buf, nread)) != nread) {
-                                       EM_DEBUG_EXCEPTION("fwrite failed...[%d] : [%s]", errno, strerror(errno));
-                                       error = EMAIL_ERROR_UNKNOWN;
-                                       goto FINISH_OFF;
+                               char *buf_ptr;
+                               ssize_t byte_written = 0;
+                               size_t remain_byte = nread;
+                               buf_ptr = buf;
+                               errno = 0;
+
+                               while(remain_byte > 0 && buf_ptr && errno == 0) {
+                                       byte_written = write(fp_dst, buf_ptr, remain_byte);
+
+                                       if (byte_written < 0) {
+                                               /* interrupted by a signal */
+                                               if (errno == EINTR) {
+                                                       errno = 0;
+                                                       continue;
+                                               }
+
+                                               EM_DEBUG_EXCEPTION("fwrite failed: %s", EM_STRERROR(errno_buf));
+                                               error = EMAIL_ERROR_UNKNOWN;
+                                               goto FINISH_OFF;
+                                       }
+                                       EM_DEBUG_LOG("NWRITTEN [%d]", byte_written);
+                                       remain_byte -= byte_written;
+                                       buf_ptr += byte_written;
                                }
-                               EM_DEBUG_LOG("NWRITTEN [%d]", nwritten);
                        }
                }
        }
@@ -10849,7 +11175,7 @@ INTERNAL_FUNC int emstorage_add_content_type(char *file_path, char *char_set, in
 
 
        if (stat(file_path, &st_buf) < 0) {
-               EM_DEBUG_EXCEPTION(" stat(\"%s\") failed...", file_path);
+               EM_DEBUG_EXCEPTION_SEC(" stat(\"%s\") failed...", file_path);
 
                error = EMAIL_ERROR_SYSTEM_FAILURE;             /* EMAIL_ERROR_INVALID_PATH; */
                goto FINISH_OFF;
@@ -10867,7 +11193,7 @@ INTERNAL_FUNC int emstorage_add_content_type(char *file_path, char *char_set, in
        }
 
        if (!(fp_src = fopen(file_path, "rb"))) {
-               EM_DEBUG_EXCEPTION(" file_path fopen failed - %s", file_path);
+               EM_DEBUG_EXCEPTION_SEC(" file_path fopen failed - %s", file_path);
 
                        error = EMAIL_ERROR_SYSTEM_FAILURE;
                        goto FINISH_OFF;
@@ -10925,11 +11251,11 @@ INTERNAL_FUNC int emstorage_add_content_type(char *file_path, char *char_set, in
                                                        EM_SAFE_FREE(temp_file_name);
                                                        goto FINISH_OFF;
                                        }
-                                       EM_DEBUG_LOG(">>>>>>> TEMP APPEND FILE PATH [ %s ] ", temp_file_name);
+                                       EM_DEBUG_LOG_SEC(">>>>>>> TEMP APPEND FILE PATH [ %s ] ", temp_file_name);
 
                                        /* Open the Temp file in Append mode */
                                        if (!(fp_dest = fopen(temp_file_name, "ab"))) {
-                                               EM_DEBUG_EXCEPTION(" fopen failed - %s", temp_file_name);
+                                               EM_DEBUG_EXCEPTION_SEC(" fopen failed - %s", temp_file_name);
                                                error = EMAIL_ERROR_SYSTEM_FAILURE;
                                                goto FINISH_OFF;
                                        }
@@ -11000,6 +11326,7 @@ INTERNAL_FUNC int emstorage_move_file(char *src_file, char *dst_file, int sync_s
 
        int ret = false;
        int error = EMAIL_ERROR_NONE;
+       char errno_buf[ERRNO_BUF_SIZE] = {0};
 
        if (src_file == NULL || dst_file == NULL)  {
                EM_DEBUG_EXCEPTION("src_file[%p], dst_file[%p]", src_file, dst_file);
@@ -11011,6 +11338,7 @@ INTERNAL_FUNC int emstorage_move_file(char *src_file, char *dst_file, int sync_s
 
        if (strcmp(src_file, dst_file) != 0) {
                if (rename(src_file, dst_file) != 0) {
+                       /* EM_DEBUG_EXCEPTION("%s", strerror(errno) ); */
                        if (errno == EXDEV)  {  /* oldpath and newpath are not on the same mounted file system.  (Linux permits a file system to be mounted at multiple points,  but  rename() */
                                /*  does not work across different mount points, even if the same file system is mounted on both.)       */
                                EM_DEBUG_LOG("oldpath and newpath are not on the same mounted file system.");
@@ -11025,18 +11353,18 @@ INTERNAL_FUNC int emstorage_move_file(char *src_file, char *dst_file, int sync_s
                        else  {
                                if (errno == ENOENT)  {
                                        struct stat temp_file_stat;
-                                       if (stat(src_file, &temp_file_stat) < 0)
-                                               EM_DEBUG_EXCEPTION("no src file found [%s]", src_file);
+                                       if (stat(src_file, &temp_file_stat) < 0) {
+                                               EM_DEBUG_EXCEPTION("no src file found [%s] : %s", src_file, EM_STRERROR(errno_buf));
+                                       }
                                        if (stat(dst_file, &temp_file_stat) < 0)
-                                               EM_DEBUG_EXCEPTION("no dst file found [%s]", src_file);
+                                               EM_DEBUG_EXCEPTION("no dst file found [%s] : %s", dst_file, EM_STRERROR(errno_buf));
 
-                                       EM_DEBUG_EXCEPTION("no file found [%d]", errno);
                                        error = EMAIL_ERROR_FILE_NOT_FOUND;
                                        goto FINISH_OFF;
 
                                }
                                else  {
-                                       EM_DEBUG_EXCEPTION("rename failed [%d]", errno);
+                                       EM_DEBUG_EXCEPTION("rename failed: %s", EM_STRERROR(errno_buf));
                                        error = EMAIL_ERROR_SYSTEM_FAILURE;
                                        goto FINISH_OFF;
                                }
@@ -11125,7 +11453,7 @@ INTERNAL_FUNC int emstorage_delete_dir(char *src_dir, int *err_code)
                        return true;
                }
                else  {
-                       EM_DEBUG_EXCEPTION("opendir failed - %d", errno);
+                       EM_DEBUG_EXCEPTION("opendir failed [%s] [%d]", src_dir, errno);
                        if (err_code != NULL)
                                *err_code = EMAIL_ERROR_SYSTEM_FAILURE;
                        return false;
@@ -11151,7 +11479,7 @@ INTERNAL_FUNC int emstorage_delete_dir(char *src_dir, int *err_code)
                        }
                        else  { /*  file */
                                if (remove(buf) < 0)  {
-                                       EM_DEBUG_EXCEPTION("remove failed - %s", buf);
+                                       EM_DEBUG_EXCEPTION("remove failed [%s] [%d]", buf, errno);
                                        closedir(dirp);
                                        if (err_code != NULL)
                                                *err_code = EMAIL_ERROR_SYSTEM_FAILURE;
@@ -11165,12 +11493,12 @@ INTERNAL_FUNC int emstorage_delete_dir(char *src_dir, int *err_code)
 
        closedir(dirp);
 
-       EM_DEBUG_LOG("remove direcotory [%s]", src_dir);
+       EM_DEBUG_LOG_DEV ("remove direcotory [%s]", src_dir);
 
        /* EM_DEBUG_FUNC_BEGIN(); */
 
        if (remove(src_dir) < 0)  {
-               EM_DEBUG_EXCEPTION("remove failed [%s]", src_dir);
+               EM_DEBUG_EXCEPTION("remove failed [%s] [%d]", src_dir, errno);
                if (err_code != NULL)
                        *err_code = EMAIL_ERROR_SYSTEM_FAILURE;
                return false;
@@ -11194,7 +11522,8 @@ INTERNAL_FUNC int emstorage_update_server_uid(char *old_server_uid, char *new_se
 
        if (!old_server_uid || !new_server_uid) {
                EM_DEBUG_EXCEPTION("Invalid parameters");
-               error = EMAIL_ERROR_INVALID_PARAM;
+               if (err_code) 
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
                return false;
        }
        sqlite3 *local_db_handle = emstorage_get_db_connection();
@@ -11226,7 +11555,7 @@ FINISH_OFF:
 
 INTERNAL_FUNC int emstorage_update_read_mail_uid(int mail_id, char *new_server_uid, char *mbox_name, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("mail_id[%d], new_server_uid[%s], mbox_name[%s]", mail_id, new_server_uid, mbox_name);
+       EM_DEBUG_FUNC_BEGIN_SEC("mail_id[%d], new_server_uid[%s], mbox_name[%s]", mail_id, new_server_uid, mbox_name);
 
        int rc, ret = false;
        int error = EMAIL_ERROR_NONE;
@@ -11236,7 +11565,8 @@ INTERNAL_FUNC int emstorage_update_read_mail_uid(int mail_id, char *new_server_u
 
        if (!mail_id || !new_server_uid || !mbox_name)  {
                EM_DEBUG_EXCEPTION("Invalid parameters");
-               error = EMAIL_ERROR_INVALID_PARAM;
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
                return false;
        }
        sqlite3 *local_db_handle = emstorage_get_db_connection();
@@ -11244,7 +11574,7 @@ INTERNAL_FUNC int emstorage_update_read_mail_uid(int mail_id, char *new_server_u
 
 
        SNPRINTF(sql_query_string, sizeof(sql_query_string),
-                "UPDATE mail_read_mail_uid_tbl SET s_uid=\'%s\', mailbox_id=\'%s\', mailbox_name=\'%s\' WHERE local_uid=%d ", new_server_uid, mbox_name, mbox_name, mail_id);
+                "UPDATE mail_read_mail_uid_tbl SET server_uid=\'%s\', mailbox_id=\'%s\', mailbox_name=\'%s\' WHERE local_uid=%d ", new_server_uid, mbox_name, mbox_name, mail_id);
        EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
        EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
                ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
@@ -11523,6 +11853,10 @@ INTERNAL_FUNC int emstorage_test(int mail_id, int account_id, char *full_address
                ", ?" /*  digest_type */
                ", ?" /*  smime_type */
                ", ?" /*  scheduled_sending_time */
+               ", ?" /*  remaining_resend_times */
+               ", ?" /*  tag_id   */
+               ", ?" /*  replied_time */
+               ", ?" /*  forwarded_time */
                ", ?" /*  eas_data_length */
                ", ?" /*  eas_data */
                ")");
@@ -11583,6 +11917,11 @@ INTERNAL_FUNC int emstorage_test(int mail_id, int account_id, char *full_address
        _bind_stmt_field_data_int(hStmt, MESSAGE_CLASS_IDX_IN_MAIL_TBL, 0);
        _bind_stmt_field_data_int(hStmt, DIGEST_TYPE_IDX_IN_MAIL_TBL, 0);
        _bind_stmt_field_data_int(hStmt, SMIME_TYPE_IDX_IN_MAIL_TBL, 0);
+       _bind_stmt_field_data_int(hStmt, SCHEDULED_SENDING_TIME_IDX_IN_MAIL_TBL, 0);
+       _bind_stmt_field_data_int(hStmt, REMAINING_RESEND_TIMES_IDX_IN_MAIL_TBL, 0);
+       _bind_stmt_field_data_int(hStmt, TAG_ID_IDX_IN_MAIL_TBL, 0);
+       _bind_stmt_field_data_int(hStmt, REPLIED_TIME_IDX_IN_MAIL_TBL, 0);
+       _bind_stmt_field_data_int(hStmt, FORWARDED_TIME_IDX_IN_MAIL_TBL, 0);
        _bind_stmt_field_data_int(hStmt, EAS_DATA_LENGTH_IDX_IN_MAIL_TBL, 0);
        _bind_stmt_field_data_blob(hStmt, EAS_DATA_IDX_IN_MAIL_TBL, NULL, 0);
 
@@ -11594,6 +11933,8 @@ INTERNAL_FUNC int emstorage_test(int mail_id, int account_id, char *full_address
        ret = true;
 
 FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
        if (hStmt != NULL)  {
                rc = sqlite3_finalize(hStmt);
                if (rc != SQLITE_OK)  {
@@ -11602,9 +11943,6 @@ FINISH_OFF:
                }
        }
 
-       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
-       _DISCONNECT_DB;
-
        if (err_code != NULL)
                *err_code = error;
 
@@ -11639,6 +11977,8 @@ INTERNAL_FUNC int emstorage_get_thread_id_of_thread_mails(emstorage_mail_tbl_t *
        char     stripped_subject[STRIPPED_SUBJECT_BUFFER_SIZE];
        sqlite3 *local_db_handle = emstorage_get_db_connection();
 
+       EM_DEBUG_LOG("subject: [%p], mail_id: [%d]", subject, mail_tbl->mail_id);
+
        EM_IF_NULL_RETURN_VALUE(mail_tbl, EMAIL_ERROR_INVALID_PARAM);
        EM_IF_NULL_RETURN_VALUE(thread_id, EMAIL_ERROR_INVALID_PARAM);
        EM_IF_NULL_RETURN_VALUE(result_latest_mail_id_in_thread, EMAIL_ERROR_INVALID_PARAM);
@@ -11648,7 +11988,7 @@ INTERNAL_FUNC int emstorage_get_thread_id_of_thread_mails(emstorage_mail_tbl_t *
        subject      = mail_tbl->subject;
        date_time    = mail_tbl->date_time;
 
-       EM_DEBUG_LOG("subject : %s", subject);
+       EM_DEBUG_LOG("subject: [%s]", subject);
 
        if (em_find_pos_stripped_subject_for_thread_view(subject, stripped_subject, STRIPPED_SUBJECT_BUFFER_SIZE) != EMAIL_ERROR_NONE)  {
                EM_DEBUG_EXCEPTION("em_find_pos_stripped_subject_for_thread_view  is failed");
@@ -11775,7 +12115,7 @@ FINISH_OFF:
 
 INTERNAL_FUNC int emstorage_get_sender_list(int account_id, int mailbox_id, int search_type, const char *search_value, email_sort_type_t sorting, email_sender_list_t** sender_list, int *sender_count,  int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("account_id [%d], mailbox_id [%d], search_type [%d], search_value [%p], sorting [%d], sender_list[%p], sender_count[%p] err_code[%p]"
+       EM_DEBUG_FUNC_BEGIN_SEC("account_id [%d], mailbox_id [%d], search_type [%d], search_value [%p], sorting [%d], sender_list[%p], sender_count[%p] err_code[%p]"
                , account_id , mailbox_id , search_type , search_value , sorting , sender_list, sender_count, err_code);
 
        if ((!sender_list) ||(!sender_count)) {
@@ -11967,6 +12307,7 @@ INTERNAL_FUNC int emstorage_free_address_info_list(email_address_info_list_t **a
 
                        node = g_list_next(node);
                }
+               g_list_free(list);
        }
 
        EM_SAFE_FREE(*address_info_list);
@@ -12026,7 +12367,7 @@ INTERNAL_FUNC int emstorage_add_pbd_activity(email_event_partial_body_thd* local
 
        *activity_id = local_activity->activity_id = rc;
 
-       EM_DEBUG_LOG(">>>>> ACTIVITY ID [ %d ], MAIL ID [ %d ], ACTIVITY TYPE [ %d ], SERVER MAIL ID [ %lu ]", \
+       EM_DEBUG_LOG_SEC(">>>>> ACTIVITY ID [ %d ], MAIL ID [ %d ], ACTIVITY TYPE [ %d ], SERVER MAIL ID [ %lu ]", \
                local_activity->activity_id, local_activity->mail_id, local_activity->activity_type, local_activity->server_mail_id);
 
        if (local_activity->mailbox_id)
@@ -12058,7 +12399,8 @@ INTERNAL_FUNC int emstorage_add_pbd_activity(email_event_partial_body_thd* local
        ret = true;
 
 FINISH_OFF:
-
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
        if (hStmt != NULL) {
                EM_DEBUG_LOG("Before sqlite3_finalize hStmt = %p", hStmt);
 
@@ -12070,12 +12412,10 @@ FINISH_OFF:
                }
        }
 
-        EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
-       _DISCONNECT_DB;
-        if (err_code != NULL)
-                *err_code = error;
+       if (err_code != NULL)
+               *err_code = error;
 
-        EM_DEBUG_FUNC_END("ret [%d]", ret);
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
        return ret;
 }
 
@@ -12333,8 +12673,7 @@ INTERNAL_FUNC int emstorage_get_pbd_activity_data(int account_id, int input_mail
        EM_DEBUG_LOG("Query = [%s]", sql_query_string);
 
        if (!*count) {
-               EM_DEBUG_EXCEPTION("No matched activity found in mail_partial_body_activity_tbl");
-
+               EM_DEBUG_LOG("No matched activity found in mail_partial_body_activity_tbl");
                error = EMAIL_ERROR_MAIL_NOT_FOUND;
                ret = true;
                goto FINISH_OFF;
@@ -12389,7 +12728,11 @@ FINISH_OFF:
        if (true == ret)
          *event_start = event_list;
        else {
-               EM_SAFE_FREE(event_list);
+               for (i=0; i < (*count); i++)
+                       emcore_free_partial_body_thd_event(event_list, NULL);
+               EM_SAFE_FREE(event_list); /*prevent 54559*/
+               *event_start = NULL;
+               *count = 0;
        }
 
        if (hStmt != NULL) {
@@ -12462,9 +12805,7 @@ INTERNAL_FUNC int emstorage_delete_pbd_activity(int account_id, int mail_id, int
        ret = true;
 
 FINISH_OFF:
-
        EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
-
        _DISCONNECT_DB;
        if (err_code != NULL)
                *err_code = error;
@@ -12563,11 +12904,11 @@ INTERNAL_FUNC int emstorage_get_pbd_activity_count(int *activity_count, int tran
 
        SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT count(*) FROM mail_partial_body_activity_tbl;");
 
-       EM_DEBUG_LOG(" Query [%s]", sql_query_string);
+       EM_DEBUG_LOG_DEV(" Query [%s]", sql_query_string);
 
 
        EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
-       EM_DEBUG_LOG("  before sqlite3_prepare hStmt = %p", hStmt);
+       EM_DEBUG_LOG_DEV ("  before sqlite3_prepare hStmt = %p", hStmt);
        EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
                ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
 
@@ -12586,7 +12927,7 @@ FINISH_OFF:
 
 
        if (hStmt != NULL) {
-               EM_DEBUG_LOG("Before sqlite3_finalize hStmt = %p", hStmt);
+/*             EM_DEBUG_LOG("Before sqlite3_finalize hStmt = %p", hStmt); */
 
                rc = sqlite3_finalize(hStmt);
                hStmt=NULL;
@@ -12594,7 +12935,7 @@ FINISH_OFF:
                        EM_DEBUG_EXCEPTION("sqlite3_finalize failed - %d", rc);
                        error = EMAIL_ERROR_DB_FAILURE;
                }
-               EM_DEBUG_LOG("sqlite3_finalize- %d", rc);
+/*             EM_DEBUG_LOG("sqlite3_finalize- %d", rc); */
        }
 
        EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
@@ -12646,7 +12987,6 @@ INTERNAL_FUNC int emstorage_delete_full_pbd_activity_data(int account_id, int tr
        ret = true;
 
 FINISH_OFF:
-
        EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
        _DISCONNECT_DB;
        if (err_code != NULL)
@@ -12661,7 +13001,7 @@ if a mail is moved before its partial body is downloaded.Currently not used but
 
 INTERNAL_FUNC int emstorage_update_pbd_activity(char *old_server_uid, char *new_server_uid, char *mbox_name, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("old_server_uid[%s], new_server_uid[%s], mbox_name[%s]", old_server_uid, new_server_uid, mbox_name);
+       EM_DEBUG_FUNC_BEGIN_SEC("old_server_uid[%s], new_server_uid[%s], mbox_name[%s]", old_server_uid, new_server_uid, mbox_name);
 
        int rc = -1, ret = false;
        int error = EMAIL_ERROR_NONE;
@@ -12699,7 +13039,6 @@ INTERNAL_FUNC int emstorage_update_pbd_activity(char *old_server_uid, char *new_
        ret = true;
 
 FINISH_OFF:
-
        EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
        _DISCONNECT_DB;
        if (err_code != NULL)
@@ -12712,15 +13051,15 @@ FINISH_OFF:
 
 INTERNAL_FUNC int emstorage_create_file(char *data_string, size_t file_size, char *dst_file_name, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("file_size[%d] , dst_file_name[%s], err_code[%p]", file_size, dst_file_name, err_code);
+       EM_DEBUG_FUNC_BEGIN_SEC("file_size[%d] , dst_file_name[%s], err_code[%p]", file_size, dst_file_name, err_code);
 
        int ret = false;
        int error = EMAIL_ERROR_NONE;
-
        FILE* fp_dst = NULL;
+       char errno_buf[ERRNO_BUF_SIZE] = {0};
 
        if (!data_string || !dst_file_name)  {
-               EM_DEBUG_EXCEPTION("data_string[%p], dst_file_name[%p]", data_string, dst_file_name);
+               EM_DEBUG_LOG("data_string[%p], dst_file_name[%p]", data_string, dst_file_name);
                error = EMAIL_ERROR_INVALID_PARAM;
                goto FINISH_OFF;
        }
@@ -12728,7 +13067,7 @@ INTERNAL_FUNC int emstorage_create_file(char *data_string, size_t file_size, cha
        fp_dst = fopen(dst_file_name, "w");
 
        if (!fp_dst)  {
-               EM_DEBUG_EXCEPTION("fopen failed - %s", dst_file_name);
+               EM_DEBUG_EXCEPTION_SEC("fopen failed - %s: %s", dst_file_name, EM_STRERROR(errno_buf));
                if (errno == 28)
                        error = EMAIL_ERROR_MAIL_MEMORY_FULL;
                else
@@ -12737,7 +13076,7 @@ INTERNAL_FUNC int emstorage_create_file(char *data_string, size_t file_size, cha
        }
 
        if (fwrite(data_string, 1, file_size, fp_dst) == 0) {
-               EM_DEBUG_EXCEPTION("fwrite failed...");
+               EM_DEBUG_EXCEPTION("fwrite failed: %s", EM_STRERROR(errno_buf));
                error = EMAIL_ERROR_UNKNOWN;
                goto FINISH_OFF;
        }
@@ -12774,18 +13113,19 @@ INTERNAL_FUNC int emstorage_update_read_mail_uid_by_server_uid(char *old_server_
 
        if (!old_server_uid || !new_server_uid || !mbox_name)  {
                EM_DEBUG_EXCEPTION("Invalid parameters");
-               error = EMAIL_ERROR_INVALID_PARAM;
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
                return false;
        }
 
-       EM_DEBUG_LOG("old_server_uid[%s], new_server_uid[%s], mbox_name[%s]", old_server_uid, new_server_uid, mbox_name);
+       EM_DEBUG_LOG_SEC("old_server_uid[%s], new_server_uid[%s], mbox_name[%s]", old_server_uid, new_server_uid, mbox_name);
 
        sqlite3 *local_db_handle = emstorage_get_db_connection();
        EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
 
 
        SNPRINTF(sql_query_string, sizeof(sql_query_string),
-                "UPDATE mail_read_mail_uid_tbl SET s_uid=\'%s\' , mailbox_id=\'%s\', mailbox_name=\'%s\' WHERE s_uid=%s ", new_server_uid, mbox_name, mbox_name, old_server_uid);
+                "UPDATE mail_read_mail_uid_tbl SET server_uid=\'%s\' , mailbox_name=\'%s\' WHERE server_uid=%s ", new_server_uid, mbox_name, old_server_uid);
 
         EM_DEBUG_LOG(" Query [%s]", sql_query_string);
 
@@ -12804,11 +13144,9 @@ INTERNAL_FUNC int emstorage_update_read_mail_uid_by_server_uid(char *old_server_
                 goto FINISH_OFF;
         }
 
-
         ret = true;
 
 FINISH_OFF:
-
        EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
        _DISCONNECT_DB;
 
@@ -12857,13 +13195,14 @@ INTERNAL_FUNC int emstorage_get_id_set_from_mail_ids(char *mail_ids, email_id_se
 
        if (NULL == mail_ids || NULL == idset || NULL == id_set_count) {
                EM_DEBUG_EXCEPTION("Invalid Parameters mail_ids[%p] idset[%p]  id_set_count [%p]", mail_ids, idset, id_set_count);
-               error = EMAIL_ERROR_INVALID_PARAM;
-               goto FINISH_OFF;
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
        }
 
        sqlite3 *local_db_handle = emstorage_get_db_connection();
 
-       SNPRINTF(sql_query_string, space_left_in_query_buffer, "SELECT local_uid, s_uid FROM mail_read_mail_uid_tbl WHERE local_uid in (%s) ORDER BY s_uid", mail_ids);
+       SNPRINTF(sql_query_string, space_left_in_query_buffer, "SELECT local_uid, server_uid FROM mail_read_mail_uid_tbl WHERE local_uid in (%s) ORDER BY server_uid", mail_ids);
 
        EM_DEBUG_LOG("SQL Query formed [%s] ", sql_query_string);
 
@@ -12894,8 +13233,10 @@ INTERNAL_FUNC int emstorage_get_id_set_from_mail_ids(char *mail_ids, email_id_se
        for (i = 0; i < count; i++)  {
                _get_table_field_data_int(result, &(p_id_set[i].mail_id), col_index++);
                _get_table_field_data_string(result, &server_mail_id, 1, col_index++);
-               p_id_set[i].server_mail_id = strtoul(server_mail_id, NULL, 10);
-               EM_SAFE_FREE(server_mail_id);
+               if (server_mail_id) {
+                       p_id_set[i].server_mail_id = strtoul(server_mail_id, NULL, 10);
+                       EM_SAFE_FREE(server_mail_id);
+               }
        }
        EM_DEBUG_LOG(">>>> DATA ASSIGN END [count : %d]", count);
        EM_PROFILE_END(EmStorageGetIdSetFromMailIds_Loop);
@@ -12962,20 +13303,59 @@ INTERNAL_FUNC int emstorage_delete_triggers_from_lucene()
        ret = true;
 
 FINISH_OFF:
-
        EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_update_tag_id(int old_filter_id, int new_filter_id, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("new_filter_id[%d], old_filter_id[%d]", new_filter_id, old_filter_id);
+       int rc, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       int transaction = true;
+
+       if (old_filter_id < 0 || new_filter_id < 0) {
+               EM_DEBUG_EXCEPTION("Invalid parameters");
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+                "UPDATE mail_tbl SET tag_id=%d WHERE tag_id=%d ", new_filter_id, old_filter_id);
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+
+       EM_DEBUG_DB_EXEC((SQLITE_FULL == rc), {error = EMAIL_ERROR_MAIL_MEMORY_FULL;goto FINISH_OFF; },
+               ("sqlite3_exec fail:%d", rc));
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
 
+       ret = true;
+
+FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
        _DISCONNECT_DB;
 
+       if (err_code != NULL)
+               *err_code = error;
+
        EM_DEBUG_FUNC_END("ret [%d]", ret);
        return ret;
 }
 
-INTERNAL_FUNC int emstorage_filter_mails_by_rule(int account_id, int dest_mailbox_id, int dest_mailbox_type, emstorage_rule_tbl_t *rule, int ** filtered_mail_id_list, int *count_of_mails, int *err_code)
+INTERNAL_FUNC int emstorage_filter_mails_by_rule(int account_id, int dest_mailbox_id, int dest_mailbox_type, int reset, emstorage_rule_tbl_t *rule, int ** filtered_mail_id_list, int *count_of_mails, int *err_code)
 {
        EM_DEBUG_FUNC_BEGIN("account_id[%d], dest_mailbox_id[%d] rule[%p], filtered_mail_id_list[%p], count_of_mails[%p], err_code[%p]", account_id, dest_mailbox_id, rule, filtered_mail_id_list, count_of_mails, err_code);
 
-       if ((account_id <= 0) || (dest_mailbox_id <= 0) || (!rule) || (!rule->value)|| (!filtered_mail_id_list) || (!count_of_mails)) {
+       if ((account_id < 0) || (dest_mailbox_id < 0) || (!rule)) {
                EM_DEBUG_EXCEPTION("Invalid Parameter");
 
                if (err_code != NULL)
@@ -12985,6 +13365,7 @@ INTERNAL_FUNC int emstorage_filter_mails_by_rule(int account_id, int dest_mailbo
 
        int rc = -1, ret = false, error = EMAIL_ERROR_NONE;
        int count = 0, col_index = 0, i = 0, where_pararaph_length = 0, *mail_list = NULL;
+       int tag_id = rule->rule_id;
        char **result = NULL, *where_pararaph = NULL;
        char sql_query_string[QUERY_SIZE] = {0, };
 
@@ -12992,37 +13373,40 @@ INTERNAL_FUNC int emstorage_filter_mails_by_rule(int account_id, int dest_mailbo
 
        SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT mail_id FROM mail_tbl ");
 
-       EM_DEBUG_LOG("rule->value [%s]", rule->value);
-
-       where_pararaph_length = EM_SAFE_STRLEN(rule->value) + 100;
-       where_pararaph = malloc(sizeof(char) * where_pararaph_length);
-
+       where_pararaph_length = EM_SAFE_STRLEN(rule->value) + EM_SAFE_STRLEN(rule->value2) + 100;
+       where_pararaph = em_malloc(sizeof(char) * where_pararaph_length);
        if (where_pararaph == NULL) {
                EM_DEBUG_EXCEPTION("malloc failed for where_pararaph.");
                error = EMAIL_ERROR_OUT_OF_MEMORY;
                goto FINISH_OFF;
        }
 
-       memset(where_pararaph, 0, sizeof(char) * where_pararaph_length);
-
-       EM_DEBUG_LOG("rule->type [%d], rule->flag2[%d]", rule->type, rule->flag2);
+       if (account_id != ALL_ACCOUNT) 
+               SNPRINTF(where_pararaph, where_pararaph_length, "WHERE account_id = %d AND mailbox_type NOT in (3,5)", account_id);
+       else
+               SNPRINTF(where_pararaph, where_pararaph_length, "WHERE mailbox_type NOT in (3,5)");
 
-       if (rule->type == EMAIL_FILTER_FROM) {
+       if (rule->type & EMAIL_FILTER_SUBJECT) {
                if (rule->flag2 == RULE_TYPE_INCLUDES)
-                       SNPRINTF(where_pararaph, where_pararaph_length, "WHERE account_id = %d AND mailbox_type NOT in (3,5) AND full_address_from like \'%%%s%%\'", account_id, rule->value);
+                       sqlite3_snprintf(where_pararaph_length - (EM_SAFE_STRLEN(where_pararaph) + 1), where_pararaph + EM_SAFE_STRLEN(where_pararaph), " AND subject like \'%%%q%%\'", rule->value);
                else /*  RULE_TYPE_EXACTLY */
-                       SNPRINTF(where_pararaph, where_pararaph_length, "WHERE account_id = %d AND mailbox_type NOT in (3,5) AND full_address_from = \'%s\'", account_id, rule->value);
+                       sqlite3_snprintf(where_pararaph_length - (EM_SAFE_STRLEN(where_pararaph) + 1), where_pararaph + EM_SAFE_STRLEN(where_pararaph), " AND subject = \'%q\'", rule->value);
        }
-       else if (rule->type == EMAIL_FILTER_SUBJECT) {
+
+       if (rule->type & EMAIL_FILTER_FROM) {
                if (rule->flag2 == RULE_TYPE_INCLUDES)
-                       SNPRINTF(where_pararaph, where_pararaph_length, "WHERE account_id = %d AND mailbox_type NOT in (3,5) AND subject like \'%%%s%%\'", account_id, rule->value);
+                       sqlite3_snprintf(where_pararaph_length - (EM_SAFE_STRLEN(where_pararaph) + 1), where_pararaph + EM_SAFE_STRLEN(where_pararaph), " AND full_address_from like \'%%%q%%\'", rule->value2);
                else /*  RULE_TYPE_EXACTLY */
-                       SNPRINTF(where_pararaph, where_pararaph_length, "WHERE account_id = %d AND mailbox_type NOT in (3,5) AND subject = \'%s\'", account_id, rule->value);
+                       sqlite3_snprintf(where_pararaph_length - (EM_SAFE_STRLEN(where_pararaph) + 1), where_pararaph + EM_SAFE_STRLEN(where_pararaph), " AND full_address_from = \'%q\'", rule->value2);
        }
-       else {
-               error = EMAIL_ERROR_INVALID_PARAM;
-               EM_DEBUG_EXCEPTION("rule->type is invald");
-               goto FINISH_OFF;
+
+       if (rule->type == EMAIL_PRIORITY_SENDER) {
+               if (rule->flag2 == RULE_TYPE_INCLUDES)
+                       sqlite3_snprintf(where_pararaph_length - (EM_SAFE_STRLEN(where_pararaph) + 1), where_pararaph + EM_SAFE_STRLEN(where_pararaph), " AND full_address_from like \'%%%q%%\'", rule->value2);
+               else /*  RULE_TYPE_EXACTLY */
+                       sqlite3_snprintf(where_pararaph_length - (EM_SAFE_STRLEN(where_pararaph) + 1), where_pararaph + EM_SAFE_STRLEN(where_pararaph), " AND full_address_from = \'%q\'", rule->value2);
+
+               tag_id = PRIORITY_SENDER_TAG_ID;
        }
 
        /* prevent 34361 */
@@ -13052,11 +13436,34 @@ INTERNAL_FUNC int emstorage_filter_mails_by_rule(int account_id, int dest_mailbo
                        _get_table_field_data_int(result, &(mail_list[i]), col_index++);
 
                memset(sql_query_string, 0x00, QUERY_SIZE);
-               SNPRINTF(sql_query_string, sizeof(sql_query_string), "UPDATE mail_tbl SET mailbox_id = %d, mailbox_type = %d ", dest_mailbox_id, dest_mailbox_type);
-
+               if (reset) {
+                       switch (rule->action_type) {
+                       case EMAIL_FILTER_MOVE :
+                               SNPRINTF(sql_query_string, sizeof(sql_query_string), "UPDATE mail_tbl SET tag_id = 0 ");
+                               break;
+                       case EMAIL_FILTER_BLOCK:
+                       default:
+                               EM_DEBUG_LOG("Not support : action_type[%d]", rule->action_type);
+                               ret = true;
+                               goto FINISH_OFF;
+                       }
+               } else {
+                       switch (rule->action_type) {
+                       case EMAIL_FILTER_MOVE :
+                               SNPRINTF(sql_query_string, sizeof(sql_query_string), "UPDATE mail_tbl SET tag_id = %d ", tag_id);
+                               break;
+                       case EMAIL_FILTER_BLOCK :
+                               SNPRINTF(sql_query_string, sizeof(sql_query_string), "UPDATE mail_tbl SET mailbox_id = %d, mailbox_type = %d ", dest_mailbox_id, dest_mailbox_type);
+                               break;
+                       default:
+                               EM_DEBUG_LOG("Not support");
+                               ret = true;
+                               goto FINISH_OFF;
+                       }
+               }
                /* prevent 34361 */
                if(strlen(sql_query_string) + strlen(where_pararaph) < QUERY_SIZE)
-               strcat(sql_query_string, where_pararaph);
+                       strcat(sql_query_string, where_pararaph);
 
                EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
                EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
@@ -13064,15 +13471,17 @@ INTERNAL_FUNC int emstorage_filter_mails_by_rule(int account_id, int dest_mailbo
 
 #ifdef __FEATURE_BODY_SEARCH__
                /* Updating mail_text_tbl */
-               memset(sql_query_string, 0x00, QUERY_SIZE);
-               SNPRINTF(sql_query_string, QUERY_SIZE, "UPDATE mail_text_tbl SET mailbox_id = %d ", dest_mailbox_id);
-               if(strlen(sql_query_string) + strlen(where_pararaph) < QUERY_SIZE)
-                       strcat(sql_query_string, where_pararaph);
-               EM_DEBUG_LOG("Query [%s]", sql_query_string);
+               if (rule->action_type == EMAIL_FILTER_BLOCK) {
+                       memset(sql_query_string, 0x00, QUERY_SIZE);
+                       SNPRINTF(sql_query_string, QUERY_SIZE, "UPDATE mail_text_tbl SET mailbox_id = %d ", dest_mailbox_id);
+                       if(strlen(sql_query_string) + strlen(where_pararaph) < QUERY_SIZE)
+                               strcat(sql_query_string, where_pararaph);
+                       EM_DEBUG_LOG("Query [%s]", sql_query_string);
 
-               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
-               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
-                       ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+                       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+                       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+               }
 #endif
        }
 
@@ -13080,9 +13489,13 @@ INTERNAL_FUNC int emstorage_filter_mails_by_rule(int account_id, int dest_mailbo
 
 FINISH_OFF:
 
-       if (ret)
-               *filtered_mail_id_list = mail_list;
-       else
+       if (ret) {
+               if (filtered_mail_id_list)
+                       *filtered_mail_id_list = mail_list;
+
+               if (count_of_mails)
+                       *count_of_mails = count;
+       } else  
                EM_SAFE_FREE(mail_list);
 
        sqlite3_free_table(result);
@@ -13092,9 +13505,6 @@ FINISH_OFF:
 
        EM_SAFE_FREE(where_pararaph);
 
-       if (ret && count_of_mails)
-               *count_of_mails = count;
-
        if (err_code != NULL)
                *err_code = error;
 
@@ -13168,9 +13578,7 @@ INTERNAL_FUNC int emstorage_set_mail_slot_size(int account_id, int mailbox_id, i
        ret = true;
 
 FINISH_OFF:
-
        EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, err);
-
        _DISCONNECT_DB;
 
        EM_SAFE_FREE(where_pararaph);
@@ -13237,21 +13645,21 @@ INTERNAL_FUNC int emstorage_add_meeting_request(int account_id, int input_mailbo
 
        col_index = 0;
        /*
-       EM_DEBUG_LOG(">>>>> meeting_req->mail_id[%d]", meeting_req->mail_id);
-       EM_DEBUG_LOG(">>>>> account_id[%d]", account_id);
-       EM_DEBUG_LOG(">>>>> mailbox_name[%s]", mailbox_name);
-       EM_DEBUG_LOG(">>>>> meeting_req->meeting_response[%d]", meeting_req->meeting_response);
-       EM_DEBUG_LOG(">>>>> meeting_req->start_time[%s]", asctime(&(meeting_req->start_time)));
-       EM_DEBUG_LOG(">>>>> meeting_req->end_time[%s]", asctime(&(meeting_req->end_time)));
-       EM_DEBUG_LOG(">>>>> meeting_req->location[%s]", meeting_req->location);
-       EM_DEBUG_LOG(">>>>> meeting_req->global_object_id[%s]", meeting_req->global_object_id);
-       EM_DEBUG_LOG(">>>>> meeting_req->time_zone.offset_from_GMT[%d]", meeting_req->time_zone.offset_from_GMT);
-       EM_DEBUG_LOG(">>>>> meeting_req->time_zone.standard_name[%s]", meeting_req->time_zone.standard_name);
-       EM_DEBUG_LOG(">>>>> meeting_req->time_zone.standard_time_start_date[%s]", asctime(&(meeting_req->time_zone.standard_time_start_date)));
-       EM_DEBUG_LOG(">>>>> meeting_req->time_zone.standard_bias[%d]", meeting_req->time_zone.standard_bias);
-       EM_DEBUG_LOG(">>>>> meeting_req->time_zone.daylight_name[%s]", meeting_req->time_zone.daylight_name);
-       EM_DEBUG_LOG(">>>>> meeting_req->time_zone.daylight_time_start_date[%s]", asctime(&(meeting_req->time_zone.daylight_time_start_date)));
-       EM_DEBUG_LOG(">>>>> meeting_req->time_zone.daylight_bias[%d]", meeting_req->time_zone.daylight_bias);
+       EM_DEBUG_LOG_SEC(">>>>> meeting_req->mail_id[%d]", meeting_req->mail_id);
+       EM_DEBUG_LOG_SEC(">>>>> account_id[%d]", account_id);
+       EM_DEBUG_LOG_SEC(">>>>> mailbox_name[%s]", mailbox_name);
+       EM_DEBUG_LOG_SEC(">>>>> meeting_req->meeting_response[%d]", meeting_req->meeting_response);
+       EM_DEBUG_LOG_SEC(">>>>> meeting_req->start_time[%s]", asctime(&(meeting_req->start_time)));
+       EM_DEBUG_LOG_SEC(">>>>> meeting_req->end_time[%s]", asctime(&(meeting_req->end_time)));
+       EM_DEBUG_LOG_SEC(">>>>> meeting_req->location[%s]", meeting_req->location);
+       EM_DEBUG_LOG_SEC(">>>>> meeting_req->global_object_id[%s]", meeting_req->global_object_id);
+       EM_DEBUG_LOG_SEC(">>>>> meeting_req->time_zone.offset_from_GMT[%d]", meeting_req->time_zone.offset_from_GMT);
+       EM_DEBUG_LOG_SEC(">>>>> meeting_req->time_zone.standard_name[%s]", meeting_req->time_zone.standard_name);
+       EM_DEBUG_LOG_SEC(">>>>> meeting_req->time_zone.standard_time_start_date[%s]", asctime(&(meeting_req->time_zone.standard_time_start_date)));
+       EM_DEBUG_LOG_SEC(">>>>> meeting_req->time_zone.standard_bias[%d]", meeting_req->time_zone.standard_bias);
+       EM_DEBUG_LOG_SEC(">>>>> meeting_req->time_zone.daylight_name[%s]", meeting_req->time_zone.daylight_name);
+       EM_DEBUG_LOG_SEC(">>>>> meeting_req->time_zone.daylight_time_start_date[%s]", asctime(&(meeting_req->time_zone.daylight_time_start_date)));
+       EM_DEBUG_LOG_SEC(">>>>> meeting_req->time_zone.daylight_bias[%d]", meeting_req->time_zone.daylight_bias);
        */
        _bind_stmt_field_data_int(hStmt, col_index++, meeting_req->mail_id);
        _bind_stmt_field_data_int(hStmt, col_index++, account_id);
@@ -13287,6 +13695,8 @@ INTERNAL_FUNC int emstorage_add_meeting_request(int account_id, int input_mailbo
        ret = true;
 
 FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
        if (hStmt != NULL)  {
                EM_DEBUG_LOG("before sqlite3_finalize hStmt = %p", hStmt);
 
@@ -13297,9 +13707,6 @@ FINISH_OFF:
                }
        }
 
-       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
-       _DISCONNECT_DB;
-
        if (err_code != NULL)
                *err_code = error;
 
@@ -13307,119 +13714,140 @@ FINISH_OFF:
        return ret;
 }
 
-INTERNAL_FUNC int emstorage_get_meeting_request(int mail_id, email_meeting_request_t ** meeting_req, int transaction, int *err_code)
+INTERNAL_FUNC int emstorage_query_meeting_request(const char *conditional_clause, email_meeting_request_t **output_meeting_req, int *output_result_count, int transaction)
 {
-       EM_DEBUG_FUNC_BEGIN();
+       EM_DEBUG_FUNC_BEGIN("conditional_clause[%s] output_meeting_req[%p] output_result_count[%p] transaction[%d]", conditional_clause, output_meeting_req, output_result_count, transaction);
 
-       int count = 0;
-       int rc = -1;
-       int ret = false;
-       int error = EMAIL_ERROR_NONE;
-       email_meeting_request_t *p_temp_meeting_req = NULL;
+       int i = 0;
        int col_index = 0;
-       time_t temp_unix_time;
-
-       EM_IF_NULL_RETURN_VALUE(meeting_req, false);
-
-       DB_STMT hStmt = NULL;
+       int rc;
+       int count = 0;
+       int dummy = 0;
+       int err = EMAIL_ERROR_NONE;
+       char **result = NULL;
        char sql_query_string[QUERY_SIZE] = {0, };
+       email_meeting_request_t* p_temp_meeting_req = NULL;
+       sqlite3 *local_db_handle = NULL;
+       time_t temp_unix_time;
 
-       sqlite3 *local_db_handle = emstorage_get_db_connection();
-       EMSTORAGE_START_READ_TRANSACTION(transaction);
+       if (conditional_clause == NULL || output_meeting_req == NULL || output_result_count == NULL) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
 
-       SNPRINTF(sql_query_string, sizeof(sql_query_string),
-               "SELECT  mail_id, meeting_response, start_time, end_time, location, global_object_id, offset, standard_name, standard_time_start_date, standard_bias, daylight_name, daylight_time_start_date, daylight_bias "
-               " FROM mail_meeting_tbl "
-               " WHERE mail_id = %d", mail_id);
-       EM_DEBUG_LOG("sql : %s ", sql_query_string);
+       col_index = _field_count_of_table[CREATE_TABLE_MAIL_MEETING_TBL];
+       EM_DEBUG_LOG("col_index [%d]", col_index);
 
+       local_db_handle = emstorage_get_db_connection();
 
-       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+       EMSTORAGE_START_READ_TRANSACTION(transaction);
 
-       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
-               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT * FROM mail_meeting_tbl %s", conditional_clause);
 
+       EM_DEBUG_LOG("Query [%s]", sql_query_string);
 
-       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
-       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
-               ("sqlite3_step fail:%d", rc));
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql_query_string, &result, &count, 0, NULL), rc);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc && -1 != rc), {err = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
 
-       if (rc == SQLITE_DONE)  {
-               EM_DEBUG_EXCEPTION(" no Meeting request found...");
-               count = 0;
-               ret = false;
-               error= EMAIL_ERROR_DATA_NOT_FOUND;
+       if (!count) {
+               EM_DEBUG_EXCEPTION("No meeting_request found...");
+               err = EMAIL_ERROR_DATA_NOT_FOUND;
                goto FINISH_OFF;
        }
 
-       if (!(p_temp_meeting_req = (email_meeting_request_t*)malloc(sizeof(email_meeting_request_t)))) {
-               EM_DEBUG_EXCEPTION(" malloc failed...");
-               error = EMAIL_ERROR_OUT_OF_MEMORY;
+       EM_DEBUG_LOG("There are [%d] meeting requests.", count);
+       if (!(p_temp_meeting_req = (email_meeting_request_t*)em_malloc(sizeof(email_meeting_request_t) * count))) {
+               EM_DEBUG_EXCEPTION("malloc for emstorage_mail_tbl_t failed...");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
                goto FINISH_OFF;
        }
 
-       memset(p_temp_meeting_req, 0x00, sizeof(email_meeting_request_t));
-
-       col_index = 0;
+       EM_DEBUG_LOG(">>>> DATA ASSIGN START >> ");
 
-       _get_stmt_field_data_int(hStmt, &(p_temp_meeting_req->mail_id), col_index++);
-       _get_stmt_field_data_int(hStmt, (int *)&(p_temp_meeting_req->meeting_response), col_index++);
-       _get_stmt_field_data_int(hStmt, (int *)(&temp_unix_time), col_index++);
-       gmtime_r(&temp_unix_time, &(p_temp_meeting_req->start_time));
-       _get_stmt_field_data_int(hStmt, (int *)(&temp_unix_time), col_index++);
-       gmtime_r(&temp_unix_time, &(p_temp_meeting_req->end_time));
-       _get_stmt_field_data_string(hStmt, &p_temp_meeting_req->location, 1, col_index++);
-       _get_stmt_field_data_string(hStmt, &p_temp_meeting_req->global_object_id, 1, col_index++);
-       _get_stmt_field_data_int(hStmt, &(p_temp_meeting_req->time_zone.offset_from_GMT), col_index++);
-
-       _get_stmt_field_data_string_without_allocation(hStmt, p_temp_meeting_req->time_zone.standard_name, STANDARD_NAME_LEN_IN_MAIL_MEETING_TBL, 1, col_index++);
-       _get_stmt_field_data_int(hStmt, (int *)(&temp_unix_time), col_index++);
-       gmtime_r(&temp_unix_time, &(p_temp_meeting_req->time_zone.standard_time_start_date));
-       _get_stmt_field_data_int(hStmt, &(p_temp_meeting_req->time_zone.standard_bias), col_index++);
-
-       _get_stmt_field_data_string_without_allocation(hStmt, p_temp_meeting_req->time_zone.daylight_name, DAYLIGHT_NAME_LEN_IN_MAIL_MEETING_TBL, 1, col_index++);
-       _get_stmt_field_data_int(hStmt, (int *)(&temp_unix_time), col_index++);
-       gmtime_r(&temp_unix_time, &(p_temp_meeting_req->time_zone.daylight_time_start_date));
-       _get_stmt_field_data_int(hStmt, &(p_temp_meeting_req->time_zone.daylight_bias), col_index++);
+       for (i = 0; i < count; i++) {
+               _get_table_field_data_int(result, &(p_temp_meeting_req[i].mail_id), col_index++);
+               _get_table_field_data_int(result, &dummy, col_index++); /* account_id. but why should this field exist in DB table? */
+               _get_table_field_data_int(result, &dummy, col_index++); /* mailbox_id */
+               _get_table_field_data_int(result, (int*)&(p_temp_meeting_req[i].meeting_response), col_index++);
+               _get_table_field_data_int(result, (int*)(&temp_unix_time), col_index++); /* start time */
+               gmtime_r(&temp_unix_time, &(p_temp_meeting_req[i].start_time));
+               _get_table_field_data_int(result, (int*)(&temp_unix_time), col_index++); /* end time */
+               gmtime_r(&temp_unix_time, &(p_temp_meeting_req[i].end_time));
+               _get_table_field_data_string(result, &p_temp_meeting_req[i].location, 1, col_index++);
+               _get_table_field_data_string(result, &p_temp_meeting_req[i].global_object_id, 1, col_index++);
+               _get_table_field_data_int(result, &(p_temp_meeting_req[i].time_zone.offset_from_GMT), col_index++);
+               _get_table_field_data_string_without_allocation(result, p_temp_meeting_req[i].time_zone.standard_name, STANDARD_NAME_LEN_IN_MAIL_MEETING_TBL, 1, col_index++);
+               _get_table_field_data_int(result, (int*)(&temp_unix_time), col_index++);
+               gmtime_r(&temp_unix_time, &(p_temp_meeting_req[i].time_zone.standard_time_start_date));
+               _get_table_field_data_int(result, &(p_temp_meeting_req[i].time_zone.standard_bias), col_index++);
+               _get_table_field_data_string_without_allocation(result, p_temp_meeting_req[i].time_zone.daylight_name, DAYLIGHT_NAME_LEN_IN_MAIL_MEETING_TBL, 1, col_index++);
+               _get_table_field_data_int(result, (int*)(&temp_unix_time), col_index++);
+               gmtime_r(&temp_unix_time, &(p_temp_meeting_req[i].time_zone.daylight_time_start_date));
+               _get_table_field_data_int(result, &(p_temp_meeting_req[i].time_zone.daylight_bias), col_index++);
+       }
 
-       /*
-       EM_DEBUG_LOG(">>>>> meeting_req->mail_id[%d]", p_temp_meeting_req->mail_id);
-       EM_DEBUG_LOG(">>>>> meeting_req->meeting_response[%d]", p_temp_meeting_req->meeting_response);
-       EM_DEBUG_LOG(">>>>> meeting_req->start_time[%s]", asctime(&(p_temp_meeting_req->start_time)));
-       EM_DEBUG_LOG(">>>>> meeting_req->end_time[%s]", asctime(&(p_temp_meeting_req->end_time)));
-       EM_DEBUG_LOG(">>>>> meeting_req->location[%s]", p_temp_meeting_req->location);
-       EM_DEBUG_LOG(">>>>> meeting_req->global_object_id[%s]", p_temp_meeting_req->global_object_id);
-       EM_DEBUG_LOG(">>>>> meeting_req->time_zone.offset_from_GMT[%d]", p_temp_meeting_req->time_zone.offset_from_GMT);
-       EM_DEBUG_LOG(">>>>> meeting_req->time_zone.standard_name[%s]", p_temp_meeting_req->time_zone.standard_name);
-       EM_DEBUG_LOG(">>>>> meeting_req->time_zone.standard_time_start_date[%s]", asctime(&(p_temp_meeting_req->time_zone.standard_time_start_date)));
-       EM_DEBUG_LOG(">>>>> meeting_req->time_zone.standard_bias[%d]", p_temp_meeting_req->time_zone.standard_bias);
-       EM_DEBUG_LOG(">>>>> meeting_req->time_zone.daylight_name[%s]", p_temp_meeting_req->time_zone.daylight_name);
-       EM_DEBUG_LOG(">>>>> meeting_req->time_zone.daylight_time_start_date[%s]", asctime(&(p_temp_meeting_req->time_zone.daylight_time_start_date)));
-       EM_DEBUG_LOG(">>>>> meeting_req->time_zone.daylight_bias[%d]", p_temp_meeting_req->time_zone.daylight_bias);
-       */
-       ret = true;
 
 FINISH_OFF:
-       if (ret == true)
-               *meeting_req = p_temp_meeting_req;
-       else  {
-               EM_SAFE_FREE(p_temp_meeting_req);
-       }
-
-       if (hStmt != NULL)  {
-               EM_DEBUG_LOG("before sqlite3_finalize hStmt = %p", hStmt);
+       if(result)
+               sqlite3_free_table(result);
 
-               rc = sqlite3_finalize(hStmt);
-               hStmt = NULL;
-               if (rc != SQLITE_OK)  {
-                       EM_DEBUG_EXCEPTION("sqlite3_finalize failed - %d", rc);
-                       error = EMAIL_ERROR_DB_FAILURE;
-               }
+       if (err == EMAIL_ERROR_NONE)  {
+               if (p_temp_meeting_req)
+                       *output_meeting_req = p_temp_meeting_req;
+               *output_result_count = count;
        }
+       else
+               EM_SAFE_FREE(p_temp_meeting_req);
 
        EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
+
+       sqlite3_db_release_memory(local_db_handle);
+
        _DISCONNECT_DB;
 
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC int emstorage_get_meeting_request(int mail_id, email_meeting_request_t ** meeting_req, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int count = 0;
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char conditional_clause[QUERY_SIZE] = {0, };
+
+       EM_IF_NULL_RETURN_VALUE(meeting_req, false);
+
+
+       SNPRINTF(conditional_clause, QUERY_SIZE, " WHERE mail_id = %d", mail_id);
+       EM_DEBUG_LOG("conditional_clause [%s]", conditional_clause);
+
+       if((error = emstorage_query_meeting_request(conditional_clause, meeting_req, &count, transaction)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emstorage_query_meeting_request failed. [%d]", error);
+               goto FINISH_OFF;
+       }
+
+       EM_DEBUG_LOG_SEC(">>>>> (*meeting_req)->mail_id[%d]", (*meeting_req)->mail_id);
+       EM_DEBUG_LOG_SEC(">>>>> (*meeting_req)->meeting_response[%d]", (*meeting_req)->meeting_response);
+       EM_DEBUG_LOG_SEC(">>>>> (*meeting_req)->start_time[%s]", asctime(&((*meeting_req)->start_time)));
+       EM_DEBUG_LOG_SEC(">>>>> (*meeting_req)->end_time[%s]", asctime(&((*meeting_req)->end_time)));
+       EM_DEBUG_LOG_SEC(">>>>> (*meeting_req)->location[%s]", (*meeting_req)->location);
+       EM_DEBUG_LOG_SEC(">>>>> (*meeting_req)->global_object_id[%s]", (*meeting_req)->global_object_id);
+       EM_DEBUG_LOG_SEC(">>>>> (*meeting_req)->time_zone.offset_from_GMT[%d]", (*meeting_req)->time_zone.offset_from_GMT);
+       EM_DEBUG_LOG_SEC(">>>>> (*meeting_req)->time_zone.standard_name[%s]", (*meeting_req)->time_zone.standard_name);
+       EM_DEBUG_LOG_SEC(">>>>> (*meeting_req)->time_zone.standard_time_start_date[%s]", asctime(&((*meeting_req)->time_zone.standard_time_start_date)));
+       EM_DEBUG_LOG_SEC(">>>>> (*meeting_req)->time_zone.standard_bias[%d]", (*meeting_req)->time_zone.standard_bias);
+       EM_DEBUG_LOG_SEC(">>>>> (*meeting_req)->time_zone.daylight_name[%s]", (*meeting_req)->time_zone.daylight_name);
+       EM_DEBUG_LOG_SEC(">>>>> (*meeting_req)->time_zone.daylight_time_start_date[%s]", asctime(&((*meeting_req)->time_zone.daylight_time_start_date)));
+       EM_DEBUG_LOG_SEC(">>>>> (*meeting_req)->time_zone.daylight_bias[%d]", (*meeting_req)->time_zone.daylight_bias);
+       ret = true;
+
+FINISH_OFF:
+
        if (err_code != NULL)
                *err_code = error;
 
@@ -13441,8 +13869,9 @@ INTERNAL_FUNC int emstorage_update_meeting_request(email_meeting_request_t* meet
 
        if (!meeting_req) {
                EM_DEBUG_EXCEPTION("Invalid Parameter!");
-               error = EMAIL_ERROR_INVALID_PARAM;
-               goto FINISH_OFF;
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
        }
 
        sqlite3 *local_db_handle = emstorage_get_db_connection();
@@ -13475,19 +13904,19 @@ INTERNAL_FUNC int emstorage_update_meeting_request(email_meeting_request_t* meet
        EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
                ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
 /*
-       EM_DEBUG_LOG(">>>>> meeting_req->mail_id[%d]", meeting_req->mail_id);
-       EM_DEBUG_LOG(">>>>> meeting_req->meeting_response[%d]", meeting_req->meeting_response);
-       EM_DEBUG_LOG(">>>>> meeting_req->start_time[%s]", asctime(&(meeting_req->start_time)));
-       EM_DEBUG_LOG(">>>>> meeting_req->end_time[%s]", asctime(&(meeting_req->end_time)));
-       EM_DEBUG_LOG(">>>>> meeting_req->location[%s]", meeting_req->location);
-       EM_DEBUG_LOG(">>>>> meeting_req->global_object_id[%s]", meeting_req->global_object_id);
-       EM_DEBUG_LOG(">>>>> meeting_req->time_zone.offset_from_GMT[%d]", meeting_req->time_zone.offset_from_GMT);
-       EM_DEBUG_LOG(">>>>> meeting_req->time_zone.standard_name[%s]", meeting_req->time_zone.standard_name);
-       EM_DEBUG_LOG(">>>>> meeting_req->time_zone.standard_time_start_date[%s]", asctime(&(meeting_req->time_zone.standard_time_start_date)));
-       EM_DEBUG_LOG(">>>>> meeting_req->time_zone.standard_bias[%d]", meeting_req->time_zone.standard_bias);
-       EM_DEBUG_LOG(">>>>> meeting_req->time_zone.daylight_name[%s]", meeting_req->time_zone.daylight_name);
-       EM_DEBUG_LOG(">>>>> meeting_req->time_zone.daylight_time_start_date[%s]", asctime(&(meeting_req->time_zone.daylight_time_start_date)));
-       EM_DEBUG_LOG(">>>>> meeting_req->time_zone.daylight_bias[%d]", meeting_req->time_zone.daylight_bias);
+       EM_DEBUG_LOG_SEC(">>>>> meeting_req->mail_id[%d]", meeting_req->mail_id);
+       EM_DEBUG_LOG_SEC(">>>>> meeting_req->meeting_response[%d]", meeting_req->meeting_response);
+       EM_DEBUG_LOG_SEC(">>>>> meeting_req->start_time[%s]", asctime(&(meeting_req->start_time)));
+       EM_DEBUG_LOG_SEC(">>>>> meeting_req->end_time[%s]", asctime(&(meeting_req->end_time)));
+       EM_DEBUG_LOG_SEC(">>>>> meeting_req->location[%s]", meeting_req->location);
+       EM_DEBUG_LOG_SEC(">>>>> meeting_req->global_object_id[%s]", meeting_req->global_object_id);
+       EM_DEBUG_LOG_SEC(">>>>> meeting_req->time_zone.offset_from_GMT[%d]", meeting_req->time_zone.offset_from_GMT);
+       EM_DEBUG_LOG_SEC(">>>>> meeting_req->time_zone.standard_name[%s]", meeting_req->time_zone.standard_name);
+       EM_DEBUG_LOG_SEC(">>>>> meeting_req->time_zone.standard_time_start_date[%s]", asctime(&(meeting_req->time_zone.standard_time_start_date)));
+       EM_DEBUG_LOG_SEC(">>>>> meeting_req->time_zone.standard_bias[%d]", meeting_req->time_zone.standard_bias);
+       EM_DEBUG_LOG_SEC(">>>>> meeting_req->time_zone.daylight_name[%s]", meeting_req->time_zone.daylight_name);
+       EM_DEBUG_LOG_SEC(">>>>> meeting_req->time_zone.daylight_time_start_date[%s]", asctime(&(meeting_req->time_zone.daylight_time_start_date)));
+       EM_DEBUG_LOG_SEC(">>>>> meeting_req->time_zone.daylight_bias[%d]", meeting_req->time_zone.daylight_bias);
 */
        int col_index = 0;
 
@@ -13517,6 +13946,7 @@ INTERNAL_FUNC int emstorage_update_meeting_request(email_meeting_request_t* meet
 
 FINISH_OFF:
        EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
 
        if (hStmt != NULL)  {
                EM_DEBUG_LOG("before sqlite3_finalize hStmt = %p", hStmt);
@@ -13529,8 +13959,6 @@ FINISH_OFF:
                }
        }
 
-       _DISCONNECT_DB;
-
        if (err_code != NULL)
                *err_code = error;
 
@@ -13595,10 +14023,7 @@ INTERNAL_FUNC void emstorage_free_meeting_request(email_meeting_request_t *meeti
 {
        EM_DEBUG_FUNC_BEGIN();
 
-       if (!meeting_req ) {
-               EM_DEBUG_EXCEPTION("NULL PARAM");
-               return;
-               }
+       if (!meeting_req ) return;
 
        EM_SAFE_FREE(meeting_req->location);
        EM_SAFE_FREE(meeting_req->global_object_id);
@@ -13621,8 +14046,9 @@ INTERNAL_FUNC int emstorage_get_overflowed_mail_id_list(int account_id, int inpu
 
        if (input_mailbox_id <= 0 || !mail_id_list || !mail_id_count || account_id < 1) {
                EM_DEBUG_EXCEPTION("Invalid Parameter");
-               error = EMAIL_ERROR_INVALID_PARAM;
-               goto FINISH_OFF;
+               if (err_code)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
        }
 
        SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT mail_id FROM mail_tbl WHERE account_id = %d AND mailbox_id = %d ORDER BY date_time DESC LIMIT %d, 10000", account_id, input_mailbox_id, mail_slot_size);
@@ -13698,9 +14124,9 @@ INTERNAL_FUNC int emstorage_get_thread_id_by_mail_id(int mail_id, int *thread_id
 
        if (mail_id == 0 || thread_id == NULL) {
                EM_DEBUG_EXCEPTION("Invalid Parameter");
-               if (err_code != NULL)
+               if (err_code)
                        *err_code = EMAIL_ERROR_INVALID_PARAM;
-               goto FINISH_OFF;
+               return false;
        }
 
        sqlite3 *local_db_handle = emstorage_get_db_connection();
@@ -13714,7 +14140,7 @@ INTERNAL_FUNC int emstorage_get_thread_id_by_mail_id(int mail_id, int *thread_id
                ("SQL(%s) sqlite3_get_table fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
 
        if (!result_count) {
-               EM_DEBUG_EXCEPTION("No mail found...");
+               EM_DEBUG_LOG("No mail found...");
                ret = false;
                err= EMAIL_ERROR_MAIL_NOT_FOUND;
                /* sqlite3_free_table(result); */
@@ -13728,7 +14154,6 @@ INTERNAL_FUNC int emstorage_get_thread_id_by_mail_id(int mail_id, int *thread_id
        ret = true;
 
 FINISH_OFF:
-
        _DISCONNECT_DB;
 
        if (err_code != NULL)
@@ -13751,9 +14176,9 @@ INTERNAL_FUNC int emstorage_update_latest_thread_mail(int account_id, int thread
 
        if (thread_id == 0) {
                EM_DEBUG_EXCEPTION("Invalid Parameter");
-               if (err_code != NULL)
+               if (err_code)
                        *err_code = EMAIL_ERROR_INVALID_PARAM;
-               goto FINISH_OFF;
+               return false;
        }
 
        sqlite3 *local_db_handle = emstorage_get_db_connection();
@@ -13768,11 +14193,12 @@ INTERNAL_FUNC int emstorage_update_latest_thread_mail(int account_id, int thread
                        ("SQL(%s) sqlite3_get_table fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
                EM_DEBUG_LOG("result_count[%d]", result_count);
                if (result_count == 0) {
-                       EM_DEBUG_EXCEPTION("No mail found...");
+                       EM_DEBUG_LOG("No mail found...");
                        ret = false;
-                       err= EMAIL_ERROR_MAIL_NOT_FOUND;
+                       if (err_code)
+                               *err_code =  EMAIL_ERROR_MAIL_NOT_FOUND;
                        sqlite3_free_table(result);
-                       goto FINISH_OFF;
+                       return false;
                }
 
                _get_table_field_data_int(result, &latest_mail_id, 2);
@@ -13808,9 +14234,7 @@ INTERNAL_FUNC int emstorage_update_latest_thread_mail(int account_id, int thread
        ret = true;
 
 FINISH_OFF:
-
        EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, err);
-
        _DISCONNECT_DB;
 
        if (err_code != NULL)
@@ -13823,7 +14247,7 @@ FINISH_OFF:
 
 INTERNAL_FUNC void emstorage_flush_db_cache()
 {
-       sqlite3_release_memory(-1);
+       /* sqlite3_release_memory(-1); */
 }
 
 #ifdef __FEATURE_LOCAL_ACTIVITY__
@@ -13860,7 +14284,7 @@ INTERNAL_FUNC int emstorage_add_activity(emstorage_activity_tbl_t* local_activit
        EM_DEBUG_LOG(">>>>> MAIL ID [ %d ] ", local_activity->mail_id);
        EM_DEBUG_LOG(">>>>> ACCOUNT ID [ %d ] ", local_activity->account_id);
        EM_DEBUG_LOG(">>>>> ACTIVITY TYPE [ %d ] ", local_activity->activity_type);
-       EM_DEBUG_LOG(">>>>> SERVER MAIL ID [ %s ] ", local_activity->server_mailid);
+       EM_DEBUG_LOG_SEC(">>>>> SERVER MAIL ID [ %s ] ", local_activity->server_mailid);
        EM_DEBUG_LOG(">>>>> SOURCE MAILBOX [ %s ] ", local_activity->src_mbox);
        EM_DEBUG_LOG(">>>>> DEST MAILBOX   [ %s ] ", local_activity->dest_mbox);
 
@@ -13873,9 +14297,6 @@ INTERNAL_FUNC int emstorage_add_activity(emstorage_activity_tbl_t* local_activit
 
        EM_DEBUG_LOG(">>>> SQL STMT [ %s ] ", sql_query_string);
 
-
-
-
        _bind_stmt_field_data_int(hStmt, i++, local_activity->activity_id);
        _bind_stmt_field_data_int(hStmt, i++, local_activity->account_id);
        _bind_stmt_field_data_int(hStmt, i++, local_activity->mail_id);
@@ -13895,6 +14316,8 @@ INTERNAL_FUNC int emstorage_add_activity(emstorage_activity_tbl_t* local_activit
        ret = true;
 
 FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
 
        if (hStmt != NULL)  {
                rc = sqlite3_finalize(hStmt);
@@ -13904,13 +14327,6 @@ FINISH_OFF:
                        error = EMAIL_ERROR_DB_FAILURE;
                }
        }
-       else {
-               EM_DEBUG_LOG(" >>>>>>>>>> hStmt is NULL!!!");
-       }
-
-       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
-       _DISCONNECT_DB;
-
 
        if (err_code != NULL)
                *err_code = error;
@@ -13941,11 +14357,13 @@ INTERNAL_FUNC int emstorage_get_activity(int account_id, int activityid, emstora
 
        if (!select_num || !activity_list || account_id <= 0 || activityid < 0) {
                EM_DEBUG_LOG(" select_num[%p], activity_list[%p] account_id [%d] activityid [%d] ", select_num, activity_list, account_id, activityid);
-               if (err_code != NULL)
+               if (err_code)
                        *err_code = EMAIL_ERROR_INVALID_PARAM;
                return false;
        }
 
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
        EMSTORAGE_START_READ_TRANSACTION(transaction);
 
        memset(sql_query_string, 0x00, sizeof(sql_query_string));
@@ -13965,8 +14383,6 @@ INTERNAL_FUNC int emstorage_get_activity(int account_id, int activityid, emstora
        EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
                ("SQL(%s) sqlite3_get_table fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
 
-
-
        col_index = 7;
 
        if (!(p_activity_tbl = (emstorage_activity_tbl_t*)em_malloc(sizeof(emstorage_activity_tbl_t) * count))) {
@@ -14020,7 +14436,7 @@ INTERNAL_FUNC int emstorage_get_activity(int account_id, int activityid, emstora
        ret = true;
 
 FINISH_OFF:
-
+       EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
 
        if (ret == true)  {
                *activity_list = p_activity_tbl;
@@ -14031,7 +14447,7 @@ FINISH_OFF:
                emstorage_free_local_activity(&p_activity_tbl, count, NULL);
        }
 
-       EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
+
        if (err_code != NULL)
                *err_code = error;
 
@@ -14051,14 +14467,15 @@ INTERNAL_FUNC int emstorage_get_next_activity_id(int *activity_id, int *err_code
        char *sql = NULL;
        char **result = NULL;
 
-       if (NULL == activity_id)
-       {
+       if (NULL == activity_id) {
                EM_DEBUG_EXCEPTION(" activity_id[%p]", activity_id);
-
-               err = EMAIL_ERROR_INVALID_PARAM;
-               goto FINISH_OFF;
+               if (err_code) 
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
        }
 
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
        /*  increase unique id */
 
        sql = "SELECT max(rowid) FROM mail_local_activity_tbl;";
@@ -14081,9 +14498,8 @@ INTERNAL_FUNC int emstorage_get_next_activity_id(int *activity_id, int *err_code
 
        FINISH_OFF:
 
-       if (NULL != err_code) {
+       if (err_code)
                *err_code = err;
-       }
 
        EM_DEBUG_FUNC_END("ret [%d]", ret);
        return ret;
@@ -14110,7 +14526,7 @@ INTERNAL_FUNC int emstorage_get_activity_id_list(int account_id, int ** activity
        int *activity_ids = NULL;
        int col_index = 0;
        char **result = NULL;
-
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
        EMSTORAGE_START_READ_TRANSACTION(transaction);
 
        memset(sql_query_string, 0x00, sizeof(sql_query_string));
@@ -14177,8 +14593,7 @@ INTERNAL_FUNC int emstorage_free_activity_id_list(int *activity_id_list, int *er
                goto FINISH_OFF;
        }
        else {
-               free(activity_id_list);
-               activity_id_list = NULL;
+               EM_SAFE_FREE (activity_id_list);
        }
 
 
@@ -14218,6 +14633,7 @@ INTERNAL_FUNC int emstorage_delete_local_activity(emstorage_activity_tbl_t* loca
        int query_and = 0;
        int query_where = 0;
        char sql_query_string[8192] = { 0x00, };
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
        EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
 
        memset(sql_query_string, 0x00, sizeof(sql_query_string));
@@ -14309,12 +14725,13 @@ INTERNAL_FUNC int emstorage_free_local_activity(emstorage_activity_tbl_t **local
                int i = 0;
                if (p) {
                        for (; i < count; i++)  {
-                               EM_SAFE_FREE(p[i].dest_mbox);
-                               EM_SAFE_FREE(p[i].src_mbox);
-                               EM_SAFE_FREE(p[i].server_mailid);
+                               EM_SAFE_FREE (p[i].dest_mbox);
+                               EM_SAFE_FREE (p[i].src_mbox);
+                               EM_SAFE_FREE (p[i].server_mailid);
                        }
 
-                       free(p);        *local_activity_list = NULL;
+                       EM_SAFE_FREE (p);       
+                       *local_activity_list = NULL;
                }
        }
 
@@ -14353,6 +14770,7 @@ static int _get_key_value_string_for_list_filter_rule(email_list_filter_rule_t *
        case EMAIL_MAIL_ATTRIBUTE_SERVER_MAIL_STATUS      :
        case EMAIL_MAIL_ATTRIBUTE_REFERENCE_MAIL_ID       :
        case EMAIL_MAIL_ATTRIBUTE_BODY_DOWNLOAD_STATUS    :
+       case EMAIL_MAIL_ATTRIBUTE_MAIL_SIZE               :
        case EMAIL_MAIL_ATTRIBUTE_FILE_PATH_PLAIN         :
        case EMAIL_MAIL_ATTRIBUTE_FILE_PATH_HTML          :
        case EMAIL_MAIL_ATTRIBUTE_FILE_SIZE               :
@@ -14376,6 +14794,9 @@ static int _get_key_value_string_for_list_filter_rule(email_list_filter_rule_t *
        case EMAIL_MAIL_ATTRIBUTE_MESSAGE_CLASS           :
        case EMAIL_MAIL_ATTRIBUTE_DIGEST_TYPE             :
        case EMAIL_MAIL_ATTRIBUTE_SMIME_TYPE              :
+       case EMAIL_MAIL_ATTRIBUTE_REMAINING_RESEND_TIMES  :
+       case EMAIL_MAIL_ATTRIBUTE_TAG_ID                  :
+       case EMAIL_MAIL_ATTRIBUTE_EAS_DATA_LENGTH_TYPE    :
                SNPRINTF(key_value_string, QUERY_SIZE, "%d", input_list_filter_rule->key_value.integer_type_value);
                break;
 
@@ -14407,6 +14828,9 @@ static int _get_key_value_string_for_list_filter_rule(email_list_filter_rule_t *
                break;
 
        case EMAIL_MAIL_ATTRIBUTE_DATE_TIME               :
+       case EMAIL_MAIL_ATTRIBUTE_SCHEDULED_SENDING_TIME  :
+       case EMAIL_MAIL_ATTRIBUTE_REPLIED_TIME            :
+       case EMAIL_MAIL_ATTRIBUTE_FORWARDED_TIME          :
                SNPRINTF(key_value_string, QUERY_SIZE, "%d", (int)input_list_filter_rule->key_value.datetime_type_value);
                break;
 
@@ -14556,6 +14980,104 @@ FINISH_OFF:
        return ret;
 }
 
+static int _make_filter_attach_rule_string(email_list_filter_rule_attach_t *input_list_filter_rule, char **output_string)
+{
+       EM_DEBUG_FUNC_BEGIN("input_list_filter_rule [%p], output_string [%p]", input_list_filter_rule, output_string);
+
+       int   ret = EMAIL_ERROR_NONE;
+       char *field_name_string = NULL;
+       char  key_value_string[QUERY_SIZE] = {0,};
+       char  result_rule_string[QUERY_SIZE] = {0,};
+
+       int rc = -1;
+       int count = 0;
+       int col_index = 0;
+       int error = EMAIL_ERROR_NONE;
+       char **result = NULL;
+       char sql_query_string[QUERY_SIZE] = {0,};
+       char sql_query_string2[QUERY_SIZE] = {0,};
+       sqlite3 *local_db_handle = NULL;
+
+       if(input_list_filter_rule == NULL || output_string == NULL) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               return  EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       field_name_string = EM_SAFE_STRDUP("attachment_name");
+       SNPRINTF(key_value_string, QUERY_SIZE, "%s", input_list_filter_rule->key_value.string_type_value);
+
+       switch (input_list_filter_rule->rule_type) {
+
+       case EMAIL_LIST_FILTER_RULE_INCLUDE:
+               SNPRINTF(result_rule_string, QUERY_SIZE, "WHERE %s LIKE \'%%%s%%\' ", field_name_string, key_value_string);
+               break;
+
+       case EMAIL_LIST_FILTER_RULE_MATCH:
+               SNPRINTF(result_rule_string, QUERY_SIZE, "WHERE %s MATCH \'%s\' ", field_name_string, key_value_string);
+               break;
+
+       default :
+               EM_DEBUG_EXCEPTION("Invalid rule_type [%d]", input_list_filter_rule->rule_type);
+               ret = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_READ_TRANSACTION(true);
+       SNPRINTF(sql_query_string, QUERY_SIZE, "SELECT mail_id FROM mail_attachment_tbl %s", result_rule_string);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql_query_string, &result, &count, 0, NULL), rc);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc && -1 != rc), {error = EMAIL_ERROR_DB_FAILURE; sqlite3_free_table(result); goto FINISH_OFF;},
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       col_index = 1;
+
+       if (!count) {
+               EM_DEBUG_LOG("No mail found...");
+               ret = true;
+               error= EMAIL_ERROR_MAIL_NOT_FOUND;
+               *output_string = strdup("mail_id IN ( ) ");
+               goto FINISH_OFF;
+       }
+
+       EM_DEBUG_LOG_DEV (">>>> DATA ASSIGN START >>");
+       int i = 0;
+       int *mail_ids = NULL;
+       if (!(mail_ids = (int *)em_malloc(sizeof(int) * count))) {
+               EM_DEBUG_EXCEPTION("malloc for mail_ids failed...");
+               error = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       for (i = 0; i < count; i++) {
+               _get_table_field_data_int(result, &(mail_ids[i]), col_index++);
+               EM_DEBUG_LOG_DEV (">>>> DATA ASSIGN [mail_id : %d] >>", mail_ids[i]);
+       }
+
+       EM_DEBUG_LOG_DEV (">>>> DATA ASSIGN END [count : %d] >>", count);
+       sqlite3_free_table(result);
+       EMSTORAGE_FINISH_READ_TRANSACTION(true);
+
+       sqlite3_db_release_memory(local_db_handle);
+
+       _DISCONNECT_DB;
+
+       int cur_query = 0;
+       cur_query += SNPRINTF_OFFSET(sql_query_string2, cur_query, QUERY_SIZE, "mail_id IN ( ");
+       for (i = 0; i < count-1; i++) {
+               cur_query += SNPRINTF_OFFSET(sql_query_string2, cur_query, QUERY_SIZE, "%d, ", mail_ids[i]);
+       }
+       cur_query += SNPRINTF_OFFSET(sql_query_string2, cur_query, QUERY_SIZE, "%d ) ", mail_ids[count-1]);
+
+       *output_string = strdup(sql_query_string2);
+       EM_SAFE_FREE(mail_ids); /*prevent 50929*/
+
+FINISH_OFF:
+       EM_SAFE_FREE(field_name_string);
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
 static int _make_filter_fts_rule_string(email_list_filter_rule_fts_t *input_list_filter_rule, char **output_string)
 {
        EM_DEBUG_FUNC_BEGIN("input_list_filter_rule [%p], output_string [%p]", input_list_filter_rule, output_string);
@@ -14609,14 +15131,14 @@ static int _make_filter_fts_rule_string(email_list_filter_rule_fts_t *input_list
        col_index = 1;
 
        if (!count) {
-               EM_DEBUG_EXCEPTION("No mail found...");
+               EM_DEBUG_LOG("No mail found...");
                ret = true;
                error= EMAIL_ERROR_MAIL_NOT_FOUND;
                *output_string = strdup("mail_id IN ( ) ");
                goto FINISH_OFF;
        }
 
-       EM_DEBUG_LOG(">>>> DATA ASSIGN START >>");
+       EM_DEBUG_LOG_DEV (">>>> DATA ASSIGN START >>");
        int i = 0;
        int *mail_ids = NULL;
        if (!(mail_ids = (int *)em_malloc(sizeof(int) * count))) {
@@ -14627,15 +15149,14 @@ static int _make_filter_fts_rule_string(email_list_filter_rule_fts_t *input_list
 
        for (i = 0; i < count; i++) {
                _get_table_field_data_int(result, &(mail_ids[i]), col_index++);
-               EM_DEBUG_LOG(">>>> DATA ASSIGN [mail_id : %d] >>", mail_ids[i]);
+               EM_DEBUG_LOG_DEV (">>>> DATA ASSIGN [mail_id : %d] >>", mail_ids[i]);
        }
 
-       EM_DEBUG_LOG(">>>> DATA ASSIGN END [count : %d] >>", count);
-       EM_PROFILE_END(emstorage_query_mail_list_loop);
+       EM_DEBUG_LOG_DEV (">>>> DATA ASSIGN END [count : %d] >>", count);
        sqlite3_free_table(result);
        EMSTORAGE_FINISH_READ_TRANSACTION(true);
 
-       sqlite3_release_memory(-1);
+       sqlite3_db_release_memory(local_db_handle);
 
        _DISCONNECT_DB;
 
@@ -14647,7 +15168,6 @@ static int _make_filter_fts_rule_string(email_list_filter_rule_fts_t *input_list
        cur_query += SNPRINTF_OFFSET(sql_query_string2, cur_query, QUERY_SIZE, "%d ) ", mail_ids[count-1]);
 
        *output_string = strdup(sql_query_string2);
-
        EM_SAFE_FREE(mail_ids); /*prevent 50929*/
 
 FINISH_OFF:
@@ -14662,6 +15182,14 @@ static int _make_order_rule_string(email_list_sorting_rule_t *input_sorting_rule
        char  result_rule_string[QUERY_SIZE] = { 0 , };
        int   ret = EMAIL_ERROR_NONE;
 
+       emstorage_account_tbl_t *account_tbl_array = NULL;
+       int count = 0;
+       int i = 0;
+       char *result_str = NULL;
+       char *tmp_str1 = NULL;
+       char *tmp_str2 = NULL;
+       char query_per_account[QUERY_SIZE] = { 0 , };
+
        if(input_sorting_rule->force_boolean_check) {
                SNPRINTF(result_rule_string, QUERY_SIZE, "%s = 0 ", emcore_get_mail_field_name_by_attribute_type(input_sorting_rule->target_attribute));
        }
@@ -14669,14 +15197,70 @@ static int _make_order_rule_string(email_list_sorting_rule_t *input_sorting_rule
                EM_SAFE_STRCPY(result_rule_string, emcore_get_mail_field_name_by_attribute_type(input_sorting_rule->target_attribute));
 
        switch (input_sorting_rule->sort_order) {
-               case EMAIL_SORT_ORDER_ASCEND     :
+               case EMAIL_SORT_ORDER_ASCEND :
                        EM_SAFE_STRCAT(result_rule_string, " ASC ");
                        break;
 
-               case EMAIL_SORT_ORDER_DESCEND    :
+               case EMAIL_SORT_ORDER_DESCEND :
                        EM_SAFE_STRCAT(result_rule_string, " DESC ");
                        break;
 
+               case EMAIL_SORT_ORDER_TO_CCBCC :
+                       memset(result_rule_string, 0, QUERY_SIZE);
+                       if (input_sorting_rule->key_value.string_type_value)
+                               sqlite3_snprintf(QUERY_SIZE, result_rule_string,
+                                               " CASE WHEN full_address_to LIKE \'%%%q%%\' THEN 1 ELSE 2 END ",
+                                               input_sorting_rule->key_value.string_type_value);
+                       break;
+
+               case EMAIL_SORT_ORDER_TO_CC_BCC :
+                       memset(result_rule_string, 0, QUERY_SIZE);
+                       if (input_sorting_rule->key_value.string_type_value)
+                               sqlite3_snprintf(QUERY_SIZE, result_rule_string,
+                                               " CASE WHEN full_address_to LIKE \'%%%q%%\' THEN 1 WHEN full_address_cc LIKE \'%%%q%%\' THEN 2 ELSE 3 END ",
+                                               input_sorting_rule->key_value.string_type_value, input_sorting_rule->key_value.string_type_value);
+                       break;
+
+               case EMAIL_SORT_ORDER_TO_CCBCC_ALL :
+                       if (!emstorage_get_account_list(&count, &account_tbl_array, true, false, NULL)) {
+                               EM_DEBUG_EXCEPTION("emstorage_get_account_list failed");
+                               goto FINISH_OFF;
+                       }
+
+                       if (!count) {
+                               EM_DEBUG_LOG("No account exist");
+                               ret = EMAIL_ERROR_INVALID_PARAM;
+                               goto FINISH_OFF;
+                       }
+
+                       for (i = 0; i < count; i++) {
+                               if (i > 0 && result_str) {
+                                       tmp_str2 = result_str;
+                                       result_str = g_strconcat(tmp_str2, " OR ", NULL);
+                                       EM_SAFE_FREE(tmp_str2);
+                               }
+
+                               memset(query_per_account, 0, QUERY_SIZE);
+                               snprintf(query_per_account, QUERY_SIZE,
+                                               "(account_id = %d AND full_address_to LIKE \'%%%s%%\')",
+                                               account_tbl_array[i].account_id, account_tbl_array[i].user_email_address);
+
+                               tmp_str1 = result_str;
+                               if (tmp_str1)
+                                       result_str = g_strconcat(tmp_str1, query_per_account, NULL);
+                               else
+                                       result_str = g_strdup(query_per_account);
+                               EM_SAFE_FREE(tmp_str1);
+                       }
+
+                       snprintf(result_rule_string, QUERY_SIZE,
+                                       " CASE WHEN %s THEN 1 ELSE 2 END ", result_str);
+
+                       EM_SAFE_FREE(result_str);
+                       if (account_tbl_array)
+                               emstorage_free_account(&account_tbl_array, count, NULL);
+                       break;
+
                default :
                        EM_DEBUG_EXCEPTION("Invalid sort_order [%d]", input_sorting_rule->sort_order);
                        ret = EMAIL_ERROR_INVALID_PARAM;
@@ -14710,17 +15294,22 @@ INTERNAL_FUNC int emstorage_write_conditional_clause_for_getting_mail_list(email
                for ( i = 0; i < input_filter_count; i++) {
                        switch (input_filter_list[i].list_filter_item_type) {
                        case EMAIL_LIST_FILTER_ITEM_RULE :
-                               EM_DEBUG_LOG("[%d]list_filter_item_type is EMAIL_LIST_FILTER_ITEM_RULE", i);
+                               EM_DEBUG_LOG_DEV("[%d]list_filter_item_type is EMAIL_LIST_FILTER_ITEM_RULE", i);
                                _make_filter_rule_string(&(input_filter_list[i].list_filter_item.rule), &result_string_for_a_item);
                                break;
 
                        case EMAIL_LIST_FILTER_ITEM_RULE_FTS :
-                               EM_DEBUG_LOG("[%d]list_filter_item_type is EMAIL_LIST_FILTER_ITEM_RULE_FTS", i);
+                               EM_DEBUG_LOG_DEV("[%d]list_filter_item_type is EMAIL_LIST_FILTER_ITEM_RULE_FTS", i);
                                _make_filter_fts_rule_string(&(input_filter_list[i].list_filter_item.rule_fts), &result_string_for_a_item);
                                break;
 
+                       case EMAIL_LIST_FILTER_ITEM_RULE_ATTACH :
+                               EM_DEBUG_LOG_DEV("[%d]list_filter_item_type is EMAIL_LIST_FILTER_ITEM_RULE_ATTACH", i);
+                               _make_filter_attach_rule_string(&(input_filter_list[i].list_filter_item.rule_attach), &result_string_for_a_item);
+                               break;
+
                        case EMAIL_LIST_FILTER_ITEM_OPERATOR :
-                               EM_DEBUG_LOG("[%d]list_filter_item_type is EMAIL_LIST_FILTER_ITEM_OPERATOR", i);
+                               EM_DEBUG_LOG_DEV("[%d]list_filter_item_type is EMAIL_LIST_FILTER_ITEM_OPERATOR", i);
                                switch(input_filter_list[i].list_filter_item.operator_type) {
                                case EMAIL_LIST_FILTER_OPERATOR_AND :
                                        result_string_for_a_item = strdup("AND ");
@@ -14821,8 +15410,7 @@ INTERNAL_FUNC int emstorage_free_list_filter(email_list_filter_t **input_filter_
                }
        }
 
-       free(*input_filter_list);
-       *input_filter_list = NULL;
+       EM_SAFE_FREE (*input_filter_list);
 
        EM_DEBUG_FUNC_END("err [%d]", err);
        return err;
@@ -14834,9 +15422,8 @@ INTERNAL_FUNC int emstorage_add_certificate(emstorage_certificate_tbl_t *certifi
 
        if (!certificate) {
                EM_DEBUG_EXCEPTION("certificate:[%p], transaction:[%d], err_code:[%p]", certificate, transaction, err_code);
-               if (err_code != NULL)
+               if (err_code)
                        *err_code = EMAIL_ERROR_INVALID_PARAM;
-
                return false;
        }
 
@@ -14914,20 +15501,17 @@ INTERNAL_FUNC int emstorage_add_certificate(emstorage_certificate_tbl_t *certifi
                ("sqlite3_step fail:%d, errmsg = %s.", rc, sqlite3_errmsg(local_db_handle)));
 #ifdef __FEATURE_SUPPORT_PRIVATE_CERTIFICATE__
        if (ssm_write_buffer(certificate->password, EM_SAFE_STRLEN(certificate->password), cert_password_file_name, SSM_FLAG_SECRET_OPERATION, NULL) < 0) {
-               EM_DEBUG_EXCEPTION("ssm_write_buffer failed - Private certificate password : [%s]", cert_password_file_name);
+               EM_DEBUG_EXCEPTION_SEC("ssm_write_buffer failed - Private certificate password : [%s]", cert_password_file_name);
                error = EMAIL_ERROR_SYSTEM_FAILURE;
                goto FINISH_OFF;
        }
 #endif
        ret = true;
 
-       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
-
-       if (!emcore_notify_storage_event(NOTI_CERTIFICATE_ADD, certificate->certificate_id, 0, NULL, 0))
-               EM_DEBUG_EXCEPTION("emcore_notify_storage_event(NOTI_CERTIFICATE_ADD] : Notification failed");
 
 FINISH_OFF:
-
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
        if (hStmt != NULL)  {
                rc = sqlite3_finalize(hStmt);
                if (rc != SQLITE_OK)  {
@@ -14935,11 +15519,11 @@ FINISH_OFF:
                        error = EMAIL_ERROR_DB_FAILURE;
                }
        }
-       else
-               EM_DEBUG_LOG("hStmt is NULL!!!");
 
-       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
-       _DISCONNECT_DB;
+       if (error == EMAIL_ERROR_NONE) {
+               if (!emcore_notify_storage_event (NOTI_CERTIFICATE_ADD, certificate->certificate_id, 0, NULL, 0))
+                       EM_DEBUG_EXCEPTION ("emcore_notify_storage_event(NOTI_CERTIFICATE_ADD] : Notification failed");
+       }
 
        if (err_code != NULL)
                *err_code = error;
@@ -15085,7 +15669,7 @@ INTERNAL_FUNC int emstorage_get_certificate_list(int *select_num, emstorage_cert
                                EM_DEBUG_EXCEPTION("_read_password_from_secure_storage() failed...");
                                goto FINISH_OFF;
                        }
-                       EM_DEBUG_LOG("recv_password_file_name[%s], password[%s]", cert_password_file_name,  p_data_tbl[i].password);
+                       EM_DEBUG_LOG_SEC("recv_password_file_name[%s], password[%s]", cert_password_file_name,  p_data_tbl[i].password);
 #endif
                }
 
@@ -15129,10 +15713,10 @@ FINISH_OFF:
 
 INTERNAL_FUNC int emstorage_get_certificate_by_email_address(char *email_address, emstorage_certificate_tbl_t **certificate, int transaction, int with_password, int *err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("email_address[%s], certificate[%p], transaction[%d], err_code[%p]", email_address, certificate, transaction, err_code);
+       EM_DEBUG_FUNC_BEGIN_SEC("email_address[%s], certificate[%p], transaction[%d], err_code[%p]", email_address, certificate, transaction, err_code);
 
        if (!certificate)  {
-               EM_DEBUG_EXCEPTION("email_address[%s], certificate[%p]", email_address, certificate);
+               EM_DEBUG_EXCEPTION_SEC("email_address[%s], certificate[%p]", email_address, certificate);
                if (err_code != NULL)
                        *err_code = EMAIL_ERROR_INVALID_PARAM;
                return false;
@@ -15209,7 +15793,7 @@ INTERNAL_FUNC int emstorage_get_certificate_by_email_address(char *email_address
                        EM_DEBUG_EXCEPTION(" _read_password_from_secure_storage()  failed...");
                        goto FINISH_OFF;
                }
-               EM_DEBUG_LOG("cert_password_file_name[%s], password[%s]", cert_password_file_name,  p_data_tbl->password);
+               EM_DEBUG_LOG_SEC("cert_password_file_name[%s], password[%s]", cert_password_file_name,  p_data_tbl->password);
 #endif
        }
        ret = true;
@@ -15319,7 +15903,7 @@ INTERNAL_FUNC int emstorage_get_certificate_by_index(int index, emstorage_certif
                        EM_DEBUG_EXCEPTION(" _read_password_from_secure_storage()  failed...");
                        goto FINISH_OFF;
                }
-               EM_DEBUG_LOG("cert_password_file_name[%s], password[%s]", cert_password_file_name,  p_data_tbl->password);
+               EM_DEBUG_LOG_SEC("cert_password_file_name[%s], password[%s]", cert_password_file_name,  p_data_tbl->password);
 #endif
        }
        ret = true;
@@ -15352,8 +15936,7 @@ INTERNAL_FUNC int emstorage_delete_certificate(int certificate_id, int transacti
 
        if (certificate_id < 1)  {
                EM_DEBUG_EXCEPTION(" certificate_id[%d]", certificate_id);
-
-               if (err_code != NULL)
+               if (err_code)
                        *err_code = EMAIL_ERROR_INVALID_PARAM;
                return false;
        }
@@ -15394,7 +15977,7 @@ INTERNAL_FUNC int emstorage_delete_certificate(int certificate_id, int transacti
 #ifdef __FEATURE_SUPPORT_PRIVATE_CERTIFICATE__
        /*  delete from secure storage */
        if (ssm_delete_file(cert_password_file_name,  SSM_FLAG_SECRET_OPERATION, NULL) < 0) {
-               EM_DEBUG_EXCEPTION(" ssm_delete_file failed -cert password : file[%s]", cert_password_file_name);
+               EM_DEBUG_EXCEPTION_SEC(" ssm_delete_file failed -cert password : file[%s]", cert_password_file_name);
                error = EMAIL_ERROR_SYSTEM_FAILURE;
                goto FINISH_OFF;
        }
@@ -15402,6 +15985,8 @@ INTERNAL_FUNC int emstorage_delete_certificate(int certificate_id, int transacti
        ret = true;
 
 FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
 
        if (hStmt != NULL)  {
                rc = sqlite3_finalize(hStmt);
@@ -15411,9 +15996,6 @@ FINISH_OFF:
                }
        }
 
-       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
-       _DISCONNECT_DB;
-
        if (err_code != NULL)
                *err_code = error;
 
@@ -15427,8 +16009,7 @@ INTERNAL_FUNC int emstorage_update_certificate(int certificate_id, emstorage_cer
 
        if (certificate_id < 1)  {
                EM_DEBUG_EXCEPTION(" certificate_id[%d]", certificate_id);
-
-               if (err_code != NULL)
+               if (err_code)
                        *err_code = EMAIL_ERROR_INVALID_PARAM;
                return false;
        }
@@ -15500,17 +16081,17 @@ INTERNAL_FUNC int emstorage_update_certificate(int certificate_id, emstorage_cer
 
        /*  save passwords to the secure storage */
        if (ssm_write_buffer(certificate->password, EM_SAFE_STRLEN(certificate->password), cert_password_file_name, SSM_FLAG_SECRET_OPERATION, NULL) < 0) {
-               EM_DEBUG_EXCEPTION("ssm_write_buffer failed - Private certificate password : [%s]", cert_password_file_name);
+               EM_DEBUG_EXCEPTION_SEC("ssm_write_buffer failed - Private certificate password : [%s]", cert_password_file_name);
                error = EMAIL_ERROR_SYSTEM_FAILURE;
                goto FINISH_OFF;
        }
 #endif
-       if (!emcore_notify_storage_event(NOTI_CERTIFICATE_UPDATE, certificate->certificate_id, 0, NULL, 0))
-               EM_DEBUG_EXCEPTION(" emcore_notify_storage_event[ NOTI_CERTIFICATE_UPDATE] : Notification Failed >>> ");
 
        ret = true;
 
 FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
 
        if (hStmt != NULL)  {
                EM_DEBUG_LOG(" Before sqlite3_finalize hStmt = %p", hStmt);
@@ -15522,9 +16103,10 @@ FINISH_OFF:
                }
        }
 
-       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
-
-       _DISCONNECT_DB;
+       if (error == EMAIL_ERROR_NONE) {
+               if (!emcore_notify_storage_event (NOTI_CERTIFICATE_UPDATE, certificate->certificate_id, 0, NULL, 0))
+                       EM_DEBUG_EXCEPTION ("emcore_notify_storage_event[ NOTI_CERTIFICATE_UPDATE] : Notification Failed >>> ");
+       }
 
        if (err_code != NULL)
                *err_code = error;
@@ -15550,12 +16132,10 @@ INTERNAL_FUNC int emstorage_add_task(email_task_type_t input_task_type, email_ta
 
        if (input_task_parameter == NULL || output_task_id == NULL)  {
                EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
-               err = EMAIL_ERROR_INVALID_PARAM;
-               goto FINISH_OFF;
+               return EMAIL_ERROR_INVALID_PARAM;
        }
 
        local_db_handle = emstorage_get_db_connection();
-
        EMSTORAGE_START_WRITE_TRANSACTION(input_transaction, err);
 
        EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql, &result, NULL, NULL, NULL), rc);
@@ -15607,9 +16187,10 @@ INTERNAL_FUNC int emstorage_add_task(email_task_type_t input_task_type, email_ta
                ("sqlite3_step fail:%d, errmsg = %s.", rc, sqlite3_errmsg(local_db_handle)));
 
        ret = (err == EMAIL_ERROR_NONE);
-       EMSTORAGE_FINISH_WRITE_TRANSACTION(input_transaction, ret, err);
 
 FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(input_transaction, ret, err);
+       _DISCONNECT_DB;
 
        if (hStmt != NULL)  {
                rc = sqlite3_finalize(hStmt);
@@ -15618,10 +16199,6 @@ FINISH_OFF:
                        err = EMAIL_ERROR_DB_FAILURE;
                }
        }
-       else
-               EM_DEBUG_LOG("hStmt is NULL!!!");
-
-       _DISCONNECT_DB;
 
        EM_DEBUG_FUNC_END("err [%d]", err);
        return err;
@@ -15637,8 +16214,7 @@ INTERNAL_FUNC int emstorage_delete_task(int task_id, int transaction)
 
        if (task_id < 0)  {
                EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
-               err = EMAIL_ERROR_INVALID_PARAM;
-               goto FINISH_OFF;
+               return EMAIL_ERROR_INVALID_PARAM;
        }
 
        local_db_handle = emstorage_get_db_connection();
@@ -15669,7 +16245,6 @@ INTERNAL_FUNC int emstorage_update_task_status(int task_id, email_task_status_ty
        char sql_query_string[QUERY_SIZE] = {0, };
 
        sqlite3 *local_db_handle = emstorage_get_db_connection();
-
        EMSTORAGE_START_WRITE_TRANSACTION(transaction, err);
 
        SNPRINTF(sql_query_string, sizeof(sql_query_string),
@@ -15797,6 +16372,88 @@ FINISH_OFF:
        EM_DEBUG_FUNC_END("err [%d]", err);
        return err;
 }
+
+INTERNAL_FUNC int emstorage_check_and_update_server_uid_by_message_id(int account_id, email_mailbox_type_e input_mailbox_type, char *message_id, char *server_uid, int *mail_id)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id:[%d], mailbox_type:[%d], message_id:[%s], server_uid:[%s]", account_id, input_mailbox_type, message_id, server_uid);
+       int err = EMAIL_ERROR_NONE;
+
+       if (message_id == NULL) {
+               EM_DEBUG_EXCEPTION("Invalid parameter");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               return err;
+       }
+
+       int rc = -1;
+       int count = 0;
+       int temp_mail_id = 0;
+       int where_pararaph_length = 0;
+       char *where_pararaph = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+       char **result = NULL;
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT mail_id from mail_tbl ");
+
+       where_pararaph_length = EM_SAFE_STRLEN(message_id) + 100;
+       where_pararaph = em_malloc(sizeof(char) * where_pararaph_length);
+       if (where_pararaph == NULL) {
+               EM_DEBUG_EXCEPTION("em_malloc failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       if (account_id != ALL_ACCOUNT)
+               sqlite3_snprintf(where_pararaph_length, where_pararaph, "WHERE account_id = %d AND mailbox_type = %d AND message_id like '%q'", account_id, input_mailbox_type, message_id);
+       else
+               sqlite3_snprintf(where_pararaph_length, where_pararaph, "WHERE mailbox_type = %d AND message_id like '%q'", input_mailbox_type, message_id);
+
+       if (strlen(sql_query_string) + strlen(where_pararaph) < QUERY_SIZE)
+               strcat(sql_query_string, where_pararaph);
+
+       EM_DEBUG_LOG("query[%s]", sql_query_string);
+
+        EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql_query_string, &result, &count, 0, NULL), rc);
+        EM_DEBUG_DB_EXEC((SQLITE_OK != rc && -1 != rc), {err = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+                ("SQL(%s) sqlite3_get_table fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+
+        EM_DEBUG_LOG("Count of mails [%d]", count);
+
+       if (count) {
+               _get_table_field_data_int(result, &temp_mail_id, 1);
+               EM_DEBUG_LOG("Searched mail_id [%d]", temp_mail_id);
+
+               memset(sql_query_string, 0x00, QUERY_SIZE);
+               sqlite3_snprintf(sizeof(sql_query_string), sql_query_string, "UPDATE mail_tbl set server_mail_id = '%q'", server_uid);
+
+                if(strlen(sql_query_string) + strlen(where_pararaph) < QUERY_SIZE)
+                        strcat(sql_query_string, where_pararaph);
+
+                EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+                EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {err = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                        ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       } else {
+               err = EMAIL_ERROR_MAIL_NOT_FOUND;
+       }
+
+FINISH_OFF:
+
+       sqlite3_free_table(result);
+       result = NULL;
+
+       _DISCONNECT_DB;
+
+       EM_SAFE_FREE(where_pararaph);
+
+       if (mail_id != NULL)
+               *mail_id = temp_mail_id;
+
+       EM_DEBUG_FUNC_END("err : [%d]", err);
+       return err;
+}
 /* Tasks --------------------------------------------------------------------------*/
 
 /*EOF*/
index 1927679..7b4b313 100755 (executable)
@@ -70,7 +70,7 @@ typedef struct
        int                                sync_status;                              /* Sync Status. SYNC_STATUS_FINISHED, SYNC_STATUS_SYNCING, SYNC_STATUS_HAVE_NEW_MAILS */
        int                                sync_disabled;                            /* If this attriube is set as true, email-service will not synchronize this account. */
        int                                default_mail_slot_size;
-
+       email_roaming_option_t             roaming_option;                           /* roaming option */
        void                              *user_data;                                /* binary user data */
        int                                user_data_length;                         /* user data length */
 
@@ -93,6 +93,10 @@ typedef struct
        int                                keep_mails_on_pop_server_after_download;  /* Keep mails on POP server after download */
        int                                check_interval;                           /* Specifies the interval for checking new mail periodically */
        int                                auto_download_size;                       /* Specifies the size for auto download in bytes. -1 means entire mails body */
+       int                                peak_interval;                            /* Specifies the interval for checking new mail periodically of peak schedule */
+       int                                peak_days;                                /* Specifies the weekdays of peak schedule */
+       int                                peak_start_time;                          /* Specifies the start time of peak schedule */
+       int                                peak_end_time;                            /* Specifies the end time of peak schedule */
 
        /* Configuration for outgoing server */
        email_account_server_t             outgoing_server_type;
@@ -102,14 +106,17 @@ typedef struct
        char                              *outgoing_server_password;
        int                                outgoing_server_secure_connection;        /* Does outgoing server requires secured connection? */
        int                                outgoing_server_need_authentication;      /* Does outgoing server requires authentication? */
-       int                                outgoing_server_use_same_authenticator;   /* Use same authenticator for outgoing server */ /* flag2 */
+       int                                outgoing_server_use_same_authenticator;   /* Use same authenticator for outgoing server */
 
        /* Options for outgoing server */
        email_option_t                     options;
+       int                                auto_resend_times;                        /* Auto retry count for sending a email */
+       int                                outgoing_server_size_limit;               /* Mail size limitation for SMTP sending*/
 
        /* Authentication Options */
        int                                pop_before_smtp;                          /* POP before SMTP Authentication */
        int                                incoming_server_requires_apop;            /* APOP authentication */
+       email_authentication_method_t      incoming_server_authentication_method;                    /* authentication method */
 
        /* S/MIME Options */
        email_smime_type                   smime_type;                               /* Sepeifies the smime type 0=Normal 1=Clear signed 2=encrypted 3=Signed + encrypted */
@@ -138,8 +145,10 @@ typedef struct
 {
        int   account_id;      /*  MUST BE '0'  :  currently, only global rule supported. */
        int   rule_id;
+       char *filter_name;
        int   type;            /*  from/subject/body  */
        char *value;
+       char *value2;           /* from address */
        int   action_type;     /*  move/block/delete  */
        int   target_mailbox_id;    /*  destination mailbox  */
        int   flag1;           /*  for rule ON/OFF */
@@ -164,6 +173,8 @@ typedef struct
        int                   no_select;
        time_t                last_sync_time;             /*  The last synchronization time */
        int                   deleted_flag;               /*  whether mailbox is deleted */
+       int                   eas_data_length;            /*  Specifies the length of eas_data. */
+       char                  *eas_data;                  /*  Specifies the data for eas engine. */
 } emstorage_mailbox_tbl_t;
 
 /* mail_read_uid_tbl table entity */
@@ -171,13 +182,13 @@ typedef struct
 {
        int     account_id;
        int     mailbox_id;
+       char   *mailbox_name;     /* server mailbox */
        int     local_uid;
-       char   *mailbox_name;   /*  server mailbox */
-       char   *s_uid;          /*  uid on server */
-       int     data1;          /*  rfc822 size */
-       char   *data2;
-       int     flag;           /*  rule id */
-       int     reserved;
+       char   *server_uid;       /* uid on server */
+       int     rfc822_size;      /* rfc822 size */
+       int     sync_status;
+       char    flags_seen_field; /* SEEN flag */
+       char    flags_flagged_field; /* Favorite flag */
 } emstorage_read_mail_uid_tbl_t;
 
 #ifdef __FEATURE_BODY_SEARCH__
@@ -240,6 +251,10 @@ typedef struct
        email_digest_type      digest_type;
        email_smime_type       smime_type;
        time_t                 scheduled_sending_time;
+       int                    remaining_resend_times;
+       int                    tag_id;
+       time_t                 replied_time;
+       time_t                 forwarded_time;
        int                    eas_data_length;
        char                  *eas_data;
 } emstorage_mail_tbl_t;
@@ -384,6 +399,8 @@ INTERNAL_FUNC int emstorage_close(int *err_code);
 INTERNAL_FUNC int emstorage_create_table(emstorage_create_db_type_t type, int *err_code);
 
 
+INTERNAL_FUNC int emstorage_initialize_field_count();
+
 /**
  * Check whether there is the same account information in the db
  *
@@ -445,7 +462,9 @@ INTERNAL_FUNC int emstorage_get_account_by_id(int account_id, int pulloption, em
  * return :
  */
 
-INTERNAL_FUNC int emstorage_get_password_length_of_account(int account_id, int *password_length, int* err_code);
+INTERNAL_FUNC int emstorage_get_password_length_of_account(int account_id, int password_type, int *password_length, int* err_code);
+
+INTERNAL_FUNC int emstorage_update_account_password(int input_account_id, char *input_incoming_server_password, char *input_outgoing_server_password);
 
 /*
  * emstorage_update_account
@@ -576,6 +595,7 @@ INTERNAL_FUNC int emstorage_get_child_mailbox_list(int account_id, char *parent_
 INTERNAL_FUNC int emstorage_get_mailbox_by_name(int account_id, int local_yn, char *mailbox_name, emstorage_mailbox_tbl_t **mailbox, int transaction, int *err_code);
 INTERNAL_FUNC int emstorage_get_mailbox_by_mailbox_type(int account_id, email_mailbox_type_e mailbox_type, emstorage_mailbox_tbl_t **mailbox, int transaction, int *err_code);
 INTERNAL_FUNC int emstorage_get_mailbox_by_id(int input_mailbox_id, emstorage_mailbox_tbl_t** output_mailbox);
+INTERNAL_FUNC int emstorage_get_mailbox_by_keyword(int account_id, char *keyword, emstorage_mailbox_tbl_t** result_mailbox, int * result_count, int transaction, int *err_code);
 INTERNAL_FUNC int emstorage_get_mailbox_list_ex(int account_id, int local_yn, int with_count, int *select_num, emstorage_mailbox_tbl_t **mailbox_list, int transaction, int *err_code);
 INTERNAL_FUNC int emstorage_get_mailbox_id_by_mailbox_type(int account_id, email_mailbox_type_e mailbox_type, int *mailbox_id, int transaction, int *err_code);
 INTERNAL_FUNC int emstorage_get_mailbox_name_by_mailbox_type(int account_id, email_mailbox_type_e mailbox_type, char **mailbox_name, int transaction, int *err_code);
@@ -602,7 +622,7 @@ INTERNAL_FUNC int emstorage_update_mailbox(int account_id, int local_yn, int inp
  * arguments : 
  * return  : 
  */
-INTERNAL_FUNC int emstorage_update_mailbox_type(int account_id, int local_yn, char *mailbox_name, email_mailbox_type_e new_mailbox_type, int transaction, int *err_code);
+INTERNAL_FUNC int emstorage_update_mailbox_type(int account_id, int local_yn, int input_mailbox_id, email_mailbox_type_e new_mailbox_type, int transaction, int *err_code);
 
 /*
  * emstorage_set_local_mailbox
@@ -635,7 +655,7 @@ INTERNAL_FUNC int emstorage_add_mailbox(emstorage_mailbox_tbl_t *mailbox, int tr
  */
 INTERNAL_FUNC int emstorage_delete_mailbox(int account_id, int local_yn, int input_mailbox_id, int transaction, int *err_code);
 
-INTERNAL_FUNC int emstorage_rename_mailbox(int input_mailbox_id, char *input_new_mailbox_path, char *input_new_mailbox_alias, int input_transaction);
+INTERNAL_FUNC int emstorage_rename_mailbox(int input_mailbox_id, char *input_new_mailbox_name, char *input_new_mailbox_alias, void *input_eas_data, int input_eas_data_length, int input_transaction);
 INTERNAL_FUNC int emstorage_get_overflowed_mail_id_list(int account_id, int input_mailbox_id, int mail_slot_size, int **mail_id_list, int *mail_id_count, int transaction, int *err_code);
 INTERNAL_FUNC int emstorage_set_mail_slot_size(int account_id, int mailbox_id, int new_slot_size, int transaction, int *err_code);
 
@@ -669,7 +689,7 @@ INTERNAL_FUNC int emstorage_get_count_read_mail_uid(int account_id, char *mailbo
  * arguments : 
  *    db  :  database pointer
  *    mailbox_name  :  mailbox name
- *    s_uid  :  uid string to be checked
+ *    uid  :  uid string to be checked
  *    exist  :  variable to hold checking result. (0 : not exist, 1 : exist)
  * return  : 
  */
@@ -1162,7 +1182,7 @@ INTERNAL_FUNC int emstorage_free_mail(emstorage_mail_tbl_t **mail_list, int coun
  *    count  :  the number of array element
  * return  :
  */
-INTERNAL_FUNC int emstorage_free_mail_text(emstorage_mail_text_tbl_t** mail_text_list, int count, int *err_code);
+INTERNAL_FUNC void emstorage_free_mail_text(emstorage_mail_text_tbl_t** mail_text_list, int count, int *err_code);
 #endif
 
 /*
@@ -1481,7 +1501,7 @@ INTERNAL_FUNC int emstorage_update_read_mail_uid_by_server_uid(char *old_server_
  * @param[out] id_set_count            Returns the no. of cells in idset array i.e. no. of sets of mail_ids and server_mail_ids
  * @param[out] err_code                Returns the error code.
  * @remarks                                    An Example of Query to be exexuted in this API : 
- *                                                     SELECT local_uid, s_uid from mail_read_mail_uid_tbl where local_uid in (12, 13, 56, 78);
+ *                                                     SELECT local_uid, server_uid from mail_read_mail_uid_tbl where local_uid in (12, 13, 56, 78);
  * @return This function returns true on success or false on failure.
  */
 
@@ -1490,13 +1510,14 @@ INTERNAL_FUNC int emstorage_get_id_set_from_mail_ids(char *mail_ids, email_id_se
 #endif
 
 /**
- * @fn emstorage_filter_mails_by_rule(int account_id, int dest_mailbox_id, int dst_mailbox_type, email_rule_t *rule, int **filtered_mail_id_list, int *count_of_mails, int err_code)
+ * @fn emstorage_filter_mails_by_rule(int account_id, int dest_mailbox_id, int dst_mailbox_type, int reset, email_rule_t *rule, int **filtered_mail_id_list, int *count_of_mails, int err_code)
  * Move mails by specified rule for spam filtering. 
  *
  * @author                                                             kyuho.jo@samsung.com
  * @param[in] account_id                               Account id of the mails and the mailboxes.
  * @param[in] dest_mailbox_id                  Mailbox id of spam mailbox.
  * @param[in] dest_mailbox_type                        Mailbox id of spam mailbox.
+ * @param[in] reset                            Tag id reset which when deleting the rule 
  * @param[in] rule                                             Filtering rule.
  * @param[out] filtered_mail_id_list   Mail id list which are filtered by the rule.
  * @param[out] count_of_mails                  Count of mails which are filtered by the rule.
@@ -1505,9 +1526,11 @@ INTERNAL_FUNC int emstorage_get_id_set_from_mail_ids(char *mail_ids, email_id_se
  * @remarks                                                                    
  * @return This function returns true on success or false on failure.
  */
-INTERNAL_FUNC int emstorage_filter_mails_by_rule(int account_id, int dest_mailbox_id, int dest_mailbox_type, emstorage_rule_tbl_t *rule, int **filtered_mail_id_list, int *count_of_mails, int *err_code);
+INTERNAL_FUNC int emstorage_filter_mails_by_rule(int account_id, int dest_mailbox_id, int dest_mailbox_type, int reset, emstorage_rule_tbl_t *rule, int **filtered_mail_id_list, int *count_of_mails, int *err_code);
 
+INTERNAL_FUNC int emstorage_update_tag_id(int old_filter_id, int new_filter_id, int *err_code);
 INTERNAL_FUNC int emstorage_add_meeting_request(int account_id, int input_mailbox_id, email_meeting_request_t *meeting_req, int transaction, int *err_code);
+INTERNAL_FUNC int emstorage_query_meeting_request(const char *conditional_clause, email_meeting_request_t **output_meeting_req, int *output_result_count, int transaction);
 INTERNAL_FUNC int emstorage_get_meeting_request(int mail_id, email_meeting_request_t **meeting_req, int transaction, int *err_code);
 INTERNAL_FUNC int emstorage_update_meeting_request(email_meeting_request_t *meeting_req, int transaction, int *err_code);
 INTERNAL_FUNC int emstorage_delete_meeting_request(int account_id, int mail_id, int input_mailbox_id, int transaction, int *err_code);
@@ -1592,6 +1615,8 @@ INTERNAL_FUNC int emstorage_update_task_status(int task_id, email_task_status_ty
 INTERNAL_FUNC int emstorage_query_task(const char *input_conditional_clause, const char *input_ordering_clause, email_task_t **output_task_list, int *output_task_count);
 /* task end*/
 
+INTERNAL_FUNC int emstorage_check_and_update_server_uid_by_message_id(int account_id, email_mailbox_type_e input_mailbox_type, char *message_id, char *server_uid, int *searched_mail_id);
+
 #ifdef __cplusplus
 }
 #endif /* __cplusplus */
index 024260a..748bfc6 100755 (executable)
@@ -42,7 +42,7 @@ extern "C"
 
 INTERNAL_FUNC int emcore_validate_account(int account_id, int *err_code);
 
-INTERNAL_FUNC int emcore_validate_account_with_account_info(email_account_t *account, int *err_code);
+INTERNAL_FUNC int emcore_validate_account_with_account_info(email_account_t *account, email_event_type_t event_type, int *err_code);
 
 INTERNAL_FUNC int emcore_create_account(email_account_t *account, int *err_code);
 
@@ -76,6 +76,8 @@ INTERNAL_FUNC int emcore_recover_from_secured_storage_failure();
 
 INTERNAL_FUNC int emcore_update_sync_status_of_account(int input_account_id, email_set_type_t input_set_operator, int input_sync_status);
 
+INTERNAL_FUNC int emcore_refresh_xoauth2_access_token(int input_account_id);
+
 
 #ifdef __FEATURE_BACKUP_ACCOUNT__
 INTERNAL_FUNC int emcore_backup_accounts(const char *file_path, int *error_code);
index 081594d..25f747d 100755 (executable)
@@ -39,24 +39,26 @@ extern "C"
 {\r
 #endif /* __cplusplus */\r
 \r
+#define EMAIL_ALARM_DESTINATION "email-service-0"\r
+\r
 typedef struct _email_alarm_data_t {\r
        alarm_id_t                  alarm_id;\r
-       int                         class_id;\r
+       email_alarm_class_t           class_id;\r
        int                         reference_id;\r
        time_t                      trigger_at_time;\r
        int                       (*alarm_callback)(int, void *);\r
        void                       *user_data;\r
 } email_alarm_data_t;\r
 \r
-INTERNAL_FUNC int emcore_init_alarm_data_list();\r
 \r
-INTERNAL_FUNC int emcore_add_alarm(time_t input_trigger_at_time, int input_class_id, int input_reference_id, int (*input_alarm_callback)(int, void *), void *input_user_data);\r
+INTERNAL_FUNC int emcore_add_alarm(time_t input_trigger_at_time, email_alarm_class_t input_class_id, int input_reference_id, int (*input_alarm_callback)(int, void *), void *input_user_data);\r
 \r
 INTERNAL_FUNC int emcore_delete_alram_data_from_alarm_data_list(email_alarm_data_t *input_alarm_data);\r
-INTERNAL_FUNC int emcore_delete_alram_data_by_reference_id(int input_class_id, int input_reference_id);\r
+INTERNAL_FUNC int emcore_delete_alram_data_by_reference_id(email_alarm_class_t input_class_id, int input_reference_id);\r
 \r
 INTERNAL_FUNC int emcore_get_alarm_data_by_alarm_id(alarm_id_t input_alarm_id, email_alarm_data_t **output_alarm_data);\r
-INTERNAL_FUNC int emcore_get_alarm_data_by_reference_id(int input_class_id, int input_reference_id, email_alarm_data_t **output_alarm_data);\r
+INTERNAL_FUNC int emcore_get_alarm_data_by_reference_id(email_alarm_class_t input_class_id, int input_reference_id, email_alarm_data_t **output_alarm_data);\r
+INTERNAL_FUNC int emcore_check_alarm_by_class_id(email_alarm_class_t input_class_id);\r
 \r
 #ifdef __cplusplus\r
 }\r
diff --git a/email-core/include/email-core-api.h b/email-core/include/email-core-api.h
deleted file mode 100755 (executable)
index 9605a72..0000000
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
-*  email-service
-*
-* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
-* 
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*
-*/
-
-
-/******************************************************************************
- * File :  email-core-api.h
- * Desc :  email-core-api Header
- *
- * Auth : 
- *
- * History : 
- *    2006.08.16  :  created
- *****************************************************************************/
-#ifndef __EMAIL_CORE_API_H__
-#define __EMAIL_CORE_API_H__
-
-#ifdef __cplusplus
-extern "C"
-{
-#endif /* __cplusplus */
-
-int emcore_init(int *err_code);
-
-#ifdef __cplusplus
-}
-#endif /* __cplusplus */
-
-#endif /*__EMAIL_CORE_API_H__*/
index 9f13ed4..3654c2f 100755 (executable)
@@ -40,21 +40,21 @@ extern "C"
 {
 #endif /* __cplusplus */
 
+#define TOTAL_PARTIAL_BODY_EVENTS 100
+
 void emcore_execute_event_callback(email_action_t action, int total, int done, int status, int account_id, int mail_id, int handle, int error);
-int  emcore_get_active_queue_idx(void);
-int  emcore_check_send_mail_thread_status();
 
-INTERNAL_FUNC int          emcore_get_current_thread_type();
 INTERNAL_FUNC int          emcore_register_event_callback(email_action_t action, email_event_callback callback, void *event_data);
 INTERNAL_FUNC int          emcore_unregister_event_callback(email_action_t action, email_event_callback callback);
-INTERNAL_FUNC int          emcore_start_event_loop(int *err_code);
 INTERNAL_FUNC int          emcore_stop_event_loop(int *err_code);
 INTERNAL_FUNC int          emcore_insert_event(email_event_t *event_data, int *handle, int *err_code);
 INTERNAL_FUNC int          emcore_cancel_thread(int handle, void *arg, int *err_code);
-INTERNAL_FUNC int          emcore_start_event_loop_for_sending_mails(int *err_code);
+INTERNAL_FUNC int          emcore_cancel_all_thread(int *err_code);
 INTERNAL_FUNC int          emcore_send_event_loop_stop(int *err_code);
 INTERNAL_FUNC int          emcore_cancel_send_mail_thread(int handle, void *arg, int *err_code);
+INTERNAL_FUNC int          emcore_cancel_all_send_mail_thread(int *err_code);
 INTERNAL_FUNC int          emcore_check_thread_status(void);
+INTERNAL_FUNC int          emcore_check_send_mail_thread_status(void);
 INTERNAL_FUNC void         emcore_get_event_queue_status(int *on_sending, int *on_receiving);
 INTERNAL_FUNC int          emcore_insert_event_for_sending_mails(email_event_t *event_data, int *handle, int *err_code);
 INTERNAL_FUNC int          emcore_get_receiving_event_queue(email_event_t **event_queue, int *event_count, int *err);
@@ -62,12 +62,24 @@ INTERNAL_FUNC int          emcore_cancel_all_threads_of_an_account(int account_i
 INTERNAL_FUNC int          emcore_free_event(email_event_t *event_data);
 INTERNAL_FUNC int          emcore_get_task_information(email_task_information_t **output_task_information, int *output_task_information_count);
 
+INTERNAL_FUNC void emcore_initialize_event_callback_table();
+INTERNAL_FUNC int emcore_event_loop_continue(void);
+INTERNAL_FUNC int emcore_retrieve_event(email_event_t **event_data, int *err_code);
+INTERNAL_FUNC int emcore_return_handle(int handle);
+INTERNAL_FUNC int emcore_retrieve_send_event(email_event_t **event_data, int *err_code);
+INTERNAL_FUNC int emcore_return_send_handle(int handle);
+INTERNAL_FUNC int emcore_retrieve_partial_body_thread_event(email_event_partial_body_thd *partial_body_thd_event, int *error_code);
+INTERNAL_FUNC int emcore_mail_partial_body_download(email_event_partial_body_thd *pbd_event, int *error_code);
+INTERNAL_FUNC void emcore_pb_thd_set_local_activity_continue(int flag);
+INTERNAL_FUNC int emcore_pb_thd_can_local_activity_continue();
+INTERNAL_FUNC int emcore_set_pbd_thd_state(int flag);
+
+
 #ifdef __FEATURE_PARTIAL_BODY_DOWNLOAD__
 /*  Please contact -> Himanshu [h.gahlaut@samsung.com] for any explanation in code here under this MACRO */
 INTERNAL_FUNC int          emcore_insert_partial_body_thread_event(email_event_partial_body_thd *partial_body_thd_event, int *error_code);
 INTERNAL_FUNC int          emcore_is_partial_body_thd_que_empty();
 INTERNAL_FUNC int          emcore_is_partial_body_thd_que_full();
-INTERNAL_FUNC int          emcore_start_thread_for_downloading_partial_body(int *err_code);
 INTERNAL_FUNC int          emcore_clear_partial_body_thd_event_que(int *err_code);
 INTERNAL_FUNC int          emcore_free_partial_body_thd_event(email_event_partial_body_thd *partial_body_thd_event, int *error_code);
 INTERNAL_FUNC unsigned int emcore_get_partial_body_thd_id();
index ce8b1a0..1c17bd4 100755 (executable)
@@ -39,7 +39,6 @@ extern "C"
 {
 #endif /* __cplusplus */
 
-INTERNAL_FUNC int emcore_check_sync_imap_mailbox(email_mailbox_t *mailbox, int *synchronous, int *err_code);
 /**
  * Get mailbox list from imap server.
  *
@@ -68,11 +67,17 @@ INTERNAL_FUNC int emcore_download_mailbox_list(void *mail_stream, char *mailbox,
 INTERNAL_FUNC int emcore_delete_imap_mailbox(int input_mailbox_id, int *err_code);
 INTERNAL_FUNC int emcore_create_imap_mailbox(email_mailbox_t *mailbox, int *err_code);
 INTERNAL_FUNC int emcore_rename_mailbox_on_imap_server(int input_account_id, int input_mailbox_id, char *input_old_mailbox_path, char *input_new_mailbox_path, int handle_to_be_published);
-INTERNAL_FUNC int emcore_set_sync_imap_mailbox(email_internal_mailbox_t *mailbox, int synchronous, int *err_code);
 INTERNAL_FUNC int emcore_set_mail_slot_size(int account_id, int mailbox_id, int new_slot_size, int *err_code);
 INTERNAL_FUNC int emcore_remove_overflowed_mails(emstorage_mailbox_tbl_t *intput_mailbox_tbl, int *err_code);  
 INTERNAL_FUNC int emcore_get_default_mail_slot_count(int input_account_id, int *output_count);
 
+#ifdef __FEATURE_IMAP_QUOTA__
+INTERNAL_FUNC int emcore_register_quota_callback();
+INTERNAL_FUNC int emcore_get_quota_root(int input_mailbox_id, email_quota_resource_t *output_list_of_resource_limits);
+INTERNAL_FUNC int emcore_get_quota(int input_mailbox_id, char *input_quota_root, email_quota_resource_t *output_list_of_resource_limits);
+INTERNAL_FUNC int emcore_set_quota(int input_mailbox_id, char *input_quota_root, email_quota_resource_t *input_list_of_resource_limits);
+#endif /* __FEATURE_IMAP_QUOTA__ */
+
 #ifdef __cplusplus
 }
 #endif /* __cplusplus */
index e7c0f47..5a48918 100755 (executable)
@@ -84,6 +84,7 @@ struct _m_content_info
                int   drm2;                 /*  0 : none 1 : FL 2 : CD 3 : SSD 4 : SD */
                char *attachment_mime_type; /*  attachment mime type */
                char *content_id;           /*  mime content id */
+               int   save_status;
 #ifdef __ATTACHMENT_OPTI__
                int   encoding;         /*  encoding  */
                char *section;          /*  section number */
@@ -124,8 +125,8 @@ INTERNAL_FUNC int emcore_download_body_multi_sections_bulk(void *mail_stream, in
  * @return This function returns true on success or false on failure.
  */
 INTERNAL_FUNC int emcore_download_attachment(int acconut_id, int mail_id, int nth, int *err_code);
-INTERNAL_FUNC int emcore_mail_add_attachment(int mail_id, email_attachment_data_t *attachment, int *err_code);        /* TODO : Remove duplicated function */
-INTERNAL_FUNC int emcore_mail_add_attachment_data(int input_mail_id, email_attachment_data_t *input_attachment_data); /* TODO : Remove duplicated function */
+INTERNAL_FUNC int emcore_add_attachment(int mail_id, email_attachment_data_t *attachment, int *err_code);        /* TODO : Remove duplicated function */
+INTERNAL_FUNC int emcore_add_attachment_data(int input_mail_id, email_attachment_data_t *input_attachment_data); /* TODO : Remove duplicated function */
 INTERNAL_FUNC int emcore_delete_mail_attachment(int attachment_id, int *err_code);
 INTERNAL_FUNC int emcore_get_attachment_info(int attachment_id, email_attachment_data_t **attachment, int *err_code);
 INTERNAL_FUNC int emcore_get_attachment_data_list(int input_mail_id, email_attachment_data_t **output_attachment_data, int *output_attachment_count);
@@ -216,5 +217,11 @@ INTERNAL_FUNC int   emcore_mail_filter_by_rule(email_rule_t *filter_info, int *e
 }
 #endif /* __cplusplus */
 
+
+#define        EMAIL_SIGNAL_FILE_DELETED       1
+#define        EMAIL_SIGNAL_DB_DELETED 2
+INTERNAL_FUNC int *emcore_init_pipe_for_del_account ();
+INTERNAL_FUNC void emcore_send_signal_for_del_account (int signal);
+
 #endif
 /* EOF */
index b70d6ef..de17e48 100755 (executable)
@@ -46,11 +46,12 @@ extern "C"
 #define IMAGE_DISPLAY_PARTIAL_BODY_COUNT 30
 typedef struct 
 {
-       char  image_file_name[100];
+       char  *image_file_name;
        char *text_image;
        char *content_id;
        int   dec_len;
        char *mime_type;
+       int   fully_downloaded;
 } email_image_data;
 
 typedef struct 
@@ -77,11 +78,11 @@ int pop3_mailbox_get_uids(MAILSTREAM *stream, emcore_uid_list** uid_list, int *e
 int imap4_mail_calc_rfc822_size(MAILSTREAM *stream, int msgno, int *size, int *err_code);
 int imap4_mailbox_get_uids(MAILSTREAM *stream, emcore_uid_list** uid_list, int *err_code);
 
-int emcore_check_rule(const char *input_full_address_from, const char *input_subject, emstorage_rule_tbl_t *rule, int rule_len, int *matched, int *err_code);
+int emcore_check_rule(const char *input_full_address_from, const char *input_subject, emstorage_rule_tbl_t *rule, int rule_len, int *priority_sender, int *blocked, int *err_code);
 
-int emcore_make_mail_tbl_data_from_envelope(MAILSTREAM *mail_stream, ENVELOPE *input_envelope, emcore_uid_list *input_uid_elem, emstorage_mail_tbl_t **output_mail_tbl_data,  int *err_code);
+INTERNAL_FUNC int emcore_make_mail_tbl_data_from_envelope(int account_id, MAILSTREAM *mail_stream, ENVELOPE *input_envelope, emcore_uid_list *input_uid_elem, emstorage_mail_tbl_t **output_mail_tbl_data,  int *err_code);
 
-int emcore_add_mail_to_mailbox(emstorage_mailbox_tbl_t *input_maibox_data, emstorage_mail_tbl_t *input_new_mail_tbl_data, int *output_mail_id, int *output_thread_id);
+INTERNAL_FUNC int emcore_add_mail_to_mailbox(emstorage_mailbox_tbl_t *input_maibox_data, emstorage_mail_tbl_t *input_new_mail_tbl_data, int *output_mail_id, int *output_thread_id);
 
 #ifdef __FEATURE_BODY_SEARCH__
 int emcore_add_mail_text(emstorage_mailbox_tbl_t *input_maibox_data, emstorage_mail_tbl_t *input_new_mail_tbl_data, char *stripped_text, int *err_code);
@@ -98,7 +99,7 @@ int emcore_add_mail_text(emstorage_mailbox_tbl_t *input_maibox_data, emstorage_m
  * @remarks N/A
  * @return This function returns true on success or false on failure.
  */
-INTERNAL_FUNC int emcore_sync_header(emstorage_mailbox_tbl_t *input_mailbox_tbl, void *stream_recycle, emcore_uid_list **input_uid_list, int *unread_mail, int *err_code);
+INTERNAL_FUNC int emcore_sync_header(emstorage_mailbox_tbl_t *input_mailbox_tbl, void **stream, emcore_uid_list **input_uid_list, int *mail_count, int *unread_mail, int *err_code);
 
 typedef enum
 {
@@ -119,13 +120,9 @@ typedef enum
  * @remarks N/A
  * @return This function returns true on success or false on failure.
  */
-int emcore_download_uid_all(email_internal_mailbox_t *mailbox,
-                                                       emcore_uid_list         **uid_list,
-                                                       int                                                     *total,
-                                                       emstorage_read_mail_uid_tbl_t *read_mail_uids, 
-                                                       int                           count, 
-                                                       emcore_get_uids_for_delete_t  for_delete, 
-                                                       int                                                     *err_code);
+int emcore_download_uid_all (MAILSTREAM *mail_stream, email_internal_mailbox_t *mailbox, emcore_uid_list **uid_list,
+                                int *total, emstorage_read_mail_uid_tbl_t *read_mail_uids, int count, 
+                                         emcore_get_uids_for_delete_t  for_delete, int *err_code);
 
 
 
@@ -174,6 +171,7 @@ int emcore_get_uid(emcore_uid_list *uid_list, int msgno, char **uid, int *err_co
  */
 int emcore_free_uids(emcore_uid_list *uid_list, int *err_code);
 
+INTERNAL_FUNC char *emcore_guess_charset(char *source_string);
 INTERNAL_FUNC int emcore_sync_mail_from_client_to_server(int mail_id);
 
 #ifdef __FEATURE_PARTIAL_BODY_DOWNLOAD__
index a1f721d..037f58d 100755 (executable)
@@ -69,7 +69,7 @@ INTERNAL_FUNC int  emcore_create_mailbox(email_mailbox_t *new_mailbox, int on_se
 INTERNAL_FUNC int  emcore_delete_mailbox(int input_mailbox_id, int input_on_server, int input_recursive);
 INTERNAL_FUNC int  emcore_delete_mailbox_ex(int input_account_id, int *input_mailbox_id_array, int input_mailbox_id_count, int input_on_server, int input_recursive);
 INTERNAL_FUNC int  emcore_delete_mailbox_all(email_mailbox_t *mailbox, int *err_code);
-INTERNAL_FUNC int  emcore_rename_mailbox(int input_mailbox_id, char *input_new_mailbox_name, char *input_new_mailbox_alias, int input_on_server, int input_recursive, int handle_to_be_published);
+INTERNAL_FUNC int  emcore_rename_mailbox(int input_mailbox_id, char *input_new_mailbox_name, char *input_new_mailbox_alias, void *input_eas_data, int input_eas_data_length, int input_on_server, int input_recursive, int handle_to_be_published);
 INTERNAL_FUNC int  emcore_save_local_activity_sync(int account_id, int *err_code);
 INTERNAL_FUNC int  emcore_send_mail_event(email_mailbox_t *mailbox, int mail_id , int *err_code);
 INTERNAL_FUNC int  emcore_partial_body_thd_local_activity_sync(int *is_event_inserted, int *err_code);
index 8c110ec..a619132 100755 (executable)
@@ -42,6 +42,8 @@ extern "C" {
 
 char *emcore_get_line_from_file(void *stream, char *buf, int size, int *err_code);
 int   emcore_parse_mime(void *stream, int is_file, struct _m_content_info *cnt_info, int *err_code);
+char *emcore_mime_get_save_file_name(int *err_code);
+char *emcore_mime_get_line_from_sock(void *stream, char *buf, int size, int *err_code);
 INTERNAL_FUNC int   emcore_get_content_type_from_mime_string(char *input_mime_string, char **output_content_type);
 INTERNAL_FUNC int   emcore_get_content_type_from_mail_bodystruct(BODY *input_body, int input_buffer_length, char *output_content_type);
 INTERNAL_FUNC int   emcore_get_attribute_value_of_body_part(PARAMETER *input_param, char *atribute_name, char *output_value, int output_buffer_length, int with_rfc2047_text, int *err_code);
@@ -50,11 +52,11 @@ INTERNAL_FUNC int   emcore_get_body(MAILSTREAM *stream, int account_id, int mail
 INTERNAL_FUNC int   emcore_get_body_structure(MAILSTREAM *stream, int msg_uid, BODY **body, int *err_code);
 INTERNAL_FUNC char *emcore_decode_rfc2047_text(char *rfc2047_text, int *err_code);
 INTERNAL_FUNC int   emcore_decode_body_text(char *enc_buf, int enc_len, int enc_type, int *dec_len, int *err_code);
-INTERNAL_FUNC int   emcore_set_fetch_body_section(BODY *body, int enable_inline_list, int *total_mail_size, int *err_code);
+INTERNAL_FUNC int   emcore_set_fetch_body_section(BODY *body, int enable_inline_list, int *total_mail_size, int *total_body_size, int *err_code);
 INTERNAL_FUNC int   emcore_parse_mime_file_to_mail(char *eml_file_path, email_mail_data_t **output_mail_data, email_attachment_data_t **output_attachment_data, int *output_attachment_count, int *err_code);
 INTERNAL_FUNC int   emcore_delete_parsed_data(email_mail_data_t *input_mail_data, int *err_code);
 INTERNAL_FUNC int   emcore_get_mime_entity(char *mime_path, char **mime_entity, int *err_code);
-
+INTERNAL_FUNC int   emcore_get_utf8_address(char **dest, ADDRESS *address, int *err_code);
 #ifdef __cplusplus
 }
 #endif /* __cplusplus */
index 401bce0..f6232ff 100755 (executable)
@@ -36,6 +36,8 @@ INTERNAL_FUNC int emcore_initialize_signal();
 \r
 INTERNAL_FUNC int emcore_finalize_signal();\r
 \r
+INTERNAL_FUNC int em_send_notification_to_active_sync_engine(int subType, ASNotiData *data);\r
+\r
 /* emcore_notify_storage_event - Notification for storage related operations */\r
 INTERNAL_FUNC int emcore_notify_storage_event(email_noti_on_storage_event event_type, int data1, int data2 , char *data3, int data4);\r
 \r
index 55e9c29..77eefb8 100755 (executable)
@@ -54,12 +54,16 @@ INTERNAL_FUNC int emcore_make_rfc822_file_from_mail(emstorage_mail_tbl_t *input_
 
 INTERNAL_FUNC int emcore_make_rfc822_file(email_mail_data_t *input_mail_tbl_data, email_attachment_data_t *input_attachment_tbl, int input_attachment_count, char **file_path, int *err_code);
 
-INTERNAL_FUNC int emcore_add_mail(email_mail_data_t *input_mail_data, email_attachment_data_t *input_attachment_data_list, int input_attachment_count, email_meeting_request_t *input_meeting_request, int input_from_eas);
+INTERNAL_FUNC int emcore_add_mail(email_mail_data_t *input_mail_data, email_attachment_data_t *input_attachment_data_list, int input_attachment_count, email_meeting_request_t *input_meeting_request, int input_from_eas, int move_flag);
 
 INTERNAL_FUNC int emcore_add_read_receipt(int input_read_mail_id, int *output_receipt_mail_id);
 
 INTERNAL_FUNC int emcore_add_meeting_request(int account_id, int input_mailbox_id, email_meeting_request_t *meeting_req, int *err_code);
 
+INTERNAL_FUNC int emcore_create_alarm_for_auto_resend(int input_alarm_interval_in_second);
+
+INTERNAL_FUNC int emcore_query_mail_size_limit(int account_id, int handle, int *err_code);
+
 #ifdef __cplusplus
 }
 #endif /* __cplusplus */
index 6335ea4..9c98d7e 100755 (executable)
 
 #include <vconf-keys.h>
 #include <vconf.h>
-#include <mm_player.h>
-#include <mm_error.h>
-#include <mm_session_private.h>
-#include <feedback.h>
 
 typedef enum
 {
@@ -42,6 +38,7 @@ typedef enum
        EMAIL_ALERT_TYPE_VIB, 
        EMAIL_ALERT_TYPE_MELODY_AND_VIB, 
        EMAIL_ALERT_TYPE_MUTE, 
+       EMAIL_ALERT_TYPE_NONE,
 } EMAIL_ALERT_TYPE;
 
 typedef enum
@@ -63,5 +60,5 @@ typedef enum
 #undef Min
 #endif
 
-INTERNAL_FUNC int  emcore_start_thread_for_alerting_new_mails(int *err_code);
-INTERNAL_FUNC void emcore_start_alert();
+INTERNAL_FUNC int emcore_get_alert_policy(EMAIL_ALERT_TYPE *output_alert_type, char **output_alert_tone_path);
+
index fb7501d..832324d 100755 (executable)
@@ -53,15 +53,15 @@ typedef int (*email_get_unread_email_count_cb)(int unread, int *err_code);
 char* emcore_get_alias_of_mailbox(const char *mailbox_path);
 
 /* Parse the Mailbox Path and get the Account Email address */
-int   emcore_get_temp_file_name(char **filename, int *err_code);
+INTERNAL_FUNC int   emcore_get_temp_file_name(char **filename, int *err_code);
 int   emcore_get_long_encoded_path(int account_id, char *path, int delimiter, char **long_enc_path, int *err_code);
 int   emcore_get_encoded_mailbox_name(char *name, char **enc_name, int *err_code);
 int   emcore_get_file_name(char *path, char **filename, int *err_code);
-int   emcore_get_file_size(char *path, int *size, int *err_code);
+INTERNAL_FUNC int   emcore_get_file_size(char *path, int *size, int *err_code);
 int   emcore_get_actual_mail_size(char *pBodyPlane, char *pBodyHtml, struct attachment_info *pAttachment, int *error_code);
 int   emcore_calc_mail_size(email_mail_data_t *mail_data_src, email_attachment_data_t *attachment_data_src, int attachment_count, int *error_code);
 int   emcore_get_address_count(char *addr_str, int *to_num, int *err_code);
-int   emcore_is_storage_full(int *error);
+INTERNAL_FUNC int   emcore_is_storage_full(int *error);
 int   emcore_get_long_encoded_path_with_account_info(email_account_t *account, char *path, int delimiter, char **long_enc_path, int *err_code);
 void  emcore_fill_address_information_of_mail_tbl(emstorage_mail_tbl_t *mail_data);
 
@@ -74,18 +74,27 @@ INTERNAL_FUNC int emcore_strip_mail_body_from_file(emstorage_mail_tbl_t *mail, c
 #endif
 
 int   reg_replace (char *input_source_text, char *input_old_pattern_string, char *input_new_string);
-int   emcore_strip_HTML(char *source_string);
+int   reg_replace_new (char **input_source_text, char *input_old_pattern_string, char *input_new_string);
+int   emcore_strip_HTML(char **source_string);
 int   emcore_send_noti_for_new_mail(int account_id, char *mailbox_name, char *subject, char *from, char *uid, char *datetime);
 int   emcore_make_attachment_file_name_with_extension(char *source_file_name, char *sub_type, char *result_file_name, int result_file_name_buffer_length, int *err_code);
 
 /* Session Handling */
-int   emcore_get_empty_session(email_session_t **session);
-int   emcore_clear_session(email_session_t *session);
-int   emcore_get_current_session(email_session_t **session);
+INTERNAL_FUNC int   emcore_get_empty_session(email_session_t **session);
+INTERNAL_FUNC int   emcore_clear_session(email_session_t *session);
+INTERNAL_FUNC int   emcore_get_current_session(email_session_t **session);
+
+INTERNAL_FUNC int emcore_get_mail_count_by_query(int account_id, int mailbox_type, int priority_sender, int *total_mail, int *unread_mail, int *err_code);
+
+INTERNAL_FUNC int emcore_check_drm_file(char *path, int *err_code);
+INTERNAL_FUNC int emcore_check_drm_is_ringtone(char *ringtone_path, int *err_code);
 
 INTERNAL_FUNC int emcore_display_unread_in_badge();
+INTERNAL_FUNC int emcore_display_badge_count(int count);
 INTERNAL_FUNC int emcore_set_network_error(int err_code);
 
+INTERNAL_FUNC int emcore_calc_next_time_to_sync(int input_account_id, time_t input_current_time, time_t *output_time);
+
 /* Transaction Handling */
 INTERNAL_FUNC int emcore_add_transaction_info(int mail_id , int handle  , int *err_code);
 INTERNAL_FUNC int emcore_get_handle_by_mailId_from_transaction_info(int mail_id , int *pHandle);
@@ -95,9 +104,11 @@ INTERNAL_FUNC int emcore_delete_transaction_info_by_mailId(int mail_id);
 INTERNAL_FUNC int emcore_update_notification_for_unread_mail(int account_id);
 INTERNAL_FUNC int emcore_clear_all_notifications();
 //INTERNAL_FUNC int emcore_add_notification_for_unread_mail(emstorage_mail_tbl_t *input_mail_tbl_data);
+INTERNAL_FUNC int emcore_add_notification(int account_id, int mail_id, int unread_mail_count, int input_play_alert_tone, int sending_error, unsigned long display);
+INTERNAL_FUNC int emcore_add_notification_for_send(int account_id, int mail_id, email_action_t action, int sending_error, unsigned long display);
+INTERNAL_FUNC void emcore_update_notification_for_send(int account_id, int mail_id, double progress);
 INTERNAL_FUNC int emcore_delete_notification_for_read_mail(int mail_id);
-INTERNAL_FUNC int emcore_delete_notification_by_account(int account_id);
-INTERNAL_FUNC int emcore_finalize_sync(int account_id, int *error);
+INTERNAL_FUNC int emcore_delete_notification_by_account(int account_id, int with_noti_tray);
 
 INTERNAL_FUNC int emcore_show_user_message(int id, email_action_t action, int error);
 
@@ -191,11 +202,14 @@ INTERNAL_FUNC int emcore_delete_activity(emstorage_activity_tbl_t *activity, int
 #endif /* __FEATURE_LOCAL_ACTIVITY__ */
 
 INTERNAL_FUNC void emcore_free_rule(email_rule_t* rule);
+INTERNAL_FUNC void emcore_free_body_sparep(void **p);
 
-INTERNAL_FUNC int emcore_search_string_from_file(char *file_path, char *search_string, int *result);
+INTERNAL_FUNC int emcore_search_string_from_file(char *file_path, char *search_string, char *new_string, int *result);
 
 INTERNAL_FUNC int emcore_load_query_from_file(char *file_path, char ***query_array, int *array_len);
 
+INTERNAL_FUNC int emcore_start_driving_mode(int account_id);
+
 #ifdef __FEATURE_BLOCKING_MODE__
 INTERNAL_FUNC bool emcore_init_blocking_mode_status();
 INTERNAL_FUNC void emcore_set_blocking_mode_of_setting(int input_blocking_mode_of_setting);
@@ -204,6 +218,8 @@ INTERNAL_FUNC void emcore_set_blocking_mode_status(int blocking_mode);
 INTERNAL_FUNC int emcore_check_blocking_mode(char *sender_address, int *blocking_status);
 #endif /* __FEATURE_BLOCKING_MODE__ */
 
+INTERNAL_FUNC char *emcore_set_mime_entity(char *mime_path);
+
 #ifdef __cplusplus
 }
 #endif /* __cplusplus */
index 98f696f..06ec746 100755 (executable)
@@ -11,6 +11,9 @@ MESSAGE("")
 MESSAGE(">>> current directory: ${CMAKE_CURRENT_SOURCE_DIR}")
 MESSAGE(">>> Build type: ${CMAKE_BUILD_TYPE}")
 
+ADD_DEFINITIONS("-DSSL_CERT_DIRECTORY=\"/opt/etc/ssl/certs\"")
+ADD_DEFINITIONS("-DSSL_KEY_DIRECTORY=\"/opt/etc/ssl/certs\"")
+
 SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${VISIBILITY} -fvisibility=hidden")
 
 ##########################################################
@@ -19,6 +22,7 @@ SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${VISIBILITY} -fvisibility=hidden")
 
 SET(MAIN-SRCS 
        ${CMAKE_SOURCE_DIR}/email-daemon/main.c
+       ${CMAKE_SOURCE_DIR}/email-daemon/email-daemon-event.c
        ${CMAKE_SOURCE_DIR}/email-daemon/email-daemon-init.c
        ${CMAKE_SOURCE_DIR}/email-daemon/email-daemon-account.c
        ${CMAKE_SOURCE_DIR}/email-daemon/email-daemon-mail.c
@@ -31,15 +35,21 @@ SET(MAIN-SRCS
 INCLUDE_DIRECTORIES(
        ${CMAKE_SOURCE_DIR}/email-common-use/include
        ${CMAKE_SOURCE_DIR}/email-ipc/include
+       ${CMAKE_SOURCE_DIR}/email-ipc/email-ipc-api/include
+       ${CMAKE_SOURCE_DIR}/email-ipc/email-activation/include
        ${CMAKE_SOURCE_DIR}/email-api/include
        ${CMAKE_SOURCE_DIR}/email-core/include
        ${CMAKE_SOURCE_DIR}/email-core/email-storage/include
+       ${CMAKE_SOURCE_DIR}/email-core/email-network/include
+       ${CMAKE_SOURCE_DIR}/email-core/email-device/include
        ${CMAKE_SOURCE_DIR}/email-daemon/include
 )
 
 INCLUDE(FindPkgConfig)
-pkg_check_modules(main_pkgs REQUIRED glib-2.0 dlog dbus-1 gthread-2.0  db-util openssl uw-imap-toolkit vconf contacts-service2 alarm-service mm-player drm-client feedback msg-service libwbxml2)
-
+pkg_check_modules(main_pkgs REQUIRED glib-2.0 dlog dbus-1 gthread-2.0 db-util 
+                               openssl uw-imap-toolkit vconf vconf-internal-keys contacts-service2 
+                               alarm-service mm-player drm-client feedback msg-service 
+                               libwbxml2 libsmack notification)
 
 FOREACH(flag ${main_pkgs_CFLAGS})
        SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag}")
@@ -49,6 +59,6 @@ SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${EXTRA_CFLAGS}")
 SET(CMAKE_EXE_LINKER_FLAGS "-Wl,--as-needed")
 
 ADD_EXECUTABLE(${PROJECT_NAME} ${MAIN-SRCS})
-TARGET_LINK_LIBRARIES(${PROJECT_NAME} ${main_pkgs_LDFLAGS} dl ssl email-core email-storage email-network email-ipc email-common-use)
+TARGET_LINK_LIBRARIES(${PROJECT_NAME} ${main_pkgs_LDFLAGS} dl ssl email-core email-core-sound email-storage email-network email-ipc email-common-use email-device email-smime)
 INSTALL(TARGETS ${PROJECT_NAME} DESTINATION bin)
 
index 6e7e517..11c1088 100755 (executable)
@@ -106,11 +106,12 @@ FINISH_OFF:
 
 INTERNAL_FUNC int emdaemon_delete_account(int account_id, int* err_code)
 {
-       EM_DEBUG_FUNC_BEGIN();
-       int ret;
+       EM_DEBUG_FUNC_BEGIN("account_id[%d] err_code[%p]", account_id, err_code);
+       int ret = false;
 
        ret = emcore_delete_account(account_id, err_code);
-       EM_DEBUG_FUNC_END();
+
+       EM_DEBUG_FUNC_END("ret[%d]", ret);
        return ret;
 }
 
@@ -162,10 +163,10 @@ INTERNAL_FUNC int emdaemon_validate_account(int account_id, int *handle, int* er
 
        int ret = false;
        int err = EMAIL_ERROR_NONE;
-       email_event_t event_data = {0};
-       email_account_tref_account = NULL;
+       email_event_t *event_data = NULL;
+       email_account_t *ref_account = NULL;
 
-       if (account_id < 1)  {
+       if (account_id < 1) {
                EM_DEBUG_EXCEPTION(" account_id[%d]", account_id);
                err = EMAIL_ERROR_INVALID_PARAM;
                goto FINISH_OFF;
@@ -177,13 +178,15 @@ INTERNAL_FUNC int emdaemon_validate_account(int account_id, int *handle, int* er
                goto FINISH_OFF;
        }
 
-       event_data.type = EMAIL_EVENT_VALIDATE_ACCOUNT;
-       event_data.event_param_data_1 = NULL;
-       event_data.event_param_data_3 = NULL;
-       event_data.account_id = account_id;
+       event_data = em_malloc(sizeof(email_event_t));
+       event_data->type = EMAIL_EVENT_VALIDATE_ACCOUNT;
+       event_data->event_param_data_1 = NULL;
+       event_data->event_param_data_3 = NULL;
+       event_data->account_id = account_id;
 
-       if (!emcore_insert_event(&event_data, (int*)handle, &err))  {
+       if (!emcore_insert_event(event_data, (int*)handle, &err)) {
                EM_DEBUG_EXCEPTION(" emcore_insert_event falied [%d]", err);
+               goto FINISH_OFF;
        }
 
        ret = true;
@@ -195,9 +198,16 @@ FINISH_OFF:
                EM_SAFE_FREE(ref_account);
        }
 
+       if (ret == false && event_data) {
+               emcore_free_event(event_data);
+               EM_SAFE_FREE(event_data);
+       }
+
        if (err_code)
                *err_code = err;
+
        EM_DEBUG_FUNC_END();
+
        return ret;
 }
 
@@ -205,22 +215,39 @@ INTERNAL_FUNC int emdaemon_validate_account_ex(email_account_t* input_account, i
 {
        EM_DEBUG_FUNC_BEGIN("input_account[%p], output_handle[%p]", input_account, output_handle);
 
+       int ret = false;
        int err = EMAIL_ERROR_NONE;
-       email_event_t event_data = {0};
+       email_event_t *event_data = NULL;
+
+       event_data = em_malloc(sizeof(email_event_t));
+
+       if(!event_data) { /*prevent 53095*/
+               EM_DEBUG_EXCEPTION("em_malloc failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
 
-       event_data.type               = EMAIL_EVENT_VALIDATE_ACCOUNT_EX;
-       event_data.event_param_data_1 = (void*)input_account;
-       event_data.event_param_data_3 = NULL;
-       event_data.account_id         = NEW_ACCOUNT_ID;
+       event_data->type               = EMAIL_EVENT_VALIDATE_ACCOUNT_EX;
+       event_data->event_param_data_1 = (void*)input_account;
+       event_data->event_param_data_3 = NULL;
+       event_data->account_id         = NEW_ACCOUNT_ID;
 
-       if (!emcore_insert_event(&event_data, (int*)output_handle, &err))  {
+       if (!emcore_insert_event(event_data, (int*)output_handle, &err)) {
                EM_DEBUG_EXCEPTION(" emcore_insert_event falied [%d]", err);
                goto FINISH_OFF;
        }
 
+       ret = true;
 
 FINISH_OFF:
+
+       if (ret == false && event_data) {
+               emcore_free_event(event_data);
+               EM_SAFE_FREE(event_data);
+       }
+
        EM_DEBUG_FUNC_END("err [%d]", err);
+
        return err;
 }
 
@@ -230,14 +257,22 @@ INTERNAL_FUNC int emdaemon_validate_account_and_create(email_account_t* new_acco
 
        int ret = false;
        int err = EMAIL_ERROR_NONE;
-       email_event_t event_data = {0};
+       email_event_t *event_data = NULL;
+
+       event_data = em_malloc(sizeof(email_event_t));
+
+       if(!event_data) { /*prevent 53093*/
+               EM_DEBUG_EXCEPTION("em_malloc failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
 
-       event_data.type = EMAIL_EVENT_VALIDATE_AND_CREATE_ACCOUNT;
-       event_data.event_param_data_1 = (void*) new_account;
-       event_data.event_param_data_3 = NULL;
-       event_data.account_id = NEW_ACCOUNT_ID;
+       event_data->type = EMAIL_EVENT_VALIDATE_AND_CREATE_ACCOUNT;
+       event_data->event_param_data_1 = (void *)new_account;
+       event_data->event_param_data_3 = NULL;
+       event_data->account_id = NEW_ACCOUNT_ID;
 
-       if (!emcore_insert_event(&event_data, (int*)handle, &err))  {
+       if (!emcore_insert_event(event_data, (int*)handle, &err))  {
                EM_DEBUG_EXCEPTION(" emcore_insert_event falied [%d]", err);
                goto FINISH_OFF;
        }
@@ -245,9 +280,17 @@ INTERNAL_FUNC int emdaemon_validate_account_and_create(email_account_t* new_acco
        ret = true;
 
 FINISH_OFF:
+
+       if (ret == false && event_data) {
+               emcore_free_event(event_data);
+               EM_SAFE_FREE(event_data);
+       }
+
        if (err_code)
                *err_code = err;
+
        EM_DEBUG_FUNC_END();
+
        return ret;
 }
 
@@ -273,11 +316,10 @@ INTERNAL_FUNC int emdaemon_update_account(int account_id, email_account_t* new_a
                goto FINISH_OFF;
        }
 
-       EM_DEBUG_LOG("new_account->email_addr[%s]", new_account->user_email_address);
+       EM_DEBUG_LOG_SEC("new_account->email_addr[%s]", new_account->user_email_address);
        if(new_account->user_email_address) {
-               if (!em_verify_email_address(new_account->user_email_address, true, &err)) {
-                       err = EMAIL_ERROR_INVALID_ADDRESS;
-                       EM_DEBUG_EXCEPTION("Invalid Email Address");
+               if ((err = em_verify_email_address (new_account->user_email_address, true)) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("em_verify_email_address error [%d]", err);
                        goto FINISH_OFF;
                }
        }
@@ -298,23 +340,19 @@ INTERNAL_FUNC int emdaemon_update_account(int account_id, email_account_t* new_a
        emcore_init_account_reference();
 
 #ifdef __FEATURE_AUTO_POLLING__
-       int  old_check_interval = old_account_info.check_interval;
-       if( old_check_interval <= 0 && new_account->check_interval > 0) {
-               if(!emdaemon_add_polling_alarm(account_id, new_account->check_interval))
-                       EM_DEBUG_EXCEPTION("emdaemon_add_polling_alarm[ CHANGEACCOUNT] : start auto poll failed >>> ");
+       int  change_in_auto_polling_option = 0;
 
-       }
-       else if( (old_check_interval > 0) && (new_account->check_interval <= 0)) {
+       change_in_auto_polling_option = (old_account_info.check_interval  != new_account->check_interval)  ||
+                                                                       (old_account_info.peak_interval   != new_account->peak_interval)   ||
+                                                                       (old_account_info.peak_start_time != new_account->peak_start_time) ||
+                                                                       (old_account_info.peak_end_time   != new_account->peak_end_time);
+
+       if(change_in_auto_polling_option) {
                if(!emdaemon_remove_polling_alarm(account_id))
-                       EM_DEBUG_EXCEPTION("emdaemon_remove_polling_alarm[ CHANGEACCOUNT] : start auto poll failed >>> ");
-       }
-       else if(old_check_interval != new_account->check_interval && new_account->check_interval > 0) {
-               if(!emdaemon_remove_polling_alarm(account_id)) {
-                       EM_DEBUG_EXCEPTION("emdaemon_remove_polling_alarm[ CHANGEACCOUNT] : start auto poll failed >>> ");
-                       goto FINISH_OFF;
-               }
-               if(!emdaemon_add_polling_alarm(account_id, new_account->check_interval))
-                       EM_DEBUG_EXCEPTION("emdaemon_add_polling_alarm[ CHANGEACCOUNT] : start auto poll failed >>> ");
+                       EM_DEBUG_LOG("emdaemon_remove_polling_alarm failed");
+
+               if(!emdaemon_add_polling_alarm(account_id))
+                       EM_DEBUG_EXCEPTION("emdaemon_add_polling_alarm failed");
        }
 #endif
 
@@ -340,12 +378,20 @@ INTERNAL_FUNC int emdaemon_validate_account_and_update(int old_account_id, email
 
        int ret = false;
        int err = EMAIL_ERROR_NONE;
-       email_event_t event_data = {0};
+       email_event_t *event_data = NULL;
+
+       event_data = em_malloc(sizeof(email_event_t));
+
+       if(!event_data) { /*prevent 53094*/
+               EM_DEBUG_EXCEPTION("em_malloc failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
 
-       event_data.type = EMAIL_EVENT_VALIDATE_AND_UPDATE_ACCOUNT;
-       event_data.event_param_data_1 = (char *) duplicate_account(new_account_info);
-       event_data.event_param_data_3 = NULL;
-       event_data.account_id = old_account_id;
+       event_data->type = EMAIL_EVENT_VALIDATE_AND_UPDATE_ACCOUNT;
+       event_data->event_param_data_1 = (char *) duplicate_account(new_account_info);
+       event_data->event_param_data_3 = NULL;
+       event_data->account_id = old_account_id;
 
 #if 0
        email_account_t *pAccount = (email_account_t *)em_malloc(sizeof(email_account_t));
@@ -375,7 +421,7 @@ INTERNAL_FUNC int emdaemon_validate_account_and_update(int old_account_id, email
        memcpy(pAccount->user_data, new_account_info->user_data, new_account_info->user_data_length);
 #endif
 
-       if (!emcore_insert_event(&event_data, (int*)handle, &err)) {
+       if (!emcore_insert_event(event_data, (int*)handle, &err)) {
                EM_DEBUG_EXCEPTION("emcore_insert_event falied [%d]", err);
                goto FINISH_OFF;
        }
@@ -383,9 +429,17 @@ INTERNAL_FUNC int emdaemon_validate_account_and_update(int old_account_id, email
        ret = true;
 
 FINISH_OFF:
+
+       if (ret == false && event_data) {
+               emcore_free_event(event_data);
+               EM_SAFE_FREE(event_data);
+       }
+
        if (err_code)
                *err_code = err;
+
        EM_DEBUG_FUNC_END();
+
        return ret;
 }
 
@@ -542,29 +596,35 @@ INTERNAL_FUNC int emdaemon_find_filter(email_rule_t* filter_info, int* err_code)
        int ret = false;
        int err = EMAIL_ERROR_NONE;
 
-       if (!filter_info)  {
+       if (!filter_info) {
                EM_DEBUG_EXCEPTION(" filter_info[%p]", filter_info);
                err = EMAIL_ERROR_INVALID_PARAM;
                goto FINISH_OFF;
        }
 
-       if (filter_info->faction == EMAIL_FILTER_MOVE && !filter_info->target_mailbox_id) {
-               EM_DEBUG_EXCEPTION(" filter_info->faction[%d], filter_info->target_mailbox_id[%d]", filter_info->faction, filter_info->target_mailbox_id);
+       if (filter_info->faction == EMAIL_FILTER_MOVE && filter_info->target_mailbox_id <= 0) {
+               EM_DEBUG_EXCEPTION("filter_info->faction[%d], filter_info->target_mailbox_id[%d]", filter_info->faction, filter_info->target_mailbox_id);
                err = EMAIL_ERROR_INVALID_FILTER;
                goto FINISH_OFF;
        }
 
        filter_info->account_id = ALL_ACCOUNT;          /*  MUST BE */
 
-       if (!emstorage_find_rule((emstorage_rule_tbl_t*)filter_info, true, &err))  {
-               EM_DEBUG_EXCEPTION(" emstorage_find_rule failed [%d]", err);
-               err = EMAIL_ERROR_FILTER_NOT_FOUND;
+       if (!emstorage_find_rule((emstorage_rule_tbl_t*)filter_info, true, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_find_rule failed [%d]", err);
                goto FINISH_OFF;
+       } else {
+               if (err == EMAIL_ERROR_FILTER_NOT_FOUND) {
+                       EM_DEBUG_LOG("EMAIL_ERROR_FILTER_NOT_FOUND");
+                       err = EMAIL_ERROR_FILTER_NOT_FOUND;
+                       goto FINISH_OFF;
+               }
        }
 
        ret = true;
 
 FINISH_OFF:
+
        if (err_code)
                *err_code = err;
        EM_DEBUG_FUNC_END();
@@ -577,22 +637,27 @@ INTERNAL_FUNC int emdaemon_add_filter(email_rule_t* filter_info)
 
        /*  default variable */
        int err = EMAIL_ERROR_NONE;
-       if (!filter_info || !(filter_info->value))  {
+       if (!filter_info) {
                EM_DEBUG_EXCEPTION("filter_info[%p]", filter_info);
                err = EMAIL_ERROR_INVALID_PARAM;
                goto FINISH_OFF;
        }
 
-       if (emstorage_find_rule((emstorage_rule_tbl_t*)filter_info, true, &err))  {
+       if (!emstorage_find_rule((emstorage_rule_tbl_t*)filter_info, true, &err)) {
                EM_DEBUG_EXCEPTION("emstorage_find_rule failed [%d]", err);
-               err = EMAIL_ERROR_ALREADY_EXISTS;
                goto FINISH_OFF;
+       } else {
+               if (err != EMAIL_ERROR_FILTER_NOT_FOUND) {
+                       EM_DEBUG_LOG("filter already exist");
+                       err = EMAIL_ERROR_ALREADY_EXISTS;
+                       goto FINISH_OFF;
+               }
        }
 
        switch (filter_info->faction) {
        case EMAIL_FILTER_MOVE :
-               if (!filter_info->target_mailbox_id && (filter_info->account_id <= 0)) {
-                       EM_DEBUG_EXCEPTION("target_mailbox_id[%d], account_id[%d]",  filter_info->target_mailbox_id, filter_info->account_id);
+               if (filter_info->account_id < 0) {
+                       EM_DEBUG_EXCEPTION("Invalid Param : target_mailbox_id[%d], account_id[%d]", filter_info->target_mailbox_id, filter_info->account_id);
                        err = EMAIL_ERROR_INVALID_PARAM;
                        goto FINISH_OFF;
                }
@@ -606,7 +671,7 @@ INTERNAL_FUNC int emdaemon_add_filter(email_rule_t* filter_info)
                break;
        }
 
-       if (!emstorage_add_rule((emstorage_rule_tbl_t*)filter_info, true, &err))  {
+       if (!emstorage_add_rule((emstorage_rule_tbl_t*)filter_info, true, &err)) {
                EM_DEBUG_EXCEPTION("emstorage_add_rule failed [%d]", err);
                goto FINISH_OFF;
        }
@@ -659,6 +724,7 @@ INTERNAL_FUNC int emdaemon_delete_filter(int filter_id, int* err_code)
        /*  default variable */
        int ret = false;
        int err = EMAIL_ERROR_NONE;
+       emstorage_rule_tbl_t *p_rule_tbl = NULL;
 
        if (filter_id <= 0)  {
                EM_DEBUG_EXCEPTION(" fliter_id[%d]", filter_id);
@@ -666,12 +732,17 @@ INTERNAL_FUNC int emdaemon_delete_filter(int filter_id, int* err_code)
                goto FINISH_OFF;
        }
 
-       if (!emdaemon_check_filter_id(filter_id, &err))  {
-               EM_DEBUG_EXCEPTION(" emdaemon_check_filter_id failed [%d]", err);
+       if (!emstorage_get_rule_by_id(filter_id, &p_rule_tbl, false, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_get_rule_by_id failed : [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (!emstorage_filter_mails_by_rule(p_rule_tbl->account_id, p_rule_tbl->target_mailbox_id, false, true, p_rule_tbl, NULL, NULL, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_filter_mails_by_rule failed : [%d]", err);
                goto FINISH_OFF;
        }
 
-       if (!emstorage_delete_rule(filter_id, true, &err))  {
+       if (!emstorage_delete_rule(filter_id, true, &err)) {
                EM_DEBUG_EXCEPTION(" emstorage_delete_rule failed [%d]", err);
                goto FINISH_OFF;
        }
@@ -679,8 +750,10 @@ INTERNAL_FUNC int emdaemon_delete_filter(int filter_id, int* err_code)
        ret = true;
 
 FINISH_OFF:
+
        if (err_code)
                *err_code = err;
+
        EM_DEBUG_FUNC_END();
        return ret;
 }
@@ -740,7 +813,7 @@ INTERNAL_FUNC int emdaemon_apply_filter(int filter_id, int *err_code)
        }
 
        if (!emcore_mail_filter_by_rule((email_rule_t *)filter_info, &err))  {
-               EM_DEBUG_EXCEPTION(" emstorage_delete_rule failed [%d]", err);
+               EM_DEBUG_EXCEPTION(" emstorage_mail_filter_by_rule failed [%d]", err);
                goto FINISH_OFF;
        }
 
@@ -773,7 +846,10 @@ int emdaemon_initialize_account_reference()
                        }
                }
                else {
-                       EM_DEBUG_EXCEPTION("emcore_init_account_reference failed [%d]", err);
+                       if (err == EMAIL_ERROR_ACCOUNT_NOT_FOUND)
+                               EM_DEBUG_LOG ("no account found");
+                       else
+                               EM_DEBUG_EXCEPTION ("emcore_init_account_reference failed [%d]", err);
                        goto FINISH_OFF;
                }
        }
@@ -808,4 +884,46 @@ INTERNAL_FUNC int emdaemon_update_accountinfo_to_contact(email_account_t* old_ac
        return ret;
 }
 
+INTERNAL_FUNC int emdaemon_query_smtp_mail_size_limit(int account_id, int *handle, int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], handle[%p], err_code[%p]", account_id, handle, err_code);
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       email_event_t *event_data = NULL;
+
+       if (account_id < 1) {
+               EM_DEBUG_EXCEPTION(" account_id[%d]", account_id);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       event_data = em_malloc(sizeof(email_event_t));
+       event_data->type = EMAIL_EVENT_QUERY_SMTP_MAIL_SIZE_LIMIT;
+       event_data->event_param_data_1 = NULL;
+       event_data->event_param_data_3 = NULL;
+       event_data->account_id = account_id;
+
+       if (!emcore_insert_event(event_data, (int*)handle, &err)) {
+               EM_DEBUG_EXCEPTION(" emcore_insert_event falied [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (ret == false && event_data) {
+               emcore_free_event(event_data);
+               EM_SAFE_FREE(event_data);
+       }
+
+       if (err_code)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END();
+
+       return ret;
+}
+
 /* EOF */
index 775b687..fa4f9a3 100755 (executable)
 #include "email-core-alarm.h"
 #include "email-debug-log.h"
 #include "email-storage.h"
+#include "email-network.h"
 #include "email-utilities.h"
 
 
 static int _emdaemon_get_polling_account_and_timeinterval(alarm_id_t  alarm_id, int *account_id, int *timer_interval);
-static int _emdaemon_create_alarm(int input_account_id, int input_alarm_interval);
+static int _emdaemon_create_alarm_for_auto_polling(int input_account_id);
 
-INTERNAL_FUNC int emdaemon_add_polling_alarm(int input_account_id, int input_alarm_interval_in_minutes)
+INTERNAL_FUNC int emdaemon_add_polling_alarm(int input_account_id)
 {
-       EM_DEBUG_FUNC_BEGIN("input_account_id[%d] input_alarm_interval_in_minutes[%d]", input_account_id, input_alarm_interval_in_minutes);
+       EM_DEBUG_FUNC_BEGIN("input_account_id[%d]", input_account_id);
        int err = EMAIL_ERROR_NONE;
 
-       if(input_alarm_interval_in_minutes <= 0) {
+       if(input_account_id <= 0) {
                EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
                err = EMAIL_ERROR_INVALID_PARAM;
                goto FINISH_OFF;
@@ -61,8 +62,8 @@ INTERNAL_FUNC int emdaemon_add_polling_alarm(int input_account_id, int input_ala
                goto FINISH_OFF;
        }
 
-       if((err = _emdaemon_create_alarm(input_account_id, input_alarm_interval_in_minutes * 60)) != EMAIL_ERROR_NONE) {
-               EM_DEBUG_EXCEPTION("_emdaemon_create_alarm failed[%d]", err);
+       if((err = _emdaemon_create_alarm_for_auto_polling(input_account_id)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("_emdaemon_create_alarm_for_auto_polling failed[%d]", err);
                goto FINISH_OFF;
        }
 FINISH_OFF:
@@ -78,7 +79,7 @@ INTERNAL_FUNC int emdaemon_remove_polling_alarm(int account_id)
 
        /* delete from list */
        if((err = emcore_delete_alram_data_by_reference_id(EMAIL_ALARM_CLASS_AUTO_POLLING, account_id)) != EMAIL_ERROR_NONE) {
-               EM_DEBUG_EXCEPTION("emcore_delete_alram_data_by_reference_id failed[%d]", err);
+               EM_DEBUG_LOG ("emcore_delete_alram_data_by_reference_id return [%d]", err);
        }
 
        EM_DEBUG_FUNC_END("err[%d]", err);
@@ -92,7 +93,7 @@ INTERNAL_FUNC int emdaemon_check_auto_polling_started(int account_id)
        email_alarm_data_t *alarm_data = NULL;
 
        if((err = emcore_get_alarm_data_by_reference_id(EMAIL_ALARM_CLASS_AUTO_POLLING, account_id, &alarm_data)) != EMAIL_ERROR_NONE) {
-               EM_DEBUG_EXCEPTION("emcore_get_alarm_data_by_reference_id  failed [%d]", err);
+               EM_DEBUG_LOG ("emcore_get_alarm_data_by_reference_id error [%d]", err);
                goto FINISH_OFF;
        }
 
@@ -108,9 +109,15 @@ INTERNAL_FUNC int emdaemon_alarm_polling_cb(alarm_id_t alarm_id, void* user_para
 
        int ret = false;
        int err = EMAIL_ERROR_NONE;
+       int handle = 0;
        int account_id = 0;
        int mailbox_id = 0;
        int timer_interval = 0;
+       int roaming_status = 0;
+       int wifi_status = 0;
+       email_account_t *ref_account = NULL;
+
+       EM_DEBUG_ALARM_LOG("alarm_id [%d]", alarm_id);
 
        if(!_emdaemon_get_polling_account_and_timeinterval(alarm_id, &account_id, &timer_interval)) {
                EM_DEBUG_EXCEPTION("email_get_polling_account failed");
@@ -120,23 +127,51 @@ INTERNAL_FUNC int emdaemon_alarm_polling_cb(alarm_id_t alarm_id, void* user_para
        /* delete from list */
        if ((err = emdaemon_remove_polling_alarm(account_id)) != EMAIL_ERROR_NONE) {
                EM_DEBUG_EXCEPTION("email_get_polling_account failed [%d]", err);
-               return false;
        }
 
        EM_DEBUG_LOG("target account_id [%d]",account_id);
 
        /* create alarm, for polling */
-       if ((err = _emdaemon_create_alarm(account_id, timer_interval * 60)) != EMAIL_ERROR_NONE) {
-               EM_DEBUG_EXCEPTION("_emdaemon_create_alarm failed [%d]", err);
+       if ((err = _emdaemon_create_alarm_for_auto_polling(account_id)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("_emdaemon_create_alarm_for_auto_polling failed [%d]", err);
                return false;
        }
 
+       ref_account = emcore_get_account_reference(account_id);
+
+       if (ref_account == NULL) {
+               EM_DEBUG_EXCEPTION("emcore_get_account_reference failed");
+               err = EMAIL_ERROR_ACCOUNT_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+
+       if (ref_account->sync_disabled) {
+               err = EMAIL_ERROR_ACCOUNT_SYNC_IS_DISALBED;
+               EM_DEBUG_LOG("Sync disabled for this account. Do not sync.");
+               goto FINISH_OFF;
+       }
+
+       if ((err = emnetwork_get_roaming_status(&roaming_status)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emnetwork_get_roaming_status failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if ((err = emnetwork_get_wifi_status(&wifi_status)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emnetwork_get_roaming_status failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (wifi_status == 0 && roaming_status == 1 && ref_account->roaming_option == EMAIL_ROAMING_OPTION_RESTRICTED_BACKGROUND_TASK) {
+               EM_DEBUG_LOG("wifi_status[%d], roaming_status[%d], roaming_option[%d]", wifi_status, roaming_status, ref_account->roaming_option);
+               goto FINISH_OFF;
+       }
+
        if (!emstorage_get_mailbox_id_by_mailbox_type(account_id,EMAIL_MAILBOX_TYPE_INBOX, &mailbox_id, false, &err))  {
                EM_DEBUG_EXCEPTION("emstorage_get_mailbox_name_by_mailbox_type failed [%d]", err);
                goto FINISH_OFF;
        }
 
-       if (!emdaemon_sync_header(account_id, mailbox_id, NULL, &err))  {
+       if (!emdaemon_sync_header(account_id, mailbox_id, &handle, &err))  {
                EM_DEBUG_EXCEPTION("emdaemon_sync_header falied [%d]", err);
                goto FINISH_OFF;
        }
@@ -144,6 +179,12 @@ INTERNAL_FUNC int emdaemon_alarm_polling_cb(alarm_id_t alarm_id, void* user_para
        ret = true;
 FINISH_OFF :
 
+       if(ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+
+       EM_DEBUG_FUNC_END("err[%d]", err);
        return ret;
 }
 
@@ -184,14 +225,15 @@ FINISH_OFF:
 }
 
 
-static int _emdaemon_create_alarm(int input_account_id, int input_alarm_interval_in_second)
+
+static int _emdaemon_create_alarm_for_auto_polling(int input_account_id)
 {
-       EM_DEBUG_FUNC_BEGIN("input_account_id [%d] input_alarm_interval_in_second[%d]", input_account_id, input_alarm_interval_in_second);
+       EM_DEBUG_FUNC_BEGIN("input_account_id [%d]", input_account_id);
        int err = EMAIL_ERROR_NONE;
-       time_t current_time;
        time_t trigger_at_time;
+       time_t current_time;
 
-       if(input_alarm_interval_in_second <= 0) {
+       if(input_account_id <= 0) {
                EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
                err = EMAIL_ERROR_INVALID_PARAM;
                goto FINISH_OFF;
@@ -199,9 +241,15 @@ static int _emdaemon_create_alarm(int input_account_id, int input_alarm_interval
 
        time(&current_time);
 
-       trigger_at_time = current_time + input_alarm_interval_in_second;
+       if ((err = emcore_calc_next_time_to_sync(input_account_id, current_time, &trigger_at_time)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emcore_add_alarm failed [%d]",err);
+               goto FINISH_OFF;
+       }
 
-       if ((err = emcore_add_alarm(trigger_at_time, EMAIL_ALARM_CLASS_AUTO_POLLING, input_account_id, emdaemon_alarm_polling_cb, NULL)) != EMAIL_ERROR_NONE) {
+       if (trigger_at_time == 0) {
+               EM_DEBUG_LOG("trigger_at_time is 0. It means auto polling is disabled");
+       }
+       else if ((err = emcore_add_alarm(trigger_at_time, EMAIL_ALARM_CLASS_AUTO_POLLING, input_account_id, emdaemon_alarm_polling_cb, NULL)) != EMAIL_ERROR_NONE) {
                EM_DEBUG_EXCEPTION("emcore_add_alarm failed [%d]",err);
                goto FINISH_OFF;
        }
index a51bca1..d193b8f 100755 (executable)
@@ -50,7 +50,7 @@ static void _cb_parser_start_document(void* ctx, WB_LONG charset, const WBXMLLan
 {
        EM_DEBUG_FUNC_BEGIN();
        EM_DEBUG_LOG("Root Element: %s", lang->publicID->xmlRootElt);
-       EM_DEBUG_LOG("Public ID: %s",    lang->publicID->xmlPublicID);
+       EM_DEBUG_LOG_SEC("Public ID: %s",        lang->publicID->xmlPublicID);
        EM_DEBUG_LOG("DTD: %s",                  lang->publicID->xmlDTD);
        EM_DEBUG_FUNC_END();
 }
@@ -89,12 +89,12 @@ static void _cb_parser_start_element(void* ctx, WBXMLTag* element, WBXMLAttribut
                return ;
        }
 
-       EM_DEBUG_LOG("<%s", (char *)wbxml_tag_get_xml_name(element));
+       EM_DEBUG_LOG_SEC("<%s", (char *)wbxml_tag_get_xml_name(element));
        sprintf((char *)p, "<%s", (char *)wbxml_tag_get_xml_name(element));
 
        j = 0;
        while (atts[j] != NULL) {
-               EM_DEBUG_LOG(" %s=\"%s\"", (char *)wbxml_attribute_get_xml_name(atts[j]), (char *)wbxml_attribute_get_xml_value(atts[j]));
+               EM_DEBUG_LOG_SEC(" %s=\"%s\"", (char *)wbxml_attribute_get_xml_name(atts[j]), (char *)wbxml_attribute_get_xml_value(atts[j]));
                strcat((char *)p, " ");
                strcat((char *)p, (char *)wbxml_attribute_get_xml_name(atts[j]));
                strcat((char *)p, "=");
@@ -105,11 +105,11 @@ static void _cb_parser_start_element(void* ctx, WBXMLTag* element, WBXMLAttribut
        }
 
        if (empty) {
-               EM_DEBUG_LOG("/>");
+               EM_DEBUG_LOG_SEC("/>");
                strcat((char *)p, "/>");
        }
        else {
-               EM_DEBUG_LOG(">");
+               EM_DEBUG_LOG_SEC(">");
                strcat((char *)p, ">");
        }
 
@@ -351,6 +351,7 @@ static int _get_emn_account(unsigned char *input_wbxml, int input_wbxml_length,
        unsigned char*  mbox_name = NULL;
        unsigned char*  auth_type = NULL;
        unsigned char*  time_stamp = NULL;
+       unsigned char   email_address[MAX_EMAIL_ADDRESS_LENGTH] = { 0, };
        int                             type = 0;
        int                             i = 0;
        int                             count = 0;
@@ -416,12 +417,15 @@ static int _get_emn_account(unsigned char *input_wbxml, int input_wbxml_length,
        EM_SAFE_FREE(elm);
 
        EM_DEBUG_LOG("user_type = [%d]", type);
-       EM_DEBUG_LOG("incoming_server_user_name = [%s]", (char *)incoming_server_user_name ? (char*)incoming_server_user_name : "NIL");
+       EM_DEBUG_LOG_SEC("incoming_server_user_name = [%s]", (char *)incoming_server_user_name ? (char*)incoming_server_user_name : "NIL");
        EM_DEBUG_LOG("host_addr = [%s]", (char *)host_addr ? (char*)host_addr : "NIL");
-       EM_DEBUG_LOG("mbox_name = [%s]", (char *)mbox_name ? (char*)mbox_name : "NIL");
+       EM_DEBUG_LOG_SEC("mbox_name = [%s]", (char *)mbox_name ? (char*)mbox_name : "NIL");
        EM_DEBUG_LOG("auth_type = [%s]", (char *)auth_type ? (char*)auth_type : "NIL");
        EM_DEBUG_LOG("time_stamp= [%s]", (char *)time_stamp? (char*)time_stamp: "NIL");
 
+       if(incoming_server_user_name && host_addr)
+               SNPRINTF((char*)email_address, MAX_EMAIL_ADDRESS_LENGTH, "%s@%s", incoming_server_user_name, host_addr);
+
        if (!emdaemon_get_account_list(&accounts, &count, &err)) {
                EM_DEBUG_EXCEPTION("EMAIL_ERROR_DB_FAILURE");
                err = EMAIL_ERROR_DB_FAILURE;
@@ -440,15 +444,14 @@ static int _get_emn_account(unsigned char *input_wbxml, int input_wbxml_length,
                        accounts[i].incoming_server_user_name  = (char*)EM_SAFE_STRDUP((char *)temp_account_name);
                }
                EM_SAFE_FREE(temp_account_name);
-               if (incoming_server_user_name)  {
-                       if (strcmp(accounts[i].incoming_server_user_name, (char *)incoming_server_user_name) == 0 &&
-                               strstr(accounts[i].user_email_address, (char *)host_addr)) {
+               if (incoming_server_user_name && host_addr)     {
+                       if (strstr(accounts[i].user_email_address, (char*)email_address)) {
                                EM_DEBUG_LOG(">>>> Account Match >>> ");
                                if ((type == 1) ||
                                        (type == 2 && accounts[i].incoming_server_type == EMAIL_SERVER_TYPE_POP3) ||
                                        (type == 3 && accounts[i].incoming_server_type == EMAIL_SERVER_TYPE_IMAP4)) {
                                        /* accounts[i].flag2 = type; */
-                                       EM_DEBUG_LOG("found target account id[%d] name[%s]", accounts[i].account_id, accounts[i].incoming_server_user_name);
+                                       EM_DEBUG_LOG_SEC("found target account id[%d] name[%s]", accounts[i].account_id, accounts[i].incoming_server_user_name);
                                        break;
                                }
                        }
@@ -503,7 +506,8 @@ static int emdaemon_handle_emn_notification(unsigned char* wbxml_b64, int input_
 {
        EM_DEBUG_FUNC_BEGIN("wbxml_b64[%p] input_body_lenth[%d]", wbxml_b64, input_body_lenth);
 
-       int err = EMAIL_ERROR_NONE;;
+       int err = EMAIL_ERROR_NONE;
+       int handle = 0;
        char* mailbox_name = NULL;
        email_account_t account = { 0 };
        emstorage_mailbox_tbl_t *mailbox_tbl = NULL;
@@ -532,7 +536,7 @@ static int emdaemon_handle_emn_notification(unsigned char* wbxml_b64, int input_
                }
        }
 
-       if (!emdaemon_sync_header(mailbox_tbl->account_id, mailbox_tbl->mailbox_id, NULL, &err))  {
+       if (!emdaemon_sync_header(mailbox_tbl->account_id, mailbox_tbl->mailbox_id, &handle, &err))  {
                EM_DEBUG_EXCEPTION("emdaemon_sync_header failed [%d]", err);
                goto FINISH_OFF;
        }
@@ -552,9 +556,9 @@ void oma_emn_push_cb(msg_handle_t input_handle, const char *input_push_header, c
        EM_DEBUG_FUNC_BEGIN("input_handle[%d] input_push_header[%p] input_push_body[%p] input_push_body_lenth[%d] input_user_param[%p]", input_handle, input_push_header, input_push_body, input_push_body_lenth, input_user_param);
        int err = EMAIL_ERROR_NONE;
 
-       EM_DEBUG_EXCEPTION("input_push_header [%s]", input_push_header);
-       EM_DEBUG_EXCEPTION("input_push_body [%s]", input_push_body);
-       EM_DEBUG_EXCEPTION("input_push_body_lenth [%d]", input_push_body_lenth);
+       EM_DEBUG_LOG("input_push_header [%s]", input_push_header);
+       EM_DEBUG_LOG("input_push_body [%s]", input_push_body);
+       EM_DEBUG_LOG("input_push_body_lenth [%d]", input_push_body_lenth);
 
        if((err = emdaemon_handle_emn_notification((unsigned char*)input_push_body, input_push_body_lenth)) != EMAIL_ERROR_NONE) {
                EM_DEBUG_EXCEPTION("emdaemon_handle_emn_notification failed [%d]", err);
@@ -595,7 +599,7 @@ static int emdaemon_register_wap_push_callback(msg_handle_t *input_msg_handle, c
        msg_add_push_event(*input_msg_handle, msg_struct);
 
        if ((msg_err = msg_reg_push_message_callback(*input_msg_handle, &oma_emn_push_cb, input_app_id, NULL)) != MSG_SUCCESS) {
-               EM_DEBUG_EXCEPTION("msg_reg_push_message_callback() for %s failed [%d]", msg_err, input_app_id);
+               EM_DEBUG_EXCEPTION_SEC("msg_reg_push_message_callback() for %s failed [%d]", msg_err, input_app_id);
                err = EMAIL_ERROR_INPROPER_RESPONSE_FROM_MSG_SERVICE;
                goto FINISH_OFF;
        }
index c75d1ab..073c1bd 100755 (executable)
 #include <stdlib.h>
 #include <string.h>
 #include <vconf.h>
+#include <vconf-keys.h>
+#include <glib.h>
+#include <glib-object.h>
+#include <sys/smack.h>
+#include <notification.h>
+#include <notification_type.h>
+
 #include "email-daemon.h"
 #include "email-daemon-account.h"
 #include "email-debug-log.h"
 #include "email-core-utils.h"
 #include "email-core-alarm.h"
 #include "email-core-smtp.h"
+#include "email-core-sound.h"
 #include "email-utilities.h"
 #include "email-storage.h"
+#include "email-ipc.h"
 
+extern pthread_mutex_t sound_mutex;
+extern pthread_cond_t sound_condition;
 
 int emdaemon_register_event_callback(email_action_t action, email_event_callback callback, void* event_data)
 {
@@ -312,6 +323,7 @@ INTERNAL_FUNC int emdaemon_search_mail_on_server(int input_account_id, int input
        int error = EMAIL_ERROR_NONE;
        int ret = false;
        char *criteria = NULL;
+       email_event_t *event_data = NULL;
        
        if (input_mailbox_id == 0 || input_account_id < 0) {
                EM_DEBUG_EXCEPTION("Invalid parameter");
@@ -319,22 +331,19 @@ INTERNAL_FUNC int emdaemon_search_mail_on_server(int input_account_id, int input
                return false;
        }
 
-       email_event_t event_data;
-
-       memset(&event_data, 0x00, sizeof(email_event_t));
-
        criteria = _make_criteria_to_search_filter(input_search_filter, input_search_filter_count, &error);
        if (criteria == NULL) {
                EM_DEBUG_EXCEPTION("_make_criteria_to_search_filter failed");
                goto FINISH_OFF;
        }
-               
-       event_data.type = EMAIL_EVENT_SEARCH_ON_SERVER;
-       event_data.account_id = input_account_id;
-       event_data.event_param_data_1 = EM_SAFE_STRDUP(criteria);
-       event_data.event_param_data_4 = input_mailbox_id;
 
-       if (!emcore_insert_event(&event_data, (int *)output_handle, &error)) {
+       event_data = em_malloc(sizeof(email_event_t));
+       event_data->type = EMAIL_EVENT_SEARCH_ON_SERVER;
+       event_data->account_id = input_account_id;
+       event_data->event_param_data_1 = EM_SAFE_STRDUP(criteria);
+       event_data->event_param_data_4 = input_mailbox_id;
+
+       if (!emcore_insert_event(event_data, (int *)output_handle, &error)) {
                EM_DEBUG_EXCEPTION("emcore_insert_event failed [%d]", error);
                error = EMAIL_ERROR_NONE;
                goto FINISH_OFF;
@@ -343,8 +352,10 @@ INTERNAL_FUNC int emdaemon_search_mail_on_server(int input_account_id, int input
        ret = true;
 
 FINISH_OFF:
-       if (!ret) {
-               EM_SAFE_FREE(event_data.event_param_data_1);
+
+       if (ret == false && event_data) {
+               emcore_free_event(event_data);
+               EM_SAFE_FREE(event_data);
        }
 
        EM_SAFE_FREE(criteria);
@@ -361,9 +372,9 @@ INTERNAL_FUNC int emdaemon_reschedule_sending_mail()
        EM_DEBUG_FUNC_BEGIN();
        int err = EMAIL_ERROR_NONE;
        char *conditional_clause_string = NULL;
-       email_list_filter_t filter_list[3];
+       email_list_filter_t filter_list[7];
        email_mail_list_item_t *result_mail_list = NULL;
-       int filter_rule_count = 3;
+       int filter_rule_count = 7;
        int result_mail_count = 0;
        int i = 0;
 
@@ -377,10 +388,24 @@ INTERNAL_FUNC int emdaemon_reschedule_sending_mail()
        filter_list[1].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_OPERATOR;
        filter_list[1].list_filter_item.operator_type                      = EMAIL_LIST_FILTER_OPERATOR_AND;
 
-       filter_list[2].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_RULE;
-       filter_list[2].list_filter_item.rule.target_attribute              = EMAIL_MAIL_ATTRIBUTE_SAVE_STATUS;
-       filter_list[2].list_filter_item.rule.rule_type                     = EMAIL_LIST_FILTER_RULE_EQUAL;
-       filter_list[2].list_filter_item.rule.key_value.integer_type_value  = EMAIL_MAIL_STATUS_SEND_SCHEDULED;
+       filter_list[2].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_OPERATOR;
+       filter_list[2].list_filter_item.operator_type                      = EMAIL_LIST_FILTER_OPERATOR_LEFT_PARENTHESIS;
+
+       filter_list[3].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_RULE;
+       filter_list[3].list_filter_item.rule.target_attribute              = EMAIL_MAIL_ATTRIBUTE_SAVE_STATUS;
+       filter_list[3].list_filter_item.rule.rule_type                     = EMAIL_LIST_FILTER_RULE_EQUAL;
+       filter_list[3].list_filter_item.rule.key_value.integer_type_value  = EMAIL_MAIL_STATUS_SEND_SCHEDULED;
+
+       filter_list[4].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_OPERATOR;
+       filter_list[4].list_filter_item.operator_type                      = EMAIL_LIST_FILTER_OPERATOR_OR;
+
+       filter_list[5].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_RULE;
+       filter_list[5].list_filter_item.rule.target_attribute              = EMAIL_MAIL_ATTRIBUTE_SAVE_STATUS;
+       filter_list[5].list_filter_item.rule.rule_type                     = EMAIL_LIST_FILTER_RULE_EQUAL;
+       filter_list[5].list_filter_item.rule.key_value.integer_type_value  = EMAIL_MAIL_STATUS_SEND_DELAYED;
+
+       filter_list[6].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_OPERATOR;
+       filter_list[6].list_filter_item.operator_type                      = EMAIL_LIST_FILTER_OPERATOR_RIGHT_PARENTHESIS;
 
        /* Get scheduled mail list */
        if( (err = emstorage_write_conditional_clause_for_getting_mail_list(filter_list, filter_rule_count, NULL, 0, -1, -1, &conditional_clause_string)) != EMAIL_ERROR_NONE) {
@@ -442,5 +467,174 @@ INTERNAL_FUNC int emdaemon_clear_all_mail_data(int* err_code)
        EM_DEBUG_FUNC_END();
     return ret;
 }
-       
+
+INTERNAL_FUNC int emdaemon_kill_daemon_if_no_account()
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int err = EMAIL_ERROR_NONE;
+       email_account_t *account_list = NULL;
+       int account_count = 0;
+
+       if (!emcore_get_account_reference_list(&account_list, &account_count, &err)) {
+               EM_DEBUG_LOG("emcore_get_account_reference_list failed [%d]", err);
+       }
+
+       EM_DEBUG_LOG("account_count [%d]", account_count);
+
+       if (account_count == 0) {
+               EM_DEBUG_LOG("kill email-service daemon");
+               exit(44); /* exit with exit code 44 to prevent restarting */
+       }
+
+       if(account_list)
+               emcore_free_account_list(&account_list, account_count, NULL);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC int emdaemon_check_smack_rule(int app_sockfd, char *file_path)
+{
+       EM_DEBUG_FUNC_BEGIN_SEC("app_sockfd[%d], file_path[%s]", app_sockfd, file_path);
+
+       if (app_sockfd <= 0 || !file_path) {
+               EM_DEBUG_LOG("Invalid parameter");
+               return false;
+       }
+
+       char *app_label = NULL;
+       char *file_label = NULL;
+       char *real_file_path = NULL;
+       int ret = 0;
+       int result = false;
+
+       static int have_smack = -1;
+
+       if (-1 == have_smack) {
+               if (NULL == smack_smackfs_path()) {
+                       have_smack = 0;
+               } else {
+                       have_smack = 1;
+               }
+       }
+
+       if(!have_smack) {
+               EM_DEBUG_LOG("smack is disabled");
+               result = true;
+               goto FINISH_OFF;
+       }
+
+       /* Smack is enabled */
+
+       ret = smack_new_label_from_socket(app_sockfd, &app_label);
+       if (ret < 0) {
+               EM_DEBUG_LOG("smack_new_label_from_socket failed");
+               result = false;
+               goto FINISH_OFF;
+       }
+
+       real_file_path = realpath(file_path, NULL);
+       if (!real_file_path) {
+               EM_DEBUG_LOG("realpath failed");
+               result = false;
+               goto FINISH_OFF;
+       }
+
+       ret = smack_getlabel(real_file_path, &file_label, SMACK_LABEL_ACCESS);
+       if (ret < 0) {
+               EM_DEBUG_LOG("smack_getlabel failed");
+               result = false;
+               goto FINISH_OFF;
+       }
+
+       EM_DEBUG_LOG("APP_LABEL[%s], FILE_LABEL[%s]", app_label, file_label);
+
+       ret = smack_have_access(app_label, file_label, "r");
+       if (ret == 0) {
+               /* Access Denied */
+               result = false;
+               goto FINISH_OFF;
+       }
+
+       /* Access granted */
+       result = true;
+
+FINISH_OFF:
+
+       EM_SAFE_FREE(app_label);
+       EM_SAFE_FREE(file_label);
+       EM_SAFE_FREE(real_file_path);
+
+       EM_DEBUG_FUNC_END();
+       return result;
+}
+
+INTERNAL_FUNC int emdaemon_set_smack_label(char *file_path, char *label)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int ret = 0;
+       int result = true;
+
+       if ((ret = smack_setlabel(file_path, label, SMACK_LABEL_ACCESS)) < 0) {
+               EM_DEBUG_LOG("smack_setlabel failed");
+               result = false;
+       }
+
+       EM_DEBUG_FUNC_END();
+       return result;
+}
+
+INTERNAL_FUNC int emdaemon_finalize_sync(int account_id, int total_mail_count, int unread_mail_count, int *error)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id [%d], total_mail_count [%d], unread_mail_count [%d], error [%p]", account_id, total_mail_count, unread_mail_count, error);
+       int err = EMAIL_ERROR_NONE, ret = true, result_sync_status = SYNC_STATUS_FINISHED;
+       int topmost = false;
+
+       if ((err = emcore_update_sync_status_of_account(account_id, SET_TYPE_MINUS, SYNC_STATUS_SYNCING)) != EMAIL_ERROR_NONE)
+               EM_DEBUG_EXCEPTION("emcore_update_sync_status_of_account failed [%d]", err);
+
+       if (!emstorage_get_sync_status_of_account(ALL_ACCOUNT, &result_sync_status, &err))
+               EM_DEBUG_EXCEPTION("emstorage_get_sync_status_of_account failed [%d]", err);
+
+       /* Check the topmost of email app */
+       if (vconf_get_int(VCONF_KEY_TOPMOST_WINDOW, &topmost) != 0) {
+               EM_DEBUG_EXCEPTION("vconf_get_int failed");
+       }
+
+       if (result_sync_status == SYNC_STATUS_SYNCING) {
+               if (topmost) {
+                       EM_DEBUG_LOG("The email app is topmost");
+               } else {
+                       if ((err = emcore_add_notification(account_id, 0, total_mail_count, 0, EMAIL_ERROR_NONE, NOTIFICATION_DISPLAY_APP_ALL^NOTIFICATION_DISPLAY_APP_TICKER)) != EMAIL_ERROR_NONE)
+                               EM_DEBUG_EXCEPTION("emcore_add_notification failed : [%d]", err);
+               }
+       } else if (result_sync_status == SYNC_STATUS_HAVE_NEW_MAILS) {
+               if (topmost) {
+                       EM_DEBUG_LOG("The email app is topmost");
+               } else {
+
+                       if ((err = emcore_add_notification(account_id, 0, total_mail_count, 1, EMAIL_ERROR_NONE, NOTIFICATION_DISPLAY_APP_ALL)) != EMAIL_ERROR_NONE)
+                               EM_DEBUG_EXCEPTION("emcore_add_notification failed : [%d]", err);
+
+#ifdef __FEATURE_BLOCKING_MODE__
+                       emcore_set_blocking_mode_status(false);
+#endif /* __FEATURE_BLOCKING_MODE__ */
+
+                       if ((err = emcore_start_driving_mode(account_id)) != EMAIL_ERROR_NONE) {
+                               EM_DEBUG_EXCEPTION("emcore_start_driving_mode failed : [%d]", err);
+                       }
+               }
+
+               if (!emcore_display_unread_in_badge())
+                       EM_DEBUG_EXCEPTION("emcore_display_unread_in_badge failed");
+
+               if ((err = emcore_update_sync_status_of_account(account_id, SET_TYPE_MINUS, SYNC_STATUS_HAVE_NEW_MAILS)) != EMAIL_ERROR_NONE)
+                       EM_DEBUG_EXCEPTION("emcore_update_sync_status_of_account failed [%d]", err);
+       } else {
+               EM_DEBUG_LOG("sync status : [%d]", result_sync_status);
+       }
+
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
 /* --------------------------------------------------------------------------------*/
index bb33235..c54aa02 100755 (executable)
 #include <vconf.h>
 #include <vconf-internal-account-keys.h>
 #include <dbus/dbus.h>
-#include <dlfcn.h>           /* added for Disabling the Pthread flag log */
+#include <dlfcn.h>                             /* added for Disabling the Pthread flag log */
 
 #include "email-daemon.h"
 #include "email-storage.h"
 #include "email-debug-log.h"
+#include "email-daemon-init.h"
 #include "email-daemon-account.h"
-#include "email-daemon-auto-poll.h"   
+#include "email-daemon-auto-poll.h"
+#include "email-daemon-event.h"
 #include "email-core-utils.h"
 #include "email-core-mail.h"
 #include "email-core-event.h" 
-#include "email-core-account.h"    
-#include "email-core-mailbox.h"    
-#include "email-core-api.h"
-#include "email-core-smtp.h"    
+#include "email-core-account.h"
+#include "email-core-mailbox.h"
+#include "email-core-smtp.h"
 #include "email-core-global.h"
-#include "email-storage.h"   
+#include "email-storage.h"
 #include "email-core-sound.h" 
 #include "email-core-task-manager.h"
+#include "email-core-alarm.h"
 #include "email-daemon-emn.h"
+#include "email-network.h"
+#include "email-device.h"
+#include "c-client.h"
+
+extern void *
+pop3_parameters(long function, void *value);
+extern void *
+imap_parameters(long function, void *value);
+
+INTERNAL_FUNC int g_client_count = 0;
+extern int blocking_mode_of_setting;
+extern GList *alarm_data_list;
 
-extern int g_client_count ;
+static int default_alarm_callback(int input_timer_id, void *user_parameter);
 
 /*  static functions */
 static int _emdaemon_load_email_core()
@@ -68,13 +82,13 @@ static int _emdaemon_load_email_core()
        int err = EMAIL_ERROR_NONE;
 
        /* initialize mail core */
-       if (!emcore_init(&err))
+       if (!emdaemon_core_init(&err))
                goto FINISH_OFF;
 
-       if (emcore_start_event_loop(&err) < 0)
+       if (emdaemon_start_event_loop(&err) < 0)
                goto FINISH_OFF;
 
-       if (emcore_start_event_loop_for_sending_mails(&err) < 0)
+       if (emdaemon_start_event_loop_for_sending_mails(&err) < 0)
                goto FINISH_OFF;
 
        emcore_init_task_handler_array();
@@ -87,19 +101,16 @@ static int _emdaemon_load_email_core()
        */
 
 #ifdef __FEATURE_PARTIAL_BODY_DOWNLOAD__
-       if (emcore_start_thread_for_downloading_partial_body(&err) < 0) {
+       if (emdaemon_start_thread_for_downloading_partial_body(&err) < 0) {
                EM_DEBUG_EXCEPTION("emcore_start_thread_for_downloading_partial_body failed [%d]",err);
                goto FINISH_OFF;
        }
 #endif
 
 #ifdef __FEATURE_BLOCKING_MODE__
-       emcore_init_blocking_mode_status();
+       emdaemon_init_blocking_mode_status();
 #endif /* __FEATURE_BLOCKING_MODE__ */
 
-       if (emcore_start_thread_for_alerting_new_mails(&err) < 0)
-               goto FINISH_OFF;
-
 FINISH_OFF:
 
        return err;
@@ -148,7 +159,7 @@ static void callback_for_SYNC_ALL_STATUS_from_account_svc(keynode_t *input_node,
                                EM_DEBUG_EXCEPTION("emdaemon_sync_header for [%d] failed [%d]", account_list[i].account_id, err);
                        }
 
-                       emstorage_free_mailbox(&mailbox_tbl_data, 1, NULL); /* prevent 27459: remove unnecesary if clause */
+                       emstorage_free_mailbox(&mailbox_tbl_data, 1, NULL); /* prevent 27459: remove unnecessary if clause */
                        mailbox_tbl_data = NULL;
                }
                else {
@@ -314,6 +325,113 @@ static void callback_for_VCONFKEY_MSG_SERVER_READY(keynode_t *input_node, void *
        return;
 }
 
+static void callback_for_VCONFKEY_GLOBAL_BADGE_STATUS(keynode_t *input_node, void *input_user_data)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int noti_status = 0;
+       int err = EMAIL_ERROR_NONE;
+       int badge_ticker = 0;
+
+       if (!input_node) {
+               EM_DEBUG_EXCEPTION("Invalid param");
+               return;
+       }
+
+       noti_status = vconf_keynode_get_bool(input_node);
+
+       if (noti_status) {
+               if (!emcore_display_unread_in_badge()) 
+                       EM_DEBUG_EXCEPTION("emcore_display_unread_in_badge failed");
+       } else {
+               if (vconf_get_bool(VCONF_VIP_NOTI_BADGE_TICKER, &badge_ticker) != 0) {
+                       EM_DEBUG_EXCEPTION("vconf_get_bool failed");
+                       err = EMAIL_ERROR_GCONF_FAILURE;
+                       goto FINISH_OFF;
+               }
+               /* if priority sender is on, show the priority sender unread */
+               if (badge_ticker) {
+                       if (!emcore_display_unread_in_badge()) 
+                               EM_DEBUG_EXCEPTION("emcore_display_unread_in_badge failed");
+                       goto FINISH_OFF;
+               }
+
+               /* reset badge */
+               if ((err = emcore_display_badge_count(0)) != EMAIL_ERROR_NONE) 
+                       EM_DEBUG_EXCEPTION("emcore_display_badge_count failed : [%d]", err);
+       }
+
+FINISH_OFF:
+       EM_DEBUG_FUNC_END();
+}
+
+
+static void callback_for_VCONFKEY_PRIORITY_BADGE_STATUS(keynode_t *input_node, void *input_user_data)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int noti_status = 0;
+       int err = EMAIL_ERROR_NONE;
+       int badge_ticker = 0;
+
+       if (!input_node) {
+               EM_DEBUG_EXCEPTION("Invalid param");
+               return;
+       }
+
+       noti_status = vconf_keynode_get_bool(input_node);
+
+       if (noti_status) {
+               if (!emcore_display_unread_in_badge()) 
+                       EM_DEBUG_EXCEPTION("emcore_display_unread_in_badge failed");
+       } else {
+
+               if (vconf_get_bool(VCONFKEY_TICKER_NOTI_BADGE_EMAIL, &badge_ticker) != 0) {
+                       EM_DEBUG_EXCEPTION("vconf_get_bool failed");
+                       err = EMAIL_ERROR_GCONF_FAILURE;
+                       goto FINISH_OFF;
+               }
+
+               /*if global badge is on, show the global unread*/
+               if (badge_ticker) {
+                       if (!emcore_display_unread_in_badge()) 
+                               EM_DEBUG_EXCEPTION("emcore_display_unread_in_badge failed");
+                       goto FINISH_OFF;
+               }
+               /* if all badges are off, reset badge count */
+               if ((err = emcore_display_badge_count(0)) != EMAIL_ERROR_NONE) 
+                       EM_DEBUG_EXCEPTION("emcore_display_badge_count failed : [%d]", err);
+       }
+
+FINISH_OFF:
+       EM_DEBUG_FUNC_END();
+}
+
+static void callback_for_VCONFKEY_TELEPHONY_ZONE_TYPE(keynode_t *input_node, void *input_user_data)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int telephony_zone = 0;
+
+       if (!input_node) {
+               EM_DEBUG_EXCEPTION("Invalid param");
+               return;
+       }
+
+       telephony_zone = vconf_keynode_get_int(input_node);
+
+       EM_DEBUG_LOG("telephony_zone [%d]", telephony_zone);
+
+       /*
+       switch(telephony_zone) {
+       case VCONFKEY_TELEPHONY_ZONE_NONE :
+       case VCONFKEY_TELEPHONY_ZONE_HOME :
+       case VCONFKEY_TELEPHONY_ZONE_CITY :
+       default :
+               break;
+       }
+       */
+
+       EM_DEBUG_FUNC_END();
+}
+
 INTERNAL_FUNC int emdaemon_initialize(int* err_code)
 {
        EM_DEBUG_FUNC_BEGIN();
@@ -356,7 +474,7 @@ INTERNAL_FUNC int emdaemon_initialize(int* err_code)
                err = EMAIL_ERROR_DB_FAILURE;
                goto FINISH_OFF;
        }
-    EM_DEBUG_LOG("emdaemon_initialize_account_reference over - g_client_count [%d]", g_client_count);  
+       EM_DEBUG_LOG("emdaemon_initialize_account_reference over - g_client_count [%d]", g_client_count);
        
        if ((err = _emdaemon_load_email_core()) != EMAIL_ERROR_NONE)  {
                EM_DEBUG_EXCEPTION("_emdaemon_load_email_core failed [%d]", err);
@@ -369,13 +487,27 @@ INTERNAL_FUNC int emdaemon_initialize(int* err_code)
        }
 #endif
 
+#ifdef __FEATURE_AUTO_RETRY_SEND__
+       if ((err = emcore_create_alarm_for_auto_resend (AUTO_RESEND_INTERVAL)) != EMAIL_ERROR_NONE) {
+               if (err == EMAIL_ERROR_MAIL_NOT_FOUND)
+                       EM_DEBUG_LOG ("no mail found");
+               else
+                       EM_DEBUG_EXCEPTION("emcore_create_alarm_for_auto_resend failed [%d]", err);
+       }
+#endif /* __FEATURE_AUTO_RETRY_SEND__ */
+
        /* Subscribe Events */
-       vconf_notify_key_changed(VCONFKEY_ACCOUNT_SYNC_ALL_STATUS_INT,  callback_for_SYNC_ALL_STATUS_from_account_svc,  NULL);
-       vconf_notify_key_changed(VCONFKEY_ACCOUNT_AUTO_SYNC_STATUS_INT, callback_for_AUTO_SYNC_STATUS_from_account_svc, NULL);
+
        vconf_notify_key_changed(VCONFKEY_NETWORK_STATUS, callback_for_NETWORK_STATUS, NULL);
 #ifdef __FEATURE_BLOCKING_MODE__
-       vconf_notify_key_changed(VCONFKEY_NETWORK_STATUS, callback_for_BLOCKING_MODE_STATUS, NULL);
+       vconf_notify_key_changed(VCONFKEY_SETAPPL_BLOCKINGMODE_NOTIFICATIONS, callback_for_BLOCKING_MODE_STATUS, NULL);
 #endif
+       vconf_notify_key_changed(VCONFKEY_TICKER_NOTI_BADGE_EMAIL, callback_for_VCONFKEY_GLOBAL_BADGE_STATUS, NULL);
+
+       vconf_notify_key_changed(VCONF_VIP_NOTI_BADGE_TICKER, callback_for_VCONFKEY_PRIORITY_BADGE_STATUS, NULL);
+       /* VCONFKEY_TELEPHONY_SVC_ROAM */
+       /*vconf_notify_key_changed(VCONFKEY_TELEPHONY_ZONE_TYPE, callback_for_VCONFKEY_TELEPHONY_ZONE_TYPE, NULL);*/
+       
        emcore_display_unread_in_badge();
        
        ret = true;
@@ -449,8 +581,8 @@ INTERNAL_FUNC int emdaemon_start_auto_polling(int* err_code)
 
        for (i = 0; i < count; i++)  {
                /* start auto polling, if check_interval not zero */
-               if(account_list[i].check_interval > 0) {
-                       if(!emdaemon_add_polling_alarm( account_list[i].account_id,account_list[i].check_interval))
+               if(account_list[i].check_interval > 0 || (account_list[i].peak_days && account_list[i].peak_interval > 0)) {
+                       if(!emdaemon_add_polling_alarm( account_list[i].account_id))
                                EM_DEBUG_EXCEPTION("emdaemon_add_polling_alarm failed");
                }
        }
@@ -463,7 +595,128 @@ FINISH_OFF:
        if (err_code != NULL)
                *err_code = err;
        
+       EM_DEBUG_FUNC_END("ret[%d]", ret);
        return ret;
 }
 #endif /* __FEATURE_AUTO_POLLING__ */
 
+/* initialize mail core */
+INTERNAL_FUNC int emdaemon_core_init(int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       if (err_code != NULL) {
+               *err_code = EMAIL_ERROR_NONE;
+       }
+
+       mail_link(&imapdriver);    /*  link in the imap driver  */
+       mail_link(&pop3driver);    /*  link in the pop3 driver  */
+
+       mail_link(&unixdriver);    /*  link in the unix driver  */
+       mail_link(&dummydriver);   /*  link in the dummy driver  */
+
+       ssl_onceonlyinit();
+
+       auth_link(&auth_xoauth2);  /*  link in the xoauth2 authenticator  */
+       auth_link(&auth_md5);      /*  link in the md5 authenticator  */
+       auth_link(&auth_pla);      /*  link in the pla authenticator  */
+       auth_link(&auth_log);      /*  link in the log authenticator  */
+
+       /* Disabled to authenticate with plain text */
+       mail_parameters(NIL, SET_DISABLEPLAINTEXT, (void *) 2);
+
+       /* Set max trials for login */
+       imap_parameters(SET_MAXLOGINTRIALS, (void *)3);
+       pop3_parameters(SET_MAXLOGINTRIALS, (void *)3);
+       smtp_parameters(SET_MAXLOGINTRIALS, (void *)3);
+
+       mail_parameters(NIL, SET_SSLCERTIFICATEQUERY, (void *)emnetwork_callback_ssl_cert_query);
+       mail_parameters(NIL, SET_SSLCAPATH, (void *)SSL_CERT_DIRECTORY);
+
+       /* Set time out in second */
+       mail_parameters(NIL, SET_OPENTIMEOUT  , (void *)50);
+       mail_parameters(NIL, SET_READTIMEOUT  , (void *)180);
+       mail_parameters(NIL, SET_WRITETIMEOUT , (void *)180);
+       mail_parameters(NIL, SET_CLOSETIMEOUT , (void *)30);
+
+       emdaemon_init_alarm_data_list();
+
+       if (err_code)
+               *err_code = EMAIL_ERROR_NONE;
+
+       return true;
+}
+
+#ifdef __FEATURE_BLOCKING_MODE__
+INTERNAL_FUNC bool emdaemon_init_blocking_mode_status()
+{
+       EM_DEBUG_FUNC_BEGIN("blocking_mode_of_setting : [%d]", blocking_mode_of_setting);
+
+       /*if (vconf_get_bool(VCONFKEY_SETAPPL_BLOCKINGMODE_NOTIFICATIONS, &blocking_mode_of_setting) != 0) {
+               EM_DEBUG_EXCEPTION("vconf_get_bool failed");
+               return false;
+       }*/
+
+       EM_DEBUG_FUNC_END();
+       return false;
+}
+#endif
+
+INTERNAL_FUNC int emdaemon_init_alarm_data_list()
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int ret = ALARMMGR_RESULT_SUCCESS;
+       int err = EMAIL_ERROR_NONE;
+       alarm_data_list = NULL;
+
+       if ((ret = alarmmgr_init(EMAIL_ALARM_DESTINATION)) != ALARMMGR_RESULT_SUCCESS) {
+               EM_DEBUG_EXCEPTION("alarmmgr_init failed [%d]",ret);
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       if ((ret = alarmmgr_set_cb(default_alarm_callback, NULL)) != ALARMMGR_RESULT_SUCCESS) {
+               EM_DEBUG_EXCEPTION("alarmmgr_set_cb() failed [%d]", ret);
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+FINISH_OFF:
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+static int default_alarm_callback(int input_timer_id, void *user_parameter)
+{
+       EM_DEBUG_FUNC_BEGIN("input_timer_id [%d] user_parameter [%p]", input_timer_id, user_parameter);
+       int err = EMAIL_ERROR_NONE;
+       email_alarm_data_t *alarm_data = NULL;
+
+       EM_DEBUG_ALARM_LOG("default_alarm_callback input_timer_id[%d]", input_timer_id);
+
+       emdevice_set_sleep_on_off(false, NULL);
+
+       if ((err = emcore_get_alarm_data_by_alarm_id(input_timer_id, &alarm_data)) != EMAIL_ERROR_NONE || alarm_data == NULL) {
+               EM_DEBUG_EXCEPTION("emcore_get_alarm_data_by_alarm_id failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if ((err = alarm_data->alarm_callback(input_timer_id, user_parameter)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("alarm_callback failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       emcore_delete_alram_data_from_alarm_data_list(alarm_data);
+       EM_SAFE_FREE(alarm_data);
+
+FINISH_OFF:
+
+       if(err != EMAIL_ERROR_NONE) {
+               emdevice_set_sleep_on_off(true, NULL);
+       }
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
index 4ed1b6a..f422ac5 100755 (executable)
@@ -67,7 +67,7 @@ INTERNAL_FUNC int emdaemon_send_mail(int mail_id, int *handle, int* err_code)
 
        int ret = false, err = EMAIL_ERROR_NONE, err_2 = EMAIL_ERROR_NONE;
        int  result_handle = 0, account_id = 0;
-       email_event_t event_data = { 0, };
+       email_event_t *event_data = NULL;
        emstorage_mail_tbl_t* mail_table_data = NULL;
        emstorage_mailbox_tbl_t* local_mailbox = NULL;
        email_account_t* ref_account = NULL;
@@ -130,12 +130,13 @@ INTERNAL_FUNC int emdaemon_send_mail(int mail_id, int *handle, int* err_code)
                goto FINISH_OFF;
        }
 
-       event_data.type               = EMAIL_EVENT_SEND_MAIL;
-       event_data.account_id         = account_id;
-       event_data.event_param_data_4 = mail_id;
-       event_data.event_param_data_5 = mail_table_data->mailbox_id;
+       event_data = em_malloc(sizeof(email_event_t));
+       event_data->type               = EMAIL_EVENT_SEND_MAIL;
+       event_data->account_id         = account_id;
+       event_data->event_param_data_4 = mail_id;
+       event_data->event_param_data_5 = mail_table_data->mailbox_id;
 
-       if (!emcore_insert_event_for_sending_mails(&event_data, &result_handle, &err)) {
+       if (!emcore_insert_event_for_sending_mails(event_data, &result_handle, &err)) {
                EM_DEBUG_EXCEPTION(" emcore_insert_event failed [%d]", err);
                goto FINISH_OFF;
        }
@@ -157,7 +158,10 @@ FINISH_OFF:
                if(!emstorage_set_field_of_mails_with_integer_value(account_id, &mail_id, 1, "save_status", EMAIL_MAIL_STATUS_SAVED, true, &err))
                        EM_DEBUG_EXCEPTION("emstorage_set_field_of_mails_with_integer_value [%d]",err);
 
-               EM_SAFE_FREE(event_data.event_param_data_3);
+               if (event_data) {
+                       emcore_free_event(event_data);
+                       EM_SAFE_FREE(event_data);
+               }
        }
 
        if (ref_account) {
@@ -187,11 +191,11 @@ INTERNAL_FUNC int emdaemon_send_mail_saved(int account_id, int *handle, int* err
 
        int ret = false;
        int err = EMAIL_ERROR_NONE;
-       email_event_t event_data = { 0 , };
-       email_account_tref_account = NULL;
+       email_event_t *event_data = NULL;
+       email_account_t *ref_account = NULL;
        char *mailbox_name = NULL;
 
-       if (account_id <= 0)  {
+       if (account_id <= 0) {
                EM_DEBUG_EXCEPTION("account_id = %d", account_id);
                err = EMAIL_ERROR_INVALID_PARAM;
                goto FINISH_OFF;
@@ -199,22 +203,23 @@ INTERNAL_FUNC int emdaemon_send_mail_saved(int account_id, int *handle, int* err
 
        ref_account = emcore_get_account_reference(account_id);
 
-       if (!ref_account)  {
+       if (!ref_account) {
                EM_DEBUG_EXCEPTION("emcore_get_account_reference failed [%d]", account_id);
                err = EMAIL_ERROR_INVALID_ACCOUNT;
                goto FINISH_OFF;
        }
 
-       if (!emstorage_get_mailbox_name_by_mailbox_type(account_id,EMAIL_MAILBOX_TYPE_OUTBOX,&mailbox_name, false, &err))  {
+       if (!emstorage_get_mailbox_name_by_mailbox_type(account_id,EMAIL_MAILBOX_TYPE_OUTBOX,&mailbox_name, false, &err)) {
                EM_DEBUG_EXCEPTION("emstorage_get_mailbox_name_by_mailbox_type failed [%d]", err);
                goto FINISH_OFF;
        }
 
-       event_data.type               = EMAIL_EVENT_SEND_MAIL_SAVED;
-       event_data.account_id         = account_id;
-       event_data.event_param_data_3 = EM_SAFE_STRDUP(mailbox_name);
+       event_data = em_malloc(sizeof(email_event_t));
+       event_data->type               = EMAIL_EVENT_SEND_MAIL_SAVED;
+       event_data->account_id         = account_id;
+       event_data->event_param_data_3 = EM_SAFE_STRDUP(mailbox_name);
 
-       if (!emcore_insert_event(&event_data, (int*)handle, &err))  {
+       if (!emcore_insert_event(event_data, (int*)handle, &err)) {
                EM_DEBUG_EXCEPTION("emcore_insert_event failed [%d]", err);
                goto FINISH_OFF;
        }
@@ -222,8 +227,10 @@ INTERNAL_FUNC int emdaemon_send_mail_saved(int account_id, int *handle, int* err
        ret = true;
 
 FINISH_OFF:
-       if (ret == false)  {
-               EM_SAFE_FREE(event_data.event_param_data_3);
+
+       if (ret == false && event_data) {
+               emcore_free_event(event_data);
+               EM_SAFE_FREE(event_data);
        }
 
        if (ref_account) {
@@ -244,10 +251,11 @@ INTERNAL_FUNC int emdaemon_add_mail(email_mail_data_t *input_mail_data, email_at
 {
        EM_DEBUG_FUNC_BEGIN("input_mail_data[%p], input_attachment_data_list[%p], input_attachment_count [%d], input_meeting_req [%p], input_from_eas[%d]", input_mail_data, input_attachment_data_list, input_attachment_count, input_meeting_request, input_from_eas);
 
-       int         err = EMAIL_ERROR_NONE;
-       int         handle = 0;
-       email_event_t event_data = { 0 };
-       email_account_t* ref_account = NULL;
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       int handle = 0;
+       email_event_t *event_data = NULL;
+       email_account_t *ref_account = NULL;
 
        if (!input_mail_data || input_mail_data->account_id <= 0 ||
                ( ((input_mail_data->report_status & EMAIL_MAIL_REPORT_MDN) != 0) && !input_mail_data->full_address_to))  {
@@ -263,32 +271,41 @@ INTERNAL_FUNC int emdaemon_add_mail(email_mail_data_t *input_mail_data, email_at
                goto FINISH_OFF;
        }
 
-       if ((err = emcore_add_mail(input_mail_data, input_attachment_data_list, input_attachment_count, input_meeting_request, input_from_eas)) != EMAIL_ERROR_NONE) {
+       if ((err = emcore_add_mail(input_mail_data, input_attachment_data_list, input_attachment_count, input_meeting_request, input_from_eas, false)) != EMAIL_ERROR_NONE) {
                EM_DEBUG_EXCEPTION("emcore_add_mail failed [%d]", err);
                goto FINISH_OFF;
        }
 
 #ifdef __FEATURE_SYNC_CLIENT_TO_SERVER__
        if ( input_from_eas == 0 && ref_account->incoming_server_type == EMAIL_SERVER_TYPE_IMAP4) {
-               event_data.type               = EMAIL_EVENT_SAVE_MAIL;
-               event_data.account_id         = input_mail_data->account_id;
-               event_data.event_param_data_4 = input_mail_data->mail_id;
+               event_data = em_malloc(sizeof(email_event_t));
+               event_data->type               = EMAIL_EVENT_SAVE_MAIL;
+               event_data->account_id         = input_mail_data->account_id;
+               event_data->event_param_data_4 = input_mail_data->mail_id;
 
-               if (!emcore_insert_event(&event_data, &handle, &err))  {
+               if (!emcore_insert_event(event_data, &handle, &err)) {
                        EM_DEBUG_EXCEPTION("emcore_insert_event failed [%d]", err);
                        goto FINISH_OFF;
                }
        }
 #endif
 
+       ret = true;
+
 FINISH_OFF:
 
+       if (ret == false && event_data) {
+               emcore_free_event(event_data);
+               EM_SAFE_FREE(event_data);
+       }
+
        if (ref_account) {
                emcore_free_account(ref_account);
                EM_SAFE_FREE(ref_account);
        }
 
        EM_DEBUG_FUNC_END("err [%d]", err);
+
        return err;
 }
 
@@ -327,30 +344,27 @@ INTERNAL_FUNC int emdaemon_download_body(int account_id, int mail_id, int verbos
 {
        EM_DEBUG_FUNC_BEGIN("account_id[%d], mail_id[%d], verbose[%d], with_attachment[%d], handle[%p], err_code[%p]", account_id, mail_id, verbose, with_attachment,  handle, err_code);
 
-       /*  default variable */
        int ret = false;
        int err = EMAIL_ERROR_NONE;
-/*     mpNewMail_StopAlertSound(); */
+       email_event_t *event_data = NULL;
 
-       if (!_emdaemon_check_mail_id(mail_id, &err))  {
+       if (!_emdaemon_check_mail_id(mail_id, &err)) {
                EM_DEBUG_EXCEPTION("_emdaemon_check_mail_id failed [%d]", err);
                goto FINISH_OFF;
        }
 
-       email_event_t event_data;
-
-       memset(&event_data, 0x00, sizeof(email_event_t));
-
-       event_data.type = EMAIL_EVENT_DOWNLOAD_BODY;
-       event_data.event_param_data_4 = mail_id;
-       event_data.account_id = account_id;
-       event_data.event_param_data_3 = GINT_TO_POINTER(verbose << 1 | with_attachment);
+       event_data = em_malloc(sizeof(email_event_t));
+       event_data->type = EMAIL_EVENT_DOWNLOAD_BODY;
+       event_data->account_id = account_id;
+       event_data->event_param_data_4 = mail_id;
+       event_data->event_param_data_5 = (verbose << 1 | with_attachment);
 
-       if (!emcore_insert_event(&event_data, (int*)handle, &err))  {
+       if (!emcore_insert_event(event_data, (int*)handle, &err)) {
                EM_DEBUG_EXCEPTION("emcore_insert_event failed [%d]", err);
                err = EMAIL_ERROR_DB_FAILURE;
                goto FINISH_OFF;
        }
+
 #ifdef __FEATURE_LOCAL_ACTIVITY__
        EM_DEBUG_LOG("Setting g_local_activity_run ");
        g_local_activity_run = 1;
@@ -358,9 +372,17 @@ INTERNAL_FUNC int emdaemon_download_body(int account_id, int mail_id, int verbos
        ret = true;
 
 FINISH_OFF:
+
+       if (ret == false && event_data) {
+               emcore_free_event(event_data);
+               EM_SAFE_FREE(event_data);
+       }
+
        if (err_code)
                *err_code = err;
+
        EM_DEBUG_FUNC_END();
+
        return ret;
 }
 
@@ -386,9 +408,12 @@ int emdaemon_get_attachment(int attachment_id, email_attachment_data_t** attachm
        ret = true;
 
 FINISH_OFF:
+
        if (err_code)
                *err_code = err;
+
        EM_DEBUG_FUNC_END();
+
        return ret;
 }
 
@@ -411,17 +436,20 @@ int emdaemon_add_attachment(int mail_id, email_attachment_data_t* attachment, in
                goto FINISH_OFF;
        }
 
-       if (!emcore_mail_add_attachment(mail_id, attachment, &err))  {
-               EM_DEBUG_EXCEPTION(" emcore_mail_add_attachment failed [%d]", err);
+       if (!emcore_add_attachment(mail_id, attachment, &err))  {
+               EM_DEBUG_EXCEPTION(" emcore_add_attachment failed [%d]", err);
                goto FINISH_OFF;
        }
 
        ret = true;
 
 FINISH_OFF:
+
        if (err_code)
                *err_code = err;
+
        EM_DEBUG_FUNC_END();
+
        return ret;
 }
 
@@ -447,9 +475,12 @@ int emdaemon_delete_mail_attachment(int attachment_id, int* err_code)
        ret = true;
 
 FINISH_OFF:
+
        if (err_code)
                *err_code = err;
+
        EM_DEBUG_FUNC_END();
+
        return ret;
 }
 
@@ -459,28 +490,26 @@ INTERNAL_FUNC int emdaemon_download_attachment(int account_id, int mail_id, int
 
        int ret = false;
        int err = EMAIL_ERROR_NONE;
+       email_event_t *event_data = NULL;
 
-       if (!nth)  {
+       if (!nth) {
                EM_DEBUG_EXCEPTION("nth[%p] is invalid", nth);
                err = EMAIL_ERROR_INVALID_PARAM;
                goto FINISH_OFF;
        }
 
-       if (!_emdaemon_check_mail_id(mail_id, &err))  {
+       if (!_emdaemon_check_mail_id(mail_id, &err)) {
                EM_DEBUG_EXCEPTION("_emdaemon_check_mail_id failed [%d]", err);
                goto FINISH_OFF;
        }
 
-       email_event_t event_data;
-
-       memset(&event_data, 0x00, sizeof(email_event_t));
+       event_data = em_malloc(sizeof(email_event_t));
+       event_data->type = EMAIL_EVENT_DOWNLOAD_ATTACHMENT;
+       event_data->account_id         = account_id;
+       event_data->event_param_data_4 = mail_id;
+       event_data->event_param_data_5 = nth;
 
-       event_data.type = EMAIL_EVENT_DOWNLOAD_ATTACHMENT;
-       event_data.account_id         = account_id;
-       event_data.event_param_data_4 = mail_id;
-       event_data.event_param_data_5 = nth;
-
-       if (!emcore_insert_event(&event_data, (int*)handle, &err))  {
+       if (!emcore_insert_event(event_data, (int*)handle, &err))  {
                EM_DEBUG_EXCEPTION("emcore_insert_event failed [%d]", err);
                goto FINISH_OFF;
        }
@@ -493,9 +522,17 @@ INTERNAL_FUNC int emdaemon_download_attachment(int account_id, int mail_id, int
        ret = true;
 
 FINISH_OFF:
+
+       if (ret == false && event_data) {
+               emcore_free_event(event_data);
+               EM_SAFE_FREE(event_data);
+       }
+
        if (err_code)
                *err_code = err;
 
+       EM_DEBUG_FUNC_END();
+
        return ret;
 }
 
@@ -524,23 +561,29 @@ void* thread_func_to_delete_mail(void *thread_argument)
 
        if (!emcore_delete_mail(account_id, mail_id_list, mail_id_count, EMAIL_DELETE_LOCALLY, EMAIL_DELETED_BY_COMMAND, noti_param_2, &err)) {
                EM_DEBUG_EXCEPTION(" emcore_delete_mail failed [%d]", err);
+               emcore_free_event(event_data); /* prevent 17922 */
+               EM_SAFE_FREE(event_data);
                goto FINISH_OFF;
        }
 
        if (from_server == EMAIL_DELETE_LOCAL_AND_SERVER || from_server == EMAIL_DELETE_FROM_SERVER) {
                if (!emcore_insert_event(event_data, (int*)handle, &err)) {
                        EM_DEBUG_EXCEPTION("emcore_insert_event failed [%d]", err);
+/*                     if (from_server != EMAIL_DELETE_LOCAL_AND_SERVER && from_server != EMAIL_DELETE_FROM_SERVER) {
+                               EM_SAFE_FREE(event_data->event_param_data_3);
+                       } */
+                       emcore_free_event(event_data); /* prevent 17922 */
+                       EM_SAFE_FREE(event_data);
                        goto FINISH_OFF;
                }
        }
+       else {
+               emcore_free_event(event_data); /* prevent 17922 */
+               EM_SAFE_FREE(event_data);
+       }
 
 FINISH_OFF:
-       /* all of members will be freed after using in each event handler */
-
-       if (from_server != EMAIL_DELETE_LOCAL_AND_SERVER && from_server != EMAIL_DELETE_FROM_SERVER) {
-               EM_SAFE_FREE(event_data->event_param_data_3);
-       }
-       EM_SAFE_FREE(event_data);
+       /* Don't free event_data as if the data is destined to be passed to event handler through emcore_insert_event.*/
 
        EM_DEBUG_FUNC_END();
        return SUCCESS;
@@ -632,10 +675,10 @@ int emdaemon_delete_mail_all(int input_mailbox_id, int input_from_server, int *o
 {
        EM_DEBUG_FUNC_BEGIN("input_mailbox_id[%d], input_from_server[%d], handle[%p], err_code[%p]", input_mailbox_id, input_from_server, output_handle, output_err_code);
 
-       int                      ret = false;
-       int                      err = EMAIL_ERROR_NONE;
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
        emstorage_mailbox_tbl_t *mailbox_tbl = NULL;
-       email_event_t              event_data = { 0 };
+       email_event_t *event_data = NULL;
 
        if (!input_mailbox_id) {
                EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
@@ -655,12 +698,13 @@ int emdaemon_delete_mail_all(int input_mailbox_id, int input_from_server, int *o
 
 #ifdef __FEATURE_SYNC_CLIENT_TO_SERVER__
        if(input_from_server == EMAIL_DELETE_LOCAL_AND_SERVER || input_from_server == EMAIL_DELETE_FROM_SERVER) {
-               event_data.type               = EMAIL_EVENT_DELETE_MAIL_ALL;
-               event_data.account_id         = mailbox_tbl->account_id;
-               event_data.event_param_data_4 = input_mailbox_id;
-               event_data.event_param_data_5 = input_from_server;
+               event_data = em_malloc(sizeof(email_event_t));
+               event_data->type               = EMAIL_EVENT_DELETE_MAIL_ALL;
+               event_data->account_id         = mailbox_tbl->account_id;
+               event_data->event_param_data_4 = input_mailbox_id;
+               event_data->event_param_data_5 = input_from_server;
 
-               if (!emcore_insert_event(&event_data, (int*)output_handle, &err))  {
+               if (!emcore_insert_event(event_data, (int*)output_handle, &err)) {
                        EM_DEBUG_EXCEPTION("emcore_insert_event falied [%d]", err);
                        goto FINISH_OFF;
                }
@@ -724,6 +768,11 @@ int emdaemon_delete_mail_all(int input_mailbox_id, int input_from_server, int *o
 
 FINISH_OFF:
 
+       if (ret == false && event_data) {
+               emcore_free_event(event_data);
+               EM_SAFE_FREE(event_data);
+       }
+
        if (mailbox_tbl)
                emstorage_free_mailbox(&mailbox_tbl, 1, NULL);
 
@@ -736,11 +785,19 @@ FINISH_OFF:
 void* thread_func_to_move_mail(void *thread_argument)
 {
        EM_DEBUG_FUNC_BEGIN();
+
+       int ret = false;
        int *mail_ids = NULL, mail_ids_count, noti_param_1, noti_param_2, err;
        int handle = 0;
        email_event_t *event_data = (email_event_t*)thread_argument;
        int dst_mailbox_id = 0;
 
+       if(!event_data) { /*prevent 53096*/
+               EM_DEBUG_EXCEPTION("INVALID_PARMAETER");
+               return NULL;
+       }
+
+
 /*     dst_mailbox_name   = (char*)event_data->event_param_data_1; */ /*prevent 33693*/
        mail_ids           = (int*)event_data->event_param_data_3;
        mail_ids_count     = event_data->event_param_data_4;
@@ -759,9 +816,14 @@ void* thread_func_to_move_mail(void *thread_argument)
                goto FINISH_OFF;
        }
 
+       ret = true;
+
 FINISH_OFF:
-       /* emcore_free_event(event_data); */ /* all of members will be freed after using in each event handler */
-       EM_SAFE_FREE(event_data);
+
+       if (ret == false && event_data) {
+               emcore_free_event(event_data);
+               EM_SAFE_FREE(event_data);
+       }
 
        EM_DEBUG_FUNC_END();
        return SUCCESS;
@@ -1033,10 +1095,13 @@ FINISH_OFF:
 
 INTERNAL_FUNC int emdaemon_set_flags_field(int account_id, int mail_ids[], int num, email_flags_field_type field_type, int value, int onserver, int* err_code)
 {
-       EM_DEBUG_FUNC_BEGIN("mail_ids[%d], num[%d], field_type [%d], value[%d], err_code[%p]", mail_ids[0], num, field_type, value, err_code);
+       EM_DEBUG_FUNC_BEGIN("mail_ids[%p], num[%d], field_type [%d], value[%d], err_code[%p]", mail_ids, num, field_type, value, err_code); /*prevent 27460*/
 
        int ret = false, err = EMAIL_ERROR_NONE;
        emstorage_account_tbl_t *account_tbl = NULL;
+       int *mail_id_array = NULL;
+       email_event_t *event_data = NULL;
+       int handle = 0;
 
        if(account_id <= 0 || !mail_ids || num <= 0) {
                err = EMAIL_ERROR_INVALID_PARAM;
@@ -1054,30 +1119,27 @@ INTERNAL_FUNC int emdaemon_set_flags_field(int account_id, int mail_ids[], int n
                goto FINISH_OFF;
        }
 
-       if( onserver && account_tbl->incoming_server_type == EMAIL_SERVER_TYPE_IMAP4 )  {
-               int *mail_id_array = NULL;
-               email_event_t event_data = {0};
-               int handle = 0;
-
+       if( onserver && account_tbl->incoming_server_type == EMAIL_SERVER_TYPE_IMAP4 ) {
                mail_id_array = em_malloc(sizeof(int) * num);
 
                if (mail_id_array == NULL)  {
                        EM_DEBUG_EXCEPTION("em_malloc failed...");
-              err = EMAIL_ERROR_OUT_OF_MEMORY;
-              goto FINISH_OFF;
+                       err = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
                }
 
                memcpy(mail_id_array, mail_ids, sizeof(int) * num);
 
-               event_data.type               = EMAIL_EVENT_SYNC_FLAGS_FIELD_TO_SERVER;
-               event_data.account_id         = account_id;
-               event_data.event_param_data_1 = NULL;
-               event_data.event_param_data_3 = (char*)mail_id_array;
-               event_data.event_param_data_4 = num;
-               event_data.event_param_data_5 = field_type;
-               event_data.event_param_data_6 = value;
+               event_data = em_malloc(sizeof(email_event_t));
+               event_data->type               = EMAIL_EVENT_SYNC_FLAGS_FIELD_TO_SERVER;
+               event_data->account_id         = account_id;
+               event_data->event_param_data_1 = NULL;
+               event_data->event_param_data_3 = (char*)mail_id_array;
+               event_data->event_param_data_4 = num;
+               event_data->event_param_data_5 = field_type;
+               event_data->event_param_data_6 = value;
 
-               if (!emcore_insert_event(&event_data, (int*)&handle, &err))  {
+               if (!emcore_insert_event(event_data, (int*)&handle, &err))  {
                        EM_DEBUG_LOG("emcore_insert_event failed [%d]", err);
                        goto FINISH_OFF;
                }
@@ -1087,6 +1149,11 @@ INTERNAL_FUNC int emdaemon_set_flags_field(int account_id, int mail_ids[], int n
 
 FINISH_OFF:
 
+       if (ret == false && event_data) {
+               emcore_free_event(event_data);
+               EM_SAFE_FREE(event_data);
+       }
+
        if (account_tbl)
                emstorage_free_account(&account_tbl, 1, NULL);
 
@@ -1101,9 +1168,9 @@ INTERNAL_FUNC int emdaemon_update_mail(email_mail_data_t *input_mail_data, email
 {
        EM_DEBUG_FUNC_BEGIN("input_mail_data[%p], input_attachment_data_list[%p], input_attachment_count [%d], input_meeting_req [%p], input_from_eas[%d]", input_mail_data, input_attachment_data_list, input_attachment_count, input_meeting_request, input_from_eas);
 
-       int            err = EMAIL_ERROR_NONE;
-       int            handle = 0;
-       email_event_t    event_data = { 0 };
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       /*email_event_t *event_data = NULL;*/
        email_account_t *ref_account = NULL;
 
        if (!input_mail_data || input_mail_data->account_id <= 0 || input_mail_data->mail_id == 0 ||
@@ -1126,25 +1193,35 @@ INTERNAL_FUNC int emdaemon_update_mail(email_mail_data_t *input_mail_data, email
        }
 
 #ifdef __FEATURE_SYNC_CLIENT_TO_SERVER__
-       if ( input_from_eas == 0) {
-               event_data.type               = EMAIL_EVENT_UPDATE_MAIL;
-               event_data.account_id         = input_mail_data->account_id;
-               event_data.event_param_data_1 = (char*)input_mail_data;
-               event_data.event_param_data_2 = (char*)input_attachment_data_list;
-               event_data.event_param_data_3 = (char*)input_meeting_request;
-               event_data.event_param_data_4 = input_attachment_count;
-               event_data.event_param_data_5 = input_from_eas;
-
-               if (!emcore_insert_event(&event_data, &handle, &err)) {
+/*     if ( input_from_eas == 0) {
+               event_data = em_malloc(sizeof(email_event_t));
+               event_data->type               = EMAIL_EVENT_UPDATE_MAIL;
+               event_data->account_id         = input_mail_data->account_id;
+               event_data->event_param_data_1 = (char*)input_mail_data;                        // need to be duplicated, it is double freed
+               event_data->event_param_data_2 = (char*)input_attachment_data_list;     // need to be duplicated, it is double freed
+               event_data->event_param_data_3 = (char*)input_meeting_request;          // need to be duplicated, it is double freed
+               event_data->event_param_data_4 = input_attachment_count;
+               event_data->event_param_data_5 = input_from_eas;
+
+               if (!emcore_insert_event(event_data, &handle, &err))  {
                        EM_DEBUG_EXCEPTION("emcore_insert_event_for_sending_mails failed [%d]", err);
                        err = EMAIL_ERROR_NONE;
                        goto FINISH_OFF;
                }
        }
+*/
 #endif
 
+       ret = true;
+
 FINISH_OFF:
 
+/*prevent 64298*/
+/*     if (ret == false && event_data) {
+               emcore_free_event(event_data);
+               EM_SAFE_FREE(event_data);
+       }
+*/
        if (ref_account) {
                emcore_free_account(ref_account);
                EM_SAFE_FREE(ref_account);
@@ -1289,7 +1366,7 @@ INTERNAL_FUNC int emdaemon_move_mail_thread_to_mailbox(int thread_id, int target
        }
 
        for(i = 0; i < mailbox_count; i++) {
-               EM_DEBUG_LOG("%s %d", target_mailbox_list[i].mailbox_name, target_mailbox_id);
+               EM_DEBUG_LOG_SEC("%s %d", target_mailbox_list[i].mailbox_name, target_mailbox_id);
                if(target_mailbox_list[i].mailbox_id == target_mailbox_id) {
                        target_mailbox = (target_mailbox_list + i);
                        break;
@@ -1301,10 +1378,12 @@ INTERNAL_FUNC int emdaemon_move_mail_thread_to_mailbox(int thread_id, int target
                goto FINISH_OFF;
        }
 
+/*
        if (!emdaemon_move_mail(mail_id_list, result_count, target_mailbox->mailbox_id, EMAIL_MOVED_BY_MOVING_THREAD, move_always_flag, &err)) {
                EM_DEBUG_EXCEPTION("emdaemon_move_mail failed [%d]", err);
                goto FINISH_OFF;
        }
+*/
 
        SNPRINTF(mailbox_id_param_string, 10, "%d", target_mailbox->mailbox_id);
        if (!emcore_notify_storage_event(NOTI_THREAD_MOVE, account_id, thread_id, mailbox_id_param_string, move_always_flag))
@@ -1426,10 +1505,12 @@ FINISH_OFF:
 INTERNAL_FUNC int emdaemon_expunge_mails_deleted_flagged(int input_mailbox_id, int input_on_server, int *output_handle)
 {
        EM_DEBUG_FUNC_BEGIN("input_mailbox_id [%d], input_on_server [%d], output_handle [%p]", input_mailbox_id, input_on_server, output_handle);
-       int                      err = EMAIL_ERROR_NONE;
-       int                      handle = 0;
-       email_event_t              event_data = { 0 };
-       email_account_t           *ref_account = NULL;
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       int handle = 0;
+       int event_insert = false;
+       email_event_t *event_data = NULL;
+       email_account_t *ref_account = NULL;
        emstorage_mailbox_tbl_t *mailbox_tbl = NULL;
 
        if (input_mailbox_id <= 0)  {
@@ -1452,14 +1533,16 @@ INTERNAL_FUNC int emdaemon_expunge_mails_deleted_flagged(int input_mailbox_id, i
 
 #ifdef __FEATURE_SYNC_CLIENT_TO_SERVER__
        if(input_on_server) {
-               event_data.type               = EMAIL_EVENT_EXPUNGE_MAILS_DELETED_FLAGGED;
-               event_data.account_id         = mailbox_tbl->account_id;
-               event_data.event_param_data_4 = input_mailbox_id;
+               event_data = em_malloc(sizeof(email_event_t));
+               event_data->type               = EMAIL_EVENT_EXPUNGE_MAILS_DELETED_FLAGGED;
+               event_data->account_id         = mailbox_tbl->account_id;
+               event_data->event_param_data_4 = input_mailbox_id;
 
-               if (!emcore_insert_event(&event_data, &handle, &err))  {
+               if (!emcore_insert_event(event_data, &handle, &err)) {
                        EM_DEBUG_EXCEPTION("emcore_insert_event failed [%d]", err);
                        goto FINISH_OFF;
                }
+               event_insert = true;
        }
        else
 #endif
@@ -1468,8 +1551,15 @@ INTERNAL_FUNC int emdaemon_expunge_mails_deleted_flagged(int input_mailbox_id, i
                        goto FINISH_OFF;
                }
 
+       ret = true;
+
 FINISH_OFF:
 
+       if (event_insert == false && event_data) {
+               emcore_free_event(event_data);
+               EM_SAFE_FREE(event_data);
+       }
+
        if (ref_account) {
                emcore_free_account(ref_account);
                EM_SAFE_FREE(ref_account);
index d71f8e5..86926f9 100755 (executable)
@@ -42,6 +42,8 @@
 #include "email-core-account.h"
 #include "email-core-global.h"
 #include "email-core-utils.h"
+#include "email-core-signal.h"
+#include "email-utilities.h"
 
 #ifdef __FEATURE_LOCAL_ACTIVITY__
 extern int g_local_activity_run;
@@ -51,10 +53,10 @@ INTERNAL_FUNC int emdaemon_get_imap_mailbox_list(int account_id, char* mailbox,
 {
        EM_DEBUG_FUNC_BEGIN("account_id[%d] mailbox[%p] err_code[%p]", account_id, mailbox, err_code);
 
-       /*  default variable */
        int ret = false;
        int err = EMAIL_ERROR_NONE;
-       email_account_t* ref_account = NULL;
+       email_account_t *ref_account = NULL;
+       email_event_t *event_data = NULL;
 
        if (account_id <= 0 ||!mailbox)  {
                EM_DEBUG_EXCEPTION("account_id[%d], mailbox[%p]", account_id, mailbox);
@@ -64,20 +66,18 @@ INTERNAL_FUNC int emdaemon_get_imap_mailbox_list(int account_id, char* mailbox,
 
        ref_account = emcore_get_account_reference(account_id);
 
-       if (!ref_account)  {
+       if (!ref_account) {
                EM_DEBUG_EXCEPTION("emcore_get_account_reference failed [%d]", account_id);
                err = EMAIL_ERROR_INVALID_ACCOUNT;
                goto FINISH_OFF;
        }
 
-       email_event_t event_data;
-       memset(&event_data, 0x00, sizeof(email_event_t));
-
-       event_data.type = EMAIL_EVENT_SYNC_IMAP_MAILBOX;
-       event_data.account_id = account_id;
-       event_data.event_param_data_3 = EM_SAFE_STRDUP(mailbox);
+       event_data = em_malloc(sizeof(email_event_t));
+       event_data->type = EMAIL_EVENT_SYNC_IMAP_MAILBOX;
+       event_data->account_id = account_id;
+       event_data->event_param_data_3 = EM_SAFE_STRDUP(mailbox);
 
-       if (!emcore_insert_event(&event_data, (int*)handle, &err))  {
+       if (!emcore_insert_event(event_data, (int*)handle, &err)) {
                EM_DEBUG_EXCEPTION("emcore_insert_event failed [%d]", err);
                goto FINISH_OFF;
        }
@@ -86,6 +86,11 @@ INTERNAL_FUNC int emdaemon_get_imap_mailbox_list(int account_id, char* mailbox,
 
 FINISH_OFF:
 
+       if (ret == false && event_data) {
+               emcore_free_event(event_data);
+               EM_SAFE_FREE(event_data);
+       }
+
        if (ref_account) {
                emcore_free_account(ref_account);
                EM_SAFE_FREE(ref_account);
@@ -187,11 +192,13 @@ INTERNAL_FUNC int emdaemon_add_mailbox(email_mailbox_t* new_mailbox, int on_serv
 {
        EM_DEBUG_FUNC_BEGIN("new_mailbox[%p], err_code[%p]", new_mailbox, err_code);
 
-       int ret = false;;
+       int ret = false;
        int err = EMAIL_ERROR_NONE;
-       email_account_t* ref_account = NULL;
+       email_account_t *ref_account = NULL;
+       email_event_t   *event_data  = NULL;
+       email_mailbox_t *mailbox     = NULL;
 
-       if (!new_mailbox || new_mailbox->account_id <= 0 || !new_mailbox->mailbox_name)  {
+       if (!new_mailbox || new_mailbox->account_id <= 0 || !new_mailbox->mailbox_name) {
                if (new_mailbox != NULL)
                        EM_DEBUG_EXCEPTION("new_mailbox->account_id[%d], new_mailbox->mailbox_name[%p]", new_mailbox->account_id, new_mailbox->mailbox_name);
                err = EMAIL_ERROR_INVALID_PARAM;
@@ -206,27 +213,45 @@ INTERNAL_FUNC int emdaemon_add_mailbox(email_mailbox_t* new_mailbox, int on_serv
                goto FINISH_OFF;
        }
 
-       email_event_t event_data;
-       memset(&event_data, 0x00, sizeof(email_event_t));
-
-
        /*  on_server is allowed to be only 0 when server_type is EMAIL_SERVER_TYPE_ACTIVE_SYNC */
        if ( ref_account->incoming_server_type == EMAIL_SERVER_TYPE_ACTIVE_SYNC )
                on_server = 0;
 
-       if ( on_server ) {      /*  async */
-               event_data.type               = EMAIL_EVENT_CREATE_MAILBOX;
-               event_data.account_id         = new_mailbox->account_id;
-               event_data.event_param_data_1 = EM_SAFE_STRDUP(new_mailbox->mailbox_name);
-               event_data.event_param_data_2 = EM_SAFE_STRDUP(new_mailbox->alias);
-               event_data.event_param_data_4 = on_server;
-               event_data.event_param_data_3 = GINT_TO_POINTER(new_mailbox->mailbox_type);
-               if(!emcore_insert_event(&event_data, (int*)handle, &err))    {
+       if ( on_server ) {      /* async */
+
+               mailbox = em_malloc(sizeof(email_mailbox_t));
+
+               if(mailbox == NULL) {
+                       EM_DEBUG_EXCEPTION("em_malloc failed");
+                       err = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+
+               memcpy(mailbox, new_mailbox, sizeof(email_mailbox_t));
+               mailbox->mailbox_name  = EM_SAFE_STRDUP(new_mailbox->mailbox_name);
+               mailbox->alias         = EM_SAFE_STRDUP(new_mailbox->alias);
+
+               if(new_mailbox->eas_data_length > 0 && new_mailbox->eas_data) {
+                       mailbox->eas_data = em_malloc(new_mailbox->eas_data_length);
+                       if(mailbox->eas_data == NULL) {
+                               EM_DEBUG_EXCEPTION("em_malloc failed");
+                               err = EMAIL_ERROR_OUT_OF_MEMORY;
+                               goto FINISH_OFF;
+                       }
+                       memcpy(mailbox->eas_data, new_mailbox->eas_data, new_mailbox->eas_data_length);
+               }
+
+               event_data                     = em_malloc(sizeof(email_event_t));
+               event_data->type               = EMAIL_EVENT_CREATE_MAILBOX;
+               event_data->account_id         = new_mailbox->account_id;
+               event_data->event_param_data_1 = (char*)mailbox;
+               event_data->event_param_data_4 = on_server;
+
+               if(!emcore_insert_event(event_data, (int*)handle, &err)) {
                        EM_DEBUG_EXCEPTION("emcore_insert_event failed [%d]", err);
                        goto FINISH_OFF;
                }
-       }
-       else {  /*  sync */
+       } else {        /* sync */
                if (!emcore_create_mailbox(new_mailbox, on_server, &err))  {
                        EM_DEBUG_EXCEPTION("emcore_create failed [%d]", err);
                        goto FINISH_OFF;
@@ -237,6 +262,17 @@ INTERNAL_FUNC int emdaemon_add_mailbox(email_mailbox_t* new_mailbox, int on_serv
 
 FINISH_OFF:
 
+       if (ret == false) {
+               if(event_data) {
+                       emcore_free_event(event_data);
+                       EM_SAFE_FREE(event_data);
+               }
+               if(mailbox) {
+                       emcore_free_mailbox(mailbox);
+                       EM_SAFE_FREE(mailbox);
+               }
+       }
+
        if (ref_account) {
                emcore_free_account(ref_account);
                EM_SAFE_FREE(ref_account);
@@ -267,7 +303,7 @@ INTERNAL_FUNC int emdaemon_set_mailbox_type(int input_mailbox_id, email_mailbox_
                goto FINISH_OFF;
        }
 
-       if (!emstorage_update_mailbox_type(mailbox_tbl->account_id, -1, mailbox_tbl->mailbox_name, input_mailbox_type, true, &err))  {
+       if (!emstorage_update_mailbox_type(mailbox_tbl->account_id, -1, input_mailbox_id, input_mailbox_type, true, &err))  {
                EM_DEBUG_EXCEPTION("emstorage_update_mailbox failed [%d]", err);
                goto FINISH_OFF;
        }
@@ -310,19 +346,19 @@ INTERNAL_FUNC int emdaemon_delete_mailbox(int input_mailbox_id, int on_server, i
 {
        EM_DEBUG_FUNC_BEGIN("input_mailbox_id[%d], err_code[%p]", input_mailbox_id, err_code);
 
-       /*  default variable */
        int ret = false;
        int err = EMAIL_ERROR_NONE;
        int recursive = 1;
        emstorage_mailbox_tbl_t *mailbox_tbl = NULL;
-       email_account_t* ref_account = NULL;
+       email_account_t *ref_account = NULL;
+       email_event_t *event_data = NULL;
 
        if ((err = emstorage_get_mailbox_by_id(input_mailbox_id, &mailbox_tbl)) != EMAIL_ERROR_NONE || !mailbox_tbl) {
                EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_id failed. [%d]", err);
                goto FINISH_OFF;
        }
 
-       if (!input_mailbox_id || mailbox_tbl->account_id <= 0)  {
+       if (!input_mailbox_id || mailbox_tbl->account_id <= 0) {
                if (input_mailbox_id != 0)
                        EM_DEBUG_EXCEPTION("mailbox_tbl->account_id[%d]", mailbox_tbl->account_id);
                err = EMAIL_ERROR_INVALID_PARAM;
@@ -331,33 +367,29 @@ INTERNAL_FUNC int emdaemon_delete_mailbox(int input_mailbox_id, int on_server, i
 
        ref_account = emcore_get_account_reference(mailbox_tbl->account_id);
 
-       if (!ref_account)  {
+       if (!ref_account) {
                EM_DEBUG_EXCEPTION("emcore_get_account_reference failed [%d]", mailbox_tbl->account_id);
                err = EMAIL_ERROR_INVALID_ACCOUNT;
                goto FINISH_OFF;
        }
 
-       email_event_t event_data;
-       memset(&event_data, 0x00, sizeof(email_event_t));
-
        /*  on_server is allowed to be only 0 when server_type is EMAIL_SERVER_TYPE_ACTIVE_SYNC */
        if ( ref_account->incoming_server_type == EMAIL_SERVER_TYPE_ACTIVE_SYNC ) {
                on_server = 0;
-               recursive = 0;
        }
 
        if ( on_server ) {      /*  async */
-               event_data.type = EMAIL_EVENT_DELETE_MAILBOX;
-               event_data.account_id = mailbox_tbl->account_id;
-               event_data.event_param_data_4 = input_mailbox_id;
-               event_data.event_param_data_5 = on_server;
-               event_data.event_param_data_6 = recursive;
-               if(!emcore_insert_event(&event_data, (int*)handle, &err))    {
+               event_data = em_malloc(sizeof(email_event_t));
+               event_data->type = EMAIL_EVENT_DELETE_MAILBOX;
+               event_data->account_id = mailbox_tbl->account_id;
+               event_data->event_param_data_4 = input_mailbox_id;
+               event_data->event_param_data_5 = on_server;
+               event_data->event_param_data_6 = recursive;
+               if(!emcore_insert_event(event_data, (int*)handle, &err)) {
                        EM_DEBUG_EXCEPTION("emcore_insert_event failed [%d]", err);
                        goto FINISH_OFF;
                }
-       }
-       else {
+       } else {
                if (!emcore_delete_mailbox(input_mailbox_id, on_server, recursive))  {
                        EM_DEBUG_EXCEPTION("emcore_delete failed [%d]", err);
                        goto FINISH_OFF;
@@ -368,6 +400,11 @@ INTERNAL_FUNC int emdaemon_delete_mailbox(int input_mailbox_id, int on_server, i
 
 FINISH_OFF:
 
+       if (ret == false && event_data) {
+               emcore_free_event(event_data);
+               EM_SAFE_FREE(event_data);
+       }
+
        if (ref_account) {
                emcore_free_account(ref_account);
                EM_SAFE_FREE(ref_account);
@@ -432,49 +469,58 @@ INTERNAL_FUNC int emdaemon_sync_header(int input_account_id, int input_mailbox_i
 {
        EM_DEBUG_FUNC_BEGIN("input_account_id[%d], input_mailbox_id[%d], handle[%p], err_code[%p]", input_account_id, input_mailbox_id, handle, err_code);
 
-       /*  default variable */
        int ret = false;
        int err = EMAIL_ERROR_NONE;
+       email_event_t *event_data = NULL;
 
-       email_event_t event_data;
-
-       memset(&event_data, 0x00, sizeof(email_event_t));
-
-       if (input_mailbox_id < 0) {
+       if (input_mailbox_id < 0 || handle == NULL) {
                EM_DEBUG_EXCEPTION("parameter is invalid");
-               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               err = EMAIL_ERROR_INVALID_PARAM;
                goto FINISH_OFF;
        }
 
+       event_data = em_malloc(sizeof(email_event_t));
+
        if(input_account_id == ALL_ACCOUNT) {
-               EM_DEBUG_LOG(">>>> emdaemon_sync_header for all account event_data.event_param_data_4 [%d]", event_data.event_param_data_4);
-               event_data.type               = EMAIL_EVENT_SYNC_HEADER;
-               event_data.account_id         = input_account_id;
-               event_data.event_param_data_5 = input_mailbox_id;
+               EM_DEBUG_LOG(">>>> emdaemon_sync_header for all account event_data.event_param_data_4 [%d]", event_data->event_param_data_4);
+               event_data->type               = EMAIL_EVENT_SYNC_HEADER;
+               event_data->account_id         = input_account_id;
+               event_data->event_param_data_5 = input_mailbox_id;
                /* In case of Mailbox NULL, we need to set arg as EMAIL_SYNC_ALL_MAILBOX */
                if (input_mailbox_id == 0)
-                       event_data.event_param_data_4 = EMAIL_SYNC_ALL_MAILBOX;
+                       event_data->event_param_data_4 = EMAIL_SYNC_ALL_MAILBOX;
 
-               if (!emcore_insert_event(&event_data, (int*)handle, &err))   {
+               if (!emcore_insert_event(event_data, (int*)handle, &err)) {
                        EM_DEBUG_EXCEPTION("emcore_insert_event falied [%d]", err);
                        goto FINISH_OFF;
                }
        } else {
                /* Modified the code to sync all mailbox in a Single Event */
-               event_data.type               = EMAIL_EVENT_SYNC_HEADER;
-               event_data.account_id         = input_account_id;
-               event_data.event_param_data_5 = input_mailbox_id;
+               event_data->type               = EMAIL_EVENT_SYNC_HEADER;
+               event_data->account_id         = input_account_id;
+               event_data->event_param_data_5 = input_mailbox_id;
                /* In case of Mailbox NULL, we need to set arg as EMAIL_SYNC_ALL_MAILBOX */
                if (input_mailbox_id == 0)
-                       event_data.event_param_data_4 = EMAIL_SYNC_ALL_MAILBOX;
-               EM_DEBUG_LOG(">>>> EVENT ARG [ %d ] ", event_data.event_param_data_4);
+                       event_data->event_param_data_4 = EMAIL_SYNC_ALL_MAILBOX;
+               EM_DEBUG_LOG(">>>> EVENT ARG [ %d ] ", event_data->event_param_data_4);
 
-               if (!emcore_insert_event(&event_data, (int*)handle, &err))   {
+               if (!emcore_insert_event(event_data, (int*)handle, &err)) {
                        EM_DEBUG_EXCEPTION("emcore_insert_event falied [%d]", err);
                        goto FINISH_OFF;
                }
        }
 
+       /* Due to fast response, event noti is moved here from worker_event_queue */
+       char input_mailbox_id_str[10] = {0};
+       snprintf(input_mailbox_id_str, 10, "%d ", input_mailbox_id);
+       if (!emcore_notify_network_event(NOTI_DOWNLOAD_START, input_account_id, ((input_mailbox_id==0)? NULL:input_mailbox_id_str), *handle, 0))
+               EM_DEBUG_EXCEPTION("emcore_notify_network_event [ NOTI_DOWNLOAD_START] Failed >>>> ");
+
+/*     if ((err = emcore_update_sync_status_of_account(input_account_id, SET_TYPE_SET, SYNC_STATUS_SYNCING)) != EMAIL_ERROR_NONE)
+               EM_DEBUG_EXCEPTION("emcore_update_sync_status_of_account failed [%d]", err);
+*/
+
+
 #ifdef __FEATURE_LOCAL_ACTIVITY__
        EM_DEBUG_LOG("Setting g_local_activity_run ");
        g_local_activity_run = 1;
@@ -484,6 +530,11 @@ INTERNAL_FUNC int emdaemon_sync_header(int input_account_id, int input_mailbox_i
 
 FINISH_OFF:
 
+       if (ret == false && event_data) {
+               emcore_free_event(event_data);
+               EM_SAFE_FREE(event_data);
+       }
+
        if (err_code)
                *err_code = err;
        EM_DEBUG_FUNC_END();
@@ -496,7 +547,7 @@ INTERNAL_FUNC int emdaemon_set_mail_slot_size_of_mailbox(int account_id, int mai
 
        int ret = false;
        int err = EMAIL_ERROR_NONE;
-       email_event_t event_data;
+       email_event_t *event_data = NULL;
 
        if(handle == NULL) {
                EM_DEBUG_EXCEPTION("handle is required");
@@ -504,14 +555,13 @@ INTERNAL_FUNC int emdaemon_set_mail_slot_size_of_mailbox(int account_id, int mai
                goto FINISH_OFF;
        }
 
-       memset(&event_data, 0x00, sizeof(email_event_t));
-
-       event_data.type = EMAIL_EVENT_SET_MAIL_SLOT_SIZE;
-       event_data.account_id = account_id;
-       event_data.event_param_data_4 = mailbox_id;
-       event_data.event_param_data_5 = new_slot_size;
+       event_data = em_malloc(sizeof(email_event_t));
+       event_data->type = EMAIL_EVENT_SET_MAIL_SLOT_SIZE;
+       event_data->account_id = account_id;
+       event_data->event_param_data_4 = mailbox_id;
+       event_data->event_param_data_5 = new_slot_size;
 
-       if (!emcore_insert_event(&event_data, (int*)handle, &err))   {
+       if (!emcore_insert_event(event_data, (int*)handle, &err))   {
                EM_DEBUG_EXCEPTION("emcore_insert_event falied [%d]", err);
                goto FINISH_OFF;
        }
@@ -519,20 +569,27 @@ INTERNAL_FUNC int emdaemon_set_mail_slot_size_of_mailbox(int account_id, int mai
        ret = true;
 
 FINISH_OFF:
+
+       if (ret == false && event_data) {
+               emcore_free_event(event_data);
+               EM_SAFE_FREE(event_data);
+       }
+
        if (err_code)
                *err_code = err;
        EM_DEBUG_FUNC_END();
        return ret;
 }
 
-INTERNAL_FUNC int emdaemon_rename_mailbox(int input_mailbox_id, char *input_mailbox_path, char *input_mailbox_alias, int input_on_server, int *output_handle)
+INTERNAL_FUNC int emdaemon_rename_mailbox(int input_mailbox_id, char *input_mailbox_path, char *input_mailbox_alias, void *input_eas_data, int input_eas_data_length, int input_on_server, int *output_handle)
 {
-       EM_DEBUG_FUNC_BEGIN("input_mailbox_id [%d], input_mailbox_path [%p], input_mailbox_alias[%p], input_on_server [%d], output_handle[%p]", input_mailbox_id, input_mailbox_path, input_mailbox_alias, input_on_server, output_handle);
+       EM_DEBUG_FUNC_BEGIN("input_mailbox_id[%d] input_mailbox_path[%p] input_mailbox_alias[%p] input_eas_data[%p] input_eas_data_length[%d] input_on_server[%d] output_handle[%p]", input_mailbox_id, input_mailbox_path, input_mailbox_alias, input_eas_data, input_eas_data_length, input_on_server, output_handle);
 
+       int ret = false;
        int err = EMAIL_ERROR_NONE;
        emstorage_account_tbl_t *account_data = NULL;
        emstorage_mailbox_tbl_t *old_mailbox_data = NULL;
-       email_event_t event_data;
+       email_event_t *event_data = NULL;
 
        if(input_mailbox_id <= 0 || output_handle == NULL) {
                EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
@@ -552,29 +609,35 @@ INTERNAL_FUNC int emdaemon_rename_mailbox(int input_mailbox_id, char *input_mail
                }
 
                if (account_data->incoming_server_type == EMAIL_SERVER_TYPE_IMAP4) {
-                       memset(&event_data, 0x00, sizeof(email_event_t));
-
-                       event_data.type               = EMAIL_EVENT_RENAME_MAILBOX_ON_IMAP_SERVER;
-                       event_data.event_param_data_1 = EM_SAFE_STRDUP(old_mailbox_data->mailbox_name);
-                       event_data.event_param_data_2 = EM_SAFE_STRDUP(input_mailbox_path);
-                       event_data.event_param_data_3 = EM_SAFE_STRDUP(input_mailbox_alias);
-                       event_data.event_param_data_4 = input_mailbox_id;
-                       event_data.account_id         = old_mailbox_data->account_id;
-
-                       if (!emcore_insert_event(&event_data, (int*)output_handle, &err)) {
+                       event_data = em_malloc(sizeof(email_event_t));
+                       event_data->type               = EMAIL_EVENT_RENAME_MAILBOX_ON_IMAP_SERVER;
+                       event_data->event_param_data_1 = EM_SAFE_STRDUP(old_mailbox_data->mailbox_name);
+                       event_data->event_param_data_2 = EM_SAFE_STRDUP(input_mailbox_path);
+                       event_data->event_param_data_3 = EM_SAFE_STRDUP(input_mailbox_alias);
+                       event_data->event_param_data_4 = input_mailbox_id;
+                       event_data->account_id         = old_mailbox_data->account_id;
+
+                       if (!emcore_insert_event(event_data, (int*)output_handle, &err)) {
                                EM_DEBUG_EXCEPTION("emcore_insert_event falied [%d]", err);
                                goto FINISH_OFF;
                        }
                }
-       }
-       else {
-               if ((err = emcore_rename_mailbox(input_mailbox_id, input_mailbox_path, input_mailbox_alias, false, true, 0)) != EMAIL_ERROR_NONE) {
+       } else {
+               if ((err = emcore_rename_mailbox(input_mailbox_id, input_mailbox_path, input_mailbox_alias, input_eas_data, input_eas_data_length, false, true, 0)) != EMAIL_ERROR_NONE) {
                        EM_DEBUG_EXCEPTION("emcore_rename_mailbox failed [%d]", err);
                        goto FINISH_OFF;
                }
        }
 
+       ret = true;
+
 FINISH_OFF:
+
+       if (ret == false && event_data) {
+               emcore_free_event(event_data);
+               EM_SAFE_FREE(event_data);
+       }
+
        if (old_mailbox_data)
                emstorage_free_mailbox(&old_mailbox_data, 1, NULL);
 
index b165b18..b3fa69b 100755 (executable)
@@ -41,7 +41,7 @@ extern "C"
 #endif /* __cplusplus */
 
 
-INTERNAL_FUNC int emdaemon_add_polling_alarm(int account_id, int alarm_interval);
+INTERNAL_FUNC int emdaemon_add_polling_alarm(int account_id);
 INTERNAL_FUNC int emdaemon_remove_polling_alarm(int account_id);
 INTERNAL_FUNC int emdaemon_check_auto_polling_started(int account_id);
 INTERNAL_FUNC int emdaemon_alarm_polling_cb(alarm_id_t  alarm_id, void* user_param);
index 74760fc..9524e37 100755 (executable)
@@ -39,6 +39,14 @@ extern "C"
 
 #include "email-storage.h"
 
+INTERNAL_FUNC int emdaemon_core_init(int *err_code);
+
+#ifdef __FEATURE_BLOCKING_MODE__
+INTERNAL_FUNC bool emdaemon_init_blocking_mode_status();
+#endif
+
+INTERNAL_FUNC int emdaemon_init_alarm_data_list();
+
 #ifdef __cplusplus
 }
 #endif /* __cplusplus */
index 06a742c..e82347c 100755 (executable)
@@ -634,7 +634,7 @@ INTERNAL_FUNC int emdaemon_validate_account_and_create(email_account_t* new_acco
 
 INTERNAL_FUNC int emdaemon_set_mail_slot_size_of_mailbox(int account_id, int mailbox_id, int new_slot_size, int *handle, int *err_code);
 
-INTERNAL_FUNC int emdaemon_rename_mailbox(int input_mailbox_id, char *input_mailbox_path, char *input_mailbox_alias, int input_on_server, int *output_handle);
+INTERNAL_FUNC int emdaemon_rename_mailbox(int input_mailbox_id, char *input_mailbox_path, char *input_mailbox_alias, void *input_eas_data, int input_eas_data_length, int input_on_server, int *output_handle);
 
 INTERNAL_FUNC int emdaemon_move_mail_thread_to_mailbox(int thread_id, int target_mailbox_id, int move_always_flag, int *err_code);
 
@@ -644,6 +644,17 @@ INTERNAL_FUNC int emdaemon_modify_seen_flag_of_thread(int thread_id, int seen_fl
 
 INTERNAL_FUNC int emdaemon_expunge_mails_deleted_flagged(int input_mailbox_id, int input_on_server, int *output_handle);
 
+INTERNAL_FUNC int emdaemon_kill_daemon_if_no_account();
+
+INTERNAL_FUNC int emdaemon_check_smack_rule(int app_sockfd, char *file_path);
+
+INTERNAL_FUNC int emdaemon_set_smack_label(char *file_path, char *label);
+
+INTERNAL_FUNC void emdaemon_start_alert(void);
+
+INTERNAL_FUNC int emdaemon_finalize_sync(int account_id, int total_mail_count, int unread_mail_count, int *error);
+
+INTERNAL_FUNC int emdaemon_query_smtp_mail_size_limit(int account_id, int *handle, int* err_code);
 #ifdef __cplusplus
 }
 #endif /* __cplusplus */
index 6c2109b..5a01c29 100755 (executable)
@@ -34,6 +34,7 @@
 
 #include "email-daemon.h"
 #include "email-ipc.h"
+#include "email-ipc-api-info.h"
 #include "email-utilities.h"
 #include "email-debug-log.h"
 #include "email-daemon-auto-poll.h"
@@ -53,6 +54,7 @@
 #include "email-core-task-manager.h"
 #include "email-core-signal.h"
 #include "email-storage.h"
+#include "email-dbus-activation.h"
 
 void stb_create_account(HIPC_API a_hAPI)
 {
@@ -76,9 +78,8 @@ void stb_create_account(HIPC_API a_hAPI)
        /* Convert account stream to structure */
        em_convert_byte_stream_to_account(local_account_stream, buffer_size, &account);
 
-
-       EM_DEBUG_LOG("Account name - %s", account.account_name);
-       EM_DEBUG_LOG("Email Address - %s", account.user_email_address);
+       EM_DEBUG_LOG_SEC("Account name - %s", account.account_name);
+       EM_DEBUG_LOG_SEC("Email Address - %s", account.user_email_address);
 
        if(!emdaemon_create_account(&account, &err)) {
                EM_DEBUG_EXCEPTION("emdaemon_create_account fail ");
@@ -88,8 +89,8 @@ void stb_create_account(HIPC_API a_hAPI)
 
 #ifdef __FEATURE_AUTO_POLLING__
        /* start auto polling, if check_interval not zero */
-       if(account.check_interval > 0) {
-               if(!emdaemon_add_polling_alarm( account.account_id,account.check_interval))
+       if(account.check_interval > 0 || (account.peak_days && account.peak_interval > 0)) {
+               if(!emdaemon_add_polling_alarm(account.account_id))
                        EM_DEBUG_EXCEPTION("emdaemon_add_polling_alarm[NOTI_ACCOUNT_ADD] : start auto poll failed >>> ");
        }
 #endif
@@ -112,6 +113,7 @@ void stb_create_account(HIPC_API a_hAPI)
                EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
 
 FINISH_OFF:
+       
        if ( local_result == 0 ) {
                if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &local_result, sizeof(int)))
                        EM_DEBUG_EXCEPTION("emipc_add_parameter failed : local_result ");
@@ -120,6 +122,8 @@ FINISH_OFF:
                if (!emipc_execute_stub_api(a_hAPI))
                        EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
        }
+
+       emcore_free_account(&account); /* valgrind */
        EM_DEBUG_FUNC_END();
 }
 
@@ -128,10 +132,17 @@ void stb_delete_account(HIPC_API a_hAPI)
        EM_DEBUG_FUNC_BEGIN();
        int account_id = 0;
        int local_result = 0;
+       int *ret_nth_value = NULL;
        int err = EMAIL_ERROR_NONE;
 
        /* account_id */
-       account_id = *((int*) emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, 0));
+       if ((ret_nth_value = (int *)emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, 0)))
+               account_id = *ret_nth_value;
+       else {
+               err = EMAIL_ERROR_IPC_SOCKET_FAILURE;
+               goto FINISH_OFF;
+       }
+       
        if(!emdaemon_delete_account(account_id, &err)) {
                if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &local_result, sizeof(int)))
                        EM_DEBUG_LOG("emipc_add_parameter failed ");
@@ -167,14 +178,19 @@ void stb_update_account(HIPC_API a_hAPI)
 {
        EM_DEBUG_FUNC_BEGIN();
        int account_id = 0, buffer_size = 0, local_result = 0, with_validation = 0;
+       int *ret_nth_value = NULL;
        char* local_account_stream = NULL;
        email_account_t new_account_info = {0};
        email_account_t old_account_info = {0};
        int err = EMAIL_ERROR_NONE;
        int handle = 0;
 
-       account_id = *((int*)emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, 0));
-
+       if ((ret_nth_value = (int *)emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, 0)))
+               account_id = *ret_nth_value;
+       else {
+               err = EMAIL_ERROR_IPC_SOCKET_FAILURE;
+               goto FINISH_OFF;
+       }
        /* get account structure from stream */
        buffer_size = emipc_get_nth_parameter_length(a_hAPI, ePARAMETER_IN, 1);
        EM_DEBUG_LOG("size [%d]", buffer_size);
@@ -182,8 +198,12 @@ void stb_update_account(HIPC_API a_hAPI)
        em_convert_byte_stream_to_account(local_account_stream, buffer_size, &new_account_info);
 
        /*get validation flag */
-       with_validation = *((int*)emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, 2));
-
+       if ((ret_nth_value = (int *)emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, 2))) {
+               with_validation = *ret_nth_value;
+       } else {
+               err = EMAIL_ERROR_IPC_SOCKET_FAILURE;
+               goto FINISH_OFF;
+       }
 
        if(!emdaemon_get_account(account_id, EMAIL_ACC_GET_OPT_FULL_DATA, &old_account_info, &err)) {
                EM_DEBUG_EXCEPTION("emdaemon_get_account failed ");
@@ -193,7 +213,7 @@ void stb_update_account(HIPC_API a_hAPI)
 
        if( EM_SAFE_STRLEN (new_account_info.incoming_server_password) == 0 ) {
                EM_SAFE_FREE(new_account_info.incoming_server_password); /* be allocated but has zero length */
-               EM_DEBUG_LOG("old_account_info->incoming_server_password [%s]", old_account_info.incoming_server_password);
+               EM_DEBUG_LOG_SEC("old_account_info->incoming_server_password [%s]", old_account_info.incoming_server_password);
                new_account_info.incoming_server_password = EM_SAFE_STRDUP(old_account_info.incoming_server_password);
                if(new_account_info.incoming_server_password == NULL) {
                                EM_DEBUG_EXCEPTION("allocation for new_account_info->password failed");
@@ -313,7 +333,7 @@ void stb_get_account_list(HIPC_API a_hAPI)
                        EM_DEBUG_EXCEPTION("emipc_add_parameter count failed ");
 
                for(i=0; i<count; i++) {
-                       EM_DEBUG_LOG("Name - %s", account_list[i].account_name);
+                       EM_DEBUG_LOG_SEC("Name - %s", account_list[i].account_name);
 
                        local_stream = em_convert_account_to_byte_stream(account_list+i, &size);
 
@@ -359,14 +379,12 @@ void stb_sync_header(HIPC_API a_hAPI)
 
        /* account_id */
        emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), &account_id);
-       EM_DEBUG_LOG("account_id [%d]", account_id);
-
        /* maibox_id */
        emipc_get_parameter(a_hAPI, ePARAMETER_IN, 1, sizeof(int), &maibox_id);
-       EM_DEBUG_LOG("maibox_id [%d]", maibox_id);
+       EM_DEBUG_LOG("account_id [%d] maibox_id [%d]", account_id, maibox_id);
 
-       if(emdaemon_sync_header(account_id, maibox_id, &handle, &err)) {
-               EM_DEBUG_LOG("emdaemon_sync_header success ");
+       if(!emdaemon_sync_header(account_id, maibox_id, &handle, &err)) {
+               EM_DEBUG_EXCEPTION ("emdaemon_sync_header failed [%d]", err);
        }
 
        if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
@@ -420,12 +438,13 @@ FINISH_OFF:
 void stb_create_mailbox(HIPC_API a_hAPI)
 {
        EM_DEBUG_FUNC_BEGIN();
-       int                 buffer_size                         = 0;
-       int                 err = EMAIL_ERROR_NONE;
-       char               *local_stream  = NULL;
-       int                 on_server           = 0;
-       email_mailbox_t mailbox = {0};
-       int             handle = 0; /* Added for cancelling mailbox creating  */
+       int                   buffer_size                       = 0;
+       int                   err = EMAIL_ERROR_NONE;
+       int                  *ret_nth_value = NULL;
+       char                 *local_stream  = NULL;
+       int                   on_server                 = 0;
+       email_mailbox_t   mailbox = { 0 };
+       int               handle = 0; /* Added for cancelling mailbox creating  */
 
        buffer_size = emipc_get_nth_parameter_length(a_hAPI, ePARAMETER_IN, 0);
        EM_DEBUG_LOG("size [%d]", buffer_size);
@@ -438,13 +457,19 @@ void stb_create_mailbox(HIPC_API a_hAPI)
 
        local_stream = emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, 0);
        em_convert_byte_stream_to_mailbox(local_stream, buffer_size, &mailbox);
-       EM_DEBUG_LOG("Mailbox name - %s", mailbox.mailbox_name);
+       EM_DEBUG_LOG_SEC("Mailbox name - %s", mailbox.mailbox_name);
 
-       on_server = *((int*)emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, 1));
+       if ((ret_nth_value = emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, 1)))
+               on_server = *ret_nth_value;
+       else
+               err = EMAIL_ERROR_IPC_SOCKET_FAILURE;
 
        emdaemon_add_mailbox(&mailbox, on_server, &handle, &err);
 
 FINISH_OFF:
+
+       emcore_free_mailbox(&mailbox);
+
        if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
                EM_DEBUG_EXCEPTION("emipc_add_parameter failed 1");
        if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &handle, sizeof(int)))
@@ -609,7 +634,7 @@ void stb_rename_mailbox(HIPC_API a_hAPI)
        emipc_get_parameter(a_hAPI, ePARAMETER_IN, 3, sizeof(int), &on_server);
        EM_DEBUG_LOG("on_server[%d]", on_server);
 
-       if ((err = emdaemon_rename_mailbox(mailbox_id, mailbox_path, mailbox_alias, on_server, &handle)) != EMAIL_ERROR_NONE) {
+       if ((err = emdaemon_rename_mailbox(mailbox_id, mailbox_path, mailbox_alias, NULL, 0, on_server, &handle)) != EMAIL_ERROR_NONE) {
                EM_DEBUG_EXCEPTION("emdaemon_rename_mailbox failed [%d]", err);
        }
 
@@ -628,6 +653,68 @@ void stb_rename_mailbox(HIPC_API a_hAPI)
        EM_DEBUG_FUNC_END();
 }
 
+void stb_rename_mailbox_ex(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int buffer_size  = 0;
+       int     err = EMAIL_ERROR_NONE;
+       int handle = 0;
+       int mailbox_id = 0;
+       int on_server = 0;
+       int eas_data_length = 0;
+       char *mailbox_path = NULL;
+       char *mailbox_alias = NULL;
+       void *eas_data = NULL;
+
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), &mailbox_id);
+       EM_DEBUG_LOG("mailbox_id[%d]", mailbox_id);
+
+       buffer_size = emipc_get_parameter_length(a_hAPI, ePARAMETER_IN, 1);
+       EM_DEBUG_LOG("mailbox_path string size[%d]", buffer_size);
+       if(buffer_size > 0)       {
+               mailbox_path = (char*)em_malloc(buffer_size);
+               emipc_get_parameter(a_hAPI, ePARAMETER_IN, 1, buffer_size, mailbox_path);
+               EM_DEBUG_LOG("mailbox_path [%s]", mailbox_path);
+       }
+
+       buffer_size = emipc_get_parameter_length(a_hAPI, ePARAMETER_IN, 2);
+       EM_DEBUG_LOG("mailbox_alias string size[%d]", buffer_size);
+       if(buffer_size > 0)       {
+               mailbox_alias = (char*)em_malloc(buffer_size);
+               emipc_get_parameter(a_hAPI, ePARAMETER_IN, 2, buffer_size, mailbox_alias);
+               EM_DEBUG_LOG("mailbox_alias [%s]", mailbox_alias);
+       }
+
+       eas_data_length = emipc_get_parameter_length(a_hAPI, ePARAMETER_IN, 3);
+       EM_DEBUG_LOG("eas_data_length  size[%d]", eas_data_length);
+       if(eas_data_length > 0)   {
+               eas_data = (char*)em_malloc(eas_data_length);
+               emipc_get_parameter(a_hAPI, ePARAMETER_IN, 3, eas_data_length, eas_data);
+       }
+
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 4, sizeof(int), &on_server);
+       EM_DEBUG_LOG("on_server[%d]", on_server);
+
+       if ((err = emdaemon_rename_mailbox(mailbox_id, mailbox_path, mailbox_alias, eas_data, eas_data_length, on_server, &handle)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emdaemon_rename_mailbox failed [%d]", err);
+       }
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed 1");
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &handle, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed 2");
+
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+
+       EM_SAFE_FREE(mailbox_alias);
+       EM_SAFE_FREE(mailbox_path);
+       EM_SAFE_FREE(eas_data);
+
+       EM_DEBUG_FUNC_END();
+}
+
 void stb_send_mail(HIPC_API a_hAPI)
 {
        EM_DEBUG_FUNC_BEGIN();
@@ -661,6 +748,35 @@ void stb_send_mail(HIPC_API a_hAPI)
        EM_DEBUG_FUNC_END();
 }
 
+void stb_query_smtp_mail_size_limit(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int account_id;
+       int handle;
+       int err = EMAIL_ERROR_NONE;
+
+       /* Mail_id */
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), &account_id);
+       EM_DEBUG_LOG("account_id [%d]", account_id);
+
+       if(emdaemon_query_smtp_mail_size_limit(account_id, &handle, &err)) {
+               err = EMAIL_ERROR_NONE;
+               if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter result failed ");
+               if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &handle, sizeof(int)))
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter result failed ");
+               if (!emipc_execute_stub_api(a_hAPI))
+                       EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+       } else {
+               if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed ");
+               if (!emipc_execute_stub_api(a_hAPI))
+                       EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+       }
+
+       EM_DEBUG_FUNC_END();
+}
 
 /* obsolete - there is no api calling this function */
 void stb_get_mailbox_list(HIPC_API a_hAPI)
@@ -688,7 +804,7 @@ void stb_get_mailbox_list(HIPC_API a_hAPI)
                        EM_DEBUG_EXCEPTION("emipc_add_parameter failed ");
 
                for(counter=0; counter<count; counter++) {
-                       EM_DEBUG_LOG("Name - %s", mailbox_list[counter].mailbox_name);
+                       EM_DEBUG_LOG_SEC("Name - %s", mailbox_list[counter].mailbox_name);
 
                        local_stream = em_convert_mailbox_to_byte_stream(mailbox_list+counter, &size);
 
@@ -848,15 +964,20 @@ void stb_get_rule(HIPC_API a_hAPI)
 {
        EM_DEBUG_FUNC_BEGIN();
        int err = EMAIL_ERROR_NONE;
+       int *ret_nth_value = NULL;
        int filter_id = 0;
        email_rule_t* rule = NULL;
        int size =0;
        char* local_rule_stream = NULL;
 
-       filter_id = *((int*)emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, 0));
-
-       emdaemon_get_filter(filter_id, &rule, &err);
+       if ((ret_nth_value = emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, 0))) {
+               filter_id = *ret_nth_value;
 
+               emdaemon_get_filter(filter_id, &rule, &err);
+       } else {
+               err = EMAIL_ERROR_IPC_SOCKET_FAILURE;   
+       }
+               
        if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
                EM_DEBUG_EXCEPTION("emipc_add_parameter failed ");
 
@@ -970,12 +1091,18 @@ void stb_update_rule(HIPC_API a_hAPI)
        int filter_id = 0;
        int buffer_size = 0;
        int err = EMAIL_ERROR_NONE;
+       int *ret_nth_value = NULL;
        char* rule_stream = NULL;
        email_rule_t rule = {0};
 
 
        /* get filter_id */
-       filter_id = *((int*) emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, 0));
+       if ((ret_nth_value = emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, 0))) {
+               filter_id = *ret_nth_value;
+       } else {
+               err = EMAIL_ERROR_IPC_SOCKET_FAILURE;
+               goto FINISH_OFF;
+       }
 
        /* get rule */
        buffer_size = emipc_get_nth_parameter_length(a_hAPI, ePARAMETER_IN, 1);
@@ -1110,15 +1237,18 @@ FINISH_OFF:
 void stb_add_mail(HIPC_API a_hAPI)
 {
        EM_DEBUG_FUNC_BEGIN();
-       int  buffer_size = 0;
-       int  local_result = 0;
-       int  result_attachment_data_count = 0;
-       int  param_index = 0;
-       int  sync_server = 0;
-       int  err = EMAIL_ERROR_NONE;
+       int buffer_size = 0;
+       int local_result = 0;
+       int result_attachment_data_count = 0;
+       int param_index = 0;
+       int sync_server = 0;
+       int err = EMAIL_ERROR_NONE;
+       int mdm_err = EMAIL_ERROR_NONE;
+       int i = 0;
        email_mail_data_t result_mail_data = {0};
        email_attachment_data_t *result_attachment_data = NULL;
        email_meeting_request_t result_meeting_request = {0};
+       emipc_email_api_info *api_info = (emipc_email_api_info *)a_hAPI;
 
 
        /* email_mail_data_t */;
@@ -1131,27 +1261,63 @@ void stb_add_mail(HIPC_API a_hAPI)
                em_convert_byte_stream_to_mail_data(stream, buffer_size, &result_mail_data);
        }
 
-       /* attachment */
-       if (result_mail_data.attachment_count > 0) {
-               buffer_size = emipc_get_nth_parameter_length(a_hAPI, ePARAMETER_IN, param_index);
-               EM_DEBUG_LOG("email_attachment_data_t buffer_size[%d]", buffer_size);
+       /* check smack rule for accessing file path */
+       if (result_mail_data.file_path_html) {
+               if (!emdaemon_check_smack_rule(api_info->response_id, result_mail_data.file_path_html)) {
+                       EM_DEBUG_EXCEPTION("emdaemon_check_smack_rule fail");
+                       err = EMAIL_ERROR_NO_SMACK_RULE;
+                       goto FINISH_OFF;
+               }
+       }
 
-               if(buffer_size > 0)      {
-                       char *stream = (char*) emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, param_index);
-                       em_convert_byte_stream_to_attachment_data(stream, buffer_size, &result_attachment_data, &result_attachment_data_count);
+       if (result_mail_data.file_path_plain) {
+               if (!emdaemon_check_smack_rule(api_info->response_id, result_mail_data.file_path_plain)) {
+                       EM_DEBUG_EXCEPTION("emdaemon_check_smack_rule fail");
+                       err = EMAIL_ERROR_NO_SMACK_RULE;
+                       goto FINISH_OFF;
+               }
+       }
+
+       if (result_mail_data.file_path_mime_entity) {
+               if (!emdaemon_check_smack_rule(api_info->response_id, result_mail_data.file_path_mime_entity)) {
+                       EM_DEBUG_EXCEPTION("emdaemon_check_smack_rule fail");
+                       err = EMAIL_ERROR_NO_SMACK_RULE;
+                       goto FINISH_OFF;
+               }
+       }
+       /* check smack rule - END */
 
-                       EM_DEBUG_LOG("result_attachment_data_count[%d]", result_attachment_data_count);
+       /* attachment */
+       buffer_size = emipc_get_nth_parameter_length(a_hAPI, ePARAMETER_IN, param_index);
+       EM_DEBUG_LOG("email_attachment_data_t buffer_size[%d]", buffer_size);
 
-                       if(result_attachment_data_count && !result_attachment_data) {
+       if(buffer_size > 0)      {
+               char *stream = (char*) emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, param_index);
+               em_convert_byte_stream_to_attachment_data(stream, buffer_size, &result_attachment_data, &result_attachment_data_count);
+
+               EM_DEBUG_LOG("result_attachment_data_count[%d]", result_attachment_data_count);
+               if (!result_attachment_data_count) {
+                       EM_DEBUG_LOG("Not include attachment data");
+               } else {
+                       if(!result_attachment_data) {
                                EM_DEBUG_EXCEPTION("em_convert_byte_stream_to_attachment_data failed");
                                err = EMAIL_ERROR_ON_PARSING;
                                goto FINISH_OFF;
                        }
+                       param_index++;
                }
-
-               param_index++;
        }
 
+       /* check smack rule for accessing file path */
+       for (i = 0; i < result_attachment_data_count ; i++) {
+               if (result_attachment_data[i].attachment_path) {
+                       if (!emdaemon_check_smack_rule(api_info->response_id, result_attachment_data[i].attachment_path)) {
+                               EM_DEBUG_EXCEPTION("emdaemon_check_smack_rule fail");
+                               err = EMAIL_ERROR_NO_SMACK_RULE;
+                               goto FINISH_OFF;
+                       }
+               }
+       }
 
        /* meeting request */
        EM_DEBUG_LOG("email_meeting_request_t");
@@ -1215,9 +1381,11 @@ void stb_update_mail(HIPC_API a_hAPI)
        int  sync_server = 0;
        int  *temp_buffer = NULL;
        int  err = EMAIL_ERROR_NONE;
+       int  i = 0;
        email_mail_data_t result_mail_data = {0};
        email_attachment_data_t *result_attachment_data = NULL;
        email_meeting_request_t result_meeting_request = {0};
+       emipc_email_api_info *api_info = (emipc_email_api_info *)a_hAPI;
 
        EM_DEBUG_LOG("email_mail_data_t");
        buffer_size = emipc_get_nth_parameter_length(a_hAPI, ePARAMETER_IN, param_index);
@@ -1227,27 +1395,61 @@ void stb_update_mail(HIPC_API a_hAPI)
                em_convert_byte_stream_to_mail_data(stream, buffer_size, &result_mail_data);
        }
 
-       if (result_mail_data.attachment_count > 0) {
-               buffer_size = emipc_get_nth_parameter_length(a_hAPI, ePARAMETER_IN, param_index);
-               EM_DEBUG_LOG("email_attachment_data_t buffer_size[%d]", buffer_size);
-
-               if(buffer_size > 0) {
-                       char *stream = (char*) emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, param_index);
-                       em_convert_byte_stream_to_attachment_data(stream, buffer_size, &result_attachment_data, &result_attachment_data_count);
+       /* check smack rule for accessing file path */
+       if (result_mail_data.file_path_html) {
+               if (!emdaemon_check_smack_rule(api_info->response_id, result_mail_data.file_path_html)) {
+                       EM_DEBUG_EXCEPTION("emdaemon_check_smack_rule fail");
+                       err = EMAIL_ERROR_NO_SMACK_RULE;
+                       goto FINISH_OFF;
+               }
+       }
 
-                       EM_DEBUG_LOG("result_attachment_data_count[%d]", result_attachment_data_count);
+       if (result_mail_data.file_path_plain) {
+               if (!emdaemon_check_smack_rule(api_info->response_id, result_mail_data.file_path_plain)) {
+                       EM_DEBUG_EXCEPTION("emdaemon_check_smack_rule fail");
+                       err = EMAIL_ERROR_NO_SMACK_RULE;
+                       goto FINISH_OFF;
+               }
+       }
 
-                       if(result_attachment_data_count && !result_attachment_data) {
+       if (result_mail_data.file_path_mime_entity) {
+               if (!emdaemon_check_smack_rule(api_info->response_id, result_mail_data.file_path_mime_entity)) {
+                       EM_DEBUG_EXCEPTION("emdaemon_check_smack_rule fail");
+                       err = EMAIL_ERROR_NO_SMACK_RULE;
+                       goto FINISH_OFF;
+               }
+       }
+       /* check smack rule - END */
+       buffer_size = emipc_get_nth_parameter_length(a_hAPI, ePARAMETER_IN, param_index);
+       if(buffer_size > 0)      {
+               char *stream = (char*) emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, param_index);
+               em_convert_byte_stream_to_attachment_data(stream, buffer_size, &result_attachment_data, &result_attachment_data_count);
+
+               EM_DEBUG_LOG("result_attachment_data_count[%d]", result_attachment_data_count);
+               if (!result_attachment_data_count) {
+                       EM_DEBUG_LOG("Not include attachment data");
+               } else {
+                       if(!result_attachment_data) {
                                EM_DEBUG_EXCEPTION("em_convert_byte_stream_to_attachment_data failed");
                                err = EMAIL_ERROR_ON_PARSING;
                                goto FINISH_OFF;
                        }
+                       param_index++;
                }
-               param_index++;
        }
 
-       EM_DEBUG_LOG("email_meeting_request_t");
+       /* check smack rule for accessing file path */
+       for (i = 0; i < result_attachment_data_count ; i++) {
+               if (result_attachment_data[i].attachment_path) {
+                       if (!emdaemon_check_smack_rule(api_info->response_id, result_attachment_data[i].attachment_path)) {
+                               EM_DEBUG_EXCEPTION("emdaemon_check_smack_rule fail");
+                               err = EMAIL_ERROR_NO_SMACK_RULE;
+                               goto FINISH_OFF;
+                       }
+               }
+       }
 
+       EM_DEBUG_LOG("email_meeting_request_t");
        if ( result_mail_data.meeting_request_status == EMAIL_MAIL_TYPE_MEETING_REQUEST
                || result_mail_data.meeting_request_status == EMAIL_MAIL_TYPE_MEETING_RESPONSE
                || result_mail_data.meeting_request_status == EMAIL_MAIL_TYPE_MEETING_ORIGINATINGREQUEST) {
@@ -1522,8 +1724,10 @@ void stb_add_attachment(HIPC_API a_hAPI)
        int err = EMAIL_ERROR_NONE;
        int mail_id = -1;
        int attachment_count = 0;
+       int i = 0;
        char* attachment_stream = NULL;
        email_attachment_data_t* attachment = NULL;
+       emipc_email_api_info *api_info = (emipc_email_api_info *)a_hAPI;
 
        /* mail_id */
        emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), &mail_id);
@@ -1543,11 +1747,25 @@ void stb_add_attachment(HIPC_API a_hAPI)
 
        if (!attachment) {
                EM_DEBUG_EXCEPTION("em_convert_byte_stream_to_attachment_data failed  ");
-               return;
+               err = EMAIL_ERROR_ON_PARSING;
+               goto FINISH_OFF;
+       }
+
+       /* check smack rule for accessing file path */
+       for (i = 0; i < attachment_count ; i++) {
+               if (attachment[i].attachment_path) {
+                       if (!emdaemon_check_smack_rule(api_info->response_id, attachment[i].attachment_path)) {
+                               EM_DEBUG_EXCEPTION("emdaemon_check_smack_rule fail");
+                               err = EMAIL_ERROR_NO_SMACK_RULE;
+                               goto FINISH_OFF;
+                       }
+               }
        }
 
        emdaemon_add_attachment(mail_id, attachment, &err);
 
+FINISH_OFF:
+
        if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
                EM_DEBUG_EXCEPTION("emipc_add_parameter local_result failed ");
        if(EMAIL_ERROR_NONE == err) {
@@ -1773,10 +1991,8 @@ void stb_cancel_job(HIPC_API a_hAPI)
        int err = EMAIL_ERROR_NONE;
 
        emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), &account_id);
-       EM_DEBUG_LOG("account_id [%d]", account_id);
-
        emipc_get_parameter(a_hAPI, ePARAMETER_IN, 1, sizeof(int), &handle);
-       EM_DEBUG_LOG("handle [%d]", handle);
+       EM_DEBUG_LOG("account_id [%d] handle [%d]", account_id, handle);
 
        if(emdaemon_cancel_job(account_id, handle, &err))
                err = EMAIL_ERROR_NONE;
@@ -1968,7 +2184,7 @@ void stb_add_account_with_validation(HIPC_API a_hAPI)
        }
 
        ref_check_interval = ref_account->check_interval;
-       ref_account_id = ref_account->account_id;
+       ref_account_id     = ref_account->account_id;
 
        if(!emdaemon_validate_account_and_create(ref_account, &handle, &err)) {
                EM_DEBUG_EXCEPTION("emdaemon_validate_account_and_create fail [%d]", err);
@@ -1976,8 +2192,8 @@ void stb_add_account_with_validation(HIPC_API a_hAPI)
        }
 #ifdef __FEATURE_AUTO_POLLING__
        /*  start auto polling, if check_interval not zero */
-       if(ref_check_interval > 0) {
-               if(!emdaemon_add_polling_alarm(ref_account_id, ref_check_interval))
+       if(ref_check_interval > 0 || (ref_account->peak_days && ref_account->peak_interval > 0)) {
+               if(!emdaemon_add_polling_alarm(ref_account_id))
                        EM_DEBUG_EXCEPTION("emdaemon_add_polling_alarm[NOTI_ACCOUNT_ADD] : start auto poll failed >>> ");
        }
 #endif /*  __FEATURE_AUTO_POLLING__ */
@@ -2022,7 +2238,7 @@ void stb_backup_account(HIPC_API a_hAPI)
                EM_DEBUG_LOG("file_path_length [%d]", file_path_length);
                file_path = em_malloc(file_path_length);
                emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, file_path_length, file_path);
-               EM_DEBUG_LOG("file_path [%s]", file_path);
+               EM_DEBUG_LOG_SEC("file_path [%s]", file_path);
                local_result = emcore_backup_accounts((const char*)file_path, &err_code);
        }
 
@@ -2056,7 +2272,7 @@ void stb_restore_account(HIPC_API a_hAPI)
                EM_DEBUG_LOG("file_path_length [%d]", file_path_length);
                file_path = em_malloc(file_path_length);
                emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, file_path_length, file_path);
-               EM_DEBUG_LOG("file_path [%s]", file_path);
+               EM_DEBUG_LOG_SEC("file_path [%s]", file_path);
                local_result = emcore_restore_accounts((const char*)file_path, &err_code);
        }
 
@@ -2082,13 +2298,16 @@ void stb_get_password_length(HIPC_API a_hAPI)
 {
        EM_DEBUG_FUNC_BEGIN();
        int account_id = 0;
+       int password_type = 0;
        int local_result = 0;
        int err_code = 0;
        int password_length = 0;
 
        /* account_id */
        emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), &account_id);
-       local_result = emstorage_get_password_length_of_account(account_id, &password_length,&err_code);
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 1, sizeof(int), &password_type);
+
+       local_result = emstorage_get_password_length_of_account(account_id, password_type, &password_length,&err_code);
 
        EM_DEBUG_LOG("password_length [%d]", password_length);
 
@@ -2147,6 +2366,7 @@ void stb_add_certificate(HIPC_API a_hAPI)
        int email_address_len = 0;
        char *cert_file_path = NULL;
        char *email_address = NULL;
+       emipc_email_api_info *api_info = (emipc_email_api_info *)a_hAPI;
 
        cert_file_len = emipc_get_parameter_length(a_hAPI, ePARAMETER_IN, 0);
        if (cert_file_len > 0) {
@@ -2154,6 +2374,15 @@ void stb_add_certificate(HIPC_API a_hAPI)
                emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, cert_file_len, cert_file_path);
        }
 
+       /* check smack rule for accessing file path */
+       if (cert_file_path) {
+               if (!emdaemon_check_smack_rule(api_info->response_id, cert_file_path)) {
+                       EM_DEBUG_EXCEPTION("emdaemon_check_smack_rule fail");
+                       err = EMAIL_ERROR_NO_SMACK_RULE;
+                       goto FINISH_OFF;
+               }
+       }
+
        email_address_len = emipc_get_parameter_length(a_hAPI, ePARAMETER_IN, 1);
        if (email_address_len > 0) {
                email_address = em_malloc(email_address_len + 1);
@@ -2164,6 +2393,8 @@ void stb_add_certificate(HIPC_API a_hAPI)
                EM_DEBUG_EXCEPTION("em_core_smime_add_certificate failed");
        }
 
+FINISH_OFF:
+
        if (!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
                EM_DEBUG_EXCEPTION("emipc_add_parameter local_result failed ");
 
@@ -2174,9 +2405,9 @@ void stb_add_certificate(HIPC_API a_hAPI)
        if (!emipc_execute_stub_api(a_hAPI))
                EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
 
-       EM_SAFE_FREE(cert_file_path);          
-       EM_SAFE_FREE(email_address); 
-       EM_DEBUG_FUNC_END();    
+       EM_SAFE_FREE(cert_file_path);
+       EM_SAFE_FREE(email_address);
+       EM_DEBUG_FUNC_END();
 }
 
 void stb_delete_certificate(HIPC_API a_hAPI)
@@ -2191,7 +2422,7 @@ void stb_delete_certificate(HIPC_API a_hAPI)
                EM_DEBUG_LOG("email address string length [%d]", email_address_len);
                email_address = em_malloc(email_address_len + 1);
                emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, email_address_len, email_address);
-               EM_DEBUG_LOG("email address [%s]", email_address);
+               EM_DEBUG_LOG_SEC("email address [%s]", email_address);
        }
 
        SNPRINTF(temp_email_address, sizeof(temp_email_address), "<%s>", email_address);
@@ -2317,11 +2548,13 @@ void stb_ping_service(HIPC_API a_hAPI)
 {
        EM_DEBUG_FUNC_BEGIN();
        int err = EMAIL_ERROR_NONE;
+
        if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
                EM_DEBUG_EXCEPTION("emipc_add_parameter failed ");
 
        if (!emipc_execute_stub_api(a_hAPI))
-               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");  
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+
        EM_DEBUG_FUNC_END();
 }
 
@@ -2329,13 +2562,20 @@ void stb_update_notification_bar_for_unread_mail(HIPC_API a_hAPI)
 {
        EM_DEBUG_FUNC_BEGIN();
        int err = EMAIL_ERROR_NONE, account_id;
+       int total_mail_count = 0, unread_mail_count = 0;
 
        /* account_id */
        emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), &account_id);
        EM_DEBUG_LOG("account_id [%d]", account_id);
 
-       if(!emcore_finalize_sync(account_id, &err)) {
-               EM_DEBUG_EXCEPTION("emcore_finalize_sync failed [%d]", err);
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 1, sizeof(int), &total_mail_count);
+       EM_DEBUG_LOG("total_mail_count [%d]", total_mail_count);
+
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 2, sizeof(int), &unread_mail_count);
+       EM_DEBUG_LOG("unread_mail_count [%d]", unread_mail_count);
+
+       if(!emdaemon_finalize_sync(account_id, total_mail_count, unread_mail_count, &err)) {
+               EM_DEBUG_EXCEPTION("emdaemon_finalize_sync failed [%d]", err);
        }
 
        if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
@@ -2396,6 +2636,7 @@ void stb_write_mime_file(HIPC_API a_hAPI)
        email_attachment_data_t *result_attachment_data = NULL;
        emstorage_mail_tbl_t *input_mail_tbl_data = NULL;
        emstorage_attachment_tbl_t *input_attachment_tbl_data = NULL;
+       emipc_email_api_info *api_info = (emipc_email_api_info *)a_hAPI;
        
        /* email_mail_data_t */;
        buffer_size = emipc_get_nth_parameter_length(a_hAPI, ePARAMETER_IN, param_index);
@@ -2407,32 +2648,68 @@ void stb_write_mime_file(HIPC_API a_hAPI)
                em_convert_byte_stream_to_mail_data(stream, buffer_size, &result_mail_data);
        }
 
-       /* attachment */
-       if (result_mail_data.attachment_count > 0) {
-               buffer_size = emipc_get_nth_parameter_length(a_hAPI, ePARAMETER_IN, param_index);
-               EM_DEBUG_LOG("email_attachment_data_t buffer_size[%d]", buffer_size);
+       /* check smack rule for accessing file path */
+       if (result_mail_data.file_path_html) {
+               if (!emdaemon_check_smack_rule(api_info->response_id, result_mail_data.file_path_html)) {
+                       EM_DEBUG_EXCEPTION("emdaemon_check_smack_rule fail");
+                       err = EMAIL_ERROR_NO_SMACK_RULE;
+                       goto FINISH_OFF;
+               }
+       }
 
-               if(buffer_size > 0) {
-                       char *stream = (char*) emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, param_index);
-                       em_convert_byte_stream_to_attachment_data(stream, buffer_size, &result_attachment_data, &result_attachment_data_count);
+       if (result_mail_data.file_path_plain) {
+               if (!emdaemon_check_smack_rule(api_info->response_id, result_mail_data.file_path_plain)) {
+                       EM_DEBUG_EXCEPTION("emdaemon_check_smack_rule fail");
+                       err = EMAIL_ERROR_NO_SMACK_RULE;
+                       goto FINISH_OFF;
+               }
+       }
+
+       if (result_mail_data.file_path_mime_entity) {
+               if (!emdaemon_check_smack_rule(api_info->response_id, result_mail_data.file_path_mime_entity)) {
+                       EM_DEBUG_EXCEPTION("emdaemon_check_smack_rule fail");
+                       err = EMAIL_ERROR_NO_SMACK_RULE;
+                       goto FINISH_OFF;
+               }
+       }
+       /* check smack rule - END */
 
-                       EM_DEBUG_LOG("result_attachment_data_count[%d]", result_attachment_data_count);
+       /* attachment */
+       buffer_size = emipc_get_nth_parameter_length(a_hAPI, ePARAMETER_IN, param_index);
+       EM_DEBUG_LOG("email_attachment_data_t buffer_size[%d]", buffer_size);
+
+       if(buffer_size > 0) {
+               char *stream = (char*) emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, param_index);
+               em_convert_byte_stream_to_attachment_data(stream, buffer_size, &result_attachment_data, &result_attachment_data_count);
 
-                       if(result_attachment_data_count && !result_attachment_data) {
+               EM_DEBUG_LOG("result_attachment_data_count[%d]", result_attachment_data_count);
+               if (!result_attachment_data_count) {
+                       EM_DEBUG_LOG("Not include attachment data");
+               } else {
+                       if(!result_attachment_data) {
                                EM_DEBUG_EXCEPTION("em_convert_byte_stream_to_attachment_data failed");
                                err = EMAIL_ERROR_ON_PARSING;
                                goto FINISH_OFF;
                        }
+                       param_index++;
                }
+       }
 
-               param_index++;
+       /* check smack rule for accessing file path */
+       for (i = 0; i < result_attachment_data_count ; i++) {
+               if (result_attachment_data[i].attachment_path && result_attachment_data[i].save_status) {
+                       if (!emdaemon_check_smack_rule(api_info->response_id, result_attachment_data[i].attachment_path)) {
+                               EM_DEBUG_EXCEPTION("emdaemon_check_smack_rule fail");
+                               err = EMAIL_ERROR_NO_SMACK_RULE;
+                               goto FINISH_OFF;
+                       }
+               }
        }
 
-       
        buffer_size = emipc_get_nth_parameter_length(a_hAPI, ePARAMETER_IN, param_index);
        if (buffer_size > 0) {
                output_file_path = (char *)emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, param_index);
-               EM_DEBUG_LOG("output_file_path : [%s]", output_file_path);
+               EM_DEBUG_LOG_SEC("output_file_path : [%s]", output_file_path);
        }
 
        /* Convert mail_data to mail_tbl */
@@ -2465,11 +2742,6 @@ void stb_write_mime_file(HIPC_API a_hAPI)
                input_attachment_tbl_data[i].attachment_mime_type = EM_SAFE_STRDUP(result_attachment_data[i].attachment_mime_type);
        }
 
-       if ((err = em_verify_email_address_of_mail_tbl(input_mail_tbl_data, false)) != EMAIL_ERROR_NONE) {
-               EM_DEBUG_EXCEPTION("em_verify_email_address_of_mail_tbl failed : [%d]", err);
-               goto FINISH_OFF;
-       }
-
        if (!emcore_make_rfc822_file_from_mail(input_mail_tbl_data, input_attachment_tbl_data, result_attachment_data_count, NULL, &file_path, NULL, &err)) {
                EM_DEBUG_EXCEPTION("emcore_make_rfc822_file_from_mail failed");
                goto FINISH_OFF;
@@ -2485,11 +2757,8 @@ void stb_write_mime_file(HIPC_API a_hAPI)
                output_file_path = EM_SAFE_STRDUP(file_path);
        }
 
-
-       if (!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, (char *)output_file_path, EM_SAFE_STRLEN(output_file_path) + 1)) {
-               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
-               err = EMAIL_ERROR_NULL_VALUE;
-               goto FINISH_OFF;
+       if (!emdaemon_set_smack_label(output_file_path, "system::media")) {
+               EM_DEBUG_EXCEPTION("emdaemon_set_smack_label failed");
        }
 
        local_result = 1;
@@ -2498,6 +2767,15 @@ FINISH_OFF:
        if ( local_result == 0 ) {
                if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
                        EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+       } else {
+               if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+
+               if (!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, (char *)output_file_path, EM_SAFE_STRLEN(output_file_path) + 1)) {
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+                       err = EMAIL_ERROR_NULL_VALUE;
+                       goto FINISH_OFF;
+               }
        }
 
        if (!emipc_execute_stub_api(a_hAPI))
@@ -2568,6 +2846,7 @@ void stb_validate_account_ex(HIPC_API a_hAPI)
                goto FINISH_OFF;
        }
 
+       /* ref_account will be removed by worker_event_queue() */
        if((err = emdaemon_validate_account_ex(ref_account, &handle)) != EMAIL_ERROR_NONE) {
                EM_DEBUG_EXCEPTION("emdaemon_validate_account_ex fail [%d]", err);
                goto FINISH_OFF;
@@ -2591,9 +2870,6 @@ FINISH_OFF:
                        EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
        }
 
-/*     note: account is freed in thread_func_branch_command, which is run by other thread */
-/*     emcore_free_account(account); */
-
        EM_DEBUG_FUNC_END();
 }
 void stb_handle_task(int task_type, HIPC_API a_hAPI)
@@ -2944,8 +3220,24 @@ FINISH_OFF:
 void stb_API_mapper(HIPC_API a_hAPI)
 {
        EM_DEBUG_FUNC_BEGIN();
+       int err = EMAIL_ERROR_NONE;
        int nAPIID = emipc_get_api_id(a_hAPI);
 
+#ifdef __FEATURE_ACCESS_CONTROL__
+       int nAPPID = emipc_get_app_id(a_hAPI);
+               err = em_check_socket_privilege_by_pid(nAPPID);
+               if (err == EMAIL_ERROR_PERMISSION_DENIED) {
+                       EM_DEBUG_LOG("permission denied");
+                       if (!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+                               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+
+                       if (!emipc_execute_stub_api(a_hAPI))
+                               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed");
+
+                       return;
+               }
+#endif
+
        switch(nAPIID) {
                case _EMAIL_API_ADD_ACCOUNT:
                        stb_create_account(a_hAPI);
@@ -2975,10 +3267,18 @@ void stb_API_mapper(HIPC_API a_hAPI)
                        stb_rename_mailbox(a_hAPI);
                        break;
 
+               case _EMAIL_API_RENAME_MAILBOX_EX:
+                       stb_rename_mailbox_ex(a_hAPI);
+                       break;
+
                case _EMAIL_API_SEND_MAIL:
                        stb_send_mail(a_hAPI);
                        break;
 
+               case _EMAIL_API_QUERY_SMTP_MAIL_SIZE_LIMIT:
+                       stb_query_smtp_mail_size_limit(a_hAPI);
+                       break;
+
                case _EMAIL_API_GET_MAILBOX_LIST:
                        stb_get_mailbox_list(a_hAPI);
                        break;
@@ -3219,6 +3519,43 @@ static void callback_for_sigterm(int signum)
        EM_DEBUG_FUNC_END();
 }
 
+gboolean callback_for_timeout(gpointer user_data)
+{
+       EM_DEBUG_FUNC_BEGIN("user_data[%p]", user_data);
+
+       if(emipc_get_launch_method() != EMAIL_LAUNCHED_BY_DBUS_ACTIVATION) {
+               emdaemon_kill_daemon_if_no_account();
+       }
+
+       EM_DEBUG_FUNC_END();
+       return FALSE;
+}
+
+gboolean callback_for_del_account (GIOChannel *ch, GIOCondition cond, gpointer data)
+{
+       static int file_del = 0;
+       static int db_del = 0;
+       int event = 0;
+       gsize len = 0;
+       g_io_channel_read_chars (ch, (gchar*) &event, sizeof (event), &len, NULL);
+
+       if (event==EMAIL_SIGNAL_DB_DELETED) {
+               db_del = 1;
+       }
+       else if (event==EMAIL_SIGNAL_FILE_DELETED) {
+               file_del = 1;
+       }
+       EM_DEBUG_LOG ("callback_for_del_account called file_del[%d] db_del[%d]", file_del, db_del);
+
+       /* if called twice, process termination begins. 
+          two threads should complete the delete task */
+       if (file_del && db_del) {
+               emdaemon_kill_daemon_if_no_account();
+               file_del = db_del = 0; /* if there is an account, reset status */
+       }
+       return TRUE;
+}
+
 INTERNAL_FUNC int main(int argc, char *argv[])
 {
        /* Do the email-service Initialization 
@@ -3255,11 +3592,9 @@ INTERNAL_FUNC int main(int argc, char *argv[])
        
        /* Clean up resources */
        g_main_loop_unref(mainloop);
-
        g_mainloop = NULL;
 
        emipc_finalize_stub();
-
        emdaemon_finalize(NULL);
 
        EM_DEBUG_FUNC_END();
index b85a4db..e0438db 100755 (executable)
@@ -27,6 +27,7 @@
 #include "email-types.h"\r
 #include "email-debug-log.h"\r
 #include "email-dbus-activation.h"\r
+#include "email-daemon-init.h"\r
 #include "email-service-binding.h"\r
 #include "email-service-glue.h"\r
 #include <unistd.h>\r
 \r
 G_DEFINE_TYPE(EmailService, email_service, G_TYPE_OBJECT)\r
 \r
+int _launch_method = EMAIL_LAUNCHED_BY_UNKNOWN_METHOD;\r
+\r
+EXPORT_API void emipc_set_launch_method(int input_launch_method)\r
+{\r
+       EM_DEBUG_LOG("input_launch_method [%d]", input_launch_method);\r
+       _launch_method = input_launch_method;\r
+}\r
+\r
+EXPORT_API int emipc_get_launch_method()\r
+{\r
+       EM_DEBUG_LOG("_launch_method[%d]", _launch_method);\r
+       return _launch_method;\r
+}\r
+\r
 static void email_service_init(EmailService *email_service)\r
 {\r
        EM_DEBUG_LOG("email_service_init entered");\r
@@ -46,6 +61,15 @@ static void email_service_class_init(EmailServiceClass *email_service_class)
        dbus_g_object_type_install_info(EMAIL_SERVICE_TYPE, &dbus_glib_email_service_object_info);\r
 }\r
 \r
+gboolean daemon_launched = false;\r
+\r
+gboolean callback_for_timeout (void *arg)\r
+{\r
+       if (!daemon_launched)\r
+               EM_DEBUG_EXCEPTION ("org_tizen_email_service_launch is not responding");\r
+       return FALSE;\r
+}\r
+\r
 EXPORT_API int emipc_launch_email_service()\r
 {\r
        EM_DEBUG_FUNC_BEGIN();\r
index 7592427..7e32541 100755 (executable)
@@ -61,4 +61,7 @@ gboolean email_service_launch(EmailService *email_service, guint *result_val, GE
 EXPORT_API int emipc_init_dbus_connection();\r
 EXPORT_API int emipc_launch_email_service();\r
 \r
+EXPORT_API void emipc_set_launch_method(int input_launch_method);\r
+EXPORT_API int  emipc_get_launch_method();\r
+\r
 #endif /* __EMAIL_DBUS_ACTIVATION_H__ */\r
index 33fe936..c2d527f 100755 (executable)
@@ -20,6 +20,7 @@
 */
 
 #include <malloc.h>
+#include <unistd.h>
 
 #include "email-ipc.h"
 #include "email-ipc-build.h"
@@ -51,6 +52,7 @@ EXPORT_API HIPC_API emipc_create_email_api(long api_id)
        }
 
        api_info->api_id = api_id;
+       api_info->app_id = getpid();
 
        return (HIPC_API)api_info;
 }
@@ -58,6 +60,8 @@ EXPORT_API HIPC_API emipc_create_email_api(long api_id)
 EXPORT_API void emipc_destroy_email_api(HIPC_API api)
 {
        EM_DEBUG_FUNC_BEGIN("API = %p", api);
+       if (!api)
+               return;
        emipc_email_api_info *api_info = (emipc_email_api_info *)api;
        emipc_free_api_info(api_info);
        EM_SAFE_FREE(api_info);
@@ -67,6 +71,7 @@ EXPORT_API long emipc_get_api_id(HIPC_API api)
 {
        EM_DEBUG_FUNC_BEGIN();
        emipc_email_api_info *api_info = (emipc_email_api_info*)api;
+       EM_DEBUG_FUNC_END("api_id [%d]", api_info->api_id);
        return api_info->api_id;
 }
 
index b963da7..bfec354 100755 (executable)
@@ -56,7 +56,6 @@ EXPORT_API bool emipc_destroy_param_list(emipc_param_list *param_list)
        int index = 0;
 
        if (!param_list) {
-               EM_DEBUG_EXCEPTION("Invalid parameter.");
                return false;
        }
 
@@ -85,7 +84,7 @@ EXPORT_API bool emipc_parse_stream_of_param_list(emipc_param_list *param_list, v
 
        int stream_len = malloc_usable_size(stream);
        int remain_len = stream_len - (sizeof(long) * eSTREAM_DATA);
-       EM_DEBUG_LOG("Allocated stream size : %dbyte", stream_len);
+       EM_DEBUG_LOG_DEV ("Allocated stream size : %dbyte", stream_len);
 
        unsigned char* cur = ((unsigned char*)stream) + sizeof(int)*eSTREAM_DATA;
 
@@ -128,15 +127,12 @@ EXPORT_API unsigned char *emipc_serialize_param_list(emipc_param_list *param_lis
 {
        EM_DEBUG_FUNC_BEGIN("param_list [%p] stream_length [%p]", param_list, stream_length);
 
-       if(param_list == NULL) {
-               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+       if (!param_list) {
+               EM_DEBUG_LOG ("no data to be serialized");
                return NULL;
        }
 
-       if(param_list->byte_stream) {
-               EM_DEBUG_LOG("param_list->byte_stream exist");
-               goto FINISH_OFF;
-       }
+       EM_SAFE_FREE (param_list->byte_stream);
 
        int stream_len = emipc_sum_param_list_length (param_list);
 
index 6b571c7..35fcb66 100755 (executable)
@@ -26,7 +26,6 @@
 #include <stdio.h>
 
 #include "email-ipc.h"
-#include "email-ipc-api-info.h"
 #include "email-ipc-param-list.h"
 
 typedef struct {
@@ -186,6 +185,9 @@ EXPORT_API bool emipc_free_api_info(emipc_email_api_info *api_info);
                        case _EMAIL_API_VALIDATE_ACCOUNT :\
                                        s = "_EMAIL_API_VALIDATE_ACCOUNT";\
                                        break;\
+                       case _EMAIL_API_VALIDATE_ACCOUNT_EX :\
+                                       s = "_EMAIL_API_VALIDATE_ACCOUNT_EX";\
+                                       break;\
                        case _EMAIL_API_SEND_MAIL_CANCEL_JOB :\
                                        s = "_EMAIL_API_SEND_MAIL_CANCEL_JOB";\
                                        break;\
index ed11691..ccc117f 100755 (executable)
 #include "email-ipc-param-list.h"
 #include "email-ipc-socket.h"
 #include "email-proxy-main.h"
+#include "email-proxy-socket.h"
 
 #include "email-debug-log.h"
 #include "email-api.h"
 #include "email-types.h"
 #include "email-internal-types.h"
 #include "email-dbus-activation.h"
+#include "email-storage.h"
 
-EXPORT_API int emipc_initialize_proxy()
+EXPORT_API int emipc_initialize_proxy ()
 {
        EM_DEBUG_FUNC_BEGIN();
 
@@ -61,14 +63,14 @@ EXPORT_API int emipc_execute_proxy_api(HIPC_API api)
        int err = EMAIL_ERROR_NONE;
        emipc_email_api_info *api_info = (emipc_email_api_info *)api;
 
-       EM_DEBUG_LOG("API [%p]", api_info);
+       EM_DEBUG_LOG_DEV ("API [%p]", api_info);
 
        if(api_info == NULL) {
                EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
                return EMAIL_ERROR_INVALID_PARAM;
        }
 
-       EM_DEBUG_LOG("APIID [%s], ResponseID [%d], APPID[%d]",
+       EM_DEBUG_LOG_SEC("Request: API_ID[%s] RES_ID[%d] APP_ID[%d]",\
                                EM_APIID_TO_STR(api_info->api_id), api_info->response_id, api_info->app_id);
 
        ret = emipc_execute_api_of_proxy_main(api_info);
@@ -87,7 +89,7 @@ EXPORT_API int emipc_execute_proxy_api(HIPC_API api)
 
                ret = emipc_execute_api_of_proxy_main(api_info);
                if (!ret) {
-                       EM_DEBUG_EXCEPTION("emipc_proxy_main : emipc_execute_api failed [%d]", err);
+                       EM_DEBUG_EXCEPTION("emipc_execute_api_of_proxy_main failed [%d]", err);
                        err = EMAIL_ERROR_CONNECTION_FAILURE;
                        goto FINISH_OFF;
                }
index 2155050..b3c130e 100755 (executable)
@@ -41,7 +41,7 @@ EXPORT_API bool emipc_finalize_stub()
 
 EXPORT_API bool emipc_execute_stub_api(HIPC_API api)
 {
-       EM_DEBUG_LOG("ipcEmailStub_ExecuteAPI [%x]", api);
+       EM_DEBUG_LOG_DEV ("ipcEmailStub_ExecuteAPI [%x]", api);
        emipc_email_api_info *api_info = (emipc_email_api_info *)api;
        if (api_info == NULL)
                return false;
index f58b1da..af730a9 100755 (executable)
@@ -39,7 +39,7 @@ EXPORT_API int emipc_initialize_proxy_main()
        int sock_fd = 0;
 
        sock_fd = emipc_get_proxy_socket_id();
-       
+
        if (sock_fd) {
                EM_DEBUG_LOG("Socket already initialized");
                return EMAIL_ERROR_IPC_ALREADY_INITIALIZED;
@@ -58,8 +58,8 @@ EXPORT_API int emipc_initialize_proxy_main()
 EXPORT_API int emipc_finalize_proxy_main()
 {
        EM_DEBUG_FUNC_BEGIN();
-       if (!emipc_end_proxy_socket()) {
-               EM_DEBUG_EXCEPTION("emipc_finalize_proxy_main failed");
+       if (!emipc_end_all_proxy_sockets()) {
+               EM_DEBUG_EXCEPTION("emipc_end_all_proxy_sockets failed");
                return EMAIL_ERROR_IPC_SOCKET_FAILURE;
        }
 
@@ -91,7 +91,7 @@ EXPORT_API bool emipc_execute_api_of_proxy_main(emipc_email_api_info *api_info)
 
        sending_bytes = emipc_send_proxy_socket(in_stream, length);
 
-       EM_DEBUG_LOG("Proxy=>stub sending %d byte.", sending_bytes);
+       /*EM_DEBUG_LOG("Proxy=>stub sending %d byte.", sending_bytes);*/
 
        if (sending_bytes > 0) {
 #ifdef IPCLIB_STREAM_TRACE_ON
index 2e45c48..6d5fa5a 100644 (file)
@@ -58,8 +58,17 @@ EXPORT_API bool emipc_start_proxy_socket()
                return false;
        }
 
+#ifdef __FEATURE_ACCESS_CONTROL__
+       int err = EMAIL_ERROR_NONE;
+       err = em_check_socket_privilege_by_pid(getpid());
+       if (err == EMAIL_ERROR_PERMISSION_DENIED) {
+               EM_DEBUG_LOG("permission denied");
+               return false;
+       }
+#endif
+
        ret = emipc_connect_email_socket(socket_fd);
-       if( !ret ) {
+       if (!ret) {
                EM_DEBUG_EXCEPTION("emipc_connect_email_socket failed");
                return false;
        }
@@ -85,7 +94,44 @@ EXPORT_API bool emipc_start_proxy_socket()
 EXPORT_API bool emipc_end_proxy_socket()
 {
        EM_DEBUG_FUNC_BEGIN();
-       EM_DEBUG_LOG("[IPCLib] emipc_end_proxy_socket_fd");
+       EM_DEBUG_LOG("[IPCLib] emipc_end_proxy_socket");
+       pthread_t tid = pthread_self();
+
+       ENTER_CRITICAL_SECTION(proxy_mutex);
+       GList *cur = socket_head;
+       while( cur ) {
+               thread_socket_t* cur_socket = g_list_nth_data(cur,0);
+
+               /* close the socket of current thread */
+               if( tid == cur_socket->tid ) {
+#ifdef __FEATURE_ACCESS_CONTROL__
+                       int err = EMAIL_ERROR_NONE;
+                       err = em_check_socket_privilege_by_pid(cur_socket->pid);
+                       if (err == EMAIL_ERROR_PERMISSION_DENIED) {
+                               LEAVE_CRITICAL_SECTION(proxy_mutex); /*prevent 30968*/
+                               EM_DEBUG_LOG("permission denied");
+                               return false;
+                       }
+#endif
+                       emipc_close_email_socket(&cur_socket->socket_fd);
+                       EM_SAFE_FREE(cur_socket);
+                       GList *del = cur;
+                       cur = g_list_next(cur);
+                       socket_head = g_list_remove_link(socket_head, del);
+                       break;
+               }
+
+               cur = g_list_next(cur);
+       }
+       LEAVE_CRITICAL_SECTION(proxy_mutex);
+
+       return true;
+}
+
+EXPORT_API bool emipc_end_all_proxy_sockets()
+{
+       EM_DEBUG_FUNC_BEGIN();
+       EM_DEBUG_LOG("[IPCLib] emipc_end_all_proxy_sockets");
 
        pid_t pid = getpid();
 
@@ -96,6 +142,16 @@ EXPORT_API bool emipc_end_proxy_socket()
 
                /* close all sockets of the pid */
                if( pid == cur_socket->pid ) {
+#ifdef __FEATURE_ACCESS_CONTROL__
+                       int err = EMAIL_ERROR_NONE;
+                       err = em_check_socket_privilege_by_pid(cur_socket->pid);
+                       if (err == EMAIL_ERROR_PERMISSION_DENIED) {
+                               LEAVE_CRITICAL_SECTION(proxy_mutex); /*prevent 30967*/
+                               EM_DEBUG_LOG("permission denied");
+                               return false;
+                       }
+#endif
+
                        emipc_close_email_socket(&cur_socket->socket_fd);
                        EM_SAFE_FREE(cur_socket);
                        GList *del = cur;
@@ -164,7 +220,10 @@ EXPORT_API int emipc_get_proxy_socket_id()
  */
 static bool wait_for_reply (int fd)
 {
+       int return_from_select = -1;
        fd_set fds;
+       struct timeval tv;
+       char errno_buf[ERRNO_BUF_SIZE] = {0};
 
        if (fd == 0) {
                EM_DEBUG_EXCEPTION("Invalid file description : [%d]", fd);
@@ -174,8 +233,17 @@ static bool wait_for_reply (int fd)
        FD_ZERO(&fds);
        FD_SET(fd, &fds);
 
-       if (select(fd + 1, &fds, NULL, NULL, NULL) == -1) {
-               EM_DEBUG_EXCEPTION("[IPCLib] select: %s", strerror(errno) );
+       tv.tv_sec  = 20; /* should be tuned */
+       tv.tv_usec = 0;
+
+       EM_DEBUG_LOG_DEV ("wait for response [%d]", fd);
+
+       if ((return_from_select = select(fd + 1, &fds, NULL, NULL, &tv)) == -1) {
+               EM_DEBUG_EXCEPTION("[IPCLib] select failed: %s", EM_STRERROR(errno_buf));
+               return false;
+       }
+       else if (return_from_select == 0) {
+               EM_DEBUG_EXCEPTION("[IPCLib] select: timeout");
                return false;
        }
 
index cf2244b..c89917e 100755 (executable)
@@ -30,6 +30,8 @@ EXPORT_API bool emipc_start_proxy_socket();
 
 EXPORT_API bool emipc_end_proxy_socket();
 
+EXPORT_API bool emipc_end_all_proxy_sockets();
+
 EXPORT_API int emipc_send_proxy_socket(unsigned char *data, int len);
 
 EXPORT_API int emipc_get_proxy_socket_id();
index 8be734a..cc494c8 100755 (executable)
 EXPORT_API bool emipc_init_email_socket(int *fd)
 {
        bool ret = true;
+       char errno_buf[ERRNO_BUF_SIZE] = {0};
 
        *fd = socket(AF_UNIX, SOCK_STREAM, 0);
-
        if (*fd < 0) {
-               EM_DEBUG_EXCEPTION("socket creation fails!!!: %s", strerror(errno));
+               EM_DEBUG_EXCEPTION("socket failed: %s", EM_STRERROR(errno_buf));
                ret = false;
        }
 
@@ -71,11 +71,12 @@ static int emipc_writen(int fd, const char *buf, int len)
 {
        int length = len;
        int passed_len = 0;
+       char errno_buf[ERRNO_BUF_SIZE] = {0};
 
        while (length > 0) {
                passed_len = send(fd, (const void *)buf, length, MSG_NOSIGNAL);
                if (passed_len == -1) {
-                       EM_DEBUG_LOG("write : %s", EM_STRERROR(errno));
+                       EM_DEBUG_LOG("write : %s", EM_STRERROR(errno_buf));
                        if (errno == EINTR) continue;
                        else if (errno == EPIPE) return 0; /* connection closed */
                        else return passed_len; /* -1 */
@@ -116,11 +117,12 @@ static int emipc_readn(int fd, char *buf, int len)
 {
        int length = len;
        int read_len = 0;
+       char errno_buf[ERRNO_BUF_SIZE] = {0};
 
        while (length > 0) {
                read_len = read(fd, (void *)buf, length);
                if (read_len < 0) {
-                       EM_DEBUG_EXCEPTION("Read : %s", EM_STRERROR(errno));
+                       EM_DEBUG_EXCEPTION("Read : %s", EM_STRERROR(errno_buf));
                        if (errno == EINTR) continue;
                        return read_len;
                } else if (read_len == 0)
@@ -139,6 +141,7 @@ static int emipc_readn(int fd, char *buf, int len)
 EXPORT_API int emipc_recv_email_socket(int fd, char **buf)
 {
        EM_DEBUG_FUNC_BEGIN();
+       char errno_buf[ERRNO_BUF_SIZE] = {0};
 
        if (!buf) {
                EM_DEBUG_LOG("Buffer must not null");
@@ -148,11 +151,11 @@ EXPORT_API int emipc_recv_email_socket(int fd, char **buf)
        int read_len = 0;
        /* read the size of message. note that ioctl is non-blocking */
        if (ioctl(fd, FIONREAD, &read_len)) {
-               EM_DEBUG_EXCEPTION("ioctl: %s", strerror(errno));
+               EM_DEBUG_EXCEPTION ("ioctl failed: %s", EM_STRERROR(errno_buf));
                return EMAIL_ERROR_IPC_SOCKET_FAILURE;
        }
        /* when server or client closed socket */
-       if ( read_len == 0 ) {
+       if (read_len == 0) {
                EM_DEBUG_LOG("[IPC Socket] connection is closed");
                return 0;
        }
@@ -164,7 +167,7 @@ EXPORT_API int emipc_recv_email_socket(int fd, char **buf)
        }
        memset(*buf, 0x00, read_len);
 
-       EM_DEBUG_LOG("[IPC Socket] Receiving [%d] bytes", read_len);
+       EM_DEBUG_LOG_DEV("[IPC Socket] Receiving [%d] bytes", read_len);
        int len = emipc_readn(fd, *buf, read_len);
        if (read_len != len) {
                EM_SAFE_FREE(*buf);
@@ -172,7 +175,7 @@ EXPORT_API int emipc_recv_email_socket(int fd, char **buf)
                return EMAIL_ERROR_IPC_SOCKET_FAILURE;
        }
 
-       EM_DEBUG_LOG("[IPC Socket] Receiving [%d] bytes Completed", len);
+       EM_DEBUG_LOG_DEV("[IPC Socket] Receiving [%d] bytes Completed", len);
 
        return len;
 }
@@ -180,9 +183,10 @@ EXPORT_API int emipc_recv_email_socket(int fd, char **buf)
 EXPORT_API int emipc_accept_email_socket(int fd)
 {
        EM_DEBUG_FUNC_BEGIN();
+       char errno_buf[ERRNO_BUF_SIZE] = {0};
 
        if (fd == -1) {
-               EM_DEBUG_LOG("Server_socket not init");
+               EM_DEBUG_EXCEPTION ("Server_socket is not yet initialized");
                return EMAIL_ERROR_INVALID_PARAM;
        }
 
@@ -190,7 +194,7 @@ EXPORT_API int emipc_accept_email_socket(int fd)
        int remote_len = sizeof(remote);
        int client_fd = accept(fd, (struct sockaddr *)&remote, (socklen_t*) &remote_len);
        if (client_fd == -1) {
-               EM_DEBUG_LOG("accept: %s", EM_STRERROR(errno));
+               EM_DEBUG_EXCEPTION ("accept failed [%s][%d]", EM_STRERROR(errno_buf), errno);
                return EMAIL_ERROR_IPC_SOCKET_FAILURE;
        }
 
@@ -204,6 +208,7 @@ EXPORT_API int emipc_open_email_socket(int fd, const char *path)
 {
        EM_DEBUG_FUNC_BEGIN("path [%s]", path);
        int sock_fd = 0;
+       char errno_buf[ERRNO_BUF_SIZE] = {0};
 
        if (strcmp(path, EM_SOCKET_PATH) == 0 &&
                sd_listen_fds(1) == 1 &&
@@ -214,12 +219,12 @@ EXPORT_API int emipc_open_email_socket(int fd, const char *path)
        }
 
        if (!path || EM_SAFE_STRLEN(path) > 108) {
-               EM_DEBUG_LOG("Path is null");
+               EM_DEBUG_EXCEPTION ("Path is null");
                return EMAIL_ERROR_IPC_SOCKET_FAILURE;
        }
 
        if (fd <= 0) {
-               EM_DEBUG_LOG("Socket not created %d", fd);
+               EM_DEBUG_EXCEPTION ("Socket not created %d", fd);
                return EMAIL_ERROR_IPC_SOCKET_FAILURE;
        }
 
@@ -231,7 +236,7 @@ EXPORT_API int emipc_open_email_socket(int fd, const char *path)
        int len = EM_SAFE_STRLEN(local.sun_path) + sizeof(local.sun_family);
 
        if (bind(fd, (struct sockaddr *)&local, len) == -1) {
-               EM_DEBUG_LOG("bind: %s", EM_STRERROR(errno));
+               EM_DEBUG_LOG("bind: %s", EM_STRERROR(errno_buf));
                return EMAIL_ERROR_IPC_SOCKET_FAILURE;
        }
 
@@ -249,12 +254,12 @@ EXPORT_API int emipc_open_email_socket(int fd, const char *path)
        mode_t sock_mode = (S_IRWXU | S_IRWXG | S_IRWXO); /*  has 777 permission */
 
        if (chmod(path, sock_mode) == -1) {
-               EM_DEBUG_LOG("chmod: %s", EM_STRERROR(errno));
+               EM_DEBUG_LOG("chmod: %s", EM_STRERROR(errno_buf));
                return EMAIL_ERROR_IPC_SOCKET_FAILURE;
        }
 
        if (listen(fd, 10) == -1) {
-               EM_DEBUG_LOG("listen: %s", EM_STRERROR(errno));
+               EM_DEBUG_LOG("listen: %s", EM_STRERROR(errno_buf));
                return EMAIL_ERROR_IPC_SOCKET_FAILURE;
        }
 
@@ -266,16 +271,17 @@ EXPORT_API bool emipc_connect_email_socket(int fd)
 {
        EM_DEBUG_FUNC_BEGIN();
        struct sockaddr_un server;
+       memset(&server, 0, sizeof(server));
        server.sun_family = AF_UNIX;
        strcpy(server.sun_path, EM_SOCKET_PATH);
+       char errno_buf[ERRNO_BUF_SIZE] = {0};
 
-       int len = EM_SAFE_STRLEN(server.sun_path) + sizeof(server.sun_family);
-
-       if (connect(fd, (struct sockaddr *)&server, len) == -1) {
-               EM_DEBUG_LOG("Cannot connect server %s", EM_STRERROR(errno));
+       if (connect(fd, (struct sockaddr *)&server, sizeof(server)) < 0) {
+               EM_DEBUG_EXCEPTION ("connect failed: [%s][errno=%d][fd=%d]", EM_STRERROR(errno_buf), errno, fd);
                return false;
        }
 
+       EM_DEBUG_FUNC_END();
        return true;
 }
 
index 523f762..3a8027f 100755 (executable)
@@ -27,6 +27,7 @@
 #include "email-ipc-build.h"
 #include "email-dbus-activation.h"
 #include "email-stub-socket.h"
+#include "email-stub-task-manager.h"
 
 #include "email-api.h"
 #include "email-debug-log.h"
@@ -94,7 +95,7 @@ EXPORT_API bool emipc_execute_api_stub_to_proxy(emipc_email_api_info *api_info)
 {
        EM_DEBUG_FUNC_BEGIN("api_info [%p]", api_info);
        EM_IF_NULL_RETURN_VALUE(api_info, false);
-       EM_DEBUG_LOG("APIID [%s], response Socket ID [%d], APPID [%d]",
+       EM_DEBUG_LOG_SEC ("Response: API_ID [%s], RES_ID [%d], APP_ID [%d]",\
                                EM_APIID_TO_STR(api_info->api_id), api_info->response_id, api_info->app_id);
        
        unsigned char *stream = NULL;
index 7d3eaae..9450d20 100755 (executable)
 #include "email-stub-socket.h"
 
 #include "email-debug-log.h"
+#include "email-proxy-socket.h"
 
-#define MAX_EPOLL_EVENT 50
+#define MAX_EPOLL_EVENT 100
 
 static int stub_socket = 0;
 static pthread_t stub_socket_thread = 0;
 static bool stop_thread = false;
 
+GList *connected_fd = NULL;
+
 static void *emipc_stub_socket_thread_proc();
 
 EXPORT_API bool emipc_start_stub_socket()
@@ -101,12 +104,22 @@ static void *emipc_stub_socket_thread_proc()
        return NULL;
 }
 
+static int emipc_check_connected(int fd)
+{
+       EM_DEBUG_FUNC_BEGIN ("fd[%d]", fd);
+       int found = (g_list_find (connected_fd, (gpointer)fd))? true : false;
+       EM_DEBUG_FUNC_END ("fd found?? [%d]", found);
+       return found;
+}
+
+
 EXPORT_API void emipc_wait_for_ipc_request()
 {
        struct epoll_event ev = {0};
-       struct epoll_event events[MAX_EPOLL_EVENT] = {{0}, };
        int epfd = 0;
        int event_num = 0;
+       char errno_buf[ERRNO_BUF_SIZE] = {0};
+       struct epoll_event events[MAX_EPOLL_EVENT] = {{0}, };
 
        if (!stub_socket) {
                EM_DEBUG_EXCEPTION("Server Socket is not initialized");
@@ -117,45 +130,48 @@ EXPORT_API void emipc_wait_for_ipc_request()
        
        epfd = epoll_create(MAX_EPOLL_EVENT);
        if (epfd < 0) {
-               EM_DEBUG_EXCEPTION("epoll_ctl: %s[%d]", strerror(errno), errno);
-               EM_DEBUG_CRITICAL_EXCEPTION("epoll_create: %s[%d]", strerror(errno), errno);
-               abort();
+               EM_DEBUG_EXCEPTION("epoll_ctl failed: %s[%d]", EM_STRERROR(errno_buf), errno);
+               EM_DEBUG_CRITICAL_EXCEPTION("epoll_create failed: %s[%d]", EM_STRERROR(errno_buf), errno);
+               return;
        }
 
        ev.events = EPOLLIN;
        ev.data.fd = stub_socket;
        
        if (epoll_ctl(epfd, EPOLL_CTL_ADD, stub_socket, &ev) == -1) {
-               EM_DEBUG_EXCEPTION("epoll_ctl: %s[%d]", strerror(errno), errno);
-               EM_DEBUG_CRITICAL_EXCEPTION("epoll_ctl:%s[%d]", strerror(errno), errno);        
+               EM_DEBUG_EXCEPTION("epoll_ctl failed: %s[%d]", EM_STRERROR(errno_buf), errno);
+               EM_DEBUG_CRITICAL_EXCEPTION("epoll_ctl failed:%s[%d]", EM_STRERROR(errno_buf), errno);  
        }
-       while (1) {
+       while (!stop_thread) {
                int i = 0;
 
                event_num = epoll_wait(epfd, events, MAX_EPOLL_EVENT, -1);
                
+               if (stop_thread) {
+                       EM_DEBUG_LOG ("IPC hanlder thread is going to be shut down");
+                       break;
+               }
+
                if (event_num == -1) {
-                       EM_DEBUG_EXCEPTION("epoll_wait: %s[%d]", strerror(errno), errno);
-                       EM_DEBUG_CRITICAL_EXCEPTION("epoll_wait: %s[%d]", strerror(errno), errno);
-                       if (errno == EINTR) continue; /* resume when interrupted system call*/
-                       else abort();
+                       EM_DEBUG_EXCEPTION("epoll_wait failed: %s[%d]", EM_STRERROR(errno_buf), errno);
+                       EM_DEBUG_CRITICAL_EXCEPTION("epoll_wait failed: %s[%d]", EM_STRERROR(errno_buf), errno);
                } else {
                        for (i = 0; i < event_num; i++) {
                                int event_fd = events[i].data.fd;
 
                                if (event_fd == stub_socket) { /*  if it is socket connection request */
-                                       int cfd = emipc_accept_email_socket(stub_socket);
+                                       int cfd = emipc_accept_email_socket (stub_socket);
                                        if (cfd < 0) {
-                                               EM_DEBUG_EXCEPTION("accept error: %s[%d]", strerror(errno), errno);
-                                               EM_DEBUG_CRITICAL_EXCEPTION("accept error: %s[%d]", strerror(errno), errno);
-                                               /*  abort(); */
+                                               EM_DEBUG_EXCEPTION ("emipc_accept_email_socket failed [%d]", cfd);
+                                               /* EM_DEBUG_CRITICAL_EXCEPTION ("accept failed: %s[%d]", EM_STRERROR(errno_buf), errno);*/
                                        }
                                        ev.events = EPOLLIN;
                                        ev.data.fd = cfd;
                                        if (epoll_ctl(epfd, EPOLL_CTL_ADD, cfd, &ev) == -1) {
-                                               EM_DEBUG_EXCEPTION("epoll_ctl: %s[%d]", strerror(errno), errno);
-                                               EM_DEBUG_CRITICAL_EXCEPTION("epoll_ctl:%s[%d]", strerror(errno), errno);
+                                               EM_DEBUG_EXCEPTION("epoll_ctl failed [%s][%d]", EM_STRERROR(errno_buf), errno);
+                                               /*EM_DEBUG_CRITICAL_EXCEPTION("epoll_ctl failed:%s[%d]", EM_STRERROR(errno_buf), errno);*/
                                        }
+                                       connected_fd = g_list_prepend (connected_fd, (gpointer)cfd);
                                } else {
                                        int recv_len;
                                        char *sz_buf = NULL;
@@ -163,9 +179,7 @@ EXPORT_API void emipc_wait_for_ipc_request()
                                        recv_len = emipc_recv_email_socket(event_fd, &sz_buf);
                                        
                                        if(recv_len > 0) {
-                                               EM_DEBUG_LOG("====================================================================");
                                                EM_DEBUG_LOG("[IPCLib]Stub Socket Recv [Socket ID = %d], [recv_len = %d]", event_fd, recv_len);
-                                               EM_DEBUG_LOG("====================================================================");
 
                                                /* IPC request stream is at least 16byte */
                                                if (recv_len >= sizeof(long) * eSTREAM_DATA) {
@@ -175,9 +189,10 @@ EXPORT_API void emipc_wait_for_ipc_request()
                                        } else if( recv_len == 0 ) {
                                                EM_DEBUG_LOG("[IPCLib] Client closed connection [%d]", event_fd);
                                                if (epoll_ctl(epfd, EPOLL_CTL_DEL, event_fd, events) == -1) {
-                                                       EM_DEBUG_EXCEPTION("epoll_ctl: %s[%d]", strerror(errno), errno);
-                                                       EM_DEBUG_CRITICAL_EXCEPTION("epoll_ctl:%s[%d]", strerror(errno), errno);
+                                                       EM_DEBUG_EXCEPTION("epoll_ctl failed: %s[%d]", EM_STRERROR(errno_buf), errno);
+                                                       EM_DEBUG_CRITICAL_EXCEPTION("epoll_ctl failed: %s[%d]", EM_STRERROR(errno_buf), errno);
                                                }
+                                               connected_fd = g_list_remove (connected_fd, (gpointer)event_fd);
                                                close(event_fd);
                                        } 
                                        EM_SAFE_FREE(sz_buf);
@@ -185,27 +200,23 @@ EXPORT_API void emipc_wait_for_ipc_request()
                        }
                }
        }       
+       emipc_end_all_proxy_sockets ();
+       emipc_close_email_socket(&stub_socket);
+       EM_DEBUG_LOG ("IPC hanlder thread is shut down");
 }
 
 EXPORT_API bool emipc_end_stub_socket()
 {
-       EM_DEBUG_FUNC_BEGIN();
+       EM_DEBUG_FUNC_BEGIN ();
        
-       if (stub_socket) {
-               emipc_close_email_socket(&stub_socket);
-       }
+       /* stop IPC handler thread */
+       emipc_stop_stub_socket_thread (stub_socket_thread);
+       stub_socket_thread = 0;
 
-       if (stub_socket_thread) {
-               emipc_stop_stub_socket_thread(stub_socket_thread);
-               pthread_cancel(stub_socket_thread);
-               stub_socket_thread = 0;
-       }
+       /* stop task thread */
+       emipc_stop_task_thread ();
 
-       if (!emipc_stop_task_thread()) {
-               EM_DEBUG_EXCEPTION("emipc_stop_task_thread failed");
-               return false;   
-       }
-               
+       EM_DEBUG_FUNC_END ();           
        return true;
 }
 
@@ -213,8 +224,15 @@ EXPORT_API int emipc_send_stub_socket(int sock_fd, void *data, int len)
 {
        EM_DEBUG_FUNC_BEGIN("Stub socket sending %d bytes", len);
 
-       int sending_bytes = emipc_send_email_socket(sock_fd, data, len);
-       
+       int sending_bytes = 0;
+       if (emipc_check_connected(sock_fd)) { /* client may be shut down and the sock_fd can be reused by another module */
+               sending_bytes = emipc_send_email_socket(sock_fd, data, len);
+       }
+
+       if (sending_bytes == 0) {
+               EM_DEBUG_LOG ("sending byte for fd [%d] is zero", sock_fd);
+       }
+
        EM_DEBUG_FUNC_END("sending_bytes = %d", sending_bytes);
        return sending_bytes;
 }
index 28ebba4..3774d2a 100755 (executable)
@@ -47,10 +47,11 @@ EXPORT_API bool emipc_start_task_thread()
        if (task_thread)
                return true;
 
+       char errno_buf[ERRNO_BUF_SIZE] = {0};
        task_queue = g_queue_new();
 
        if (pthread_create(&task_thread, NULL, &emipc_do_task_thread, NULL) != 0) {
-               EM_DEBUG_LOG("Worker thread creation failed: %s", strerror(errno));
+               EM_DEBUG_LOG("Worker thread creation failed: %s", EM_STRERROR(errno_buf));
                return false;   
        }
 
@@ -85,16 +86,22 @@ EXPORT_API void *emipc_do_task_thread()
        while (!stop_flag) {
                ENTER_CRITICAL_SECTION(ipc_task_mutex);
                while (g_queue_is_empty(task_queue)) {
-                       EM_DEBUG_LOG("Blocked until new task arrives %p.", &ipc_task_cond);
+/*                     EM_DEBUG_LOG("Blocked until new task arrives %p.", &ipc_task_cond); */
                        SLEEP_CONDITION_VARIABLE(ipc_task_cond, ipc_task_mutex);
                }
                
+               if (stop_flag) {
+                       EM_DEBUG_LOG ("task thread is going to be shut down");
+                       break;
+               }
+
                task = (emipc_email_task *)g_queue_pop_head(task_queue);
                LEAVE_CRITICAL_SECTION(ipc_task_mutex);
 
                if (task) {
                        emipc_run_task(task);
                        emipc_free_email_task(task);
+                       EM_SAFE_FREE(task);
                }
        }
        
@@ -117,15 +124,15 @@ EXPORT_API bool emipc_create_task(unsigned char *task_stream, int response_chann
                        return false;
                }
                
-               EM_DEBUG_LOG("[IPCLib] ======================================================");
-               EM_DEBUG_LOG("[IPCLib] Register new task : %p", task);
-               EM_DEBUG_LOG("[IPCLib] Task API ID : %s (%d)", EM_APIID_TO_STR(task->api_info->api_id), task->api_info->api_id);
-               EM_DEBUG_LOG("[IPCLib] Task Response ID : %d", task->api_info->response_id);
-               EM_DEBUG_LOG("[IPCLib] Task APP ID : %d", task->api_info->app_id);
-               EM_DEBUG_LOG("[IPCLib] ======================================================");
+               EM_DEBUG_LOG_DEV ("[IPCLib] ======================================================");
+               EM_DEBUG_LOG_SEC ("[IPCLib] Register new task: API_ID[%s][0x%x] RES_ID[%d] APP_ID[%d]", EM_APIID_TO_STR(task->api_info->api_id),\
+                                                                                                       task->api_info->api_id,\
+                                                                                                       task->api_info->response_id,\
+                                                                                                       task->api_info->app_id);
+               EM_DEBUG_LOG_DEV ("[IPCLib] ======================================================");
 
                ENTER_CRITICAL_SECTION(ipc_task_mutex);
-               g_queue_push_head(task_queue, (void *)task);
+               g_queue_push_tail(task_queue, (void *)task);
                
                WAKE_CONDITION_VARIABLE(ipc_task_cond);
                LEAVE_CRITICAL_SECTION(ipc_task_mutex);
index eaa4c1b..45937f4 100755 (executable)
@@ -43,7 +43,7 @@ EXPORT_API void emipc_free_email_task(emipc_email_task *task)
        }
 
        emipc_free_api_info(task->api_info);
-       EM_SAFE_FREE(task);
+       EM_SAFE_FREE(task->api_info);
 }
 
 EXPORT_API bool emipc_parse_stream_email_task(emipc_email_task *task, void *stream, int response_id)
@@ -80,12 +80,12 @@ EXPORT_API int emipc_get_response_channel(emipc_email_task *task)
 
 EXPORT_API bool emipc_run_task(emipc_email_task *task)
 {
-       EM_DEBUG_LOG("[IPCLib] starting a new task...");
-
        int api_id = task->api_info->api_id;
        int app_id = task->api_info->app_id;
+       int res_id = task->api_info->response_id;
 
-       EM_DEBUG_LOG("[IPCLib] This task (%s) is for async. App id [%d], Response ID [%d]", EM_APIID_TO_STR(api_id), app_id, api_id);
+       EM_DEBUG_LOG_SEC("[IPCLib] Processing task: API_ID[%s][0x%x] RES_ID[%d] APP_ID[%d] ", EM_APIID_TO_STR(api_id),\
+                                                                                               api_id, res_id, app_id);
 
        if (!emipc_execute_api_proxy_to_stub(task->api_info)) {
                EM_DEBUG_EXCEPTION("emipc_execute_api_proxy_to_stub failed");
index f18ca3c..5af460c 100755 (executable)
@@ -36,7 +36,7 @@ extern "C" {
                return val;     \
        }; }
 
-       
+
 /*  ------------------------------------------------------------------------------------------------------------ */
 /*     Type Definitio */
 /*  ------------------------------------------------------------------------------------------------------------ */
index 5c6d6f4..c4750ef 100755 (executable)
@@ -5,5 +5,5 @@ includedir=${prefix}/include
 Name: email-service library\r
 Description: email-service library 1.0\r
 Version: $version\r
-Libs: -L${libdir} -lemail-storage -lemail-core -lemail-common-use -lemail-ipc -lemail-api -lemail-network \r
+Libs: -L${libdir} -lemail-storage -lemail-core -lemail-common-use -lemail-ipc -lemail-api -lemail-network -lemail-smime-api\r
 Cflags: -I${includedir}/email-service \r
index 61db117..9b45e1b 100644 (file)
@@ -1,9 +1,22 @@
 email-service email-service::db rw
+email-service _ w
+email-service system::share rwx
+email-service msg-service w
+email-service calender-service x
+email-service deviced w
 email-service system::use_internet w
 email-service system::vconf arwxt
+email-service system::vconf_inhouse rw
+email-service system::vconf_setting r
 email-service data-provider-master rw
+email-service secure-storage::pkcs12 r
+email-service data-provider-master::notification rw
+email-service data-provider-master::badge rw
+email-service device::app_logging w
+email-service device::sys_logging w
 
 system::use_internet email-service rwx
+system::share email-service rwx
 webkit2-efl email-service rx
 
 com.samsung.quickpanel email-service rx
index 4e6f2a4..f29981a 100755 (executable)
@@ -228,7 +228,7 @@ account->outgoing_server_secure_connection             = 0x02;
 account->outgoing_server_need_authentication                 = 1;
 account->outgoing_server_user_name                 = strdup("tom@gmail.com");
 account->sending_password             = strdup("tioimi");
-account->pop_before_smtp              = 0;
+account->auto_resend_times            = 3;
 account->incoming_server_requires_apop                         = 0;
 account->flag1                        = 2;
 account->flag2                        = 1;
diff --git a/packaging/email-service.changes b/packaging/email-service.changes
deleted file mode 100644 (file)
index c28175c..0000000
+++ /dev/null
@@ -1,13 +0,0 @@
-* Mon Jul 01 2013 Anas Nashif <anas.nashif@intel.com> accepted/tizen/20130602.015250@d13cb47
-- we do not actually depend on gconf
-
-* Wed Jun 05 2013 Xavier Roche <xavrock.os@gmail.com> accepted/tizen/20130602.015250@5b47f61
-- Replace manifest with default floor
-
-* Sat Jun 01 2013 Anas Nashif <anas.nashif@intel.com> submit/tizen/20130527.191630@14a0320
-- Remove license/group placeholders
-- Disable manifests temporarily
-
-* Mon May 27 2013 Anas Nashif <anas.nashif@intel.com> accepted/tizen/20130520.101100@9fed1bb
-- move test app to a sub-package
-
diff --git a/packaging/email-service.manifest b/packaging/email-service.manifest
deleted file mode 100644 (file)
index 017d22d..0000000
+++ /dev/null
@@ -1,5 +0,0 @@
-<manifest>
- <request>
-    <domain name="_"/>
- </request>
-</manifest>
index 630f2c5..38b14ce 100755 (executable)
@@ -6,13 +6,14 @@ Group:      Messaging/Service
 License:    Apache-2.0
 Source0:    %{name}-%{version}.tar.gz
 Source1:    email.service
-Source1001:    email-service.manifest
 Requires: connman
 Requires: webkit2-efl
 Requires(post):    /sbin/ldconfig
 Requires(post):    systemd
 Requires(post):    /usr/bin/sqlite3
 Requires(post):    /usr/bin/vconftool
+Requires(post):    libss-client
+Requires(post):    ss-server
 Requires(preun):   systemd
 Requires(postun):  /sbin/ldconfig
 Requires(postun):  systemd
@@ -40,23 +41,22 @@ BuildRequires:  pkgconfig(libsystemd-daemon)
 BuildRequires:  pkgconfig(capi-base-common)
 BuildRequires:  pkgconfig(libcurl)
 BuildRequires:  pkgconfig(libxml-2.0)
+BuildRequires:  pkgconfig(gconf-2.0)
 BuildRequires:  pkgconfig(cert-svc)
 BuildRequires:  pkgconfig(badge)
 BuildRequires:  pkgconfig(feedback)
 BuildRequires:  pkgconfig(capi-appfw-application)
 BuildRequires:  pkgconfig(libwbxml2)
 BuildRequires:  pkgconfig(msg-service)
+BuildRequires:  pkgconfig(pmapi)
+BuildRequires:  pkgconfig(libsmack)
+BuildRequires:  pkgconfig(security-server)
+BuildRequires:  pkgconfig(deviced)
+BuildRequires:  pkgconfig(icu-i18n)
 
 %description
 E-mail Framework Middleware Library/Binary package
 
-%package tests
-Summary:    E-mail Framework Middleware - Test Applications
-Group:      Messaging/Testing
-Requires:   %{name} = %{version}-%{release}
-
-%description tests
-E-mail Framework Middleware test application
 
 %package devel
 Summary:    E-mail Framework Middleware Development package
@@ -69,12 +69,12 @@ E-mail Framework Middleware Development package
 
 %prep
 %setup -q
-cp %{SOURCE1001} .
 
 %build
 
 export CFLAGS="${CFLAGS} -fPIC -Wall -g -fvisibility=hidden"
 export CXXFLAGS="${CXXFLAGS} -fPIC -Wall -g -fvisibility=hidden"
+export LDFLAGS="${LDFLAGS} -Wl,--hash-style=both -Wl,--rpath=%{_libdir} -Wl,--as-needed"
 
 %cmake .
 
@@ -99,24 +99,27 @@ echo "[EMAIL-SERVICE] Start adding preset account information..."
 
 ################################################################################################
 
+# for active sync
+vconftool set -t int    db/email_handle/active_sync_handle "0"          -g 6514 -s "email::vconf_active_sync_handle"
+
 # for default mail slot szie
-vconftool set -t int    db/private/email-service/slot_size "100"        -g 6514
+vconftool set -t int    db/private/email-service/slot_size "100"        -g 6514 -s "email::vconf_slot_size"
 
 # for latest mail id
-vconftool set -t int    db/private/email-service/latest_mail_id "0"     -g 6514
+vconftool set -t int    db/private/email-service/latest_mail_id "0"     -g 6514 -s "email::vconf_latest_mail_id"
 
 # for default account id
-vconftool set -t int    db/private/email-service/default_account_id "0" -g 6514
+vconftool set -t int    db/private/email-service/default_account_id "0" -g 6514 -s "email::vconf_default_account_id"
 
 # for default account id
-vconftool set -t int    memory/sync/email "0" -i -g 6514
+vconftool set -t int    memory/sync/email "0" -i -g 6514                        -s "email::vconf_sync_status"
 
 # for priority send 
-vconftool set -t string db/private/email-service/noti_ringtone_path "Whistle.mp3" -g 6514
-vconftool set -t int    db/private/email-service/noti_rep_type "0" -g 6514
-vconftool set -t bool   db/private/email-service/noti_notification_ticker "0" -g 6514
-vconftool set -t bool   db/private/email-service/noti_display_content_ticker "0" -g 6514
-vconftool set -t bool   db/private/email-service/noti_badge_ticker "0" -i -g 6514
+vconftool set -t string db/private/email-service/noti_ringtone_path "/opt/usr/share/settings/Alerts/Over the horizon.mp3" -g 6514 -s "email::vconf_ringtone_path"
+vconftool set -t int    db/private/email-service/noti_rep_type "0" -g 6514                -s "email::vconf_rep_type"
+vconftool set -t bool   db/private/email-service/noti_notification_ticker "0" -g 6514     -s "email::vconf_notification"
+vconftool set -t bool   db/private/email-service/noti_display_content_ticker "0" -g 6514  -s "email::vconf_display_content"
+vconftool set -t bool   db/private/email-service/noti_badge_ticker "0" -i -g 6514         -s "email::vconf_bagdge"
 vconftool set -t int    db/private/email-service/noti_private_id/1 "0" -i -g 6514
 vconftool set -t int    db/private/email-service/noti_private_id/2 "0" -i -g 6514
 vconftool set -t int    db/private/email-service/noti_private_id/3 "0" -i -g 6514
@@ -127,6 +130,11 @@ vconftool set -t int    db/private/email-service/noti_private_id/7 "0" -i -g 651
 vconftool set -t int    db/private/email-service/noti_private_id/8 "0" -i -g 6514
 vconftool set -t int    db/private/email-service/noti_private_id/9 "0" -i -g 6514
 vconftool set -t int    db/private/email-service/noti_private_id/10 "0" -i -g 6514
+vconftool set -t bool   db/private/email-service/noti_vibration_status "0" -g 6514        -s "email::vconf_vibration"
+vconftool set -t bool   db/private/email-service/noti_vip_vibration_status "0" -g 6514    -s "email::vconf_vip_vibration"
+vconftool set -t bool   db/private/email-service/noti_use_default_ringtone "1" -g 6514    -s "email::vconf_use_default_ringtone"
+vconftool set -t bool   db/private/email-service/noti_vip_use_default_ringtone "1" -g 6514    -s "email::vconf_vip_use_default_ringtone"
+
 
 #################################################################
 # Set executin script
@@ -171,13 +179,20 @@ chmod 664 /opt/usr/dbspace/.email-service.db-journal
 
 mkdir -m775 -p /opt/usr/data/email/.email_data
 chgrp 6006 /opt/usr/data/email/.email_data
+chsmack -a 'email-service' /opt/usr/data/email/.email_data
 
 mkdir -m775 -p /opt/usr/data/email/.email_data/tmp
 chgrp 6006 /opt/usr/data/email/.email_data/tmp
+chsmack -a 'email-service' /opt/usr/data/email/.email_data/tmp
 
 mkdir -p /opt/share/cert-svc/certs/trusteduser/email
 chgrp 6006 /opt/share/cert-svc/certs/trusteduser/email
 
+if [ -f /opt/usr/dbspace/.email-service.db ]
+then
+       chsmack -a 'email-service::db' /opt/usr/dbspace/.email-service.db*
+fi
+
 systemctl daemon-reload
 if [ $1 == 1 ]; then
     systemctl restart email.service
@@ -194,24 +209,19 @@ systemctl daemon-reload
 
 
 %files
-%manifest %{name}.manifest
-#%manifest email-service.manifest
+%manifest email-service.manifest
+%exclude /usr/bin/email-test-app
 %{_bindir}/email-service
 /opt/usr/data/email/res/*
 %{_libdir}/lib*.so.*
 /usr/lib/systemd/user/email.service
 /usr/lib/systemd/user/tizen-middleware.target.wants/email.service
 /usr/share/dbus-1/services/email-service.service
-/usr/share/license/email-service/LICENSE
+/usr/share/license/email-service
 
 /opt/etc/smack/accesses.d/email-service.rule
 
-%files tests
-%manifest %{name}.manifest
-/usr/bin/email-test-app
-
 %files devel
-%manifest %{name}.manifest
 %{_includedir}/email-service/*.h
 %{_libdir}/lib*.so
 %{_libdir}/pkgconfig/*.pc
index 2cbab3f..30f64ec 100644 (file)
@@ -1,11 +1,10 @@
-
 [Unit]
 Description=Start the Email service
 
 [Service]
-EnvironmentFile=/run/tizen-mobile-ui
 ExecStart=/usr/bin/email-service
 Nice=5
+EnvironmentFile=/run/tizen-mobile-ui
 OOMScoreAdjust=100
 Restart=always
 
index 2f2f19b..ff46c40 100755 (executable)
@@ -9,6 +9,7 @@ CREATE TABLE mail_account_tbl
        sync_status                              INTEGER,
        sync_disabled                            INTEGER,
        default_mail_slot_size                   INTEGER,
+       roaming_option                           INTEGER,
        user_display_name                        VARCHAR(31),
        user_email_address                       VARCHAR(129),
        reply_to_address                         VARCHAR(129),
@@ -19,10 +20,15 @@ CREATE TABLE mail_account_tbl
        incoming_server_user_name                VARCHAR(51),
        incoming_server_password                 VARCHAR(51),
        incoming_server_secure_connection        INTEGER,
+       incoming_server_authentication_method    INTEGER,
        retrieval_mode                           INTEGER,
        keep_mails_on_pop_server_after_download  INTEGER,
        check_interval                           INTEGER,
        auto_download_size                       INTEGER,
+       peak_interval                            INTEGER,
+       peak_days                                INTEGER,
+       peak_start_time                          INTEGER,
+       peak_end_time                            INTEGER,
        outgoing_server_type                     INTEGER,
        outgoing_server_address                  VARCHAR(51),
        outgoing_server_port_number              INTEGER,
@@ -45,6 +51,8 @@ CREATE TABLE mail_account_tbl
        add_signature                            INTEGER,
        signature                                VARCHAR(256),
        add_my_address_to_bcc                    INTEGER,
+       auto_resend_times                        INTEGER,
+       outgoing_server_size_limit               INTEGER,
        pop_before_smtp                          INTEGER,
        incoming_server_requires_apop            INTEGER,
        smime_type                               INTEGER,
@@ -66,26 +74,31 @@ CREATE TABLE mail_box_tbl
        has_archived_mails               INTEGER,    
        mail_slot_size                   INTEGER,
        no_select                        INTEGER,
-       last_sync_time                   DATETIME
+       last_sync_time                   DATETIME,
+       eas_data_length                  INTEGER,
+       eas_data                         BLOB
 );
 CREATE TABLE mail_read_mail_uid_tbl          
 (    
        account_id                       INTEGER ,
        mailbox_id                       INTEGER ,
-       local_uid                        INTEGER ,
        mailbox_name                     VARCHAR(256) ,
-       s_uid                            VARCHAR(129) ,
-       data1                            INTEGER ,
-       data2                            VARCHAR(257) ,
-       flag                             INTEGER ,
+       local_uid                        INTEGER ,
+       server_uid                       VARCHAR(129) ,
+       rfc822_size                      INTEGER ,
+       sync_status                      INTEGER ,
+       flags_seen_field                 INTEGER ,
+       flags_flagged_field              INTEGER ,
        idx_num                          INTEGER PRIMARY KEY
 );
 CREATE TABLE mail_rule_tbl          
 (    
        account_id                       INTEGER ,
        rule_id                          INTEGER PRIMARY KEY,
+       filter_name                      VARCHAR(257)  ,
        type                             INTEGER ,
        value                            VARCHAR(257)  ,
+       value2                           VARCHAR(257)  ,
        action_type                      INTEGER ,
        target_mailbox_id                INTEGER ,
        flag1                            INTEGER ,
@@ -141,6 +154,10 @@ CREATE TABLE mail_tbl
        digest_type                      INTEGER,
        smime_type                       INTEGER,
        scheduled_sending_time           DATETIME,
+       remaining_resend_times           INTEGER,
+       tag_id                           INTEGER,
+       replied_time                     DATETIME,
+       forwarded_time                   DATETIME,
        eas_data_length                  INTEGER,
        eas_data                         BLOB,
        FOREIGN KEY(account_id)          REFERENCES mail_account_tbl(account_id)
@@ -232,10 +249,18 @@ CREATE VIRTUAL TABLE mail_text_tbl USING fts4
 );
 CREATE UNIQUE INDEX mail_account_idx1 ON mail_account_tbl (account_id);
 CREATE UNIQUE INDEX mail_box_idx1 ON mail_box_tbl (mailbox_id);
-CREATE UNIQUE INDEX mail_read_mail_uid_idx1 ON mail_read_mail_uid_tbl (account_id, mailbox_id, local_uid, mailbox_name, s_uid);
+CREATE UNIQUE INDEX mail_read_mail_uid_idx1 ON mail_read_mail_uid_tbl (account_id, mailbox_id, local_uid, mailbox_name, server_uid);
 CREATE UNIQUE INDEX mail_idx1 ON mail_tbl (mail_id, account_id);
 CREATE UNIQUE INDEX mail_attachment_idx1 ON mail_attachment_tbl (mail_id, attachment_id);
 CREATE UNIQUE INDEX mail_meeting_idx1 ON mail_meeting_tbl (mail_id);
 CREATE UNIQUE INDEX task_idx1 ON mail_task_tbl (task_id);
 CREATE INDEX mail_idx_date_time ON mail_tbl (date_time);
 CREATE INDEX mail_idx_thread_item_count ON mail_tbl (thread_item_count);
+CREATE TRIGGER update_flags_seen_field UPDATE OF flags_seen_field ON mail_tbl 
+  BEGIN
+    UPDATE mail_read_mail_uid_tbl SET flags_seen_field = new.flags_seen_field WHERE local_uid = old.mail_id;
+  END;
+CREATE TRIGGER update_flags_flagged_field UPDATE OF flags_flagged_field ON mail_tbl 
+  BEGIN
+    UPDATE mail_read_mail_uid_tbl SET flags_flagged_field = new.flags_flagged_field WHERE local_uid = old.mail_id;
+  END;
index 945d38f..2a04870 100755 (executable)
@@ -12,8 +12,7 @@ MESSAGE(">>> current directory: ${CMAKE_CURRENT_SOURCE_DIR}")
 MESSAGE(">>> Build type: ${CMAKE_BUILD_TYPE}")
 
 SET(VISIBILITY "-DEXPORT_API=\"__attribute__((visibility(\\\"default\\\")))\"")
-SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${VISIBILITY} -fvisibility=hidden ")
-ADD_DEFINITIONS("-DLIBPATH=\"${LIB_INSTALL_DIR}\"")
+SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${VISIBILITY} -fvisibility=hidden")
 
 ##########################################################
 # Define Test App
@@ -41,7 +40,7 @@ INCLUDE_DIRECTORIES(
 )
 
 INCLUDE(FindPkgConfig)
-pkg_check_modules(test_app_pkgs REQUIRED glib-2.0 gthread-2.0 vconf db-util uw-imap-toolkit contacts-service2 drm-client)
+pkg_check_modules(test_app_pkgs REQUIRED glib-2.0 gthread-2.0 vconf db-util uw-imap-toolkit contacts-service2 drm-client pmapi)
 
 FOREACH(flag ${test_app_pkgs_CFLAGS})
        SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag}")
@@ -51,7 +50,7 @@ SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${EXTRA_CFLAGS}")
 SET(CMAKE_EXE_LINKER_FLAGS "-Wl,--as-needed")
 
 ADD_EXECUTABLE(email-test-app ${TEST-APP-SRCS})
-TARGET_LINK_LIBRARIES(email-test-app ${test_app_pkgs_LDFLAGS} email-api)
+TARGET_LINK_LIBRARIES(email-test-app ${test_app_pkgs_LDFLAGS} email-api email-smime-api)
 
 INSTALL(TARGETS email-test-app DESTINATION bin)
 
index 45f14e2..3b5a6a2 100755 (executable)
@@ -35,6 +35,7 @@ typedef enum
        EMAIL_RULE_MENU,
        EMAIL_THREAD_MENU,
        EMAIL_OTHERS_MENU,
+       EMAIL_GMIME_MENU
 } eEMAIL_MENU;
 
 
index 7cdec48..27cbfdd 100755 (executable)
@@ -41,6 +41,9 @@
 #include "testapp-rule.h"
 #include "testapp-thread.h"
 #include "testapp-others.h"
+#ifdef __FEATURE_USE_GMIME__
+#include "testapp-gmime.h"
+#endif /* __FEATURE_USE_GMIME__ */
 #include "db-util.h"
 
 /* function prototype */
@@ -162,6 +165,11 @@ static gboolean testapp_interpret_command (int menu_number)
                case 7:
                        testapp_others_main();
                        break;
+#ifdef __FEATURE_USE_GMIME__
+               case 8:
+                       testapp_gmime_main();
+                       break;
+#endif /* __FEATURE_USE_GMIME__ */
                case 0:
                        go_to_loop = FALSE;
                        break;
index 2b2d94e..c1b121b 100755 (executable)
@@ -28,6 +28,7 @@
 #include <glib.h>
 
 #include "email-api.h"
+#include "email-api-smime.h"
 #include "email-api-account.h"
 #include "email-api-network.h"
 
@@ -59,7 +60,8 @@
 gboolean  testapp_create_account_object(email_account_t **result_account)
 {
        email_account_t *account = NULL;
-       char id_string[100] = { 0, }, password_string[100] = { 0, }, address_string[100]  = { 0, };
+       char id_string[100] = { 0, }, password_string[1000] = { 0, }, address_string[100]  = { 0, };
+       char accesss_token[1000] = { 0, }, refresh_token[1000] = { 0, };
        int samsung3g_account_index;
        int result_from_scanf = 0;
        int account_type;
@@ -76,6 +78,9 @@ gboolean  testapp_create_account_object(email_account_t **result_account)
        testapp_print("11. Daum (IMAP4)\n");
        testapp_print("12. Daum (POP3)\n");
        testapp_print("13. Yahoo (IMAP ID)\n");
+       testapp_print("14. Gmail IMAP with XOAUTH\n");
+       testapp_print("15. Yandex\n");
+       testapp_print("16. mopera\n");
        testapp_print("Choose server type: ");
 
        result_from_scanf = scanf("%d",&account_type);
@@ -89,7 +94,20 @@ gboolean  testapp_create_account_object(email_account_t **result_account)
                        }while( samsung3g_account_index > 10 || samsung3g_account_index < 1);
                        sprintf(id_string, "test%02d", samsung3g_account_index);
                        sprintf(address_string, "test%02d@streaming.s3glab.net", samsung3g_account_index);
-                       strcpy(password_string, id_string);
+                       sprintf(password_string, "test%02d", samsung3g_account_index);
+                       break;
+               case 14 :
+                       testapp_print("Enter email address : ");
+                       result_from_scanf = scanf("%s", address_string);
+                       strcpy(id_string, address_string);
+
+                       testapp_print("Enter access token : ");
+                       result_from_scanf = scanf("%s", accesss_token);
+
+                       testapp_print("Enter refresh token : ");
+                       result_from_scanf = scanf("%s", refresh_token);
+
+                       snprintf(password_string, 100, "%s\001%s\001", accesss_token, refresh_token);
                        break;
                default:
                        testapp_print("Enter email address : ");
@@ -121,8 +139,10 @@ gboolean  testapp_create_account_object(email_account_t **result_account)
        account->outgoing_server_type                    = EMAIL_SERVER_TYPE_SMTP;
        account->auto_download_size                                  = 2;
        account->outgoing_server_use_same_authenticator  = 1;
+       account->auto_resend_times                       = 3;
        account->pop_before_smtp                         = 0;
        account->incoming_server_requires_apop           = 0;
+       account->incoming_server_authentication_method   = 0;
        account->logo_icon_path                          = NULL;
        account->user_data                               = malloc (data_length);
        memcpy( account->user_data, (void*) &data, data_length );
@@ -144,6 +164,11 @@ gboolean  testapp_create_account_object(email_account_t **result_account)
        account->check_interval                          = 0;
        account->keep_mails_on_pop_server_after_download = 1;
        account->default_mail_slot_size                  = 200;
+       account->roaming_option                          = EMAIL_ROAMING_OPTION_RESTRICTED_BACKGROUND_TASK;
+       account->peak_interval                           = 30;
+       account->peak_days                               = EMAIL_PEAK_DAYS_MONDAY | EMAIL_PEAK_DAYS_TUEDAY | EMAIL_PEAK_DAYS_THUDAY | EMAIL_PEAK_DAYS_FRIDAY;
+       account->peak_start_time                         = 830;
+       account->peak_end_time                           = 1920;
 
        account->account_name                            = strdup(address_string);
        account->user_display_name                       = strdup(id_string);
@@ -213,13 +238,14 @@ gboolean  testapp_create_account_object(email_account_t **result_account)
 
                case 7 : /*  Gmail IMAP4 */
                        account->incoming_server_type  = EMAIL_SERVER_TYPE_IMAP4;
-                       account->incoming_server_address= strdup("imap.gmail.com");
+                       account->incoming_server_address = strdup("imap.gmail.com");
                        account->incoming_server_port_number = 993;
                        account->incoming_server_secure_connection      = 1;
-                       account->outgoing_server_address    = strdup("smtp.gmail.com");
+                       account->outgoing_server_address = strdup("smtp.gmail.com");
                        account->outgoing_server_port_number = 465;
                        account->outgoing_server_secure_connection = 1;
-                       account->outgoing_server_need_authentication = 1;
+                       account->outgoing_server_need_authentication   = EMAIL_AUTHENTICATION_METHOD_DEFAULT;
+                       account->incoming_server_authentication_method = EMAIL_AUTHENTICATION_METHOD_NO_AUTH;
                        break;
 
                case 8: /*  Active Sync */
@@ -288,6 +314,42 @@ gboolean  testapp_create_account_object(email_account_t **result_account)
                        account->outgoing_server_need_authentication = 1;
                        break;
 
+               case 14 : /*  XOAUTH */
+                       account->incoming_server_type  = EMAIL_SERVER_TYPE_IMAP4;
+                       account->incoming_server_address = strdup("imap.gmail.com");
+                       account->incoming_server_port_number = 993;
+                       account->incoming_server_secure_connection      = 1;
+                       account->outgoing_server_address = strdup("smtp.gmail.com");
+                       account->outgoing_server_port_number = 465;
+                       account->outgoing_server_secure_connection = 1;
+                       account->outgoing_server_need_authentication   = EMAIL_AUTHENTICATION_METHOD_XOAUTH2;
+                       account->incoming_server_authentication_method = EMAIL_AUTHENTICATION_METHOD_XOAUTH2;
+                       break;
+
+               case 15 : /*  yandex */
+                       account->incoming_server_type  = EMAIL_SERVER_TYPE_IMAP4;
+                       account->incoming_server_address = strdup("imap.yandex.ru");
+                       account->incoming_server_port_number = 993;
+                       account->incoming_server_secure_connection      = 1;
+                       account->outgoing_server_address = strdup("smtp.yandex.ru");
+                       account->outgoing_server_port_number = 465;
+                       account->outgoing_server_secure_connection = 1;
+                       account->outgoing_server_need_authentication   = EMAIL_AUTHENTICATION_METHOD_DEFAULT;
+                       account->incoming_server_authentication_method = EMAIL_AUTHENTICATION_METHOD_DEFAULT;
+                       break;
+
+               case 16 : /*  mopera */
+                       account->incoming_server_type                  = EMAIL_SERVER_TYPE_POP3;
+                       account->incoming_server_address               = strdup("mail.mopera.net");
+                       account->incoming_server_port_number           = 110;
+                       account->incoming_server_secure_connection         = 0;
+                       account->incoming_server_authentication_method = EMAIL_AUTHENTICATION_METHOD_NO_AUTH;
+                       account->outgoing_server_address               = strdup("mail.mopera.net");
+                       account->outgoing_server_port_number           = 465;
+                       account->outgoing_server_secure_connection     = 0;
+                       account->outgoing_server_need_authentication   = EMAIL_AUTHENTICATION_METHOD_DEFAULT;
+                       break;
+
                default:
                        testapp_print("Invalid Account Number\n");
                        return FALSE;
@@ -342,14 +404,12 @@ static gboolean testapp_test_update_account()
        testapp_print("\n>> Enter Account No: ");
        result_from_scanf = scanf("%d",&account_id);
 
-/* sowmya.kr, 281209 Adding signature to options in email_account_t changes */
        if( (err = email_get_account(account_id, GET_FULL_DATA,&account)) != EMAIL_ERROR_NONE) {
                testapp_print ("email_get_account failed - %d\n", err);
                return false;
        }
 
        testapp_print ("email_get_account result account_name - %s \n", account->account_name);
-
        testapp_print ("email_get_account result signature - %s \n", account->options.signature);
 
 #ifdef __FEATURE_AUTO_POLLING__
@@ -365,6 +425,18 @@ static gboolean testapp_test_update_account()
 #ifdef __FEATURE_AUTO_POLLING__
        testapp_print("\n Enter new check interval (in mins):");
        result_from_scanf = scanf("%d",&(account->check_interval));
+
+       testapp_print("\n Enter new peak interval (in mins):");
+       result_from_scanf = scanf("%d",&(account->peak_interval));
+
+       testapp_print("\n Enter new peak days:");
+       result_from_scanf = scanf("%d",&(account->peak_days));
+
+       testapp_print("\n Enter new peak start time:");
+       result_from_scanf = scanf("%d",&(account->peak_start_time));
+
+       testapp_print("\n Enter new peak end time:");
+       result_from_scanf = scanf("%d",&(account->peak_end_time));
 #endif
        testapp_print("\n Enter new signature:");
        result_from_scanf = scanf("%s",signature);
@@ -521,6 +593,13 @@ static gboolean testapp_test_get_account()
                        "index_color %d\n"
                        "certificate_path %s\n"
                        "digest_type %d\n"
+                       "auto_resend_times %d\n"
+                       "roaming_option %d\n"
+
+                       "peak_interval %d\n"
+                       "peak_days %d\n"
+                       "peak_start_time %d\n"
+                       "peak_end_time %d\n"
                ,
                account->account_name,
                account->user_email_address,
@@ -537,7 +616,13 @@ static gboolean testapp_test_get_account()
                is_preset_account,
                index_color,
                account->certificate_path,
-               account->digest_type
+               account->digest_type,
+               account->auto_resend_times,
+               account->roaming_option,
+               account->peak_interval,
+               account->peak_days,
+               account->peak_start_time,
+               account->peak_end_time
                );
 
        err_code = email_free_account(&account, 1);
@@ -849,6 +934,56 @@ static gboolean testapp_test_add_account()
        return true;
 }
 
+static gboolean testapp_test_update_peak_schedule()
+{
+       int result_from_scanf = 0;
+       int account_id;
+       email_account_t *account = NULL;
+       int err = EMAIL_ERROR_NONE;
+
+       testapp_print("\n>> Enter Account No: ");
+       result_from_scanf = scanf("%d",&account_id);
+
+       if( (err = email_get_account(account_id, GET_FULL_DATA, &account)) != EMAIL_ERROR_NONE) {
+               testapp_print ("email_get_account failed [%d]\n", err);
+               return false;
+       }
+
+       testapp_print ("old check_interval - %d \n", account->check_interval);
+
+       testapp_print("\n Enter new check interval (in mins):");
+       result_from_scanf = scanf("%d",&(account->check_interval));
+
+       testapp_print ("old peak_interval - %d \n", account->peak_interval);
+
+       testapp_print("\n Enter new peak interval (in mins):");
+       result_from_scanf = scanf("%d",&(account->peak_interval));
+
+       testapp_print ("old peak_days - %d \n", account->peak_days);
+
+       testapp_print("\n Enter new peak days:");
+       result_from_scanf = scanf("%d",&(account->peak_days));
+
+       testapp_print ("old peak_start_time - %d \n", account->peak_start_time);
+
+       testapp_print("\n Enter new peak start time:");
+       result_from_scanf = scanf("%d",&(account->peak_start_time));
+
+       testapp_print ("old peak_end_time - %d \n", account->peak_start_time);
+
+       testapp_print("\n Enter new peak end time:");
+       result_from_scanf = scanf("%d",&(account->peak_end_time));
+
+       if( account )  {
+               if((err = email_update_account(account_id, account)) != EMAIL_ERROR_NONE) {
+                       testapp_print ("email_update_account failed [%d]\n", err);
+                       return false;
+               }
+               testapp_print ("email_update_account successful \n");
+       }
+       return true;
+}
+
 static gboolean testapp_test_interpret_command (int selected_number)
 {
        gboolean go_to_loop = TRUE;
@@ -930,6 +1065,10 @@ static gboolean testapp_test_interpret_command (int selected_number)
                        testapp_test_add_account();
                        break;
 
+               case 20:
+                       testapp_test_update_peak_schedule();
+                       break;
+
                case 0:
                        go_to_loop = FALSE;
                        break;
index f65e426..add534f 100755 (executable)
@@ -140,17 +140,18 @@ static gboolean testapp_add_mail_for_sending (int *result_mail_id)
 
        SNPRINTF(from_address, 300, "<%s>", account_data->user_email_address);
 
-       test_mail_data->account_id           = account_id;
-       test_mail_data->save_status          = 1;
-       test_mail_data->body_download_status = 1;
-       test_mail_data->flags_seen_field     = 1;
-       test_mail_data->file_path_plain      = strdup(body_file_path);
-       test_mail_data->mailbox_id           = mailbox_data->mailbox_id;
-       test_mail_data->mailbox_type         = mailbox_data->mailbox_type;
-       test_mail_data->full_address_from    = strdup(from_address);
-       test_mail_data->full_address_to      = strdup(receipient_address);
-       test_mail_data->subject              = strdup("Read receipt request from TIZEN");
-       test_mail_data->report_status        = EMAIL_MAIL_REQUEST_DSN | EMAIL_MAIL_REQUEST_MDN;
+       test_mail_data->account_id             = account_id;
+       test_mail_data->save_status            = EMAIL_MAIL_STATUS_SEND_DELAYED;
+       test_mail_data->body_download_status   = 1;
+       test_mail_data->flags_seen_field       = 1;
+       test_mail_data->file_path_plain        = strdup(body_file_path);
+       test_mail_data->mailbox_id             = mailbox_data->mailbox_id;
+       test_mail_data->mailbox_type           = mailbox_data->mailbox_type;
+       test_mail_data->full_address_from      = strdup(from_address);
+       test_mail_data->full_address_to        = strdup(receipient_address);
+       test_mail_data->subject                = strdup("Read receipt request from TIZEN");
+       test_mail_data->remaining_resend_times = 3;
+       test_mail_data->report_status          = EMAIL_MAIL_REQUEST_DSN | EMAIL_MAIL_REQUEST_MDN;
 
        body_file = fopen(body_file_path, "w");
 
@@ -222,20 +223,21 @@ static gboolean testapp_test_add_mail (int *result_mail_id)
        testapp_print("\n From EAS? [0/1]> ");
        result_from_scanf = scanf("%d", &from_eas);
 
-       test_mail_data->account_id           = account_id;
-       test_mail_data->save_status          = 1;
-       test_mail_data->body_download_status = 1;
-       test_mail_data->flags_seen_field     = 1;
-       test_mail_data->file_path_plain      = strdup(body_file_path);
-       test_mail_data->mailbox_id           = mailbox_id;
-       test_mail_data->mailbox_type         = mailbox_data->mailbox_type;
-       test_mail_data->full_address_from    = strdup("<test1@test.com>");
-       test_mail_data->full_address_to      = strdup("<test2@test.com>");
-       test_mail_data->full_address_cc      = strdup("<test3@test.com>");
-       test_mail_data->full_address_bcc     = strdup("<test4@test.com>");
-       test_mail_data->subject              = strdup("Meeting request mail");
-       test_mail_data->eas_data             = strdup("EAS DATA TEST");
-       test_mail_data->eas_data_length      = strlen(test_mail_data->eas_data) + 1;
+       test_mail_data->account_id             = account_id;
+       test_mail_data->save_status            = 1;
+       test_mail_data->body_download_status   = 1;
+       test_mail_data->flags_seen_field       = 1;
+       test_mail_data->file_path_plain        = strdup(body_file_path);
+       test_mail_data->mailbox_id             = mailbox_id;
+       test_mail_data->mailbox_type           = mailbox_data->mailbox_type;
+       test_mail_data->full_address_from      = strdup("<test1@test.com>");
+       test_mail_data->full_address_to        = strdup("<test2@test.com>");
+       test_mail_data->full_address_cc        = strdup("<test3@test.com>");
+       test_mail_data->full_address_bcc       = strdup("<test4@test.com>");
+       test_mail_data->subject                = strdup("Meeting request mail");
+       test_mail_data->remaining_resend_times = 3;
+       test_mail_data->eas_data               = strdup("EAS DATA TEST");
+       test_mail_data->eas_data_length        = strlen(test_mail_data->eas_data) + 1;
 
        body_file = fopen(body_file_path, "w");
 
@@ -361,7 +363,7 @@ static gboolean testapp_test_update_mail()
 
        if (test_mail_data->attachment_count > 0) {
                if ( (err = email_get_attachment_data_list(mail_id, &test_attachment_data_list, &test_attachment_data_count)) != EMAIL_ERROR_NONE ) {
-                       testapp_print("email_get_meeting_request() failed [%d]\n", err);
+                       testapp_print("email_get_attachment_data_list() failed [%d]\n", err);
                        goto FINISH_OFF;
                }
        }       
@@ -456,13 +458,13 @@ static gboolean testapp_test_get_mails()
 
        /* Get mail list */
        if(mailbox_id == 0) {
-               testapp_print("Calling email_get_mail_list for all mailbox.\n");
+               testapp_print("Calling email_get_mails for all mailbox.\n");
                err_code = email_get_mails(account_id, 0, list_type, start_index, limit_count, sorting, mails_pointer, &count);
                if ( err_code < 0)
                        testapp_print("email_get_mails failed - err[%d]\n", err_code);
        }
        else {
-               testapp_print("Calling email_get_mail_list for %d mailbox_id.\n", mailbox_id);
+               testapp_print("Calling email_get_mails for %d mailbox_id.\n", mailbox_id);
                err_code = email_get_mails(account_id, mailbox_id, list_type, start_index, limit_count, sorting,  mails_pointer, &count);
                if ( err_code < 0)
                        testapp_print("email_get_mails failed - err[%d]\n", err_code);
@@ -553,21 +555,44 @@ static gboolean testapp_test_get_mail_list_ex()
        filter_list = malloc(sizeof(email_list_filter_t) * filter_rule_count);
        memset(filter_list, 0 , sizeof(email_list_filter_t) * filter_rule_count);
 
-       filter_list[0].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_RULE_FTS;
-       filter_list[0].list_filter_item.rule_fts.target_attribute              = EMAIL_MAIL_TEXT_ATTRIBUTE_FULL_TEXT;
-       filter_list[0].list_filter_item.rule_fts.rule_type                     = EMAIL_LIST_FILTER_RULE_MATCH;
-       filter_list[0].list_filter_item.rule_fts.key_value.string_type_value  = strdup("ieee");
+       filter_list[0].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_RULE;
+       filter_list[0].list_filter_item.rule.target_attribute              = EMAIL_MAIL_ATTRIBUTE_ACCOUNT_ID;
+       filter_list[0].list_filter_item.rule.rule_type                     = EMAIL_LIST_FILTER_RULE_EQUAL;
+       filter_list[0].list_filter_item.rule.key_value.integer_type_value  = 1;
+       filter_list[0].list_filter_item.rule.case_sensitivity              = false;
+
+       filter_list[1].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_OPERATOR;
+       filter_list[1].list_filter_item.operator_type                      = EMAIL_LIST_FILTER_OPERATOR_AND;
+
+       filter_list[2].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_RULE;
+       filter_list[2].list_filter_item.rule.target_attribute              = EMAIL_MAIL_ATTRIBUTE_MAILBOX_TYPE;
+       filter_list[2].list_filter_item.rule.rule_type                     = EMAIL_LIST_FILTER_RULE_EQUAL;
+       filter_list[2].list_filter_item.rule.key_value.integer_type_value  = EMAIL_MAILBOX_TYPE_INBOX;
+       filter_list[2].list_filter_item.rule.case_sensitivity              = false;
+
+       /*filter_list[0].list_filter_item_type                                     = EMAIL_LIST_FILTER_ITEM_RULE_ATTACH;
+       filter_list[0].list_filter_item.rule_attach.target_attribute             = EMAIL_MAIL_ATTACH_ATTRIBUTE_ATTACHMENT_NAME;
+       filter_list[0].list_filter_item.rule_attach.rule_type                    = EMAIL_LIST_FILTER_RULE_INCLUDE;
+       filter_list[0].list_filter_item.rule_attach.key_value.string_type_value  = strdup("test");
+       filter_list[0].list_filter_item.rule_attach.case_sensitivity             = false;*/
+
+       /*
+       filter_list[0].list_filter_item_type                                  = EMAIL_LIST_FILTER_ITEM_RULE;
+       filter_list[0].list_filter_item.rule_fts.target_attribute             = EMAIL_MAIL_ATTRIBUTE_ACCOUNT_ID;
+       filter_list[0].list_filter_item.rule_fts.rule_type                    = EMAIL_LIST_FILTER_RULE_EQUAL;
+       filter_list[0].list_filter_item.rule_fts.key_value.integer_type_value = 1;
 
        filter_list[1].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_OPERATOR;
        filter_list[1].list_filter_item.operator_type                      = EMAIL_LIST_FILTER_OPERATOR_OR;
 
+
        filter_list[2].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_RULE;
        filter_list[2].list_filter_item.rule.target_attribute              = EMAIL_MAIL_ATTRIBUTE_SUBJECT;
        filter_list[2].list_filter_item.rule.rule_type                     = EMAIL_LIST_FILTER_RULE_INCLUDE;
        filter_list[2].list_filter_item.rule.key_value.string_type_value   = strdup("2013");
        filter_list[2].list_filter_item.rule.case_sensitivity              = false;
 
-       /*
+
        filter_list[1].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_OPERATOR;
        filter_list[1].list_filter_item.operator_type                      = EMAIL_LIST_FILTER_OPERATOR_OR;
 
@@ -620,21 +645,25 @@ static gboolean testapp_test_get_mail_list_ex()
        filter_list[2].list_filter_item.rule.key_value.string_type_value   = strdup("INBOX");
        filter_list[2].list_filter_item.rule.case_sensitivity              = true;
        */
-       sorting_rule_count = 1;
+       sorting_rule_count = 2;
 
        sorting_rule_list = malloc(sizeof(email_list_sorting_rule_t) * sorting_rule_count);
        memset(sorting_rule_list, 0 , sizeof(email_list_sorting_rule_t) * sorting_rule_count);
 
-       sorting_rule_list[0].target_attribute                              = EMAIL_MAIL_ATTRIBUTE_DATE_TIME;
-       sorting_rule_list[0].sort_order                                    = EMAIL_SORT_ORDER_DESCEND;
+       sorting_rule_list[0].target_attribute                              = EMAIL_MAIL_ATTRIBUTE_RECIPIENT_ADDRESS;
+       sorting_rule_list[0].key_value.string_type_value                   = strdup("minsoo.kimn@gmail.com");
+       sorting_rule_list[0].sort_order                                    = EMAIL_SORT_ORDER_TO_CCBCC;
 
-       err = email_get_mail_list_ex(filter_list, filter_rule_count, sorting_rule_list, sorting_rule_count, 0, 10, &result_mail_list, &result_mail_count);
+       sorting_rule_list[1].target_attribute                              = EMAIL_MAIL_ATTRIBUTE_DATE_TIME;
+       sorting_rule_list[1].sort_order                                    = EMAIL_SORT_ORDER_DESCEND;
+
+       err = email_get_mail_list_ex(filter_list, filter_rule_count, sorting_rule_list, sorting_rule_count, -1, -1, &result_mail_list, &result_mail_count);
 
        if(err == EMAIL_ERROR_NONE) {
                testapp_print("email_get_mail_list_ex succeed.\n");
 
                for(i = 0; i < result_mail_count; i++) {
-                       testapp_print("mail_id [%d], subject [%s], full_address_from [%s]\n", result_mail_list[i].mail_id, result_mail_list[i].subject, result_mail_list[i].full_address_from);
+                       testapp_print("mail_id [%d], subject [%s], mailbox_type [%d] full_address_from [%s]\n", result_mail_list[i].mail_id, result_mail_list[i].subject, result_mail_list[i].mailbox_type, result_mail_list[i].full_address_from);
                }
        }
        else {
@@ -990,6 +1019,7 @@ static gboolean testapp_test_get_mail_list()
                for (i=0; i< count; i++) {
                        testapp_print("\n[%d]\n", i);
                        testapp_print(" >>> mailbox_id [ %d ] \n", mail_list[i].mailbox_id);
+                       testapp_print(" >>> mailbox_type [ %d ] \n", mail_list[i].mailbox_type);
                        testapp_print(" >>> mail_id [ %d ] \n", mail_list[i].mail_id);
                        testapp_print(" >>> account_id [ %d ] \n", mail_list[i].account_id);
                        if (  mail_list[i].full_address_from != NULL )
@@ -1410,6 +1440,7 @@ static gboolean   testapp_test_get_mail_data()
        testapp_print("digest_type [%d]\n", mail_data->digest_type);
        testapp_print("smime_type [%d]\n", mail_data->smime_type);
        testapp_print("scheduled_sending_time [%d]\n", mail_data->scheduled_sending_time);
+       testapp_print("remaining_resend_times [%d]\n", mail_data->remaining_resend_times);
        testapp_print("eas_data_length [%d]\n", mail_data->eas_data_length);
 
        return TRUE;
@@ -1540,12 +1571,58 @@ static gboolean testapp_test_download_attachment ()
 
 static gboolean testapp_test_get_attachment_data_list()
 {
+       int err = EMAIL_ERROR_NONE;
+       int i = 0;
        int mail_id = 0;
        int result_from_scanf = 0;
+       int test_attachment_data_count;
+       email_attachment_data_t *test_attachment_data_list = NULL;
+
+       testapp_print("\n > Enter Mail id: ");
+       result_from_scanf = scanf("%d", &mail_id);
+
+       if ( (err = email_get_attachment_data_list(mail_id, &test_attachment_data_list, &test_attachment_data_count)) != EMAIL_ERROR_NONE ) {
+               testapp_print("email_get_attachment_data_list() failed [%d]\n", err);
+               goto FINISH_OFF;
+       }
+       if(test_attachment_data_list) {
+               for(i = 0; i < test_attachment_data_count; i++) {
+                       testapp_print("index [%d]\n", i);
+                       testapp_print("attachment_name [%s]\n", test_attachment_data_list[i].attachment_name);
+                       testapp_print("attachment_path [%s]\n", test_attachment_data_list[i].attachment_path);
+                       testapp_print("attachment_size [%d]\n", test_attachment_data_list[i].attachment_size);
+                       testapp_print("mail_id [%d]\n", test_attachment_data_list[i].mail_id);
+                       testapp_print("attachment_mime_type [%s]\n", test_attachment_data_list[i].attachment_mime_type);
+               }
+               email_free_attachment_data(&test_attachment_data_list, test_attachment_data_count);
+       }
+
+FINISH_OFF:
+
+       return TRUE;
+}
+
+static gboolean testapp_test_get_meeting_request()
+{
+       int mail_id = 0;
+       int result_from_scanf = 0;
+       int err = EMAIL_ERROR_NONE;
+       email_meeting_request_t *meeting_request;
 
        testapp_print("\n > Enter Mail Id: ");
        result_from_scanf = scanf("%d", &mail_id);
 
+       err = email_get_meeting_request(mail_id, &meeting_request);
+
+       testapp_print("err[%d]\n", err);
+
+       if(err == EMAIL_ERROR_NONE && meeting_request) {
+               testapp_print("mail_id [%d]\n", meeting_request->mail_id);
+               testapp_print("global_object_id [%s]\n", meeting_request->global_object_id);
+               testapp_print("meeting_response [%d]\n", meeting_request->meeting_response);
+       }
+
+       email_free_meeting_request(&meeting_request, 1);
        return TRUE;
 }
 
@@ -1569,6 +1646,28 @@ static gboolean testapp_test_retry_send()
        return TRUE;            
 }
 
+static gboolean testapp_test_get_attachment_data()
+{
+       int attachment_id = 0;
+       int result_from_scanf = 0;
+       email_attachment_data_t *attachment = NULL;
+
+       testapp_print("\n > Enter attachment id: ");
+       result_from_scanf = scanf("%d", &attachment_id);
+
+       email_get_attachment_data(attachment_id, &attachment);
+
+       if(attachment) {
+               testapp_print("attachment_name [%s]\n", attachment->attachment_name);
+               testapp_print("attachment_path [%s]\n", attachment->attachment_path);
+               testapp_print("attachment_size [%d]\n", attachment->attachment_size);
+               testapp_print("mail_id [%d]\n", attachment->mail_id);
+               testapp_print("attachment_mime_type [%s]\n", attachment->attachment_mime_type);
+       }
+
+       return TRUE;
+}
+
 static gboolean testapp_test_move_all_mails_to_mailbox()
 {
        int err = EMAIL_ERROR_NONE;
@@ -1977,18 +2076,19 @@ static gboolean testapp_test_add_mail_to_search_result_box()
        testapp_print("\n From EAS? [0/1]> ");
        result_from_scanf = scanf("%d", &from_eas);
 
-       test_mail_data->account_id           = account_id;
-       test_mail_data->save_status          = 1;
-       test_mail_data->body_download_status = 1;
-       test_mail_data->flags_seen_field     = 1;
-       test_mail_data->file_path_plain      = strdup(body_file_path);
-       test_mail_data->mailbox_id           = mailbox_data->mailbox_id;
-       test_mail_data->mailbox_type         = mailbox_data->mailbox_type;
-       test_mail_data->full_address_from    = strdup("<test1@test.com>");
-       test_mail_data->full_address_to      = strdup("<test2@test.com>");
-       test_mail_data->full_address_cc      = strdup("<test3@test.com>");
-       test_mail_data->full_address_bcc     = strdup("<test4@test.com>");
-       test_mail_data->subject              = strdup("Into search result mailbox");
+       test_mail_data->account_id             = account_id;
+       test_mail_data->save_status            = 1;
+       test_mail_data->body_download_status   = 1;
+       test_mail_data->flags_seen_field       = 1;
+       test_mail_data->file_path_plain        = strdup(body_file_path);
+       test_mail_data->mailbox_id             = mailbox_data->mailbox_id;
+       test_mail_data->mailbox_type           = mailbox_data->mailbox_type;
+       test_mail_data->full_address_from      = strdup("<test1@test.com>");
+       test_mail_data->full_address_to        = strdup("<test2@test.com>");
+       test_mail_data->full_address_cc        = strdup("<test3@test.com>");
+       test_mail_data->full_address_bcc       = strdup("<test4@test.com>");
+       test_mail_data->subject                = strdup("Into search result mailbox");
+       test_mail_data->remaining_resend_times = 3;
 
        body_file = fopen(body_file_path, "w");
 
@@ -2073,9 +2173,11 @@ static gboolean testapp_test_email_parse_mime_file()
        email_attachment_data_t *mail_attachment_data = NULL;
        int i = 0;
        int attachment_count = 0;
+       int verify = 0;
        int err = EMAIL_ERROR_NONE;
        int result_from_scanf = 0;
        char eml_file_path[255] = {0, };
+        struct tm *struct_time;
 
        testapp_print("Input eml file path : ");
        result_from_scanf = scanf("%s", eml_file_path);
@@ -2085,8 +2187,20 @@ static gboolean testapp_test_email_parse_mime_file()
                testapp_print("email_parse_mime_file failed : [%d]\n", err);
                return false;   
        }
-       
-       testapp_print("load success\n");
+       
+        testapp_print("load success\n");
+
+        struct_time = localtime(&(mail_data->date_time));
+
+        testapp_print("%4d year",       struct_time->tm_year +1900);
+        testapp_print("  %2d month(0-11)\n", struct_time->tm_mon  +1   );
+        testapp_print("  %2d day(1-31)\n", struct_time->tm_mday      );
+        testapp_print("  %2d wday\n", struct_time->tm_wday);
+        testapp_print("  %2d hour(0-23)\n", struct_time->tm_hour      );
+        testapp_print("  %2d minutes(0-59)\n", struct_time->tm_min       );
+        testapp_print("  %2d second(0-59)\n", struct_time->tm_sec       );
+        testapp_print("year day %3d\n", struct_time->tm_yday);
+
        testapp_print("Return-Path: %s\n", mail_data->full_address_return);
        testapp_print("To: %s\n", mail_data->full_address_to);
        testapp_print("Subject: %s\n", mail_data->subject);
@@ -2097,8 +2211,10 @@ static gboolean testapp_test_email_parse_mime_file()
        testapp_print("attachment_count: %d\n", mail_data->attachment_count);
        testapp_print("SMIME type : %d\n", mail_data->smime_type);
        testapp_print("inline content count : %d\n", mail_data->inline_content_count);
+       testapp_print("download_body_status : %d\n", mail_data->body_download_status);
+
 
-       for (i = 0;i < mail_data->attachment_count ; i++) {
+       for (i = 0;i < attachment_count ; i++) {
                testapp_print("attachment_id: %d\n", mail_attachment_data[i].attachment_id);
                testapp_print("inline_attachment_status: %d\n", mail_attachment_data[i].inline_content_status);
                testapp_print("attachment_name: %s\n", mail_attachment_data[i].attachment_name);
@@ -2107,6 +2223,15 @@ static gboolean testapp_test_email_parse_mime_file()
        }
 
        testapp_print("Success : Open eml file\n");
+
+       if (mail_data->smime_type == EMAIL_SMIME_SIGNED) {
+               if (!email_verify_signature_ex(mail_data, mail_attachment_data, attachment_count, &verify)) {
+                       testapp_print("email_verify_signature_ex failed\n");
+               }       
+
+               testapp_print("verify : [%d]\n", verify);
+       }       
+
        
        if ((err = email_delete_parsed_data(mail_data)) != EMAIL_ERROR_NONE) {
                testapp_print("email_delete_eml_data failed : [%d]\n", err);
@@ -2272,6 +2397,9 @@ static gboolean testapp_test_interpret_command (int menu_number)
                case 18:
                        testapp_test_get_attachment_data_list();
                        break;
+               case 19:
+                       testapp_test_get_meeting_request();
+                       break;
                case 20:
                        testapp_test_delete_all();
                        break;
@@ -2281,6 +2409,9 @@ static gboolean testapp_test_interpret_command (int menu_number)
                case 23:
                        testapp_test_retry_send();
                        break;
+               case 24:
+                       testapp_test_get_attachment_data();
+                       break;
                case 27:
                        testapp_test_move_all_mails_to_mailbox();
                        break;
index 283cb06..6caee04 100755 (executable)
@@ -48,7 +48,7 @@ static gboolean testapp_print_mailbox_list(email_mailbox_t *input_mailbox_list,
        testapp_print("There are %d mailboxes\n", input_count);
 
        testapp_print("============================================================================\n");
-       testapp_print("id   a_id  name\t\t\t         alias\t\t unread\t total\t total_on_ server\tmailbox_type\t last_sync_time\n");
+       testapp_print("id\ta_id\talias\tunread\t total\t total_on_ server\tmailbox_type\tlast_sync_time\n");
        testapp_print("============================================================================\n");
        if ( input_count == 0 ) {
                testapp_print("No mailbox is matched\n");
@@ -56,9 +56,9 @@ static gboolean testapp_print_mailbox_list(email_mailbox_t *input_mailbox_list,
        else {
                for(i=0;i<input_count;i++) {
                        strftime(time_string, 40, "%Y-%m-%d %H:%M:%S", localtime(&(input_mailbox_list[i].last_sync_time)));
-                       testapp_print("[%2d]", input_mailbox_list[i].mailbox_id);
-                       testapp_print("  %2d  [%2d]\t[%-12s]  ", input_mailbox_list[i].account_id, input_mailbox_list[i].mailbox_id, input_mailbox_list[i].alias);
-                       testapp_print(" %3d\t %3d\t %3d\t %3d\t %s\n"
+                       testapp_print("%2d\t", input_mailbox_list[i].mailbox_id);
+                       testapp_print("%2d\t%-12s\t", input_mailbox_list[i].account_id, input_mailbox_list[i].alias);
+                       testapp_print("%3d\t%3d\t%3d\t%3d\t%s\n"
                                        , input_mailbox_list[i].unread_count
                                        , input_mailbox_list[i].total_mail_count_on_local
                                        , input_mailbox_list[i].total_mail_count_on_server
@@ -81,6 +81,8 @@ static gboolean testapp_test_add_mailbox()
     int handle;
     int result_from_scanf = 0;
 
+    memset(&mailbox, 0, sizeof(email_mailbox_t));
+
        memset(arg, 0x00, 500);
        testapp_print("\n> Enter mailbox name: ");
        result_from_scanf = scanf("%s",arg);
@@ -99,11 +101,14 @@ static gboolean testapp_test_add_mailbox()
        result_from_scanf = scanf("%d", &local_yn);
        mailbox.local= local_yn;        
 
-
        testapp_print("> Enter mailbox type: ");
        result_from_scanf = scanf("%d", &mailbox_type);
        mailbox.mailbox_type= mailbox_type;
 
+       mailbox.eas_data               = strdup("EAS DATA TEST");
+       mailbox.eas_data_length        = strlen(mailbox.eas_data) + 1;
+
+
        ret = email_add_mailbox(&mailbox, local_yn?0:1, &handle);
 
        if (ret  < 0) {
@@ -113,6 +118,9 @@ static gboolean testapp_test_add_mailbox()
                testapp_print("\n email_add_mailbox succeed : handle[%d], mailbox_id [%d]\n", handle, mailbox.mailbox_id);
        }
        
+       if(mailbox.eas_data)
+               free(mailbox.eas_data);
+
        return FALSE;
 }
 
@@ -167,7 +175,7 @@ static gboolean testapp_test_rename_mailbox()
                testapp_print("\n email_rename_mailbox failed[%d]\n", err);
        }
        else {
-               testapp_print("\n email_rename_mailbox succeed\n");
+               testapp_print("\n email_rename_mailbox succeed. handle [%d]\n", handle);
        }
 
        return FALSE;
@@ -351,6 +359,33 @@ static gboolean testapp_test_get_mailbox_list ()
        return FALSE;
 }
 
+static gboolean testapp_test_get_mailbox_list_by_keyword ()
+{
+       int result_from_scanf = 0;
+       int account_id =0;
+       int count = 0;
+       char keyword[500] = { 0, };
+       int error_code = EMAIL_ERROR_NONE;
+       email_mailbox_t *mailbox_list = NULL;
+       testapp_print("\n > Enter account id: ");
+       result_from_scanf = scanf("%d", &account_id);
+
+       testapp_print("> Enter keyword: ");
+       result_from_scanf = scanf("%s", keyword);
+
+       if ((error_code = email_get_mailbox_list_by_keyword(account_id, keyword, &mailbox_list, &count)) < 0) {
+               testapp_print("   email_get_mailbox_list_by_keyword error %d\n", error_code);
+               return false ;
+       }
+
+       testapp_print_mailbox_list(mailbox_list, count);
+
+       email_free_mailbox(&mailbox_list, count);
+
+       return FALSE;
+}
+
+
 static gboolean testapp_test_sync_mailbox()
 {
        int result_from_scanf = 0;
@@ -393,6 +428,36 @@ static gboolean testapp_test_stamp_sync_time()
        return FALSE;
 }
 
+static gboolean testapp_test_rename_mailbox_ex()
+{
+       testapp_print ("testapp_test_rename_mailbox_ex\n");
+       int mailbox_id;
+       char mailbox_name[500] = { 0, };
+       char mailbox_alias[500] = { 0, };
+       char eas_data[500] = "OK. Done";
+       int err;
+       int result_from_scanf = 0;
+       int handle = 0;
+
+       testapp_print("> Enter mailbox id: ");
+       result_from_scanf = scanf("%d", &mailbox_id);
+
+       testapp_print("> Enter new mailbox name: ");
+       result_from_scanf = scanf("%s", mailbox_name);
+
+       testapp_print("> Enter new mailbox alias: ");
+       result_from_scanf = scanf("%s", mailbox_alias);
+
+
+       if ( (err = email_rename_mailbox_ex(mailbox_id, mailbox_name, mailbox_alias, eas_data, strlen(eas_data), false, &handle)) < 0) {
+               testapp_print("\n email_rename_mailbox failed[%d]\n", err);
+       }
+       else {
+               testapp_print("\n email_rename_mailbox succeed\n");
+       }
+       return FALSE;
+}
+
 static gboolean testapp_test_interpret_command (int menu_number)
 {
        gboolean go_to_loop = TRUE;
@@ -446,6 +511,14 @@ static gboolean testapp_test_interpret_command (int menu_number)
                        testapp_test_stamp_sync_time();
                        break;
 
+               case 13:
+                       testapp_test_rename_mailbox_ex();
+                       break;
+
+               case 14:
+                       testapp_test_get_mailbox_list_by_keyword();
+                       break;
+
                case 0:
                        go_to_loop = FALSE;
                        break;
index 487bc46..e24d32e 100755 (executable)
 #include "email-ipc.h"
 #include "email-core-utils.h"
 
+static gboolean testapp_test_ping_service()
+{
+       if(email_ping_service() < 0)
+               testapp_print("email_ping_service failed..!");
+
+       return FALSE;
+}
+
 static gboolean testapp_test_cancel_job        ()
 {
        int account_id = 0;
@@ -208,7 +216,7 @@ FINISH_OFF:
        return error;
 }
 
-#define LIB_EMAIL_SERVICE_PATH LIBPATH "libemail-api.so"
+#define LIB_EMAIL_SERVICE_PATH "/usr/lib/libemail-api.so"
 
 int (*Datastore_FI_EMTB)(char **);
 int (*Datastore_FI_EMSB)(char **);
@@ -377,11 +385,25 @@ static gboolean testapp_test_get_mime_entity()
        return true;
 }
 
+static gboolean testapp_test_query_smtp_mail_size_limit()
+{
+       int result_from_scanf = 0;
+       int account_id = 0;
+       testapp_print("\n > Enter account id : ");
+       result_from_scanf = scanf("%d", &account_id);
+
+       email_query_smtp_mail_size_limit(account_id, NULL);
+       return true;
+}
+
 static gboolean testapp_test_interpret_command (int menu_number)
 {
        gboolean go_to_loop = TRUE;
 
        switch (menu_number) {
+               case 1:
+                       testapp_test_ping_service();
+                       break;
                case 3:
                        testapp_test_cancel_job ();
                        break;
@@ -414,6 +436,9 @@ static gboolean testapp_test_interpret_command (int menu_number)
                case 16:
                        testapp_test_get_mime_entity();
                        break;
+               case 17:
+                       testapp_test_query_smtp_mail_size_limit();
+                       break;
                case 0:
                        go_to_loop = FALSE;
                        break;
index 9daf8ef..c834b7e 100755 (executable)
@@ -56,6 +56,7 @@ void testapp_show_menu (eEMAIL_MENU menu)
                        testapp_print ("5. Rule Test\n");
                        testapp_print ("6. Thread Test\n");
                        testapp_print ("7. Others\n");
+                       testapp_print ("8. Gmime test\n");
                        testapp_print ("0. Exit \n");
                        testapp_print ("------------------------------------------\n");
                        break;
@@ -83,6 +84,7 @@ void testapp_show_menu (eEMAIL_MENU menu)
                        testapp_print (" 17. Get certificate\n");
                        testapp_print (" 18. Delete certificate\n");
                        testapp_print (" 19. Add Account\n");
+                       testapp_print (" 20. Update peak schedule\n");
                        testapp_print (" 0.  Go to Main Menu\n");
                        testapp_print ("------------------------------------------\n");
                        break;
@@ -108,9 +110,12 @@ void testapp_show_menu (eEMAIL_MENU menu)
                        testapp_print ("15. Update mail attribute \n");
                        testapp_print ("16. Download mail body\n");
                        testapp_print ("17. Download an attachment\n");
+                       testapp_print ("18. Get attachment list\n");
+                       testapp_print ("19. Get meeting request\n");
                        testapp_print ("20. Delete all mail\n");
                        testapp_print ("21. Move Mail \n");
                        testapp_print ("23. Resend Mail \n");
+                       testapp_print ("24. Get attachment data \n");
                        testapp_print ("27. Move all mails to mailbox\n");
                        testapp_print ("38. Get total email disk usage \n");    
                        testapp_print ("40. Verify Email Address Format\n");
@@ -149,6 +154,8 @@ void testapp_show_menu (eEMAIL_MENU menu)
                        testapp_print ("10. Get mailbox list\n");
                        testapp_print ("11. Sync mailbox\n");
                        testapp_print ("12. Stamp sync time\n");
+                       testapp_print ("13. Raname mailbox ex\n");
+                       testapp_print ("14. Get mailbox list by keyword\n");
                        testapp_print ("0. Go to Main Menu\n");
                        testapp_print ("------------------------------------------\n");
                        break;
@@ -181,6 +188,7 @@ void testapp_show_menu (eEMAIL_MENU menu)
                        testapp_print ("==========================================\n");
                        testapp_print ("   OTHERS\n");
                        testapp_print ("==========================================\n");
+                       testapp_print ("1.  Ping service\n");
                        testapp_print ("3.  Cancel Job\n");
                        testapp_print ("5.  Set DNET Proper Profile Type\n");
                        testapp_print ("6.  Get DNET Proper Profile Type\n");
@@ -191,10 +199,20 @@ void testapp_show_menu (eEMAIL_MENU menu)
                        testapp_print ("14. DTT Test\n");
                        testapp_print ("15. Show User Message\n");
                        testapp_print ("16. Get mime entity in signed file\n");
+                       testapp_print ("17. Query SMTP mail size limit\n");
                        testapp_print ("0.  Go to Main Menu\n");
                        testapp_print ("------------------------------------------\n");
                        break;
                        
+               case EMAIL_GMIME_MENU:
+                       testapp_print ("==========================================\n");
+                       testapp_print ("   Gmime Test\n");
+                       testapp_print ("==========================================\n");
+                       testapp_print ("1. Parsing eml\n");
+                       testapp_print ("0.  Go to Main Menu\n");
+                       testapp_print ("------------------------------------------\n");
+                       break;
+
                default:
                        break;
        }
@@ -230,6 +248,10 @@ void testapp_show_prompt (eEMAIL_MENU menu)
                        testapp_print ("[OTHERS]# ");
                        break;
                        
+               case EMAIL_GMIME_MENU:
+                       testapp_print ("[Gmime Test]# ");
+                       break;
+
                default:
                        break;
        }