2 * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3 * Copyright (C) 1999-2003 Hiroyuki Yamamoto
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
44 #include "procheader.h"
46 #include "prefs_account.h"
49 #include "inputdialog.h"
52 #define IMAP4_PORT 143
54 #define IMAPS_PORT 993
57 #define QUOTE_IF_REQUIRED(out, str) \
59 if (*str != '"' && strpbrk(str, " \t(){}%*") != NULL) { \
63 len = strlen(str) + 3; \
64 Xalloca(__tmp, len, return IMAP_ERROR); \
65 g_snprintf(__tmp, len, "\"%s\"", str); \
68 Xstrdup_a(out, str, return IMAP_ERROR); \
72 struct _IMAPFolderItem
80 static GList *session_list = NULL;
82 static gint imap_cmd_count = 0;
84 static void imap_folder_init (Folder *folder,
88 static FolderItem *imap_folder_item_new (Folder *folder);
89 static void imap_folder_item_destroy (Folder *folder,
92 static IMAPSession *imap_session_get (Folder *folder);
94 static gint imap_scan_tree_recursive (IMAPSession *session,
96 static GSList *imap_parse_list (Folder *folder,
98 const gchar *real_path,
101 static void imap_create_missing_folders (Folder *folder);
102 static FolderItem *imap_create_special_folder
104 SpecialFolderItemType stype,
107 static gint imap_do_copy (Folder *folder,
110 gboolean remove_source);
112 static gint imap_do_copy_msgs_with_dest (Folder *folder,
115 gboolean remove_source);
118 static GSList *imap_get_uncached_messages (IMAPSession *session,
122 static GSList *imap_delete_cached_messages (GSList *mlist,
126 static void imap_delete_all_cached_messages (FolderItem *item);
129 static SockInfo *imap_open (const gchar *server,
133 static SockInfo *imap_open (const gchar *server,
138 static SockInfo *imap_open_tunnel(const gchar *server,
139 const gchar *tunnelcmd,
142 static SockInfo *imap_open_tunnel(const gchar *server,
143 const gchar *tunnelcmd);
147 static SockInfo *imap_init_sock(SockInfo *sock, SSLType ssl_type);
149 static SockInfo *imap_init_sock(SockInfo *sock);
152 static gint imap_set_message_flags (IMAPSession *session,
157 static gint imap_select (IMAPSession *session,
163 guint32 *uid_validity);
164 static gint imap_get_uid (IMAPSession *session,
167 static gint imap_status (IMAPSession *session,
173 guint32 *uid_validity,
176 static void imap_parse_namespace (IMAPSession *session,
178 static void imap_get_namespace_by_list (IMAPSession *session,
180 static IMAPNameSpace *imap_find_namespace (IMAPFolder *folder,
182 static gchar imap_get_path_separator (IMAPFolder *folder,
184 static gchar *imap_get_real_path (IMAPFolder *folder,
187 static gchar *imap_parse_atom (SockInfo *sock,
192 static MsgFlags imap_parse_flags (const gchar *flag_str);
193 static MsgInfo *imap_parse_envelope (SockInfo *sock,
196 static gint imap_greeting (SockInfo *sock,
197 gboolean *is_preauth);
198 static void imap_get_capability (Session *session);
199 static gboolean imap_has_capability (IMAPSession *session,
202 /* low-level IMAP4rev1 commands */
203 static gint imap_cmd_login (SockInfo *sock,
206 static gint imap_cmd_logout (SockInfo *sock);
207 static gint imap_cmd_noop (SockInfo *sock);
208 static gint imap_cmd_starttls (SockInfo *sock);
209 static gint imap_cmd_namespace (SockInfo *sock,
211 static gint imap_cmd_list (SockInfo *sock,
213 const gchar *mailbox,
215 static gint imap_cmd_do_select (SockInfo *sock,
221 guint32 *uid_validity);
222 static gint imap_cmd_select (SockInfo *sock,
227 guint32 *uid_validity);
228 static gint imap_cmd_examine (SockInfo *sock,
233 guint32 *uid_validity);
234 static gint imap_cmd_create (SockInfo *sock,
235 const gchar *folder);
236 static gint imap_cmd_rename (SockInfo *sock,
237 const gchar *oldfolder,
238 const gchar *newfolder);
239 static gint imap_cmd_delete (SockInfo *sock,
240 const gchar *folder);
241 static gint imap_cmd_envelope (SockInfo *sock,
245 static gint imap_cmd_search (SockInfo *sock,
248 static gint imap_cmd_fetch (SockInfo *sock,
250 const gchar *filename);
251 static gint imap_cmd_append (SockInfo *sock,
252 const gchar *destfolder,
254 static gint imap_cmd_copy (IMAPSession *session,
256 const gchar *destfolder,
258 static gint imap_cmd_store (SockInfo *sock,
262 static gint imap_cmd_expunge (SockInfo *sock);
264 static gint imap_cmd_ok (SockInfo *sock,
266 static void imap_cmd_gen_send (SockInfo *sock,
267 const gchar *format, ...);
268 static gint imap_cmd_gen_recv (SockInfo *sock,
272 /* misc utility functions */
273 static gchar *strchr_cpy (const gchar *src,
277 static gchar *get_quoted (const gchar *src,
281 static gchar *search_array_contain_str (GPtrArray *array,
283 static gchar *search_array_str (GPtrArray *array,
285 static void imap_path_separator_subst (gchar *str,
288 static gchar *imap_modified_utf7_to_locale (const gchar *mutf7_str);
289 static gchar *imap_locale_to_modified_utf7 (const gchar *from);
291 static gboolean imap_rename_folder_func (GNode *node,
293 gint imap_get_num_list (Folder *folder,
296 MsgInfo *imap_get_msginfo (Folder *folder,
299 gboolean imap_check_msgnum_validity (Folder *folder,
302 Folder *imap_folder_new(const gchar *name, const gchar *path)
306 folder = (Folder *)g_new0(IMAPFolder, 1);
307 imap_folder_init(folder, name, path);
312 void imap_folder_destroy(Folder *folder)
316 dir = folder_get_path(folder);
317 if (is_dir_exist(dir))
318 remove_dir_recursive(dir);
321 folder_remote_folder_destroy(REMOTE_FOLDER(folder));
324 static void imap_folder_init(Folder *folder, const gchar *name,
327 folder->type = F_IMAP;
329 folder_remote_folder_init((Folder *)folder, name, path);
332 folder->get_msg_list = imap_get_msg_list;
334 folder->item_new = imap_folder_item_new;
335 folder->item_destroy = imap_folder_item_destroy;
336 folder->fetch_msg = imap_fetch_msg;
337 folder->add_msg = imap_add_msg;
338 folder->move_msg = imap_move_msg;
340 folder->move_msgs_with_dest = imap_move_msgs_with_dest;
342 folder->copy_msg = imap_copy_msg;
344 folder->copy_msgs_with_dest = imap_copy_msgs_with_dest;
346 folder->remove_msg = imap_remove_msg;
347 folder->remove_msgs = imap_remove_msgs;
348 folder->remove_all_msg = imap_remove_all_msg;
349 folder->is_msg_changed = imap_is_msg_changed;
351 folder->scan = imap_scan_folder;
353 folder->scan_tree = imap_scan_tree;
354 folder->create_tree = imap_create_tree;
355 folder->create_folder = imap_create_folder;
356 folder->rename_folder = imap_rename_folder;
357 folder->remove_folder = imap_remove_folder;
358 folder->destroy = imap_folder_destroy;
359 folder->check_msgnum_validity = imap_check_msgnum_validity;
361 folder->get_num_list = imap_get_num_list;
362 folder->get_msginfo = imap_get_msginfo;
365 static FolderItem *imap_folder_item_new(Folder *folder)
367 IMAPFolderItem *item;
369 item = g_new0(IMAPFolderItem, 1);
371 item->uid_list = NULL;
373 return (FolderItem *)item;
376 static void imap_folder_item_destroy(Folder *folder, FolderItem *_item)
378 IMAPFolderItem *item = (IMAPFolderItem *)_item;
380 g_return_if_fail(item != NULL);
381 g_slist_free(item->uid_list);
386 static gboolean imap_reset_uid_lists_func(GNode *node, gpointer data)
388 IMAPFolderItem *item = (IMAPFolderItem *)node->data;
391 g_slist_free(item->uid_list);
392 item->uid_list = NULL;
397 static void imap_reset_uid_lists(Folder *folder)
399 if(folder->node == NULL)
402 /* Destroy all uid lists and rest last uid */
403 g_node_traverse(folder->node, G_IN_ORDER, G_TRAVERSE_ALL, -1, imap_reset_uid_lists_func, NULL);
406 static IMAPSession *imap_session_get(Folder *folder)
408 RemoteFolder *rfolder = REMOTE_FOLDER(folder);
409 Session *session = NULL;
412 g_return_val_if_fail(folder != NULL, NULL);
413 g_return_val_if_fail(folder->type == F_IMAP, NULL);
414 g_return_val_if_fail(folder->account != NULL, NULL);
417 port = folder->account->set_imapport ? folder->account->imapport
418 : folder->account->ssl_imap == SSL_TUNNEL
419 ? IMAPS_PORT : IMAP4_PORT;
421 port = folder->account->set_imapport ? folder->account->imapport
425 /* Make sure we have a session */
426 if (rfolder->session != NULL) {
427 session = rfolder->session;
429 imap_reset_uid_lists(folder);
430 session = imap_session_new(folder->account);
436 imap_get_capability(session);
438 /* Make sure session is authenticated */
439 if (!IMAP_SESSION(session)->authenticated)
440 imap_session_authenticate(IMAP_SESSION(session), folder->account);
441 if (!IMAP_SESSION(session)->authenticated) {
442 session_destroy(session);
443 rfolder->session = NULL;
447 /* Make sure we have parsed the IMAP namespace */
448 imap_parse_namespace(IMAP_SESSION(session),
449 IMAP_FOLDER(folder));
451 /* I think the point of this code is to avoid sending a
452 * keepalive if we've used the session recently and therefore
453 * think it's still alive. Unfortunately, most of the code
454 * does not yet check for errors on the socket, and so if the
455 * connection drops we don't notice until the timeout expires.
456 * A better solution than sending a NOOP every time would be
457 * for every command to be prepared to retry until it is
458 * successfully sent. -- mbp */
459 if (time(NULL) - session->last_access_time > SESSION_TIMEOUT) {
460 /* verify that the session is still alive */
461 if (imap_cmd_noop(session->sock) != IMAP_SUCCESS) {
462 /* Check if this is the first try to establish a
463 connection, if yes we don't try to reconnect */
464 if (rfolder->session == NULL) {
465 log_warning(_("Connecting %s:%d failed"),
466 folder->account->recv_server, port);
467 session_destroy(session);
470 log_warning(_("IMAP4 connection to %s:%d has been"
471 " disconnected. Reconnecting...\n"),
472 folder->account->recv_server, port);
473 session_destroy(session);
474 /* Clear folders session to make imap_session_get create
475 a new session, because of rfolder->session == NULL
476 it will not try to reconnect again and so avoid an
478 rfolder->session = NULL;
479 session = SESSION(imap_session_get(folder));
484 rfolder->session = session;
486 session->last_access_time = time(NULL);
488 return IMAP_SESSION(session);
491 Session *imap_session_new(const PrefsAccount *account)
493 IMAPSession *session;
499 /* FIXME: IMAP over SSL only... */
502 port = account->set_imapport ? account->imapport
503 : account->ssl_imap ? IMAPS_PORT : IMAP4_PORT;
504 ssl_type = account->ssl_imap ? TRUE : FALSE;
506 port = account->set_imapport ? account->imapport
510 if (account->set_tunnelcmd) {
511 log_message(_("creating tunneled IMAP4 connection\n"));
513 if ((imap_sock = imap_open_tunnel(account->recv_server,
517 if ((imap_sock = imap_open_tunnel(account->recv_server,
518 account->tunnelcmd)) == NULL)
522 g_return_val_if_fail(account->recv_server != NULL, NULL);
524 log_message(_("creating IMAP4 connection to %s:%d ...\n"),
525 account->recv_server, port);
528 if ((imap_sock = imap_open(account->recv_server, port,
531 if ((imap_sock = imap_open(account->recv_server, port)) == NULL)
536 /* Only need to log in if the connection was not PREAUTH */
537 if (imap_greeting(imap_sock, &is_preauth) != IMAP_SUCCESS) {
538 sock_close(imap_sock);
541 log_message("IMAP connection is %s-authenticated\n",
542 (is_preauth) ? "pre" : "un");
544 session = g_new(IMAPSession, 1);
545 SESSION(session)->type = SESSION_IMAP;
546 SESSION(session)->server = g_strdup(account->recv_server);
547 SESSION(session)->sock = imap_sock;
548 SESSION(session)->connected = TRUE;
549 SESSION(session)->phase = SESSION_READY;
550 SESSION(session)->last_access_time = time(NULL);
551 SESSION(session)->data = NULL;
553 SESSION(session)->destroy = imap_session_destroy;
555 session->capability = NULL;
557 session->mbox = NULL;
558 session->authenticated = is_preauth;
560 session_list = g_list_append(session_list, session);
562 return SESSION(session);
565 void imap_session_authenticate(IMAPSession *session, const PrefsAccount *account)
569 g_return_if_fail(account->userid != NULL);
571 pass = account->passwd;
574 tmp_pass = input_dialog_query_password(account->recv_server, account->userid);
577 Xstrdup_a(pass, tmp_pass, {g_free(tmp_pass); return;});
581 if (imap_cmd_login(SESSION(session)->sock, account->userid, pass) != IMAP_SUCCESS) {
582 imap_cmd_logout(SESSION(session)->sock);
586 session->authenticated = TRUE;
589 void imap_session_destroy(Session *session)
591 sock_close(session->sock);
592 session->sock = NULL;
594 g_free(IMAP_SESSION(session)->mbox);
596 g_strfreev(IMAP_SESSION(session)->capability);
598 session_list = g_list_remove(session_list, session);
601 void imap_session_destroy_all(void)
603 while (session_list != NULL) {
604 IMAPSession *session = (IMAPSession *)session_list->data;
606 imap_cmd_logout(SESSION(session)->sock);
607 session_destroy(SESSION(session));
611 #define THROW goto catch
613 GSList *imap_get_msg_list(Folder *folder, FolderItem *item, gboolean use_cache)
615 GSList *mlist = NULL;
616 IMAPSession *session;
617 gint ok, exists = 0, recent = 0, unseen = 0;
618 guint32 uid_validity = 0;
619 guint32 first_uid = 0, last_uid = 0, begin;
621 g_return_val_if_fail(folder != NULL, NULL);
622 g_return_val_if_fail(item != NULL, NULL);
623 g_return_val_if_fail(folder->type == F_IMAP, NULL);
624 g_return_val_if_fail(folder->account != NULL, NULL);
626 session = imap_session_get(folder);
629 mlist = procmsg_read_cache(item, FALSE);
630 item->last_num = procmsg_get_last_num_in_msg_list(mlist);
631 procmsg_set_flags(mlist, item);
635 ok = imap_select(session, IMAP_FOLDER(folder), item->path,
636 &exists, &recent, &unseen, &uid_validity);
637 if (ok != IMAP_SUCCESS) THROW;
639 ok = imap_get_uid(session, 1, &first_uid);
640 if (ok != IMAP_SUCCESS) THROW;
642 ok = imap_get_uid(session, exists, &last_uid);
643 if (ok != IMAP_SUCCESS) THROW;
645 last_uid = first_uid;
647 imap_delete_all_cached_messages(item);
654 mlist = procmsg_read_cache(item, FALSE);
655 procmsg_set_flags(mlist, item);
656 cache_last = procmsg_get_last_num_in_msg_list(mlist);
658 /* calculating the range of envelope to get */
659 if (item->mtime != uid_validity) {
660 /* mailbox is changed (get all) */
662 } else if (last_uid < cache_last) {
663 /* mailbox is changed (get all) */
665 } else if (last_uid == cache_last) {
666 /* mailbox unchanged (get none)*/
669 begin = cache_last + 1;
672 item->mtime = uid_validity;
674 if (first_uid > 0 && last_uid > 0) {
675 mlist = imap_delete_cached_messages(mlist, item,
677 mlist = imap_delete_cached_messages(mlist, item,
682 mlist = imap_delete_cached_messages(mlist, item,
685 imap_delete_all_cached_messages(item);
689 if (begin > 0 && begin <= last_uid) {
691 newlist = imap_get_uncached_messages(session, item,
693 mlist = g_slist_concat(mlist, newlist);
696 item->last_num = last_uid;
704 gchar *imap_fetch_msg(Folder *folder, FolderItem *item, gint uid)
706 gchar *path, *filename;
707 IMAPSession *session;
710 g_return_val_if_fail(folder != NULL, NULL);
711 g_return_val_if_fail(item != NULL, NULL);
713 path = folder_item_get_path(item);
714 if (!is_dir_exist(path))
716 filename = g_strconcat(path, G_DIR_SEPARATOR_S, itos(uid), NULL);
719 if (is_file_exist(filename)) {
720 debug_print("message %d has been already cached.\n", uid);
724 session = imap_session_get(folder);
730 ok = imap_select(session, IMAP_FOLDER(folder), item->path,
731 NULL, NULL, NULL, NULL);
732 if (ok != IMAP_SUCCESS) {
733 g_warning("can't select mailbox %s\n", item->path);
738 debug_print("getting message %d...\n", uid);
739 ok = imap_cmd_fetch(SESSION(session)->sock, (guint32)uid, filename);
741 if (ok != IMAP_SUCCESS) {
742 g_warning("can't fetch message %d\n", uid);
750 gint imap_add_msg(Folder *folder, FolderItem *dest, const gchar *file,
751 gboolean remove_source)
754 IMAPSession *session;
757 g_return_val_if_fail(folder != NULL, -1);
758 g_return_val_if_fail(dest != NULL, -1);
759 g_return_val_if_fail(file != NULL, -1);
761 session = imap_session_get(folder);
762 if (!session) return -1;
764 destdir = imap_get_real_path(IMAP_FOLDER(folder), dest->path);
765 ok = imap_cmd_append(SESSION(session)->sock, destdir, file);
768 if (ok != IMAP_SUCCESS) {
769 g_warning("can't append message %s\n", file);
774 if (unlink(file) < 0)
775 FILE_OP_ERROR(file, "unlink");
781 static gint imap_do_copy(Folder *folder, FolderItem *dest, MsgInfo *msginfo,
782 gboolean remove_source)
785 IMAPSession *session;
786 IMAPFlags iflags = 0;
787 gint messages, recent, unseen;
788 guint32 newuid = 0, uid_validity;
791 g_return_val_if_fail(folder != NULL, -1);
792 g_return_val_if_fail(folder->type == F_IMAP, -1);
793 g_return_val_if_fail(dest != NULL, -1);
794 g_return_val_if_fail(msginfo != NULL, -1);
796 session = imap_session_get(folder);
797 if (!session) return -1;
799 if (msginfo->folder == dest) {
800 g_warning("the src folder is identical to the dest.\n");
804 /* if we don't have UIDPLUS we get UID-NEXT and hope that the
805 message really gets this uid */
806 if (!imap_has_capability(session, "UIDPLUS")) {
807 ok = imap_status(session, IMAP_FOLDER(folder), dest->path,
808 &messages, &recent, &newuid, &uid_validity, &unseen);
809 if (ok != IMAP_SUCCESS) {
810 g_warning("can't copy message\n");
815 destdir = imap_get_real_path(IMAP_FOLDER(folder), dest->path);
817 /* ensure source folder selected */
818 ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder->path,
819 NULL, NULL, NULL, NULL);
820 if (ok != IMAP_SUCCESS)
824 debug_print("Moving message %s%c%d to %s ...\n",
825 msginfo->folder->path, G_DIR_SEPARATOR,
826 msginfo->msgnum, destdir);
828 debug_print("Copying message %s%c%d to %s ...\n",
829 msginfo->folder->path, G_DIR_SEPARATOR,
830 msginfo->msgnum, destdir);
832 ok = imap_cmd_copy(session, msginfo->msgnum, destdir, &newuid);
834 if (ok == IMAP_SUCCESS && remove_source) {
835 imap_set_message_flags(session, msginfo->msgnum, msginfo->msgnum,
836 IMAP_FLAG_DELETED, TRUE);
837 ok = imap_cmd_expunge(SESSION(session)->sock);
840 /* get the dest folder to set the flags */
842 ok = imap_select(session, IMAP_FOLDER(folder), dest->path,
843 NULL, NULL, NULL, NULL);
844 if (ok != IMAP_SUCCESS) /* the folder disappeared? */
847 if (msginfo->flags.perm_flags & MSG_MARKED) iflags |= IMAP_FLAG_FLAGGED;
848 if (msginfo->flags.perm_flags & MSG_REPLIED) iflags |= IMAP_FLAG_ANSWERED;
850 if (imap_set_message_flags(session, newuid, newuid, iflags, TRUE)
857 if (ok == IMAP_SUCCESS)
864 static gint imap_do_copy_msgs_with_dest(Folder *folder, FolderItem *dest,
866 gboolean remove_source)
871 IMAPSession *session;
872 gint ok = IMAP_SUCCESS;
874 g_return_val_if_fail(folder != NULL, -1);
875 g_return_val_if_fail(dest != NULL, -1);
876 g_return_val_if_fail(msglist != NULL, -1);
878 session = imap_session_get(folder);
879 if (!session) return -1;
881 destdir = imap_get_real_path(IMAP_FOLDER(folder), dest->path);
883 for (cur = msglist; cur != NULL; cur = cur->next) {
884 msginfo = (MsgInfo *)cur->data;
886 if (msginfo->folder == dest) {
887 g_warning("the src folder is identical to the dest.\n");
891 /* ensure source folder selected */
892 ok = imap_select(session, IMAP_FOLDER(folder),
893 msginfo->folder->path, NULL, NULL, NULL, NULL);
896 debug_print("Moving message %s%c%d to %s ...\n",
897 msginfo->folder->path, G_DIR_SEPARATOR,
898 msginfo->msgnum, destdir);
900 debug_print("Copying message %s%c%d to %s ...\n",
901 msginfo->folder->path, G_DIR_SEPARATOR,
902 msginfo->msgnum, destdir);
904 ok = imap_cmd_copy(session, msginfo, destdir);
906 if (ok == IMAP_SUCCESS && remove_source) {
907 imap_set_message_flags
908 (session, msginfo->msgnum, msginfo->msgnum,
909 IMAP_FLAG_DELETED, TRUE);
914 ok = imap_cmd_expunge(SESSION(session)->sock);
918 if (ok == IMAP_SUCCESS)
925 gint imap_move_msg(Folder *folder, FolderItem *dest, MsgInfo *msginfo)
930 g_return_val_if_fail(folder != NULL, -1);
931 g_return_val_if_fail(dest != NULL, -1);
932 g_return_val_if_fail(msginfo != NULL, -1);
933 g_return_val_if_fail(msginfo->folder != NULL, -1);
935 if (folder == msginfo->folder->folder)
936 return imap_do_copy(folder, dest, msginfo, TRUE);
938 srcfile = procmsg_get_message_file(msginfo);
939 if (!srcfile) return -1;
941 ret = imap_add_msg(folder, dest, srcfile, FALSE);
945 if(folder_item_remove_msg(msginfo->folder, msginfo->msgnum)) {
954 gint imap_move_msgs_with_dest(Folder *folder, FolderItem *dest,
961 g_return_val_if_fail(folder != NULL, -1);
962 g_return_val_if_fail(dest != NULL, -1);
963 g_return_val_if_fail(msglist != NULL, -1);
965 msginfo = (MsgInfo *)msglist->data;
966 if (folder == msginfo->folder->folder)
967 return imap_do_copy_msgs_with_dest(folder, dest, msglist, TRUE);
969 for (cur = msglist; cur != NULL; cur = cur->next) {
970 msginfo = (MsgInfo *)cur->data;
971 ret = imap_move_msg(folder, dest, msginfo);
972 if (ret == -1) break;
979 gint imap_copy_msg(Folder *folder, FolderItem *dest, MsgInfo *msginfo)
984 g_return_val_if_fail(folder != NULL, -1);
985 g_return_val_if_fail(dest != NULL, -1);
986 g_return_val_if_fail(msginfo != NULL, -1);
987 g_return_val_if_fail(msginfo->folder != NULL, -1);
989 if (folder == msginfo->folder->folder)
990 return imap_do_copy(folder, dest, msginfo, FALSE);
992 srcfile = procmsg_get_message_file(msginfo);
993 if (!srcfile) return -1;
995 ret = imap_add_msg(folder, dest, srcfile, FALSE);
1003 gint imap_copy_msgs_with_dest(Folder *folder, FolderItem *dest,
1010 g_return_val_if_fail(folder != NULL, -1);
1011 g_return_val_if_fail(dest != NULL, -1);
1012 g_return_val_if_fail(msglist != NULL, -1);
1014 msginfo = (MsgInfo *)msglist->data;
1015 if (folder == msginfo->folder->folder)
1016 return imap_do_copy_msgs_with_dest
1017 (folder, dest, msglist, FALSE);
1019 for (cur = msglist; cur != NULL; cur = cur->next) {
1020 msginfo = (MsgInfo *)cur->data;
1021 ret = imap_copy_msg(folder, dest, msginfo);
1022 if (ret == -1) break;
1029 gint imap_remove_msg(Folder *folder, FolderItem *item, gint uid)
1032 IMAPSession *session;
1035 g_return_val_if_fail(folder != NULL, -1);
1036 g_return_val_if_fail(folder->type == F_IMAP, -1);
1037 g_return_val_if_fail(item != NULL, -1);
1039 session = imap_session_get(folder);
1040 if (!session) return -1;
1042 ok = imap_select(session, IMAP_FOLDER(folder), item->path,
1043 NULL, NULL, NULL, NULL);
1044 if (ok != IMAP_SUCCESS)
1047 ok = imap_set_message_flags
1048 (IMAP_SESSION(REMOTE_FOLDER(folder)->session),
1049 (guint32)uid, (guint32)uid, IMAP_FLAG_DELETED, TRUE);
1050 if (ok != IMAP_SUCCESS) {
1051 log_warning(_("can't set deleted flags: %d\n"), uid);
1055 ok = imap_cmd_expunge(SESSION(session)->sock);
1056 if (ok != IMAP_SUCCESS) {
1057 log_warning(_("can't expunge\n"));
1061 dir = folder_item_get_path(item);
1062 if (is_dir_exist(dir))
1063 remove_numbered_files(dir, uid, uid);
1066 return IMAP_SUCCESS;
1069 gint imap_remove_msgs(Folder *folder, FolderItem *item, GSList *msglist)
1072 IMAPSession *session;
1078 g_return_val_if_fail(folder != NULL, -1);
1079 g_return_val_if_fail(folder->type == F_IMAP, -1);
1080 g_return_val_if_fail(item != NULL, -1);
1081 g_return_val_if_fail(msglist != NULL, -1);
1083 session = imap_session_get(folder);
1084 if (!session) return -1;
1086 ok = imap_select(session, IMAP_FOLDER(folder), item->path,
1087 NULL, NULL, NULL, NULL);
1088 if (ok != IMAP_SUCCESS)
1091 for (cur = msglist; cur != NULL; cur = cur->next) {
1092 msginfo = (MsgInfo *)cur->data;
1093 uid = msginfo->msgnum;
1094 ok = imap_set_message_flags
1095 (IMAP_SESSION(REMOTE_FOLDER(folder)->session),
1096 uid, uid, IMAP_FLAG_DELETED, TRUE);
1097 if (ok != IMAP_SUCCESS) {
1098 log_warning(_("can't set deleted flags: %d\n"), uid);
1103 ok = imap_cmd_expunge(SESSION(session)->sock);
1104 if (ok != IMAP_SUCCESS) {
1105 log_warning(_("can't expunge\n"));
1109 dir = folder_item_get_path(item);
1110 if (is_dir_exist(dir)) {
1111 for (cur = msglist; cur != NULL; cur = cur->next) {
1112 msginfo = (MsgInfo *)cur->data;
1113 uid = msginfo->msgnum;
1114 remove_numbered_files(dir, uid, uid);
1119 return IMAP_SUCCESS;
1122 gint imap_remove_all_msg(Folder *folder, FolderItem *item)
1124 gint exists, recent, unseen;
1125 guint32 uid_validity;
1127 IMAPSession *session;
1130 g_return_val_if_fail(folder != NULL, -1);
1131 g_return_val_if_fail(item != NULL, -1);
1133 session = imap_session_get(folder);
1134 if (!session) return -1;
1136 ok = imap_select(session, IMAP_FOLDER(folder), item->path,
1137 &exists, &recent, &unseen, &uid_validity);
1138 if (ok != IMAP_SUCCESS)
1141 return IMAP_SUCCESS;
1143 imap_cmd_gen_send(SESSION(session)->sock,
1144 "STORE 1:%d +FLAGS (\\Deleted)", exists);
1145 ok = imap_cmd_ok(SESSION(session)->sock, NULL);
1146 if (ok != IMAP_SUCCESS) {
1147 log_warning(_("can't set deleted flags: 1:%d\n"), exists);
1151 ok = imap_cmd_expunge(SESSION(session)->sock);
1152 if (ok != IMAP_SUCCESS) {
1153 log_warning(_("can't expunge\n"));
1157 dir = folder_item_get_path(item);
1158 if (is_dir_exist(dir))
1159 remove_all_numbered_files(dir);
1162 return IMAP_SUCCESS;
1165 gboolean imap_is_msg_changed(Folder *folder, FolderItem *item, MsgInfo *msginfo)
1167 /* TODO: properly implement this method */
1171 gint imap_scan_folder(Folder *folder, FolderItem *item)
1173 IMAPSession *session;
1174 gint messages, recent, unseen;
1175 guint32 uid_next, uid_validity;
1178 g_return_val_if_fail(folder != NULL, -1);
1179 g_return_val_if_fail(item != NULL, -1);
1181 session = imap_session_get(folder);
1182 if (!session) return -1;
1184 ok = imap_status(session, IMAP_FOLDER(folder), item->path,
1185 &messages, &recent, &uid_next, &uid_validity, &unseen);
1186 if (ok != IMAP_SUCCESS) return -1;
1188 item->new = unseen > 0 ? recent : 0;
1189 item->unread = unseen;
1190 item->total = messages;
1191 item->last_num = (messages > 0 && uid_next > 0) ? uid_next - 1 : 0;
1192 /* item->mtime = uid_validity; */
1197 void imap_scan_tree(Folder *folder)
1200 IMAPSession *session;
1201 gchar *root_folder = NULL;
1203 g_return_if_fail(folder != NULL);
1204 g_return_if_fail(folder->account != NULL);
1206 session = imap_session_get(folder);
1208 if (!folder->node) {
1209 folder_tree_destroy(folder);
1210 item = folder_item_new(folder, folder->name, NULL);
1211 item->folder = folder;
1212 folder->node = g_node_new(item);
1217 if (folder->account->imap_dir && *folder->account->imap_dir) {
1218 Xstrdup_a(root_folder, folder->account->imap_dir, return);
1219 strtailchomp(root_folder, '/');
1220 debug_print("IMAP root directory: %s\n", root_folder);
1223 item = folder_item_new(folder, folder->name, root_folder);
1224 item->folder = folder;
1225 item->no_select = TRUE;
1226 folder->node = g_node_new(item);
1228 imap_scan_tree_recursive(session, item);
1230 imap_create_missing_folders(folder);
1233 static gint imap_scan_tree_recursive(IMAPSession *session, FolderItem *item)
1236 IMAPFolder *imapfolder;
1237 FolderItem *new_item;
1238 GSList *item_list, *cur;
1240 gchar *wildcard_path;
1244 g_return_val_if_fail(item != NULL, -1);
1245 g_return_val_if_fail(item->folder != NULL, -1);
1246 g_return_val_if_fail(item->no_sub == FALSE, -1);
1248 folder = FOLDER(item->folder);
1249 imapfolder = IMAP_FOLDER(folder);
1251 separator = imap_get_path_separator(imapfolder, item->path);
1253 if (item->folder->ui_func)
1254 item->folder->ui_func(folder, item, folder->ui_func_data);
1257 wildcard[0] = separator;
1260 real_path = imap_get_real_path(imapfolder, item->path);
1264 real_path = g_strdup("");
1267 Xstrcat_a(wildcard_path, real_path, wildcard,
1268 {g_free(real_path); return IMAP_ERROR;});
1269 QUOTE_IF_REQUIRED(wildcard_path, wildcard_path);
1271 imap_cmd_gen_send(SESSION(session)->sock, "LIST \"\" %s",
1274 strtailchomp(real_path, separator);
1275 item_list = imap_parse_list(folder, session, real_path, NULL);
1278 for (cur = item_list; cur != NULL; cur = cur->next) {
1279 new_item = cur->data;
1280 if (!strcmp(new_item->path, "INBOX")) {
1281 if (!folder->inbox) {
1282 new_item->stype = F_INBOX;
1283 item->folder->inbox = new_item;
1285 folder_item_destroy(new_item);
1288 } else if (!item->parent || item->stype == F_INBOX) {
1291 base = g_basename(new_item->path);
1293 if (!folder->outbox && !strcasecmp(base, "Sent")) {
1294 new_item->stype = F_OUTBOX;
1295 folder->outbox = new_item;
1296 } else if (!folder->draft && !strcasecmp(base, "Drafts")) {
1297 new_item->stype = F_DRAFT;
1298 folder->draft = new_item;
1299 } else if (!folder->queue && !strcasecmp(base, "Queue")) {
1300 new_item->stype = F_QUEUE;
1301 folder->queue = new_item;
1302 } else if (!folder->trash && !strcasecmp(base, "Trash")) {
1303 new_item->stype = F_TRASH;
1304 folder->trash = new_item;
1307 folder_item_append(item, new_item);
1308 if (new_item->no_select == FALSE)
1309 imap_scan_folder(folder, new_item);
1310 if (new_item->no_sub == FALSE)
1311 imap_scan_tree_recursive(session, new_item);
1314 return IMAP_SUCCESS;
1317 static GSList *imap_parse_list(Folder *folder, IMAPSession *session,
1318 const gchar *real_path, gchar *separator)
1320 gchar buf[IMAPBUFSIZE];
1322 gchar separator_str[16];
1325 gchar *loc_name, *loc_path;
1326 GSList *item_list = NULL;
1328 FolderItem *new_item;
1330 debug_print("getting list of %s ...\n",
1331 *real_path ? real_path : "\"\"");
1333 str = g_string_new(NULL);
1336 if (sock_gets(SESSION(session)->sock, buf, sizeof(buf)) <= 0) {
1337 log_warning(_("error occured while getting LIST.\n"));
1341 if (buf[0] != '*' || buf[1] != ' ') {
1342 log_print("IMAP4< %s\n", buf);
1345 debug_print("IMAP4< %s\n", buf);
1347 g_string_assign(str, buf);
1349 if (strncmp(p, "LIST ", 5) != 0) continue;
1352 if (*p != '(') continue;
1354 p = strchr_cpy(p, ')', flags, sizeof(flags));
1356 while (*p == ' ') p++;
1358 p = strchr_cpy(p, ' ', separator_str, sizeof(separator_str));
1360 extract_quote(separator_str, '"');
1361 if (!strcmp(separator_str, "NIL"))
1362 separator_str[0] = '\0';
1364 *separator = separator_str[0];
1367 while (*p == ' ') p++;
1368 if (*p == '{' || *p == '"')
1369 p = imap_parse_atom(SESSION(session)->sock, p,
1370 buf, sizeof(buf), str);
1372 strncpy2(buf, p, sizeof(buf));
1373 strtailchomp(buf, separator_str[0]);
1374 if (buf[0] == '\0') continue;
1375 if (!strcmp(buf, real_path)) continue;
1377 if (separator_str[0] != '\0')
1378 subst_char(buf, separator_str[0], '/');
1379 name = g_basename(buf);
1380 if (name[0] == '.') continue;
1382 loc_name = imap_modified_utf7_to_locale(name);
1383 loc_path = imap_modified_utf7_to_locale(buf);
1384 new_item = folder_item_new(folder, loc_name, loc_path);
1385 if (strcasestr(flags, "\\Noinferiors") != NULL)
1386 new_item->no_sub = TRUE;
1387 if (strcmp(buf, "INBOX") != 0 &&
1388 strcasestr(flags, "\\Noselect") != NULL)
1389 new_item->no_select = TRUE;
1391 item_list = g_slist_append(item_list, new_item);
1393 debug_print("folder %s has been added.\n", loc_path);
1398 g_string_free(str, TRUE);
1403 gint imap_create_tree(Folder *folder)
1405 g_return_val_if_fail(folder != NULL, -1);
1406 g_return_val_if_fail(folder->node != NULL, -1);
1407 g_return_val_if_fail(folder->node->data != NULL, -1);
1408 g_return_val_if_fail(folder->account != NULL, -1);
1410 imap_scan_tree(folder);
1411 imap_create_missing_folders(folder);
1416 static void imap_create_missing_folders(Folder *folder)
1418 g_return_if_fail(folder != NULL);
1421 folder->inbox = imap_create_special_folder
1422 (folder, F_INBOX, "INBOX");
1424 if (!folder->outbox)
1425 folder->outbox = imap_create_special_folder
1426 (folder, F_OUTBOX, "Sent");
1428 folder->draft = imap_create_special_folder
1429 (folder, F_DRAFT, "Drafts");
1431 folder->queue = imap_create_special_folder
1432 (folder, F_QUEUE, "Queue");
1435 folder->trash = imap_create_special_folder
1436 (folder, F_TRASH, "Trash");
1439 static FolderItem *imap_create_special_folder(Folder *folder,
1440 SpecialFolderItemType stype,
1444 FolderItem *new_item;
1446 g_return_val_if_fail(folder != NULL, NULL);
1447 g_return_val_if_fail(folder->node != NULL, NULL);
1448 g_return_val_if_fail(folder->node->data != NULL, NULL);
1449 g_return_val_if_fail(folder->account != NULL, NULL);
1450 g_return_val_if_fail(name != NULL, NULL);
1452 item = FOLDER_ITEM(folder->node->data);
1453 new_item = imap_create_folder(folder, item, name);
1456 g_warning("Can't create '%s'\n", name);
1457 if (!folder->inbox) return NULL;
1459 new_item = imap_create_folder(folder, folder->inbox, name);
1461 g_warning("Can't create '%s' under INBOX\n", name);
1463 new_item->stype = stype;
1465 new_item->stype = stype;
1470 FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
1473 gchar *dirpath, *imap_path;
1474 IMAPSession *session;
1475 FolderItem *new_item;
1481 g_return_val_if_fail(folder != NULL, NULL);
1482 g_return_val_if_fail(folder->account != NULL, NULL);
1483 g_return_val_if_fail(parent != NULL, NULL);
1484 g_return_val_if_fail(name != NULL, NULL);
1486 session = imap_session_get(folder);
1487 if (!session) return NULL;
1489 if (!parent->parent && strcmp(name, "INBOX") == 0)
1490 dirpath = g_strdup(name);
1491 else if (parent->path)
1492 dirpath = g_strconcat(parent->path, "/", name, NULL);
1493 else if ((p = strchr(name, '/')) != NULL && *(p + 1) != '\0')
1494 dirpath = g_strdup(name);
1495 else if (folder->account->imap_dir && *folder->account->imap_dir) {
1498 Xstrdup_a(imap_dir, folder->account->imap_dir, return NULL);
1499 strtailchomp(imap_dir, '/');
1500 dirpath = g_strconcat(imap_dir, "/", name, NULL);
1502 dirpath = g_strdup(name);
1504 /* keep trailing directory separator to create a folder that contains
1506 imap_path = imap_locale_to_modified_utf7(dirpath);
1507 strtailchomp(dirpath, '/');
1508 Xstrdup_a(new_name, name, {g_free(dirpath); return NULL;});
1509 strtailchomp(new_name, '/');
1510 separator = imap_get_path_separator(IMAP_FOLDER(folder), imap_path);
1511 imap_path_separator_subst(imap_path, separator);
1512 subst_char(new_name, '/', separator);
1514 if (strcmp(name, "INBOX") != 0) {
1517 gboolean exist = FALSE;
1519 argbuf = g_ptr_array_new();
1520 ok = imap_cmd_list(SESSION(session)->sock, NULL, imap_path,
1522 if (ok != IMAP_SUCCESS) {
1523 log_warning(_("can't create mailbox: LIST failed\n"));
1526 ptr_array_free_strings(argbuf);
1527 g_ptr_array_free(argbuf, TRUE);
1531 for (i = 0; i < argbuf->len; i++) {
1533 str = g_ptr_array_index(argbuf, i);
1534 if (!strncmp(str, "LIST ", 5)) {
1539 ptr_array_free_strings(argbuf);
1540 g_ptr_array_free(argbuf, TRUE);
1543 ok = imap_cmd_create(SESSION(session)->sock, imap_path);
1544 if (ok != IMAP_SUCCESS) {
1545 log_warning(_("can't create mailbox\n"));
1553 new_item = folder_item_new(folder, new_name, dirpath);
1554 folder_item_append(parent, new_item);
1558 dirpath = folder_item_get_path(new_item);
1559 if (!is_dir_exist(dirpath))
1560 make_dir_hier(dirpath);
1566 gint imap_rename_folder(Folder *folder, FolderItem *item, const gchar *name)
1570 gchar *real_oldpath;
1571 gchar *real_newpath;
1574 gchar *old_cache_dir;
1575 gchar *new_cache_dir;
1576 IMAPSession *session;
1579 gint exists, recent, unseen;
1580 guint32 uid_validity;
1582 g_return_val_if_fail(folder != NULL, -1);
1583 g_return_val_if_fail(item != NULL, -1);
1584 g_return_val_if_fail(item->path != NULL, -1);
1585 g_return_val_if_fail(name != NULL, -1);
1587 session = imap_session_get(folder);
1588 if (!session) return -1;
1590 real_oldpath = imap_get_real_path(IMAP_FOLDER(folder), item->path);
1592 g_free(session->mbox);
1593 session->mbox = NULL;
1594 ok = imap_cmd_examine(SESSION(session)->sock, "INBOX",
1595 &exists, &recent, &unseen, &uid_validity);
1596 if (ok != IMAP_SUCCESS) {
1597 g_free(real_oldpath);
1601 separator = imap_get_path_separator(IMAP_FOLDER(folder), item->path);
1602 if (strchr(item->path, G_DIR_SEPARATOR)) {
1603 dirpath = g_dirname(item->path);
1604 newpath = g_strconcat(dirpath, G_DIR_SEPARATOR_S, name, NULL);
1607 newpath = g_strdup(name);
1609 real_newpath = imap_locale_to_modified_utf7(newpath);
1610 imap_path_separator_subst(real_newpath, separator);
1612 ok = imap_cmd_rename(SESSION(session)->sock, real_oldpath, real_newpath);
1613 if (ok != IMAP_SUCCESS) {
1614 log_warning(_("can't rename mailbox: %s to %s\n"),
1615 real_oldpath, real_newpath);
1616 g_free(real_oldpath);
1618 g_free(real_newpath);
1623 item->name = g_strdup(name);
1625 old_cache_dir = folder_item_get_path(item);
1627 node = g_node_find(item->folder->node, G_PRE_ORDER, G_TRAVERSE_ALL,
1629 paths[0] = g_strdup(item->path);
1631 g_node_traverse(node, G_PRE_ORDER, G_TRAVERSE_ALL, -1,
1632 imap_rename_folder_func, paths);
1634 if (is_dir_exist(old_cache_dir)) {
1635 new_cache_dir = folder_item_get_path(item);
1636 if (rename(old_cache_dir, new_cache_dir) < 0) {
1637 FILE_OP_ERROR(old_cache_dir, "rename");
1639 g_free(new_cache_dir);
1642 g_free(old_cache_dir);
1645 g_free(real_oldpath);
1646 g_free(real_newpath);
1651 gint imap_remove_folder(Folder *folder, FolderItem *item)
1654 IMAPSession *session;
1657 gint exists, recent, unseen;
1658 guint32 uid_validity;
1660 g_return_val_if_fail(folder != NULL, -1);
1661 g_return_val_if_fail(item != NULL, -1);
1662 g_return_val_if_fail(item->path != NULL, -1);
1664 session = imap_session_get(folder);
1665 if (!session) return -1;
1667 path = imap_get_real_path(IMAP_FOLDER(folder), item->path);
1669 ok = imap_cmd_examine(SESSION(session)->sock, "INBOX",
1670 &exists, &recent, &unseen, &uid_validity);
1671 if (ok != IMAP_SUCCESS) {
1676 ok = imap_cmd_delete(SESSION(session)->sock, path);
1677 if (ok != IMAP_SUCCESS) {
1678 log_warning(_("can't delete mailbox\n"));
1684 cache_dir = folder_item_get_path(item);
1685 if (is_dir_exist(cache_dir) && remove_dir_recursive(cache_dir) < 0)
1686 g_warning("can't remove directory '%s'\n", cache_dir);
1688 folder_item_remove(item);
1693 static GSList *imap_get_uncached_messages(IMAPSession *session,
1695 guint32 first_uid, guint32 last_uid)
1698 GSList *newlist = NULL;
1699 GSList *llast = NULL;
1703 g_return_val_if_fail(session != NULL, NULL);
1704 g_return_val_if_fail(item != NULL, NULL);
1705 g_return_val_if_fail(item->folder != NULL, NULL);
1706 g_return_val_if_fail(item->folder->type == F_IMAP, NULL);
1707 g_return_val_if_fail(first_uid <= last_uid, NULL);
1709 if (imap_cmd_envelope(SESSION(session)->sock, first_uid, last_uid)
1711 log_warning(_("can't get envelope\n"));
1715 str = g_string_new(NULL);
1718 if ((tmp = sock_getline(SESSION(session)->sock)) == NULL) {
1719 log_warning(_("error occurred while getting envelope.\n"));
1720 g_string_free(str, TRUE);
1724 if (tmp[0] != '*' || tmp[1] != ' ') {
1725 log_print("IMAP4< %s\n", tmp);
1729 if (strstr(tmp, "FETCH") == NULL) {
1730 log_print("IMAP4< %s\n", tmp);
1734 log_print("IMAP4< %s\n", tmp);
1735 g_string_assign(str, tmp);
1738 msginfo = imap_parse_envelope
1739 (SESSION(session)->sock, item, str);
1741 log_warning(_("can't parse envelope: %s\n"), str->str);
1744 if (item->stype == F_QUEUE) {
1745 MSG_SET_TMP_FLAGS(msginfo->flags, MSG_QUEUED);
1746 } else if (item->stype == F_DRAFT) {
1747 MSG_SET_TMP_FLAGS(msginfo->flags, MSG_DRAFT);
1750 msginfo->folder = item;
1753 llast = newlist = g_slist_append(newlist, msginfo);
1755 llast = g_slist_append(llast, msginfo);
1756 llast = llast->next;
1760 g_string_free(str, TRUE);
1765 static GSList *imap_delete_cached_messages(GSList *mlist, FolderItem *item,
1766 guint32 first_uid, guint32 last_uid)
1772 g_return_val_if_fail(item != NULL, mlist);
1773 g_return_val_if_fail(item->folder != NULL, mlist);
1774 g_return_val_if_fail(item->folder->type == F_IMAP, mlist);
1776 debug_print("Deleting cached messages %u - %u ... ",
1777 first_uid, last_uid);
1779 dir = folder_item_get_path(item);
1780 if (is_dir_exist(dir))
1781 remove_numbered_files(dir, first_uid, last_uid);
1784 for (cur = mlist; cur != NULL; ) {
1787 msginfo = (MsgInfo *)cur->data;
1788 if (msginfo != NULL && first_uid <= msginfo->msgnum &&
1789 msginfo->msgnum <= last_uid) {
1790 procmsg_msginfo_free(msginfo);
1791 mlist = g_slist_remove(mlist, msginfo);
1797 debug_print("done.\n");
1802 static void imap_delete_all_cached_messages(FolderItem *item)
1806 g_return_if_fail(item != NULL);
1807 g_return_if_fail(item->folder != NULL);
1808 g_return_if_fail(item->folder->type == F_IMAP);
1810 debug_print("Deleting all cached messages...\n");
1812 dir = folder_item_get_path(item);
1813 if (is_dir_exist(dir))
1814 remove_all_numbered_files(dir);
1817 debug_print("done.\n");
1821 static SockInfo *imap_open_tunnel(const gchar *server,
1822 const gchar *tunnelcmd,
1825 static SockInfo *imap_open_tunnel(const gchar *server,
1826 const gchar *tunnelcmd)
1831 if ((sock = sock_connect_cmd(server, tunnelcmd)) == NULL)
1832 log_warning(_("Can't establish IMAP4 session with: %s\n"),
1836 return imap_init_sock(sock, ssl_type);
1838 return imap_init_sock(sock);
1844 static SockInfo *imap_open(const gchar *server, gushort port,
1847 static SockInfo *imap_open(const gchar *server, gushort port)
1852 if ((sock = sock_connect(server, port)) == NULL) {
1853 log_warning(_("Can't connect to IMAP4 server: %s:%d\n"),
1859 if (ssl_type == SSL_TUNNEL && !ssl_init_socket(sock)) {
1860 log_warning(_("Can't establish IMAP4 session with: %s:%d\n"),
1865 return imap_init_sock(sock, ssl_type);
1867 return imap_init_sock(sock);
1872 static SockInfo *imap_init_sock(SockInfo *sock, SSLType ssl_type)
1874 static SockInfo *imap_init_sock(SockInfo *sock)
1879 if (ssl_type == SSL_STARTTLS) {
1882 ok = imap_cmd_starttls(sock);
1883 if (ok != IMAP_SUCCESS) {
1884 log_warning(_("Can't start TLS session.\n"));
1888 if (!ssl_init_socket_with_method(sock, SSL_METHOD_TLSv1)) {
1895 if (imap_cmd_noop(sock) != IMAP_SUCCESS) {
1896 log_warning(_("Can't establish IMAP4 session.\n"));
1904 static GList *imap_parse_namespace_str(gchar *str)
1909 IMAPNameSpace *namespace;
1910 GList *ns_list = NULL;
1912 while (*p != '\0') {
1913 /* parse ("#foo" "/") */
1915 while (*p && *p != '(') p++;
1916 if (*p == '\0') break;
1919 while (*p && *p != '"') p++;
1920 if (*p == '\0') break;
1924 while (*p && *p != '"') p++;
1925 if (*p == '\0') break;
1929 while (*p && isspace(*p)) p++;
1930 if (*p == '\0') break;
1931 if (strncmp(p, "NIL", 3) == 0)
1933 else if (*p == '"') {
1936 while (*p && *p != '"') p++;
1937 if (*p == '\0') break;
1942 while (*p && *p != ')') p++;
1943 if (*p == '\0') break;
1946 namespace = g_new(IMAPNameSpace, 1);
1947 namespace->name = g_strdup(name);
1948 namespace->separator = separator ? separator[0] : '\0';
1949 ns_list = g_list_append(ns_list, namespace);
1955 static void imap_parse_namespace(IMAPSession *session, IMAPFolder *folder)
1960 g_return_if_fail(session != NULL);
1961 g_return_if_fail(folder != NULL);
1963 if (folder->ns_personal != NULL ||
1964 folder->ns_others != NULL ||
1965 folder->ns_shared != NULL)
1968 if (!imap_has_capability(session, "NAMESPACE")) {
1969 imap_get_namespace_by_list(session, folder);
1973 if (imap_cmd_namespace(SESSION(session)->sock, &ns_str)
1975 log_warning(_("can't get namespace\n"));
1979 str_array = strsplit_parenthesis(ns_str, '(', ')', 3);
1980 if (str_array == NULL) {
1982 imap_get_namespace_by_list(session, folder);
1986 folder->ns_personal = imap_parse_namespace_str(str_array[0]);
1987 if (str_array[0] && str_array[1])
1988 folder->ns_others = imap_parse_namespace_str(str_array[1]);
1989 if (str_array[0] && str_array[1] && str_array[2])
1990 folder->ns_shared = imap_parse_namespace_str(str_array[2]);
1991 g_strfreev(str_array);
1995 static void imap_get_namespace_by_list(IMAPSession *session, IMAPFolder *folder)
1997 GSList *item_list, *cur;
1998 gchar separator = '\0';
1999 IMAPNameSpace *namespace;
2001 g_return_if_fail(session != NULL);
2002 g_return_if_fail(folder != NULL);
2004 if (folder->ns_personal != NULL ||
2005 folder->ns_others != NULL ||
2006 folder->ns_shared != NULL)
2009 imap_cmd_gen_send(SESSION(session)->sock, "LIST \"\" \"\"");
2010 item_list = imap_parse_list(NULL, session, "", &separator);
2011 for (cur = item_list; cur != NULL; cur = cur->next)
2012 folder_item_destroy(FOLDER_ITEM(cur->data));
2013 g_slist_free(item_list);
2015 namespace = g_new(IMAPNameSpace, 1);
2016 namespace->name = g_strdup("");
2017 namespace->separator = separator;
2018 folder->ns_personal = g_list_append(NULL, namespace);
2021 static IMAPNameSpace *imap_find_namespace_from_list(GList *ns_list,
2024 IMAPNameSpace *namespace = NULL;
2025 gchar *tmp_path, *name;
2027 if (!path) path = "";
2029 Xstrcat_a(tmp_path, path, "/", return NULL);
2031 for (; ns_list != NULL; ns_list = ns_list->next) {
2032 IMAPNameSpace *tmp_ns = ns_list->data;
2034 Xstrdup_a(name, tmp_ns->name, return namespace);
2035 if (tmp_ns->separator && tmp_ns->separator != '/')
2036 subst_char(name, tmp_ns->separator, '/');
2037 if (strncmp(tmp_path, name, strlen(name)) == 0)
2044 static IMAPNameSpace *imap_find_namespace(IMAPFolder *folder,
2047 IMAPNameSpace *namespace;
2049 g_return_val_if_fail(folder != NULL, NULL);
2051 namespace = imap_find_namespace_from_list(folder->ns_personal, path);
2052 if (namespace) return namespace;
2053 namespace = imap_find_namespace_from_list(folder->ns_others, path);
2054 if (namespace) return namespace;
2055 namespace = imap_find_namespace_from_list(folder->ns_shared, path);
2056 if (namespace) return namespace;
2061 static gchar imap_get_path_separator(IMAPFolder *folder, const gchar *path)
2063 IMAPNameSpace *namespace;
2064 gchar separator = '/';
2066 namespace = imap_find_namespace(folder, path);
2067 if (namespace && namespace->separator)
2068 separator = namespace->separator;
2073 static gchar *imap_get_real_path(IMAPFolder *folder, const gchar *path)
2078 g_return_val_if_fail(folder != NULL, NULL);
2079 g_return_val_if_fail(path != NULL, NULL);
2081 real_path = imap_locale_to_modified_utf7(path);
2082 separator = imap_get_path_separator(folder, path);
2083 imap_path_separator_subst(real_path, separator);
2088 static gchar *imap_parse_atom(SockInfo *sock, gchar *src,
2089 gchar *dest, gint dest_len, GString *str)
2091 gchar *cur_pos = src;
2094 g_return_val_if_fail(str != NULL, cur_pos);
2096 /* read the next line if the current response buffer is empty */
2097 while (isspace(*cur_pos)) cur_pos++;
2098 while (*cur_pos == '\0') {
2099 if ((nextline = sock_getline(sock)) == NULL)
2101 g_string_assign(str, nextline);
2103 strretchomp(nextline);
2104 /* log_print("IMAP4< %s\n", nextline); */
2105 debug_print("IMAP4< %s\n", nextline);
2108 while (isspace(*cur_pos)) cur_pos++;
2111 if (!strncmp(cur_pos, "NIL", 3)) {
2114 } else if (*cur_pos == '\"') {
2117 p = get_quoted(cur_pos, '\"', dest, dest_len);
2118 cur_pos = p ? p : cur_pos + 2;
2119 } else if (*cur_pos == '{') {
2124 cur_pos = strchr_cpy(cur_pos + 1, '}', buf, sizeof(buf));
2127 g_string_truncate(str, 0);
2131 if ((nextline = sock_getline(sock)) == NULL)
2133 line_len += strlen(nextline);
2134 g_string_append(str, nextline);
2136 strretchomp(nextline);
2137 /* log_print("IMAP4< %s\n", nextline); */
2138 debug_print("IMAP4< %s\n", nextline);
2140 } while (line_len < len);
2142 memcpy(dest, cur_pos, MIN(len, dest_len - 1));
2143 dest[MIN(len, dest_len - 1)] = '\0';
2150 static gchar *imap_get_header(SockInfo *sock, gchar *cur_pos, gchar **headers,
2160 g_return_val_if_fail(str != NULL, cur_pos);
2162 while (isspace(*cur_pos)) cur_pos++;
2164 g_return_val_if_fail(*cur_pos == '{', cur_pos);
2166 cur_pos = strchr_cpy(cur_pos + 1, '}', buf, sizeof(buf));
2169 g_string_truncate(str, 0);
2173 if ((nextline = sock_getline(sock)) == NULL)
2175 block_len += strlen(nextline);
2176 g_string_append(str, nextline);
2178 strretchomp(nextline);
2179 /* debug_print("IMAP4< %s\n", nextline); */
2181 } while (block_len < len);
2183 debug_print("IMAP4< [contents of RFC822.HEADER]\n");
2185 *headers = g_strndup(cur_pos, len);
2188 while (isspace(*cur_pos)) cur_pos++;
2189 while (*cur_pos == '\0') {
2190 if ((nextline = sock_getline(sock)) == NULL)
2192 g_string_assign(str, nextline);
2194 strretchomp(nextline);
2195 debug_print("IMAP4< %s\n", nextline);
2198 while (isspace(*cur_pos)) cur_pos++;
2204 static MsgFlags imap_parse_flags(const gchar *flag_str)
2206 const gchar *p = flag_str;
2207 MsgFlags flags = {0, 0};
2209 flags.perm_flags = MSG_UNREAD;
2211 while ((p = strchr(p, '\\')) != NULL) {
2214 if (g_strncasecmp(p, "Recent", 6) == 0 && MSG_IS_UNREAD(flags)) {
2215 MSG_SET_PERM_FLAGS(flags, MSG_NEW);
2216 } else if (g_strncasecmp(p, "Seen", 4) == 0) {
2217 MSG_UNSET_PERM_FLAGS(flags, MSG_NEW|MSG_UNREAD);
2218 } else if (g_strncasecmp(p, "Deleted", 7) == 0) {
2219 MSG_SET_PERM_FLAGS(flags, MSG_DELETED);
2220 } else if (g_strncasecmp(p, "Flagged", 7) == 0) {
2221 MSG_SET_PERM_FLAGS(flags, MSG_MARKED);
2222 } else if (g_strncasecmp(p, "Answered", 8) == 0) {
2223 MSG_SET_PERM_FLAGS(flags, MSG_REPLIED);
2230 static MsgInfo *imap_parse_envelope(SockInfo *sock, FolderItem *item,
2233 gchar buf[IMAPBUFSIZE];
2234 MsgInfo *msginfo = NULL;
2239 MsgFlags flags = {0, 0}, imap_flags = {0, 0};
2241 g_return_val_if_fail(line_str != NULL, NULL);
2242 g_return_val_if_fail(line_str->str[0] == '*' &&
2243 line_str->str[1] == ' ', NULL);
2245 MSG_SET_TMP_FLAGS(flags, MSG_IMAP);
2246 if (item->stype == F_QUEUE) {
2247 MSG_SET_TMP_FLAGS(flags, MSG_QUEUED);
2248 } else if (item->stype == F_DRAFT) {
2249 MSG_SET_TMP_FLAGS(flags, MSG_DRAFT);
2252 cur_pos = line_str->str + 2;
2254 #define PARSE_ONE_ELEMENT(ch) \
2256 cur_pos = strchr_cpy(cur_pos, ch, buf, sizeof(buf)); \
2257 if (cur_pos == NULL) { \
2258 g_warning("cur_pos == NULL\n"); \
2259 procmsg_msginfo_free(msginfo); \
2264 PARSE_ONE_ELEMENT(' ');
2267 PARSE_ONE_ELEMENT(' ');
2268 g_return_val_if_fail(!strcmp(buf, "FETCH"), NULL);
2270 g_return_val_if_fail(*cur_pos == '(', NULL);
2273 while (*cur_pos != '\0' && *cur_pos != ')') {
2274 while (*cur_pos == ' ') cur_pos++;
2276 if (!strncmp(cur_pos, "UID ", 4)) {
2278 uid = strtoul(cur_pos, &cur_pos, 10);
2279 } else if (!strncmp(cur_pos, "FLAGS ", 6)) {
2281 if (*cur_pos != '(') {
2282 g_warning("*cur_pos != '('\n");
2283 procmsg_msginfo_free(msginfo);
2287 PARSE_ONE_ELEMENT(')');
2288 imap_flags = imap_parse_flags(buf);
2289 } else if (!strncmp(cur_pos, "RFC822.SIZE ", 12)) {
2291 size = strtol(cur_pos, &cur_pos, 10);
2292 } else if (!strncmp(cur_pos, "RFC822.HEADER ", 14)) {
2296 cur_pos = imap_get_header(sock, cur_pos, &headers,
2298 msginfo = procheader_parse_str(headers, flags, FALSE, FALSE);
2301 g_warning("invalid FETCH response: %s\n", cur_pos);
2307 msginfo->msgnum = uid;
2308 msginfo->size = size;
2309 msginfo->flags.tmp_flags |= imap_flags.tmp_flags;
2310 msginfo->flags.perm_flags = imap_flags.perm_flags;
2316 gint imap_msg_set_perm_flags(MsgInfo *msginfo, MsgPermFlags flags)
2319 IMAPSession *session;
2320 IMAPFlags iflags = 0;
2321 gint ok = IMAP_SUCCESS;
2323 g_return_val_if_fail(msginfo != NULL, -1);
2324 g_return_val_if_fail(msginfo->folder != NULL, -1);
2325 g_return_val_if_fail(msginfo->folder->folder != NULL, -1);
2327 folder = msginfo->folder->folder;
2328 g_return_val_if_fail(folder->type == F_IMAP, -1);
2330 session = imap_session_get(folder);
2331 if (!session) return -1;
2333 if ((ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder->path,
2334 NULL, NULL, NULL, NULL)) != IMAP_SUCCESS)
2337 if (flags & MSG_MARKED) iflags |= IMAP_FLAG_FLAGGED;
2338 if (flags & MSG_REPLIED) iflags |= IMAP_FLAG_ANSWERED;
2340 ok = imap_set_message_flags(session, msginfo->msgnum,
2341 msginfo->msgnum, iflags, TRUE);
2342 if (ok != IMAP_SUCCESS) return ok;
2345 if (flags & MSG_UNREAD)
2346 ok = imap_set_message_flags(session, msginfo->msgnum,
2347 msginfo->msgnum, IMAP_FLAG_SEEN,
2352 gint imap_msg_unset_perm_flags(MsgInfo *msginfo, MsgPermFlags flags)
2355 IMAPSession *session;
2356 IMAPFlags iflags = 0;
2357 gint ok = IMAP_SUCCESS;
2359 g_return_val_if_fail(msginfo != NULL, -1);
2360 g_return_val_if_fail(msginfo->folder != NULL, -1);
2361 g_return_val_if_fail(msginfo->folder->folder != NULL, -1);
2363 folder = msginfo->folder->folder;
2364 g_return_val_if_fail(folder->type == F_IMAP, -1);
2366 session = imap_session_get(folder);
2367 if (!session) return -1;
2369 if (flags & MSG_MARKED) iflags |= IMAP_FLAG_FLAGGED;
2370 if (flags & MSG_REPLIED) iflags |= IMAP_FLAG_ANSWERED;
2372 ok = imap_set_message_flags(session, msginfo->msgnum,
2373 msginfo->msgnum, iflags, FALSE);
2374 if (ok != IMAP_SUCCESS) return ok;
2377 if (flags & MSG_UNREAD)
2378 ok = imap_set_message_flags(session, msginfo->msgnum,
2379 msginfo->msgnum, IMAP_FLAG_SEEN,
2384 static gint imap_set_message_flags(IMAPSession *session,
2393 buf = g_string_new(is_set ? "+FLAGS (" : "-FLAGS (");
2395 if (IMAP_IS_SEEN(flags)) g_string_append(buf, "\\Seen ");
2396 if (IMAP_IS_ANSWERED(flags)) g_string_append(buf, "\\Answered ");
2397 if (IMAP_IS_FLAGGED(flags)) g_string_append(buf, "\\Flagged ");
2398 if (IMAP_IS_DELETED(flags)) g_string_append(buf, "\\Deleted ");
2399 if (IMAP_IS_DRAFT(flags)) g_string_append(buf, "\\Draft");
2401 if (buf->str[buf->len - 1] == ' ')
2402 g_string_truncate(buf, buf->len - 1);
2404 g_string_append_c(buf, ')');
2406 ok = imap_cmd_store(SESSION(session)->sock, first_uid, last_uid,
2408 g_string_free(buf, TRUE);
2413 static gint imap_select(IMAPSession *session, IMAPFolder *folder,
2415 gint *exists, gint *recent, gint *unseen,
2416 guint32 *uid_validity)
2420 gint exists_, recent_, unseen_, uid_validity_;
2422 if (!exists || !recent || !unseen || !uid_validity) {
2423 if (session->mbox && strcmp(session->mbox, path) == 0)
2424 return IMAP_SUCCESS;
2428 uid_validity = &uid_validity_;
2431 g_free(session->mbox);
2432 session->mbox = NULL;
2434 real_path = imap_get_real_path(folder, path);
2435 ok = imap_cmd_select(SESSION(session)->sock, real_path,
2436 exists, recent, unseen, uid_validity);
2437 if (ok != IMAP_SUCCESS)
2438 log_warning(_("can't select folder: %s\n"), real_path);
2440 session->mbox = g_strdup(path);
2446 #define THROW(err) { ok = err; goto catch; }
2448 static gint imap_get_uid(IMAPSession *session, gint msgnum, guint32 *uid)
2456 argbuf = g_ptr_array_new();
2458 imap_cmd_gen_send(SESSION(session)->sock, "FETCH %d (UID)", msgnum);
2459 if ((ok = imap_cmd_ok(SESSION(session)->sock, argbuf)) != IMAP_SUCCESS)
2462 str = search_array_contain_str(argbuf, "FETCH");
2463 if (!str) THROW(IMAP_ERROR);
2465 if (sscanf(str, "%d FETCH (UID %d)", &num, uid) != 2 ||
2467 g_warning("imap_get_uid(): invalid FETCH line.\n");
2472 ptr_array_free_strings(argbuf);
2473 g_ptr_array_free(argbuf, TRUE);
2478 static gint imap_status(IMAPSession *session, IMAPFolder *folder,
2480 gint *messages, gint *recent,
2481 guint32 *uid_next, guint32 *uid_validity,
2490 *messages = *recent = *uid_next = *uid_validity = *unseen = 0;
2492 argbuf = g_ptr_array_new();
2494 real_path = imap_get_real_path(folder, path);
2495 QUOTE_IF_REQUIRED(real_path_, real_path);
2496 imap_cmd_gen_send(SESSION(session)->sock, "STATUS %s "
2497 "(MESSAGES RECENT UIDNEXT UIDVALIDITY UNSEEN)",
2500 ok = imap_cmd_ok(SESSION(session)->sock, argbuf);
2501 if (ok != IMAP_SUCCESS) THROW(ok);
2503 str = search_array_str(argbuf, "STATUS");
2504 if (!str) THROW(IMAP_ERROR);
2506 str = strchr(str, '(');
2507 if (!str) THROW(IMAP_ERROR);
2509 while (*str != '\0' && *str != ')') {
2510 while (*str == ' ') str++;
2512 if (!strncmp(str, "MESSAGES ", 9)) {
2514 *messages = strtol(str, &str, 10);
2515 } else if (!strncmp(str, "RECENT ", 7)) {
2517 *recent = strtol(str, &str, 10);
2518 } else if (!strncmp(str, "UIDNEXT ", 8)) {
2520 *uid_next = strtoul(str, &str, 10);
2521 } else if (!strncmp(str, "UIDVALIDITY ", 12)) {
2523 *uid_validity = strtoul(str, &str, 10);
2524 } else if (!strncmp(str, "UNSEEN ", 7)) {
2526 *unseen = strtol(str, &str, 10);
2528 g_warning("invalid STATUS response: %s\n", str);
2535 ptr_array_free_strings(argbuf);
2536 g_ptr_array_free(argbuf, TRUE);
2544 /* low-level IMAP4rev1 commands */
2546 static gint imap_cmd_login(SockInfo *sock,
2547 const gchar *user, const gchar *pass)
2549 gchar *user_, *pass_;
2552 QUOTE_IF_REQUIRED(user_, user);
2553 QUOTE_IF_REQUIRED(pass_, pass);
2554 imap_cmd_gen_send(sock, "LOGIN %s %s", user_, pass_);
2556 ok = imap_cmd_ok(sock, NULL);
2557 if (ok != IMAP_SUCCESS)
2558 log_warning(_("IMAP4 login failed.\n"));
2563 static gint imap_cmd_logout(SockInfo *sock)
2565 imap_cmd_gen_send(sock, "LOGOUT");
2566 return imap_cmd_ok(sock, NULL);
2569 /* Send a NOOP, and examine the server's response to see whether this
2570 * connection is pre-authenticated or not. */
2571 static gint imap_greeting(SockInfo *sock, gboolean *is_preauth)
2576 imap_cmd_gen_send(sock, "NOOP");
2577 argbuf = g_ptr_array_new(); /* will hold messages sent back */
2578 r = imap_cmd_ok(sock, argbuf);
2579 *is_preauth = search_array_str(argbuf, "PREAUTH") != NULL;
2581 ptr_array_free_strings(argbuf);
2582 g_ptr_array_free(argbuf, TRUE);
2587 static void imap_get_capability(Session *session)
2592 if (IMAP_SESSION(session)->capability != NULL)
2595 imap_cmd_gen_send(session->sock, "CAPABILITY");
2597 argbuf = g_ptr_array_new();
2599 if (imap_cmd_ok(session->sock, argbuf) != IMAP_SUCCESS ||
2600 ((capstr = search_array_str(argbuf, "CAPABILITY ")) == NULL)) {
2601 ptr_array_free_strings(argbuf);
2602 g_ptr_array_free(argbuf, TRUE);
2606 capstr += strlen("CAPABILITY ");
2608 IMAP_SESSION(session)->capability = g_strsplit(capstr, " ", 0);
2610 ptr_array_free_strings(argbuf);
2611 g_ptr_array_free(argbuf, TRUE);
2614 static gboolean imap_has_capability(IMAPSession *session, const gchar *cap)
2618 for (p = session->capability; *p != NULL; ++p)
2619 if (g_strcasecmp(*p, cap) == 0)
2625 static gint imap_cmd_noop(SockInfo *sock)
2627 imap_cmd_gen_send(sock, "NOOP");
2628 return imap_cmd_ok(sock, NULL);
2631 static gint imap_cmd_starttls(SockInfo *sock)
2633 imap_cmd_gen_send(sock, "STARTTLS");
2634 return imap_cmd_ok(sock, NULL);
2637 #define THROW(err) { ok = err; goto catch; }
2639 static gint imap_cmd_namespace(SockInfo *sock, gchar **ns_str)
2645 argbuf = g_ptr_array_new();
2647 imap_cmd_gen_send(sock, "NAMESPACE");
2648 if ((ok = imap_cmd_ok(sock, argbuf)) != IMAP_SUCCESS) THROW(ok);
2650 str = search_array_str(argbuf, "NAMESPACE");
2651 if (!str) THROW(IMAP_ERROR);
2653 *ns_str = g_strdup(str);
2656 ptr_array_free_strings(argbuf);
2657 g_ptr_array_free(argbuf, TRUE);
2664 static gint imap_cmd_list(SockInfo *sock, const gchar *ref,
2665 const gchar *mailbox, GPtrArray *argbuf)
2667 gchar *ref_, *mailbox_;
2669 if (!ref) ref = "\"\"";
2670 if (!mailbox) mailbox = "\"\"";
2672 QUOTE_IF_REQUIRED(ref_, ref);
2673 QUOTE_IF_REQUIRED(mailbox_, mailbox);
2674 imap_cmd_gen_send(sock, "LIST %s %s", ref_, mailbox_);
2676 return imap_cmd_ok(sock, argbuf);
2679 #define THROW goto catch
2681 static gint imap_cmd_do_select(SockInfo *sock, const gchar *folder,
2683 gint *exists, gint *recent, gint *unseen,
2684 guint32 *uid_validity)
2692 *exists = *recent = *unseen = *uid_validity = 0;
2693 argbuf = g_ptr_array_new();
2696 select_cmd = "EXAMINE";
2698 select_cmd = "SELECT";
2700 QUOTE_IF_REQUIRED(folder_, folder);
2701 imap_cmd_gen_send(sock, "%s %s", select_cmd, folder_);
2703 if ((ok = imap_cmd_ok(sock, argbuf)) != IMAP_SUCCESS) THROW;
2705 resp_str = search_array_contain_str(argbuf, "EXISTS");
2707 if (sscanf(resp_str,"%d EXISTS", exists) != 1) {
2708 g_warning("imap_cmd_select(): invalid EXISTS line.\n");
2713 resp_str = search_array_contain_str(argbuf, "RECENT");
2715 if (sscanf(resp_str, "%d RECENT", recent) != 1) {
2716 g_warning("imap_cmd_select(): invalid RECENT line.\n");
2721 resp_str = search_array_contain_str(argbuf, "UIDVALIDITY");
2723 if (sscanf(resp_str, "OK [UIDVALIDITY %u] ", uid_validity)
2725 g_warning("imap_cmd_select(): invalid UIDVALIDITY line.\n");
2730 resp_str = search_array_contain_str(argbuf, "UNSEEN");
2732 if (sscanf(resp_str, "OK [UNSEEN %d] ", unseen) != 1) {
2733 g_warning("imap_cmd_select(): invalid UNSEEN line.\n");
2739 ptr_array_free_strings(argbuf);
2740 g_ptr_array_free(argbuf, TRUE);
2745 static gint imap_cmd_select(SockInfo *sock, const gchar *folder,
2746 gint *exists, gint *recent, gint *unseen,
2747 guint32 *uid_validity)
2749 return imap_cmd_do_select(sock, folder, FALSE,
2750 exists, recent, unseen, uid_validity);
2753 static gint imap_cmd_examine(SockInfo *sock, const gchar *folder,
2754 gint *exists, gint *recent, gint *unseen,
2755 guint32 *uid_validity)
2757 return imap_cmd_do_select(sock, folder, TRUE,
2758 exists, recent, unseen, uid_validity);
2763 static gint imap_cmd_create(SockInfo *sock, const gchar *folder)
2767 QUOTE_IF_REQUIRED(folder_, folder);
2768 imap_cmd_gen_send(sock, "CREATE %s", folder_);
2770 return imap_cmd_ok(sock, NULL);
2773 static gint imap_cmd_rename(SockInfo *sock, const gchar *old_folder,
2774 const gchar *new_folder)
2776 gchar *old_folder_, *new_folder_;
2778 QUOTE_IF_REQUIRED(old_folder_, old_folder);
2779 QUOTE_IF_REQUIRED(new_folder_, new_folder);
2780 imap_cmd_gen_send(sock, "RENAME %s %s", old_folder_, new_folder_);
2782 return imap_cmd_ok(sock, NULL);
2785 static gint imap_cmd_delete(SockInfo *sock, const gchar *folder)
2789 QUOTE_IF_REQUIRED(folder_, folder);
2790 imap_cmd_gen_send(sock, "DELETE %s", folder_);
2792 return imap_cmd_ok(sock, NULL);
2795 static gint imap_cmd_fetch(SockInfo *sock, guint32 uid, const gchar *filename)
2798 gchar buf[IMAPBUFSIZE];
2803 g_return_val_if_fail(filename != NULL, IMAP_ERROR);
2805 imap_cmd_gen_send(sock, "UID FETCH %d BODY[]", uid);
2807 while ((ok = imap_cmd_gen_recv(sock, buf, sizeof(buf)))
2809 if (buf[0] != '*' || buf[1] != ' ')
2811 if (strstr(buf, "FETCH") != NULL)
2814 if (ok != IMAP_SUCCESS)
2817 cur_pos = strchr(buf, '{');
2818 g_return_val_if_fail(cur_pos != NULL, IMAP_ERROR);
2819 cur_pos = strchr_cpy(cur_pos + 1, '}', size_str, sizeof(size_str));
2820 g_return_val_if_fail(cur_pos != NULL, IMAP_ERROR);
2821 size_num = atol(size_str);
2823 if (*cur_pos != '\0') return IMAP_ERROR;
2825 if (recv_bytes_write_to_file(sock, size_num, filename) != 0)
2828 if (imap_cmd_gen_recv(sock, buf, sizeof(buf)) != IMAP_SUCCESS)
2831 if (buf[0] == '\0' || buf[strlen(buf) - 1] != ')')
2834 ok = imap_cmd_ok(sock, NULL);
2839 static gint imap_cmd_append(SockInfo *sock, const gchar *destfolder,
2845 gchar buf[BUFFSIZE];
2848 g_return_val_if_fail(file != NULL, IMAP_ERROR);
2850 size = get_file_size_as_crlf(file);
2851 if ((fp = fopen(file, "rb")) == NULL) {
2852 FILE_OP_ERROR(file, "fopen");
2855 QUOTE_IF_REQUIRED(destfolder_, destfolder);
2856 imap_cmd_gen_send(sock, "APPEND %s (\\Seen) {%d}", destfolder_, size);
2858 ok = imap_cmd_gen_recv(sock, buf, sizeof(buf));
2859 if (ok != IMAP_SUCCESS || buf[0] != '+' || buf[1] != ' ') {
2860 log_warning(_("can't append %s to %s\n"), file, destfolder_);
2865 log_print("IMAP4> %s\n", _("(sending file...)"));
2867 while (fgets(buf, sizeof(buf), fp) != NULL) {
2869 if (sock_puts(sock, buf) < 0) {
2877 FILE_OP_ERROR(file, "fgets");
2883 sock_puts(sock, "");
2886 return imap_cmd_ok(sock, NULL);
2890 static void imap_uidplus_copy(IMAPSession *session, MsgInfo *msginfo,
2891 const gchar *destfolder, const gchar *okmsginfo)
2893 unsigned int olduid, newuid;
2894 IMAPFlags iflags = 0;
2896 if (okmsginfo == NULL)
2899 if (sscanf(okmsginfo, "%*u OK [COPYUID %*llu %u %u]", &olduid, &newuid) != 2)
2902 if (olduid != msginfo->msgnum) /* this should NEVER happen */
2905 if (imap_select(session, IMAP_FOLDER(msginfo->folder->folder), destfolder,
2906 NULL, NULL, NULL, NULL) != IMAP_SUCCESS)
2909 if (msginfo->flags.perm_flags & MSG_MARKED) iflags |= IMAP_FLAG_FLAGGED;
2910 if (msginfo->flags.perm_flags & MSG_REPLIED) iflags |= IMAP_FLAG_ANSWERED;
2912 imap_set_message_flags(session, newuid, newuid, iflags, TRUE);
2914 if (msginfo->flags.perm_flags & MSG_UNREAD)
2915 imap_set_message_flags(session, newuid, newuid, IMAP_FLAG_SEEN, FALSE);
2917 imap_select(session, IMAP_FOLDER(msginfo->folder->folder), msginfo->folder->path,
2918 NULL, NULL, NULL, NULL);
2922 static gint imap_cmd_copy(IMAPSession *session,
2923 gint32 msgnum, const gchar *destfolder, gint32 *new_uid)
2926 gint32 olduid, newuid;
2931 g_return_val_if_fail(destfolder != NULL, IMAP_ERROR);
2932 g_return_val_if_fail(session != NULL, IMAP_ERROR);
2933 g_return_val_if_fail(new_uid != NULL, IMAP_ERROR);
2935 QUOTE_IF_REQUIRED(destfolder_, destfolder);
2936 imap_cmd_gen_send(SESSION(session)->sock, "UID COPY %d %s", msgnum, destfolder_);
2938 reply = g_ptr_array_new();
2940 ok = imap_cmd_ok(SESSION(session)->sock, reply);
2941 if (ok != IMAP_SUCCESS)
2942 log_warning(_("can't copy %d to %s\n"), msgnum, destfolder_);
2943 else if (imap_has_capability(session, "UIDPLUS") && reply->len > 0)
2944 if ((okmsginfo = g_ptr_array_index(reply, reply->len - 1)) != NULL &&
2945 sscanf(okmsginfo, "%*u OK [COPYUID %*llu %u %u]", &olduid, &newuid) == 2 &&
2949 ptr_array_free_strings(reply);
2950 g_ptr_array_free(reply, TRUE);
2954 gint imap_cmd_envelope(SockInfo *sock, guint32 first_uid, guint32 last_uid)
2957 (sock, "UID FETCH %d:%d (UID FLAGS RFC822.SIZE RFC822.HEADER)",
2958 first_uid, last_uid);
2960 return IMAP_SUCCESS;
2963 static gint imap_cmd_store(SockInfo *sock, guint32 first_uid, guint32 last_uid,
2968 imap_cmd_gen_send(sock, "UID STORE %d:%d %s",
2969 first_uid, last_uid, sub_cmd);
2971 if ((ok = imap_cmd_ok(sock, NULL)) != IMAP_SUCCESS) {
2972 log_warning(_("error while imap command: STORE %d:%d %s\n"),
2973 first_uid, last_uid, sub_cmd);
2977 return IMAP_SUCCESS;
2980 static gint imap_cmd_expunge(SockInfo *sock)
2984 imap_cmd_gen_send(sock, "EXPUNGE");
2985 if ((ok = imap_cmd_ok(sock, NULL)) != IMAP_SUCCESS) {
2986 log_warning(_("error while imap command: EXPUNGE\n"));
2990 return IMAP_SUCCESS;
2993 static gint imap_cmd_ok(SockInfo *sock, GPtrArray *argbuf)
2996 gchar buf[IMAPBUFSIZE];
2998 gchar cmd_status[IMAPBUFSIZE];
3000 while ((ok = imap_cmd_gen_recv(sock, buf, sizeof(buf)))
3002 if (buf[0] == '*' && buf[1] == ' ') {
3004 g_ptr_array_add(argbuf, g_strdup(buf + 2));
3008 if (sscanf(buf, "%d %s", &cmd_num, cmd_status) < 2)
3010 else if (cmd_num == imap_cmd_count &&
3011 !strcmp(cmd_status, "OK")) {
3013 g_ptr_array_add(argbuf, g_strdup(buf));
3014 return IMAP_SUCCESS;
3022 static void imap_cmd_gen_send(SockInfo *sock, const gchar *format, ...)
3024 gchar buf[IMAPBUFSIZE];
3025 gchar tmp[IMAPBUFSIZE];
3029 va_start(args, format);
3030 g_vsnprintf(tmp, sizeof(tmp), format, args);
3035 g_snprintf(buf, sizeof(buf), "%d %s\r\n", imap_cmd_count, tmp);
3036 if (!strncasecmp(tmp, "LOGIN ", 6) && (p = strchr(tmp + 6, ' '))) {
3038 log_print("IMAP4> %d %s ********\n", imap_cmd_count, tmp);
3040 log_print("IMAP4> %d %s\n", imap_cmd_count, tmp);
3042 sock_write(sock, buf, strlen(buf));
3045 static gint imap_cmd_gen_recv(SockInfo *sock, gchar *buf, gint size)
3047 if (sock_gets(sock, buf, size) == -1)
3052 log_print("IMAP4< %s\n", buf);
3054 return IMAP_SUCCESS;
3058 /* misc utility functions */
3060 static gchar *strchr_cpy(const gchar *src, gchar ch, gchar *dest, gint len)
3065 tmp = strchr(src, ch);
3069 memcpy(dest, src, MIN(tmp - src, len - 1));
3070 dest[MIN(tmp - src, len - 1)] = '\0';
3075 static gchar *get_quoted(const gchar *src, gchar ch, gchar *dest, gint len)
3077 const gchar *p = src;
3080 g_return_val_if_fail(*p == ch, NULL);
3085 while (*p != '\0' && *p != ch) {
3087 if (*p == '\\' && *(p + 1) != '\0')
3096 return (gchar *)(*p == ch ? p + 1 : p);
3099 static gchar *search_array_contain_str(GPtrArray *array, const gchar *str)
3103 for (i = 0; i < array->len; i++) {
3106 tmp = g_ptr_array_index(array, i);
3107 if (strstr(tmp, str) != NULL)
3114 static gchar *search_array_str(GPtrArray *array, const gchar *str)
3121 for (i = 0; i < array->len; i++) {
3124 tmp = g_ptr_array_index(array, i);
3125 if (!strncmp(tmp, str, len))
3132 static void imap_path_separator_subst(gchar *str, gchar separator)
3135 gboolean in_escape = FALSE;
3137 if (!separator || separator == '/') return;
3139 for (p = str; *p != '\0'; p++) {
3140 if (*p == '/' && !in_escape)
3142 else if (*p == '&' && *(p + 1) != '-' && !in_escape)
3144 else if (*p == '-' && in_escape)
3149 static gchar *imap_modified_utf7_to_locale(const gchar *mutf7_str)
3152 return g_strdup(mutf7_str);
3154 static iconv_t cd = (iconv_t)-1;
3155 static gboolean iconv_ok = TRUE;
3158 size_t norm_utf7_len;
3160 gchar *to_str, *to_p;
3162 gboolean in_escape = FALSE;
3164 if (!iconv_ok) return g_strdup(mutf7_str);
3166 if (cd == (iconv_t)-1) {
3167 cd = iconv_open(conv_get_current_charset_str(), "UTF-7");
3168 if (cd == (iconv_t)-1) {
3169 g_warning("iconv cannot convert UTF-7 to %s\n",
3170 conv_get_current_charset_str());
3172 return g_strdup(mutf7_str);
3176 norm_utf7 = g_string_new(NULL);
3178 for (p = mutf7_str; *p != '\0'; p++) {
3179 /* replace: '&' -> '+',
3181 escaped ',' -> '/' */
3182 if (!in_escape && *p == '&') {
3183 if (*(p + 1) != '-') {
3184 g_string_append_c(norm_utf7, '+');
3187 g_string_append_c(norm_utf7, '&');
3190 } else if (in_escape && *p == ',') {
3191 g_string_append_c(norm_utf7, '/');
3192 } else if (in_escape && *p == '-') {
3193 g_string_append_c(norm_utf7, '-');
3196 g_string_append_c(norm_utf7, *p);
3200 norm_utf7_p = norm_utf7->str;
3201 norm_utf7_len = norm_utf7->len;
3202 to_len = strlen(mutf7_str) * 5;
3203 to_p = to_str = g_malloc(to_len + 1);
3205 if (iconv(cd, &norm_utf7_p, &norm_utf7_len, &to_p, &to_len) == -1) {
3206 g_warning("iconv cannot convert UTF-7 to %s\n",
3207 conv_get_current_charset_str());
3208 g_string_free(norm_utf7, TRUE);
3210 return g_strdup(mutf7_str);
3213 /* second iconv() call for flushing */
3214 iconv(cd, NULL, NULL, &to_p, &to_len);
3215 g_string_free(norm_utf7, TRUE);
3219 #endif /* !HAVE_ICONV */
3222 static gchar *imap_locale_to_modified_utf7(const gchar *from)
3225 return g_strdup(from);
3227 static iconv_t cd = (iconv_t)-1;
3228 static gboolean iconv_ok = TRUE;
3229 gchar *norm_utf7, *norm_utf7_p;
3230 size_t from_len, norm_utf7_len;
3232 gchar *from_tmp, *to, *p;
3233 gboolean in_escape = FALSE;
3235 if (!iconv_ok) return g_strdup(from);
3237 if (cd == (iconv_t)-1) {
3238 cd = iconv_open("UTF-7", conv_get_current_charset_str());
3239 if (cd == (iconv_t)-1) {
3240 g_warning("iconv cannot convert %s to UTF-7\n",
3241 conv_get_current_charset_str());
3243 return g_strdup(from);
3247 Xstrdup_a(from_tmp, from, return g_strdup(from));
3248 from_len = strlen(from);
3249 norm_utf7_len = from_len * 5;
3250 Xalloca(norm_utf7, norm_utf7_len + 1, return g_strdup(from));
3251 norm_utf7_p = norm_utf7;
3253 #define IS_PRINT(ch) (isprint(ch) && isascii(ch))
3255 while (from_len > 0) {
3256 if (IS_PRINT(*from_tmp)) {
3257 /* printable ascii char */
3258 *norm_utf7_p = *from_tmp;
3265 /* unprintable char: convert to UTF-7 */
3267 !IS_PRINT(from_tmp[mblen]) && mblen < from_len;
3271 if (iconv(cd, &from_tmp, &mblen,
3272 &norm_utf7_p, &norm_utf7_len) == -1) {
3273 g_warning("iconv cannot convert %s to UTF-7\n",
3274 conv_get_current_charset_str());
3275 return g_strdup(from);
3278 /* second iconv() call for flushing */
3279 iconv(cd, NULL, NULL, &norm_utf7_p, &norm_utf7_len);
3285 *norm_utf7_p = '\0';
3286 to_str = g_string_new(NULL);
3287 for (p = norm_utf7; p < norm_utf7_p; p++) {
3288 /* replace: '&' -> "&-",
3290 escaped '/' -> ',' */
3291 if (!in_escape && *p == '&') {
3292 g_string_append(to_str, "&-");
3293 } else if (!in_escape && *p == '+') {
3294 g_string_append_c(to_str, '&');
3296 } else if (in_escape && *p == '/') {
3297 g_string_append_c(to_str, ',');
3298 } else if (in_escape && *p == '-') {
3300 g_string_append_c(to_str, '-');
3302 g_string_append_c(to_str, *p);
3308 g_string_append_c(to_str, '-');
3312 g_string_free(to_str, FALSE);
3315 #endif /* !HAVE_ICONV */
3318 static gboolean imap_rename_folder_func(GNode *node, gpointer data)
3320 FolderItem *item = node->data;
3321 gchar **paths = data;
3322 const gchar *oldpath = paths[0];
3323 const gchar *newpath = paths[1];
3325 gchar *new_itempath;
3328 oldpathlen = strlen(oldpath);
3329 if (strncmp(oldpath, item->path, oldpathlen) != 0) {
3330 g_warning("path doesn't match: %s, %s\n", oldpath, item->path);
3334 base = item->path + oldpathlen;
3335 while (*base == G_DIR_SEPARATOR) base++;
3337 new_itempath = g_strdup(newpath);
3339 new_itempath = g_strconcat(newpath, G_DIR_SEPARATOR_S, base,
3342 item->path = new_itempath;
3347 gint imap_get_num_list(Folder *folder, FolderItem *_item, GSList **msgnum_list)
3349 IMAPFolderItem *item = (IMAPFolderItem *)_item;
3350 IMAPSession *session;
3351 gint ok, i, lastuid_old, nummsgs = 0;
3353 gchar *cmdbuf = NULL;
3356 g_return_val_if_fail(folder != NULL, -1);
3357 g_return_val_if_fail(item != NULL, -1);
3358 g_return_val_if_fail(item->item.path != NULL, -1);
3359 g_return_val_if_fail(folder->type == F_IMAP, -1);
3360 g_return_val_if_fail(folder->account != NULL, -1);
3362 session = imap_session_get(folder);
3363 g_return_val_if_fail(session != NULL, -1);
3365 ok = imap_select(session, IMAP_FOLDER(folder), item->item.path,
3366 NULL, NULL, NULL, NULL);
3367 if (ok != IMAP_SUCCESS)
3370 argbuf = g_ptr_array_new();
3372 cmdbuf = g_strdup_printf("UID FETCH %d:* (UID)", (item->lastuid + 1));
3374 cmdbuf = g_strdup("FETCH 1:* (UID)");
3376 imap_cmd_gen_send(SESSION(session)->sock, cmdbuf);
3378 ok = imap_cmd_ok(SESSION(session)->sock, argbuf);
3379 if (ok != IMAP_SUCCESS) {
3380 ptr_array_free_strings(argbuf);
3381 g_ptr_array_free(argbuf, TRUE);
3385 lastuid_old = item->lastuid;
3386 *msgnum_list = g_slist_copy(item->uid_list);
3387 debug_print("Got %d uids from cache\n", g_slist_length(item->uid_list));
3388 for(i = 0; i < argbuf->len; i++) {
3389 int ret, msgidx, msgnum;
3391 if((ret = sscanf(g_ptr_array_index(argbuf, i), "%d FETCH (UID %d)", &msgidx, &msgnum)) == 2) {
3392 if(msgnum > lastuid_old) {
3393 *msgnum_list = g_slist_prepend(*msgnum_list, GINT_TO_POINTER(msgnum));
3394 item->uid_list = g_slist_prepend(item->uid_list, GINT_TO_POINTER(msgnum));
3397 if(msgnum > item->lastuid)
3398 item->lastuid = msgnum;
3403 dir = folder_item_get_path((FolderItem *)item);
3404 debug_print("removing old messages from %s\n", dir);
3405 remove_numbered_files_not_in_list(dir, *msgnum_list);
3408 ptr_array_free_strings(argbuf);
3409 g_ptr_array_free(argbuf, TRUE);
3414 static MsgInfo *imap_parse_msg(const gchar *file, FolderItem *item)
3419 flags.perm_flags = MSG_NEW|MSG_UNREAD;
3420 flags.tmp_flags = 0;
3422 g_return_val_if_fail(item != NULL, NULL);
3423 g_return_val_if_fail(file != NULL, NULL);
3425 if (item->stype == F_QUEUE) {
3426 MSG_SET_TMP_FLAGS(flags, MSG_QUEUED);
3427 } else if (item->stype == F_DRAFT) {
3428 MSG_SET_TMP_FLAGS(flags, MSG_DRAFT);
3431 msginfo = procheader_parse_file(file, flags, FALSE, FALSE);
3432 if (!msginfo) return NULL;
3434 msginfo->folder = item;
3440 MsgInfo *imap_get_msginfo(Folder *folder, FolderItem *item, gint uid)
3442 IMAPSession *session;
3443 MsgInfo *msginfo = NULL;
3446 g_return_val_if_fail(folder != NULL, NULL);
3447 g_return_val_if_fail(item != NULL, NULL);
3449 session = imap_session_get(folder);
3450 g_return_val_if_fail(session != NULL, NULL);
3452 ok = imap_select(session, IMAP_FOLDER(folder), item->path,
3453 NULL, NULL, NULL, NULL);
3454 if (ok != IMAP_SUCCESS)
3457 if (!(item->stype == F_QUEUE || item->stype == F_DRAFT)) {
3460 list = imap_get_uncached_messages(session, item, uid, uid);
3462 msginfo = (MsgInfo *)list->data;
3465 procmsg_msg_list_free(list);
3469 file = imap_fetch_msg(folder, item, uid);
3471 msginfo = imap_parse_msg(file, item);
3472 if (msginfo != NULL)
3473 msginfo->msgnum = uid;
3481 gboolean imap_check_msgnum_validity(Folder *folder, FolderItem *_item)
3483 IMAPSession *session;
3484 IMAPFolderItem *item = (IMAPFolderItem *)_item;
3485 gint ok, exists = 0, recent = 0, unseen = 0;
3486 guint32 uid_next, uid_validity = 0;
3488 g_return_val_if_fail(folder != NULL, FALSE);
3489 g_return_val_if_fail(item != NULL, FALSE);
3490 g_return_val_if_fail(item->item.folder != NULL, FALSE);
3491 g_return_val_if_fail(item->item.folder->type == F_IMAP, FALSE);
3493 session = imap_session_get(folder);
3494 g_return_val_if_fail(session != NULL, FALSE);
3496 ok = imap_status(session, IMAP_FOLDER(folder), item->item.path,
3497 &exists, &recent, &uid_next, &uid_validity, &unseen);
3498 if (ok != IMAP_SUCCESS)
3501 if(item->item.mtime == uid_validity)
3504 debug_print("Freeing imap uid cache");
3506 g_slist_free(item->uid_list);
3507 item->uid_list = NULL;
3509 item->item.mtime = uid_validity;
3511 imap_delete_all_cached_messages((FolderItem *)item);