support image/x-eps format via pdf_viewer
[claws.git] / src / imap.c
blobd1ec86fe12d944f7edd0e07758a01747d415c5e5
1 /*
2 * Claws Mail -- a GTK based, lightweight, and fast e-mail client
3 * Copyright (C) 1999-2024 the Claws Mail team and Hiroyuki Yamamoto
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 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 <unistd.h>
40 #include <ctype.h>
41 #include <time.h>
42 #include <errno.h>
43 #if HAVE_ICONV
44 # include <iconv.h>
45 #endif
47 #ifdef USE_GNUTLS
48 # include "ssl.h"
49 #endif
51 #include "folder.h"
52 #include "session.h"
53 #include "procmsg.h"
54 #include "socket.h"
55 #include "recv.h"
56 #include "procheader.h"
57 #include "prefs_account.h"
58 #include "codeconv.h"
59 #include "md5.h"
60 #include "utils.h"
61 #include "prefs_common.h"
62 #include "inputdialog.h"
63 #include "log.h"
64 #include "remotefolder.h"
65 #include "claws.h"
66 #include "statusbar.h"
67 #include "msgcache.h"
68 #include "imap-thread.h"
69 #include "account.h"
70 #include "tags.h"
71 #include "main.h"
72 #include "passwordstore.h"
73 #include "file-utils.h"
74 #ifdef USE_OAUTH2
75 #include "oauth2.h"
76 #endif
78 typedef struct _IMAPFolder IMAPFolder;
79 typedef struct _IMAPSession IMAPSession;
80 typedef struct _IMAPNameSpace IMAPNameSpace;
81 typedef struct _IMAPFolderItem IMAPFolderItem;
83 #define IMAP_FOLDER(obj) ((IMAPFolder *)obj)
84 #define IMAP_FOLDER_ITEM(obj) ((IMAPFolderItem *)obj)
85 #define IMAP_SESSION(obj) ((IMAPSession *)obj)
87 struct _IMAPFolder
89 RemoteFolder rfolder;
91 /* list of IMAPNameSpace */
92 GList *ns_personal;
93 GList *ns_others;
94 GList *ns_shared;
95 gchar last_seen_separator;
96 guint refcnt;
97 guint max_set_size;
98 gchar *search_charset;
99 gboolean search_charset_supported;
102 struct _IMAPSession
104 Session session;
106 gboolean authenticated;
108 GSList *capability;
109 gboolean uidplus;
111 gchar *mbox;
112 guint cmd_count;
114 /* CLAWS */
115 gboolean folder_content_changed;
116 guint exists;
117 guint recent;
118 guint expunge;
119 guint unseen;
120 guint uid_validity;
121 guint uid_next;
123 Folder * folder;
124 gboolean busy;
125 gboolean cancelled;
126 gboolean sens_update_block;
127 gboolean do_destroy;
129 gint scan_tree_recurs_depth;
132 struct _IMAPNameSpace
134 gchar *name;
135 gchar separator;
138 #define IMAPBUFSIZE 8192
140 #define IMAP_IS_SEEN(flags) ((flags & IMAP_FLAG_SEEN) != 0)
141 #define IMAP_IS_ANSWERED(flags) ((flags & IMAP_FLAG_ANSWERED) != 0)
142 #define IMAP_IS_FLAGGED(flags) ((flags & IMAP_FLAG_FLAGGED) != 0)
143 #define IMAP_IS_DELETED(flags) ((flags & IMAP_FLAG_DELETED) != 0)
144 #define IMAP_IS_DRAFT(flags) ((flags & IMAP_FLAG_DRAFT) != 0)
145 #define IMAP_IS_FORWARDED(flags) ((flags & IMAP_FLAG_FORWARDED) != 0)
146 #define IMAP_IS_SPAM(flags) ((flags & IMAP_FLAG_SPAM) != 0)
147 #define IMAP_IS_HAM(flags) ((flags & IMAP_FLAG_HAM) != 0)
150 #define IMAP4_PORT 143
151 #ifdef USE_GNUTLS
152 #define IMAPS_PORT 993
153 #endif
155 #define IMAP_CMD_LIMIT 1000
157 enum {
158 ITEM_CAN_CREATE_FLAGS_UNKNOWN = 0,
159 ITEM_CAN_CREATE_FLAGS,
160 ITEM_CANNOT_CREATE_FLAGS
163 struct _IMAPFolderItem
165 FolderItem item;
167 guint lastuid;
168 guint uid_next;
169 GSList *uid_list;
170 gboolean batching;
172 GHashTable *flags_set_table;
173 GHashTable *flags_unset_table;
174 guint32 last_change;
175 guint32 last_sync;
176 gboolean should_update;
177 gboolean should_trash_cache;
178 gint can_create_flags;
180 GHashTable *tags_set_table;
181 GHashTable *tags_unset_table;
182 GSList *ok_flags;
186 static XMLTag *imap_item_get_xml(Folder *folder, FolderItem *item);
187 static void imap_item_set_xml(Folder *folder, FolderItem *item, XMLTag *tag);
189 static void imap_folder_init (Folder *folder,
190 const gchar *name,
191 const gchar *path);
193 static Folder *imap_folder_new (const gchar *name,
194 const gchar *path);
195 static void imap_folder_destroy (Folder *folder);
197 static IMAPSession *imap_session_new (Folder *folder,
198 const PrefsAccount *account);
199 static gint imap_session_authenticate(IMAPSession *session,
200 PrefsAccount *account);
201 static void imap_session_destroy (Session *session);
203 static gchar *imap_fetch_msg (Folder *folder,
204 FolderItem *item,
205 gint uid);
206 static gchar *imap_fetch_msg_full (Folder *folder,
207 FolderItem *item,
208 gint uid,
209 gboolean headers,
210 gboolean body);
211 static void imap_remove_cached_msg (Folder *folder,
212 FolderItem *item,
213 MsgInfo *msginfo);
214 static gint imap_add_msg (Folder *folder,
215 FolderItem *dest,
216 const gchar *file,
217 MsgFlags *flags);
218 static gint imap_add_msgs (Folder *folder,
219 FolderItem *dest,
220 GSList *file_list,
221 GHashTable *relation);
223 static gint imap_copy_msg (Folder *folder,
224 FolderItem *dest,
225 MsgInfo *msginfo);
226 static gint imap_copy_msgs (Folder *folder,
227 FolderItem *dest,
228 MsgInfoList *msglist,
229 GHashTable *relation);
231 static gint search_msgs (Folder *folder,
232 FolderItem *container,
233 MsgNumberList **msgs,
234 gboolean *on_server,
235 MatcherList *predicate,
236 SearchProgressNotify progress_cb,
237 gpointer progress_data);
239 static gint imap_remove_msg (Folder *folder,
240 FolderItem *item,
241 gint uid);
242 static gint imap_remove_msgs (Folder *folder,
243 FolderItem *dest,
244 MsgInfoList *msglist,
245 GHashTable *relation);
246 static gint imap_expunge (Folder *folder,
247 FolderItem *dest);
248 static gint imap_remove_all_msg (Folder *folder,
249 FolderItem *item);
251 static gboolean imap_is_msg_changed (Folder *folder,
252 FolderItem *item,
253 MsgInfo *msginfo);
255 static gint imap_close (Folder *folder,
256 FolderItem *item);
258 static gint imap_scan_tree (Folder *folder);
260 static gint imap_create_tree (Folder *folder);
262 static FolderItem *imap_create_folder (Folder *folder,
263 FolderItem *parent,
264 const gchar *name);
265 static gint imap_rename_folder (Folder *folder,
266 FolderItem *item,
267 const gchar *name);
268 static gint imap_remove_folder (Folder *folder,
269 FolderItem *item);
271 static FolderItem *imap_folder_item_new (Folder *folder);
272 static void imap_folder_item_destroy (Folder *folder,
273 FolderItem *item);
275 static IMAPSession *imap_session_get (Folder *folder);
277 static gint imap_auth (IMAPSession *session,
278 const gchar *user,
279 const gchar *pass,
280 IMAPAuthType type);
282 static gint imap_scan_tree_recursive (IMAPSession *session,
283 FolderItem *item,
284 gboolean subs_only);
285 static gint imap_scan_tree_recursive_dive (IMAPSession *session,
286 FolderItem *item,
287 gboolean subs_only);
289 static void imap_create_missing_folders (Folder *folder);
290 static FolderItem *imap_create_special_folder
291 (Folder *folder,
292 SpecialFolderItemType stype,
293 const gchar *name);
295 static gint imap_do_copy_msgs (Folder *folder,
296 FolderItem *dest,
297 MsgInfoList *msglist,
298 GHashTable *relation,
299 gboolean same_dest_ok);
301 static gint imap_do_remove_msgs (Folder *folder,
302 FolderItem *dest,
303 MsgInfoList *msglist,
304 GHashTable *relation);
306 static void imap_delete_all_cached_messages (FolderItem *item);
307 static void imap_set_batch (Folder *folder,
308 FolderItem *item,
309 gboolean batch);
310 static gint imap_set_message_flags (IMAPSession *session,
311 IMAPFolderItem *item,
312 MsgNumberList *numlist,
313 IMAPFlags flags,
314 GSList *tags,
315 gboolean is_set);
316 static gint imap_select (IMAPSession *session,
317 IMAPFolder *folder,
318 FolderItem *item,
319 gint *exists,
320 gint *recent,
321 gint *unseen,
322 guint32 *uid_validity,
323 gint *can_create_flags,
324 gboolean block);
325 static gint imap_status (IMAPSession *session,
326 IMAPFolder *folder,
327 const gchar *path,
328 IMAPFolderItem *item,
329 gint *messages,
330 guint32 *uid_next,
331 guint32 *uid_validity,
332 gint *unseen,
333 gboolean block);
334 static void imap_commit_tags (FolderItem *item,
335 MsgInfo *msginfo,
336 GSList *set_tags,
337 GSList *unset_tags);
339 static gchar imap_get_path_separator (IMAPSession *session,
340 IMAPFolder *folder,
341 const gchar *path,
342 gint *ok);
343 static gchar *imap_get_real_path (IMAPSession *session,
344 IMAPFolder *folder,
345 const gchar *path,
346 gint *ok);
347 #ifdef HAVE_LIBETPAN
348 static void imap_synchronise (FolderItem *item, gint days);
349 #endif
350 static gboolean imap_is_busy (Folder *folder);
352 static void imap_free_capabilities (IMAPSession *session);
354 /* low-level IMAP4rev1 commands */
355 static gint imap_cmd_login (IMAPSession *session,
356 const gchar *user,
357 const gchar *pass,
358 const gchar *type);
359 static gint imap_cmd_noop (IMAPSession *session);
360 #ifdef USE_GNUTLS
361 static gint imap_cmd_starttls (IMAPSession *session);
362 #endif
363 static gint imap_cmd_select (IMAPSession *session,
364 const gchar *folder,
365 gint *exists,
366 gint *recent,
367 gint *unseen,
368 guint32 *uid_validity,
369 gint *can_create_flags,
370 GSList **ok_flags,
371 gboolean block);
372 static gint imap_cmd_close (IMAPSession *session);
373 static gint imap_cmd_examine (IMAPSession *session,
374 const gchar *folder,
375 gint *exists,
376 gint *recent,
377 gint *unseen,
378 guint32 *uid_validity,
379 gboolean block);
380 static gint imap_cmd_create (IMAPSession *sock,
381 const gchar *folder);
382 static gint imap_cmd_rename (IMAPSession *sock,
383 const gchar *oldfolder,
384 const gchar *newfolder);
385 static gint imap_cmd_delete (IMAPSession *session,
386 const gchar *folder);
387 static gint imap_cmd_fetch (IMAPSession *sock,
388 guint32 uid,
389 const gchar *filename,
390 gboolean headers,
391 gboolean body);
392 static gint imap_cmd_append (IMAPSession *session,
393 IMAPFolderItem *item,
394 const gchar *destfolder,
395 const gchar *file,
396 IMAPFlags flags,
397 guint32 *new_uid);
398 static gint imap_cmd_copy (IMAPSession *session,
399 struct mailimap_set * set,
400 const gchar *destfolder,
401 struct mailimap_set ** source,
402 struct mailimap_set ** dest);
403 static gint imap_cmd_store (IMAPSession *session,
404 IMAPFolderItem *item,
405 struct mailimap_set * set,
406 IMAPFlags flags,
407 GSList *tags,
408 int do_add);
409 static gint imap_cmd_expunge (IMAPSession *session);
411 static void imap_path_separator_subst (gchar *str,
412 gchar separator);
414 static gboolean imap_rename_folder_func (GNode *node,
415 gpointer data);
416 static gint imap_get_num_list (Folder *folder,
417 FolderItem *item,
418 GSList **list,
419 gboolean *old_uids_valid);
420 static GSList *imap_get_msginfos (Folder *folder,
421 FolderItem *item,
422 GSList *msgnum_list);
423 static MsgInfo *imap_get_msginfo (Folder *folder,
424 FolderItem *item,
425 gint num);
426 static gboolean imap_scan_required (Folder *folder,
427 FolderItem *item);
428 static void imap_change_flags (Folder *folder,
429 FolderItem *item,
430 MsgInfo *msginfo,
431 MsgPermFlags newflags);
432 static gint imap_get_flags (Folder *folder,
433 FolderItem *item,
434 MsgInfoList *msglist,
435 GHashTable *msgflags);
436 static gchar *imap_item_get_path (Folder *folder,
437 FolderItem *item);
438 static MsgInfo *imap_parse_msg(const gchar *file, FolderItem *item);
441 /* data types conversion libetpan <-> claws */
442 static GSList * imap_list_from_lep(IMAPFolder * folder,
443 clist * list, const gchar * real_path, gboolean all);
444 static GSList * imap_get_lep_set_from_numlist(IMAPFolder *folder, MsgNumberList *numlist);
445 static GSList * imap_get_lep_set_from_msglist(IMAPFolder *folder, MsgInfoList *msglist);
446 static GSList * imap_uid_list_from_lep(clist * list, gint* length);
447 static GSList * imap_uid_list_from_lep_tab(carray * list);
448 static void imap_flags_hash_from_lep_uid_flags_tab(carray * list,
449 GHashTable * hash,
450 GHashTable *tags_hash);
451 static MsgInfo *imap_envelope_from_lep(struct imap_fetch_env_info * info,
452 FolderItem *item);
453 static void imap_lep_set_free(GSList *seq_list);
454 static struct mailimap_flag_list * imap_flag_to_lep(IMAPFolderItem *item, IMAPFlags flags, GSList *tags);
456 typedef struct _hashtable_data {
457 GSList *msglist;
458 IMAPFolderItem *item;
459 } hashtable_data;
461 static FolderClass imap_class;
463 FolderClass *imap_get_class(void)
465 if (imap_class.idstr == NULL) {
466 imap_class.type = F_IMAP;
467 imap_class.idstr = "imap";
468 imap_class.uistr = "IMAP";
469 imap_class.supports_server_search = TRUE;
471 /* Folder functions */
472 imap_class.new_folder = imap_folder_new;
473 imap_class.destroy_folder = imap_folder_destroy;
474 imap_class.scan_tree = imap_scan_tree;
475 imap_class.create_tree = imap_create_tree;
477 /* FolderItem functions */
478 imap_class.item_new = imap_folder_item_new;
479 imap_class.item_destroy = imap_folder_item_destroy;
480 imap_class.item_get_path = imap_item_get_path;
481 imap_class.create_folder = imap_create_folder;
482 imap_class.rename_folder = imap_rename_folder;
483 imap_class.remove_folder = imap_remove_folder;
484 imap_class.close = imap_close;
485 imap_class.get_num_list = imap_get_num_list;
486 imap_class.scan_required = imap_scan_required;
487 imap_class.set_xml = folder_set_xml;
488 imap_class.get_xml = folder_get_xml;
489 imap_class.item_set_xml = imap_item_set_xml;
490 imap_class.item_get_xml = imap_item_get_xml;
492 /* Message functions */
493 imap_class.get_msginfo = imap_get_msginfo;
494 imap_class.get_msginfos = imap_get_msginfos;
495 imap_class.fetch_msg = imap_fetch_msg;
496 imap_class.fetch_msg_full = imap_fetch_msg_full;
497 imap_class.add_msg = imap_add_msg;
498 imap_class.add_msgs = imap_add_msgs;
499 imap_class.copy_msg = imap_copy_msg;
500 imap_class.copy_msgs = imap_copy_msgs;
501 imap_class.search_msgs = search_msgs;
502 imap_class.remove_msg = imap_remove_msg;
503 imap_class.remove_msgs = imap_remove_msgs;
504 imap_class.expunge = imap_expunge;
505 imap_class.remove_all_msg = imap_remove_all_msg;
506 imap_class.is_msg_changed = imap_is_msg_changed;
507 imap_class.change_flags = imap_change_flags;
508 imap_class.get_flags = imap_get_flags;
509 imap_class.set_batch = imap_set_batch;
510 imap_class.synchronise = imap_synchronise;
511 imap_class.remove_cached_msg = imap_remove_cached_msg;
512 imap_class.commit_tags = imap_commit_tags;
515 return &imap_class;
518 static void imap_refresh_sensitivity (IMAPSession *session)
520 MainWindow *mainwin;
522 if (session->sens_update_block)
523 return;
524 mainwin = mainwindow_get_mainwindow();
525 if (mainwin) {
526 toolbar_main_set_sensitive(mainwin);
527 main_window_set_menu_sensitive(mainwin);
531 static void lock_session(IMAPSession *session)
533 if (session) {
534 debug_print("locking session %p (%d)\n", session, session->busy);
535 if (session->busy)
536 debug_print(" SESSION WAS LOCKED !! \n");
537 session->busy = TRUE;
538 imap_refresh_sensitivity(session);
539 } else {
540 debug_print("can't lock null session\n");
544 static void unlock_session(IMAPSession *session)
546 if (session) {
547 debug_print("unlocking session %p\n", session);
548 session->busy = FALSE;
549 imap_refresh_sensitivity(session);
550 } else {
551 debug_print("can't unlock null session\n");
555 static gboolean imap_ping(gpointer data)
557 Session *session = (Session *)data;
558 IMAPSession *imap_session = IMAP_SESSION(session);
559 int r;
561 if (session->state != SESSION_READY)
562 return FALSE;
563 if (imap_session->busy || !imap_session->authenticated)
564 return TRUE;
566 lock_session(imap_session);
567 r = imap_cmd_noop(imap_session);
568 unlock_session(imap_session);
570 return r == MAILIMAP_NO_ERROR;
573 static void imap_disc_session_destroy(IMAPSession *session)
575 RemoteFolder *rfolder = NULL;
577 if (session == NULL)
578 return;
580 rfolder = REMOTE_FOLDER(IMAP_SESSION(session)->folder);
582 if (rfolder == NULL)
583 return;
584 log_warning(LOG_PROTOCOL, _("IMAP connection broken\n"));
585 SESSION(session)->state = SESSION_DISCONNECTED;
586 SESSION(session)->sock = NULL;
589 static void imap_safe_destroy(IMAPSession *session)
591 if (!session->busy)
592 session_destroy(SESSION(session));
593 else
594 session->do_destroy = TRUE;
597 static gboolean is_fatal(int libetpan_errcode)
599 switch(libetpan_errcode) {
600 case MAILIMAP_ERROR_STREAM:
601 case MAILIMAP_ERROR_PROTOCOL:
602 case MAILIMAP_ERROR_PARSE:
603 case MAILIMAP_ERROR_BAD_STATE:
604 return TRUE;
605 default:
606 return FALSE;
610 #define MY_LOG_WARNING(concat_cmd, ...) \
611 msg = concat_cmd; \
612 log_warning(LOG_PROTOCOL, msg, __VA_ARGS__); \
613 g_free(msg);
615 static void imap_handle_error(Session *session, const gchar *server, int libetpan_errcode)
617 const gchar *session_server = (session ? session->server : NULL);
618 gchar *msg;
620 if (session_server == NULL)
621 session_server = server;
622 if (session_server == NULL)
623 session_server = "(null)";
625 switch(libetpan_errcode) {
626 case MAILIMAP_NO_ERROR:
627 return;
628 case MAILIMAP_NO_ERROR_AUTHENTICATED:
629 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("authenticated"), "\n", NULL), session_server)
630 break;
631 case MAILIMAP_NO_ERROR_NON_AUTHENTICATED:
632 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("not authenticated"), "\n", NULL), session_server)
633 break;
634 case MAILIMAP_ERROR_BAD_STATE:
635 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("bad state"), "\n", NULL), session_server)
636 break;
637 case MAILIMAP_ERROR_STREAM:
638 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("stream error"), "\n", NULL), session_server)
639 break;
640 case MAILIMAP_ERROR_PARSE:
641 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("parse error "
642 "(very probably non-RFC compliance from the server)"), "\n", NULL), session_server)
643 break;
644 case MAILIMAP_ERROR_CONNECTION_REFUSED:
645 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("connection refused"), "\n", NULL), session_server)
646 break;
647 case MAILIMAP_ERROR_MEMORY:
648 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("memory error"), "\n", NULL), session_server)
649 break;
650 case MAILIMAP_ERROR_FATAL:
651 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("fatal error"), "\n", NULL), session_server)
652 break;
653 case MAILIMAP_ERROR_PROTOCOL:
654 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("protocol error "
655 "(very probably non-RFC compliance from the server)"), "\n", NULL), session_server)
656 break;
657 case MAILIMAP_ERROR_DONT_ACCEPT_CONNECTION:
658 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("connection not accepted"), "\n", NULL), session_server)
659 break;
660 case MAILIMAP_ERROR_APPEND:
661 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("APPEND error"), "\n", NULL), session_server)
662 break;
663 case MAILIMAP_ERROR_NOOP:
664 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("NOOP error"), "\n", NULL), session_server)
665 break;
666 case MAILIMAP_ERROR_LOGOUT:
667 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("LOGOUT error"), "\n", NULL), session_server)
668 break;
669 case MAILIMAP_ERROR_CAPABILITY:
670 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("CAPABILITY error"), "\n", NULL), session_server)
671 break;
672 case MAILIMAP_ERROR_CHECK:
673 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("CHECK error"), "\n", NULL), session_server)
674 break;
675 case MAILIMAP_ERROR_CLOSE:
676 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("CLOSE error"), "\n", NULL), session_server)
677 break;
678 case MAILIMAP_ERROR_EXPUNGE:
679 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("EXPUNGE error"), "\n", NULL), session_server)
680 break;
681 case MAILIMAP_ERROR_COPY:
682 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("COPY error"), "\n", NULL), session_server)
683 break;
684 case MAILIMAP_ERROR_UID_COPY:
685 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("UID COPY error"), "\n", NULL), session_server)
686 break;
687 case MAILIMAP_ERROR_CREATE:
688 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("CREATE error"), "\n", NULL), session_server)
689 break;
690 case MAILIMAP_ERROR_DELETE:
691 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("DELETE error"), "\n", NULL), session_server)
692 break;
693 case MAILIMAP_ERROR_EXAMINE:
694 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("EXAMINE error"), "\n", NULL), session_server)
695 break;
696 case MAILIMAP_ERROR_FETCH:
697 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("FETCH error"), "\n", NULL), session_server)
698 break;
699 case MAILIMAP_ERROR_UID_FETCH:
700 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("UID FETCH error"), "\n", NULL), session_server)
701 break;
702 case MAILIMAP_ERROR_LIST:
703 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("LIST error"), "\n", NULL), session_server)
704 break;
705 case MAILIMAP_ERROR_LOGIN:
706 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("LOGIN error"), "\n", NULL), session_server)
707 break;
708 case MAILIMAP_ERROR_LSUB:
709 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("LSUB error"), "\n", NULL), session_server)
710 break;
711 case MAILIMAP_ERROR_RENAME:
712 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("RENAME error"), "\n", NULL), session_server)
713 break;
714 case MAILIMAP_ERROR_SEARCH:
715 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("SEARCH error"), "\n", NULL), session_server)
716 break;
717 case MAILIMAP_ERROR_UID_SEARCH:
718 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("UID SEARCH error"), "\n", NULL), session_server)
719 break;
720 case MAILIMAP_ERROR_SELECT:
721 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("SELECT error"), "\n", NULL), session_server)
722 break;
723 case MAILIMAP_ERROR_STATUS:
724 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("STATUS error"), "\n", NULL), session_server)
725 break;
726 case MAILIMAP_ERROR_STORE:
727 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("STORE error"), "\n", NULL), session_server)
728 break;
729 case MAILIMAP_ERROR_UID_STORE:
730 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("UID STORE error"), "\n", NULL), session_server)
731 break;
732 case MAILIMAP_ERROR_SUBSCRIBE:
733 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("SUBSCRIBE error"), "\n", NULL), session_server)
734 break;
735 case MAILIMAP_ERROR_UNSUBSCRIBE:
736 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("UNSUBSCRIBE error"), "\n", NULL), session_server)
737 break;
738 case MAILIMAP_ERROR_STARTTLS:
739 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("STARTTLS error"), "\n", NULL), session_server)
740 break;
741 case MAILIMAP_ERROR_INVAL:
742 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("INVAL error"), "\n", NULL), session_server)
743 break;
744 case MAILIMAP_ERROR_EXTENSION:
745 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("EXTENSION error"), "\n", NULL), session_server)
746 break;
747 case MAILIMAP_ERROR_SASL:
748 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("SASL error"), "\n", NULL), session_server)
749 break;
750 #ifdef USE_GNUTLS
751 case MAILIMAP_ERROR_SSL:
752 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("TLS error"), "\n", NULL), session_server)
753 break;
754 #endif
755 default:
756 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("Unknown error [%d]"), "\n", NULL),
757 session_server, libetpan_errcode)
758 break;
761 if (session && is_fatal(libetpan_errcode)) {
762 imap_disc_session_destroy(IMAP_SESSION(session));
763 } else if (session && !is_fatal(libetpan_errcode)) {
764 if (IMAP_SESSION(session)->busy)
765 unlock_session(IMAP_SESSION(session));
769 #undef MY_LOG_WARNING
771 static Folder *imap_folder_new(const gchar *name, const gchar *path)
773 Folder *folder;
775 folder = (Folder *)g_new0(IMAPFolder, 1);
776 folder->klass = &imap_class;
777 imap_folder_init(folder, name, path);
779 return folder;
782 static void imap_folder_destroy(Folder *folder)
784 while (imap_folder_get_refcnt(folder) > 0)
785 gtk_main_iteration();
787 g_free(IMAP_FOLDER(folder)->search_charset);
789 folder_remote_folder_destroy(REMOTE_FOLDER(folder));
790 imap_done(folder);
793 static void imap_folder_init(Folder *folder, const gchar *name,
794 const gchar *path)
796 folder_remote_folder_init((Folder *)folder, name, path);
797 IMAP_FOLDER(folder)->search_charset_supported = TRUE;
798 IMAP_FOLDER(folder)->search_charset = g_strdup(conv_get_locale_charset_str_no_utf8());
801 static FolderItem *imap_folder_item_new(Folder *folder)
803 IMAPFolderItem *item;
805 item = g_new0(IMAPFolderItem, 1);
806 item->lastuid = 0;
807 item->uid_next = 0;
808 item->uid_list = NULL;
810 return (FolderItem *)item;
813 static void imap_folder_item_destroy(Folder *folder, FolderItem *_item)
815 IMAPFolderItem *item = (IMAPFolderItem *)_item;
817 g_return_if_fail(item != NULL);
818 g_slist_free(item->uid_list);
820 g_free(_item);
823 static gboolean imap_reset_uid_lists_func(GNode *node, gpointer data)
825 IMAPFolderItem *item = (IMAPFolderItem *)node->data;
827 item->lastuid = 0;
828 g_slist_free(item->uid_list);
829 item->uid_list = NULL;
831 return FALSE;
834 static void imap_reset_uid_lists(Folder *folder)
836 if(folder->node == NULL)
837 return;
839 /* Destroy all uid lists and rest last uid */
840 g_node_traverse(folder->node, G_IN_ORDER, G_TRAVERSE_ALL, -1, imap_reset_uid_lists_func, NULL);
843 static int imap_get_capabilities(IMAPSession *session)
845 struct mailimap_capability_data *capabilities = NULL;
846 clistiter *cur;
847 int result;
849 if (session->capability != NULL)
850 return MAILIMAP_NO_ERROR;
852 result = imap_threaded_capability(session->folder, &capabilities);
854 if (result != MAILIMAP_NO_ERROR) {
855 return result;
858 if (capabilities == NULL || capabilities->cap_list == NULL) {
859 return MAILIMAP_NO_ERROR;
862 for(cur = clist_begin(capabilities->cap_list) ; cur != NULL ;
863 cur = clist_next(cur)) {
864 struct mailimap_capability * cap =
865 clist_content(cur);
866 if (!cap || cap->cap_data.cap_name == NULL)
867 continue;
868 session->capability = g_slist_append
869 (session->capability,
870 g_strdup(cap->cap_data.cap_name));
871 debug_print("got capa %s\n", cap->cap_data.cap_name);
873 mailimap_capability_data_free(capabilities);
874 return MAILIMAP_NO_ERROR;
877 static gboolean imap_has_capability(IMAPSession *session, const gchar *cap)
879 GSList *cur;
880 for (cur = session->capability; cur; cur = cur->next) {
881 if (!g_ascii_strcasecmp(cur->data, cap))
882 return TRUE;
884 return FALSE;
887 static gint imap_auth(IMAPSession *session, const gchar *user, const gchar *pass,
888 IMAPAuthType type)
890 gint ok = MAILIMAP_ERROR_LOGIN;
891 static time_t last_login_err = 0;
892 gchar *ext_info = "";
893 int r;
894 gchar *server = NULL;
895 if ((r = imap_get_capabilities(session)) != MAILIMAP_NO_ERROR) {
896 imap_handle_error(SESSION(session), NULL, r);
897 return r;
899 server = g_strdup(SESSION(session)->server);
900 switch(type) {
901 case IMAP_AUTH_ANON:
902 ok = imap_cmd_login(session, user, pass, "ANONYMOUS");
903 break;
904 case IMAP_AUTH_CRAM_MD5:
905 ok = imap_cmd_login(session, user, pass, "CRAM-MD5");
906 break;
907 case IMAP_AUTH_DIGEST_MD5:
908 ok = imap_cmd_login(session, user, pass, "DIGEST-MD5");
909 break;
910 case IMAP_AUTH_SCRAM_SHA1:
911 ok = imap_cmd_login(session, user, pass, "SCRAM-SHA-1");
912 break;
913 case IMAP_AUTH_SCRAM_SHA224:
914 ok = imap_cmd_login(session, user, pass, "SCRAM-SHA-224");
915 break;
916 case IMAP_AUTH_SCRAM_SHA256:
917 ok = imap_cmd_login(session, user, pass, "SCRAM-SHA-256");
918 break;
919 case IMAP_AUTH_SCRAM_SHA384:
920 ok = imap_cmd_login(session, user, pass, "SCRAM-SHA-384");
921 break;
922 case IMAP_AUTH_SCRAM_SHA512:
923 ok = imap_cmd_login(session, user, pass, "SCRAM-SHA-512");
924 break;
925 case IMAP_AUTH_PLAIN:
926 ok = imap_cmd_login(session, user, pass, "PLAIN");
927 break;
928 #ifdef USE_GNUTLS
929 case IMAP_AUTH_OAUTH2:
930 ok = imap_cmd_login(session, user, pass, "XOAUTH2");
931 break;
932 #endif
933 case IMAP_AUTH_LOGIN:
934 ok = imap_cmd_login(session, user, pass, "LOGIN");
935 break;
936 case IMAP_AUTH_PLAINTEXT:
937 ok = imap_cmd_login(session, user, pass, "plaintext");
938 break;
939 case IMAP_AUTH_GSSAPI:
940 ok = imap_cmd_login(session, user, pass, "GSSAPI");
941 break;
942 default:
943 debug_print("capabilities:\n"
944 "\t ANONYMOUS %d\n"
945 "\t CRAM-MD5 %d\n"
946 "\t DIGEST-MD5 %d\n"
947 "\t SCRAM-SHA-1 %d\n"
948 "\t SCRAM-SHA-224 %d\n"
949 "\t SCRAM-SHA-256 %d\n"
950 "\t SCRAM-SHA-384 %d\n"
951 "\t SCRAM-SHA-512 %d\n"
952 "\t PLAIN %d\n"
953 #ifdef USE_GNUTLS
954 "\t OAUTH2 %d\n"
955 #endif
956 "\t LOGIN %d\n"
957 "\t GSSAPI %d\n",
958 imap_has_capability(session, "ANONYMOUS"),
959 imap_has_capability(session, "CRAM-MD5"),
960 imap_has_capability(session, "DIGEST-MD5"),
961 imap_has_capability(session, "SCRAM-SHA-1"),
962 imap_has_capability(session, "SCRAM-SHA-224"),
963 imap_has_capability(session, "SCRAM-SHA-256"),
964 imap_has_capability(session, "SCRAM-SHA-384"),
965 imap_has_capability(session, "SCRAM-SHA-512"),
966 imap_has_capability(session, "PLAIN"),
967 #ifdef USE_GNUTLS
968 imap_has_capability(session, "XOAUTH2"),
969 #endif
970 imap_has_capability(session, "LOGIN"),
971 imap_has_capability(session, "GSSAPI"));
972 if (imap_has_capability(session, "CRAM-MD5"))
973 ok = imap_cmd_login(session, user, pass, "CRAM-MD5");
974 if (ok == MAILIMAP_ERROR_LOGIN && imap_has_capability(session, "DIGEST-MD5"))
975 ok = imap_cmd_login(session, user, pass, "DIGEST-MD5");
976 if (ok == MAILIMAP_ERROR_LOGIN && imap_has_capability(session, "SCRAM-SHA-512"))
977 ok = imap_cmd_login(session, user, pass, "SCRAM-SHA-512");
978 if (ok == MAILIMAP_ERROR_LOGIN && imap_has_capability(session, "SCRAM-SHA-384"))
979 ok = imap_cmd_login(session, user, pass, "SCRAM-SHA-384");
980 if (ok == MAILIMAP_ERROR_LOGIN && imap_has_capability(session, "SCRAM-SHA-256"))
981 ok = imap_cmd_login(session, user, pass, "SCRAM-SHA-256");
982 if (ok == MAILIMAP_ERROR_LOGIN && imap_has_capability(session, "SCRAM-SHA-224"))
983 ok = imap_cmd_login(session, user, pass, "SCRAM-SHA-224");
984 if (ok == MAILIMAP_ERROR_LOGIN && imap_has_capability(session, "SCRAM-SHA-1"))
985 ok = imap_cmd_login(session, user, pass, "SCRAM-SHA-1");
986 if (ok == MAILIMAP_ERROR_LOGIN && imap_has_capability(session, "PLAIN"))
987 ok = imap_cmd_login(session, user, pass, "PLAIN");
988 if (ok == MAILIMAP_ERROR_LOGIN && imap_has_capability(session, "LOGIN"))
989 ok = imap_cmd_login(session, user, pass, "LOGIN");
990 if (ok == MAILIMAP_ERROR_LOGIN && imap_has_capability(session, "GSSAPI"))
991 ok = imap_cmd_login(session, user, pass, "GSSAPI");
992 if (ok == MAILIMAP_ERROR_LOGIN) /* we always try plaintext login before giving up */
993 ok = imap_cmd_login(session, user, pass, "plaintext");
994 #ifdef USE_GNUTLS
995 if (ok == MAILIMAP_ERROR_LOGIN && imap_has_capability(session, "XOAUTH2"))
996 ok = imap_cmd_login(session, user, pass, "XOAUTH2");
997 #endif
1000 if (ok == MAILIMAP_NO_ERROR)
1001 session->authenticated = TRUE;
1002 else {
1003 if (type == IMAP_AUTH_CRAM_MD5) {
1004 ext_info = _("\n\nCRAM-MD5 logins only work if libetpan has been "
1005 "compiled with SASL support and the "
1006 "CRAM-MD5 SASL plugin is installed.");
1009 if (type == IMAP_AUTH_DIGEST_MD5) {
1010 ext_info = _("\n\nDIGEST-MD5 logins only work if libetpan has been "
1011 "compiled with SASL support and the "
1012 "DIGEST-MD5 SASL plugin is installed.");
1015 if (type == IMAP_AUTH_SCRAM_SHA1) {
1016 ext_info = _("\n\nSCRAM-SHA-1 logins only work if libetpan has been "
1017 "compiled with SASL support and the "
1018 "SCRAM SASL plugin is installed.");
1021 if (type == IMAP_AUTH_SCRAM_SHA224) {
1022 ext_info = _("\n\nSCRAM-SHA-224 logins only work if libetpan has been "
1023 "compiled with SASL support and the "
1024 "SCRAM SASL plugin is installed.");
1027 if (type == IMAP_AUTH_SCRAM_SHA256) {
1028 ext_info = _("\n\nSCRAM-SHA-256 logins only work if libetpan has been "
1029 "compiled with SASL support and the "
1030 "SCRAM SASL plugin is installed.");
1033 if (type == IMAP_AUTH_SCRAM_SHA384) {
1034 ext_info = _("\n\nSCRAM-SHA-384 logins only work if libetpan has been "
1035 "compiled with SASL support and the "
1036 "SCRAM SASL plugin is installed.");
1039 if (type == IMAP_AUTH_SCRAM_SHA512) {
1040 ext_info = _("\n\nSCRAM-SHA-512 logins only work if libetpan has been "
1041 "compiled with SASL support and the "
1042 "SCRAM SASL plugin is installed.");
1045 if (type == IMAP_AUTH_PLAIN) {
1046 ext_info = _("\n\nPLAIN logins only work if libetpan has been "
1047 "compiled with SASL support and the "
1048 "PLAIN SASL plugin is installed.");
1051 if (type == IMAP_AUTH_LOGIN) {
1052 ext_info = _("\n\nLOGIN logins only work if libetpan has been "
1053 "compiled with SASL support and the "
1054 "LOGIN SASL plugin is installed.");
1056 #ifdef USE_GNUTLS
1057 if (type == IMAP_AUTH_OAUTH2) {
1058 ext_info = _("\n\nOAuth2 error. Check and correct your OAuth2 "
1059 "account preferences.");
1061 #endif
1062 if (time(NULL) - last_login_err > 10) {
1063 if (prefs_common.show_recv_err_dialog) {
1064 alertpanel_error_log(_("Connection to %s failed: "
1065 "login refused.%s"),
1066 server, ext_info);
1067 } else {
1068 log_error(LOG_PROTOCOL, _("Connection to %s failed: "
1069 "login refused.%s\n"),
1070 server, ext_info);
1073 last_login_err = time(NULL);
1075 g_free(server);
1076 return ok;
1079 static IMAPSession *imap_reconnect_if_possible(Folder *folder, IMAPSession *session)
1081 RemoteFolder *rfolder = REMOTE_FOLDER(folder);
1082 /* Check if this is the first try to establish a
1083 connection, if yes we don't try to reconnect */
1084 debug_print("reconnecting\n");
1085 if (rfolder->session == NULL) {
1086 log_warning(LOG_PROTOCOL, _("Connecting to %s failed"),
1087 folder->account->recv_server);
1088 SESSION(session)->sock = NULL;
1089 imap_safe_destroy(session);
1090 session = NULL;
1091 } else {
1092 rfolder->session = NULL;
1093 log_warning(LOG_PROTOCOL, _("IMAP connection to %s has been"
1094 " disconnected. Reconnecting...\n"),
1095 folder->account->recv_server);
1096 statusbar_print_all(_("IMAP connection to %s has been"
1097 " disconnected. Reconnecting...\n"),
1098 folder->account->recv_server);
1099 SESSION(session)->state = SESSION_DISCONNECTED;
1100 SESSION(session)->sock = NULL;
1101 imap_safe_destroy(session);
1102 /* Clear folders session to make imap_session_get create
1103 a new session, because of rfolder->session == NULL
1104 it will not try to reconnect again and so avoid an
1105 endless loop */
1106 debug_print("getting session...\n");
1107 session = imap_session_get(folder);
1108 rfolder->session = SESSION(session);
1109 statusbar_pop_all();
1111 return session;
1114 static IMAPSession *imap_session_get(Folder *folder)
1116 RemoteFolder *rfolder = REMOTE_FOLDER(folder);
1117 IMAPSession *session = NULL;
1118 gint r = MAILIMAP_NO_ERROR;
1120 g_return_val_if_fail(folder != NULL, NULL);
1121 g_return_val_if_fail(FOLDER_CLASS(folder) == &imap_class, NULL);
1122 g_return_val_if_fail(folder->account != NULL, NULL);
1124 if (prefs_common.work_offline &&
1125 !inc_offline_should_override(FALSE,
1126 _("Claws Mail needs network access in order "
1127 "to access the IMAP server."))) {
1128 return NULL;
1131 /* check for deferred destroy */
1132 if (rfolder->session != NULL) {
1133 session = IMAP_SESSION(rfolder->session);
1134 if (!session->busy && session->do_destroy) {
1135 rfolder->session = NULL;
1136 imap_safe_destroy(session);
1137 session = NULL;
1141 /* Make sure we have a session */
1142 if (rfolder->session != NULL && rfolder->session->state != SESSION_DISCONNECTED) {
1143 session = IMAP_SESSION(rfolder->session);
1144 } else if (rfolder->session != NULL && rfolder->session->state == SESSION_DISCONNECTED) {
1145 imap_safe_destroy(IMAP_SESSION(rfolder->session));
1146 rfolder->session = NULL;
1147 goto new_conn;
1148 } else if (rfolder->connecting) {
1149 debug_print("already connecting\n");
1150 return NULL;
1151 } else {
1152 new_conn:
1153 imap_reset_uid_lists(folder);
1154 if (time(NULL) - rfolder->last_failure <= 2)
1155 return NULL;
1156 rfolder->connecting = TRUE;
1157 session = imap_session_new(folder, folder->account);
1159 if(session == NULL) {
1160 rfolder->last_failure = time(NULL);
1161 rfolder->connecting = FALSE;
1162 return NULL;
1165 /* Make sure session is authenticated */
1166 if (!IMAP_SESSION(session)->authenticated)
1167 r = imap_session_authenticate(IMAP_SESSION(session), folder->account);
1169 if (r != MAILIMAP_NO_ERROR || (!is_fatal(r) && !IMAP_SESSION(session)->authenticated)) {
1170 rfolder->session = NULL;
1171 if (!is_fatal(r)) {
1172 imap_threaded_disconnect(session->folder);
1174 SESSION(session)->state = SESSION_DISCONNECTED;
1175 SESSION(session)->sock = NULL;
1176 imap_safe_destroy(session);
1177 rfolder->last_failure = time(NULL);
1178 rfolder->connecting = FALSE;
1179 return NULL;
1182 /* I think the point of this code is to avoid sending a
1183 * keepalive if we've used the session recently and therefore
1184 * think it's still alive. Unfortunately, most of the code
1185 * does not yet check for errors on the socket, and so if the
1186 * connection drops we don't notice until the timeout expires.
1187 * A better solution than sending a NOOP every time would be
1188 * for every command to be prepared to retry until it is
1189 * successfully sent. -- mbp */
1190 if ((time(NULL) - SESSION(session)->last_access_time > SESSION_TIMEOUT_INTERVAL) || session->cancelled) {
1191 /* verify that the session is still alive */
1192 r = imap_cmd_noop(session);
1194 if (r != MAILIMAP_NO_ERROR) {
1195 debug_print("disconnected!\n");
1196 if (!is_fatal(r))
1197 session = imap_reconnect_if_possible(folder, session);
1198 else {
1199 rfolder->session = NULL;
1200 rfolder->connecting = FALSE;
1201 SESSION(session)->state = SESSION_DISCONNECTED;
1202 SESSION(session)->sock = NULL;
1203 imap_safe_destroy(session);
1204 session = imap_session_get(folder);
1207 if (session)
1208 session->cancelled = FALSE;
1211 rfolder->session = SESSION(session);
1212 rfolder->connecting = FALSE;
1214 return IMAP_SESSION(session);
1217 static IMAPSession *imap_session_new(Folder * folder,
1218 const PrefsAccount *account)
1220 IMAPSession *session;
1221 ProxyInfo *proxy_info = NULL;
1222 gushort port;
1223 int r;
1224 int authenticated = FALSE;
1225 gchar *buf;
1227 #ifdef USE_GNUTLS
1228 /* FIXME: IMAP over SSL only... */
1229 SSLType ssl_type;
1231 port = account->set_imapport ? account->imapport
1232 : account->ssl_imap == SSL_TUNNEL ? IMAPS_PORT : IMAP4_PORT;
1233 ssl_type = account->ssl_imap;
1234 #else
1235 if (account->ssl_imap != SSL_NONE) {
1236 if (alertpanel_full(_("Insecure connection"),
1237 _("This connection is configured to be secured "
1238 "using TLS, but TLS is not available "
1239 "in this build of Claws Mail. \n\n"
1240 "Do you want to continue connecting to this "
1241 "server? The communication would not be "
1242 "secure."),
1243 NULL, _("_Cancel"), NULL, _("Con_tinue connecting"), NULL, NULL,
1244 ALERTFOCUS_FIRST, FALSE, NULL, ALERT_WARNING) != G_ALERTALTERNATE)
1245 return NULL;
1247 port = account->set_imapport ? account->imapport
1248 : IMAP4_PORT;
1249 #endif
1251 imap_init(folder);
1252 IMAP_FOLDER(folder)->max_set_size = account->imap_batch_size;
1253 buf = g_strdup_printf(_("Account '%s': Connecting to IMAP server: %s:%d..."),
1254 folder->account->account_name, folder->account->recv_server,
1255 port);
1256 statusbar_print_all("%s", buf);
1257 log_message(LOG_PROTOCOL, "%s\n", buf);
1258 g_free(buf);
1260 if (account->use_proxy) {
1261 if (account->use_default_proxy) {
1262 proxy_info = (ProxyInfo *)&(prefs_common.proxy_info);
1263 if (proxy_info->use_proxy_auth)
1264 proxy_info->proxy_pass = passwd_store_get(PWS_CORE, PWS_CORE_PROXY,
1265 PWS_CORE_PROXY_PASS);
1266 } else {
1267 proxy_info = (ProxyInfo *)&(account->proxy_info);
1268 if (proxy_info->use_proxy_auth)
1269 proxy_info->proxy_pass = passwd_store_get_account(account->account_id,
1270 PWS_ACCOUNT_PROXY_PASS);
1274 #ifndef G_OS_WIN32
1275 if (account->set_tunnelcmd) {
1276 r = imap_threaded_connect_cmd(folder,
1277 account->tunnelcmd,
1278 account->recv_server,
1279 port);
1281 else
1282 #endif
1284 #ifdef USE_GNUTLS
1286 if (ssl_type == SSL_TUNNEL) {
1287 r = imap_threaded_connect_ssl(folder,
1288 account->recv_server,
1289 port,
1290 proxy_info);
1292 else
1293 #endif
1295 r = imap_threaded_connect(folder,
1296 account->recv_server,
1297 port,
1298 proxy_info);
1302 statusbar_pop_all();
1303 if (r == MAILIMAP_NO_ERROR_AUTHENTICATED) {
1304 authenticated = TRUE;
1306 else if (r == MAILIMAP_NO_ERROR_NON_AUTHENTICATED) {
1307 authenticated = FALSE;
1309 else {
1310 #ifdef USE_GNUTLS
1311 if (r == MAILIMAP_ERROR_SSL)
1312 log_error(LOG_PROTOCOL, _("TLS handshake failed\n"));
1313 else
1314 #endif
1315 imap_handle_error(NULL, account->recv_server, r);
1317 if(prefs_common.show_recv_err_dialog) {
1318 alertpanel_error_log(_("Can't connect to IMAP server: %s:%d"),
1319 account->recv_server, port);
1320 } else {
1321 log_error(LOG_PROTOCOL, _("Can't connect to IMAP server: %s:%d\n"),
1322 account->recv_server, port);
1325 return NULL;
1328 session = g_new0(IMAPSession, 1);
1329 session_init(SESSION(session), account, FALSE);
1330 SESSION(session)->type = SESSION_IMAP;
1331 SESSION(session)->server = g_strdup(account->recv_server);
1332 SESSION(session)->port = port;
1333 SESSION(session)->sock = NULL;
1334 SESSION(session)->proxy_info = proxy_info;
1335 SESSION(session)->destroy = imap_session_destroy;
1337 session->capability = NULL;
1338 session->authenticated = authenticated;
1339 session->mbox = NULL;
1340 session->exists = 0;
1341 session->recent = 0;
1342 session->expunge = 0;
1343 session->cmd_count = 0;
1344 session->folder = folder;
1345 IMAP_FOLDER(session->folder)->last_seen_separator = 0;
1347 #ifdef USE_GNUTLS
1348 if (account->ssl_imap == SSL_STARTTLS) {
1349 gint ok;
1351 ok = imap_cmd_starttls(session);
1352 if (ok != MAILIMAP_NO_ERROR) {
1353 log_warning(LOG_PROTOCOL, _("Can't start STARTTLS session.\n"));
1354 if (!is_fatal(ok)) {
1355 SESSION(session)->sock = NULL;
1356 imap_safe_destroy(session);
1358 return NULL;
1361 imap_free_capabilities(session);
1362 session->authenticated = FALSE;
1363 session->uidplus = FALSE;
1364 session->cmd_count = 1;
1366 SESSION(session)->use_tls_sni = account->use_tls_sni;
1367 #endif
1369 log_message(LOG_PROTOCOL, "IMAP connection is %s-authenticated\n",
1370 (session->authenticated) ? "pre" : "un");
1372 session_register_ping(SESSION(session), imap_ping);
1374 return session;
1377 static gint imap_session_authenticate(IMAPSession *session,
1378 PrefsAccount *account)
1380 gchar *pass, *acc_pass = NULL;
1381 gboolean failed = FALSE;
1382 gint ok = MAILIMAP_NO_ERROR;
1383 g_return_val_if_fail(account->userid != NULL, MAILIMAP_ERROR_BAD_STATE);
1384 #ifdef USE_OAUTH2
1385 if(account->imap_auth_type == IMAP_AUTH_OAUTH2)
1386 oauth2_check_passwds (account);
1387 #endif
1388 if (!password_get(account->userid, account->recv_server, "imap",
1389 SESSION(session)->port, &acc_pass)) {
1390 acc_pass = passwd_store_get_account(account->account_id,
1391 PWS_ACCOUNT_RECV);
1394 try_again:
1395 pass = acc_pass;
1396 if (!pass && account->imap_auth_type != IMAP_AUTH_ANON && account->imap_auth_type != IMAP_AUTH_GSSAPI) {
1397 gchar *tmp_pass;
1398 tmp_pass = input_dialog_query_password_keep(account->recv_server,
1399 account->userid,
1400 &(account->session_passwd));
1401 if (!tmp_pass) {
1402 return MAILIMAP_NO_ERROR;
1404 Xstrdup_a(pass, tmp_pass, {g_free(tmp_pass); return MAILIMAP_NO_ERROR;});
1405 g_free(tmp_pass);
1406 } else if (account->imap_auth_type == IMAP_AUTH_ANON || account->imap_auth_type == IMAP_AUTH_GSSAPI) {
1407 pass = "";
1409 if ((ok = imap_auth(session, account->userid, pass, account->imap_auth_type)) != MAILIMAP_NO_ERROR) {
1411 if (!failed && !is_fatal(ok)) {
1412 if (acc_pass != NULL) {
1413 memset(acc_pass, 0, strlen(acc_pass));
1414 g_free(acc_pass);
1415 acc_pass = NULL;
1417 failed = TRUE;
1418 if (account->session_passwd != NULL) {
1419 g_free(account->session_passwd);
1420 account->session_passwd = NULL;
1422 goto try_again;
1423 } else {
1424 if (!prefs_common.show_recv_err_dialog) {
1425 log_error(LOG_PROTOCOL, _("Couldn't login to IMAP server %s.\n"), account->recv_server);
1426 mainwindow_show_error();
1427 } else
1428 alertpanel_error_log(_("Couldn't login to IMAP server %s."), account->recv_server);
1431 if (acc_pass != NULL) {
1432 memset(acc_pass, 0, strlen(acc_pass));
1433 g_free(acc_pass);
1434 acc_pass = NULL;
1437 return ok;
1440 if (acc_pass) {
1441 memset(acc_pass, 0, strlen(acc_pass));
1442 g_free(acc_pass);
1444 statusbar_pop_all();
1445 session->authenticated = TRUE;
1446 return MAILIMAP_NO_ERROR;
1449 static void imap_session_destroy(Session *session)
1451 if (session->state != SESSION_DISCONNECTED)
1452 imap_threaded_disconnect(IMAP_SESSION(session)->folder);
1454 imap_free_capabilities(IMAP_SESSION(session));
1455 g_free(IMAP_SESSION(session)->mbox);
1458 static gchar *imap_fetch_msg(Folder *folder, FolderItem *item, gint uid)
1460 return imap_fetch_msg_full(folder, item, uid, TRUE, TRUE);
1463 static guint get_file_size_with_crs(const gchar *filename)
1465 FILE *fp = NULL;
1466 guint cnt = 0;
1467 gchar buf[4096];
1469 if (filename == NULL)
1470 return -1;
1472 fp = claws_fopen(filename, "rb");
1473 if (!fp)
1474 return -1;
1476 while (claws_fgets(buf, sizeof (buf), fp) != NULL) {
1477 cnt += strlen(buf);
1478 if (!strstr(buf, "\r\n") && strstr(buf, "\n"))
1479 cnt++;
1482 claws_fclose(fp);
1483 return cnt;
1486 static gchar *imap_get_cached_filename(FolderItem *item, guint msgnum)
1488 gchar *path, *filename;
1490 cm_return_val_if_fail(item != NULL, NULL);
1492 path = folder_item_get_path(item);
1494 if (!is_dir_exist(path)) {
1495 g_free(path);
1496 return NULL;
1499 filename = g_strconcat(path, G_DIR_SEPARATOR_S, itos(msgnum), NULL);
1501 if (is_dir_exist(filename)) {
1502 g_free(filename);
1503 filename = g_strconcat(path, G_DIR_SEPARATOR_S, ".", itos(msgnum), NULL);
1505 g_free(path);
1507 return filename;
1510 static void imap_remove_cached_msg(Folder *folder, FolderItem *item, MsgInfo *msginfo)
1512 gchar *filename;
1514 filename = imap_get_cached_filename(item, msginfo->msgnum);
1516 cm_return_if_fail(filename != NULL);
1518 if (is_file_exist(filename)) {
1519 claws_unlink(filename);
1521 g_free(filename);
1524 typedef struct _TagsData {
1525 gchar *str;
1526 GSList *msglist;
1527 IMAPFolderItem *item;
1528 } TagsData;
1530 static void imap_commit_tags(FolderItem *item, MsgInfo *msginfo, GSList *tags_set, GSList *tags_unset)
1532 IMAPSession *session;
1533 gint ok, can_create_tags;
1534 Folder *folder = NULL;
1535 TagsData *ht_data = NULL;
1536 GSList *cur;
1538 g_return_if_fail(item != NULL);
1539 g_return_if_fail(msginfo != NULL);
1541 folder = item->folder;
1542 debug_print("getting session...\n");
1543 session = imap_session_get(folder);
1545 if (!session) {
1546 debug_print("can't get session\n");
1547 return;
1550 ok = imap_select(session, IMAP_FOLDER(folder), item,
1551 NULL, NULL, NULL, NULL, &can_create_tags, FALSE);
1553 if (ok != MAILIMAP_NO_ERROR) {
1554 return;
1558 if (IMAP_FOLDER_ITEM(item)->can_create_flags != ITEM_CAN_CREATE_FLAGS)
1559 return;
1561 if (IMAP_FOLDER_ITEM(item)->batching) {
1562 /* instead of performing an UID STORE command for each message change,
1563 * as a lot of them can change "together", we just fill in hashtables
1564 * and defer the treatment so that we're able to send only one
1565 * command.
1567 debug_print("IMAP batch mode on, deferring tags change\n");
1568 for (cur = tags_set; cur; cur = cur->next) {
1569 gint cur_tag = GPOINTER_TO_INT(cur->data);
1570 if (cur_tag) {
1571 ht_data = g_hash_table_lookup(IMAP_FOLDER_ITEM(item)->tags_set_table,
1572 GINT_TO_POINTER(cur_tag));
1573 if (ht_data == NULL) {
1574 ht_data = g_new0(TagsData, 1);
1575 ht_data->str = g_strdup(tags_get_tag(cur_tag));
1576 ht_data->item = IMAP_FOLDER_ITEM(item);
1577 g_hash_table_insert(IMAP_FOLDER_ITEM(item)->tags_set_table,
1578 GINT_TO_POINTER(cur_tag), ht_data);
1580 ht_data->msglist = g_slist_prepend(ht_data->msglist, GINT_TO_POINTER(msginfo->msgnum));
1583 for (cur = tags_unset; cur; cur = cur->next) {
1584 gint cur_tag = GPOINTER_TO_INT(cur->data);
1585 if (cur_tag) {
1586 ht_data = g_hash_table_lookup(IMAP_FOLDER_ITEM(item)->tags_unset_table,
1587 GINT_TO_POINTER(cur_tag));
1588 if (ht_data == NULL) {
1589 ht_data = g_new0(TagsData, 1);
1590 ht_data->str = g_strdup(tags_get_tag(cur_tag));
1591 ht_data->item = IMAP_FOLDER_ITEM(item);
1592 g_hash_table_insert(IMAP_FOLDER_ITEM(item)->tags_unset_table,
1593 GINT_TO_POINTER(cur_tag), ht_data);
1595 ht_data->msglist = g_slist_prepend(ht_data->msglist, GINT_TO_POINTER(msginfo->msgnum));
1598 } else {
1599 GSList *list_set = NULL;
1600 GSList *list_unset = NULL;
1601 GSList numlist;
1603 numlist.data = GINT_TO_POINTER(msginfo->msgnum);
1604 numlist.next = NULL;
1606 debug_print("IMAP changing tags NOW\n");
1607 for (cur = tags_set; cur; cur = cur->next) {
1608 gint cur_tag = GPOINTER_TO_INT(cur->data);
1609 const gchar *str = tags_get_tag(cur_tag);
1610 if (IS_NOT_RESERVED_TAG(str))
1611 list_set = g_slist_prepend(list_set, g_strdup(str));
1613 if (list_set) {
1614 ok = imap_set_message_flags(session,
1615 IMAP_FOLDER_ITEM(item), &numlist, 0, list_set, TRUE);
1616 slist_free_strings_full(list_set);
1617 if (ok != MAILIMAP_NO_ERROR) {
1618 return;
1622 for (cur = tags_unset; cur; cur = cur->next) {
1623 gint cur_tag = GPOINTER_TO_INT(cur->data);
1624 const gchar *str = tags_get_tag(cur_tag);
1625 if (IS_NOT_RESERVED_TAG(str))
1626 list_unset = g_slist_prepend(list_unset, g_strdup(str));
1628 if (list_unset) {
1629 ok = imap_set_message_flags(session,
1630 IMAP_FOLDER_ITEM(item), &numlist, 0, list_unset, FALSE);
1631 slist_free_strings_full(list_unset);
1632 if (ok != MAILIMAP_NO_ERROR) {
1633 return;
1639 static gchar *imap_fetch_msg_full(Folder *folder, FolderItem *item, gint uid,
1640 gboolean headers, gboolean body)
1642 gchar *path, *filename;
1643 IMAPSession *session;
1644 gint ok;
1646 g_return_val_if_fail(folder != NULL, NULL);
1647 g_return_val_if_fail(item != NULL, NULL);
1649 if (uid == 0)
1650 return NULL;
1652 path = folder_item_get_path(item);
1653 if (!is_dir_exist(path)) {
1654 if(is_file_exist(path))
1655 claws_unlink(path);
1656 make_dir_hier(path);
1658 g_free(path);
1660 filename = imap_get_cached_filename(item, uid);
1661 debug_print("trying to fetch cached %s\n", filename);
1663 if (is_file_exist(filename)) {
1664 /* see whether the local file represents the whole message
1665 * or not. As the IMAP server reports size with \r chars,
1666 * we have to update the local file (UNIX \n only) size */
1667 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1668 guint have_size = -1;
1670 if (cached)
1671 debug_print("message %d has been already %scached.\n", uid,
1672 MSG_IS_FULLY_CACHED(cached->flags) ? "fully ":"");
1674 if (!cached || !MSG_IS_FULLY_CACHED(cached->flags)) {
1675 have_size = get_file_size_with_crs(filename);
1676 if (cached && (cached->size <= have_size || !body)) {
1677 ok = file_strip_crs(filename);
1678 if (ok == 0 && cached && cached->size <= have_size) {
1679 /* we have it all and stripped */
1680 debug_print("...fully cached in fact (%u/%"G_GOFFSET_FORMAT"); setting flag.\n",
1681 have_size, cached->size);
1682 procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
1684 procmsg_msginfo_free(&cached);
1685 return filename;
1686 } else if (!cached && time(NULL) - get_file_mtime(filename) < 60) {
1687 debug_print("message not cached and file recent, considering file complete\n");
1688 ok = file_strip_crs(filename);
1689 if (ok == 0)
1690 return filename;
1691 } else {
1692 procmsg_msginfo_free(&cached);
1695 if (cached && MSG_IS_FULLY_CACHED(cached->flags)) {
1696 procmsg_msginfo_free(&cached);
1697 return filename;
1699 } else {
1700 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1701 if (cached) {
1702 procmsg_msginfo_unset_flags(cached, MSG_FULLY_CACHED, 0);
1703 procmsg_msginfo_free(&cached);
1707 debug_print("getting session...\n");
1708 session = imap_session_get(folder);
1710 if (!session) {
1711 g_free(filename);
1712 return NULL;
1714 session_set_access_time(SESSION(session));
1715 lock_session(session); /* unlocked later in the function */
1717 debug_print("IMAP fetching messages\n");
1718 ok = imap_select(session, IMAP_FOLDER(folder), item,
1719 NULL, NULL, NULL, NULL, NULL, FALSE);
1720 if (ok != MAILIMAP_NO_ERROR) {
1721 g_warning("can't select mailbox %s", item->path);
1722 g_free(filename);
1723 return NULL;
1726 session_set_access_time(SESSION(session));
1728 debug_print("getting message %d...\n", uid);
1729 ok = imap_cmd_fetch(session, (guint32)uid, filename, headers, body);
1731 if (ok != MAILIMAP_NO_ERROR) {
1732 g_warning("can't fetch message %d", uid);
1733 g_free(filename);
1734 return NULL;
1737 session_set_access_time(SESSION(session));
1738 unlock_session(session);
1740 ok = file_strip_crs(filename);
1742 if (ok == 0 && headers && body) {
1743 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1744 if (cached) {
1745 procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
1746 procmsg_msginfo_free(&cached);
1748 } else if (ok == -1) {
1749 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1750 if (cached) {
1751 procmsg_msginfo_unset_flags(cached, MSG_FULLY_CACHED, 0);
1752 procmsg_msginfo_free(&cached);
1755 return filename;
1758 static gboolean imap_is_msg_fully_cached(Folder *folder, FolderItem *item, gint uid)
1760 gchar *filename;
1761 guint size = 0;
1762 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1764 if (!cached)
1765 return FALSE;
1767 if (MSG_IS_FULLY_CACHED(cached->flags)) {
1768 procmsg_msginfo_free(&cached);
1769 return TRUE;
1772 filename = imap_get_cached_filename(item, uid);
1774 if (is_file_exist(filename)) {
1775 if (cached && cached->total_size == cached->size) {
1776 /* fast path */
1777 g_free(filename);
1778 procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
1779 return TRUE;
1781 size = get_file_size_with_crs(filename);
1783 g_free(filename);
1784 debug_print("msg %d cached, has size %d, full should be %"G_GOFFSET_FORMAT".\n", uid, size, cached->size);
1785 if (cached && size >= cached->size) {
1786 cached->total_size = cached->size;
1787 procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
1788 procmsg_msginfo_free(&cached);
1789 return TRUE;
1791 if (cached)
1792 procmsg_msginfo_free(&cached);
1793 return FALSE;
1796 void imap_cache_msg(FolderItem *item, gint msgnum)
1798 Folder *folder = NULL;
1800 if (!item)
1801 return;
1802 folder = item->folder;
1804 if (!imap_is_msg_fully_cached(folder, item, msgnum)) {
1805 gchar *tmp = imap_fetch_msg_full(folder, item, msgnum, TRUE, TRUE);
1806 debug_print("fetched %s\n", tmp);
1807 g_free(tmp);
1811 static gint imap_add_msg(Folder *folder, FolderItem *dest,
1812 const gchar *file, MsgFlags *flags)
1814 gint ret;
1815 GSList file_list;
1816 MsgFileInfo fileinfo;
1818 g_return_val_if_fail(file != NULL, -1);
1820 fileinfo.msginfo = NULL;
1821 fileinfo.file = (gchar *)file;
1822 fileinfo.flags = flags;
1823 file_list.data = &fileinfo;
1824 file_list.next = NULL;
1826 ret = imap_add_msgs(folder, dest, &file_list, NULL);
1827 return ret;
1830 static gint imap_add_msgs(Folder *folder, FolderItem *dest, GSList *file_list,
1831 GHashTable *relation)
1833 gchar *destdir;
1834 IMAPSession *session;
1835 guint32 last_uid = 0;
1836 GSList *cur;
1837 MsgFileInfo *fileinfo;
1838 gint ok = MAILIMAP_NO_ERROR;
1839 gint curnum = 0, total = 0;
1840 gboolean missing_uids = FALSE;
1842 g_return_val_if_fail(folder != NULL, -1);
1843 g_return_val_if_fail(dest != NULL, -1);
1844 g_return_val_if_fail(file_list != NULL, -1);
1846 debug_print("getting session...\n");
1847 session = imap_session_get(folder);
1848 if (!session) {
1849 return -1;
1851 destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path, &ok);
1852 if (is_fatal(ok)) {
1853 g_free(destdir);
1854 return -1;
1856 statusbar_print_all(_("Adding messages..."));
1857 total = g_slist_length(file_list);
1858 for (cur = file_list; cur != NULL; cur = cur->next) {
1859 IMAPFlags iflags = 0;
1860 guint32 new_uid = 0;
1861 gchar *real_file = NULL;
1862 fileinfo = (MsgFileInfo *)cur->data;
1864 statusbar_progress_all(curnum, total, total < 10 ? 1:10);
1865 curnum++;
1867 if (fileinfo->flags) {
1868 if (MSG_IS_MARKED(*fileinfo->flags))
1869 iflags |= IMAP_FLAG_FLAGGED;
1870 if (MSG_IS_REPLIED(*fileinfo->flags))
1871 iflags |= IMAP_FLAG_ANSWERED;
1872 if (MSG_IS_FORWARDED(*fileinfo->flags))
1873 iflags |= IMAP_FLAG_FORWARDED;
1874 if (MSG_IS_SPAM(*fileinfo->flags))
1875 iflags |= IMAP_FLAG_SPAM;
1876 else
1877 iflags |= IMAP_FLAG_HAM;
1878 if (!MSG_IS_UNREAD(*fileinfo->flags))
1879 iflags |= IMAP_FLAG_SEEN;
1883 if (real_file == NULL)
1884 real_file = g_strdup(fileinfo->file);
1886 if (folder_has_parent_of_type(dest, F_QUEUE) ||
1887 folder_has_parent_of_type(dest, F_OUTBOX) ||
1888 folder_has_parent_of_type(dest, F_DRAFT) ||
1889 folder_has_parent_of_type(dest, F_TRASH))
1890 iflags |= IMAP_FLAG_SEEN;
1892 ok = imap_cmd_append(session, IMAP_FOLDER_ITEM(dest), destdir, real_file, iflags,
1893 &new_uid);
1895 if (ok != MAILIMAP_NO_ERROR) {
1896 g_warning("can't append message %s", real_file);
1897 g_free(real_file);
1898 g_free(destdir);
1899 statusbar_progress_all(0,0,0);
1900 statusbar_pop_all();
1901 return -1;
1902 } else {
1903 debug_print("appended new message as %d\n", new_uid);
1904 /* put the local file in the imapcache, so that we don't
1905 * have to fetch it back later. */
1907 if (new_uid == 0) {
1908 missing_uids = TRUE;
1909 debug_print("Missing UID (0)\n");
1911 if (new_uid > 0) {
1912 gchar *cache_path = folder_item_get_path(dest);
1913 if (!is_dir_exist(cache_path))
1914 make_dir_hier(cache_path);
1915 if (is_dir_exist(cache_path)) {
1916 gchar *cache_file = g_strconcat(
1917 cache_path, G_DIR_SEPARATOR_S,
1918 itos(new_uid), NULL);
1919 if (copy_file(real_file, cache_file, TRUE) < 0) {
1920 g_warning("can't copy %s to %s.bak", real_file, cache_file);
1921 } else {
1922 debug_print("got UID %d, copied to cache: %s\n", new_uid, cache_file);
1924 g_free(cache_file);
1926 g_free(cache_path);
1930 if (relation != NULL)
1931 g_hash_table_insert(relation, fileinfo->msginfo != NULL ?
1932 (gpointer) fileinfo->msginfo : (gpointer) fileinfo,
1933 GINT_TO_POINTER(new_uid));
1934 if (last_uid < new_uid) {
1935 last_uid = new_uid;
1938 g_free(real_file);
1941 statusbar_progress_all(0,0,0);
1942 statusbar_pop_all();
1945 g_free(destdir);
1947 imap_scan_required(folder, dest);
1949 session = imap_session_get(folder);
1950 if (!session) {
1951 return -1;
1953 if (missing_uids) {
1954 gint a;
1955 ok = imap_select(session, IMAP_FOLDER(folder), dest,
1956 &a, NULL, NULL, NULL, NULL, FALSE);
1958 return last_uid;
1961 static GSList *flatten_mailimap_set(struct mailimap_set * set)
1963 GSList *result = NULL;
1964 clistiter *list;
1965 guint32 start, end, t;
1966 GSList *cur;
1968 if (!set || !set->set_list)
1969 return NULL;
1971 for (list = clist_begin(set->set_list); list; list = clist_next(list)) {
1972 struct mailimap_set_item *item = (struct mailimap_set_item *)clist_content(list);
1973 start = item->set_first;
1974 end = item->set_last;
1975 if (start <= end) {
1976 for (t = start; t <= end; t++) {
1977 result = g_slist_prepend(result, GINT_TO_POINTER(t));
1981 result = g_slist_reverse(result);
1982 if (debug_get_mode()) {
1983 debug_print("flat imap set: ");
1984 for (cur = result; cur; cur = cur->next) {
1985 debug_print("%d ", GPOINTER_TO_INT(cur->data));
1987 debug_print("\n");
1990 return result;
1992 static gint imap_do_copy_msgs(Folder *folder, FolderItem *dest,
1993 MsgInfoList *msglist, GHashTable *relation,
1994 gboolean same_dest_ok)
1996 FolderItem *src;
1997 gchar *destdir;
1998 GSList *seq_list, *cur;
1999 MsgInfo *msginfo;
2000 IMAPSession *session;
2001 gint ok = MAILIMAP_NO_ERROR;
2002 GHashTable *uid_hash;
2003 gint last_num = 0;
2005 g_return_val_if_fail(folder != NULL, -1);
2006 g_return_val_if_fail(dest != NULL, -1);
2007 g_return_val_if_fail(msglist != NULL, -1);
2009 debug_print("getting session...\n");
2010 session = imap_session_get(folder);
2012 if (!session) {
2013 return -1;
2016 msginfo = (MsgInfo *)msglist->data;
2017 src = msginfo->folder;
2018 if (!same_dest_ok && src == dest) {
2019 g_warning("the src folder is identical to the dest");
2020 return -1;
2023 if (src->folder != dest->folder) {
2024 GSList *infolist = NULL, *cur;
2025 int res = -1;
2026 for (cur = msglist; cur; cur = cur->next) {
2027 msginfo = (MsgInfo *)cur->data;
2028 MsgFileInfo *fileinfo = g_new0(MsgFileInfo, 1);
2029 fileinfo->file = procmsg_get_message_file(msginfo);
2030 fileinfo->flags = &(msginfo->flags);
2031 infolist = g_slist_prepend(infolist, fileinfo);
2033 infolist = g_slist_reverse(infolist);
2034 res = folder_item_add_msgs(dest, infolist, FALSE);
2035 for (cur = infolist; cur; cur = cur->next) {
2036 MsgFileInfo *info = (MsgFileInfo *)cur->data;
2037 g_free(info->file);
2038 g_free(info);
2040 g_slist_free(infolist);
2041 return res;
2044 lock_session(session); /* unlocked later in the function */
2046 ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder,
2047 NULL, NULL, NULL, NULL, NULL, FALSE);
2048 if (ok != MAILIMAP_NO_ERROR) {
2049 return ok;
2052 unlock_session(session);
2054 destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path, &ok);
2056 if (is_fatal(ok)) {
2057 g_free(destdir);
2058 return ok;
2061 seq_list = imap_get_lep_set_from_msglist(IMAP_FOLDER(folder), msglist);
2062 uid_hash = g_hash_table_new(g_direct_hash, g_direct_equal);
2064 statusbar_print_all(_("Copying messages..."));
2065 for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
2066 struct mailimap_set * seq_set;
2067 struct mailimap_set * source = NULL;
2068 struct mailimap_set * dest = NULL;
2069 seq_set = cur->data;
2071 debug_print("Copying messages from %s to %s ...\n",
2072 src->path, destdir);
2074 lock_session(session); /* unlocked later in the function */
2075 ok = imap_cmd_copy(session, seq_set, destdir,
2076 &source, &dest);
2078 if (is_fatal(ok)) {
2079 session = NULL;
2082 if (ok == MAILIMAP_NO_ERROR) {
2083 unlock_session(session);
2084 if (relation && source && dest) {
2085 GSList *s_list = flatten_mailimap_set(source);
2086 GSList *d_list = flatten_mailimap_set(dest);
2087 GSList *s_cur, *d_cur;
2088 if (g_slist_length(s_list) == g_slist_length(d_list)) {
2090 for (s_cur = s_list, d_cur = d_list;
2091 s_cur && d_cur;
2092 s_cur = s_cur->next, d_cur = d_cur->next) {
2093 g_hash_table_insert(uid_hash, s_cur->data, d_cur->data);
2096 } else {
2097 debug_print("hhhmm, source list length != dest list length.\n");
2099 g_slist_free(s_list);
2100 g_slist_free(d_list);
2105 if (source)
2106 mailimap_set_free(source);
2107 if (dest)
2108 mailimap_set_free(dest);
2110 if (ok != MAILIMAP_NO_ERROR) {
2111 g_hash_table_destroy(uid_hash);
2112 imap_lep_set_free(seq_list);
2113 statusbar_pop_all();
2114 return -1;
2118 for (cur = msglist; cur != NULL; cur = g_slist_next(cur)) {
2119 MsgInfo *msginfo = (MsgInfo *)cur->data;
2120 gpointer hashval;
2122 hashval = g_hash_table_lookup(uid_hash, GINT_TO_POINTER(msginfo->msgnum));
2124 if (hashval != NULL) {
2125 gint num = GPOINTER_TO_INT(hashval);
2126 g_hash_table_insert(relation, msginfo,
2127 GINT_TO_POINTER(num));
2128 if (num > last_num)
2129 last_num = num;
2130 debug_print("copied message %d as %d\n", msginfo->msgnum, num);
2131 /* put the local file in the imapcache, so that we don't
2132 * have to fetch it back later. */
2133 if (num > 0) {
2134 gchar *cache_path = folder_item_get_path(msginfo->folder);
2135 gchar *real_file = g_strconcat(
2136 cache_path, G_DIR_SEPARATOR_S,
2137 itos(msginfo->msgnum), NULL);
2138 gchar *cache_file = NULL;
2139 g_free(cache_path);
2140 cache_path = folder_item_get_path(dest);
2141 cache_file = g_strconcat(
2142 cache_path, G_DIR_SEPARATOR_S,
2143 itos(num), NULL);
2144 if (!is_dir_exist(cache_path))
2145 make_dir_hier(cache_path);
2146 if (is_file_exist(real_file) && is_dir_exist(cache_path)) {
2147 if (copy_file(real_file, cache_file, TRUE) < 0)
2148 debug_print("couldn't cache to %s: %s\n", cache_file,
2149 strerror(errno));
2150 else
2151 debug_print("copied to cache: %s\n", cache_file);
2153 g_free(real_file);
2154 g_free(cache_file);
2155 g_free(cache_path);
2157 } else
2158 g_hash_table_insert(relation, msginfo,
2159 GINT_TO_POINTER(0));
2161 statusbar_pop_all();
2163 g_hash_table_destroy(uid_hash);
2164 imap_lep_set_free(seq_list);
2166 g_free(destdir);
2168 IMAP_FOLDER_ITEM(dest)->lastuid = 0;
2169 IMAP_FOLDER_ITEM(dest)->uid_next = 0;
2170 g_slist_free(IMAP_FOLDER_ITEM(dest)->uid_list);
2171 IMAP_FOLDER_ITEM(dest)->uid_list = NULL;
2173 imap_scan_required(folder, dest);
2174 if (ok == MAILIMAP_NO_ERROR)
2175 return last_num;
2176 else
2177 return -1;
2180 static gint imap_copy_msg(Folder *folder, FolderItem *dest, MsgInfo *msginfo)
2182 GSList msglist;
2184 g_return_val_if_fail(msginfo != NULL, -1);
2186 msglist.data = msginfo;
2187 msglist.next = NULL;
2189 return imap_copy_msgs(folder, dest, &msglist, NULL);
2192 static gint imap_copy_msgs(Folder *folder, FolderItem *dest,
2193 MsgInfoList *msglist, GHashTable *relation)
2195 MsgInfo *msginfo;
2196 gint ret;
2198 g_return_val_if_fail(folder != NULL, -1);
2199 g_return_val_if_fail(dest != NULL, -1);
2200 g_return_val_if_fail(msglist != NULL, -1);
2202 msginfo = (MsgInfo *)msglist->data;
2203 g_return_val_if_fail(msginfo->folder != NULL, -1);
2205 ret = imap_do_copy_msgs(folder, dest, msglist, relation, FALSE);
2206 return ret;
2209 static gboolean imap_matcher_type_is_local(gint matchertype)
2211 switch (matchertype) {
2212 case MATCHCRITERIA_FROM:
2213 case MATCHCRITERIA_TO:
2214 case MATCHCRITERIA_CC:
2215 case MATCHCRITERIA_TO_OR_CC:
2216 case MATCHCRITERIA_SUBJECT:
2217 case MATCHCRITERIA_REFERENCES:
2218 case MATCHCRITERIA_MESSAGEID:
2219 case MATCHCRITERIA_INREPLYTO:
2220 case MATCHCRITERIA_AGE_GREATER:
2221 case MATCHCRITERIA_AGE_LOWER:
2222 case MATCHCRITERIA_FORWARDED:
2223 case MATCHCRITERIA_SPAM:
2224 case MATCHCRITERIA_UNREAD:
2225 case MATCHCRITERIA_NEW:
2226 case MATCHCRITERIA_MARKED:
2227 case MATCHCRITERIA_REPLIED:
2228 case MATCHCRITERIA_DELETED:
2229 case MATCHCRITERIA_SIZE_GREATER:
2230 case MATCHCRITERIA_SIZE_SMALLER:
2231 case MATCHCRITERIA_SIZE_EQUAL:
2232 return TRUE;
2234 return FALSE;
2237 static IMAPSearchKey* search_make_key(MatcherProp* match, gboolean* is_all)
2239 if (match->matchtype == MATCHTYPE_MATCHCASE || match->matchtype == MATCHTYPE_MATCH) {
2240 IMAPSearchKey* result = NULL;
2241 gboolean invert = FALSE;
2242 gint matchertype = match->criteria;
2244 if (is_all) {
2245 *is_all = FALSE;
2248 switch (matchertype) {
2249 case MATCHCRITERIA_NOT_NEW: invert = TRUE; matchertype = MATCHCRITERIA_NEW; break;
2250 case MATCHCRITERIA_NOT_MARKED: invert = TRUE; matchertype = MATCHCRITERIA_MARKED; break;
2251 case MATCHCRITERIA_NOT_FORWARDED: invert = TRUE; matchertype = MATCHCRITERIA_FORWARDED; break;
2252 case MATCHCRITERIA_NOT_SPAM: invert = TRUE; matchertype = MATCHCRITERIA_SPAM; break;
2253 case MATCHCRITERIA_NOT_SUBJECT: invert = TRUE; matchertype = MATCHCRITERIA_SUBJECT; break;
2254 case MATCHCRITERIA_NOT_FROM: invert = TRUE; matchertype = MATCHCRITERIA_FROM; break;
2255 case MATCHCRITERIA_NOT_TO: invert = TRUE; matchertype = MATCHCRITERIA_TO; break;
2256 case MATCHCRITERIA_NOT_CC: invert = TRUE; matchertype = MATCHCRITERIA_CC; break;
2257 case MATCHCRITERIA_NOT_REFERENCES: invert = TRUE; matchertype = MATCHCRITERIA_REFERENCES; break;
2258 case MATCHCRITERIA_NOT_HEADER: invert = TRUE; matchertype = MATCHCRITERIA_HEADER; break;
2259 case MATCHCRITERIA_NOT_TAG: invert = TRUE; matchertype = MATCHCRITERIA_TAG; break;
2260 case MATCHCRITERIA_NOT_HEADERS_PART: invert = TRUE; matchertype = MATCHCRITERIA_HEADERS_PART; break;
2261 case MATCHCRITERIA_NOT_HEADERS_CONT: invert = TRUE; matchertype = MATCHCRITERIA_HEADERS_CONT; break;
2262 case MATCHCRITERIA_NOT_MESSAGE: invert = TRUE; matchertype = MATCHCRITERIA_MESSAGE; break;
2263 case MATCHCRITERIA_NOT_BODY_PART: invert = TRUE; matchertype = MATCHCRITERIA_BODY_PART; break;
2264 case MATCHCRITERIA_NOT_TO_AND_NOT_CC: invert = TRUE; matchertype = MATCHCRITERIA_TO_OR_CC; break;
2265 case MATCHCRITERIA_NOT_MESSAGEID: invert = TRUE; matchertype = MATCHCRITERIA_MESSAGEID; break;
2266 case MATCHCRITERIA_NOT_INREPLYTO: invert = TRUE; matchertype = MATCHCRITERIA_INREPLYTO; break;
2270 * this aborts conversion even for predicates understood by the following code.
2271 * while that might seem wasteful, claws local search for information listed below
2272 * has proven faster than IMAP search plus network roundtrips. once this changes,
2273 * consider removing these exceptions.
2275 if (imap_matcher_type_is_local(matchertype))
2276 return NULL;
2278 /* the Message-ID header is also cached */
2279 if (matchertype == MATCHCRITERIA_HEADER && g_strcmp0("Message-ID", match->header) == 0) {
2280 return NULL;
2283 switch (matchertype) {
2284 case MATCHCRITERIA_FORWARDED:
2285 result = imap_search_new(IMAP_SEARCH_CRITERIA_TAG, NULL, RTAG_FORWARDED, 0);
2286 break;
2288 case MATCHCRITERIA_SPAM:
2289 result = imap_search_new(IMAP_SEARCH_CRITERIA_TAG, NULL, RTAG_JUNK, 0);
2290 break;
2292 case MATCHCRITERIA_MESSAGEID:
2293 result = imap_search_new(IMAP_SEARCH_CRITERIA_HEADER, "Message-ID", match->expr, 0);
2294 break;
2296 case MATCHCRITERIA_INREPLYTO:
2297 result = imap_search_new(IMAP_SEARCH_CRITERIA_HEADER, "In-Reply-To", match->expr, 0);
2298 break;
2300 case MATCHCRITERIA_REFERENCES:
2301 result = imap_search_new(IMAP_SEARCH_CRITERIA_HEADER, "References", match->expr, 0);
2302 break;
2304 case MATCHCRITERIA_TO_OR_CC:
2305 result = imap_search_or(
2306 imap_search_new(IMAP_SEARCH_CRITERIA_TO, NULL, match->expr, 0),
2307 imap_search_new(IMAP_SEARCH_CRITERIA_CC, NULL, match->expr, 0)
2309 break;
2311 case MATCHCRITERIA_HEADERS_PART:
2312 case MATCHCRITERIA_HEADERS_CONT:
2313 result = imap_search_and(
2314 imap_search_not(imap_search_new(IMAP_SEARCH_CRITERIA_BODY, NULL, match->expr, 0)),
2315 imap_search_new(IMAP_SEARCH_CRITERIA_MESSAGE, NULL, match->expr, 0)
2317 break;
2319 case MATCHCRITERIA_SIZE_EQUAL:
2320 result = imap_search_and(
2321 imap_search_not(imap_search_new(IMAP_SEARCH_CRITERIA_SIZE_SMALLER, NULL, NULL, match->value)),
2322 imap_search_not(imap_search_new(IMAP_SEARCH_CRITERIA_SIZE_GREATER, NULL, NULL, match->value))
2324 break;
2326 case MATCHCRITERIA_NOT_UNREAD:
2327 result = imap_search_new(IMAP_SEARCH_CRITERIA_READ, NULL, NULL, 0);
2328 break;
2330 case MATCHCRITERIA_UNREAD:
2331 result = imap_search_new(IMAP_SEARCH_CRITERIA_UNREAD, NULL, NULL, 0);
2332 break;
2334 case MATCHCRITERIA_NEW:
2335 result = imap_search_new(IMAP_SEARCH_CRITERIA_NEW, NULL, NULL, 0);
2336 break;
2338 case MATCHCRITERIA_MARKED:
2339 result = imap_search_new(IMAP_SEARCH_CRITERIA_MARKED, NULL, NULL, 0);
2340 break;
2342 case MATCHCRITERIA_DELETED:
2343 result = imap_search_new(IMAP_SEARCH_CRITERIA_DELETED, NULL, NULL, 0);
2344 break;
2346 case MATCHCRITERIA_REPLIED:
2347 result = imap_search_new(IMAP_SEARCH_CRITERIA_REPLIED, NULL, NULL, 0);
2348 break;
2350 case MATCHCRITERIA_TAG:
2352 gchar *tmp = imap_utf8_to_modified_utf7(match->expr, TRUE);
2353 result = imap_search_new(IMAP_SEARCH_CRITERIA_TAG, NULL, tmp, 0);
2354 g_free(tmp);
2356 break;
2358 case MATCHCRITERIA_SUBJECT:
2359 result = imap_search_new(IMAP_SEARCH_CRITERIA_SUBJECT, NULL, match->expr, 0);
2360 break;
2362 case MATCHCRITERIA_FROM:
2363 result = imap_search_new(IMAP_SEARCH_CRITERIA_FROM, NULL, match->expr, 0);
2364 break;
2366 case MATCHCRITERIA_TO:
2367 result = imap_search_new(IMAP_SEARCH_CRITERIA_TO, NULL, match->expr, 0);
2368 break;
2370 case MATCHCRITERIA_CC:
2371 result = imap_search_new(IMAP_SEARCH_CRITERIA_CC, NULL, match->expr, 0);
2372 break;
2374 case MATCHCRITERIA_AGE_GREATER:
2375 result = imap_search_new(IMAP_SEARCH_CRITERIA_AGE_GREATER, NULL, NULL, match->value);
2376 break;
2378 case MATCHCRITERIA_AGE_LOWER:
2379 result = imap_search_new(IMAP_SEARCH_CRITERIA_AGE_LOWER, NULL, NULL, match->value);
2380 break;
2382 case MATCHCRITERIA_BODY_PART:
2383 result = imap_search_new(IMAP_SEARCH_CRITERIA_BODY, NULL, match->expr, 0);
2384 break;
2386 case MATCHCRITERIA_MESSAGE:
2387 result = imap_search_new(IMAP_SEARCH_CRITERIA_MESSAGE, NULL, match->expr, 0);
2388 break;
2390 case MATCHCRITERIA_HEADER:
2391 result = imap_search_new(IMAP_SEARCH_CRITERIA_HEADER, match->header, match->expr, 0);
2392 break;
2394 case MATCHCRITERIA_SIZE_GREATER:
2395 result = imap_search_new(IMAP_SEARCH_CRITERIA_SIZE_GREATER, NULL, NULL, match->value);
2396 break;
2398 case MATCHCRITERIA_SIZE_SMALLER:
2399 result = imap_search_new(IMAP_SEARCH_CRITERIA_SIZE_SMALLER, NULL, NULL, match->value);
2400 break;
2402 default:
2403 result = imap_search_new(IMAP_SEARCH_CRITERIA_ALL, NULL, NULL, 0);
2404 if (is_all) {
2405 *is_all = TRUE;
2407 break;
2410 if (invert) {
2411 result = imap_search_not(result);
2412 if (is_all && *is_all) {
2413 *is_all = FALSE;
2417 return result;
2420 return NULL;
2423 static void imap_change_search_charset(IMAPFolder *folder)
2425 /* If server supports charset in searches, but the last used one failed,
2426 * changed to the next preferred charset. If none are still available,
2427 * disable charset searches.
2428 * Charsets are tried in the following order:
2429 * UTF-8, locale's charset, UTF-7.
2432 if (folder->search_charset_supported) {
2433 if (folder->search_charset && !strcmp(folder->search_charset, conv_get_locale_charset_str_no_utf8()))
2434 folder->search_charset = "UTF-8";
2435 else if (folder->search_charset && !strcmp(folder->search_charset, "UTF-8"))
2436 folder->search_charset = "UTF-7";
2437 else {
2438 folder->search_charset = NULL;
2439 folder->search_charset_supported = FALSE;
2444 static MatcherProp *imap_matcher_prop_set_charset(IMAPFolder *folder,
2445 MatcherProp *utf8_prop,
2446 gchar **charset)
2448 /* If the match is going to be done locally, or the criteria is on
2449 * tag (special-cased to modified-UTF-7), or the expression searched
2450 * is ASCII, don't bother converting.
2452 if (imap_matcher_type_is_local(utf8_prop->criteria)
2453 || utf8_prop->criteria == MATCHCRITERIA_TAG
2454 || utf8_prop->criteria == MATCHCRITERIA_NOT_TAG
2455 || utf8_prop->expr == NULL
2456 || is_ascii_str(utf8_prop->expr))
2457 return matcherprop_new(utf8_prop->criteria,
2458 utf8_prop->header,
2459 utf8_prop->matchtype,
2460 utf8_prop->expr,
2461 utf8_prop->value);
2462 else {
2463 gchar *conv_expr = NULL;
2465 /* If the search is server-side and the server doesn't support
2466 * searching with the charsets we handle, bail out.
2468 if (folder->search_charset_supported == FALSE)
2469 return NULL;
2471 /* Else, convert. */
2472 if (*charset == NULL)
2473 *charset = g_strdup(folder->search_charset);
2475 conv_expr = conv_codeset_strdup(utf8_prop->expr, CS_UTF_8, *charset);
2477 if (conv_expr == NULL)
2478 conv_expr = g_strdup(utf8_prop->expr);
2480 return matcherprop_new(utf8_prop->criteria,
2481 utf8_prop->header,
2482 utf8_prop->matchtype,
2483 conv_expr,
2484 utf8_prop->value);
2488 static gint search_msgs (Folder *folder,
2489 FolderItem *container,
2490 MsgNumberList **msgs,
2491 gboolean *on_server,
2492 MatcherList *predicate,
2493 SearchProgressNotify progress_cb,
2494 gpointer progress_data)
2496 IMAPSearchKey* key = NULL;
2497 GSList* cur;
2498 int result = -1;
2499 clist* uidlist = NULL;
2500 gboolean server_filtering_useless = FALSE;
2501 IMAPSession *session;
2502 gchar *charset_to_use = NULL;
2504 if (on_server == NULL || !*on_server) {
2505 return folder_item_search_msgs_local(folder, container, msgs, on_server,
2506 predicate, progress_cb, progress_data);
2509 for (cur = predicate->matchers; cur != NULL; cur = cur->next) {
2510 IMAPSearchKey* matcherPart = NULL;
2511 MatcherProp* prop = (MatcherProp*) cur->data;
2512 gboolean is_all;
2513 MatcherProp *imap_prop = imap_matcher_prop_set_charset(IMAP_FOLDER(folder), prop, &charset_to_use);
2515 if (imap_prop == NULL) {
2516 /* Couldn't convert matcherprop to IMAP - probably not ascii
2517 * and server doesn't support the charsets we do. */
2518 return -1;
2521 matcherPart = search_make_key(imap_prop, &is_all);
2523 matcherprop_free(imap_prop);
2525 if (on_server) {
2526 *on_server &= matcherPart != NULL && prop->matchtype == MATCHTYPE_MATCHCASE;
2529 if (matcherPart) {
2530 if (key == NULL) {
2531 key = matcherPart;
2532 server_filtering_useless = is_all;
2533 } else if (predicate->bool_and) {
2534 key = imap_search_and(key, matcherPart);
2535 server_filtering_useless &= is_all;
2536 } else {
2537 key = imap_search_or(key, matcherPart);
2538 server_filtering_useless |= is_all;
2543 if (server_filtering_useless) {
2544 imap_search_free(key);
2545 key = NULL;
2548 if (key == NULL && progress_cb != NULL) {
2549 GSList* cur;
2550 GSList* list;
2551 int count = 0;
2553 progress_cb(progress_data, TRUE, 0, 0, container->total_msgs);
2554 progress_cb(progress_data, TRUE, container->total_msgs, 0, container->total_msgs);
2556 list = folder_item_get_msg_list(container);
2557 for (cur = list; cur != NULL; cur = cur->next) {
2558 *msgs = g_slist_prepend(*msgs, GUINT_TO_POINTER(((MsgInfo*) cur->data)->msgnum));
2559 count++;
2561 procmsg_msg_list_free(list);
2563 *msgs = g_slist_reverse(*msgs);
2565 return count;
2568 session = imap_session_get(folder);
2569 if (!session) {
2570 return -1;
2572 result = imap_select(session, IMAP_FOLDER(folder), FOLDER_ITEM(container),
2573 NULL, NULL, NULL, NULL, NULL, TRUE);
2574 if (result != MAILIMAP_NO_ERROR)
2575 return -1;
2577 if (progress_cb)
2578 progress_cb(progress_data, TRUE, 0, 0, container->total_msgs);
2579 result = imap_threaded_search(folder, IMAP_SEARCH_TYPE_KEYED, key, charset_to_use, NULL, &uidlist);
2580 if (progress_cb)
2581 progress_cb(progress_data, TRUE, container->total_msgs, 0, container->total_msgs);
2583 if (result == MAILIMAP_ERROR_PROTOCOL) {
2584 debug_print("Server side search unavailable, using local search\n");
2585 imap_handle_error(SESSION(session), NULL, result);
2586 result = folder_item_search_msgs_local(folder, container, msgs, NULL,
2587 predicate, progress_cb, progress_data);
2588 if (result < 0) {
2589 debug_print("search_msgs - got protocol error, aborting\n");
2590 alertpanel_error_log(_("Search failed due to server error."));
2591 return -1;
2594 return result;
2597 if (result == MAILIMAP_NO_ERROR) {
2598 gint result = 0;
2600 *msgs = imap_uid_list_from_lep(uidlist, &result);
2602 mailimap_search_result_free(uidlist);
2604 if (charset_to_use != NULL)
2605 g_free(charset_to_use);
2607 return result;
2608 } else if (charset_to_use != NULL) {
2609 /* If search failed and was on an 8-bit string, try the next
2610 * available charset to search if there still are some.
2612 g_free(charset_to_use);
2614 imap_change_search_charset(IMAP_FOLDER(folder));
2615 if (IMAP_FOLDER(folder)->search_charset_supported)
2616 return search_msgs(folder, container, msgs, on_server, predicate,
2617 progress_cb, progress_data);
2618 else {
2619 imap_handle_error(SESSION(session), NULL, result);
2620 return -1;
2622 } else {
2623 imap_handle_error(SESSION(session), NULL, result);
2624 return -1;
2629 static gint imap_do_remove_msgs(Folder *folder, FolderItem *dest,
2630 MsgInfoList *msglist, GHashTable *relation)
2632 gchar *destdir, *dir;
2633 GSList *numlist = NULL, *cur;
2634 MsgInfo *msginfo;
2635 IMAPSession *session;
2636 gint ok = MAILIMAP_NO_ERROR;
2638 g_return_val_if_fail(folder != NULL, -1);
2639 g_return_val_if_fail(dest != NULL, -1);
2640 g_return_val_if_fail(msglist != NULL, -1);
2642 debug_print("getting session...\n");
2643 session = imap_session_get(folder);
2644 if (!session) {
2645 return -1;
2648 lock_session(session); /* unlocked later in the function */
2650 msginfo = (MsgInfo *)msglist->data;
2652 ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder,
2653 NULL, NULL, NULL, NULL, NULL, FALSE);
2654 if (ok != MAILIMAP_NO_ERROR) {
2655 return ok;
2658 destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path, &ok);
2659 if (is_fatal(ok)) {
2660 g_free(destdir);
2661 return ok;
2663 for (cur = msglist; cur; cur = cur->next) {
2664 msginfo = (MsgInfo *)cur->data;
2665 if (!MSG_IS_DELETED(msginfo->flags))
2666 numlist = g_slist_prepend(numlist, GINT_TO_POINTER(msginfo->msgnum));
2668 numlist = g_slist_reverse(numlist);
2670 if (numlist != NULL) {
2671 ok = imap_set_message_flags
2672 (session, IMAP_FOLDER_ITEM(msginfo->folder), numlist, IMAP_FLAG_DELETED, NULL, TRUE);
2673 if (ok != MAILIMAP_NO_ERROR) {
2674 log_warning(LOG_PROTOCOL, _("can't set deleted flags\n"));
2675 g_free(destdir);
2676 return ok;
2678 } /* else we just need to expunge */
2679 ok = imap_cmd_expunge(session);
2680 if (ok != MAILIMAP_NO_ERROR) {
2681 log_warning(LOG_PROTOCOL, _("can't expunge\n"));
2682 g_free(destdir);
2683 return ok;
2686 session->folder_content_changed = TRUE;
2687 unlock_session(session);
2689 dir = folder_item_get_path(msginfo->folder);
2690 if (is_dir_exist(dir)) {
2691 for (cur = msglist; cur; cur = cur->next) {
2692 msginfo = (MsgInfo *)cur->data;
2693 remove_numbered_files(dir, msginfo->msgnum, msginfo->msgnum);
2696 g_free(dir);
2698 g_slist_free(numlist);
2700 imap_scan_required(folder, dest);
2702 g_free(destdir);
2704 return 0;
2707 static gint imap_remove_msgs(Folder *folder, FolderItem *dest,
2708 MsgInfoList *msglist, GHashTable *relation)
2710 MsgInfo *msginfo;
2712 g_return_val_if_fail(folder != NULL, -1);
2713 g_return_val_if_fail(dest != NULL, -1);
2714 if (msglist == NULL)
2715 return 0;
2717 msginfo = (MsgInfo *)msglist->data;
2718 g_return_val_if_fail(msginfo->folder != NULL, -1);
2720 return imap_do_remove_msgs(folder, dest, msglist, relation);
2723 static gint imap_remove_all_msg(Folder *folder, FolderItem *item)
2725 GSList *list = folder_item_get_msg_list(item);
2726 gint res = imap_remove_msgs(folder, item, list, NULL);
2727 procmsg_msg_list_free(list);
2728 return res;
2731 static gboolean imap_is_msg_changed(Folder *folder, FolderItem *item,
2732 MsgInfo *msginfo)
2734 /* TODO: properly implement this method */
2735 return FALSE;
2738 static gint imap_close(Folder *folder, FolderItem *item)
2740 return 0;
2743 static gint imap_scan_tree_real(Folder *folder, gboolean subs_only)
2745 FolderItem *item = NULL;
2746 IMAPSession *session;
2747 gchar *root_folder = NULL;
2749 g_return_val_if_fail(folder != NULL, -1);
2750 g_return_val_if_fail(folder->account != NULL, -1);
2752 debug_print("getting session...\n");
2753 session = imap_session_get(folder);
2754 if (!session) {
2755 if (!folder->node) {
2756 folder_tree_destroy(folder);
2757 item = folder_item_new(folder, folder->name, NULL);
2758 item->folder = folder;
2759 folder->node = item->node = g_node_new(item);
2761 return -1;
2764 if (folder->account->imap_dir && *folder->account->imap_dir) {
2765 gchar *real_path;
2766 int r = MAILIMAP_NO_ERROR;
2767 clist * lep_list;
2769 Xstrdup_a(root_folder, folder->account->imap_dir, {return -1;});
2770 extract_quote(root_folder, '"');
2771 subst_char(root_folder,
2772 imap_get_path_separator(session, IMAP_FOLDER(folder),
2773 root_folder, &r),
2774 '/');
2775 if (is_fatal(r))
2776 return -1;
2777 strtailchomp(root_folder, '/');
2778 real_path = imap_get_real_path
2779 (session, IMAP_FOLDER(folder), root_folder, &r);
2780 if (is_fatal(r)) {
2781 g_free(real_path);
2782 return -1;
2784 debug_print("IMAP root directory: %s\n", real_path);
2786 /* check if root directory exist */
2788 r = imap_threaded_list(session->folder, "", real_path,
2789 &lep_list);
2791 if (r != MAILIMAP_NO_ERROR)
2792 imap_handle_error(SESSION(session), NULL, r);
2794 if ((r != MAILIMAP_NO_ERROR) || (clist_count(lep_list) == 0)) {
2795 if (!folder->node) {
2796 item = folder_item_new(folder, folder->name, NULL);
2797 item->folder = folder;
2798 folder->node = item->node = g_node_new(item);
2800 return -1;
2802 mailimap_list_result_free(lep_list);
2804 g_free(real_path);
2807 if (folder->node)
2808 item = FOLDER_ITEM(folder->node->data);
2810 if (item && !item->path && root_folder) {
2811 item->path = g_strdup(root_folder);
2814 if (!item || ((item->path || root_folder) &&
2815 g_strcmp0(item->path, root_folder) != 0)) {
2816 folder_tree_destroy(folder);
2817 item = folder_item_new(folder, folder->name, root_folder);
2818 item->folder = folder;
2819 folder->node = item->node = g_node_new(item);
2822 imap_scan_tree_recursive(session, FOLDER_ITEM(folder->node->data), subs_only);
2823 imap_create_missing_folders(folder);
2825 return 0;
2828 static gint imap_scan_tree(Folder *folder)
2830 gboolean subs_only = FALSE;
2831 if (folder->account) {
2832 debug_print(" scanning only subs %d\n", folder->account->imap_subsonly);
2833 subs_only = folder->account->imap_subsonly;
2835 return imap_scan_tree_real(folder, subs_only);
2838 static gint imap_scan_tree_recursive(IMAPSession *session, FolderItem *item, gboolean subs_only)
2840 /* reset recursion depth counter */
2841 session->scan_tree_recurs_depth = 0;
2843 return imap_scan_tree_recursive_dive(session, item, subs_only);
2846 static gint imap_scan_tree_recursive_dive(IMAPSession *session, FolderItem *item, gboolean subs_only)
2848 Folder *folder;
2849 IMAPFolder *imapfolder;
2850 FolderItem *new_item;
2851 GSList *item_list, *cur;
2852 GNode *node;
2853 gchar *real_path;
2854 gchar *wildcard_path;
2855 gchar separator;
2856 gchar wildcard[3];
2857 clist * lep_list;
2858 int r = MAILIMAP_NO_ERROR;
2860 g_return_val_if_fail(item != NULL, -1);
2861 g_return_val_if_fail(item->folder != NULL, -1);
2862 g_return_val_if_fail(item->no_sub == FALSE, -1);
2864 /* recursion depth limiter */
2865 if(session->scan_tree_recurs_depth >= prefs_common.imap_scan_tree_recurs_limit) {
2866 g_warning("IMAP scan tree recursion limit reached (%d, folder '%s')",
2867 prefs_common.imap_scan_tree_recurs_limit, item->folder->name);
2868 return -1;
2870 /* entering recursion func: increase depth counter */
2871 session->scan_tree_recurs_depth++;
2873 folder = item->folder;
2874 imapfolder = IMAP_FOLDER(folder);
2876 separator = imap_get_path_separator(session, imapfolder, item->path, &r);
2877 if (is_fatal(r))
2878 return r;
2880 if (folder->ui_func)
2881 folder->ui_func(folder, item, folder->ui_func_data);
2883 if (item->path) {
2884 wildcard[0] = separator;
2885 wildcard[1] = '%';
2886 wildcard[2] = '\0';
2887 real_path = imap_get_real_path(session, imapfolder, item->path, &r);
2888 if (is_fatal(r)) {
2889 g_free(real_path);
2890 return r;
2892 } else {
2893 wildcard[0] = '%';
2894 wildcard[1] = '\0';
2895 real_path = g_strdup("");
2898 Xstrcat_a(wildcard_path, real_path, wildcard,
2899 {g_free(real_path); return MAILIMAP_ERROR_BAD_STATE;});
2900 lep_list = NULL;
2902 if (subs_only)
2903 r = imap_threaded_lsub(folder, "", wildcard_path, &lep_list);
2904 else
2905 r = imap_threaded_list(folder, "", wildcard_path, &lep_list);
2907 if (r != MAILIMAP_NO_ERROR) {
2908 imap_handle_error(SESSION(session), NULL, r);
2909 item_list = NULL;
2910 g_free(real_path);
2911 return r;
2913 else {
2914 item_list = imap_list_from_lep(imapfolder,
2915 lep_list, real_path, FALSE);
2916 mailimap_list_result_free(lep_list);
2919 g_free(real_path);
2921 node = item->node->children;
2922 while (node != NULL) {
2923 FolderItem *old_item = FOLDER_ITEM(node->data);
2924 GNode *next = node->next;
2926 new_item = NULL;
2927 for (cur = item_list; cur != NULL; cur = cur->next) {
2928 FolderItem *cur_item = FOLDER_ITEM(cur->data);
2929 if (!g_strcmp0(old_item->path, cur_item->path)) {
2930 new_item = cur_item;
2931 break;
2934 if (!new_item) {
2935 if (old_item && old_item->path && !strcasecmp(old_item->path, "INBOX")) {
2936 debug_print("not removing INBOX\n");
2937 } else {
2938 debug_print("folder '%s' not found. removing...\n",
2939 old_item->path);
2940 folder_item_remove(old_item);
2942 } else {
2943 old_item->no_sub = new_item->no_sub;
2944 old_item->no_select = new_item->no_select;
2945 if (old_item->no_sub == TRUE && node->children) {
2946 debug_print("folder '%s' doesn't have "
2947 "subfolders. removing...\n",
2948 old_item->path);
2949 folder_item_remove_children(old_item);
2953 node = next;
2956 for (cur = item_list; cur != NULL; cur = cur->next) {
2957 FolderItem *cur_item = FOLDER_ITEM(cur->data);
2958 new_item = NULL;
2960 for (node = item->node->children; node != NULL;
2961 node = node->next) {
2962 if (!g_strcmp0(FOLDER_ITEM(node->data)->path,
2963 cur_item->path)) {
2964 new_item = FOLDER_ITEM(node->data);
2965 folder_item_destroy(cur_item);
2966 cur_item = NULL;
2967 break;
2970 if (!new_item) {
2971 new_item = cur_item;
2972 debug_print("new folder '%s' found.\n", new_item->path);
2973 folder_item_append(item, new_item);
2976 if (!strcasecmp(new_item->path, "INBOX")) {
2977 new_item->stype = F_INBOX;
2978 folder->inbox = new_item;
2979 } else if (!folder_item_parent(item) || item->stype == F_INBOX) {
2980 gchar *base;
2982 base = g_path_get_basename(new_item->path);
2984 if (!folder->outbox && !g_ascii_strcasecmp(base, "Sent")) {
2985 new_item->stype = F_OUTBOX;
2986 folder->outbox = new_item;
2987 } else if (!folder->draft && (!g_ascii_strcasecmp(base, "Drafts") || !g_ascii_strcasecmp(base, "Draft"))) {
2988 new_item->stype = F_DRAFT;
2989 folder->draft = new_item;
2990 } else if (!folder->queue && !g_ascii_strcasecmp(base, "Queue")) {
2991 new_item->stype = F_QUEUE;
2992 folder->queue = new_item;
2993 } else if (!folder->trash && !g_ascii_strcasecmp(base, "Trash")) {
2994 new_item->stype = F_TRASH;
2995 folder->trash = new_item;
2997 g_free(base);
3000 if (new_item->no_sub == FALSE) {
3001 imap_scan_tree_recursive_dive(session, new_item, subs_only);
3003 /* entering recursion func: increase depth counter */
3004 session->scan_tree_recurs_depth--;
3005 if (session->scan_tree_recurs_depth < 0)
3006 g_error("IMAP scan tree recursion underflow (%d)",
3007 session->scan_tree_recurs_depth);
3011 g_slist_free(item_list);
3013 return MAILIMAP_NO_ERROR;
3016 GList *imap_scan_subtree(Folder *folder, FolderItem *item, gboolean unsubs_only, gboolean recursive)
3018 IMAPSession *session = imap_session_get(folder);
3019 gchar *real_path;
3020 gchar *wildcard_path;
3021 gchar separator;
3022 gchar wildcard[3];
3023 clist * lep_list;
3024 GSList *item_list = NULL, *cur;
3025 GList *child_list = NULL, *tmplist = NULL;
3026 GSList *sub_list = NULL;
3027 int r = MAILIMAP_NO_ERROR;
3029 if (!session)
3030 return NULL;
3032 separator = imap_get_path_separator(session, IMAP_FOLDER(folder), item->path, &r);
3033 if (is_fatal(r))
3034 return NULL;
3036 if (item->path) {
3037 wildcard[0] = separator;
3038 wildcard[1] = '%';
3039 wildcard[2] = '\0';
3040 real_path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path, &r);
3041 if (is_fatal(r)) {
3042 g_free(real_path);
3043 return NULL;
3045 } else {
3046 wildcard[0] = '%';
3047 wildcard[1] = '\0';
3048 real_path = g_strdup("");
3051 Xstrcat_a(wildcard_path, real_path, wildcard,
3052 {g_free(real_path); return NULL;});
3053 lep_list = NULL;
3055 if (unsubs_only)
3056 statusbar_print_all(_("Looking for unsubscribed folders in %s..."),
3057 item->path?item->path:item->name);
3058 else
3059 statusbar_print_all(_("Looking for subfolders of %s..."),
3060 item->path?item->path:item->name);
3062 r = imap_threaded_list(folder, "", wildcard_path, &lep_list);
3063 if (r) {
3064 g_free(real_path);
3065 statusbar_pop_all();
3066 return NULL;
3068 item_list = imap_list_from_lep(IMAP_FOLDER(folder),
3069 lep_list, real_path, FALSE);
3070 mailimap_list_result_free(lep_list);
3072 for (cur = item_list; cur != NULL; cur = cur->next) {
3073 FolderItem *cur_item = FOLDER_ITEM(cur->data);
3074 if (recursive) {
3075 tmplist = imap_scan_subtree(folder, cur_item,
3076 unsubs_only, recursive);
3077 if (tmplist)
3078 child_list = g_list_concat(child_list, tmplist);
3080 child_list = g_list_prepend(child_list,
3081 imap_get_real_path(session,
3082 IMAP_FOLDER(folder), cur_item->path, &r));
3083 if (is_fatal(r)) {
3084 g_free(real_path);
3085 statusbar_pop_all();
3086 return NULL;
3088 folder_item_destroy(cur_item);
3090 child_list = g_list_reverse(child_list);
3091 g_slist_free(item_list);
3093 if (unsubs_only) {
3094 r = imap_threaded_lsub(folder, "", wildcard_path, &lep_list);
3095 if (r) {
3096 g_free(real_path);
3097 statusbar_pop_all();
3098 return NULL;
3100 sub_list = imap_list_from_lep(IMAP_FOLDER(folder),
3101 lep_list, real_path, FALSE);
3102 mailimap_list_result_free(lep_list);
3104 for (cur = sub_list; cur != NULL; cur = cur->next) {
3105 FolderItem *cur_item = FOLDER_ITEM(cur->data);
3106 GList *oldlitem = NULL;
3107 gchar *tmp = imap_get_real_path(session,
3108 IMAP_FOLDER(folder), cur_item->path, &r);
3109 if (r) {
3110 g_free(real_path);
3111 statusbar_pop_all();
3112 g_free(tmp);
3113 return NULL;
3115 folder_item_destroy(cur_item);
3116 oldlitem = g_list_find_custom(
3117 child_list, tmp, (GCompareFunc)g_strcmp0);
3118 if (oldlitem) {
3119 child_list = g_list_remove_link(child_list, oldlitem);
3120 g_free(oldlitem->data);
3121 g_list_free(oldlitem);
3123 g_free(tmp);
3127 g_free(real_path);
3128 statusbar_pop_all();
3130 return child_list;
3133 static gint imap_create_tree(Folder *folder)
3135 g_return_val_if_fail(folder != NULL, -1);
3136 g_return_val_if_fail(folder->node != NULL, -1);
3137 g_return_val_if_fail(folder->node->data != NULL, -1);
3138 g_return_val_if_fail(folder->account != NULL, -1);
3140 imap_scan_tree(folder);
3141 imap_create_missing_folders(folder);
3143 return 0;
3146 static void imap_create_missing_folders(Folder *folder)
3148 g_return_if_fail(folder != NULL);
3150 if (!folder->inbox)
3151 folder->inbox = imap_create_special_folder
3152 (folder, F_INBOX, "INBOX");
3153 if (!folder->trash)
3154 folder->trash = imap_create_special_folder
3155 (folder, F_TRASH, "Trash");
3156 if (!folder->queue)
3157 folder->queue = imap_create_special_folder
3158 (folder, F_QUEUE, "Queue");
3159 if (!folder->outbox)
3160 folder->outbox = imap_create_special_folder
3161 (folder, F_OUTBOX, "Sent");
3162 if (!folder->draft)
3163 folder->draft = imap_create_special_folder
3164 (folder, F_DRAFT, "Drafts");
3167 static FolderItem *imap_create_special_folder(Folder *folder,
3168 SpecialFolderItemType stype,
3169 const gchar *name)
3171 FolderItem *item;
3172 FolderItem *new_item;
3174 g_return_val_if_fail(folder != NULL, NULL);
3175 g_return_val_if_fail(folder->node != NULL, NULL);
3176 g_return_val_if_fail(folder->node->data != NULL, NULL);
3177 g_return_val_if_fail(folder->account != NULL, NULL);
3178 g_return_val_if_fail(name != NULL, NULL);
3180 item = FOLDER_ITEM(folder->node->data);
3181 new_item = imap_create_folder(folder, item, name);
3183 if (!new_item) {
3184 g_warning("can't create '%s'", name);
3185 if (!folder->inbox) return NULL;
3187 new_item = imap_create_folder(folder, folder->inbox, name);
3188 if (!new_item)
3189 g_warning("can't create '%s' under INBOX", name);
3190 else
3191 new_item->stype = stype;
3192 } else
3193 new_item->stype = stype;
3195 return new_item;
3198 #ifdef G_OS_WIN32
3199 static gchar *imap_encode_unsafe_chars(const gchar *str)
3201 gchar *ret = NULL, *o_ret;
3202 gchar *i;
3203 if (!str)
3204 return NULL;
3205 ret = g_malloc(3*strlen(str)+1);
3206 o_ret = ret;
3207 for (i = (gchar *)str; *i; i++) {
3208 switch(*i) {
3209 case ':':
3210 case '|':
3211 case '<':
3212 case '>':
3213 case '*':
3214 case '?':
3215 case '#':
3216 *ret++ = '%';
3217 *ret++ = '0'+(*i/10);
3218 *ret++ = '0'+(*i%10);
3219 break;
3220 default:
3221 *ret++ = *i;
3224 *ret++ = '\0';
3225 return o_ret;
3227 #endif
3228 static gchar *imap_item_get_path(Folder *folder, FolderItem *item)
3230 gchar *folder_path, *path;
3231 gchar *item_path = NULL;
3233 g_return_val_if_fail(folder != NULL, NULL);
3234 g_return_val_if_fail(folder->account != NULL, NULL);
3235 g_return_val_if_fail(item != NULL, NULL);
3236 folder_path = prefs_account_cache_dir(folder->account, FALSE);
3238 g_return_val_if_fail(folder_path != NULL, NULL);
3240 #ifdef G_OS_UNIX
3241 item_path = g_strdup(item->path);
3242 #else
3243 item_path = imap_encode_unsafe_chars(item->path);
3244 #endif
3246 if (g_path_is_absolute(folder_path)) {
3247 if (item_path)
3248 path = g_strconcat(folder_path, G_DIR_SEPARATOR_S,
3249 item_path, NULL);
3250 else
3251 path = g_strdup(folder_path);
3252 } else {
3253 if (item_path)
3254 path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
3255 folder_path, G_DIR_SEPARATOR_S,
3256 item_path, NULL);
3257 else
3258 path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
3259 folder_path, NULL);
3261 g_free(folder_path);
3262 g_free(item_path);
3263 #ifdef G_OS_WIN32
3264 while (strchr(path, '/'))
3265 *strchr(path, '/') = '\\';
3266 #endif
3268 return path;
3271 static FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
3272 const gchar *name)
3274 gchar *dirpath, *imap_path;
3275 IMAPSession *session;
3276 FolderItem *new_item;
3277 gchar separator;
3278 gchar *new_name;
3279 const gchar *p;
3280 gint ok = MAILIMAP_NO_ERROR;
3281 gboolean no_select = FALSE, no_sub = FALSE;
3282 gboolean exist = FALSE;
3284 g_return_val_if_fail(folder != NULL, NULL);
3285 g_return_val_if_fail(folder->account != NULL, NULL);
3286 g_return_val_if_fail(parent != NULL, NULL);
3287 g_return_val_if_fail(name != NULL, NULL);
3289 if (to_number(name) > 0) {
3290 gchar *cached_msg = imap_get_cached_filename(parent, to_number(name));
3291 if (is_file_exist(cached_msg)) {
3292 if (claws_unlink(cached_msg) != 0) {
3293 g_free(cached_msg);
3294 return NULL;
3297 g_free(cached_msg);
3300 debug_print("getting session...\n");
3301 session = imap_session_get(folder);
3302 if (!session) {
3303 return NULL;
3306 if (!folder_item_parent(parent) && strcasecmp(name, "INBOX") == 0) {
3307 dirpath = g_strdup(name);
3308 }else if (parent->path)
3309 dirpath = g_strconcat(parent->path, "/", name, NULL);
3310 else if ((p = strchr(name, '/')) != NULL && *(p + 1) != '\0')
3311 dirpath = g_strdup(name);
3312 else if (folder->account->imap_dir && *folder->account->imap_dir) {
3313 gchar *imap_dir;
3315 Xstrdup_a(imap_dir, folder->account->imap_dir, {return NULL;});
3316 strtailchomp(imap_dir, '/');
3317 dirpath = g_strconcat(imap_dir, "/", name, NULL);
3318 } else
3319 dirpath = g_strdup(name);
3323 /* keep trailing directory separator to create a folder that contains
3324 sub folder */
3325 imap_path = imap_utf8_to_modified_utf7(dirpath, FALSE);
3327 strtailchomp(dirpath, '/');
3328 Xstrdup_a(new_name, name, {
3329 g_free(dirpath);
3330 g_free(imap_path);
3331 return NULL;});
3333 separator = imap_get_path_separator(session, IMAP_FOLDER(folder), imap_path, &ok);
3334 if (is_fatal(ok)) {
3335 g_free(dirpath);
3336 g_free(imap_path);
3337 return NULL;
3339 imap_path_separator_subst(imap_path, separator);
3340 /* remove trailing / for display */
3341 strtailchomp(new_name, '/');
3343 if (strcasecmp(dirpath, "INBOX") != 0) {
3344 int r;
3345 clist * lep_list;
3347 r = imap_threaded_list(folder, "", imap_path, &lep_list);
3348 if (r != MAILIMAP_NO_ERROR) {
3349 imap_handle_error(SESSION(session), NULL, r);
3350 log_warning(LOG_PROTOCOL, _("can't create mailbox: LIST failed\n"));
3351 g_free(imap_path);
3352 g_free(dirpath);
3353 return NULL;
3356 if (clist_count(lep_list) > 0)
3357 exist = TRUE;
3358 mailimap_list_result_free(lep_list);
3359 lep_list = NULL;
3360 if (!exist) {
3361 ok = imap_cmd_create(session, imap_path);
3362 if (ok != MAILIMAP_NO_ERROR) {
3363 log_warning(LOG_PROTOCOL, _("can't create mailbox\n"));
3364 g_free(imap_path);
3365 g_free(dirpath);
3366 return NULL;
3368 r = imap_threaded_list(folder, "", imap_path, &lep_list);
3369 if (r == MAILIMAP_NO_ERROR) {
3370 GSList *item_list = imap_list_from_lep(IMAP_FOLDER(folder),
3371 lep_list, dirpath, TRUE);
3372 if (item_list) {
3373 FolderItem *cur_item = FOLDER_ITEM(item_list->data);
3374 no_select = cur_item->no_select;
3375 no_sub = cur_item->no_sub;
3376 g_slist_free(item_list);
3378 mailimap_list_result_free(lep_list);
3379 } else {
3380 imap_handle_error(SESSION(session), NULL, r);
3383 imap_threaded_subscribe(folder, imap_path, TRUE);
3384 } else {
3385 clist *lep_list;
3386 int r;
3387 /* just get flags */
3388 r = imap_threaded_list(folder, "", "INBOX", &lep_list);
3389 if (r == MAILIMAP_NO_ERROR) {
3390 GSList *item_list = imap_list_from_lep(IMAP_FOLDER(folder),
3391 lep_list, dirpath, TRUE);
3392 if (item_list) {
3393 FolderItem *cur_item = FOLDER_ITEM(item_list->data);
3394 no_select = cur_item->no_select;
3395 no_sub = cur_item->no_sub;
3396 g_slist_free(item_list);
3398 mailimap_list_result_free(lep_list);
3399 } else {
3400 imap_handle_error(SESSION(session), NULL, r);
3404 new_item = folder_item_new(folder, new_name, dirpath);
3405 new_item->no_select = no_select;
3406 new_item->no_sub = no_sub;
3407 folder_item_append(parent, new_item);
3408 g_free(imap_path);
3409 g_free(dirpath);
3411 dirpath = folder_item_get_path(new_item);
3412 if (!is_dir_exist(dirpath))
3413 make_dir_hier(dirpath);
3414 g_free(dirpath);
3416 if (exist) {
3417 /* folder existed, scan it */
3418 imap_scan_required(folder, new_item);
3419 folder_item_scan_full(new_item, FALSE);
3422 return new_item;
3425 static gint imap_rename_folder(Folder *folder, FolderItem *item,
3426 const gchar *name)
3428 gchar *dirpath;
3429 gchar *newpath;
3430 gchar *real_oldpath;
3431 gchar *real_newpath;
3432 gchar *paths[2];
3433 gchar *old_cache_dir;
3434 gchar *new_cache_dir;
3435 IMAPSession *session;
3436 gchar separator;
3437 gint ok = MAILIMAP_NO_ERROR;
3438 gint exists, recent, unseen;
3439 guint32 uid_validity;
3441 g_return_val_if_fail(folder != NULL, -1);
3442 g_return_val_if_fail(item != NULL, -1);
3443 g_return_val_if_fail(item->path != NULL, -1);
3444 g_return_val_if_fail(name != NULL, -1);
3446 debug_print("getting session...\n");
3447 session = imap_session_get(folder);
3448 if (!session) {
3449 return -1;
3452 if (strchr(name, imap_get_path_separator(session, IMAP_FOLDER(folder), item->path, &ok)) != NULL ||
3453 is_fatal(ok)) {
3454 g_warning("new folder name must not contain the namespace path separator");
3455 return -1;
3458 real_oldpath = imap_get_real_path(session, IMAP_FOLDER(folder), item->path, &ok);
3459 if (is_fatal(ok)) {
3460 g_free(real_oldpath);
3461 return -1;
3464 g_free(session->mbox);
3465 session->mbox = NULL;
3466 session->exists = 0;
3467 session->recent = 0;
3468 session->expunge = 0;
3469 ok = imap_cmd_examine(session, "INBOX",
3470 &exists, &recent, &unseen, &uid_validity, FALSE);
3471 if (ok != MAILIMAP_NO_ERROR) {
3472 g_free(real_oldpath);
3473 return -1;
3476 separator = imap_get_path_separator(session, IMAP_FOLDER(folder), item->path, &ok);
3477 if (is_fatal(ok)) {
3478 g_free(real_oldpath);
3479 return -1;
3481 if (strchr(item->path, '/')) {
3482 dirpath = g_path_get_dirname(item->path);
3483 newpath = g_strconcat(dirpath, "/", name, NULL);
3484 g_free(dirpath);
3485 } else
3486 newpath = g_strdup(name);
3488 real_newpath = imap_utf8_to_modified_utf7(newpath, FALSE);
3489 imap_path_separator_subst(real_newpath, separator);
3491 ok = imap_cmd_rename(session, real_oldpath, real_newpath);
3492 if (ok != MAILIMAP_NO_ERROR) {
3493 log_warning(LOG_PROTOCOL, _("can't rename mailbox: %s to %s\n"),
3494 real_oldpath, real_newpath);
3495 g_free(real_oldpath);
3496 g_free(newpath);
3497 g_free(real_newpath);
3498 return -1;
3500 g_free(item->name);
3501 item->name = g_strdup(name);
3503 old_cache_dir = folder_item_get_path(item);
3505 paths[0] = g_strdup(item->path);
3506 paths[1] = newpath;
3507 g_node_traverse(item->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1,
3508 imap_rename_folder_func, paths);
3510 if (is_dir_exist(old_cache_dir)) {
3511 new_cache_dir = folder_item_get_path(item);
3512 if (g_rename(old_cache_dir, new_cache_dir) < 0) {
3513 FILE_OP_ERROR(old_cache_dir, "rename");
3515 g_free(new_cache_dir);
3518 g_free(old_cache_dir);
3519 g_free(paths[0]);
3520 g_free(newpath);
3521 g_free(real_oldpath);
3522 g_free(real_newpath);
3523 return 0;
3526 gint imap_subscribe(Folder *folder, FolderItem *item, gchar *rpath, gboolean sub)
3528 gchar *path;
3529 gint r = MAILIMAP_NO_ERROR;
3530 IMAPSession *session;
3531 debug_print("getting session...\n");
3533 session = imap_session_get(folder);
3534 if (!session) {
3535 return -1;
3537 if (item && item->path) {
3538 path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path, &r);
3539 if (!path)
3540 return -1;
3541 if (is_fatal(r)) {
3542 g_free(path);
3543 return -1;
3545 if (!strcasecmp(path, "INBOX") && sub == FALSE) {
3546 g_free(path);
3547 return -1;
3549 debug_print("%ssubscribing %s\n", sub?"":"un", path);
3550 r = imap_threaded_subscribe(folder, path, sub);
3551 g_free(path);
3552 } else if (rpath) {
3553 r = imap_threaded_subscribe(folder, rpath, sub);
3554 } else
3555 return -1;
3556 return r;
3559 static gint imap_remove_folder_real(Folder *folder, FolderItem *item)
3561 gint ok = MAILIMAP_NO_ERROR;
3562 IMAPSession *session;
3563 gchar *path;
3564 gchar *cache_dir;
3565 gboolean selected_folder;
3567 g_return_val_if_fail(folder != NULL, -1);
3568 g_return_val_if_fail(item != NULL, -1);
3569 g_return_val_if_fail(item->path != NULL, -1);
3571 debug_print("getting session...\n");
3572 session = imap_session_get(folder);
3573 if (!session) {
3574 return -1;
3576 path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path, &ok);
3577 if (is_fatal(ok)) {
3578 g_free(path);
3579 return -1;
3581 imap_threaded_subscribe(folder, path, FALSE);
3583 selected_folder = (session->mbox != NULL) &&
3584 (!strcmp(session->mbox, item->path));
3585 if (selected_folder) {
3586 ok = imap_cmd_close(session);
3587 if (ok != MAILIMAP_NO_ERROR) {
3588 debug_print("close err %d\n", ok);
3589 return ok;
3592 ok = imap_cmd_delete(session, path);
3593 if (ok != MAILIMAP_NO_ERROR && !is_fatal(ok)) {
3594 gchar *tmp = NULL;
3596 ok = MAILIMAP_NO_ERROR;
3597 tmp = g_strdup_printf("%s%c", path,
3598 imap_get_path_separator(session, IMAP_FOLDER(folder), path, &ok));
3599 g_free(path);
3600 path = tmp;
3601 if (!is_fatal(ok))
3602 ok = imap_cmd_delete(session, path);
3605 if (ok != MAILIMAP_NO_ERROR) {
3606 log_warning(LOG_PROTOCOL, _("can't delete mailbox\n"));
3607 g_free(path);
3608 return -1;
3611 g_free(path);
3612 cache_dir = folder_item_get_path(item);
3613 if (is_dir_exist(cache_dir) && remove_dir_recursive(cache_dir) < 0)
3614 g_warning("can't remove directory '%s'", cache_dir);
3615 g_free(cache_dir);
3616 folder_item_remove(item);
3617 return 0;
3620 static gint imap_remove_folder(Folder *folder, FolderItem *item)
3622 GNode *node, *next;
3624 g_return_val_if_fail(item != NULL, -1);
3625 g_return_val_if_fail(item->folder != NULL, -1);
3626 g_return_val_if_fail(item->node != NULL, -1);
3628 node = item->node->children;
3629 while (node != NULL) {
3630 next = node->next;
3631 if (imap_remove_folder(folder, FOLDER_ITEM(node->data)) < 0)
3632 return -1;
3633 node = next;
3635 debug_print("IMAP removing %s\n", item->path);
3637 if (imap_remove_all_msg(folder, item) < 0)
3638 return -1;
3639 return imap_remove_folder_real(folder, item);
3642 typedef struct _uncached_data {
3643 IMAPSession *session;
3644 FolderItem *item;
3645 MsgNumberList *numlist;
3646 guint cur;
3647 guint total;
3648 gboolean done;
3649 int ok;
3650 } uncached_data;
3652 static void *imap_get_uncached_messages_thread(void *data)
3654 uncached_data *stuff = (uncached_data *)data;
3655 IMAPSession *session = stuff->session;
3656 FolderItem *item = stuff->item;
3657 MsgNumberList *numlist = stuff->numlist;
3658 GSList *newlist = NULL;
3659 GSList *llast = NULL;
3660 GSList *seq_list, *cur;
3661 gboolean got_alien_tags = FALSE;
3663 debug_print("uncached_messages\n");
3665 if (session == NULL || item == NULL || item->folder == NULL
3666 || FOLDER_CLASS(item->folder) != &imap_class) {
3667 stuff->done = TRUE;
3668 return NULL;
3671 seq_list = imap_get_lep_set_from_numlist(IMAP_FOLDER(item->folder), numlist);
3672 debug_print("get msgs info\n");
3673 for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
3674 struct mailimap_set * imapset;
3675 unsigned int i;
3676 int r;
3677 carray * env_list;
3678 int count;
3680 if (session->cancelled)
3681 break;
3683 imapset = cur->data;
3685 r = imap_threaded_fetch_env(session->folder,
3686 imapset, &env_list);
3687 if (r != MAILIMAP_NO_ERROR) {
3688 imap_handle_error(SESSION(session), NULL, r);
3689 if (is_fatal(r)) {
3690 stuff->ok = r;
3691 return NULL;
3693 continue;
3696 session_set_access_time(SESSION(session));
3698 count = 0;
3699 for(i = 0 ; i < carray_count(env_list) ; i += 2) {
3700 struct imap_fetch_env_info * info;
3701 MsgInfo * msginfo;
3702 GSList *tags = NULL, *cur = NULL;
3703 info = carray_get(env_list, i);
3704 tags = carray_get(env_list, i+1);
3705 msginfo = imap_envelope_from_lep(info, item);
3706 if (msginfo == NULL) {
3707 slist_free_strings_full(tags);
3708 continue;
3710 g_slist_free(msginfo->tags);
3711 msginfo->tags = NULL;
3713 for (cur = tags; cur; cur = cur->next) {
3714 gchar *real_tag = imap_modified_utf7_to_utf8(cur->data, TRUE);
3715 gint id = 0;
3716 id = tags_get_id_for_str(real_tag);
3717 if (id == -1) {
3718 id = tags_add_tag(real_tag);
3719 got_alien_tags = TRUE;
3721 if (!g_slist_find(msginfo->tags, GINT_TO_POINTER(id))) {
3722 msginfo->tags = g_slist_prepend(
3723 msginfo->tags,
3724 GINT_TO_POINTER(id));
3726 g_free(real_tag);
3728 if (msginfo->tags)
3729 msginfo->tags = g_slist_reverse(msginfo->tags);
3730 slist_free_strings_full(tags);
3731 msginfo->folder = item;
3732 if (!newlist)
3733 llast = newlist = g_slist_append(newlist, msginfo);
3734 else {
3735 llast = g_slist_append(llast, msginfo);
3736 llast = llast->next;
3738 count ++;
3741 imap_fetch_env_free(env_list);
3744 if (got_alien_tags) {
3745 tags_write_tags();
3746 main_window_reflect_tags_changes(mainwindow_get_mainwindow());
3749 imap_lep_set_free(seq_list);
3751 session_set_access_time(SESSION(session));
3752 stuff->done = TRUE;
3753 return newlist;
3756 #define MAX_MSG_NUM 50
3758 static GSList *imap_get_uncached_messages(IMAPSession *session,
3759 FolderItem *item,
3760 MsgNumberList *numlist,
3761 int *r)
3763 GSList *result = NULL;
3764 GSList * cur;
3765 uncached_data *data = g_new0(uncached_data, 1);
3767 cur = numlist;
3768 data->total = g_slist_length(numlist);
3769 data->ok = MAILIMAP_NO_ERROR;
3770 debug_print("messages list : %i\n", data->total);
3772 while (cur != NULL) {
3773 GSList * partial_result;
3774 int count;
3775 GSList * newlist;
3776 GSList * llast;
3778 llast = NULL;
3779 count = 0;
3780 newlist = NULL;
3781 while (count < MAX_MSG_NUM) {
3782 void * p;
3784 p = cur->data;
3786 if (newlist == NULL)
3787 llast = newlist = g_slist_append(newlist, p);
3788 else {
3789 llast = g_slist_append(llast, p);
3790 llast = llast->next;
3792 count ++;
3794 cur = cur->next;
3795 if (cur == NULL)
3796 break;
3799 data->done = FALSE;
3800 data->session = session;
3801 data->item = item;
3802 data->numlist = newlist;
3803 data->cur += count;
3805 if (prefs_common.work_offline &&
3806 !inc_offline_should_override(FALSE,
3807 _("Claws Mail needs network access in order "
3808 "to access the IMAP server."))) {
3809 g_free(data);
3810 return NULL;
3813 partial_result =
3814 (GSList *)imap_get_uncached_messages_thread(data);
3815 *r = data->ok;
3816 if (data->ok != MAILIMAP_NO_ERROR) {
3817 goto bail;
3819 statusbar_progress_all(data->cur,data->total, 1);
3821 g_slist_free(newlist);
3823 result = g_slist_concat(result, partial_result);
3825 bail:
3826 g_free(data);
3828 statusbar_progress_all(0,0,0);
3829 statusbar_pop_all();
3831 return result;
3834 static void imap_delete_all_cached_messages(FolderItem *item)
3836 gchar *dir;
3838 g_return_if_fail(item != NULL);
3839 g_return_if_fail(item->folder != NULL);
3840 g_return_if_fail(FOLDER_CLASS(item->folder) == &imap_class);
3842 debug_print("Deleting all cached messages...\n");
3844 dir = folder_item_get_path(item);
3845 if (is_dir_exist(dir))
3846 remove_all_numbered_files(dir);
3847 g_free(dir);
3849 debug_print("Deleting all cached messages done.\n");
3852 gchar imap_get_path_separator_for_item(FolderItem *item)
3854 Folder *folder = NULL;
3855 IMAPFolder *imap_folder = NULL;
3856 IMAPSession *session = NULL;
3857 gchar result = '/';
3858 gint ok = MAILIMAP_NO_ERROR;
3859 if (!item)
3860 return '/';
3861 folder = item->folder;
3863 if (!folder)
3864 return '/';
3866 imap_folder = IMAP_FOLDER(folder);
3868 debug_print("getting session...\n");
3869 session = imap_session_get(FOLDER(folder));
3870 result = imap_get_path_separator(session, imap_folder, item->path, &ok);
3871 return result;
3874 static gchar imap_refresh_path_separator(IMAPSession *session, IMAPFolder *folder, const gchar *subfolder, gint *ok)
3876 clist * lep_list;
3877 int r;
3878 gchar separator = '\0';
3880 g_return_val_if_fail(session != NULL, '/');
3881 r = imap_threaded_list((Folder *)folder, "", subfolder, &lep_list);
3883 if (r != MAILIMAP_NO_ERROR) {
3884 imap_handle_error(SESSION(session), NULL, r);
3885 log_warning(LOG_PROTOCOL, _("LIST failed\n"));
3886 *ok = r;
3887 return '\0';
3890 if (lep_list != NULL && clist_count(lep_list) > 0) {
3891 clistiter * iter = clist_begin(lep_list);
3892 struct mailimap_mailbox_list * mb;
3893 mb = clist_content(iter);
3895 separator = mb->mb_delimiter;
3896 debug_print("got separator: %c\n", folder->last_seen_separator);
3898 *ok = MAILIMAP_NO_ERROR;
3899 mailimap_list_result_free(lep_list);
3900 return separator;
3903 static gchar imap_get_path_separator(IMAPSession *session, IMAPFolder *folder, const gchar *path, gint *ok)
3905 gchar separator = '/';
3906 *ok = MAILIMAP_NO_ERROR;
3907 if (folder->last_seen_separator == 0) {
3908 folder->last_seen_separator = imap_refresh_path_separator(session, folder, "", ok);
3911 if (folder->last_seen_separator == 0) {
3912 folder->last_seen_separator = imap_refresh_path_separator(session, folder, "INBOX", ok);
3915 if (folder->last_seen_separator != 0) {
3916 debug_print("using separator: %c\n", folder->last_seen_separator);
3917 return folder->last_seen_separator;
3920 return separator;
3923 static gchar *imap_get_real_path(IMAPSession *session, IMAPFolder *folder, const gchar *path, gint *ok)
3925 gchar *real_path = NULL;
3926 gchar separator;
3928 g_return_val_if_fail(folder != NULL, NULL);
3929 g_return_val_if_fail(path != NULL, NULL);
3931 *ok = MAILIMAP_NO_ERROR;
3933 real_path = imap_utf8_to_modified_utf7(path, FALSE);
3934 separator = imap_get_path_separator(session, folder, path, ok);
3935 if (*ok == MAILIMAP_NO_ERROR)
3936 imap_path_separator_subst(real_path, separator);
3938 return real_path;
3941 static gint imap_set_message_flags(IMAPSession *session,
3942 IMAPFolderItem *item,
3943 MsgNumberList *numlist,
3944 IMAPFlags flags,
3945 GSList *tags,
3946 gboolean is_set)
3948 gint ok = 0;
3949 GSList *seq_list;
3950 GSList * cur;
3951 gint total = 0;
3952 IMAPFolder *folder = NULL;
3953 GSList *sorted_list = NULL;
3955 if (numlist == NULL || session == NULL)
3956 return MAILIMAP_ERROR_BAD_STATE;
3958 folder = IMAP_FOLDER(session->folder);
3960 sorted_list = g_slist_copy(numlist);
3961 sorted_list = g_slist_sort(sorted_list, g_int_compare);
3963 cur = g_slist_last(sorted_list);
3965 if (cur)
3966 total = GPOINTER_TO_INT(cur->data);
3968 seq_list = imap_get_lep_set_from_numlist(IMAP_FOLDER(session->folder), sorted_list);
3970 statusbar_print_all(_("Flagging messages..."));
3972 for(cur = seq_list ; cur != NULL ; cur = g_slist_next(cur)) {
3973 struct mailimap_set * imapset = (struct mailimap_set *)cur->data;
3974 struct mailimap_set_item *set_item = NULL;
3976 if (imapset->set_list)
3977 set_item = clist_content(clist_begin(imapset->set_list));
3978 else
3979 continue;
3981 if (set_item == NULL)
3982 continue;
3984 statusbar_progress_all(set_item->set_first, total, 1);
3986 ok = imap_cmd_store(session, item, imapset,
3987 flags, tags, is_set);
3988 statusbar_progress_all(set_item->set_last, total, 1);
3989 if (ok != MAILIMAP_NO_ERROR && folder->max_set_size > 20) {
3990 /* reduce max set size */
3991 folder->max_set_size /= 2;
3993 if (ok != MAILIMAP_NO_ERROR && is_fatal(ok)) {
3994 break;
3998 g_slist_free(sorted_list);
4000 statusbar_progress_all(0,0,0);
4001 statusbar_pop_all();
4003 imap_lep_set_free(seq_list);
4005 return ok;
4008 typedef struct _select_data {
4009 IMAPSession *session;
4010 gchar *real_path;
4011 gint *exists;
4012 gint *recent;
4013 gint *unseen;
4014 guint32 *uid_validity;
4015 gboolean done;
4016 } select_data;
4018 static gint imap_select(IMAPSession *session, IMAPFolder *folder,
4019 FolderItem *item,
4020 gint *exists, gint *recent, gint *unseen,
4021 guint32 *uid_validity, gint *can_create_flags,
4022 gboolean block)
4024 gchar *real_path;
4025 gint ok = MAILIMAP_NO_ERROR;
4026 gint exists_, recent_, unseen_;
4027 guint32 uid_validity_;
4028 gint can_create_flags_;
4029 const gchar *path = item ? item->path:NULL;
4031 if (!item) {
4032 return MAILIMAP_ERROR_BAD_STATE;
4035 if (!exists && !recent && !unseen && !uid_validity && !can_create_flags) {
4036 if (session->mbox && strcmp(session->mbox, path) == 0)
4037 return MAILIMAP_NO_ERROR;
4039 if (!exists && !recent && !unseen && !uid_validity && can_create_flags) {
4040 if (session->mbox && strcmp(session->mbox, path) == 0) {
4041 if (IMAP_FOLDER_ITEM(item)->can_create_flags != ITEM_CAN_CREATE_FLAGS_UNKNOWN)
4042 return MAILIMAP_NO_ERROR;
4045 if (!exists)
4046 exists = &exists_;
4047 if (!recent)
4048 recent = &recent_;
4049 if (!unseen)
4050 unseen = &unseen_;
4051 if (!uid_validity)
4052 uid_validity = &uid_validity_;
4053 if (!can_create_flags)
4054 can_create_flags = &can_create_flags_;
4056 g_free(session->mbox);
4057 session->mbox = NULL;
4058 session->exists = 0;
4059 session->recent = 0;
4060 session->expunge = 0;
4062 real_path = imap_get_real_path(session, folder, path, &ok);
4063 if (is_fatal(ok)) {
4064 g_free(real_path);
4065 return ok;
4067 g_slist_free(IMAP_FOLDER_ITEM(item)->ok_flags);
4068 IMAP_FOLDER_ITEM(item)->ok_flags = NULL;
4069 ok = imap_cmd_select(session, real_path,
4070 exists, recent, unseen, uid_validity, can_create_flags,
4071 &(IMAP_FOLDER_ITEM(item)->ok_flags), block);
4072 if (ok != MAILIMAP_NO_ERROR) {
4073 log_warning(LOG_PROTOCOL, _("can't select folder: %s\n"), real_path);
4074 } else {
4075 session->mbox = g_strdup(path);
4076 session->folder_content_changed = FALSE;
4077 session->exists = *exists;
4078 session->recent = *recent;
4079 session->expunge = 0;
4080 session->unseen = *unseen;
4081 session->uid_validity = *uid_validity;
4082 debug_print("select: exists %d recent %d expunge %d uid_validity %d can_create_flags %d\n",
4083 session->exists, session->recent, session->expunge,
4084 session->uid_validity, *can_create_flags);
4086 if (*can_create_flags) {
4087 IMAP_FOLDER_ITEM(item)->can_create_flags = ITEM_CAN_CREATE_FLAGS;
4088 } else {
4089 IMAP_FOLDER_ITEM(item)->can_create_flags = ITEM_CANNOT_CREATE_FLAGS;
4091 g_free(real_path);
4093 return ok;
4096 static gint imap_status(IMAPSession *session, IMAPFolder *folder,
4097 const gchar *path, IMAPFolderItem *item,
4098 gint *messages,
4099 guint32 *uid_next, guint32 *uid_validity,
4100 gint *unseen, gboolean block)
4102 int r = MAILIMAP_NO_ERROR;
4103 clistiter * iter;
4104 struct mailimap_mailbox_data_status * data_status;
4105 int got_values;
4106 gchar *real_path;
4107 guint mask = 0;
4109 real_path = imap_get_real_path(session, folder, path, &r);
4110 if (is_fatal(r)) {
4111 g_free(real_path);
4112 return r;
4114 if (messages) {
4115 mask |= 1 << 0;
4116 *messages = 0;
4118 if (uid_next) {
4119 mask |= 1 << 2;
4120 *uid_next = 0;
4122 if (uid_validity) {
4123 mask |= 1 << 3;
4124 *uid_validity = 0;
4126 if (unseen) {
4127 mask |= 1 << 4;
4128 *unseen = 0;
4131 if (session->mbox != NULL &&
4132 !strcmp(session->mbox, item->item.path)) {
4133 r = imap_cmd_close(session);
4134 if (r != MAILIMAP_NO_ERROR) {
4135 debug_print("close err %d\n", r);
4136 g_free(real_path);
4137 return r;
4141 r = imap_threaded_status(FOLDER(folder), real_path,
4142 &data_status, mask);
4144 g_free(real_path);
4145 if (r != MAILIMAP_NO_ERROR) {
4146 imap_handle_error(SESSION(session), NULL, r);
4147 debug_print("status err %d\n", r);
4148 return r;
4151 if (data_status == NULL || data_status->st_info_list == NULL) {
4152 debug_print("data_status %p\n", data_status);
4153 if (data_status) {
4154 debug_print("data_status->st_info_list %p\n", data_status->st_info_list);
4155 mailimap_mailbox_data_status_free(data_status);
4157 return MAILIMAP_ERROR_BAD_STATE;
4160 got_values = 0;
4161 if (data_status->st_info_list) {
4162 for(iter = clist_begin(data_status->st_info_list) ; iter != NULL ;
4163 iter = clist_next(iter)) {
4164 struct mailimap_status_info * info;
4166 info = clist_content(iter);
4167 switch (info->st_att) {
4168 case MAILIMAP_STATUS_ATT_MESSAGES:
4169 if (messages) {
4170 * messages = info->st_value;
4171 got_values |= 1 << 0;
4173 break;
4175 case MAILIMAP_STATUS_ATT_UIDNEXT:
4176 if (uid_next) {
4177 * uid_next = info->st_value;
4178 got_values |= 1 << 2;
4180 break;
4182 case MAILIMAP_STATUS_ATT_UIDVALIDITY:
4183 if (uid_validity) {
4184 * uid_validity = info->st_value;
4185 got_values |= 1 << 3;
4187 break;
4189 case MAILIMAP_STATUS_ATT_UNSEEN:
4190 if (unseen) {
4191 * unseen = info->st_value;
4192 got_values |= 1 << 4;
4194 break;
4198 mailimap_mailbox_data_status_free(data_status);
4200 if (got_values != mask) {
4201 g_warning("status: incomplete values received (%d)", got_values);
4203 return MAILIMAP_NO_ERROR;
4206 static void imap_free_capabilities(IMAPSession *session)
4208 slist_free_strings_full(session->capability);
4209 session->capability = NULL;
4212 /* low-level IMAP4rev1 commands */
4214 static gint imap_cmd_login(IMAPSession *session,
4215 const gchar *user, const gchar *pass,
4216 const gchar *type)
4218 int r;
4219 gint ok;
4221 if (!strcmp(type, "plaintext") && imap_has_capability(session, "LOGINDISABLED")) {
4222 ok = MAILIMAP_ERROR_BAD_STATE;
4223 if (imap_has_capability(session, "STARTTLS")) {
4224 #ifdef USE_GNUTLS
4225 log_warning(LOG_PROTOCOL, _("Server requires STARTTLS to log in.\n"));
4226 ok = imap_cmd_starttls(session);
4227 if (ok != MAILIMAP_NO_ERROR) {
4228 log_warning(LOG_PROTOCOL, _("Can't start STARTTLS session.\n"));
4229 return ok;
4230 } else {
4231 /* refresh capas */
4232 imap_free_capabilities(session);
4233 if ((r = imap_get_capabilities(session)) != MAILIMAP_NO_ERROR) {
4234 imap_handle_error(SESSION(session), NULL, r);
4235 log_warning(LOG_PROTOCOL, _("Can't refresh capabilities.\n"));
4236 return r;
4239 #else
4240 log_error(LOG_PROTOCOL, _("Connection to %s failed: "
4241 "server requires STARTTLS, but Claws Mail "
4242 "has been compiled without STARTTLS "
4243 "support.\n"),
4244 SESSION(session)->server);
4245 return MAILIMAP_ERROR_LOGIN;
4246 #endif
4247 } else {
4248 log_error(LOG_PROTOCOL, _("Server logins are disabled.\n"));
4249 return MAILIMAP_ERROR_LOGIN;
4253 log_print(LOG_PROTOCOL, "IMAP> Logging %s to %s using %s\n",
4254 user,
4255 SESSION(session)->server,
4256 type);
4257 r = imap_threaded_login(session->folder, user, pass, type);
4258 if (r != MAILIMAP_NO_ERROR) {
4259 imap_handle_error(SESSION(session), NULL, r);
4260 log_print(LOG_PROTOCOL, "IMAP< Error logging in to %s\n",
4261 SESSION(session)->server);
4262 ok = r;
4263 } else {
4264 log_print(LOG_PROTOCOL, "IMAP< Login to %s successful\n",
4265 SESSION(session)->server);
4266 ok = MAILIMAP_NO_ERROR;
4268 return ok;
4271 static gint imap_cmd_noop(IMAPSession *session)
4273 int r;
4274 unsigned int exists, recent, expunge, unseen, uidnext, uidval;
4276 r = imap_threaded_noop(session->folder, &exists, &recent, &expunge, &unseen, &uidnext, &uidval);
4277 if (r != MAILIMAP_NO_ERROR) {
4278 imap_handle_error(SESSION(session), NULL, r);
4279 debug_print("noop err %d\n", r);
4280 return r;
4283 if ((exists && exists != session->exists)
4284 || (recent && recent != session->recent)
4285 || (expunge && expunge != session->expunge)
4286 || (unseen && unseen != session->unseen)) {
4287 session->folder_content_changed = TRUE;
4289 if (uidnext != 0 && uidnext != session->uid_next) {
4290 session->uid_next = uidnext;
4291 session->folder_content_changed = TRUE;
4293 if (uidval != 0 && uidval != session->uid_validity) {
4294 session->uid_validity = uidval;
4295 session->folder_content_changed = TRUE;
4298 session->exists = exists;
4299 session->recent = recent;
4300 session->expunge = expunge;
4301 session->unseen = unseen;
4303 session_set_access_time(SESSION(session));
4305 return MAILIMAP_NO_ERROR;
4308 #ifdef USE_GNUTLS
4309 static gint imap_cmd_starttls(IMAPSession *session)
4311 int r;
4313 r = imap_threaded_starttls(session->folder,
4314 SESSION(session)->server, SESSION(session)->port);
4315 if (r != MAILIMAP_NO_ERROR) {
4316 imap_handle_error(SESSION(session), NULL, r);
4317 debug_print("STARTTLS err %d\n", r);
4318 return r;
4320 return MAILIMAP_NO_ERROR;
4322 #endif
4324 static gint imap_cmd_select(IMAPSession *session, const gchar *folder,
4325 gint *exists, gint *recent, gint *unseen,
4326 guint32 *uid_validity, gint *can_create_flags,
4327 GSList **ok_flags, gboolean block)
4329 int r;
4331 r = imap_threaded_select(session->folder, folder,
4332 exists, recent, unseen, uid_validity, can_create_flags, ok_flags);
4333 if (r != MAILIMAP_NO_ERROR) {
4334 imap_handle_error(SESSION(session), NULL, r);
4335 debug_print("select err %d\n", r);
4336 return r;
4338 return MAILIMAP_NO_ERROR;
4341 static gint imap_cmd_close(IMAPSession *session)
4343 int r;
4345 r = imap_threaded_close(session->folder);
4346 if (r != MAILIMAP_NO_ERROR) {
4347 imap_handle_error(SESSION(session), NULL, r);
4348 debug_print("close err %d\n", r);
4349 return r;
4351 g_free(session->mbox);
4352 session->mbox = NULL;
4353 session->exists = 0;
4354 session->recent = 0;
4355 session->expunge = 0;
4356 return MAILIMAP_NO_ERROR;
4359 static gint imap_cmd_examine(IMAPSession *session, const gchar *folder,
4360 gint *exists, gint *recent, gint *unseen,
4361 guint32 *uid_validity, gboolean block)
4363 int r;
4365 r = imap_threaded_examine(session->folder, folder,
4366 exists, recent, unseen, uid_validity);
4367 if (r != MAILIMAP_NO_ERROR) {
4368 imap_handle_error(SESSION(session), NULL, r);
4369 debug_print("examine err %d\n", r);
4371 return r;
4373 return MAILIMAP_NO_ERROR;
4376 static gint imap_cmd_create(IMAPSession *session, const gchar *folder)
4378 int r;
4380 r = imap_threaded_create(session->folder, folder);
4381 if (r != MAILIMAP_NO_ERROR) {
4382 imap_handle_error(SESSION(session), NULL, r);
4383 return r;
4386 return MAILIMAP_NO_ERROR;
4389 static gint imap_cmd_rename(IMAPSession *session, const gchar *old_folder,
4390 const gchar *new_folder)
4392 int r;
4394 r = imap_threaded_rename(session->folder, old_folder,
4395 new_folder);
4396 if (r != MAILIMAP_NO_ERROR) {
4397 imap_handle_error(SESSION(session), NULL, r);
4398 return r;
4401 return MAILIMAP_NO_ERROR;
4404 static gint imap_cmd_delete(IMAPSession *session, const gchar *folder)
4406 int r;
4409 r = imap_threaded_delete(session->folder, folder);
4410 if (r != MAILIMAP_NO_ERROR) {
4411 imap_handle_error(SESSION(session), NULL, r);
4412 return r;
4415 return MAILIMAP_NO_ERROR;
4418 typedef struct _fetch_data {
4419 IMAPSession *session;
4420 guint32 uid;
4421 const gchar *filename;
4422 gboolean headers;
4423 gboolean body;
4424 gboolean done;
4425 } fetch_data;
4427 static void *imap_cmd_fetch_thread(void *data)
4429 fetch_data *stuff = (fetch_data *)data;
4430 IMAPSession *session = stuff->session;
4431 guint32 uid = stuff->uid;
4432 const gchar *filename = stuff->filename;
4433 int r;
4435 if (stuff->body) {
4436 r = imap_threaded_fetch_content(session->folder,
4437 uid, 1, filename);
4439 else {
4440 r = imap_threaded_fetch_content(session->folder,
4441 uid, 0, filename);
4443 if (r != MAILIMAP_NO_ERROR) {
4444 imap_handle_error(SESSION(session), NULL, r);
4445 debug_print("fetch err %d\n", r);
4446 return GINT_TO_POINTER(r);
4448 return GINT_TO_POINTER(MAILIMAP_NO_ERROR);
4451 static gint imap_cmd_fetch(IMAPSession *session, guint32 uid,
4452 const gchar *filename, gboolean headers,
4453 gboolean body)
4455 fetch_data *data = g_new0(fetch_data, 1);
4456 int result = 0;
4457 data->done = FALSE;
4458 data->session = session;
4459 data->uid = uid;
4460 data->filename = filename;
4461 data->headers = headers;
4462 data->body = body;
4464 if (prefs_common.work_offline &&
4465 !inc_offline_should_override(FALSE,
4466 _("Claws Mail needs network access in order "
4467 "to access the IMAP server."))) {
4468 g_free(data);
4469 return -1;
4471 statusbar_print_all(_("Fetching message..."));
4472 result = GPOINTER_TO_INT(imap_cmd_fetch_thread(data));
4473 statusbar_pop_all();
4474 g_free(data);
4475 return result;
4479 static gint imap_cmd_append(IMAPSession *session,
4480 IMAPFolderItem *item,
4481 const gchar *destfolder,
4482 const gchar *file, IMAPFlags flags,
4483 guint32 *new_uid)
4485 struct mailimap_flag_list * flag_list;
4486 int r;
4488 cm_return_val_if_fail(file != NULL, MAILIMAP_ERROR_BAD_STATE);
4490 flag_list = imap_flag_to_lep(item, flags, NULL);
4491 lock_session(session);
4492 r = imap_threaded_append(session->folder, destfolder,
4493 file, flag_list, (int *)new_uid);
4494 mailimap_flag_list_free(flag_list);
4496 if (r != MAILIMAP_NO_ERROR) {
4497 imap_handle_error(SESSION(session), NULL, r);
4498 debug_print("append err %d\n", r);
4499 return r;
4502 unlock_session(session);
4504 return MAILIMAP_NO_ERROR;
4507 static gint imap_cmd_copy(IMAPSession *session, struct mailimap_set * set,
4508 const gchar *destfolder,
4509 struct mailimap_set **source, struct mailimap_set **dest)
4511 int r;
4513 g_return_val_if_fail(session != NULL, MAILIMAP_ERROR_BAD_STATE);
4514 g_return_val_if_fail(set != NULL, MAILIMAP_ERROR_BAD_STATE);
4515 g_return_val_if_fail(destfolder != NULL, MAILIMAP_ERROR_BAD_STATE);
4517 r = imap_threaded_copy(session->folder, set, destfolder, source, dest);
4518 if (r != MAILIMAP_NO_ERROR) {
4519 imap_handle_error(SESSION(session), NULL, r);
4520 return r;
4523 return MAILIMAP_NO_ERROR;
4526 static gint imap_cmd_store(IMAPSession *session,
4527 IMAPFolderItem *item,
4528 struct mailimap_set * set,
4529 IMAPFlags flags, GSList *tags, int do_add)
4531 int r;
4532 struct mailimap_flag_list * flag_list = NULL;
4533 struct mailimap_store_att_flags * store_att_flags;
4535 flag_list = imap_flag_to_lep(item, flags, tags);
4537 if (do_add)
4538 store_att_flags =
4539 mailimap_store_att_flags_new_add_flags_silent(flag_list);
4540 else
4541 store_att_flags =
4542 mailimap_store_att_flags_new_remove_flags_silent(flag_list);
4544 r = imap_threaded_store(session->folder, set, store_att_flags);
4545 mailimap_store_att_flags_free(store_att_flags);
4546 if (r != MAILIMAP_NO_ERROR) {
4547 imap_handle_error(SESSION(session), NULL, r);
4548 return r;
4551 return MAILIMAP_NO_ERROR;
4554 static gint imap_cmd_expunge(IMAPSession *session)
4556 int r;
4558 if (prefs_common.work_offline &&
4559 !inc_offline_should_override(FALSE,
4560 _("Claws Mail needs network access in order "
4561 "to access the IMAP server."))) {
4562 return -1;
4565 statusbar_print_all(_("Expunging deleted messages..."));
4566 r = imap_threaded_expunge(session->folder);
4567 statusbar_pop_all();
4568 if (r != MAILIMAP_NO_ERROR) {
4569 imap_handle_error(SESSION(session), NULL, r);
4570 return r;
4573 return MAILIMAP_NO_ERROR;
4576 gint imap_expunge(Folder *folder, FolderItem *item)
4578 IMAPSession *session = imap_session_get(folder);
4579 if (session == NULL)
4580 return -1;
4582 return imap_cmd_expunge(session);
4585 static void imap_path_separator_subst(gchar *str, gchar separator)
4587 gchar *p;
4588 gboolean in_escape = FALSE;
4590 if (!separator || separator == '/') return;
4592 for (p = str; *p != '\0'; p++) {
4593 if (*p == '/' && !in_escape)
4594 *p = separator;
4595 else if (*p == '&' && *(p + 1) != '-' && !in_escape)
4596 in_escape = TRUE;
4597 else if (*p == '-' && in_escape)
4598 in_escape = FALSE;
4602 static gboolean imap_rename_folder_func(GNode *node, gpointer data)
4604 FolderItem *item = node->data;
4605 gchar **paths = data;
4606 const gchar *oldpath = paths[0];
4607 const gchar *newpath = paths[1];
4608 gchar *real_oldpath, *real_newpath;
4609 gchar *base;
4610 gchar *new_itempath;
4611 gint oldpathlen;
4612 IMAPSession *session = imap_session_get(item->folder);
4613 gint ok = MAILIMAP_NO_ERROR;
4614 oldpathlen = strlen(oldpath);
4615 if (strncmp(oldpath, item->path, oldpathlen) != 0) {
4616 g_warning("path doesn't match: %s, %s", oldpath, item->path);
4617 return TRUE;
4620 base = item->path + oldpathlen;
4621 while (*base == '/') base++;
4622 if (*base == '\0')
4623 new_itempath = g_strdup(newpath);
4624 else
4625 new_itempath = g_strconcat(newpath, "/", base,
4626 NULL);
4628 real_oldpath = imap_get_real_path(session, IMAP_FOLDER(item->folder), item->path, &ok);
4629 g_free(item->path);
4630 item->path = new_itempath;
4632 real_newpath = imap_get_real_path(session, IMAP_FOLDER(item->folder), item->path, &ok);
4634 imap_threaded_subscribe(item->folder, real_oldpath, FALSE);
4635 imap_threaded_subscribe(item->folder, real_newpath, TRUE);
4637 g_free(real_oldpath);
4638 g_free(real_newpath);
4639 return FALSE;
4642 static gint get_list_of_uids(IMAPSession *session, Folder *folder, IMAPFolderItem *item, GSList **msgnum_list)
4644 GSList *uidlist, *elem;
4645 int r = -1;
4646 clist * lep_uidlist;
4647 gint ok, nummsgs = 0;
4649 if (session == NULL) {
4650 return -1;
4653 ok = imap_select(session, IMAP_FOLDER(folder), FOLDER_ITEM(item),
4654 NULL, NULL, NULL, NULL, NULL, TRUE);
4655 if (ok != MAILIMAP_NO_ERROR) {
4656 return -1;
4659 g_slist_free(item->uid_list);
4660 item->uid_list = NULL;
4662 uidlist = NULL;
4664 if (folder->account && folder->account->low_bandwidth) {
4665 r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_SIMPLE,
4666 NULL, NULL, NULL, &lep_uidlist);
4669 if (r == MAILIMAP_NO_ERROR) {
4670 uidlist = imap_uid_list_from_lep(lep_uidlist, NULL);
4671 mailimap_search_result_free(lep_uidlist);
4672 } else {
4673 carray * lep_uidtab;
4674 if (r != -1) { /* inited */
4675 imap_handle_error(SESSION(session), NULL, r);
4676 if (is_fatal(r))
4677 return -1;
4679 r = imap_threaded_fetch_uid(folder, 1,
4680 &lep_uidtab);
4681 if (r == MAILIMAP_NO_ERROR) {
4682 uidlist = imap_uid_list_from_lep_tab(lep_uidtab);
4683 imap_fetch_uid_list_free(lep_uidtab);
4687 if (r != MAILIMAP_NO_ERROR) {
4688 imap_handle_error(SESSION(session), NULL, r);
4689 return -1;
4692 for (elem = uidlist; elem != NULL; elem = g_slist_next(elem)) {
4693 guint msgnum;
4695 msgnum = GPOINTER_TO_INT(elem->data);
4697 *msgnum_list = g_slist_prepend(*msgnum_list, GINT_TO_POINTER(msgnum));
4698 item->uid_list = g_slist_prepend(item->uid_list, GINT_TO_POINTER(msgnum));
4699 nummsgs++;
4701 g_slist_free(uidlist);
4703 return nummsgs;
4707 gint imap_get_num_list(Folder *folder, FolderItem *_item, GSList **msgnum_list, gboolean *old_uids_valid)
4709 IMAPFolderItem *item = (IMAPFolderItem *)_item;
4710 IMAPSession *session;
4711 gint nummsgs;
4712 GSList *uidlist = NULL;
4713 gchar *dir;
4714 gint known_list_len = 0;
4715 gchar *path;
4717 debug_print("get_num_list\n");
4719 g_return_val_if_fail(folder != NULL, -1);
4720 g_return_val_if_fail(item != NULL, -1);
4721 g_return_val_if_fail(item->item.path != NULL, -1);
4722 g_return_val_if_fail(FOLDER_CLASS(folder) == &imap_class, -1);
4723 g_return_val_if_fail(folder->account != NULL, -1);
4725 known_list_len = g_slist_length(item->uid_list);
4726 if (!item->should_update) {
4727 debug_print("get_num_list: nothing to update\n");
4728 *old_uids_valid = TRUE;
4729 if (known_list_len == item->item.total_msgs
4730 && known_list_len > 0) {
4731 *msgnum_list = g_slist_copy(item->uid_list);
4732 return known_list_len;
4733 } else {
4734 debug_print("don't know the list length...\n");
4738 if (prefs_common.work_offline &&
4739 !inc_offline_should_override(FALSE,
4740 _("Claws Mail needs network access in order "
4741 "to access the IMAP server."))) {
4742 return -1;
4745 path = folder_item_get_path(_item);
4746 if (!is_dir_exist(path)) {
4747 if(is_file_exist(path))
4748 claws_unlink(path);
4749 make_dir_hier(path);
4751 g_free(path);
4753 debug_print("getting session...\n");
4754 session = imap_session_get(folder);
4755 g_return_val_if_fail(session != NULL, -1);
4757 lock_session(session);
4758 if (FOLDER_ITEM(item)->path)
4759 statusbar_print_all(_("Scanning folder %s/%s..."),
4760 FOLDER_ITEM(item)->folder->name,
4761 FOLDER_ITEM(item)->path);
4762 else
4763 statusbar_print_all(_("Scanning folder %s..."),
4764 FOLDER_ITEM(item)->folder->name);
4766 if (item->should_trash_cache) {
4767 *old_uids_valid = FALSE;
4768 debug_print("get_num_list: trashing num list\n");
4769 debug_print("Freeing imap uid cache\n");
4770 item->lastuid = 0;
4771 g_slist_free(item->uid_list);
4772 item->uid_list = NULL;
4774 imap_delete_all_cached_messages((FolderItem *)item);
4775 } else {
4776 debug_print("get_num_list: updating num list\n");
4777 *old_uids_valid = TRUE;
4780 nummsgs = get_list_of_uids(session, folder, item, &uidlist);
4782 unlock_session(session);
4784 /* session could be broken now, in case of fatal error */
4786 debug_print("get_num_list: got %d msgs\n", nummsgs);
4788 if (nummsgs < 0) {
4789 statusbar_pop_all();
4790 return -1;
4793 *msgnum_list = uidlist;
4795 dir = folder_item_get_path((FolderItem *)item);
4796 debug_print("removing old messages from %s\n", dir);
4797 remove_numbered_files_not_in_list(dir, *msgnum_list);
4798 g_free(dir);
4800 debug_print("get_num_list - ok - %i\n", nummsgs);
4801 statusbar_pop_all();
4802 item->should_trash_cache = FALSE;
4803 item->should_update = FALSE;
4804 return nummsgs;
4807 static MsgInfo *imap_parse_msg(const gchar *file, FolderItem *item)
4809 MsgInfo *msginfo;
4810 MsgFlags flags;
4812 flags.perm_flags = MSG_NEW|MSG_UNREAD;
4813 flags.tmp_flags = 0;
4815 g_return_val_if_fail(item != NULL, NULL);
4816 g_return_val_if_fail(file != NULL, NULL);
4818 if (folder_has_parent_of_type(item, F_QUEUE)) {
4819 MSG_SET_TMP_FLAGS(flags, MSG_QUEUED);
4820 } else if (folder_has_parent_of_type(item, F_DRAFT)) {
4821 MSG_SET_TMP_FLAGS(flags, MSG_DRAFT);
4824 msginfo = procheader_parse_file(file, flags, FALSE, FALSE);
4825 if (!msginfo) return NULL;
4827 msginfo->plaintext_file = g_strdup(file);
4828 msginfo->folder = item;
4830 return msginfo;
4833 GSList *imap_get_msginfos(Folder *folder, FolderItem *item,
4834 GSList *msgnum_list)
4836 IMAPSession *session;
4837 MsgInfoList *ret = NULL;
4838 gint ok;
4840 debug_print("get_msginfos\n");
4842 g_return_val_if_fail(folder != NULL, NULL);
4843 g_return_val_if_fail(item != NULL, NULL);
4844 g_return_val_if_fail(msgnum_list != NULL, NULL);
4846 debug_print("getting session...\n");
4847 session = imap_session_get(folder);
4848 g_return_val_if_fail(session != NULL, NULL);
4850 lock_session(session); /* unlocked later in the function */
4852 debug_print("IMAP getting msginfos\n");
4853 ok = imap_select(session, IMAP_FOLDER(folder), item,
4854 NULL, NULL, NULL, NULL, NULL, FALSE);
4855 if (ok != MAILIMAP_NO_ERROR) {
4856 return NULL;
4858 if (!(folder_has_parent_of_type(item, F_DRAFT) ||
4859 folder_has_parent_of_type(item, F_QUEUE))) {
4860 ret = g_slist_concat(ret,
4861 imap_get_uncached_messages(session, item,
4862 msgnum_list, &ok));
4863 if (ok != MAILIMAP_NO_ERROR)
4864 return NULL;
4865 unlock_session(session);
4866 } else {
4867 MsgNumberList *sorted_list, *elem, *llast = NULL;
4868 gint startnum, lastnum;
4870 unlock_session(session);
4872 sorted_list = g_slist_sort(g_slist_copy(msgnum_list), g_int_compare);
4874 startnum = lastnum = GPOINTER_TO_INT(sorted_list->data);
4876 llast = g_slist_last(ret);
4877 for (elem = sorted_list;; elem = g_slist_next(elem)) {
4878 guint num = 0;
4880 if (elem)
4881 num = GPOINTER_TO_INT(elem->data);
4883 if (num > lastnum + 1 || elem == NULL) {
4884 int i;
4885 for (i = startnum; i <= lastnum; ++i) {
4886 gchar *file;
4887 file = imap_fetch_msg(folder, item, i);
4888 if (file != NULL) {
4889 MsgInfo *msginfo = imap_parse_msg(file, item);
4890 if (msginfo != NULL) {
4891 msginfo->msgnum = i;
4892 if (llast == NULL)
4893 llast = ret = g_slist_append(ret, msginfo);
4894 else {
4895 llast = g_slist_append(llast, msginfo);
4896 llast = llast->next;
4899 g_free(file);
4903 if (elem == NULL)
4904 break;
4906 startnum = num;
4908 lastnum = num;
4911 g_slist_free(sorted_list);
4913 return ret;
4916 MsgInfo *imap_get_msginfo(Folder *folder, FolderItem *item, gint uid)
4918 MsgInfo *msginfo = NULL;
4919 MsgInfoList *msginfolist;
4920 MsgNumberList numlist;
4922 numlist.next = NULL;
4923 numlist.data = GINT_TO_POINTER(uid);
4925 msginfolist = imap_get_msginfos(folder, item, &numlist);
4926 if (msginfolist != NULL) {
4927 msginfo = msginfolist->data;
4928 g_slist_free(msginfolist);
4931 return msginfo;
4934 gboolean imap_scan_required(Folder *folder, FolderItem *_item)
4936 IMAPSession *session;
4937 IMAPFolderItem *item = (IMAPFolderItem *)_item;
4938 gint ok, exists = 0, unseen = 0;
4939 guint32 uid_next = 0, uid_val = 0;
4940 gboolean selected_folder;
4942 g_return_val_if_fail(folder != NULL, FALSE);
4943 g_return_val_if_fail(item != NULL, FALSE);
4944 g_return_val_if_fail(item->item.folder != NULL, FALSE);
4945 g_return_val_if_fail(FOLDER_CLASS(item->item.folder) == &imap_class, FALSE);
4947 if (item->item.path == NULL)
4948 return FALSE;
4950 if (item->should_update) {
4951 debug_print("scan already required\n");
4952 return TRUE;
4954 debug_print("getting session...\n");
4955 session = imap_session_get(folder);
4957 g_return_val_if_fail(session != NULL, FALSE);
4958 lock_session(session); /* unlocked later in the function */
4960 selected_folder = (session->mbox != NULL) &&
4961 (!strcmp(session->mbox, item->item.path));
4962 if (selected_folder) {
4963 if (!session->folder_content_changed) {
4964 ok = imap_cmd_noop(session);
4965 if (ok != MAILIMAP_NO_ERROR) {
4966 debug_print("disconnected!\n");
4967 if (!is_fatal(ok))
4968 session = imap_reconnect_if_possible(folder, session);
4969 else
4970 session = imap_session_get(folder);
4971 if (session == NULL)
4972 return FALSE;
4975 if (session->folder_content_changed) {
4976 debug_print("CHANGED (self-noop)! scan_required\n");
4977 item->should_update = TRUE;
4978 if (session->uid_validity && session->uid_validity != item->item.mtime) {
4979 item->item.mtime = session->uid_validity;
4980 item->should_trash_cache = TRUE;
4982 unlock_session(session);
4983 return TRUE;
4985 } else {
4986 debug_print("CHANGED (previous noop)! scan_required\n");
4987 item->should_update = TRUE;
4988 if (session->uid_validity && session->uid_validity != item->item.mtime) {
4989 item->item.mtime = session->uid_validity;
4990 item->should_trash_cache = TRUE;
4992 unlock_session(session);
4993 return TRUE;
4995 } else {
4996 ok = imap_status(session, IMAP_FOLDER(folder), item->item.path, IMAP_FOLDER_ITEM(item),
4997 &exists, &uid_next, &uid_val, &unseen, FALSE);
4998 if (ok != MAILIMAP_NO_ERROR) {
4999 return FALSE;
5002 debug_print("exists %d, item->item.total_msgs %d\n"
5003 "\tunseen %d, item->item.unread_msgs %d\n"
5004 "\tuid_next %d, item->uid_next %d\n"
5005 "\tuid_val %d, item->item.mtime %ld\n",
5006 exists, item->item.total_msgs, unseen, item->item.unread_msgs,
5007 uid_next, item->uid_next, uid_val, (long)(item->item.mtime));
5008 if (exists != item->item.total_msgs
5009 || unseen != item->item.unread_msgs
5010 || uid_next != item->uid_next
5011 || uid_val != item->item.mtime) {
5012 debug_print("CHANGED (status)! scan_required\n");
5013 item->last_change = time(NULL);
5014 item->should_update = TRUE;
5015 item->uid_next = uid_next;
5016 if (uid_val != item->item.mtime) {
5017 item->item.mtime = uid_val;
5018 item->should_trash_cache = TRUE;
5020 unlock_session(session);
5021 return TRUE;
5024 unlock_session(session);
5026 item->should_update = FALSE;
5027 return FALSE;
5030 void imap_change_flags(Folder *folder, FolderItem *item, MsgInfo *msginfo, MsgPermFlags newflags)
5032 IMAPSession *session;
5033 IMAPFlags flags_set = 0, flags_unset = 0;
5034 gint ok = MAILIMAP_NO_ERROR;
5035 MsgNumberList numlist;
5036 hashtable_data *ht_data = NULL;
5038 g_return_if_fail(folder != NULL);
5039 g_return_if_fail(folder->klass == &imap_class);
5040 g_return_if_fail(item != NULL);
5041 g_return_if_fail(item->folder == folder);
5042 g_return_if_fail(msginfo != NULL);
5043 g_return_if_fail(msginfo->folder == item);
5045 if (!MSG_IS_MARKED(msginfo->flags) && (newflags & MSG_MARKED))
5046 flags_set |= IMAP_FLAG_FLAGGED;
5047 if ( MSG_IS_MARKED(msginfo->flags) && !(newflags & MSG_MARKED))
5048 flags_unset |= IMAP_FLAG_FLAGGED;
5050 if (!MSG_IS_UNREAD(msginfo->flags) && (newflags & MSG_UNREAD))
5051 flags_unset |= IMAP_FLAG_SEEN;
5052 if ( MSG_IS_UNREAD(msginfo->flags) && !(newflags & MSG_UNREAD))
5053 flags_set |= IMAP_FLAG_SEEN;
5055 if (!MSG_IS_REPLIED(msginfo->flags) && (newflags & MSG_REPLIED))
5056 flags_set |= IMAP_FLAG_ANSWERED;
5057 if ( MSG_IS_REPLIED(msginfo->flags) && !(newflags & MSG_REPLIED))
5058 flags_unset |= IMAP_FLAG_ANSWERED;
5060 if (!MSG_IS_FORWARDED(msginfo->flags) && (newflags & MSG_FORWARDED))
5061 flags_set |= IMAP_FLAG_FORWARDED;
5062 if ( MSG_IS_FORWARDED(msginfo->flags) && !(newflags & MSG_FORWARDED))
5063 flags_unset |= IMAP_FLAG_FORWARDED;
5065 if (!MSG_IS_SPAM(msginfo->flags) && (newflags & MSG_SPAM)) {
5066 flags_set |= IMAP_FLAG_SPAM;
5067 flags_unset |= IMAP_FLAG_HAM;
5069 if ( MSG_IS_SPAM(msginfo->flags) && !(newflags & MSG_SPAM)) {
5070 flags_set |= IMAP_FLAG_HAM;
5071 flags_unset |= IMAP_FLAG_SPAM;
5073 if (!MSG_IS_DELETED(msginfo->flags) && (newflags & MSG_DELETED))
5074 flags_set |= IMAP_FLAG_DELETED;
5075 if ( MSG_IS_DELETED(msginfo->flags) && !(newflags & MSG_DELETED))
5076 flags_unset |= IMAP_FLAG_DELETED;
5078 if (!flags_set && !flags_unset) {
5079 /* the changed flags were not translatable to IMAP-speak.
5080 * like MSG_POSTFILTERED, so just apply. */
5081 msginfo->flags.perm_flags = newflags;
5082 return;
5085 debug_print("getting session...\n");
5086 session = imap_session_get(folder);
5087 if (!session) {
5088 return;
5091 if ((ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder,
5092 NULL, NULL, NULL, NULL, NULL, FALSE)) != MAILIMAP_NO_ERROR) {
5093 return;
5095 numlist.next = NULL;
5096 numlist.data = GINT_TO_POINTER(msginfo->msgnum);
5098 if (IMAP_FOLDER_ITEM(item)->batching) {
5099 /* instead of performing an UID STORE command for each message change,
5100 * as a lot of them can change "together", we just fill in hashtables
5101 * and defer the treatment so that we're able to send only one
5102 * command.
5104 debug_print("IMAP batch mode on, deferring flags change\n");
5105 if (flags_set) {
5106 ht_data = g_hash_table_lookup(IMAP_FOLDER_ITEM(item)->flags_set_table,
5107 GINT_TO_POINTER(flags_set));
5108 if (ht_data == NULL) {
5109 ht_data = g_new0(hashtable_data, 1);
5110 ht_data->item = IMAP_FOLDER_ITEM(item);
5111 g_hash_table_insert(IMAP_FOLDER_ITEM(item)->flags_set_table,
5112 GINT_TO_POINTER(flags_set), ht_data);
5114 ht_data->msglist = g_slist_prepend(ht_data->msglist, GINT_TO_POINTER(msginfo->msgnum));
5116 if (flags_unset) {
5117 ht_data = g_hash_table_lookup(IMAP_FOLDER_ITEM(item)->flags_unset_table,
5118 GINT_TO_POINTER(flags_unset));
5119 if (ht_data == NULL) {
5120 ht_data = g_new0(hashtable_data, 1);
5121 ht_data->item = IMAP_FOLDER_ITEM(item);
5122 g_hash_table_insert(IMAP_FOLDER_ITEM(item)->flags_unset_table,
5123 GINT_TO_POINTER(flags_unset), ht_data);
5125 ht_data->msglist = g_slist_prepend(ht_data->msglist,
5126 GINT_TO_POINTER(msginfo->msgnum));
5128 } else {
5129 debug_print("IMAP changing flags\n");
5130 if (flags_set) {
5131 ok = imap_set_message_flags(session, IMAP_FOLDER_ITEM(item), &numlist, flags_set, NULL, TRUE);
5132 if (ok != MAILIMAP_NO_ERROR) {
5133 return;
5137 if (flags_unset) {
5138 ok = imap_set_message_flags(session, IMAP_FOLDER_ITEM(item), &numlist, flags_unset, NULL, FALSE);
5139 if (ok != MAILIMAP_NO_ERROR) {
5140 return;
5144 msginfo->flags.perm_flags = newflags;
5145 return;
5148 static gint imap_remove_msg(Folder *folder, FolderItem *item, gint uid)
5150 gint ok;
5151 IMAPSession *session;
5152 gchar *dir;
5153 MsgNumberList numlist;
5155 g_return_val_if_fail(folder != NULL, -1);
5156 g_return_val_if_fail(FOLDER_CLASS(folder) == &imap_class, -1);
5157 g_return_val_if_fail(item != NULL, -1);
5159 debug_print("getting session...\n");
5160 session = imap_session_get(folder);
5161 if (!session) return -1;
5163 ok = imap_select(session, IMAP_FOLDER(folder), item,
5164 NULL, NULL, NULL, NULL, NULL, FALSE);
5165 if (ok != MAILIMAP_NO_ERROR) {
5166 return ok;
5168 numlist.next = NULL;
5169 numlist.data = GINT_TO_POINTER(uid);
5171 ok = imap_set_message_flags
5172 (session, IMAP_FOLDER_ITEM(item), &numlist, IMAP_FLAG_DELETED, NULL, TRUE);
5173 if (ok != MAILIMAP_NO_ERROR) {
5174 log_warning(LOG_PROTOCOL, _("can't set deleted flags: %d\n"), uid);
5175 return ok;
5178 ok = imap_cmd_expunge(session);
5180 if (ok != MAILIMAP_NO_ERROR) {
5181 log_warning(LOG_PROTOCOL, _("can't expunge\n"));
5182 return ok;
5185 IMAP_FOLDER_ITEM(item)->uid_list = g_slist_remove(
5186 IMAP_FOLDER_ITEM(item)->uid_list, numlist.data);
5187 dir = folder_item_get_path(item);
5188 if (is_dir_exist(dir))
5189 remove_numbered_files(dir, uid, uid);
5190 g_free(dir);
5191 return MAILIMAP_NO_ERROR;
5194 static gint compare_msginfo(gconstpointer a, gconstpointer b)
5196 return ((MsgInfo *)a)->msgnum - ((MsgInfo *)b)->msgnum;
5199 static guint gslist_find_next_num(MsgNumberList **list, guint num)
5201 GSList *elem;
5203 g_return_val_if_fail(list != NULL, -1);
5205 for (elem = *list; elem != NULL; elem = g_slist_next(elem))
5206 if (GPOINTER_TO_INT(elem->data) >= num)
5207 break;
5208 *list = elem;
5209 return elem != NULL ? GPOINTER_TO_INT(elem->data) : (gint)-1;
5212 static gboolean flag_ok(IMAPFolderItem *item, guint flag)
5214 if (item->ok_flags && g_slist_find(item->ok_flags, GUINT_TO_POINTER(flag))) {
5215 debug_print("flag %d is OK\n", flag);
5216 return TRUE;
5218 if (item->can_create_flags == ITEM_CAN_CREATE_FLAGS) {
5219 debug_print("creating flags is OK\n");
5220 return TRUE;
5222 return FALSE;
5226 * NEW and DELETED flags are not syncronized
5227 * - The NEW/RECENT flags in IMAP folders can not really be directly
5228 * modified by Claws Mail
5229 * - The DELETE/DELETED flag in IMAP and Claws Mail do not have the same
5230 * meaning, in IMAP it always removes the messages from the FolderItem
5231 * in Claws Mail it can mean to move the message to Trash
5234 typedef struct _get_flags_data {
5235 Folder *folder;
5236 FolderItem *item;
5237 MsgInfoList *msginfo_list;
5238 GHashTable *msgflags;
5239 gboolean full_search;
5240 gboolean done;
5241 } get_flags_data;
5243 static /*gint*/ void *imap_get_flags_thread(void *data)
5245 get_flags_data *stuff = (get_flags_data *)data;
5246 Folder *folder = stuff->folder;
5247 FolderItem *fitem = (FolderItem *) stuff->item;
5248 MsgInfoList *msginfo_list = stuff->msginfo_list;
5249 GHashTable *msgflags = stuff->msgflags;
5250 GSList *elem;
5251 carray * lep_uidtab;
5252 IMAPSession *session;
5253 gint ok;
5254 int r = MAILIMAP_NO_ERROR;
5255 GHashTable *flags_hash = NULL;
5256 GHashTable *tags_hash = NULL;
5257 gboolean full_search = stuff->full_search;
5258 GSList *sorted_list = NULL;
5259 GSList *unseen = NULL, *answered = NULL, *flagged = NULL, *deleted = NULL, *forwarded = NULL, *spam = NULL;
5260 GSList *seq_list, *cur;
5261 gboolean reverse_seen = FALSE;
5262 gboolean selected_folder;
5263 gint exists_cnt, unseen_cnt;
5264 gboolean got_alien_tags = FALSE;
5266 session = imap_session_get(folder);
5268 if (session == NULL) {
5269 stuff->done = TRUE;
5270 return GINT_TO_POINTER(-1);
5272 selected_folder = (session->mbox != NULL) &&
5273 (!strcmp(session->mbox, fitem->path));
5275 lock_session(session);
5276 if (!selected_folder) {
5277 ok = imap_select(session, IMAP_FOLDER(folder), fitem,
5278 &exists_cnt, NULL, &unseen_cnt, NULL, NULL, TRUE);
5279 if (ok != MAILIMAP_NO_ERROR) {
5280 stuff->done = TRUE;
5281 return GINT_TO_POINTER(-1);
5284 if (unseen_cnt > exists_cnt / 2)
5285 reverse_seen = TRUE;
5287 else {
5288 if (fitem->unread_msgs > fitem->total_msgs / 2)
5289 reverse_seen = TRUE;
5292 sorted_list = g_slist_sort(g_slist_copy(msginfo_list), compare_msginfo);
5293 if (!full_search) {
5294 seq_list = imap_get_lep_set_from_msglist(IMAP_FOLDER(folder), msginfo_list);
5295 } else {
5296 struct mailimap_set * set;
5297 set = mailimap_set_new_interval(1, 0);
5298 seq_list = g_slist_append(NULL, set);
5301 if (folder->account && folder->account->low_bandwidth) {
5302 for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
5303 struct mailimap_set * imapset;
5304 clist * lep_uidlist;
5305 int r;
5307 imapset = cur->data;
5308 if (reverse_seen) {
5309 r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_SEEN, NULL,
5310 NULL, full_search ? NULL:imapset, &lep_uidlist);
5312 else {
5313 r = imap_threaded_search(folder,
5314 IMAP_SEARCH_TYPE_UNSEEN, NULL,
5315 NULL, full_search ? NULL:imapset, &lep_uidlist);
5317 if (r == MAILIMAP_NO_ERROR) {
5318 GSList * uidlist;
5320 uidlist = imap_uid_list_from_lep(lep_uidlist, NULL);
5321 mailimap_search_result_free(lep_uidlist);
5323 unseen = g_slist_concat(unseen, uidlist);
5324 } else {
5325 imap_handle_error(SESSION(session), NULL, r);
5326 goto bail;
5329 r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_FLAGGED, NULL,
5330 NULL, full_search ? NULL:imapset, &lep_uidlist);
5331 if (r == MAILIMAP_NO_ERROR) {
5332 GSList * uidlist;
5334 uidlist = imap_uid_list_from_lep(lep_uidlist, NULL);
5335 mailimap_search_result_free(lep_uidlist);
5337 flagged = g_slist_concat(flagged, uidlist);
5338 } else {
5339 imap_handle_error(SESSION(session), NULL, r);
5340 goto bail;
5343 if (fitem->opened || fitem->processing_pending || fitem == folder->inbox) {
5344 r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_ANSWERED, NULL,
5345 NULL, full_search ? NULL:imapset, &lep_uidlist);
5346 if (r == MAILIMAP_NO_ERROR) {
5347 GSList * uidlist;
5349 uidlist = imap_uid_list_from_lep(lep_uidlist, NULL);
5350 mailimap_search_result_free(lep_uidlist);
5352 answered = g_slist_concat(answered, uidlist);
5353 } else {
5354 imap_handle_error(SESSION(session), NULL, r);
5355 goto bail;
5358 if (flag_ok(IMAP_FOLDER_ITEM(fitem), IMAP_FLAG_FORWARDED)) {
5359 r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_FORWARDED, NULL,
5360 NULL, full_search ? NULL:imapset, &lep_uidlist);
5361 if (r == MAILIMAP_NO_ERROR) {
5362 GSList * uidlist;
5364 uidlist = imap_uid_list_from_lep(lep_uidlist, NULL);
5365 mailimap_search_result_free(lep_uidlist);
5367 forwarded = g_slist_concat(forwarded, uidlist);
5368 } else {
5369 imap_handle_error(SESSION(session), NULL, r);
5370 goto bail;
5374 if (flag_ok(IMAP_FOLDER_ITEM(fitem), IMAP_FLAG_SPAM)) {
5375 r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_SPAM, NULL,
5376 NULL, full_search ? NULL:imapset, &lep_uidlist);
5377 if (r == MAILIMAP_NO_ERROR) {
5378 GSList * uidlist;
5380 uidlist = imap_uid_list_from_lep(lep_uidlist, NULL);
5381 mailimap_search_result_free(lep_uidlist);
5383 spam = g_slist_concat(spam, uidlist);
5384 } else {
5385 imap_handle_error(SESSION(session), NULL, r);
5386 goto bail;
5390 r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_DELETED, NULL,
5391 NULL, full_search ? NULL:imapset, &lep_uidlist);
5392 if (r == MAILIMAP_NO_ERROR) {
5393 GSList * uidlist;
5395 uidlist = imap_uid_list_from_lep(lep_uidlist, NULL);
5396 mailimap_search_result_free(lep_uidlist);
5398 deleted = g_slist_concat(deleted, uidlist);
5399 } else {
5400 imap_handle_error(SESSION(session), NULL, r);
5401 goto bail;
5406 } else {
5407 r = imap_threaded_fetch_uid_flags(folder, 1, &lep_uidtab);
5408 if (r == MAILIMAP_NO_ERROR) {
5409 flags_hash = g_hash_table_new_full(g_direct_hash, g_direct_equal, NULL, NULL);
5410 tags_hash = g_hash_table_new_full(g_direct_hash, g_direct_equal, NULL, NULL);
5411 imap_flags_hash_from_lep_uid_flags_tab(lep_uidtab, flags_hash, tags_hash);
5412 imap_fetch_uid_flags_list_free(lep_uidtab);
5413 } else {
5414 imap_handle_error(SESSION(session), NULL, r);
5415 goto bail;
5419 bail:
5420 if (r == MAILIMAP_NO_ERROR)
5421 unlock_session(session);
5423 for (elem = sorted_list; elem != NULL; elem = g_slist_next(elem)) {
5424 MsgInfo *msginfo;
5425 MsgPermFlags flags, oldflags;
5426 gboolean wasnew;
5428 msginfo = (MsgInfo *) elem->data;
5429 flags = msginfo->flags.perm_flags;
5430 wasnew = (flags & MSG_NEW);
5431 oldflags = flags & ~(MSG_NEW|MSG_UNREAD|MSG_REPLIED|MSG_FORWARDED|MSG_MARKED|MSG_DELETED|MSG_SPAM);
5433 if (folder->account && folder->account->low_bandwidth) {
5434 if (fitem->opened || fitem->processing_pending || fitem == folder->inbox) {
5435 flags &= ~((reverse_seen ? 0 : MSG_UNREAD | MSG_NEW) | MSG_REPLIED | MSG_FORWARDED | MSG_MARKED | MSG_SPAM);
5436 } else {
5437 flags &= ~((reverse_seen ? 0 : MSG_UNREAD | MSG_NEW | MSG_MARKED));
5439 if (reverse_seen)
5440 flags |= MSG_UNREAD | (wasnew ? MSG_NEW : 0);
5441 if (gslist_find_next_num(&unseen, msginfo->msgnum) == msginfo->msgnum) {
5442 if (!reverse_seen) {
5443 flags |= MSG_UNREAD | (wasnew ? MSG_NEW : 0);
5444 } else {
5445 flags &= ~(MSG_UNREAD | MSG_NEW);
5449 if (gslist_find_next_num(&flagged, msginfo->msgnum) == msginfo->msgnum)
5450 flags |= MSG_MARKED;
5451 else
5452 flags &= ~MSG_MARKED;
5454 if (fitem->opened || fitem->processing_pending || fitem == folder->inbox) {
5455 if (gslist_find_next_num(&answered, msginfo->msgnum) == msginfo->msgnum)
5456 flags |= MSG_REPLIED;
5457 else
5458 flags &= ~MSG_REPLIED;
5459 if (gslist_find_next_num(&forwarded, msginfo->msgnum) == msginfo->msgnum)
5460 flags |= MSG_FORWARDED;
5461 else
5462 flags &= ~MSG_FORWARDED;
5463 if (gslist_find_next_num(&spam, msginfo->msgnum) == msginfo->msgnum)
5464 flags |= MSG_SPAM;
5465 else
5466 flags &= ~MSG_SPAM;
5467 if (gslist_find_next_num(&deleted, msginfo->msgnum) == msginfo->msgnum)
5468 flags |= MSG_DELETED;
5469 else
5470 flags &= ~MSG_DELETED;
5472 } else {
5473 if (flags_hash != NULL) {
5475 flags = GPOINTER_TO_INT(g_hash_table_lookup(flags_hash,
5476 GINT_TO_POINTER(msginfo->msgnum)));
5479 if ((flags & MSG_UNREAD) == 0)
5480 flags &= ~MSG_NEW;
5481 else if (wasnew)
5482 flags |= MSG_NEW;
5483 flags |= oldflags;
5485 if (tags_hash != NULL) {
5486 GSList *tags = g_hash_table_lookup(tags_hash, GINT_TO_POINTER(msginfo->msgnum));
5487 GSList *cur;
5489 g_slist_free(msginfo->tags);
5490 msginfo->tags = NULL;
5492 for (cur = tags; cur; cur = cur->next) {
5493 gchar *real_tag = imap_modified_utf7_to_utf8(cur->data, TRUE);
5494 gint id = 0;
5495 id = tags_get_id_for_str(real_tag);
5496 if (id == -1) {
5497 id = tags_add_tag(real_tag);
5498 got_alien_tags = TRUE;
5500 msginfo->tags = g_slist_append(
5501 msginfo->tags,
5502 GINT_TO_POINTER(id));
5503 g_free(real_tag);
5505 slist_free_strings_full(tags);
5509 g_hash_table_insert(msgflags, msginfo, GINT_TO_POINTER(flags));
5512 if (got_alien_tags) {
5513 tags_write_tags();
5514 main_window_reflect_tags_changes(mainwindow_get_mainwindow());
5517 if (flags_hash)
5518 g_hash_table_destroy(flags_hash);
5519 if (tags_hash)
5520 g_hash_table_destroy(tags_hash);
5522 imap_lep_set_free(seq_list);
5523 g_slist_free(flagged);
5524 g_slist_free(deleted);
5525 g_slist_free(answered);
5526 g_slist_free(forwarded);
5527 g_slist_free(spam);
5528 g_slist_free(unseen);
5529 g_slist_free(sorted_list);
5531 stuff->done = TRUE;
5532 return GINT_TO_POINTER(0);
5535 static gint imap_get_flags(Folder *folder, FolderItem *item,
5536 MsgInfoList *msginfo_list, GHashTable *msgflags)
5538 gint result;
5539 get_flags_data *data = g_new0(get_flags_data, 1);
5540 data->done = FALSE;
5541 data->folder = folder;
5542 data->item = item;
5543 data->msginfo_list = msginfo_list;
5544 data->msgflags = msgflags;
5545 data->full_search = FALSE;
5547 GSList *tmp = NULL, *cur;
5549 if (prefs_common.work_offline &&
5550 !inc_offline_should_override(FALSE,
5551 _("Claws Mail needs network access in order "
5552 "to access the IMAP server."))) {
5553 g_free(data);
5554 return -1;
5557 tmp = folder_item_get_msg_list(item);
5559 if (g_slist_length(tmp) <= g_slist_length(msginfo_list))
5560 data->full_search = TRUE;
5562 for (cur = tmp; cur; cur = cur->next)
5563 procmsg_msginfo_free((MsgInfo **)&(cur->data));
5565 g_slist_free(tmp);
5567 result = GPOINTER_TO_INT(imap_get_flags_thread(data));
5569 g_free(data);
5570 return result;
5574 static gboolean process_flags(gpointer key, gpointer value, gpointer user_data)
5576 gboolean flags_set = GPOINTER_TO_INT(user_data);
5577 gint flags_value = GPOINTER_TO_INT(key);
5578 hashtable_data *data = (hashtable_data *)value;
5579 IMAPFolderItem *_item = data->item;
5580 FolderItem *item = (FolderItem *)_item;
5581 gint ok = MAILIMAP_ERROR_BAD_STATE;
5582 IMAPSession *session = NULL;
5584 debug_print("getting session...\n");
5585 session = imap_session_get(item->folder);
5587 data->msglist = g_slist_reverse(data->msglist);
5589 debug_print("IMAP %ssetting flags to %d for %d messages\n",
5590 flags_set?"":"un",
5591 flags_value,
5592 g_slist_length(data->msglist));
5594 lock_session(session);
5595 if (session) {
5596 ok = imap_select(session, IMAP_FOLDER(item->folder), item,
5597 NULL, NULL, NULL, NULL, NULL, FALSE);
5599 if (ok == MAILIMAP_NO_ERROR) {
5600 ok = imap_set_message_flags(session, IMAP_FOLDER_ITEM(item),
5601 data->msglist, flags_value, NULL, flags_set);
5602 } else {
5603 g_warning("can't select mailbox %s", item->path);
5606 if (!is_fatal(ok))
5607 unlock_session(session);
5609 g_slist_free(data->msglist);
5610 g_free(data);
5611 return TRUE;
5614 static gboolean process_tags(gpointer key, gpointer value, gpointer user_data)
5616 gboolean tags_set = GPOINTER_TO_INT(user_data);
5617 TagsData *data = (TagsData *)value;
5618 IMAPFolderItem *_item = data->item;
5619 FolderItem *item = (FolderItem *)_item;
5620 gchar *str = data->str;
5621 gint ok = MAILIMAP_ERROR_BAD_STATE;
5622 IMAPSession *session = NULL;
5624 debug_print("getting session...\n");
5625 session = imap_session_get(item->folder);
5627 data->msglist = g_slist_reverse(data->msglist);
5629 debug_print("IMAP %ssetting tags %s for %d messages\n",
5630 tags_set?"":"un",
5631 str,
5632 g_slist_length(data->msglist));
5634 lock_session(session);
5635 if (session) {
5636 ok = imap_select(session, IMAP_FOLDER(item->folder), item,
5637 NULL, NULL, NULL, NULL, NULL, FALSE);
5639 if (ok == MAILIMAP_NO_ERROR) {
5640 GSList list;
5641 list.data = str;
5642 list.next = NULL;
5643 ok = imap_set_message_flags(session, IMAP_FOLDER_ITEM(item),
5644 data->msglist, 0, &list, tags_set);
5645 } else {
5646 g_warning("can't select mailbox %s", item->path);
5649 if (!is_fatal(ok))
5650 unlock_session(session);
5652 g_slist_free(data->msglist);
5653 g_free(data->str);
5654 g_free(data);
5655 return TRUE;
5658 static void process_hashtable(IMAPFolderItem *item)
5660 if (item->flags_set_table) {
5661 g_hash_table_foreach_remove(item->flags_set_table, process_flags, GINT_TO_POINTER(TRUE));
5662 g_hash_table_destroy(item->flags_set_table);
5663 item->flags_set_table = NULL;
5665 if (item->flags_unset_table) {
5666 g_hash_table_foreach_remove(item->flags_unset_table, process_flags, GINT_TO_POINTER(FALSE));
5667 g_hash_table_destroy(item->flags_unset_table);
5668 item->flags_unset_table = NULL;
5670 if (item->tags_set_table) {
5671 g_hash_table_foreach_remove(item->tags_set_table, process_tags, GINT_TO_POINTER(TRUE));
5672 g_hash_table_destroy(item->tags_set_table);
5673 item->tags_set_table = NULL;
5675 if (item->tags_unset_table) {
5676 g_hash_table_foreach_remove(item->tags_unset_table, process_tags, GINT_TO_POINTER(FALSE));
5677 g_hash_table_destroy(item->tags_unset_table);
5678 item->tags_unset_table = NULL;
5683 static void imap_set_batch (Folder *folder, FolderItem *_item, gboolean batch)
5685 IMAPFolderItem *item = (IMAPFolderItem *)_item;
5686 IMAPSession *session;
5688 g_return_if_fail(item != NULL);
5690 if (item->batching == batch)
5691 return;
5693 if (batch) {
5694 item->batching = TRUE;
5695 debug_print("IMAP switching to batch mode\n");
5696 if (!item->flags_set_table) {
5697 item->flags_set_table = g_hash_table_new(NULL, g_direct_equal);
5699 if (!item->flags_unset_table) {
5700 item->flags_unset_table = g_hash_table_new(NULL, g_direct_equal);
5702 if (!item->tags_set_table) {
5703 item->tags_set_table = g_hash_table_new(NULL, g_direct_equal);
5705 if (!item->tags_unset_table) {
5706 item->tags_unset_table = g_hash_table_new(NULL, g_direct_equal);
5708 session = imap_session_get(folder);
5709 if (session) {
5710 imap_refresh_sensitivity(session);
5711 session->sens_update_block = TRUE;
5713 } else {
5714 debug_print("IMAP switching away from batch mode\n");
5715 /* process stuff */
5716 process_hashtable(item);
5717 item->batching = FALSE;
5718 session = imap_session_get(folder);
5719 if (session) {
5720 session->sens_update_block = FALSE;
5721 imap_refresh_sensitivity(session);
5728 /* data types conversion libetpan <-> claws */
5732 #define ETPAN_IMAP_MB_MARKED 1
5733 #define ETPAN_IMAP_MB_UNMARKED 2
5734 #define ETPAN_IMAP_MB_NOSELECT 4
5735 #define ETPAN_IMAP_MB_NOINFERIORS 8
5737 static int imap_flags_to_flags(struct mailimap_mbx_list_flags * imap_flags)
5739 int flags;
5740 clistiter * cur;
5742 flags = 0;
5743 if (imap_flags->mbf_type == MAILIMAP_MBX_LIST_FLAGS_SFLAG) {
5744 switch (imap_flags->mbf_sflag) {
5745 case MAILIMAP_MBX_LIST_SFLAG_MARKED:
5746 flags |= ETPAN_IMAP_MB_MARKED;
5747 break;
5748 case MAILIMAP_MBX_LIST_SFLAG_NOSELECT:
5749 flags |= ETPAN_IMAP_MB_NOSELECT;
5750 break;
5751 case MAILIMAP_MBX_LIST_SFLAG_UNMARKED:
5752 flags |= ETPAN_IMAP_MB_UNMARKED;
5753 break;
5757 if (imap_flags->mbf_oflags) {
5758 for(cur = clist_begin(imap_flags->mbf_oflags) ; cur != NULL ;
5759 cur = clist_next(cur)) {
5760 struct mailimap_mbx_list_oflag * oflag;
5762 oflag = clist_content(cur);
5764 switch (oflag->of_type) {
5765 case MAILIMAP_MBX_LIST_OFLAG_NOINFERIORS:
5766 flags |= ETPAN_IMAP_MB_NOINFERIORS;
5767 break;
5771 return flags;
5774 static GSList * imap_list_from_lep(IMAPFolder * folder,
5775 clist * list, const gchar * real_path, gboolean all)
5777 clistiter * iter;
5778 GSList * item_list = NULL, *llast = NULL;
5780 if (list) {
5781 for(iter = clist_begin(list) ; iter != NULL ;
5782 iter = clist_next(iter)) {
5783 struct mailimap_mailbox_list * mb;
5784 int flags;
5785 char delimiter;
5786 char * name;
5787 char * dup_name;
5788 gchar * base;
5789 gchar * loc_name;
5790 gchar * loc_path;
5791 FolderItem *new_item;
5793 mb = clist_content(iter);
5795 if (mb == NULL)
5796 continue;
5798 flags = 0;
5799 if (mb->mb_flag != NULL)
5800 flags = imap_flags_to_flags(mb->mb_flag);
5802 delimiter = mb->mb_delimiter;
5803 name = mb->mb_name;
5805 dup_name = strdup(name);
5806 if (delimiter != '\0')
5807 subst_char(dup_name, delimiter, '/');
5809 base = g_path_get_basename(dup_name);
5810 if (base[0] == '.') {
5811 g_free(base);
5812 free(dup_name);
5813 continue;
5815 if (!all && path_cmp(name, real_path) == 0) {
5816 g_free(base);
5817 free(dup_name);
5818 continue;
5821 if (!all && dup_name[strlen(dup_name)-1] == '/') {
5822 g_free(base);
5823 free(dup_name);
5824 continue;
5827 loc_name = imap_modified_utf7_to_utf8(base, FALSE);
5828 loc_path = imap_modified_utf7_to_utf8(dup_name, FALSE);
5830 new_item = folder_item_new(FOLDER(folder), loc_name, loc_path);
5831 if ((flags & ETPAN_IMAP_MB_NOINFERIORS) != 0)
5832 new_item->no_sub = TRUE;
5833 if (strcasecmp(dup_name, "INBOX") != 0 &&
5834 ((flags & ETPAN_IMAP_MB_NOSELECT) != 0))
5835 new_item->no_select = TRUE;
5837 if (item_list == NULL)
5838 llast = item_list = g_slist_append(item_list, new_item);
5839 else {
5840 llast = g_slist_append(llast, new_item);
5841 llast = llast->next;
5843 debug_print("folder '%s' found.\n", loc_path);
5844 g_free(base);
5845 g_free(loc_path);
5846 g_free(loc_name);
5848 free(dup_name);
5851 return item_list;
5854 static GSList * imap_get_lep_set_from_numlist(IMAPFolder *folder, MsgNumberList *numlist)
5856 GSList *sorted_list, *cur;
5857 guint first, last, next;
5858 GSList *ret_list = NULL, *llast = NULL;
5859 struct mailimap_set * current_set;
5860 unsigned int item_count;
5862 if (numlist == NULL)
5863 return NULL;
5865 current_set = mailimap_set_new_empty();
5867 sorted_list = g_slist_copy(numlist);
5868 sorted_list = g_slist_sort(sorted_list, g_int_compare);
5870 first = GPOINTER_TO_INT(sorted_list->data);
5872 item_count = 0;
5873 for (cur = sorted_list; cur != NULL; cur = g_slist_next(cur)) {
5874 if (GPOINTER_TO_INT(cur->data) == 0)
5875 continue;
5877 item_count ++;
5879 last = GPOINTER_TO_INT(cur->data);
5880 if (cur->next)
5881 next = GPOINTER_TO_INT(cur->next->data);
5882 else
5883 next = 0;
5885 if (last + 1 != next || next == 0 || item_count >= folder->max_set_size) {
5887 struct mailimap_set_item * item;
5888 item = mailimap_set_item_new(first, last);
5889 mailimap_set_add(current_set, item);
5891 first = next;
5893 if (item_count >= folder->max_set_size) {
5894 if (ret_list == NULL)
5895 llast = ret_list = g_slist_append(ret_list,
5896 current_set);
5897 else {
5898 llast = g_slist_append(llast, current_set);
5899 llast = llast->next;
5902 current_set = mailimap_set_new_empty();
5903 item_count = 0;
5908 if (clist_count(current_set->set_list) > 0) {
5909 ret_list = g_slist_append(ret_list,
5910 current_set);
5913 g_slist_free(sorted_list);
5915 return ret_list;
5918 static GSList * imap_get_lep_set_from_msglist(IMAPFolder *folder, MsgInfoList *msglist)
5920 MsgNumberList *numlist = NULL;
5921 GSList *seq_list;
5923 numlist = procmsg_get_number_list_for_msgs(msglist);
5925 seq_list = imap_get_lep_set_from_numlist(folder, numlist);
5926 g_slist_free(numlist);
5928 return seq_list;
5931 static GSList * imap_uid_list_from_lep(clist * list, gint* length)
5933 clistiter * iter;
5934 GSList * result;
5935 gint len = 0;
5937 result = NULL;
5939 if (list) {
5940 for(iter = clist_begin(list) ; iter != NULL ;
5941 iter = clist_next(iter)) {
5942 uint32_t * puid;
5944 puid = clist_content(iter);
5945 result = g_slist_prepend(result, GINT_TO_POINTER(* puid));
5946 len++;
5948 result = g_slist_reverse(result);
5950 if (length)
5951 *length = len;
5952 return result;
5955 static GSList * imap_uid_list_from_lep_tab(carray * list)
5957 unsigned int i;
5958 GSList * result;
5960 result = NULL;
5962 for(i = 0 ; i < carray_count(list) ; i ++) {
5963 uint32_t * puid;
5965 puid = carray_get(list, i);
5966 result = g_slist_prepend(result, GINT_TO_POINTER(* puid));
5968 result = g_slist_reverse(result);
5969 return result;
5972 static void imap_flags_hash_from_lep_uid_flags_tab(carray * list,
5973 GHashTable * hash,
5974 GHashTable * tags_hash)
5976 unsigned int i;
5978 for(i = 0 ; i < carray_count(list) ; i += 3) {
5979 uint32_t * puid;
5980 int * pflags;
5981 GSList *tags;
5983 puid = carray_get(list, i);
5984 pflags = carray_get(list, i + 1);
5985 tags = carray_get(list, i + 2);
5987 g_hash_table_insert(hash, GINT_TO_POINTER(*puid), GINT_TO_POINTER(* pflags));
5988 g_hash_table_insert(tags_hash, GINT_TO_POINTER(*puid), tags);
5992 static MsgInfo *imap_envelope_from_lep(struct imap_fetch_env_info * info,
5993 FolderItem *item)
5995 MsgInfo *msginfo = NULL;
5996 guint32 uid = 0;
5997 goffset size = 0;
5998 MsgFlags flags = {0, 0};
6000 if (info->headers == NULL)
6001 return NULL;
6003 MSG_SET_TMP_FLAGS(flags, MSG_IMAP);
6004 if (folder_has_parent_of_type(item, F_QUEUE)) {
6005 MSG_SET_TMP_FLAGS(flags, MSG_QUEUED);
6006 } else if (folder_has_parent_of_type(item, F_DRAFT)) {
6007 MSG_SET_TMP_FLAGS(flags, MSG_DRAFT);
6009 flags.perm_flags = info->flags;
6011 uid = info->uid;
6012 size = (goffset) info->size;
6013 msginfo = procheader_parse_str(info->headers, flags, FALSE, FALSE);
6015 if (msginfo) {
6016 msginfo->msgnum = uid;
6017 msginfo->size = size;
6020 return msginfo;
6023 static void imap_lep_set_free(GSList *seq_list)
6025 GSList * cur;
6027 for(cur = seq_list ; cur != NULL ; cur = g_slist_next(cur)) {
6028 struct mailimap_set * imapset;
6030 imapset = cur->data;
6031 mailimap_set_free(imapset);
6033 g_slist_free(seq_list);
6036 static struct mailimap_flag_list * imap_flag_to_lep(IMAPFolderItem *item, IMAPFlags flags, GSList *tags)
6038 struct mailimap_flag_list * flag_list;
6039 GSList *cur = tags;
6041 flag_list = mailimap_flag_list_new_empty();
6043 if (IMAP_IS_SEEN(flags))
6044 mailimap_flag_list_add(flag_list,
6045 mailimap_flag_new_seen());
6046 if (IMAP_IS_ANSWERED(flags))
6047 mailimap_flag_list_add(flag_list,
6048 mailimap_flag_new_answered());
6049 if (IMAP_IS_FLAGGED(flags))
6050 mailimap_flag_list_add(flag_list,
6051 mailimap_flag_new_flagged());
6052 if (IMAP_IS_DELETED(flags))
6053 mailimap_flag_list_add(flag_list,
6054 mailimap_flag_new_deleted());
6055 if (IMAP_IS_DRAFT(flags))
6056 mailimap_flag_list_add(flag_list,
6057 mailimap_flag_new_draft());
6058 if (IMAP_IS_FORWARDED(flags) && flag_ok(item, IMAP_FLAG_FORWARDED))
6059 mailimap_flag_list_add(flag_list,
6060 mailimap_flag_new_flag_keyword(strdup(RTAG_FORWARDED)));
6061 if (IMAP_IS_SPAM(flags) && flag_ok(item, IMAP_FLAG_SPAM))
6062 mailimap_flag_list_add(flag_list,
6063 mailimap_flag_new_flag_keyword(strdup(RTAG_JUNK)));
6064 else if (IMAP_IS_HAM(flags) && flag_ok(item, IMAP_FLAG_HAM))
6065 mailimap_flag_list_add(flag_list,
6066 mailimap_flag_new_flag_keyword(strdup(RTAG_NON_JUNK)));
6068 for (; cur; cur = cur->next) {
6069 gchar *enc_str =
6070 imap_utf8_to_modified_utf7(cur->data, TRUE);
6071 g_strstrip(enc_str);
6073 mailimap_flag_list_add(flag_list,
6074 mailimap_flag_new_flag_keyword(enc_str));
6077 return flag_list;
6080 guint imap_folder_get_refcnt(Folder *folder)
6082 return ((IMAPFolder *)folder)->refcnt;
6085 void imap_folder_ref(Folder *folder)
6087 ((IMAPFolder *)folder)->refcnt++;
6090 void imap_disconnect_all(gboolean have_connectivity)
6092 GList *list;
6093 gboolean short_timeout;
6094 #ifdef HAVE_NETWORKMANAGER_SUPPORT
6095 GError *error = NULL;
6097 short_timeout = !networkmanager_is_online(&error);
6098 if(error) {
6099 short_timeout = TRUE;
6100 g_error_free(error);
6102 #else
6103 short_timeout = TRUE;
6104 #endif
6106 if(short_timeout)
6107 imap_main_set_timeout(1);
6109 for (list = account_get_list(); list != NULL; list = list->next) {
6110 PrefsAccount *account = list->data;
6111 if (account->protocol == A_IMAP4) {
6112 RemoteFolder *folder = (RemoteFolder *)account->folder;
6113 if (folder && folder->session) {
6114 if (imap_is_busy(FOLDER(folder)))
6115 imap_threaded_cancel(FOLDER(folder));
6117 IMAPSession *session = (IMAPSession *)folder->session;
6118 if (have_connectivity)
6119 imap_threaded_disconnect(FOLDER(folder));
6120 SESSION(session)->state = SESSION_DISCONNECTED;
6121 SESSION(session)->sock = NULL;
6122 imap_safe_destroy(session);
6123 folder->session = NULL;
6128 if(short_timeout)
6129 imap_main_set_timeout(prefs_common.io_timeout_secs);
6132 void imap_folder_unref(Folder *folder)
6134 if (((IMAPFolder *)folder)->refcnt > 0)
6135 ((IMAPFolder *)folder)->refcnt--;
6138 void imap_cancel_all(void)
6140 GList *folderlist;
6141 GList *cur;
6143 folderlist = folder_get_list();
6144 for (cur = folderlist; cur != NULL; cur = g_list_next(cur)) {
6145 Folder *folder = (Folder *) cur->data;
6147 if (folder->klass == &imap_class) {
6148 if (imap_is_busy(folder)) {
6149 IMAPSession *imap_session;
6150 RemoteFolder *rfolder;
6152 g_printerr("cancelled\n");
6153 imap_threaded_cancel(folder);
6154 rfolder = (RemoteFolder *) folder;
6155 imap_session = (IMAPSession *) rfolder->session;
6156 if (imap_session)
6157 imap_session->cancelled = 1;
6163 gboolean imap_cancel_all_enabled(void)
6165 GList *folderlist;
6166 GList *cur;
6168 folderlist = folder_get_list();
6169 for (cur = folderlist; cur != NULL; cur = g_list_next(cur)) {
6170 Folder *folder = (Folder *) cur->data;
6172 if (folder->klass == &imap_class) {
6173 if (imap_is_busy(folder)) {
6174 return TRUE;
6179 return FALSE;
6182 static gboolean imap_is_busy(Folder *folder)
6184 IMAPSession *imap_session;
6185 RemoteFolder *rfolder;
6187 rfolder = (RemoteFolder *) folder;
6188 imap_session = (IMAPSession *) rfolder->session;
6189 if (imap_session == NULL)
6190 return FALSE;
6192 return imap_session->busy;
6195 #else /* HAVE_LIBETPAN */
6197 static FolderClass imap_class;
6199 static XMLTag *imap_item_get_xml(Folder *folder, FolderItem *item);
6200 static void imap_item_set_xml(Folder *folder, FolderItem *item, XMLTag *tag);
6202 static Folder *imap_folder_new (const gchar *name,
6203 const gchar *path)
6205 static gboolean missing_imap_warning = TRUE;
6206 if (missing_imap_warning) {
6207 missing_imap_warning = FALSE;
6208 alertpanel_error(
6209 _("You have one or more IMAP accounts "
6210 "defined. However this version of "
6211 "Claws Mail has been built without "
6212 "IMAP support; your IMAP accounts are "
6213 "disabled.\n\n"
6214 "You probably need to "
6215 "install libetpan and recompile "
6216 "Claws Mail."));
6218 return NULL;
6220 static gint imap_create_tree (Folder *folder)
6222 return -1;
6224 static FolderItem *imap_create_folder (Folder *folder,
6225 FolderItem *parent,
6226 const gchar *name)
6228 return NULL;
6230 static gint imap_rename_folder (Folder *folder,
6231 FolderItem *item,
6232 const gchar *name)
6234 return -1;
6237 gchar imap_get_path_separator_for_item(FolderItem *item)
6239 return '/';
6242 FolderClass *imap_get_class(void)
6244 if (imap_class.idstr == NULL) {
6245 imap_class.type = F_IMAP;
6246 imap_class.idstr = "imap";
6247 imap_class.uistr = "IMAP";
6249 imap_class.new_folder = imap_folder_new;
6250 imap_class.create_tree = imap_create_tree;
6251 imap_class.create_folder = imap_create_folder;
6252 imap_class.rename_folder = imap_rename_folder;
6254 imap_class.set_xml = folder_set_xml;
6255 imap_class.get_xml = folder_get_xml;
6256 imap_class.item_set_xml = imap_item_set_xml;
6257 imap_class.item_get_xml = imap_item_get_xml;
6258 /* nothing implemented */
6261 return &imap_class;
6264 void imap_disconnect_all(gboolean have_connectivity)
6268 gint imap_subscribe(Folder *folder, FolderItem *item, gchar *rpath, gboolean sub)
6270 return -1;
6273 GList * imap_scan_subtree(Folder *folder, FolderItem *item, gboolean unsubs_only, gboolean recursive)
6275 return NULL;
6278 void imap_cache_msg(FolderItem *item, gint msgnum)
6282 void imap_cancel_all(void)
6286 gboolean imap_cancel_all_enabled(void)
6288 return FALSE;
6291 #endif
6293 #ifdef HAVE_LIBETPAN
6294 static void imap_synchronise(FolderItem *item, gint days)
6296 if (IMAP_FOLDER_ITEM(item)->last_sync == IMAP_FOLDER_ITEM(item)->last_change) {
6297 debug_print("%s already synced\n", item->path?item->path:item->name);
6298 return;
6300 debug_print("syncing %s\n", item->path?item->path:item->name);
6301 imap_gtk_synchronise(item, days);
6302 IMAP_FOLDER_ITEM(item)->last_sync = IMAP_FOLDER_ITEM(item)->last_change;
6304 #endif
6306 static void imap_item_set_xml(Folder *folder, FolderItem *item, XMLTag *tag)
6308 #ifdef HAVE_LIBETPAN
6309 GList *cur;
6310 #endif
6311 folder_item_set_xml(folder, item, tag);
6313 #ifdef HAVE_LIBETPAN
6314 for (cur = tag->attr; cur != NULL; cur = g_list_next(cur)) {
6315 XMLAttr *attr = (XMLAttr *) cur->data;
6317 if (!attr || !attr->name || !attr->value) continue;
6318 if (!strcmp(attr->name, "uidnext"))
6319 IMAP_FOLDER_ITEM(item)->uid_next = atoi(attr->value);
6320 if (!strcmp(attr->name, "last_sync"))
6321 IMAP_FOLDER_ITEM(item)->last_sync = atoi(attr->value);
6322 if (!strcmp(attr->name, "last_change"))
6323 IMAP_FOLDER_ITEM(item)->last_change = atoi(attr->value);
6325 if (IMAP_FOLDER_ITEM(item)->last_change == 0)
6326 IMAP_FOLDER_ITEM(item)->last_change = time(NULL);
6327 #endif
6330 static XMLTag *imap_item_get_xml(Folder *folder, FolderItem *item)
6332 XMLTag *tag;
6334 tag = folder_item_get_xml(folder, item);
6336 #ifdef HAVE_LIBETPAN
6337 xml_tag_add_attr(tag, xml_attr_new_int("uidnext",
6338 IMAP_FOLDER_ITEM(item)->uid_next));
6339 xml_tag_add_attr(tag, xml_attr_new_int("last_sync",
6340 IMAP_FOLDER_ITEM(item)->last_sync));
6341 xml_tag_add_attr(tag, xml_attr_new_int("last_change",
6342 IMAP_FOLDER_ITEM(item)->last_change));
6344 #endif
6345 return tag;
6348 /* ===================================================================
6349 * UTF-7 conversion routines as in RFC 2192
6350 * ===================================================================
6351 * These two functions from:
6352 * libimap library.
6353 * Copyright (C) 2003-2004 Pawel Salek. */
6355 /* UTF7 modified base64 alphabet */
6356 static char base64chars[] =
6357 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+,";
6358 #define UNDEFINED 64
6360 /* UTF16 definitions */
6361 #define UTF16MASK 0x03FFUL
6362 #define UTF16SHIFT 10
6363 #define UTF16BASE 0x10000UL
6364 #define UTF16HIGHSTART 0xD800UL
6365 #define UTF16HIGHEND 0xDBFFUL
6366 #define UTF16LOSTART 0xDC00UL
6367 #define UTF16LOEND 0xDFFFUL
6370 /* Convert an IMAP mailbox to a UTF-8 string.
6371 * dst needs to have roughly 4 times the storage space of src
6372 * Hex encoding can triple the size of the input
6373 * UTF-7 can be slightly denser than UTF-8
6374 * (worst case: 8 octets UTF-7 becomes 9 octets UTF-8)
6376 char* imap_modified_utf7_to_utf8(const char *mbox, gboolean change_spaces)
6378 unsigned c, i, bitcount;
6379 unsigned long ucs4, utf16, bitbuf;
6380 unsigned char base64[256];
6381 const char *src;
6382 char *dst, *res = g_malloc(2*strlen(mbox)+1);
6384 dst = res;
6385 src = mbox;
6386 if(!dst) return NULL;
6387 /* initialize modified base64 decoding table */
6388 memset(base64, UNDEFINED, sizeof (base64));
6389 for (i = 0; i < sizeof (base64chars); ++i) {
6390 base64[(unsigned)base64chars[i]] = i;
6393 /* loop until end of string */
6394 while (*src != '\0') {
6395 c = *src++;
6396 /* deal with literal characters and &- */
6397 if (c != '&' || *src == '-') {
6398 /* encode literally */
6399 if (change_spaces && c == '_')
6400 *dst++ = ' ';
6401 else
6402 *dst++ = c;
6403 /* skip over the '-' if this is an &- sequence */
6404 if (c == '&') ++src;
6405 } else {
6406 /* convert modified UTF-7 -> UTF-16 -> UCS-4 -> UTF-8 -> HEX */
6407 bitbuf = 0;
6408 bitcount = 0;
6409 ucs4 = 0;
6410 while ((c = base64[(unsigned char) *src]) != UNDEFINED) {
6411 ++src;
6412 bitbuf = (bitbuf << 6) | c;
6413 bitcount += 6;
6414 /* enough bits for a UTF-16 character? */
6415 if (bitcount >= 16) {
6416 bitcount -= 16;
6417 utf16 = (bitcount ? bitbuf >> bitcount
6418 : bitbuf) & 0xffff;
6419 /* convert UTF16 to UCS4 */
6421 (utf16 >= UTF16HIGHSTART && utf16 <= UTF16HIGHEND) {
6422 ucs4 = (utf16 - UTF16HIGHSTART) << UTF16SHIFT;
6423 continue;
6424 } else if
6425 (utf16 >= UTF16LOSTART && utf16 <= UTF16LOEND) {
6426 ucs4 += utf16 - UTF16LOSTART + UTF16BASE;
6427 } else {
6428 ucs4 = utf16;
6431 /* convert UTF-16 range of UCS4 to UTF-8 */
6432 if (ucs4 <= 0x7fUL) {
6433 dst[0] = ucs4;
6434 dst += 1;
6435 } else if (ucs4 <= 0x7ffUL) {
6436 dst[0] = 0xc0 | (ucs4 >> 6);
6437 dst[1] = 0x80 | (ucs4 & 0x3f);
6438 dst += 2;
6439 } else if (ucs4 <= 0xffffUL) {
6440 dst[0] = 0xe0 | (ucs4 >> 12);
6441 dst[1] = 0x80 | ((ucs4 >> 6) & 0x3f);
6442 dst[2] = 0x80 | (ucs4 & 0x3f);
6443 dst += 3;
6444 } else {
6445 dst[0] = 0xf0 | (ucs4 >> 18);
6446 dst[1] = 0x80 | ((ucs4 >> 12) & 0x3f);
6447 dst[2] = 0x80 | ((ucs4 >> 6) & 0x3f);
6448 dst[3] = 0x80 | (ucs4 & 0x3f);
6449 dst += 4;
6453 /* skip over trailing '-' in modified UTF-7 encoding */
6454 if (*src == '-') ++src;
6457 /* terminate destination string */
6458 *dst = '\0';
6459 return res;
6462 /* Convert hex coded UTF-8 string to modified UTF-7 IMAP mailbox
6463 * dst should be about twice the length of src to deal with non-hex
6464 * coded URLs
6466 char* imap_utf8_to_modified_utf7(const char *src, gboolean change_spaces)
6468 unsigned int utf8pos, utf8total, c, utf7mode, bitstogo, utf16flag;
6469 unsigned long ucs4 = 0, bitbuf = 0;
6471 /* initialize hex lookup table */
6472 char *dst, *res;
6474 if (!src) return NULL;
6476 res = malloc(2*strlen(src)+1);
6477 dst = res;
6478 if(!dst) return NULL;
6480 utf7mode = 0;
6481 utf8total = 0;
6482 bitstogo = 0;
6483 utf8pos = 0;
6484 while ((c = (unsigned char)*src) != '\0') {
6485 ++src;
6486 /* normal character? */
6487 if (c >= ' ' && c <= '~' && (c != '_' || !change_spaces)) {
6488 /* switch out of UTF-7 mode */
6489 if (utf7mode) {
6490 if (bitstogo) {
6491 *dst++ = base64chars[(bitbuf << (6 - bitstogo)) & 0x3F];
6493 *dst++ = '-';
6494 utf7mode = 0;
6495 utf8pos = 0;
6496 bitstogo = 0;
6497 utf8total= 0;
6499 if (change_spaces && c == ' ')
6500 *dst++ = '_';
6501 else
6502 *dst++ = c;
6503 /* encode '&' as '&-' */
6504 if (c == '&') {
6505 *dst++ = '-';
6507 continue;
6509 /* switch to UTF-7 mode */
6510 if (!utf7mode) {
6511 *dst++ = '&';
6512 utf7mode = 1;
6514 /* Encode US-ASCII characters as themselves */
6515 if (c < 0x80) {
6516 ucs4 = c;
6517 } else if (utf8total) {
6518 /* save UTF8 bits into UCS4 */
6519 ucs4 = (ucs4 << 6) | (c & 0x3FUL);
6520 if (++utf8pos < utf8total) {
6521 continue;
6523 } else {
6524 utf8pos = 1;
6525 if (c < 0xE0) {
6526 utf8total = 2;
6527 ucs4 = c & 0x1F;
6528 } else if (c < 0xF0) {
6529 utf8total = 3;
6530 ucs4 = c & 0x0F;
6531 } else {
6532 /* NOTE: can't convert UTF8 sequences longer than 4 */
6533 utf8total = 4;
6534 ucs4 = c & 0x03;
6536 continue;
6538 /* loop to split ucs4 into two utf16 chars if necessary */
6539 utf8total = 0;
6540 do {
6541 if (ucs4 >= UTF16BASE) {
6542 ucs4 -= UTF16BASE;
6543 bitbuf = (bitbuf << 16) | ((ucs4 >> UTF16SHIFT)
6544 + UTF16HIGHSTART);
6545 ucs4 = (ucs4 & UTF16MASK) + UTF16LOSTART;
6546 utf16flag = 1;
6547 } else {
6548 bitbuf = (bitbuf << 16) | ucs4;
6549 utf16flag = 0;
6551 bitstogo += 16;
6552 /* spew out base64 */
6553 while (bitstogo >= 6) {
6554 bitstogo -= 6;
6555 *dst++ = base64chars[(bitstogo ? (bitbuf >> bitstogo)
6556 : bitbuf)
6557 & 0x3F];
6559 } while (utf16flag);
6561 /* if in UTF-7 mode, finish in ASCII */
6562 if (utf7mode) {
6563 if (bitstogo) {
6564 *dst++ = base64chars[(bitbuf << (6 - bitstogo)) & 0x3F];
6566 *dst++ = '-';
6568 /* tie off string */
6569 *dst = '\0';
6570 return res;