3.7.2 unleashed
[claws.git] / src / imap.c
blob712d0fdb150a54d405f15fb5b230b44cb47a4f23
1 /*
2 * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3 * Copyright (C) 1999-2009 Hiroyuki Yamamoto and the Claws Mail team
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 #ifdef HAVE_CONFIG_H
21 # include "config.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 "base64.h"
62 #include "utils.h"
63 #include "prefs_common.h"
64 #include "inputdialog.h"
65 #include "log.h"
66 #include "remotefolder.h"
67 #include "claws.h"
68 #include "statusbar.h"
69 #include "msgcache.h"
70 #include "imap-thread.h"
71 #include "account.h"
72 #include "tags.h"
73 #include "main.h"
75 typedef struct _IMAPFolder IMAPFolder;
76 typedef struct _IMAPSession IMAPSession;
77 typedef struct _IMAPNameSpace IMAPNameSpace;
78 typedef struct _IMAPFolderItem IMAPFolderItem;
80 #include "prefs_account.h"
82 #define IMAP_FOLDER(obj) ((IMAPFolder *)obj)
83 #define IMAP_FOLDER_ITEM(obj) ((IMAPFolderItem *)obj)
84 #define IMAP_SESSION(obj) ((IMAPSession *)obj)
86 struct _IMAPFolder
88 RemoteFolder rfolder;
90 /* list of IMAPNameSpace */
91 GList *ns_personal;
92 GList *ns_others;
93 GList *ns_shared;
94 gchar last_seen_separator;
95 guint refcnt;
96 guint max_set_size;
99 struct _IMAPSession
101 Session session;
103 gboolean authenticated;
105 GSList *capability;
106 gboolean uidplus;
108 gchar *mbox;
109 guint cmd_count;
111 /* CLAWS */
112 gboolean folder_content_changed;
113 guint exists;
114 guint recent;
115 guint expunge;
116 guint unseen;
117 guint uid_validity;
118 guint uid_next;
120 Folder * folder;
121 gboolean busy;
122 gboolean cancelled;
123 gboolean sens_update_block;
126 struct _IMAPNameSpace
128 gchar *name;
129 gchar separator;
132 #define IMAPBUFSIZE 8192
134 #define IMAP_IS_SEEN(flags) ((flags & IMAP_FLAG_SEEN) != 0)
135 #define IMAP_IS_ANSWERED(flags) ((flags & IMAP_FLAG_ANSWERED) != 0)
136 #define IMAP_IS_FLAGGED(flags) ((flags & IMAP_FLAG_FLAGGED) != 0)
137 #define IMAP_IS_DELETED(flags) ((flags & IMAP_FLAG_DELETED) != 0)
138 #define IMAP_IS_DRAFT(flags) ((flags & IMAP_FLAG_DRAFT) != 0)
139 #define IMAP_IS_FORWARDED(flags) ((flags & IMAP_FLAG_FORWARDED) != 0)
140 #define IMAP_IS_SPAM(flags) ((flags & IMAP_FLAG_SPAM) != 0)
141 #define IMAP_IS_HAM(flags) ((flags & IMAP_FLAG_HAM) != 0)
144 #define IMAP4_PORT 143
145 #ifdef USE_GNUTLS
146 #define IMAPS_PORT 993
147 #endif
149 #define IMAP_CMD_LIMIT 1000
151 enum {
152 ITEM_CAN_CREATE_FLAGS_UNKNOWN = 0,
153 ITEM_CAN_CREATE_FLAGS,
154 ITEM_CANNOT_CREATE_FLAGS
157 struct _IMAPFolderItem
159 FolderItem item;
161 guint lastuid;
162 guint uid_next;
163 GSList *uid_list;
164 gboolean batching;
166 GHashTable *flags_set_table;
167 GHashTable *flags_unset_table;
168 guint32 last_change;
169 guint32 last_sync;
170 gboolean should_update;
171 gboolean should_trash_cache;
172 gint can_create_flags;
174 GHashTable *tags_set_table;
175 GHashTable *tags_unset_table;
176 GSList *ok_flags;
180 static XMLTag *imap_item_get_xml(Folder *folder, FolderItem *item);
181 static void imap_item_set_xml(Folder *folder, FolderItem *item, XMLTag *tag);
183 static void imap_folder_init (Folder *folder,
184 const gchar *name,
185 const gchar *path);
187 static Folder *imap_folder_new (const gchar *name,
188 const gchar *path);
189 static void imap_folder_destroy (Folder *folder);
191 static IMAPSession *imap_session_new (Folder *folder,
192 const PrefsAccount *account);
193 static gint imap_session_authenticate(IMAPSession *session,
194 PrefsAccount *account);
195 static void imap_session_destroy (Session *session);
197 static gchar *imap_fetch_msg (Folder *folder,
198 FolderItem *item,
199 gint uid);
200 static gchar *imap_fetch_msg_full (Folder *folder,
201 FolderItem *item,
202 gint uid,
203 gboolean headers,
204 gboolean body);
205 static void imap_remove_cached_msg (Folder *folder,
206 FolderItem *item,
207 MsgInfo *msginfo);
208 static gint imap_add_msg (Folder *folder,
209 FolderItem *dest,
210 const gchar *file,
211 MsgFlags *flags);
212 static gint imap_add_msgs (Folder *folder,
213 FolderItem *dest,
214 GSList *file_list,
215 GRelation *relation);
217 static gint imap_copy_msg (Folder *folder,
218 FolderItem *dest,
219 MsgInfo *msginfo);
220 static gint imap_copy_msgs (Folder *folder,
221 FolderItem *dest,
222 MsgInfoList *msglist,
223 GRelation *relation);
225 static gint imap_remove_msg (Folder *folder,
226 FolderItem *item,
227 gint uid);
228 static gint imap_remove_msgs (Folder *folder,
229 FolderItem *dest,
230 MsgInfoList *msglist,
231 GRelation *relation);
232 static gint imap_expunge (Folder *folder,
233 FolderItem *dest);
234 static gint imap_remove_all_msg (Folder *folder,
235 FolderItem *item);
237 static gboolean imap_is_msg_changed (Folder *folder,
238 FolderItem *item,
239 MsgInfo *msginfo);
241 static gint imap_close (Folder *folder,
242 FolderItem *item);
244 static gint imap_scan_tree (Folder *folder);
246 static gint imap_create_tree (Folder *folder);
248 static FolderItem *imap_create_folder (Folder *folder,
249 FolderItem *parent,
250 const gchar *name);
251 static gint imap_rename_folder (Folder *folder,
252 FolderItem *item,
253 const gchar *name);
254 static gint imap_remove_folder (Folder *folder,
255 FolderItem *item);
257 static FolderItem *imap_folder_item_new (Folder *folder);
258 static void imap_folder_item_destroy (Folder *folder,
259 FolderItem *item);
261 static IMAPSession *imap_session_get (Folder *folder);
263 static gint imap_auth (IMAPSession *session,
264 const gchar *user,
265 const gchar *pass,
266 IMAPAuthType type);
268 static gint imap_scan_tree_recursive (IMAPSession *session,
269 FolderItem *item,
270 gboolean subs_only);
272 static void imap_create_missing_folders (Folder *folder);
273 static FolderItem *imap_create_special_folder
274 (Folder *folder,
275 SpecialFolderItemType stype,
276 const gchar *name);
278 static gint imap_do_copy_msgs (Folder *folder,
279 FolderItem *dest,
280 MsgInfoList *msglist,
281 GRelation *relation);
283 static void imap_delete_all_cached_messages (FolderItem *item);
284 static void imap_set_batch (Folder *folder,
285 FolderItem *item,
286 gboolean batch);
287 static gint imap_set_message_flags (IMAPSession *session,
288 IMAPFolderItem *item,
289 MsgNumberList *numlist,
290 IMAPFlags flags,
291 GSList *tags,
292 gboolean is_set);
293 static gint imap_select (IMAPSession *session,
294 IMAPFolder *folder,
295 FolderItem *item,
296 gint *exists,
297 gint *recent,
298 gint *unseen,
299 guint32 *uid_validity,
300 gint *can_create_flags,
301 gboolean block);
302 static gint imap_status (IMAPSession *session,
303 IMAPFolder *folder,
304 const gchar *path,
305 IMAPFolderItem *item,
306 gint *messages,
307 guint32 *uid_next,
308 guint32 *uid_validity,
309 gint *unseen,
310 gboolean block);
311 static void imap_commit_tags (FolderItem *item,
312 MsgInfo *msginfo,
313 GSList *set_tags,
314 GSList *unset_tags);
316 static gchar imap_get_path_separator (IMAPSession *session,
317 IMAPFolder *folder,
318 const gchar *path,
319 gint *ok);
320 static gchar *imap_get_real_path (IMAPSession *session,
321 IMAPFolder *folder,
322 const gchar *path,
323 gint *ok);
324 #ifdef HAVE_LIBETPAN
325 static void imap_synchronise (FolderItem *item, gint days);
326 #endif
327 static gboolean imap_is_busy (Folder *folder);
329 static void imap_free_capabilities (IMAPSession *session);
331 /* low-level IMAP4rev1 commands */
332 static gint imap_cmd_login (IMAPSession *session,
333 const gchar *user,
334 const gchar *pass,
335 const gchar *type);
336 static gint imap_cmd_noop (IMAPSession *session);
337 #ifdef USE_GNUTLS
338 static gint imap_cmd_starttls (IMAPSession *session);
339 #endif
340 static gint imap_cmd_select (IMAPSession *session,
341 const gchar *folder,
342 gint *exists,
343 gint *recent,
344 gint *unseen,
345 guint32 *uid_validity,
346 gint *can_create_flags,
347 GSList **ok_flags,
348 gboolean block);
349 static gint imap_cmd_close (IMAPSession *session);
350 static gint imap_cmd_examine (IMAPSession *session,
351 const gchar *folder,
352 gint *exists,
353 gint *recent,
354 gint *unseen,
355 guint32 *uid_validity,
356 gboolean block);
357 static gint imap_cmd_create (IMAPSession *sock,
358 const gchar *folder);
359 static gint imap_cmd_rename (IMAPSession *sock,
360 const gchar *oldfolder,
361 const gchar *newfolder);
362 static gint imap_cmd_delete (IMAPSession *session,
363 const gchar *folder);
364 static gint imap_cmd_fetch (IMAPSession *sock,
365 guint32 uid,
366 const gchar *filename,
367 gboolean headers,
368 gboolean body);
369 static gint imap_cmd_append (IMAPSession *session,
370 IMAPFolderItem *item,
371 const gchar *destfolder,
372 const gchar *file,
373 IMAPFlags flags,
374 guint32 *new_uid);
375 static gint imap_cmd_copy (IMAPSession *session,
376 struct mailimap_set * set,
377 const gchar *destfolder,
378 GRelation *uid_mapping,
379 struct mailimap_set ** source,
380 struct mailimap_set ** dest);
381 static gint imap_cmd_store (IMAPSession *session,
382 IMAPFolderItem *item,
383 struct mailimap_set * set,
384 IMAPFlags flags,
385 GSList *tags,
386 int do_add);
387 static gint imap_cmd_expunge (IMAPSession *session, gboolean force);
389 static void imap_path_separator_subst (gchar *str,
390 gchar separator);
392 static gboolean imap_rename_folder_func (GNode *node,
393 gpointer data);
394 static gint imap_get_num_list (Folder *folder,
395 FolderItem *item,
396 GSList **list,
397 gboolean *old_uids_valid);
398 static GSList *imap_get_msginfos (Folder *folder,
399 FolderItem *item,
400 GSList *msgnum_list);
401 static MsgInfo *imap_get_msginfo (Folder *folder,
402 FolderItem *item,
403 gint num);
404 static gboolean imap_scan_required (Folder *folder,
405 FolderItem *item);
406 static void imap_change_flags (Folder *folder,
407 FolderItem *item,
408 MsgInfo *msginfo,
409 MsgPermFlags newflags);
410 static gint imap_get_flags (Folder *folder,
411 FolderItem *item,
412 MsgInfoList *msglist,
413 GRelation *msgflags);
414 static gchar *imap_folder_get_path (Folder *folder);
415 static gchar *imap_item_get_path (Folder *folder,
416 FolderItem *item);
417 static MsgInfo *imap_parse_msg(const gchar *file, FolderItem *item);
420 /* data types conversion libetpan <-> claws */
421 static GSList * imap_list_from_lep(IMAPFolder * folder,
422 clist * list, const gchar * real_path, gboolean all);
423 static GSList * imap_get_lep_set_from_numlist(IMAPFolder *folder, MsgNumberList *numlist);
424 static GSList * imap_get_lep_set_from_msglist(IMAPFolder *folder, MsgInfoList *msglist);
425 static GSList * imap_uid_list_from_lep(clist * list);
426 static GSList * imap_uid_list_from_lep_tab(carray * list);
427 static void imap_flags_hash_from_lep_uid_flags_tab(carray * list,
428 GHashTable * hash,
429 GHashTable *tags_hash);
430 static MsgInfo *imap_envelope_from_lep(struct imap_fetch_env_info * info,
431 FolderItem *item);
432 static void imap_lep_set_free(GSList *seq_list);
433 static struct mailimap_flag_list * imap_flag_to_lep(IMAPFolderItem *item, IMAPFlags flags, GSList *tags);
435 typedef struct _hashtable_data {
436 GSList *msglist;
437 IMAPFolderItem *item;
438 } hashtable_data;
440 static FolderClass imap_class;
442 FolderClass *imap_get_class(void)
444 if (imap_class.idstr == NULL) {
445 imap_class.type = F_IMAP;
446 imap_class.idstr = "imap";
447 imap_class.uistr = "IMAP4";
449 /* Folder functions */
450 imap_class.new_folder = imap_folder_new;
451 imap_class.destroy_folder = imap_folder_destroy;
452 imap_class.scan_tree = imap_scan_tree;
453 imap_class.create_tree = imap_create_tree;
455 /* FolderItem functions */
456 imap_class.item_new = imap_folder_item_new;
457 imap_class.item_destroy = imap_folder_item_destroy;
458 imap_class.item_get_path = imap_item_get_path;
459 imap_class.create_folder = imap_create_folder;
460 imap_class.rename_folder = imap_rename_folder;
461 imap_class.remove_folder = imap_remove_folder;
462 imap_class.close = imap_close;
463 imap_class.get_num_list = imap_get_num_list;
464 imap_class.scan_required = imap_scan_required;
465 imap_class.set_xml = folder_set_xml;
466 imap_class.get_xml = folder_get_xml;
467 imap_class.item_set_xml = imap_item_set_xml;
468 imap_class.item_get_xml = imap_item_get_xml;
470 /* Message functions */
471 imap_class.get_msginfo = imap_get_msginfo;
472 imap_class.get_msginfos = imap_get_msginfos;
473 imap_class.fetch_msg = imap_fetch_msg;
474 imap_class.fetch_msg_full = imap_fetch_msg_full;
475 imap_class.add_msg = imap_add_msg;
476 imap_class.add_msgs = imap_add_msgs;
477 imap_class.copy_msg = imap_copy_msg;
478 imap_class.copy_msgs = imap_copy_msgs;
479 imap_class.remove_msg = imap_remove_msg;
480 imap_class.remove_msgs = imap_remove_msgs;
481 imap_class.expunge = imap_expunge;
482 imap_class.remove_all_msg = imap_remove_all_msg;
483 imap_class.is_msg_changed = imap_is_msg_changed;
484 imap_class.change_flags = imap_change_flags;
485 imap_class.get_flags = imap_get_flags;
486 imap_class.set_batch = imap_set_batch;
487 imap_class.synchronise = imap_synchronise;
488 imap_class.remove_cached_msg = imap_remove_cached_msg;
489 imap_class.commit_tags = imap_commit_tags;
490 #ifdef USE_PTREAD
491 pthread_mutex_init(&imap_mutex, NULL);
492 #endif
495 return &imap_class;
498 static void imap_refresh_sensitivity (IMAPSession *session)
500 MainWindow *mainwin;
502 if (session->sens_update_block)
503 return;
504 mainwin = mainwindow_get_mainwindow();
505 if (mainwin) {
506 toolbar_main_set_sensitive(mainwin);
507 main_window_set_menu_sensitive(mainwin);
511 static void lock_session(IMAPSession *session)
513 if (session) {
514 debug_print("locking session %p (%d)\n", session, session->busy);
515 if (session->busy)
516 debug_print(" SESSION WAS LOCKED !! \n");
517 session->busy = TRUE;
518 imap_refresh_sensitivity(session);
519 } else {
520 debug_print("can't lock null session\n");
524 static void unlock_session(IMAPSession *session)
526 if (session) {
527 debug_print("unlocking session %p\n", session);
528 session->busy = FALSE;
529 imap_refresh_sensitivity(session);
530 } else {
531 debug_print("can't unlock null session\n");
535 static void imap_disc_session_destroy(IMAPSession *session)
537 RemoteFolder *rfolder = NULL;
539 if (session == NULL)
540 return;
542 rfolder = REMOTE_FOLDER(IMAP_SESSION(session)->folder);
544 if (rfolder == NULL)
545 return;
546 log_warning(LOG_PROTOCOL, _("IMAP4 connection broken\n"));
547 SESSION(session)->state = SESSION_DISCONNECTED;
548 SESSION(session)->sock = NULL;
551 static gboolean is_fatal(int libetpan_errcode)
553 switch(libetpan_errcode) {
554 case MAILIMAP_ERROR_STREAM:
555 case MAILIMAP_ERROR_PROTOCOL:
556 case MAILIMAP_ERROR_PARSE:
557 case MAILIMAP_ERROR_BAD_STATE:
558 return TRUE;
559 default:
560 return FALSE;
564 static void imap_handle_error(Session *session, int libetpan_errcode)
566 const gchar *session_server = (session ? session->server:"(null)");
567 switch(libetpan_errcode) {
568 case MAILIMAP_NO_ERROR:
569 return;
570 case MAILIMAP_NO_ERROR_AUTHENTICATED:
571 log_warning(LOG_PROTOCOL, _("IMAP error on %s: authenticated\n"), session_server);
572 break;
573 case MAILIMAP_NO_ERROR_NON_AUTHENTICATED:
574 log_warning(LOG_PROTOCOL, _("IMAP error on %s: not authenticated\n"), session_server);
575 break;
576 case MAILIMAP_ERROR_BAD_STATE:
577 log_warning(LOG_PROTOCOL, _("IMAP error on %s: bad state\n"), session_server);
578 break;
579 case MAILIMAP_ERROR_STREAM:
580 log_warning(LOG_PROTOCOL, _("IMAP error on %s: stream error\n"), session_server);
581 break;
582 case MAILIMAP_ERROR_PARSE:
583 log_warning(LOG_PROTOCOL, _("IMAP error on %s: parse error "
584 "(very probably non-RFC compliance from the server)\n"), session_server);
585 break;
586 case MAILIMAP_ERROR_CONNECTION_REFUSED:
587 log_warning(LOG_PROTOCOL, _("IMAP error on %s: connection refused\n"), session_server);
588 break;
589 case MAILIMAP_ERROR_MEMORY:
590 log_warning(LOG_PROTOCOL, _("IMAP error on %s: memory error\n"), session_server);
591 break;
592 case MAILIMAP_ERROR_FATAL:
593 log_warning(LOG_PROTOCOL, _("IMAP error on %s: fatal error\n"), session_server);
594 break;
595 case MAILIMAP_ERROR_PROTOCOL:
596 log_warning(LOG_PROTOCOL, _("IMAP error on %s: protocol error"
597 "(very probably non-RFC compliance from the server)\n"), session_server);
598 break;
599 case MAILIMAP_ERROR_DONT_ACCEPT_CONNECTION:
600 log_warning(LOG_PROTOCOL, _("IMAP error on %s: connection not accepted\n"), session_server);
601 break;
602 case MAILIMAP_ERROR_APPEND:
603 log_warning(LOG_PROTOCOL, _("IMAP error on %s: APPEND error\n"), session_server);
604 break;
605 case MAILIMAP_ERROR_NOOP:
606 log_warning(LOG_PROTOCOL, _("IMAP error on %s: NOOP error\n"), session_server);
607 break;
608 case MAILIMAP_ERROR_LOGOUT:
609 log_warning(LOG_PROTOCOL, _("IMAP error on %s: LOGOUT error\n"), session_server);
610 break;
611 case MAILIMAP_ERROR_CAPABILITY:
612 log_warning(LOG_PROTOCOL, _("IMAP error on %s: CAPABILITY error\n"), session_server);
613 break;
614 case MAILIMAP_ERROR_CHECK:
615 log_warning(LOG_PROTOCOL, _("IMAP error on %s: CHECK error\n"), session_server);
616 break;
617 case MAILIMAP_ERROR_CLOSE:
618 log_warning(LOG_PROTOCOL, _("IMAP error on %s: CLOSE error\n"), session_server);
619 break;
620 case MAILIMAP_ERROR_EXPUNGE:
621 log_warning(LOG_PROTOCOL, _("IMAP error on %s: EXPUNGE error\n"), session_server);
622 break;
623 case MAILIMAP_ERROR_COPY:
624 log_warning(LOG_PROTOCOL, _("IMAP error on %s: COPY error\n"), session_server);
625 break;
626 case MAILIMAP_ERROR_UID_COPY:
627 log_warning(LOG_PROTOCOL, _("IMAP error on %s: UID COPY error\n"), session_server);
628 break;
629 case MAILIMAP_ERROR_CREATE:
630 log_warning(LOG_PROTOCOL, _("IMAP error on %s: CREATE error\n"), session_server);
631 break;
632 case MAILIMAP_ERROR_DELETE:
633 log_warning(LOG_PROTOCOL, _("IMAP error on %s: DELETE error\n"), session_server);
634 break;
635 case MAILIMAP_ERROR_EXAMINE:
636 log_warning(LOG_PROTOCOL, _("IMAP error on %s: EXAMINE error\n"), session_server);
637 break;
638 case MAILIMAP_ERROR_FETCH:
639 log_warning(LOG_PROTOCOL, _("IMAP error on %s: FETCH error\n"), session_server);
640 break;
641 case MAILIMAP_ERROR_UID_FETCH:
642 log_warning(LOG_PROTOCOL, _("IMAP error on %s: UID FETCH error\n"), session_server);
643 break;
644 case MAILIMAP_ERROR_LIST:
645 log_warning(LOG_PROTOCOL, _("IMAP error on %s: LIST error\n"), session_server);
646 break;
647 case MAILIMAP_ERROR_LOGIN:
648 log_warning(LOG_PROTOCOL, _("IMAP error on %s: LOGIN error\n"), session_server);
649 break;
650 case MAILIMAP_ERROR_LSUB:
651 log_warning(LOG_PROTOCOL, _("IMAP error on %s: LSUB error\n"), session_server);
652 break;
653 case MAILIMAP_ERROR_RENAME:
654 log_warning(LOG_PROTOCOL, _("IMAP error on %s: RENAME error\n"), session_server);
655 break;
656 case MAILIMAP_ERROR_SEARCH:
657 log_warning(LOG_PROTOCOL, _("IMAP error on %s: SEARCH error\n"), session_server);
658 break;
659 case MAILIMAP_ERROR_UID_SEARCH:
660 log_warning(LOG_PROTOCOL, _("IMAP error on %s: UID SEARCH error\n"), session_server);
661 break;
662 case MAILIMAP_ERROR_SELECT:
663 log_warning(LOG_PROTOCOL, _("IMAP error on %s: SELECT error\n"), session_server);
664 break;
665 case MAILIMAP_ERROR_STATUS:
666 log_warning(LOG_PROTOCOL, _("IMAP error on %s: STATUS error\n"), session_server);
667 break;
668 case MAILIMAP_ERROR_STORE:
669 log_warning(LOG_PROTOCOL, _("IMAP error on %s: STORE error\n"), session_server);
670 break;
671 case MAILIMAP_ERROR_UID_STORE:
672 log_warning(LOG_PROTOCOL, _("IMAP error on %s: UID STORE error\n"), session_server);
673 break;
674 case MAILIMAP_ERROR_SUBSCRIBE:
675 log_warning(LOG_PROTOCOL, _("IMAP error on %s: SUBSCRIBE error\n"), session_server);
676 break;
677 case MAILIMAP_ERROR_UNSUBSCRIBE:
678 log_warning(LOG_PROTOCOL, _("IMAP error on %s: UNSUBSCRIBE error\n"), session_server);
679 break;
680 case MAILIMAP_ERROR_STARTTLS:
681 log_warning(LOG_PROTOCOL, _("IMAP error on %s: STARTTLS error\n"), session_server);
682 break;
683 case MAILIMAP_ERROR_INVAL:
684 log_warning(LOG_PROTOCOL, _("IMAP error on %s: INVAL error\n"), session_server);
685 break;
686 case MAILIMAP_ERROR_EXTENSION:
687 log_warning(LOG_PROTOCOL, _("IMAP error on %s: EXTENSION error\n"), session_server);
688 break;
689 case MAILIMAP_ERROR_SASL:
690 log_warning(LOG_PROTOCOL, _("IMAP error on %s: SASL error\n"), session_server);
691 break;
692 #ifdef USE_GNUTLS
693 case MAILIMAP_ERROR_SSL:
694 log_warning(LOG_PROTOCOL, _("IMAP error on %s: SSL error\n"), session_server);
695 break;
696 #endif
697 default:
698 log_warning(LOG_PROTOCOL, _("IMAP error on %s: Unknown error [%d]\n"),
699 session_server, libetpan_errcode);
700 break;
703 if (session && is_fatal(libetpan_errcode)) {
704 imap_disc_session_destroy(IMAP_SESSION(session));
705 } else if (session && !is_fatal(libetpan_errcode)) {
706 if (IMAP_SESSION(session)->busy)
707 unlock_session(IMAP_SESSION(session));
711 static Folder *imap_folder_new(const gchar *name, const gchar *path)
713 Folder *folder;
715 folder = (Folder *)g_new0(IMAPFolder, 1);
716 folder->klass = &imap_class;
717 imap_folder_init(folder, name, path);
719 return folder;
722 static void imap_folder_destroy(Folder *folder)
724 while (imap_folder_get_refcnt(folder) > 0)
725 gtk_main_iteration();
727 folder_remote_folder_destroy(REMOTE_FOLDER(folder));
728 imap_done(folder);
731 static void imap_folder_init(Folder *folder, const gchar *name,
732 const gchar *path)
734 folder_remote_folder_init((Folder *)folder, name, path);
735 IMAP_FOLDER(folder)->max_set_size = IMAP_SET_MAX_COUNT;
738 static FolderItem *imap_folder_item_new(Folder *folder)
740 IMAPFolderItem *item;
742 item = g_new0(IMAPFolderItem, 1);
743 item->lastuid = 0;
744 item->uid_next = 0;
745 item->uid_list = NULL;
747 return (FolderItem *)item;
750 static void imap_folder_item_destroy(Folder *folder, FolderItem *_item)
752 IMAPFolderItem *item = (IMAPFolderItem *)_item;
754 g_return_if_fail(item != NULL);
755 g_slist_free(item->uid_list);
757 g_free(_item);
760 static gboolean imap_reset_uid_lists_func(GNode *node, gpointer data)
762 IMAPFolderItem *item = (IMAPFolderItem *)node->data;
764 item->lastuid = 0;
765 g_slist_free(item->uid_list);
766 item->uid_list = NULL;
768 return FALSE;
771 static void imap_reset_uid_lists(Folder *folder)
773 if(folder->node == NULL)
774 return;
776 /* Destroy all uid lists and rest last uid */
777 g_node_traverse(folder->node, G_IN_ORDER, G_TRAVERSE_ALL, -1, imap_reset_uid_lists_func, NULL);
780 static int imap_get_capabilities(IMAPSession *session)
782 struct mailimap_capability_data *capabilities = NULL;
783 clistiter *cur;
784 int result = -1;
786 if (session->capability != NULL)
787 return MAILIMAP_NO_ERROR;
789 capabilities = imap_threaded_capability(session->folder, &result);
791 if (result != MAILIMAP_NO_ERROR) {
792 return result;
795 if (capabilities == NULL || capabilities->cap_list == NULL) {
796 return MAILIMAP_NO_ERROR;
799 for(cur = clist_begin(capabilities->cap_list) ; cur != NULL ;
800 cur = clist_next(cur)) {
801 struct mailimap_capability * cap =
802 clist_content(cur);
803 if (!cap || cap->cap_data.cap_name == NULL)
804 continue;
805 session->capability = g_slist_append
806 (session->capability,
807 g_strdup(cap->cap_data.cap_name));
808 debug_print("got capa %s\n", cap->cap_data.cap_name);
810 mailimap_capability_data_free(capabilities);
811 return MAILIMAP_NO_ERROR;
814 static gboolean imap_has_capability(IMAPSession *session, const gchar *cap)
816 GSList *cur;
817 for (cur = session->capability; cur; cur = cur->next) {
818 if (!g_ascii_strcasecmp(cur->data, cap))
819 return TRUE;
821 return FALSE;
824 static gint imap_auth(IMAPSession *session, const gchar *user, const gchar *pass,
825 IMAPAuthType type)
827 gint ok = MAILIMAP_ERROR_LOGIN;
828 static time_t last_login_err = 0;
829 gchar *ext_info = "";
830 int r;
831 gchar *server = NULL;
832 if ((r = imap_get_capabilities(session)) != MAILIMAP_NO_ERROR) {
833 imap_handle_error(SESSION(session), r);
834 return r;
836 server = g_strdup(SESSION(session)->server);
837 switch(type) {
838 case IMAP_AUTH_ANON:
839 ok = imap_cmd_login(session, user, pass, "ANONYMOUS");
840 break;
841 case IMAP_AUTH_CRAM_MD5:
842 ok = imap_cmd_login(session, user, pass, "CRAM-MD5");
843 break;
844 case IMAP_AUTH_DIGEST_MD5:
845 ok = imap_cmd_login(session, user, pass, "DIGEST-MD5");
846 break;
847 case IMAP_AUTH_LOGIN:
848 ok = imap_cmd_login(session, user, pass, "LOGIN");
849 break;
850 case IMAP_AUTH_GSSAPI:
851 ok = imap_cmd_login(session, user, pass, "GSSAPI");
852 break;
853 default:
854 debug_print("capabilities:\n"
855 "\t ANONYMOUS %d\n"
856 "\t CRAM-MD5 %d\n"
857 "\t DIGEST-MD5 %d\n"
858 "\t LOGIN %d\n"
859 "\t GSSAPI %d\n",
860 imap_has_capability(session, "ANONYMOUS"),
861 imap_has_capability(session, "CRAM-MD5"),
862 imap_has_capability(session, "DIGEST-MD5"),
863 imap_has_capability(session, "LOGIN"),
864 imap_has_capability(session, "GSSAPI"));
865 if (imap_has_capability(session, "CRAM-MD5"))
866 ok = imap_cmd_login(session, user, pass, "CRAM-MD5");
867 if (ok == MAILIMAP_ERROR_LOGIN && imap_has_capability(session, "DIGEST-MD5"))
868 ok = imap_cmd_login(session, user, pass, "DIGEST-MD5");
869 if (ok == MAILIMAP_ERROR_LOGIN && imap_has_capability(session, "GSSAPI"))
870 ok = imap_cmd_login(session, user, pass, "GSSAPI");
871 if (ok == MAILIMAP_ERROR_LOGIN) /* we always try LOGIN before giving up */
872 ok = imap_cmd_login(session, user, pass, "LOGIN");
875 if (ok == MAILIMAP_NO_ERROR)
876 session->authenticated = TRUE;
877 else {
878 if (type == IMAP_AUTH_CRAM_MD5) {
879 ext_info = _("\n\nCRAM-MD5 logins only work if libetpan has been "
880 "compiled with SASL support and the "
881 "CRAM-MD5 SASL plugin is installed.");
884 if (type == IMAP_AUTH_DIGEST_MD5) {
885 ext_info = _("\n\nDIGEST-MD5 logins only work if libetpan has been "
886 "compiled with SASL support and the "
887 "DIGEST-MD5 SASL plugin is installed.");
890 if (time(NULL) - last_login_err > 10) {
891 if (!prefs_common.no_recv_err_panel) {
892 alertpanel_error_log(_("Connection to %s failed: "
893 "login refused.%s"),
894 server, ext_info);
895 } else {
896 log_error(LOG_PROTOCOL, _("Connection to %s failed: "
897 "login refused.%s\n"),
898 server, ext_info);
901 last_login_err = time(NULL);
903 g_free(server);
904 return ok;
907 static IMAPSession *imap_reconnect_if_possible(Folder *folder, IMAPSession *session)
909 RemoteFolder *rfolder = REMOTE_FOLDER(folder);
910 /* Check if this is the first try to establish a
911 connection, if yes we don't try to reconnect */
912 debug_print("reconnecting\n");
913 if (rfolder->session == NULL) {
914 log_warning(LOG_PROTOCOL, _("Connecting to %s failed"),
915 folder->account->recv_server);
916 SESSION(session)->sock = NULL;
917 session_destroy(SESSION(session));
918 session = NULL;
919 } else {
920 rfolder->session = NULL;
921 log_warning(LOG_PROTOCOL, _("IMAP4 connection to %s has been"
922 " disconnected. Reconnecting...\n"),
923 folder->account->recv_server);
924 statusbar_print_all(_("IMAP4 connection to %s has been"
925 " disconnected. Reconnecting...\n"),
926 folder->account->recv_server);
927 SESSION(session)->state = SESSION_DISCONNECTED;
928 SESSION(session)->sock = NULL;
929 session_destroy(SESSION(session));
930 /* Clear folders session to make imap_session_get create
931 a new session, because of rfolder->session == NULL
932 it will not try to reconnect again and so avoid an
933 endless loop */
934 debug_print("getting session...\n");
935 session = imap_session_get(folder);
936 rfolder->session = SESSION(session);
937 statusbar_pop_all();
939 return session;
942 static IMAPSession *imap_session_get(Folder *folder)
944 RemoteFolder *rfolder = REMOTE_FOLDER(folder);
945 IMAPSession *session = NULL;
946 gint r = MAILIMAP_NO_ERROR;
948 g_return_val_if_fail(folder != NULL, NULL);
949 g_return_val_if_fail(FOLDER_CLASS(folder) == &imap_class, NULL);
950 g_return_val_if_fail(folder->account != NULL, NULL);
952 if (prefs_common.work_offline &&
953 !inc_offline_should_override(FALSE,
954 _("Claws Mail needs network access in order "
955 "to access the IMAP server."))) {
956 return NULL;
959 /* Make sure we have a session */
960 if (rfolder->session != NULL && rfolder->session->state != SESSION_DISCONNECTED) {
961 session = IMAP_SESSION(rfolder->session);
962 } else if (rfolder->session != NULL && rfolder->session->state == SESSION_DISCONNECTED) {
963 session_destroy(SESSION(rfolder->session));
964 rfolder->session = NULL;
965 goto new_conn;
966 } else if (rfolder->connecting) {
967 debug_print("already connecting\n");
968 return NULL;
969 } else {
970 new_conn:
971 imap_reset_uid_lists(folder);
972 if (time(NULL) - rfolder->last_failure <= 2)
973 return NULL;
974 rfolder->connecting = TRUE;
975 session = imap_session_new(folder, folder->account);
977 if(session == NULL) {
978 rfolder->last_failure = time(NULL);
979 rfolder->connecting = FALSE;
980 return NULL;
983 /* Make sure session is authenticated */
984 if (!IMAP_SESSION(session)->authenticated)
985 r = imap_session_authenticate(IMAP_SESSION(session), folder->account);
987 if (r != MAILIMAP_NO_ERROR || (!is_fatal(r) && !IMAP_SESSION(session)->authenticated)) {
988 rfolder->session = NULL;
989 if (!is_fatal(r)) {
990 imap_threaded_disconnect(session->folder);
991 SESSION(session)->state = SESSION_DISCONNECTED;
992 SESSION(session)->sock = NULL;
993 session_destroy(SESSION(session));
995 rfolder->last_failure = time(NULL);
996 rfolder->connecting = FALSE;
997 return NULL;
1000 /* I think the point of this code is to avoid sending a
1001 * keepalive if we've used the session recently and therefore
1002 * think it's still alive. Unfortunately, most of the code
1003 * does not yet check for errors on the socket, and so if the
1004 * connection drops we don't notice until the timeout expires.
1005 * A better solution than sending a NOOP every time would be
1006 * for every command to be prepared to retry until it is
1007 * successfully sent. -- mbp */
1008 if ((time(NULL) - SESSION(session)->last_access_time > SESSION_TIMEOUT_INTERVAL) || session->cancelled) {
1009 /* verify that the session is still alive */
1010 if ((r = imap_cmd_noop(session)) != MAILIMAP_NO_ERROR) {
1011 debug_print("disconnected!\n");
1012 if (!is_fatal(r))
1013 session = imap_reconnect_if_possible(folder, session);
1014 else {
1015 rfolder->session = NULL;
1016 rfolder->connecting = FALSE;
1017 session = imap_session_get(folder);
1020 if (session)
1021 session->cancelled = FALSE;
1024 rfolder->session = SESSION(session);
1025 rfolder->connecting = FALSE;
1027 return IMAP_SESSION(session);
1030 static IMAPSession *imap_session_new(Folder * folder,
1031 const PrefsAccount *account)
1033 IMAPSession *session;
1034 gushort port;
1035 int r;
1036 int authenticated = FALSE;
1038 #ifdef USE_GNUTLS
1039 /* FIXME: IMAP over SSL only... */
1040 SSLType ssl_type;
1042 port = account->set_imapport ? account->imapport
1043 : account->ssl_imap == SSL_TUNNEL ? IMAPS_PORT : IMAP4_PORT;
1044 ssl_type = account->ssl_imap;
1045 #else
1046 if (account->ssl_imap != SSL_NONE) {
1047 if (alertpanel_full(_("Insecure connection"),
1048 _("This connection is configured to be secured "
1049 "using SSL, but SSL is not available in this "
1050 "build of Claws Mail. \n\n"
1051 "Do you want to continue connecting to this "
1052 "server? The communication would not be "
1053 "secure."),
1054 GTK_STOCK_CANCEL, _("Con_tinue connecting"),
1055 NULL, FALSE, NULL, ALERT_WARNING,
1056 G_ALERTDEFAULT) != G_ALERTALTERNATE)
1057 return NULL;
1059 port = account->set_imapport ? account->imapport
1060 : IMAP4_PORT;
1061 #endif
1063 imap_init(folder);
1064 statuswindow_print_all(_("Connecting to IMAP4 server: %s..."), folder->account->recv_server);
1065 #ifndef G_OS_WIN32
1066 if (account->set_tunnelcmd) {
1067 r = imap_threaded_connect_cmd(folder,
1068 account->tunnelcmd,
1069 account->recv_server,
1070 port);
1072 else
1073 #endif
1075 #ifdef USE_GNUTLS
1076 if (ssl_type == SSL_TUNNEL) {
1077 r = imap_threaded_connect_ssl(folder,
1078 account->recv_server,
1079 port);
1081 else
1082 #endif
1084 r = imap_threaded_connect(folder,
1085 account->recv_server,
1086 port);
1090 statuswindow_pop_all();
1091 if (r == MAILIMAP_NO_ERROR_AUTHENTICATED) {
1092 authenticated = TRUE;
1094 else if (r == MAILIMAP_NO_ERROR_NON_AUTHENTICATED) {
1095 authenticated = FALSE;
1097 else {
1098 #ifdef USE_GNUTLS
1099 if (r == MAILIMAP_ERROR_SSL)
1100 log_error(LOG_PROTOCOL, _("SSL handshake failed\n"));
1101 else
1102 #endif
1103 imap_handle_error(NULL, r);
1105 if(!prefs_common.no_recv_err_panel) {
1106 alertpanel_error_log(_("Can't connect to IMAP4 server: %s:%d"),
1107 account->recv_server, port);
1108 } else {
1109 log_error(LOG_PROTOCOL, _("Can't connect to IMAP4 server: %s:%d\n"),
1110 account->recv_server, port);
1113 return NULL;
1116 session = g_new0(IMAPSession, 1);
1117 session_init(SESSION(session), account, FALSE);
1118 SESSION(session)->type = SESSION_IMAP;
1119 SESSION(session)->server = g_strdup(account->recv_server);
1120 SESSION(session)->port = port;
1121 SESSION(session)->sock = NULL;
1123 SESSION(session)->destroy = imap_session_destroy;
1125 session->capability = NULL;
1127 session->authenticated = authenticated;
1128 session->mbox = NULL;
1129 session->exists = 0;
1130 session->recent = 0;
1131 session->expunge = 0;
1132 session->cmd_count = 0;
1133 session->folder = folder;
1134 IMAP_FOLDER(session->folder)->last_seen_separator = 0;
1136 #ifdef USE_GNUTLS
1137 if (account->ssl_imap == SSL_STARTTLS) {
1138 gint ok;
1140 ok = imap_cmd_starttls(session);
1141 if (ok != MAILIMAP_NO_ERROR) {
1142 log_warning(LOG_PROTOCOL, _("Can't start TLS session.\n"));
1143 if (!is_fatal(ok)) {
1144 SESSION(session)->sock = NULL;
1145 session_destroy(SESSION(session));
1147 return NULL;
1150 imap_free_capabilities(session);
1151 session->authenticated = FALSE;
1152 session->uidplus = FALSE;
1153 session->cmd_count = 1;
1155 #endif
1156 log_message(LOG_PROTOCOL, "IMAP connection is %s-authenticated\n",
1157 (session->authenticated) ? "pre" : "un");
1159 return session;
1162 static gint imap_session_authenticate(IMAPSession *session,
1163 PrefsAccount *account)
1165 gchar *pass, *acc_pass;
1166 gboolean failed = FALSE;
1167 gint ok = MAILIMAP_NO_ERROR;
1168 g_return_val_if_fail(account->userid != NULL, MAILIMAP_ERROR_BAD_STATE);
1169 acc_pass = account->passwd;
1170 try_again:
1171 pass = acc_pass;
1172 if (!pass && account->imap_auth_type != IMAP_AUTH_ANON && account->imap_auth_type != IMAP_AUTH_GSSAPI) {
1173 gchar *tmp_pass;
1174 tmp_pass = input_dialog_query_password_keep(account->recv_server,
1175 account->userid,
1176 &(account->session_passwd));
1177 if (!tmp_pass)
1178 return MAILIMAP_NO_ERROR;
1179 Xstrdup_a(pass, tmp_pass, {g_free(tmp_pass); return MAILIMAP_NO_ERROR;});
1180 g_free(tmp_pass);
1181 } else if (account->imap_auth_type == IMAP_AUTH_ANON || account->imap_auth_type == IMAP_AUTH_GSSAPI) {
1182 pass = "";
1184 statuswindow_print_all(_("Connecting to IMAP4 server %s...\n"),
1185 account->recv_server);
1186 if ((ok = imap_auth(session, account->userid, pass, account->imap_auth_type)) != MAILIMAP_NO_ERROR) {
1187 statusbar_pop_all();
1189 if (!failed && !is_fatal(ok)) {
1190 acc_pass = NULL;
1191 failed = TRUE;
1192 if (account->session_passwd != NULL) {
1193 g_free(account->session_passwd);
1194 account->session_passwd = NULL;
1196 goto try_again;
1197 } else {
1198 if (prefs_common.no_recv_err_panel) {
1199 log_error(LOG_PROTOCOL, _("Couldn't login to IMAP server %s.\n"), account->recv_server);
1200 mainwindow_show_error();
1201 } else
1202 alertpanel_error_log(_("Couldn't login to IMAP server %s."), account->recv_server);
1205 return ok;
1208 statuswindow_pop_all();
1209 session->authenticated = TRUE;
1210 return MAILIMAP_NO_ERROR;
1213 static void imap_session_destroy(Session *session)
1215 if (session->state != SESSION_DISCONNECTED)
1216 imap_threaded_disconnect(IMAP_SESSION(session)->folder);
1218 imap_free_capabilities(IMAP_SESSION(session));
1219 g_free(IMAP_SESSION(session)->mbox);
1222 static gchar *imap_fetch_msg(Folder *folder, FolderItem *item, gint uid)
1224 return imap_fetch_msg_full(folder, item, uid, TRUE, TRUE);
1227 static guint get_file_size_with_crs(const gchar *filename)
1229 FILE *fp = NULL;
1230 guint cnt = 0;
1231 gchar buf[4096];
1233 if (filename == NULL)
1234 return -1;
1236 fp = g_fopen(filename, "rb");
1237 if (!fp)
1238 return -1;
1240 while (fgets(buf, sizeof (buf), fp) != NULL) {
1241 cnt += strlen(buf);
1242 if (!strstr(buf, "\r\n") && strstr(buf, "\n"))
1243 cnt++;
1246 fclose(fp);
1247 return cnt;
1250 static void imap_remove_cached_msg(Folder *folder, FolderItem *item, MsgInfo *msginfo)
1252 gchar *path, *filename;
1254 path = folder_item_get_path(item);
1256 if (!is_dir_exist(path)) {
1257 g_free(path);
1258 return;
1261 filename = g_strconcat(path, G_DIR_SEPARATOR_S, itos(msginfo->msgnum), NULL);
1262 g_free(path);
1264 if (is_file_exist(filename)) {
1265 claws_unlink(filename);
1267 g_free(filename);
1270 typedef struct _TagsData {
1271 gchar *str;
1272 GSList *msglist;
1273 IMAPFolderItem *item;
1274 } TagsData;
1276 static void imap_commit_tags(FolderItem *item, MsgInfo *msginfo, GSList *tags_set, GSList *tags_unset)
1278 IMAPSession *session;
1279 gint ok, can_create_tags;
1280 Folder *folder = NULL;
1281 TagsData *ht_data = NULL;
1282 GSList *cur;
1284 g_return_if_fail(item != NULL);
1285 g_return_if_fail(msginfo != NULL);
1287 folder = item->folder;
1288 debug_print("getting session...\n");
1289 session = imap_session_get(folder);
1291 if (!session) {
1292 debug_print("can't get session\n");
1293 return;
1296 ok = imap_select(session, IMAP_FOLDER(folder), item,
1297 NULL, NULL, NULL, NULL, &can_create_tags, FALSE);
1299 if (ok != MAILIMAP_NO_ERROR) {
1300 return;
1304 if (IMAP_FOLDER_ITEM(item)->can_create_flags != ITEM_CAN_CREATE_FLAGS)
1305 return;
1307 if (IMAP_FOLDER_ITEM(item)->batching) {
1308 /* instead of performing an UID STORE command for each message change,
1309 * as a lot of them can change "together", we just fill in hashtables
1310 * and defer the treatment so that we're able to send only one
1311 * command.
1313 debug_print("IMAP batch mode on, deferring tags change\n");
1314 for (cur = tags_set; cur; cur = cur->next) {
1315 gint cur_tag = GPOINTER_TO_INT(cur->data);
1316 if (cur_tag) {
1317 ht_data = g_hash_table_lookup(IMAP_FOLDER_ITEM(item)->tags_set_table,
1318 GINT_TO_POINTER(cur_tag));
1319 if (ht_data == NULL) {
1320 ht_data = g_new0(TagsData, 1);
1321 ht_data->str = g_strdup(tags_get_tag(cur_tag));
1322 ht_data->item = IMAP_FOLDER_ITEM(item);
1323 g_hash_table_insert(IMAP_FOLDER_ITEM(item)->tags_set_table,
1324 GINT_TO_POINTER(cur_tag), ht_data);
1326 ht_data->msglist = g_slist_prepend(ht_data->msglist, GINT_TO_POINTER(msginfo->msgnum));
1329 for (cur = tags_unset; cur; cur = cur->next) {
1330 gint cur_tag = GPOINTER_TO_INT(cur->data);
1331 if (cur_tag) {
1332 ht_data = g_hash_table_lookup(IMAP_FOLDER_ITEM(item)->tags_unset_table,
1333 GINT_TO_POINTER(cur_tag));
1334 if (ht_data == NULL) {
1335 ht_data = g_new0(TagsData, 1);
1336 ht_data->str = g_strdup(tags_get_tag(cur_tag));
1337 ht_data->item = IMAP_FOLDER_ITEM(item);
1338 g_hash_table_insert(IMAP_FOLDER_ITEM(item)->tags_unset_table,
1339 GINT_TO_POINTER(cur_tag), ht_data);
1341 ht_data->msglist = g_slist_prepend(ht_data->msglist, GINT_TO_POINTER(msginfo->msgnum));
1344 } else {
1345 GSList *list_set = NULL;
1346 GSList *list_unset = NULL;
1347 GSList numlist;
1349 numlist.data = GINT_TO_POINTER(msginfo->msgnum);
1350 numlist.next = NULL;
1352 debug_print("IMAP changing tags NOW\n");
1353 for (cur = tags_set; cur; cur = cur->next) {
1354 gint cur_tag = GPOINTER_TO_INT(cur->data);
1355 const gchar *str = tags_get_tag(cur_tag);
1356 if (strcmp(str, "$Forwarded") && strcmp(str, "Junk") && strcmp(str, "NonJunk") && strcmp(str, "NotJunk") && strcmp(str, "NoJunk") && strcmp(str, "Junk") )
1357 list_set = g_slist_prepend(list_set, g_strdup(str));
1359 if (list_set) {
1360 ok = imap_set_message_flags(session,
1361 IMAP_FOLDER_ITEM(item), &numlist, 0, list_set, TRUE);
1362 slist_free_strings(list_set);
1363 g_slist_free(list_set);
1364 if (ok != MAILIMAP_NO_ERROR) {
1365 return;
1369 for (cur = tags_unset; cur; cur = cur->next) {
1370 gint cur_tag = GPOINTER_TO_INT(cur->data);
1371 const gchar *str = tags_get_tag(cur_tag);
1372 if (strcmp(str, "$Forwarded") && strcmp(str, "Junk") && strcmp(str, "NonJunk") && strcmp(str, "NotJunk") && strcmp(str, "NoJunk") && strcmp(str, "Junk") )
1373 list_unset = g_slist_prepend(list_unset, g_strdup(str));
1375 if (list_unset) {
1376 ok = imap_set_message_flags(session,
1377 IMAP_FOLDER_ITEM(item), &numlist, 0, list_unset, FALSE);
1378 slist_free_strings(list_unset);
1379 g_slist_free(list_unset);
1380 if (ok != MAILIMAP_NO_ERROR) {
1381 return;
1387 static gchar *imap_fetch_msg_full(Folder *folder, FolderItem *item, gint uid,
1388 gboolean headers, gboolean body)
1390 gchar *path, *filename;
1391 IMAPSession *session;
1392 gint ok;
1394 g_return_val_if_fail(folder != NULL, NULL);
1395 g_return_val_if_fail(item != NULL, NULL);
1397 if (uid == 0)
1398 return NULL;
1400 path = folder_item_get_path(item);
1401 if (!is_dir_exist(path))
1402 make_dir_hier(path);
1403 filename = g_strconcat(path, G_DIR_SEPARATOR_S, itos(uid), NULL);
1404 g_free(path);
1405 debug_print("trying to fetch cached %s\n", filename);
1406 if (is_file_exist(filename)) {
1407 /* see whether the local file represents the whole message
1408 * or not. As the IMAP server reports size with \r chars,
1409 * we have to update the local file (UNIX \n only) size */
1410 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1411 guint have_size = -1;
1413 if (cached)
1414 debug_print("message %d has been already %scached.\n", uid,
1415 MSG_IS_FULLY_CACHED(cached->flags) ? "fully ":"");
1417 if (!cached || !MSG_IS_FULLY_CACHED(cached->flags)) {
1418 have_size = get_file_size_with_crs(filename);
1419 if (cached && (cached->size <= have_size || !body)) {
1420 procmsg_msginfo_free(cached);
1421 ok = file_strip_crs(filename);
1422 if (ok == 0 && cached && cached->size <= have_size) {
1423 /* we have it all and stripped */
1424 debug_print("...fully cached in fact; setting flag.\n");
1425 procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
1427 return filename;
1428 } else if (!cached && time(NULL) - get_file_mtime(filename) < 60) {
1429 debug_print("message not cached and file recent, considering file complete\n");
1430 ok = file_strip_crs(filename);
1431 if (ok == 0)
1432 return filename;
1433 } else {
1434 procmsg_msginfo_free(cached);
1437 if (cached && MSG_IS_FULLY_CACHED(cached->flags)) {
1438 procmsg_msginfo_free(cached);
1439 return filename;
1441 } else {
1442 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1443 if (cached) {
1444 procmsg_msginfo_unset_flags(cached, MSG_FULLY_CACHED, 0);
1445 procmsg_msginfo_free(cached);
1449 debug_print("getting session...\n");
1450 session = imap_session_get(folder);
1452 if (!session) {
1453 g_free(filename);
1454 return NULL;
1456 session_set_access_time(SESSION(session));
1457 lock_session(session); /* unlocked later in the function */
1459 debug_print("IMAP fetching messages\n");
1460 ok = imap_select(session, IMAP_FOLDER(folder), item,
1461 NULL, NULL, NULL, NULL, NULL, FALSE);
1462 if (ok != MAILIMAP_NO_ERROR) {
1463 g_warning("can't select mailbox %s\n", item->path);
1464 g_free(filename);
1465 return NULL;
1468 session_set_access_time(SESSION(session));
1470 debug_print("getting message %d...\n", uid);
1471 ok = imap_cmd_fetch(session, (guint32)uid, filename, headers, body);
1473 if (ok != MAILIMAP_NO_ERROR) {
1474 g_warning("can't fetch message %d\n", uid);
1475 g_free(filename);
1476 return NULL;
1479 session_set_access_time(SESSION(session));
1480 unlock_session(session);
1482 ok = file_strip_crs(filename);
1484 if (ok == 0 && headers && body) {
1485 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1486 if (cached) {
1487 procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
1488 procmsg_msginfo_free(cached);
1490 } else if (ok == -1) {
1491 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1492 if (cached) {
1493 procmsg_msginfo_unset_flags(cached, MSG_FULLY_CACHED, 0);
1494 procmsg_msginfo_free(cached);
1497 return filename;
1500 static gboolean imap_is_msg_fully_cached(Folder *folder, FolderItem *item, gint uid)
1502 gchar *path, *filename;
1503 guint size = 0;
1504 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1506 if (!cached)
1507 return FALSE;
1509 if (MSG_IS_FULLY_CACHED(cached->flags)) {
1510 procmsg_msginfo_free(cached);
1511 return TRUE;
1513 path = folder_item_get_path(item);
1514 if (!is_dir_exist(path))
1515 return FALSE;
1517 filename = g_strconcat(path, G_DIR_SEPARATOR_S, itos(uid), NULL);
1518 g_free(path);
1519 if (is_file_exist(filename)) {
1520 if (cached && cached->total_size == cached->size) {
1521 /* fast path */
1522 g_free(filename);
1523 procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
1524 return TRUE;
1526 size = get_file_size_with_crs(filename);
1527 g_free(filename);
1529 if (cached && size >= cached->size) {
1530 cached->total_size = cached->size;
1531 procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
1532 procmsg_msginfo_free(cached);
1533 return TRUE;
1535 if (cached)
1536 procmsg_msginfo_free(cached);
1537 return FALSE;
1540 void imap_cache_msg(FolderItem *item, gint msgnum)
1542 Folder *folder = NULL;
1544 if (!item)
1545 return;
1546 folder = item->folder;
1548 if (!imap_is_msg_fully_cached(folder, item, msgnum)) {
1549 gchar *tmp = imap_fetch_msg_full(folder, item, msgnum, TRUE, TRUE);
1550 debug_print("fetched %s\n", tmp);
1551 g_free(tmp);
1555 static gint imap_add_msg(Folder *folder, FolderItem *dest,
1556 const gchar *file, MsgFlags *flags)
1558 gint ret;
1559 GSList file_list;
1560 MsgFileInfo fileinfo;
1562 g_return_val_if_fail(file != NULL, -1);
1564 fileinfo.msginfo = NULL;
1565 fileinfo.file = (gchar *)file;
1566 fileinfo.flags = flags;
1567 file_list.data = &fileinfo;
1568 file_list.next = NULL;
1570 ret = imap_add_msgs(folder, dest, &file_list, NULL);
1571 return ret;
1574 static gint imap_add_msgs(Folder *folder, FolderItem *dest, GSList *file_list,
1575 GRelation *relation)
1577 gchar *destdir;
1578 IMAPSession *session;
1579 guint32 last_uid = 0;
1580 GSList *cur;
1581 MsgFileInfo *fileinfo;
1582 gint ok = MAILIMAP_NO_ERROR;
1583 gint curnum = 0, total = 0;
1584 gboolean missing_uids = FALSE;
1586 g_return_val_if_fail(folder != NULL, -1);
1587 g_return_val_if_fail(dest != NULL, -1);
1588 g_return_val_if_fail(file_list != NULL, -1);
1590 debug_print("getting session...\n");
1591 session = imap_session_get(folder);
1592 if (!session) {
1593 return -1;
1595 destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path, &ok);
1596 if (is_fatal(ok))
1597 return -1;
1598 statusbar_print_all(_("Adding messages..."));
1599 total = g_slist_length(file_list);
1600 for (cur = file_list; cur != NULL; cur = cur->next) {
1601 IMAPFlags iflags = 0;
1602 guint32 new_uid = 0;
1603 gchar *real_file = NULL;
1604 fileinfo = (MsgFileInfo *)cur->data;
1606 statusbar_progress_all(curnum, total, total < 10 ? 1:10);
1607 curnum++;
1609 if (fileinfo->flags) {
1610 if (MSG_IS_MARKED(*fileinfo->flags))
1611 iflags |= IMAP_FLAG_FLAGGED;
1612 if (MSG_IS_REPLIED(*fileinfo->flags))
1613 iflags |= IMAP_FLAG_ANSWERED;
1614 if (MSG_IS_FORWARDED(*fileinfo->flags))
1615 iflags |= IMAP_FLAG_FORWARDED;
1616 if (MSG_IS_SPAM(*fileinfo->flags))
1617 iflags |= IMAP_FLAG_SPAM;
1618 else
1619 iflags |= IMAP_FLAG_HAM;
1620 if (!MSG_IS_UNREAD(*fileinfo->flags))
1621 iflags |= IMAP_FLAG_SEEN;
1625 if (real_file == NULL)
1626 real_file = g_strdup(fileinfo->file);
1628 if (folder_has_parent_of_type(dest, F_QUEUE) ||
1629 folder_has_parent_of_type(dest, F_OUTBOX) ||
1630 folder_has_parent_of_type(dest, F_DRAFT) ||
1631 folder_has_parent_of_type(dest, F_TRASH))
1632 iflags |= IMAP_FLAG_SEEN;
1634 ok = imap_cmd_append(session, IMAP_FOLDER_ITEM(dest), destdir, real_file, iflags,
1635 &new_uid);
1637 if (ok != MAILIMAP_NO_ERROR) {
1638 g_warning("can't append message %s\n", real_file);
1639 g_free(real_file);
1640 g_free(destdir);
1641 statusbar_progress_all(0,0,0);
1642 statusbar_pop_all();
1643 return -1;
1644 } else {
1645 debug_print("appended new message as %d\n", new_uid);
1646 /* put the local file in the imapcache, so that we don't
1647 * have to fetch it back later. */
1649 if (new_uid == 0) {
1650 missing_uids = TRUE;
1651 debug_print("Missing UID (0)\n");
1653 if (new_uid > 0) {
1654 gchar *cache_path = folder_item_get_path(dest);
1655 if (!is_dir_exist(cache_path))
1656 make_dir_hier(cache_path);
1657 if (is_dir_exist(cache_path)) {
1658 gchar *cache_file = g_strconcat(
1659 cache_path, G_DIR_SEPARATOR_S,
1660 itos(new_uid), NULL);
1661 copy_file(real_file, cache_file, TRUE);
1662 debug_print("got UID %d, copied to cache: %s\n", new_uid, cache_file);
1663 g_free(cache_file);
1665 g_free(cache_path);
1669 if (relation != NULL)
1670 g_relation_insert(relation, fileinfo->msginfo != NULL ?
1671 (gpointer) fileinfo->msginfo : (gpointer) fileinfo,
1672 GINT_TO_POINTER(new_uid));
1673 if (last_uid < new_uid) {
1674 last_uid = new_uid;
1677 g_free(real_file);
1680 statusbar_progress_all(0,0,0);
1681 statusbar_pop_all();
1684 g_free(destdir);
1686 imap_scan_required(folder, dest);
1688 session = imap_session_get(folder);
1689 if (!session) {
1690 return -1;
1692 if (missing_uids) {
1693 gint a;
1694 ok = imap_select(session, IMAP_FOLDER(folder), dest,
1695 &a, NULL, NULL, NULL, NULL, FALSE);
1697 return last_uid;
1700 static GSList *flatten_mailimap_set(struct mailimap_set * set)
1702 GSList *result = NULL;
1703 clistiter *list;
1704 int start, end, t;
1705 GSList *cur;
1707 if (!set || !set->set_list)
1708 return NULL;
1710 for (list = clist_begin(set->set_list); list; list = clist_next(list)) {
1711 struct mailimap_set_item *item = (struct mailimap_set_item *)clist_content(list);
1712 start = item->set_first;
1713 end = item->set_last;
1714 for (t = start; t <= end; t++) {
1715 result = g_slist_prepend(result, GINT_TO_POINTER(t));
1718 result = g_slist_reverse(result);
1719 if (debug_get_mode()) {
1720 debug_print("flat imap set: ");
1721 for (cur = result; cur; cur = cur->next) {
1722 debug_print("%d ", GPOINTER_TO_INT(cur->data));
1724 debug_print("\n");
1727 return result;
1729 static gint imap_do_copy_msgs(Folder *folder, FolderItem *dest,
1730 MsgInfoList *msglist, GRelation *relation)
1732 FolderItem *src;
1733 gchar *destdir;
1734 GSList *seq_list, *cur;
1735 MsgInfo *msginfo;
1736 IMAPSession *session;
1737 gint ok = MAILIMAP_NO_ERROR;
1738 GRelation *uid_mapping;
1739 gint last_num = 0;
1740 gboolean single = FALSE;
1742 g_return_val_if_fail(folder != NULL, -1);
1743 g_return_val_if_fail(dest != NULL, -1);
1744 g_return_val_if_fail(msglist != NULL, -1);
1746 debug_print("getting session...\n");
1747 session = imap_session_get(folder);
1749 if (!session) {
1750 return -1;
1753 msginfo = (MsgInfo *)msglist->data;
1754 if (msglist->next == NULL)
1755 single = TRUE;
1756 src = msginfo->folder;
1757 if (src == dest) {
1758 g_warning("the src folder is identical to the dest.\n");
1759 return -1;
1762 if (src->folder != dest->folder) {
1763 GSList *infolist = NULL, *cur;
1764 int res = -1;
1765 for (cur = msglist; cur; cur = cur->next) {
1766 msginfo = (MsgInfo *)cur->data;
1767 MsgFileInfo *fileinfo = g_new0(MsgFileInfo, 1);
1768 fileinfo->file = procmsg_get_message_file(msginfo);
1769 fileinfo->flags = &(msginfo->flags);
1770 infolist = g_slist_prepend(infolist, fileinfo);
1772 infolist = g_slist_reverse(infolist);
1773 res = folder_item_add_msgs(dest, infolist, FALSE);
1774 for (cur = infolist; cur; cur = cur->next) {
1775 MsgFileInfo *info = (MsgFileInfo *)cur->data;
1776 g_free(info->file);
1777 g_free(info);
1779 g_slist_free(infolist);
1780 return res;
1783 lock_session(session); /* unlocked later in the function */
1785 ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder,
1786 NULL, NULL, NULL, NULL, NULL, FALSE);
1787 if (ok != MAILIMAP_NO_ERROR) {
1788 return ok;
1791 unlock_session(session);
1793 destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path, &ok);
1795 if (is_fatal(ok))
1796 return ok;
1798 seq_list = imap_get_lep_set_from_msglist(IMAP_FOLDER(folder), msglist);
1799 uid_mapping = g_relation_new(2);
1800 g_relation_index(uid_mapping, 0, g_direct_hash, g_direct_equal);
1802 statusbar_print_all(_("Copying messages..."));
1803 for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
1804 struct mailimap_set * seq_set;
1805 struct mailimap_set * source = NULL;
1806 struct mailimap_set * dest = NULL;
1807 seq_set = cur->data;
1809 debug_print("Copying messages from %s to %s ...\n",
1810 src->path, destdir);
1812 lock_session(session); /* unlocked later in the function */
1813 ok = imap_cmd_copy(session, seq_set, destdir, uid_mapping,
1814 &source, &dest);
1816 if (is_fatal(ok)) {
1817 session = NULL;
1820 if (ok == MAILIMAP_NO_ERROR) {
1821 unlock_session(session);
1822 if (relation && source && dest) {
1823 GSList *s_list = flatten_mailimap_set(source);
1824 GSList *d_list = flatten_mailimap_set(dest);
1825 GSList *s_cur, *d_cur;
1826 if (g_slist_length(s_list) == g_slist_length(d_list)) {
1828 for (s_cur = s_list, d_cur = d_list;
1829 s_cur && d_cur;
1830 s_cur = s_cur->next, d_cur = d_cur->next) {
1831 g_relation_insert(uid_mapping, s_cur->data, d_cur->data);
1834 } else {
1835 debug_print("hhhmm, source list length != dest list length.\n");
1837 g_slist_free(s_list);
1838 g_slist_free(d_list);
1843 if (source)
1844 mailimap_set_free(source);
1845 if (dest)
1846 mailimap_set_free(dest);
1848 if (ok != MAILIMAP_NO_ERROR) {
1849 g_relation_destroy(uid_mapping);
1850 imap_lep_set_free(seq_list);
1851 statusbar_pop_all();
1852 return -1;
1856 for (cur = msglist; cur != NULL; cur = g_slist_next(cur)) {
1857 MsgInfo *msginfo = (MsgInfo *)cur->data;
1858 GTuples *tuples;
1860 tuples = g_relation_select(uid_mapping,
1861 GINT_TO_POINTER(msginfo->msgnum),
1863 if (tuples->len > 0) {
1864 gint num = GPOINTER_TO_INT(g_tuples_index(tuples, 0, 1));
1865 g_relation_insert(relation, msginfo,
1866 GINT_TO_POINTER(num));
1867 if (num > last_num)
1868 last_num = num;
1869 debug_print("copied message %d as %d\n", msginfo->msgnum, num);
1870 /* put the local file in the imapcache, so that we don't
1871 * have to fetch it back later. */
1872 if (num > 0) {
1873 gchar *cache_path = folder_item_get_path(msginfo->folder);
1874 gchar *real_file = g_strconcat(
1875 cache_path, G_DIR_SEPARATOR_S,
1876 itos(msginfo->msgnum), NULL);
1877 gchar *cache_file = NULL;
1878 g_free(cache_path);
1879 cache_path = folder_item_get_path(dest);
1880 cache_file = g_strconcat(
1881 cache_path, G_DIR_SEPARATOR_S,
1882 itos(num), NULL);
1883 if (!is_dir_exist(cache_path))
1884 make_dir_hier(cache_path);
1885 if (is_file_exist(real_file) && is_dir_exist(cache_path)) {
1886 copy_file(real_file, cache_file, TRUE);
1887 debug_print("copied to cache: %s\n", cache_file);
1889 g_free(real_file);
1890 g_free(cache_file);
1891 g_free(cache_path);
1893 } else
1894 g_relation_insert(relation, msginfo,
1895 GINT_TO_POINTER(0));
1896 g_tuples_destroy(tuples);
1898 statusbar_pop_all();
1900 g_relation_destroy(uid_mapping);
1901 imap_lep_set_free(seq_list);
1903 g_free(destdir);
1905 IMAP_FOLDER_ITEM(dest)->lastuid = 0;
1906 IMAP_FOLDER_ITEM(dest)->uid_next = 0;
1907 g_slist_free(IMAP_FOLDER_ITEM(dest)->uid_list);
1908 IMAP_FOLDER_ITEM(dest)->uid_list = NULL;
1910 imap_scan_required(folder, dest);
1911 if (ok == MAILIMAP_NO_ERROR)
1912 return last_num;
1913 else
1914 return -1;
1917 static gint imap_copy_msg(Folder *folder, FolderItem *dest, MsgInfo *msginfo)
1919 GSList msglist;
1921 g_return_val_if_fail(msginfo != NULL, -1);
1923 msglist.data = msginfo;
1924 msglist.next = NULL;
1926 return imap_copy_msgs(folder, dest, &msglist, NULL);
1929 static gint imap_copy_msgs(Folder *folder, FolderItem *dest,
1930 MsgInfoList *msglist, GRelation *relation)
1932 MsgInfo *msginfo;
1933 gint ret;
1935 g_return_val_if_fail(folder != NULL, -1);
1936 g_return_val_if_fail(dest != NULL, -1);
1937 g_return_val_if_fail(msglist != NULL, -1);
1939 msginfo = (MsgInfo *)msglist->data;
1940 g_return_val_if_fail(msginfo->folder != NULL, -1);
1942 ret = imap_do_copy_msgs(folder, dest, msglist, relation);
1943 return ret;
1947 static gint imap_do_remove_msgs(Folder *folder, FolderItem *dest,
1948 MsgInfoList *msglist, GRelation *relation)
1950 gchar *destdir, *dir;
1951 GSList *numlist = NULL, *cur;
1952 MsgInfo *msginfo;
1953 IMAPSession *session;
1954 gint ok = MAILIMAP_NO_ERROR;
1955 GRelation *uid_mapping;
1957 g_return_val_if_fail(folder != NULL, -1);
1958 g_return_val_if_fail(dest != NULL, -1);
1959 g_return_val_if_fail(msglist != NULL, -1);
1961 debug_print("getting session...\n");
1962 session = imap_session_get(folder);
1963 if (!session) {
1964 return -1;
1967 lock_session(session); /* unlocked later in the function */
1969 msginfo = (MsgInfo *)msglist->data;
1971 ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder,
1972 NULL, NULL, NULL, NULL, NULL, FALSE);
1973 if (ok != MAILIMAP_NO_ERROR) {
1974 return ok;
1977 destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path, &ok);
1978 if (is_fatal(ok)) {
1979 g_free(destdir);
1980 return ok;
1982 for (cur = msglist; cur; cur = cur->next) {
1983 msginfo = (MsgInfo *)cur->data;
1984 if (!MSG_IS_DELETED(msginfo->flags))
1985 numlist = g_slist_prepend(numlist, GINT_TO_POINTER(msginfo->msgnum));
1987 numlist = g_slist_reverse(numlist);
1989 uid_mapping = g_relation_new(2);
1990 g_relation_index(uid_mapping, 0, g_direct_hash, g_direct_equal);
1992 if (numlist != NULL) {
1993 ok = imap_set_message_flags
1994 (session, IMAP_FOLDER_ITEM(msginfo->folder), numlist, IMAP_FLAG_DELETED, NULL, TRUE);
1995 if (ok != MAILIMAP_NO_ERROR) {
1996 log_warning(LOG_PROTOCOL, _("can't set deleted flags\n"));
1997 g_free(destdir);
1998 return ok;
2000 } /* else we just need to expunge */
2001 ok = imap_cmd_expunge(session, folder->account->imap_use_trash);
2002 if (ok != MAILIMAP_NO_ERROR) {
2003 log_warning(LOG_PROTOCOL, _("can't expunge\n"));
2004 g_free(destdir);
2005 return ok;
2008 session->folder_content_changed = TRUE;
2009 unlock_session(session);
2011 dir = folder_item_get_path(msginfo->folder);
2012 if (is_dir_exist(dir)) {
2013 for (cur = msglist; cur; cur = cur->next) {
2014 msginfo = (MsgInfo *)cur->data;
2015 remove_numbered_files(dir, msginfo->msgnum, msginfo->msgnum);
2018 g_free(dir);
2020 g_relation_destroy(uid_mapping);
2021 g_slist_free(numlist);
2023 imap_scan_required(folder, dest);
2025 g_free(destdir);
2026 if (ok == MAILIMAP_NO_ERROR)
2027 return 0;
2028 else
2029 return -1;
2032 static gint imap_remove_msgs(Folder *folder, FolderItem *dest,
2033 MsgInfoList *msglist, GRelation *relation)
2035 MsgInfo *msginfo;
2037 g_return_val_if_fail(folder != NULL, -1);
2038 g_return_val_if_fail(dest != NULL, -1);
2039 if (msglist == NULL)
2040 return 0;
2042 msginfo = (MsgInfo *)msglist->data;
2043 g_return_val_if_fail(msginfo->folder != NULL, -1);
2045 return imap_do_remove_msgs(folder, dest, msglist, relation);
2048 static gint imap_remove_all_msg(Folder *folder, FolderItem *item)
2050 GSList *list = folder_item_get_msg_list(item);
2051 gint res = imap_remove_msgs(folder, item, list, NULL);
2052 procmsg_msg_list_free(list);
2053 return res;
2056 static gboolean imap_is_msg_changed(Folder *folder, FolderItem *item,
2057 MsgInfo *msginfo)
2059 /* TODO: properly implement this method */
2060 return FALSE;
2063 static gint imap_close(Folder *folder, FolderItem *item)
2065 return 0;
2068 static gint imap_scan_tree_real(Folder *folder, gboolean subs_only)
2070 FolderItem *item = NULL;
2071 IMAPSession *session;
2072 gchar *root_folder = NULL;
2074 g_return_val_if_fail(folder != NULL, -1);
2075 g_return_val_if_fail(folder->account != NULL, -1);
2077 debug_print("getting session...\n");
2078 session = imap_session_get(folder);
2079 if (!session) {
2080 if (!folder->node) {
2081 folder_tree_destroy(folder);
2082 item = folder_item_new(folder, folder->name, NULL);
2083 item->folder = folder;
2084 folder->node = item->node = g_node_new(item);
2086 return -1;
2089 if (folder->account->imap_dir && *folder->account->imap_dir) {
2090 gchar *real_path;
2091 int r = MAILIMAP_NO_ERROR;
2092 clist * lep_list;
2094 Xstrdup_a(root_folder, folder->account->imap_dir, {return -1;});
2095 extract_quote(root_folder, '"');
2096 subst_char(root_folder,
2097 imap_get_path_separator(session, IMAP_FOLDER(folder),
2098 root_folder, &r),
2099 '/');
2100 if (is_fatal(r))
2101 return -1;
2102 strtailchomp(root_folder, '/');
2103 real_path = imap_get_real_path
2104 (session, IMAP_FOLDER(folder), root_folder, &r);
2105 if (is_fatal(r))
2106 return -1;
2107 debug_print("IMAP root directory: %s\n", real_path);
2109 /* check if root directory exist */
2111 r = imap_threaded_list(session->folder, "", real_path,
2112 &lep_list);
2114 if (r != MAILIMAP_NO_ERROR)
2115 imap_handle_error(SESSION(session), r);
2117 if ((r != MAILIMAP_NO_ERROR) || (clist_count(lep_list) == 0)) {
2118 if (!folder->node) {
2119 item = folder_item_new(folder, folder->name, NULL);
2120 item->folder = folder;
2121 folder->node = item->node = g_node_new(item);
2123 return -1;
2125 mailimap_list_result_free(lep_list);
2127 g_free(real_path);
2130 if (folder->node)
2131 item = FOLDER_ITEM(folder->node->data);
2133 if (item && !item->path && root_folder) {
2134 item->path = g_strdup(root_folder);
2137 if (!item || ((item->path || root_folder) &&
2138 strcmp2(item->path, root_folder) != 0)) {
2139 folder_tree_destroy(folder);
2140 item = folder_item_new(folder, folder->name, root_folder);
2141 item->folder = folder;
2142 folder->node = item->node = g_node_new(item);
2145 imap_scan_tree_recursive(session, FOLDER_ITEM(folder->node->data), subs_only);
2146 imap_create_missing_folders(folder);
2148 return 0;
2151 static gint imap_scan_tree(Folder *folder)
2153 gboolean subs_only = FALSE;
2154 if (folder->account) {
2155 debug_print(" scanning only subs %d\n", folder->account->imap_subsonly);
2156 subs_only = folder->account->imap_subsonly;
2158 return imap_scan_tree_real(folder, subs_only);
2161 static gint imap_scan_tree_recursive(IMAPSession *session, FolderItem *item, gboolean subs_only)
2163 Folder *folder;
2164 IMAPFolder *imapfolder;
2165 FolderItem *new_item;
2166 GSList *item_list, *cur;
2167 GNode *node;
2168 gchar *real_path;
2169 gchar *wildcard_path;
2170 gchar separator;
2171 gchar wildcard[3];
2172 clist * lep_list;
2173 int r = MAILIMAP_NO_ERROR;
2175 g_return_val_if_fail(item != NULL, -1);
2176 g_return_val_if_fail(item->folder != NULL, -1);
2177 g_return_val_if_fail(item->no_sub == FALSE, -1);
2179 folder = item->folder;
2180 imapfolder = IMAP_FOLDER(folder);
2182 separator = imap_get_path_separator(session, imapfolder, item->path, &r);
2183 if (is_fatal(r))
2184 return r;
2186 if (folder->ui_func)
2187 folder->ui_func(folder, item, folder->ui_func_data);
2189 if (item->path) {
2190 wildcard[0] = separator;
2191 wildcard[1] = '%';
2192 wildcard[2] = '\0';
2193 real_path = imap_get_real_path(session, imapfolder, item->path, &r);
2194 if (is_fatal(r)) {
2195 g_free(real_path);
2196 return r;
2198 } else {
2199 wildcard[0] = '%';
2200 wildcard[1] = '\0';
2201 real_path = g_strdup("");
2204 Xstrcat_a(wildcard_path, real_path, wildcard,
2205 {g_free(real_path); return MAILIMAP_ERROR_BAD_STATE;});
2206 lep_list = NULL;
2208 if (subs_only)
2209 r = imap_threaded_lsub(folder, "", wildcard_path, &lep_list);
2210 else
2211 r = imap_threaded_list(folder, "", wildcard_path, &lep_list);
2213 if (r != MAILIMAP_NO_ERROR) {
2214 imap_handle_error(SESSION(session), r);
2215 item_list = NULL;
2216 g_free(real_path);
2217 return r;
2219 else {
2220 item_list = imap_list_from_lep(imapfolder,
2221 lep_list, real_path, FALSE);
2222 mailimap_list_result_free(lep_list);
2225 g_free(real_path);
2227 node = item->node->children;
2228 while (node != NULL) {
2229 FolderItem *old_item = FOLDER_ITEM(node->data);
2230 GNode *next = node->next;
2232 new_item = NULL;
2233 for (cur = item_list; cur != NULL; cur = cur->next) {
2234 FolderItem *cur_item = FOLDER_ITEM(cur->data);
2235 if (!strcmp2(old_item->path, cur_item->path)) {
2236 new_item = cur_item;
2237 break;
2240 if (!new_item) {
2241 if (old_item && old_item->path && !strcmp(old_item->path, "INBOX")) {
2242 debug_print("not removing INBOX\n");
2243 } else {
2244 debug_print("folder '%s' not found. removing...\n",
2245 old_item->path);
2246 folder_item_remove(old_item);
2248 } else {
2249 old_item->no_sub = new_item->no_sub;
2250 old_item->no_select = new_item->no_select;
2251 if (old_item->no_sub == TRUE && node->children) {
2252 debug_print("folder '%s' doesn't have "
2253 "subfolders. removing...\n",
2254 old_item->path);
2255 folder_item_remove_children(old_item);
2259 node = next;
2262 for (cur = item_list; cur != NULL; cur = cur->next) {
2263 FolderItem *cur_item = FOLDER_ITEM(cur->data);
2264 new_item = NULL;
2266 for (node = item->node->children; node != NULL;
2267 node = node->next) {
2268 if (!strcmp2(FOLDER_ITEM(node->data)->path,
2269 cur_item->path)) {
2270 new_item = FOLDER_ITEM(node->data);
2271 folder_item_destroy(cur_item);
2272 cur_item = NULL;
2273 break;
2276 if (!new_item) {
2277 new_item = cur_item;
2278 debug_print("new folder '%s' found.\n", new_item->path);
2279 folder_item_append(item, new_item);
2282 if (!strcmp(new_item->path, "INBOX")) {
2283 new_item->stype = F_INBOX;
2284 folder->inbox = new_item;
2285 } else if (!folder_item_parent(item) || item->stype == F_INBOX) {
2286 gchar *base;
2288 base = g_path_get_basename(new_item->path);
2290 if (!folder->outbox && !g_ascii_strcasecmp(base, "Sent")) {
2291 new_item->stype = F_OUTBOX;
2292 folder->outbox = new_item;
2293 } else if (!folder->draft && !g_ascii_strcasecmp(base, "Drafts")) {
2294 new_item->stype = F_DRAFT;
2295 folder->draft = new_item;
2296 } else if (!folder->queue && !g_ascii_strcasecmp(base, "Queue")) {
2297 new_item->stype = F_QUEUE;
2298 folder->queue = new_item;
2299 } else if (!folder->trash && !g_ascii_strcasecmp(base, "Trash")) {
2300 new_item->stype = F_TRASH;
2301 folder->trash = new_item;
2303 g_free(base);
2306 if (new_item->no_sub == FALSE)
2307 imap_scan_tree_recursive(session, new_item, subs_only);
2310 g_slist_free(item_list);
2312 return MAILIMAP_NO_ERROR;
2315 GList *imap_scan_subtree(Folder *folder, FolderItem *item, gboolean unsubs_only, gboolean recursive)
2317 IMAPSession *session = imap_session_get(folder);
2318 gchar *real_path;
2319 gchar *wildcard_path;
2320 gchar separator;
2321 gchar wildcard[3];
2322 clist * lep_list;
2323 GSList *item_list = NULL, *cur;
2324 GList *child_list = NULL, *tmplist = NULL;
2325 GSList *sub_list = NULL;
2326 int r = MAILIMAP_NO_ERROR;
2328 if (!session)
2329 return NULL;
2331 separator = imap_get_path_separator(session, IMAP_FOLDER(folder), item->path, &r);
2332 if (is_fatal(r))
2333 return NULL;
2335 if (item->path) {
2336 wildcard[0] = separator;
2337 wildcard[1] = '%';
2338 wildcard[2] = '\0';
2339 real_path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path, &r);
2340 if (is_fatal(r)) {
2341 g_free(real_path);
2342 return NULL;
2344 } else {
2345 wildcard[0] = '%';
2346 wildcard[1] = '\0';
2347 real_path = g_strdup("");
2350 Xstrcat_a(wildcard_path, real_path, wildcard,
2351 {g_free(real_path); return NULL;});
2352 lep_list = NULL;
2354 if (unsubs_only)
2355 statusbar_print_all(_("Looking for unsubscribed folders in %s..."),
2356 item->path?item->path:item->name);
2357 else
2358 statusbar_print_all(_("Looking for subfolders of %s..."),
2359 item->path?item->path:item->name);
2361 r = imap_threaded_list(folder, "", wildcard_path, &lep_list);
2362 if (r) {
2363 g_free(real_path);
2364 statusbar_pop_all();
2365 return NULL;
2367 item_list = imap_list_from_lep(IMAP_FOLDER(folder),
2368 lep_list, real_path, FALSE);
2369 mailimap_list_result_free(lep_list);
2371 for (cur = item_list; cur != NULL; cur = cur->next) {
2372 FolderItem *cur_item = FOLDER_ITEM(cur->data);
2373 if (recursive) {
2374 tmplist = imap_scan_subtree(folder, cur_item,
2375 unsubs_only, recursive);
2376 if (tmplist)
2377 child_list = g_list_concat(child_list, tmplist);
2379 child_list = g_list_prepend(child_list,
2380 imap_get_real_path(session,
2381 IMAP_FOLDER(folder), cur_item->path, &r));
2382 if (is_fatal(r)) {
2383 g_free(real_path);
2384 statusbar_pop_all();
2385 return NULL;
2387 folder_item_destroy(cur_item);
2389 child_list = g_list_reverse(child_list);
2390 g_slist_free(item_list);
2392 if (unsubs_only) {
2393 r = imap_threaded_lsub(folder, "", wildcard_path, &lep_list);
2394 if (r) {
2395 g_free(real_path);
2396 statusbar_pop_all();
2397 return NULL;
2399 sub_list = imap_list_from_lep(IMAP_FOLDER(folder),
2400 lep_list, real_path, FALSE);
2401 mailimap_list_result_free(lep_list);
2403 for (cur = sub_list; cur != NULL; cur = cur->next) {
2404 FolderItem *cur_item = FOLDER_ITEM(cur->data);
2405 GList *oldlitem = NULL;
2406 gchar *tmp = imap_get_real_path(session,
2407 IMAP_FOLDER(folder), cur_item->path, &r);
2408 if (r) {
2409 g_free(real_path);
2410 statusbar_pop_all();
2411 return NULL;
2413 folder_item_destroy(cur_item);
2414 oldlitem = g_list_find_custom(
2415 child_list, tmp, (GCompareFunc)strcmp2);
2416 if (oldlitem) {
2417 child_list = g_list_remove_link(child_list, oldlitem);
2418 g_free(oldlitem->data);
2419 g_list_free(oldlitem);
2421 g_free(tmp);
2425 g_free(real_path);
2426 statusbar_pop_all();
2428 return child_list;
2431 static gint imap_create_tree(Folder *folder)
2433 g_return_val_if_fail(folder != NULL, -1);
2434 g_return_val_if_fail(folder->node != NULL, -1);
2435 g_return_val_if_fail(folder->node->data != NULL, -1);
2436 g_return_val_if_fail(folder->account != NULL, -1);
2438 imap_scan_tree(folder);
2439 imap_create_missing_folders(folder);
2441 return 0;
2444 static void imap_create_missing_folders(Folder *folder)
2446 g_return_if_fail(folder != NULL);
2448 if (!folder->inbox)
2449 folder->inbox = imap_create_special_folder
2450 (folder, F_INBOX, "INBOX");
2451 if (!folder->trash)
2452 folder->trash = imap_create_special_folder
2453 (folder, F_TRASH, "Trash");
2454 if (!folder->queue)
2455 folder->queue = imap_create_special_folder
2456 (folder, F_QUEUE, "Queue");
2457 if (!folder->outbox)
2458 folder->outbox = imap_create_special_folder
2459 (folder, F_OUTBOX, "Sent");
2460 if (!folder->draft)
2461 folder->draft = imap_create_special_folder
2462 (folder, F_DRAFT, "Drafts");
2465 static FolderItem *imap_create_special_folder(Folder *folder,
2466 SpecialFolderItemType stype,
2467 const gchar *name)
2469 FolderItem *item;
2470 FolderItem *new_item;
2472 g_return_val_if_fail(folder != NULL, NULL);
2473 g_return_val_if_fail(folder->node != NULL, NULL);
2474 g_return_val_if_fail(folder->node->data != NULL, NULL);
2475 g_return_val_if_fail(folder->account != NULL, NULL);
2476 g_return_val_if_fail(name != NULL, NULL);
2478 item = FOLDER_ITEM(folder->node->data);
2479 new_item = imap_create_folder(folder, item, name);
2481 if (!new_item) {
2482 g_warning("Can't create '%s'\n", name);
2483 if (!folder->inbox) return NULL;
2485 new_item = imap_create_folder(folder, folder->inbox, name);
2486 if (!new_item)
2487 g_warning("Can't create '%s' under INBOX\n", name);
2488 else
2489 new_item->stype = stype;
2490 } else
2491 new_item->stype = stype;
2493 return new_item;
2496 static gchar *imap_folder_get_path(Folder *folder)
2498 gchar *folder_path;
2500 g_return_val_if_fail(folder != NULL, NULL);
2501 g_return_val_if_fail(folder->account != NULL, NULL);
2503 folder_path = g_strconcat(get_imap_cache_dir(),
2504 G_DIR_SEPARATOR_S,
2505 folder->account->recv_server,
2506 G_DIR_SEPARATOR_S,
2507 folder->account->userid,
2508 NULL);
2510 return folder_path;
2513 #ifdef G_OS_WIN32
2514 static gchar *imap_encode_unsafe_chars(const gchar *str)
2516 gchar *ret = NULL, *o_ret;
2517 gchar *i;
2518 if (!str)
2519 return NULL;
2520 ret = g_malloc(3*strlen(str)+1);
2521 o_ret = ret;
2522 for (i = str; *i; i++) {
2523 switch(*i) {
2524 case ':':
2525 case '|':
2526 case '<':
2527 case '>':
2528 case '*':
2529 case '?':
2530 case '#':
2531 *ret++ = '%';
2532 *ret++ = '0'+(*i/10);
2533 *ret++ = '0'+(*i%10);
2534 break;
2535 default:
2536 *ret++ = *i;
2539 *ret++ = '\0';
2540 return o_ret;
2542 #endif
2543 static gchar *imap_item_get_path(Folder *folder, FolderItem *item)
2545 gchar *folder_path, *path;
2546 gchar *item_path = NULL;
2548 g_return_val_if_fail(folder != NULL, NULL);
2549 g_return_val_if_fail(item != NULL, NULL);
2550 folder_path = imap_folder_get_path(folder);
2552 g_return_val_if_fail(folder_path != NULL, NULL);
2554 #ifdef G_OS_UNIX
2555 item_path = g_strdup(item->path);
2556 #else
2557 item_path = imap_encode_unsafe_chars(item->path);
2558 #endif
2560 if (g_path_is_absolute(folder_path)) {
2561 if (item_path)
2562 path = g_strconcat(folder_path, G_DIR_SEPARATOR_S,
2563 item_path, NULL);
2564 else
2565 path = g_strdup(folder_path);
2566 } else {
2567 if (item_path)
2568 path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
2569 folder_path, G_DIR_SEPARATOR_S,
2570 item_path, NULL);
2571 else
2572 path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
2573 folder_path, NULL);
2575 g_free(folder_path);
2576 g_free(item_path);
2577 #ifdef G_OS_WIN32
2578 while (strchr(path, '/'))
2579 *strchr(path, '/') = '\\';
2580 #endif
2582 return path;
2585 static FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
2586 const gchar *name)
2588 gchar *dirpath, *imap_path;
2589 IMAPSession *session;
2590 FolderItem *new_item;
2591 gchar separator;
2592 gchar *new_name;
2593 const gchar *p;
2594 gint ok = MAILIMAP_NO_ERROR;
2595 gboolean no_select = FALSE, no_sub = FALSE;
2596 gboolean exist = FALSE;
2598 g_return_val_if_fail(folder != NULL, NULL);
2599 g_return_val_if_fail(folder->account != NULL, NULL);
2600 g_return_val_if_fail(parent != NULL, NULL);
2601 g_return_val_if_fail(name != NULL, NULL);
2603 debug_print("getting session...\n");
2604 session = imap_session_get(folder);
2605 if (!session) {
2606 return NULL;
2609 if (!folder_item_parent(parent) && strcmp(name, "INBOX") == 0) {
2610 dirpath = g_strdup(name);
2611 }else if (parent->path)
2612 dirpath = g_strconcat(parent->path, "/", name, NULL);
2613 else if ((p = strchr(name, '/')) != NULL && *(p + 1) != '\0')
2614 dirpath = g_strdup(name);
2615 else if (folder->account->imap_dir && *folder->account->imap_dir) {
2616 gchar *imap_dir;
2618 Xstrdup_a(imap_dir, folder->account->imap_dir, {return NULL;});
2619 strtailchomp(imap_dir, '/');
2620 dirpath = g_strconcat(imap_dir, "/", name, NULL);
2621 } else
2622 dirpath = g_strdup(name);
2626 /* keep trailing directory separator to create a folder that contains
2627 sub folder */
2628 imap_path = imap_utf8_to_modified_utf7(dirpath, FALSE);
2630 strtailchomp(dirpath, '/');
2631 Xstrdup_a(new_name, name, {
2632 g_free(dirpath);
2633 g_free(imap_path);
2634 return NULL;});
2636 separator = imap_get_path_separator(session, IMAP_FOLDER(folder), imap_path, &ok);
2637 if (is_fatal(ok)) {
2638 g_free(imap_path);
2639 return NULL;
2641 imap_path_separator_subst(imap_path, separator);
2642 /* remove trailing / for display */
2643 strtailchomp(new_name, '/');
2645 if (strcmp(dirpath, "INBOX") != 0) {
2646 GPtrArray *argbuf;
2647 int r;
2648 clist * lep_list;
2650 argbuf = g_ptr_array_new();
2651 r = imap_threaded_list(folder, "", imap_path, &lep_list);
2652 if (r != MAILIMAP_NO_ERROR) {
2653 imap_handle_error(SESSION(session), r);
2654 log_warning(LOG_PROTOCOL, _("can't create mailbox: LIST failed\n"));
2655 g_free(imap_path);
2656 g_free(dirpath);
2657 ptr_array_free_strings(argbuf);
2658 g_ptr_array_free(argbuf, TRUE);
2659 return NULL;
2662 if (clist_count(lep_list) > 0)
2663 exist = TRUE;
2664 mailimap_list_result_free(lep_list);
2665 lep_list = NULL;
2666 if (!exist) {
2667 ok = imap_cmd_create(session, imap_path);
2668 if (ok != MAILIMAP_NO_ERROR) {
2669 log_warning(LOG_PROTOCOL, _("can't create mailbox\n"));
2670 g_free(imap_path);
2671 g_free(dirpath);
2672 return NULL;
2674 r = imap_threaded_list(folder, "", imap_path, &lep_list);
2675 if (r == MAILIMAP_NO_ERROR) {
2676 GSList *item_list = imap_list_from_lep(IMAP_FOLDER(folder),
2677 lep_list, dirpath, TRUE);
2678 if (item_list) {
2679 FolderItem *cur_item = FOLDER_ITEM(item_list->data);
2680 no_select = cur_item->no_select;
2681 no_sub = cur_item->no_sub;
2682 g_slist_free(item_list);
2684 mailimap_list_result_free(lep_list);
2685 } else {
2686 imap_handle_error(SESSION(session), r);
2689 imap_threaded_subscribe(folder, imap_path, TRUE);
2690 } else {
2691 clist *lep_list;
2692 int r;
2693 /* just get flags */
2694 r = imap_threaded_list(folder, "", "INBOX", &lep_list);
2695 if (r == MAILIMAP_NO_ERROR) {
2696 GSList *item_list = imap_list_from_lep(IMAP_FOLDER(folder),
2697 lep_list, dirpath, TRUE);
2698 if (item_list) {
2699 FolderItem *cur_item = FOLDER_ITEM(item_list->data);
2700 no_select = cur_item->no_select;
2701 no_sub = cur_item->no_sub;
2702 g_slist_free(item_list);
2704 mailimap_list_result_free(lep_list);
2705 } else {
2706 imap_handle_error(SESSION(session), r);
2710 new_item = folder_item_new(folder, new_name, dirpath);
2711 new_item->no_select = no_select;
2712 new_item->no_sub = no_sub;
2713 folder_item_append(parent, new_item);
2714 g_free(imap_path);
2715 g_free(dirpath);
2717 dirpath = folder_item_get_path(new_item);
2718 if (!is_dir_exist(dirpath))
2719 make_dir_hier(dirpath);
2720 g_free(dirpath);
2722 if (exist) {
2723 /* folder existed, scan it */
2724 imap_scan_required(folder, new_item);
2725 folder_item_scan_full(new_item, FALSE);
2728 return new_item;
2731 static gint imap_rename_folder(Folder *folder, FolderItem *item,
2732 const gchar *name)
2734 gchar *dirpath;
2735 gchar *newpath;
2736 gchar *real_oldpath;
2737 gchar *real_newpath;
2738 gchar *paths[2];
2739 gchar *old_cache_dir;
2740 gchar *new_cache_dir;
2741 IMAPSession *session;
2742 gchar separator;
2743 gint ok = MAILIMAP_NO_ERROR;
2744 gint exists, recent, unseen;
2745 guint32 uid_validity;
2747 g_return_val_if_fail(folder != NULL, -1);
2748 g_return_val_if_fail(item != NULL, -1);
2749 g_return_val_if_fail(item->path != NULL, -1);
2750 g_return_val_if_fail(name != NULL, -1);
2752 debug_print("getting session...\n");
2753 session = imap_session_get(folder);
2754 if (!session) {
2755 return -1;
2758 if (strchr(name, imap_get_path_separator(session, IMAP_FOLDER(folder), item->path, &ok)) != NULL ||
2759 is_fatal(ok)) {
2760 g_warning(_("New folder name must not contain the namespace "
2761 "path separator"));
2762 return -1;
2765 real_oldpath = imap_get_real_path(session, IMAP_FOLDER(folder), item->path, &ok);
2766 if (is_fatal(ok)) {
2767 return -1;
2770 g_free(session->mbox);
2771 session->mbox = NULL;
2772 session->exists = 0;
2773 session->recent = 0;
2774 session->expunge = 0;
2775 ok = imap_cmd_examine(session, "INBOX",
2776 &exists, &recent, &unseen, &uid_validity, FALSE);
2777 if (ok != MAILIMAP_NO_ERROR) {
2778 g_free(real_oldpath);
2779 return -1;
2782 separator = imap_get_path_separator(session, IMAP_FOLDER(folder), item->path, &ok);
2783 if (is_fatal(ok))
2784 return -1;
2785 if (strchr(item->path, G_DIR_SEPARATOR)) {
2786 dirpath = g_path_get_dirname(item->path);
2787 newpath = g_strconcat(dirpath, G_DIR_SEPARATOR_S, name, NULL);
2788 g_free(dirpath);
2789 } else
2790 newpath = g_strdup(name);
2792 real_newpath = imap_utf8_to_modified_utf7(newpath, FALSE);
2793 imap_path_separator_subst(real_newpath, separator);
2795 ok = imap_cmd_rename(session, real_oldpath, real_newpath);
2796 if (ok != MAILIMAP_NO_ERROR) {
2797 log_warning(LOG_PROTOCOL, _("can't rename mailbox: %s to %s\n"),
2798 real_oldpath, real_newpath);
2799 g_free(real_oldpath);
2800 g_free(newpath);
2801 g_free(real_newpath);
2802 return -1;
2804 g_free(item->name);
2805 item->name = g_strdup(name);
2807 old_cache_dir = folder_item_get_path(item);
2809 paths[0] = g_strdup(item->path);
2810 paths[1] = newpath;
2811 g_node_traverse(item->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1,
2812 imap_rename_folder_func, paths);
2814 if (is_dir_exist(old_cache_dir)) {
2815 new_cache_dir = folder_item_get_path(item);
2816 if (g_rename(old_cache_dir, new_cache_dir) < 0) {
2817 FILE_OP_ERROR(old_cache_dir, "rename");
2819 g_free(new_cache_dir);
2822 g_free(old_cache_dir);
2823 g_free(paths[0]);
2824 g_free(newpath);
2825 g_free(real_oldpath);
2826 g_free(real_newpath);
2827 return 0;
2830 gint imap_subscribe(Folder *folder, FolderItem *item, gchar *rpath, gboolean sub)
2832 gchar *path;
2833 gint r = MAILIMAP_NO_ERROR;
2834 IMAPSession *session;
2835 debug_print("getting session...\n");
2837 session = imap_session_get(folder);
2838 if (!session) {
2839 return -1;
2841 if (item && item->path) {
2842 path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path, &r);
2843 if (!path)
2844 return -1;
2845 if (is_fatal(r)) {
2846 g_free(path);
2847 return -1;
2849 if (!strcmp(path, "INBOX") && sub == FALSE) {
2850 g_free(path);
2851 return -1;
2853 debug_print("%ssubscribing %s\n", sub?"":"un", path);
2854 r = imap_threaded_subscribe(folder, path, sub);
2855 g_free(path);
2856 } else if (rpath) {
2857 r = imap_threaded_subscribe(folder, rpath, sub);
2858 } else
2859 return -1;
2860 return r;
2863 static gint imap_remove_folder_real(Folder *folder, FolderItem *item)
2865 gint ok = MAILIMAP_NO_ERROR;
2866 IMAPSession *session;
2867 gchar *path;
2868 gchar *cache_dir;
2869 gboolean selected_folder;
2871 g_return_val_if_fail(folder != NULL, -1);
2872 g_return_val_if_fail(item != NULL, -1);
2873 g_return_val_if_fail(item->path != NULL, -1);
2875 debug_print("getting session...\n");
2876 session = imap_session_get(folder);
2877 if (!session) {
2878 return -1;
2880 path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path, &ok);
2881 if (is_fatal(ok))
2882 return -1;
2884 imap_threaded_subscribe(folder, path, FALSE);
2886 selected_folder = (session->mbox != NULL) &&
2887 (!strcmp(session->mbox, item->path));
2888 if (selected_folder) {
2889 ok = imap_cmd_close(session);
2890 if (ok != MAILIMAP_NO_ERROR) {
2891 debug_print("close err %d\n", ok);
2892 return ok;
2895 ok = imap_cmd_delete(session, path);
2896 if (ok != MAILIMAP_NO_ERROR && !is_fatal(ok)) {
2897 gchar *tmp = NULL;
2899 ok = MAILIMAP_NO_ERROR;
2900 tmp = g_strdup_printf("%s%c", path,
2901 imap_get_path_separator(session, IMAP_FOLDER(folder), path, &ok));
2902 g_free(path);
2903 path = tmp;
2904 if (!is_fatal(ok))
2905 ok = imap_cmd_delete(session, path);
2908 if (ok != MAILIMAP_NO_ERROR) {
2909 log_warning(LOG_PROTOCOL, _("can't delete mailbox\n"));
2910 g_free(path);
2911 return -1;
2914 g_free(path);
2915 cache_dir = folder_item_get_path(item);
2916 if (is_dir_exist(cache_dir) && remove_dir_recursive(cache_dir) < 0)
2917 g_warning("can't remove directory '%s'\n", cache_dir);
2918 g_free(cache_dir);
2919 folder_item_remove(item);
2920 return 0;
2923 static gint imap_remove_folder(Folder *folder, FolderItem *item)
2925 GNode *node, *next;
2927 g_return_val_if_fail(item != NULL, -1);
2928 g_return_val_if_fail(item->folder != NULL, -1);
2929 g_return_val_if_fail(item->node != NULL, -1);
2931 node = item->node->children;
2932 while (node != NULL) {
2933 next = node->next;
2934 if (imap_remove_folder(folder, FOLDER_ITEM(node->data)) < 0)
2935 return -1;
2936 node = next;
2938 debug_print("IMAP removing %s\n", item->path);
2940 if (imap_remove_all_msg(folder, item) < 0)
2941 return -1;
2942 return imap_remove_folder_real(folder, item);
2945 typedef struct _uncached_data {
2946 IMAPSession *session;
2947 FolderItem *item;
2948 MsgNumberList *numlist;
2949 guint cur;
2950 guint total;
2951 gboolean done;
2952 int ok;
2953 } uncached_data;
2955 static void *imap_get_uncached_messages_thread(void *data)
2957 uncached_data *stuff = (uncached_data *)data;
2958 IMAPSession *session = stuff->session;
2959 FolderItem *item = stuff->item;
2960 MsgNumberList *numlist = stuff->numlist;
2961 GSList *newlist = NULL;
2962 GSList *llast = NULL;
2963 GSList *seq_list, *cur;
2964 gboolean got_alien_tags = FALSE;
2966 debug_print("uncached_messages\n");
2968 if (session == NULL || item == NULL || item->folder == NULL
2969 || FOLDER_CLASS(item->folder) != &imap_class) {
2970 stuff->done = TRUE;
2971 return NULL;
2974 seq_list = imap_get_lep_set_from_numlist(IMAP_FOLDER(item->folder), numlist);
2975 debug_print("get msgs info\n");
2976 for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
2977 struct mailimap_set * imapset;
2978 unsigned int i;
2979 int r;
2980 carray * env_list;
2981 int count;
2983 if (session->cancelled)
2984 break;
2986 imapset = cur->data;
2988 r = imap_threaded_fetch_env(session->folder,
2989 imapset, &env_list);
2990 if (r != MAILIMAP_NO_ERROR) {
2991 imap_handle_error(SESSION(session), r);
2992 if (is_fatal(r)) {
2993 stuff->ok = r;
2994 return NULL;
2996 continue;
2999 session_set_access_time(SESSION(session));
3001 count = 0;
3002 for(i = 0 ; i < carray_count(env_list) ; i += 2) {
3003 struct imap_fetch_env_info * info;
3004 MsgInfo * msginfo;
3005 GSList *tags = NULL, *cur = NULL;
3006 info = carray_get(env_list, i);
3007 tags = carray_get(env_list, i+1);
3008 msginfo = imap_envelope_from_lep(info, item);
3009 if (msginfo == NULL) {
3010 slist_free_strings(tags);
3011 g_slist_free(tags);
3012 continue;
3014 g_slist_free(msginfo->tags);
3015 msginfo->tags = NULL;
3017 for (cur = tags; cur; cur = cur->next) {
3018 gchar *real_tag = imap_modified_utf7_to_utf8(cur->data, TRUE);
3019 gint id = 0;
3020 id = tags_get_id_for_str(real_tag);
3021 if (id == -1) {
3022 id = tags_add_tag(real_tag);
3023 got_alien_tags = TRUE;
3025 if (!g_slist_find(msginfo->tags, GINT_TO_POINTER(id))) {
3026 msginfo->tags = g_slist_prepend(
3027 msginfo->tags,
3028 GINT_TO_POINTER(id));
3030 g_free(real_tag);
3032 if (msginfo->tags)
3033 msginfo->tags = g_slist_reverse(msginfo->tags);
3034 slist_free_strings(tags);
3035 g_slist_free(tags);
3036 msginfo->folder = item;
3037 if (!newlist)
3038 llast = newlist = g_slist_append(newlist, msginfo);
3039 else {
3040 llast = g_slist_append(llast, msginfo);
3041 llast = llast->next;
3043 count ++;
3046 imap_fetch_env_free(env_list);
3049 if (got_alien_tags) {
3050 tags_write_tags();
3051 main_window_reflect_tags_changes(mainwindow_get_mainwindow());
3054 for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
3055 struct mailimap_set * imapset;
3057 imapset = cur->data;
3058 mailimap_set_free(imapset);
3061 session_set_access_time(SESSION(session));
3062 stuff->done = TRUE;
3063 return newlist;
3066 #define MAX_MSG_NUM 50
3068 static GSList *imap_get_uncached_messages(IMAPSession *session,
3069 FolderItem *item,
3070 MsgNumberList *numlist,
3071 int *r)
3073 GSList *result = NULL;
3074 GSList * cur;
3075 uncached_data *data = g_new0(uncached_data, 1);
3076 int finished;
3078 finished = 0;
3079 cur = numlist;
3080 data->total = g_slist_length(numlist);
3081 data->ok = MAILIMAP_NO_ERROR;
3082 debug_print("messages list : %i\n", data->total);
3084 while (cur != NULL) {
3085 GSList * partial_result;
3086 int count;
3087 GSList * newlist;
3088 GSList * llast;
3090 llast = NULL;
3091 count = 0;
3092 newlist = NULL;
3093 while (count < MAX_MSG_NUM) {
3094 void * p;
3096 p = cur->data;
3098 if (newlist == NULL)
3099 llast = newlist = g_slist_append(newlist, p);
3100 else {
3101 llast = g_slist_append(llast, p);
3102 llast = llast->next;
3104 count ++;
3106 cur = cur->next;
3107 if (cur == NULL)
3108 break;
3111 data->done = FALSE;
3112 data->session = session;
3113 data->item = item;
3114 data->numlist = newlist;
3115 data->cur += count;
3117 if (prefs_common.work_offline &&
3118 !inc_offline_should_override(FALSE,
3119 _("Claws Mail needs network access in order "
3120 "to access the IMAP server."))) {
3121 g_free(data);
3122 return NULL;
3125 partial_result =
3126 (GSList *)imap_get_uncached_messages_thread(data);
3127 *r = data->ok;
3128 if (data->ok != MAILIMAP_NO_ERROR) {
3129 goto bail;
3131 statusbar_progress_all(data->cur,data->total, 1);
3133 g_slist_free(newlist);
3135 result = g_slist_concat(result, partial_result);
3137 bail:
3138 g_free(data);
3140 statusbar_progress_all(0,0,0);
3141 statusbar_pop_all();
3143 return result;
3146 static void imap_delete_all_cached_messages(FolderItem *item)
3148 gchar *dir;
3150 g_return_if_fail(item != NULL);
3151 g_return_if_fail(item->folder != NULL);
3152 g_return_if_fail(FOLDER_CLASS(item->folder) == &imap_class);
3154 debug_print("Deleting all cached messages...\n");
3156 dir = folder_item_get_path(item);
3157 if (is_dir_exist(dir))
3158 remove_all_numbered_files(dir);
3159 g_free(dir);
3161 debug_print("done.\n");
3164 gchar imap_get_path_separator_for_item(FolderItem *item)
3166 Folder *folder = NULL;
3167 IMAPFolder *imap_folder = NULL;
3168 IMAPSession *session = NULL;
3169 gchar result = '/';
3170 gint ok = MAILIMAP_NO_ERROR;
3171 if (!item)
3172 return '/';
3173 folder = item->folder;
3175 if (!folder)
3176 return '/';
3178 imap_folder = IMAP_FOLDER(folder);
3180 if (!imap_folder)
3181 return '/';
3183 debug_print("getting session...");
3184 session = imap_session_get(FOLDER(folder));
3185 result = imap_get_path_separator(session, imap_folder, item->path, &ok);
3186 return result;
3189 static gchar imap_refresh_path_separator(IMAPSession *session, IMAPFolder *folder, const gchar *subfolder, gint *ok)
3191 clist * lep_list;
3192 int r;
3193 gchar separator = '\0';
3195 g_return_val_if_fail(session != NULL, '/');
3196 r = imap_threaded_list((Folder *)folder, "", subfolder, &lep_list);
3198 if (r != MAILIMAP_NO_ERROR) {
3199 imap_handle_error(SESSION(session), r);
3200 log_warning(LOG_PROTOCOL, _("LIST failed\n"));
3201 *ok = r;
3202 return '\0';
3205 if (lep_list != NULL && clist_count(lep_list) > 0) {
3206 clistiter * iter = clist_begin(lep_list);
3207 struct mailimap_mailbox_list * mb;
3208 mb = clist_content(iter);
3210 separator = mb->mb_delimiter;
3211 debug_print("got separator: %c\n", folder->last_seen_separator);
3213 *ok = MAILIMAP_NO_ERROR;
3214 mailimap_list_result_free(lep_list);
3215 return separator;
3218 static gchar imap_get_path_separator(IMAPSession *session, IMAPFolder *folder, const gchar *path, gint *ok)
3220 gchar separator = '/';
3221 *ok = MAILIMAP_NO_ERROR;
3222 if (folder->last_seen_separator == 0) {
3223 folder->last_seen_separator = imap_refresh_path_separator(session, folder, "", ok);
3226 if (folder->last_seen_separator == 0) {
3227 folder->last_seen_separator = imap_refresh_path_separator(session, folder, "INBOX", ok);
3230 if (folder->last_seen_separator != 0) {
3231 debug_print("using separator: %c\n", folder->last_seen_separator);
3232 return folder->last_seen_separator;
3235 return separator;
3238 static gchar *imap_get_real_path(IMAPSession *session, IMAPFolder *folder, const gchar *path, gint *ok)
3240 gchar *real_path = NULL;
3241 gchar separator;
3243 g_return_val_if_fail(folder != NULL, NULL);
3244 g_return_val_if_fail(path != NULL, NULL);
3246 *ok = MAILIMAP_NO_ERROR;
3248 real_path = imap_utf8_to_modified_utf7(path, FALSE);
3249 separator = imap_get_path_separator(session, folder, path, ok);
3250 if (*ok == MAILIMAP_NO_ERROR)
3251 imap_path_separator_subst(real_path, separator);
3253 return real_path;
3256 static gint imap_set_message_flags(IMAPSession *session,
3257 IMAPFolderItem *item,
3258 MsgNumberList *numlist,
3259 IMAPFlags flags,
3260 GSList *tags,
3261 gboolean is_set)
3263 gint ok = 0;
3264 GSList *seq_list;
3265 GSList * cur;
3266 gint total = 0;
3267 IMAPFolder *folder = NULL;
3268 GSList *sorted_list = NULL;
3270 if (numlist == NULL || session == NULL)
3271 return MAILIMAP_ERROR_BAD_STATE;
3273 folder = IMAP_FOLDER(session->folder);
3275 sorted_list = g_slist_copy(numlist);
3276 sorted_list = g_slist_sort(sorted_list, g_int_compare);
3278 cur = g_slist_last(sorted_list);
3280 if (cur)
3281 total = GPOINTER_TO_INT(cur->data);
3283 seq_list = imap_get_lep_set_from_numlist(IMAP_FOLDER(session->folder), sorted_list);
3285 statusbar_print_all(_("Flagging messages..."));
3287 for(cur = seq_list ; cur != NULL ; cur = g_slist_next(cur)) {
3288 struct mailimap_set * imapset = (struct mailimap_set *)cur->data;
3289 struct mailimap_set_item *set_item = NULL;
3291 if (imapset->set_list)
3292 set_item = clist_content(clist_begin(imapset->set_list));
3293 else
3294 continue;
3296 if (set_item == NULL)
3297 continue;
3299 statusbar_progress_all(set_item->set_first, total, 1);
3301 ok = imap_cmd_store(session, item, imapset,
3302 flags, tags, is_set);
3303 statusbar_progress_all(set_item->set_last, total, 1);
3304 if (ok != MAILIMAP_NO_ERROR && folder->max_set_size > 20) {
3305 /* reduce max set size */
3306 folder->max_set_size /= 2;
3308 if (ok != MAILIMAP_NO_ERROR && is_fatal(ok)) {
3309 break;
3313 g_slist_free(sorted_list);
3315 statusbar_progress_all(0,0,0);
3316 statusbar_pop_all();
3318 imap_lep_set_free(seq_list);
3320 return ok;
3323 typedef struct _select_data {
3324 IMAPSession *session;
3325 gchar *real_path;
3326 gint *exists;
3327 gint *recent;
3328 gint *unseen;
3329 guint32 *uid_validity;
3330 gboolean done;
3331 } select_data;
3333 static gint imap_select(IMAPSession *session, IMAPFolder *folder,
3334 FolderItem *item,
3335 gint *exists, gint *recent, gint *unseen,
3336 guint32 *uid_validity, gint *can_create_flags,
3337 gboolean block)
3339 gchar *real_path;
3340 gint ok = MAILIMAP_NO_ERROR;
3341 gint exists_, recent_, unseen_;
3342 guint32 uid_validity_;
3343 gint can_create_flags_;
3344 const gchar *path = item ? item->path:NULL;
3346 if (!item) {
3347 return MAILIMAP_ERROR_BAD_STATE;
3350 if (!exists && !recent && !unseen && !uid_validity && !can_create_flags) {
3351 if (session->mbox && strcmp(session->mbox, path) == 0)
3352 return MAILIMAP_NO_ERROR;
3354 if (!exists && !recent && !unseen && !uid_validity && can_create_flags) {
3355 if (session->mbox && strcmp(session->mbox, path) == 0) {
3356 if (IMAP_FOLDER_ITEM(item)->can_create_flags != ITEM_CAN_CREATE_FLAGS_UNKNOWN)
3357 return MAILIMAP_NO_ERROR;
3360 if (!exists)
3361 exists = &exists_;
3362 if (!recent)
3363 recent = &recent_;
3364 if (!unseen)
3365 unseen = &unseen_;
3366 if (!uid_validity)
3367 uid_validity = &uid_validity_;
3368 if (!can_create_flags)
3369 can_create_flags = &can_create_flags_;
3371 g_free(session->mbox);
3372 session->mbox = NULL;
3373 session->exists = 0;
3374 session->recent = 0;
3375 session->expunge = 0;
3377 real_path = imap_get_real_path(session, folder, path, &ok);
3378 if (is_fatal(ok))
3379 return ok;
3380 g_slist_free(IMAP_FOLDER_ITEM(item)->ok_flags);
3381 IMAP_FOLDER_ITEM(item)->ok_flags = NULL;
3382 ok = imap_cmd_select(session, real_path,
3383 exists, recent, unseen, uid_validity, can_create_flags,
3384 &(IMAP_FOLDER_ITEM(item)->ok_flags), block);
3385 if (ok != MAILIMAP_NO_ERROR) {
3386 log_warning(LOG_PROTOCOL, _("can't select folder: %s\n"), real_path);
3387 } else {
3388 session->mbox = g_strdup(path);
3389 session->folder_content_changed = FALSE;
3390 session->exists = *exists;
3391 session->recent = *recent;
3392 session->expunge = 0;
3393 session->unseen = *unseen;
3394 session->uid_validity = *uid_validity;
3395 debug_print("select: exists %d recent %d expunge %d uid_validity %d can_create_flags %d\n",
3396 session->exists, session->recent, session->expunge,
3397 session->uid_validity, *can_create_flags);
3399 if (*can_create_flags) {
3400 IMAP_FOLDER_ITEM(item)->can_create_flags = ITEM_CAN_CREATE_FLAGS;
3401 } else {
3402 IMAP_FOLDER_ITEM(item)->can_create_flags = ITEM_CANNOT_CREATE_FLAGS;
3404 g_free(real_path);
3406 return ok;
3409 static gint imap_status(IMAPSession *session, IMAPFolder *folder,
3410 const gchar *path, IMAPFolderItem *item,
3411 gint *messages,
3412 guint32 *uid_next, guint32 *uid_validity,
3413 gint *unseen, gboolean block)
3415 int r = MAILIMAP_NO_ERROR;
3416 clistiter * iter;
3417 struct mailimap_mailbox_data_status * data_status;
3418 int got_values;
3419 gchar *real_path;
3420 guint mask = 0;
3422 real_path = imap_get_real_path(session, folder, path, &r);
3423 if (is_fatal(r)) {
3424 g_free(real_path);
3425 return r;
3427 if (messages) {
3428 mask |= 1 << 0;
3429 *messages = 0;
3431 if (uid_next) {
3432 mask |= 1 << 2;
3433 *uid_next = 0;
3435 if (uid_validity) {
3436 mask |= 1 << 3;
3437 *uid_validity = 0;
3439 if (unseen) {
3440 mask |= 1 << 4;
3441 *unseen = 0;
3444 if (session->mbox != NULL &&
3445 !strcmp(session->mbox, item->item.path)) {
3446 r = imap_cmd_close(session);
3447 if (r != MAILIMAP_NO_ERROR) {
3448 debug_print("close err %d\n", r);
3449 g_free(real_path);
3450 return r;
3454 r = imap_threaded_status(FOLDER(folder), real_path,
3455 &data_status, mask);
3457 g_free(real_path);
3458 if (r != MAILIMAP_NO_ERROR) {
3459 imap_handle_error(SESSION(session), r);
3460 debug_print("status err %d\n", r);
3461 return r;
3464 if (data_status->st_info_list == NULL) {
3465 mailimap_mailbox_data_status_free(data_status);
3466 debug_print("status->st_info_list == NULL\n");
3467 return MAILIMAP_ERROR_BAD_STATE;
3470 got_values = 0;
3471 if (data_status->st_info_list) {
3472 for(iter = clist_begin(data_status->st_info_list) ; iter != NULL ;
3473 iter = clist_next(iter)) {
3474 struct mailimap_status_info * info;
3476 info = clist_content(iter);
3477 switch (info->st_att) {
3478 case MAILIMAP_STATUS_ATT_MESSAGES:
3479 if (messages) {
3480 * messages = info->st_value;
3481 got_values |= 1 << 0;
3483 break;
3485 case MAILIMAP_STATUS_ATT_UIDNEXT:
3486 if (uid_next) {
3487 * uid_next = info->st_value;
3488 got_values |= 1 << 2;
3490 break;
3492 case MAILIMAP_STATUS_ATT_UIDVALIDITY:
3493 if (uid_validity) {
3494 * uid_validity = info->st_value;
3495 got_values |= 1 << 3;
3497 break;
3499 case MAILIMAP_STATUS_ATT_UNSEEN:
3500 if (unseen) {
3501 * unseen = info->st_value;
3502 got_values |= 1 << 4;
3504 break;
3508 mailimap_mailbox_data_status_free(data_status);
3510 if (got_values != mask) {
3511 g_warning("status: incomplete values received (%d)\n", got_values);
3513 return MAILIMAP_NO_ERROR;
3516 static void imap_free_capabilities(IMAPSession *session)
3518 slist_free_strings(session->capability);
3519 g_slist_free(session->capability);
3520 session->capability = NULL;
3523 /* low-level IMAP4rev1 commands */
3525 static gint imap_cmd_login(IMAPSession *session,
3526 const gchar *user, const gchar *pass,
3527 const gchar *type)
3529 int r;
3530 gint ok;
3532 if (!strcmp(type, "LOGIN") && imap_has_capability(session, "LOGINDISABLED")) {
3533 gint ok = MAILIMAP_ERROR_BAD_STATE;
3534 if (imap_has_capability(session, "STARTTLS")) {
3535 #ifdef USE_GNUTLS
3536 log_warning(LOG_PROTOCOL, _("Server requires TLS to log in.\n"));
3537 ok = imap_cmd_starttls(session);
3538 if (ok != MAILIMAP_NO_ERROR) {
3539 log_warning(LOG_PROTOCOL, _("Can't start TLS session.\n"));
3540 return ok;
3541 } else {
3542 /* refresh capas */
3543 imap_free_capabilities(session);
3544 if ((r = imap_get_capabilities(session)) != MAILIMAP_NO_ERROR) {
3545 imap_handle_error(SESSION(session), r);
3546 log_warning(LOG_PROTOCOL, _("Can't refresh capabilities.\n"));
3547 return r;
3550 #else
3551 log_error(LOG_PROTOCOL, _("Connection to %s failed: "
3552 "server requires TLS, but Claws Mail "
3553 "has been compiled without OpenSSL "
3554 "support.\n"),
3555 SESSION(session)->server);
3556 return MAILIMAP_ERROR_LOGIN;
3557 #endif
3558 } else {
3559 log_error(LOG_PROTOCOL, _("Server logins are disabled.\n"));
3560 return MAILIMAP_ERROR_LOGIN;
3564 log_print(LOG_PROTOCOL, "IMAP4> Logging %s to %s using %s\n",
3565 user,
3566 SESSION(session)->server,
3567 type);
3568 r = imap_threaded_login(session->folder, user, pass, type);
3569 if (r != MAILIMAP_NO_ERROR) {
3570 imap_handle_error(SESSION(session), r);
3571 log_print(LOG_PROTOCOL, "IMAP4< Error logging in to %s\n",
3572 SESSION(session)->server);
3573 ok = r;
3574 } else {
3575 log_print(LOG_PROTOCOL, "IMAP4< Login to %s successful\n",
3576 SESSION(session)->server);
3577 ok = MAILIMAP_NO_ERROR;
3579 return ok;
3582 static gint imap_cmd_noop(IMAPSession *session)
3584 int r;
3585 unsigned int exists, recent, expunge, unseen, uidnext, uidval;
3587 r = imap_threaded_noop(session->folder, &exists, &recent, &expunge, &unseen, &uidnext, &uidval);
3588 if (r != MAILIMAP_NO_ERROR) {
3589 imap_handle_error(SESSION(session), r);
3590 debug_print("noop err %d\n", r);
3591 return r;
3594 session->folder_content_changed = FALSE;
3596 if ((exists && exists != session->exists)
3597 || (recent && recent != session->recent)
3598 || (expunge && expunge != session->expunge)
3599 || (unseen && unseen != session->unseen)) {
3600 session->folder_content_changed = TRUE;
3602 if (uidnext != 0 && uidnext != session->uid_next) {
3603 session->uid_next = uidnext;
3604 session->folder_content_changed = TRUE;
3606 if (uidval != 0 && uidval != session->uid_validity) {
3607 session->uid_validity = uidval;
3608 session->folder_content_changed = TRUE;
3611 session->exists = exists;
3612 session->recent = recent;
3613 session->expunge = expunge;
3614 session->unseen = unseen;
3616 session_set_access_time(SESSION(session));
3618 return MAILIMAP_NO_ERROR;
3621 #ifdef USE_GNUTLS
3622 static gint imap_cmd_starttls(IMAPSession *session)
3624 int r;
3626 r = imap_threaded_starttls(session->folder,
3627 SESSION(session)->server, SESSION(session)->port);
3628 if (r != MAILIMAP_NO_ERROR) {
3629 imap_handle_error(SESSION(session), r);
3630 debug_print("starttls err %d\n", r);
3631 return r;
3633 return MAILIMAP_NO_ERROR;
3635 #endif
3637 static gint imap_cmd_select(IMAPSession *session, const gchar *folder,
3638 gint *exists, gint *recent, gint *unseen,
3639 guint32 *uid_validity, gint *can_create_flags,
3640 GSList **ok_flags, gboolean block)
3642 int r;
3644 r = imap_threaded_select(session->folder, folder,
3645 exists, recent, unseen, uid_validity, can_create_flags, ok_flags);
3646 if (r != MAILIMAP_NO_ERROR) {
3647 imap_handle_error(SESSION(session), r);
3648 debug_print("select err %d\n", r);
3649 return r;
3651 return MAILIMAP_NO_ERROR;
3654 static gint imap_cmd_close(IMAPSession *session)
3656 int r;
3658 r = imap_threaded_close(session->folder);
3659 if (r != MAILIMAP_NO_ERROR) {
3660 imap_handle_error(SESSION(session), r);
3661 debug_print("close err %d\n", r);
3662 return r;
3664 g_free(session->mbox);
3665 session->mbox = NULL;
3666 session->exists = 0;
3667 session->recent = 0;
3668 session->expunge = 0;
3669 return MAILIMAP_NO_ERROR;
3672 static gint imap_cmd_examine(IMAPSession *session, const gchar *folder,
3673 gint *exists, gint *recent, gint *unseen,
3674 guint32 *uid_validity, gboolean block)
3676 int r;
3678 r = imap_threaded_examine(session->folder, folder,
3679 exists, recent, unseen, uid_validity);
3680 if (r != MAILIMAP_NO_ERROR) {
3681 imap_handle_error(SESSION(session), r);
3682 debug_print("examine err %d\n", r);
3684 return r;
3686 return MAILIMAP_NO_ERROR;
3689 static gint imap_cmd_create(IMAPSession *session, const gchar *folder)
3691 int r;
3693 r = imap_threaded_create(session->folder, folder);
3694 if (r != MAILIMAP_NO_ERROR) {
3695 imap_handle_error(SESSION(session), r);
3696 return r;
3699 return MAILIMAP_NO_ERROR;
3702 static gint imap_cmd_rename(IMAPSession *session, const gchar *old_folder,
3703 const gchar *new_folder)
3705 int r;
3707 r = imap_threaded_rename(session->folder, old_folder,
3708 new_folder);
3709 if (r != MAILIMAP_NO_ERROR) {
3710 imap_handle_error(SESSION(session), r);
3711 return r;
3714 return MAILIMAP_NO_ERROR;
3717 static gint imap_cmd_delete(IMAPSession *session, const gchar *folder)
3719 int r;
3722 r = imap_threaded_delete(session->folder, folder);
3723 if (r != MAILIMAP_NO_ERROR) {
3724 imap_handle_error(SESSION(session), r);
3725 return r;
3728 return MAILIMAP_NO_ERROR;
3731 typedef struct _fetch_data {
3732 IMAPSession *session;
3733 guint32 uid;
3734 const gchar *filename;
3735 gboolean headers;
3736 gboolean body;
3737 gboolean done;
3738 } fetch_data;
3740 static void *imap_cmd_fetch_thread(void *data)
3742 fetch_data *stuff = (fetch_data *)data;
3743 IMAPSession *session = stuff->session;
3744 guint32 uid = stuff->uid;
3745 const gchar *filename = stuff->filename;
3746 int r;
3748 if (stuff->body) {
3749 r = imap_threaded_fetch_content(session->folder,
3750 uid, 1, filename);
3752 else {
3753 r = imap_threaded_fetch_content(session->folder,
3754 uid, 0, filename);
3756 if (r != MAILIMAP_NO_ERROR) {
3757 imap_handle_error(SESSION(session), r);
3758 debug_print("fetch err %d\n", r);
3759 return GINT_TO_POINTER(r);
3761 return GINT_TO_POINTER(MAILIMAP_NO_ERROR);
3764 static gint imap_cmd_fetch(IMAPSession *session, guint32 uid,
3765 const gchar *filename, gboolean headers,
3766 gboolean body)
3768 fetch_data *data = g_new0(fetch_data, 1);
3769 int result = 0;
3770 data->done = FALSE;
3771 data->session = session;
3772 data->uid = uid;
3773 data->filename = filename;
3774 data->headers = headers;
3775 data->body = body;
3777 if (prefs_common.work_offline &&
3778 !inc_offline_should_override(FALSE,
3779 _("Claws Mail needs network access in order "
3780 "to access the IMAP server."))) {
3781 g_free(data);
3782 return -1;
3784 statusbar_print_all(_("Fetching message..."));
3785 result = GPOINTER_TO_INT(imap_cmd_fetch_thread(data));
3786 statusbar_pop_all();
3787 g_free(data);
3788 return result;
3792 static gint imap_cmd_append(IMAPSession *session,
3793 IMAPFolderItem *item,
3794 const gchar *destfolder,
3795 const gchar *file, IMAPFlags flags,
3796 guint32 *new_uid)
3798 struct mailimap_flag_list * flag_list;
3799 int r;
3801 cm_return_val_if_fail(file != NULL, MAILIMAP_ERROR_BAD_STATE);
3803 flag_list = imap_flag_to_lep(item, flags, NULL);
3804 lock_session(session);
3805 r = imap_threaded_append(session->folder, destfolder,
3806 file, flag_list, (int *)new_uid);
3807 mailimap_flag_list_free(flag_list);
3809 if (r != MAILIMAP_NO_ERROR) {
3810 imap_handle_error(SESSION(session), r);
3811 debug_print("append err %d\n", r);
3812 return r;
3815 unlock_session(session);
3817 return MAILIMAP_NO_ERROR;
3820 static gint imap_cmd_copy(IMAPSession *session, struct mailimap_set * set,
3821 const gchar *destfolder, GRelation *uid_mapping,
3822 struct mailimap_set **source, struct mailimap_set **dest)
3824 int r;
3826 g_return_val_if_fail(session != NULL, MAILIMAP_ERROR_BAD_STATE);
3827 g_return_val_if_fail(set != NULL, MAILIMAP_ERROR_BAD_STATE);
3828 g_return_val_if_fail(destfolder != NULL, MAILIMAP_ERROR_BAD_STATE);
3830 r = imap_threaded_copy(session->folder, set, destfolder, source, dest);
3831 if (r != MAILIMAP_NO_ERROR) {
3832 imap_handle_error(SESSION(session), r);
3833 return r;
3836 return MAILIMAP_NO_ERROR;
3839 static gint imap_cmd_store(IMAPSession *session,
3840 IMAPFolderItem *item,
3841 struct mailimap_set * set,
3842 IMAPFlags flags, GSList *tags, int do_add)
3844 int r;
3845 struct mailimap_flag_list * flag_list = NULL;
3846 struct mailimap_store_att_flags * store_att_flags;
3848 flag_list = imap_flag_to_lep(item, flags, tags);
3850 if (do_add)
3851 store_att_flags =
3852 mailimap_store_att_flags_new_add_flags_silent(flag_list);
3853 else
3854 store_att_flags =
3855 mailimap_store_att_flags_new_remove_flags_silent(flag_list);
3857 r = imap_threaded_store(session->folder, set, store_att_flags);
3858 mailimap_store_att_flags_free(store_att_flags);
3859 if (r != MAILIMAP_NO_ERROR) {
3860 imap_handle_error(SESSION(session), r);
3861 return r;
3864 return MAILIMAP_NO_ERROR;
3867 static gint imap_cmd_expunge(IMAPSession *session, gboolean do_expunge)
3869 int r;
3871 if (!do_expunge)
3872 return MAILIMAP_NO_ERROR;
3874 if (prefs_common.work_offline &&
3875 !inc_offline_should_override(FALSE,
3876 _("Claws Mail needs network access in order "
3877 "to access the IMAP server."))) {
3878 return -1;
3881 r = imap_threaded_expunge(session->folder);
3882 if (r != MAILIMAP_NO_ERROR) {
3883 imap_handle_error(SESSION(session), r);
3884 return r;
3887 return MAILIMAP_NO_ERROR;
3890 gint imap_expunge(Folder *folder, FolderItem *item)
3892 IMAPSession *session = imap_session_get(folder);
3893 if (session == NULL)
3894 return -1;
3896 return imap_cmd_expunge(session, TRUE);
3899 static void imap_path_separator_subst(gchar *str, gchar separator)
3901 gchar *p;
3902 gboolean in_escape = FALSE;
3904 if (!separator || separator == '/') return;
3906 for (p = str; *p != '\0'; p++) {
3907 if (*p == '/' && !in_escape)
3908 *p = separator;
3909 else if (*p == '&' && *(p + 1) != '-' && !in_escape)
3910 in_escape = TRUE;
3911 else if (*p == '-' && in_escape)
3912 in_escape = FALSE;
3916 static gboolean imap_rename_folder_func(GNode *node, gpointer data)
3918 FolderItem *item = node->data;
3919 gchar **paths = data;
3920 const gchar *oldpath = paths[0];
3921 const gchar *newpath = paths[1];
3922 gchar *real_oldpath, *real_newpath;
3923 gchar *base;
3924 gchar *new_itempath;
3925 gint oldpathlen;
3926 IMAPSession *session = imap_session_get(item->folder);
3927 gint ok = MAILIMAP_NO_ERROR;
3928 oldpathlen = strlen(oldpath);
3929 if (strncmp(oldpath, item->path, oldpathlen) != 0) {
3930 g_warning("path doesn't match: %s, %s\n", oldpath, item->path);
3931 return TRUE;
3934 base = item->path + oldpathlen;
3935 while (*base == G_DIR_SEPARATOR) base++;
3936 if (*base == '\0')
3937 new_itempath = g_strdup(newpath);
3938 else
3939 new_itempath = g_strconcat(newpath, G_DIR_SEPARATOR_S, base,
3940 NULL);
3942 real_oldpath = imap_get_real_path(session, IMAP_FOLDER(item->folder), item->path, &ok);
3943 g_free(item->path);
3944 item->path = new_itempath;
3946 real_newpath = imap_get_real_path(session, IMAP_FOLDER(item->folder), item->path, &ok);
3948 imap_threaded_subscribe(item->folder, real_oldpath, FALSE);
3949 imap_threaded_subscribe(item->folder, real_newpath, TRUE);
3951 g_free(real_oldpath);
3952 g_free(real_newpath);
3953 return FALSE;
3956 static gint get_list_of_uids(IMAPSession *session, Folder *folder, IMAPFolderItem *item, GSList **msgnum_list)
3958 GSList *uidlist, *elem;
3959 int r = -1;
3960 clist * lep_uidlist;
3961 gint ok, nummsgs = 0, lastuid_old;
3963 if (session == NULL) {
3964 return -1;
3967 ok = imap_select(session, IMAP_FOLDER(folder), FOLDER_ITEM(item),
3968 NULL, NULL, NULL, NULL, NULL, TRUE);
3969 if (ok != MAILIMAP_NO_ERROR) {
3970 return -1;
3973 g_slist_free(item->uid_list);
3974 item->uid_list = NULL;
3976 uidlist = NULL;
3978 if (folder->account && folder->account->low_bandwidth) {
3979 r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_SIMPLE, NULL,
3980 &lep_uidlist);
3983 if (r == MAILIMAP_NO_ERROR) {
3984 GSList * fetchuid_list =
3985 imap_uid_list_from_lep(lep_uidlist);
3986 mailimap_search_result_free(lep_uidlist);
3988 uidlist = g_slist_concat(fetchuid_list, uidlist);
3989 } else {
3990 carray * lep_uidtab;
3991 if (r != -1) { /* inited */
3992 imap_handle_error(SESSION(session), r);
3993 if (is_fatal(r))
3994 return -1;
3996 r = imap_threaded_fetch_uid(folder, 1,
3997 &lep_uidtab);
3998 if (r == MAILIMAP_NO_ERROR) {
3999 GSList * fetchuid_list =
4000 imap_uid_list_from_lep_tab(lep_uidtab);
4001 imap_fetch_uid_list_free(lep_uidtab);
4002 uidlist = g_slist_concat(fetchuid_list, uidlist);
4006 if (r != MAILIMAP_NO_ERROR) {
4007 imap_handle_error(SESSION(session), r);
4008 return -1;
4011 lastuid_old = item->lastuid;
4013 for (elem = uidlist; elem != NULL; elem = g_slist_next(elem)) {
4014 guint msgnum;
4016 msgnum = GPOINTER_TO_INT(elem->data);
4018 *msgnum_list = g_slist_prepend(*msgnum_list, GINT_TO_POINTER(msgnum));
4019 item->uid_list = g_slist_prepend(item->uid_list, GINT_TO_POINTER(msgnum));
4020 nummsgs++;
4022 g_slist_free(uidlist);
4024 unlock_session(session); /* locked from imap_get_num_list */
4026 return nummsgs;
4030 gint imap_get_num_list(Folder *folder, FolderItem *_item, GSList **msgnum_list, gboolean *old_uids_valid)
4032 IMAPFolderItem *item = (IMAPFolderItem *)_item;
4033 IMAPSession *session;
4034 gint nummsgs;
4035 GSList *uidlist = NULL;
4036 gchar *dir;
4037 gboolean selected_folder;
4038 gint known_list_len = 0;
4039 debug_print("get_num_list\n");
4041 g_return_val_if_fail(folder != NULL, -1);
4042 g_return_val_if_fail(item != NULL, -1);
4043 g_return_val_if_fail(item->item.path != NULL, -1);
4044 g_return_val_if_fail(FOLDER_CLASS(folder) == &imap_class, -1);
4045 g_return_val_if_fail(folder->account != NULL, -1);
4047 known_list_len = g_slist_length(item->uid_list);
4048 if (!item->should_update) {
4049 debug_print("get_num_list: nothing to update\n");
4050 *old_uids_valid = TRUE;
4051 if (known_list_len == item->item.total_msgs
4052 && known_list_len > 0) {
4053 *msgnum_list = g_slist_copy(item->uid_list);
4054 return known_list_len;
4055 } else {
4056 debug_print("don't know the list length...\n");
4060 if (prefs_common.work_offline &&
4061 !inc_offline_should_override(FALSE,
4062 _("Claws Mail needs network access in order "
4063 "to access the IMAP server."))) {
4064 return -1;
4067 debug_print("getting session...\n");
4068 session = imap_session_get(folder);
4069 g_return_val_if_fail(session != NULL, -1);
4071 lock_session(session); /* unlocked by get_list_of_uids */
4072 if (FOLDER_ITEM(item)->path)
4073 statusbar_print_all(_("Scanning folder %s%c%s ..."),
4074 FOLDER_ITEM(item)->folder->name,
4075 G_DIR_SEPARATOR,
4076 FOLDER_ITEM(item)->path);
4077 else
4078 statusbar_print_all(_("Scanning folder %s ..."),
4079 FOLDER_ITEM(item)->folder->name);
4081 selected_folder = (session->mbox != NULL) &&
4082 (!strcmp(session->mbox, item->item.path));
4084 if (item->should_trash_cache) {
4085 *old_uids_valid = FALSE;
4086 debug_print("get_num_list: trashing num list\n");
4087 debug_print("Freeing imap uid cache\n");
4088 item->lastuid = 0;
4089 g_slist_free(item->uid_list);
4090 item->uid_list = NULL;
4092 imap_delete_all_cached_messages((FolderItem *)item);
4093 } else {
4094 debug_print("get_num_list: updating num list\n");
4095 *old_uids_valid = TRUE;
4098 nummsgs = get_list_of_uids(session, folder, item, &uidlist);
4099 /* session could be broken now, in case of fatal error */
4101 debug_print("get_num_list: got %d msgs\n", nummsgs);
4103 if (nummsgs < 0) {
4104 statusbar_pop_all();
4105 return -1;
4108 *msgnum_list = uidlist;
4110 dir = folder_item_get_path((FolderItem *)item);
4111 debug_print("removing old messages from %s\n", dir);
4112 remove_numbered_files_not_in_list(dir, *msgnum_list);
4113 g_free(dir);
4115 debug_print("get_num_list - ok - %i\n", nummsgs);
4116 statusbar_pop_all();
4117 item->should_trash_cache = FALSE;
4118 item->should_update = FALSE;
4119 return nummsgs;
4122 static MsgInfo *imap_parse_msg(const gchar *file, FolderItem *item)
4124 MsgInfo *msginfo;
4125 MsgFlags flags;
4127 flags.perm_flags = MSG_NEW|MSG_UNREAD;
4128 flags.tmp_flags = 0;
4130 g_return_val_if_fail(item != NULL, NULL);
4131 g_return_val_if_fail(file != NULL, NULL);
4133 if (folder_has_parent_of_type(item, F_QUEUE)) {
4134 MSG_SET_TMP_FLAGS(flags, MSG_QUEUED);
4135 } else if (folder_has_parent_of_type(item, F_DRAFT)) {
4136 MSG_SET_TMP_FLAGS(flags, MSG_DRAFT);
4139 msginfo = procheader_parse_file(file, flags, FALSE, FALSE);
4140 if (!msginfo) return NULL;
4142 msginfo->plaintext_file = g_strdup(file);
4143 msginfo->folder = item;
4145 return msginfo;
4148 GSList *imap_get_msginfos(Folder *folder, FolderItem *item,
4149 GSList *msgnum_list)
4151 IMAPSession *session;
4152 MsgInfoList *ret = NULL;
4153 gint ok;
4155 debug_print("get_msginfos\n");
4157 g_return_val_if_fail(folder != NULL, NULL);
4158 g_return_val_if_fail(item != NULL, NULL);
4159 g_return_val_if_fail(msgnum_list != NULL, NULL);
4161 debug_print("getting session...\n");
4162 session = imap_session_get(folder);
4163 g_return_val_if_fail(session != NULL, NULL);
4165 lock_session(session); /* unlocked later in the function */
4167 debug_print("IMAP getting msginfos\n");
4168 ok = imap_select(session, IMAP_FOLDER(folder), item,
4169 NULL, NULL, NULL, NULL, NULL, FALSE);
4170 if (ok != MAILIMAP_NO_ERROR) {
4171 return NULL;
4173 if (!(folder_has_parent_of_type(item, F_DRAFT) ||
4174 folder_has_parent_of_type(item, F_QUEUE))) {
4175 ret = g_slist_concat(ret,
4176 imap_get_uncached_messages(session, item,
4177 msgnum_list, &ok));
4178 if (ok != MAILIMAP_NO_ERROR)
4179 return NULL;
4180 unlock_session(session);
4181 } else {
4182 MsgNumberList *sorted_list, *elem, *llast = NULL;
4183 gint startnum, lastnum;
4185 unlock_session(session);
4187 sorted_list = g_slist_sort(g_slist_copy(msgnum_list), g_int_compare);
4189 startnum = lastnum = GPOINTER_TO_INT(sorted_list->data);
4191 llast = g_slist_last(ret);
4192 for (elem = sorted_list;; elem = g_slist_next(elem)) {
4193 guint num = 0;
4195 if (elem)
4196 num = GPOINTER_TO_INT(elem->data);
4198 if (num > lastnum + 1 || elem == NULL) {
4199 int i;
4200 for (i = startnum; i <= lastnum; ++i) {
4201 gchar *file;
4202 file = imap_fetch_msg(folder, item, i);
4203 if (file != NULL) {
4204 MsgInfo *msginfo = imap_parse_msg(file, item);
4205 if (msginfo != NULL) {
4206 msginfo->msgnum = i;
4207 if (llast == NULL)
4208 llast = ret = g_slist_append(ret, msginfo);
4209 else {
4210 llast = g_slist_append(llast, msginfo);
4211 llast = llast->next;
4214 g_free(file);
4218 if (elem == NULL)
4219 break;
4221 startnum = num;
4223 lastnum = num;
4226 g_slist_free(sorted_list);
4228 return ret;
4231 MsgInfo *imap_get_msginfo(Folder *folder, FolderItem *item, gint uid)
4233 MsgInfo *msginfo = NULL;
4234 MsgInfoList *msginfolist;
4235 MsgNumberList numlist;
4237 numlist.next = NULL;
4238 numlist.data = GINT_TO_POINTER(uid);
4240 msginfolist = imap_get_msginfos(folder, item, &numlist);
4241 if (msginfolist != NULL) {
4242 msginfo = msginfolist->data;
4243 g_slist_free(msginfolist);
4246 return msginfo;
4249 gboolean imap_scan_required(Folder *folder, FolderItem *_item)
4251 IMAPSession *session;
4252 IMAPFolderItem *item = (IMAPFolderItem *)_item;
4253 gint ok, exists = 0, unseen = 0;
4254 guint32 uid_next = 0, uid_val = 0;
4255 gboolean selected_folder;
4257 g_return_val_if_fail(folder != NULL, FALSE);
4258 g_return_val_if_fail(item != NULL, FALSE);
4259 g_return_val_if_fail(item->item.folder != NULL, FALSE);
4260 g_return_val_if_fail(FOLDER_CLASS(item->item.folder) == &imap_class, FALSE);
4262 if (item->item.path == NULL)
4263 return FALSE;
4265 if (item->should_update) {
4266 debug_print("scan already required\n");
4267 return TRUE;
4269 debug_print("getting session...\n");
4270 session = imap_session_get(folder);
4272 g_return_val_if_fail(session != NULL, FALSE);
4273 lock_session(session); /* unlocked later in the function */
4275 selected_folder = (session->mbox != NULL) &&
4276 (!strcmp(session->mbox, item->item.path));
4277 if (selected_folder) {
4278 if (!session->folder_content_changed) {
4279 ok = imap_cmd_noop(session);
4280 if (ok != MAILIMAP_NO_ERROR) {
4281 debug_print("disconnected!\n");
4282 if (!is_fatal(ok))
4283 session = imap_reconnect_if_possible(folder, session);
4284 else
4285 session = imap_session_get(folder);
4286 if (session == NULL)
4287 return FALSE;
4290 if (session->folder_content_changed) {
4291 debug_print("CHANGED (self-noop)! scan_required\n");
4292 item->should_update = TRUE;
4293 if (session->uid_validity && session->uid_validity != item->item.mtime) {
4294 item->item.mtime = session->uid_validity;
4295 item->should_trash_cache = TRUE;
4297 unlock_session(session);
4298 return TRUE;
4300 } else {
4301 debug_print("CHANGED (previous noop)! scan_required\n");
4302 item->should_update = TRUE;
4303 if (session->uid_validity && session->uid_validity != item->item.mtime) {
4304 item->item.mtime = session->uid_validity;
4305 item->should_trash_cache = TRUE;
4307 unlock_session(session);
4308 return TRUE;
4310 } else {
4311 ok = imap_status(session, IMAP_FOLDER(folder), item->item.path, IMAP_FOLDER_ITEM(item),
4312 &exists, &uid_next, &uid_val, &unseen, FALSE);
4313 if (ok != MAILIMAP_NO_ERROR) {
4314 return FALSE;
4317 debug_print("exists %d, item->item.total_msgs %d\n",
4318 exists, item->item.total_msgs);
4319 if (exists != item->item.total_msgs
4320 || unseen != item->item.unread_msgs
4321 || uid_next != item->uid_next
4322 || uid_val != item->item.mtime) {
4323 debug_print("CHANGED (status)! scan_required\n");
4324 item->last_change = time(NULL);
4325 item->should_update = TRUE;
4326 item->uid_next = uid_next;
4327 if (uid_val != item->item.mtime) {
4328 item->item.mtime = uid_val;
4329 item->should_trash_cache = TRUE;
4331 unlock_session(session);
4332 return TRUE;
4335 unlock_session(session);
4337 item->should_update = FALSE;
4338 return FALSE;
4341 void imap_change_flags(Folder *folder, FolderItem *item, MsgInfo *msginfo, MsgPermFlags newflags)
4343 IMAPSession *session;
4344 IMAPFlags flags_set = 0, flags_unset = 0;
4345 gint ok = MAILIMAP_NO_ERROR;
4346 MsgNumberList numlist;
4347 hashtable_data *ht_data = NULL;
4349 g_return_if_fail(folder != NULL);
4350 g_return_if_fail(folder->klass == &imap_class);
4351 g_return_if_fail(item != NULL);
4352 g_return_if_fail(item->folder == folder);
4353 g_return_if_fail(msginfo != NULL);
4354 g_return_if_fail(msginfo->folder == item);
4356 if (!MSG_IS_MARKED(msginfo->flags) && (newflags & MSG_MARKED))
4357 flags_set |= IMAP_FLAG_FLAGGED;
4358 if ( MSG_IS_MARKED(msginfo->flags) && !(newflags & MSG_MARKED))
4359 flags_unset |= IMAP_FLAG_FLAGGED;
4361 if (!MSG_IS_UNREAD(msginfo->flags) && (newflags & MSG_UNREAD))
4362 flags_unset |= IMAP_FLAG_SEEN;
4363 if ( MSG_IS_UNREAD(msginfo->flags) && !(newflags & MSG_UNREAD))
4364 flags_set |= IMAP_FLAG_SEEN;
4366 if (!MSG_IS_REPLIED(msginfo->flags) && (newflags & MSG_REPLIED))
4367 flags_set |= IMAP_FLAG_ANSWERED;
4368 if ( MSG_IS_REPLIED(msginfo->flags) && !(newflags & MSG_REPLIED))
4369 flags_unset |= IMAP_FLAG_ANSWERED;
4371 if (!MSG_IS_FORWARDED(msginfo->flags) && (newflags & MSG_FORWARDED))
4372 flags_set |= IMAP_FLAG_FORWARDED;
4373 if ( MSG_IS_FORWARDED(msginfo->flags) && !(newflags & MSG_FORWARDED))
4374 flags_unset |= IMAP_FLAG_FORWARDED;
4376 if (!MSG_IS_SPAM(msginfo->flags) && (newflags & MSG_SPAM)) {
4377 flags_set |= IMAP_FLAG_SPAM;
4378 flags_unset |= IMAP_FLAG_HAM;
4380 if ( MSG_IS_SPAM(msginfo->flags) && !(newflags & MSG_SPAM)) {
4381 flags_set |= IMAP_FLAG_HAM;
4382 flags_unset |= IMAP_FLAG_SPAM;
4384 if (!MSG_IS_DELETED(msginfo->flags) && (newflags & MSG_DELETED))
4385 flags_set |= IMAP_FLAG_DELETED;
4386 if ( MSG_IS_DELETED(msginfo->flags) && !(newflags & MSG_DELETED))
4387 flags_unset |= IMAP_FLAG_DELETED;
4389 if (!flags_set && !flags_unset) {
4390 /* the changed flags were not translatable to IMAP-speak.
4391 * like MSG_POSTFILTERED, so just apply. */
4392 msginfo->flags.perm_flags = newflags;
4393 return;
4396 debug_print("getting session...\n");
4397 session = imap_session_get(folder);
4398 if (!session) {
4399 return;
4402 if ((ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder,
4403 NULL, NULL, NULL, NULL, NULL, FALSE)) != MAILIMAP_NO_ERROR) {
4404 return;
4406 numlist.next = NULL;
4407 numlist.data = GINT_TO_POINTER(msginfo->msgnum);
4409 if (IMAP_FOLDER_ITEM(item)->batching) {
4410 /* instead of performing an UID STORE command for each message change,
4411 * as a lot of them can change "together", we just fill in hashtables
4412 * and defer the treatment so that we're able to send only one
4413 * command.
4415 debug_print("IMAP batch mode on, deferring flags change\n");
4416 if (flags_set) {
4417 ht_data = g_hash_table_lookup(IMAP_FOLDER_ITEM(item)->flags_set_table,
4418 GINT_TO_POINTER(flags_set));
4419 if (ht_data == NULL) {
4420 ht_data = g_new0(hashtable_data, 1);
4421 ht_data->item = IMAP_FOLDER_ITEM(item);
4422 g_hash_table_insert(IMAP_FOLDER_ITEM(item)->flags_set_table,
4423 GINT_TO_POINTER(flags_set), ht_data);
4425 ht_data->msglist = g_slist_prepend(ht_data->msglist, GINT_TO_POINTER(msginfo->msgnum));
4427 if (flags_unset) {
4428 ht_data = g_hash_table_lookup(IMAP_FOLDER_ITEM(item)->flags_unset_table,
4429 GINT_TO_POINTER(flags_unset));
4430 if (ht_data == NULL) {
4431 ht_data = g_new0(hashtable_data, 1);
4432 ht_data->item = IMAP_FOLDER_ITEM(item);
4433 g_hash_table_insert(IMAP_FOLDER_ITEM(item)->flags_unset_table,
4434 GINT_TO_POINTER(flags_unset), ht_data);
4436 ht_data->msglist = g_slist_prepend(ht_data->msglist,
4437 GINT_TO_POINTER(msginfo->msgnum));
4439 } else {
4440 debug_print("IMAP changing flags\n");
4441 if (flags_set) {
4442 ok = imap_set_message_flags(session, IMAP_FOLDER_ITEM(item), &numlist, flags_set, NULL, TRUE);
4443 if (ok != MAILIMAP_NO_ERROR) {
4444 return;
4448 if (flags_unset) {
4449 ok = imap_set_message_flags(session, IMAP_FOLDER_ITEM(item), &numlist, flags_unset, NULL, FALSE);
4450 if (ok != MAILIMAP_NO_ERROR) {
4451 return;
4455 msginfo->flags.perm_flags = newflags;
4456 return;
4459 static gint imap_remove_msg(Folder *folder, FolderItem *item, gint uid)
4461 gint ok;
4462 IMAPSession *session;
4463 gchar *dir;
4464 MsgNumberList numlist;
4466 g_return_val_if_fail(folder != NULL, -1);
4467 g_return_val_if_fail(FOLDER_CLASS(folder) == &imap_class, -1);
4468 g_return_val_if_fail(item != NULL, -1);
4470 debug_print("getting session...\n");
4471 session = imap_session_get(folder);
4472 if (!session) return -1;
4474 ok = imap_select(session, IMAP_FOLDER(folder), item,
4475 NULL, NULL, NULL, NULL, NULL, FALSE);
4476 if (ok != MAILIMAP_NO_ERROR) {
4477 return ok;
4479 numlist.next = NULL;
4480 numlist.data = GINT_TO_POINTER(uid);
4482 ok = imap_set_message_flags
4483 (session, IMAP_FOLDER_ITEM(item), &numlist, IMAP_FLAG_DELETED, NULL, TRUE);
4484 if (ok != MAILIMAP_NO_ERROR) {
4485 log_warning(LOG_PROTOCOL, _("can't set deleted flags: %d\n"), uid);
4486 return ok;
4489 ok = imap_cmd_expunge(session, folder->account->imap_use_trash);
4491 if (ok != MAILIMAP_NO_ERROR) {
4492 log_warning(LOG_PROTOCOL, _("can't expunge\n"));
4493 return ok;
4496 IMAP_FOLDER_ITEM(item)->uid_list = g_slist_remove(
4497 IMAP_FOLDER_ITEM(item)->uid_list, numlist.data);
4498 dir = folder_item_get_path(item);
4499 if (is_dir_exist(dir))
4500 remove_numbered_files(dir, uid, uid);
4501 g_free(dir);
4502 return MAILIMAP_NO_ERROR;
4505 static gint compare_msginfo(gconstpointer a, gconstpointer b)
4507 return ((MsgInfo *)a)->msgnum - ((MsgInfo *)b)->msgnum;
4510 static guint gslist_find_next_num(MsgNumberList **list, guint num)
4512 GSList *elem;
4514 g_return_val_if_fail(list != NULL, -1);
4516 for (elem = *list; elem != NULL; elem = g_slist_next(elem))
4517 if (GPOINTER_TO_INT(elem->data) >= num)
4518 break;
4519 *list = elem;
4520 return elem != NULL ? GPOINTER_TO_INT(elem->data) : (gint)-1;
4523 static gboolean flag_ok(IMAPFolderItem *item, guint flag)
4525 if (item->ok_flags && g_slist_find(item->ok_flags, GUINT_TO_POINTER(flag))) {
4526 debug_print("flag %d is OK\n", flag);
4527 return TRUE;
4529 if (item->can_create_flags == ITEM_CAN_CREATE_FLAGS) {
4530 debug_print("creating flags is OK\n");
4531 return TRUE;
4533 return FALSE;
4537 * NEW and DELETED flags are not syncronized
4538 * - The NEW/RECENT flags in IMAP folders can not really be directly
4539 * modified by Sylpheed
4540 * - The DELETE/DELETED flag in IMAP and Sylpheed don't have the same
4541 * meaning, in IMAP it always removes the messages from the FolderItem
4542 * in Sylpheed it can mean to move the message to trash
4545 typedef struct _get_flags_data {
4546 Folder *folder;
4547 FolderItem *item;
4548 MsgInfoList *msginfo_list;
4549 GRelation *msgflags;
4550 gboolean full_search;
4551 gboolean done;
4552 } get_flags_data;
4554 static /*gint*/ void *imap_get_flags_thread(void *data)
4556 get_flags_data *stuff = (get_flags_data *)data;
4557 Folder *folder = stuff->folder;
4558 FolderItem *fitem = (FolderItem *) stuff->item;
4559 MsgInfoList *msginfo_list = stuff->msginfo_list;
4560 GRelation *msgflags = stuff->msgflags;
4561 GSList *elem;
4562 carray * lep_uidtab;
4563 IMAPSession *session;
4564 gint ok;
4565 int r = MAILIMAP_NO_ERROR;
4566 GHashTable *flags_hash = NULL;
4567 GHashTable *tags_hash = NULL;
4568 gboolean full_search = stuff->full_search;
4569 GSList *sorted_list = NULL;
4570 GSList *unseen = NULL, *answered = NULL, *flagged = NULL, *deleted = NULL, *forwarded = NULL, *spam = NULL;
4571 GSList *seq_list, *cur;
4572 gboolean reverse_seen = FALSE;
4573 gboolean selected_folder;
4574 gint exists_cnt, unseen_cnt;
4575 gboolean got_alien_tags = FALSE;
4577 session = imap_session_get(folder);
4579 if (session == NULL) {
4580 stuff->done = TRUE;
4581 return GINT_TO_POINTER(-1);
4583 selected_folder = (session->mbox != NULL) &&
4584 (!strcmp(session->mbox, fitem->path));
4586 lock_session(session);
4587 if (!selected_folder) {
4588 ok = imap_select(session, IMAP_FOLDER(folder), fitem,
4589 &exists_cnt, NULL, &unseen_cnt, NULL, NULL, TRUE);
4590 if (ok != MAILIMAP_NO_ERROR) {
4591 stuff->done = TRUE;
4592 return GINT_TO_POINTER(-1);
4595 if (unseen_cnt > exists_cnt / 2)
4596 reverse_seen = TRUE;
4598 else {
4599 if (fitem->unread_msgs > fitem->total_msgs / 2)
4600 reverse_seen = TRUE;
4603 sorted_list = g_slist_sort(g_slist_copy(msginfo_list), compare_msginfo);
4604 if (!full_search) {
4605 seq_list = imap_get_lep_set_from_msglist(IMAP_FOLDER(folder), msginfo_list);
4606 } else {
4607 struct mailimap_set * set;
4608 set = mailimap_set_new_interval(1, 0);
4609 seq_list = g_slist_append(NULL, set);
4612 if (folder->account && folder->account->low_bandwidth) {
4613 for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
4614 struct mailimap_set * imapset;
4615 clist * lep_uidlist;
4616 int r;
4618 imapset = cur->data;
4619 if (reverse_seen) {
4620 r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_SEEN,
4621 full_search ? NULL:imapset, &lep_uidlist);
4623 else {
4624 r = imap_threaded_search(folder,
4625 IMAP_SEARCH_TYPE_UNSEEN,
4626 full_search ? NULL:imapset, &lep_uidlist);
4628 if (r == MAILIMAP_NO_ERROR) {
4629 GSList * uidlist;
4631 uidlist = imap_uid_list_from_lep(lep_uidlist);
4632 mailimap_search_result_free(lep_uidlist);
4634 unseen = g_slist_concat(unseen, uidlist);
4635 } else {
4636 imap_handle_error(SESSION(session), r);
4637 goto bail;
4640 r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_FLAGGED,
4641 full_search ? NULL:imapset, &lep_uidlist);
4642 if (r == MAILIMAP_NO_ERROR) {
4643 GSList * uidlist;
4645 uidlist = imap_uid_list_from_lep(lep_uidlist);
4646 mailimap_search_result_free(lep_uidlist);
4648 flagged = g_slist_concat(flagged, uidlist);
4649 } else {
4650 imap_handle_error(SESSION(session), r);
4651 goto bail;
4654 if (fitem->opened || fitem->processing_pending || fitem == folder->inbox) {
4655 r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_ANSWERED,
4656 full_search ? NULL:imapset, &lep_uidlist);
4657 if (r == MAILIMAP_NO_ERROR) {
4658 GSList * uidlist;
4660 uidlist = imap_uid_list_from_lep(lep_uidlist);
4661 mailimap_search_result_free(lep_uidlist);
4663 answered = g_slist_concat(answered, uidlist);
4664 } else {
4665 imap_handle_error(SESSION(session), r);
4666 goto bail;
4669 if (flag_ok(IMAP_FOLDER_ITEM(fitem), IMAP_FLAG_FORWARDED)) {
4670 r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_FORWARDED,
4671 full_search ? NULL:imapset, &lep_uidlist);
4672 if (r == MAILIMAP_NO_ERROR) {
4673 GSList * uidlist;
4675 uidlist = imap_uid_list_from_lep(lep_uidlist);
4676 mailimap_search_result_free(lep_uidlist);
4678 forwarded = g_slist_concat(forwarded, uidlist);
4679 } else {
4680 imap_handle_error(SESSION(session), r);
4681 goto bail;
4685 if (flag_ok(IMAP_FOLDER_ITEM(fitem), IMAP_FLAG_SPAM)) {
4686 r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_SPAM,
4687 full_search ? NULL:imapset, &lep_uidlist);
4688 if (r == MAILIMAP_NO_ERROR) {
4689 GSList * uidlist;
4691 uidlist = imap_uid_list_from_lep(lep_uidlist);
4692 mailimap_search_result_free(lep_uidlist);
4694 spam = g_slist_concat(spam, uidlist);
4695 } else {
4696 imap_handle_error(SESSION(session), r);
4697 goto bail;
4701 r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_DELETED,
4702 full_search ? NULL:imapset, &lep_uidlist);
4703 if (r == MAILIMAP_NO_ERROR) {
4704 GSList * uidlist;
4706 uidlist = imap_uid_list_from_lep(lep_uidlist);
4707 mailimap_search_result_free(lep_uidlist);
4709 deleted = g_slist_concat(deleted, uidlist);
4710 } else {
4711 imap_handle_error(SESSION(session), r);
4712 goto bail;
4717 } else {
4718 r = imap_threaded_fetch_uid_flags(folder, 1, &lep_uidtab);
4719 if (r == MAILIMAP_NO_ERROR) {
4720 flags_hash = g_hash_table_new_full(g_direct_hash, g_direct_equal, NULL, NULL);
4721 tags_hash = g_hash_table_new_full(g_direct_hash, g_direct_equal, NULL, NULL);
4722 imap_flags_hash_from_lep_uid_flags_tab(lep_uidtab, flags_hash, tags_hash);
4723 imap_fetch_uid_flags_list_free(lep_uidtab);
4724 } else {
4725 imap_handle_error(SESSION(session), r);
4726 goto bail;
4730 bail:
4731 if (r == MAILIMAP_NO_ERROR)
4732 unlock_session(session);
4734 for (elem = sorted_list; elem != NULL; elem = g_slist_next(elem)) {
4735 MsgInfo *msginfo;
4736 MsgPermFlags flags, oldflags;
4737 gboolean wasnew;
4739 msginfo = (MsgInfo *) elem->data;
4740 flags = msginfo->flags.perm_flags;
4741 wasnew = (flags & MSG_NEW);
4742 oldflags = flags & ~(MSG_NEW|MSG_UNREAD|MSG_REPLIED|MSG_FORWARDED|MSG_MARKED|MSG_DELETED|MSG_SPAM);
4744 if (folder->account && folder->account->low_bandwidth) {
4745 if (fitem->opened || fitem->processing_pending || fitem == folder->inbox) {
4746 flags &= ~((reverse_seen ? 0 : MSG_UNREAD | MSG_NEW) | MSG_REPLIED | MSG_FORWARDED | MSG_MARKED | MSG_SPAM);
4747 } else {
4748 flags &= ~((reverse_seen ? 0 : MSG_UNREAD | MSG_NEW | MSG_MARKED));
4750 if (reverse_seen)
4751 flags |= MSG_UNREAD | (wasnew ? MSG_NEW : 0);
4752 if (gslist_find_next_num(&unseen, msginfo->msgnum) == msginfo->msgnum) {
4753 if (!reverse_seen) {
4754 flags |= MSG_UNREAD | (wasnew ? MSG_NEW : 0);
4755 } else {
4756 flags &= ~(MSG_UNREAD | MSG_NEW);
4760 if (gslist_find_next_num(&flagged, msginfo->msgnum) == msginfo->msgnum)
4761 flags |= MSG_MARKED;
4762 else
4763 flags &= ~MSG_MARKED;
4765 if (fitem->opened || fitem->processing_pending || fitem == folder->inbox) {
4766 if (gslist_find_next_num(&answered, msginfo->msgnum) == msginfo->msgnum)
4767 flags |= MSG_REPLIED;
4768 else
4769 flags &= ~MSG_REPLIED;
4770 if (gslist_find_next_num(&forwarded, msginfo->msgnum) == msginfo->msgnum)
4771 flags |= MSG_FORWARDED;
4772 else
4773 flags &= ~MSG_FORWARDED;
4774 if (gslist_find_next_num(&spam, msginfo->msgnum) == msginfo->msgnum)
4775 flags |= MSG_SPAM;
4776 else
4777 flags &= ~MSG_SPAM;
4778 if (gslist_find_next_num(&deleted, msginfo->msgnum) == msginfo->msgnum)
4779 flags |= MSG_DELETED;
4780 else
4781 flags &= ~MSG_DELETED;
4783 } else {
4784 if (flags_hash != NULL) {
4786 flags = GPOINTER_TO_INT(g_hash_table_lookup(flags_hash,
4787 GINT_TO_POINTER(msginfo->msgnum)));
4790 if ((flags & MSG_UNREAD) == 0)
4791 flags &= ~MSG_NEW;
4792 else if (wasnew)
4793 flags |= MSG_NEW;
4794 flags |= oldflags;
4796 if (tags_hash != NULL) {
4797 GSList *tags = g_hash_table_lookup(tags_hash, GINT_TO_POINTER(msginfo->msgnum));
4798 GSList *cur;
4800 if (tags != NULL) {
4801 g_slist_free(msginfo->tags);
4802 msginfo->tags = NULL;
4804 for (cur = tags; cur; cur = cur->next) {
4805 gchar *real_tag = imap_modified_utf7_to_utf8(cur->data, TRUE);
4806 gint id = 0;
4807 id = tags_get_id_for_str(real_tag);
4808 if (id == -1) {
4809 id = tags_add_tag(real_tag);
4810 got_alien_tags = TRUE;
4812 if (!g_slist_find(msginfo->tags, GINT_TO_POINTER(id))) {
4813 msginfo->tags = g_slist_append(
4814 msginfo->tags,
4815 GINT_TO_POINTER(id));
4817 g_free(real_tag);
4819 slist_free_strings(tags);
4820 g_slist_free(tags);
4824 g_relation_insert(msgflags, msginfo, GINT_TO_POINTER(flags));
4827 if (got_alien_tags) {
4828 tags_write_tags();
4829 main_window_reflect_tags_changes(mainwindow_get_mainwindow());
4832 if (flags_hash)
4833 g_hash_table_destroy(flags_hash);
4834 if (tags_hash)
4835 g_hash_table_destroy(tags_hash);
4837 imap_lep_set_free(seq_list);
4838 g_slist_free(flagged);
4839 g_slist_free(deleted);
4840 g_slist_free(answered);
4841 g_slist_free(forwarded);
4842 g_slist_free(spam);
4843 g_slist_free(unseen);
4844 g_slist_free(sorted_list);
4846 stuff->done = TRUE;
4847 return GINT_TO_POINTER(0);
4850 static gint imap_get_flags(Folder *folder, FolderItem *item,
4851 MsgInfoList *msginfo_list, GRelation *msgflags)
4853 gint result;
4854 get_flags_data *data = g_new0(get_flags_data, 1);
4855 data->done = FALSE;
4856 data->folder = folder;
4857 data->item = item;
4858 data->msginfo_list = msginfo_list;
4859 data->msgflags = msgflags;
4860 data->full_search = FALSE;
4862 GSList *tmp = NULL, *cur;
4864 if (prefs_common.work_offline &&
4865 !inc_offline_should_override(FALSE,
4866 _("Claws Mail needs network access in order "
4867 "to access the IMAP server."))) {
4868 g_free(data);
4869 return -1;
4872 tmp = folder_item_get_msg_list(item);
4874 if (g_slist_length(tmp) <= g_slist_length(msginfo_list))
4875 data->full_search = TRUE;
4877 for (cur = tmp; cur; cur = cur->next)
4878 procmsg_msginfo_free((MsgInfo *)cur->data);
4880 g_slist_free(tmp);
4882 result = GPOINTER_TO_INT(imap_get_flags_thread(data));
4884 g_free(data);
4885 return result;
4889 static gboolean process_flags(gpointer key, gpointer value, gpointer user_data)
4891 gboolean flags_set = GPOINTER_TO_INT(user_data);
4892 gint flags_value = GPOINTER_TO_INT(key);
4893 hashtable_data *data = (hashtable_data *)value;
4894 IMAPFolderItem *_item = data->item;
4895 FolderItem *item = (FolderItem *)_item;
4896 gint ok = MAILIMAP_ERROR_BAD_STATE;
4897 IMAPSession *session = NULL;
4899 debug_print("getting session...\n");
4900 session = imap_session_get(item->folder);
4902 data->msglist = g_slist_reverse(data->msglist);
4904 debug_print("IMAP %ssetting flags to %d for %d messages\n",
4905 flags_set?"":"un",
4906 flags_value,
4907 g_slist_length(data->msglist));
4909 lock_session(session);
4910 if (session) {
4911 ok = imap_select(session, IMAP_FOLDER(item->folder), item,
4912 NULL, NULL, NULL, NULL, NULL, FALSE);
4914 if (ok == MAILIMAP_NO_ERROR) {
4915 ok = imap_set_message_flags(session, IMAP_FOLDER_ITEM(item),
4916 data->msglist, flags_value, NULL, flags_set);
4917 } else {
4918 g_warning("can't select mailbox %s\n", item->path);
4921 if (!is_fatal(ok))
4922 unlock_session(session);
4924 g_slist_free(data->msglist);
4925 g_free(data);
4926 return TRUE;
4929 static gboolean process_tags(gpointer key, gpointer value, gpointer user_data)
4931 gboolean tags_set = GPOINTER_TO_INT(user_data);
4932 TagsData *data = (TagsData *)value;
4933 IMAPFolderItem *_item = data->item;
4934 FolderItem *item = (FolderItem *)_item;
4935 gchar *str = data->str;
4936 gint ok = MAILIMAP_ERROR_BAD_STATE;
4937 IMAPSession *session = NULL;
4939 debug_print("getting session...\n");
4940 session = imap_session_get(item->folder);
4942 data->msglist = g_slist_reverse(data->msglist);
4944 debug_print("IMAP %ssetting tags %s for %d messages\n",
4945 tags_set?"":"un",
4946 str,
4947 g_slist_length(data->msglist));
4949 lock_session(session);
4950 if (session) {
4951 ok = imap_select(session, IMAP_FOLDER(item->folder), item,
4952 NULL, NULL, NULL, NULL, NULL, FALSE);
4954 if (ok == MAILIMAP_NO_ERROR) {
4955 GSList list;
4956 list.data = str;
4957 list.next = NULL;
4958 ok = imap_set_message_flags(session, IMAP_FOLDER_ITEM(item),
4959 data->msglist, 0, &list, tags_set);
4960 } else {
4961 g_warning("can't select mailbox %s\n", item->path);
4964 if (!is_fatal(ok))
4965 unlock_session(session);
4967 g_slist_free(data->msglist);
4968 g_free(data->str);
4969 g_free(data);
4970 return TRUE;
4973 static void process_hashtable(IMAPFolderItem *item)
4975 if (item->flags_set_table) {
4976 g_hash_table_foreach_remove(item->flags_set_table, process_flags, GINT_TO_POINTER(TRUE));
4977 g_hash_table_destroy(item->flags_set_table);
4978 item->flags_set_table = NULL;
4980 if (item->flags_unset_table) {
4981 g_hash_table_foreach_remove(item->flags_unset_table, process_flags, GINT_TO_POINTER(FALSE));
4982 g_hash_table_destroy(item->flags_unset_table);
4983 item->flags_unset_table = NULL;
4985 if (item->tags_set_table) {
4986 g_hash_table_foreach_remove(item->tags_set_table, process_tags, GINT_TO_POINTER(TRUE));
4987 g_hash_table_destroy(item->tags_set_table);
4988 item->tags_set_table = NULL;
4990 if (item->tags_unset_table) {
4991 g_hash_table_foreach_remove(item->tags_unset_table, process_tags, GINT_TO_POINTER(FALSE));
4992 g_hash_table_destroy(item->tags_unset_table);
4993 item->tags_unset_table = NULL;
4998 static void imap_set_batch (Folder *folder, FolderItem *_item, gboolean batch)
5000 IMAPFolderItem *item = (IMAPFolderItem *)_item;
5001 IMAPSession *session;
5003 g_return_if_fail(item != NULL);
5005 if (item->batching == batch)
5006 return;
5008 if (batch) {
5009 item->batching = TRUE;
5010 debug_print("IMAP switching to batch mode\n");
5011 if (!item->flags_set_table) {
5012 item->flags_set_table = g_hash_table_new(NULL, g_direct_equal);
5014 if (!item->flags_unset_table) {
5015 item->flags_unset_table = g_hash_table_new(NULL, g_direct_equal);
5017 if (!item->tags_set_table) {
5018 item->tags_set_table = g_hash_table_new(NULL, g_direct_equal);
5020 if (!item->tags_unset_table) {
5021 item->tags_unset_table = g_hash_table_new(NULL, g_direct_equal);
5023 session = imap_session_get(folder);
5024 if (session) {
5025 imap_refresh_sensitivity(session);
5026 session->sens_update_block = TRUE;
5028 } else {
5029 debug_print("IMAP switching away from batch mode\n");
5030 /* process stuff */
5031 process_hashtable(item);
5032 item->batching = FALSE;
5033 session = imap_session_get(folder);
5034 if (session) {
5035 session->sens_update_block = FALSE;
5036 imap_refresh_sensitivity(session);
5043 /* data types conversion libetpan <-> claws */
5047 #define ETPAN_IMAP_MB_MARKED 1
5048 #define ETPAN_IMAP_MB_UNMARKED 2
5049 #define ETPAN_IMAP_MB_NOSELECT 4
5050 #define ETPAN_IMAP_MB_NOINFERIORS 8
5052 static int imap_flags_to_flags(struct mailimap_mbx_list_flags * imap_flags)
5054 int flags;
5055 clistiter * cur;
5057 flags = 0;
5058 if (imap_flags->mbf_type == MAILIMAP_MBX_LIST_FLAGS_SFLAG) {
5059 switch (imap_flags->mbf_sflag) {
5060 case MAILIMAP_MBX_LIST_SFLAG_MARKED:
5061 flags |= ETPAN_IMAP_MB_MARKED;
5062 break;
5063 case MAILIMAP_MBX_LIST_SFLAG_NOSELECT:
5064 flags |= ETPAN_IMAP_MB_NOSELECT;
5065 break;
5066 case MAILIMAP_MBX_LIST_SFLAG_UNMARKED:
5067 flags |= ETPAN_IMAP_MB_UNMARKED;
5068 break;
5072 if (imap_flags->mbf_oflags) {
5073 for(cur = clist_begin(imap_flags->mbf_oflags) ; cur != NULL ;
5074 cur = clist_next(cur)) {
5075 struct mailimap_mbx_list_oflag * oflag;
5077 oflag = clist_content(cur);
5079 switch (oflag->of_type) {
5080 case MAILIMAP_MBX_LIST_OFLAG_NOINFERIORS:
5081 flags |= ETPAN_IMAP_MB_NOINFERIORS;
5082 break;
5086 return flags;
5089 static GSList * imap_list_from_lep(IMAPFolder * folder,
5090 clist * list, const gchar * real_path, gboolean all)
5092 clistiter * iter;
5093 GSList * item_list = NULL, *llast = NULL;
5095 if (list) {
5096 for(iter = clist_begin(list) ; iter != NULL ;
5097 iter = clist_next(iter)) {
5098 struct mailimap_mailbox_list * mb;
5099 int flags;
5100 char delimiter;
5101 char * name;
5102 char * dup_name;
5103 gchar * base;
5104 gchar * loc_name;
5105 gchar * loc_path;
5106 FolderItem *new_item;
5108 mb = clist_content(iter);
5110 if (mb == NULL)
5111 continue;
5113 flags = 0;
5114 if (mb->mb_flag != NULL)
5115 flags = imap_flags_to_flags(mb->mb_flag);
5117 delimiter = mb->mb_delimiter;
5118 name = mb->mb_name;
5120 dup_name = strdup(name);
5121 if (delimiter != '\0')
5122 subst_char(dup_name, delimiter, '/');
5124 base = g_path_get_basename(dup_name);
5125 if (base[0] == '.') {
5126 g_free(base);
5127 free(dup_name);
5128 continue;
5130 if (!all && path_cmp(name, real_path) == 0) {
5131 g_free(base);
5132 free(dup_name);
5133 continue;
5136 if (!all && dup_name[strlen(dup_name)-1] == '/') {
5137 dup_name[strlen(dup_name)-1] = '\0';
5140 loc_name = imap_modified_utf7_to_utf8(base, FALSE);
5141 loc_path = imap_modified_utf7_to_utf8(dup_name, FALSE);
5143 new_item = folder_item_new(FOLDER(folder), loc_name, loc_path);
5144 if ((flags & ETPAN_IMAP_MB_NOINFERIORS) != 0)
5145 new_item->no_sub = TRUE;
5146 if (strcmp(dup_name, "INBOX") != 0 &&
5147 ((flags & ETPAN_IMAP_MB_NOSELECT) != 0))
5148 new_item->no_select = TRUE;
5150 if (item_list == NULL)
5151 llast = item_list = g_slist_append(item_list, new_item);
5152 else {
5153 llast = g_slist_append(llast, new_item);
5154 llast = llast->next;
5156 debug_print("folder '%s' found.\n", loc_path);
5157 g_free(base);
5158 g_free(loc_path);
5159 g_free(loc_name);
5161 free(dup_name);
5164 return item_list;
5167 static GSList * imap_get_lep_set_from_numlist(IMAPFolder *folder, MsgNumberList *numlist)
5169 GSList *sorted_list, *cur;
5170 guint first, last, next;
5171 GSList *ret_list = NULL, *llast = NULL;
5172 struct mailimap_set * current_set;
5173 unsigned int item_count;
5175 if (numlist == NULL)
5176 return NULL;
5178 current_set = mailimap_set_new_empty();
5180 sorted_list = g_slist_copy(numlist);
5181 sorted_list = g_slist_sort(sorted_list, g_int_compare);
5183 first = GPOINTER_TO_INT(sorted_list->data);
5185 item_count = 0;
5186 for (cur = sorted_list; cur != NULL; cur = g_slist_next(cur)) {
5187 if (GPOINTER_TO_INT(cur->data) == 0)
5188 continue;
5190 item_count ++;
5192 last = GPOINTER_TO_INT(cur->data);
5193 if (cur->next)
5194 next = GPOINTER_TO_INT(cur->next->data);
5195 else
5196 next = 0;
5198 if (last + 1 != next || next == 0 || item_count >= folder->max_set_size) {
5200 struct mailimap_set_item * item;
5201 item = mailimap_set_item_new(first, last);
5202 mailimap_set_add(current_set, item);
5204 first = next;
5206 if (item_count >= folder->max_set_size) {
5207 if (ret_list == NULL)
5208 llast = ret_list = g_slist_append(ret_list,
5209 current_set);
5210 else {
5211 llast = g_slist_append(llast, current_set);
5212 llast = llast->next;
5215 current_set = mailimap_set_new_empty();
5216 item_count = 0;
5221 if (clist_count(current_set->set_list) > 0) {
5222 ret_list = g_slist_append(ret_list,
5223 current_set);
5226 g_slist_free(sorted_list);
5228 return ret_list;
5231 static GSList * imap_get_lep_set_from_msglist(IMAPFolder *folder, MsgInfoList *msglist)
5233 MsgNumberList *numlist = NULL;
5234 MsgInfoList *cur;
5235 GSList *seq_list;
5237 for (cur = msglist; cur != NULL; cur = g_slist_next(cur)) {
5238 MsgInfo *msginfo = (MsgInfo *) cur->data;
5240 numlist = g_slist_prepend(numlist, GINT_TO_POINTER(msginfo->msgnum));
5242 numlist = g_slist_reverse(numlist);
5243 seq_list = imap_get_lep_set_from_numlist(folder, numlist);
5244 g_slist_free(numlist);
5246 return seq_list;
5249 static GSList * imap_uid_list_from_lep(clist * list)
5251 clistiter * iter;
5252 GSList * result;
5254 result = NULL;
5256 if (list) {
5257 for(iter = clist_begin(list) ; iter != NULL ;
5258 iter = clist_next(iter)) {
5259 uint32_t * puid;
5261 puid = clist_content(iter);
5262 result = g_slist_prepend(result, GINT_TO_POINTER(* puid));
5264 result = g_slist_reverse(result);
5266 return result;
5269 static GSList * imap_uid_list_from_lep_tab(carray * list)
5271 unsigned int i;
5272 GSList * result;
5274 result = NULL;
5276 for(i = 0 ; i < carray_count(list) ; i ++) {
5277 uint32_t * puid;
5279 puid = carray_get(list, i);
5280 result = g_slist_prepend(result, GINT_TO_POINTER(* puid));
5282 result = g_slist_reverse(result);
5283 return result;
5286 static void imap_flags_hash_from_lep_uid_flags_tab(carray * list,
5287 GHashTable * hash,
5288 GHashTable * tags_hash)
5290 unsigned int i;
5291 GSList * result;
5293 result = NULL;
5295 for(i = 0 ; i < carray_count(list) ; i += 3) {
5296 uint32_t * puid;
5297 int * pflags;
5298 GSList *tags;
5300 puid = carray_get(list, i);
5301 pflags = carray_get(list, i + 1);
5302 tags = carray_get(list, i + 2);
5304 g_hash_table_insert(hash, GINT_TO_POINTER(*puid), GINT_TO_POINTER(* pflags));
5305 g_hash_table_insert(tags_hash, GINT_TO_POINTER(*puid), tags);
5309 static MsgInfo *imap_envelope_from_lep(struct imap_fetch_env_info * info,
5310 FolderItem *item)
5312 MsgInfo *msginfo = NULL;
5313 guint32 uid = 0;
5314 goffset size = 0;
5315 MsgFlags flags = {0, 0};
5317 if (info->headers == NULL)
5318 return NULL;
5320 MSG_SET_TMP_FLAGS(flags, MSG_IMAP);
5321 if (folder_has_parent_of_type(item, F_QUEUE)) {
5322 MSG_SET_TMP_FLAGS(flags, MSG_QUEUED);
5323 } else if (folder_has_parent_of_type(item, F_DRAFT)) {
5324 MSG_SET_TMP_FLAGS(flags, MSG_DRAFT);
5326 flags.perm_flags = info->flags;
5328 uid = info->uid;
5329 size = (goffset) info->size;
5330 msginfo = procheader_parse_str(info->headers, flags, FALSE, FALSE);
5332 if (msginfo) {
5333 msginfo->msgnum = uid;
5334 msginfo->size = size;
5337 return msginfo;
5340 static void imap_lep_set_free(GSList *seq_list)
5342 GSList * cur;
5344 for(cur = seq_list ; cur != NULL ; cur = g_slist_next(cur)) {
5345 struct mailimap_set * imapset;
5347 imapset = cur->data;
5348 mailimap_set_free(imapset);
5350 g_slist_free(seq_list);
5353 static struct mailimap_flag_list * imap_flag_to_lep(IMAPFolderItem *item, IMAPFlags flags, GSList *tags)
5355 struct mailimap_flag_list * flag_list;
5356 GSList *cur = tags;
5358 flag_list = mailimap_flag_list_new_empty();
5360 if (IMAP_IS_SEEN(flags))
5361 mailimap_flag_list_add(flag_list,
5362 mailimap_flag_new_seen());
5363 if (IMAP_IS_ANSWERED(flags))
5364 mailimap_flag_list_add(flag_list,
5365 mailimap_flag_new_answered());
5366 if (IMAP_IS_FLAGGED(flags))
5367 mailimap_flag_list_add(flag_list,
5368 mailimap_flag_new_flagged());
5369 if (IMAP_IS_DELETED(flags))
5370 mailimap_flag_list_add(flag_list,
5371 mailimap_flag_new_deleted());
5372 if (IMAP_IS_DRAFT(flags))
5373 mailimap_flag_list_add(flag_list,
5374 mailimap_flag_new_draft());
5375 if (IMAP_IS_FORWARDED(flags) && flag_ok(item, IMAP_FLAG_FORWARDED))
5376 mailimap_flag_list_add(flag_list,
5377 mailimap_flag_new_flag_keyword(strdup("$Forwarded")));
5378 if (IMAP_IS_SPAM(flags) && flag_ok(item, IMAP_FLAG_SPAM))
5379 mailimap_flag_list_add(flag_list,
5380 mailimap_flag_new_flag_keyword(strdup("Junk")));
5381 else if (IMAP_IS_HAM(flags) && flag_ok(item, IMAP_FLAG_HAM))
5382 mailimap_flag_list_add(flag_list,
5383 mailimap_flag_new_flag_keyword(strdup("NonJunk")));
5385 for (; cur; cur = cur->next) {
5386 gchar *enc_str =
5387 imap_utf8_to_modified_utf7(cur->data, TRUE);
5388 g_strstrip(enc_str);
5390 mailimap_flag_list_add(flag_list,
5391 mailimap_flag_new_flag_keyword(enc_str));
5394 return flag_list;
5397 guint imap_folder_get_refcnt(Folder *folder)
5399 return ((IMAPFolder *)folder)->refcnt;
5402 void imap_folder_ref(Folder *folder)
5404 ((IMAPFolder *)folder)->refcnt++;
5407 void imap_disconnect_all(void)
5409 GList *list;
5410 gboolean short_timeout;
5411 #ifdef HAVE_NETWORKMANAGER_SUPPORT
5412 GError *error;
5413 #endif
5415 #ifdef HAVE_NETWORKMANAGER_SUPPORT
5416 error = NULL;
5417 short_timeout = !networkmanager_is_online(&error);
5418 if(error) {
5419 short_timeout = TRUE;
5420 g_error_free(error);
5422 #else
5423 short_timeout = TRUE;
5424 #endif
5426 if(short_timeout)
5427 imap_main_set_timeout(1);
5429 for (list = account_get_list(); list != NULL; list = list->next) {
5430 PrefsAccount *account = list->data;
5431 if (account->protocol == A_IMAP4) {
5432 RemoteFolder *folder = (RemoteFolder *)account->folder;
5433 if (folder && folder->session) {
5434 IMAPSession *session = (IMAPSession *)folder->session;
5435 imap_threaded_disconnect(FOLDER(folder));
5436 SESSION(session)->state = SESSION_DISCONNECTED;
5437 SESSION(session)->sock = NULL;
5438 session_destroy(SESSION(session));
5439 folder->session = NULL;
5444 if(short_timeout)
5445 imap_main_set_timeout(prefs_common.io_timeout_secs);
5448 void imap_folder_unref(Folder *folder)
5450 if (((IMAPFolder *)folder)->refcnt > 0)
5451 ((IMAPFolder *)folder)->refcnt--;
5454 void imap_cancel_all(void)
5456 GList *folderlist;
5457 GList *cur;
5459 folderlist = folder_get_list();
5460 for (cur = folderlist; cur != NULL; cur = g_list_next(cur)) {
5461 Folder *folder = (Folder *) cur->data;
5463 if (folder->klass == &imap_class) {
5464 if (imap_is_busy(folder)) {
5465 IMAPSession *imap_session;
5466 RemoteFolder *rfolder;
5468 g_printerr("cancelled\n");
5469 imap_threaded_cancel(folder);
5470 rfolder = (RemoteFolder *) folder;
5471 imap_session = (IMAPSession *) rfolder->session;
5472 if (imap_session)
5473 imap_session->cancelled = 1;
5479 gboolean imap_cancel_all_enabled(void)
5481 GList *folderlist;
5482 GList *cur;
5484 folderlist = folder_get_list();
5485 for (cur = folderlist; cur != NULL; cur = g_list_next(cur)) {
5486 Folder *folder = (Folder *) cur->data;
5488 if (folder->klass == &imap_class) {
5489 if (imap_is_busy(folder)) {
5490 return TRUE;
5495 return FALSE;
5498 static gboolean imap_is_busy(Folder *folder)
5500 IMAPSession *imap_session;
5501 RemoteFolder *rfolder;
5503 rfolder = (RemoteFolder *) folder;
5504 imap_session = (IMAPSession *) rfolder->session;
5505 if (imap_session == NULL)
5506 return FALSE;
5508 return imap_session->busy;
5511 #else /* HAVE_LIBETPAN */
5513 static FolderClass imap_class;
5515 static XMLTag *imap_item_get_xml(Folder *folder, FolderItem *item);
5516 static void imap_item_set_xml(Folder *folder, FolderItem *item, XMLTag *tag);
5518 static Folder *imap_folder_new (const gchar *name,
5519 const gchar *path)
5521 static gboolean missing_imap_warning = TRUE;
5522 if (missing_imap_warning) {
5523 missing_imap_warning = FALSE;
5524 alertpanel_error(
5525 _("You have one or more IMAP accounts "
5526 "defined. However this version of "
5527 "Claws Mail has been built without "
5528 "IMAP support; your IMAP account(s) are "
5529 "disabled.\n\n"
5530 "You probably need to "
5531 "install libetpan and recompile "
5532 "Claws Mail."));
5534 return NULL;
5536 static gint imap_create_tree (Folder *folder)
5538 return -1;
5540 static FolderItem *imap_create_folder (Folder *folder,
5541 FolderItem *parent,
5542 const gchar *name)
5544 return NULL;
5546 static gint imap_rename_folder (Folder *folder,
5547 FolderItem *item,
5548 const gchar *name)
5550 return -1;
5553 gchar imap_get_path_separator_for_item(FolderItem *item)
5555 return '/';
5558 FolderClass *imap_get_class(void)
5560 if (imap_class.idstr == NULL) {
5561 imap_class.type = F_IMAP;
5562 imap_class.idstr = "imap";
5563 imap_class.uistr = "IMAP4";
5565 imap_class.new_folder = imap_folder_new;
5566 imap_class.create_tree = imap_create_tree;
5567 imap_class.create_folder = imap_create_folder;
5568 imap_class.rename_folder = imap_rename_folder;
5570 imap_class.set_xml = folder_set_xml;
5571 imap_class.get_xml = folder_get_xml;
5572 imap_class.item_set_xml = imap_item_set_xml;
5573 imap_class.item_get_xml = imap_item_get_xml;
5574 /* nothing implemented */
5577 return &imap_class;
5580 void imap_disconnect_all(void)
5584 gint imap_subscribe(Folder *folder, FolderItem *item, gchar *rpath, gboolean sub)
5586 return -1;
5589 GList * imap_scan_subtree(Folder *folder, FolderItem *item, gboolean unsubs_only, gboolean recursive)
5591 return NULL;
5594 void imap_cache_msg(FolderItem *item, gint msgnum)
5598 void imap_cancel_all(void)
5602 gboolean imap_cancel_all_enabled(void)
5604 return FALSE;
5607 #endif
5609 #ifdef HAVE_LIBETPAN
5610 static void imap_synchronise(FolderItem *item, gint days)
5612 if (IMAP_FOLDER_ITEM(item)->last_sync == IMAP_FOLDER_ITEM(item)->last_change) {
5613 debug_print("%s already synced\n", item->path?item->path:item->name);
5614 return;
5616 debug_print("syncing %s\n", item->path?item->path:item->name);
5617 imap_gtk_synchronise(item, days);
5618 IMAP_FOLDER_ITEM(item)->last_sync = IMAP_FOLDER_ITEM(item)->last_change;
5620 #endif
5622 static void imap_item_set_xml(Folder *folder, FolderItem *item, XMLTag *tag)
5624 #ifdef HAVE_LIBETPAN
5625 GList *cur;
5626 #endif
5627 folder_item_set_xml(folder, item, tag);
5629 #ifdef HAVE_LIBETPAN
5630 for (cur = tag->attr; cur != NULL; cur = g_list_next(cur)) {
5631 XMLAttr *attr = (XMLAttr *) cur->data;
5633 if (!attr || !attr->name || !attr->value) continue;
5634 if (!strcmp(attr->name, "uidnext"))
5635 IMAP_FOLDER_ITEM(item)->uid_next = atoi(attr->value);
5636 if (!strcmp(attr->name, "last_sync"))
5637 IMAP_FOLDER_ITEM(item)->last_sync = atoi(attr->value);
5638 if (!strcmp(attr->name, "last_change"))
5639 IMAP_FOLDER_ITEM(item)->last_change = atoi(attr->value);
5641 if (IMAP_FOLDER_ITEM(item)->last_change == 0)
5642 IMAP_FOLDER_ITEM(item)->last_change = time(NULL);
5643 #endif
5646 static XMLTag *imap_item_get_xml(Folder *folder, FolderItem *item)
5648 XMLTag *tag;
5650 tag = folder_item_get_xml(folder, item);
5652 #ifdef HAVE_LIBETPAN
5653 xml_tag_add_attr(tag, xml_attr_new_int("uidnext",
5654 IMAP_FOLDER_ITEM(item)->uid_next));
5655 xml_tag_add_attr(tag, xml_attr_new_int("last_sync",
5656 IMAP_FOLDER_ITEM(item)->last_sync));
5657 xml_tag_add_attr(tag, xml_attr_new_int("last_change",
5658 IMAP_FOLDER_ITEM(item)->last_change));
5660 #endif
5661 return tag;
5664 /* ===================================================================
5665 * UTF-7 conversion routines as in RFC 2192
5666 * ===================================================================
5667 * These two functions from:
5668 * libimap library.
5669 * Copyright (C) 2003-2004 Pawel Salek. */
5671 /* UTF7 modified base64 alphabet */
5672 static char base64chars[] =
5673 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+,";
5674 #define UNDEFINED 64
5676 /* UTF16 definitions */
5677 #define UTF16MASK 0x03FFUL
5678 #define UTF16SHIFT 10
5679 #define UTF16BASE 0x10000UL
5680 #define UTF16HIGHSTART 0xD800UL
5681 #define UTF16HIGHEND 0xDBFFUL
5682 #define UTF16LOSTART 0xDC00UL
5683 #define UTF16LOEND 0xDFFFUL
5686 /* Convert an IMAP mailbox to a UTF-8 string.
5687 * dst needs to have roughly 4 times the storage space of src
5688 * Hex encoding can triple the size of the input
5689 * UTF-7 can be slightly denser than UTF-8
5690 * (worst case: 8 octets UTF-7 becomes 9 octets UTF-8)
5692 char* imap_modified_utf7_to_utf8(const char *mbox, gboolean change_spaces)
5694 unsigned c, i, bitcount;
5695 unsigned long ucs4, utf16, bitbuf;
5696 unsigned char base64[256];
5697 const char *src;
5698 char *dst, *res = malloc(2*strlen(mbox)+1);
5700 bitbuf = 0;
5701 dst = res;
5702 src = mbox;
5703 if(!dst) return NULL;
5704 /* initialize modified base64 decoding table */
5705 memset(base64, UNDEFINED, sizeof (base64));
5706 for (i = 0; i < sizeof (base64chars); ++i) {
5707 base64[(unsigned)base64chars[i]] = i;
5710 /* loop until end of string */
5711 while (*src != '\0') {
5712 c = *src++;
5713 /* deal with literal characters and &- */
5714 if (c != '&' || *src == '-') {
5715 /* encode literally */
5716 if (change_spaces && c == '_')
5717 *dst++ = ' ';
5718 else
5719 *dst++ = c;
5720 /* skip over the '-' if this is an &- sequence */
5721 if (c == '&') ++src;
5722 } else {
5723 /* convert modified UTF-7 -> UTF-16 -> UCS-4 -> UTF-8 -> HEX */
5724 bitbuf = 0;
5725 bitcount = 0;
5726 ucs4 = 0;
5727 while ((c = base64[(unsigned char) *src]) != UNDEFINED) {
5728 ++src;
5729 bitbuf = (bitbuf << 6) | c;
5730 bitcount += 6;
5731 /* enough bits for a UTF-16 character? */
5732 if (bitcount >= 16) {
5733 bitcount -= 16;
5734 utf16 = (bitcount ? bitbuf >> bitcount
5735 : bitbuf) & 0xffff;
5736 /* convert UTF16 to UCS4 */
5738 (utf16 >= UTF16HIGHSTART && utf16 <= UTF16HIGHEND) {
5739 ucs4 = (utf16 - UTF16HIGHSTART) << UTF16SHIFT;
5740 continue;
5741 } else if
5742 (utf16 >= UTF16LOSTART && utf16 <= UTF16LOEND) {
5743 ucs4 += utf16 - UTF16LOSTART + UTF16BASE;
5744 } else {
5745 ucs4 = utf16;
5748 /* convert UTF-16 range of UCS4 to UTF-8 */
5749 if (ucs4 <= 0x7fUL) {
5750 dst[0] = ucs4;
5751 dst += 1;
5752 } else if (ucs4 <= 0x7ffUL) {
5753 dst[0] = 0xc0 | (ucs4 >> 6);
5754 dst[1] = 0x80 | (ucs4 & 0x3f);
5755 dst += 2;
5756 } else if (ucs4 <= 0xffffUL) {
5757 dst[0] = 0xe0 | (ucs4 >> 12);
5758 dst[1] = 0x80 | ((ucs4 >> 6) & 0x3f);
5759 dst[2] = 0x80 | (ucs4 & 0x3f);
5760 dst += 3;
5761 } else {
5762 dst[0] = 0xf0 | (ucs4 >> 18);
5763 dst[1] = 0x80 | ((ucs4 >> 12) & 0x3f);
5764 dst[2] = 0x80 | ((ucs4 >> 6) & 0x3f);
5765 dst[3] = 0x80 | (ucs4 & 0x3f);
5766 dst += 4;
5770 /* skip over trailing '-' in modified UTF-7 encoding */
5771 if (*src == '-') ++src;
5774 /* terminate destination string */
5775 *dst = '\0';
5776 return res;
5779 /* Convert hex coded UTF-8 string to modified UTF-7 IMAP mailbox
5780 * dst should be about twice the length of src to deal with non-hex
5781 * coded URLs
5783 char* imap_utf8_to_modified_utf7(const char *src, gboolean change_spaces)
5785 unsigned int utf8pos, utf8total, c, utf7mode, bitstogo, utf16flag;
5786 unsigned long ucs4 = 0, bitbuf = 0;
5788 /* initialize hex lookup table */
5789 char *dst, *res;
5791 if (!src) return NULL;
5793 res = malloc(2*strlen(src)+1);
5794 dst = res;
5795 if(!dst) return NULL;
5797 utf7mode = 0;
5798 utf8total = 0;
5799 bitstogo = 0;
5800 utf8pos = 0;
5801 while ((c = (unsigned char)*src) != '\0') {
5802 ++src;
5803 /* normal character? */
5804 if (c >= ' ' && c <= '~' && (c != '_' || !change_spaces)) {
5805 /* switch out of UTF-7 mode */
5806 if (utf7mode) {
5807 if (bitstogo) {
5808 *dst++ = base64chars[(bitbuf << (6 - bitstogo)) & 0x3F];
5810 *dst++ = '-';
5811 utf7mode = 0;
5812 utf8pos = 0;
5813 bitstogo = 0;
5814 utf8total= 0;
5816 if (change_spaces && c == ' ')
5817 *dst++ = '_';
5818 else
5819 *dst++ = c;
5820 /* encode '&' as '&-' */
5821 if (c == '&') {
5822 *dst++ = '-';
5824 continue;
5826 /* switch to UTF-7 mode */
5827 if (!utf7mode) {
5828 *dst++ = '&';
5829 utf7mode = 1;
5831 /* Encode US-ASCII characters as themselves */
5832 if (c < 0x80) {
5833 ucs4 = c;
5834 utf8total = 1;
5835 } else if (utf8total) {
5836 /* save UTF8 bits into UCS4 */
5837 ucs4 = (ucs4 << 6) | (c & 0x3FUL);
5838 if (++utf8pos < utf8total) {
5839 continue;
5841 } else {
5842 utf8pos = 1;
5843 if (c < 0xE0) {
5844 utf8total = 2;
5845 ucs4 = c & 0x1F;
5846 } else if (c < 0xF0) {
5847 utf8total = 3;
5848 ucs4 = c & 0x0F;
5849 } else {
5850 /* NOTE: can't convert UTF8 sequences longer than 4 */
5851 utf8total = 4;
5852 ucs4 = c & 0x03;
5854 continue;
5856 /* loop to split ucs4 into two utf16 chars if necessary */
5857 utf8total = 0;
5858 do {
5859 if (ucs4 >= UTF16BASE) {
5860 ucs4 -= UTF16BASE;
5861 bitbuf = (bitbuf << 16) | ((ucs4 >> UTF16SHIFT)
5862 + UTF16HIGHSTART);
5863 ucs4 = (ucs4 & UTF16MASK) + UTF16LOSTART;
5864 utf16flag = 1;
5865 } else {
5866 bitbuf = (bitbuf << 16) | ucs4;
5867 utf16flag = 0;
5869 bitstogo += 16;
5870 /* spew out base64 */
5871 while (bitstogo >= 6) {
5872 bitstogo -= 6;
5873 *dst++ = base64chars[(bitstogo ? (bitbuf >> bitstogo)
5874 : bitbuf)
5875 & 0x3F];
5877 } while (utf16flag);
5879 /* if in UTF-7 mode, finish in ASCII */
5880 if (utf7mode) {
5881 if (bitstogo) {
5882 *dst++ = base64chars[(bitbuf << (6 - bitstogo)) & 0x3F];
5884 *dst++ = '-';
5886 /* tie off string */
5887 *dst = '\0';
5888 return res;