change labels, remove empty lines, show phishing warning on copy
[claws.git] / src / imap.c
blob93fd8e3b56f162e6bd018766c6b3aeb942bd8042
1 /*
2 * Claws Mail -- a GTK+ based, lightweight, and fast e-mail client
3 * Copyright (C) 1999-2020 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 <dirent.h>
40 #include <unistd.h>
41 #include <ctype.h>
42 #include <time.h>
43 #include <errno.h>
44 #if HAVE_ICONV
45 # include <iconv.h>
46 #endif
48 #ifdef USE_GNUTLS
49 # include "ssl.h"
50 #endif
52 #include "folder.h"
53 #include "session.h"
54 #include "procmsg.h"
55 #include "socket.h"
56 #include "recv.h"
57 #include "procheader.h"
58 #include "prefs_account.h"
59 #include "codeconv.h"
60 #include "md5.h"
61 #include "utils.h"
62 #include "prefs_common.h"
63 #include "inputdialog.h"
64 #include "log.h"
65 #include "remotefolder.h"
66 #include "claws.h"
67 #include "statusbar.h"
68 #include "msgcache.h"
69 #include "imap-thread.h"
70 #include "account.h"
71 #include "tags.h"
72 #include "main.h"
73 #include "passwordstore.h"
74 #include "file-utils.h"
75 #include "oauth2.h"
77 typedef struct _IMAPFolder IMAPFolder;
78 typedef struct _IMAPSession IMAPSession;
79 typedef struct _IMAPNameSpace IMAPNameSpace;
80 typedef struct _IMAPFolderItem IMAPFolderItem;
82 #define IMAP_FOLDER(obj) ((IMAPFolder *)obj)
83 #define IMAP_FOLDER_ITEM(obj) ((IMAPFolderItem *)obj)
84 #define IMAP_SESSION(obj) ((IMAPSession *)obj)
86 struct _IMAPFolder
88 RemoteFolder rfolder;
90 /* list of IMAPNameSpace */
91 GList *ns_personal;
92 GList *ns_others;
93 GList *ns_shared;
94 gchar last_seen_separator;
95 guint refcnt;
96 guint max_set_size;
97 gchar *search_charset;
98 gboolean search_charset_supported;
101 struct _IMAPSession
103 Session session;
105 gboolean authenticated;
107 GSList *capability;
108 gboolean uidplus;
110 gchar *mbox;
111 guint cmd_count;
113 /* CLAWS */
114 gboolean folder_content_changed;
115 guint exists;
116 guint recent;
117 guint expunge;
118 guint unseen;
119 guint uid_validity;
120 guint uid_next;
122 Folder * folder;
123 gboolean busy;
124 gboolean cancelled;
125 gboolean sens_update_block;
126 gboolean do_destroy;
128 gint scan_tree_recurs_depth;
131 struct _IMAPNameSpace
133 gchar *name;
134 gchar separator;
137 #define IMAPBUFSIZE 8192
139 #define IMAP_IS_SEEN(flags) ((flags & IMAP_FLAG_SEEN) != 0)
140 #define IMAP_IS_ANSWERED(flags) ((flags & IMAP_FLAG_ANSWERED) != 0)
141 #define IMAP_IS_FLAGGED(flags) ((flags & IMAP_FLAG_FLAGGED) != 0)
142 #define IMAP_IS_DELETED(flags) ((flags & IMAP_FLAG_DELETED) != 0)
143 #define IMAP_IS_DRAFT(flags) ((flags & IMAP_FLAG_DRAFT) != 0)
144 #define IMAP_IS_FORWARDED(flags) ((flags & IMAP_FLAG_FORWARDED) != 0)
145 #define IMAP_IS_SPAM(flags) ((flags & IMAP_FLAG_SPAM) != 0)
146 #define IMAP_IS_HAM(flags) ((flags & IMAP_FLAG_HAM) != 0)
149 #define IMAP4_PORT 143
150 #ifdef USE_GNUTLS
151 #define IMAPS_PORT 993
152 #endif
154 #define IMAP_CMD_LIMIT 1000
156 enum {
157 ITEM_CAN_CREATE_FLAGS_UNKNOWN = 0,
158 ITEM_CAN_CREATE_FLAGS,
159 ITEM_CANNOT_CREATE_FLAGS
162 struct _IMAPFolderItem
164 FolderItem item;
166 guint lastuid;
167 guint uid_next;
168 GSList *uid_list;
169 gboolean batching;
171 GHashTable *flags_set_table;
172 GHashTable *flags_unset_table;
173 guint32 last_change;
174 guint32 last_sync;
175 gboolean should_update;
176 gboolean should_trash_cache;
177 gint can_create_flags;
179 GHashTable *tags_set_table;
180 GHashTable *tags_unset_table;
181 GSList *ok_flags;
185 static XMLTag *imap_item_get_xml(Folder *folder, FolderItem *item);
186 static void imap_item_set_xml(Folder *folder, FolderItem *item, XMLTag *tag);
188 static void imap_folder_init (Folder *folder,
189 const gchar *name,
190 const gchar *path);
192 static Folder *imap_folder_new (const gchar *name,
193 const gchar *path);
194 static void imap_folder_destroy (Folder *folder);
196 static IMAPSession *imap_session_new (Folder *folder,
197 const PrefsAccount *account);
198 static gint imap_session_authenticate(IMAPSession *session,
199 PrefsAccount *account);
200 static void imap_session_destroy (Session *session);
202 static gchar *imap_fetch_msg (Folder *folder,
203 FolderItem *item,
204 gint uid);
205 static gchar *imap_fetch_msg_full (Folder *folder,
206 FolderItem *item,
207 gint uid,
208 gboolean headers,
209 gboolean body);
210 static void imap_remove_cached_msg (Folder *folder,
211 FolderItem *item,
212 MsgInfo *msginfo);
213 static gint imap_add_msg (Folder *folder,
214 FolderItem *dest,
215 const gchar *file,
216 MsgFlags *flags);
217 static gint imap_add_msgs (Folder *folder,
218 FolderItem *dest,
219 GSList *file_list,
220 GHashTable *relation);
222 static gint imap_copy_msg (Folder *folder,
223 FolderItem *dest,
224 MsgInfo *msginfo);
225 static gint imap_copy_msgs (Folder *folder,
226 FolderItem *dest,
227 MsgInfoList *msglist,
228 GHashTable *relation);
230 static gint search_msgs (Folder *folder,
231 FolderItem *container,
232 MsgNumberList **msgs,
233 gboolean *on_server,
234 MatcherList *predicate,
235 SearchProgressNotify progress_cb,
236 gpointer progress_data);
238 static gint imap_remove_msg (Folder *folder,
239 FolderItem *item,
240 gint uid);
241 static gint imap_remove_msgs (Folder *folder,
242 FolderItem *dest,
243 MsgInfoList *msglist,
244 GHashTable *relation);
245 static gint imap_expunge (Folder *folder,
246 FolderItem *dest);
247 static gint imap_remove_all_msg (Folder *folder,
248 FolderItem *item);
250 static gboolean imap_is_msg_changed (Folder *folder,
251 FolderItem *item,
252 MsgInfo *msginfo);
254 static gint imap_close (Folder *folder,
255 FolderItem *item);
257 static gint imap_scan_tree (Folder *folder);
259 static gint imap_create_tree (Folder *folder);
261 static FolderItem *imap_create_folder (Folder *folder,
262 FolderItem *parent,
263 const gchar *name);
264 static gint imap_rename_folder (Folder *folder,
265 FolderItem *item,
266 const gchar *name);
267 static gint imap_remove_folder (Folder *folder,
268 FolderItem *item);
270 static FolderItem *imap_folder_item_new (Folder *folder);
271 static void imap_folder_item_destroy (Folder *folder,
272 FolderItem *item);
274 static IMAPSession *imap_session_get (Folder *folder);
276 static gint imap_auth (IMAPSession *session,
277 const gchar *user,
278 const gchar *pass,
279 IMAPAuthType type);
281 static gint imap_scan_tree_recursive (IMAPSession *session,
282 FolderItem *item,
283 gboolean subs_only);
284 static gint imap_scan_tree_recursive_dive (IMAPSession *session,
285 FolderItem *item,
286 gboolean subs_only);
288 static void imap_create_missing_folders (Folder *folder);
289 static FolderItem *imap_create_special_folder
290 (Folder *folder,
291 SpecialFolderItemType stype,
292 const gchar *name);
294 static gint imap_do_copy_msgs (Folder *folder,
295 FolderItem *dest,
296 MsgInfoList *msglist,
297 GHashTable *relation,
298 gboolean same_dest_ok);
300 static gint imap_do_remove_msgs (Folder *folder,
301 FolderItem *dest,
302 MsgInfoList *msglist,
303 GHashTable *relation);
305 static void imap_delete_all_cached_messages (FolderItem *item);
306 static void imap_set_batch (Folder *folder,
307 FolderItem *item,
308 gboolean batch);
309 static gint imap_set_message_flags (IMAPSession *session,
310 IMAPFolderItem *item,
311 MsgNumberList *numlist,
312 IMAPFlags flags,
313 GSList *tags,
314 gboolean is_set);
315 static gint imap_select (IMAPSession *session,
316 IMAPFolder *folder,
317 FolderItem *item,
318 gint *exists,
319 gint *recent,
320 gint *unseen,
321 guint32 *uid_validity,
322 gint *can_create_flags,
323 gboolean block);
324 static gint imap_status (IMAPSession *session,
325 IMAPFolder *folder,
326 const gchar *path,
327 IMAPFolderItem *item,
328 gint *messages,
329 guint32 *uid_next,
330 guint32 *uid_validity,
331 gint *unseen,
332 gboolean block);
333 static void imap_commit_tags (FolderItem *item,
334 MsgInfo *msginfo,
335 GSList *set_tags,
336 GSList *unset_tags);
338 static gchar imap_get_path_separator (IMAPSession *session,
339 IMAPFolder *folder,
340 const gchar *path,
341 gint *ok);
342 static gchar *imap_get_real_path (IMAPSession *session,
343 IMAPFolder *folder,
344 const gchar *path,
345 gint *ok);
346 #ifdef HAVE_LIBETPAN
347 static void imap_synchronise (FolderItem *item, gint days);
348 #endif
349 static gboolean imap_is_busy (Folder *folder);
351 static void imap_free_capabilities (IMAPSession *session);
353 /* low-level IMAP4rev1 commands */
354 static gint imap_cmd_login (IMAPSession *session,
355 const gchar *user,
356 const gchar *pass,
357 const gchar *type);
358 static gint imap_cmd_noop (IMAPSession *session);
359 #ifdef USE_GNUTLS
360 static gint imap_cmd_starttls (IMAPSession *session);
361 #endif
362 static gint imap_cmd_select (IMAPSession *session,
363 const gchar *folder,
364 gint *exists,
365 gint *recent,
366 gint *unseen,
367 guint32 *uid_validity,
368 gint *can_create_flags,
369 GSList **ok_flags,
370 gboolean block);
371 static gint imap_cmd_close (IMAPSession *session);
372 static gint imap_cmd_examine (IMAPSession *session,
373 const gchar *folder,
374 gint *exists,
375 gint *recent,
376 gint *unseen,
377 guint32 *uid_validity,
378 gboolean block);
379 static gint imap_cmd_create (IMAPSession *sock,
380 const gchar *folder);
381 static gint imap_cmd_rename (IMAPSession *sock,
382 const gchar *oldfolder,
383 const gchar *newfolder);
384 static gint imap_cmd_delete (IMAPSession *session,
385 const gchar *folder);
386 static gint imap_cmd_fetch (IMAPSession *sock,
387 guint32 uid,
388 const gchar *filename,
389 gboolean headers,
390 gboolean body);
391 static gint imap_cmd_append (IMAPSession *session,
392 IMAPFolderItem *item,
393 const gchar *destfolder,
394 const gchar *file,
395 IMAPFlags flags,
396 guint32 *new_uid);
397 static gint imap_cmd_copy (IMAPSession *session,
398 struct mailimap_set * set,
399 const gchar *destfolder,
400 struct mailimap_set ** source,
401 struct mailimap_set ** dest);
402 static gint imap_cmd_store (IMAPSession *session,
403 IMAPFolderItem *item,
404 struct mailimap_set * set,
405 IMAPFlags flags,
406 GSList *tags,
407 int do_add);
408 static gint imap_cmd_expunge (IMAPSession *session);
410 static void imap_path_separator_subst (gchar *str,
411 gchar separator);
413 static gboolean imap_rename_folder_func (GNode *node,
414 gpointer data);
415 static gint imap_get_num_list (Folder *folder,
416 FolderItem *item,
417 GSList **list,
418 gboolean *old_uids_valid);
419 static GSList *imap_get_msginfos (Folder *folder,
420 FolderItem *item,
421 GSList *msgnum_list);
422 static MsgInfo *imap_get_msginfo (Folder *folder,
423 FolderItem *item,
424 gint num);
425 static gboolean imap_scan_required (Folder *folder,
426 FolderItem *item);
427 static void imap_change_flags (Folder *folder,
428 FolderItem *item,
429 MsgInfo *msginfo,
430 MsgPermFlags newflags);
431 static gint imap_get_flags (Folder *folder,
432 FolderItem *item,
433 MsgInfoList *msglist,
434 GHashTable *msgflags);
435 static gchar *imap_item_get_path (Folder *folder,
436 FolderItem *item);
437 static MsgInfo *imap_parse_msg(const gchar *file, FolderItem *item);
440 /* data types conversion libetpan <-> claws */
441 static GSList * imap_list_from_lep(IMAPFolder * folder,
442 clist * list, const gchar * real_path, gboolean all);
443 static GSList * imap_get_lep_set_from_numlist(IMAPFolder *folder, MsgNumberList *numlist);
444 static GSList * imap_get_lep_set_from_msglist(IMAPFolder *folder, MsgInfoList *msglist);
445 static GSList * imap_uid_list_from_lep(clist * list, gint* length);
446 static GSList * imap_uid_list_from_lep_tab(carray * list);
447 static void imap_flags_hash_from_lep_uid_flags_tab(carray * list,
448 GHashTable * hash,
449 GHashTable *tags_hash);
450 static MsgInfo *imap_envelope_from_lep(struct imap_fetch_env_info * info,
451 FolderItem *item);
452 static void imap_lep_set_free(GSList *seq_list);
453 static struct mailimap_flag_list * imap_flag_to_lep(IMAPFolderItem *item, IMAPFlags flags, GSList *tags);
455 typedef struct _hashtable_data {
456 GSList *msglist;
457 IMAPFolderItem *item;
458 } hashtable_data;
460 static FolderClass imap_class;
462 FolderClass *imap_get_class(void)
464 if (imap_class.idstr == NULL) {
465 imap_class.type = F_IMAP;
466 imap_class.idstr = "imap";
467 imap_class.uistr = "IMAP";
468 imap_class.supports_server_search = TRUE;
470 /* Folder functions */
471 imap_class.new_folder = imap_folder_new;
472 imap_class.destroy_folder = imap_folder_destroy;
473 imap_class.scan_tree = imap_scan_tree;
474 imap_class.create_tree = imap_create_tree;
476 /* FolderItem functions */
477 imap_class.item_new = imap_folder_item_new;
478 imap_class.item_destroy = imap_folder_item_destroy;
479 imap_class.item_get_path = imap_item_get_path;
480 imap_class.create_folder = imap_create_folder;
481 imap_class.rename_folder = imap_rename_folder;
482 imap_class.remove_folder = imap_remove_folder;
483 imap_class.close = imap_close;
484 imap_class.get_num_list = imap_get_num_list;
485 imap_class.scan_required = imap_scan_required;
486 imap_class.set_xml = folder_set_xml;
487 imap_class.get_xml = folder_get_xml;
488 imap_class.item_set_xml = imap_item_set_xml;
489 imap_class.item_get_xml = imap_item_get_xml;
491 /* Message functions */
492 imap_class.get_msginfo = imap_get_msginfo;
493 imap_class.get_msginfos = imap_get_msginfos;
494 imap_class.fetch_msg = imap_fetch_msg;
495 imap_class.fetch_msg_full = imap_fetch_msg_full;
496 imap_class.add_msg = imap_add_msg;
497 imap_class.add_msgs = imap_add_msgs;
498 imap_class.copy_msg = imap_copy_msg;
499 imap_class.copy_msgs = imap_copy_msgs;
500 imap_class.search_msgs = search_msgs;
501 imap_class.remove_msg = imap_remove_msg;
502 imap_class.remove_msgs = imap_remove_msgs;
503 imap_class.expunge = imap_expunge;
504 imap_class.remove_all_msg = imap_remove_all_msg;
505 imap_class.is_msg_changed = imap_is_msg_changed;
506 imap_class.change_flags = imap_change_flags;
507 imap_class.get_flags = imap_get_flags;
508 imap_class.set_batch = imap_set_batch;
509 imap_class.synchronise = imap_synchronise;
510 imap_class.remove_cached_msg = imap_remove_cached_msg;
511 imap_class.commit_tags = imap_commit_tags;
514 return &imap_class;
517 static void imap_refresh_sensitivity (IMAPSession *session)
519 MainWindow *mainwin;
521 if (session->sens_update_block)
522 return;
523 mainwin = mainwindow_get_mainwindow();
524 if (mainwin) {
525 toolbar_main_set_sensitive(mainwin);
526 main_window_set_menu_sensitive(mainwin);
530 static void lock_session(IMAPSession *session)
532 if (session) {
533 debug_print("locking session %p (%d)\n", session, session->busy);
534 if (session->busy)
535 debug_print(" SESSION WAS LOCKED !! \n");
536 session->busy = TRUE;
537 imap_refresh_sensitivity(session);
538 } else {
539 debug_print("can't lock null session\n");
543 static void unlock_session(IMAPSession *session)
545 if (session) {
546 debug_print("unlocking session %p\n", session);
547 session->busy = FALSE;
548 imap_refresh_sensitivity(session);
549 } else {
550 debug_print("can't unlock null session\n");
554 static gboolean imap_ping(gpointer data)
556 Session *session = (Session *)data;
557 IMAPSession *imap_session = IMAP_SESSION(session);
558 int r;
560 if (session->state != SESSION_READY)
561 return FALSE;
562 if (imap_session->busy || !imap_session->authenticated)
563 return TRUE;
565 lock_session(imap_session);
566 r = imap_cmd_noop(imap_session);
567 unlock_session(imap_session);
569 return r == MAILIMAP_NO_ERROR;
572 static void imap_disc_session_destroy(IMAPSession *session)
574 RemoteFolder *rfolder = NULL;
576 if (session == NULL)
577 return;
579 rfolder = REMOTE_FOLDER(IMAP_SESSION(session)->folder);
581 if (rfolder == NULL)
582 return;
583 log_warning(LOG_PROTOCOL, _("IMAP connection broken\n"));
584 SESSION(session)->state = SESSION_DISCONNECTED;
585 SESSION(session)->sock = NULL;
588 static void imap_safe_destroy(IMAPSession *session)
590 if (!session->busy)
591 session_destroy(SESSION(session));
592 else
593 session->do_destroy = TRUE;
596 static gboolean is_fatal(int libetpan_errcode)
598 switch(libetpan_errcode) {
599 case MAILIMAP_ERROR_STREAM:
600 case MAILIMAP_ERROR_PROTOCOL:
601 case MAILIMAP_ERROR_PARSE:
602 case MAILIMAP_ERROR_BAD_STATE:
603 return TRUE;
604 default:
605 return FALSE;
609 #define MY_LOG_WARNING(concat_cmd, ...) \
610 msg = concat_cmd; \
611 log_warning(LOG_PROTOCOL, msg, __VA_ARGS__); \
612 g_free(msg);
614 static void imap_handle_error(Session *session, const gchar *server, int libetpan_errcode)
616 const gchar *session_server = (session ? session->server : NULL);
617 gchar *msg;
619 if (session_server == NULL)
620 session_server = server;
621 if (session_server == NULL)
622 session_server = "(null)";
624 switch(libetpan_errcode) {
625 case MAILIMAP_NO_ERROR:
626 return;
627 case MAILIMAP_NO_ERROR_AUTHENTICATED:
628 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("authenticated"), "\n", NULL), session_server)
629 break;
630 case MAILIMAP_NO_ERROR_NON_AUTHENTICATED:
631 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("not authenticated"), "\n", NULL), session_server)
632 break;
633 case MAILIMAP_ERROR_BAD_STATE:
634 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("bad state"), "\n", NULL), session_server)
635 break;
636 case MAILIMAP_ERROR_STREAM:
637 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("stream error"), "\n", NULL), session_server)
638 break;
639 case MAILIMAP_ERROR_PARSE:
640 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("parse error "
641 "(very probably non-RFC compliance from the server)"), "\n", NULL), session_server)
642 break;
643 case MAILIMAP_ERROR_CONNECTION_REFUSED:
644 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("connection refused"), "\n", NULL), session_server)
645 break;
646 case MAILIMAP_ERROR_MEMORY:
647 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("memory error"), "\n", NULL), session_server)
648 break;
649 case MAILIMAP_ERROR_FATAL:
650 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("fatal error"), "\n", NULL), session_server)
651 break;
652 case MAILIMAP_ERROR_PROTOCOL:
653 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("protocol error "
654 "(very probably non-RFC compliance from the server)"), "\n", NULL), session_server)
655 break;
656 case MAILIMAP_ERROR_DONT_ACCEPT_CONNECTION:
657 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("connection not accepted"), "\n", NULL), session_server)
658 break;
659 case MAILIMAP_ERROR_APPEND:
660 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("APPEND error"), "\n", NULL), session_server)
661 break;
662 case MAILIMAP_ERROR_NOOP:
663 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("NOOP error"), "\n", NULL), session_server)
664 break;
665 case MAILIMAP_ERROR_LOGOUT:
666 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("LOGOUT error"), "\n", NULL), session_server)
667 break;
668 case MAILIMAP_ERROR_CAPABILITY:
669 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("CAPABILITY error"), "\n", NULL), session_server)
670 break;
671 case MAILIMAP_ERROR_CHECK:
672 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("CHECK error"), "\n", NULL), session_server)
673 break;
674 case MAILIMAP_ERROR_CLOSE:
675 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("CLOSE error"), "\n", NULL), session_server)
676 break;
677 case MAILIMAP_ERROR_EXPUNGE:
678 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("EXPUNGE error"), "\n", NULL), session_server)
679 break;
680 case MAILIMAP_ERROR_COPY:
681 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("COPY error"), "\n", NULL), session_server)
682 break;
683 case MAILIMAP_ERROR_UID_COPY:
684 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("UID COPY error"), "\n", NULL), session_server)
685 break;
686 case MAILIMAP_ERROR_CREATE:
687 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("CREATE error"), "\n", NULL), session_server)
688 break;
689 case MAILIMAP_ERROR_DELETE:
690 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("DELETE error"), "\n", NULL), session_server)
691 break;
692 case MAILIMAP_ERROR_EXAMINE:
693 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("EXAMINE error"), "\n", NULL), session_server)
694 break;
695 case MAILIMAP_ERROR_FETCH:
696 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("FETCH error"), "\n", NULL), session_server)
697 break;
698 case MAILIMAP_ERROR_UID_FETCH:
699 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("UID FETCH error"), "\n", NULL), session_server)
700 break;
701 case MAILIMAP_ERROR_LIST:
702 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("LIST error"), "\n", NULL), session_server)
703 break;
704 case MAILIMAP_ERROR_LOGIN:
705 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("LOGIN error"), "\n", NULL), session_server)
706 break;
707 case MAILIMAP_ERROR_LSUB:
708 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("LSUB error"), "\n", NULL), session_server)
709 break;
710 case MAILIMAP_ERROR_RENAME:
711 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("RENAME error"), "\n", NULL), session_server)
712 break;
713 case MAILIMAP_ERROR_SEARCH:
714 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("SEARCH error"), "\n", NULL), session_server)
715 break;
716 case MAILIMAP_ERROR_UID_SEARCH:
717 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("UID SEARCH error"), "\n", NULL), session_server)
718 break;
719 case MAILIMAP_ERROR_SELECT:
720 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("SELECT error"), "\n", NULL), session_server)
721 break;
722 case MAILIMAP_ERROR_STATUS:
723 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("STATUS error"), "\n", NULL), session_server)
724 break;
725 case MAILIMAP_ERROR_STORE:
726 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("STORE error"), "\n", NULL), session_server)
727 break;
728 case MAILIMAP_ERROR_UID_STORE:
729 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("UID STORE error"), "\n", NULL), session_server)
730 break;
731 case MAILIMAP_ERROR_SUBSCRIBE:
732 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("SUBSCRIBE error"), "\n", NULL), session_server)
733 break;
734 case MAILIMAP_ERROR_UNSUBSCRIBE:
735 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("UNSUBSCRIBE error"), "\n", NULL), session_server)
736 break;
737 case MAILIMAP_ERROR_STARTTLS:
738 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("STARTTLS error"), "\n", NULL), session_server)
739 break;
740 case MAILIMAP_ERROR_INVAL:
741 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("INVAL error"), "\n", NULL), session_server)
742 break;
743 case MAILIMAP_ERROR_EXTENSION:
744 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("EXTENSION error"), "\n", NULL), session_server)
745 break;
746 case MAILIMAP_ERROR_SASL:
747 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("SASL error"), "\n", NULL), session_server)
748 break;
749 #ifdef USE_GNUTLS
750 case MAILIMAP_ERROR_SSL:
751 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("SSL/TLS error"), "\n", NULL), session_server)
752 break;
753 #endif
754 default:
755 MY_LOG_WARNING(g_strconcat(_("IMAP error on %s:"), " ", _("Unknown error [%d]"), "\n", NULL),
756 session_server, libetpan_errcode)
757 break;
760 if (session && is_fatal(libetpan_errcode)) {
761 imap_disc_session_destroy(IMAP_SESSION(session));
762 } else if (session && !is_fatal(libetpan_errcode)) {
763 if (IMAP_SESSION(session)->busy)
764 unlock_session(IMAP_SESSION(session));
768 #undef MY_LOG_WARNING
770 static Folder *imap_folder_new(const gchar *name, const gchar *path)
772 Folder *folder;
774 folder = (Folder *)g_new0(IMAPFolder, 1);
775 folder->klass = &imap_class;
776 imap_folder_init(folder, name, path);
778 return folder;
781 static void imap_folder_destroy(Folder *folder)
783 while (imap_folder_get_refcnt(folder) > 0)
784 gtk_main_iteration();
786 g_free(IMAP_FOLDER(folder)->search_charset);
788 folder_remote_folder_destroy(REMOTE_FOLDER(folder));
789 imap_done(folder);
792 static void imap_folder_init(Folder *folder, const gchar *name,
793 const gchar *path)
795 folder_remote_folder_init((Folder *)folder, name, path);
796 IMAP_FOLDER(folder)->max_set_size = IMAP_SET_MAX_COUNT;
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_PLAIN:
914 ok = imap_cmd_login(session, user, pass, "PLAIN");
915 break;
916 case IMAP_AUTH_OAUTH2:
917 ok = imap_cmd_login(session, user, pass, "XOAUTH2");
918 break;
919 case IMAP_AUTH_LOGIN:
920 ok = imap_cmd_login(session, user, pass, "LOGIN");
921 break;
922 case IMAP_AUTH_PLAINTEXT:
923 ok = imap_cmd_login(session, user, pass, "plaintext");
924 break;
925 case IMAP_AUTH_GSSAPI:
926 ok = imap_cmd_login(session, user, pass, "GSSAPI");
927 break;
928 default:
929 debug_print("capabilities:\n"
930 "\t ANONYMOUS %d\n"
931 "\t CRAM-MD5 %d\n"
932 "\t DIGEST-MD5 %d\n"
933 "\t SCRAM-SHA-1 %d\n"
934 "\t PLAIN %d\n"
935 "\t OAUTH2 %d\n"
936 "\t LOGIN %d\n"
937 "\t GSSAPI %d\n",
938 imap_has_capability(session, "ANONYMOUS"),
939 imap_has_capability(session, "CRAM-MD5"),
940 imap_has_capability(session, "DIGEST-MD5"),
941 imap_has_capability(session, "SCRAM-SHA-1"),
942 imap_has_capability(session, "PLAIN"),
943 imap_has_capability(session, "XOAUTH2"),
944 imap_has_capability(session, "LOGIN"),
945 imap_has_capability(session, "GSSAPI"));
946 if (imap_has_capability(session, "CRAM-MD5"))
947 ok = imap_cmd_login(session, user, pass, "CRAM-MD5");
948 if (ok == MAILIMAP_ERROR_LOGIN && imap_has_capability(session, "DIGEST-MD5"))
949 ok = imap_cmd_login(session, user, pass, "DIGEST-MD5");
950 if (ok == MAILIMAP_ERROR_LOGIN && imap_has_capability(session, "SCRAM-SHA-1"))
951 ok = imap_cmd_login(session, user, pass, "SCRAM-SHA-1");
952 if (ok == MAILIMAP_ERROR_LOGIN && imap_has_capability(session, "PLAIN"))
953 ok = imap_cmd_login(session, user, pass, "PLAIN");
954 if (ok == MAILIMAP_ERROR_LOGIN && imap_has_capability(session, "LOGIN"))
955 ok = imap_cmd_login(session, user, pass, "LOGIN");
956 if (ok == MAILIMAP_ERROR_LOGIN && imap_has_capability(session, "GSSAPI"))
957 ok = imap_cmd_login(session, user, pass, "GSSAPI");
958 if (ok == MAILIMAP_ERROR_LOGIN) /* we always try plaintext login before giving up */
959 ok = imap_cmd_login(session, user, pass, "plaintext");
960 if (ok == MAILIMAP_ERROR_LOGIN && imap_has_capability(session, "XOAUTH2"))
961 ok = imap_cmd_login(session, user, pass, "XOAUTH2");
964 if (ok == MAILIMAP_NO_ERROR)
965 session->authenticated = TRUE;
966 else {
967 if (type == IMAP_AUTH_CRAM_MD5) {
968 ext_info = _("\n\nCRAM-MD5 logins only work if libetpan has been "
969 "compiled with SASL support and the "
970 "CRAM-MD5 SASL plugin is installed.");
973 if (type == IMAP_AUTH_DIGEST_MD5) {
974 ext_info = _("\n\nDIGEST-MD5 logins only work if libetpan has been "
975 "compiled with SASL support and the "
976 "DIGEST-MD5 SASL plugin is installed.");
979 if (type == IMAP_AUTH_SCRAM_SHA1) {
980 ext_info = _("\n\nSCRAM-SHA-1 logins only work if libetpan has been "
981 "compiled with SASL support and the "
982 "SCRAM SASL plugin is installed.");
985 if (type == IMAP_AUTH_PLAIN) {
986 ext_info = _("\n\nPLAIN logins only work if libetpan has been "
987 "compiled with SASL support and the "
988 "PLAIN SASL plugin is installed.");
991 if (type == IMAP_AUTH_LOGIN) {
992 ext_info = _("\n\nLOGIN logins only work if libetpan has been "
993 "compiled with SASL support and the "
994 "LOGIN SASL plugin is installed.");
997 if (type == IMAP_AUTH_OAUTH2) {
998 ext_info = _("\n\nOAuth2 error. Check and correct your OAuth2 "
999 "account preferences.");
1002 if (time(NULL) - last_login_err > 10) {
1003 if (!prefs_common.no_recv_err_panel) {
1004 alertpanel_error_log(_("Connection to %s failed: "
1005 "login refused.%s"),
1006 server, ext_info);
1007 } else {
1008 log_error(LOG_PROTOCOL, _("Connection to %s failed: "
1009 "login refused.%s\n"),
1010 server, ext_info);
1013 last_login_err = time(NULL);
1015 g_free(server);
1016 return ok;
1019 static IMAPSession *imap_reconnect_if_possible(Folder *folder, IMAPSession *session)
1021 RemoteFolder *rfolder = REMOTE_FOLDER(folder);
1022 /* Check if this is the first try to establish a
1023 connection, if yes we don't try to reconnect */
1024 debug_print("reconnecting\n");
1025 if (rfolder->session == NULL) {
1026 log_warning(LOG_PROTOCOL, _("Connecting to %s failed"),
1027 folder->account->recv_server);
1028 SESSION(session)->sock = NULL;
1029 imap_safe_destroy(session);
1030 session = NULL;
1031 } else {
1032 rfolder->session = NULL;
1033 log_warning(LOG_PROTOCOL, _("IMAP connection to %s has been"
1034 " disconnected. Reconnecting...\n"),
1035 folder->account->recv_server);
1036 statusbar_print_all(_("IMAP connection to %s has been"
1037 " disconnected. Reconnecting...\n"),
1038 folder->account->recv_server);
1039 SESSION(session)->state = SESSION_DISCONNECTED;
1040 SESSION(session)->sock = NULL;
1041 imap_safe_destroy(session);
1042 /* Clear folders session to make imap_session_get create
1043 a new session, because of rfolder->session == NULL
1044 it will not try to reconnect again and so avoid an
1045 endless loop */
1046 debug_print("getting session...\n");
1047 session = imap_session_get(folder);
1048 rfolder->session = SESSION(session);
1049 statusbar_pop_all();
1051 return session;
1054 static IMAPSession *imap_session_get(Folder *folder)
1056 RemoteFolder *rfolder = REMOTE_FOLDER(folder);
1057 IMAPSession *session = NULL;
1058 gint r = MAILIMAP_NO_ERROR;
1060 g_return_val_if_fail(folder != NULL, NULL);
1061 g_return_val_if_fail(FOLDER_CLASS(folder) == &imap_class, NULL);
1062 g_return_val_if_fail(folder->account != NULL, NULL);
1064 if (prefs_common.work_offline &&
1065 !inc_offline_should_override(FALSE,
1066 _("Claws Mail needs network access in order "
1067 "to access the IMAP server."))) {
1068 return NULL;
1071 /* check for deferred destroy */
1072 if (rfolder->session != NULL) {
1073 session = IMAP_SESSION(rfolder->session);
1074 if (!session->busy && session->do_destroy) {
1075 rfolder->session = NULL;
1076 imap_safe_destroy(session);
1077 session = NULL;
1081 /* Make sure we have a session */
1082 if (rfolder->session != NULL && rfolder->session->state != SESSION_DISCONNECTED) {
1083 session = IMAP_SESSION(rfolder->session);
1084 } else if (rfolder->session != NULL && rfolder->session->state == SESSION_DISCONNECTED) {
1085 imap_safe_destroy(IMAP_SESSION(rfolder->session));
1086 rfolder->session = NULL;
1087 goto new_conn;
1088 } else if (rfolder->connecting) {
1089 debug_print("already connecting\n");
1090 return NULL;
1091 } else {
1092 new_conn:
1093 imap_reset_uid_lists(folder);
1094 if (time(NULL) - rfolder->last_failure <= 2)
1095 return NULL;
1096 rfolder->connecting = TRUE;
1097 session = imap_session_new(folder, folder->account);
1099 if(session == NULL) {
1100 rfolder->last_failure = time(NULL);
1101 rfolder->connecting = FALSE;
1102 return NULL;
1105 /* Make sure session is authenticated */
1106 if (!IMAP_SESSION(session)->authenticated)
1107 r = imap_session_authenticate(IMAP_SESSION(session), folder->account);
1109 if (r != MAILIMAP_NO_ERROR || (!is_fatal(r) && !IMAP_SESSION(session)->authenticated)) {
1110 rfolder->session = NULL;
1111 if (!is_fatal(r)) {
1112 imap_threaded_disconnect(session->folder);
1114 SESSION(session)->state = SESSION_DISCONNECTED;
1115 SESSION(session)->sock = NULL;
1116 imap_safe_destroy(session);
1117 rfolder->last_failure = time(NULL);
1118 rfolder->connecting = FALSE;
1119 return NULL;
1122 /* I think the point of this code is to avoid sending a
1123 * keepalive if we've used the session recently and therefore
1124 * think it's still alive. Unfortunately, most of the code
1125 * does not yet check for errors on the socket, and so if the
1126 * connection drops we don't notice until the timeout expires.
1127 * A better solution than sending a NOOP every time would be
1128 * for every command to be prepared to retry until it is
1129 * successfully sent. -- mbp */
1130 if ((time(NULL) - SESSION(session)->last_access_time > SESSION_TIMEOUT_INTERVAL) || session->cancelled) {
1131 /* verify that the session is still alive */
1132 r = imap_cmd_noop(session);
1134 if (r != MAILIMAP_NO_ERROR) {
1135 debug_print("disconnected!\n");
1136 if (!is_fatal(r))
1137 session = imap_reconnect_if_possible(folder, session);
1138 else {
1139 rfolder->session = NULL;
1140 rfolder->connecting = FALSE;
1141 SESSION(session)->state = SESSION_DISCONNECTED;
1142 SESSION(session)->sock = NULL;
1143 imap_safe_destroy(session);
1144 session = imap_session_get(folder);
1147 if (session)
1148 session->cancelled = FALSE;
1151 rfolder->session = SESSION(session);
1152 rfolder->connecting = FALSE;
1154 return IMAP_SESSION(session);
1157 static IMAPSession *imap_session_new(Folder * folder,
1158 const PrefsAccount *account)
1160 IMAPSession *session;
1161 ProxyInfo *proxy_info = NULL;
1162 gushort port;
1163 int r;
1164 int authenticated = FALSE;
1165 gchar *buf;
1167 #ifdef USE_GNUTLS
1168 /* FIXME: IMAP over SSL only... */
1169 SSLType ssl_type;
1171 port = account->set_imapport ? account->imapport
1172 : account->ssl_imap == SSL_TUNNEL ? IMAPS_PORT : IMAP4_PORT;
1173 ssl_type = account->ssl_imap;
1174 #else
1175 if (account->ssl_imap != SSL_NONE) {
1176 if (alertpanel_full(_("Insecure connection"),
1177 _("This connection is configured to be secured "
1178 "using SSL/TLS, but SSL/TLS is not available "
1179 "in this build of Claws Mail. \n\n"
1180 "Do you want to continue connecting to this "
1181 "server? The communication would not be "
1182 "secure."),
1183 GTK_STOCK_CANCEL, _("Con_tinue connecting"), NULL,
1184 ALERTFOCUS_FIRST, FALSE, NULL, ALERT_WARNING) != G_ALERTALTERNATE)
1185 return NULL;
1187 port = account->set_imapport ? account->imapport
1188 : IMAP4_PORT;
1189 #endif
1191 imap_init(folder);
1192 buf = g_strdup_printf(_("Account '%s': Connecting to IMAP server: %s:%d..."),
1193 folder->account->account_name, folder->account->recv_server,
1194 port);
1195 statusbar_print_all("%s", buf);
1196 log_message(LOG_PROTOCOL, "%s\n", buf);
1197 g_free(buf);
1199 if (account->use_proxy) {
1200 if (account->use_default_proxy) {
1201 proxy_info = (ProxyInfo *)&(prefs_common.proxy_info);
1202 if (proxy_info->use_proxy_auth)
1203 proxy_info->proxy_pass = passwd_store_get(PWS_CORE, PWS_CORE_PROXY,
1204 PWS_CORE_PROXY_PASS);
1205 } else {
1206 proxy_info = (ProxyInfo *)&(account->proxy_info);
1207 if (proxy_info->use_proxy_auth)
1208 proxy_info->proxy_pass = passwd_store_get_account(account->account_id,
1209 PWS_ACCOUNT_PROXY_PASS);
1213 #ifndef G_OS_WIN32
1214 if (account->set_tunnelcmd) {
1215 r = imap_threaded_connect_cmd(folder,
1216 account->tunnelcmd,
1217 account->recv_server,
1218 port);
1220 else
1221 #endif
1223 #ifdef USE_GNUTLS
1225 if (ssl_type == SSL_TUNNEL) {
1226 r = imap_threaded_connect_ssl(folder,
1227 account->recv_server,
1228 port,
1229 proxy_info);
1231 else
1232 #endif
1234 r = imap_threaded_connect(folder,
1235 account->recv_server,
1236 port,
1237 proxy_info);
1241 statusbar_pop_all();
1242 if (r == MAILIMAP_NO_ERROR_AUTHENTICATED) {
1243 authenticated = TRUE;
1245 else if (r == MAILIMAP_NO_ERROR_NON_AUTHENTICATED) {
1246 authenticated = FALSE;
1248 else {
1249 #ifdef USE_GNUTLS
1250 if (r == MAILIMAP_ERROR_SSL)
1251 log_error(LOG_PROTOCOL, _("SSL/TLS handshake failed\n"));
1252 else
1253 #endif
1254 imap_handle_error(NULL, account->recv_server, r);
1256 if(!prefs_common.no_recv_err_panel) {
1257 alertpanel_error_log(_("Can't connect to IMAP server: %s:%d"),
1258 account->recv_server, port);
1259 } else {
1260 log_error(LOG_PROTOCOL, _("Can't connect to IMAP server: %s:%d\n"),
1261 account->recv_server, port);
1264 return NULL;
1267 session = g_new0(IMAPSession, 1);
1268 session_init(SESSION(session), account, FALSE);
1269 SESSION(session)->type = SESSION_IMAP;
1270 SESSION(session)->server = g_strdup(account->recv_server);
1271 SESSION(session)->port = port;
1272 SESSION(session)->sock = NULL;
1273 SESSION(session)->proxy_info = proxy_info;
1274 SESSION(session)->destroy = imap_session_destroy;
1276 session->capability = NULL;
1277 session->authenticated = authenticated;
1278 session->mbox = NULL;
1279 session->exists = 0;
1280 session->recent = 0;
1281 session->expunge = 0;
1282 session->cmd_count = 0;
1283 session->folder = folder;
1284 IMAP_FOLDER(session->folder)->last_seen_separator = 0;
1286 #ifdef USE_GNUTLS
1287 if (account->ssl_imap == SSL_STARTTLS) {
1288 gint ok;
1290 ok = imap_cmd_starttls(session);
1291 if (ok != MAILIMAP_NO_ERROR) {
1292 log_warning(LOG_PROTOCOL, _("Can't start STARTTLS session.\n"));
1293 if (!is_fatal(ok)) {
1294 SESSION(session)->sock = NULL;
1295 imap_safe_destroy(session);
1297 return NULL;
1300 imap_free_capabilities(session);
1301 session->authenticated = FALSE;
1302 session->uidplus = FALSE;
1303 session->cmd_count = 1;
1305 SESSION(session)->use_tls_sni = account->use_tls_sni;
1306 #endif
1308 log_message(LOG_PROTOCOL, "IMAP connection is %s-authenticated\n",
1309 (session->authenticated) ? "pre" : "un");
1311 session_register_ping(SESSION(session), imap_ping);
1313 return session;
1316 static gint imap_session_authenticate(IMAPSession *session,
1317 PrefsAccount *account)
1319 gchar *pass, *acc_pass = NULL;
1320 gboolean failed = FALSE;
1321 gint ok = MAILIMAP_NO_ERROR;
1322 g_return_val_if_fail(account->userid != NULL, MAILIMAP_ERROR_BAD_STATE);
1324 if(account->imap_auth_type == IMAP_AUTH_OAUTH2)
1325 oauth2_check_passwds (account);
1327 if (!password_get(account->userid, account->recv_server, "imap",
1328 SESSION(session)->port, &acc_pass)) {
1329 acc_pass = passwd_store_get_account(account->account_id,
1330 PWS_ACCOUNT_RECV);
1333 try_again:
1334 pass = acc_pass;
1335 if (!pass && account->imap_auth_type != IMAP_AUTH_ANON && account->imap_auth_type != IMAP_AUTH_GSSAPI) {
1336 gchar *tmp_pass;
1337 tmp_pass = input_dialog_query_password_keep(account->recv_server,
1338 account->userid,
1339 &(account->session_passwd));
1340 if (!tmp_pass) {
1341 return MAILIMAP_NO_ERROR;
1343 Xstrdup_a(pass, tmp_pass, {g_free(tmp_pass); return MAILIMAP_NO_ERROR;});
1344 g_free(tmp_pass);
1345 } else if (account->imap_auth_type == IMAP_AUTH_ANON || account->imap_auth_type == IMAP_AUTH_GSSAPI) {
1346 pass = "";
1348 if ((ok = imap_auth(session, account->userid, pass, account->imap_auth_type)) != MAILIMAP_NO_ERROR) {
1350 if (!failed && !is_fatal(ok)) {
1351 if (acc_pass != NULL) {
1352 memset(acc_pass, 0, strlen(acc_pass));
1353 g_free(acc_pass);
1354 acc_pass = NULL;
1356 failed = TRUE;
1357 if (account->session_passwd != NULL) {
1358 g_free(account->session_passwd);
1359 account->session_passwd = NULL;
1361 goto try_again;
1362 } else {
1363 if (prefs_common.no_recv_err_panel) {
1364 log_error(LOG_PROTOCOL, _("Couldn't login to IMAP server %s.\n"), account->recv_server);
1365 mainwindow_show_error();
1366 } else
1367 alertpanel_error_log(_("Couldn't login to IMAP server %s."), account->recv_server);
1370 if (acc_pass != NULL) {
1371 memset(acc_pass, 0, strlen(acc_pass));
1372 g_free(acc_pass);
1373 acc_pass = NULL;
1376 return ok;
1379 if (acc_pass) {
1380 memset(acc_pass, 0, strlen(acc_pass));
1381 g_free(acc_pass);
1383 statusbar_pop_all();
1384 session->authenticated = TRUE;
1385 return MAILIMAP_NO_ERROR;
1388 static void imap_session_destroy(Session *session)
1390 if (session->state != SESSION_DISCONNECTED)
1391 imap_threaded_disconnect(IMAP_SESSION(session)->folder);
1393 imap_free_capabilities(IMAP_SESSION(session));
1394 g_free(IMAP_SESSION(session)->mbox);
1397 static gchar *imap_fetch_msg(Folder *folder, FolderItem *item, gint uid)
1399 return imap_fetch_msg_full(folder, item, uid, TRUE, TRUE);
1402 static guint get_file_size_with_crs(const gchar *filename)
1404 FILE *fp = NULL;
1405 guint cnt = 0;
1406 gchar buf[4096];
1408 if (filename == NULL)
1409 return -1;
1411 fp = claws_fopen(filename, "rb");
1412 if (!fp)
1413 return -1;
1415 while (claws_fgets(buf, sizeof (buf), fp) != NULL) {
1416 cnt += strlen(buf);
1417 if (!strstr(buf, "\r\n") && strstr(buf, "\n"))
1418 cnt++;
1421 claws_fclose(fp);
1422 return cnt;
1425 static gchar *imap_get_cached_filename(FolderItem *item, guint msgnum)
1427 gchar *path, *filename;
1429 cm_return_val_if_fail(item != NULL, NULL);
1431 path = folder_item_get_path(item);
1433 if (!is_dir_exist(path)) {
1434 g_free(path);
1435 return NULL;
1438 filename = g_strconcat(path, G_DIR_SEPARATOR_S, itos(msgnum), NULL);
1440 if (is_dir_exist(filename)) {
1441 g_free(filename);
1442 filename = g_strconcat(path, G_DIR_SEPARATOR_S, ".", itos(msgnum), NULL);
1444 g_free(path);
1446 return filename;
1449 static void imap_remove_cached_msg(Folder *folder, FolderItem *item, MsgInfo *msginfo)
1451 gchar *filename;
1453 filename = imap_get_cached_filename(item, msginfo->msgnum);
1455 cm_return_if_fail(filename != NULL);
1457 if (is_file_exist(filename)) {
1458 claws_unlink(filename);
1460 g_free(filename);
1463 typedef struct _TagsData {
1464 gchar *str;
1465 GSList *msglist;
1466 IMAPFolderItem *item;
1467 } TagsData;
1469 static void imap_commit_tags(FolderItem *item, MsgInfo *msginfo, GSList *tags_set, GSList *tags_unset)
1471 IMAPSession *session;
1472 gint ok, can_create_tags;
1473 Folder *folder = NULL;
1474 TagsData *ht_data = NULL;
1475 GSList *cur;
1477 g_return_if_fail(item != NULL);
1478 g_return_if_fail(msginfo != NULL);
1480 folder = item->folder;
1481 debug_print("getting session...\n");
1482 session = imap_session_get(folder);
1484 if (!session) {
1485 debug_print("can't get session\n");
1486 return;
1489 ok = imap_select(session, IMAP_FOLDER(folder), item,
1490 NULL, NULL, NULL, NULL, &can_create_tags, FALSE);
1492 if (ok != MAILIMAP_NO_ERROR) {
1493 return;
1497 if (IMAP_FOLDER_ITEM(item)->can_create_flags != ITEM_CAN_CREATE_FLAGS)
1498 return;
1500 if (IMAP_FOLDER_ITEM(item)->batching) {
1501 /* instead of performing an UID STORE command for each message change,
1502 * as a lot of them can change "together", we just fill in hashtables
1503 * and defer the treatment so that we're able to send only one
1504 * command.
1506 debug_print("IMAP batch mode on, deferring tags change\n");
1507 for (cur = tags_set; cur; cur = cur->next) {
1508 gint cur_tag = GPOINTER_TO_INT(cur->data);
1509 if (cur_tag) {
1510 ht_data = g_hash_table_lookup(IMAP_FOLDER_ITEM(item)->tags_set_table,
1511 GINT_TO_POINTER(cur_tag));
1512 if (ht_data == NULL) {
1513 ht_data = g_new0(TagsData, 1);
1514 ht_data->str = g_strdup(tags_get_tag(cur_tag));
1515 ht_data->item = IMAP_FOLDER_ITEM(item);
1516 g_hash_table_insert(IMAP_FOLDER_ITEM(item)->tags_set_table,
1517 GINT_TO_POINTER(cur_tag), ht_data);
1519 ht_data->msglist = g_slist_prepend(ht_data->msglist, GINT_TO_POINTER(msginfo->msgnum));
1522 for (cur = tags_unset; cur; cur = cur->next) {
1523 gint cur_tag = GPOINTER_TO_INT(cur->data);
1524 if (cur_tag) {
1525 ht_data = g_hash_table_lookup(IMAP_FOLDER_ITEM(item)->tags_unset_table,
1526 GINT_TO_POINTER(cur_tag));
1527 if (ht_data == NULL) {
1528 ht_data = g_new0(TagsData, 1);
1529 ht_data->str = g_strdup(tags_get_tag(cur_tag));
1530 ht_data->item = IMAP_FOLDER_ITEM(item);
1531 g_hash_table_insert(IMAP_FOLDER_ITEM(item)->tags_unset_table,
1532 GINT_TO_POINTER(cur_tag), ht_data);
1534 ht_data->msglist = g_slist_prepend(ht_data->msglist, GINT_TO_POINTER(msginfo->msgnum));
1537 } else {
1538 GSList *list_set = NULL;
1539 GSList *list_unset = NULL;
1540 GSList numlist;
1542 numlist.data = GINT_TO_POINTER(msginfo->msgnum);
1543 numlist.next = NULL;
1545 debug_print("IMAP changing tags NOW\n");
1546 for (cur = tags_set; cur; cur = cur->next) {
1547 gint cur_tag = GPOINTER_TO_INT(cur->data);
1548 const gchar *str = tags_get_tag(cur_tag);
1549 if (IS_NOT_RESERVED_TAG(str))
1550 list_set = g_slist_prepend(list_set, g_strdup(str));
1552 if (list_set) {
1553 ok = imap_set_message_flags(session,
1554 IMAP_FOLDER_ITEM(item), &numlist, 0, list_set, TRUE);
1555 slist_free_strings_full(list_set);
1556 if (ok != MAILIMAP_NO_ERROR) {
1557 return;
1561 for (cur = tags_unset; cur; cur = cur->next) {
1562 gint cur_tag = GPOINTER_TO_INT(cur->data);
1563 const gchar *str = tags_get_tag(cur_tag);
1564 if (IS_NOT_RESERVED_TAG(str))
1565 list_unset = g_slist_prepend(list_unset, g_strdup(str));
1567 if (list_unset) {
1568 ok = imap_set_message_flags(session,
1569 IMAP_FOLDER_ITEM(item), &numlist, 0, list_unset, FALSE);
1570 slist_free_strings_full(list_unset);
1571 if (ok != MAILIMAP_NO_ERROR) {
1572 return;
1578 static gchar *imap_fetch_msg_full(Folder *folder, FolderItem *item, gint uid,
1579 gboolean headers, gboolean body)
1581 gchar *path, *filename;
1582 IMAPSession *session;
1583 gint ok;
1585 g_return_val_if_fail(folder != NULL, NULL);
1586 g_return_val_if_fail(item != NULL, NULL);
1588 if (uid == 0)
1589 return NULL;
1591 path = folder_item_get_path(item);
1592 if (!is_dir_exist(path)) {
1593 if(is_file_exist(path))
1594 claws_unlink(path);
1595 make_dir_hier(path);
1597 g_free(path);
1599 filename = imap_get_cached_filename(item, uid);
1600 debug_print("trying to fetch cached %s\n", filename);
1602 if (is_file_exist(filename)) {
1603 /* see whether the local file represents the whole message
1604 * or not. As the IMAP server reports size with \r chars,
1605 * we have to update the local file (UNIX \n only) size */
1606 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1607 guint have_size = -1;
1609 if (cached)
1610 debug_print("message %d has been already %scached.\n", uid,
1611 MSG_IS_FULLY_CACHED(cached->flags) ? "fully ":"");
1613 if (!cached || !MSG_IS_FULLY_CACHED(cached->flags)) {
1614 have_size = get_file_size_with_crs(filename);
1615 if (cached && (cached->size <= have_size || !body)) {
1616 ok = file_strip_crs(filename);
1617 if (ok == 0 && cached && cached->size <= have_size) {
1618 /* we have it all and stripped */
1619 debug_print("...fully cached in fact (%u/%"G_GOFFSET_FORMAT"); setting flag.\n",
1620 have_size, cached->size);
1621 procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
1623 procmsg_msginfo_free(&cached);
1624 return filename;
1625 } else if (!cached && time(NULL) - get_file_mtime(filename) < 60) {
1626 debug_print("message not cached and file recent, considering file complete\n");
1627 ok = file_strip_crs(filename);
1628 if (ok == 0)
1629 return filename;
1630 } else {
1631 procmsg_msginfo_free(&cached);
1634 if (cached && MSG_IS_FULLY_CACHED(cached->flags)) {
1635 procmsg_msginfo_free(&cached);
1636 return filename;
1638 } else {
1639 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1640 if (cached) {
1641 procmsg_msginfo_unset_flags(cached, MSG_FULLY_CACHED, 0);
1642 procmsg_msginfo_free(&cached);
1646 debug_print("getting session...\n");
1647 session = imap_session_get(folder);
1649 if (!session) {
1650 g_free(filename);
1651 return NULL;
1653 session_set_access_time(SESSION(session));
1654 lock_session(session); /* unlocked later in the function */
1656 debug_print("IMAP fetching messages\n");
1657 ok = imap_select(session, IMAP_FOLDER(folder), item,
1658 NULL, NULL, NULL, NULL, NULL, FALSE);
1659 if (ok != MAILIMAP_NO_ERROR) {
1660 g_warning("can't select mailbox %s", item->path);
1661 g_free(filename);
1662 return NULL;
1665 session_set_access_time(SESSION(session));
1667 debug_print("getting message %d...\n", uid);
1668 ok = imap_cmd_fetch(session, (guint32)uid, filename, headers, body);
1670 if (ok != MAILIMAP_NO_ERROR) {
1671 g_warning("can't fetch message %d", uid);
1672 g_free(filename);
1673 return NULL;
1676 session_set_access_time(SESSION(session));
1677 unlock_session(session);
1679 ok = file_strip_crs(filename);
1681 if (ok == 0 && headers && body) {
1682 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1683 if (cached) {
1684 procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
1685 procmsg_msginfo_free(&cached);
1687 } else if (ok == -1) {
1688 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1689 if (cached) {
1690 procmsg_msginfo_unset_flags(cached, MSG_FULLY_CACHED, 0);
1691 procmsg_msginfo_free(&cached);
1694 return filename;
1697 static gboolean imap_is_msg_fully_cached(Folder *folder, FolderItem *item, gint uid)
1699 gchar *filename;
1700 guint size = 0;
1701 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1703 if (!cached)
1704 return FALSE;
1706 if (MSG_IS_FULLY_CACHED(cached->flags)) {
1707 procmsg_msginfo_free(&cached);
1708 return TRUE;
1711 filename = imap_get_cached_filename(item, uid);
1713 if (is_file_exist(filename)) {
1714 if (cached && cached->total_size == cached->size) {
1715 /* fast path */
1716 g_free(filename);
1717 procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
1718 return TRUE;
1720 size = get_file_size_with_crs(filename);
1722 g_free(filename);
1723 debug_print("msg %d cached, has size %d, full should be %"G_GOFFSET_FORMAT".\n", uid, size, cached->size);
1724 if (cached && size >= cached->size) {
1725 cached->total_size = cached->size;
1726 procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
1727 procmsg_msginfo_free(&cached);
1728 return TRUE;
1730 if (cached)
1731 procmsg_msginfo_free(&cached);
1732 return FALSE;
1735 void imap_cache_msg(FolderItem *item, gint msgnum)
1737 Folder *folder = NULL;
1739 if (!item)
1740 return;
1741 folder = item->folder;
1743 if (!imap_is_msg_fully_cached(folder, item, msgnum)) {
1744 gchar *tmp = imap_fetch_msg_full(folder, item, msgnum, TRUE, TRUE);
1745 debug_print("fetched %s\n", tmp);
1746 g_free(tmp);
1750 static gint imap_add_msg(Folder *folder, FolderItem *dest,
1751 const gchar *file, MsgFlags *flags)
1753 gint ret;
1754 GSList file_list;
1755 MsgFileInfo fileinfo;
1757 g_return_val_if_fail(file != NULL, -1);
1759 fileinfo.msginfo = NULL;
1760 fileinfo.file = (gchar *)file;
1761 fileinfo.flags = flags;
1762 file_list.data = &fileinfo;
1763 file_list.next = NULL;
1765 ret = imap_add_msgs(folder, dest, &file_list, NULL);
1766 return ret;
1769 static gint imap_add_msgs(Folder *folder, FolderItem *dest, GSList *file_list,
1770 GHashTable *relation)
1772 gchar *destdir;
1773 IMAPSession *session;
1774 guint32 last_uid = 0;
1775 GSList *cur;
1776 MsgFileInfo *fileinfo;
1777 gint ok = MAILIMAP_NO_ERROR;
1778 gint curnum = 0, total = 0;
1779 gboolean missing_uids = FALSE;
1781 g_return_val_if_fail(folder != NULL, -1);
1782 g_return_val_if_fail(dest != NULL, -1);
1783 g_return_val_if_fail(file_list != NULL, -1);
1785 debug_print("getting session...\n");
1786 session = imap_session_get(folder);
1787 if (!session) {
1788 return -1;
1790 destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path, &ok);
1791 if (is_fatal(ok)) {
1792 g_free(destdir);
1793 return -1;
1795 statusbar_print_all(_("Adding messages..."));
1796 total = g_slist_length(file_list);
1797 for (cur = file_list; cur != NULL; cur = cur->next) {
1798 IMAPFlags iflags = 0;
1799 guint32 new_uid = 0;
1800 gchar *real_file = NULL;
1801 fileinfo = (MsgFileInfo *)cur->data;
1803 statusbar_progress_all(curnum, total, total < 10 ? 1:10);
1804 curnum++;
1806 if (fileinfo->flags) {
1807 if (MSG_IS_MARKED(*fileinfo->flags))
1808 iflags |= IMAP_FLAG_FLAGGED;
1809 if (MSG_IS_REPLIED(*fileinfo->flags))
1810 iflags |= IMAP_FLAG_ANSWERED;
1811 if (MSG_IS_FORWARDED(*fileinfo->flags))
1812 iflags |= IMAP_FLAG_FORWARDED;
1813 if (MSG_IS_SPAM(*fileinfo->flags))
1814 iflags |= IMAP_FLAG_SPAM;
1815 else
1816 iflags |= IMAP_FLAG_HAM;
1817 if (!MSG_IS_UNREAD(*fileinfo->flags))
1818 iflags |= IMAP_FLAG_SEEN;
1822 if (real_file == NULL)
1823 real_file = g_strdup(fileinfo->file);
1825 if (folder_has_parent_of_type(dest, F_QUEUE) ||
1826 folder_has_parent_of_type(dest, F_OUTBOX) ||
1827 folder_has_parent_of_type(dest, F_DRAFT) ||
1828 folder_has_parent_of_type(dest, F_TRASH))
1829 iflags |= IMAP_FLAG_SEEN;
1831 ok = imap_cmd_append(session, IMAP_FOLDER_ITEM(dest), destdir, real_file, iflags,
1832 &new_uid);
1834 if (ok != MAILIMAP_NO_ERROR) {
1835 g_warning("can't append message %s", real_file);
1836 g_free(real_file);
1837 g_free(destdir);
1838 statusbar_progress_all(0,0,0);
1839 statusbar_pop_all();
1840 return -1;
1841 } else {
1842 debug_print("appended new message as %d\n", new_uid);
1843 /* put the local file in the imapcache, so that we don't
1844 * have to fetch it back later. */
1846 if (new_uid == 0) {
1847 missing_uids = TRUE;
1848 debug_print("Missing UID (0)\n");
1850 if (new_uid > 0) {
1851 gchar *cache_path = folder_item_get_path(dest);
1852 if (!is_dir_exist(cache_path))
1853 make_dir_hier(cache_path);
1854 if (is_dir_exist(cache_path)) {
1855 gchar *cache_file = g_strconcat(
1856 cache_path, G_DIR_SEPARATOR_S,
1857 itos(new_uid), NULL);
1858 copy_file(real_file, cache_file, TRUE);
1859 debug_print("got UID %d, copied to cache: %s\n", new_uid, cache_file);
1860 g_free(cache_file);
1862 g_free(cache_path);
1866 if (relation != NULL)
1867 g_hash_table_insert(relation, fileinfo->msginfo != NULL ?
1868 (gpointer) fileinfo->msginfo : (gpointer) fileinfo,
1869 GINT_TO_POINTER(new_uid));
1870 if (last_uid < new_uid) {
1871 last_uid = new_uid;
1874 g_free(real_file);
1877 statusbar_progress_all(0,0,0);
1878 statusbar_pop_all();
1881 g_free(destdir);
1883 imap_scan_required(folder, dest);
1885 session = imap_session_get(folder);
1886 if (!session) {
1887 return -1;
1889 if (missing_uids) {
1890 gint a;
1891 ok = imap_select(session, IMAP_FOLDER(folder), dest,
1892 &a, NULL, NULL, NULL, NULL, FALSE);
1894 return last_uid;
1897 static GSList *flatten_mailimap_set(struct mailimap_set * set)
1899 GSList *result = NULL;
1900 clistiter *list;
1901 guint32 start, end, t;
1902 GSList *cur;
1904 if (!set || !set->set_list)
1905 return NULL;
1907 for (list = clist_begin(set->set_list); list; list = clist_next(list)) {
1908 struct mailimap_set_item *item = (struct mailimap_set_item *)clist_content(list);
1909 start = item->set_first;
1910 end = item->set_last;
1911 if (start <= end) {
1912 for (t = start; t <= end; t++) {
1913 result = g_slist_prepend(result, GINT_TO_POINTER(t));
1917 result = g_slist_reverse(result);
1918 if (debug_get_mode()) {
1919 debug_print("flat imap set: ");
1920 for (cur = result; cur; cur = cur->next) {
1921 debug_print("%d ", GPOINTER_TO_INT(cur->data));
1923 debug_print("\n");
1926 return result;
1928 static gint imap_do_copy_msgs(Folder *folder, FolderItem *dest,
1929 MsgInfoList *msglist, GHashTable *relation,
1930 gboolean same_dest_ok)
1932 FolderItem *src;
1933 gchar *destdir;
1934 GSList *seq_list, *cur;
1935 MsgInfo *msginfo;
1936 IMAPSession *session;
1937 gint ok = MAILIMAP_NO_ERROR;
1938 GHashTable *uid_hash;
1939 gint last_num = 0;
1941 g_return_val_if_fail(folder != NULL, -1);
1942 g_return_val_if_fail(dest != NULL, -1);
1943 g_return_val_if_fail(msglist != NULL, -1);
1945 debug_print("getting session...\n");
1946 session = imap_session_get(folder);
1948 if (!session) {
1949 return -1;
1952 msginfo = (MsgInfo *)msglist->data;
1953 src = msginfo->folder;
1954 if (!same_dest_ok && src == dest) {
1955 g_warning("the src folder is identical to the dest.");
1956 return -1;
1959 if (src->folder != dest->folder) {
1960 GSList *infolist = NULL, *cur;
1961 int res = -1;
1962 for (cur = msglist; cur; cur = cur->next) {
1963 msginfo = (MsgInfo *)cur->data;
1964 MsgFileInfo *fileinfo = g_new0(MsgFileInfo, 1);
1965 fileinfo->file = procmsg_get_message_file(msginfo);
1966 fileinfo->flags = &(msginfo->flags);
1967 infolist = g_slist_prepend(infolist, fileinfo);
1969 infolist = g_slist_reverse(infolist);
1970 res = folder_item_add_msgs(dest, infolist, FALSE);
1971 for (cur = infolist; cur; cur = cur->next) {
1972 MsgFileInfo *info = (MsgFileInfo *)cur->data;
1973 g_free(info->file);
1974 g_free(info);
1976 g_slist_free(infolist);
1977 return res;
1980 lock_session(session); /* unlocked later in the function */
1982 ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder,
1983 NULL, NULL, NULL, NULL, NULL, FALSE);
1984 if (ok != MAILIMAP_NO_ERROR) {
1985 return ok;
1988 unlock_session(session);
1990 destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path, &ok);
1992 if (is_fatal(ok)) {
1993 g_free(destdir);
1994 return ok;
1997 seq_list = imap_get_lep_set_from_msglist(IMAP_FOLDER(folder), msglist);
1998 uid_hash = g_hash_table_new(g_direct_hash, g_direct_equal);
2000 statusbar_print_all(_("Copying messages..."));
2001 for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
2002 struct mailimap_set * seq_set;
2003 struct mailimap_set * source = NULL;
2004 struct mailimap_set * dest = NULL;
2005 seq_set = cur->data;
2007 debug_print("Copying messages from %s to %s ...\n",
2008 src->path, destdir);
2010 lock_session(session); /* unlocked later in the function */
2011 ok = imap_cmd_copy(session, seq_set, destdir,
2012 &source, &dest);
2014 if (is_fatal(ok)) {
2015 session = NULL;
2018 if (ok == MAILIMAP_NO_ERROR) {
2019 unlock_session(session);
2020 if (relation && source && dest) {
2021 GSList *s_list = flatten_mailimap_set(source);
2022 GSList *d_list = flatten_mailimap_set(dest);
2023 GSList *s_cur, *d_cur;
2024 if (g_slist_length(s_list) == g_slist_length(d_list)) {
2026 for (s_cur = s_list, d_cur = d_list;
2027 s_cur && d_cur;
2028 s_cur = s_cur->next, d_cur = d_cur->next) {
2029 g_hash_table_insert(uid_hash, s_cur->data, d_cur->data);
2032 } else {
2033 debug_print("hhhmm, source list length != dest list length.\n");
2035 g_slist_free(s_list);
2036 g_slist_free(d_list);
2041 if (source)
2042 mailimap_set_free(source);
2043 if (dest)
2044 mailimap_set_free(dest);
2046 if (ok != MAILIMAP_NO_ERROR) {
2047 g_hash_table_destroy(uid_hash);
2048 imap_lep_set_free(seq_list);
2049 statusbar_pop_all();
2050 return -1;
2054 for (cur = msglist; cur != NULL; cur = g_slist_next(cur)) {
2055 MsgInfo *msginfo = (MsgInfo *)cur->data;
2056 gpointer hashval;
2058 hashval = g_hash_table_lookup(uid_hash, GINT_TO_POINTER(msginfo->msgnum));
2060 if (hashval != NULL) {
2061 gint num = GPOINTER_TO_INT(hashval);
2062 g_hash_table_insert(relation, msginfo,
2063 GINT_TO_POINTER(num));
2064 if (num > last_num)
2065 last_num = num;
2066 debug_print("copied message %d as %d\n", msginfo->msgnum, num);
2067 /* put the local file in the imapcache, so that we don't
2068 * have to fetch it back later. */
2069 if (num > 0) {
2070 gchar *cache_path = folder_item_get_path(msginfo->folder);
2071 gchar *real_file = g_strconcat(
2072 cache_path, G_DIR_SEPARATOR_S,
2073 itos(msginfo->msgnum), NULL);
2074 gchar *cache_file = NULL;
2075 g_free(cache_path);
2076 cache_path = folder_item_get_path(dest);
2077 cache_file = g_strconcat(
2078 cache_path, G_DIR_SEPARATOR_S,
2079 itos(num), NULL);
2080 if (!is_dir_exist(cache_path))
2081 make_dir_hier(cache_path);
2082 if (is_file_exist(real_file) && is_dir_exist(cache_path)) {
2083 if (copy_file(real_file, cache_file, TRUE) < 0)
2084 debug_print("couldn't cache to %s: %s\n", cache_file,
2085 strerror(errno));
2086 else
2087 debug_print("copied to cache: %s\n", cache_file);
2089 g_free(real_file);
2090 g_free(cache_file);
2091 g_free(cache_path);
2093 } else
2094 g_hash_table_insert(relation, msginfo,
2095 GINT_TO_POINTER(0));
2097 statusbar_pop_all();
2099 g_hash_table_destroy(uid_hash);
2100 imap_lep_set_free(seq_list);
2102 g_free(destdir);
2104 IMAP_FOLDER_ITEM(dest)->lastuid = 0;
2105 IMAP_FOLDER_ITEM(dest)->uid_next = 0;
2106 g_slist_free(IMAP_FOLDER_ITEM(dest)->uid_list);
2107 IMAP_FOLDER_ITEM(dest)->uid_list = NULL;
2109 imap_scan_required(folder, dest);
2110 if (ok == MAILIMAP_NO_ERROR)
2111 return last_num;
2112 else
2113 return -1;
2116 static gint imap_copy_msg(Folder *folder, FolderItem *dest, MsgInfo *msginfo)
2118 GSList msglist;
2120 g_return_val_if_fail(msginfo != NULL, -1);
2122 msglist.data = msginfo;
2123 msglist.next = NULL;
2125 return imap_copy_msgs(folder, dest, &msglist, NULL);
2128 static gint imap_copy_msgs(Folder *folder, FolderItem *dest,
2129 MsgInfoList *msglist, GHashTable *relation)
2131 MsgInfo *msginfo;
2132 gint ret;
2134 g_return_val_if_fail(folder != NULL, -1);
2135 g_return_val_if_fail(dest != NULL, -1);
2136 g_return_val_if_fail(msglist != NULL, -1);
2138 msginfo = (MsgInfo *)msglist->data;
2139 g_return_val_if_fail(msginfo->folder != NULL, -1);
2141 ret = imap_do_copy_msgs(folder, dest, msglist, relation, FALSE);
2142 return ret;
2145 static gboolean imap_matcher_type_is_local(gint matchertype)
2147 switch (matchertype) {
2148 case MATCHCRITERIA_FROM:
2149 case MATCHCRITERIA_TO:
2150 case MATCHCRITERIA_CC:
2151 case MATCHCRITERIA_TO_OR_CC:
2152 case MATCHCRITERIA_SUBJECT:
2153 case MATCHCRITERIA_REFERENCES:
2154 case MATCHCRITERIA_MESSAGEID:
2155 case MATCHCRITERIA_INREPLYTO:
2156 case MATCHCRITERIA_AGE_GREATER:
2157 case MATCHCRITERIA_AGE_LOWER:
2158 case MATCHCRITERIA_FORWARDED:
2159 case MATCHCRITERIA_SPAM:
2160 case MATCHCRITERIA_UNREAD:
2161 case MATCHCRITERIA_NEW:
2162 case MATCHCRITERIA_MARKED:
2163 case MATCHCRITERIA_REPLIED:
2164 case MATCHCRITERIA_DELETED:
2165 case MATCHCRITERIA_SIZE_GREATER:
2166 case MATCHCRITERIA_SIZE_SMALLER:
2167 case MATCHCRITERIA_SIZE_EQUAL:
2168 return TRUE;
2170 return FALSE;
2173 static IMAPSearchKey* search_make_key(MatcherProp* match, gboolean* is_all)
2175 if (match->matchtype == MATCHTYPE_MATCHCASE || match->matchtype == MATCHTYPE_MATCH) {
2176 IMAPSearchKey* result = NULL;
2177 gboolean invert = FALSE;
2178 gint matchertype = match->criteria;
2180 if (is_all) {
2181 *is_all = FALSE;
2184 switch (matchertype) {
2185 case MATCHCRITERIA_NOT_NEW: invert = TRUE; matchertype = MATCHCRITERIA_NEW; break;
2186 case MATCHCRITERIA_NOT_MARKED: invert = TRUE; matchertype = MATCHCRITERIA_MARKED; break;
2187 case MATCHCRITERIA_NOT_FORWARDED: invert = TRUE; matchertype = MATCHCRITERIA_FORWARDED; break;
2188 case MATCHCRITERIA_NOT_SPAM: invert = TRUE; matchertype = MATCHCRITERIA_SPAM; break;
2189 case MATCHCRITERIA_NOT_SUBJECT: invert = TRUE; matchertype = MATCHCRITERIA_SUBJECT; break;
2190 case MATCHCRITERIA_NOT_FROM: invert = TRUE; matchertype = MATCHCRITERIA_FROM; break;
2191 case MATCHCRITERIA_NOT_TO: invert = TRUE; matchertype = MATCHCRITERIA_TO; break;
2192 case MATCHCRITERIA_NOT_CC: invert = TRUE; matchertype = MATCHCRITERIA_CC; break;
2193 case MATCHCRITERIA_NOT_REFERENCES: invert = TRUE; matchertype = MATCHCRITERIA_REFERENCES; break;
2194 case MATCHCRITERIA_NOT_HEADER: invert = TRUE; matchertype = MATCHCRITERIA_HEADER; break;
2195 case MATCHCRITERIA_NOT_TAG: invert = TRUE; matchertype = MATCHCRITERIA_TAG; break;
2196 case MATCHCRITERIA_NOT_HEADERS_PART: invert = TRUE; matchertype = MATCHCRITERIA_HEADERS_PART; break;
2197 case MATCHCRITERIA_NOT_HEADERS_CONT: invert = TRUE; matchertype = MATCHCRITERIA_HEADERS_CONT; break;
2198 case MATCHCRITERIA_NOT_MESSAGE: invert = TRUE; matchertype = MATCHCRITERIA_MESSAGE; break;
2199 case MATCHCRITERIA_NOT_BODY_PART: invert = TRUE; matchertype = MATCHCRITERIA_BODY_PART; break;
2200 case MATCHCRITERIA_NOT_TO_AND_NOT_CC: invert = TRUE; matchertype = MATCHCRITERIA_TO_OR_CC; break;
2201 case MATCHCRITERIA_NOT_MESSAGEID: invert = TRUE; matchertype = MATCHCRITERIA_MESSAGEID; break;
2202 case MATCHCRITERIA_NOT_INREPLYTO: invert = TRUE; matchertype = MATCHCRITERIA_INREPLYTO; break;
2206 * this aborts conversion even for predicates understood by the following code.
2207 * while that might seem wasteful, claws local search for information listed below
2208 * has proven faster than IMAP search plus network roundtrips. once this changes,
2209 * consider removing these exceptions.
2211 if (imap_matcher_type_is_local(matchertype))
2212 return NULL;
2214 /* the Message-ID header is also cached */
2215 if (matchertype == MATCHCRITERIA_HEADER && g_strcmp0("Message-ID", match->header) == 0) {
2216 return NULL;
2219 switch (matchertype) {
2220 case MATCHCRITERIA_FORWARDED:
2221 result = imap_search_new(IMAP_SEARCH_CRITERIA_TAG, NULL, RTAG_FORWARDED, 0);
2222 break;
2224 case MATCHCRITERIA_SPAM:
2225 result = imap_search_new(IMAP_SEARCH_CRITERIA_TAG, NULL, RTAG_JUNK, 0);
2226 break;
2228 case MATCHCRITERIA_MESSAGEID:
2229 result = imap_search_new(IMAP_SEARCH_CRITERIA_HEADER, "Message-ID", match->expr, 0);
2230 break;
2232 case MATCHCRITERIA_INREPLYTO:
2233 result = imap_search_new(IMAP_SEARCH_CRITERIA_HEADER, "In-Reply-To", match->expr, 0);
2234 break;
2236 case MATCHCRITERIA_REFERENCES:
2237 result = imap_search_new(IMAP_SEARCH_CRITERIA_HEADER, "References", match->expr, 0);
2238 break;
2240 case MATCHCRITERIA_TO_OR_CC:
2241 result = imap_search_or(
2242 imap_search_new(IMAP_SEARCH_CRITERIA_TO, NULL, match->expr, 0),
2243 imap_search_new(IMAP_SEARCH_CRITERIA_CC, NULL, match->expr, 0)
2245 break;
2247 case MATCHCRITERIA_HEADERS_PART:
2248 case MATCHCRITERIA_HEADERS_CONT:
2249 result = imap_search_and(
2250 imap_search_not(imap_search_new(IMAP_SEARCH_CRITERIA_BODY, NULL, match->expr, 0)),
2251 imap_search_new(IMAP_SEARCH_CRITERIA_MESSAGE, NULL, match->expr, 0)
2253 break;
2255 case MATCHCRITERIA_SIZE_EQUAL:
2256 result = imap_search_and(
2257 imap_search_not(imap_search_new(IMAP_SEARCH_CRITERIA_SIZE_SMALLER, NULL, NULL, match->value)),
2258 imap_search_not(imap_search_new(IMAP_SEARCH_CRITERIA_SIZE_GREATER, NULL, NULL, match->value))
2260 break;
2262 case MATCHCRITERIA_NOT_UNREAD:
2263 result = imap_search_new(IMAP_SEARCH_CRITERIA_READ, NULL, NULL, 0);
2264 break;
2266 case MATCHCRITERIA_UNREAD:
2267 result = imap_search_new(IMAP_SEARCH_CRITERIA_UNREAD, NULL, NULL, 0);
2268 break;
2270 case MATCHCRITERIA_NEW:
2271 result = imap_search_new(IMAP_SEARCH_CRITERIA_NEW, NULL, NULL, 0);
2272 break;
2274 case MATCHCRITERIA_MARKED:
2275 result = imap_search_new(IMAP_SEARCH_CRITERIA_MARKED, NULL, NULL, 0);
2276 break;
2278 case MATCHCRITERIA_DELETED:
2279 result = imap_search_new(IMAP_SEARCH_CRITERIA_DELETED, NULL, NULL, 0);
2280 break;
2282 case MATCHCRITERIA_REPLIED:
2283 result = imap_search_new(IMAP_SEARCH_CRITERIA_REPLIED, NULL, NULL, 0);
2284 break;
2286 case MATCHCRITERIA_TAG:
2288 gchar *tmp = imap_utf8_to_modified_utf7(match->expr, TRUE);
2289 result = imap_search_new(IMAP_SEARCH_CRITERIA_TAG, NULL, tmp, 0);
2290 g_free(tmp);
2292 break;
2294 case MATCHCRITERIA_SUBJECT:
2295 result = imap_search_new(IMAP_SEARCH_CRITERIA_SUBJECT, NULL, match->expr, 0);
2296 break;
2298 case MATCHCRITERIA_FROM:
2299 result = imap_search_new(IMAP_SEARCH_CRITERIA_FROM, NULL, match->expr, 0);
2300 break;
2302 case MATCHCRITERIA_TO:
2303 result = imap_search_new(IMAP_SEARCH_CRITERIA_TO, NULL, match->expr, 0);
2304 break;
2306 case MATCHCRITERIA_CC:
2307 result = imap_search_new(IMAP_SEARCH_CRITERIA_CC, NULL, match->expr, 0);
2308 break;
2310 case MATCHCRITERIA_AGE_GREATER:
2311 result = imap_search_new(IMAP_SEARCH_CRITERIA_AGE_GREATER, NULL, NULL, match->value);
2312 break;
2314 case MATCHCRITERIA_AGE_LOWER:
2315 result = imap_search_new(IMAP_SEARCH_CRITERIA_AGE_LOWER, NULL, NULL, match->value);
2316 break;
2318 case MATCHCRITERIA_BODY_PART:
2319 result = imap_search_new(IMAP_SEARCH_CRITERIA_BODY, NULL, match->expr, 0);
2320 break;
2322 case MATCHCRITERIA_MESSAGE:
2323 result = imap_search_new(IMAP_SEARCH_CRITERIA_MESSAGE, NULL, match->expr, 0);
2324 break;
2326 case MATCHCRITERIA_HEADER:
2327 result = imap_search_new(IMAP_SEARCH_CRITERIA_HEADER, match->header, match->expr, 0);
2328 break;
2330 case MATCHCRITERIA_SIZE_GREATER:
2331 result = imap_search_new(IMAP_SEARCH_CRITERIA_SIZE_GREATER, NULL, NULL, match->value);
2332 break;
2334 case MATCHCRITERIA_SIZE_SMALLER:
2335 result = imap_search_new(IMAP_SEARCH_CRITERIA_SIZE_SMALLER, NULL, NULL, match->value);
2336 break;
2338 default:
2339 result = imap_search_new(IMAP_SEARCH_CRITERIA_ALL, NULL, NULL, 0);
2340 if (is_all) {
2341 *is_all = TRUE;
2343 break;
2346 if (invert) {
2347 result = imap_search_not(result);
2348 if (is_all && *is_all) {
2349 *is_all = FALSE;
2353 return result;
2356 return NULL;
2359 static void imap_change_search_charset(IMAPFolder *folder)
2361 /* If server supports charset in searches, but the last used one failed,
2362 * changed to the next preferred charset. If none are still available,
2363 * disable charset searches.
2364 * Charsets are tried in the following order:
2365 * UTF-8, locale's charset, UTF-7.
2368 if (folder->search_charset_supported) {
2369 if (folder->search_charset && !strcmp(folder->search_charset, conv_get_locale_charset_str_no_utf8()))
2370 folder->search_charset = "UTF-8";
2371 else if (folder->search_charset && !strcmp(folder->search_charset, "UTF-8"))
2372 folder->search_charset = "UTF-7";
2373 else {
2374 folder->search_charset = NULL;
2375 folder->search_charset_supported = FALSE;
2380 static MatcherProp *imap_matcher_prop_set_charset(IMAPFolder *folder,
2381 MatcherProp *utf8_prop,
2382 gchar **charset)
2384 /* If the match is going to be done locally, or the criteria is on
2385 * tag (special-cased to modified-UTF-7), or the expression searched
2386 * is ASCII, don't bother converting.
2388 if (imap_matcher_type_is_local(utf8_prop->criteria)
2389 || utf8_prop->criteria == MATCHCRITERIA_TAG
2390 || utf8_prop->criteria == MATCHCRITERIA_NOT_TAG
2391 || utf8_prop->expr == NULL
2392 || is_ascii_str(utf8_prop->expr))
2393 return matcherprop_new(utf8_prop->criteria,
2394 utf8_prop->header,
2395 utf8_prop->matchtype,
2396 utf8_prop->expr,
2397 utf8_prop->value);
2398 else {
2399 gchar *conv_expr = NULL;
2401 /* If the search is server-side and the server doesn't support
2402 * searching with the charsets we handle, bail out.
2404 if (folder->search_charset_supported == FALSE)
2405 return NULL;
2407 /* Else, convert. */
2408 if (*charset == NULL)
2409 *charset = g_strdup(folder->search_charset);
2411 conv_expr = conv_codeset_strdup(utf8_prop->expr, CS_UTF_8, *charset);
2413 if (conv_expr == NULL)
2414 conv_expr = g_strdup(utf8_prop->expr);
2416 return matcherprop_new(utf8_prop->criteria,
2417 utf8_prop->header,
2418 utf8_prop->matchtype,
2419 conv_expr,
2420 utf8_prop->value);
2424 static gint search_msgs (Folder *folder,
2425 FolderItem *container,
2426 MsgNumberList **msgs,
2427 gboolean *on_server,
2428 MatcherList *predicate,
2429 SearchProgressNotify progress_cb,
2430 gpointer progress_data)
2432 IMAPSearchKey* key = NULL;
2433 GSList* cur;
2434 int result = -1;
2435 clist* uidlist = NULL;
2436 gboolean server_filtering_useless = FALSE;
2437 IMAPSession *session;
2438 gchar *charset_to_use = NULL;
2440 if (on_server == NULL || !*on_server) {
2441 return folder_item_search_msgs_local(folder, container, msgs, on_server,
2442 predicate, progress_cb, progress_data);
2445 for (cur = predicate->matchers; cur != NULL; cur = cur->next) {
2446 IMAPSearchKey* matcherPart = NULL;
2447 MatcherProp* prop = (MatcherProp*) cur->data;
2448 gboolean is_all;
2449 MatcherProp *imap_prop = imap_matcher_prop_set_charset(IMAP_FOLDER(folder), prop, &charset_to_use);
2451 if (imap_prop == NULL) {
2452 /* Couldn't convert matcherprop to IMAP - probably not ascii
2453 * and server doesn't support the charsets we do. */
2454 return -1;
2457 matcherPart = search_make_key(imap_prop, &is_all);
2459 matcherprop_free(imap_prop);
2461 if (on_server) {
2462 *on_server &= matcherPart != NULL && prop->matchtype == MATCHTYPE_MATCHCASE;
2465 if (matcherPart) {
2466 if (key == NULL) {
2467 key = matcherPart;
2468 server_filtering_useless = is_all;
2469 } else if (predicate->bool_and) {
2470 key = imap_search_and(key, matcherPart);
2471 server_filtering_useless &= is_all;
2472 } else {
2473 key = imap_search_or(key, matcherPart);
2474 server_filtering_useless |= is_all;
2479 if (server_filtering_useless) {
2480 imap_search_free(key);
2481 key = NULL;
2484 if (key == NULL && progress_cb != NULL) {
2485 GSList* cur;
2486 GSList* list;
2487 int count = 0;
2489 progress_cb(progress_data, TRUE, 0, 0, container->total_msgs);
2490 progress_cb(progress_data, TRUE, container->total_msgs, 0, container->total_msgs);
2492 list = folder_item_get_msg_list(container);
2493 for (cur = list; cur != NULL; cur = cur->next) {
2494 *msgs = g_slist_prepend(*msgs, GUINT_TO_POINTER(((MsgInfo*) cur->data)->msgnum));
2495 count++;
2497 procmsg_msg_list_free(list);
2499 *msgs = g_slist_reverse(*msgs);
2501 return count;
2504 session = imap_session_get(folder);
2505 if (!session) {
2506 return -1;
2508 result = imap_select(session, IMAP_FOLDER(folder), FOLDER_ITEM(container),
2509 NULL, NULL, NULL, NULL, NULL, TRUE);
2510 if (result != MAILIMAP_NO_ERROR)
2511 return -1;
2513 if (progress_cb)
2514 progress_cb(progress_data, TRUE, 0, 0, container->total_msgs);
2515 result = imap_threaded_search(folder, IMAP_SEARCH_TYPE_KEYED, key, charset_to_use, NULL, &uidlist);
2516 if (progress_cb)
2517 progress_cb(progress_data, TRUE, container->total_msgs, 0, container->total_msgs);
2519 if (result == MAILIMAP_ERROR_PROTOCOL) {
2520 debug_print("Server side search unavailable, using local search\n");
2521 imap_handle_error(SESSION(session), NULL, result);
2522 result = folder_item_search_msgs_local(folder, container, msgs, NULL,
2523 predicate, progress_cb, progress_data);
2524 if (result < 0) {
2525 debug_print("search_msgs - got protocol error, aborting\n");
2526 alertpanel_error_log(_("Search failed due to server error."));
2527 return -1;
2530 return result;
2533 if (result == MAILIMAP_NO_ERROR) {
2534 gint result = 0;
2536 *msgs = imap_uid_list_from_lep(uidlist, &result);
2538 mailimap_search_result_free(uidlist);
2540 if (charset_to_use != NULL)
2541 g_free(charset_to_use);
2543 return result;
2544 } else if (charset_to_use != NULL) {
2545 /* If search failed and was on an 8-bit string, try the next
2546 * available charset to search if there still are some.
2548 g_free(charset_to_use);
2550 imap_change_search_charset(IMAP_FOLDER(folder));
2551 if (IMAP_FOLDER(folder)->search_charset_supported)
2552 return search_msgs(folder, container, msgs, on_server, predicate,
2553 progress_cb, progress_data);
2554 else {
2555 imap_handle_error(SESSION(session), NULL, result);
2556 return -1;
2558 } else {
2559 imap_handle_error(SESSION(session), NULL, result);
2560 return -1;
2565 static gint imap_do_remove_msgs(Folder *folder, FolderItem *dest,
2566 MsgInfoList *msglist, GHashTable *relation)
2568 gchar *destdir, *dir;
2569 GSList *numlist = NULL, *cur;
2570 MsgInfo *msginfo;
2571 IMAPSession *session;
2572 gint ok = MAILIMAP_NO_ERROR;
2574 g_return_val_if_fail(folder != NULL, -1);
2575 g_return_val_if_fail(dest != NULL, -1);
2576 g_return_val_if_fail(msglist != NULL, -1);
2578 debug_print("getting session...\n");
2579 session = imap_session_get(folder);
2580 if (!session) {
2581 return -1;
2584 lock_session(session); /* unlocked later in the function */
2586 msginfo = (MsgInfo *)msglist->data;
2588 ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder,
2589 NULL, NULL, NULL, NULL, NULL, FALSE);
2590 if (ok != MAILIMAP_NO_ERROR) {
2591 return ok;
2594 destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path, &ok);
2595 if (is_fatal(ok)) {
2596 g_free(destdir);
2597 return ok;
2599 for (cur = msglist; cur; cur = cur->next) {
2600 msginfo = (MsgInfo *)cur->data;
2601 if (!MSG_IS_DELETED(msginfo->flags))
2602 numlist = g_slist_prepend(numlist, GINT_TO_POINTER(msginfo->msgnum));
2604 numlist = g_slist_reverse(numlist);
2606 if (numlist != NULL) {
2607 ok = imap_set_message_flags
2608 (session, IMAP_FOLDER_ITEM(msginfo->folder), numlist, IMAP_FLAG_DELETED, NULL, TRUE);
2609 if (ok != MAILIMAP_NO_ERROR) {
2610 log_warning(LOG_PROTOCOL, _("can't set deleted flags\n"));
2611 g_free(destdir);
2612 return ok;
2614 } /* else we just need to expunge */
2615 ok = imap_cmd_expunge(session);
2616 if (ok != MAILIMAP_NO_ERROR) {
2617 log_warning(LOG_PROTOCOL, _("can't expunge\n"));
2618 g_free(destdir);
2619 return ok;
2622 session->folder_content_changed = TRUE;
2623 unlock_session(session);
2625 dir = folder_item_get_path(msginfo->folder);
2626 if (is_dir_exist(dir)) {
2627 for (cur = msglist; cur; cur = cur->next) {
2628 msginfo = (MsgInfo *)cur->data;
2629 remove_numbered_files(dir, msginfo->msgnum, msginfo->msgnum);
2632 g_free(dir);
2634 g_slist_free(numlist);
2636 imap_scan_required(folder, dest);
2638 g_free(destdir);
2640 return 0;
2643 static gint imap_remove_msgs(Folder *folder, FolderItem *dest,
2644 MsgInfoList *msglist, GHashTable *relation)
2646 MsgInfo *msginfo;
2648 g_return_val_if_fail(folder != NULL, -1);
2649 g_return_val_if_fail(dest != NULL, -1);
2650 if (msglist == NULL)
2651 return 0;
2653 msginfo = (MsgInfo *)msglist->data;
2654 g_return_val_if_fail(msginfo->folder != NULL, -1);
2656 return imap_do_remove_msgs(folder, dest, msglist, relation);
2659 static gint imap_remove_all_msg(Folder *folder, FolderItem *item)
2661 GSList *list = folder_item_get_msg_list(item);
2662 gint res = imap_remove_msgs(folder, item, list, NULL);
2663 procmsg_msg_list_free(list);
2664 return res;
2667 static gboolean imap_is_msg_changed(Folder *folder, FolderItem *item,
2668 MsgInfo *msginfo)
2670 /* TODO: properly implement this method */
2671 return FALSE;
2674 static gint imap_close(Folder *folder, FolderItem *item)
2676 return 0;
2679 static gint imap_scan_tree_real(Folder *folder, gboolean subs_only)
2681 FolderItem *item = NULL;
2682 IMAPSession *session;
2683 gchar *root_folder = NULL;
2685 g_return_val_if_fail(folder != NULL, -1);
2686 g_return_val_if_fail(folder->account != NULL, -1);
2688 debug_print("getting session...\n");
2689 session = imap_session_get(folder);
2690 if (!session) {
2691 if (!folder->node) {
2692 folder_tree_destroy(folder);
2693 item = folder_item_new(folder, folder->name, NULL);
2694 item->folder = folder;
2695 folder->node = item->node = g_node_new(item);
2697 return -1;
2700 if (folder->account->imap_dir && *folder->account->imap_dir) {
2701 gchar *real_path;
2702 int r = MAILIMAP_NO_ERROR;
2703 clist * lep_list;
2705 Xstrdup_a(root_folder, folder->account->imap_dir, {return -1;});
2706 extract_quote(root_folder, '"');
2707 subst_char(root_folder,
2708 imap_get_path_separator(session, IMAP_FOLDER(folder),
2709 root_folder, &r),
2710 '/');
2711 if (is_fatal(r))
2712 return -1;
2713 strtailchomp(root_folder, '/');
2714 real_path = imap_get_real_path
2715 (session, IMAP_FOLDER(folder), root_folder, &r);
2716 if (is_fatal(r)) {
2717 g_free(real_path);
2718 return -1;
2720 debug_print("IMAP root directory: %s\n", real_path);
2722 /* check if root directory exist */
2724 r = imap_threaded_list(session->folder, "", real_path,
2725 &lep_list);
2727 if (r != MAILIMAP_NO_ERROR)
2728 imap_handle_error(SESSION(session), NULL, r);
2730 if ((r != MAILIMAP_NO_ERROR) || (clist_count(lep_list) == 0)) {
2731 if (!folder->node) {
2732 item = folder_item_new(folder, folder->name, NULL);
2733 item->folder = folder;
2734 folder->node = item->node = g_node_new(item);
2736 return -1;
2738 mailimap_list_result_free(lep_list);
2740 g_free(real_path);
2743 if (folder->node)
2744 item = FOLDER_ITEM(folder->node->data);
2746 if (item && !item->path && root_folder) {
2747 item->path = g_strdup(root_folder);
2750 if (!item || ((item->path || root_folder) &&
2751 g_strcmp0(item->path, root_folder) != 0)) {
2752 folder_tree_destroy(folder);
2753 item = folder_item_new(folder, folder->name, root_folder);
2754 item->folder = folder;
2755 folder->node = item->node = g_node_new(item);
2758 imap_scan_tree_recursive(session, FOLDER_ITEM(folder->node->data), subs_only);
2759 imap_create_missing_folders(folder);
2761 return 0;
2764 static gint imap_scan_tree(Folder *folder)
2766 gboolean subs_only = FALSE;
2767 if (folder->account) {
2768 debug_print(" scanning only subs %d\n", folder->account->imap_subsonly);
2769 subs_only = folder->account->imap_subsonly;
2771 return imap_scan_tree_real(folder, subs_only);
2774 static gint imap_scan_tree_recursive(IMAPSession *session, FolderItem *item, gboolean subs_only)
2776 /* reset recursion depth counter */
2777 session->scan_tree_recurs_depth = 0;
2779 return imap_scan_tree_recursive_dive(session, item, subs_only);
2782 static gint imap_scan_tree_recursive_dive(IMAPSession *session, FolderItem *item, gboolean subs_only)
2784 Folder *folder;
2785 IMAPFolder *imapfolder;
2786 FolderItem *new_item;
2787 GSList *item_list, *cur;
2788 GNode *node;
2789 gchar *real_path;
2790 gchar *wildcard_path;
2791 gchar separator;
2792 gchar wildcard[3];
2793 clist * lep_list;
2794 int r = MAILIMAP_NO_ERROR;
2796 g_return_val_if_fail(item != NULL, -1);
2797 g_return_val_if_fail(item->folder != NULL, -1);
2798 g_return_val_if_fail(item->no_sub == FALSE, -1);
2800 /* recursion depth limiter */
2801 if(session->scan_tree_recurs_depth >= prefs_common.imap_scan_tree_recurs_limit) {
2802 g_warning("IMAP scan tree recursion limit reached (%d, folder '%s')",
2803 prefs_common.imap_scan_tree_recurs_limit, item->folder->name);
2804 return -1;
2806 /* entering recursion func: increase depth counter */
2807 session->scan_tree_recurs_depth++;
2809 folder = item->folder;
2810 imapfolder = IMAP_FOLDER(folder);
2812 separator = imap_get_path_separator(session, imapfolder, item->path, &r);
2813 if (is_fatal(r))
2814 return r;
2816 if (folder->ui_func)
2817 folder->ui_func(folder, item, folder->ui_func_data);
2819 if (item->path) {
2820 wildcard[0] = separator;
2821 wildcard[1] = '%';
2822 wildcard[2] = '\0';
2823 real_path = imap_get_real_path(session, imapfolder, item->path, &r);
2824 if (is_fatal(r)) {
2825 g_free(real_path);
2826 return r;
2828 } else {
2829 wildcard[0] = '%';
2830 wildcard[1] = '\0';
2831 real_path = g_strdup("");
2834 Xstrcat_a(wildcard_path, real_path, wildcard,
2835 {g_free(real_path); return MAILIMAP_ERROR_BAD_STATE;});
2836 lep_list = NULL;
2838 if (subs_only)
2839 r = imap_threaded_lsub(folder, "", wildcard_path, &lep_list);
2840 else
2841 r = imap_threaded_list(folder, "", wildcard_path, &lep_list);
2843 if (r != MAILIMAP_NO_ERROR) {
2844 imap_handle_error(SESSION(session), NULL, r);
2845 item_list = NULL;
2846 g_free(real_path);
2847 return r;
2849 else {
2850 item_list = imap_list_from_lep(imapfolder,
2851 lep_list, real_path, FALSE);
2852 mailimap_list_result_free(lep_list);
2855 g_free(real_path);
2857 node = item->node->children;
2858 while (node != NULL) {
2859 FolderItem *old_item = FOLDER_ITEM(node->data);
2860 GNode *next = node->next;
2862 new_item = NULL;
2863 for (cur = item_list; cur != NULL; cur = cur->next) {
2864 FolderItem *cur_item = FOLDER_ITEM(cur->data);
2865 if (!g_strcmp0(old_item->path, cur_item->path)) {
2866 new_item = cur_item;
2867 break;
2870 if (!new_item) {
2871 if (old_item && old_item->path && !strcasecmp(old_item->path, "INBOX")) {
2872 debug_print("not removing INBOX\n");
2873 } else {
2874 debug_print("folder '%s' not found. removing...\n",
2875 old_item->path);
2876 folder_item_remove(old_item);
2878 } else {
2879 old_item->no_sub = new_item->no_sub;
2880 old_item->no_select = new_item->no_select;
2881 if (old_item->no_sub == TRUE && node->children) {
2882 debug_print("folder '%s' doesn't have "
2883 "subfolders. removing...\n",
2884 old_item->path);
2885 folder_item_remove_children(old_item);
2889 node = next;
2892 for (cur = item_list; cur != NULL; cur = cur->next) {
2893 FolderItem *cur_item = FOLDER_ITEM(cur->data);
2894 new_item = NULL;
2896 for (node = item->node->children; node != NULL;
2897 node = node->next) {
2898 if (!g_strcmp0(FOLDER_ITEM(node->data)->path,
2899 cur_item->path)) {
2900 new_item = FOLDER_ITEM(node->data);
2901 folder_item_destroy(cur_item);
2902 cur_item = NULL;
2903 break;
2906 if (!new_item) {
2907 new_item = cur_item;
2908 debug_print("new folder '%s' found.\n", new_item->path);
2909 folder_item_append(item, new_item);
2912 if (!strcasecmp(new_item->path, "INBOX")) {
2913 new_item->stype = F_INBOX;
2914 folder->inbox = new_item;
2915 } else if (!folder_item_parent(item) || item->stype == F_INBOX) {
2916 gchar *base;
2918 base = g_path_get_basename(new_item->path);
2920 if (!folder->outbox && !g_ascii_strcasecmp(base, "Sent")) {
2921 new_item->stype = F_OUTBOX;
2922 folder->outbox = new_item;
2923 } else if (!folder->draft && (!g_ascii_strcasecmp(base, "Drafts") || !g_ascii_strcasecmp(base, "Draft"))) {
2924 new_item->stype = F_DRAFT;
2925 folder->draft = new_item;
2926 } else if (!folder->queue && !g_ascii_strcasecmp(base, "Queue")) {
2927 new_item->stype = F_QUEUE;
2928 folder->queue = new_item;
2929 } else if (!folder->trash && !g_ascii_strcasecmp(base, "Trash")) {
2930 new_item->stype = F_TRASH;
2931 folder->trash = new_item;
2933 g_free(base);
2936 if (new_item->no_sub == FALSE) {
2937 imap_scan_tree_recursive_dive(session, new_item, subs_only);
2939 /* entering recursion func: increase depth counter */
2940 session->scan_tree_recurs_depth--;
2941 if (session->scan_tree_recurs_depth < 0)
2942 g_error("IMAP scan tree recursion underflow (%d)",
2943 session->scan_tree_recurs_depth);
2947 g_slist_free(item_list);
2949 return MAILIMAP_NO_ERROR;
2952 GList *imap_scan_subtree(Folder *folder, FolderItem *item, gboolean unsubs_only, gboolean recursive)
2954 IMAPSession *session = imap_session_get(folder);
2955 gchar *real_path;
2956 gchar *wildcard_path;
2957 gchar separator;
2958 gchar wildcard[3];
2959 clist * lep_list;
2960 GSList *item_list = NULL, *cur;
2961 GList *child_list = NULL, *tmplist = NULL;
2962 GSList *sub_list = NULL;
2963 int r = MAILIMAP_NO_ERROR;
2965 if (!session)
2966 return NULL;
2968 separator = imap_get_path_separator(session, IMAP_FOLDER(folder), item->path, &r);
2969 if (is_fatal(r))
2970 return NULL;
2972 if (item->path) {
2973 wildcard[0] = separator;
2974 wildcard[1] = '%';
2975 wildcard[2] = '\0';
2976 real_path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path, &r);
2977 if (is_fatal(r)) {
2978 g_free(real_path);
2979 return NULL;
2981 } else {
2982 wildcard[0] = '%';
2983 wildcard[1] = '\0';
2984 real_path = g_strdup("");
2987 Xstrcat_a(wildcard_path, real_path, wildcard,
2988 {g_free(real_path); return NULL;});
2989 lep_list = NULL;
2991 if (unsubs_only)
2992 statusbar_print_all(_("Looking for unsubscribed folders in %s..."),
2993 item->path?item->path:item->name);
2994 else
2995 statusbar_print_all(_("Looking for subfolders of %s..."),
2996 item->path?item->path:item->name);
2998 r = imap_threaded_list(folder, "", wildcard_path, &lep_list);
2999 if (r) {
3000 g_free(real_path);
3001 statusbar_pop_all();
3002 return NULL;
3004 item_list = imap_list_from_lep(IMAP_FOLDER(folder),
3005 lep_list, real_path, FALSE);
3006 mailimap_list_result_free(lep_list);
3008 for (cur = item_list; cur != NULL; cur = cur->next) {
3009 FolderItem *cur_item = FOLDER_ITEM(cur->data);
3010 if (recursive) {
3011 tmplist = imap_scan_subtree(folder, cur_item,
3012 unsubs_only, recursive);
3013 if (tmplist)
3014 child_list = g_list_concat(child_list, tmplist);
3016 child_list = g_list_prepend(child_list,
3017 imap_get_real_path(session,
3018 IMAP_FOLDER(folder), cur_item->path, &r));
3019 if (is_fatal(r)) {
3020 g_free(real_path);
3021 statusbar_pop_all();
3022 return NULL;
3024 folder_item_destroy(cur_item);
3026 child_list = g_list_reverse(child_list);
3027 g_slist_free(item_list);
3029 if (unsubs_only) {
3030 r = imap_threaded_lsub(folder, "", wildcard_path, &lep_list);
3031 if (r) {
3032 g_free(real_path);
3033 statusbar_pop_all();
3034 return NULL;
3036 sub_list = imap_list_from_lep(IMAP_FOLDER(folder),
3037 lep_list, real_path, FALSE);
3038 mailimap_list_result_free(lep_list);
3040 for (cur = sub_list; cur != NULL; cur = cur->next) {
3041 FolderItem *cur_item = FOLDER_ITEM(cur->data);
3042 GList *oldlitem = NULL;
3043 gchar *tmp = imap_get_real_path(session,
3044 IMAP_FOLDER(folder), cur_item->path, &r);
3045 if (r) {
3046 g_free(real_path);
3047 statusbar_pop_all();
3048 g_free(tmp);
3049 return NULL;
3051 folder_item_destroy(cur_item);
3052 oldlitem = g_list_find_custom(
3053 child_list, tmp, (GCompareFunc)g_strcmp0);
3054 if (oldlitem) {
3055 child_list = g_list_remove_link(child_list, oldlitem);
3056 g_free(oldlitem->data);
3057 g_list_free(oldlitem);
3059 g_free(tmp);
3063 g_free(real_path);
3064 statusbar_pop_all();
3066 return child_list;
3069 static gint imap_create_tree(Folder *folder)
3071 g_return_val_if_fail(folder != NULL, -1);
3072 g_return_val_if_fail(folder->node != NULL, -1);
3073 g_return_val_if_fail(folder->node->data != NULL, -1);
3074 g_return_val_if_fail(folder->account != NULL, -1);
3076 imap_scan_tree(folder);
3077 imap_create_missing_folders(folder);
3079 return 0;
3082 static void imap_create_missing_folders(Folder *folder)
3084 g_return_if_fail(folder != NULL);
3086 if (!folder->inbox)
3087 folder->inbox = imap_create_special_folder
3088 (folder, F_INBOX, "INBOX");
3089 if (!folder->trash)
3090 folder->trash = imap_create_special_folder
3091 (folder, F_TRASH, "Trash");
3092 if (!folder->queue)
3093 folder->queue = imap_create_special_folder
3094 (folder, F_QUEUE, "Queue");
3095 if (!folder->outbox)
3096 folder->outbox = imap_create_special_folder
3097 (folder, F_OUTBOX, "Sent");
3098 if (!folder->draft)
3099 folder->draft = imap_create_special_folder
3100 (folder, F_DRAFT, "Drafts");
3103 static FolderItem *imap_create_special_folder(Folder *folder,
3104 SpecialFolderItemType stype,
3105 const gchar *name)
3107 FolderItem *item;
3108 FolderItem *new_item;
3110 g_return_val_if_fail(folder != NULL, NULL);
3111 g_return_val_if_fail(folder->node != NULL, NULL);
3112 g_return_val_if_fail(folder->node->data != NULL, NULL);
3113 g_return_val_if_fail(folder->account != NULL, NULL);
3114 g_return_val_if_fail(name != NULL, NULL);
3116 item = FOLDER_ITEM(folder->node->data);
3117 new_item = imap_create_folder(folder, item, name);
3119 if (!new_item) {
3120 g_warning("Can't create '%s'", name);
3121 if (!folder->inbox) return NULL;
3123 new_item = imap_create_folder(folder, folder->inbox, name);
3124 if (!new_item)
3125 g_warning("Can't create '%s' under INBOX", name);
3126 else
3127 new_item->stype = stype;
3128 } else
3129 new_item->stype = stype;
3131 return new_item;
3134 #ifdef G_OS_WIN32
3135 static gchar *imap_encode_unsafe_chars(const gchar *str)
3137 gchar *ret = NULL, *o_ret;
3138 gchar *i;
3139 if (!str)
3140 return NULL;
3141 ret = g_malloc(3*strlen(str)+1);
3142 o_ret = ret;
3143 for (i = (gchar *)str; *i; i++) {
3144 switch(*i) {
3145 case ':':
3146 case '|':
3147 case '<':
3148 case '>':
3149 case '*':
3150 case '?':
3151 case '#':
3152 *ret++ = '%';
3153 *ret++ = '0'+(*i/10);
3154 *ret++ = '0'+(*i%10);
3155 break;
3156 default:
3157 *ret++ = *i;
3160 *ret++ = '\0';
3161 return o_ret;
3163 #endif
3164 static gchar *imap_item_get_path(Folder *folder, FolderItem *item)
3166 gchar *folder_path, *path;
3167 gchar *item_path = NULL;
3169 g_return_val_if_fail(folder != NULL, NULL);
3170 g_return_val_if_fail(folder->account != NULL, NULL);
3171 g_return_val_if_fail(item != NULL, NULL);
3172 folder_path = prefs_account_cache_dir(folder->account, FALSE);
3174 g_return_val_if_fail(folder_path != NULL, NULL);
3176 #ifdef G_OS_UNIX
3177 item_path = g_strdup(item->path);
3178 #else
3179 item_path = imap_encode_unsafe_chars(item->path);
3180 #endif
3182 if (g_path_is_absolute(folder_path)) {
3183 if (item_path)
3184 path = g_strconcat(folder_path, G_DIR_SEPARATOR_S,
3185 item_path, NULL);
3186 else
3187 path = g_strdup(folder_path);
3188 } else {
3189 if (item_path)
3190 path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
3191 folder_path, G_DIR_SEPARATOR_S,
3192 item_path, NULL);
3193 else
3194 path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
3195 folder_path, NULL);
3197 g_free(folder_path);
3198 g_free(item_path);
3199 #ifdef G_OS_WIN32
3200 while (strchr(path, '/'))
3201 *strchr(path, '/') = '\\';
3202 #endif
3204 return path;
3207 static FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
3208 const gchar *name)
3210 gchar *dirpath, *imap_path;
3211 IMAPSession *session;
3212 FolderItem *new_item;
3213 gchar separator;
3214 gchar *new_name;
3215 const gchar *p;
3216 gint ok = MAILIMAP_NO_ERROR;
3217 gboolean no_select = FALSE, no_sub = FALSE;
3218 gboolean exist = FALSE;
3220 g_return_val_if_fail(folder != NULL, NULL);
3221 g_return_val_if_fail(folder->account != NULL, NULL);
3222 g_return_val_if_fail(parent != NULL, NULL);
3223 g_return_val_if_fail(name != NULL, NULL);
3225 if (to_number(name) > 0) {
3226 gchar *cached_msg = imap_get_cached_filename(parent, to_number(name));
3227 if (is_file_exist(cached_msg)) {
3228 if (claws_unlink(cached_msg) != 0) {
3229 return NULL;
3234 debug_print("getting session...\n");
3235 session = imap_session_get(folder);
3236 if (!session) {
3237 return NULL;
3240 if (!folder_item_parent(parent) && strcasecmp(name, "INBOX") == 0) {
3241 dirpath = g_strdup(name);
3242 }else if (parent->path)
3243 dirpath = g_strconcat(parent->path, "/", name, NULL);
3244 else if ((p = strchr(name, '/')) != NULL && *(p + 1) != '\0')
3245 dirpath = g_strdup(name);
3246 else if (folder->account->imap_dir && *folder->account->imap_dir) {
3247 gchar *imap_dir;
3249 Xstrdup_a(imap_dir, folder->account->imap_dir, {return NULL;});
3250 strtailchomp(imap_dir, '/');
3251 dirpath = g_strconcat(imap_dir, "/", name, NULL);
3252 } else
3253 dirpath = g_strdup(name);
3257 /* keep trailing directory separator to create a folder that contains
3258 sub folder */
3259 imap_path = imap_utf8_to_modified_utf7(dirpath, FALSE);
3261 strtailchomp(dirpath, '/');
3262 Xstrdup_a(new_name, name, {
3263 g_free(dirpath);
3264 g_free(imap_path);
3265 return NULL;});
3267 separator = imap_get_path_separator(session, IMAP_FOLDER(folder), imap_path, &ok);
3268 if (is_fatal(ok)) {
3269 g_free(imap_path);
3270 return NULL;
3272 imap_path_separator_subst(imap_path, separator);
3273 /* remove trailing / for display */
3274 strtailchomp(new_name, '/');
3276 if (strcasecmp(dirpath, "INBOX") != 0) {
3277 int r;
3278 clist * lep_list;
3280 r = imap_threaded_list(folder, "", imap_path, &lep_list);
3281 if (r != MAILIMAP_NO_ERROR) {
3282 imap_handle_error(SESSION(session), NULL, r);
3283 log_warning(LOG_PROTOCOL, _("can't create mailbox: LIST failed\n"));
3284 g_free(imap_path);
3285 g_free(dirpath);
3286 return NULL;
3289 if (clist_count(lep_list) > 0)
3290 exist = TRUE;
3291 mailimap_list_result_free(lep_list);
3292 lep_list = NULL;
3293 if (!exist) {
3294 ok = imap_cmd_create(session, imap_path);
3295 if (ok != MAILIMAP_NO_ERROR) {
3296 log_warning(LOG_PROTOCOL, _("can't create mailbox\n"));
3297 g_free(imap_path);
3298 g_free(dirpath);
3299 return NULL;
3301 r = imap_threaded_list(folder, "", imap_path, &lep_list);
3302 if (r == MAILIMAP_NO_ERROR) {
3303 GSList *item_list = imap_list_from_lep(IMAP_FOLDER(folder),
3304 lep_list, dirpath, TRUE);
3305 if (item_list) {
3306 FolderItem *cur_item = FOLDER_ITEM(item_list->data);
3307 no_select = cur_item->no_select;
3308 no_sub = cur_item->no_sub;
3309 g_slist_free(item_list);
3311 mailimap_list_result_free(lep_list);
3312 } else {
3313 imap_handle_error(SESSION(session), NULL, r);
3316 imap_threaded_subscribe(folder, imap_path, TRUE);
3317 } else {
3318 clist *lep_list;
3319 int r;
3320 /* just get flags */
3321 r = imap_threaded_list(folder, "", "INBOX", &lep_list);
3322 if (r == MAILIMAP_NO_ERROR) {
3323 GSList *item_list = imap_list_from_lep(IMAP_FOLDER(folder),
3324 lep_list, dirpath, TRUE);
3325 if (item_list) {
3326 FolderItem *cur_item = FOLDER_ITEM(item_list->data);
3327 no_select = cur_item->no_select;
3328 no_sub = cur_item->no_sub;
3329 g_slist_free(item_list);
3331 mailimap_list_result_free(lep_list);
3332 } else {
3333 imap_handle_error(SESSION(session), NULL, r);
3337 new_item = folder_item_new(folder, new_name, dirpath);
3338 new_item->no_select = no_select;
3339 new_item->no_sub = no_sub;
3340 folder_item_append(parent, new_item);
3341 g_free(imap_path);
3342 g_free(dirpath);
3344 dirpath = folder_item_get_path(new_item);
3345 if (!is_dir_exist(dirpath))
3346 make_dir_hier(dirpath);
3347 g_free(dirpath);
3349 if (exist) {
3350 /* folder existed, scan it */
3351 imap_scan_required(folder, new_item);
3352 folder_item_scan_full(new_item, FALSE);
3355 return new_item;
3358 static gint imap_rename_folder(Folder *folder, FolderItem *item,
3359 const gchar *name)
3361 gchar *dirpath;
3362 gchar *newpath;
3363 gchar *real_oldpath;
3364 gchar *real_newpath;
3365 gchar *paths[2];
3366 gchar *old_cache_dir;
3367 gchar *new_cache_dir;
3368 IMAPSession *session;
3369 gchar separator;
3370 gint ok = MAILIMAP_NO_ERROR;
3371 gint exists, recent, unseen;
3372 guint32 uid_validity;
3374 g_return_val_if_fail(folder != NULL, -1);
3375 g_return_val_if_fail(item != NULL, -1);
3376 g_return_val_if_fail(item->path != NULL, -1);
3377 g_return_val_if_fail(name != NULL, -1);
3379 debug_print("getting session...\n");
3380 session = imap_session_get(folder);
3381 if (!session) {
3382 return -1;
3385 if (strchr(name, imap_get_path_separator(session, IMAP_FOLDER(folder), item->path, &ok)) != NULL ||
3386 is_fatal(ok)) {
3387 g_warning("New folder name must not contain the namespace "
3388 "path separator");
3389 return -1;
3392 real_oldpath = imap_get_real_path(session, IMAP_FOLDER(folder), item->path, &ok);
3393 if (is_fatal(ok)) {
3394 g_free(real_oldpath);
3395 return -1;
3398 g_free(session->mbox);
3399 session->mbox = NULL;
3400 session->exists = 0;
3401 session->recent = 0;
3402 session->expunge = 0;
3403 ok = imap_cmd_examine(session, "INBOX",
3404 &exists, &recent, &unseen, &uid_validity, FALSE);
3405 if (ok != MAILIMAP_NO_ERROR) {
3406 g_free(real_oldpath);
3407 return -1;
3410 separator = imap_get_path_separator(session, IMAP_FOLDER(folder), item->path, &ok);
3411 if (is_fatal(ok)) {
3412 g_free(real_oldpath);
3413 return -1;
3415 if (strchr(item->path, '/')) {
3416 dirpath = g_path_get_dirname(item->path);
3417 newpath = g_strconcat(dirpath, "/", name, NULL);
3418 g_free(dirpath);
3419 } else
3420 newpath = g_strdup(name);
3422 real_newpath = imap_utf8_to_modified_utf7(newpath, FALSE);
3423 imap_path_separator_subst(real_newpath, separator);
3425 ok = imap_cmd_rename(session, real_oldpath, real_newpath);
3426 if (ok != MAILIMAP_NO_ERROR) {
3427 log_warning(LOG_PROTOCOL, _("can't rename mailbox: %s to %s\n"),
3428 real_oldpath, real_newpath);
3429 g_free(real_oldpath);
3430 g_free(newpath);
3431 g_free(real_newpath);
3432 return -1;
3434 g_free(item->name);
3435 item->name = g_strdup(name);
3437 old_cache_dir = folder_item_get_path(item);
3439 paths[0] = g_strdup(item->path);
3440 paths[1] = newpath;
3441 g_node_traverse(item->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1,
3442 imap_rename_folder_func, paths);
3444 if (is_dir_exist(old_cache_dir)) {
3445 new_cache_dir = folder_item_get_path(item);
3446 if (g_rename(old_cache_dir, new_cache_dir) < 0) {
3447 FILE_OP_ERROR(old_cache_dir, "rename");
3449 g_free(new_cache_dir);
3452 g_free(old_cache_dir);
3453 g_free(paths[0]);
3454 g_free(newpath);
3455 g_free(real_oldpath);
3456 g_free(real_newpath);
3457 return 0;
3460 gint imap_subscribe(Folder *folder, FolderItem *item, gchar *rpath, gboolean sub)
3462 gchar *path;
3463 gint r = MAILIMAP_NO_ERROR;
3464 IMAPSession *session;
3465 debug_print("getting session...\n");
3467 session = imap_session_get(folder);
3468 if (!session) {
3469 return -1;
3471 if (item && item->path) {
3472 path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path, &r);
3473 if (!path)
3474 return -1;
3475 if (is_fatal(r)) {
3476 g_free(path);
3477 return -1;
3479 if (!strcasecmp(path, "INBOX") && sub == FALSE) {
3480 g_free(path);
3481 return -1;
3483 debug_print("%ssubscribing %s\n", sub?"":"un", path);
3484 r = imap_threaded_subscribe(folder, path, sub);
3485 g_free(path);
3486 } else if (rpath) {
3487 r = imap_threaded_subscribe(folder, rpath, sub);
3488 } else
3489 return -1;
3490 return r;
3493 static gint imap_remove_folder_real(Folder *folder, FolderItem *item)
3495 gint ok = MAILIMAP_NO_ERROR;
3496 IMAPSession *session;
3497 gchar *path;
3498 gchar *cache_dir;
3499 gboolean selected_folder;
3501 g_return_val_if_fail(folder != NULL, -1);
3502 g_return_val_if_fail(item != NULL, -1);
3503 g_return_val_if_fail(item->path != NULL, -1);
3505 debug_print("getting session...\n");
3506 session = imap_session_get(folder);
3507 if (!session) {
3508 return -1;
3510 path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path, &ok);
3511 if (is_fatal(ok)) {
3512 g_free(path);
3513 return -1;
3515 imap_threaded_subscribe(folder, path, FALSE);
3517 selected_folder = (session->mbox != NULL) &&
3518 (!strcmp(session->mbox, item->path));
3519 if (selected_folder) {
3520 ok = imap_cmd_close(session);
3521 if (ok != MAILIMAP_NO_ERROR) {
3522 debug_print("close err %d\n", ok);
3523 return ok;
3526 ok = imap_cmd_delete(session, path);
3527 if (ok != MAILIMAP_NO_ERROR && !is_fatal(ok)) {
3528 gchar *tmp = NULL;
3530 ok = MAILIMAP_NO_ERROR;
3531 tmp = g_strdup_printf("%s%c", path,
3532 imap_get_path_separator(session, IMAP_FOLDER(folder), path, &ok));
3533 g_free(path);
3534 path = tmp;
3535 if (!is_fatal(ok))
3536 ok = imap_cmd_delete(session, path);
3539 if (ok != MAILIMAP_NO_ERROR) {
3540 log_warning(LOG_PROTOCOL, _("can't delete mailbox\n"));
3541 g_free(path);
3542 return -1;
3545 g_free(path);
3546 cache_dir = folder_item_get_path(item);
3547 if (is_dir_exist(cache_dir) && remove_dir_recursive(cache_dir) < 0)
3548 g_warning("can't remove directory '%s'", cache_dir);
3549 g_free(cache_dir);
3550 folder_item_remove(item);
3551 return 0;
3554 static gint imap_remove_folder(Folder *folder, FolderItem *item)
3556 GNode *node, *next;
3558 g_return_val_if_fail(item != NULL, -1);
3559 g_return_val_if_fail(item->folder != NULL, -1);
3560 g_return_val_if_fail(item->node != NULL, -1);
3562 node = item->node->children;
3563 while (node != NULL) {
3564 next = node->next;
3565 if (imap_remove_folder(folder, FOLDER_ITEM(node->data)) < 0)
3566 return -1;
3567 node = next;
3569 debug_print("IMAP removing %s\n", item->path);
3571 if (imap_remove_all_msg(folder, item) < 0)
3572 return -1;
3573 return imap_remove_folder_real(folder, item);
3576 typedef struct _uncached_data {
3577 IMAPSession *session;
3578 FolderItem *item;
3579 MsgNumberList *numlist;
3580 guint cur;
3581 guint total;
3582 gboolean done;
3583 int ok;
3584 } uncached_data;
3586 static void *imap_get_uncached_messages_thread(void *data)
3588 uncached_data *stuff = (uncached_data *)data;
3589 IMAPSession *session = stuff->session;
3590 FolderItem *item = stuff->item;
3591 MsgNumberList *numlist = stuff->numlist;
3592 GSList *newlist = NULL;
3593 GSList *llast = NULL;
3594 GSList *seq_list, *cur;
3595 gboolean got_alien_tags = FALSE;
3597 debug_print("uncached_messages\n");
3599 if (session == NULL || item == NULL || item->folder == NULL
3600 || FOLDER_CLASS(item->folder) != &imap_class) {
3601 stuff->done = TRUE;
3602 return NULL;
3605 seq_list = imap_get_lep_set_from_numlist(IMAP_FOLDER(item->folder), numlist);
3606 debug_print("get msgs info\n");
3607 for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
3608 struct mailimap_set * imapset;
3609 unsigned int i;
3610 int r;
3611 carray * env_list;
3612 int count;
3614 if (session->cancelled)
3615 break;
3617 imapset = cur->data;
3619 r = imap_threaded_fetch_env(session->folder,
3620 imapset, &env_list);
3621 if (r != MAILIMAP_NO_ERROR) {
3622 imap_handle_error(SESSION(session), NULL, r);
3623 if (is_fatal(r)) {
3624 stuff->ok = r;
3625 return NULL;
3627 continue;
3630 session_set_access_time(SESSION(session));
3632 count = 0;
3633 for(i = 0 ; i < carray_count(env_list) ; i += 2) {
3634 struct imap_fetch_env_info * info;
3635 MsgInfo * msginfo;
3636 GSList *tags = NULL, *cur = NULL;
3637 info = carray_get(env_list, i);
3638 tags = carray_get(env_list, i+1);
3639 msginfo = imap_envelope_from_lep(info, item);
3640 if (msginfo == NULL) {
3641 slist_free_strings_full(tags);
3642 continue;
3644 g_slist_free(msginfo->tags);
3645 msginfo->tags = NULL;
3647 for (cur = tags; cur; cur = cur->next) {
3648 gchar *real_tag = imap_modified_utf7_to_utf8(cur->data, TRUE);
3649 gint id = 0;
3650 id = tags_get_id_for_str(real_tag);
3651 if (id == -1) {
3652 id = tags_add_tag(real_tag);
3653 got_alien_tags = TRUE;
3655 if (!g_slist_find(msginfo->tags, GINT_TO_POINTER(id))) {
3656 msginfo->tags = g_slist_prepend(
3657 msginfo->tags,
3658 GINT_TO_POINTER(id));
3660 g_free(real_tag);
3662 if (msginfo->tags)
3663 msginfo->tags = g_slist_reverse(msginfo->tags);
3664 slist_free_strings_full(tags);
3665 msginfo->folder = item;
3666 if (!newlist)
3667 llast = newlist = g_slist_append(newlist, msginfo);
3668 else {
3669 llast = g_slist_append(llast, msginfo);
3670 llast = llast->next;
3672 count ++;
3675 imap_fetch_env_free(env_list);
3678 if (got_alien_tags) {
3679 tags_write_tags();
3680 main_window_reflect_tags_changes(mainwindow_get_mainwindow());
3683 imap_lep_set_free(seq_list);
3685 session_set_access_time(SESSION(session));
3686 stuff->done = TRUE;
3687 return newlist;
3690 #define MAX_MSG_NUM 50
3692 static GSList *imap_get_uncached_messages(IMAPSession *session,
3693 FolderItem *item,
3694 MsgNumberList *numlist,
3695 int *r)
3697 GSList *result = NULL;
3698 GSList * cur;
3699 uncached_data *data = g_new0(uncached_data, 1);
3701 cur = numlist;
3702 data->total = g_slist_length(numlist);
3703 data->ok = MAILIMAP_NO_ERROR;
3704 debug_print("messages list : %i\n", data->total);
3706 while (cur != NULL) {
3707 GSList * partial_result;
3708 int count;
3709 GSList * newlist;
3710 GSList * llast;
3712 llast = NULL;
3713 count = 0;
3714 newlist = NULL;
3715 while (count < MAX_MSG_NUM) {
3716 void * p;
3718 p = cur->data;
3720 if (newlist == NULL)
3721 llast = newlist = g_slist_append(newlist, p);
3722 else {
3723 llast = g_slist_append(llast, p);
3724 llast = llast->next;
3726 count ++;
3728 cur = cur->next;
3729 if (cur == NULL)
3730 break;
3733 data->done = FALSE;
3734 data->session = session;
3735 data->item = item;
3736 data->numlist = newlist;
3737 data->cur += count;
3739 if (prefs_common.work_offline &&
3740 !inc_offline_should_override(FALSE,
3741 _("Claws Mail needs network access in order "
3742 "to access the IMAP server."))) {
3743 g_free(data);
3744 return NULL;
3747 partial_result =
3748 (GSList *)imap_get_uncached_messages_thread(data);
3749 *r = data->ok;
3750 if (data->ok != MAILIMAP_NO_ERROR) {
3751 goto bail;
3753 statusbar_progress_all(data->cur,data->total, 1);
3755 g_slist_free(newlist);
3757 result = g_slist_concat(result, partial_result);
3759 bail:
3760 g_free(data);
3762 statusbar_progress_all(0,0,0);
3763 statusbar_pop_all();
3765 return result;
3768 static void imap_delete_all_cached_messages(FolderItem *item)
3770 gchar *dir;
3772 g_return_if_fail(item != NULL);
3773 g_return_if_fail(item->folder != NULL);
3774 g_return_if_fail(FOLDER_CLASS(item->folder) == &imap_class);
3776 debug_print("Deleting all cached messages...\n");
3778 dir = folder_item_get_path(item);
3779 if (is_dir_exist(dir))
3780 remove_all_numbered_files(dir);
3781 g_free(dir);
3783 debug_print("Deleting all cached messages done.\n");
3786 gchar imap_get_path_separator_for_item(FolderItem *item)
3788 Folder *folder = NULL;
3789 IMAPFolder *imap_folder = NULL;
3790 IMAPSession *session = NULL;
3791 gchar result = '/';
3792 gint ok = MAILIMAP_NO_ERROR;
3793 if (!item)
3794 return '/';
3795 folder = item->folder;
3797 if (!folder)
3798 return '/';
3800 imap_folder = IMAP_FOLDER(folder);
3802 debug_print("getting session...\n");
3803 session = imap_session_get(FOLDER(folder));
3804 result = imap_get_path_separator(session, imap_folder, item->path, &ok);
3805 return result;
3808 static gchar imap_refresh_path_separator(IMAPSession *session, IMAPFolder *folder, const gchar *subfolder, gint *ok)
3810 clist * lep_list;
3811 int r;
3812 gchar separator = '\0';
3814 g_return_val_if_fail(session != NULL, '/');
3815 r = imap_threaded_list((Folder *)folder, "", subfolder, &lep_list);
3817 if (r != MAILIMAP_NO_ERROR) {
3818 imap_handle_error(SESSION(session), NULL, r);
3819 log_warning(LOG_PROTOCOL, _("LIST failed\n"));
3820 *ok = r;
3821 return '\0';
3824 if (lep_list != NULL && clist_count(lep_list) > 0) {
3825 clistiter * iter = clist_begin(lep_list);
3826 struct mailimap_mailbox_list * mb;
3827 mb = clist_content(iter);
3829 separator = mb->mb_delimiter;
3830 debug_print("got separator: %c\n", folder->last_seen_separator);
3832 *ok = MAILIMAP_NO_ERROR;
3833 mailimap_list_result_free(lep_list);
3834 return separator;
3837 static gchar imap_get_path_separator(IMAPSession *session, IMAPFolder *folder, const gchar *path, gint *ok)
3839 gchar separator = '/';
3840 *ok = MAILIMAP_NO_ERROR;
3841 if (folder->last_seen_separator == 0) {
3842 folder->last_seen_separator = imap_refresh_path_separator(session, folder, "", ok);
3845 if (folder->last_seen_separator == 0) {
3846 folder->last_seen_separator = imap_refresh_path_separator(session, folder, "INBOX", ok);
3849 if (folder->last_seen_separator != 0) {
3850 debug_print("using separator: %c\n", folder->last_seen_separator);
3851 return folder->last_seen_separator;
3854 return separator;
3857 static gchar *imap_get_real_path(IMAPSession *session, IMAPFolder *folder, const gchar *path, gint *ok)
3859 gchar *real_path = NULL;
3860 gchar separator;
3862 g_return_val_if_fail(folder != NULL, NULL);
3863 g_return_val_if_fail(path != NULL, NULL);
3865 *ok = MAILIMAP_NO_ERROR;
3867 real_path = imap_utf8_to_modified_utf7(path, FALSE);
3868 separator = imap_get_path_separator(session, folder, path, ok);
3869 if (*ok == MAILIMAP_NO_ERROR)
3870 imap_path_separator_subst(real_path, separator);
3872 return real_path;
3875 static gint imap_set_message_flags(IMAPSession *session,
3876 IMAPFolderItem *item,
3877 MsgNumberList *numlist,
3878 IMAPFlags flags,
3879 GSList *tags,
3880 gboolean is_set)
3882 gint ok = 0;
3883 GSList *seq_list;
3884 GSList * cur;
3885 gint total = 0;
3886 IMAPFolder *folder = NULL;
3887 GSList *sorted_list = NULL;
3889 if (numlist == NULL || session == NULL)
3890 return MAILIMAP_ERROR_BAD_STATE;
3892 folder = IMAP_FOLDER(session->folder);
3894 sorted_list = g_slist_copy(numlist);
3895 sorted_list = g_slist_sort(sorted_list, g_int_compare);
3897 cur = g_slist_last(sorted_list);
3899 if (cur)
3900 total = GPOINTER_TO_INT(cur->data);
3902 seq_list = imap_get_lep_set_from_numlist(IMAP_FOLDER(session->folder), sorted_list);
3904 statusbar_print_all(_("Flagging messages..."));
3906 for(cur = seq_list ; cur != NULL ; cur = g_slist_next(cur)) {
3907 struct mailimap_set * imapset = (struct mailimap_set *)cur->data;
3908 struct mailimap_set_item *set_item = NULL;
3910 if (imapset->set_list)
3911 set_item = clist_content(clist_begin(imapset->set_list));
3912 else
3913 continue;
3915 if (set_item == NULL)
3916 continue;
3918 statusbar_progress_all(set_item->set_first, total, 1);
3920 ok = imap_cmd_store(session, item, imapset,
3921 flags, tags, is_set);
3922 statusbar_progress_all(set_item->set_last, total, 1);
3923 if (ok != MAILIMAP_NO_ERROR && folder->max_set_size > 20) {
3924 /* reduce max set size */
3925 folder->max_set_size /= 2;
3927 if (ok != MAILIMAP_NO_ERROR && is_fatal(ok)) {
3928 break;
3932 g_slist_free(sorted_list);
3934 statusbar_progress_all(0,0,0);
3935 statusbar_pop_all();
3937 imap_lep_set_free(seq_list);
3939 return ok;
3942 typedef struct _select_data {
3943 IMAPSession *session;
3944 gchar *real_path;
3945 gint *exists;
3946 gint *recent;
3947 gint *unseen;
3948 guint32 *uid_validity;
3949 gboolean done;
3950 } select_data;
3952 static gint imap_select(IMAPSession *session, IMAPFolder *folder,
3953 FolderItem *item,
3954 gint *exists, gint *recent, gint *unseen,
3955 guint32 *uid_validity, gint *can_create_flags,
3956 gboolean block)
3958 gchar *real_path;
3959 gint ok = MAILIMAP_NO_ERROR;
3960 gint exists_, recent_, unseen_;
3961 guint32 uid_validity_;
3962 gint can_create_flags_;
3963 const gchar *path = item ? item->path:NULL;
3965 if (!item) {
3966 return MAILIMAP_ERROR_BAD_STATE;
3969 if (!exists && !recent && !unseen && !uid_validity && !can_create_flags) {
3970 if (session->mbox && strcmp(session->mbox, path) == 0)
3971 return MAILIMAP_NO_ERROR;
3973 if (!exists && !recent && !unseen && !uid_validity && can_create_flags) {
3974 if (session->mbox && strcmp(session->mbox, path) == 0) {
3975 if (IMAP_FOLDER_ITEM(item)->can_create_flags != ITEM_CAN_CREATE_FLAGS_UNKNOWN)
3976 return MAILIMAP_NO_ERROR;
3979 if (!exists)
3980 exists = &exists_;
3981 if (!recent)
3982 recent = &recent_;
3983 if (!unseen)
3984 unseen = &unseen_;
3985 if (!uid_validity)
3986 uid_validity = &uid_validity_;
3987 if (!can_create_flags)
3988 can_create_flags = &can_create_flags_;
3990 g_free(session->mbox);
3991 session->mbox = NULL;
3992 session->exists = 0;
3993 session->recent = 0;
3994 session->expunge = 0;
3996 real_path = imap_get_real_path(session, folder, path, &ok);
3997 if (is_fatal(ok)) {
3998 g_free(real_path);
3999 return ok;
4001 g_slist_free(IMAP_FOLDER_ITEM(item)->ok_flags);
4002 IMAP_FOLDER_ITEM(item)->ok_flags = NULL;
4003 ok = imap_cmd_select(session, real_path,
4004 exists, recent, unseen, uid_validity, can_create_flags,
4005 &(IMAP_FOLDER_ITEM(item)->ok_flags), block);
4006 if (ok != MAILIMAP_NO_ERROR) {
4007 log_warning(LOG_PROTOCOL, _("can't select folder: %s\n"), real_path);
4008 } else {
4009 session->mbox = g_strdup(path);
4010 session->folder_content_changed = FALSE;
4011 session->exists = *exists;
4012 session->recent = *recent;
4013 session->expunge = 0;
4014 session->unseen = *unseen;
4015 session->uid_validity = *uid_validity;
4016 debug_print("select: exists %d recent %d expunge %d uid_validity %d can_create_flags %d\n",
4017 session->exists, session->recent, session->expunge,
4018 session->uid_validity, *can_create_flags);
4020 if (*can_create_flags) {
4021 IMAP_FOLDER_ITEM(item)->can_create_flags = ITEM_CAN_CREATE_FLAGS;
4022 } else {
4023 IMAP_FOLDER_ITEM(item)->can_create_flags = ITEM_CANNOT_CREATE_FLAGS;
4025 g_free(real_path);
4027 return ok;
4030 static gint imap_status(IMAPSession *session, IMAPFolder *folder,
4031 const gchar *path, IMAPFolderItem *item,
4032 gint *messages,
4033 guint32 *uid_next, guint32 *uid_validity,
4034 gint *unseen, gboolean block)
4036 int r = MAILIMAP_NO_ERROR;
4037 clistiter * iter;
4038 struct mailimap_mailbox_data_status * data_status;
4039 int got_values;
4040 gchar *real_path;
4041 guint mask = 0;
4043 real_path = imap_get_real_path(session, folder, path, &r);
4044 if (is_fatal(r)) {
4045 g_free(real_path);
4046 return r;
4048 if (messages) {
4049 mask |= 1 << 0;
4050 *messages = 0;
4052 if (uid_next) {
4053 mask |= 1 << 2;
4054 *uid_next = 0;
4056 if (uid_validity) {
4057 mask |= 1 << 3;
4058 *uid_validity = 0;
4060 if (unseen) {
4061 mask |= 1 << 4;
4062 *unseen = 0;
4065 if (session->mbox != NULL &&
4066 !strcmp(session->mbox, item->item.path)) {
4067 r = imap_cmd_close(session);
4068 if (r != MAILIMAP_NO_ERROR) {
4069 debug_print("close err %d\n", r);
4070 g_free(real_path);
4071 return r;
4075 r = imap_threaded_status(FOLDER(folder), real_path,
4076 &data_status, mask);
4078 g_free(real_path);
4079 if (r != MAILIMAP_NO_ERROR) {
4080 imap_handle_error(SESSION(session), NULL, r);
4081 debug_print("status err %d\n", r);
4082 return r;
4085 if (data_status == NULL || data_status->st_info_list == NULL) {
4086 debug_print("data_status %p\n", data_status);
4087 if (data_status) {
4088 debug_print("data_status->st_info_list %p\n", data_status->st_info_list);
4089 mailimap_mailbox_data_status_free(data_status);
4091 return MAILIMAP_ERROR_BAD_STATE;
4094 got_values = 0;
4095 if (data_status->st_info_list) {
4096 for(iter = clist_begin(data_status->st_info_list) ; iter != NULL ;
4097 iter = clist_next(iter)) {
4098 struct mailimap_status_info * info;
4100 info = clist_content(iter);
4101 switch (info->st_att) {
4102 case MAILIMAP_STATUS_ATT_MESSAGES:
4103 if (messages) {
4104 * messages = info->st_value;
4105 got_values |= 1 << 0;
4107 break;
4109 case MAILIMAP_STATUS_ATT_UIDNEXT:
4110 if (uid_next) {
4111 * uid_next = info->st_value;
4112 got_values |= 1 << 2;
4114 break;
4116 case MAILIMAP_STATUS_ATT_UIDVALIDITY:
4117 if (uid_validity) {
4118 * uid_validity = info->st_value;
4119 got_values |= 1 << 3;
4121 break;
4123 case MAILIMAP_STATUS_ATT_UNSEEN:
4124 if (unseen) {
4125 * unseen = info->st_value;
4126 got_values |= 1 << 4;
4128 break;
4132 mailimap_mailbox_data_status_free(data_status);
4134 if (got_values != mask) {
4135 g_warning("status: incomplete values received (%d)", got_values);
4137 return MAILIMAP_NO_ERROR;
4140 static void imap_free_capabilities(IMAPSession *session)
4142 slist_free_strings_full(session->capability);
4143 session->capability = NULL;
4146 /* low-level IMAP4rev1 commands */
4148 static gint imap_cmd_login(IMAPSession *session,
4149 const gchar *user, const gchar *pass,
4150 const gchar *type)
4152 int r;
4153 gint ok;
4155 if (!strcmp(type, "plaintext") && imap_has_capability(session, "LOGINDISABLED")) {
4156 ok = MAILIMAP_ERROR_BAD_STATE;
4157 if (imap_has_capability(session, "STARTTLS")) {
4158 #ifdef USE_GNUTLS
4159 log_warning(LOG_PROTOCOL, _("Server requires STARTTLS to log in.\n"));
4160 ok = imap_cmd_starttls(session);
4161 if (ok != MAILIMAP_NO_ERROR) {
4162 log_warning(LOG_PROTOCOL, _("Can't start STARTTLS session.\n"));
4163 return ok;
4164 } else {
4165 /* refresh capas */
4166 imap_free_capabilities(session);
4167 if ((r = imap_get_capabilities(session)) != MAILIMAP_NO_ERROR) {
4168 imap_handle_error(SESSION(session), NULL, r);
4169 log_warning(LOG_PROTOCOL, _("Can't refresh capabilities.\n"));
4170 return r;
4173 #else
4174 log_error(LOG_PROTOCOL, _("Connection to %s failed: "
4175 "server requires STARTTLS, but Claws Mail "
4176 "has been compiled without STARTTLS "
4177 "support.\n"),
4178 SESSION(session)->server);
4179 return MAILIMAP_ERROR_LOGIN;
4180 #endif
4181 } else {
4182 log_error(LOG_PROTOCOL, _("Server logins are disabled.\n"));
4183 return MAILIMAP_ERROR_LOGIN;
4187 log_print(LOG_PROTOCOL, "IMAP> Logging %s to %s using %s\n",
4188 user,
4189 SESSION(session)->server,
4190 type);
4191 r = imap_threaded_login(session->folder, user, pass, type);
4192 if (r != MAILIMAP_NO_ERROR) {
4193 imap_handle_error(SESSION(session), NULL, r);
4194 log_print(LOG_PROTOCOL, "IMAP< Error logging in to %s\n",
4195 SESSION(session)->server);
4196 ok = r;
4197 } else {
4198 log_print(LOG_PROTOCOL, "IMAP< Login to %s successful\n",
4199 SESSION(session)->server);
4200 ok = MAILIMAP_NO_ERROR;
4202 return ok;
4205 static gint imap_cmd_noop(IMAPSession *session)
4207 int r;
4208 unsigned int exists, recent, expunge, unseen, uidnext, uidval;
4210 r = imap_threaded_noop(session->folder, &exists, &recent, &expunge, &unseen, &uidnext, &uidval);
4211 if (r != MAILIMAP_NO_ERROR) {
4212 imap_handle_error(SESSION(session), NULL, r);
4213 debug_print("noop err %d\n", r);
4214 return r;
4217 if ((exists && exists != session->exists)
4218 || (recent && recent != session->recent)
4219 || (expunge && expunge != session->expunge)
4220 || (unseen && unseen != session->unseen)) {
4221 session->folder_content_changed = TRUE;
4223 if (uidnext != 0 && uidnext != session->uid_next) {
4224 session->uid_next = uidnext;
4225 session->folder_content_changed = TRUE;
4227 if (uidval != 0 && uidval != session->uid_validity) {
4228 session->uid_validity = uidval;
4229 session->folder_content_changed = TRUE;
4232 session->exists = exists;
4233 session->recent = recent;
4234 session->expunge = expunge;
4235 session->unseen = unseen;
4237 session_set_access_time(SESSION(session));
4239 return MAILIMAP_NO_ERROR;
4242 #ifdef USE_GNUTLS
4243 static gint imap_cmd_starttls(IMAPSession *session)
4245 int r;
4247 r = imap_threaded_starttls(session->folder,
4248 SESSION(session)->server, SESSION(session)->port);
4249 if (r != MAILIMAP_NO_ERROR) {
4250 imap_handle_error(SESSION(session), NULL, r);
4251 debug_print("STARTTLS err %d\n", r);
4252 return r;
4254 return MAILIMAP_NO_ERROR;
4256 #endif
4258 static gint imap_cmd_select(IMAPSession *session, const gchar *folder,
4259 gint *exists, gint *recent, gint *unseen,
4260 guint32 *uid_validity, gint *can_create_flags,
4261 GSList **ok_flags, gboolean block)
4263 int r;
4265 r = imap_threaded_select(session->folder, folder,
4266 exists, recent, unseen, uid_validity, can_create_flags, ok_flags);
4267 if (r != MAILIMAP_NO_ERROR) {
4268 imap_handle_error(SESSION(session), NULL, r);
4269 debug_print("select err %d\n", r);
4270 return r;
4272 return MAILIMAP_NO_ERROR;
4275 static gint imap_cmd_close(IMAPSession *session)
4277 int r;
4279 r = imap_threaded_close(session->folder);
4280 if (r != MAILIMAP_NO_ERROR) {
4281 imap_handle_error(SESSION(session), NULL, r);
4282 debug_print("close err %d\n", r);
4283 return r;
4285 g_free(session->mbox);
4286 session->mbox = NULL;
4287 session->exists = 0;
4288 session->recent = 0;
4289 session->expunge = 0;
4290 return MAILIMAP_NO_ERROR;
4293 static gint imap_cmd_examine(IMAPSession *session, const gchar *folder,
4294 gint *exists, gint *recent, gint *unseen,
4295 guint32 *uid_validity, gboolean block)
4297 int r;
4299 r = imap_threaded_examine(session->folder, folder,
4300 exists, recent, unseen, uid_validity);
4301 if (r != MAILIMAP_NO_ERROR) {
4302 imap_handle_error(SESSION(session), NULL, r);
4303 debug_print("examine err %d\n", r);
4305 return r;
4307 return MAILIMAP_NO_ERROR;
4310 static gint imap_cmd_create(IMAPSession *session, const gchar *folder)
4312 int r;
4314 r = imap_threaded_create(session->folder, folder);
4315 if (r != MAILIMAP_NO_ERROR) {
4316 imap_handle_error(SESSION(session), NULL, r);
4317 return r;
4320 return MAILIMAP_NO_ERROR;
4323 static gint imap_cmd_rename(IMAPSession *session, const gchar *old_folder,
4324 const gchar *new_folder)
4326 int r;
4328 r = imap_threaded_rename(session->folder, old_folder,
4329 new_folder);
4330 if (r != MAILIMAP_NO_ERROR) {
4331 imap_handle_error(SESSION(session), NULL, r);
4332 return r;
4335 return MAILIMAP_NO_ERROR;
4338 static gint imap_cmd_delete(IMAPSession *session, const gchar *folder)
4340 int r;
4343 r = imap_threaded_delete(session->folder, folder);
4344 if (r != MAILIMAP_NO_ERROR) {
4345 imap_handle_error(SESSION(session), NULL, r);
4346 return r;
4349 return MAILIMAP_NO_ERROR;
4352 typedef struct _fetch_data {
4353 IMAPSession *session;
4354 guint32 uid;
4355 const gchar *filename;
4356 gboolean headers;
4357 gboolean body;
4358 gboolean done;
4359 } fetch_data;
4361 static void *imap_cmd_fetch_thread(void *data)
4363 fetch_data *stuff = (fetch_data *)data;
4364 IMAPSession *session = stuff->session;
4365 guint32 uid = stuff->uid;
4366 const gchar *filename = stuff->filename;
4367 int r;
4369 if (stuff->body) {
4370 r = imap_threaded_fetch_content(session->folder,
4371 uid, 1, filename);
4373 else {
4374 r = imap_threaded_fetch_content(session->folder,
4375 uid, 0, filename);
4377 if (r != MAILIMAP_NO_ERROR) {
4378 imap_handle_error(SESSION(session), NULL, r);
4379 debug_print("fetch err %d\n", r);
4380 return GINT_TO_POINTER(r);
4382 return GINT_TO_POINTER(MAILIMAP_NO_ERROR);
4385 static gint imap_cmd_fetch(IMAPSession *session, guint32 uid,
4386 const gchar *filename, gboolean headers,
4387 gboolean body)
4389 fetch_data *data = g_new0(fetch_data, 1);
4390 int result = 0;
4391 data->done = FALSE;
4392 data->session = session;
4393 data->uid = uid;
4394 data->filename = filename;
4395 data->headers = headers;
4396 data->body = body;
4398 if (prefs_common.work_offline &&
4399 !inc_offline_should_override(FALSE,
4400 _("Claws Mail needs network access in order "
4401 "to access the IMAP server."))) {
4402 g_free(data);
4403 return -1;
4405 statusbar_print_all(_("Fetching message..."));
4406 result = GPOINTER_TO_INT(imap_cmd_fetch_thread(data));
4407 statusbar_pop_all();
4408 g_free(data);
4409 return result;
4413 static gint imap_cmd_append(IMAPSession *session,
4414 IMAPFolderItem *item,
4415 const gchar *destfolder,
4416 const gchar *file, IMAPFlags flags,
4417 guint32 *new_uid)
4419 struct mailimap_flag_list * flag_list;
4420 int r;
4422 cm_return_val_if_fail(file != NULL, MAILIMAP_ERROR_BAD_STATE);
4424 flag_list = imap_flag_to_lep(item, flags, NULL);
4425 lock_session(session);
4426 r = imap_threaded_append(session->folder, destfolder,
4427 file, flag_list, (int *)new_uid);
4428 mailimap_flag_list_free(flag_list);
4430 if (r != MAILIMAP_NO_ERROR) {
4431 imap_handle_error(SESSION(session), NULL, r);
4432 debug_print("append err %d\n", r);
4433 return r;
4436 unlock_session(session);
4438 return MAILIMAP_NO_ERROR;
4441 static gint imap_cmd_copy(IMAPSession *session, struct mailimap_set * set,
4442 const gchar *destfolder,
4443 struct mailimap_set **source, struct mailimap_set **dest)
4445 int r;
4447 g_return_val_if_fail(session != NULL, MAILIMAP_ERROR_BAD_STATE);
4448 g_return_val_if_fail(set != NULL, MAILIMAP_ERROR_BAD_STATE);
4449 g_return_val_if_fail(destfolder != NULL, MAILIMAP_ERROR_BAD_STATE);
4451 r = imap_threaded_copy(session->folder, set, destfolder, source, dest);
4452 if (r != MAILIMAP_NO_ERROR) {
4453 imap_handle_error(SESSION(session), NULL, r);
4454 return r;
4457 return MAILIMAP_NO_ERROR;
4460 static gint imap_cmd_store(IMAPSession *session,
4461 IMAPFolderItem *item,
4462 struct mailimap_set * set,
4463 IMAPFlags flags, GSList *tags, int do_add)
4465 int r;
4466 struct mailimap_flag_list * flag_list = NULL;
4467 struct mailimap_store_att_flags * store_att_flags;
4469 flag_list = imap_flag_to_lep(item, flags, tags);
4471 if (do_add)
4472 store_att_flags =
4473 mailimap_store_att_flags_new_add_flags_silent(flag_list);
4474 else
4475 store_att_flags =
4476 mailimap_store_att_flags_new_remove_flags_silent(flag_list);
4478 r = imap_threaded_store(session->folder, set, store_att_flags);
4479 mailimap_store_att_flags_free(store_att_flags);
4480 if (r != MAILIMAP_NO_ERROR) {
4481 imap_handle_error(SESSION(session), NULL, r);
4482 return r;
4485 return MAILIMAP_NO_ERROR;
4488 static gint imap_cmd_expunge(IMAPSession *session)
4490 int r;
4492 if (prefs_common.work_offline &&
4493 !inc_offline_should_override(FALSE,
4494 _("Claws Mail needs network access in order "
4495 "to access the IMAP server."))) {
4496 return -1;
4499 r = imap_threaded_expunge(session->folder);
4500 if (r != MAILIMAP_NO_ERROR) {
4501 imap_handle_error(SESSION(session), NULL, r);
4502 return r;
4505 return MAILIMAP_NO_ERROR;
4508 gint imap_expunge(Folder *folder, FolderItem *item)
4510 IMAPSession *session = imap_session_get(folder);
4511 if (session == NULL)
4512 return -1;
4514 return imap_cmd_expunge(session);
4517 static void imap_path_separator_subst(gchar *str, gchar separator)
4519 gchar *p;
4520 gboolean in_escape = FALSE;
4522 if (!separator || separator == '/') return;
4524 for (p = str; *p != '\0'; p++) {
4525 if (*p == '/' && !in_escape)
4526 *p = separator;
4527 else if (*p == '&' && *(p + 1) != '-' && !in_escape)
4528 in_escape = TRUE;
4529 else if (*p == '-' && in_escape)
4530 in_escape = FALSE;
4534 static gboolean imap_rename_folder_func(GNode *node, gpointer data)
4536 FolderItem *item = node->data;
4537 gchar **paths = data;
4538 const gchar *oldpath = paths[0];
4539 const gchar *newpath = paths[1];
4540 gchar *real_oldpath, *real_newpath;
4541 gchar *base;
4542 gchar *new_itempath;
4543 gint oldpathlen;
4544 IMAPSession *session = imap_session_get(item->folder);
4545 gint ok = MAILIMAP_NO_ERROR;
4546 oldpathlen = strlen(oldpath);
4547 if (strncmp(oldpath, item->path, oldpathlen) != 0) {
4548 g_warning("path doesn't match: %s, %s", oldpath, item->path);
4549 return TRUE;
4552 base = item->path + oldpathlen;
4553 while (*base == '/') base++;
4554 if (*base == '\0')
4555 new_itempath = g_strdup(newpath);
4556 else
4557 new_itempath = g_strconcat(newpath, "/", base,
4558 NULL);
4560 real_oldpath = imap_get_real_path(session, IMAP_FOLDER(item->folder), item->path, &ok);
4561 g_free(item->path);
4562 item->path = new_itempath;
4564 real_newpath = imap_get_real_path(session, IMAP_FOLDER(item->folder), item->path, &ok);
4566 imap_threaded_subscribe(item->folder, real_oldpath, FALSE);
4567 imap_threaded_subscribe(item->folder, real_newpath, TRUE);
4569 g_free(real_oldpath);
4570 g_free(real_newpath);
4571 return FALSE;
4574 static gint get_list_of_uids(IMAPSession *session, Folder *folder, IMAPFolderItem *item, GSList **msgnum_list)
4576 GSList *uidlist, *elem;
4577 int r = -1;
4578 clist * lep_uidlist;
4579 gint ok, nummsgs = 0;
4581 if (session == NULL) {
4582 return -1;
4585 ok = imap_select(session, IMAP_FOLDER(folder), FOLDER_ITEM(item),
4586 NULL, NULL, NULL, NULL, NULL, TRUE);
4587 if (ok != MAILIMAP_NO_ERROR) {
4588 return -1;
4591 g_slist_free(item->uid_list);
4592 item->uid_list = NULL;
4594 uidlist = NULL;
4596 if (folder->account && folder->account->low_bandwidth) {
4597 r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_SIMPLE,
4598 NULL, NULL, NULL, &lep_uidlist);
4601 if (r == MAILIMAP_NO_ERROR) {
4602 uidlist = imap_uid_list_from_lep(lep_uidlist, NULL);
4603 mailimap_search_result_free(lep_uidlist);
4604 } else {
4605 carray * lep_uidtab;
4606 if (r != -1) { /* inited */
4607 imap_handle_error(SESSION(session), NULL, r);
4608 if (is_fatal(r))
4609 return -1;
4611 r = imap_threaded_fetch_uid(folder, 1,
4612 &lep_uidtab);
4613 if (r == MAILIMAP_NO_ERROR) {
4614 uidlist = imap_uid_list_from_lep_tab(lep_uidtab);
4615 imap_fetch_uid_list_free(lep_uidtab);
4619 if (r != MAILIMAP_NO_ERROR) {
4620 imap_handle_error(SESSION(session), NULL, r);
4621 return -1;
4624 for (elem = uidlist; elem != NULL; elem = g_slist_next(elem)) {
4625 guint msgnum;
4627 msgnum = GPOINTER_TO_INT(elem->data);
4629 *msgnum_list = g_slist_prepend(*msgnum_list, GINT_TO_POINTER(msgnum));
4630 item->uid_list = g_slist_prepend(item->uid_list, GINT_TO_POINTER(msgnum));
4631 nummsgs++;
4633 g_slist_free(uidlist);
4635 return nummsgs;
4639 gint imap_get_num_list(Folder *folder, FolderItem *_item, GSList **msgnum_list, gboolean *old_uids_valid)
4641 IMAPFolderItem *item = (IMAPFolderItem *)_item;
4642 IMAPSession *session;
4643 gint nummsgs;
4644 GSList *uidlist = NULL;
4645 gchar *dir;
4646 gint known_list_len = 0;
4647 gchar *path;
4649 debug_print("get_num_list\n");
4651 g_return_val_if_fail(folder != NULL, -1);
4652 g_return_val_if_fail(item != NULL, -1);
4653 g_return_val_if_fail(item->item.path != NULL, -1);
4654 g_return_val_if_fail(FOLDER_CLASS(folder) == &imap_class, -1);
4655 g_return_val_if_fail(folder->account != NULL, -1);
4657 known_list_len = g_slist_length(item->uid_list);
4658 if (!item->should_update) {
4659 debug_print("get_num_list: nothing to update\n");
4660 *old_uids_valid = TRUE;
4661 if (known_list_len == item->item.total_msgs
4662 && known_list_len > 0) {
4663 *msgnum_list = g_slist_copy(item->uid_list);
4664 return known_list_len;
4665 } else {
4666 debug_print("don't know the list length...\n");
4670 if (prefs_common.work_offline &&
4671 !inc_offline_should_override(FALSE,
4672 _("Claws Mail needs network access in order "
4673 "to access the IMAP server."))) {
4674 return -1;
4677 path = folder_item_get_path(_item);
4678 if (!is_dir_exist(path)) {
4679 if(is_file_exist(path))
4680 claws_unlink(path);
4681 make_dir_hier(path);
4683 g_free(path);
4685 debug_print("getting session...\n");
4686 session = imap_session_get(folder);
4687 g_return_val_if_fail(session != NULL, -1);
4689 lock_session(session);
4690 if (FOLDER_ITEM(item)->path)
4691 statusbar_print_all(_("Scanning folder %s/%s..."),
4692 FOLDER_ITEM(item)->folder->name,
4693 FOLDER_ITEM(item)->path);
4694 else
4695 statusbar_print_all(_("Scanning folder %s..."),
4696 FOLDER_ITEM(item)->folder->name);
4698 if (item->should_trash_cache) {
4699 *old_uids_valid = FALSE;
4700 debug_print("get_num_list: trashing num list\n");
4701 debug_print("Freeing imap uid cache\n");
4702 item->lastuid = 0;
4703 g_slist_free(item->uid_list);
4704 item->uid_list = NULL;
4706 imap_delete_all_cached_messages((FolderItem *)item);
4707 } else {
4708 debug_print("get_num_list: updating num list\n");
4709 *old_uids_valid = TRUE;
4712 nummsgs = get_list_of_uids(session, folder, item, &uidlist);
4714 unlock_session(session);
4716 /* session could be broken now, in case of fatal error */
4718 debug_print("get_num_list: got %d msgs\n", nummsgs);
4720 if (nummsgs < 0) {
4721 statusbar_pop_all();
4722 return -1;
4725 *msgnum_list = uidlist;
4727 dir = folder_item_get_path((FolderItem *)item);
4728 debug_print("removing old messages from %s\n", dir);
4729 remove_numbered_files_not_in_list(dir, *msgnum_list);
4730 g_free(dir);
4732 debug_print("get_num_list - ok - %i\n", nummsgs);
4733 statusbar_pop_all();
4734 item->should_trash_cache = FALSE;
4735 item->should_update = FALSE;
4736 return nummsgs;
4739 static MsgInfo *imap_parse_msg(const gchar *file, FolderItem *item)
4741 MsgInfo *msginfo;
4742 MsgFlags flags;
4744 flags.perm_flags = MSG_NEW|MSG_UNREAD;
4745 flags.tmp_flags = 0;
4747 g_return_val_if_fail(item != NULL, NULL);
4748 g_return_val_if_fail(file != NULL, NULL);
4750 if (folder_has_parent_of_type(item, F_QUEUE)) {
4751 MSG_SET_TMP_FLAGS(flags, MSG_QUEUED);
4752 } else if (folder_has_parent_of_type(item, F_DRAFT)) {
4753 MSG_SET_TMP_FLAGS(flags, MSG_DRAFT);
4756 msginfo = procheader_parse_file(file, flags, FALSE, FALSE);
4757 if (!msginfo) return NULL;
4759 msginfo->plaintext_file = g_strdup(file);
4760 msginfo->folder = item;
4762 return msginfo;
4765 GSList *imap_get_msginfos(Folder *folder, FolderItem *item,
4766 GSList *msgnum_list)
4768 IMAPSession *session;
4769 MsgInfoList *ret = NULL;
4770 gint ok;
4772 debug_print("get_msginfos\n");
4774 g_return_val_if_fail(folder != NULL, NULL);
4775 g_return_val_if_fail(item != NULL, NULL);
4776 g_return_val_if_fail(msgnum_list != NULL, NULL);
4778 debug_print("getting session...\n");
4779 session = imap_session_get(folder);
4780 g_return_val_if_fail(session != NULL, NULL);
4782 lock_session(session); /* unlocked later in the function */
4784 debug_print("IMAP getting msginfos\n");
4785 ok = imap_select(session, IMAP_FOLDER(folder), item,
4786 NULL, NULL, NULL, NULL, NULL, FALSE);
4787 if (ok != MAILIMAP_NO_ERROR) {
4788 return NULL;
4790 if (!(folder_has_parent_of_type(item, F_DRAFT) ||
4791 folder_has_parent_of_type(item, F_QUEUE))) {
4792 ret = g_slist_concat(ret,
4793 imap_get_uncached_messages(session, item,
4794 msgnum_list, &ok));
4795 if (ok != MAILIMAP_NO_ERROR)
4796 return NULL;
4797 unlock_session(session);
4798 } else {
4799 MsgNumberList *sorted_list, *elem, *llast = NULL;
4800 gint startnum, lastnum;
4802 unlock_session(session);
4804 sorted_list = g_slist_sort(g_slist_copy(msgnum_list), g_int_compare);
4806 startnum = lastnum = GPOINTER_TO_INT(sorted_list->data);
4808 llast = g_slist_last(ret);
4809 for (elem = sorted_list;; elem = g_slist_next(elem)) {
4810 guint num = 0;
4812 if (elem)
4813 num = GPOINTER_TO_INT(elem->data);
4815 if (num > lastnum + 1 || elem == NULL) {
4816 int i;
4817 for (i = startnum; i <= lastnum; ++i) {
4818 gchar *file;
4819 file = imap_fetch_msg(folder, item, i);
4820 if (file != NULL) {
4821 MsgInfo *msginfo = imap_parse_msg(file, item);
4822 if (msginfo != NULL) {
4823 msginfo->msgnum = i;
4824 if (llast == NULL)
4825 llast = ret = g_slist_append(ret, msginfo);
4826 else {
4827 llast = g_slist_append(llast, msginfo);
4828 llast = llast->next;
4831 g_free(file);
4835 if (elem == NULL)
4836 break;
4838 startnum = num;
4840 lastnum = num;
4843 g_slist_free(sorted_list);
4845 return ret;
4848 MsgInfo *imap_get_msginfo(Folder *folder, FolderItem *item, gint uid)
4850 MsgInfo *msginfo = NULL;
4851 MsgInfoList *msginfolist;
4852 MsgNumberList numlist;
4854 numlist.next = NULL;
4855 numlist.data = GINT_TO_POINTER(uid);
4857 msginfolist = imap_get_msginfos(folder, item, &numlist);
4858 if (msginfolist != NULL) {
4859 msginfo = msginfolist->data;
4860 g_slist_free(msginfolist);
4863 return msginfo;
4866 gboolean imap_scan_required(Folder *folder, FolderItem *_item)
4868 IMAPSession *session;
4869 IMAPFolderItem *item = (IMAPFolderItem *)_item;
4870 gint ok, exists = 0, unseen = 0;
4871 guint32 uid_next = 0, uid_val = 0;
4872 gboolean selected_folder;
4874 g_return_val_if_fail(folder != NULL, FALSE);
4875 g_return_val_if_fail(item != NULL, FALSE);
4876 g_return_val_if_fail(item->item.folder != NULL, FALSE);
4877 g_return_val_if_fail(FOLDER_CLASS(item->item.folder) == &imap_class, FALSE);
4879 if (item->item.path == NULL)
4880 return FALSE;
4882 if (item->should_update) {
4883 debug_print("scan already required\n");
4884 return TRUE;
4886 debug_print("getting session...\n");
4887 session = imap_session_get(folder);
4889 g_return_val_if_fail(session != NULL, FALSE);
4890 lock_session(session); /* unlocked later in the function */
4892 selected_folder = (session->mbox != NULL) &&
4893 (!strcmp(session->mbox, item->item.path));
4894 if (selected_folder) {
4895 if (!session->folder_content_changed) {
4896 ok = imap_cmd_noop(session);
4897 if (ok != MAILIMAP_NO_ERROR) {
4898 debug_print("disconnected!\n");
4899 if (!is_fatal(ok))
4900 session = imap_reconnect_if_possible(folder, session);
4901 else
4902 session = imap_session_get(folder);
4903 if (session == NULL)
4904 return FALSE;
4907 if (session->folder_content_changed) {
4908 debug_print("CHANGED (self-noop)! scan_required\n");
4909 item->should_update = TRUE;
4910 if (session->uid_validity && session->uid_validity != item->item.mtime) {
4911 item->item.mtime = session->uid_validity;
4912 item->should_trash_cache = TRUE;
4914 unlock_session(session);
4915 return TRUE;
4917 } else {
4918 debug_print("CHANGED (previous noop)! scan_required\n");
4919 item->should_update = TRUE;
4920 if (session->uid_validity && session->uid_validity != item->item.mtime) {
4921 item->item.mtime = session->uid_validity;
4922 item->should_trash_cache = TRUE;
4924 unlock_session(session);
4925 return TRUE;
4927 } else {
4928 ok = imap_status(session, IMAP_FOLDER(folder), item->item.path, IMAP_FOLDER_ITEM(item),
4929 &exists, &uid_next, &uid_val, &unseen, FALSE);
4930 if (ok != MAILIMAP_NO_ERROR) {
4931 return FALSE;
4934 debug_print("exists %d, item->item.total_msgs %d\n"
4935 "\tunseen %d, item->item.unread_msgs %d\n"
4936 "\tuid_next %d, item->uid_next %d\n"
4937 "\tuid_val %d, item->item.mtime %ld\n",
4938 exists, item->item.total_msgs, unseen, item->item.unread_msgs,
4939 uid_next, item->uid_next, uid_val, (long)(item->item.mtime));
4940 if (exists != item->item.total_msgs
4941 || unseen != item->item.unread_msgs
4942 || uid_next != item->uid_next
4943 || uid_val != item->item.mtime) {
4944 debug_print("CHANGED (status)! scan_required\n");
4945 item->last_change = time(NULL);
4946 item->should_update = TRUE;
4947 item->uid_next = uid_next;
4948 if (uid_val != item->item.mtime) {
4949 item->item.mtime = uid_val;
4950 item->should_trash_cache = TRUE;
4952 unlock_session(session);
4953 return TRUE;
4956 unlock_session(session);
4958 item->should_update = FALSE;
4959 return FALSE;
4962 void imap_change_flags(Folder *folder, FolderItem *item, MsgInfo *msginfo, MsgPermFlags newflags)
4964 IMAPSession *session;
4965 IMAPFlags flags_set = 0, flags_unset = 0;
4966 gint ok = MAILIMAP_NO_ERROR;
4967 MsgNumberList numlist;
4968 hashtable_data *ht_data = NULL;
4970 g_return_if_fail(folder != NULL);
4971 g_return_if_fail(folder->klass == &imap_class);
4972 g_return_if_fail(item != NULL);
4973 g_return_if_fail(item->folder == folder);
4974 g_return_if_fail(msginfo != NULL);
4975 g_return_if_fail(msginfo->folder == item);
4977 if (!MSG_IS_MARKED(msginfo->flags) && (newflags & MSG_MARKED))
4978 flags_set |= IMAP_FLAG_FLAGGED;
4979 if ( MSG_IS_MARKED(msginfo->flags) && !(newflags & MSG_MARKED))
4980 flags_unset |= IMAP_FLAG_FLAGGED;
4982 if (!MSG_IS_UNREAD(msginfo->flags) && (newflags & MSG_UNREAD))
4983 flags_unset |= IMAP_FLAG_SEEN;
4984 if ( MSG_IS_UNREAD(msginfo->flags) && !(newflags & MSG_UNREAD))
4985 flags_set |= IMAP_FLAG_SEEN;
4987 if (!MSG_IS_REPLIED(msginfo->flags) && (newflags & MSG_REPLIED))
4988 flags_set |= IMAP_FLAG_ANSWERED;
4989 if ( MSG_IS_REPLIED(msginfo->flags) && !(newflags & MSG_REPLIED))
4990 flags_unset |= IMAP_FLAG_ANSWERED;
4992 if (!MSG_IS_FORWARDED(msginfo->flags) && (newflags & MSG_FORWARDED))
4993 flags_set |= IMAP_FLAG_FORWARDED;
4994 if ( MSG_IS_FORWARDED(msginfo->flags) && !(newflags & MSG_FORWARDED))
4995 flags_unset |= IMAP_FLAG_FORWARDED;
4997 if (!MSG_IS_SPAM(msginfo->flags) && (newflags & MSG_SPAM)) {
4998 flags_set |= IMAP_FLAG_SPAM;
4999 flags_unset |= IMAP_FLAG_HAM;
5001 if ( MSG_IS_SPAM(msginfo->flags) && !(newflags & MSG_SPAM)) {
5002 flags_set |= IMAP_FLAG_HAM;
5003 flags_unset |= IMAP_FLAG_SPAM;
5005 if (!MSG_IS_DELETED(msginfo->flags) && (newflags & MSG_DELETED))
5006 flags_set |= IMAP_FLAG_DELETED;
5007 if ( MSG_IS_DELETED(msginfo->flags) && !(newflags & MSG_DELETED))
5008 flags_unset |= IMAP_FLAG_DELETED;
5010 if (!flags_set && !flags_unset) {
5011 /* the changed flags were not translatable to IMAP-speak.
5012 * like MSG_POSTFILTERED, so just apply. */
5013 msginfo->flags.perm_flags = newflags;
5014 return;
5017 debug_print("getting session...\n");
5018 session = imap_session_get(folder);
5019 if (!session) {
5020 return;
5023 if ((ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder,
5024 NULL, NULL, NULL, NULL, NULL, FALSE)) != MAILIMAP_NO_ERROR) {
5025 return;
5027 numlist.next = NULL;
5028 numlist.data = GINT_TO_POINTER(msginfo->msgnum);
5030 if (IMAP_FOLDER_ITEM(item)->batching) {
5031 /* instead of performing an UID STORE command for each message change,
5032 * as a lot of them can change "together", we just fill in hashtables
5033 * and defer the treatment so that we're able to send only one
5034 * command.
5036 debug_print("IMAP batch mode on, deferring flags change\n");
5037 if (flags_set) {
5038 ht_data = g_hash_table_lookup(IMAP_FOLDER_ITEM(item)->flags_set_table,
5039 GINT_TO_POINTER(flags_set));
5040 if (ht_data == NULL) {
5041 ht_data = g_new0(hashtable_data, 1);
5042 ht_data->item = IMAP_FOLDER_ITEM(item);
5043 g_hash_table_insert(IMAP_FOLDER_ITEM(item)->flags_set_table,
5044 GINT_TO_POINTER(flags_set), ht_data);
5046 ht_data->msglist = g_slist_prepend(ht_data->msglist, GINT_TO_POINTER(msginfo->msgnum));
5048 if (flags_unset) {
5049 ht_data = g_hash_table_lookup(IMAP_FOLDER_ITEM(item)->flags_unset_table,
5050 GINT_TO_POINTER(flags_unset));
5051 if (ht_data == NULL) {
5052 ht_data = g_new0(hashtable_data, 1);
5053 ht_data->item = IMAP_FOLDER_ITEM(item);
5054 g_hash_table_insert(IMAP_FOLDER_ITEM(item)->flags_unset_table,
5055 GINT_TO_POINTER(flags_unset), ht_data);
5057 ht_data->msglist = g_slist_prepend(ht_data->msglist,
5058 GINT_TO_POINTER(msginfo->msgnum));
5060 } else {
5061 debug_print("IMAP changing flags\n");
5062 if (flags_set) {
5063 ok = imap_set_message_flags(session, IMAP_FOLDER_ITEM(item), &numlist, flags_set, NULL, TRUE);
5064 if (ok != MAILIMAP_NO_ERROR) {
5065 return;
5069 if (flags_unset) {
5070 ok = imap_set_message_flags(session, IMAP_FOLDER_ITEM(item), &numlist, flags_unset, NULL, FALSE);
5071 if (ok != MAILIMAP_NO_ERROR) {
5072 return;
5076 msginfo->flags.perm_flags = newflags;
5077 return;
5080 static gint imap_remove_msg(Folder *folder, FolderItem *item, gint uid)
5082 gint ok;
5083 IMAPSession *session;
5084 gchar *dir;
5085 MsgNumberList numlist;
5087 g_return_val_if_fail(folder != NULL, -1);
5088 g_return_val_if_fail(FOLDER_CLASS(folder) == &imap_class, -1);
5089 g_return_val_if_fail(item != NULL, -1);
5091 debug_print("getting session...\n");
5092 session = imap_session_get(folder);
5093 if (!session) return -1;
5095 ok = imap_select(session, IMAP_FOLDER(folder), item,
5096 NULL, NULL, NULL, NULL, NULL, FALSE);
5097 if (ok != MAILIMAP_NO_ERROR) {
5098 return ok;
5100 numlist.next = NULL;
5101 numlist.data = GINT_TO_POINTER(uid);
5103 ok = imap_set_message_flags
5104 (session, IMAP_FOLDER_ITEM(item), &numlist, IMAP_FLAG_DELETED, NULL, TRUE);
5105 if (ok != MAILIMAP_NO_ERROR) {
5106 log_warning(LOG_PROTOCOL, _("can't set deleted flags: %d\n"), uid);
5107 return ok;
5110 ok = imap_cmd_expunge(session);
5112 if (ok != MAILIMAP_NO_ERROR) {
5113 log_warning(LOG_PROTOCOL, _("can't expunge\n"));
5114 return ok;
5117 IMAP_FOLDER_ITEM(item)->uid_list = g_slist_remove(
5118 IMAP_FOLDER_ITEM(item)->uid_list, numlist.data);
5119 dir = folder_item_get_path(item);
5120 if (is_dir_exist(dir))
5121 remove_numbered_files(dir, uid, uid);
5122 g_free(dir);
5123 return MAILIMAP_NO_ERROR;
5126 static gint compare_msginfo(gconstpointer a, gconstpointer b)
5128 return ((MsgInfo *)a)->msgnum - ((MsgInfo *)b)->msgnum;
5131 static guint gslist_find_next_num(MsgNumberList **list, guint num)
5133 GSList *elem;
5135 g_return_val_if_fail(list != NULL, -1);
5137 for (elem = *list; elem != NULL; elem = g_slist_next(elem))
5138 if (GPOINTER_TO_INT(elem->data) >= num)
5139 break;
5140 *list = elem;
5141 return elem != NULL ? GPOINTER_TO_INT(elem->data) : (gint)-1;
5144 static gboolean flag_ok(IMAPFolderItem *item, guint flag)
5146 if (item->ok_flags && g_slist_find(item->ok_flags, GUINT_TO_POINTER(flag))) {
5147 debug_print("flag %d is OK\n", flag);
5148 return TRUE;
5150 if (item->can_create_flags == ITEM_CAN_CREATE_FLAGS) {
5151 debug_print("creating flags is OK\n");
5152 return TRUE;
5154 return FALSE;
5158 * NEW and DELETED flags are not syncronized
5159 * - The NEW/RECENT flags in IMAP folders can not really be directly
5160 * modified by Claws Mail
5161 * - The DELETE/DELETED flag in IMAP and Claws Mail do not have the same
5162 * meaning, in IMAP it always removes the messages from the FolderItem
5163 * in Claws Mail it can mean to move the message to Trash
5166 typedef struct _get_flags_data {
5167 Folder *folder;
5168 FolderItem *item;
5169 MsgInfoList *msginfo_list;
5170 GHashTable *msgflags;
5171 gboolean full_search;
5172 gboolean done;
5173 } get_flags_data;
5175 static /*gint*/ void *imap_get_flags_thread(void *data)
5177 get_flags_data *stuff = (get_flags_data *)data;
5178 Folder *folder = stuff->folder;
5179 FolderItem *fitem = (FolderItem *) stuff->item;
5180 MsgInfoList *msginfo_list = stuff->msginfo_list;
5181 GHashTable *msgflags = stuff->msgflags;
5182 GSList *elem;
5183 carray * lep_uidtab;
5184 IMAPSession *session;
5185 gint ok;
5186 int r = MAILIMAP_NO_ERROR;
5187 GHashTable *flags_hash = NULL;
5188 GHashTable *tags_hash = NULL;
5189 gboolean full_search = stuff->full_search;
5190 GSList *sorted_list = NULL;
5191 GSList *unseen = NULL, *answered = NULL, *flagged = NULL, *deleted = NULL, *forwarded = NULL, *spam = NULL;
5192 GSList *seq_list, *cur;
5193 gboolean reverse_seen = FALSE;
5194 gboolean selected_folder;
5195 gint exists_cnt, unseen_cnt;
5196 gboolean got_alien_tags = FALSE;
5198 session = imap_session_get(folder);
5200 if (session == NULL) {
5201 stuff->done = TRUE;
5202 return GINT_TO_POINTER(-1);
5204 selected_folder = (session->mbox != NULL) &&
5205 (!strcmp(session->mbox, fitem->path));
5207 lock_session(session);
5208 if (!selected_folder) {
5209 ok = imap_select(session, IMAP_FOLDER(folder), fitem,
5210 &exists_cnt, NULL, &unseen_cnt, NULL, NULL, TRUE);
5211 if (ok != MAILIMAP_NO_ERROR) {
5212 stuff->done = TRUE;
5213 return GINT_TO_POINTER(-1);
5216 if (unseen_cnt > exists_cnt / 2)
5217 reverse_seen = TRUE;
5219 else {
5220 if (fitem->unread_msgs > fitem->total_msgs / 2)
5221 reverse_seen = TRUE;
5224 sorted_list = g_slist_sort(g_slist_copy(msginfo_list), compare_msginfo);
5225 if (!full_search) {
5226 seq_list = imap_get_lep_set_from_msglist(IMAP_FOLDER(folder), msginfo_list);
5227 } else {
5228 struct mailimap_set * set;
5229 set = mailimap_set_new_interval(1, 0);
5230 seq_list = g_slist_append(NULL, set);
5233 if (folder->account && folder->account->low_bandwidth) {
5234 for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
5235 struct mailimap_set * imapset;
5236 clist * lep_uidlist;
5237 int r;
5239 imapset = cur->data;
5240 if (reverse_seen) {
5241 r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_SEEN, NULL,
5242 NULL, full_search ? NULL:imapset, &lep_uidlist);
5244 else {
5245 r = imap_threaded_search(folder,
5246 IMAP_SEARCH_TYPE_UNSEEN, NULL,
5247 NULL, full_search ? NULL:imapset, &lep_uidlist);
5249 if (r == MAILIMAP_NO_ERROR) {
5250 GSList * uidlist;
5252 uidlist = imap_uid_list_from_lep(lep_uidlist, NULL);
5253 mailimap_search_result_free(lep_uidlist);
5255 unseen = g_slist_concat(unseen, uidlist);
5256 } else {
5257 imap_handle_error(SESSION(session), NULL, r);
5258 goto bail;
5261 r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_FLAGGED, NULL,
5262 NULL, full_search ? NULL:imapset, &lep_uidlist);
5263 if (r == MAILIMAP_NO_ERROR) {
5264 GSList * uidlist;
5266 uidlist = imap_uid_list_from_lep(lep_uidlist, NULL);
5267 mailimap_search_result_free(lep_uidlist);
5269 flagged = g_slist_concat(flagged, uidlist);
5270 } else {
5271 imap_handle_error(SESSION(session), NULL, r);
5272 goto bail;
5275 if (fitem->opened || fitem->processing_pending || fitem == folder->inbox) {
5276 r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_ANSWERED, NULL,
5277 NULL, full_search ? NULL:imapset, &lep_uidlist);
5278 if (r == MAILIMAP_NO_ERROR) {
5279 GSList * uidlist;
5281 uidlist = imap_uid_list_from_lep(lep_uidlist, NULL);
5282 mailimap_search_result_free(lep_uidlist);
5284 answered = g_slist_concat(answered, uidlist);
5285 } else {
5286 imap_handle_error(SESSION(session), NULL, r);
5287 goto bail;
5290 if (flag_ok(IMAP_FOLDER_ITEM(fitem), IMAP_FLAG_FORWARDED)) {
5291 r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_FORWARDED, NULL,
5292 NULL, full_search ? NULL:imapset, &lep_uidlist);
5293 if (r == MAILIMAP_NO_ERROR) {
5294 GSList * uidlist;
5296 uidlist = imap_uid_list_from_lep(lep_uidlist, NULL);
5297 mailimap_search_result_free(lep_uidlist);
5299 forwarded = g_slist_concat(forwarded, uidlist);
5300 } else {
5301 imap_handle_error(SESSION(session), NULL, r);
5302 goto bail;
5306 if (flag_ok(IMAP_FOLDER_ITEM(fitem), IMAP_FLAG_SPAM)) {
5307 r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_SPAM, NULL,
5308 NULL, full_search ? NULL:imapset, &lep_uidlist);
5309 if (r == MAILIMAP_NO_ERROR) {
5310 GSList * uidlist;
5312 uidlist = imap_uid_list_from_lep(lep_uidlist, NULL);
5313 mailimap_search_result_free(lep_uidlist);
5315 spam = g_slist_concat(spam, uidlist);
5316 } else {
5317 imap_handle_error(SESSION(session), NULL, r);
5318 goto bail;
5322 r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_DELETED, NULL,
5323 NULL, full_search ? NULL:imapset, &lep_uidlist);
5324 if (r == MAILIMAP_NO_ERROR) {
5325 GSList * uidlist;
5327 uidlist = imap_uid_list_from_lep(lep_uidlist, NULL);
5328 mailimap_search_result_free(lep_uidlist);
5330 deleted = g_slist_concat(deleted, uidlist);
5331 } else {
5332 imap_handle_error(SESSION(session), NULL, r);
5333 goto bail;
5338 } else {
5339 r = imap_threaded_fetch_uid_flags(folder, 1, &lep_uidtab);
5340 if (r == MAILIMAP_NO_ERROR) {
5341 flags_hash = g_hash_table_new_full(g_direct_hash, g_direct_equal, NULL, NULL);
5342 tags_hash = g_hash_table_new_full(g_direct_hash, g_direct_equal, NULL, NULL);
5343 imap_flags_hash_from_lep_uid_flags_tab(lep_uidtab, flags_hash, tags_hash);
5344 imap_fetch_uid_flags_list_free(lep_uidtab);
5345 } else {
5346 imap_handle_error(SESSION(session), NULL, r);
5347 goto bail;
5351 bail:
5352 if (r == MAILIMAP_NO_ERROR)
5353 unlock_session(session);
5355 for (elem = sorted_list; elem != NULL; elem = g_slist_next(elem)) {
5356 MsgInfo *msginfo;
5357 MsgPermFlags flags, oldflags;
5358 gboolean wasnew;
5360 msginfo = (MsgInfo *) elem->data;
5361 flags = msginfo->flags.perm_flags;
5362 wasnew = (flags & MSG_NEW);
5363 oldflags = flags & ~(MSG_NEW|MSG_UNREAD|MSG_REPLIED|MSG_FORWARDED|MSG_MARKED|MSG_DELETED|MSG_SPAM);
5365 if (folder->account && folder->account->low_bandwidth) {
5366 if (fitem->opened || fitem->processing_pending || fitem == folder->inbox) {
5367 flags &= ~((reverse_seen ? 0 : MSG_UNREAD | MSG_NEW) | MSG_REPLIED | MSG_FORWARDED | MSG_MARKED | MSG_SPAM);
5368 } else {
5369 flags &= ~((reverse_seen ? 0 : MSG_UNREAD | MSG_NEW | MSG_MARKED));
5371 if (reverse_seen)
5372 flags |= MSG_UNREAD | (wasnew ? MSG_NEW : 0);
5373 if (gslist_find_next_num(&unseen, msginfo->msgnum) == msginfo->msgnum) {
5374 if (!reverse_seen) {
5375 flags |= MSG_UNREAD | (wasnew ? MSG_NEW : 0);
5376 } else {
5377 flags &= ~(MSG_UNREAD | MSG_NEW);
5381 if (gslist_find_next_num(&flagged, msginfo->msgnum) == msginfo->msgnum)
5382 flags |= MSG_MARKED;
5383 else
5384 flags &= ~MSG_MARKED;
5386 if (fitem->opened || fitem->processing_pending || fitem == folder->inbox) {
5387 if (gslist_find_next_num(&answered, msginfo->msgnum) == msginfo->msgnum)
5388 flags |= MSG_REPLIED;
5389 else
5390 flags &= ~MSG_REPLIED;
5391 if (gslist_find_next_num(&forwarded, msginfo->msgnum) == msginfo->msgnum)
5392 flags |= MSG_FORWARDED;
5393 else
5394 flags &= ~MSG_FORWARDED;
5395 if (gslist_find_next_num(&spam, msginfo->msgnum) == msginfo->msgnum)
5396 flags |= MSG_SPAM;
5397 else
5398 flags &= ~MSG_SPAM;
5399 if (gslist_find_next_num(&deleted, msginfo->msgnum) == msginfo->msgnum)
5400 flags |= MSG_DELETED;
5401 else
5402 flags &= ~MSG_DELETED;
5404 } else {
5405 if (flags_hash != NULL) {
5407 flags = GPOINTER_TO_INT(g_hash_table_lookup(flags_hash,
5408 GINT_TO_POINTER(msginfo->msgnum)));
5411 if ((flags & MSG_UNREAD) == 0)
5412 flags &= ~MSG_NEW;
5413 else if (wasnew)
5414 flags |= MSG_NEW;
5415 flags |= oldflags;
5417 if (tags_hash != NULL) {
5418 GSList *tags = g_hash_table_lookup(tags_hash, GINT_TO_POINTER(msginfo->msgnum));
5419 GSList *cur;
5421 g_slist_free(msginfo->tags);
5422 msginfo->tags = NULL;
5424 for (cur = tags; cur; cur = cur->next) {
5425 gchar *real_tag = imap_modified_utf7_to_utf8(cur->data, TRUE);
5426 gint id = 0;
5427 id = tags_get_id_for_str(real_tag);
5428 if (id == -1) {
5429 id = tags_add_tag(real_tag);
5430 got_alien_tags = TRUE;
5432 msginfo->tags = g_slist_append(
5433 msginfo->tags,
5434 GINT_TO_POINTER(id));
5435 g_free(real_tag);
5437 slist_free_strings_full(tags);
5441 g_hash_table_insert(msgflags, msginfo, GINT_TO_POINTER(flags));
5444 if (got_alien_tags) {
5445 tags_write_tags();
5446 main_window_reflect_tags_changes(mainwindow_get_mainwindow());
5449 if (flags_hash)
5450 g_hash_table_destroy(flags_hash);
5451 if (tags_hash)
5452 g_hash_table_destroy(tags_hash);
5454 imap_lep_set_free(seq_list);
5455 g_slist_free(flagged);
5456 g_slist_free(deleted);
5457 g_slist_free(answered);
5458 g_slist_free(forwarded);
5459 g_slist_free(spam);
5460 g_slist_free(unseen);
5461 g_slist_free(sorted_list);
5463 stuff->done = TRUE;
5464 return GINT_TO_POINTER(0);
5467 static gint imap_get_flags(Folder *folder, FolderItem *item,
5468 MsgInfoList *msginfo_list, GHashTable *msgflags)
5470 gint result;
5471 get_flags_data *data = g_new0(get_flags_data, 1);
5472 data->done = FALSE;
5473 data->folder = folder;
5474 data->item = item;
5475 data->msginfo_list = msginfo_list;
5476 data->msgflags = msgflags;
5477 data->full_search = FALSE;
5479 GSList *tmp = NULL, *cur;
5481 if (prefs_common.work_offline &&
5482 !inc_offline_should_override(FALSE,
5483 _("Claws Mail needs network access in order "
5484 "to access the IMAP server."))) {
5485 g_free(data);
5486 return -1;
5489 tmp = folder_item_get_msg_list(item);
5491 if (g_slist_length(tmp) <= g_slist_length(msginfo_list))
5492 data->full_search = TRUE;
5494 for (cur = tmp; cur; cur = cur->next)
5495 procmsg_msginfo_free((MsgInfo **)&(cur->data));
5497 g_slist_free(tmp);
5499 result = GPOINTER_TO_INT(imap_get_flags_thread(data));
5501 g_free(data);
5502 return result;
5506 static gboolean process_flags(gpointer key, gpointer value, gpointer user_data)
5508 gboolean flags_set = GPOINTER_TO_INT(user_data);
5509 gint flags_value = GPOINTER_TO_INT(key);
5510 hashtable_data *data = (hashtable_data *)value;
5511 IMAPFolderItem *_item = data->item;
5512 FolderItem *item = (FolderItem *)_item;
5513 gint ok = MAILIMAP_ERROR_BAD_STATE;
5514 IMAPSession *session = NULL;
5516 debug_print("getting session...\n");
5517 session = imap_session_get(item->folder);
5519 data->msglist = g_slist_reverse(data->msglist);
5521 debug_print("IMAP %ssetting flags to %d for %d messages\n",
5522 flags_set?"":"un",
5523 flags_value,
5524 g_slist_length(data->msglist));
5526 lock_session(session);
5527 if (session) {
5528 ok = imap_select(session, IMAP_FOLDER(item->folder), item,
5529 NULL, NULL, NULL, NULL, NULL, FALSE);
5531 if (ok == MAILIMAP_NO_ERROR) {
5532 ok = imap_set_message_flags(session, IMAP_FOLDER_ITEM(item),
5533 data->msglist, flags_value, NULL, flags_set);
5534 } else {
5535 g_warning("can't select mailbox %s", item->path);
5538 if (!is_fatal(ok))
5539 unlock_session(session);
5541 g_slist_free(data->msglist);
5542 g_free(data);
5543 return TRUE;
5546 static gboolean process_tags(gpointer key, gpointer value, gpointer user_data)
5548 gboolean tags_set = GPOINTER_TO_INT(user_data);
5549 TagsData *data = (TagsData *)value;
5550 IMAPFolderItem *_item = data->item;
5551 FolderItem *item = (FolderItem *)_item;
5552 gchar *str = data->str;
5553 gint ok = MAILIMAP_ERROR_BAD_STATE;
5554 IMAPSession *session = NULL;
5556 debug_print("getting session...\n");
5557 session = imap_session_get(item->folder);
5559 data->msglist = g_slist_reverse(data->msglist);
5561 debug_print("IMAP %ssetting tags %s for %d messages\n",
5562 tags_set?"":"un",
5563 str,
5564 g_slist_length(data->msglist));
5566 lock_session(session);
5567 if (session) {
5568 ok = imap_select(session, IMAP_FOLDER(item->folder), item,
5569 NULL, NULL, NULL, NULL, NULL, FALSE);
5571 if (ok == MAILIMAP_NO_ERROR) {
5572 GSList list;
5573 list.data = str;
5574 list.next = NULL;
5575 ok = imap_set_message_flags(session, IMAP_FOLDER_ITEM(item),
5576 data->msglist, 0, &list, tags_set);
5577 } else {
5578 g_warning("can't select mailbox %s", item->path);
5581 if (!is_fatal(ok))
5582 unlock_session(session);
5584 g_slist_free(data->msglist);
5585 g_free(data->str);
5586 g_free(data);
5587 return TRUE;
5590 static void process_hashtable(IMAPFolderItem *item)
5592 if (item->flags_set_table) {
5593 g_hash_table_foreach_remove(item->flags_set_table, process_flags, GINT_TO_POINTER(TRUE));
5594 g_hash_table_destroy(item->flags_set_table);
5595 item->flags_set_table = NULL;
5597 if (item->flags_unset_table) {
5598 g_hash_table_foreach_remove(item->flags_unset_table, process_flags, GINT_TO_POINTER(FALSE));
5599 g_hash_table_destroy(item->flags_unset_table);
5600 item->flags_unset_table = NULL;
5602 if (item->tags_set_table) {
5603 g_hash_table_foreach_remove(item->tags_set_table, process_tags, GINT_TO_POINTER(TRUE));
5604 g_hash_table_destroy(item->tags_set_table);
5605 item->tags_set_table = NULL;
5607 if (item->tags_unset_table) {
5608 g_hash_table_foreach_remove(item->tags_unset_table, process_tags, GINT_TO_POINTER(FALSE));
5609 g_hash_table_destroy(item->tags_unset_table);
5610 item->tags_unset_table = NULL;
5615 static void imap_set_batch (Folder *folder, FolderItem *_item, gboolean batch)
5617 IMAPFolderItem *item = (IMAPFolderItem *)_item;
5618 IMAPSession *session;
5620 g_return_if_fail(item != NULL);
5622 if (item->batching == batch)
5623 return;
5625 if (batch) {
5626 item->batching = TRUE;
5627 debug_print("IMAP switching to batch mode\n");
5628 if (!item->flags_set_table) {
5629 item->flags_set_table = g_hash_table_new(NULL, g_direct_equal);
5631 if (!item->flags_unset_table) {
5632 item->flags_unset_table = g_hash_table_new(NULL, g_direct_equal);
5634 if (!item->tags_set_table) {
5635 item->tags_set_table = g_hash_table_new(NULL, g_direct_equal);
5637 if (!item->tags_unset_table) {
5638 item->tags_unset_table = g_hash_table_new(NULL, g_direct_equal);
5640 session = imap_session_get(folder);
5641 if (session) {
5642 imap_refresh_sensitivity(session);
5643 session->sens_update_block = TRUE;
5645 } else {
5646 debug_print("IMAP switching away from batch mode\n");
5647 /* process stuff */
5648 process_hashtable(item);
5649 item->batching = FALSE;
5650 session = imap_session_get(folder);
5651 if (session) {
5652 session->sens_update_block = FALSE;
5653 imap_refresh_sensitivity(session);
5660 /* data types conversion libetpan <-> claws */
5664 #define ETPAN_IMAP_MB_MARKED 1
5665 #define ETPAN_IMAP_MB_UNMARKED 2
5666 #define ETPAN_IMAP_MB_NOSELECT 4
5667 #define ETPAN_IMAP_MB_NOINFERIORS 8
5669 static int imap_flags_to_flags(struct mailimap_mbx_list_flags * imap_flags)
5671 int flags;
5672 clistiter * cur;
5674 flags = 0;
5675 if (imap_flags->mbf_type == MAILIMAP_MBX_LIST_FLAGS_SFLAG) {
5676 switch (imap_flags->mbf_sflag) {
5677 case MAILIMAP_MBX_LIST_SFLAG_MARKED:
5678 flags |= ETPAN_IMAP_MB_MARKED;
5679 break;
5680 case MAILIMAP_MBX_LIST_SFLAG_NOSELECT:
5681 flags |= ETPAN_IMAP_MB_NOSELECT;
5682 break;
5683 case MAILIMAP_MBX_LIST_SFLAG_UNMARKED:
5684 flags |= ETPAN_IMAP_MB_UNMARKED;
5685 break;
5689 if (imap_flags->mbf_oflags) {
5690 for(cur = clist_begin(imap_flags->mbf_oflags) ; cur != NULL ;
5691 cur = clist_next(cur)) {
5692 struct mailimap_mbx_list_oflag * oflag;
5694 oflag = clist_content(cur);
5696 switch (oflag->of_type) {
5697 case MAILIMAP_MBX_LIST_OFLAG_NOINFERIORS:
5698 flags |= ETPAN_IMAP_MB_NOINFERIORS;
5699 break;
5703 return flags;
5706 static GSList * imap_list_from_lep(IMAPFolder * folder,
5707 clist * list, const gchar * real_path, gboolean all)
5709 clistiter * iter;
5710 GSList * item_list = NULL, *llast = NULL;
5712 if (list) {
5713 for(iter = clist_begin(list) ; iter != NULL ;
5714 iter = clist_next(iter)) {
5715 struct mailimap_mailbox_list * mb;
5716 int flags;
5717 char delimiter;
5718 char * name;
5719 char * dup_name;
5720 gchar * base;
5721 gchar * loc_name;
5722 gchar * loc_path;
5723 FolderItem *new_item;
5725 mb = clist_content(iter);
5727 if (mb == NULL)
5728 continue;
5730 flags = 0;
5731 if (mb->mb_flag != NULL)
5732 flags = imap_flags_to_flags(mb->mb_flag);
5734 delimiter = mb->mb_delimiter;
5735 name = mb->mb_name;
5737 dup_name = strdup(name);
5738 if (delimiter != '\0')
5739 subst_char(dup_name, delimiter, '/');
5741 base = g_path_get_basename(dup_name);
5742 if (base[0] == '.') {
5743 g_free(base);
5744 free(dup_name);
5745 continue;
5747 if (!all && path_cmp(name, real_path) == 0) {
5748 g_free(base);
5749 free(dup_name);
5750 continue;
5753 if (!all && dup_name[strlen(dup_name)-1] == '/') {
5754 g_free(base);
5755 free(dup_name);
5756 continue;
5759 loc_name = imap_modified_utf7_to_utf8(base, FALSE);
5760 loc_path = imap_modified_utf7_to_utf8(dup_name, FALSE);
5762 new_item = folder_item_new(FOLDER(folder), loc_name, loc_path);
5763 if ((flags & ETPAN_IMAP_MB_NOINFERIORS) != 0)
5764 new_item->no_sub = TRUE;
5765 if (strcasecmp(dup_name, "INBOX") != 0 &&
5766 ((flags & ETPAN_IMAP_MB_NOSELECT) != 0))
5767 new_item->no_select = TRUE;
5769 if (item_list == NULL)
5770 llast = item_list = g_slist_append(item_list, new_item);
5771 else {
5772 llast = g_slist_append(llast, new_item);
5773 llast = llast->next;
5775 debug_print("folder '%s' found.\n", loc_path);
5776 g_free(base);
5777 g_free(loc_path);
5778 g_free(loc_name);
5780 free(dup_name);
5783 return item_list;
5786 static GSList * imap_get_lep_set_from_numlist(IMAPFolder *folder, MsgNumberList *numlist)
5788 GSList *sorted_list, *cur;
5789 guint first, last, next;
5790 GSList *ret_list = NULL, *llast = NULL;
5791 struct mailimap_set * current_set;
5792 unsigned int item_count;
5794 if (numlist == NULL)
5795 return NULL;
5797 current_set = mailimap_set_new_empty();
5799 sorted_list = g_slist_copy(numlist);
5800 sorted_list = g_slist_sort(sorted_list, g_int_compare);
5802 first = GPOINTER_TO_INT(sorted_list->data);
5804 item_count = 0;
5805 for (cur = sorted_list; cur != NULL; cur = g_slist_next(cur)) {
5806 if (GPOINTER_TO_INT(cur->data) == 0)
5807 continue;
5809 item_count ++;
5811 last = GPOINTER_TO_INT(cur->data);
5812 if (cur->next)
5813 next = GPOINTER_TO_INT(cur->next->data);
5814 else
5815 next = 0;
5817 if (last + 1 != next || next == 0 || item_count >= folder->max_set_size) {
5819 struct mailimap_set_item * item;
5820 item = mailimap_set_item_new(first, last);
5821 mailimap_set_add(current_set, item);
5823 first = next;
5825 if (item_count >= folder->max_set_size) {
5826 if (ret_list == NULL)
5827 llast = ret_list = g_slist_append(ret_list,
5828 current_set);
5829 else {
5830 llast = g_slist_append(llast, current_set);
5831 llast = llast->next;
5834 current_set = mailimap_set_new_empty();
5835 item_count = 0;
5840 if (clist_count(current_set->set_list) > 0) {
5841 ret_list = g_slist_append(ret_list,
5842 current_set);
5845 g_slist_free(sorted_list);
5847 return ret_list;
5850 static GSList * imap_get_lep_set_from_msglist(IMAPFolder *folder, MsgInfoList *msglist)
5852 MsgNumberList *numlist = NULL;
5853 GSList *seq_list;
5855 numlist = procmsg_get_number_list_for_msgs(msglist);
5857 seq_list = imap_get_lep_set_from_numlist(folder, numlist);
5858 g_slist_free(numlist);
5860 return seq_list;
5863 static GSList * imap_uid_list_from_lep(clist * list, gint* length)
5865 clistiter * iter;
5866 GSList * result;
5867 gint len = 0;
5869 result = NULL;
5871 if (list) {
5872 for(iter = clist_begin(list) ; iter != NULL ;
5873 iter = clist_next(iter)) {
5874 uint32_t * puid;
5876 puid = clist_content(iter);
5877 result = g_slist_prepend(result, GINT_TO_POINTER(* puid));
5878 len++;
5880 result = g_slist_reverse(result);
5882 if (length)
5883 *length = len;
5884 return result;
5887 static GSList * imap_uid_list_from_lep_tab(carray * list)
5889 unsigned int i;
5890 GSList * result;
5892 result = NULL;
5894 for(i = 0 ; i < carray_count(list) ; i ++) {
5895 uint32_t * puid;
5897 puid = carray_get(list, i);
5898 result = g_slist_prepend(result, GINT_TO_POINTER(* puid));
5900 result = g_slist_reverse(result);
5901 return result;
5904 static void imap_flags_hash_from_lep_uid_flags_tab(carray * list,
5905 GHashTable * hash,
5906 GHashTable * tags_hash)
5908 unsigned int i;
5910 for(i = 0 ; i < carray_count(list) ; i += 3) {
5911 uint32_t * puid;
5912 int * pflags;
5913 GSList *tags;
5915 puid = carray_get(list, i);
5916 pflags = carray_get(list, i + 1);
5917 tags = carray_get(list, i + 2);
5919 g_hash_table_insert(hash, GINT_TO_POINTER(*puid), GINT_TO_POINTER(* pflags));
5920 g_hash_table_insert(tags_hash, GINT_TO_POINTER(*puid), tags);
5924 static MsgInfo *imap_envelope_from_lep(struct imap_fetch_env_info * info,
5925 FolderItem *item)
5927 MsgInfo *msginfo = NULL;
5928 guint32 uid = 0;
5929 goffset size = 0;
5930 MsgFlags flags = {0, 0};
5932 if (info->headers == NULL)
5933 return NULL;
5935 MSG_SET_TMP_FLAGS(flags, MSG_IMAP);
5936 if (folder_has_parent_of_type(item, F_QUEUE)) {
5937 MSG_SET_TMP_FLAGS(flags, MSG_QUEUED);
5938 } else if (folder_has_parent_of_type(item, F_DRAFT)) {
5939 MSG_SET_TMP_FLAGS(flags, MSG_DRAFT);
5941 flags.perm_flags = info->flags;
5943 uid = info->uid;
5944 size = (goffset) info->size;
5945 msginfo = procheader_parse_str(info->headers, flags, FALSE, FALSE);
5947 if (msginfo) {
5948 msginfo->msgnum = uid;
5949 msginfo->size = size;
5952 return msginfo;
5955 static void imap_lep_set_free(GSList *seq_list)
5957 GSList * cur;
5959 for(cur = seq_list ; cur != NULL ; cur = g_slist_next(cur)) {
5960 struct mailimap_set * imapset;
5962 imapset = cur->data;
5963 mailimap_set_free(imapset);
5965 g_slist_free(seq_list);
5968 static struct mailimap_flag_list * imap_flag_to_lep(IMAPFolderItem *item, IMAPFlags flags, GSList *tags)
5970 struct mailimap_flag_list * flag_list;
5971 GSList *cur = tags;
5973 flag_list = mailimap_flag_list_new_empty();
5975 if (IMAP_IS_SEEN(flags))
5976 mailimap_flag_list_add(flag_list,
5977 mailimap_flag_new_seen());
5978 if (IMAP_IS_ANSWERED(flags))
5979 mailimap_flag_list_add(flag_list,
5980 mailimap_flag_new_answered());
5981 if (IMAP_IS_FLAGGED(flags))
5982 mailimap_flag_list_add(flag_list,
5983 mailimap_flag_new_flagged());
5984 if (IMAP_IS_DELETED(flags))
5985 mailimap_flag_list_add(flag_list,
5986 mailimap_flag_new_deleted());
5987 if (IMAP_IS_DRAFT(flags))
5988 mailimap_flag_list_add(flag_list,
5989 mailimap_flag_new_draft());
5990 if (IMAP_IS_FORWARDED(flags) && flag_ok(item, IMAP_FLAG_FORWARDED))
5991 mailimap_flag_list_add(flag_list,
5992 mailimap_flag_new_flag_keyword(strdup(RTAG_FORWARDED)));
5993 if (IMAP_IS_SPAM(flags) && flag_ok(item, IMAP_FLAG_SPAM))
5994 mailimap_flag_list_add(flag_list,
5995 mailimap_flag_new_flag_keyword(strdup(RTAG_JUNK)));
5996 else if (IMAP_IS_HAM(flags) && flag_ok(item, IMAP_FLAG_HAM))
5997 mailimap_flag_list_add(flag_list,
5998 mailimap_flag_new_flag_keyword(strdup(RTAG_NON_JUNK)));
6000 for (; cur; cur = cur->next) {
6001 gchar *enc_str =
6002 imap_utf8_to_modified_utf7(cur->data, TRUE);
6003 g_strstrip(enc_str);
6005 mailimap_flag_list_add(flag_list,
6006 mailimap_flag_new_flag_keyword(enc_str));
6009 return flag_list;
6012 guint imap_folder_get_refcnt(Folder *folder)
6014 return ((IMAPFolder *)folder)->refcnt;
6017 void imap_folder_ref(Folder *folder)
6019 ((IMAPFolder *)folder)->refcnt++;
6022 void imap_disconnect_all(gboolean have_connectivity)
6024 GList *list;
6025 gboolean short_timeout;
6026 #ifdef HAVE_NETWORKMANAGER_SUPPORT
6027 GError *error = NULL;
6029 short_timeout = !networkmanager_is_online(&error);
6030 if(error) {
6031 short_timeout = TRUE;
6032 g_error_free(error);
6034 #else
6035 short_timeout = TRUE;
6036 #endif
6038 if(short_timeout)
6039 imap_main_set_timeout(1);
6041 for (list = account_get_list(); list != NULL; list = list->next) {
6042 PrefsAccount *account = list->data;
6043 if (account->protocol == A_IMAP4) {
6044 RemoteFolder *folder = (RemoteFolder *)account->folder;
6045 if (folder && folder->session) {
6046 if (imap_is_busy(FOLDER(folder)))
6047 imap_threaded_cancel(FOLDER(folder));
6049 IMAPSession *session = (IMAPSession *)folder->session;
6050 if (have_connectivity)
6051 imap_threaded_disconnect(FOLDER(folder));
6052 SESSION(session)->state = SESSION_DISCONNECTED;
6053 SESSION(session)->sock = NULL;
6054 imap_safe_destroy(session);
6055 folder->session = NULL;
6060 if(short_timeout)
6061 imap_main_set_timeout(prefs_common.io_timeout_secs);
6064 void imap_folder_unref(Folder *folder)
6066 if (((IMAPFolder *)folder)->refcnt > 0)
6067 ((IMAPFolder *)folder)->refcnt--;
6070 void imap_cancel_all(void)
6072 GList *folderlist;
6073 GList *cur;
6075 folderlist = folder_get_list();
6076 for (cur = folderlist; cur != NULL; cur = g_list_next(cur)) {
6077 Folder *folder = (Folder *) cur->data;
6079 if (folder->klass == &imap_class) {
6080 if (imap_is_busy(folder)) {
6081 IMAPSession *imap_session;
6082 RemoteFolder *rfolder;
6084 g_printerr("cancelled\n");
6085 imap_threaded_cancel(folder);
6086 rfolder = (RemoteFolder *) folder;
6087 imap_session = (IMAPSession *) rfolder->session;
6088 if (imap_session)
6089 imap_session->cancelled = 1;
6095 gboolean imap_cancel_all_enabled(void)
6097 GList *folderlist;
6098 GList *cur;
6100 folderlist = folder_get_list();
6101 for (cur = folderlist; cur != NULL; cur = g_list_next(cur)) {
6102 Folder *folder = (Folder *) cur->data;
6104 if (folder->klass == &imap_class) {
6105 if (imap_is_busy(folder)) {
6106 return TRUE;
6111 return FALSE;
6114 static gboolean imap_is_busy(Folder *folder)
6116 IMAPSession *imap_session;
6117 RemoteFolder *rfolder;
6119 rfolder = (RemoteFolder *) folder;
6120 imap_session = (IMAPSession *) rfolder->session;
6121 if (imap_session == NULL)
6122 return FALSE;
6124 return imap_session->busy;
6127 #else /* HAVE_LIBETPAN */
6129 static FolderClass imap_class;
6131 static XMLTag *imap_item_get_xml(Folder *folder, FolderItem *item);
6132 static void imap_item_set_xml(Folder *folder, FolderItem *item, XMLTag *tag);
6134 static Folder *imap_folder_new (const gchar *name,
6135 const gchar *path)
6137 static gboolean missing_imap_warning = TRUE;
6138 if (missing_imap_warning) {
6139 missing_imap_warning = FALSE;
6140 alertpanel_error(
6141 _("You have one or more IMAP accounts "
6142 "defined. However this version of "
6143 "Claws Mail has been built without "
6144 "IMAP support; your IMAP accounts are "
6145 "disabled.\n\n"
6146 "You probably need to "
6147 "install libetpan and recompile "
6148 "Claws Mail."));
6150 return NULL;
6152 static gint imap_create_tree (Folder *folder)
6154 return -1;
6156 static FolderItem *imap_create_folder (Folder *folder,
6157 FolderItem *parent,
6158 const gchar *name)
6160 return NULL;
6162 static gint imap_rename_folder (Folder *folder,
6163 FolderItem *item,
6164 const gchar *name)
6166 return -1;
6169 gchar imap_get_path_separator_for_item(FolderItem *item)
6171 return '/';
6174 FolderClass *imap_get_class(void)
6176 if (imap_class.idstr == NULL) {
6177 imap_class.type = F_IMAP;
6178 imap_class.idstr = "imap";
6179 imap_class.uistr = "IMAP";
6181 imap_class.new_folder = imap_folder_new;
6182 imap_class.create_tree = imap_create_tree;
6183 imap_class.create_folder = imap_create_folder;
6184 imap_class.rename_folder = imap_rename_folder;
6186 imap_class.set_xml = folder_set_xml;
6187 imap_class.get_xml = folder_get_xml;
6188 imap_class.item_set_xml = imap_item_set_xml;
6189 imap_class.item_get_xml = imap_item_get_xml;
6190 /* nothing implemented */
6193 return &imap_class;
6196 void imap_disconnect_all(gboolean have_connectivity)
6200 gint imap_subscribe(Folder *folder, FolderItem *item, gchar *rpath, gboolean sub)
6202 return -1;
6205 GList * imap_scan_subtree(Folder *folder, FolderItem *item, gboolean unsubs_only, gboolean recursive)
6207 return NULL;
6210 void imap_cache_msg(FolderItem *item, gint msgnum)
6214 void imap_cancel_all(void)
6218 gboolean imap_cancel_all_enabled(void)
6220 return FALSE;
6223 #endif
6225 #ifdef HAVE_LIBETPAN
6226 static void imap_synchronise(FolderItem *item, gint days)
6228 if (IMAP_FOLDER_ITEM(item)->last_sync == IMAP_FOLDER_ITEM(item)->last_change) {
6229 debug_print("%s already synced\n", item->path?item->path:item->name);
6230 return;
6232 debug_print("syncing %s\n", item->path?item->path:item->name);
6233 imap_gtk_synchronise(item, days);
6234 IMAP_FOLDER_ITEM(item)->last_sync = IMAP_FOLDER_ITEM(item)->last_change;
6236 #endif
6238 static void imap_item_set_xml(Folder *folder, FolderItem *item, XMLTag *tag)
6240 #ifdef HAVE_LIBETPAN
6241 GList *cur;
6242 #endif
6243 folder_item_set_xml(folder, item, tag);
6245 #ifdef HAVE_LIBETPAN
6246 for (cur = tag->attr; cur != NULL; cur = g_list_next(cur)) {
6247 XMLAttr *attr = (XMLAttr *) cur->data;
6249 if (!attr || !attr->name || !attr->value) continue;
6250 if (!strcmp(attr->name, "uidnext"))
6251 IMAP_FOLDER_ITEM(item)->uid_next = atoi(attr->value);
6252 if (!strcmp(attr->name, "last_sync"))
6253 IMAP_FOLDER_ITEM(item)->last_sync = atoi(attr->value);
6254 if (!strcmp(attr->name, "last_change"))
6255 IMAP_FOLDER_ITEM(item)->last_change = atoi(attr->value);
6257 if (IMAP_FOLDER_ITEM(item)->last_change == 0)
6258 IMAP_FOLDER_ITEM(item)->last_change = time(NULL);
6259 #endif
6262 static XMLTag *imap_item_get_xml(Folder *folder, FolderItem *item)
6264 XMLTag *tag;
6266 tag = folder_item_get_xml(folder, item);
6268 #ifdef HAVE_LIBETPAN
6269 xml_tag_add_attr(tag, xml_attr_new_int("uidnext",
6270 IMAP_FOLDER_ITEM(item)->uid_next));
6271 xml_tag_add_attr(tag, xml_attr_new_int("last_sync",
6272 IMAP_FOLDER_ITEM(item)->last_sync));
6273 xml_tag_add_attr(tag, xml_attr_new_int("last_change",
6274 IMAP_FOLDER_ITEM(item)->last_change));
6276 #endif
6277 return tag;
6280 /* ===================================================================
6281 * UTF-7 conversion routines as in RFC 2192
6282 * ===================================================================
6283 * These two functions from:
6284 * libimap library.
6285 * Copyright (C) 2003-2004 Pawel Salek. */
6287 /* UTF7 modified base64 alphabet */
6288 static char base64chars[] =
6289 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+,";
6290 #define UNDEFINED 64
6292 /* UTF16 definitions */
6293 #define UTF16MASK 0x03FFUL
6294 #define UTF16SHIFT 10
6295 #define UTF16BASE 0x10000UL
6296 #define UTF16HIGHSTART 0xD800UL
6297 #define UTF16HIGHEND 0xDBFFUL
6298 #define UTF16LOSTART 0xDC00UL
6299 #define UTF16LOEND 0xDFFFUL
6302 /* Convert an IMAP mailbox to a UTF-8 string.
6303 * dst needs to have roughly 4 times the storage space of src
6304 * Hex encoding can triple the size of the input
6305 * UTF-7 can be slightly denser than UTF-8
6306 * (worst case: 8 octets UTF-7 becomes 9 octets UTF-8)
6308 char* imap_modified_utf7_to_utf8(const char *mbox, gboolean change_spaces)
6310 unsigned c, i, bitcount;
6311 unsigned long ucs4, utf16, bitbuf;
6312 unsigned char base64[256];
6313 const char *src;
6314 char *dst, *res = g_malloc(2*strlen(mbox)+1);
6316 dst = res;
6317 src = mbox;
6318 if(!dst) return NULL;
6319 /* initialize modified base64 decoding table */
6320 memset(base64, UNDEFINED, sizeof (base64));
6321 for (i = 0; i < sizeof (base64chars); ++i) {
6322 base64[(unsigned)base64chars[i]] = i;
6325 /* loop until end of string */
6326 while (*src != '\0') {
6327 c = *src++;
6328 /* deal with literal characters and &- */
6329 if (c != '&' || *src == '-') {
6330 /* encode literally */
6331 if (change_spaces && c == '_')
6332 *dst++ = ' ';
6333 else
6334 *dst++ = c;
6335 /* skip over the '-' if this is an &- sequence */
6336 if (c == '&') ++src;
6337 } else {
6338 /* convert modified UTF-7 -> UTF-16 -> UCS-4 -> UTF-8 -> HEX */
6339 bitbuf = 0;
6340 bitcount = 0;
6341 ucs4 = 0;
6342 while ((c = base64[(unsigned char) *src]) != UNDEFINED) {
6343 ++src;
6344 bitbuf = (bitbuf << 6) | c;
6345 bitcount += 6;
6346 /* enough bits for a UTF-16 character? */
6347 if (bitcount >= 16) {
6348 bitcount -= 16;
6349 utf16 = (bitcount ? bitbuf >> bitcount
6350 : bitbuf) & 0xffff;
6351 /* convert UTF16 to UCS4 */
6353 (utf16 >= UTF16HIGHSTART && utf16 <= UTF16HIGHEND) {
6354 ucs4 = (utf16 - UTF16HIGHSTART) << UTF16SHIFT;
6355 continue;
6356 } else if
6357 (utf16 >= UTF16LOSTART && utf16 <= UTF16LOEND) {
6358 ucs4 += utf16 - UTF16LOSTART + UTF16BASE;
6359 } else {
6360 ucs4 = utf16;
6363 /* convert UTF-16 range of UCS4 to UTF-8 */
6364 if (ucs4 <= 0x7fUL) {
6365 dst[0] = ucs4;
6366 dst += 1;
6367 } else if (ucs4 <= 0x7ffUL) {
6368 dst[0] = 0xc0 | (ucs4 >> 6);
6369 dst[1] = 0x80 | (ucs4 & 0x3f);
6370 dst += 2;
6371 } else if (ucs4 <= 0xffffUL) {
6372 dst[0] = 0xe0 | (ucs4 >> 12);
6373 dst[1] = 0x80 | ((ucs4 >> 6) & 0x3f);
6374 dst[2] = 0x80 | (ucs4 & 0x3f);
6375 dst += 3;
6376 } else {
6377 dst[0] = 0xf0 | (ucs4 >> 18);
6378 dst[1] = 0x80 | ((ucs4 >> 12) & 0x3f);
6379 dst[2] = 0x80 | ((ucs4 >> 6) & 0x3f);
6380 dst[3] = 0x80 | (ucs4 & 0x3f);
6381 dst += 4;
6385 /* skip over trailing '-' in modified UTF-7 encoding */
6386 if (*src == '-') ++src;
6389 /* terminate destination string */
6390 *dst = '\0';
6391 return res;
6394 /* Convert hex coded UTF-8 string to modified UTF-7 IMAP mailbox
6395 * dst should be about twice the length of src to deal with non-hex
6396 * coded URLs
6398 char* imap_utf8_to_modified_utf7(const char *src, gboolean change_spaces)
6400 unsigned int utf8pos, utf8total, c, utf7mode, bitstogo, utf16flag;
6401 unsigned long ucs4 = 0, bitbuf = 0;
6403 /* initialize hex lookup table */
6404 char *dst, *res;
6406 if (!src) return NULL;
6408 res = malloc(2*strlen(src)+1);
6409 dst = res;
6410 if(!dst) return NULL;
6412 utf7mode = 0;
6413 utf8total = 0;
6414 bitstogo = 0;
6415 utf8pos = 0;
6416 while ((c = (unsigned char)*src) != '\0') {
6417 ++src;
6418 /* normal character? */
6419 if (c >= ' ' && c <= '~' && (c != '_' || !change_spaces)) {
6420 /* switch out of UTF-7 mode */
6421 if (utf7mode) {
6422 if (bitstogo) {
6423 *dst++ = base64chars[(bitbuf << (6 - bitstogo)) & 0x3F];
6425 *dst++ = '-';
6426 utf7mode = 0;
6427 utf8pos = 0;
6428 bitstogo = 0;
6429 utf8total= 0;
6431 if (change_spaces && c == ' ')
6432 *dst++ = '_';
6433 else
6434 *dst++ = c;
6435 /* encode '&' as '&-' */
6436 if (c == '&') {
6437 *dst++ = '-';
6439 continue;
6441 /* switch to UTF-7 mode */
6442 if (!utf7mode) {
6443 *dst++ = '&';
6444 utf7mode = 1;
6446 /* Encode US-ASCII characters as themselves */
6447 if (c < 0x80) {
6448 ucs4 = c;
6449 } else if (utf8total) {
6450 /* save UTF8 bits into UCS4 */
6451 ucs4 = (ucs4 << 6) | (c & 0x3FUL);
6452 if (++utf8pos < utf8total) {
6453 continue;
6455 } else {
6456 utf8pos = 1;
6457 if (c < 0xE0) {
6458 utf8total = 2;
6459 ucs4 = c & 0x1F;
6460 } else if (c < 0xF0) {
6461 utf8total = 3;
6462 ucs4 = c & 0x0F;
6463 } else {
6464 /* NOTE: can't convert UTF8 sequences longer than 4 */
6465 utf8total = 4;
6466 ucs4 = c & 0x03;
6468 continue;
6470 /* loop to split ucs4 into two utf16 chars if necessary */
6471 utf8total = 0;
6472 do {
6473 if (ucs4 >= UTF16BASE) {
6474 ucs4 -= UTF16BASE;
6475 bitbuf = (bitbuf << 16) | ((ucs4 >> UTF16SHIFT)
6476 + UTF16HIGHSTART);
6477 ucs4 = (ucs4 & UTF16MASK) + UTF16LOSTART;
6478 utf16flag = 1;
6479 } else {
6480 bitbuf = (bitbuf << 16) | ucs4;
6481 utf16flag = 0;
6483 bitstogo += 16;
6484 /* spew out base64 */
6485 while (bitstogo >= 6) {
6486 bitstogo -= 6;
6487 *dst++ = base64chars[(bitstogo ? (bitbuf >> bitstogo)
6488 : bitbuf)
6489 & 0x3F];
6491 } while (utf16flag);
6493 /* if in UTF-7 mode, finish in ASCII */
6494 if (utf7mode) {
6495 if (bitstogo) {
6496 *dst++ = base64chars[(bitbuf << (6 - bitstogo)) & 0x3F];
6498 *dst++ = '-';
6500 /* tie off string */
6501 *dst = '\0';
6502 return res;