Fix bug #3574: Template addressing
[claws.git] / src / imap.c
blob6c9161aed97a29d33fd82cf131ac1b552cc0f496
1 /*
2 * Claws Mail -- a GTK+ based, lightweight, and fast e-mail client
3 * Copyright (C) 1999-2016 Hiroyuki Yamamoto and the Claws Mail team
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 3 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, see <http://www.gnu.org/licenses/>.
19 #ifdef HAVE_CONFIG_H
20 # include "config.h"
21 #include "claws-features.h"
22 #endif
24 #include "defs.h"
26 #include <glib.h>
27 #include <glib/gi18n.h>
28 #include <stdio.h>
29 #include <string.h>
30 #include "imap.h"
31 #include "imap_gtk.h"
32 #include "inc.h"
33 #include "xml.h"
34 #include "alertpanel.h"
36 #ifdef HAVE_LIBETPAN
38 #include <stdlib.h>
39 #include <dirent.h>
40 #include <unistd.h>
41 #include <ctype.h>
42 #include <time.h>
43 #include <errno.h>
44 #if HAVE_ICONV
45 # include <iconv.h>
46 #endif
48 #ifdef USE_GNUTLS
49 # include "ssl.h"
50 #endif
52 #include "folder.h"
53 #include "session.h"
54 #include "procmsg.h"
55 #include "socket.h"
56 #include "recv.h"
57 #include "procheader.h"
58 #include "prefs_account.h"
59 #include "codeconv.h"
60 #include "md5.h"
61 #include "utils.h"
62 #include "prefs_common.h"
63 #include "inputdialog.h"
64 #include "log.h"
65 #include "remotefolder.h"
66 #include "claws.h"
67 #include "statusbar.h"
68 #include "msgcache.h"
69 #include "imap-thread.h"
70 #include "account.h"
71 #include "tags.h"
72 #include "main.h"
73 #include "passwordstore.h"
75 typedef struct _IMAPFolder IMAPFolder;
76 typedef struct _IMAPSession IMAPSession;
77 typedef struct _IMAPNameSpace IMAPNameSpace;
78 typedef struct _IMAPFolderItem IMAPFolderItem;
80 #include "prefs_account.h"
82 #define IMAP_FOLDER(obj) ((IMAPFolder *)obj)
83 #define IMAP_FOLDER_ITEM(obj) ((IMAPFolderItem *)obj)
84 #define IMAP_SESSION(obj) ((IMAPSession *)obj)
86 struct _IMAPFolder
88 RemoteFolder rfolder;
90 /* list of IMAPNameSpace */
91 GList *ns_personal;
92 GList *ns_others;
93 GList *ns_shared;
94 gchar last_seen_separator;
95 guint refcnt;
96 guint max_set_size;
97 gchar *search_charset;
98 gboolean search_charset_supported;
101 struct _IMAPSession
103 Session session;
105 gboolean authenticated;
107 GSList *capability;
108 gboolean uidplus;
110 gchar *mbox;
111 guint cmd_count;
113 /* CLAWS */
114 gboolean folder_content_changed;
115 guint exists;
116 guint recent;
117 guint expunge;
118 guint unseen;
119 guint uid_validity;
120 guint uid_next;
122 Folder * folder;
123 gboolean busy;
124 gboolean cancelled;
125 gboolean sens_update_block;
126 gboolean do_destroy;
129 struct _IMAPNameSpace
131 gchar *name;
132 gchar separator;
135 #define IMAPBUFSIZE 8192
137 #define IMAP_IS_SEEN(flags) ((flags & IMAP_FLAG_SEEN) != 0)
138 #define IMAP_IS_ANSWERED(flags) ((flags & IMAP_FLAG_ANSWERED) != 0)
139 #define IMAP_IS_FLAGGED(flags) ((flags & IMAP_FLAG_FLAGGED) != 0)
140 #define IMAP_IS_DELETED(flags) ((flags & IMAP_FLAG_DELETED) != 0)
141 #define IMAP_IS_DRAFT(flags) ((flags & IMAP_FLAG_DRAFT) != 0)
142 #define IMAP_IS_FORWARDED(flags) ((flags & IMAP_FLAG_FORWARDED) != 0)
143 #define IMAP_IS_SPAM(flags) ((flags & IMAP_FLAG_SPAM) != 0)
144 #define IMAP_IS_HAM(flags) ((flags & IMAP_FLAG_HAM) != 0)
147 #define IMAP4_PORT 143
148 #ifdef USE_GNUTLS
149 #define IMAPS_PORT 993
150 #endif
152 #define IMAP_CMD_LIMIT 1000
154 enum {
155 ITEM_CAN_CREATE_FLAGS_UNKNOWN = 0,
156 ITEM_CAN_CREATE_FLAGS,
157 ITEM_CANNOT_CREATE_FLAGS
160 struct _IMAPFolderItem
162 FolderItem item;
164 guint lastuid;
165 guint uid_next;
166 GSList *uid_list;
167 gboolean batching;
169 GHashTable *flags_set_table;
170 GHashTable *flags_unset_table;
171 guint32 last_change;
172 guint32 last_sync;
173 gboolean should_update;
174 gboolean should_trash_cache;
175 gint can_create_flags;
177 GHashTable *tags_set_table;
178 GHashTable *tags_unset_table;
179 GSList *ok_flags;
183 static XMLTag *imap_item_get_xml(Folder *folder, FolderItem *item);
184 static void imap_item_set_xml(Folder *folder, FolderItem *item, XMLTag *tag);
186 static void imap_folder_init (Folder *folder,
187 const gchar *name,
188 const gchar *path);
190 static Folder *imap_folder_new (const gchar *name,
191 const gchar *path);
192 static void imap_folder_destroy (Folder *folder);
194 static IMAPSession *imap_session_new (Folder *folder,
195 const PrefsAccount *account);
196 static gint imap_session_authenticate(IMAPSession *session,
197 PrefsAccount *account);
198 static void imap_session_destroy (Session *session);
200 static gchar *imap_fetch_msg (Folder *folder,
201 FolderItem *item,
202 gint uid);
203 static gchar *imap_fetch_msg_full (Folder *folder,
204 FolderItem *item,
205 gint uid,
206 gboolean headers,
207 gboolean body);
208 static void imap_remove_cached_msg (Folder *folder,
209 FolderItem *item,
210 MsgInfo *msginfo);
211 static gint imap_add_msg (Folder *folder,
212 FolderItem *dest,
213 const gchar *file,
214 MsgFlags *flags);
215 static gint imap_add_msgs (Folder *folder,
216 FolderItem *dest,
217 GSList *file_list,
218 GHashTable *relation);
220 static gint imap_copy_msg (Folder *folder,
221 FolderItem *dest,
222 MsgInfo *msginfo);
223 static gint imap_copy_msgs (Folder *folder,
224 FolderItem *dest,
225 MsgInfoList *msglist,
226 GHashTable *relation);
228 static gint search_msgs (Folder *folder,
229 FolderItem *container,
230 MsgNumberList **msgs,
231 gboolean *on_server,
232 MatcherList *predicate,
233 SearchProgressNotify progress_cb,
234 gpointer progress_data);
236 static gint imap_remove_msg (Folder *folder,
237 FolderItem *item,
238 gint uid);
239 static gint imap_remove_msgs (Folder *folder,
240 FolderItem *dest,
241 MsgInfoList *msglist,
242 GHashTable *relation);
243 static gint imap_expunge (Folder *folder,
244 FolderItem *dest);
245 static gint imap_remove_all_msg (Folder *folder,
246 FolderItem *item);
248 static gboolean imap_is_msg_changed (Folder *folder,
249 FolderItem *item,
250 MsgInfo *msginfo);
252 static gint imap_close (Folder *folder,
253 FolderItem *item);
255 static gint imap_scan_tree (Folder *folder);
257 static gint imap_create_tree (Folder *folder);
259 static FolderItem *imap_create_folder (Folder *folder,
260 FolderItem *parent,
261 const gchar *name);
262 static gint imap_rename_folder (Folder *folder,
263 FolderItem *item,
264 const gchar *name);
265 static gint imap_remove_folder (Folder *folder,
266 FolderItem *item);
268 static FolderItem *imap_folder_item_new (Folder *folder);
269 static void imap_folder_item_destroy (Folder *folder,
270 FolderItem *item);
272 static IMAPSession *imap_session_get (Folder *folder);
274 static gint imap_auth (IMAPSession *session,
275 const gchar *user,
276 const gchar *pass,
277 IMAPAuthType type);
279 static gint imap_scan_tree_recursive (IMAPSession *session,
280 FolderItem *item,
281 gboolean subs_only);
283 static void imap_create_missing_folders (Folder *folder);
284 static FolderItem *imap_create_special_folder
285 (Folder *folder,
286 SpecialFolderItemType stype,
287 const gchar *name);
289 static gint imap_do_copy_msgs (Folder *folder,
290 FolderItem *dest,
291 MsgInfoList *msglist,
292 GHashTable *relation,
293 gboolean same_dest_ok);
295 static gint imap_do_remove_msgs (Folder *folder,
296 FolderItem *dest,
297 MsgInfoList *msglist,
298 GHashTable *relation);
300 static void imap_delete_all_cached_messages (FolderItem *item);
301 static void imap_set_batch (Folder *folder,
302 FolderItem *item,
303 gboolean batch);
304 static gint imap_set_message_flags (IMAPSession *session,
305 IMAPFolderItem *item,
306 MsgNumberList *numlist,
307 IMAPFlags flags,
308 GSList *tags,
309 gboolean is_set);
310 static gint imap_select (IMAPSession *session,
311 IMAPFolder *folder,
312 FolderItem *item,
313 gint *exists,
314 gint *recent,
315 gint *unseen,
316 guint32 *uid_validity,
317 gint *can_create_flags,
318 gboolean block);
319 static gint imap_status (IMAPSession *session,
320 IMAPFolder *folder,
321 const gchar *path,
322 IMAPFolderItem *item,
323 gint *messages,
324 guint32 *uid_next,
325 guint32 *uid_validity,
326 gint *unseen,
327 gboolean block);
328 static void imap_commit_tags (FolderItem *item,
329 MsgInfo *msginfo,
330 GSList *set_tags,
331 GSList *unset_tags);
333 static gchar imap_get_path_separator (IMAPSession *session,
334 IMAPFolder *folder,
335 const gchar *path,
336 gint *ok);
337 static gchar *imap_get_real_path (IMAPSession *session,
338 IMAPFolder *folder,
339 const gchar *path,
340 gint *ok);
341 #ifdef HAVE_LIBETPAN
342 static void imap_synchronise (FolderItem *item, gint days);
343 #endif
344 static gboolean imap_is_busy (Folder *folder);
346 static void imap_free_capabilities (IMAPSession *session);
348 /* low-level IMAP4rev1 commands */
349 static gint imap_cmd_login (IMAPSession *session,
350 const gchar *user,
351 const gchar *pass,
352 const gchar *type);
353 static gint imap_cmd_noop (IMAPSession *session);
354 #ifdef USE_GNUTLS
355 static gint imap_cmd_starttls (IMAPSession *session);
356 #endif
357 static gint imap_cmd_select (IMAPSession *session,
358 const gchar *folder,
359 gint *exists,
360 gint *recent,
361 gint *unseen,
362 guint32 *uid_validity,
363 gint *can_create_flags,
364 GSList **ok_flags,
365 gboolean block);
366 static gint imap_cmd_close (IMAPSession *session);
367 static gint imap_cmd_examine (IMAPSession *session,
368 const gchar *folder,
369 gint *exists,
370 gint *recent,
371 gint *unseen,
372 guint32 *uid_validity,
373 gboolean block);
374 static gint imap_cmd_create (IMAPSession *sock,
375 const gchar *folder);
376 static gint imap_cmd_rename (IMAPSession *sock,
377 const gchar *oldfolder,
378 const gchar *newfolder);
379 static gint imap_cmd_delete (IMAPSession *session,
380 const gchar *folder);
381 static gint imap_cmd_fetch (IMAPSession *sock,
382 guint32 uid,
383 const gchar *filename,
384 gboolean headers,
385 gboolean body);
386 static gint imap_cmd_append (IMAPSession *session,
387 IMAPFolderItem *item,
388 const gchar *destfolder,
389 const gchar *file,
390 IMAPFlags flags,
391 guint32 *new_uid);
392 static gint imap_cmd_copy (IMAPSession *session,
393 struct mailimap_set * set,
394 const gchar *destfolder,
395 struct mailimap_set ** source,
396 struct mailimap_set ** dest);
397 static gint imap_cmd_store (IMAPSession *session,
398 IMAPFolderItem *item,
399 struct mailimap_set * set,
400 IMAPFlags flags,
401 GSList *tags,
402 int do_add);
403 static gint imap_cmd_expunge (IMAPSession *session);
405 static void imap_path_separator_subst (gchar *str,
406 gchar separator);
408 static gboolean imap_rename_folder_func (GNode *node,
409 gpointer data);
410 static gint imap_get_num_list (Folder *folder,
411 FolderItem *item,
412 GSList **list,
413 gboolean *old_uids_valid);
414 static GSList *imap_get_msginfos (Folder *folder,
415 FolderItem *item,
416 GSList *msgnum_list);
417 static MsgInfo *imap_get_msginfo (Folder *folder,
418 FolderItem *item,
419 gint num);
420 static gboolean imap_scan_required (Folder *folder,
421 FolderItem *item);
422 static void imap_change_flags (Folder *folder,
423 FolderItem *item,
424 MsgInfo *msginfo,
425 MsgPermFlags newflags);
426 static gint imap_get_flags (Folder *folder,
427 FolderItem *item,
428 MsgInfoList *msglist,
429 GHashTable *msgflags);
430 static gchar *imap_folder_get_path (Folder *folder);
431 static gchar *imap_item_get_path (Folder *folder,
432 FolderItem *item);
433 static MsgInfo *imap_parse_msg(const gchar *file, FolderItem *item);
436 /* data types conversion libetpan <-> claws */
437 static GSList * imap_list_from_lep(IMAPFolder * folder,
438 clist * list, const gchar * real_path, gboolean all);
439 static GSList * imap_get_lep_set_from_numlist(IMAPFolder *folder, MsgNumberList *numlist);
440 static GSList * imap_get_lep_set_from_msglist(IMAPFolder *folder, MsgInfoList *msglist);
441 static GSList * imap_uid_list_from_lep(clist * list, gint* length);
442 static GSList * imap_uid_list_from_lep_tab(carray * list);
443 static void imap_flags_hash_from_lep_uid_flags_tab(carray * list,
444 GHashTable * hash,
445 GHashTable *tags_hash);
446 static MsgInfo *imap_envelope_from_lep(struct imap_fetch_env_info * info,
447 FolderItem *item);
448 static void imap_lep_set_free(GSList *seq_list);
449 static struct mailimap_flag_list * imap_flag_to_lep(IMAPFolderItem *item, IMAPFlags flags, GSList *tags);
451 typedef struct _hashtable_data {
452 GSList *msglist;
453 IMAPFolderItem *item;
454 } hashtable_data;
456 static FolderClass imap_class;
458 FolderClass *imap_get_class(void)
460 if (imap_class.idstr == NULL) {
461 imap_class.type = F_IMAP;
462 imap_class.idstr = "imap";
463 imap_class.uistr = "IMAP";
464 imap_class.supports_server_search = TRUE;
466 /* Folder functions */
467 imap_class.new_folder = imap_folder_new;
468 imap_class.destroy_folder = imap_folder_destroy;
469 imap_class.scan_tree = imap_scan_tree;
470 imap_class.create_tree = imap_create_tree;
472 /* FolderItem functions */
473 imap_class.item_new = imap_folder_item_new;
474 imap_class.item_destroy = imap_folder_item_destroy;
475 imap_class.item_get_path = imap_item_get_path;
476 imap_class.create_folder = imap_create_folder;
477 imap_class.rename_folder = imap_rename_folder;
478 imap_class.remove_folder = imap_remove_folder;
479 imap_class.close = imap_close;
480 imap_class.get_num_list = imap_get_num_list;
481 imap_class.scan_required = imap_scan_required;
482 imap_class.set_xml = folder_set_xml;
483 imap_class.get_xml = folder_get_xml;
484 imap_class.item_set_xml = imap_item_set_xml;
485 imap_class.item_get_xml = imap_item_get_xml;
487 /* Message functions */
488 imap_class.get_msginfo = imap_get_msginfo;
489 imap_class.get_msginfos = imap_get_msginfos;
490 imap_class.fetch_msg = imap_fetch_msg;
491 imap_class.fetch_msg_full = imap_fetch_msg_full;
492 imap_class.add_msg = imap_add_msg;
493 imap_class.add_msgs = imap_add_msgs;
494 imap_class.copy_msg = imap_copy_msg;
495 imap_class.copy_msgs = imap_copy_msgs;
496 imap_class.search_msgs = search_msgs;
497 imap_class.remove_msg = imap_remove_msg;
498 imap_class.remove_msgs = imap_remove_msgs;
499 imap_class.expunge = imap_expunge;
500 imap_class.remove_all_msg = imap_remove_all_msg;
501 imap_class.is_msg_changed = imap_is_msg_changed;
502 imap_class.change_flags = imap_change_flags;
503 imap_class.get_flags = imap_get_flags;
504 imap_class.set_batch = imap_set_batch;
505 imap_class.synchronise = imap_synchronise;
506 imap_class.remove_cached_msg = imap_remove_cached_msg;
507 imap_class.commit_tags = imap_commit_tags;
510 return &imap_class;
513 static void imap_refresh_sensitivity (IMAPSession *session)
515 MainWindow *mainwin;
517 if (session->sens_update_block)
518 return;
519 mainwin = mainwindow_get_mainwindow();
520 if (mainwin) {
521 toolbar_main_set_sensitive(mainwin);
522 main_window_set_menu_sensitive(mainwin);
526 static void lock_session(IMAPSession *session)
528 if (session) {
529 debug_print("locking session %p (%d)\n", session, session->busy);
530 if (session->busy)
531 debug_print(" SESSION WAS LOCKED !! \n");
532 session->busy = TRUE;
533 imap_refresh_sensitivity(session);
534 } else {
535 debug_print("can't lock null session\n");
539 static void unlock_session(IMAPSession *session)
541 if (session) {
542 debug_print("unlocking session %p\n", session);
543 session->busy = FALSE;
544 imap_refresh_sensitivity(session);
545 } else {
546 debug_print("can't unlock null session\n");
550 static gboolean imap_ping(gpointer data)
552 Session *session = (Session *)data;
553 IMAPSession *imap_session = IMAP_SESSION(session);
554 int r;
556 if (session->state != SESSION_READY)
557 return FALSE;
558 if (imap_session->busy || !imap_session->authenticated)
559 return TRUE;
561 lock_session(imap_session);
562 r = imap_cmd_noop(imap_session);
563 unlock_session(imap_session);
565 return r == MAILIMAP_NO_ERROR;
568 static void imap_disc_session_destroy(IMAPSession *session)
570 RemoteFolder *rfolder = NULL;
572 if (session == NULL)
573 return;
575 rfolder = REMOTE_FOLDER(IMAP_SESSION(session)->folder);
577 if (rfolder == NULL)
578 return;
579 log_warning(LOG_PROTOCOL, _("IMAP connection broken\n"));
580 SESSION(session)->state = SESSION_DISCONNECTED;
581 SESSION(session)->sock = NULL;
584 static void imap_safe_destroy(IMAPSession *session)
586 if (!session->busy)
587 session_destroy(SESSION(session));
588 else
589 session->do_destroy = TRUE;
592 static gboolean is_fatal(int libetpan_errcode)
594 switch(libetpan_errcode) {
595 case MAILIMAP_ERROR_STREAM:
596 case MAILIMAP_ERROR_PROTOCOL:
597 case MAILIMAP_ERROR_PARSE:
598 case MAILIMAP_ERROR_BAD_STATE:
599 return TRUE;
600 default:
601 return FALSE;
605 static void imap_handle_error(Session *session, const gchar *server, int libetpan_errcode)
607 const gchar *session_server = (session ? session->server : NULL);
609 if (session_server == NULL)
610 session_server = server;
611 if (session_server == NULL)
612 session_server = "(null)";
614 switch(libetpan_errcode) {
615 case MAILIMAP_NO_ERROR:
616 return;
617 case MAILIMAP_NO_ERROR_AUTHENTICATED:
618 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"), " ", _("authenticated"), "\n", NULL), session_server);
619 break;
620 case MAILIMAP_NO_ERROR_NON_AUTHENTICATED:
621 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"), " ", _("not authenticated"), "\n", NULL), session_server);
622 break;
623 case MAILIMAP_ERROR_BAD_STATE:
624 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"), " ", _("bad state"), "\n", NULL), session_server);
625 break;
626 case MAILIMAP_ERROR_STREAM:
627 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"), " ", _("stream error"), "\n", NULL), session_server);
628 break;
629 case MAILIMAP_ERROR_PARSE:
630 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"), " ", _("parse error "
631 "(very probably non-RFC compliance from the server)"), "\n", NULL), session_server);
632 break;
633 case MAILIMAP_ERROR_CONNECTION_REFUSED:
634 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"), " ", _("connection refused"), "\n", NULL), session_server);
635 break;
636 case MAILIMAP_ERROR_MEMORY:
637 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"), " ", _("memory error"), "\n", NULL), session_server);
638 break;
639 case MAILIMAP_ERROR_FATAL:
640 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"), " ", _("fatal error"), "\n", NULL), session_server);
641 break;
642 case MAILIMAP_ERROR_PROTOCOL:
643 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"), " ", _("protocol error "
644 "(very probably non-RFC compliance from the server)"), "\n", NULL), session_server);
645 break;
646 case MAILIMAP_ERROR_DONT_ACCEPT_CONNECTION:
647 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"), " ", _("connection not accepted"), "\n", NULL), session_server);
648 break;
649 case MAILIMAP_ERROR_APPEND:
650 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"), " ", _("APPEND error"), "\n", NULL), session_server);
651 break;
652 case MAILIMAP_ERROR_NOOP:
653 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"), " ", _("NOOP error"), "\n", NULL), session_server);
654 break;
655 case MAILIMAP_ERROR_LOGOUT:
656 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"), " ", _("LOGOUT error"), "\n", NULL), session_server);
657 break;
658 case MAILIMAP_ERROR_CAPABILITY:
659 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"), " ", _("CAPABILITY error"), "\n", NULL), session_server);
660 break;
661 case MAILIMAP_ERROR_CHECK:
662 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"), " ", _("CHECK error"), "\n", NULL), session_server);
663 break;
664 case MAILIMAP_ERROR_CLOSE:
665 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"), " ", _("CLOSE error"), "\n", NULL), session_server);
666 break;
667 case MAILIMAP_ERROR_EXPUNGE:
668 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"), " ", _("EXPUNGE error"), "\n", NULL), session_server);
669 break;
670 case MAILIMAP_ERROR_COPY:
671 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"), " ", _("COPY error"), "\n", NULL), session_server);
672 break;
673 case MAILIMAP_ERROR_UID_COPY:
674 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"), " ", _("UID COPY error"), "\n", NULL), session_server);
675 break;
676 case MAILIMAP_ERROR_CREATE:
677 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"), " ", _("CREATE error"), "\n", NULL), session_server);
678 break;
679 case MAILIMAP_ERROR_DELETE:
680 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"), " ", _("DELETE error"), "\n", NULL), session_server);
681 break;
682 case MAILIMAP_ERROR_EXAMINE:
683 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"), " ", _("EXAMINE error"), "\n", NULL), session_server);
684 break;
685 case MAILIMAP_ERROR_FETCH:
686 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"), " ", _("FETCH error"), "\n", NULL), session_server);
687 break;
688 case MAILIMAP_ERROR_UID_FETCH:
689 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"), " ", _("UID FETCH error"), "\n", NULL), session_server);
690 break;
691 case MAILIMAP_ERROR_LIST:
692 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"), " ", _("LIST error"), "\n", NULL), session_server);
693 break;
694 case MAILIMAP_ERROR_LOGIN:
695 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"), " ", _("LOGIN error"), "\n", NULL), session_server);
696 break;
697 case MAILIMAP_ERROR_LSUB:
698 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"), " ", _("LSUB error"), "\n", NULL), session_server);
699 break;
700 case MAILIMAP_ERROR_RENAME:
701 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"), " ", _("RENAME error"), "\n", NULL), session_server);
702 break;
703 case MAILIMAP_ERROR_SEARCH:
704 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"), " ", _("SEARCH error"), "\n", NULL), session_server);
705 break;
706 case MAILIMAP_ERROR_UID_SEARCH:
707 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"), " ", _("UID SEARCH error"), "\n", NULL), session_server);
708 break;
709 case MAILIMAP_ERROR_SELECT:
710 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"), " ", _("SELECT error"), "\n", NULL), session_server);
711 break;
712 case MAILIMAP_ERROR_STATUS:
713 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"), " ", _("STATUS error"), "\n", NULL), session_server);
714 break;
715 case MAILIMAP_ERROR_STORE:
716 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"), " ", _("STORE error"), "\n", NULL), session_server);
717 break;
718 case MAILIMAP_ERROR_UID_STORE:
719 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"), " ", _("UID STORE error"), "\n", NULL), session_server);
720 break;
721 case MAILIMAP_ERROR_SUBSCRIBE:
722 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"), " ", _("SUBSCRIBE error"), "\n", NULL), session_server);
723 break;
724 case MAILIMAP_ERROR_UNSUBSCRIBE:
725 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"), " ", _("UNSUBSCRIBE error"), "\n", NULL), session_server);
726 break;
727 case MAILIMAP_ERROR_STARTTLS:
728 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"), " ", _("STARTTLS error"), "\n", NULL), session_server);
729 break;
730 case MAILIMAP_ERROR_INVAL:
731 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"), " ", _("INVAL error"), "\n", NULL), session_server);
732 break;
733 case MAILIMAP_ERROR_EXTENSION:
734 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"), " ", _("EXTENSION error"), "\n", NULL), session_server);
735 break;
736 case MAILIMAP_ERROR_SASL:
737 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"), " ", _("SASL error"), "\n", NULL), session_server);
738 break;
739 #ifdef USE_GNUTLS
740 case MAILIMAP_ERROR_SSL:
741 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"), " ", _("SSL/TLS error"), "\n", NULL), session_server);
742 break;
743 #endif
744 default:
745 log_warning(LOG_PROTOCOL, g_strconcat(_("IMAP error on %s:"), " ", _("Unknown error [%d]"), "\n", NULL),
746 session_server, libetpan_errcode);
747 break;
750 if (session && is_fatal(libetpan_errcode)) {
751 imap_disc_session_destroy(IMAP_SESSION(session));
752 } else if (session && !is_fatal(libetpan_errcode)) {
753 if (IMAP_SESSION(session)->busy)
754 unlock_session(IMAP_SESSION(session));
758 static Folder *imap_folder_new(const gchar *name, const gchar *path)
760 Folder *folder;
762 folder = (Folder *)g_new0(IMAPFolder, 1);
763 folder->klass = &imap_class;
764 imap_folder_init(folder, name, path);
766 return folder;
769 static void imap_folder_destroy(Folder *folder)
771 while (imap_folder_get_refcnt(folder) > 0)
772 gtk_main_iteration();
774 g_free(IMAP_FOLDER(folder)->search_charset);
776 folder_remote_folder_destroy(REMOTE_FOLDER(folder));
777 imap_done(folder);
780 static void imap_folder_init(Folder *folder, const gchar *name,
781 const gchar *path)
783 folder_remote_folder_init((Folder *)folder, name, path);
784 IMAP_FOLDER(folder)->max_set_size = IMAP_SET_MAX_COUNT;
785 IMAP_FOLDER(folder)->search_charset_supported = TRUE;
786 IMAP_FOLDER(folder)->search_charset = g_strdup(conv_get_locale_charset_str_no_utf8());
789 static FolderItem *imap_folder_item_new(Folder *folder)
791 IMAPFolderItem *item;
793 item = g_new0(IMAPFolderItem, 1);
794 item->lastuid = 0;
795 item->uid_next = 0;
796 item->uid_list = NULL;
798 return (FolderItem *)item;
801 static void imap_folder_item_destroy(Folder *folder, FolderItem *_item)
803 IMAPFolderItem *item = (IMAPFolderItem *)_item;
805 g_return_if_fail(item != NULL);
806 g_slist_free(item->uid_list);
808 g_free(_item);
811 static gboolean imap_reset_uid_lists_func(GNode *node, gpointer data)
813 IMAPFolderItem *item = (IMAPFolderItem *)node->data;
815 item->lastuid = 0;
816 g_slist_free(item->uid_list);
817 item->uid_list = NULL;
819 return FALSE;
822 static void imap_reset_uid_lists(Folder *folder)
824 if(folder->node == NULL)
825 return;
827 /* Destroy all uid lists and rest last uid */
828 g_node_traverse(folder->node, G_IN_ORDER, G_TRAVERSE_ALL, -1, imap_reset_uid_lists_func, NULL);
831 static int imap_get_capabilities(IMAPSession *session)
833 struct mailimap_capability_data *capabilities = NULL;
834 clistiter *cur;
835 int result;
837 if (session->capability != NULL)
838 return MAILIMAP_NO_ERROR;
840 result = imap_threaded_capability(session->folder, &capabilities);
842 if (result != MAILIMAP_NO_ERROR) {
843 return result;
846 if (capabilities == NULL || capabilities->cap_list == NULL) {
847 return MAILIMAP_NO_ERROR;
850 for(cur = clist_begin(capabilities->cap_list) ; cur != NULL ;
851 cur = clist_next(cur)) {
852 struct mailimap_capability * cap =
853 clist_content(cur);
854 if (!cap || cap->cap_data.cap_name == NULL)
855 continue;
856 session->capability = g_slist_append
857 (session->capability,
858 g_strdup(cap->cap_data.cap_name));
859 debug_print("got capa %s\n", cap->cap_data.cap_name);
861 mailimap_capability_data_free(capabilities);
862 return MAILIMAP_NO_ERROR;
865 static gboolean imap_has_capability(IMAPSession *session, const gchar *cap)
867 GSList *cur;
868 for (cur = session->capability; cur; cur = cur->next) {
869 if (!g_ascii_strcasecmp(cur->data, cap))
870 return TRUE;
872 return FALSE;
875 static gint imap_auth(IMAPSession *session, const gchar *user, const gchar *pass,
876 IMAPAuthType type)
878 gint ok = MAILIMAP_ERROR_LOGIN;
879 static time_t last_login_err = 0;
880 gchar *ext_info = "";
881 int r;
882 gchar *server = NULL;
883 if ((r = imap_get_capabilities(session)) != MAILIMAP_NO_ERROR) {
884 imap_handle_error(SESSION(session), NULL, r);
885 return r;
887 server = g_strdup(SESSION(session)->server);
888 switch(type) {
889 case IMAP_AUTH_ANON:
890 ok = imap_cmd_login(session, user, pass, "ANONYMOUS");
891 break;
892 case IMAP_AUTH_CRAM_MD5:
893 ok = imap_cmd_login(session, user, pass, "CRAM-MD5");
894 break;
895 case IMAP_AUTH_DIGEST_MD5:
896 ok = imap_cmd_login(session, user, pass, "DIGEST-MD5");
897 break;
898 case IMAP_AUTH_SCRAM_SHA1:
899 ok = imap_cmd_login(session, user, pass, "SCRAM-SHA-1");
900 break;
901 case IMAP_AUTH_PLAIN:
902 ok = imap_cmd_login(session, user, pass, "PLAIN");
903 break;
904 case IMAP_AUTH_LOGIN:
905 ok = imap_cmd_login(session, user, pass, "LOGIN");
906 break;
907 case IMAP_AUTH_PLAINTEXT:
908 ok = imap_cmd_login(session, user, pass, "plaintext");
909 break;
910 case IMAP_AUTH_GSSAPI:
911 ok = imap_cmd_login(session, user, pass, "GSSAPI");
912 break;
913 default:
914 debug_print("capabilities:\n"
915 "\t ANONYMOUS %d\n"
916 "\t CRAM-MD5 %d\n"
917 "\t DIGEST-MD5 %d\n"
918 "\t SCRAM-SHA-1 %d\n"
919 "\t PLAIN %d\n"
920 "\t LOGIN %d\n"
921 "\t GSSAPI %d\n",
922 imap_has_capability(session, "ANONYMOUS"),
923 imap_has_capability(session, "CRAM-MD5"),
924 imap_has_capability(session, "DIGEST-MD5"),
925 imap_has_capability(session, "SCRAM-SHA-1"),
926 imap_has_capability(session, "PLAIN"),
927 imap_has_capability(session, "LOGIN"),
928 imap_has_capability(session, "GSSAPI"));
929 if (imap_has_capability(session, "CRAM-MD5"))
930 ok = imap_cmd_login(session, user, pass, "CRAM-MD5");
931 if (ok == MAILIMAP_ERROR_LOGIN && imap_has_capability(session, "DIGEST-MD5"))
932 ok = imap_cmd_login(session, user, pass, "DIGEST-MD5");
933 if (ok == MAILIMAP_ERROR_LOGIN && imap_has_capability(session, "SCRAM-SHA-1"))
934 ok = imap_cmd_login(session, user, pass, "SCRAM-SHA-1");
935 if (ok == MAILIMAP_ERROR_LOGIN && imap_has_capability(session, "PLAIN"))
936 ok = imap_cmd_login(session, user, pass, "PLAIN");
937 if (ok == MAILIMAP_ERROR_LOGIN && imap_has_capability(session, "LOGIN"))
938 ok = imap_cmd_login(session, user, pass, "LOGIN");
939 if (ok == MAILIMAP_ERROR_LOGIN && imap_has_capability(session, "GSSAPI"))
940 ok = imap_cmd_login(session, user, pass, "GSSAPI");
941 if (ok == MAILIMAP_ERROR_LOGIN) /* we always try plaintext login before giving up */
942 ok = imap_cmd_login(session, user, pass, "plaintext");
945 if (ok == MAILIMAP_NO_ERROR)
946 session->authenticated = TRUE;
947 else {
948 if (type == IMAP_AUTH_CRAM_MD5) {
949 ext_info = _("\n\nCRAM-MD5 logins only work if libetpan has been "
950 "compiled with SASL support and the "
951 "CRAM-MD5 SASL plugin is installed.");
954 if (type == IMAP_AUTH_DIGEST_MD5) {
955 ext_info = _("\n\nDIGEST-MD5 logins only work if libetpan has been "
956 "compiled with SASL support and the "
957 "DIGEST-MD5 SASL plugin is installed.");
960 if (type == IMAP_AUTH_SCRAM_SHA1) {
961 ext_info = _("\n\nSCRAM-SHA-1 logins only work if libetpan has been "
962 "compiled with SASL support and the "
963 "SCRAM SASL plugin is installed.");
966 if (type == IMAP_AUTH_PLAIN) {
967 ext_info = _("\n\nPLAIN logins only work if libetpan has been "
968 "compiled with SASL support and the "
969 "PLAIN SASL plugin is installed.");
972 if (type == IMAP_AUTH_LOGIN) {
973 ext_info = _("\n\nLOGIN logins only work if libetpan has been "
974 "compiled with SASL support and the "
975 "LOGIN SASL plugin is installed.");
978 if (time(NULL) - last_login_err > 10) {
979 if (!prefs_common.no_recv_err_panel) {
980 alertpanel_error_log(_("Connection to %s failed: "
981 "login refused.%s"),
982 server, ext_info);
983 } else {
984 log_error(LOG_PROTOCOL, _("Connection to %s failed: "
985 "login refused.%s\n"),
986 server, ext_info);
989 last_login_err = time(NULL);
991 g_free(server);
992 return ok;
995 static IMAPSession *imap_reconnect_if_possible(Folder *folder, IMAPSession *session)
997 RemoteFolder *rfolder = REMOTE_FOLDER(folder);
998 /* Check if this is the first try to establish a
999 connection, if yes we don't try to reconnect */
1000 debug_print("reconnecting\n");
1001 if (rfolder->session == NULL) {
1002 log_warning(LOG_PROTOCOL, _("Connecting to %s failed"),
1003 folder->account->recv_server);
1004 SESSION(session)->sock = NULL;
1005 imap_safe_destroy(session);
1006 session = NULL;
1007 } else {
1008 rfolder->session = NULL;
1009 log_warning(LOG_PROTOCOL, _("IMAP connection to %s has been"
1010 " disconnected. Reconnecting...\n"),
1011 folder->account->recv_server);
1012 statusbar_print_all(_("IMAP connection to %s has been"
1013 " disconnected. Reconnecting...\n"),
1014 folder->account->recv_server);
1015 SESSION(session)->state = SESSION_DISCONNECTED;
1016 SESSION(session)->sock = NULL;
1017 imap_safe_destroy(session);
1018 /* Clear folders session to make imap_session_get create
1019 a new session, because of rfolder->session == NULL
1020 it will not try to reconnect again and so avoid an
1021 endless loop */
1022 debug_print("getting session...\n");
1023 session = imap_session_get(folder);
1024 rfolder->session = SESSION(session);
1025 statusbar_pop_all();
1027 return session;
1030 static IMAPSession *imap_session_get(Folder *folder)
1032 RemoteFolder *rfolder = REMOTE_FOLDER(folder);
1033 IMAPSession *session = NULL;
1034 gint r = MAILIMAP_NO_ERROR;
1036 g_return_val_if_fail(folder != NULL, NULL);
1037 g_return_val_if_fail(FOLDER_CLASS(folder) == &imap_class, NULL);
1038 g_return_val_if_fail(folder->account != NULL, NULL);
1040 if (prefs_common.work_offline &&
1041 !inc_offline_should_override(FALSE,
1042 _("Claws Mail needs network access in order "
1043 "to access the IMAP server."))) {
1044 return NULL;
1047 /* check for deferred destroy */
1048 if (rfolder->session != NULL) {
1049 session = IMAP_SESSION(rfolder->session);
1050 if (!session->busy && session->do_destroy) {
1051 rfolder->session = NULL;
1052 imap_safe_destroy(session);
1053 session = NULL;
1057 /* Make sure we have a session */
1058 if (rfolder->session != NULL && rfolder->session->state != SESSION_DISCONNECTED) {
1059 session = IMAP_SESSION(rfolder->session);
1060 } else if (rfolder->session != NULL && rfolder->session->state == SESSION_DISCONNECTED) {
1061 imap_safe_destroy(IMAP_SESSION(rfolder->session));
1062 rfolder->session = NULL;
1063 goto new_conn;
1064 } else if (rfolder->connecting) {
1065 debug_print("already connecting\n");
1066 return NULL;
1067 } else {
1068 new_conn:
1069 imap_reset_uid_lists(folder);
1070 if (time(NULL) - rfolder->last_failure <= 2)
1071 return NULL;
1072 rfolder->connecting = TRUE;
1073 session = imap_session_new(folder, folder->account);
1075 if(session == NULL) {
1076 rfolder->last_failure = time(NULL);
1077 rfolder->connecting = FALSE;
1078 return NULL;
1081 /* Make sure session is authenticated */
1082 if (!IMAP_SESSION(session)->authenticated)
1083 r = imap_session_authenticate(IMAP_SESSION(session), folder->account);
1085 if (r != MAILIMAP_NO_ERROR || (!is_fatal(r) && !IMAP_SESSION(session)->authenticated)) {
1086 rfolder->session = NULL;
1087 if (!is_fatal(r)) {
1088 imap_threaded_disconnect(session->folder);
1090 SESSION(session)->state = SESSION_DISCONNECTED;
1091 SESSION(session)->sock = NULL;
1092 imap_safe_destroy(session);
1093 rfolder->last_failure = time(NULL);
1094 rfolder->connecting = FALSE;
1095 return NULL;
1098 /* I think the point of this code is to avoid sending a
1099 * keepalive if we've used the session recently and therefore
1100 * think it's still alive. Unfortunately, most of the code
1101 * does not yet check for errors on the socket, and so if the
1102 * connection drops we don't notice until the timeout expires.
1103 * A better solution than sending a NOOP every time would be
1104 * for every command to be prepared to retry until it is
1105 * successfully sent. -- mbp */
1106 if ((time(NULL) - SESSION(session)->last_access_time > SESSION_TIMEOUT_INTERVAL) || session->cancelled) {
1107 /* verify that the session is still alive */
1108 r = imap_cmd_noop(session);
1110 if (r != MAILIMAP_NO_ERROR) {
1111 debug_print("disconnected!\n");
1112 if (!is_fatal(r))
1113 session = imap_reconnect_if_possible(folder, session);
1114 else {
1115 rfolder->session = NULL;
1116 rfolder->connecting = FALSE;
1117 SESSION(session)->state = SESSION_DISCONNECTED;
1118 SESSION(session)->sock = NULL;
1119 imap_safe_destroy(session);
1120 session = imap_session_get(folder);
1123 if (session)
1124 session->cancelled = FALSE;
1127 rfolder->session = SESSION(session);
1128 rfolder->connecting = FALSE;
1130 return IMAP_SESSION(session);
1133 static IMAPSession *imap_session_new(Folder * folder,
1134 const PrefsAccount *account)
1136 IMAPSession *session;
1137 gushort port;
1138 int r;
1139 int authenticated = FALSE;
1140 gchar *buf;
1142 #ifdef USE_GNUTLS
1143 /* FIXME: IMAP over SSL only... */
1144 SSLType ssl_type;
1146 port = account->set_imapport ? account->imapport
1147 : account->ssl_imap == SSL_TUNNEL ? IMAPS_PORT : IMAP4_PORT;
1148 ssl_type = account->ssl_imap;
1149 #else
1150 if (account->ssl_imap != SSL_NONE) {
1151 if (alertpanel_full(_("Insecure connection"),
1152 _("This connection is configured to be secured "
1153 "using SSL/TLS, but SSL/TLS is not available "
1154 "in this build of Claws Mail. \n\n"
1155 "Do you want to continue connecting to this "
1156 "server? The communication would not be "
1157 "secure."),
1158 GTK_STOCK_CANCEL, _("Con_tinue connecting"),
1159 NULL, FALSE, NULL, ALERT_WARNING,
1160 G_ALERTDEFAULT) != G_ALERTALTERNATE)
1161 return NULL;
1163 port = account->set_imapport ? account->imapport
1164 : IMAP4_PORT;
1165 #endif
1167 imap_init(folder);
1168 buf = g_strdup_printf(_("Account '%s': Connecting to IMAP server: %s:%d..."),
1169 folder->account->account_name, folder->account->recv_server,
1170 port);
1171 statuswindow_print_all("%s", buf);
1172 log_message(LOG_PROTOCOL, "%s\n", buf);
1173 g_free(buf);
1175 #ifndef G_OS_WIN32
1176 if (account->set_tunnelcmd) {
1177 r = imap_threaded_connect_cmd(folder,
1178 account->tunnelcmd,
1179 account->recv_server,
1180 port);
1182 else
1183 #endif
1185 #ifdef USE_GNUTLS
1186 if (ssl_type == SSL_TUNNEL) {
1187 r = imap_threaded_connect_ssl(folder,
1188 account->recv_server,
1189 port);
1191 else
1192 #endif
1194 r = imap_threaded_connect(folder,
1195 account->recv_server,
1196 port);
1200 statuswindow_pop_all();
1201 if (r == MAILIMAP_NO_ERROR_AUTHENTICATED) {
1202 authenticated = TRUE;
1204 else if (r == MAILIMAP_NO_ERROR_NON_AUTHENTICATED) {
1205 authenticated = FALSE;
1207 else {
1208 #ifdef USE_GNUTLS
1209 if (r == MAILIMAP_ERROR_SSL)
1210 log_error(LOG_PROTOCOL, _("SSL/TLS handshake failed\n"));
1211 else
1212 #endif
1213 imap_handle_error(NULL, account->recv_server, r);
1215 if(!prefs_common.no_recv_err_panel) {
1216 alertpanel_error_log(_("Can't connect to IMAP server: %s:%d"),
1217 account->recv_server, port);
1218 } else {
1219 log_error(LOG_PROTOCOL, _("Can't connect to IMAP server: %s:%d\n"),
1220 account->recv_server, port);
1223 return NULL;
1226 session = g_new0(IMAPSession, 1);
1227 session_init(SESSION(session), account, FALSE);
1228 SESSION(session)->type = SESSION_IMAP;
1229 SESSION(session)->server = g_strdup(account->recv_server);
1230 SESSION(session)->port = port;
1231 SESSION(session)->sock = NULL;
1233 SESSION(session)->destroy = imap_session_destroy;
1235 session->capability = NULL;
1237 session->authenticated = authenticated;
1238 session->mbox = NULL;
1239 session->exists = 0;
1240 session->recent = 0;
1241 session->expunge = 0;
1242 session->cmd_count = 0;
1243 session->folder = folder;
1244 IMAP_FOLDER(session->folder)->last_seen_separator = 0;
1246 #ifdef USE_GNUTLS
1247 if (account->ssl_imap == SSL_STARTTLS) {
1248 gint ok;
1250 ok = imap_cmd_starttls(session);
1251 if (ok != MAILIMAP_NO_ERROR) {
1252 log_warning(LOG_PROTOCOL, _("Can't start STARTTLS session.\n"));
1253 if (!is_fatal(ok)) {
1254 SESSION(session)->sock = NULL;
1255 imap_safe_destroy(session);
1257 return NULL;
1260 imap_free_capabilities(session);
1261 session->authenticated = FALSE;
1262 session->uidplus = FALSE;
1263 session->cmd_count = 1;
1265 #endif
1266 log_message(LOG_PROTOCOL, "IMAP connection is %s-authenticated\n",
1267 (session->authenticated) ? "pre" : "un");
1269 session_register_ping(SESSION(session), imap_ping);
1271 return session;
1274 static gint imap_session_authenticate(IMAPSession *session,
1275 PrefsAccount *account)
1277 gchar *pass, *acc_pass = NULL;
1278 gboolean failed = FALSE;
1279 gint ok = MAILIMAP_NO_ERROR;
1280 g_return_val_if_fail(account->userid != NULL, MAILIMAP_ERROR_BAD_STATE);
1282 if (!password_get(account->userid, account->recv_server, "imap",
1283 SESSION(session)->port, &acc_pass)) {
1284 acc_pass = passwd_store_get_account(account->account_id,
1285 PWS_ACCOUNT_RECV);
1288 try_again:
1289 pass = acc_pass;
1290 if (!pass && account->imap_auth_type != IMAP_AUTH_ANON && account->imap_auth_type != IMAP_AUTH_GSSAPI) {
1291 gchar *tmp_pass;
1292 tmp_pass = input_dialog_query_password_keep(account->recv_server,
1293 account->userid,
1294 &(account->session_passwd));
1295 if (!tmp_pass) {
1296 return MAILIMAP_NO_ERROR;
1298 Xstrdup_a(pass, tmp_pass, {g_free(tmp_pass); return MAILIMAP_NO_ERROR;});
1299 g_free(tmp_pass);
1300 } else if (account->imap_auth_type == IMAP_AUTH_ANON || account->imap_auth_type == IMAP_AUTH_GSSAPI) {
1301 pass = "";
1303 if ((ok = imap_auth(session, account->userid, pass, account->imap_auth_type)) != MAILIMAP_NO_ERROR) {
1305 if (!failed && !is_fatal(ok)) {
1306 if (acc_pass != NULL) {
1307 memset(acc_pass, 0, strlen(acc_pass));
1308 g_free(acc_pass);
1309 acc_pass = NULL;
1311 failed = TRUE;
1312 if (account->session_passwd != NULL) {
1313 g_free(account->session_passwd);
1314 account->session_passwd = NULL;
1316 goto try_again;
1317 } else {
1318 if (prefs_common.no_recv_err_panel) {
1319 log_error(LOG_PROTOCOL, _("Couldn't login to IMAP server %s.\n"), account->recv_server);
1320 mainwindow_show_error();
1321 } else
1322 alertpanel_error_log(_("Couldn't login to IMAP server %s."), account->recv_server);
1325 if (acc_pass != NULL) {
1326 g_free(acc_pass);
1327 memset(acc_pass, 0, strlen(acc_pass));
1330 return ok;
1333 if (acc_pass) {
1334 memset(acc_pass, 0, strlen(acc_pass));
1335 g_free(acc_pass);
1337 statuswindow_pop_all();
1338 session->authenticated = TRUE;
1339 return MAILIMAP_NO_ERROR;
1342 static void imap_session_destroy(Session *session)
1344 if (session->state != SESSION_DISCONNECTED)
1345 imap_threaded_disconnect(IMAP_SESSION(session)->folder);
1347 imap_free_capabilities(IMAP_SESSION(session));
1348 g_free(IMAP_SESSION(session)->mbox);
1351 static gchar *imap_fetch_msg(Folder *folder, FolderItem *item, gint uid)
1353 return imap_fetch_msg_full(folder, item, uid, TRUE, TRUE);
1356 static guint get_file_size_with_crs(const gchar *filename)
1358 FILE *fp = NULL;
1359 guint cnt = 0;
1360 gchar buf[4096];
1362 if (filename == NULL)
1363 return -1;
1365 fp = g_fopen(filename, "rb");
1366 if (!fp)
1367 return -1;
1369 while (fgets(buf, sizeof (buf), fp) != NULL) {
1370 cnt += strlen(buf);
1371 if (!strstr(buf, "\r\n") && strstr(buf, "\n"))
1372 cnt++;
1375 fclose(fp);
1376 return cnt;
1379 static gchar *imap_get_cached_filename(FolderItem *item, guint msgnum)
1381 gchar *path, *filename;
1383 cm_return_val_if_fail(item != NULL, NULL);
1385 path = folder_item_get_path(item);
1387 if (!is_dir_exist(path)) {
1388 g_free(path);
1389 return NULL;
1392 filename = g_strconcat(path, G_DIR_SEPARATOR_S, itos(msgnum), NULL);
1394 if (is_dir_exist(filename)) {
1395 g_free(filename);
1396 filename = g_strconcat(path, G_DIR_SEPARATOR_S, ".", itos(msgnum), NULL);
1398 g_free(path);
1400 return filename;
1403 static void imap_remove_cached_msg(Folder *folder, FolderItem *item, MsgInfo *msginfo)
1405 gchar *filename;
1407 filename = imap_get_cached_filename(item, msginfo->msgnum);
1409 cm_return_if_fail(filename != NULL);
1411 if (is_file_exist(filename)) {
1412 claws_unlink(filename);
1414 g_free(filename);
1417 typedef struct _TagsData {
1418 gchar *str;
1419 GSList *msglist;
1420 IMAPFolderItem *item;
1421 } TagsData;
1423 static void imap_commit_tags(FolderItem *item, MsgInfo *msginfo, GSList *tags_set, GSList *tags_unset)
1425 IMAPSession *session;
1426 gint ok, can_create_tags;
1427 Folder *folder = NULL;
1428 TagsData *ht_data = NULL;
1429 GSList *cur;
1431 g_return_if_fail(item != NULL);
1432 g_return_if_fail(msginfo != NULL);
1434 folder = item->folder;
1435 debug_print("getting session...\n");
1436 session = imap_session_get(folder);
1438 if (!session) {
1439 debug_print("can't get session\n");
1440 return;
1443 ok = imap_select(session, IMAP_FOLDER(folder), item,
1444 NULL, NULL, NULL, NULL, &can_create_tags, FALSE);
1446 if (ok != MAILIMAP_NO_ERROR) {
1447 return;
1451 if (IMAP_FOLDER_ITEM(item)->can_create_flags != ITEM_CAN_CREATE_FLAGS)
1452 return;
1454 if (IMAP_FOLDER_ITEM(item)->batching) {
1455 /* instead of performing an UID STORE command for each message change,
1456 * as a lot of them can change "together", we just fill in hashtables
1457 * and defer the treatment so that we're able to send only one
1458 * command.
1460 debug_print("IMAP batch mode on, deferring tags change\n");
1461 for (cur = tags_set; cur; cur = cur->next) {
1462 gint cur_tag = GPOINTER_TO_INT(cur->data);
1463 if (cur_tag) {
1464 ht_data = g_hash_table_lookup(IMAP_FOLDER_ITEM(item)->tags_set_table,
1465 GINT_TO_POINTER(cur_tag));
1466 if (ht_data == NULL) {
1467 ht_data = g_new0(TagsData, 1);
1468 ht_data->str = g_strdup(tags_get_tag(cur_tag));
1469 ht_data->item = IMAP_FOLDER_ITEM(item);
1470 g_hash_table_insert(IMAP_FOLDER_ITEM(item)->tags_set_table,
1471 GINT_TO_POINTER(cur_tag), ht_data);
1473 ht_data->msglist = g_slist_prepend(ht_data->msglist, GINT_TO_POINTER(msginfo->msgnum));
1476 for (cur = tags_unset; cur; cur = cur->next) {
1477 gint cur_tag = GPOINTER_TO_INT(cur->data);
1478 if (cur_tag) {
1479 ht_data = g_hash_table_lookup(IMAP_FOLDER_ITEM(item)->tags_unset_table,
1480 GINT_TO_POINTER(cur_tag));
1481 if (ht_data == NULL) {
1482 ht_data = g_new0(TagsData, 1);
1483 ht_data->str = g_strdup(tags_get_tag(cur_tag));
1484 ht_data->item = IMAP_FOLDER_ITEM(item);
1485 g_hash_table_insert(IMAP_FOLDER_ITEM(item)->tags_unset_table,
1486 GINT_TO_POINTER(cur_tag), ht_data);
1488 ht_data->msglist = g_slist_prepend(ht_data->msglist, GINT_TO_POINTER(msginfo->msgnum));
1491 } else {
1492 GSList *list_set = NULL;
1493 GSList *list_unset = NULL;
1494 GSList numlist;
1496 numlist.data = GINT_TO_POINTER(msginfo->msgnum);
1497 numlist.next = NULL;
1499 debug_print("IMAP changing tags NOW\n");
1500 for (cur = tags_set; cur; cur = cur->next) {
1501 gint cur_tag = GPOINTER_TO_INT(cur->data);
1502 const gchar *str = tags_get_tag(cur_tag);
1503 if (IS_NOT_RESERVED_TAG(str))
1504 list_set = g_slist_prepend(list_set, g_strdup(str));
1506 if (list_set) {
1507 ok = imap_set_message_flags(session,
1508 IMAP_FOLDER_ITEM(item), &numlist, 0, list_set, TRUE);
1509 slist_free_strings_full(list_set);
1510 if (ok != MAILIMAP_NO_ERROR) {
1511 return;
1515 for (cur = tags_unset; cur; cur = cur->next) {
1516 gint cur_tag = GPOINTER_TO_INT(cur->data);
1517 const gchar *str = tags_get_tag(cur_tag);
1518 if (IS_NOT_RESERVED_TAG(str))
1519 list_unset = g_slist_prepend(list_unset, g_strdup(str));
1521 if (list_unset) {
1522 ok = imap_set_message_flags(session,
1523 IMAP_FOLDER_ITEM(item), &numlist, 0, list_unset, FALSE);
1524 slist_free_strings_full(list_unset);
1525 if (ok != MAILIMAP_NO_ERROR) {
1526 return;
1532 static gchar *imap_fetch_msg_full(Folder *folder, FolderItem *item, gint uid,
1533 gboolean headers, gboolean body)
1535 gchar *path, *filename;
1536 IMAPSession *session;
1537 gint ok;
1539 g_return_val_if_fail(folder != NULL, NULL);
1540 g_return_val_if_fail(item != NULL, NULL);
1542 if (uid == 0)
1543 return NULL;
1545 path = folder_item_get_path(item);
1546 if (!is_dir_exist(path)) {
1547 if(is_file_exist(path))
1548 claws_unlink(path);
1549 make_dir_hier(path);
1551 g_free(path);
1553 filename = imap_get_cached_filename(item, uid);
1554 debug_print("trying to fetch cached %s\n", filename);
1556 if (is_file_exist(filename)) {
1557 /* see whether the local file represents the whole message
1558 * or not. As the IMAP server reports size with \r chars,
1559 * we have to update the local file (UNIX \n only) size */
1560 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1561 guint have_size = -1;
1563 if (cached)
1564 debug_print("message %d has been already %scached.\n", uid,
1565 MSG_IS_FULLY_CACHED(cached->flags) ? "fully ":"");
1567 if (!cached || !MSG_IS_FULLY_CACHED(cached->flags)) {
1568 have_size = get_file_size_with_crs(filename);
1569 if (cached && (cached->size <= have_size || !body)) {
1570 ok = file_strip_crs(filename);
1571 if (ok == 0 && cached && cached->size <= have_size) {
1572 /* we have it all and stripped */
1573 debug_print("...fully cached in fact (%u/%zd); setting flag.\n",
1574 have_size, cached->size);
1575 procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
1577 procmsg_msginfo_free(&cached);
1578 return filename;
1579 } else if (!cached && time(NULL) - get_file_mtime(filename) < 60) {
1580 debug_print("message not cached and file recent, considering file complete\n");
1581 ok = file_strip_crs(filename);
1582 if (ok == 0)
1583 return filename;
1584 } else {
1585 procmsg_msginfo_free(&cached);
1588 if (cached && MSG_IS_FULLY_CACHED(cached->flags)) {
1589 procmsg_msginfo_free(&cached);
1590 return filename;
1592 } else {
1593 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1594 if (cached) {
1595 procmsg_msginfo_unset_flags(cached, MSG_FULLY_CACHED, 0);
1596 procmsg_msginfo_free(&cached);
1600 debug_print("getting session...\n");
1601 session = imap_session_get(folder);
1603 if (!session) {
1604 g_free(filename);
1605 return NULL;
1607 session_set_access_time(SESSION(session));
1608 lock_session(session); /* unlocked later in the function */
1610 debug_print("IMAP fetching messages\n");
1611 ok = imap_select(session, IMAP_FOLDER(folder), item,
1612 NULL, NULL, NULL, NULL, NULL, FALSE);
1613 if (ok != MAILIMAP_NO_ERROR) {
1614 g_warning("can't select mailbox %s", item->path);
1615 g_free(filename);
1616 return NULL;
1619 session_set_access_time(SESSION(session));
1621 debug_print("getting message %d...\n", uid);
1622 ok = imap_cmd_fetch(session, (guint32)uid, filename, headers, body);
1624 if (ok != MAILIMAP_NO_ERROR) {
1625 g_warning("can't fetch message %d", uid);
1626 g_free(filename);
1627 return NULL;
1630 session_set_access_time(SESSION(session));
1631 unlock_session(session);
1633 ok = file_strip_crs(filename);
1635 if (ok == 0 && headers && body) {
1636 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1637 if (cached) {
1638 procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
1639 procmsg_msginfo_free(&cached);
1641 } else if (ok == -1) {
1642 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1643 if (cached) {
1644 procmsg_msginfo_unset_flags(cached, MSG_FULLY_CACHED, 0);
1645 procmsg_msginfo_free(&cached);
1648 return filename;
1651 static gboolean imap_is_msg_fully_cached(Folder *folder, FolderItem *item, gint uid)
1653 gchar *filename;
1654 guint size = 0;
1655 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1657 if (!cached)
1658 return FALSE;
1660 if (MSG_IS_FULLY_CACHED(cached->flags)) {
1661 procmsg_msginfo_free(&cached);
1662 return TRUE;
1665 filename = imap_get_cached_filename(item, uid);
1667 if (is_file_exist(filename)) {
1668 if (cached && cached->total_size == cached->size) {
1669 /* fast path */
1670 g_free(filename);
1671 procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
1672 return TRUE;
1674 size = get_file_size_with_crs(filename);
1676 g_free(filename);
1677 debug_print("msg %d cached, has size %d, full should be %zd.\n", uid, size, cached->size);
1678 if (cached && size >= cached->size) {
1679 cached->total_size = cached->size;
1680 procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
1681 procmsg_msginfo_free(&cached);
1682 return TRUE;
1684 if (cached)
1685 procmsg_msginfo_free(&cached);
1686 return FALSE;
1689 void imap_cache_msg(FolderItem *item, gint msgnum)
1691 Folder *folder = NULL;
1693 if (!item)
1694 return;
1695 folder = item->folder;
1697 if (!imap_is_msg_fully_cached(folder, item, msgnum)) {
1698 gchar *tmp = imap_fetch_msg_full(folder, item, msgnum, TRUE, TRUE);
1699 debug_print("fetched %s\n", tmp);
1700 g_free(tmp);
1704 static gint imap_add_msg(Folder *folder, FolderItem *dest,
1705 const gchar *file, MsgFlags *flags)
1707 gint ret;
1708 GSList file_list;
1709 MsgFileInfo fileinfo;
1711 g_return_val_if_fail(file != NULL, -1);
1713 fileinfo.msginfo = NULL;
1714 fileinfo.file = (gchar *)file;
1715 fileinfo.flags = flags;
1716 file_list.data = &fileinfo;
1717 file_list.next = NULL;
1719 ret = imap_add_msgs(folder, dest, &file_list, NULL);
1720 return ret;
1723 static gint imap_add_msgs(Folder *folder, FolderItem *dest, GSList *file_list,
1724 GHashTable *relation)
1726 gchar *destdir;
1727 IMAPSession *session;
1728 guint32 last_uid = 0;
1729 GSList *cur;
1730 MsgFileInfo *fileinfo;
1731 gint ok = MAILIMAP_NO_ERROR;
1732 gint curnum = 0, total = 0;
1733 gboolean missing_uids = FALSE;
1735 g_return_val_if_fail(folder != NULL, -1);
1736 g_return_val_if_fail(dest != NULL, -1);
1737 g_return_val_if_fail(file_list != NULL, -1);
1739 debug_print("getting session...\n");
1740 session = imap_session_get(folder);
1741 if (!session) {
1742 return -1;
1744 destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path, &ok);
1745 if (is_fatal(ok)) {
1746 g_free(destdir);
1747 return -1;
1749 statusbar_print_all(_("Adding messages..."));
1750 total = g_slist_length(file_list);
1751 for (cur = file_list; cur != NULL; cur = cur->next) {
1752 IMAPFlags iflags = 0;
1753 guint32 new_uid = 0;
1754 gchar *real_file = NULL;
1755 fileinfo = (MsgFileInfo *)cur->data;
1757 statusbar_progress_all(curnum, total, total < 10 ? 1:10);
1758 curnum++;
1760 if (fileinfo->flags) {
1761 if (MSG_IS_MARKED(*fileinfo->flags))
1762 iflags |= IMAP_FLAG_FLAGGED;
1763 if (MSG_IS_REPLIED(*fileinfo->flags))
1764 iflags |= IMAP_FLAG_ANSWERED;
1765 if (MSG_IS_FORWARDED(*fileinfo->flags))
1766 iflags |= IMAP_FLAG_FORWARDED;
1767 if (MSG_IS_SPAM(*fileinfo->flags))
1768 iflags |= IMAP_FLAG_SPAM;
1769 else
1770 iflags |= IMAP_FLAG_HAM;
1771 if (!MSG_IS_UNREAD(*fileinfo->flags))
1772 iflags |= IMAP_FLAG_SEEN;
1776 if (real_file == NULL)
1777 real_file = g_strdup(fileinfo->file);
1779 if (folder_has_parent_of_type(dest, F_QUEUE) ||
1780 folder_has_parent_of_type(dest, F_OUTBOX) ||
1781 folder_has_parent_of_type(dest, F_DRAFT) ||
1782 folder_has_parent_of_type(dest, F_TRASH))
1783 iflags |= IMAP_FLAG_SEEN;
1785 ok = imap_cmd_append(session, IMAP_FOLDER_ITEM(dest), destdir, real_file, iflags,
1786 &new_uid);
1788 if (ok != MAILIMAP_NO_ERROR) {
1789 g_warning("can't append message %s", real_file);
1790 g_free(real_file);
1791 g_free(destdir);
1792 statusbar_progress_all(0,0,0);
1793 statusbar_pop_all();
1794 return -1;
1795 } else {
1796 debug_print("appended new message as %d\n", new_uid);
1797 /* put the local file in the imapcache, so that we don't
1798 * have to fetch it back later. */
1800 if (new_uid == 0) {
1801 missing_uids = TRUE;
1802 debug_print("Missing UID (0)\n");
1804 if (new_uid > 0) {
1805 gchar *cache_path = folder_item_get_path(dest);
1806 if (!is_dir_exist(cache_path))
1807 make_dir_hier(cache_path);
1808 if (is_dir_exist(cache_path)) {
1809 gchar *cache_file = g_strconcat(
1810 cache_path, G_DIR_SEPARATOR_S,
1811 itos(new_uid), NULL);
1812 copy_file(real_file, cache_file, TRUE);
1813 debug_print("got UID %d, copied to cache: %s\n", new_uid, cache_file);
1814 g_free(cache_file);
1816 g_free(cache_path);
1820 if (relation != NULL)
1821 g_hash_table_insert(relation, fileinfo->msginfo != NULL ?
1822 (gpointer) fileinfo->msginfo : (gpointer) fileinfo,
1823 GINT_TO_POINTER(new_uid));
1824 if (last_uid < new_uid) {
1825 last_uid = new_uid;
1828 g_free(real_file);
1831 statusbar_progress_all(0,0,0);
1832 statusbar_pop_all();
1835 g_free(destdir);
1837 imap_scan_required(folder, dest);
1839 session = imap_session_get(folder);
1840 if (!session) {
1841 return -1;
1843 if (missing_uids) {
1844 gint a;
1845 ok = imap_select(session, IMAP_FOLDER(folder), dest,
1846 &a, NULL, NULL, NULL, NULL, FALSE);
1848 return last_uid;
1851 static GSList *flatten_mailimap_set(struct mailimap_set * set)
1853 GSList *result = NULL;
1854 clistiter *list;
1855 guint32 start, end, t;
1856 GSList *cur;
1858 if (!set || !set->set_list)
1859 return NULL;
1861 for (list = clist_begin(set->set_list); list; list = clist_next(list)) {
1862 struct mailimap_set_item *item = (struct mailimap_set_item *)clist_content(list);
1863 start = item->set_first;
1864 end = item->set_last;
1865 if (start <= end) {
1866 for (t = start; t <= end; t++) {
1867 result = g_slist_prepend(result, GINT_TO_POINTER(t));
1871 result = g_slist_reverse(result);
1872 if (debug_get_mode()) {
1873 debug_print("flat imap set: ");
1874 for (cur = result; cur; cur = cur->next) {
1875 debug_print("%d ", GPOINTER_TO_INT(cur->data));
1877 debug_print("\n");
1880 return result;
1882 static gint imap_do_copy_msgs(Folder *folder, FolderItem *dest,
1883 MsgInfoList *msglist, GHashTable *relation,
1884 gboolean same_dest_ok)
1886 FolderItem *src;
1887 gchar *destdir;
1888 GSList *seq_list, *cur;
1889 MsgInfo *msginfo;
1890 IMAPSession *session;
1891 gint ok = MAILIMAP_NO_ERROR;
1892 GHashTable *uid_hash;
1893 gint last_num = 0;
1895 g_return_val_if_fail(folder != NULL, -1);
1896 g_return_val_if_fail(dest != NULL, -1);
1897 g_return_val_if_fail(msglist != NULL, -1);
1899 debug_print("getting session...\n");
1900 session = imap_session_get(folder);
1902 if (!session) {
1903 return -1;
1906 msginfo = (MsgInfo *)msglist->data;
1907 src = msginfo->folder;
1908 if (!same_dest_ok && src == dest) {
1909 g_warning("the src folder is identical to the dest.");
1910 return -1;
1913 if (src->folder != dest->folder) {
1914 GSList *infolist = NULL, *cur;
1915 int res = -1;
1916 for (cur = msglist; cur; cur = cur->next) {
1917 msginfo = (MsgInfo *)cur->data;
1918 MsgFileInfo *fileinfo = g_new0(MsgFileInfo, 1);
1919 fileinfo->file = procmsg_get_message_file(msginfo);
1920 fileinfo->flags = &(msginfo->flags);
1921 infolist = g_slist_prepend(infolist, fileinfo);
1923 infolist = g_slist_reverse(infolist);
1924 res = folder_item_add_msgs(dest, infolist, FALSE);
1925 for (cur = infolist; cur; cur = cur->next) {
1926 MsgFileInfo *info = (MsgFileInfo *)cur->data;
1927 g_free(info->file);
1928 g_free(info);
1930 g_slist_free(infolist);
1931 return res;
1934 lock_session(session); /* unlocked later in the function */
1936 ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder,
1937 NULL, NULL, NULL, NULL, NULL, FALSE);
1938 if (ok != MAILIMAP_NO_ERROR) {
1939 return ok;
1942 unlock_session(session);
1944 destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path, &ok);
1946 if (is_fatal(ok)) {
1947 g_free(destdir);
1948 return ok;
1951 seq_list = imap_get_lep_set_from_msglist(IMAP_FOLDER(folder), msglist);
1952 uid_hash = g_hash_table_new(g_direct_hash, g_direct_equal);
1954 statusbar_print_all(_("Copying messages..."));
1955 for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
1956 struct mailimap_set * seq_set;
1957 struct mailimap_set * source = NULL;
1958 struct mailimap_set * dest = NULL;
1959 seq_set = cur->data;
1961 debug_print("Copying messages from %s to %s ...\n",
1962 src->path, destdir);
1964 lock_session(session); /* unlocked later in the function */
1965 ok = imap_cmd_copy(session, seq_set, destdir,
1966 &source, &dest);
1968 if (is_fatal(ok)) {
1969 session = NULL;
1972 if (ok == MAILIMAP_NO_ERROR) {
1973 unlock_session(session);
1974 if (relation && source && dest) {
1975 GSList *s_list = flatten_mailimap_set(source);
1976 GSList *d_list = flatten_mailimap_set(dest);
1977 GSList *s_cur, *d_cur;
1978 if (g_slist_length(s_list) == g_slist_length(d_list)) {
1980 for (s_cur = s_list, d_cur = d_list;
1981 s_cur && d_cur;
1982 s_cur = s_cur->next, d_cur = d_cur->next) {
1983 g_hash_table_insert(uid_hash, s_cur->data, d_cur->data);
1986 } else {
1987 debug_print("hhhmm, source list length != dest list length.\n");
1989 g_slist_free(s_list);
1990 g_slist_free(d_list);
1995 if (source)
1996 mailimap_set_free(source);
1997 if (dest)
1998 mailimap_set_free(dest);
2000 if (ok != MAILIMAP_NO_ERROR) {
2001 g_hash_table_destroy(uid_hash);
2002 imap_lep_set_free(seq_list);
2003 statusbar_pop_all();
2004 return -1;
2008 for (cur = msglist; cur != NULL; cur = g_slist_next(cur)) {
2009 MsgInfo *msginfo = (MsgInfo *)cur->data;
2010 gpointer hashval;
2012 hashval = g_hash_table_lookup(uid_hash, GINT_TO_POINTER(msginfo->msgnum));
2014 if (hashval != NULL) {
2015 gint num = GPOINTER_TO_INT(hashval);
2016 g_hash_table_insert(relation, msginfo,
2017 GINT_TO_POINTER(num));
2018 if (num > last_num)
2019 last_num = num;
2020 debug_print("copied message %d as %d\n", msginfo->msgnum, num);
2021 /* put the local file in the imapcache, so that we don't
2022 * have to fetch it back later. */
2023 if (num > 0) {
2024 gchar *cache_path = folder_item_get_path(msginfo->folder);
2025 gchar *real_file = g_strconcat(
2026 cache_path, G_DIR_SEPARATOR_S,
2027 itos(msginfo->msgnum), NULL);
2028 gchar *cache_file = NULL;
2029 g_free(cache_path);
2030 cache_path = folder_item_get_path(dest);
2031 cache_file = g_strconcat(
2032 cache_path, G_DIR_SEPARATOR_S,
2033 itos(num), NULL);
2034 if (!is_dir_exist(cache_path))
2035 make_dir_hier(cache_path);
2036 if (is_file_exist(real_file) && is_dir_exist(cache_path)) {
2037 if (copy_file(real_file, cache_file, TRUE) < 0)
2038 debug_print("couldn't cache to %s: %s\n", cache_file,
2039 strerror(errno));
2040 else
2041 debug_print("copied to cache: %s\n", cache_file);
2043 g_free(real_file);
2044 g_free(cache_file);
2045 g_free(cache_path);
2047 } else
2048 g_hash_table_insert(relation, msginfo,
2049 GINT_TO_POINTER(0));
2051 statusbar_pop_all();
2053 g_hash_table_destroy(uid_hash);
2054 imap_lep_set_free(seq_list);
2056 g_free(destdir);
2058 IMAP_FOLDER_ITEM(dest)->lastuid = 0;
2059 IMAP_FOLDER_ITEM(dest)->uid_next = 0;
2060 g_slist_free(IMAP_FOLDER_ITEM(dest)->uid_list);
2061 IMAP_FOLDER_ITEM(dest)->uid_list = NULL;
2063 imap_scan_required(folder, dest);
2064 if (ok == MAILIMAP_NO_ERROR)
2065 return last_num;
2066 else
2067 return -1;
2070 static gint imap_copy_msg(Folder *folder, FolderItem *dest, MsgInfo *msginfo)
2072 GSList msglist;
2074 g_return_val_if_fail(msginfo != NULL, -1);
2076 msglist.data = msginfo;
2077 msglist.next = NULL;
2079 return imap_copy_msgs(folder, dest, &msglist, NULL);
2082 static gint imap_copy_msgs(Folder *folder, FolderItem *dest,
2083 MsgInfoList *msglist, GHashTable *relation)
2085 MsgInfo *msginfo;
2086 gint ret;
2088 g_return_val_if_fail(folder != NULL, -1);
2089 g_return_val_if_fail(dest != NULL, -1);
2090 g_return_val_if_fail(msglist != NULL, -1);
2092 msginfo = (MsgInfo *)msglist->data;
2093 g_return_val_if_fail(msginfo->folder != NULL, -1);
2095 ret = imap_do_copy_msgs(folder, dest, msglist, relation, FALSE);
2096 return ret;
2099 static gboolean imap_matcher_type_is_local(gint matchertype)
2101 switch (matchertype) {
2102 case MATCHCRITERIA_FROM:
2103 case MATCHCRITERIA_TO:
2104 case MATCHCRITERIA_CC:
2105 case MATCHCRITERIA_TO_OR_CC:
2106 case MATCHCRITERIA_SUBJECT:
2107 case MATCHCRITERIA_REFERENCES:
2108 case MATCHCRITERIA_MESSAGEID:
2109 case MATCHCRITERIA_INREPLYTO:
2110 case MATCHCRITERIA_AGE_GREATER:
2111 case MATCHCRITERIA_AGE_LOWER:
2112 case MATCHCRITERIA_FORWARDED:
2113 case MATCHCRITERIA_SPAM:
2114 case MATCHCRITERIA_UNREAD:
2115 case MATCHCRITERIA_NEW:
2116 case MATCHCRITERIA_MARKED:
2117 case MATCHCRITERIA_REPLIED:
2118 case MATCHCRITERIA_DELETED:
2119 case MATCHCRITERIA_SIZE_GREATER:
2120 case MATCHCRITERIA_SIZE_SMALLER:
2121 case MATCHCRITERIA_SIZE_EQUAL:
2122 return TRUE;
2124 return FALSE;
2127 static IMAPSearchKey* search_make_key(MatcherProp* match, gboolean* is_all)
2129 if (match->matchtype == MATCHTYPE_MATCHCASE || match->matchtype == MATCHTYPE_MATCH) {
2130 IMAPSearchKey* result = NULL;
2131 gboolean invert = FALSE;
2132 gint matchertype = match->criteria;
2134 if (is_all) {
2135 *is_all = FALSE;
2138 switch (matchertype) {
2139 case MATCHCRITERIA_NOT_NEW: invert = TRUE; matchertype = MATCHCRITERIA_NEW; break;
2140 case MATCHCRITERIA_NOT_MARKED: invert = TRUE; matchertype = MATCHCRITERIA_MARKED; break;
2141 case MATCHCRITERIA_NOT_FORWARDED: invert = TRUE; matchertype = MATCHCRITERIA_FORWARDED; break;
2142 case MATCHCRITERIA_NOT_SPAM: invert = TRUE; matchertype = MATCHCRITERIA_SPAM; break;
2143 case MATCHCRITERIA_NOT_SUBJECT: invert = TRUE; matchertype = MATCHCRITERIA_SUBJECT; break;
2144 case MATCHCRITERIA_NOT_FROM: invert = TRUE; matchertype = MATCHCRITERIA_FROM; break;
2145 case MATCHCRITERIA_NOT_TO: invert = TRUE; matchertype = MATCHCRITERIA_TO; break;
2146 case MATCHCRITERIA_NOT_CC: invert = TRUE; matchertype = MATCHCRITERIA_CC; break;
2147 case MATCHCRITERIA_NOT_REFERENCES: invert = TRUE; matchertype = MATCHCRITERIA_REFERENCES; break;
2148 case MATCHCRITERIA_NOT_HEADER: invert = TRUE; matchertype = MATCHCRITERIA_HEADER; break;
2149 case MATCHCRITERIA_NOT_TAG: invert = TRUE; matchertype = MATCHCRITERIA_TAG; break;
2150 case MATCHCRITERIA_NOT_HEADERS_PART: invert = TRUE; matchertype = MATCHCRITERIA_HEADERS_PART; break;
2151 case MATCHCRITERIA_NOT_HEADERS_CONT: invert = TRUE; matchertype = MATCHCRITERIA_HEADERS_CONT; break;
2152 case MATCHCRITERIA_NOT_MESSAGE: invert = TRUE; matchertype = MATCHCRITERIA_MESSAGE; break;
2153 case MATCHCRITERIA_NOT_BODY_PART: invert = TRUE; matchertype = MATCHCRITERIA_BODY_PART; break;
2154 case MATCHCRITERIA_NOT_TO_AND_NOT_CC: invert = TRUE; matchertype = MATCHCRITERIA_TO_OR_CC; break;
2155 case MATCHCRITERIA_NOT_MESSAGEID: invert = TRUE; matchertype = MATCHCRITERIA_MESSAGEID; break;
2156 case MATCHCRITERIA_NOT_INREPLYTO: invert = TRUE; matchertype = MATCHCRITERIA_INREPLYTO; break;
2160 * this aborts conversion even for predicates understood by the following code.
2161 * while that might seem wasteful, claws local search for information listed below
2162 * has proven faster than IMAP search plus network roundtrips. once this changes,
2163 * consider removing these exceptions.
2165 if (imap_matcher_type_is_local(matchertype))
2166 return NULL;
2168 /* the Message-ID header is also cached */
2169 if (matchertype == MATCHCRITERIA_HEADER && g_strcmp0("Message-ID", match->header) == 0) {
2170 return NULL;
2173 switch (matchertype) {
2174 case MATCHCRITERIA_FORWARDED:
2175 result = imap_search_new(IMAP_SEARCH_CRITERIA_TAG, NULL, RTAG_FORWARDED, 0);
2176 break;
2178 case MATCHCRITERIA_SPAM:
2179 result = imap_search_new(IMAP_SEARCH_CRITERIA_TAG, NULL, RTAG_JUNK, 0);
2180 break;
2182 case MATCHCRITERIA_MESSAGEID:
2183 result = imap_search_new(IMAP_SEARCH_CRITERIA_HEADER, "Message-ID", match->expr, 0);
2184 break;
2186 case MATCHCRITERIA_INREPLYTO:
2187 result = imap_search_new(IMAP_SEARCH_CRITERIA_HEADER, "In-Reply-To", match->expr, 0);
2188 break;
2190 case MATCHCRITERIA_REFERENCES:
2191 result = imap_search_new(IMAP_SEARCH_CRITERIA_HEADER, "References", match->expr, 0);
2192 break;
2194 case MATCHCRITERIA_TO_OR_CC:
2195 result = imap_search_or(
2196 imap_search_new(IMAP_SEARCH_CRITERIA_TO, NULL, match->expr, 0),
2197 imap_search_new(IMAP_SEARCH_CRITERIA_CC, NULL, match->expr, 0)
2199 break;
2201 case MATCHCRITERIA_HEADERS_PART:
2202 case MATCHCRITERIA_HEADERS_CONT:
2203 result = imap_search_and(
2204 imap_search_not(imap_search_new(IMAP_SEARCH_CRITERIA_BODY, NULL, match->expr, 0)),
2205 imap_search_new(IMAP_SEARCH_CRITERIA_MESSAGE, NULL, match->expr, 0)
2207 break;
2209 case MATCHCRITERIA_SIZE_EQUAL:
2210 result = imap_search_and(
2211 imap_search_not(imap_search_new(IMAP_SEARCH_CRITERIA_SIZE_SMALLER, NULL, NULL, match->value)),
2212 imap_search_not(imap_search_new(IMAP_SEARCH_CRITERIA_SIZE_GREATER, NULL, NULL, match->value))
2214 break;
2216 case MATCHCRITERIA_NOT_UNREAD:
2217 result = imap_search_new(IMAP_SEARCH_CRITERIA_READ, NULL, NULL, 0);
2218 break;
2220 case MATCHCRITERIA_UNREAD:
2221 result = imap_search_new(IMAP_SEARCH_CRITERIA_UNREAD, NULL, NULL, 0);
2222 break;
2224 case MATCHCRITERIA_NEW:
2225 result = imap_search_new(IMAP_SEARCH_CRITERIA_NEW, NULL, NULL, 0);
2226 break;
2228 case MATCHCRITERIA_MARKED:
2229 result = imap_search_new(IMAP_SEARCH_CRITERIA_MARKED, NULL, NULL, 0);
2230 break;
2232 case MATCHCRITERIA_DELETED:
2233 result = imap_search_new(IMAP_SEARCH_CRITERIA_DELETED, NULL, NULL, 0);
2234 break;
2236 case MATCHCRITERIA_REPLIED:
2237 result = imap_search_new(IMAP_SEARCH_CRITERIA_REPLIED, NULL, NULL, 0);
2238 break;
2240 case MATCHCRITERIA_TAG:
2242 gchar *tmp = imap_utf8_to_modified_utf7(match->expr, TRUE);
2243 result = imap_search_new(IMAP_SEARCH_CRITERIA_TAG, NULL, tmp, 0);
2244 g_free(tmp);
2246 break;
2248 case MATCHCRITERIA_SUBJECT:
2249 result = imap_search_new(IMAP_SEARCH_CRITERIA_SUBJECT, NULL, match->expr, 0);
2250 break;
2252 case MATCHCRITERIA_FROM:
2253 result = imap_search_new(IMAP_SEARCH_CRITERIA_FROM, NULL, match->expr, 0);
2254 break;
2256 case MATCHCRITERIA_TO:
2257 result = imap_search_new(IMAP_SEARCH_CRITERIA_TO, NULL, match->expr, 0);
2258 break;
2260 case MATCHCRITERIA_CC:
2261 result = imap_search_new(IMAP_SEARCH_CRITERIA_CC, NULL, match->expr, 0);
2262 break;
2264 case MATCHCRITERIA_AGE_GREATER:
2265 result = imap_search_new(IMAP_SEARCH_CRITERIA_AGE_GREATER, NULL, NULL, match->value);
2266 break;
2268 case MATCHCRITERIA_AGE_LOWER:
2269 result = imap_search_new(IMAP_SEARCH_CRITERIA_AGE_LOWER, NULL, NULL, match->value);
2270 break;
2272 case MATCHCRITERIA_BODY_PART:
2273 result = imap_search_new(IMAP_SEARCH_CRITERIA_BODY, NULL, match->expr, 0);
2274 break;
2276 case MATCHCRITERIA_MESSAGE:
2277 result = imap_search_new(IMAP_SEARCH_CRITERIA_MESSAGE, NULL, match->expr, 0);
2278 break;
2280 case MATCHCRITERIA_HEADER:
2281 result = imap_search_new(IMAP_SEARCH_CRITERIA_HEADER, match->header, match->expr, 0);
2282 break;
2284 case MATCHCRITERIA_SIZE_GREATER:
2285 result = imap_search_new(IMAP_SEARCH_CRITERIA_SIZE_GREATER, NULL, NULL, match->value);
2286 break;
2288 case MATCHCRITERIA_SIZE_SMALLER:
2289 result = imap_search_new(IMAP_SEARCH_CRITERIA_SIZE_SMALLER, NULL, NULL, match->value);
2290 break;
2292 default:
2293 result = imap_search_new(IMAP_SEARCH_CRITERIA_ALL, NULL, NULL, 0);
2294 if (is_all) {
2295 *is_all = TRUE;
2297 break;
2300 if (invert) {
2301 result = imap_search_not(result);
2302 if (is_all && *is_all) {
2303 *is_all = FALSE;
2307 return result;
2310 return NULL;
2313 static void imap_change_search_charset(IMAPFolder *folder)
2315 /* If server supports charset in searches, but the last used one failed,
2316 * changed to the next preferred charset. If none are still available,
2317 * disable charset searches.
2318 * Charsets are tried in the following order:
2319 * UTF-8, locale's charset, UTF-7.
2322 if (folder->search_charset_supported) {
2323 if (folder->search_charset && !strcmp(folder->search_charset, conv_get_locale_charset_str_no_utf8()))
2324 folder->search_charset = "UTF-8";
2325 else if (folder->search_charset && !strcmp(folder->search_charset, "UTF-8"))
2326 folder->search_charset = "UTF-7";
2327 else {
2328 folder->search_charset = NULL;
2329 folder->search_charset_supported = FALSE;
2334 static MatcherProp *imap_matcher_prop_set_charset(IMAPFolder *folder,
2335 MatcherProp *utf8_prop,
2336 gchar **charset)
2338 /* If the match is going to be done locally, or the criteria is on
2339 * tag (special-cased to modified-UTF-7), or the expression searched
2340 * is ASCII, don't bother converting.
2342 if (imap_matcher_type_is_local(utf8_prop->criteria)
2343 || utf8_prop->criteria == MATCHCRITERIA_TAG
2344 || utf8_prop->criteria == MATCHCRITERIA_NOT_TAG
2345 || utf8_prop->expr == NULL
2346 || is_ascii_str(utf8_prop->expr))
2347 return matcherprop_new(utf8_prop->criteria,
2348 utf8_prop->header,
2349 utf8_prop->matchtype,
2350 utf8_prop->expr,
2351 utf8_prop->value);
2352 else {
2353 gchar *conv_expr = NULL;
2355 /* If the search is server-side and the server doesn't support
2356 * searching with the charsets we handle, bail out.
2358 if (folder->search_charset_supported == FALSE)
2359 return NULL;
2361 /* Else, convert. */
2362 if (*charset == NULL)
2363 *charset = g_strdup(folder->search_charset);
2365 conv_expr = conv_codeset_strdup(utf8_prop->expr, CS_UTF_8, *charset);
2367 if (conv_expr == NULL)
2368 conv_expr = g_strdup(utf8_prop->expr);
2370 return matcherprop_new(utf8_prop->criteria,
2371 utf8_prop->header,
2372 utf8_prop->matchtype,
2373 conv_expr,
2374 utf8_prop->value);
2378 static gint search_msgs (Folder *folder,
2379 FolderItem *container,
2380 MsgNumberList **msgs,
2381 gboolean *on_server,
2382 MatcherList *predicate,
2383 SearchProgressNotify progress_cb,
2384 gpointer progress_data)
2386 IMAPSearchKey* key = NULL;
2387 GSList* cur;
2388 int result = -1;
2389 clist* uidlist = NULL;
2390 gboolean server_filtering_useless = FALSE;
2391 IMAPSession *session;
2392 gchar *charset_to_use = NULL;
2394 if (on_server == NULL || !*on_server) {
2395 return folder_item_search_msgs_local(folder, container, msgs, on_server,
2396 predicate, progress_cb, progress_data);
2399 for (cur = predicate->matchers; cur != NULL; cur = cur->next) {
2400 IMAPSearchKey* matcherPart = NULL;
2401 MatcherProp* prop = (MatcherProp*) cur->data;
2402 gboolean is_all;
2403 MatcherProp *imap_prop = imap_matcher_prop_set_charset(IMAP_FOLDER(folder), prop, &charset_to_use);
2405 if (imap_prop == NULL) {
2406 /* Couldn't convert matcherprop to IMAP - probably not ascii
2407 * and server doesn't support the charsets we do. */
2408 return -1;
2411 matcherPart = search_make_key(imap_prop, &is_all);
2413 matcherprop_free(imap_prop);
2415 if (on_server) {
2416 *on_server &= matcherPart != NULL && prop->matchtype == MATCHTYPE_MATCHCASE;
2419 if (matcherPart) {
2420 if (key == NULL) {
2421 key = matcherPart;
2422 server_filtering_useless = is_all;
2423 } else if (predicate->bool_and) {
2424 key = imap_search_and(key, matcherPart);
2425 server_filtering_useless &= is_all;
2426 } else {
2427 key = imap_search_or(key, matcherPart);
2428 server_filtering_useless |= is_all;
2433 if (server_filtering_useless) {
2434 imap_search_free(key);
2435 key = NULL;
2438 if (key == NULL && progress_cb != NULL) {
2439 GSList* cur;
2440 GSList* list;
2441 int count = 0;
2443 progress_cb(progress_data, TRUE, 0, 0, container->total_msgs);
2444 progress_cb(progress_data, TRUE, container->total_msgs, 0, container->total_msgs);
2446 list = folder_item_get_msg_list(container);
2447 for (cur = list; cur != NULL; cur = cur->next) {
2448 *msgs = g_slist_prepend(*msgs, GUINT_TO_POINTER(((MsgInfo*) cur->data)->msgnum));
2449 count++;
2451 procmsg_msg_list_free(list);
2453 *msgs = g_slist_reverse(*msgs);
2455 return count;
2458 session = imap_session_get(folder);
2459 if (!session) {
2460 return -1;
2462 result = imap_select(session, IMAP_FOLDER(folder), FOLDER_ITEM(container),
2463 NULL, NULL, NULL, NULL, NULL, TRUE);
2464 if (result != MAILIMAP_NO_ERROR)
2465 return -1;
2467 if (progress_cb)
2468 progress_cb(progress_data, TRUE, 0, 0, container->total_msgs);
2469 result = imap_threaded_search(folder, IMAP_SEARCH_TYPE_KEYED, key, charset_to_use, NULL, &uidlist);
2470 if (progress_cb)
2471 progress_cb(progress_data, TRUE, container->total_msgs, 0, container->total_msgs);
2473 if (result == MAILIMAP_NO_ERROR) {
2474 gint result = 0;
2476 *msgs = imap_uid_list_from_lep(uidlist, &result);
2478 mailimap_search_result_free(uidlist);
2480 if (charset_to_use != NULL)
2481 g_free(charset_to_use);
2483 return result;
2484 } else if (charset_to_use != NULL) {
2485 /* If search failed and was on an 8-bit string, try the next
2486 * available charset to search if there still are some.
2488 g_free(charset_to_use);
2490 imap_change_search_charset(IMAP_FOLDER(folder));
2491 if (IMAP_FOLDER(folder)->search_charset_supported)
2492 return search_msgs(folder, container, msgs, on_server, predicate,
2493 progress_cb, progress_data);
2494 else
2495 return -1;
2496 } else {
2497 return -1;
2502 static gint imap_do_remove_msgs(Folder *folder, FolderItem *dest,
2503 MsgInfoList *msglist, GHashTable *relation)
2505 gchar *destdir, *dir;
2506 GSList *numlist = NULL, *cur;
2507 MsgInfo *msginfo;
2508 IMAPSession *session;
2509 gint ok = MAILIMAP_NO_ERROR;
2511 g_return_val_if_fail(folder != NULL, -1);
2512 g_return_val_if_fail(dest != NULL, -1);
2513 g_return_val_if_fail(msglist != NULL, -1);
2515 debug_print("getting session...\n");
2516 session = imap_session_get(folder);
2517 if (!session) {
2518 return -1;
2521 lock_session(session); /* unlocked later in the function */
2523 msginfo = (MsgInfo *)msglist->data;
2525 ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder,
2526 NULL, NULL, NULL, NULL, NULL, FALSE);
2527 if (ok != MAILIMAP_NO_ERROR) {
2528 return ok;
2531 destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path, &ok);
2532 if (is_fatal(ok)) {
2533 g_free(destdir);
2534 return ok;
2536 for (cur = msglist; cur; cur = cur->next) {
2537 msginfo = (MsgInfo *)cur->data;
2538 if (!MSG_IS_DELETED(msginfo->flags))
2539 numlist = g_slist_prepend(numlist, GINT_TO_POINTER(msginfo->msgnum));
2541 numlist = g_slist_reverse(numlist);
2543 if (numlist != NULL) {
2544 ok = imap_set_message_flags
2545 (session, IMAP_FOLDER_ITEM(msginfo->folder), numlist, IMAP_FLAG_DELETED, NULL, TRUE);
2546 if (ok != MAILIMAP_NO_ERROR) {
2547 log_warning(LOG_PROTOCOL, _("can't set deleted flags\n"));
2548 g_free(destdir);
2549 return ok;
2551 } /* else we just need to expunge */
2552 ok = imap_cmd_expunge(session);
2553 if (ok != MAILIMAP_NO_ERROR) {
2554 log_warning(LOG_PROTOCOL, _("can't expunge\n"));
2555 g_free(destdir);
2556 return ok;
2559 session->folder_content_changed = TRUE;
2560 unlock_session(session);
2562 dir = folder_item_get_path(msginfo->folder);
2563 if (is_dir_exist(dir)) {
2564 for (cur = msglist; cur; cur = cur->next) {
2565 msginfo = (MsgInfo *)cur->data;
2566 remove_numbered_files(dir, msginfo->msgnum, msginfo->msgnum);
2569 g_free(dir);
2571 g_slist_free(numlist);
2573 imap_scan_required(folder, dest);
2575 g_free(destdir);
2577 return 0;
2580 static gint imap_remove_msgs(Folder *folder, FolderItem *dest,
2581 MsgInfoList *msglist, GHashTable *relation)
2583 MsgInfo *msginfo;
2585 g_return_val_if_fail(folder != NULL, -1);
2586 g_return_val_if_fail(dest != NULL, -1);
2587 if (msglist == NULL)
2588 return 0;
2590 msginfo = (MsgInfo *)msglist->data;
2591 g_return_val_if_fail(msginfo->folder != NULL, -1);
2593 return imap_do_remove_msgs(folder, dest, msglist, relation);
2596 static gint imap_remove_all_msg(Folder *folder, FolderItem *item)
2598 GSList *list = folder_item_get_msg_list(item);
2599 gint res = imap_remove_msgs(folder, item, list, NULL);
2600 procmsg_msg_list_free(list);
2601 return res;
2604 static gboolean imap_is_msg_changed(Folder *folder, FolderItem *item,
2605 MsgInfo *msginfo)
2607 /* TODO: properly implement this method */
2608 return FALSE;
2611 static gint imap_close(Folder *folder, FolderItem *item)
2613 return 0;
2616 static gint imap_scan_tree_real(Folder *folder, gboolean subs_only)
2618 FolderItem *item = NULL;
2619 IMAPSession *session;
2620 gchar *root_folder = NULL;
2622 g_return_val_if_fail(folder != NULL, -1);
2623 g_return_val_if_fail(folder->account != NULL, -1);
2625 debug_print("getting session...\n");
2626 session = imap_session_get(folder);
2627 if (!session) {
2628 if (!folder->node) {
2629 folder_tree_destroy(folder);
2630 item = folder_item_new(folder, folder->name, NULL);
2631 item->folder = folder;
2632 folder->node = item->node = g_node_new(item);
2634 return -1;
2637 if (folder->account->imap_dir && *folder->account->imap_dir) {
2638 gchar *real_path;
2639 int r = MAILIMAP_NO_ERROR;
2640 clist * lep_list;
2642 Xstrdup_a(root_folder, folder->account->imap_dir, {return -1;});
2643 extract_quote(root_folder, '"');
2644 subst_char(root_folder,
2645 imap_get_path_separator(session, IMAP_FOLDER(folder),
2646 root_folder, &r),
2647 '/');
2648 if (is_fatal(r))
2649 return -1;
2650 strtailchomp(root_folder, '/');
2651 real_path = imap_get_real_path
2652 (session, IMAP_FOLDER(folder), root_folder, &r);
2653 if (is_fatal(r)) {
2654 g_free(real_path);
2655 return -1;
2657 debug_print("IMAP root directory: %s\n", real_path);
2659 /* check if root directory exist */
2661 r = imap_threaded_list(session->folder, "", real_path,
2662 &lep_list);
2664 if (r != MAILIMAP_NO_ERROR)
2665 imap_handle_error(SESSION(session), NULL, r);
2667 if ((r != MAILIMAP_NO_ERROR) || (clist_count(lep_list) == 0)) {
2668 if (!folder->node) {
2669 item = folder_item_new(folder, folder->name, NULL);
2670 item->folder = folder;
2671 folder->node = item->node = g_node_new(item);
2673 return -1;
2675 mailimap_list_result_free(lep_list);
2677 g_free(real_path);
2680 if (folder->node)
2681 item = FOLDER_ITEM(folder->node->data);
2683 if (item && !item->path && root_folder) {
2684 item->path = g_strdup(root_folder);
2687 if (!item || ((item->path || root_folder) &&
2688 strcmp2(item->path, root_folder) != 0)) {
2689 folder_tree_destroy(folder);
2690 item = folder_item_new(folder, folder->name, root_folder);
2691 item->folder = folder;
2692 folder->node = item->node = g_node_new(item);
2695 imap_scan_tree_recursive(session, FOLDER_ITEM(folder->node->data), subs_only);
2696 imap_create_missing_folders(folder);
2698 return 0;
2701 static gint imap_scan_tree(Folder *folder)
2703 gboolean subs_only = FALSE;
2704 if (folder->account) {
2705 debug_print(" scanning only subs %d\n", folder->account->imap_subsonly);
2706 subs_only = folder->account->imap_subsonly;
2708 return imap_scan_tree_real(folder, subs_only);
2711 static gint imap_scan_tree_recursive(IMAPSession *session, FolderItem *item, gboolean subs_only)
2713 Folder *folder;
2714 IMAPFolder *imapfolder;
2715 FolderItem *new_item;
2716 GSList *item_list, *cur;
2717 GNode *node;
2718 gchar *real_path;
2719 gchar *wildcard_path;
2720 gchar separator;
2721 gchar wildcard[3];
2722 clist * lep_list;
2723 int r = MAILIMAP_NO_ERROR;
2725 g_return_val_if_fail(item != NULL, -1);
2726 g_return_val_if_fail(item->folder != NULL, -1);
2727 g_return_val_if_fail(item->no_sub == FALSE, -1);
2729 folder = item->folder;
2730 imapfolder = IMAP_FOLDER(folder);
2732 separator = imap_get_path_separator(session, imapfolder, item->path, &r);
2733 if (is_fatal(r))
2734 return r;
2736 if (folder->ui_func)
2737 folder->ui_func(folder, item, folder->ui_func_data);
2739 if (item->path) {
2740 wildcard[0] = separator;
2741 wildcard[1] = '%';
2742 wildcard[2] = '\0';
2743 real_path = imap_get_real_path(session, imapfolder, item->path, &r);
2744 if (is_fatal(r)) {
2745 g_free(real_path);
2746 return r;
2748 } else {
2749 wildcard[0] = '%';
2750 wildcard[1] = '\0';
2751 real_path = g_strdup("");
2754 Xstrcat_a(wildcard_path, real_path, wildcard,
2755 {g_free(real_path); return MAILIMAP_ERROR_BAD_STATE;});
2756 lep_list = NULL;
2758 if (subs_only)
2759 r = imap_threaded_lsub(folder, "", wildcard_path, &lep_list);
2760 else
2761 r = imap_threaded_list(folder, "", wildcard_path, &lep_list);
2763 if (r != MAILIMAP_NO_ERROR) {
2764 imap_handle_error(SESSION(session), NULL, r);
2765 item_list = NULL;
2766 g_free(real_path);
2767 return r;
2769 else {
2770 item_list = imap_list_from_lep(imapfolder,
2771 lep_list, real_path, FALSE);
2772 mailimap_list_result_free(lep_list);
2775 g_free(real_path);
2777 node = item->node->children;
2778 while (node != NULL) {
2779 FolderItem *old_item = FOLDER_ITEM(node->data);
2780 GNode *next = node->next;
2782 new_item = NULL;
2783 for (cur = item_list; cur != NULL; cur = cur->next) {
2784 FolderItem *cur_item = FOLDER_ITEM(cur->data);
2785 if (!strcmp2(old_item->path, cur_item->path)) {
2786 new_item = cur_item;
2787 break;
2790 if (!new_item) {
2791 if (old_item && old_item->path && !strcasecmp(old_item->path, "INBOX")) {
2792 debug_print("not removing INBOX\n");
2793 } else {
2794 debug_print("folder '%s' not found. removing...\n",
2795 old_item->path);
2796 folder_item_remove(old_item);
2798 } else {
2799 old_item->no_sub = new_item->no_sub;
2800 old_item->no_select = new_item->no_select;
2801 if (old_item->no_sub == TRUE && node->children) {
2802 debug_print("folder '%s' doesn't have "
2803 "subfolders. removing...\n",
2804 old_item->path);
2805 folder_item_remove_children(old_item);
2809 node = next;
2812 for (cur = item_list; cur != NULL; cur = cur->next) {
2813 FolderItem *cur_item = FOLDER_ITEM(cur->data);
2814 new_item = NULL;
2816 for (node = item->node->children; node != NULL;
2817 node = node->next) {
2818 if (!strcmp2(FOLDER_ITEM(node->data)->path,
2819 cur_item->path)) {
2820 new_item = FOLDER_ITEM(node->data);
2821 folder_item_destroy(cur_item);
2822 cur_item = NULL;
2823 break;
2826 if (!new_item) {
2827 new_item = cur_item;
2828 debug_print("new folder '%s' found.\n", new_item->path);
2829 folder_item_append(item, new_item);
2832 if (!strcasecmp(new_item->path, "INBOX")) {
2833 new_item->stype = F_INBOX;
2834 folder->inbox = new_item;
2835 } else if (!folder_item_parent(item) || item->stype == F_INBOX) {
2836 gchar *base;
2838 base = g_path_get_basename(new_item->path);
2840 if (!folder->outbox && !g_ascii_strcasecmp(base, "Sent")) {
2841 new_item->stype = F_OUTBOX;
2842 folder->outbox = new_item;
2843 } else if (!folder->draft && (!g_ascii_strcasecmp(base, "Drafts") || !g_ascii_strcasecmp(base, "Draft"))) {
2844 new_item->stype = F_DRAFT;
2845 folder->draft = new_item;
2846 } else if (!folder->queue && !g_ascii_strcasecmp(base, "Queue")) {
2847 new_item->stype = F_QUEUE;
2848 folder->queue = new_item;
2849 } else if (!folder->trash && !g_ascii_strcasecmp(base, "Trash")) {
2850 new_item->stype = F_TRASH;
2851 folder->trash = new_item;
2853 g_free(base);
2856 if (new_item->no_sub == FALSE)
2857 imap_scan_tree_recursive(session, new_item, subs_only);
2860 g_slist_free(item_list);
2862 return MAILIMAP_NO_ERROR;
2865 GList *imap_scan_subtree(Folder *folder, FolderItem *item, gboolean unsubs_only, gboolean recursive)
2867 IMAPSession *session = imap_session_get(folder);
2868 gchar *real_path;
2869 gchar *wildcard_path;
2870 gchar separator;
2871 gchar wildcard[3];
2872 clist * lep_list;
2873 GSList *item_list = NULL, *cur;
2874 GList *child_list = NULL, *tmplist = NULL;
2875 GSList *sub_list = NULL;
2876 int r = MAILIMAP_NO_ERROR;
2878 if (!session)
2879 return NULL;
2881 separator = imap_get_path_separator(session, IMAP_FOLDER(folder), item->path, &r);
2882 if (is_fatal(r))
2883 return NULL;
2885 if (item->path) {
2886 wildcard[0] = separator;
2887 wildcard[1] = '%';
2888 wildcard[2] = '\0';
2889 real_path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path, &r);
2890 if (is_fatal(r)) {
2891 g_free(real_path);
2892 return NULL;
2894 } else {
2895 wildcard[0] = '%';
2896 wildcard[1] = '\0';
2897 real_path = g_strdup("");
2900 Xstrcat_a(wildcard_path, real_path, wildcard,
2901 {g_free(real_path); return NULL;});
2902 lep_list = NULL;
2904 if (unsubs_only)
2905 statusbar_print_all(_("Looking for unsubscribed folders in %s..."),
2906 item->path?item->path:item->name);
2907 else
2908 statusbar_print_all(_("Looking for subfolders of %s..."),
2909 item->path?item->path:item->name);
2911 r = imap_threaded_list(folder, "", wildcard_path, &lep_list);
2912 if (r) {
2913 g_free(real_path);
2914 statusbar_pop_all();
2915 return NULL;
2917 item_list = imap_list_from_lep(IMAP_FOLDER(folder),
2918 lep_list, real_path, FALSE);
2919 mailimap_list_result_free(lep_list);
2921 for (cur = item_list; cur != NULL; cur = cur->next) {
2922 FolderItem *cur_item = FOLDER_ITEM(cur->data);
2923 if (recursive) {
2924 tmplist = imap_scan_subtree(folder, cur_item,
2925 unsubs_only, recursive);
2926 if (tmplist)
2927 child_list = g_list_concat(child_list, tmplist);
2929 child_list = g_list_prepend(child_list,
2930 imap_get_real_path(session,
2931 IMAP_FOLDER(folder), cur_item->path, &r));
2932 if (is_fatal(r)) {
2933 g_free(real_path);
2934 statusbar_pop_all();
2935 return NULL;
2937 folder_item_destroy(cur_item);
2939 child_list = g_list_reverse(child_list);
2940 g_slist_free(item_list);
2942 if (unsubs_only) {
2943 r = imap_threaded_lsub(folder, "", wildcard_path, &lep_list);
2944 if (r) {
2945 g_free(real_path);
2946 statusbar_pop_all();
2947 return NULL;
2949 sub_list = imap_list_from_lep(IMAP_FOLDER(folder),
2950 lep_list, real_path, FALSE);
2951 mailimap_list_result_free(lep_list);
2953 for (cur = sub_list; cur != NULL; cur = cur->next) {
2954 FolderItem *cur_item = FOLDER_ITEM(cur->data);
2955 GList *oldlitem = NULL;
2956 gchar *tmp = imap_get_real_path(session,
2957 IMAP_FOLDER(folder), cur_item->path, &r);
2958 if (r) {
2959 g_free(real_path);
2960 statusbar_pop_all();
2961 g_free(tmp);
2962 return NULL;
2964 folder_item_destroy(cur_item);
2965 oldlitem = g_list_find_custom(
2966 child_list, tmp, (GCompareFunc)strcmp2);
2967 if (oldlitem) {
2968 child_list = g_list_remove_link(child_list, oldlitem);
2969 g_free(oldlitem->data);
2970 g_list_free(oldlitem);
2972 g_free(tmp);
2976 g_free(real_path);
2977 statusbar_pop_all();
2979 return child_list;
2982 static gint imap_create_tree(Folder *folder)
2984 g_return_val_if_fail(folder != NULL, -1);
2985 g_return_val_if_fail(folder->node != NULL, -1);
2986 g_return_val_if_fail(folder->node->data != NULL, -1);
2987 g_return_val_if_fail(folder->account != NULL, -1);
2989 imap_scan_tree(folder);
2990 imap_create_missing_folders(folder);
2992 return 0;
2995 static void imap_create_missing_folders(Folder *folder)
2997 g_return_if_fail(folder != NULL);
2999 if (!folder->inbox)
3000 folder->inbox = imap_create_special_folder
3001 (folder, F_INBOX, "INBOX");
3002 if (!folder->trash)
3003 folder->trash = imap_create_special_folder
3004 (folder, F_TRASH, "Trash");
3005 if (!folder->queue)
3006 folder->queue = imap_create_special_folder
3007 (folder, F_QUEUE, "Queue");
3008 if (!folder->outbox)
3009 folder->outbox = imap_create_special_folder
3010 (folder, F_OUTBOX, "Sent");
3011 if (!folder->draft)
3012 folder->draft = imap_create_special_folder
3013 (folder, F_DRAFT, "Drafts");
3016 static FolderItem *imap_create_special_folder(Folder *folder,
3017 SpecialFolderItemType stype,
3018 const gchar *name)
3020 FolderItem *item;
3021 FolderItem *new_item;
3023 g_return_val_if_fail(folder != NULL, NULL);
3024 g_return_val_if_fail(folder->node != NULL, NULL);
3025 g_return_val_if_fail(folder->node->data != NULL, NULL);
3026 g_return_val_if_fail(folder->account != NULL, NULL);
3027 g_return_val_if_fail(name != NULL, NULL);
3029 item = FOLDER_ITEM(folder->node->data);
3030 new_item = imap_create_folder(folder, item, name);
3032 if (!new_item) {
3033 g_warning("Can't create '%s'", name);
3034 if (!folder->inbox) return NULL;
3036 new_item = imap_create_folder(folder, folder->inbox, name);
3037 if (!new_item)
3038 g_warning("Can't create '%s' under INBOX", name);
3039 else
3040 new_item->stype = stype;
3041 } else
3042 new_item->stype = stype;
3044 return new_item;
3047 static gchar *imap_folder_get_path(Folder *folder)
3049 gchar *folder_path;
3051 g_return_val_if_fail(folder != NULL, NULL);
3052 g_return_val_if_fail(folder->account != NULL, NULL);
3054 #ifdef G_OS_WIN32
3055 gchar *sanitized_dirname = g_strdup(folder->account->recv_server);
3056 g_strdelimit(sanitized_dirname, ":", ',');
3057 #endif
3059 folder_path = g_strconcat(get_imap_cache_dir(),
3060 G_DIR_SEPARATOR_S,
3061 #ifdef G_OS_WIN32
3062 sanitized_dirname,
3063 #else
3064 folder->account->recv_server,
3065 #endif
3066 G_DIR_SEPARATOR_S,
3067 folder->account->userid,
3068 NULL);
3070 #ifdef G_OS_WIN32
3071 g_free(sanitized_dirname);
3072 #endif
3073 return folder_path;
3076 #ifdef G_OS_WIN32
3077 static gchar *imap_encode_unsafe_chars(const gchar *str)
3079 gchar *ret = NULL, *o_ret;
3080 gchar *i;
3081 if (!str)
3082 return NULL;
3083 ret = g_malloc(3*strlen(str)+1);
3084 o_ret = ret;
3085 for (i = (gchar *)str; *i; i++) {
3086 switch(*i) {
3087 case ':':
3088 case '|':
3089 case '<':
3090 case '>':
3091 case '*':
3092 case '?':
3093 case '#':
3094 *ret++ = '%';
3095 *ret++ = '0'+(*i/10);
3096 *ret++ = '0'+(*i%10);
3097 break;
3098 default:
3099 *ret++ = *i;
3102 *ret++ = '\0';
3103 return o_ret;
3105 #endif
3106 static gchar *imap_item_get_path(Folder *folder, FolderItem *item)
3108 gchar *folder_path, *path;
3109 gchar *item_path = NULL;
3111 g_return_val_if_fail(folder != NULL, NULL);
3112 g_return_val_if_fail(item != NULL, NULL);
3113 folder_path = imap_folder_get_path(folder);
3115 g_return_val_if_fail(folder_path != NULL, NULL);
3117 #ifdef G_OS_UNIX
3118 item_path = g_strdup(item->path);
3119 #else
3120 item_path = imap_encode_unsafe_chars(item->path);
3121 #endif
3123 if (g_path_is_absolute(folder_path)) {
3124 if (item_path)
3125 path = g_strconcat(folder_path, G_DIR_SEPARATOR_S,
3126 item_path, NULL);
3127 else
3128 path = g_strdup(folder_path);
3129 } else {
3130 if (item_path)
3131 path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
3132 folder_path, G_DIR_SEPARATOR_S,
3133 item_path, NULL);
3134 else
3135 path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
3136 folder_path, NULL);
3138 g_free(folder_path);
3139 g_free(item_path);
3140 #ifdef G_OS_WIN32
3141 while (strchr(path, '/'))
3142 *strchr(path, '/') = '\\';
3143 #endif
3145 return path;
3148 static FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
3149 const gchar *name)
3151 gchar *dirpath, *imap_path;
3152 IMAPSession *session;
3153 FolderItem *new_item;
3154 gchar separator;
3155 gchar *new_name;
3156 const gchar *p;
3157 gint ok = MAILIMAP_NO_ERROR;
3158 gboolean no_select = FALSE, no_sub = FALSE;
3159 gboolean exist = FALSE;
3161 g_return_val_if_fail(folder != NULL, NULL);
3162 g_return_val_if_fail(folder->account != NULL, NULL);
3163 g_return_val_if_fail(parent != NULL, NULL);
3164 g_return_val_if_fail(name != NULL, NULL);
3166 if (to_number(name) > 0) {
3167 gchar *cached_msg = imap_get_cached_filename(parent, to_number(name));
3168 if (is_file_exist(cached_msg)) {
3169 if (claws_unlink(cached_msg) != 0) {
3170 return NULL;
3175 debug_print("getting session...\n");
3176 session = imap_session_get(folder);
3177 if (!session) {
3178 return NULL;
3181 if (!folder_item_parent(parent) && strcasecmp(name, "INBOX") == 0) {
3182 dirpath = g_strdup(name);
3183 }else if (parent->path)
3184 dirpath = g_strconcat(parent->path, "/", name, NULL);
3185 else if ((p = strchr(name, '/')) != NULL && *(p + 1) != '\0')
3186 dirpath = g_strdup(name);
3187 else if (folder->account->imap_dir && *folder->account->imap_dir) {
3188 gchar *imap_dir;
3190 Xstrdup_a(imap_dir, folder->account->imap_dir, {return NULL;});
3191 strtailchomp(imap_dir, '/');
3192 dirpath = g_strconcat(imap_dir, "/", name, NULL);
3193 } else
3194 dirpath = g_strdup(name);
3198 /* keep trailing directory separator to create a folder that contains
3199 sub folder */
3200 imap_path = imap_utf8_to_modified_utf7(dirpath, FALSE);
3202 strtailchomp(dirpath, '/');
3203 Xstrdup_a(new_name, name, {
3204 g_free(dirpath);
3205 g_free(imap_path);
3206 return NULL;});
3208 separator = imap_get_path_separator(session, IMAP_FOLDER(folder), imap_path, &ok);
3209 if (is_fatal(ok)) {
3210 g_free(imap_path);
3211 return NULL;
3213 imap_path_separator_subst(imap_path, separator);
3214 /* remove trailing / for display */
3215 strtailchomp(new_name, '/');
3217 if (strcasecmp(dirpath, "INBOX") != 0) {
3218 GPtrArray *argbuf;
3219 int r;
3220 clist * lep_list;
3222 argbuf = g_ptr_array_new();
3223 r = imap_threaded_list(folder, "", imap_path, &lep_list);
3224 if (r != MAILIMAP_NO_ERROR) {
3225 imap_handle_error(SESSION(session), NULL, r);
3226 log_warning(LOG_PROTOCOL, _("can't create mailbox: LIST failed\n"));
3227 g_free(imap_path);
3228 g_free(dirpath);
3229 ptr_array_free_strings(argbuf);
3230 g_ptr_array_free(argbuf, TRUE);
3231 return NULL;
3234 if (clist_count(lep_list) > 0)
3235 exist = TRUE;
3236 mailimap_list_result_free(lep_list);
3237 lep_list = NULL;
3238 if (!exist) {
3239 ok = imap_cmd_create(session, imap_path);
3240 if (ok != MAILIMAP_NO_ERROR) {
3241 log_warning(LOG_PROTOCOL, _("can't create mailbox\n"));
3242 g_free(imap_path);
3243 g_free(dirpath);
3244 return NULL;
3246 r = imap_threaded_list(folder, "", imap_path, &lep_list);
3247 if (r == MAILIMAP_NO_ERROR) {
3248 GSList *item_list = imap_list_from_lep(IMAP_FOLDER(folder),
3249 lep_list, dirpath, TRUE);
3250 if (item_list) {
3251 FolderItem *cur_item = FOLDER_ITEM(item_list->data);
3252 no_select = cur_item->no_select;
3253 no_sub = cur_item->no_sub;
3254 g_slist_free(item_list);
3256 mailimap_list_result_free(lep_list);
3257 } else {
3258 imap_handle_error(SESSION(session), NULL, r);
3261 imap_threaded_subscribe(folder, imap_path, TRUE);
3262 } else {
3263 clist *lep_list;
3264 int r;
3265 /* just get flags */
3266 r = imap_threaded_list(folder, "", "INBOX", &lep_list);
3267 if (r == MAILIMAP_NO_ERROR) {
3268 GSList *item_list = imap_list_from_lep(IMAP_FOLDER(folder),
3269 lep_list, dirpath, TRUE);
3270 if (item_list) {
3271 FolderItem *cur_item = FOLDER_ITEM(item_list->data);
3272 no_select = cur_item->no_select;
3273 no_sub = cur_item->no_sub;
3274 g_slist_free(item_list);
3276 mailimap_list_result_free(lep_list);
3277 } else {
3278 imap_handle_error(SESSION(session), NULL, r);
3282 new_item = folder_item_new(folder, new_name, dirpath);
3283 new_item->no_select = no_select;
3284 new_item->no_sub = no_sub;
3285 folder_item_append(parent, new_item);
3286 g_free(imap_path);
3287 g_free(dirpath);
3289 dirpath = folder_item_get_path(new_item);
3290 if (!is_dir_exist(dirpath))
3291 make_dir_hier(dirpath);
3292 g_free(dirpath);
3294 if (exist) {
3295 /* folder existed, scan it */
3296 imap_scan_required(folder, new_item);
3297 folder_item_scan_full(new_item, FALSE);
3300 return new_item;
3303 static gint imap_rename_folder(Folder *folder, FolderItem *item,
3304 const gchar *name)
3306 gchar *dirpath;
3307 gchar *newpath;
3308 gchar *real_oldpath;
3309 gchar *real_newpath;
3310 gchar *paths[2];
3311 gchar *old_cache_dir;
3312 gchar *new_cache_dir;
3313 IMAPSession *session;
3314 gchar separator;
3315 gint ok = MAILIMAP_NO_ERROR;
3316 gint exists, recent, unseen;
3317 guint32 uid_validity;
3319 g_return_val_if_fail(folder != NULL, -1);
3320 g_return_val_if_fail(item != NULL, -1);
3321 g_return_val_if_fail(item->path != NULL, -1);
3322 g_return_val_if_fail(name != NULL, -1);
3324 debug_print("getting session...\n");
3325 session = imap_session_get(folder);
3326 if (!session) {
3327 return -1;
3330 if (strchr(name, imap_get_path_separator(session, IMAP_FOLDER(folder), item->path, &ok)) != NULL ||
3331 is_fatal(ok)) {
3332 g_warning("New folder name must not contain the namespace "
3333 "path separator");
3334 return -1;
3337 real_oldpath = imap_get_real_path(session, IMAP_FOLDER(folder), item->path, &ok);
3338 if (is_fatal(ok)) {
3339 g_free(real_oldpath);
3340 return -1;
3343 g_free(session->mbox);
3344 session->mbox = NULL;
3345 session->exists = 0;
3346 session->recent = 0;
3347 session->expunge = 0;
3348 ok = imap_cmd_examine(session, "INBOX",
3349 &exists, &recent, &unseen, &uid_validity, FALSE);
3350 if (ok != MAILIMAP_NO_ERROR) {
3351 g_free(real_oldpath);
3352 return -1;
3355 separator = imap_get_path_separator(session, IMAP_FOLDER(folder), item->path, &ok);
3356 if (is_fatal(ok)) {
3357 g_free(real_oldpath);
3358 return -1;
3360 if (strchr(item->path, '/')) {
3361 dirpath = g_path_get_dirname(item->path);
3362 newpath = g_strconcat(dirpath, "/", name, NULL);
3363 g_free(dirpath);
3364 } else
3365 newpath = g_strdup(name);
3367 real_newpath = imap_utf8_to_modified_utf7(newpath, FALSE);
3368 imap_path_separator_subst(real_newpath, separator);
3370 ok = imap_cmd_rename(session, real_oldpath, real_newpath);
3371 if (ok != MAILIMAP_NO_ERROR) {
3372 log_warning(LOG_PROTOCOL, _("can't rename mailbox: %s to %s\n"),
3373 real_oldpath, real_newpath);
3374 g_free(real_oldpath);
3375 g_free(newpath);
3376 g_free(real_newpath);
3377 return -1;
3379 g_free(item->name);
3380 item->name = g_strdup(name);
3382 old_cache_dir = folder_item_get_path(item);
3384 paths[0] = g_strdup(item->path);
3385 paths[1] = newpath;
3386 g_node_traverse(item->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1,
3387 imap_rename_folder_func, paths);
3389 if (is_dir_exist(old_cache_dir)) {
3390 new_cache_dir = folder_item_get_path(item);
3391 if (g_rename(old_cache_dir, new_cache_dir) < 0) {
3392 FILE_OP_ERROR(old_cache_dir, "rename");
3394 g_free(new_cache_dir);
3397 g_free(old_cache_dir);
3398 g_free(paths[0]);
3399 g_free(newpath);
3400 g_free(real_oldpath);
3401 g_free(real_newpath);
3402 return 0;
3405 gint imap_subscribe(Folder *folder, FolderItem *item, gchar *rpath, gboolean sub)
3407 gchar *path;
3408 gint r = MAILIMAP_NO_ERROR;
3409 IMAPSession *session;
3410 debug_print("getting session...\n");
3412 session = imap_session_get(folder);
3413 if (!session) {
3414 return -1;
3416 if (item && item->path) {
3417 path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path, &r);
3418 if (!path)
3419 return -1;
3420 if (is_fatal(r)) {
3421 g_free(path);
3422 return -1;
3424 if (!strcasecmp(path, "INBOX") && sub == FALSE) {
3425 g_free(path);
3426 return -1;
3428 debug_print("%ssubscribing %s\n", sub?"":"un", path);
3429 r = imap_threaded_subscribe(folder, path, sub);
3430 g_free(path);
3431 } else if (rpath) {
3432 r = imap_threaded_subscribe(folder, rpath, sub);
3433 } else
3434 return -1;
3435 return r;
3438 static gint imap_remove_folder_real(Folder *folder, FolderItem *item)
3440 gint ok = MAILIMAP_NO_ERROR;
3441 IMAPSession *session;
3442 gchar *path;
3443 gchar *cache_dir;
3444 gboolean selected_folder;
3446 g_return_val_if_fail(folder != NULL, -1);
3447 g_return_val_if_fail(item != NULL, -1);
3448 g_return_val_if_fail(item->path != NULL, -1);
3450 debug_print("getting session...\n");
3451 session = imap_session_get(folder);
3452 if (!session) {
3453 return -1;
3455 path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path, &ok);
3456 if (is_fatal(ok)) {
3457 g_free(path);
3458 return -1;
3460 imap_threaded_subscribe(folder, path, FALSE);
3462 selected_folder = (session->mbox != NULL) &&
3463 (!strcmp(session->mbox, item->path));
3464 if (selected_folder) {
3465 ok = imap_cmd_close(session);
3466 if (ok != MAILIMAP_NO_ERROR) {
3467 debug_print("close err %d\n", ok);
3468 return ok;
3471 ok = imap_cmd_delete(session, path);
3472 if (ok != MAILIMAP_NO_ERROR && !is_fatal(ok)) {
3473 gchar *tmp = NULL;
3475 ok = MAILIMAP_NO_ERROR;
3476 tmp = g_strdup_printf("%s%c", path,
3477 imap_get_path_separator(session, IMAP_FOLDER(folder), path, &ok));
3478 g_free(path);
3479 path = tmp;
3480 if (!is_fatal(ok))
3481 ok = imap_cmd_delete(session, path);
3484 if (ok != MAILIMAP_NO_ERROR) {
3485 log_warning(LOG_PROTOCOL, _("can't delete mailbox\n"));
3486 g_free(path);
3487 return -1;
3490 g_free(path);
3491 cache_dir = folder_item_get_path(item);
3492 if (is_dir_exist(cache_dir) && remove_dir_recursive(cache_dir) < 0)
3493 g_warning("can't remove directory '%s'", cache_dir);
3494 g_free(cache_dir);
3495 folder_item_remove(item);
3496 return 0;
3499 static gint imap_remove_folder(Folder *folder, FolderItem *item)
3501 GNode *node, *next;
3503 g_return_val_if_fail(item != NULL, -1);
3504 g_return_val_if_fail(item->folder != NULL, -1);
3505 g_return_val_if_fail(item->node != NULL, -1);
3507 node = item->node->children;
3508 while (node != NULL) {
3509 next = node->next;
3510 if (imap_remove_folder(folder, FOLDER_ITEM(node->data)) < 0)
3511 return -1;
3512 node = next;
3514 debug_print("IMAP removing %s\n", item->path);
3516 if (imap_remove_all_msg(folder, item) < 0)
3517 return -1;
3518 return imap_remove_folder_real(folder, item);
3521 typedef struct _uncached_data {
3522 IMAPSession *session;
3523 FolderItem *item;
3524 MsgNumberList *numlist;
3525 guint cur;
3526 guint total;
3527 gboolean done;
3528 int ok;
3529 } uncached_data;
3531 static void *imap_get_uncached_messages_thread(void *data)
3533 uncached_data *stuff = (uncached_data *)data;
3534 IMAPSession *session = stuff->session;
3535 FolderItem *item = stuff->item;
3536 MsgNumberList *numlist = stuff->numlist;
3537 GSList *newlist = NULL;
3538 GSList *llast = NULL;
3539 GSList *seq_list, *cur;
3540 gboolean got_alien_tags = FALSE;
3542 debug_print("uncached_messages\n");
3544 if (session == NULL || item == NULL || item->folder == NULL
3545 || FOLDER_CLASS(item->folder) != &imap_class) {
3546 stuff->done = TRUE;
3547 return NULL;
3550 seq_list = imap_get_lep_set_from_numlist(IMAP_FOLDER(item->folder), numlist);
3551 debug_print("get msgs info\n");
3552 for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
3553 struct mailimap_set * imapset;
3554 unsigned int i;
3555 int r;
3556 carray * env_list;
3557 int count;
3559 if (session->cancelled)
3560 break;
3562 imapset = cur->data;
3564 r = imap_threaded_fetch_env(session->folder,
3565 imapset, &env_list);
3566 if (r != MAILIMAP_NO_ERROR) {
3567 imap_handle_error(SESSION(session), NULL, r);
3568 if (is_fatal(r)) {
3569 stuff->ok = r;
3570 return NULL;
3572 continue;
3575 session_set_access_time(SESSION(session));
3577 count = 0;
3578 for(i = 0 ; i < carray_count(env_list) ; i += 2) {
3579 struct imap_fetch_env_info * info;
3580 MsgInfo * msginfo;
3581 GSList *tags = NULL, *cur = NULL;
3582 info = carray_get(env_list, i);
3583 tags = carray_get(env_list, i+1);
3584 msginfo = imap_envelope_from_lep(info, item);
3585 if (msginfo == NULL) {
3586 slist_free_strings_full(tags);
3587 continue;
3589 g_slist_free(msginfo->tags);
3590 msginfo->tags = NULL;
3592 for (cur = tags; cur; cur = cur->next) {
3593 gchar *real_tag = imap_modified_utf7_to_utf8(cur->data, TRUE);
3594 gint id = 0;
3595 id = tags_get_id_for_str(real_tag);
3596 if (id == -1) {
3597 id = tags_add_tag(real_tag);
3598 got_alien_tags = TRUE;
3600 if (!g_slist_find(msginfo->tags, GINT_TO_POINTER(id))) {
3601 msginfo->tags = g_slist_prepend(
3602 msginfo->tags,
3603 GINT_TO_POINTER(id));
3605 g_free(real_tag);
3607 if (msginfo->tags)
3608 msginfo->tags = g_slist_reverse(msginfo->tags);
3609 slist_free_strings_full(tags);
3610 msginfo->folder = item;
3611 if (!newlist)
3612 llast = newlist = g_slist_append(newlist, msginfo);
3613 else {
3614 llast = g_slist_append(llast, msginfo);
3615 llast = llast->next;
3617 count ++;
3620 imap_fetch_env_free(env_list);
3623 if (got_alien_tags) {
3624 tags_write_tags();
3625 main_window_reflect_tags_changes(mainwindow_get_mainwindow());
3628 imap_lep_set_free(seq_list);
3630 session_set_access_time(SESSION(session));
3631 stuff->done = TRUE;
3632 return newlist;
3635 #define MAX_MSG_NUM 50
3637 static GSList *imap_get_uncached_messages(IMAPSession *session,
3638 FolderItem *item,
3639 MsgNumberList *numlist,
3640 int *r)
3642 GSList *result = NULL;
3643 GSList * cur;
3644 uncached_data *data = g_new0(uncached_data, 1);
3646 cur = numlist;
3647 data->total = g_slist_length(numlist);
3648 data->ok = MAILIMAP_NO_ERROR;
3649 debug_print("messages list : %i\n", data->total);
3651 while (cur != NULL) {
3652 GSList * partial_result;
3653 int count;
3654 GSList * newlist;
3655 GSList * llast;
3657 llast = NULL;
3658 count = 0;
3659 newlist = NULL;
3660 while (count < MAX_MSG_NUM) {
3661 void * p;
3663 p = cur->data;
3665 if (newlist == NULL)
3666 llast = newlist = g_slist_append(newlist, p);
3667 else {
3668 llast = g_slist_append(llast, p);
3669 llast = llast->next;
3671 count ++;
3673 cur = cur->next;
3674 if (cur == NULL)
3675 break;
3678 data->done = FALSE;
3679 data->session = session;
3680 data->item = item;
3681 data->numlist = newlist;
3682 data->cur += count;
3684 if (prefs_common.work_offline &&
3685 !inc_offline_should_override(FALSE,
3686 _("Claws Mail needs network access in order "
3687 "to access the IMAP server."))) {
3688 g_free(data);
3689 return NULL;
3692 partial_result =
3693 (GSList *)imap_get_uncached_messages_thread(data);
3694 *r = data->ok;
3695 if (data->ok != MAILIMAP_NO_ERROR) {
3696 goto bail;
3698 statusbar_progress_all(data->cur,data->total, 1);
3700 g_slist_free(newlist);
3702 result = g_slist_concat(result, partial_result);
3704 bail:
3705 g_free(data);
3707 statusbar_progress_all(0,0,0);
3708 statusbar_pop_all();
3710 return result;
3713 static void imap_delete_all_cached_messages(FolderItem *item)
3715 gchar *dir;
3717 g_return_if_fail(item != NULL);
3718 g_return_if_fail(item->folder != NULL);
3719 g_return_if_fail(FOLDER_CLASS(item->folder) == &imap_class);
3721 debug_print("Deleting all cached messages...\n");
3723 dir = folder_item_get_path(item);
3724 if (is_dir_exist(dir))
3725 remove_all_numbered_files(dir);
3726 g_free(dir);
3728 debug_print("Deleting all cached messages done.\n");
3731 gchar imap_get_path_separator_for_item(FolderItem *item)
3733 Folder *folder = NULL;
3734 IMAPFolder *imap_folder = NULL;
3735 IMAPSession *session = NULL;
3736 gchar result = '/';
3737 gint ok = MAILIMAP_NO_ERROR;
3738 if (!item)
3739 return '/';
3740 folder = item->folder;
3742 if (!folder)
3743 return '/';
3745 imap_folder = IMAP_FOLDER(folder);
3747 debug_print("getting session...\n");
3748 session = imap_session_get(FOLDER(folder));
3749 result = imap_get_path_separator(session, imap_folder, item->path, &ok);
3750 return result;
3753 static gchar imap_refresh_path_separator(IMAPSession *session, IMAPFolder *folder, const gchar *subfolder, gint *ok)
3755 clist * lep_list;
3756 int r;
3757 gchar separator = '\0';
3759 g_return_val_if_fail(session != NULL, '/');
3760 r = imap_threaded_list((Folder *)folder, "", subfolder, &lep_list);
3762 if (r != MAILIMAP_NO_ERROR) {
3763 imap_handle_error(SESSION(session), NULL, r);
3764 log_warning(LOG_PROTOCOL, _("LIST failed\n"));
3765 *ok = r;
3766 return '\0';
3769 if (lep_list != NULL && clist_count(lep_list) > 0) {
3770 clistiter * iter = clist_begin(lep_list);
3771 struct mailimap_mailbox_list * mb;
3772 mb = clist_content(iter);
3774 separator = mb->mb_delimiter;
3775 debug_print("got separator: %c\n", folder->last_seen_separator);
3777 *ok = MAILIMAP_NO_ERROR;
3778 mailimap_list_result_free(lep_list);
3779 return separator;
3782 static gchar imap_get_path_separator(IMAPSession *session, IMAPFolder *folder, const gchar *path, gint *ok)
3784 gchar separator = '/';
3785 *ok = MAILIMAP_NO_ERROR;
3786 if (folder->last_seen_separator == 0) {
3787 folder->last_seen_separator = imap_refresh_path_separator(session, folder, "", ok);
3790 if (folder->last_seen_separator == 0) {
3791 folder->last_seen_separator = imap_refresh_path_separator(session, folder, "INBOX", ok);
3794 if (folder->last_seen_separator != 0) {
3795 debug_print("using separator: %c\n", folder->last_seen_separator);
3796 return folder->last_seen_separator;
3799 return separator;
3802 static gchar *imap_get_real_path(IMAPSession *session, IMAPFolder *folder, const gchar *path, gint *ok)
3804 gchar *real_path = NULL;
3805 gchar separator;
3807 g_return_val_if_fail(folder != NULL, NULL);
3808 g_return_val_if_fail(path != NULL, NULL);
3810 *ok = MAILIMAP_NO_ERROR;
3812 real_path = imap_utf8_to_modified_utf7(path, FALSE);
3813 separator = imap_get_path_separator(session, folder, path, ok);
3814 if (*ok == MAILIMAP_NO_ERROR)
3815 imap_path_separator_subst(real_path, separator);
3817 return real_path;
3820 static gint imap_set_message_flags(IMAPSession *session,
3821 IMAPFolderItem *item,
3822 MsgNumberList *numlist,
3823 IMAPFlags flags,
3824 GSList *tags,
3825 gboolean is_set)
3827 gint ok = 0;
3828 GSList *seq_list;
3829 GSList * cur;
3830 gint total = 0;
3831 IMAPFolder *folder = NULL;
3832 GSList *sorted_list = NULL;
3834 if (numlist == NULL || session == NULL)
3835 return MAILIMAP_ERROR_BAD_STATE;
3837 folder = IMAP_FOLDER(session->folder);
3839 sorted_list = g_slist_copy(numlist);
3840 sorted_list = g_slist_sort(sorted_list, g_int_compare);
3842 cur = g_slist_last(sorted_list);
3844 if (cur)
3845 total = GPOINTER_TO_INT(cur->data);
3847 seq_list = imap_get_lep_set_from_numlist(IMAP_FOLDER(session->folder), sorted_list);
3849 statusbar_print_all(_("Flagging messages..."));
3851 for(cur = seq_list ; cur != NULL ; cur = g_slist_next(cur)) {
3852 struct mailimap_set * imapset = (struct mailimap_set *)cur->data;
3853 struct mailimap_set_item *set_item = NULL;
3855 if (imapset->set_list)
3856 set_item = clist_content(clist_begin(imapset->set_list));
3857 else
3858 continue;
3860 if (set_item == NULL)
3861 continue;
3863 statusbar_progress_all(set_item->set_first, total, 1);
3865 ok = imap_cmd_store(session, item, imapset,
3866 flags, tags, is_set);
3867 statusbar_progress_all(set_item->set_last, total, 1);
3868 if (ok != MAILIMAP_NO_ERROR && folder->max_set_size > 20) {
3869 /* reduce max set size */
3870 folder->max_set_size /= 2;
3872 if (ok != MAILIMAP_NO_ERROR && is_fatal(ok)) {
3873 break;
3877 g_slist_free(sorted_list);
3879 statusbar_progress_all(0,0,0);
3880 statusbar_pop_all();
3882 imap_lep_set_free(seq_list);
3884 return ok;
3887 typedef struct _select_data {
3888 IMAPSession *session;
3889 gchar *real_path;
3890 gint *exists;
3891 gint *recent;
3892 gint *unseen;
3893 guint32 *uid_validity;
3894 gboolean done;
3895 } select_data;
3897 static gint imap_select(IMAPSession *session, IMAPFolder *folder,
3898 FolderItem *item,
3899 gint *exists, gint *recent, gint *unseen,
3900 guint32 *uid_validity, gint *can_create_flags,
3901 gboolean block)
3903 gchar *real_path;
3904 gint ok = MAILIMAP_NO_ERROR;
3905 gint exists_, recent_, unseen_;
3906 guint32 uid_validity_;
3907 gint can_create_flags_;
3908 const gchar *path = item ? item->path:NULL;
3910 if (!item) {
3911 return MAILIMAP_ERROR_BAD_STATE;
3914 if (!exists && !recent && !unseen && !uid_validity && !can_create_flags) {
3915 if (session->mbox && strcmp(session->mbox, path) == 0)
3916 return MAILIMAP_NO_ERROR;
3918 if (!exists && !recent && !unseen && !uid_validity && can_create_flags) {
3919 if (session->mbox && strcmp(session->mbox, path) == 0) {
3920 if (IMAP_FOLDER_ITEM(item)->can_create_flags != ITEM_CAN_CREATE_FLAGS_UNKNOWN)
3921 return MAILIMAP_NO_ERROR;
3924 if (!exists)
3925 exists = &exists_;
3926 if (!recent)
3927 recent = &recent_;
3928 if (!unseen)
3929 unseen = &unseen_;
3930 if (!uid_validity)
3931 uid_validity = &uid_validity_;
3932 if (!can_create_flags)
3933 can_create_flags = &can_create_flags_;
3935 g_free(session->mbox);
3936 session->mbox = NULL;
3937 session->exists = 0;
3938 session->recent = 0;
3939 session->expunge = 0;
3941 real_path = imap_get_real_path(session, folder, path, &ok);
3942 if (is_fatal(ok)) {
3943 g_free(real_path);
3944 return ok;
3946 g_slist_free(IMAP_FOLDER_ITEM(item)->ok_flags);
3947 IMAP_FOLDER_ITEM(item)->ok_flags = NULL;
3948 ok = imap_cmd_select(session, real_path,
3949 exists, recent, unseen, uid_validity, can_create_flags,
3950 &(IMAP_FOLDER_ITEM(item)->ok_flags), block);
3951 if (ok != MAILIMAP_NO_ERROR) {
3952 log_warning(LOG_PROTOCOL, _("can't select folder: %s\n"), real_path);
3953 } else {
3954 session->mbox = g_strdup(path);
3955 session->folder_content_changed = FALSE;
3956 session->exists = *exists;
3957 session->recent = *recent;
3958 session->expunge = 0;
3959 session->unseen = *unseen;
3960 session->uid_validity = *uid_validity;
3961 debug_print("select: exists %d recent %d expunge %d uid_validity %d can_create_flags %d\n",
3962 session->exists, session->recent, session->expunge,
3963 session->uid_validity, *can_create_flags);
3965 if (*can_create_flags) {
3966 IMAP_FOLDER_ITEM(item)->can_create_flags = ITEM_CAN_CREATE_FLAGS;
3967 } else {
3968 IMAP_FOLDER_ITEM(item)->can_create_flags = ITEM_CANNOT_CREATE_FLAGS;
3970 g_free(real_path);
3972 return ok;
3975 static gint imap_status(IMAPSession *session, IMAPFolder *folder,
3976 const gchar *path, IMAPFolderItem *item,
3977 gint *messages,
3978 guint32 *uid_next, guint32 *uid_validity,
3979 gint *unseen, gboolean block)
3981 int r = MAILIMAP_NO_ERROR;
3982 clistiter * iter;
3983 struct mailimap_mailbox_data_status * data_status;
3984 int got_values;
3985 gchar *real_path;
3986 guint mask = 0;
3988 real_path = imap_get_real_path(session, folder, path, &r);
3989 if (is_fatal(r)) {
3990 g_free(real_path);
3991 return r;
3993 if (messages) {
3994 mask |= 1 << 0;
3995 *messages = 0;
3997 if (uid_next) {
3998 mask |= 1 << 2;
3999 *uid_next = 0;
4001 if (uid_validity) {
4002 mask |= 1 << 3;
4003 *uid_validity = 0;
4005 if (unseen) {
4006 mask |= 1 << 4;
4007 *unseen = 0;
4010 if (session->mbox != NULL &&
4011 !strcmp(session->mbox, item->item.path)) {
4012 r = imap_cmd_close(session);
4013 if (r != MAILIMAP_NO_ERROR) {
4014 debug_print("close err %d\n", r);
4015 g_free(real_path);
4016 return r;
4020 r = imap_threaded_status(FOLDER(folder), real_path,
4021 &data_status, mask);
4023 g_free(real_path);
4024 if (r != MAILIMAP_NO_ERROR) {
4025 imap_handle_error(SESSION(session), NULL, r);
4026 debug_print("status err %d\n", r);
4027 return r;
4030 if (data_status == NULL || data_status->st_info_list == NULL) {
4031 debug_print("data_status %p\n", data_status);
4032 if (data_status) {
4033 debug_print("data_status->st_info_list %p\n", data_status->st_info_list);
4034 mailimap_mailbox_data_status_free(data_status);
4036 return MAILIMAP_ERROR_BAD_STATE;
4039 got_values = 0;
4040 if (data_status->st_info_list) {
4041 for(iter = clist_begin(data_status->st_info_list) ; iter != NULL ;
4042 iter = clist_next(iter)) {
4043 struct mailimap_status_info * info;
4045 info = clist_content(iter);
4046 switch (info->st_att) {
4047 case MAILIMAP_STATUS_ATT_MESSAGES:
4048 if (messages) {
4049 * messages = info->st_value;
4050 got_values |= 1 << 0;
4052 break;
4054 case MAILIMAP_STATUS_ATT_UIDNEXT:
4055 if (uid_next) {
4056 * uid_next = info->st_value;
4057 got_values |= 1 << 2;
4059 break;
4061 case MAILIMAP_STATUS_ATT_UIDVALIDITY:
4062 if (uid_validity) {
4063 * uid_validity = info->st_value;
4064 got_values |= 1 << 3;
4066 break;
4068 case MAILIMAP_STATUS_ATT_UNSEEN:
4069 if (unseen) {
4070 * unseen = info->st_value;
4071 got_values |= 1 << 4;
4073 break;
4077 mailimap_mailbox_data_status_free(data_status);
4079 if (got_values != mask) {
4080 g_warning("status: incomplete values received (%d)", got_values);
4082 return MAILIMAP_NO_ERROR;
4085 static void imap_free_capabilities(IMAPSession *session)
4087 slist_free_strings_full(session->capability);
4088 session->capability = NULL;
4091 /* low-level IMAP4rev1 commands */
4093 static gint imap_cmd_login(IMAPSession *session,
4094 const gchar *user, const gchar *pass,
4095 const gchar *type)
4097 int r;
4098 gint ok;
4100 if (!strcmp(type, "plaintext") && imap_has_capability(session, "LOGINDISABLED")) {
4101 gint ok = MAILIMAP_ERROR_BAD_STATE;
4102 if (imap_has_capability(session, "STARTTLS")) {
4103 #ifdef USE_GNUTLS
4104 log_warning(LOG_PROTOCOL, _("Server requires STARTTLS to log in.\n"));
4105 ok = imap_cmd_starttls(session);
4106 if (ok != MAILIMAP_NO_ERROR) {
4107 log_warning(LOG_PROTOCOL, _("Can't start STARTTLS session.\n"));
4108 return ok;
4109 } else {
4110 /* refresh capas */
4111 imap_free_capabilities(session);
4112 if ((r = imap_get_capabilities(session)) != MAILIMAP_NO_ERROR) {
4113 imap_handle_error(SESSION(session), NULL, r);
4114 log_warning(LOG_PROTOCOL, _("Can't refresh capabilities.\n"));
4115 return r;
4118 #else
4119 log_error(LOG_PROTOCOL, _("Connection to %s failed: "
4120 "server requires STARTTLS, but Claws Mail "
4121 "has been compiled without STARTTLS "
4122 "support.\n"),
4123 SESSION(session)->server);
4124 return MAILIMAP_ERROR_LOGIN;
4125 #endif
4126 } else {
4127 log_error(LOG_PROTOCOL, _("Server logins are disabled.\n"));
4128 return MAILIMAP_ERROR_LOGIN;
4132 log_print(LOG_PROTOCOL, "IMAP> Logging %s to %s using %s\n",
4133 user,
4134 SESSION(session)->server,
4135 type);
4136 r = imap_threaded_login(session->folder, user, pass, type);
4137 if (r != MAILIMAP_NO_ERROR) {
4138 imap_handle_error(SESSION(session), NULL, r);
4139 log_print(LOG_PROTOCOL, "IMAP< Error logging in to %s\n",
4140 SESSION(session)->server);
4141 ok = r;
4142 } else {
4143 log_print(LOG_PROTOCOL, "IMAP< Login to %s successful\n",
4144 SESSION(session)->server);
4145 ok = MAILIMAP_NO_ERROR;
4147 return ok;
4150 static gint imap_cmd_noop(IMAPSession *session)
4152 int r;
4153 unsigned int exists, recent, expunge, unseen, uidnext, uidval;
4155 r = imap_threaded_noop(session->folder, &exists, &recent, &expunge, &unseen, &uidnext, &uidval);
4156 if (r != MAILIMAP_NO_ERROR) {
4157 imap_handle_error(SESSION(session), NULL, r);
4158 debug_print("noop err %d\n", r);
4159 return r;
4162 if ((exists && exists != session->exists)
4163 || (recent && recent != session->recent)
4164 || (expunge && expunge != session->expunge)
4165 || (unseen && unseen != session->unseen)) {
4166 session->folder_content_changed = TRUE;
4168 if (uidnext != 0 && uidnext != session->uid_next) {
4169 session->uid_next = uidnext;
4170 session->folder_content_changed = TRUE;
4172 if (uidval != 0 && uidval != session->uid_validity) {
4173 session->uid_validity = uidval;
4174 session->folder_content_changed = TRUE;
4177 session->exists = exists;
4178 session->recent = recent;
4179 session->expunge = expunge;
4180 session->unseen = unseen;
4182 session_set_access_time(SESSION(session));
4184 return MAILIMAP_NO_ERROR;
4187 #ifdef USE_GNUTLS
4188 static gint imap_cmd_starttls(IMAPSession *session)
4190 int r;
4192 r = imap_threaded_starttls(session->folder,
4193 SESSION(session)->server, SESSION(session)->port);
4194 if (r != MAILIMAP_NO_ERROR) {
4195 imap_handle_error(SESSION(session), NULL, r);
4196 debug_print("STARTTLS err %d\n", r);
4197 return r;
4199 return MAILIMAP_NO_ERROR;
4201 #endif
4203 static gint imap_cmd_select(IMAPSession *session, const gchar *folder,
4204 gint *exists, gint *recent, gint *unseen,
4205 guint32 *uid_validity, gint *can_create_flags,
4206 GSList **ok_flags, gboolean block)
4208 int r;
4210 r = imap_threaded_select(session->folder, folder,
4211 exists, recent, unseen, uid_validity, can_create_flags, ok_flags);
4212 if (r != MAILIMAP_NO_ERROR) {
4213 imap_handle_error(SESSION(session), NULL, r);
4214 debug_print("select err %d\n", r);
4215 return r;
4217 return MAILIMAP_NO_ERROR;
4220 static gint imap_cmd_close(IMAPSession *session)
4222 int r;
4224 r = imap_threaded_close(session->folder);
4225 if (r != MAILIMAP_NO_ERROR) {
4226 imap_handle_error(SESSION(session), NULL, r);
4227 debug_print("close err %d\n", r);
4228 return r;
4230 g_free(session->mbox);
4231 session->mbox = NULL;
4232 session->exists = 0;
4233 session->recent = 0;
4234 session->expunge = 0;
4235 return MAILIMAP_NO_ERROR;
4238 static gint imap_cmd_examine(IMAPSession *session, const gchar *folder,
4239 gint *exists, gint *recent, gint *unseen,
4240 guint32 *uid_validity, gboolean block)
4242 int r;
4244 r = imap_threaded_examine(session->folder, folder,
4245 exists, recent, unseen, uid_validity);
4246 if (r != MAILIMAP_NO_ERROR) {
4247 imap_handle_error(SESSION(session), NULL, r);
4248 debug_print("examine err %d\n", r);
4250 return r;
4252 return MAILIMAP_NO_ERROR;
4255 static gint imap_cmd_create(IMAPSession *session, const gchar *folder)
4257 int r;
4259 r = imap_threaded_create(session->folder, folder);
4260 if (r != MAILIMAP_NO_ERROR) {
4261 imap_handle_error(SESSION(session), NULL, r);
4262 return r;
4265 return MAILIMAP_NO_ERROR;
4268 static gint imap_cmd_rename(IMAPSession *session, const gchar *old_folder,
4269 const gchar *new_folder)
4271 int r;
4273 r = imap_threaded_rename(session->folder, old_folder,
4274 new_folder);
4275 if (r != MAILIMAP_NO_ERROR) {
4276 imap_handle_error(SESSION(session), NULL, r);
4277 return r;
4280 return MAILIMAP_NO_ERROR;
4283 static gint imap_cmd_delete(IMAPSession *session, const gchar *folder)
4285 int r;
4288 r = imap_threaded_delete(session->folder, folder);
4289 if (r != MAILIMAP_NO_ERROR) {
4290 imap_handle_error(SESSION(session), NULL, r);
4291 return r;
4294 return MAILIMAP_NO_ERROR;
4297 typedef struct _fetch_data {
4298 IMAPSession *session;
4299 guint32 uid;
4300 const gchar *filename;
4301 gboolean headers;
4302 gboolean body;
4303 gboolean done;
4304 } fetch_data;
4306 static void *imap_cmd_fetch_thread(void *data)
4308 fetch_data *stuff = (fetch_data *)data;
4309 IMAPSession *session = stuff->session;
4310 guint32 uid = stuff->uid;
4311 const gchar *filename = stuff->filename;
4312 int r;
4314 if (stuff->body) {
4315 r = imap_threaded_fetch_content(session->folder,
4316 uid, 1, filename);
4318 else {
4319 r = imap_threaded_fetch_content(session->folder,
4320 uid, 0, filename);
4322 if (r != MAILIMAP_NO_ERROR) {
4323 imap_handle_error(SESSION(session), NULL, r);
4324 debug_print("fetch err %d\n", r);
4325 return GINT_TO_POINTER(r);
4327 return GINT_TO_POINTER(MAILIMAP_NO_ERROR);
4330 static gint imap_cmd_fetch(IMAPSession *session, guint32 uid,
4331 const gchar *filename, gboolean headers,
4332 gboolean body)
4334 fetch_data *data = g_new0(fetch_data, 1);
4335 int result = 0;
4336 data->done = FALSE;
4337 data->session = session;
4338 data->uid = uid;
4339 data->filename = filename;
4340 data->headers = headers;
4341 data->body = body;
4343 if (prefs_common.work_offline &&
4344 !inc_offline_should_override(FALSE,
4345 _("Claws Mail needs network access in order "
4346 "to access the IMAP server."))) {
4347 g_free(data);
4348 return -1;
4350 statusbar_print_all(_("Fetching message..."));
4351 result = GPOINTER_TO_INT(imap_cmd_fetch_thread(data));
4352 statusbar_pop_all();
4353 g_free(data);
4354 return result;
4358 static gint imap_cmd_append(IMAPSession *session,
4359 IMAPFolderItem *item,
4360 const gchar *destfolder,
4361 const gchar *file, IMAPFlags flags,
4362 guint32 *new_uid)
4364 struct mailimap_flag_list * flag_list;
4365 int r;
4367 cm_return_val_if_fail(file != NULL, MAILIMAP_ERROR_BAD_STATE);
4369 flag_list = imap_flag_to_lep(item, flags, NULL);
4370 lock_session(session);
4371 r = imap_threaded_append(session->folder, destfolder,
4372 file, flag_list, (int *)new_uid);
4373 mailimap_flag_list_free(flag_list);
4375 if (r != MAILIMAP_NO_ERROR) {
4376 imap_handle_error(SESSION(session), NULL, r);
4377 debug_print("append err %d\n", r);
4378 return r;
4381 unlock_session(session);
4383 return MAILIMAP_NO_ERROR;
4386 static gint imap_cmd_copy(IMAPSession *session, struct mailimap_set * set,
4387 const gchar *destfolder,
4388 struct mailimap_set **source, struct mailimap_set **dest)
4390 int r;
4392 g_return_val_if_fail(session != NULL, MAILIMAP_ERROR_BAD_STATE);
4393 g_return_val_if_fail(set != NULL, MAILIMAP_ERROR_BAD_STATE);
4394 g_return_val_if_fail(destfolder != NULL, MAILIMAP_ERROR_BAD_STATE);
4396 r = imap_threaded_copy(session->folder, set, destfolder, source, dest);
4397 if (r != MAILIMAP_NO_ERROR) {
4398 imap_handle_error(SESSION(session), NULL, r);
4399 return r;
4402 return MAILIMAP_NO_ERROR;
4405 static gint imap_cmd_store(IMAPSession *session,
4406 IMAPFolderItem *item,
4407 struct mailimap_set * set,
4408 IMAPFlags flags, GSList *tags, int do_add)
4410 int r;
4411 struct mailimap_flag_list * flag_list = NULL;
4412 struct mailimap_store_att_flags * store_att_flags;
4414 flag_list = imap_flag_to_lep(item, flags, tags);
4416 if (do_add)
4417 store_att_flags =
4418 mailimap_store_att_flags_new_add_flags_silent(flag_list);
4419 else
4420 store_att_flags =
4421 mailimap_store_att_flags_new_remove_flags_silent(flag_list);
4423 r = imap_threaded_store(session->folder, set, store_att_flags);
4424 mailimap_store_att_flags_free(store_att_flags);
4425 if (r != MAILIMAP_NO_ERROR) {
4426 imap_handle_error(SESSION(session), NULL, r);
4427 return r;
4430 return MAILIMAP_NO_ERROR;
4433 static gint imap_cmd_expunge(IMAPSession *session)
4435 int r;
4437 if (prefs_common.work_offline &&
4438 !inc_offline_should_override(FALSE,
4439 _("Claws Mail needs network access in order "
4440 "to access the IMAP server."))) {
4441 return -1;
4444 r = imap_threaded_expunge(session->folder);
4445 if (r != MAILIMAP_NO_ERROR) {
4446 imap_handle_error(SESSION(session), NULL, r);
4447 return r;
4450 return MAILIMAP_NO_ERROR;
4453 gint imap_expunge(Folder *folder, FolderItem *item)
4455 IMAPSession *session = imap_session_get(folder);
4456 if (session == NULL)
4457 return -1;
4459 return imap_cmd_expunge(session);
4462 static void imap_path_separator_subst(gchar *str, gchar separator)
4464 gchar *p;
4465 gboolean in_escape = FALSE;
4467 if (!separator || separator == '/') return;
4469 for (p = str; *p != '\0'; p++) {
4470 if (*p == '/' && !in_escape)
4471 *p = separator;
4472 else if (*p == '&' && *(p + 1) != '-' && !in_escape)
4473 in_escape = TRUE;
4474 else if (*p == '-' && in_escape)
4475 in_escape = FALSE;
4479 static gboolean imap_rename_folder_func(GNode *node, gpointer data)
4481 FolderItem *item = node->data;
4482 gchar **paths = data;
4483 const gchar *oldpath = paths[0];
4484 const gchar *newpath = paths[1];
4485 gchar *real_oldpath, *real_newpath;
4486 gchar *base;
4487 gchar *new_itempath;
4488 gint oldpathlen;
4489 IMAPSession *session = imap_session_get(item->folder);
4490 gint ok = MAILIMAP_NO_ERROR;
4491 oldpathlen = strlen(oldpath);
4492 if (strncmp(oldpath, item->path, oldpathlen) != 0) {
4493 g_warning("path doesn't match: %s, %s", oldpath, item->path);
4494 return TRUE;
4497 base = item->path + oldpathlen;
4498 while (*base == '/') base++;
4499 if (*base == '\0')
4500 new_itempath = g_strdup(newpath);
4501 else
4502 new_itempath = g_strconcat(newpath, "/", base,
4503 NULL);
4505 real_oldpath = imap_get_real_path(session, IMAP_FOLDER(item->folder), item->path, &ok);
4506 g_free(item->path);
4507 item->path = new_itempath;
4509 real_newpath = imap_get_real_path(session, IMAP_FOLDER(item->folder), item->path, &ok);
4511 imap_threaded_subscribe(item->folder, real_oldpath, FALSE);
4512 imap_threaded_subscribe(item->folder, real_newpath, TRUE);
4514 g_free(real_oldpath);
4515 g_free(real_newpath);
4516 return FALSE;
4519 static gint get_list_of_uids(IMAPSession *session, Folder *folder, IMAPFolderItem *item, GSList **msgnum_list)
4521 GSList *uidlist, *elem;
4522 int r = -1;
4523 clist * lep_uidlist;
4524 gint ok, nummsgs = 0;
4526 if (session == NULL) {
4527 return -1;
4530 ok = imap_select(session, IMAP_FOLDER(folder), FOLDER_ITEM(item),
4531 NULL, NULL, NULL, NULL, NULL, TRUE);
4532 if (ok != MAILIMAP_NO_ERROR) {
4533 return -1;
4536 g_slist_free(item->uid_list);
4537 item->uid_list = NULL;
4539 uidlist = NULL;
4541 if (folder->account && folder->account->low_bandwidth) {
4542 r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_SIMPLE,
4543 NULL, NULL, NULL, &lep_uidlist);
4546 if (r == MAILIMAP_NO_ERROR) {
4547 uidlist = imap_uid_list_from_lep(lep_uidlist, NULL);
4548 mailimap_search_result_free(lep_uidlist);
4549 } else {
4550 carray * lep_uidtab;
4551 if (r != -1) { /* inited */
4552 imap_handle_error(SESSION(session), NULL, r);
4553 if (is_fatal(r))
4554 return -1;
4556 r = imap_threaded_fetch_uid(folder, 1,
4557 &lep_uidtab);
4558 if (r == MAILIMAP_NO_ERROR) {
4559 uidlist = imap_uid_list_from_lep_tab(lep_uidtab);
4560 imap_fetch_uid_list_free(lep_uidtab);
4564 if (r != MAILIMAP_NO_ERROR) {
4565 imap_handle_error(SESSION(session), NULL, r);
4566 return -1;
4569 for (elem = uidlist; elem != NULL; elem = g_slist_next(elem)) {
4570 guint msgnum;
4572 msgnum = GPOINTER_TO_INT(elem->data);
4574 *msgnum_list = g_slist_prepend(*msgnum_list, GINT_TO_POINTER(msgnum));
4575 item->uid_list = g_slist_prepend(item->uid_list, GINT_TO_POINTER(msgnum));
4576 nummsgs++;
4578 g_slist_free(uidlist);
4580 return nummsgs;
4584 gint imap_get_num_list(Folder *folder, FolderItem *_item, GSList **msgnum_list, gboolean *old_uids_valid)
4586 IMAPFolderItem *item = (IMAPFolderItem *)_item;
4587 IMAPSession *session;
4588 gint nummsgs;
4589 GSList *uidlist = NULL;
4590 gchar *dir;
4591 gint known_list_len = 0;
4592 gchar *path;
4594 debug_print("get_num_list\n");
4596 g_return_val_if_fail(folder != NULL, -1);
4597 g_return_val_if_fail(item != NULL, -1);
4598 g_return_val_if_fail(item->item.path != NULL, -1);
4599 g_return_val_if_fail(FOLDER_CLASS(folder) == &imap_class, -1);
4600 g_return_val_if_fail(folder->account != NULL, -1);
4602 known_list_len = g_slist_length(item->uid_list);
4603 if (!item->should_update) {
4604 debug_print("get_num_list: nothing to update\n");
4605 *old_uids_valid = TRUE;
4606 if (known_list_len == item->item.total_msgs
4607 && known_list_len > 0) {
4608 *msgnum_list = g_slist_copy(item->uid_list);
4609 return known_list_len;
4610 } else {
4611 debug_print("don't know the list length...\n");
4615 if (prefs_common.work_offline &&
4616 !inc_offline_should_override(FALSE,
4617 _("Claws Mail needs network access in order "
4618 "to access the IMAP server."))) {
4619 return -1;
4622 path = folder_item_get_path(_item);
4623 if (!is_dir_exist(path)) {
4624 if(is_file_exist(path))
4625 claws_unlink(path);
4626 make_dir_hier(path);
4628 g_free(path);
4630 debug_print("getting session...\n");
4631 session = imap_session_get(folder);
4632 g_return_val_if_fail(session != NULL, -1);
4634 lock_session(session);
4635 if (FOLDER_ITEM(item)->path)
4636 statusbar_print_all(_("Scanning folder %s/%s..."),
4637 FOLDER_ITEM(item)->folder->name,
4638 FOLDER_ITEM(item)->path);
4639 else
4640 statusbar_print_all(_("Scanning folder %s..."),
4641 FOLDER_ITEM(item)->folder->name);
4643 if (item->should_trash_cache) {
4644 *old_uids_valid = FALSE;
4645 debug_print("get_num_list: trashing num list\n");
4646 debug_print("Freeing imap uid cache\n");
4647 item->lastuid = 0;
4648 g_slist_free(item->uid_list);
4649 item->uid_list = NULL;
4651 imap_delete_all_cached_messages((FolderItem *)item);
4652 } else {
4653 debug_print("get_num_list: updating num list\n");
4654 *old_uids_valid = TRUE;
4657 nummsgs = get_list_of_uids(session, folder, item, &uidlist);
4659 unlock_session(session);
4661 /* session could be broken now, in case of fatal error */
4663 debug_print("get_num_list: got %d msgs\n", nummsgs);
4665 if (nummsgs < 0) {
4666 statusbar_pop_all();
4667 return -1;
4670 *msgnum_list = uidlist;
4672 dir = folder_item_get_path((FolderItem *)item);
4673 debug_print("removing old messages from %s\n", dir);
4674 remove_numbered_files_not_in_list(dir, *msgnum_list);
4675 g_free(dir);
4677 debug_print("get_num_list - ok - %i\n", nummsgs);
4678 statusbar_pop_all();
4679 item->should_trash_cache = FALSE;
4680 item->should_update = FALSE;
4681 return nummsgs;
4684 static MsgInfo *imap_parse_msg(const gchar *file, FolderItem *item)
4686 MsgInfo *msginfo;
4687 MsgFlags flags;
4689 flags.perm_flags = MSG_NEW|MSG_UNREAD;
4690 flags.tmp_flags = 0;
4692 g_return_val_if_fail(item != NULL, NULL);
4693 g_return_val_if_fail(file != NULL, NULL);
4695 if (folder_has_parent_of_type(item, F_QUEUE)) {
4696 MSG_SET_TMP_FLAGS(flags, MSG_QUEUED);
4697 } else if (folder_has_parent_of_type(item, F_DRAFT)) {
4698 MSG_SET_TMP_FLAGS(flags, MSG_DRAFT);
4701 msginfo = procheader_parse_file(file, flags, FALSE, FALSE);
4702 if (!msginfo) return NULL;
4704 msginfo->plaintext_file = g_strdup(file);
4705 msginfo->folder = item;
4707 return msginfo;
4710 GSList *imap_get_msginfos(Folder *folder, FolderItem *item,
4711 GSList *msgnum_list)
4713 IMAPSession *session;
4714 MsgInfoList *ret = NULL;
4715 gint ok;
4717 debug_print("get_msginfos\n");
4719 g_return_val_if_fail(folder != NULL, NULL);
4720 g_return_val_if_fail(item != NULL, NULL);
4721 g_return_val_if_fail(msgnum_list != NULL, NULL);
4723 debug_print("getting session...\n");
4724 session = imap_session_get(folder);
4725 g_return_val_if_fail(session != NULL, NULL);
4727 lock_session(session); /* unlocked later in the function */
4729 debug_print("IMAP getting msginfos\n");
4730 ok = imap_select(session, IMAP_FOLDER(folder), item,
4731 NULL, NULL, NULL, NULL, NULL, FALSE);
4732 if (ok != MAILIMAP_NO_ERROR) {
4733 return NULL;
4735 if (!(folder_has_parent_of_type(item, F_DRAFT) ||
4736 folder_has_parent_of_type(item, F_QUEUE))) {
4737 ret = g_slist_concat(ret,
4738 imap_get_uncached_messages(session, item,
4739 msgnum_list, &ok));
4740 if (ok != MAILIMAP_NO_ERROR)
4741 return NULL;
4742 unlock_session(session);
4743 } else {
4744 MsgNumberList *sorted_list, *elem, *llast = NULL;
4745 gint startnum, lastnum;
4747 unlock_session(session);
4749 sorted_list = g_slist_sort(g_slist_copy(msgnum_list), g_int_compare);
4751 startnum = lastnum = GPOINTER_TO_INT(sorted_list->data);
4753 llast = g_slist_last(ret);
4754 for (elem = sorted_list;; elem = g_slist_next(elem)) {
4755 guint num = 0;
4757 if (elem)
4758 num = GPOINTER_TO_INT(elem->data);
4760 if (num > lastnum + 1 || elem == NULL) {
4761 int i;
4762 for (i = startnum; i <= lastnum; ++i) {
4763 gchar *file;
4764 file = imap_fetch_msg(folder, item, i);
4765 if (file != NULL) {
4766 MsgInfo *msginfo = imap_parse_msg(file, item);
4767 if (msginfo != NULL) {
4768 msginfo->msgnum = i;
4769 if (llast == NULL)
4770 llast = ret = g_slist_append(ret, msginfo);
4771 else {
4772 llast = g_slist_append(llast, msginfo);
4773 llast = llast->next;
4776 g_free(file);
4780 if (elem == NULL)
4781 break;
4783 startnum = num;
4785 lastnum = num;
4788 g_slist_free(sorted_list);
4790 return ret;
4793 MsgInfo *imap_get_msginfo(Folder *folder, FolderItem *item, gint uid)
4795 MsgInfo *msginfo = NULL;
4796 MsgInfoList *msginfolist;
4797 MsgNumberList numlist;
4799 numlist.next = NULL;
4800 numlist.data = GINT_TO_POINTER(uid);
4802 msginfolist = imap_get_msginfos(folder, item, &numlist);
4803 if (msginfolist != NULL) {
4804 msginfo = msginfolist->data;
4805 g_slist_free(msginfolist);
4808 return msginfo;
4811 gboolean imap_scan_required(Folder *folder, FolderItem *_item)
4813 IMAPSession *session;
4814 IMAPFolderItem *item = (IMAPFolderItem *)_item;
4815 gint ok, exists = 0, unseen = 0;
4816 guint32 uid_next = 0, uid_val = 0;
4817 gboolean selected_folder;
4819 g_return_val_if_fail(folder != NULL, FALSE);
4820 g_return_val_if_fail(item != NULL, FALSE);
4821 g_return_val_if_fail(item->item.folder != NULL, FALSE);
4822 g_return_val_if_fail(FOLDER_CLASS(item->item.folder) == &imap_class, FALSE);
4824 if (item->item.path == NULL)
4825 return FALSE;
4827 if (item->should_update) {
4828 debug_print("scan already required\n");
4829 return TRUE;
4831 debug_print("getting session...\n");
4832 session = imap_session_get(folder);
4834 g_return_val_if_fail(session != NULL, FALSE);
4835 lock_session(session); /* unlocked later in the function */
4837 selected_folder = (session->mbox != NULL) &&
4838 (!strcmp(session->mbox, item->item.path));
4839 if (selected_folder) {
4840 if (!session->folder_content_changed) {
4841 ok = imap_cmd_noop(session);
4842 if (ok != MAILIMAP_NO_ERROR) {
4843 debug_print("disconnected!\n");
4844 if (!is_fatal(ok))
4845 session = imap_reconnect_if_possible(folder, session);
4846 else
4847 session = imap_session_get(folder);
4848 if (session == NULL)
4849 return FALSE;
4852 if (session->folder_content_changed) {
4853 debug_print("CHANGED (self-noop)! scan_required\n");
4854 item->should_update = TRUE;
4855 if (session->uid_validity && session->uid_validity != item->item.mtime) {
4856 item->item.mtime = session->uid_validity;
4857 item->should_trash_cache = TRUE;
4859 unlock_session(session);
4860 return TRUE;
4862 } else {
4863 debug_print("CHANGED (previous noop)! scan_required\n");
4864 item->should_update = TRUE;
4865 if (session->uid_validity && session->uid_validity != item->item.mtime) {
4866 item->item.mtime = session->uid_validity;
4867 item->should_trash_cache = TRUE;
4869 unlock_session(session);
4870 return TRUE;
4872 } else {
4873 ok = imap_status(session, IMAP_FOLDER(folder), item->item.path, IMAP_FOLDER_ITEM(item),
4874 &exists, &uid_next, &uid_val, &unseen, FALSE);
4875 if (ok != MAILIMAP_NO_ERROR) {
4876 return FALSE;
4879 debug_print("exists %d, item->item.total_msgs %d\n"
4880 "\tunseen %d, item->item.unread_msgs %d\n"
4881 "\tuid_next %d, item->uid_next %d\n"
4882 "\tuid_val %d, item->item.mtime %ld\n",
4883 exists, item->item.total_msgs, unseen, item->item.unread_msgs,
4884 uid_next, item->uid_next, uid_val, (long)(item->item.mtime));
4885 if (exists != item->item.total_msgs
4886 || unseen != item->item.unread_msgs
4887 || uid_next != item->uid_next
4888 || uid_val != item->item.mtime) {
4889 debug_print("CHANGED (status)! scan_required\n");
4890 item->last_change = time(NULL);
4891 item->should_update = TRUE;
4892 item->uid_next = uid_next;
4893 if (uid_val != item->item.mtime) {
4894 item->item.mtime = uid_val;
4895 item->should_trash_cache = TRUE;
4897 unlock_session(session);
4898 return TRUE;
4901 unlock_session(session);
4903 item->should_update = FALSE;
4904 return FALSE;
4907 void imap_change_flags(Folder *folder, FolderItem *item, MsgInfo *msginfo, MsgPermFlags newflags)
4909 IMAPSession *session;
4910 IMAPFlags flags_set = 0, flags_unset = 0;
4911 gint ok = MAILIMAP_NO_ERROR;
4912 MsgNumberList numlist;
4913 hashtable_data *ht_data = NULL;
4915 g_return_if_fail(folder != NULL);
4916 g_return_if_fail(folder->klass == &imap_class);
4917 g_return_if_fail(item != NULL);
4918 g_return_if_fail(item->folder == folder);
4919 g_return_if_fail(msginfo != NULL);
4920 g_return_if_fail(msginfo->folder == item);
4922 if (!MSG_IS_MARKED(msginfo->flags) && (newflags & MSG_MARKED))
4923 flags_set |= IMAP_FLAG_FLAGGED;
4924 if ( MSG_IS_MARKED(msginfo->flags) && !(newflags & MSG_MARKED))
4925 flags_unset |= IMAP_FLAG_FLAGGED;
4927 if (!MSG_IS_UNREAD(msginfo->flags) && (newflags & MSG_UNREAD))
4928 flags_unset |= IMAP_FLAG_SEEN;
4929 if ( MSG_IS_UNREAD(msginfo->flags) && !(newflags & MSG_UNREAD))
4930 flags_set |= IMAP_FLAG_SEEN;
4932 if (!MSG_IS_REPLIED(msginfo->flags) && (newflags & MSG_REPLIED))
4933 flags_set |= IMAP_FLAG_ANSWERED;
4934 if ( MSG_IS_REPLIED(msginfo->flags) && !(newflags & MSG_REPLIED))
4935 flags_unset |= IMAP_FLAG_ANSWERED;
4937 if (!MSG_IS_FORWARDED(msginfo->flags) && (newflags & MSG_FORWARDED))
4938 flags_set |= IMAP_FLAG_FORWARDED;
4939 if ( MSG_IS_FORWARDED(msginfo->flags) && !(newflags & MSG_FORWARDED))
4940 flags_unset |= IMAP_FLAG_FORWARDED;
4942 if (!MSG_IS_SPAM(msginfo->flags) && (newflags & MSG_SPAM)) {
4943 flags_set |= IMAP_FLAG_SPAM;
4944 flags_unset |= IMAP_FLAG_HAM;
4946 if ( MSG_IS_SPAM(msginfo->flags) && !(newflags & MSG_SPAM)) {
4947 flags_set |= IMAP_FLAG_HAM;
4948 flags_unset |= IMAP_FLAG_SPAM;
4950 if (!MSG_IS_DELETED(msginfo->flags) && (newflags & MSG_DELETED))
4951 flags_set |= IMAP_FLAG_DELETED;
4952 if ( MSG_IS_DELETED(msginfo->flags) && !(newflags & MSG_DELETED))
4953 flags_unset |= IMAP_FLAG_DELETED;
4955 if (!flags_set && !flags_unset) {
4956 /* the changed flags were not translatable to IMAP-speak.
4957 * like MSG_POSTFILTERED, so just apply. */
4958 msginfo->flags.perm_flags = newflags;
4959 return;
4962 debug_print("getting session...\n");
4963 session = imap_session_get(folder);
4964 if (!session) {
4965 return;
4968 if ((ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder,
4969 NULL, NULL, NULL, NULL, NULL, FALSE)) != MAILIMAP_NO_ERROR) {
4970 return;
4972 numlist.next = NULL;
4973 numlist.data = GINT_TO_POINTER(msginfo->msgnum);
4975 if (IMAP_FOLDER_ITEM(item)->batching) {
4976 /* instead of performing an UID STORE command for each message change,
4977 * as a lot of them can change "together", we just fill in hashtables
4978 * and defer the treatment so that we're able to send only one
4979 * command.
4981 debug_print("IMAP batch mode on, deferring flags change\n");
4982 if (flags_set) {
4983 ht_data = g_hash_table_lookup(IMAP_FOLDER_ITEM(item)->flags_set_table,
4984 GINT_TO_POINTER(flags_set));
4985 if (ht_data == NULL) {
4986 ht_data = g_new0(hashtable_data, 1);
4987 ht_data->item = IMAP_FOLDER_ITEM(item);
4988 g_hash_table_insert(IMAP_FOLDER_ITEM(item)->flags_set_table,
4989 GINT_TO_POINTER(flags_set), ht_data);
4991 ht_data->msglist = g_slist_prepend(ht_data->msglist, GINT_TO_POINTER(msginfo->msgnum));
4993 if (flags_unset) {
4994 ht_data = g_hash_table_lookup(IMAP_FOLDER_ITEM(item)->flags_unset_table,
4995 GINT_TO_POINTER(flags_unset));
4996 if (ht_data == NULL) {
4997 ht_data = g_new0(hashtable_data, 1);
4998 ht_data->item = IMAP_FOLDER_ITEM(item);
4999 g_hash_table_insert(IMAP_FOLDER_ITEM(item)->flags_unset_table,
5000 GINT_TO_POINTER(flags_unset), ht_data);
5002 ht_data->msglist = g_slist_prepend(ht_data->msglist,
5003 GINT_TO_POINTER(msginfo->msgnum));
5005 } else {
5006 debug_print("IMAP changing flags\n");
5007 if (flags_set) {
5008 ok = imap_set_message_flags(session, IMAP_FOLDER_ITEM(item), &numlist, flags_set, NULL, TRUE);
5009 if (ok != MAILIMAP_NO_ERROR) {
5010 return;
5014 if (flags_unset) {
5015 ok = imap_set_message_flags(session, IMAP_FOLDER_ITEM(item), &numlist, flags_unset, NULL, FALSE);
5016 if (ok != MAILIMAP_NO_ERROR) {
5017 return;
5021 msginfo->flags.perm_flags = newflags;
5022 return;
5025 static gint imap_remove_msg(Folder *folder, FolderItem *item, gint uid)
5027 gint ok;
5028 IMAPSession *session;
5029 gchar *dir;
5030 MsgNumberList numlist;
5032 g_return_val_if_fail(folder != NULL, -1);
5033 g_return_val_if_fail(FOLDER_CLASS(folder) == &imap_class, -1);
5034 g_return_val_if_fail(item != NULL, -1);
5036 debug_print("getting session...\n");
5037 session = imap_session_get(folder);
5038 if (!session) return -1;
5040 ok = imap_select(session, IMAP_FOLDER(folder), item,
5041 NULL, NULL, NULL, NULL, NULL, FALSE);
5042 if (ok != MAILIMAP_NO_ERROR) {
5043 return ok;
5045 numlist.next = NULL;
5046 numlist.data = GINT_TO_POINTER(uid);
5048 ok = imap_set_message_flags
5049 (session, IMAP_FOLDER_ITEM(item), &numlist, IMAP_FLAG_DELETED, NULL, TRUE);
5050 if (ok != MAILIMAP_NO_ERROR) {
5051 log_warning(LOG_PROTOCOL, _("can't set deleted flags: %d\n"), uid);
5052 return ok;
5055 ok = imap_cmd_expunge(session);
5057 if (ok != MAILIMAP_NO_ERROR) {
5058 log_warning(LOG_PROTOCOL, _("can't expunge\n"));
5059 return ok;
5062 IMAP_FOLDER_ITEM(item)->uid_list = g_slist_remove(
5063 IMAP_FOLDER_ITEM(item)->uid_list, numlist.data);
5064 dir = folder_item_get_path(item);
5065 if (is_dir_exist(dir))
5066 remove_numbered_files(dir, uid, uid);
5067 g_free(dir);
5068 return MAILIMAP_NO_ERROR;
5071 static gint compare_msginfo(gconstpointer a, gconstpointer b)
5073 return ((MsgInfo *)a)->msgnum - ((MsgInfo *)b)->msgnum;
5076 static guint gslist_find_next_num(MsgNumberList **list, guint num)
5078 GSList *elem;
5080 g_return_val_if_fail(list != NULL, -1);
5082 for (elem = *list; elem != NULL; elem = g_slist_next(elem))
5083 if (GPOINTER_TO_INT(elem->data) >= num)
5084 break;
5085 *list = elem;
5086 return elem != NULL ? GPOINTER_TO_INT(elem->data) : (gint)-1;
5089 static gboolean flag_ok(IMAPFolderItem *item, guint flag)
5091 if (item->ok_flags && g_slist_find(item->ok_flags, GUINT_TO_POINTER(flag))) {
5092 debug_print("flag %d is OK\n", flag);
5093 return TRUE;
5095 if (item->can_create_flags == ITEM_CAN_CREATE_FLAGS) {
5096 debug_print("creating flags is OK\n");
5097 return TRUE;
5099 return FALSE;
5103 * NEW and DELETED flags are not syncronized
5104 * - The NEW/RECENT flags in IMAP folders can not really be directly
5105 * modified by Sylpheed
5106 * - The DELETE/DELETED flag in IMAP and Sylpheed don't have the same
5107 * meaning, in IMAP it always removes the messages from the FolderItem
5108 * in Sylpheed it can mean to move the message to trash
5111 typedef struct _get_flags_data {
5112 Folder *folder;
5113 FolderItem *item;
5114 MsgInfoList *msginfo_list;
5115 GHashTable *msgflags;
5116 gboolean full_search;
5117 gboolean done;
5118 } get_flags_data;
5120 static /*gint*/ void *imap_get_flags_thread(void *data)
5122 get_flags_data *stuff = (get_flags_data *)data;
5123 Folder *folder = stuff->folder;
5124 FolderItem *fitem = (FolderItem *) stuff->item;
5125 MsgInfoList *msginfo_list = stuff->msginfo_list;
5126 GHashTable *msgflags = stuff->msgflags;
5127 GSList *elem;
5128 carray * lep_uidtab;
5129 IMAPSession *session;
5130 gint ok;
5131 int r = MAILIMAP_NO_ERROR;
5132 GHashTable *flags_hash = NULL;
5133 GHashTable *tags_hash = NULL;
5134 gboolean full_search = stuff->full_search;
5135 GSList *sorted_list = NULL;
5136 GSList *unseen = NULL, *answered = NULL, *flagged = NULL, *deleted = NULL, *forwarded = NULL, *spam = NULL;
5137 GSList *seq_list, *cur;
5138 gboolean reverse_seen = FALSE;
5139 gboolean selected_folder;
5140 gint exists_cnt, unseen_cnt;
5141 gboolean got_alien_tags = FALSE;
5143 session = imap_session_get(folder);
5145 if (session == NULL) {
5146 stuff->done = TRUE;
5147 return GINT_TO_POINTER(-1);
5149 selected_folder = (session->mbox != NULL) &&
5150 (!strcmp(session->mbox, fitem->path));
5152 lock_session(session);
5153 if (!selected_folder) {
5154 ok = imap_select(session, IMAP_FOLDER(folder), fitem,
5155 &exists_cnt, NULL, &unseen_cnt, NULL, NULL, TRUE);
5156 if (ok != MAILIMAP_NO_ERROR) {
5157 stuff->done = TRUE;
5158 return GINT_TO_POINTER(-1);
5161 if (unseen_cnt > exists_cnt / 2)
5162 reverse_seen = TRUE;
5164 else {
5165 if (fitem->unread_msgs > fitem->total_msgs / 2)
5166 reverse_seen = TRUE;
5169 sorted_list = g_slist_sort(g_slist_copy(msginfo_list), compare_msginfo);
5170 if (!full_search) {
5171 seq_list = imap_get_lep_set_from_msglist(IMAP_FOLDER(folder), msginfo_list);
5172 } else {
5173 struct mailimap_set * set;
5174 set = mailimap_set_new_interval(1, 0);
5175 seq_list = g_slist_append(NULL, set);
5178 if (folder->account && folder->account->low_bandwidth) {
5179 for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
5180 struct mailimap_set * imapset;
5181 clist * lep_uidlist;
5182 int r;
5184 imapset = cur->data;
5185 if (reverse_seen) {
5186 r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_SEEN, NULL,
5187 NULL, full_search ? NULL:imapset, &lep_uidlist);
5189 else {
5190 r = imap_threaded_search(folder,
5191 IMAP_SEARCH_TYPE_UNSEEN, NULL,
5192 NULL, full_search ? NULL:imapset, &lep_uidlist);
5194 if (r == MAILIMAP_NO_ERROR) {
5195 GSList * uidlist;
5197 uidlist = imap_uid_list_from_lep(lep_uidlist, NULL);
5198 mailimap_search_result_free(lep_uidlist);
5200 unseen = g_slist_concat(unseen, uidlist);
5201 } else {
5202 imap_handle_error(SESSION(session), NULL, r);
5203 goto bail;
5206 r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_FLAGGED, NULL,
5207 NULL, full_search ? NULL:imapset, &lep_uidlist);
5208 if (r == MAILIMAP_NO_ERROR) {
5209 GSList * uidlist;
5211 uidlist = imap_uid_list_from_lep(lep_uidlist, NULL);
5212 mailimap_search_result_free(lep_uidlist);
5214 flagged = g_slist_concat(flagged, uidlist);
5215 } else {
5216 imap_handle_error(SESSION(session), NULL, r);
5217 goto bail;
5220 if (fitem->opened || fitem->processing_pending || fitem == folder->inbox) {
5221 r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_ANSWERED, NULL,
5222 NULL, full_search ? NULL:imapset, &lep_uidlist);
5223 if (r == MAILIMAP_NO_ERROR) {
5224 GSList * uidlist;
5226 uidlist = imap_uid_list_from_lep(lep_uidlist, NULL);
5227 mailimap_search_result_free(lep_uidlist);
5229 answered = g_slist_concat(answered, uidlist);
5230 } else {
5231 imap_handle_error(SESSION(session), NULL, r);
5232 goto bail;
5235 if (flag_ok(IMAP_FOLDER_ITEM(fitem), IMAP_FLAG_FORWARDED)) {
5236 r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_FORWARDED, NULL,
5237 NULL, full_search ? NULL:imapset, &lep_uidlist);
5238 if (r == MAILIMAP_NO_ERROR) {
5239 GSList * uidlist;
5241 uidlist = imap_uid_list_from_lep(lep_uidlist, NULL);
5242 mailimap_search_result_free(lep_uidlist);
5244 forwarded = g_slist_concat(forwarded, uidlist);
5245 } else {
5246 imap_handle_error(SESSION(session), NULL, r);
5247 goto bail;
5251 if (flag_ok(IMAP_FOLDER_ITEM(fitem), IMAP_FLAG_SPAM)) {
5252 r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_SPAM, NULL,
5253 NULL, full_search ? NULL:imapset, &lep_uidlist);
5254 if (r == MAILIMAP_NO_ERROR) {
5255 GSList * uidlist;
5257 uidlist = imap_uid_list_from_lep(lep_uidlist, NULL);
5258 mailimap_search_result_free(lep_uidlist);
5260 spam = g_slist_concat(spam, uidlist);
5261 } else {
5262 imap_handle_error(SESSION(session), NULL, r);
5263 goto bail;
5267 r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_DELETED, NULL,
5268 NULL, full_search ? NULL:imapset, &lep_uidlist);
5269 if (r == MAILIMAP_NO_ERROR) {
5270 GSList * uidlist;
5272 uidlist = imap_uid_list_from_lep(lep_uidlist, NULL);
5273 mailimap_search_result_free(lep_uidlist);
5275 deleted = g_slist_concat(deleted, uidlist);
5276 } else {
5277 imap_handle_error(SESSION(session), NULL, r);
5278 goto bail;
5283 } else {
5284 r = imap_threaded_fetch_uid_flags(folder, 1, &lep_uidtab);
5285 if (r == MAILIMAP_NO_ERROR) {
5286 flags_hash = g_hash_table_new_full(g_direct_hash, g_direct_equal, NULL, NULL);
5287 tags_hash = g_hash_table_new_full(g_direct_hash, g_direct_equal, NULL, NULL);
5288 imap_flags_hash_from_lep_uid_flags_tab(lep_uidtab, flags_hash, tags_hash);
5289 imap_fetch_uid_flags_list_free(lep_uidtab);
5290 } else {
5291 imap_handle_error(SESSION(session), NULL, r);
5292 goto bail;
5296 bail:
5297 if (r == MAILIMAP_NO_ERROR)
5298 unlock_session(session);
5300 for (elem = sorted_list; elem != NULL; elem = g_slist_next(elem)) {
5301 MsgInfo *msginfo;
5302 MsgPermFlags flags, oldflags;
5303 gboolean wasnew;
5305 msginfo = (MsgInfo *) elem->data;
5306 flags = msginfo->flags.perm_flags;
5307 wasnew = (flags & MSG_NEW);
5308 oldflags = flags & ~(MSG_NEW|MSG_UNREAD|MSG_REPLIED|MSG_FORWARDED|MSG_MARKED|MSG_DELETED|MSG_SPAM);
5310 if (folder->account && folder->account->low_bandwidth) {
5311 if (fitem->opened || fitem->processing_pending || fitem == folder->inbox) {
5312 flags &= ~((reverse_seen ? 0 : MSG_UNREAD | MSG_NEW) | MSG_REPLIED | MSG_FORWARDED | MSG_MARKED | MSG_SPAM);
5313 } else {
5314 flags &= ~((reverse_seen ? 0 : MSG_UNREAD | MSG_NEW | MSG_MARKED));
5316 if (reverse_seen)
5317 flags |= MSG_UNREAD | (wasnew ? MSG_NEW : 0);
5318 if (gslist_find_next_num(&unseen, msginfo->msgnum) == msginfo->msgnum) {
5319 if (!reverse_seen) {
5320 flags |= MSG_UNREAD | (wasnew ? MSG_NEW : 0);
5321 } else {
5322 flags &= ~(MSG_UNREAD | MSG_NEW);
5326 if (gslist_find_next_num(&flagged, msginfo->msgnum) == msginfo->msgnum)
5327 flags |= MSG_MARKED;
5328 else
5329 flags &= ~MSG_MARKED;
5331 if (fitem->opened || fitem->processing_pending || fitem == folder->inbox) {
5332 if (gslist_find_next_num(&answered, msginfo->msgnum) == msginfo->msgnum)
5333 flags |= MSG_REPLIED;
5334 else
5335 flags &= ~MSG_REPLIED;
5336 if (gslist_find_next_num(&forwarded, msginfo->msgnum) == msginfo->msgnum)
5337 flags |= MSG_FORWARDED;
5338 else
5339 flags &= ~MSG_FORWARDED;
5340 if (gslist_find_next_num(&spam, msginfo->msgnum) == msginfo->msgnum)
5341 flags |= MSG_SPAM;
5342 else
5343 flags &= ~MSG_SPAM;
5344 if (gslist_find_next_num(&deleted, msginfo->msgnum) == msginfo->msgnum)
5345 flags |= MSG_DELETED;
5346 else
5347 flags &= ~MSG_DELETED;
5349 } else {
5350 if (flags_hash != NULL) {
5352 flags = GPOINTER_TO_INT(g_hash_table_lookup(flags_hash,
5353 GINT_TO_POINTER(msginfo->msgnum)));
5356 if ((flags & MSG_UNREAD) == 0)
5357 flags &= ~MSG_NEW;
5358 else if (wasnew)
5359 flags |= MSG_NEW;
5360 flags |= oldflags;
5362 if (tags_hash != NULL) {
5363 GSList *tags = g_hash_table_lookup(tags_hash, GINT_TO_POINTER(msginfo->msgnum));
5364 GSList *cur;
5366 g_slist_free(msginfo->tags);
5367 msginfo->tags = NULL;
5369 for (cur = tags; cur; cur = cur->next) {
5370 gchar *real_tag = imap_modified_utf7_to_utf8(cur->data, TRUE);
5371 gint id = 0;
5372 id = tags_get_id_for_str(real_tag);
5373 if (id == -1) {
5374 id = tags_add_tag(real_tag);
5375 got_alien_tags = TRUE;
5377 msginfo->tags = g_slist_append(
5378 msginfo->tags,
5379 GINT_TO_POINTER(id));
5380 g_free(real_tag);
5382 slist_free_strings_full(tags);
5386 g_hash_table_insert(msgflags, msginfo, GINT_TO_POINTER(flags));
5389 if (got_alien_tags) {
5390 tags_write_tags();
5391 main_window_reflect_tags_changes(mainwindow_get_mainwindow());
5394 if (flags_hash)
5395 g_hash_table_destroy(flags_hash);
5396 if (tags_hash)
5397 g_hash_table_destroy(tags_hash);
5399 imap_lep_set_free(seq_list);
5400 g_slist_free(flagged);
5401 g_slist_free(deleted);
5402 g_slist_free(answered);
5403 g_slist_free(forwarded);
5404 g_slist_free(spam);
5405 g_slist_free(unseen);
5406 g_slist_free(sorted_list);
5408 stuff->done = TRUE;
5409 return GINT_TO_POINTER(0);
5412 static gint imap_get_flags(Folder *folder, FolderItem *item,
5413 MsgInfoList *msginfo_list, GHashTable *msgflags)
5415 gint result;
5416 get_flags_data *data = g_new0(get_flags_data, 1);
5417 data->done = FALSE;
5418 data->folder = folder;
5419 data->item = item;
5420 data->msginfo_list = msginfo_list;
5421 data->msgflags = msgflags;
5422 data->full_search = FALSE;
5424 GSList *tmp = NULL, *cur;
5426 if (prefs_common.work_offline &&
5427 !inc_offline_should_override(FALSE,
5428 _("Claws Mail needs network access in order "
5429 "to access the IMAP server."))) {
5430 g_free(data);
5431 return -1;
5434 tmp = folder_item_get_msg_list(item);
5436 if (g_slist_length(tmp) <= g_slist_length(msginfo_list))
5437 data->full_search = TRUE;
5439 for (cur = tmp; cur; cur = cur->next)
5440 procmsg_msginfo_free((MsgInfo **)&(cur->data));
5442 g_slist_free(tmp);
5444 result = GPOINTER_TO_INT(imap_get_flags_thread(data));
5446 g_free(data);
5447 return result;
5451 static gboolean process_flags(gpointer key, gpointer value, gpointer user_data)
5453 gboolean flags_set = GPOINTER_TO_INT(user_data);
5454 gint flags_value = GPOINTER_TO_INT(key);
5455 hashtable_data *data = (hashtable_data *)value;
5456 IMAPFolderItem *_item = data->item;
5457 FolderItem *item = (FolderItem *)_item;
5458 gint ok = MAILIMAP_ERROR_BAD_STATE;
5459 IMAPSession *session = NULL;
5461 debug_print("getting session...\n");
5462 session = imap_session_get(item->folder);
5464 data->msglist = g_slist_reverse(data->msglist);
5466 debug_print("IMAP %ssetting flags to %d for %d messages\n",
5467 flags_set?"":"un",
5468 flags_value,
5469 g_slist_length(data->msglist));
5471 lock_session(session);
5472 if (session) {
5473 ok = imap_select(session, IMAP_FOLDER(item->folder), item,
5474 NULL, NULL, NULL, NULL, NULL, FALSE);
5476 if (ok == MAILIMAP_NO_ERROR) {
5477 ok = imap_set_message_flags(session, IMAP_FOLDER_ITEM(item),
5478 data->msglist, flags_value, NULL, flags_set);
5479 } else {
5480 g_warning("can't select mailbox %s", item->path);
5483 if (!is_fatal(ok))
5484 unlock_session(session);
5486 g_slist_free(data->msglist);
5487 g_free(data);
5488 return TRUE;
5491 static gboolean process_tags(gpointer key, gpointer value, gpointer user_data)
5493 gboolean tags_set = GPOINTER_TO_INT(user_data);
5494 TagsData *data = (TagsData *)value;
5495 IMAPFolderItem *_item = data->item;
5496 FolderItem *item = (FolderItem *)_item;
5497 gchar *str = data->str;
5498 gint ok = MAILIMAP_ERROR_BAD_STATE;
5499 IMAPSession *session = NULL;
5501 debug_print("getting session...\n");
5502 session = imap_session_get(item->folder);
5504 data->msglist = g_slist_reverse(data->msglist);
5506 debug_print("IMAP %ssetting tags %s for %d messages\n",
5507 tags_set?"":"un",
5508 str,
5509 g_slist_length(data->msglist));
5511 lock_session(session);
5512 if (session) {
5513 ok = imap_select(session, IMAP_FOLDER(item->folder), item,
5514 NULL, NULL, NULL, NULL, NULL, FALSE);
5516 if (ok == MAILIMAP_NO_ERROR) {
5517 GSList list;
5518 list.data = str;
5519 list.next = NULL;
5520 ok = imap_set_message_flags(session, IMAP_FOLDER_ITEM(item),
5521 data->msglist, 0, &list, tags_set);
5522 } else {
5523 g_warning("can't select mailbox %s", item->path);
5526 if (!is_fatal(ok))
5527 unlock_session(session);
5529 g_slist_free(data->msglist);
5530 g_free(data->str);
5531 g_free(data);
5532 return TRUE;
5535 static void process_hashtable(IMAPFolderItem *item)
5537 if (item->flags_set_table) {
5538 g_hash_table_foreach_remove(item->flags_set_table, process_flags, GINT_TO_POINTER(TRUE));
5539 g_hash_table_destroy(item->flags_set_table);
5540 item->flags_set_table = NULL;
5542 if (item->flags_unset_table) {
5543 g_hash_table_foreach_remove(item->flags_unset_table, process_flags, GINT_TO_POINTER(FALSE));
5544 g_hash_table_destroy(item->flags_unset_table);
5545 item->flags_unset_table = NULL;
5547 if (item->tags_set_table) {
5548 g_hash_table_foreach_remove(item->tags_set_table, process_tags, GINT_TO_POINTER(TRUE));
5549 g_hash_table_destroy(item->tags_set_table);
5550 item->tags_set_table = NULL;
5552 if (item->tags_unset_table) {
5553 g_hash_table_foreach_remove(item->tags_unset_table, process_tags, GINT_TO_POINTER(FALSE));
5554 g_hash_table_destroy(item->tags_unset_table);
5555 item->tags_unset_table = NULL;
5560 static void imap_set_batch (Folder *folder, FolderItem *_item, gboolean batch)
5562 IMAPFolderItem *item = (IMAPFolderItem *)_item;
5563 IMAPSession *session;
5565 g_return_if_fail(item != NULL);
5567 if (item->batching == batch)
5568 return;
5570 if (batch) {
5571 item->batching = TRUE;
5572 debug_print("IMAP switching to batch mode\n");
5573 if (!item->flags_set_table) {
5574 item->flags_set_table = g_hash_table_new(NULL, g_direct_equal);
5576 if (!item->flags_unset_table) {
5577 item->flags_unset_table = g_hash_table_new(NULL, g_direct_equal);
5579 if (!item->tags_set_table) {
5580 item->tags_set_table = g_hash_table_new(NULL, g_direct_equal);
5582 if (!item->tags_unset_table) {
5583 item->tags_unset_table = g_hash_table_new(NULL, g_direct_equal);
5585 session = imap_session_get(folder);
5586 if (session) {
5587 imap_refresh_sensitivity(session);
5588 session->sens_update_block = TRUE;
5590 } else {
5591 debug_print("IMAP switching away from batch mode\n");
5592 /* process stuff */
5593 process_hashtable(item);
5594 item->batching = FALSE;
5595 session = imap_session_get(folder);
5596 if (session) {
5597 session->sens_update_block = FALSE;
5598 imap_refresh_sensitivity(session);
5605 /* data types conversion libetpan <-> claws */
5609 #define ETPAN_IMAP_MB_MARKED 1
5610 #define ETPAN_IMAP_MB_UNMARKED 2
5611 #define ETPAN_IMAP_MB_NOSELECT 4
5612 #define ETPAN_IMAP_MB_NOINFERIORS 8
5614 static int imap_flags_to_flags(struct mailimap_mbx_list_flags * imap_flags)
5616 int flags;
5617 clistiter * cur;
5619 flags = 0;
5620 if (imap_flags->mbf_type == MAILIMAP_MBX_LIST_FLAGS_SFLAG) {
5621 switch (imap_flags->mbf_sflag) {
5622 case MAILIMAP_MBX_LIST_SFLAG_MARKED:
5623 flags |= ETPAN_IMAP_MB_MARKED;
5624 break;
5625 case MAILIMAP_MBX_LIST_SFLAG_NOSELECT:
5626 flags |= ETPAN_IMAP_MB_NOSELECT;
5627 break;
5628 case MAILIMAP_MBX_LIST_SFLAG_UNMARKED:
5629 flags |= ETPAN_IMAP_MB_UNMARKED;
5630 break;
5634 if (imap_flags->mbf_oflags) {
5635 for(cur = clist_begin(imap_flags->mbf_oflags) ; cur != NULL ;
5636 cur = clist_next(cur)) {
5637 struct mailimap_mbx_list_oflag * oflag;
5639 oflag = clist_content(cur);
5641 switch (oflag->of_type) {
5642 case MAILIMAP_MBX_LIST_OFLAG_NOINFERIORS:
5643 flags |= ETPAN_IMAP_MB_NOINFERIORS;
5644 break;
5648 return flags;
5651 static GSList * imap_list_from_lep(IMAPFolder * folder,
5652 clist * list, const gchar * real_path, gboolean all)
5654 clistiter * iter;
5655 GSList * item_list = NULL, *llast = NULL;
5657 if (list) {
5658 for(iter = clist_begin(list) ; iter != NULL ;
5659 iter = clist_next(iter)) {
5660 struct mailimap_mailbox_list * mb;
5661 int flags;
5662 char delimiter;
5663 char * name;
5664 char * dup_name;
5665 gchar * base;
5666 gchar * loc_name;
5667 gchar * loc_path;
5668 FolderItem *new_item;
5670 mb = clist_content(iter);
5672 if (mb == NULL)
5673 continue;
5675 flags = 0;
5676 if (mb->mb_flag != NULL)
5677 flags = imap_flags_to_flags(mb->mb_flag);
5679 delimiter = mb->mb_delimiter;
5680 name = mb->mb_name;
5682 dup_name = strdup(name);
5683 if (delimiter != '\0')
5684 subst_char(dup_name, delimiter, '/');
5686 base = g_path_get_basename(dup_name);
5687 if (base[0] == '.') {
5688 g_free(base);
5689 free(dup_name);
5690 continue;
5692 if (!all && path_cmp(name, real_path) == 0) {
5693 g_free(base);
5694 free(dup_name);
5695 continue;
5698 if (!all && dup_name[strlen(dup_name)-1] == '/') {
5699 g_free(base);
5700 free(dup_name);
5701 continue;
5704 loc_name = imap_modified_utf7_to_utf8(base, FALSE);
5705 loc_path = imap_modified_utf7_to_utf8(dup_name, FALSE);
5707 new_item = folder_item_new(FOLDER(folder), loc_name, loc_path);
5708 if ((flags & ETPAN_IMAP_MB_NOINFERIORS) != 0)
5709 new_item->no_sub = TRUE;
5710 if (strcasecmp(dup_name, "INBOX") != 0 &&
5711 ((flags & ETPAN_IMAP_MB_NOSELECT) != 0))
5712 new_item->no_select = TRUE;
5714 if (item_list == NULL)
5715 llast = item_list = g_slist_append(item_list, new_item);
5716 else {
5717 llast = g_slist_append(llast, new_item);
5718 llast = llast->next;
5720 debug_print("folder '%s' found.\n", loc_path);
5721 g_free(base);
5722 g_free(loc_path);
5723 g_free(loc_name);
5725 free(dup_name);
5728 return item_list;
5731 static GSList * imap_get_lep_set_from_numlist(IMAPFolder *folder, MsgNumberList *numlist)
5733 GSList *sorted_list, *cur;
5734 guint first, last, next;
5735 GSList *ret_list = NULL, *llast = NULL;
5736 struct mailimap_set * current_set;
5737 unsigned int item_count;
5739 if (numlist == NULL)
5740 return NULL;
5742 current_set = mailimap_set_new_empty();
5744 sorted_list = g_slist_copy(numlist);
5745 sorted_list = g_slist_sort(sorted_list, g_int_compare);
5747 first = GPOINTER_TO_INT(sorted_list->data);
5749 item_count = 0;
5750 for (cur = sorted_list; cur != NULL; cur = g_slist_next(cur)) {
5751 if (GPOINTER_TO_INT(cur->data) == 0)
5752 continue;
5754 item_count ++;
5756 last = GPOINTER_TO_INT(cur->data);
5757 if (cur->next)
5758 next = GPOINTER_TO_INT(cur->next->data);
5759 else
5760 next = 0;
5762 if (last + 1 != next || next == 0 || item_count >= folder->max_set_size) {
5764 struct mailimap_set_item * item;
5765 item = mailimap_set_item_new(first, last);
5766 mailimap_set_add(current_set, item);
5768 first = next;
5770 if (item_count >= folder->max_set_size) {
5771 if (ret_list == NULL)
5772 llast = ret_list = g_slist_append(ret_list,
5773 current_set);
5774 else {
5775 llast = g_slist_append(llast, current_set);
5776 llast = llast->next;
5779 current_set = mailimap_set_new_empty();
5780 item_count = 0;
5785 if (clist_count(current_set->set_list) > 0) {
5786 ret_list = g_slist_append(ret_list,
5787 current_set);
5790 g_slist_free(sorted_list);
5792 return ret_list;
5795 static GSList * imap_get_lep_set_from_msglist(IMAPFolder *folder, MsgInfoList *msglist)
5797 MsgNumberList *numlist = NULL;
5798 GSList *seq_list;
5800 numlist = procmsg_get_number_list_for_msgs(msglist);
5802 seq_list = imap_get_lep_set_from_numlist(folder, numlist);
5803 g_slist_free(numlist);
5805 return seq_list;
5808 static GSList * imap_uid_list_from_lep(clist * list, gint* length)
5810 clistiter * iter;
5811 GSList * result;
5812 gint len = 0;
5814 result = NULL;
5816 if (list) {
5817 for(iter = clist_begin(list) ; iter != NULL ;
5818 iter = clist_next(iter)) {
5819 uint32_t * puid;
5821 puid = clist_content(iter);
5822 result = g_slist_prepend(result, GINT_TO_POINTER(* puid));
5823 len++;
5825 result = g_slist_reverse(result);
5827 if (length)
5828 *length = len;
5829 return result;
5832 static GSList * imap_uid_list_from_lep_tab(carray * list)
5834 unsigned int i;
5835 GSList * result;
5837 result = NULL;
5839 for(i = 0 ; i < carray_count(list) ; i ++) {
5840 uint32_t * puid;
5842 puid = carray_get(list, i);
5843 result = g_slist_prepend(result, GINT_TO_POINTER(* puid));
5845 result = g_slist_reverse(result);
5846 return result;
5849 static void imap_flags_hash_from_lep_uid_flags_tab(carray * list,
5850 GHashTable * hash,
5851 GHashTable * tags_hash)
5853 unsigned int i;
5855 for(i = 0 ; i < carray_count(list) ; i += 3) {
5856 uint32_t * puid;
5857 int * pflags;
5858 GSList *tags;
5860 puid = carray_get(list, i);
5861 pflags = carray_get(list, i + 1);
5862 tags = carray_get(list, i + 2);
5864 g_hash_table_insert(hash, GINT_TO_POINTER(*puid), GINT_TO_POINTER(* pflags));
5865 g_hash_table_insert(tags_hash, GINT_TO_POINTER(*puid), tags);
5869 static MsgInfo *imap_envelope_from_lep(struct imap_fetch_env_info * info,
5870 FolderItem *item)
5872 MsgInfo *msginfo = NULL;
5873 guint32 uid = 0;
5874 goffset size = 0;
5875 MsgFlags flags = {0, 0};
5877 if (info->headers == NULL)
5878 return NULL;
5880 MSG_SET_TMP_FLAGS(flags, MSG_IMAP);
5881 if (folder_has_parent_of_type(item, F_QUEUE)) {
5882 MSG_SET_TMP_FLAGS(flags, MSG_QUEUED);
5883 } else if (folder_has_parent_of_type(item, F_DRAFT)) {
5884 MSG_SET_TMP_FLAGS(flags, MSG_DRAFT);
5886 flags.perm_flags = info->flags;
5888 uid = info->uid;
5889 size = (goffset) info->size;
5890 msginfo = procheader_parse_str(info->headers, flags, FALSE, FALSE);
5892 if (msginfo) {
5893 msginfo->msgnum = uid;
5894 msginfo->size = size;
5897 return msginfo;
5900 static void imap_lep_set_free(GSList *seq_list)
5902 GSList * cur;
5904 for(cur = seq_list ; cur != NULL ; cur = g_slist_next(cur)) {
5905 struct mailimap_set * imapset;
5907 imapset = cur->data;
5908 mailimap_set_free(imapset);
5910 g_slist_free(seq_list);
5913 static struct mailimap_flag_list * imap_flag_to_lep(IMAPFolderItem *item, IMAPFlags flags, GSList *tags)
5915 struct mailimap_flag_list * flag_list;
5916 GSList *cur = tags;
5918 flag_list = mailimap_flag_list_new_empty();
5920 if (IMAP_IS_SEEN(flags))
5921 mailimap_flag_list_add(flag_list,
5922 mailimap_flag_new_seen());
5923 if (IMAP_IS_ANSWERED(flags))
5924 mailimap_flag_list_add(flag_list,
5925 mailimap_flag_new_answered());
5926 if (IMAP_IS_FLAGGED(flags))
5927 mailimap_flag_list_add(flag_list,
5928 mailimap_flag_new_flagged());
5929 if (IMAP_IS_DELETED(flags))
5930 mailimap_flag_list_add(flag_list,
5931 mailimap_flag_new_deleted());
5932 if (IMAP_IS_DRAFT(flags))
5933 mailimap_flag_list_add(flag_list,
5934 mailimap_flag_new_draft());
5935 if (IMAP_IS_FORWARDED(flags) && flag_ok(item, IMAP_FLAG_FORWARDED))
5936 mailimap_flag_list_add(flag_list,
5937 mailimap_flag_new_flag_keyword(strdup(RTAG_FORWARDED)));
5938 if (IMAP_IS_SPAM(flags) && flag_ok(item, IMAP_FLAG_SPAM))
5939 mailimap_flag_list_add(flag_list,
5940 mailimap_flag_new_flag_keyword(strdup(RTAG_JUNK)));
5941 else if (IMAP_IS_HAM(flags) && flag_ok(item, IMAP_FLAG_HAM))
5942 mailimap_flag_list_add(flag_list,
5943 mailimap_flag_new_flag_keyword(strdup(RTAG_NON_JUNK)));
5945 for (; cur; cur = cur->next) {
5946 gchar *enc_str =
5947 imap_utf8_to_modified_utf7(cur->data, TRUE);
5948 g_strstrip(enc_str);
5950 mailimap_flag_list_add(flag_list,
5951 mailimap_flag_new_flag_keyword(enc_str));
5954 return flag_list;
5957 guint imap_folder_get_refcnt(Folder *folder)
5959 return ((IMAPFolder *)folder)->refcnt;
5962 void imap_folder_ref(Folder *folder)
5964 ((IMAPFolder *)folder)->refcnt++;
5967 void imap_disconnect_all(gboolean have_connectivity)
5969 GList *list;
5970 gboolean short_timeout;
5971 #ifdef HAVE_NETWORKMANAGER_SUPPORT
5972 GError *error = NULL;
5974 short_timeout = !networkmanager_is_online(&error);
5975 if(error) {
5976 short_timeout = TRUE;
5977 g_error_free(error);
5979 #else
5980 short_timeout = TRUE;
5981 #endif
5983 if(short_timeout)
5984 imap_main_set_timeout(1);
5986 for (list = account_get_list(); list != NULL; list = list->next) {
5987 PrefsAccount *account = list->data;
5988 if (account->protocol == A_IMAP4) {
5989 RemoteFolder *folder = (RemoteFolder *)account->folder;
5990 if (folder && folder->session) {
5991 if (imap_is_busy(FOLDER(folder)))
5992 imap_threaded_cancel(FOLDER(folder));
5994 IMAPSession *session = (IMAPSession *)folder->session;
5995 if (have_connectivity)
5996 imap_threaded_disconnect(FOLDER(folder));
5997 SESSION(session)->state = SESSION_DISCONNECTED;
5998 SESSION(session)->sock = NULL;
5999 imap_safe_destroy(session);
6000 folder->session = NULL;
6005 if(short_timeout)
6006 imap_main_set_timeout(prefs_common.io_timeout_secs);
6009 void imap_folder_unref(Folder *folder)
6011 if (((IMAPFolder *)folder)->refcnt > 0)
6012 ((IMAPFolder *)folder)->refcnt--;
6015 void imap_cancel_all(void)
6017 GList *folderlist;
6018 GList *cur;
6020 folderlist = folder_get_list();
6021 for (cur = folderlist; cur != NULL; cur = g_list_next(cur)) {
6022 Folder *folder = (Folder *) cur->data;
6024 if (folder->klass == &imap_class) {
6025 if (imap_is_busy(folder)) {
6026 IMAPSession *imap_session;
6027 RemoteFolder *rfolder;
6029 g_printerr("cancelled\n");
6030 imap_threaded_cancel(folder);
6031 rfolder = (RemoteFolder *) folder;
6032 imap_session = (IMAPSession *) rfolder->session;
6033 if (imap_session)
6034 imap_session->cancelled = 1;
6040 gboolean imap_cancel_all_enabled(void)
6042 GList *folderlist;
6043 GList *cur;
6045 folderlist = folder_get_list();
6046 for (cur = folderlist; cur != NULL; cur = g_list_next(cur)) {
6047 Folder *folder = (Folder *) cur->data;
6049 if (folder->klass == &imap_class) {
6050 if (imap_is_busy(folder)) {
6051 return TRUE;
6056 return FALSE;
6059 static gboolean imap_is_busy(Folder *folder)
6061 IMAPSession *imap_session;
6062 RemoteFolder *rfolder;
6064 rfolder = (RemoteFolder *) folder;
6065 imap_session = (IMAPSession *) rfolder->session;
6066 if (imap_session == NULL)
6067 return FALSE;
6069 return imap_session->busy;
6072 #else /* HAVE_LIBETPAN */
6074 static FolderClass imap_class;
6076 static XMLTag *imap_item_get_xml(Folder *folder, FolderItem *item);
6077 static void imap_item_set_xml(Folder *folder, FolderItem *item, XMLTag *tag);
6079 static Folder *imap_folder_new (const gchar *name,
6080 const gchar *path)
6082 static gboolean missing_imap_warning = TRUE;
6083 if (missing_imap_warning) {
6084 missing_imap_warning = FALSE;
6085 alertpanel_error(
6086 _("You have one or more IMAP accounts "
6087 "defined. However this version of "
6088 "Claws Mail has been built without "
6089 "IMAP support; your IMAP accounts are "
6090 "disabled.\n\n"
6091 "You probably need to "
6092 "install libetpan and recompile "
6093 "Claws Mail."));
6095 return NULL;
6097 static gint imap_create_tree (Folder *folder)
6099 return -1;
6101 static FolderItem *imap_create_folder (Folder *folder,
6102 FolderItem *parent,
6103 const gchar *name)
6105 return NULL;
6107 static gint imap_rename_folder (Folder *folder,
6108 FolderItem *item,
6109 const gchar *name)
6111 return -1;
6114 gchar imap_get_path_separator_for_item(FolderItem *item)
6116 return '/';
6119 FolderClass *imap_get_class(void)
6121 if (imap_class.idstr == NULL) {
6122 imap_class.type = F_IMAP;
6123 imap_class.idstr = "imap";
6124 imap_class.uistr = "IMAP";
6126 imap_class.new_folder = imap_folder_new;
6127 imap_class.create_tree = imap_create_tree;
6128 imap_class.create_folder = imap_create_folder;
6129 imap_class.rename_folder = imap_rename_folder;
6131 imap_class.set_xml = folder_set_xml;
6132 imap_class.get_xml = folder_get_xml;
6133 imap_class.item_set_xml = imap_item_set_xml;
6134 imap_class.item_get_xml = imap_item_get_xml;
6135 /* nothing implemented */
6138 return &imap_class;
6141 void imap_disconnect_all(gboolean have_connectivity)
6145 gint imap_subscribe(Folder *folder, FolderItem *item, gchar *rpath, gboolean sub)
6147 return -1;
6150 GList * imap_scan_subtree(Folder *folder, FolderItem *item, gboolean unsubs_only, gboolean recursive)
6152 return NULL;
6155 void imap_cache_msg(FolderItem *item, gint msgnum)
6159 void imap_cancel_all(void)
6163 gboolean imap_cancel_all_enabled(void)
6165 return FALSE;
6168 #endif
6170 #ifdef HAVE_LIBETPAN
6171 static void imap_synchronise(FolderItem *item, gint days)
6173 if (IMAP_FOLDER_ITEM(item)->last_sync == IMAP_FOLDER_ITEM(item)->last_change) {
6174 debug_print("%s already synced\n", item->path?item->path:item->name);
6175 return;
6177 debug_print("syncing %s\n", item->path?item->path:item->name);
6178 imap_gtk_synchronise(item, days);
6179 IMAP_FOLDER_ITEM(item)->last_sync = IMAP_FOLDER_ITEM(item)->last_change;
6181 #endif
6183 static void imap_item_set_xml(Folder *folder, FolderItem *item, XMLTag *tag)
6185 #ifdef HAVE_LIBETPAN
6186 GList *cur;
6187 #endif
6188 folder_item_set_xml(folder, item, tag);
6190 #ifdef HAVE_LIBETPAN
6191 for (cur = tag->attr; cur != NULL; cur = g_list_next(cur)) {
6192 XMLAttr *attr = (XMLAttr *) cur->data;
6194 if (!attr || !attr->name || !attr->value) continue;
6195 if (!strcmp(attr->name, "uidnext"))
6196 IMAP_FOLDER_ITEM(item)->uid_next = atoi(attr->value);
6197 if (!strcmp(attr->name, "last_sync"))
6198 IMAP_FOLDER_ITEM(item)->last_sync = atoi(attr->value);
6199 if (!strcmp(attr->name, "last_change"))
6200 IMAP_FOLDER_ITEM(item)->last_change = atoi(attr->value);
6202 if (IMAP_FOLDER_ITEM(item)->last_change == 0)
6203 IMAP_FOLDER_ITEM(item)->last_change = time(NULL);
6204 #endif
6207 static XMLTag *imap_item_get_xml(Folder *folder, FolderItem *item)
6209 XMLTag *tag;
6211 tag = folder_item_get_xml(folder, item);
6213 #ifdef HAVE_LIBETPAN
6214 xml_tag_add_attr(tag, xml_attr_new_int("uidnext",
6215 IMAP_FOLDER_ITEM(item)->uid_next));
6216 xml_tag_add_attr(tag, xml_attr_new_int("last_sync",
6217 IMAP_FOLDER_ITEM(item)->last_sync));
6218 xml_tag_add_attr(tag, xml_attr_new_int("last_change",
6219 IMAP_FOLDER_ITEM(item)->last_change));
6221 #endif
6222 return tag;
6225 /* ===================================================================
6226 * UTF-7 conversion routines as in RFC 2192
6227 * ===================================================================
6228 * These two functions from:
6229 * libimap library.
6230 * Copyright (C) 2003-2004 Pawel Salek. */
6232 /* UTF7 modified base64 alphabet */
6233 static char base64chars[] =
6234 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+,";
6235 #define UNDEFINED 64
6237 /* UTF16 definitions */
6238 #define UTF16MASK 0x03FFUL
6239 #define UTF16SHIFT 10
6240 #define UTF16BASE 0x10000UL
6241 #define UTF16HIGHSTART 0xD800UL
6242 #define UTF16HIGHEND 0xDBFFUL
6243 #define UTF16LOSTART 0xDC00UL
6244 #define UTF16LOEND 0xDFFFUL
6247 /* Convert an IMAP mailbox to a UTF-8 string.
6248 * dst needs to have roughly 4 times the storage space of src
6249 * Hex encoding can triple the size of the input
6250 * UTF-7 can be slightly denser than UTF-8
6251 * (worst case: 8 octets UTF-7 becomes 9 octets UTF-8)
6253 char* imap_modified_utf7_to_utf8(const char *mbox, gboolean change_spaces)
6255 unsigned c, i, bitcount;
6256 unsigned long ucs4, utf16, bitbuf;
6257 unsigned char base64[256];
6258 const char *src;
6259 char *dst, *res = g_malloc(2*strlen(mbox)+1);
6261 dst = res;
6262 src = mbox;
6263 if(!dst) return NULL;
6264 /* initialize modified base64 decoding table */
6265 memset(base64, UNDEFINED, sizeof (base64));
6266 for (i = 0; i < sizeof (base64chars); ++i) {
6267 base64[(unsigned)base64chars[i]] = i;
6270 /* loop until end of string */
6271 while (*src != '\0') {
6272 c = *src++;
6273 /* deal with literal characters and &- */
6274 if (c != '&' || *src == '-') {
6275 /* encode literally */
6276 if (change_spaces && c == '_')
6277 *dst++ = ' ';
6278 else
6279 *dst++ = c;
6280 /* skip over the '-' if this is an &- sequence */
6281 if (c == '&') ++src;
6282 } else {
6283 /* convert modified UTF-7 -> UTF-16 -> UCS-4 -> UTF-8 -> HEX */
6284 bitbuf = 0;
6285 bitcount = 0;
6286 ucs4 = 0;
6287 while ((c = base64[(unsigned char) *src]) != UNDEFINED) {
6288 ++src;
6289 bitbuf = (bitbuf << 6) | c;
6290 bitcount += 6;
6291 /* enough bits for a UTF-16 character? */
6292 if (bitcount >= 16) {
6293 bitcount -= 16;
6294 utf16 = (bitcount ? bitbuf >> bitcount
6295 : bitbuf) & 0xffff;
6296 /* convert UTF16 to UCS4 */
6298 (utf16 >= UTF16HIGHSTART && utf16 <= UTF16HIGHEND) {
6299 ucs4 = (utf16 - UTF16HIGHSTART) << UTF16SHIFT;
6300 continue;
6301 } else if
6302 (utf16 >= UTF16LOSTART && utf16 <= UTF16LOEND) {
6303 ucs4 += utf16 - UTF16LOSTART + UTF16BASE;
6304 } else {
6305 ucs4 = utf16;
6308 /* convert UTF-16 range of UCS4 to UTF-8 */
6309 if (ucs4 <= 0x7fUL) {
6310 dst[0] = ucs4;
6311 dst += 1;
6312 } else if (ucs4 <= 0x7ffUL) {
6313 dst[0] = 0xc0 | (ucs4 >> 6);
6314 dst[1] = 0x80 | (ucs4 & 0x3f);
6315 dst += 2;
6316 } else if (ucs4 <= 0xffffUL) {
6317 dst[0] = 0xe0 | (ucs4 >> 12);
6318 dst[1] = 0x80 | ((ucs4 >> 6) & 0x3f);
6319 dst[2] = 0x80 | (ucs4 & 0x3f);
6320 dst += 3;
6321 } else {
6322 dst[0] = 0xf0 | (ucs4 >> 18);
6323 dst[1] = 0x80 | ((ucs4 >> 12) & 0x3f);
6324 dst[2] = 0x80 | ((ucs4 >> 6) & 0x3f);
6325 dst[3] = 0x80 | (ucs4 & 0x3f);
6326 dst += 4;
6330 /* skip over trailing '-' in modified UTF-7 encoding */
6331 if (*src == '-') ++src;
6334 /* terminate destination string */
6335 *dst = '\0';
6336 return res;
6339 /* Convert hex coded UTF-8 string to modified UTF-7 IMAP mailbox
6340 * dst should be about twice the length of src to deal with non-hex
6341 * coded URLs
6343 char* imap_utf8_to_modified_utf7(const char *src, gboolean change_spaces)
6345 unsigned int utf8pos, utf8total, c, utf7mode, bitstogo, utf16flag;
6346 unsigned long ucs4 = 0, bitbuf = 0;
6348 /* initialize hex lookup table */
6349 char *dst, *res;
6351 if (!src) return NULL;
6353 res = malloc(2*strlen(src)+1);
6354 dst = res;
6355 if(!dst) return NULL;
6357 utf7mode = 0;
6358 utf8total = 0;
6359 bitstogo = 0;
6360 utf8pos = 0;
6361 while ((c = (unsigned char)*src) != '\0') {
6362 ++src;
6363 /* normal character? */
6364 if (c >= ' ' && c <= '~' && (c != '_' || !change_spaces)) {
6365 /* switch out of UTF-7 mode */
6366 if (utf7mode) {
6367 if (bitstogo) {
6368 *dst++ = base64chars[(bitbuf << (6 - bitstogo)) & 0x3F];
6370 *dst++ = '-';
6371 utf7mode = 0;
6372 utf8pos = 0;
6373 bitstogo = 0;
6374 utf8total= 0;
6376 if (change_spaces && c == ' ')
6377 *dst++ = '_';
6378 else
6379 *dst++ = c;
6380 /* encode '&' as '&-' */
6381 if (c == '&') {
6382 *dst++ = '-';
6384 continue;
6386 /* switch to UTF-7 mode */
6387 if (!utf7mode) {
6388 *dst++ = '&';
6389 utf7mode = 1;
6391 /* Encode US-ASCII characters as themselves */
6392 if (c < 0x80) {
6393 ucs4 = c;
6394 } else if (utf8total) {
6395 /* save UTF8 bits into UCS4 */
6396 ucs4 = (ucs4 << 6) | (c & 0x3FUL);
6397 if (++utf8pos < utf8total) {
6398 continue;
6400 } else {
6401 utf8pos = 1;
6402 if (c < 0xE0) {
6403 utf8total = 2;
6404 ucs4 = c & 0x1F;
6405 } else if (c < 0xF0) {
6406 utf8total = 3;
6407 ucs4 = c & 0x0F;
6408 } else {
6409 /* NOTE: can't convert UTF8 sequences longer than 4 */
6410 utf8total = 4;
6411 ucs4 = c & 0x03;
6413 continue;
6415 /* loop to split ucs4 into two utf16 chars if necessary */
6416 utf8total = 0;
6417 do {
6418 if (ucs4 >= UTF16BASE) {
6419 ucs4 -= UTF16BASE;
6420 bitbuf = (bitbuf << 16) | ((ucs4 >> UTF16SHIFT)
6421 + UTF16HIGHSTART);
6422 ucs4 = (ucs4 & UTF16MASK) + UTF16LOSTART;
6423 utf16flag = 1;
6424 } else {
6425 bitbuf = (bitbuf << 16) | ucs4;
6426 utf16flag = 0;
6428 bitstogo += 16;
6429 /* spew out base64 */
6430 while (bitstogo >= 6) {
6431 bitstogo -= 6;
6432 *dst++ = base64chars[(bitstogo ? (bitbuf >> bitstogo)
6433 : bitbuf)
6434 & 0x3F];
6436 } while (utf16flag);
6438 /* if in UTF-7 mode, finish in ASCII */
6439 if (utf7mode) {
6440 if (bitstogo) {
6441 *dst++ = base64chars[(bitbuf << (6 - bitstogo)) & 0x3F];
6443 *dst++ = '-';
6445 /* tie off string */
6446 *dst = '\0';
6447 return res;