0762e1d2929fbc8cecb4027bb629cd3f8bf9c2e8
[claws.git] / src / imap.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2007 Hiroyuki Yamamoto and the Claws Mail team
4  *
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.
9  *
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.
14  *
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/>.
17  * 
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #include "defs.h"
25
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"
35
36 #ifdef HAVE_LIBETPAN
37
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
47
48 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
49 #  include "ssl.h"
50 #endif
51
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"
74
75 typedef struct _IMAPFolder      IMAPFolder;
76 typedef struct _IMAPSession     IMAPSession;
77 typedef struct _IMAPNameSpace   IMAPNameSpace;
78 typedef struct _IMAPFolderItem  IMAPFolderItem;
79
80 #include "prefs_account.h"
81
82 #define IMAP_FOLDER(obj)        ((IMAPFolder *)obj)
83 #define IMAP_FOLDER_ITEM(obj)   ((IMAPFolderItem *)obj)
84 #define IMAP_SESSION(obj)       ((IMAPSession *)obj)
85
86 struct _IMAPFolder
87 {
88         RemoteFolder rfolder;
89
90         /* list of IMAPNameSpace */
91         GList *ns_personal;
92         GList *ns_others;
93         GList *ns_shared;
94         gchar last_seen_separator;
95         guint refcnt;
96         guint max_set_size;
97 };
98
99 struct _IMAPSession
100 {
101         Session session;
102
103         gboolean authenticated;
104
105         GSList *capability;
106         gboolean uidplus;
107
108         gchar *mbox;
109         guint cmd_count;
110
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;
119
120         Folder * folder;
121         gboolean busy;
122         gboolean cancelled;
123         gboolean sens_update_block;
124 };
125
126 struct _IMAPNameSpace
127 {
128         gchar *name;
129         gchar separator;
130 };
131
132 #define IMAPBUFSIZE     8192
133
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
141
142 #define IMAP4_PORT      143
143 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
144 #define IMAPS_PORT      993
145 #endif
146
147 #define IMAP_CMD_LIMIT  1000
148
149 enum {
150         ITEM_CAN_CREATE_FLAGS_UNKNOWN = 0,
151         ITEM_CAN_CREATE_FLAGS,
152         ITEM_CANNOT_CREATE_FLAGS
153 };
154
155 struct _IMAPFolderItem
156 {
157         FolderItem item;
158
159         guint lastuid;
160         guint uid_next;
161         GSList *uid_list;
162         gboolean batching;
163
164         GHashTable *flags_set_table;
165         GHashTable *flags_unset_table;
166         guint32 last_change;
167         guint32 last_sync;
168         gboolean should_update;
169         gboolean should_trash_cache;
170         gint can_create_flags;
171
172         GHashTable *tags_set_table;
173         GHashTable *tags_unset_table;
174         GSList *ok_flags;
175
176 };
177
178 static XMLTag *imap_item_get_xml(Folder *folder, FolderItem *item);
179 static void imap_item_set_xml(Folder *folder, FolderItem *item, XMLTag *tag);
180
181 static void imap_folder_init            (Folder         *folder,
182                                          const gchar    *name,
183                                          const gchar    *path);
184
185 static Folder   *imap_folder_new        (const gchar    *name,
186                                          const gchar    *path);
187 static void      imap_folder_destroy    (Folder         *folder);
188
189 static IMAPSession *imap_session_new    (Folder         *folder,
190                                          const PrefsAccount     *account);
191 static void     imap_session_authenticate(IMAPSession           *session,
192                                           const PrefsAccount    *account);
193 static void     imap_session_destroy    (Session        *session);
194
195 static gchar   *imap_fetch_msg          (Folder         *folder, 
196                                          FolderItem     *item, 
197                                          gint            uid);
198 static gchar   *imap_fetch_msg_full     (Folder         *folder, 
199                                          FolderItem     *item, 
200                                          gint            uid,
201                                          gboolean        headers,
202                                          gboolean        body);
203 static void     imap_remove_cached_msg  (Folder         *folder, 
204                                          FolderItem     *item, 
205                                          MsgInfo        *msginfo);
206 static gint     imap_add_msg            (Folder         *folder,
207                                          FolderItem     *dest,
208                                          const gchar    *file, 
209                                          MsgFlags       *flags);
210 static gint     imap_add_msgs           (Folder         *folder, 
211                                          FolderItem     *dest,
212                                          GSList         *file_list,
213                                          GRelation      *relation);
214
215 static gint     imap_copy_msg           (Folder         *folder,
216                                          FolderItem     *dest, 
217                                          MsgInfo        *msginfo);
218 static gint     imap_copy_msgs          (Folder         *folder, 
219                                          FolderItem     *dest, 
220                                          MsgInfoList    *msglist, 
221                                          GRelation      *relation);
222
223 static gint     imap_remove_msg         (Folder         *folder, 
224                                          FolderItem     *item, 
225                                          gint            uid);
226 static gint     imap_remove_msgs        (Folder         *folder, 
227                                          FolderItem     *dest, 
228                                          MsgInfoList    *msglist, 
229                                          GRelation      *relation);
230 static gint     imap_remove_all_msg     (Folder         *folder, 
231                                          FolderItem     *item);
232
233 static gboolean imap_is_msg_changed     (Folder         *folder,
234                                          FolderItem     *item, 
235                                          MsgInfo        *msginfo);
236
237 static gint     imap_close              (Folder         *folder, 
238                                          FolderItem     *item);
239
240 static gint     imap_scan_tree          (Folder         *folder);
241
242 static gint     imap_create_tree        (Folder         *folder);
243
244 static FolderItem *imap_create_folder   (Folder         *folder,
245                                          FolderItem     *parent,
246                                          const gchar    *name);
247 static gint     imap_rename_folder      (Folder         *folder,
248                                          FolderItem     *item, 
249                                          const gchar    *name);
250 static gint     imap_remove_folder      (Folder         *folder, 
251                                          FolderItem     *item);
252
253 static FolderItem *imap_folder_item_new (Folder         *folder);
254 static void imap_folder_item_destroy    (Folder         *folder,
255                                          FolderItem     *item);
256
257 static IMAPSession *imap_session_get    (Folder         *folder);
258
259 static gint imap_auth                   (IMAPSession    *session,
260                                          const gchar    *user,
261                                          const gchar    *pass,
262                                          IMAPAuthType    type);
263
264 static gint imap_scan_tree_recursive    (IMAPSession    *session,
265                                          FolderItem     *item,
266                                          gboolean        subs_only);
267
268 static void imap_create_missing_folders (Folder         *folder);
269 static FolderItem *imap_create_special_folder
270                                         (Folder                 *folder,
271                                          SpecialFolderItemType   stype,
272                                          const gchar            *name);
273
274 static gint imap_do_copy_msgs           (Folder         *folder,
275                                          FolderItem     *dest,
276                                          MsgInfoList    *msglist,
277                                          GRelation      *relation);
278
279 static void imap_delete_all_cached_messages     (FolderItem     *item);
280 static void imap_set_batch              (Folder         *folder,
281                                          FolderItem     *item,
282                                          gboolean        batch);
283 static gint imap_set_message_flags      (IMAPSession    *session,
284                                          IMAPFolderItem *item,
285                                          MsgNumberList  *numlist,
286                                          IMAPFlags       flags,
287                                          GSList         *tags,
288                                          gboolean        is_set);
289 static gint imap_select                 (IMAPSession    *session,
290                                          IMAPFolder     *folder,
291                                          FolderItem     *item,
292                                          gint           *exists,
293                                          gint           *recent,
294                                          gint           *unseen,
295                                          guint32        *uid_validity,
296                                          gint           *can_create_flags,
297                                          gboolean        block);
298 static gint imap_status                 (IMAPSession    *session,
299                                          IMAPFolder     *folder,
300                                          const gchar    *path,
301                                          IMAPFolderItem *item,
302                                          gint           *messages,
303                                          guint32        *uid_next,
304                                          guint32        *uid_validity,
305                                          gint           *unseen,
306                                          gboolean        block);
307 static void     imap_commit_tags        (FolderItem     *item, 
308                                          MsgInfo        *msginfo,
309                                          GSList         *set_tags,
310                                          GSList         *unset_tags);
311
312 static gchar imap_get_path_separator            (IMAPSession    *session,
313                                                  IMAPFolder     *folder,
314                                                  const gchar    *path);
315 static gchar *imap_get_real_path                (IMAPSession    *session,
316                                                  IMAPFolder     *folder,
317                                                  const gchar    *path);
318 #ifdef HAVE_LIBETPAN
319 static void imap_synchronise            (FolderItem     *item, gint days);
320 #endif
321 static gboolean imap_is_busy            (Folder *folder);
322
323 static void imap_free_capabilities      (IMAPSession    *session);
324
325 /* low-level IMAP4rev1 commands */
326 static gint imap_cmd_login      (IMAPSession    *session,
327                                  const gchar    *user,
328                                  const gchar    *pass,
329                                  const gchar    *type);
330 static gint imap_cmd_noop       (IMAPSession    *session);
331 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
332 static gint imap_cmd_starttls   (IMAPSession    *session);
333 #endif
334 static gint imap_cmd_select     (IMAPSession    *session,
335                                  const gchar    *folder,
336                                  gint           *exists,
337                                  gint           *recent,
338                                  gint           *unseen,
339                                  guint32        *uid_validity,
340                                  gint           *can_create_flags,
341                                  GSList         **ok_flags,
342                                  gboolean        block);
343 static gint imap_cmd_close      (IMAPSession    *session);
344 static gint imap_cmd_examine    (IMAPSession    *session,
345                                  const gchar    *folder,
346                                  gint           *exists,
347                                  gint           *recent,
348                                  gint           *unseen,
349                                  guint32        *uid_validity,
350                                  gboolean        block);
351 static gint imap_cmd_create     (IMAPSession    *sock,
352                                  const gchar    *folder);
353 static gint imap_cmd_rename     (IMAPSession    *sock,
354                                  const gchar    *oldfolder,
355                                  const gchar    *newfolder);
356 static gint imap_cmd_delete     (IMAPSession    *session,
357                                  const gchar    *folder);
358 static gint imap_cmd_fetch      (IMAPSession    *sock,
359                                  guint32         uid,
360                                  const gchar    *filename,
361                                  gboolean        headers,
362                                  gboolean        body);
363 static gint imap_cmd_append     (IMAPSession    *session,
364                                  IMAPFolderItem *item,
365                                  const gchar    *destfolder,
366                                  const gchar    *file,
367                                  IMAPFlags       flags,
368                                  guint32        *new_uid);
369 static gint imap_cmd_copy       (IMAPSession *session,
370                                  struct mailimap_set * set,
371                                  const gchar *destfolder,
372                                  GRelation *uid_mapping,
373                                  struct mailimap_set ** source,
374                                  struct mailimap_set ** dest);
375 static gint imap_cmd_store      (IMAPSession    *session,
376                                  IMAPFolderItem *item,
377                                  struct mailimap_set * set,
378                                  IMAPFlags flags,
379                                  GSList *tags,
380                                  int do_add);
381 static gint imap_cmd_expunge    (IMAPSession    *session);
382
383 static void imap_path_separator_subst           (gchar          *str,
384                                                  gchar           separator);
385
386 static gboolean imap_rename_folder_func         (GNode          *node,
387                                                  gpointer        data);
388 static gint imap_get_num_list                   (Folder         *folder,
389                                                  FolderItem     *item,
390                                                  GSList        **list,
391                                                  gboolean       *old_uids_valid);
392 static GSList *imap_get_msginfos                (Folder         *folder,
393                                                  FolderItem     *item,
394                                                  GSList         *msgnum_list);
395 static MsgInfo *imap_get_msginfo                (Folder         *folder,
396                                                  FolderItem     *item,
397                                                  gint            num);
398 static gboolean imap_scan_required              (Folder         *folder,
399                                                  FolderItem     *item);
400 static void imap_change_flags                   (Folder         *folder,
401                                                  FolderItem     *item,
402                                                  MsgInfo        *msginfo,
403                                                  MsgPermFlags    newflags);
404 static gint imap_get_flags                      (Folder         *folder,
405                                                  FolderItem     *item,
406                                                  MsgInfoList    *msglist,
407                                                  GRelation      *msgflags);
408 static gchar *imap_folder_get_path              (Folder         *folder);
409 static gchar *imap_item_get_path                (Folder         *folder,
410                                                  FolderItem     *item);
411 static MsgInfo *imap_parse_msg(const gchar *file, FolderItem *item);
412
413
414 /* data types conversion libetpan <-> claws */
415 static GSList * imap_list_from_lep(IMAPFolder * folder,
416                                    clist * list, const gchar * real_path, gboolean all);
417 static GSList * imap_get_lep_set_from_numlist(IMAPFolder *folder, MsgNumberList *numlist);
418 static GSList * imap_get_lep_set_from_msglist(IMAPFolder *folder, MsgInfoList *msglist);
419 static GSList * imap_uid_list_from_lep(clist * list);
420 static GSList * imap_uid_list_from_lep_tab(carray * list);
421 static void imap_flags_hash_from_lep_uid_flags_tab(carray * list,
422                                                    GHashTable * hash,
423                                                    GHashTable *tags_hash);
424 static MsgInfo *imap_envelope_from_lep(struct imap_fetch_env_info * info,
425                                        FolderItem *item);
426 static void imap_lep_set_free(GSList *seq_list);
427 static struct mailimap_flag_list * imap_flag_to_lep(IMAPFolderItem *item, IMAPFlags flags, GSList *tags);
428
429 typedef struct _hashtable_data {
430         GSList *msglist;
431         IMAPFolderItem *item;
432 } hashtable_data;
433
434 static FolderClass imap_class;
435
436 FolderClass *imap_get_class(void)
437 {
438         if (imap_class.idstr == NULL) {
439                 imap_class.type = F_IMAP;
440                 imap_class.idstr = "imap";
441                 imap_class.uistr = "IMAP4";
442
443                 /* Folder functions */
444                 imap_class.new_folder = imap_folder_new;
445                 imap_class.destroy_folder = imap_folder_destroy;
446                 imap_class.scan_tree = imap_scan_tree;
447                 imap_class.create_tree = imap_create_tree;
448
449                 /* FolderItem functions */
450                 imap_class.item_new = imap_folder_item_new;
451                 imap_class.item_destroy = imap_folder_item_destroy;
452                 imap_class.item_get_path = imap_item_get_path;
453                 imap_class.create_folder = imap_create_folder;
454                 imap_class.rename_folder = imap_rename_folder;
455                 imap_class.remove_folder = imap_remove_folder;
456                 imap_class.close = imap_close;
457                 imap_class.get_num_list = imap_get_num_list;
458                 imap_class.scan_required = imap_scan_required;
459                 imap_class.set_xml = folder_set_xml;
460                 imap_class.get_xml = folder_get_xml;
461                 imap_class.item_set_xml = imap_item_set_xml;
462                 imap_class.item_get_xml = imap_item_get_xml;
463
464                 /* Message functions */
465                 imap_class.get_msginfo = imap_get_msginfo;
466                 imap_class.get_msginfos = imap_get_msginfos;
467                 imap_class.fetch_msg = imap_fetch_msg;
468                 imap_class.fetch_msg_full = imap_fetch_msg_full;
469                 imap_class.add_msg = imap_add_msg;
470                 imap_class.add_msgs = imap_add_msgs;
471                 imap_class.copy_msg = imap_copy_msg;
472                 imap_class.copy_msgs = imap_copy_msgs;
473                 imap_class.remove_msg = imap_remove_msg;
474                 imap_class.remove_msgs = imap_remove_msgs;
475                 imap_class.remove_all_msg = imap_remove_all_msg;
476                 imap_class.is_msg_changed = imap_is_msg_changed;
477                 imap_class.change_flags = imap_change_flags;
478                 imap_class.get_flags = imap_get_flags;
479                 imap_class.set_batch = imap_set_batch;
480                 imap_class.synchronise = imap_synchronise;
481                 imap_class.remove_cached_msg = imap_remove_cached_msg;
482                 imap_class.commit_tags = imap_commit_tags;
483 #ifdef USE_PTREAD
484                 pthread_mutex_init(&imap_mutex, NULL);
485 #endif
486         }
487         
488         return &imap_class;
489 }
490
491 static void imap_refresh_sensitivity (IMAPSession *session)
492 {
493         MainWindow *mainwin;
494
495         if (session->sens_update_block)
496                 return;
497         mainwin = mainwindow_get_mainwindow();
498         if (mainwin) {
499                 toolbar_main_set_sensitive(mainwin);
500                 main_window_set_menu_sensitive(mainwin);
501         }
502 }
503
504 static void lock_session(IMAPSession *session)
505 {
506         if (session) {
507                 debug_print("locking session %p (%d)\n", session, session->busy);
508                 if (session->busy)
509                         debug_print("         SESSION WAS LOCKED !!      \n");
510                 session->busy = TRUE;
511                 imap_refresh_sensitivity(session);
512         } else {
513                 debug_print("can't lock null session\n");
514         }
515 }
516
517 static void unlock_session(IMAPSession *session)
518 {
519         if (session) {
520                 debug_print("unlocking session %p\n", session);
521                 session->busy = FALSE;
522                 imap_refresh_sensitivity(session);
523         } else {
524                 debug_print("can't unlock null session\n");
525         }
526 }
527
528 static void imap_disc_session_destroy(IMAPSession *session)
529 {
530         RemoteFolder *rfolder = REMOTE_FOLDER(IMAP_SESSION(session)->folder);
531         
532         if (!rfolder)
533                 return;
534         if (!session)
535                 return;
536         rfolder->session = NULL;
537         log_warning(LOG_PROTOCOL, _("IMAP4 connection broken\n"));
538         SESSION(session)->state = SESSION_DISCONNECTED;
539         SESSION(session)->sock = NULL;
540         session_destroy(SESSION(session));
541 }
542
543 static gboolean is_fatal(int libetpan_errcode)
544 {
545         switch(libetpan_errcode) {
546         case MAILIMAP_ERROR_STREAM:
547         case MAILIMAP_ERROR_PROTOCOL:
548         case MAILIMAP_ERROR_PARSE:
549         case MAILIMAP_ERROR_BAD_STATE:
550                 return TRUE;
551         default:
552                 return FALSE;
553         }
554 }
555
556 static void imap_handle_error(Session *session, int libetpan_errcode)
557 {
558         switch(libetpan_errcode) {
559         case MAILIMAP_NO_ERROR:
560                 return;
561         case MAILIMAP_NO_ERROR_AUTHENTICATED:
562                 log_warning(LOG_PROTOCOL, _("IMAP error: authenticated\n"));
563                 break;
564         case MAILIMAP_NO_ERROR_NON_AUTHENTICATED:
565                 log_warning(LOG_PROTOCOL, _("IMAP error: not authenticated\n"));
566                 break;
567         case MAILIMAP_ERROR_BAD_STATE:
568                 log_warning(LOG_PROTOCOL, _("IMAP error: bad state\n"));
569                 break;
570         case MAILIMAP_ERROR_STREAM:
571                 log_warning(LOG_PROTOCOL, _("IMAP error: stream error\n"));
572                 break;
573         case MAILIMAP_ERROR_PARSE:
574                 log_warning(LOG_PROTOCOL, _("IMAP error: parse error "
575                                             "(very probably non-RFC compliance from the server)\n"));
576                 break;
577         case MAILIMAP_ERROR_CONNECTION_REFUSED:
578                 log_warning(LOG_PROTOCOL, _("IMAP error: connection refused\n"));
579                 break;
580         case MAILIMAP_ERROR_MEMORY:
581                 log_warning(LOG_PROTOCOL, _("IMAP error: memory error\n"));
582                 break;
583         case MAILIMAP_ERROR_FATAL:
584                 log_warning(LOG_PROTOCOL, _("IMAP error: fatal error\n"));
585                 break;
586         case MAILIMAP_ERROR_PROTOCOL:
587                 log_warning(LOG_PROTOCOL, _("IMAP error: protocol error"
588                                             "(very probably non-RFC compliance from the server)\n"));
589                 break;
590         case MAILIMAP_ERROR_DONT_ACCEPT_CONNECTION:
591                 log_warning(LOG_PROTOCOL, _("IMAP error: connection not accepted\n"));
592                 break;
593         case MAILIMAP_ERROR_APPEND:
594                 log_warning(LOG_PROTOCOL, _("IMAP error: APPEND error\n"));
595                 break;
596         case MAILIMAP_ERROR_NOOP:
597                 log_warning(LOG_PROTOCOL, _("IMAP error: NOOP error\n"));
598                 break;
599         case MAILIMAP_ERROR_LOGOUT:
600                 log_warning(LOG_PROTOCOL, _("IMAP error: LOGOUT error\n"));
601                 break;
602         case MAILIMAP_ERROR_CAPABILITY:
603                 log_warning(LOG_PROTOCOL, _("IMAP error: CAPABILITY error\n"));
604                 break;
605         case MAILIMAP_ERROR_CHECK:
606                 log_warning(LOG_PROTOCOL, _("IMAP error: CHECK error\n"));
607                 break;
608         case MAILIMAP_ERROR_CLOSE:
609                 log_warning(LOG_PROTOCOL, _("IMAP error: CLOSE error\n"));
610                 break;
611         case MAILIMAP_ERROR_EXPUNGE:
612                 log_warning(LOG_PROTOCOL, _("IMAP error: EXPUNGE error\n"));
613                 break;
614         case MAILIMAP_ERROR_COPY:
615                 log_warning(LOG_PROTOCOL, _("IMAP error: COPY error\n"));
616                 break;
617         case MAILIMAP_ERROR_UID_COPY:
618                 log_warning(LOG_PROTOCOL, _("IMAP error: UID COPY error\n"));
619                 break;
620         case MAILIMAP_ERROR_CREATE:
621                 log_warning(LOG_PROTOCOL, _("IMAP error: CREATE error\n"));
622                 break;
623         case MAILIMAP_ERROR_DELETE:
624                 log_warning(LOG_PROTOCOL, _("IMAP error: DELETE error\n"));
625                 break;
626         case MAILIMAP_ERROR_EXAMINE:
627                 log_warning(LOG_PROTOCOL, _("IMAP error: EXAMINE error\n"));
628                 break;
629         case MAILIMAP_ERROR_FETCH:
630                 log_warning(LOG_PROTOCOL, _("IMAP error: FETCH error\n"));
631                 break;
632         case MAILIMAP_ERROR_UID_FETCH:
633                 log_warning(LOG_PROTOCOL, _("IMAP error: UID FETCH error\n"));
634                 break;
635         case MAILIMAP_ERROR_LIST:
636                 log_warning(LOG_PROTOCOL, _("IMAP error: LIST error\n"));
637                 break;
638         case MAILIMAP_ERROR_LOGIN:
639                 log_warning(LOG_PROTOCOL, _("IMAP error: LOGIN error\n"));
640                 break;
641         case MAILIMAP_ERROR_LSUB:
642                 log_warning(LOG_PROTOCOL, _("IMAP error: LSUB error\n"));
643                 break;
644         case MAILIMAP_ERROR_RENAME:
645                 log_warning(LOG_PROTOCOL, _("IMAP error: RENAME error\n"));
646                 break;
647         case MAILIMAP_ERROR_SEARCH:
648                 log_warning(LOG_PROTOCOL, _("IMAP error: SEARCH error\n"));
649                 break;
650         case MAILIMAP_ERROR_UID_SEARCH:
651                 log_warning(LOG_PROTOCOL, _("IMAP error: UID SEARCH error\n"));
652                 break;
653         case MAILIMAP_ERROR_SELECT:
654                 log_warning(LOG_PROTOCOL, _("IMAP error: SELECT error\n"));
655                 break;
656         case MAILIMAP_ERROR_STATUS:
657                 log_warning(LOG_PROTOCOL, _("IMAP error: STATUS error\n"));
658                 break;
659         case MAILIMAP_ERROR_STORE:
660                 log_warning(LOG_PROTOCOL, _("IMAP error: STORE error\n"));
661                 break;
662         case MAILIMAP_ERROR_UID_STORE:
663                 log_warning(LOG_PROTOCOL, _("IMAP error: UID STORE error\n"));
664                 break;
665         case MAILIMAP_ERROR_SUBSCRIBE:
666                 log_warning(LOG_PROTOCOL, _("IMAP error: SUBSCRIBE error\n"));
667                 break;
668         case MAILIMAP_ERROR_UNSUBSCRIBE:
669                 log_warning(LOG_PROTOCOL, _("IMAP error: UNSUBSCRIBE error\n"));
670                 break;
671         case MAILIMAP_ERROR_STARTTLS:
672                 log_warning(LOG_PROTOCOL, _("IMAP error: STARTTLS error\n"));
673                 break;
674         case MAILIMAP_ERROR_INVAL:
675                 log_warning(LOG_PROTOCOL, _("IMAP error: INVAL error\n"));
676                 break;
677         case MAILIMAP_ERROR_EXTENSION:
678                 log_warning(LOG_PROTOCOL, _("IMAP error: EXTENSION error\n"));
679                 break;
680         case MAILIMAP_ERROR_SASL:
681                 log_warning(LOG_PROTOCOL, _("IMAP error: SASL error\n"));
682                 break;
683 #if (LIBETPAN_VERSION_MAJOR > 0 || LIBETPAN_VERSION_MINOR > 48)
684 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
685         case MAILIMAP_ERROR_SSL:
686                 log_warning(LOG_PROTOCOL, _("IMAP error: SSL error\n"));
687                 break;
688 #endif
689 #endif
690         default:
691                 log_warning(LOG_PROTOCOL, _("IMAP error: Unknown error [%d]\n"),
692                         libetpan_errcode);
693                 break;
694         }
695
696         if (session && is_fatal(libetpan_errcode)) {
697                 imap_disc_session_destroy(IMAP_SESSION(session));
698         } else if (session && !is_fatal(libetpan_errcode)) {
699                 if (IMAP_SESSION(session)->busy)
700                         unlock_session(IMAP_SESSION(session));
701         }
702 }
703
704 static Folder *imap_folder_new(const gchar *name, const gchar *path)
705 {
706         Folder *folder;
707
708         folder = (Folder *)g_new0(IMAPFolder, 1);
709         folder->klass = &imap_class;
710         imap_folder_init(folder, name, path);
711
712         return folder;
713 }
714
715 static void imap_folder_destroy(Folder *folder)
716 {
717         while (imap_folder_get_refcnt(folder) > 0)
718                 gtk_main_iteration();
719         
720         folder_remote_folder_destroy(REMOTE_FOLDER(folder));
721         imap_done(folder);
722 }
723
724 static void imap_folder_init(Folder *folder, const gchar *name,
725                              const gchar *path)
726 {
727         folder_remote_folder_init((Folder *)folder, name, path);
728         IMAP_FOLDER(folder)->max_set_size = IMAP_SET_MAX_COUNT;
729 }
730
731 static FolderItem *imap_folder_item_new(Folder *folder)
732 {
733         IMAPFolderItem *item;
734         
735         item = g_new0(IMAPFolderItem, 1);
736         item->lastuid = 0;
737         item->uid_next = 0;
738         item->uid_list = NULL;
739
740         return (FolderItem *)item;
741 }
742
743 static void imap_folder_item_destroy(Folder *folder, FolderItem *_item)
744 {
745         IMAPFolderItem *item = (IMAPFolderItem *)_item;
746
747         g_return_if_fail(item != NULL);
748         g_slist_free(item->uid_list);
749
750         g_free(_item);
751 }
752
753 static gboolean imap_reset_uid_lists_func(GNode *node, gpointer data)
754 {
755         IMAPFolderItem *item = (IMAPFolderItem *)node->data;
756         
757         item->lastuid = 0;
758         g_slist_free(item->uid_list);
759         item->uid_list = NULL;
760         
761         return FALSE;
762 }
763
764 static void imap_reset_uid_lists(Folder *folder)
765 {
766         if(folder->node == NULL)
767                 return;
768         
769         /* Destroy all uid lists and rest last uid */
770         g_node_traverse(folder->node, G_IN_ORDER, G_TRAVERSE_ALL, -1, imap_reset_uid_lists_func, NULL); 
771 }
772
773 static int imap_get_capabilities(IMAPSession *session)
774 {
775         struct mailimap_capability_data *capabilities = NULL;
776         clistiter *cur;
777         int result = -1;
778
779         if (session->capability != NULL)
780                 return MAILIMAP_NO_ERROR;
781
782         capabilities = imap_threaded_capability(session->folder, &result);
783
784         if (result != MAILIMAP_NO_ERROR) {
785                 imap_handle_error(SESSION(session), result);
786                 return MAILIMAP_ERROR_CAPABILITY;
787         }
788
789         if (capabilities == NULL) {
790                 return MAILIMAP_NO_ERROR;
791         }
792
793         for(cur = clist_begin(capabilities->cap_list) ; cur != NULL ;
794             cur = clist_next(cur)) {
795                 struct mailimap_capability * cap = 
796                         clist_content(cur);
797                 if (!cap || cap->cap_data.cap_name == NULL)
798                         continue;
799                 session->capability = g_slist_append
800                                 (session->capability,
801                                  g_strdup(cap->cap_data.cap_name));
802                 debug_print("got capa %s\n", cap->cap_data.cap_name);
803         }
804         mailimap_capability_data_free(capabilities);
805         return MAILIMAP_NO_ERROR;
806 }
807
808 static gboolean imap_has_capability(IMAPSession *session, const gchar *cap) 
809 {
810         GSList *cur;
811         for (cur = session->capability; cur; cur = cur->next) {
812                 if (!g_ascii_strcasecmp(cur->data, cap))
813                         return TRUE;
814         }
815         return FALSE;
816 }
817
818 static gint imap_auth(IMAPSession *session, const gchar *user, const gchar *pass,
819                       IMAPAuthType type)
820 {
821         gint ok = MAILIMAP_ERROR_BAD_STATE;
822         static time_t last_login_err = 0;
823         gchar *ext_info = "";
824         int r;
825         if ((r = imap_get_capabilities(session)) != MAILIMAP_NO_ERROR) {
826                 imap_handle_error(SESSION(session), r);
827                 return r;
828         }
829         switch(type) {
830         case IMAP_AUTH_ANON:
831                 ok = imap_cmd_login(session, user, pass, "ANONYMOUS");
832                 break;
833         case IMAP_AUTH_CRAM_MD5:
834                 ok = imap_cmd_login(session, user, pass, "CRAM-MD5");
835                 break;
836         case IMAP_AUTH_DIGEST_MD5:
837                 ok = imap_cmd_login(session, user, pass, "DIGEST-MD5");
838                 break;
839         case IMAP_AUTH_LOGIN:
840                 ok = imap_cmd_login(session, user, pass, "LOGIN");
841                 break;
842         case IMAP_AUTH_GSSAPI:
843                 ok = imap_cmd_login(session, user, pass, "GSSAPI");
844                 break;
845         default:
846                 debug_print("capabilities:\n"
847                                 "\t ANONYMOUS %d\n"
848                                 "\t CRAM-MD5 %d\n"
849                                 "\t DIGEST-MD5 %d\n"
850                                 "\t LOGIN %d\n"
851                                 "\t GSSAPI %d\n", 
852                         imap_has_capability(session, "ANONYMOUS"),
853                         imap_has_capability(session, "CRAM-MD5"),
854                         imap_has_capability(session, "DIGEST-MD5"),
855                         imap_has_capability(session, "LOGIN"),
856                         imap_has_capability(session, "GSSAPI"));
857                 if (imap_has_capability(session, "CRAM-MD5"))
858                         ok = imap_cmd_login(session, user, pass, "CRAM-MD5");
859                 if ((ok == MAILIMAP_ERROR_BAD_STATE ||
860                      ok == MAILIMAP_ERROR_LOGIN) && imap_has_capability(session, "DIGEST-MD5"))
861                         ok = imap_cmd_login(session, user, pass, "DIGEST-MD5");
862                 if ((ok == MAILIMAP_ERROR_BAD_STATE ||
863                      ok == MAILIMAP_ERROR_LOGIN) && imap_has_capability(session, "GSSAPI"))
864                         ok = imap_cmd_login(session, user, pass, "GSSAPI");
865                 if (ok == MAILIMAP_ERROR_BAD_STATE||
866                     ok == MAILIMAP_ERROR_LOGIN) /* we always try LOGIN before giving up */
867                         ok = imap_cmd_login(session, user, pass, "LOGIN");
868         }
869
870         if (ok == MAILIMAP_NO_ERROR)
871                 session->authenticated = TRUE;
872         else {
873                 if (type == IMAP_AUTH_CRAM_MD5) {
874                         ext_info = _("\n\nCRAM-MD5 logins only work if libetpan has been "
875                                      "compiled with SASL support and the "
876                                      "CRAM-MD5 SASL plugin is installed.");
877                 } 
878
879                 if (type == IMAP_AUTH_DIGEST_MD5) {
880                         ext_info = _("\n\nDIGEST-MD5 logins only work if libetpan has been "
881                                      "compiled with SASL support and the "
882                                      "DIGEST-MD5 SASL plugin is installed.");
883                 } 
884
885                 if (time(NULL) - last_login_err > 10) {
886                         if (!prefs_common.no_recv_err_panel) {
887                                 alertpanel_error_log(_("Connection to %s failed: "
888                                         "login refused.%s"),
889                                         SESSION(session)->server, ext_info);
890                         } else {
891                                 log_error(LOG_PROTOCOL, _("Connection to %s failed: "
892                                         "login refused.%s\n"),
893                                         SESSION(session)->server, ext_info);
894                         }
895                 }
896                 last_login_err = time(NULL);
897         }
898         return ok;
899 }
900
901 static IMAPSession *imap_reconnect_if_possible(Folder *folder, IMAPSession *session)
902 {
903         RemoteFolder *rfolder = REMOTE_FOLDER(folder);
904         /* Check if this is the first try to establish a
905            connection, if yes we don't try to reconnect */
906         debug_print("reconnecting\n");
907         if (rfolder->session == NULL) {
908                 log_warning(LOG_PROTOCOL, _("Connecting to %s failed"),
909                             folder->account->recv_server);
910                 SESSION(session)->sock = NULL;
911                 session_destroy(SESSION(session));
912                 session = NULL;
913         } else {
914                 rfolder->session = NULL;
915                 log_warning(LOG_PROTOCOL, _("IMAP4 connection to %s has been"
916                             " disconnected. Reconnecting...\n"),
917                             folder->account->recv_server);
918                 statusbar_print_all(_("IMAP4 connection to %s has been"
919                             " disconnected. Reconnecting...\n"),
920                             folder->account->recv_server);
921                 SESSION(session)->state = SESSION_DISCONNECTED;
922                 SESSION(session)->sock = NULL;
923                 session_destroy(SESSION(session));
924                 /* Clear folders session to make imap_session_get create
925                    a new session, because of rfolder->session == NULL
926                    it will not try to reconnect again and so avoid an
927                    endless loop */
928                 debug_print("getting session...\n");
929                 session = imap_session_get(folder);
930                 rfolder->session = SESSION(session);
931                 statusbar_pop_all();
932         }
933         return session;
934 }
935
936 static IMAPSession *imap_session_get(Folder *folder)
937 {
938         RemoteFolder *rfolder = REMOTE_FOLDER(folder);
939         IMAPSession *session = NULL;
940         gint r = MAILIMAP_NO_ERROR;
941
942         g_return_val_if_fail(folder != NULL, NULL);
943         g_return_val_if_fail(FOLDER_CLASS(folder) == &imap_class, NULL);
944         g_return_val_if_fail(folder->account != NULL, NULL);
945         
946         if (prefs_common.work_offline && 
947             !inc_offline_should_override(FALSE,
948                 _("Claws Mail needs network access in order "
949                   "to access the IMAP server."))) {
950                 return NULL;
951         }
952
953         /* Make sure we have a session */
954         if (rfolder->session != NULL) {
955                 session = IMAP_SESSION(rfolder->session);
956         } else if (rfolder->connecting) {
957                 debug_print("already connecting\n");
958                 return NULL;
959         } else {
960                 imap_reset_uid_lists(folder);
961                 if (time(NULL) - rfolder->last_failure <= 2)
962                         return NULL;
963                 rfolder->connecting = TRUE;
964                 session = imap_session_new(folder, folder->account);
965         }
966         if(session == NULL) {
967                 rfolder->last_failure = time(NULL);
968                 rfolder->connecting = FALSE;
969                 return NULL;
970         }
971
972         /* Make sure session is authenticated */
973         if (!IMAP_SESSION(session)->authenticated)
974                 imap_session_authenticate(IMAP_SESSION(session), folder->account);
975         
976         if (!IMAP_SESSION(session)->authenticated) {
977                 imap_threaded_disconnect(session->folder);
978                 rfolder->session = NULL;
979                 SESSION(session)->state = SESSION_DISCONNECTED;
980                 SESSION(session)->sock = NULL;
981                 session_destroy(SESSION(session));
982                 rfolder->last_failure = time(NULL);
983                 rfolder->connecting = FALSE;
984                 return NULL;
985         }
986
987         /* I think the point of this code is to avoid sending a
988          * keepalive if we've used the session recently and therefore
989          * think it's still alive.  Unfortunately, most of the code
990          * does not yet check for errors on the socket, and so if the
991          * connection drops we don't notice until the timeout expires.
992          * A better solution than sending a NOOP every time would be
993          * for every command to be prepared to retry until it is
994          * successfully sent. -- mbp */
995         if ((time(NULL) - SESSION(session)->last_access_time > SESSION_TIMEOUT_INTERVAL) || session->cancelled) {
996                 /* verify that the session is still alive */
997                 if ((r = imap_cmd_noop(session)) != MAILIMAP_NO_ERROR) {
998                         debug_print("disconnected!\n");
999                         if (!is_fatal(r))
1000                                 session = imap_reconnect_if_possible(folder, session);
1001                         else {
1002                                 rfolder->session = NULL;
1003                                 rfolder->connecting = FALSE;
1004                                 session = imap_session_get(folder);
1005                         }
1006                 }
1007                 if (session)
1008                         session->cancelled = FALSE;
1009         }
1010
1011         rfolder->session = SESSION(session);
1012         rfolder->connecting = FALSE;
1013
1014         return IMAP_SESSION(session);
1015 }
1016
1017 static IMAPSession *imap_session_new(Folder * folder,
1018                                      const PrefsAccount *account)
1019 {
1020         IMAPSession *session;
1021         gushort port;
1022         int r;
1023         int authenticated = FALSE;
1024         
1025 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
1026         /* FIXME: IMAP over SSL only... */ 
1027         SSLType ssl_type;
1028
1029         port = account->set_imapport ? account->imapport
1030                 : account->ssl_imap == SSL_TUNNEL ? IMAPS_PORT : IMAP4_PORT;
1031         ssl_type = account->ssl_imap;   
1032 #else
1033         if (account->ssl_imap != SSL_NONE) {
1034                 if (alertpanel_full(_("Insecure connection"),
1035                         _("This connection is configured to be secured "
1036                           "using SSL, but SSL is not available in this "
1037                           "build of Claws Mail. \n\n"
1038                           "Do you want to continue connecting to this "
1039                           "server? The communication would not be "
1040                           "secure."),
1041                           GTK_STOCK_CANCEL, _("Con_tinue connecting"), 
1042                           NULL, FALSE, NULL, ALERT_WARNING,
1043                           G_ALERTDEFAULT) != G_ALERTALTERNATE)
1044                         return NULL;
1045         }
1046         port = account->set_imapport ? account->imapport
1047                 : IMAP4_PORT;
1048 #endif
1049
1050         imap_init(folder);
1051         statuswindow_print_all(_("Connecting to IMAP4 server: %s..."), folder->account->recv_server);
1052 #ifndef G_OS_WIN32
1053         if (account->set_tunnelcmd) {
1054                 r = imap_threaded_connect_cmd(folder,
1055                                               account->tunnelcmd,
1056                                               account->recv_server,
1057                                               port);
1058         }
1059         else 
1060 #endif
1061         {
1062 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
1063                 if (ssl_type == SSL_TUNNEL) {
1064                         r = imap_threaded_connect_ssl(folder,
1065                                                       account->recv_server,
1066                                                       port);
1067                 }
1068                 else 
1069 #endif
1070                 {
1071                         r = imap_threaded_connect(folder,
1072                                                   account->recv_server,
1073                                                   port);
1074                 }
1075         }
1076         
1077         statuswindow_pop_all();
1078         if (r == MAILIMAP_NO_ERROR_AUTHENTICATED) {
1079                 authenticated = TRUE;
1080         }
1081         else if (r == MAILIMAP_NO_ERROR_NON_AUTHENTICATED) {
1082                 authenticated = FALSE;
1083         }
1084         else {
1085 #if (LIBETPAN_VERSION_MAJOR > 0 || LIBETPAN_VERSION_MINOR > 48)
1086 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
1087                 if (r == MAILIMAP_ERROR_SSL)
1088                         log_error(LOG_PROTOCOL, _("SSL handshake failed\n"));
1089                 else
1090 #endif
1091 #endif
1092                         imap_handle_error(NULL, r);
1093
1094                 if(!prefs_common.no_recv_err_panel) {
1095                         alertpanel_error_log(_("Can't connect to IMAP4 server: %s:%d"),
1096                                          account->recv_server, port);
1097                 } else {
1098                         log_error(LOG_PROTOCOL, _("Can't connect to IMAP4 server: %s:%d\n"),
1099                                          account->recv_server, port);
1100                 } 
1101                 
1102                 return NULL;
1103         }
1104         
1105         session = g_new0(IMAPSession, 1);
1106         session_init(SESSION(session));
1107         SESSION(session)->type             = SESSION_IMAP;
1108         SESSION(session)->server           = g_strdup(account->recv_server);
1109         SESSION(session)->sock             = NULL;
1110         
1111         SESSION(session)->destroy          = imap_session_destroy;
1112
1113         session->capability = NULL;
1114         
1115         session->authenticated = authenticated;
1116         session->mbox = NULL;
1117         session->exists = 0;
1118         session->recent = 0;
1119         session->expunge = 0;
1120         session->cmd_count = 0;
1121         session->folder = folder;
1122         IMAP_FOLDER(session->folder)->last_seen_separator = 0;
1123
1124 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
1125         if (account->ssl_imap == SSL_STARTTLS) {
1126                 gint ok;
1127
1128                 ok = imap_cmd_starttls(session);
1129                 if (ok != MAILIMAP_NO_ERROR) {
1130                         log_warning(LOG_PROTOCOL, _("Can't start TLS session.\n"));
1131                         if (!is_fatal(ok)) {
1132                                 SESSION(session)->sock = NULL;
1133                                 session_destroy(SESSION(session));
1134                         }
1135                         return NULL;
1136                 }
1137
1138                 imap_free_capabilities(session);
1139                 session->authenticated = FALSE;
1140                 session->uidplus = FALSE;
1141                 session->cmd_count = 1;
1142         }
1143 #endif
1144         log_message(LOG_PROTOCOL, "IMAP connection is %s-authenticated\n",
1145                     (session->authenticated) ? "pre" : "un");
1146         
1147         return session;
1148 }
1149
1150 static void imap_session_authenticate(IMAPSession *session, 
1151                                       const PrefsAccount *account)
1152 {
1153         gchar *pass, *acc_pass;
1154         gboolean failed = FALSE;
1155
1156         g_return_if_fail(account->userid != NULL);
1157         acc_pass = account->passwd;
1158 try_again:
1159         pass = acc_pass;
1160         if (!pass && account->imap_auth_type != IMAP_AUTH_ANON) {
1161                 gchar *tmp_pass;
1162                 tmp_pass = input_dialog_query_password(account->recv_server, account->userid);
1163                 if (!tmp_pass)
1164                         return;
1165                 Xstrdup_a(pass, tmp_pass, {g_free(tmp_pass); return;});
1166                 g_free(tmp_pass);
1167         } else if (account->imap_auth_type == IMAP_AUTH_ANON) {
1168                 pass = "";
1169         }
1170         statuswindow_print_all(_("Connecting to IMAP4 server %s...\n"),
1171                                 account->recv_server);
1172         if (imap_auth(session, account->userid, pass, account->imap_auth_type) != MAILIMAP_NO_ERROR) {
1173                 statusbar_pop_all();
1174                 
1175                 if (!failed) {
1176                         acc_pass = NULL;
1177                         failed = TRUE;
1178                         goto try_again;
1179                 } else {
1180                         if (prefs_common.no_recv_err_panel) {
1181                                 log_error(LOG_PROTOCOL, _("Couldn't login to IMAP server %s."), account->recv_server);
1182                                 mainwindow_show_error();
1183                         } else
1184                                 alertpanel_error_log(_("Couldn't login to IMAP server %s."), account->recv_server);
1185                 }               
1186
1187                 return;
1188         } 
1189
1190         statuswindow_pop_all();
1191         session->authenticated = TRUE;
1192         return;
1193 }
1194
1195 static void imap_session_destroy(Session *session)
1196 {
1197         if (session->state != SESSION_DISCONNECTED)
1198                 imap_threaded_disconnect(IMAP_SESSION(session)->folder);
1199         
1200         imap_free_capabilities(IMAP_SESSION(session));
1201         g_free(IMAP_SESSION(session)->mbox);
1202 }
1203
1204 static gchar *imap_fetch_msg(Folder *folder, FolderItem *item, gint uid)
1205 {
1206         return imap_fetch_msg_full(folder, item, uid, TRUE, TRUE);
1207 }
1208
1209 static guint get_file_size_with_crs(const gchar *filename) 
1210 {
1211         FILE *fp = NULL;
1212         guint cnt = 0;
1213         gchar buf[4096];
1214         
1215         if (filename == NULL)
1216                 return -1;
1217         
1218         fp = fopen(filename, "rb");
1219         if (!fp)
1220                 return -1;
1221         
1222         while (fgets(buf, sizeof (buf), fp) != NULL) {
1223                 cnt += strlen(buf);
1224                 if (!strstr(buf, "\r\n") && strstr(buf, "\n"))
1225                         cnt++;
1226         }
1227         
1228         fclose(fp);
1229         return cnt;
1230 }
1231
1232 static void imap_remove_cached_msg(Folder *folder, FolderItem *item, MsgInfo *msginfo)
1233 {
1234         gchar *path, *filename;
1235
1236         path = folder_item_get_path(item);
1237
1238         if (!is_dir_exist(path)) {
1239                 g_free(path);
1240                 return;
1241         }
1242
1243         filename = g_strconcat(path, G_DIR_SEPARATOR_S, itos(msginfo->msgnum), NULL);
1244         g_free(path);
1245
1246         if (is_file_exist(filename)) {
1247                 claws_unlink(filename);
1248         }
1249         g_free(filename);
1250 }
1251
1252 typedef struct _TagsData {
1253         gchar *str;
1254         GSList *msglist;
1255         IMAPFolderItem *item;
1256 } TagsData;
1257
1258 static void imap_commit_tags(FolderItem *item, MsgInfo *msginfo, GSList *tags_set, GSList *tags_unset)
1259 {
1260         IMAPSession *session;
1261         gint ok, can_create_tags;
1262         Folder *folder = NULL;
1263         TagsData *ht_data = NULL;
1264         GSList *cur;
1265
1266         g_return_if_fail(item != NULL);
1267         g_return_if_fail(msginfo != NULL);
1268
1269         folder = item->folder;
1270         debug_print("getting session...\n");
1271         session = imap_session_get(folder);
1272         
1273         if (!session) {
1274                 debug_print("can't get session\n");
1275                 return;
1276         }
1277
1278         ok = imap_select(session, IMAP_FOLDER(folder), item,
1279                          NULL, NULL, NULL, NULL, &can_create_tags, FALSE);
1280
1281         if (ok != MAILIMAP_NO_ERROR) {
1282                 imap_handle_error(SESSION(session), ok);
1283                 return;
1284         }
1285
1286         
1287         if (IMAP_FOLDER_ITEM(item)->can_create_flags != ITEM_CAN_CREATE_FLAGS)
1288                 return;
1289         
1290         if (IMAP_FOLDER_ITEM(item)->batching) {
1291                 /* instead of performing an UID STORE command for each message change,
1292                  * as a lot of them can change "together", we just fill in hashtables
1293                  * and defer the treatment so that we're able to send only one
1294                  * command.
1295                  */
1296                 debug_print("IMAP batch mode on, deferring tags change\n");
1297                 for (cur = tags_set; cur; cur = cur->next) {
1298                         gint cur_tag = GPOINTER_TO_INT(cur->data);
1299                         if (cur_tag) {
1300                                 ht_data = g_hash_table_lookup(IMAP_FOLDER_ITEM(item)->tags_set_table, 
1301                                         GINT_TO_POINTER(cur_tag));
1302                                 if (ht_data == NULL) {
1303                                         ht_data = g_new0(TagsData, 1);
1304                                         ht_data->str = g_strdup(tags_get_tag(cur_tag));
1305                                         ht_data->item = IMAP_FOLDER_ITEM(item);
1306                                         g_hash_table_insert(IMAP_FOLDER_ITEM(item)->tags_set_table, 
1307                                                 GINT_TO_POINTER(cur_tag), ht_data);
1308                                 }
1309                                 ht_data->msglist = g_slist_prepend(ht_data->msglist, GINT_TO_POINTER(msginfo->msgnum));
1310                         } 
1311                 }
1312                 for (cur = tags_unset; cur; cur = cur->next) {
1313                         gint cur_tag = GPOINTER_TO_INT(cur->data);
1314                         if (cur_tag) {
1315                                 ht_data = g_hash_table_lookup(IMAP_FOLDER_ITEM(item)->tags_unset_table, 
1316                                         GINT_TO_POINTER(cur_tag));
1317                                 if (ht_data == NULL) {
1318                                         ht_data = g_new0(TagsData, 1);
1319                                         ht_data->str = g_strdup(tags_get_tag(cur_tag));
1320                                         ht_data->item = IMAP_FOLDER_ITEM(item);
1321                                         g_hash_table_insert(IMAP_FOLDER_ITEM(item)->tags_unset_table, 
1322                                                 GINT_TO_POINTER(cur_tag), ht_data);
1323                                 }
1324                                 ht_data->msglist = g_slist_prepend(ht_data->msglist, GINT_TO_POINTER(msginfo->msgnum));
1325                         }
1326                 }
1327         } else {
1328                 GSList *list_set = NULL;
1329                 GSList *list_unset = NULL;
1330                 GSList numlist;
1331                 
1332                 numlist.data = GINT_TO_POINTER(msginfo->msgnum);
1333                 numlist.next = NULL;
1334         
1335                 debug_print("IMAP changing tags NOW\n");
1336                 for (cur = tags_set; cur; cur = cur->next) {
1337                         gint cur_tag = GPOINTER_TO_INT(cur->data);
1338                         const gchar *str = tags_get_tag(cur_tag);
1339                         list_set = g_slist_prepend(list_set, g_strdup(str));
1340                 }
1341                 if (list_set) {
1342                         ok = imap_set_message_flags(session, 
1343                                 IMAP_FOLDER_ITEM(item), &numlist, 0, list_set, TRUE);
1344                         slist_free_strings(list_set);
1345                         g_slist_free(list_set);
1346                         if (ok != MAILIMAP_NO_ERROR) {
1347                                 return;
1348                         }
1349                 }
1350
1351                 for (cur = tags_unset; cur; cur = cur->next) {
1352                         gint cur_tag = GPOINTER_TO_INT(cur->data);
1353                         const gchar *str = tags_get_tag(cur_tag);
1354                         list_unset = g_slist_prepend(list_unset, g_strdup(str));
1355                 }
1356                 if (list_unset) {
1357                         ok = imap_set_message_flags(session, 
1358                                 IMAP_FOLDER_ITEM(item), &numlist, 0, list_unset, FALSE);
1359                         slist_free_strings(list_unset);
1360                         g_slist_free(list_unset);
1361                         if (ok != MAILIMAP_NO_ERROR) {
1362                                 return;
1363                         }
1364                 }
1365         }
1366 }
1367
1368 static gchar *imap_fetch_msg_full(Folder *folder, FolderItem *item, gint uid,
1369                                   gboolean headers, gboolean body)
1370 {
1371         gchar *path, *filename;
1372         IMAPSession *session;
1373         gint ok;
1374
1375         g_return_val_if_fail(folder != NULL, NULL);
1376         g_return_val_if_fail(item != NULL, NULL);
1377
1378         if (uid == 0)
1379                 return NULL;
1380
1381         path = folder_item_get_path(item);
1382         if (!is_dir_exist(path))
1383                 make_dir_hier(path);
1384         filename = g_strconcat(path, G_DIR_SEPARATOR_S, itos(uid), NULL);
1385         g_free(path);
1386         debug_print("trying to fetch cached %s\n", filename);
1387         if (is_file_exist(filename)) {
1388                 /* see whether the local file represents the whole message
1389                  * or not. As the IMAP server reports size with \r chars,
1390                  * we have to update the local file (UNIX \n only) size */
1391                 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1392                 guint have_size = -1;
1393
1394                 if (cached)
1395                         debug_print("message %d has been already %scached.\n", uid,
1396                                 MSG_IS_FULLY_CACHED(cached->flags) ? "fully ":"");
1397                 
1398                 if (!cached || !MSG_IS_FULLY_CACHED(cached->flags)) {
1399                         have_size = get_file_size_with_crs(filename);
1400                         if (cached && (cached->size <= have_size || !body)) {
1401                                 procmsg_msginfo_free(cached);
1402                                 ok = file_strip_crs(filename);
1403                                 if (ok == 0 && cached && cached->size <= have_size) {
1404                                         /* we have it all and stripped */
1405                                         debug_print("...fully cached in fact; setting flag.\n");
1406                                         procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
1407                                 }
1408                                 return filename;
1409                         } else if (!cached && time(NULL) - get_file_mtime(filename) < 60) {
1410                                 debug_print("message not cached and file recent, considering file complete\n");
1411                                 ok = file_strip_crs(filename);
1412                                 if (ok == 0)
1413                                         return filename;
1414                         } else {
1415                                 procmsg_msginfo_free(cached);
1416                         }
1417                 }
1418                 if (cached && MSG_IS_FULLY_CACHED(cached->flags)) {
1419                         procmsg_msginfo_free(cached);
1420                         return filename;
1421                 }
1422         } else {
1423                 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1424                 if (cached) {
1425                         procmsg_msginfo_unset_flags(cached, MSG_FULLY_CACHED, 0);
1426                         procmsg_msginfo_free(cached);
1427                 }
1428         }
1429
1430         debug_print("getting session...\n");
1431         session = imap_session_get(folder);
1432         
1433         if (!session) {
1434                 g_free(filename);
1435                 return NULL;
1436         }
1437         session_set_access_time(SESSION(session));
1438         lock_session(session); /* unlocked later in the function */
1439
1440         debug_print("IMAP fetching messages\n");
1441         ok = imap_select(session, IMAP_FOLDER(folder), item,
1442                          NULL, NULL, NULL, NULL, NULL, FALSE);
1443         if (ok != MAILIMAP_NO_ERROR) {
1444                 g_warning("can't select mailbox %s\n", item->path);
1445                 g_free(filename);
1446                 return NULL;
1447         }
1448
1449         session_set_access_time(SESSION(session));
1450
1451         debug_print("getting message %d...\n", uid);
1452         ok = imap_cmd_fetch(session, (guint32)uid, filename, headers, body);
1453
1454         if (ok != MAILIMAP_NO_ERROR) {
1455                 g_warning("can't fetch message %d\n", uid);
1456                 g_free(filename);
1457                 return NULL;
1458         }
1459
1460         session_set_access_time(SESSION(session));
1461         unlock_session(session);
1462
1463         ok = file_strip_crs(filename);
1464
1465         if (ok == 0 && headers && body) {
1466                 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1467                 if (cached) {
1468                         procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
1469                         procmsg_msginfo_free(cached);
1470                 }
1471         } else if (ok == -1) {
1472                 MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1473                 if (cached) {
1474                         procmsg_msginfo_unset_flags(cached, MSG_FULLY_CACHED, 0);
1475                         procmsg_msginfo_free(cached);
1476                 }
1477         }
1478         return filename;
1479 }
1480
1481 static gboolean imap_is_msg_fully_cached(Folder *folder, FolderItem *item, gint uid)
1482 {
1483         gchar *path, *filename;
1484         guint size = 0;
1485         MsgInfo *cached = msgcache_get_msg(item->cache,uid);
1486         
1487         if (!cached)
1488                 return FALSE;
1489
1490         if (MSG_IS_FULLY_CACHED(cached->flags)) {
1491                 procmsg_msginfo_free(cached);
1492                 return TRUE;
1493         }
1494         path = folder_item_get_path(item);
1495         if (!is_dir_exist(path))
1496                 return FALSE;
1497
1498         filename = g_strconcat(path, G_DIR_SEPARATOR_S, itos(uid), NULL);
1499         g_free(path);
1500         if (is_file_exist(filename)) {
1501                 if (cached && cached->total_size == cached->size) {
1502                         /* fast path */
1503                         g_free(filename);
1504                         procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
1505                         return TRUE;
1506                 }
1507                 size = get_file_size_with_crs(filename);
1508                 g_free(filename);
1509         }
1510         if (cached && size >= cached->size) {
1511                 cached->total_size = cached->size;
1512                 procmsg_msginfo_set_flags(cached, MSG_FULLY_CACHED, 0);
1513                 procmsg_msginfo_free(cached);
1514                 return TRUE;
1515         }
1516         if (cached)
1517                 procmsg_msginfo_free(cached);
1518         return FALSE;   
1519 }
1520
1521 void imap_cache_msg(FolderItem *item, gint msgnum)
1522 {
1523         Folder *folder = NULL;
1524         
1525         if (!item)
1526                 return;
1527         folder = item->folder;
1528         
1529         if (!imap_is_msg_fully_cached(folder, item, msgnum)) {
1530                 gchar *tmp = imap_fetch_msg_full(folder, item, msgnum, TRUE, TRUE);
1531                 debug_print("fetched %s\n", tmp);
1532                 g_free(tmp);
1533         }
1534 }
1535
1536 static gint imap_add_msg(Folder *folder, FolderItem *dest, 
1537                          const gchar *file, MsgFlags *flags)
1538 {
1539         gint ret;
1540         GSList file_list;
1541         MsgFileInfo fileinfo;
1542
1543         g_return_val_if_fail(file != NULL, -1);
1544
1545         fileinfo.msginfo = NULL;
1546         fileinfo.file = (gchar *)file;
1547         fileinfo.flags = flags;
1548         file_list.data = &fileinfo;
1549         file_list.next = NULL;
1550
1551         ret = imap_add_msgs(folder, dest, &file_list, NULL);
1552         return ret;
1553 }
1554
1555 static gint imap_add_msgs(Folder *folder, FolderItem *dest, GSList *file_list,
1556                    GRelation *relation)
1557 {
1558         gchar *destdir;
1559         IMAPSession *session;
1560         guint32 last_uid = 0;
1561         GSList *cur;
1562         MsgFileInfo *fileinfo;
1563         gint ok = MAILIMAP_NO_ERROR;
1564         gint curnum = 0, total = 0;
1565         gboolean missing_uids = FALSE;
1566
1567         g_return_val_if_fail(folder != NULL, -1);
1568         g_return_val_if_fail(dest != NULL, -1);
1569         g_return_val_if_fail(file_list != NULL, -1);
1570         
1571         debug_print("getting session...\n");
1572         session = imap_session_get(folder);
1573         if (!session) {
1574                 return -1;
1575         }
1576         destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path);
1577
1578         statusbar_print_all(_("Adding messages..."));
1579         total = g_slist_length(file_list);
1580         for (cur = file_list; cur != NULL; cur = cur->next) {
1581                 IMAPFlags iflags = 0;
1582                 guint32 new_uid = 0;
1583                 gchar *real_file = NULL;
1584                 fileinfo = (MsgFileInfo *)cur->data;
1585
1586                 statusbar_progress_all(curnum, total, total < 10 ? 1:10);
1587                 curnum++;
1588
1589                 if (fileinfo->flags) {
1590                         if (MSG_IS_MARKED(*fileinfo->flags))
1591                                 iflags |= IMAP_FLAG_FLAGGED;
1592                         if (MSG_IS_REPLIED(*fileinfo->flags))
1593                                 iflags |= IMAP_FLAG_ANSWERED;
1594                         if (MSG_IS_FORWARDED(*fileinfo->flags))
1595                                 iflags |= IMAP_FLAG_FORWARDED;
1596                         if (!MSG_IS_UNREAD(*fileinfo->flags))
1597                                 iflags |= IMAP_FLAG_SEEN;
1598                         
1599                 }
1600                 
1601                 if (real_file == NULL)
1602                         real_file = g_strdup(fileinfo->file);
1603                 
1604                 if (folder_has_parent_of_type(dest, F_QUEUE) ||
1605                     folder_has_parent_of_type(dest, F_OUTBOX) ||
1606                     folder_has_parent_of_type(dest, F_DRAFT) ||
1607                     folder_has_parent_of_type(dest, F_TRASH))
1608                         iflags |= IMAP_FLAG_SEEN;
1609
1610                 ok = imap_cmd_append(session, IMAP_FOLDER_ITEM(dest), destdir, real_file, iflags, 
1611                                      &new_uid);
1612
1613                 if (ok != MAILIMAP_NO_ERROR) {
1614                         g_warning("can't append message %s\n", real_file);
1615                         g_free(real_file);
1616                         g_free(destdir);
1617                         statusbar_progress_all(0,0,0);
1618                         statusbar_pop_all();
1619                         return -1;
1620                 } else {
1621                         debug_print("appended new message as %d\n", new_uid);
1622                         /* put the local file in the imapcache, so that we don't
1623                          * have to fetch it back later. */
1624                         
1625                         if (new_uid == 0) {
1626                                 missing_uids = TRUE;
1627                                 debug_print("Missing UID (0)\n");
1628                         }
1629                         if (new_uid > 0) {
1630                                 gchar *cache_path = folder_item_get_path(dest);
1631                                 if (!is_dir_exist(cache_path))
1632                                         make_dir_hier(cache_path);
1633                                 if (is_dir_exist(cache_path)) {
1634                                         gchar *cache_file = g_strconcat(
1635                                                 cache_path, G_DIR_SEPARATOR_S, 
1636                                                 itos(new_uid), NULL);
1637                                         copy_file(real_file, cache_file, TRUE);
1638                                         debug_print("got UID %d, copied to cache: %s\n", new_uid, cache_file);
1639                                         g_free(cache_file);
1640                                 }
1641                                 g_free(cache_path);
1642                         }
1643                 }
1644
1645                 if (relation != NULL)
1646                         g_relation_insert(relation, fileinfo->msginfo != NULL ? 
1647                                           (gpointer) fileinfo->msginfo : (gpointer) fileinfo,
1648                                           GINT_TO_POINTER(new_uid));
1649                 if (last_uid < new_uid) {
1650                         last_uid = new_uid;
1651                 }
1652
1653                 g_free(real_file);
1654         }
1655         
1656         statusbar_progress_all(0,0,0);
1657         statusbar_pop_all();
1658         
1659         
1660         g_free(destdir);
1661
1662         imap_scan_required(folder, dest);
1663
1664         session = imap_session_get(folder);
1665         if (!session) {
1666                 return -1;
1667         }
1668         if (missing_uids) {
1669                 gint a;
1670                 ok = imap_select(session, IMAP_FOLDER(folder), dest,
1671                          &a, NULL, NULL, NULL, NULL, FALSE);
1672         }
1673         return last_uid;
1674 }
1675
1676 static GSList *flatten_mailimap_set(struct mailimap_set * set) 
1677 {
1678         GSList *result = NULL;
1679         clistiter *list;
1680         int start, end, t;
1681         GSList *cur;
1682
1683         for (list = clist_begin(set->set_list); list; list = clist_next(list)) {
1684                 struct mailimap_set_item *item = (struct mailimap_set_item *)clist_content(list);
1685                 start = item->set_first;
1686                 end = item->set_last;
1687                 for (t = start; t <= end; t++) {
1688                         result = g_slist_prepend(result, GINT_TO_POINTER(t));
1689                 }
1690         }
1691         result = g_slist_reverse(result);
1692         if (debug_get_mode()) {
1693                 debug_print("flat imap set: ");
1694                 for (cur = result; cur; cur = cur->next) {
1695                         debug_print("%d ", GPOINTER_TO_INT(cur->data));
1696                 }
1697                 debug_print("\n");
1698         }
1699         
1700         return result;
1701 }
1702 static gint imap_do_copy_msgs(Folder *folder, FolderItem *dest, 
1703                               MsgInfoList *msglist, GRelation *relation)
1704 {
1705         FolderItem *src;
1706         gchar *destdir;
1707         GSList *seq_list, *cur;
1708         MsgInfo *msginfo;
1709         IMAPSession *session;
1710         gint ok = MAILIMAP_NO_ERROR;
1711         GRelation *uid_mapping;
1712         gint last_num = 0;
1713         gboolean single = FALSE;
1714
1715         g_return_val_if_fail(folder != NULL, -1);
1716         g_return_val_if_fail(dest != NULL, -1);
1717         g_return_val_if_fail(msglist != NULL, -1);
1718         
1719         debug_print("getting session...\n");
1720         session = imap_session_get(folder);
1721         
1722         if (!session) {
1723                 return -1;
1724         }
1725
1726         msginfo = (MsgInfo *)msglist->data;
1727         if (msglist->next == NULL)
1728                 single = TRUE;
1729         src = msginfo->folder;
1730         if (src == dest) {
1731                 g_warning("the src folder is identical to the dest.\n");
1732                 return -1;
1733         }
1734
1735         if (src->folder != dest->folder) {
1736                 GSList *infolist = NULL, *cur;
1737                 int res = -1;
1738                 for (cur = msglist; cur; cur = cur->next) {
1739                         msginfo = (MsgInfo *)cur->data;
1740                         MsgFileInfo *fileinfo = g_new0(MsgFileInfo, 1);
1741                         fileinfo->file = procmsg_get_message_file(msginfo);
1742                         fileinfo->flags = &(msginfo->flags);
1743                         infolist = g_slist_prepend(infolist, fileinfo);
1744                 }
1745                 infolist = g_slist_reverse(infolist);
1746                 res = folder_item_add_msgs(dest, infolist, FALSE);
1747                 for (cur = infolist; cur; cur = cur->next) {
1748                         MsgFileInfo *info = (MsgFileInfo *)cur->data;
1749                         g_free(info->file);
1750                         g_free(info);
1751                 }
1752                 g_slist_free(infolist);
1753                 return res;
1754         } 
1755
1756         lock_session(session); /* unlocked later in the function */
1757
1758         ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder,
1759                          NULL, NULL, NULL, NULL, NULL, FALSE);
1760         if (ok != MAILIMAP_NO_ERROR) {
1761                 return ok;
1762         }
1763
1764         unlock_session(session);
1765
1766         destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path);
1767         seq_list = imap_get_lep_set_from_msglist(IMAP_FOLDER(folder), msglist);
1768         uid_mapping = g_relation_new(2);
1769         g_relation_index(uid_mapping, 0, g_direct_hash, g_direct_equal);
1770         
1771         statusbar_print_all(_("Copying messages..."));
1772         for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
1773                 struct mailimap_set * seq_set;
1774                 struct mailimap_set * source = NULL;
1775                 struct mailimap_set * dest = NULL;
1776                 seq_set = cur->data;
1777
1778                 debug_print("Copying messages from %s to %s ...\n",
1779                             src->path, destdir);
1780
1781                 lock_session(session); /* unlocked later in the function */
1782                 ok = imap_cmd_copy(session, seq_set, destdir, uid_mapping,
1783                         &source, &dest);
1784                 
1785                 if (is_fatal(ok)) {
1786                         session = NULL;
1787                 }
1788
1789                 if (ok == MAILIMAP_NO_ERROR) {
1790                         unlock_session(session);
1791                         if (relation && source && dest) {
1792                                 GSList *s_list = flatten_mailimap_set(source);
1793                                 GSList *d_list = flatten_mailimap_set(dest);
1794                                 GSList *s_cur, *d_cur;
1795                                 if (g_slist_length(s_list) == g_slist_length(d_list)) {
1796
1797                                         for (s_cur = s_list, d_cur = d_list; 
1798                                              s_cur && d_cur; 
1799                                              s_cur = s_cur->next, d_cur = d_cur->next) {
1800                                                 g_relation_insert(uid_mapping, s_cur->data, d_cur->data);
1801                                         }
1802
1803                                 } else {
1804                                         debug_print("hhhmm, source list length != dest list length.\n");
1805                                 }
1806                                 g_slist_free(s_list);
1807                                 g_slist_free(d_list);
1808                         }
1809                 }
1810
1811
1812                 if (source)
1813                         mailimap_set_free(source);
1814                 if (dest)
1815                         mailimap_set_free(dest);
1816
1817                 if (ok != MAILIMAP_NO_ERROR) {
1818                         g_relation_destroy(uid_mapping);
1819                         imap_lep_set_free(seq_list);
1820                         statusbar_pop_all();
1821                         return -1;
1822                 }
1823         }
1824
1825         for (cur = msglist; cur != NULL; cur = g_slist_next(cur)) {
1826                 MsgInfo *msginfo = (MsgInfo *)cur->data;
1827                 GTuples *tuples;
1828
1829                 tuples = g_relation_select(uid_mapping, 
1830                                            GINT_TO_POINTER(msginfo->msgnum),
1831                                            0);
1832                 if (tuples->len > 0) {
1833                         gint num = GPOINTER_TO_INT(g_tuples_index(tuples, 0, 1));
1834                         g_relation_insert(relation, msginfo,
1835                                           GINT_TO_POINTER(num));
1836                         if (num > last_num)
1837                                 last_num = num;
1838                         debug_print("copied message %d as %d\n", msginfo->msgnum, num);
1839                         /* put the local file in the imapcache, so that we don't
1840                          * have to fetch it back later. */
1841                         if (num > 0) {
1842                                 gchar *cache_path = folder_item_get_path(msginfo->folder);
1843                                 gchar *real_file = g_strconcat(
1844                                         cache_path, G_DIR_SEPARATOR_S, 
1845                                         itos(msginfo->msgnum), NULL);
1846                                 gchar *cache_file = NULL;
1847                                 g_free(cache_path);
1848                                 cache_path = folder_item_get_path(dest);
1849                                 cache_file = g_strconcat(
1850                                         cache_path, G_DIR_SEPARATOR_S, 
1851                                         itos(num), NULL);
1852                                 if (!is_dir_exist(cache_path))
1853                                         make_dir_hier(cache_path);
1854                                 if (is_file_exist(real_file) && is_dir_exist(cache_path)) {
1855                                         copy_file(real_file, cache_file, TRUE);
1856                                         debug_print("copied to cache: %s\n", cache_file);
1857                                 }
1858                                 g_free(real_file);
1859                                 g_free(cache_file);
1860                                 g_free(cache_path);
1861                         }
1862                 } else
1863                         g_relation_insert(relation, msginfo,
1864                                           GINT_TO_POINTER(0));
1865                 g_tuples_destroy(tuples);
1866         }
1867         statusbar_pop_all();
1868
1869         g_relation_destroy(uid_mapping);
1870         imap_lep_set_free(seq_list);
1871
1872         g_free(destdir);
1873         
1874         IMAP_FOLDER_ITEM(dest)->lastuid = 0;
1875         IMAP_FOLDER_ITEM(dest)->uid_next = 0;
1876         g_slist_free(IMAP_FOLDER_ITEM(dest)->uid_list);
1877         IMAP_FOLDER_ITEM(dest)->uid_list = NULL;
1878
1879         imap_scan_required(folder, dest);
1880         if (ok == MAILIMAP_NO_ERROR)
1881                 return last_num;
1882         else
1883                 return -1;
1884 }
1885
1886 static gint imap_copy_msg(Folder *folder, FolderItem *dest, MsgInfo *msginfo)
1887 {
1888         GSList msglist;
1889
1890         g_return_val_if_fail(msginfo != NULL, -1);
1891
1892         msglist.data = msginfo;
1893         msglist.next = NULL;
1894
1895         return imap_copy_msgs(folder, dest, &msglist, NULL);
1896 }
1897
1898 static gint imap_copy_msgs(Folder *folder, FolderItem *dest, 
1899                     MsgInfoList *msglist, GRelation *relation)
1900 {
1901         MsgInfo *msginfo;
1902         gint ret;
1903
1904         g_return_val_if_fail(folder != NULL, -1);
1905         g_return_val_if_fail(dest != NULL, -1);
1906         g_return_val_if_fail(msglist != NULL, -1);
1907
1908         msginfo = (MsgInfo *)msglist->data;
1909         g_return_val_if_fail(msginfo->folder != NULL, -1);
1910
1911         ret = imap_do_copy_msgs(folder, dest, msglist, relation);
1912         return ret;
1913 }
1914
1915
1916 static gint imap_do_remove_msgs(Folder *folder, FolderItem *dest, 
1917                                 MsgInfoList *msglist, GRelation *relation)
1918 {
1919         gchar *destdir, *dir;
1920         GSList *numlist = NULL, *cur;
1921         MsgInfo *msginfo;
1922         IMAPSession *session;
1923         gint ok = MAILIMAP_NO_ERROR;
1924         GRelation *uid_mapping;
1925         
1926         g_return_val_if_fail(folder != NULL, -1);
1927         g_return_val_if_fail(dest != NULL, -1);
1928         g_return_val_if_fail(msglist != NULL, -1);
1929
1930         debug_print("getting session...\n");
1931         session = imap_session_get(folder);
1932         if (!session) {
1933                 return -1;
1934         }
1935
1936         lock_session(session); /* unlocked later in the function */
1937
1938         msginfo = (MsgInfo *)msglist->data;
1939
1940         ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder,
1941                          NULL, NULL, NULL, NULL, NULL, FALSE);
1942         if (ok != MAILIMAP_NO_ERROR) {
1943                 return ok;
1944         }
1945
1946         destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path);
1947         for (cur = msglist; cur; cur = cur->next) {
1948                 msginfo = (MsgInfo *)cur->data;
1949                 if (!MSG_IS_DELETED(msginfo->flags))
1950                         numlist = g_slist_prepend(numlist, GINT_TO_POINTER(msginfo->msgnum));
1951         }
1952         numlist = g_slist_reverse(numlist);
1953
1954         uid_mapping = g_relation_new(2);
1955         g_relation_index(uid_mapping, 0, g_direct_hash, g_direct_equal);
1956
1957         if (numlist != NULL) {
1958                 ok = imap_set_message_flags
1959                         (session, IMAP_FOLDER_ITEM(msginfo->folder), numlist, IMAP_FLAG_DELETED, NULL, TRUE);
1960                 if (ok != MAILIMAP_NO_ERROR) {
1961                         log_warning(LOG_PROTOCOL, _("can't set deleted flags\n"));
1962                         return ok;
1963                 }
1964         } /* else we just need to expunge */
1965         ok = imap_cmd_expunge(session);
1966         if (ok != MAILIMAP_NO_ERROR) {
1967                 log_warning(LOG_PROTOCOL, _("can't expunge\n"));
1968                 return ok;
1969         }
1970         
1971         session->folder_content_changed = TRUE;
1972         unlock_session(session);
1973
1974         dir = folder_item_get_path(msginfo->folder);
1975         if (is_dir_exist(dir)) {
1976                 for (cur = msglist; cur; cur = cur->next) {
1977                         msginfo = (MsgInfo *)cur->data;
1978                         remove_numbered_files(dir, msginfo->msgnum, msginfo->msgnum);
1979                 }
1980         }
1981         g_free(dir);
1982
1983         g_relation_destroy(uid_mapping);
1984         g_slist_free(numlist);
1985
1986         imap_scan_required(folder, dest);
1987
1988         g_free(destdir);
1989         if (ok == MAILIMAP_NO_ERROR)
1990                 return 0;
1991         else
1992                 return -1;
1993 }
1994
1995 static gint imap_remove_msgs(Folder *folder, FolderItem *dest, 
1996                     MsgInfoList *msglist, GRelation *relation)
1997 {
1998         MsgInfo *msginfo;
1999
2000         g_return_val_if_fail(folder != NULL, -1);
2001         g_return_val_if_fail(dest != NULL, -1);
2002         if (msglist == NULL)
2003                 return 0;
2004
2005         msginfo = (MsgInfo *)msglist->data;
2006         g_return_val_if_fail(msginfo->folder != NULL, -1);
2007
2008         return imap_do_remove_msgs(folder, dest, msglist, relation);
2009 }
2010
2011 static gint imap_remove_all_msg(Folder *folder, FolderItem *item)
2012 {
2013         GSList *list = folder_item_get_msg_list(item);
2014         gint res = imap_remove_msgs(folder, item, list, NULL);
2015         procmsg_msg_list_free(list);
2016         return res;
2017 }
2018
2019 static gboolean imap_is_msg_changed(Folder *folder, FolderItem *item,
2020                                     MsgInfo *msginfo)
2021 {
2022         /* TODO: properly implement this method */
2023         return FALSE;
2024 }
2025
2026 static gint imap_close(Folder *folder, FolderItem *item)
2027 {
2028         return 0;
2029 }
2030
2031 static gint imap_scan_tree_real(Folder *folder, gboolean subs_only)
2032 {
2033         FolderItem *item = NULL;
2034         IMAPSession *session;
2035         gchar *root_folder = NULL;
2036
2037         g_return_val_if_fail(folder != NULL, -1);
2038         g_return_val_if_fail(folder->account != NULL, -1);
2039
2040         debug_print("getting session...\n");
2041         session = imap_session_get(folder);
2042         if (!session) {
2043                 if (!folder->node) {
2044                         folder_tree_destroy(folder);
2045                         item = folder_item_new(folder, folder->name, NULL);
2046                         item->folder = folder;
2047                         folder->node = item->node = g_node_new(item);
2048                 }
2049                 return -1;
2050         }
2051
2052         if (folder->account->imap_dir && *folder->account->imap_dir) {
2053                 gchar *real_path;
2054                 int r;
2055                 clist * lep_list;
2056
2057                 Xstrdup_a(root_folder, folder->account->imap_dir, {return -1;});
2058                 extract_quote(root_folder, '"');
2059                 subst_char(root_folder,
2060                            imap_get_path_separator(session, IMAP_FOLDER(folder),
2061                                                    root_folder),
2062                            '/');
2063                 strtailchomp(root_folder, '/');
2064                 real_path = imap_get_real_path
2065                         (session, IMAP_FOLDER(folder), root_folder);
2066                 debug_print("IMAP root directory: %s\n", real_path);
2067
2068                 /* check if root directory exist */
2069
2070                 r = imap_threaded_list(session->folder, "", real_path,
2071                                        &lep_list);
2072
2073                 if (r != MAILIMAP_NO_ERROR)
2074                         imap_handle_error(SESSION(session), r);
2075
2076                 if ((r != MAILIMAP_NO_ERROR) || (clist_count(lep_list) == 0)) {
2077                         if (!folder->node) {
2078                                 item = folder_item_new(folder, folder->name, NULL);
2079                                 item->folder = folder;
2080                                 folder->node = item->node = g_node_new(item);
2081                         }
2082                         return -1;
2083                 }
2084                 mailimap_list_result_free(lep_list);
2085                                 
2086                 g_free(real_path);
2087         }
2088
2089         if (folder->node)
2090                 item = FOLDER_ITEM(folder->node->data);
2091                 
2092         if (item && !item->path && root_folder) {
2093                 item->path = g_strdup(root_folder);
2094         }
2095
2096         if (!item || ((item->path || root_folder) &&
2097                       strcmp2(item->path, root_folder) != 0)) {
2098                 folder_tree_destroy(folder);
2099                 item = folder_item_new(folder, folder->name, root_folder);
2100                 item->folder = folder;
2101                 folder->node = item->node = g_node_new(item);
2102         }
2103
2104         imap_scan_tree_recursive(session, FOLDER_ITEM(folder->node->data), subs_only);
2105         imap_create_missing_folders(folder);
2106
2107         return 0;
2108 }
2109
2110 static gint imap_scan_tree(Folder *folder)
2111 {
2112         gboolean subs_only = FALSE;
2113         if (folder->account) {
2114                 debug_print(" scanning only subs %d\n", folder->account->imap_subsonly);
2115                 subs_only = folder->account->imap_subsonly;
2116         }
2117         return imap_scan_tree_real(folder, subs_only);
2118 }
2119
2120 static gint imap_scan_tree_recursive(IMAPSession *session, FolderItem *item, gboolean subs_only)
2121 {
2122         Folder *folder;
2123         IMAPFolder *imapfolder;
2124         FolderItem *new_item;
2125         GSList *item_list, *cur;
2126         GNode *node;
2127         gchar *real_path;
2128         gchar *wildcard_path;
2129         gchar separator;
2130         gchar wildcard[3];
2131         clist * lep_list;
2132         int r;
2133         
2134         g_return_val_if_fail(item != NULL, -1);
2135         g_return_val_if_fail(item->folder != NULL, -1);
2136         g_return_val_if_fail(item->no_sub == FALSE, -1);
2137
2138         folder = item->folder;
2139         imapfolder = IMAP_FOLDER(folder);
2140
2141         separator = imap_get_path_separator(session, imapfolder, item->path);
2142
2143         if (folder->ui_func)
2144                 folder->ui_func(folder, item, folder->ui_func_data);
2145
2146         if (item->path) {
2147                 wildcard[0] = separator;
2148                 wildcard[1] = '%';
2149                 wildcard[2] = '\0';
2150                 real_path = imap_get_real_path(session, imapfolder, item->path);
2151         } else {
2152                 wildcard[0] = '%';
2153                 wildcard[1] = '\0';
2154                 real_path = g_strdup("");
2155         }
2156
2157         Xstrcat_a(wildcard_path, real_path, wildcard,
2158                   {g_free(real_path); return MAILIMAP_ERROR_BAD_STATE;});
2159         lep_list = NULL;
2160         
2161         if (subs_only)
2162                 r = imap_threaded_lsub(folder, "", wildcard_path, &lep_list);
2163         else
2164                 r = imap_threaded_list(folder, "", wildcard_path, &lep_list);
2165
2166         if (r != MAILIMAP_NO_ERROR) {
2167                 imap_handle_error(SESSION(session), r);
2168                 item_list = NULL;
2169         }
2170         else {
2171                 item_list = imap_list_from_lep(imapfolder,
2172                                                lep_list, real_path, FALSE);
2173                 mailimap_list_result_free(lep_list);
2174         }
2175         
2176         g_free(real_path);
2177
2178         node = item->node->children;
2179         while (node != NULL) {
2180                 FolderItem *old_item = FOLDER_ITEM(node->data);
2181                 GNode *next = node->next;
2182
2183                 new_item = NULL;
2184                 for (cur = item_list; cur != NULL; cur = cur->next) {
2185                         FolderItem *cur_item = FOLDER_ITEM(cur->data);
2186                         if (!strcmp2(old_item->path, cur_item->path)) {
2187                                 new_item = cur_item;
2188                                 break;
2189                         }
2190                 }
2191                 if (!new_item) {
2192                         if (old_item && old_item->path && !strcmp(old_item->path, "INBOX")) {
2193                                 debug_print("not removing INBOX\n");
2194                         } else {
2195                                 debug_print("folder '%s' not found. removing...\n",
2196                                             old_item->path);
2197                                 folder_item_remove(old_item);
2198                         }
2199                 } else {
2200                         old_item->no_sub = new_item->no_sub;
2201                         old_item->no_select = new_item->no_select;
2202                         if (old_item->no_sub == TRUE && node->children) {
2203                                 debug_print("folder '%s' doesn't have "
2204                                             "subfolders. removing...\n",
2205                                             old_item->path);
2206                                 folder_item_remove_children(old_item);
2207                         }
2208                 }
2209
2210                 node = next;
2211         }
2212
2213         for (cur = item_list; cur != NULL; cur = cur->next) {
2214                 FolderItem *cur_item = FOLDER_ITEM(cur->data);
2215                 new_item = NULL;
2216
2217                 for (node = item->node->children; node != NULL;
2218                      node = node->next) {
2219                         if (!strcmp2(FOLDER_ITEM(node->data)->path,
2220                                      cur_item->path)) {
2221                                 new_item = FOLDER_ITEM(node->data);
2222                                 folder_item_destroy(cur_item);
2223                                 cur_item = NULL;
2224                                 break;
2225                         }
2226                 }
2227                 if (!new_item) {
2228                         new_item = cur_item;
2229                         debug_print("new folder '%s' found.\n", new_item->path);
2230                         folder_item_append(item, new_item);
2231                 }
2232
2233                 if (!strcmp(new_item->path, "INBOX")) {
2234                         new_item->stype = F_INBOX;
2235                         folder->inbox = new_item;
2236                 } else if (!folder_item_parent(item) || item->stype == F_INBOX) {
2237                         gchar *base;
2238
2239                         base = g_path_get_basename(new_item->path);
2240
2241                         if (!folder->outbox && !g_ascii_strcasecmp(base, "Sent")) {
2242                                 new_item->stype = F_OUTBOX;
2243                                 folder->outbox = new_item;
2244                         } else if (!folder->draft && !g_ascii_strcasecmp(base, "Drafts")) {
2245                                 new_item->stype = F_DRAFT;
2246                                 folder->draft = new_item;
2247                         } else if (!folder->queue && !g_ascii_strcasecmp(base, "Queue")) {
2248                                 new_item->stype = F_QUEUE;
2249                                 folder->queue = new_item;
2250                         } else if (!folder->trash && !g_ascii_strcasecmp(base, "Trash")) {
2251                                 new_item->stype = F_TRASH;
2252                                 folder->trash = new_item;
2253                         }
2254                         g_free(base);
2255                 }
2256
2257                 if (new_item->no_sub == FALSE)
2258                         imap_scan_tree_recursive(session, new_item, subs_only);
2259         }
2260
2261         g_slist_free(item_list);
2262
2263         return MAILIMAP_NO_ERROR;
2264 }
2265
2266 GList *imap_scan_subtree(Folder *folder, FolderItem *item, gboolean unsubs_only, gboolean recursive)
2267 {
2268         IMAPSession *session = imap_session_get(folder);
2269         gchar *real_path;
2270         gchar *wildcard_path;
2271         gchar separator;
2272         gchar wildcard[3];
2273         clist * lep_list;
2274         GSList *item_list = NULL, *cur;
2275         GList *child_list = NULL, *tmplist = NULL;
2276         GSList *sub_list = NULL;
2277         int r;
2278
2279         if (!session)
2280                 return NULL;
2281
2282         separator = imap_get_path_separator(session, IMAP_FOLDER(folder), item->path);
2283
2284         if (item->path) {
2285                 wildcard[0] = separator;
2286                 wildcard[1] = '%';
2287                 wildcard[2] = '\0';
2288                 real_path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path);
2289         } else {
2290                 wildcard[0] = '%';
2291                 wildcard[1] = '\0';
2292                 real_path = g_strdup("");
2293         }
2294
2295         Xstrcat_a(wildcard_path, real_path, wildcard,
2296                   {g_free(real_path); return NULL;});
2297         lep_list = NULL;
2298         
2299         if (unsubs_only)
2300                 statusbar_print_all(_("Looking for unsubscribed folders in %s..."), 
2301                                 item->path?item->path:item->name);
2302         else
2303                 statusbar_print_all(_("Looking for subfolders of %s..."), 
2304                                 item->path?item->path:item->name);
2305
2306         r = imap_threaded_list(folder, "", wildcard_path, &lep_list);
2307         if (r) {
2308                 statusbar_pop_all();
2309                 return NULL;
2310         }
2311         item_list = imap_list_from_lep(IMAP_FOLDER(folder),
2312                                lep_list, real_path, FALSE);
2313         mailimap_list_result_free(lep_list);
2314
2315         for (cur = item_list; cur != NULL; cur = cur->next) {
2316                 FolderItem *cur_item = FOLDER_ITEM(cur->data);
2317                 if (recursive) {
2318                         tmplist = imap_scan_subtree(folder, cur_item, 
2319                                         unsubs_only, recursive);
2320                         if (tmplist)
2321                                 child_list = g_list_concat(child_list, tmplist);
2322                 }
2323                 child_list = g_list_prepend(child_list,
2324                                 imap_get_real_path(session, 
2325                                         IMAP_FOLDER(folder), cur_item->path));
2326                 
2327                 folder_item_destroy(cur_item);
2328         }
2329         child_list = g_list_reverse(child_list);
2330         g_slist_free(item_list);
2331
2332         if (unsubs_only) {
2333                 r = imap_threaded_lsub(folder, "", wildcard_path, &lep_list);
2334                 if (r) {
2335                         statusbar_pop_all();
2336                         return NULL;
2337                 }
2338                 sub_list = imap_list_from_lep(IMAP_FOLDER(folder),
2339                                        lep_list, real_path, FALSE);
2340                 mailimap_list_result_free(lep_list);
2341
2342                 for (cur = sub_list; cur != NULL; cur = cur->next) {
2343                         FolderItem *cur_item = FOLDER_ITEM(cur->data);
2344                         GList *oldlitem = NULL;
2345                         gchar *tmp = imap_get_real_path(session, 
2346                                         IMAP_FOLDER(folder), cur_item->path);
2347                         folder_item_destroy(cur_item);
2348                         oldlitem = g_list_find_custom(
2349                                         child_list, tmp, (GCompareFunc)strcmp2);
2350                         if (oldlitem) {
2351                                 child_list = g_list_remove_link(child_list, oldlitem);
2352                                 g_free(oldlitem->data);
2353                                 g_list_free(oldlitem);
2354                         }
2355                         g_free(tmp);
2356                 }
2357         }
2358
2359         statusbar_pop_all();
2360
2361         return child_list;
2362 }
2363
2364 static gint imap_create_tree(Folder *folder)
2365 {
2366         g_return_val_if_fail(folder != NULL, -1);
2367         g_return_val_if_fail(folder->node != NULL, -1);
2368         g_return_val_if_fail(folder->node->data != NULL, -1);
2369         g_return_val_if_fail(folder->account != NULL, -1);
2370
2371         imap_scan_tree(folder);
2372         imap_create_missing_folders(folder);
2373
2374         return 0;
2375 }
2376
2377 static void imap_create_missing_folders(Folder *folder)
2378 {
2379         g_return_if_fail(folder != NULL);
2380
2381         if (!folder->inbox)
2382                 folder->inbox = imap_create_special_folder
2383                         (folder, F_INBOX, "INBOX");
2384         if (!folder->trash)
2385                 folder->trash = imap_create_special_folder
2386                         (folder, F_TRASH, "Trash");
2387         if (!folder->queue)
2388                 folder->queue = imap_create_special_folder
2389                         (folder, F_QUEUE, "Queue");
2390         if (!folder->outbox)
2391                 folder->outbox = imap_create_special_folder
2392                         (folder, F_OUTBOX, "Sent");
2393         if (!folder->draft)
2394                 folder->draft = imap_create_special_folder
2395                         (folder, F_DRAFT, "Drafts");
2396 }
2397
2398 static FolderItem *imap_create_special_folder(Folder *folder,
2399                                               SpecialFolderItemType stype,
2400                                               const gchar *name)
2401 {
2402         FolderItem *item;
2403         FolderItem *new_item;
2404
2405         g_return_val_if_fail(folder != NULL, NULL);
2406         g_return_val_if_fail(folder->node != NULL, NULL);
2407         g_return_val_if_fail(folder->node->data != NULL, NULL);
2408         g_return_val_if_fail(folder->account != NULL, NULL);
2409         g_return_val_if_fail(name != NULL, NULL);
2410
2411         item = FOLDER_ITEM(folder->node->data);
2412         new_item = imap_create_folder(folder, item, name);
2413
2414         if (!new_item) {
2415                 g_warning("Can't create '%s'\n", name);
2416                 if (!folder->inbox) return NULL;
2417
2418                 new_item = imap_create_folder(folder, folder->inbox, name);
2419                 if (!new_item)
2420                         g_warning("Can't create '%s' under INBOX\n", name);
2421                 else
2422                         new_item->stype = stype;
2423         } else
2424                 new_item->stype = stype;
2425
2426         return new_item;
2427 }
2428
2429 static gchar *imap_folder_get_path(Folder *folder)
2430 {
2431         gchar *folder_path;
2432
2433         g_return_val_if_fail(folder != NULL, NULL);
2434         g_return_val_if_fail(folder->account != NULL, NULL);
2435
2436         folder_path = g_strconcat(get_imap_cache_dir(),
2437                                   G_DIR_SEPARATOR_S,
2438                                   folder->account->recv_server,
2439                                   G_DIR_SEPARATOR_S,
2440                                   folder->account->userid,
2441                                   NULL);
2442
2443         return folder_path;
2444 }
2445
2446 static gchar *imap_item_get_path(Folder *folder, FolderItem *item)
2447 {
2448         gchar *folder_path, *path;
2449
2450         g_return_val_if_fail(folder != NULL, NULL);
2451         g_return_val_if_fail(item != NULL, NULL);
2452         folder_path = imap_folder_get_path(folder);
2453
2454         g_return_val_if_fail(folder_path != NULL, NULL);
2455         if (folder_path[0] == G_DIR_SEPARATOR) {
2456                 if (item->path)
2457                         path = g_strconcat(folder_path, G_DIR_SEPARATOR_S,
2458                                            item->path, NULL);
2459                 else
2460                         path = g_strdup(folder_path);
2461         } else {
2462                 if (item->path)
2463                         path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
2464                                            folder_path, G_DIR_SEPARATOR_S,
2465                                            item->path, NULL);
2466                 else
2467                         path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
2468                                            folder_path, NULL);
2469         }
2470         g_free(folder_path);
2471
2472         return path;
2473 }
2474
2475 static FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
2476                                const gchar *name)
2477 {
2478         gchar *dirpath, *imap_path;
2479         IMAPSession *session;
2480         FolderItem *new_item;
2481         gchar separator;
2482         gchar *new_name;
2483         const gchar *p;
2484         gint ok;
2485         gboolean no_select = FALSE, no_sub = FALSE;
2486         gboolean exist = FALSE;
2487         
2488         g_return_val_if_fail(folder != NULL, NULL);
2489         g_return_val_if_fail(folder->account != NULL, NULL);
2490         g_return_val_if_fail(parent != NULL, NULL);
2491         g_return_val_if_fail(name != NULL, NULL);
2492
2493         debug_print("getting session...\n");
2494         session = imap_session_get(folder);
2495         if (!session) {
2496                 return NULL;
2497         }
2498
2499         if (!folder_item_parent(parent) && strcmp(name, "INBOX") == 0) {
2500                 dirpath = g_strdup(name);
2501         }else if (parent->path)
2502                 dirpath = g_strconcat(parent->path, "/", name, NULL);
2503         else if ((p = strchr(name, '/')) != NULL && *(p + 1) != '\0')
2504                 dirpath = g_strdup(name);
2505         else if (folder->account->imap_dir && *folder->account->imap_dir) {
2506                 gchar *imap_dir;
2507
2508                 Xstrdup_a(imap_dir, folder->account->imap_dir, {return NULL;});
2509                 strtailchomp(imap_dir, '/');
2510                 dirpath = g_strconcat(imap_dir, "/", name, NULL);
2511         } else
2512                 dirpath = g_strdup(name);
2513                 
2514         
2515
2516         /* keep trailing directory separator to create a folder that contains
2517            sub folder */
2518         imap_path = imap_utf8_to_modified_utf7(dirpath, FALSE);
2519
2520         strtailchomp(dirpath, '/');
2521         Xstrdup_a(new_name, name, {
2522                 g_free(dirpath); 
2523                 return NULL;});
2524
2525         separator = imap_get_path_separator(session, IMAP_FOLDER(folder), imap_path);
2526         imap_path_separator_subst(imap_path, separator);
2527         /* remove trailing / for display */
2528         strtailchomp(new_name, '/');
2529
2530         if (strcmp(dirpath, "INBOX") != 0) {
2531                 GPtrArray *argbuf;
2532                 int r;
2533                 clist * lep_list;
2534                 
2535                 argbuf = g_ptr_array_new();
2536                 r = imap_threaded_list(folder, "", imap_path, &lep_list);
2537                 if (r != MAILIMAP_NO_ERROR) {
2538                         imap_handle_error(SESSION(session), r);
2539                         log_warning(LOG_PROTOCOL, _("can't create mailbox: LIST failed\n"));
2540                         g_free(imap_path);
2541                         g_free(dirpath);
2542                         ptr_array_free_strings(argbuf);
2543                         g_ptr_array_free(argbuf, TRUE);
2544                         return NULL;
2545                 }
2546                 
2547                 if (clist_count(lep_list) > 0)
2548                         exist = TRUE;
2549                 mailimap_list_result_free(lep_list);
2550                 lep_list = NULL;
2551                 if (!exist) {
2552                         ok = imap_cmd_create(session, imap_path);
2553                         if (ok != MAILIMAP_NO_ERROR) {
2554                                 log_warning(LOG_PROTOCOL, _("can't create mailbox\n"));
2555                                 g_free(imap_path);
2556                                 g_free(dirpath);
2557                                 return NULL;
2558                         }
2559                         r = imap_threaded_list(folder, "", imap_path, &lep_list);
2560                         if (r == MAILIMAP_NO_ERROR) {
2561                                 GSList *item_list = imap_list_from_lep(IMAP_FOLDER(folder),
2562                                                lep_list, dirpath, TRUE);
2563                                 if (item_list) {
2564                                         FolderItem *cur_item = FOLDER_ITEM(item_list->data);
2565                                         no_select = cur_item->no_select;
2566                                         no_sub = cur_item->no_sub;
2567                                         g_slist_free(item_list);
2568                                 } 
2569                                 mailimap_list_result_free(lep_list);
2570                         } else {
2571                                 imap_handle_error(SESSION(session), r);
2572                         }
2573                 }
2574                 imap_threaded_subscribe(folder, imap_path, TRUE);
2575         } else {
2576                 clist *lep_list;
2577                 int r;
2578                 /* just get flags */
2579                 r = imap_threaded_list(folder, "", "INBOX", &lep_list);
2580                 if (r == MAILIMAP_NO_ERROR) {
2581                         GSList *item_list = imap_list_from_lep(IMAP_FOLDER(folder),
2582                                        lep_list, dirpath, TRUE);
2583                         if (item_list) {
2584                                 FolderItem *cur_item = FOLDER_ITEM(item_list->data);
2585                                 no_select = cur_item->no_select;
2586                                 no_sub = cur_item->no_sub;
2587                                 g_slist_free(item_list);
2588                         } 
2589                         mailimap_list_result_free(lep_list);
2590                 } else {
2591                         imap_handle_error(SESSION(session), r);
2592                 }
2593         }
2594
2595         new_item = folder_item_new(folder, new_name, dirpath);
2596         new_item->no_select = no_select;
2597         new_item->no_sub = no_sub;
2598         folder_item_append(parent, new_item);
2599         g_free(imap_path);
2600         g_free(dirpath);
2601
2602         dirpath = folder_item_get_path(new_item);
2603         if (!is_dir_exist(dirpath))
2604                 make_dir_hier(dirpath);
2605         g_free(dirpath);
2606
2607         if (exist) {
2608                 /* folder existed, scan it */
2609                 imap_scan_required(folder, new_item);
2610                 folder_item_scan_full(new_item, FALSE);
2611         }
2612
2613         return new_item;
2614 }
2615
2616 static gint imap_rename_folder(Folder *folder, FolderItem *item,
2617                                const gchar *name)
2618 {
2619         gchar *dirpath;
2620         gchar *newpath;
2621         gchar *real_oldpath;
2622         gchar *real_newpath;
2623         gchar *paths[2];
2624         gchar *old_cache_dir;
2625         gchar *new_cache_dir;
2626         IMAPSession *session;
2627         gchar separator;
2628         gint ok;
2629         gint exists, recent, unseen;
2630         guint32 uid_validity;
2631
2632         g_return_val_if_fail(folder != NULL, -1);
2633         g_return_val_if_fail(item != NULL, -1);
2634         g_return_val_if_fail(item->path != NULL, -1);
2635         g_return_val_if_fail(name != NULL, -1);
2636
2637         debug_print("getting session...\n");
2638         session = imap_session_get(folder);
2639         if (!session) {
2640                 return -1;
2641         }
2642
2643         if (strchr(name, imap_get_path_separator(session, IMAP_FOLDER(folder), item->path)) != NULL) {
2644                 g_warning(_("New folder name must not contain the namespace "
2645                             "path separator"));
2646                 return -1;
2647         }
2648
2649         real_oldpath = imap_get_real_path(session, IMAP_FOLDER(folder), item->path);
2650
2651         g_free(session->mbox);
2652         session->mbox = NULL;
2653         session->exists = 0;
2654         session->recent = 0;
2655         session->expunge = 0;
2656         ok = imap_cmd_examine(session, "INBOX",
2657                               &exists, &recent, &unseen, &uid_validity, FALSE);
2658         if (ok != MAILIMAP_NO_ERROR) {
2659                 g_free(real_oldpath);
2660                 return -1;
2661         }
2662
2663         separator = imap_get_path_separator(session, IMAP_FOLDER(folder), item->path);
2664         if (strchr(item->path, G_DIR_SEPARATOR)) {
2665                 dirpath = g_path_get_dirname(item->path);
2666                 newpath = g_strconcat(dirpath, G_DIR_SEPARATOR_S, name, NULL);
2667                 g_free(dirpath);
2668         } else
2669                 newpath = g_strdup(name);
2670
2671         real_newpath = imap_utf8_to_modified_utf7(newpath, FALSE);
2672         imap_path_separator_subst(real_newpath, separator);
2673
2674         ok = imap_cmd_rename(session, real_oldpath, real_newpath);
2675         if (ok != MAILIMAP_NO_ERROR) {
2676                 log_warning(LOG_PROTOCOL, _("can't rename mailbox: %s to %s\n"),
2677                             real_oldpath, real_newpath);
2678                 g_free(real_oldpath);
2679                 g_free(newpath);
2680                 g_free(real_newpath);
2681                 return -1;
2682         }
2683         g_free(item->name);
2684         item->name = g_strdup(name);
2685
2686         old_cache_dir = folder_item_get_path(item);
2687
2688         paths[0] = g_strdup(item->path);
2689         paths[1] = newpath;
2690         g_node_traverse(item->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1,
2691                         imap_rename_folder_func, paths);
2692
2693         if (is_dir_exist(old_cache_dir)) {
2694                 new_cache_dir = folder_item_get_path(item);
2695                 if (rename(old_cache_dir, new_cache_dir) < 0) {
2696                         FILE_OP_ERROR(old_cache_dir, "rename");
2697                 }
2698                 g_free(new_cache_dir);
2699         }
2700
2701         g_free(old_cache_dir);
2702         g_free(paths[0]);
2703         g_free(newpath);
2704         g_free(real_oldpath);
2705         g_free(real_newpath);
2706         return 0;
2707 }
2708
2709 gint imap_subscribe(Folder *folder, FolderItem *item, gchar *rpath, gboolean sub)
2710 {
2711         gchar *path;
2712         gint r = -1;
2713         IMAPSession *session;
2714         debug_print("getting session...\n");
2715
2716         session = imap_session_get(folder);
2717         if (!session) {
2718                 return -1;
2719         }
2720         if (item && item->path) {
2721                 path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path);
2722                 if (!path)
2723                         return -1;
2724                 if (!strcmp(path, "INBOX") && sub == FALSE)
2725                         return -1;
2726                 debug_print("%ssubscribing %s\n", sub?"":"un", path);
2727                 r = imap_threaded_subscribe(folder, path, sub);
2728                 g_free(path);
2729         } else if (rpath) {
2730                 r = imap_threaded_subscribe(folder, rpath, sub);
2731         } else
2732                 return -1;
2733         return r;
2734 }
2735
2736 static gint imap_remove_folder_real(Folder *folder, FolderItem *item)
2737 {
2738         gint ok;
2739         IMAPSession *session;
2740         gchar *path;
2741         gchar *cache_dir;
2742         gboolean selected_folder;
2743
2744         g_return_val_if_fail(folder != NULL, -1);
2745         g_return_val_if_fail(item != NULL, -1);
2746         g_return_val_if_fail(item->path != NULL, -1);
2747
2748         debug_print("getting session...\n");
2749         session = imap_session_get(folder);
2750         if (!session) {
2751                 return -1;
2752         }
2753         path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path);
2754
2755         imap_threaded_subscribe(folder, path, FALSE);
2756
2757         selected_folder = (session->mbox != NULL) &&
2758                           (!strcmp(session->mbox, item->path));
2759         if (selected_folder) {
2760                 ok = imap_cmd_close(session);
2761                 if (ok != MAILIMAP_NO_ERROR) {
2762                         debug_print("close err %d\n", ok);
2763                         imap_handle_error(SESSION(session), ok);
2764                         return ok;
2765                 }
2766         }
2767         ok = imap_cmd_delete(session, path);
2768         if (ok != MAILIMAP_NO_ERROR) {
2769                 gchar *tmp = g_strdup_printf("%s%c", path, 
2770                                 imap_get_path_separator(session, IMAP_FOLDER(folder), path));
2771                 g_free(path);
2772                 path = tmp;
2773                 ok = imap_cmd_delete(session, path);
2774         }
2775
2776         if (ok != MAILIMAP_NO_ERROR) {
2777                 log_warning(LOG_PROTOCOL, _("can't delete mailbox\n"));
2778                 g_free(path);
2779                 return -1;
2780         }
2781
2782         g_free(path);
2783         cache_dir = folder_item_get_path(item);
2784         if (is_dir_exist(cache_dir) && remove_dir_recursive(cache_dir) < 0)
2785                 g_warning("can't remove directory '%s'\n", cache_dir);
2786         g_free(cache_dir);
2787         folder_item_remove(item);
2788         return 0;
2789 }
2790
2791 static gint imap_remove_folder(Folder *folder, FolderItem *item)
2792 {
2793         GNode *node, *next;
2794
2795         g_return_val_if_fail(item != NULL, -1);
2796         g_return_val_if_fail(item->folder != NULL, -1);
2797         g_return_val_if_fail(item->node != NULL, -1);
2798
2799         node = item->node->children;
2800         while (node != NULL) {
2801                 next = node->next;
2802                 if (imap_remove_folder(folder, FOLDER_ITEM(node->data)) < 0)
2803                         return -1;
2804                 node = next;
2805         }
2806         debug_print("IMAP removing %s\n", item->path);
2807
2808         if (imap_remove_all_msg(folder, item) < 0)
2809                 return -1;
2810         return imap_remove_folder_real(folder, item);
2811 }
2812
2813 typedef struct _uncached_data {
2814         IMAPSession *session;
2815         FolderItem *item;
2816         MsgNumberList *numlist;
2817         guint cur;
2818         guint total;
2819         gboolean done;
2820         int ok;
2821 } uncached_data;
2822
2823 static void *imap_get_uncached_messages_thread(void *data)
2824 {
2825         uncached_data *stuff = (uncached_data *)data;
2826         IMAPSession *session = stuff->session;
2827         FolderItem *item = stuff->item;
2828         MsgNumberList *numlist = stuff->numlist;
2829         GSList *newlist = NULL;
2830         GSList *llast = NULL;
2831         GSList *seq_list, *cur;
2832         gboolean got_alien_tags = FALSE;
2833
2834         debug_print("uncached_messages\n");
2835         
2836         if (session == NULL || item == NULL || item->folder == NULL
2837             || FOLDER_CLASS(item->folder) != &imap_class) {
2838                 stuff->done = TRUE;
2839                 return NULL;
2840         }
2841         
2842         seq_list = imap_get_lep_set_from_numlist(IMAP_FOLDER(item->folder), numlist);
2843         debug_print("get msgs info\n");
2844         for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
2845                 struct mailimap_set * imapset;
2846                 unsigned int i;
2847                 int r;
2848                 carray * env_list;
2849                 int count;
2850                 
2851                 if (session->cancelled)
2852                         break;
2853                 
2854                 imapset = cur->data;
2855                 
2856                 r = imap_threaded_fetch_env(session->folder,
2857                                             imapset, &env_list);
2858                 if (r != MAILIMAP_NO_ERROR) {
2859                         imap_handle_error(SESSION(session), r);
2860                         if (is_fatal(r)) {
2861                                 stuff->ok = r;
2862                                 return NULL;
2863                         }
2864                         continue;
2865                 }
2866
2867                 session_set_access_time(SESSION(session));
2868
2869                 count = 0;
2870                 for(i = 0 ; i < carray_count(env_list) ; i += 2) {
2871                         struct imap_fetch_env_info * info;
2872                         MsgInfo * msginfo;
2873                         GSList *tags = NULL, *cur = NULL;
2874                         info = carray_get(env_list, i);
2875                         tags = carray_get(env_list, i+1);
2876                         msginfo = imap_envelope_from_lep(info, item);
2877                         if (msginfo == NULL) {
2878                                 slist_free_strings(tags);
2879                                 g_slist_free(tags);
2880                                 continue;
2881                         }
2882                         if (tags != NULL) {
2883                                 g_slist_free(msginfo->tags);
2884                                 msginfo->tags = NULL;
2885                         }
2886                         for (cur = tags; cur; cur = cur->next) {
2887                                 gchar *real_tag = imap_modified_utf7_to_utf8(cur->data, TRUE);
2888                                 gint id = 0;
2889                                 id = tags_get_id_for_str(real_tag);
2890                                 if (id == -1) {
2891                                         id = tags_add_tag(real_tag);
2892                                         got_alien_tags = TRUE;
2893                                 }
2894                                 if (!g_slist_find(msginfo->tags, GINT_TO_POINTER(id))) {
2895                                         msginfo->tags = g_slist_append(
2896                                                         msginfo->tags,
2897                                                         GINT_TO_POINTER(id));
2898                                 }
2899                                 g_free(real_tag);
2900                         }
2901                         slist_free_strings(tags);
2902                         g_slist_free(tags);
2903                         msginfo->folder = item;
2904                         if (!newlist)
2905                                 llast = newlist = g_slist_append(newlist, msginfo);
2906                         else {
2907                                 llast = g_slist_append(llast, msginfo);
2908                                 llast = llast->next;
2909                         }
2910                         count ++;
2911                 }
2912                 
2913                 imap_fetch_env_free(env_list);
2914         }
2915         
2916         if (got_alien_tags) {
2917                 tags_write_tags();
2918                 main_window_reflect_tags_changes(mainwindow_get_mainwindow());
2919         }
2920
2921         for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
2922                 struct mailimap_set * imapset;
2923                 
2924                 imapset = cur->data;
2925                 mailimap_set_free(imapset);
2926         }
2927         
2928         session_set_access_time(SESSION(session));
2929         stuff->done = TRUE;
2930         return newlist;
2931 }
2932
2933 #define MAX_MSG_NUM 50
2934
2935 static GSList *imap_get_uncached_messages(IMAPSession *session,
2936                                         FolderItem *item,
2937                                         MsgNumberList *numlist,
2938                                         int *r)
2939 {
2940         GSList *result = NULL;
2941         GSList * cur;
2942         uncached_data *data = g_new0(uncached_data, 1);
2943         int finished;
2944         
2945         finished = 0;
2946         cur = numlist;
2947         data->total = g_slist_length(numlist);
2948         data->ok = MAILIMAP_NO_ERROR;
2949         debug_print("messages list : %i\n", data->total);
2950
2951         while (cur != NULL) {
2952                 GSList * partial_result;
2953                 int count;
2954                 GSList * newlist;
2955                 GSList * llast;
2956                 
2957                 llast = NULL;
2958                 count = 0;
2959                 newlist = NULL;
2960                 while (count < MAX_MSG_NUM) {
2961                         void * p;
2962                         
2963                         p = cur->data;
2964                         
2965                         if (newlist == NULL)
2966                                 llast = newlist = g_slist_append(newlist, p);
2967                         else {
2968                                 llast = g_slist_append(llast, p);
2969                                 llast = llast->next;
2970                         }
2971                         count ++;
2972                         
2973                         cur = cur->next;
2974                         if (cur == NULL)
2975                                 break;
2976                 }
2977                 
2978                 data->done = FALSE;
2979                 data->session = session;
2980                 data->item = item;
2981                 data->numlist = newlist;
2982                 data->cur += count;
2983                 
2984                 if (prefs_common.work_offline && 
2985                     !inc_offline_should_override(FALSE,
2986                         _("Claws Mail needs network access in order "
2987                           "to access the IMAP server."))) {
2988                         g_free(data);
2989                         return NULL;
2990                 }
2991                 
2992                 partial_result =
2993                         (GSList *)imap_get_uncached_messages_thread(data);
2994                 *r = data->ok;
2995                 if (data->ok != MAILIMAP_NO_ERROR) {
2996                         goto bail;
2997                 }
2998                 statusbar_progress_all(data->cur,data->total, 1);
2999                 
3000                 g_slist_free(newlist);
3001                 
3002                 result = g_slist_concat(result, partial_result);
3003         }
3004 bail:
3005         g_free(data);
3006         
3007         statusbar_progress_all(0,0,0);
3008         statusbar_pop_all();
3009         
3010         return result;
3011 }
3012
3013 static void imap_delete_all_cached_messages(FolderItem *item)
3014 {
3015         gchar *dir;
3016
3017         g_return_if_fail(item != NULL);
3018         g_return_if_fail(item->folder != NULL);
3019         g_return_if_fail(FOLDER_CLASS(item->folder) == &imap_class);
3020
3021         debug_print("Deleting all cached messages...\n");
3022
3023         dir = folder_item_get_path(item);
3024         if (is_dir_exist(dir))
3025                 remove_all_numbered_files(dir);
3026         g_free(dir);
3027
3028         debug_print("done.\n");
3029 }
3030
3031 gchar imap_get_path_separator_for_item(FolderItem *item)
3032 {
3033         Folder *folder = NULL;
3034         IMAPFolder *imap_folder = NULL;
3035         IMAPSession *session = NULL;
3036         gchar result = '/';
3037         
3038         if (!item)
3039                 return '/';
3040         folder = item->folder;
3041         
3042         if (!folder)
3043                 return '/';
3044         
3045         imap_folder = IMAP_FOLDER(folder);
3046         
3047         if (!imap_folder)
3048                 return '/';
3049         
3050         debug_print("getting session...");
3051         session = imap_session_get(FOLDER(folder));
3052         result = imap_get_path_separator(session, imap_folder, item->path);
3053         return result;
3054 }
3055
3056 static gchar imap_refresh_path_separator(IMAPSession *session, IMAPFolder *folder, const gchar *subfolder)
3057 {
3058         clist * lep_list;
3059         int r;
3060         gchar separator = '\0';
3061         
3062         g_return_val_if_fail(session != NULL, '/');
3063         r = imap_threaded_list((Folder *)folder, "", subfolder, &lep_list);
3064         
3065         if (r != MAILIMAP_NO_ERROR) {
3066                 imap_handle_error(SESSION(session), r);
3067                 log_warning(LOG_PROTOCOL, _("LIST failed\n"));
3068                 return '\0';
3069         }
3070
3071         if (clist_count(lep_list) > 0) {
3072                 clistiter * iter = clist_begin(lep_list); 
3073                 struct mailimap_mailbox_list * mb;
3074                 mb = clist_content(iter);
3075
3076                 separator = mb->mb_delimiter;
3077                 debug_print("got separator: %c\n", folder->last_seen_separator);
3078         }
3079         mailimap_list_result_free(lep_list);
3080         return separator;
3081 }
3082
3083 static gchar imap_get_path_separator(IMAPSession *session, IMAPFolder *folder, const gchar *path)
3084 {
3085         gchar separator = '/';
3086
3087         if (folder->last_seen_separator == 0) {
3088                 folder->last_seen_separator = imap_refresh_path_separator(session, folder, "");
3089         }
3090
3091         if (folder->last_seen_separator == 0) {
3092                 folder->last_seen_separator = imap_refresh_path_separator(session, folder, "INBOX");
3093         }
3094
3095         if (folder->last_seen_separator != 0) {
3096                 debug_print("using separator: %c\n", folder->last_seen_separator);
3097                 return folder->last_seen_separator;
3098         }
3099
3100         return separator;
3101 }
3102
3103 static gchar *imap_get_real_path(IMAPSession *session, IMAPFolder *folder, const gchar *path)
3104 {
3105         gchar *real_path;
3106         gchar separator;
3107
3108         g_return_val_if_fail(folder != NULL, NULL);
3109         g_return_val_if_fail(path != NULL, NULL);
3110
3111         real_path = imap_utf8_to_modified_utf7(path, FALSE);
3112         separator = imap_get_path_separator(session, folder, path);
3113         imap_path_separator_subst(real_path, separator);
3114
3115         return real_path;
3116 }
3117
3118 static gint imap_set_message_flags(IMAPSession *session,
3119                                    IMAPFolderItem *item,
3120                                    MsgNumberList *numlist,
3121                                    IMAPFlags flags,
3122                                    GSList *tags,
3123                                    gboolean is_set)
3124 {
3125         gint ok = 0;
3126         GSList *seq_list;
3127         GSList * cur;
3128         gint total = 0;
3129         IMAPFolder *folder = NULL;
3130         GSList *sorted_list = NULL;
3131
3132         if (numlist == NULL || session == NULL)
3133                 return MAILIMAP_ERROR_BAD_STATE;
3134         
3135         folder = IMAP_FOLDER(session->folder);
3136         
3137         sorted_list = g_slist_copy(numlist);
3138         sorted_list = g_slist_sort(sorted_list, g_int_compare);
3139         
3140         cur = g_slist_last(sorted_list);
3141
3142         if (cur)
3143                 total = GPOINTER_TO_INT(cur->data);
3144         
3145         seq_list = imap_get_lep_set_from_numlist(IMAP_FOLDER(session->folder), sorted_list);
3146
3147         statusbar_print_all(_("Flagging messages..."));
3148
3149         for(cur = seq_list ; cur != NULL ; cur = g_slist_next(cur)) {
3150                 struct mailimap_set * imapset = (struct mailimap_set *)cur->data;
3151                 struct mailimap_set_item *set_item = clist_content(
3152                                                         clist_begin(imapset->set_list));
3153
3154                 statusbar_progress_all(set_item->set_first, total, 1);
3155
3156                 ok = imap_cmd_store(session, item, imapset,
3157                                     flags, tags, is_set);
3158                 statusbar_progress_all(set_item->set_last, total, 1);
3159                 if (ok != MAILIMAP_NO_ERROR && folder->max_set_size > 20) {
3160                         /* reduce max set size */
3161                         folder->max_set_size /= 2;
3162                 }
3163                 if (ok != MAILIMAP_NO_ERROR && is_fatal(ok)) {
3164                         break;
3165                 }
3166         }
3167         
3168         g_slist_free(sorted_list);
3169
3170         statusbar_progress_all(0,0,0);
3171         statusbar_pop_all();
3172
3173         imap_lep_set_free(seq_list);
3174         
3175         return ok;
3176 }
3177
3178 typedef struct _select_data {
3179         IMAPSession *session;
3180         gchar *real_path;
3181         gint *exists;
3182         gint *recent;
3183         gint *unseen;
3184         guint32 *uid_validity;
3185         gboolean done;
3186 } select_data;
3187
3188 static gint imap_select(IMAPSession *session, IMAPFolder *folder,
3189                         FolderItem *item,
3190                         gint *exists, gint *recent, gint *unseen,
3191                         guint32 *uid_validity, gint *can_create_flags,
3192                         gboolean block)
3193 {
3194         gchar *real_path;
3195         gint ok;
3196         gint exists_, recent_, unseen_;
3197         guint32 uid_validity_;
3198         gint can_create_flags_;
3199         const gchar *path = item ? item->path:NULL;
3200
3201         if (!item) {
3202                 return MAILIMAP_ERROR_BAD_STATE;
3203         }
3204
3205         if (!exists && !recent && !unseen && !uid_validity && !can_create_flags) {
3206                 if (session->mbox && strcmp(session->mbox, path) == 0)
3207                         return MAILIMAP_NO_ERROR;
3208         }
3209         if (!exists && !recent && !unseen && !uid_validity && can_create_flags) {
3210                 if (session->mbox && strcmp(session->mbox, path) == 0) {
3211                         if (IMAP_FOLDER_ITEM(item)->can_create_flags != ITEM_CAN_CREATE_FLAGS_UNKNOWN)
3212                                 return MAILIMAP_NO_ERROR;
3213                 }
3214         }
3215         if (!exists)
3216                 exists = &exists_;
3217         if (!recent)
3218                 recent = &recent_;
3219         if (!unseen)
3220                 unseen = &unseen_;
3221         if (!uid_validity)
3222                 uid_validity = &uid_validity_;
3223         if (!can_create_flags)
3224                 can_create_flags = &can_create_flags_;
3225
3226         g_free(session->mbox);
3227         session->mbox = NULL;
3228         session->exists = 0;
3229         session->recent = 0;
3230         session->expunge = 0;
3231
3232         real_path = imap_get_real_path(session, folder, path);
3233
3234         g_slist_free(IMAP_FOLDER_ITEM(item)->ok_flags);
3235         IMAP_FOLDER_ITEM(item)->ok_flags = NULL;
3236         ok = imap_cmd_select(session, real_path,
3237                              exists, recent, unseen, uid_validity, can_create_flags, 
3238                              &(IMAP_FOLDER_ITEM(item)->ok_flags), block);
3239         if (ok != MAILIMAP_NO_ERROR) {
3240                 log_warning(LOG_PROTOCOL, _("can't select folder: %s\n"), real_path);
3241         } else {
3242                 session->mbox = g_strdup(path);
3243                 session->folder_content_changed = FALSE;
3244                 session->exists = *exists;
3245                 session->recent = *recent;
3246                 session->expunge = 0;
3247                 session->unseen = *unseen;
3248                 session->uid_validity = *uid_validity;
3249                 debug_print("select: exists %d recent %d expunge %d uid_validity %d can_create_flags %d\n", 
3250                         session->exists, session->recent, session->expunge,
3251                         session->uid_validity, *can_create_flags);
3252         }
3253         if (*can_create_flags) {
3254                 IMAP_FOLDER_ITEM(item)->can_create_flags = ITEM_CAN_CREATE_FLAGS;
3255         } else {
3256                 IMAP_FOLDER_ITEM(item)->can_create_flags = ITEM_CANNOT_CREATE_FLAGS;
3257         }
3258         g_free(real_path);
3259
3260         return ok;
3261 }
3262
3263 static gint imap_status(IMAPSession *session, IMAPFolder *folder,
3264                         const gchar *path, IMAPFolderItem *item,
3265                         gint *messages,
3266                         guint32 *uid_next, guint32 *uid_validity,
3267                         gint *unseen, gboolean block)
3268 {
3269         int r;
3270         clistiter * iter;
3271         struct mailimap_mailbox_data_status * data_status;
3272         int got_values;
3273         gchar *real_path;
3274         guint mask = 0;
3275         
3276         real_path = imap_get_real_path(session, folder, path);
3277
3278         if (messages) {
3279                 mask |= 1 << 0;
3280                 *messages = 0;
3281         }
3282         if (uid_next) {
3283                 mask |= 1 << 2;
3284                 *uid_next = 0;
3285         }
3286         if (uid_validity) {
3287                 mask |= 1 << 3;
3288                 *uid_validity = 0;
3289         }
3290         if (unseen) {
3291                 mask |= 1 << 4;
3292                 *unseen = 0;
3293         }
3294         
3295         if (session->mbox != NULL &&
3296             !strcmp(session->mbox, item->item.path)) {
3297                 r = imap_cmd_close(session);
3298                 if (r != MAILIMAP_NO_ERROR) {
3299                         imap_handle_error(SESSION(session), r);
3300                         debug_print("close err %d\n", r);
3301                         return r;
3302                 }
3303         }
3304         
3305         r = imap_threaded_status(FOLDER(folder), real_path, 
3306                 &data_status, mask);
3307
3308         g_free(real_path);
3309         if (r != MAILIMAP_NO_ERROR) {
3310                 imap_handle_error(SESSION(session), r);
3311                 debug_print("status err %d\n", r);
3312                 return r;
3313         }
3314         
3315         if (data_status->st_info_list == NULL) {
3316                 mailimap_mailbox_data_status_free(data_status);
3317                 debug_print("status->st_info_list == NULL\n");
3318                 return MAILIMAP_ERROR_BAD_STATE;
3319         }
3320         
3321         got_values = 0;
3322         for(iter = clist_begin(data_status->st_info_list) ; iter != NULL ;
3323             iter = clist_next(iter)) {
3324                 struct mailimap_status_info * info;             
3325                 
3326                 info = clist_content(iter);
3327                 switch (info->st_att) {
3328                 case MAILIMAP_STATUS_ATT_MESSAGES:
3329                         if (messages) {
3330                                 * messages = info->st_value;
3331                                 got_values |= 1 << 0;
3332                         }
3333                         break;
3334                         
3335                 case MAILIMAP_STATUS_ATT_UIDNEXT:
3336                         if (uid_next) {
3337                                 * uid_next = info->st_value;
3338                                 got_values |= 1 << 2;
3339                         }
3340                         break;
3341                         
3342                 case MAILIMAP_STATUS_ATT_UIDVALIDITY:
3343                         if (uid_validity) {
3344                                 * uid_validity = info->st_value;
3345                                 got_values |= 1 << 3;
3346                         }
3347                         break;
3348                         
3349                 case MAILIMAP_STATUS_ATT_UNSEEN:
3350                         if (unseen) {
3351                                 * unseen = info->st_value;
3352                                 got_values |= 1 << 4;
3353                         }
3354                         break;
3355                 }
3356         }
3357         mailimap_mailbox_data_status_free(data_status);
3358         
3359         if (got_values != mask) {
3360                 g_warning("status: incomplete values received (%d)\n", got_values);
3361         }
3362         return MAILIMAP_NO_ERROR;
3363 }
3364
3365 static void imap_free_capabilities(IMAPSession *session)
3366 {
3367         slist_free_strings(session->capability);
3368         g_slist_free(session->capability);
3369         session->capability = NULL;
3370 }
3371
3372 /* low-level IMAP4rev1 commands */
3373
3374 static gint imap_cmd_login(IMAPSession *session,
3375                            const gchar *user, const gchar *pass,
3376                            const gchar *type)
3377 {
3378         int r;
3379         gint ok;
3380
3381         if (!strcmp(type, "LOGIN") && imap_has_capability(session, "LOGINDISABLED")) {
3382                 gint ok = MAILIMAP_ERROR_BAD_STATE;
3383                 if (imap_has_capability(session, "STARTTLS")) {
3384 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
3385                         log_warning(LOG_PROTOCOL, _("Server requires TLS to log in.\n"));
3386                         ok = imap_cmd_starttls(session);
3387                         if (ok != MAILIMAP_NO_ERROR) {
3388                                 log_warning(LOG_PROTOCOL, _("Can't start TLS session.\n"));
3389                                 return ok;
3390                         } else {
3391                                 /* refresh capas */
3392                                 imap_free_capabilities(session);
3393                                 if ((r = imap_get_capabilities(session)) != MAILIMAP_NO_ERROR) {
3394                                         imap_handle_error(SESSION(session), r);
3395                                         log_warning(LOG_PROTOCOL, _("Can't refresh capabilities.\n"));
3396                                         return r;
3397                                 }
3398                         }
3399 #else           
3400                         log_error(LOG_PROTOCOL, _("Connection to %s failed: "
3401                                         "server requires TLS, but Claws Mail "
3402                                         "has been compiled without OpenSSL "
3403                                         "support.\n"),
3404                                         SESSION(session)->server);
3405                         return MAILIMAP_ERROR_BAD_STATE;
3406 #endif
3407                 } else {
3408                         log_error(LOG_PROTOCOL, _("Server logins are disabled.\n"));
3409                         return MAILIMAP_ERROR_BAD_STATE;
3410                 }
3411         }
3412
3413         log_print(LOG_PROTOCOL, "IMAP4> Logging %s to %s using %s\n", 
3414                         user,
3415                         SESSION(session)->server,
3416                         type);
3417         r = imap_threaded_login(session->folder, user, pass, type);
3418         if (r != MAILIMAP_NO_ERROR) {
3419                 imap_handle_error(SESSION(session), r);
3420                 log_print(LOG_PROTOCOL, "IMAP4< Error logging in to %s\n",
3421                                 SESSION(session)->server);
3422                 ok = r;
3423         } else {
3424                 log_print(LOG_PROTOCOL, "IMAP4< Login to %s successful\n",
3425                                 SESSION(session)->server);
3426                 ok = MAILIMAP_NO_ERROR;
3427         }
3428         return ok;
3429 }
3430
3431 static gint imap_cmd_noop(IMAPSession *session)
3432 {
3433         int r;
3434         unsigned int exists, recent, expunge, unseen, uidnext, uidval;
3435         
3436         r = imap_threaded_noop(session->folder, &exists, &recent, &expunge, &unseen, &uidnext, &uidval);
3437         if (r != MAILIMAP_NO_ERROR) {
3438                 imap_handle_error(SESSION(session), r);
3439                 debug_print("noop err %d\n", r);
3440                 return r;
3441         }
3442
3443         session->folder_content_changed = FALSE;
3444
3445         if ((exists && exists != session->exists)
3446          || (recent && recent != session->recent)
3447          || (expunge && expunge != session->expunge)
3448          || (unseen && unseen != session->unseen)) {
3449                 session->folder_content_changed = TRUE;
3450         }
3451         if (uidnext != 0 && uidnext != session->uid_next) {
3452                 session->uid_next = uidnext;
3453                 session->folder_content_changed = TRUE;
3454         }
3455         if (uidval != 0 && uidval != session->uid_validity) {
3456                 session->uid_validity = uidval;
3457                 session->folder_content_changed = TRUE;
3458         }
3459
3460         session->exists = exists;
3461         session->recent = recent;
3462         session->expunge = expunge;
3463         session->unseen = unseen;
3464
3465         session_set_access_time(SESSION(session));
3466
3467         return MAILIMAP_NO_ERROR;
3468 }
3469
3470 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
3471 static gint imap_cmd_starttls(IMAPSession *session)
3472 {
3473         int r;
3474         
3475         r = imap_threaded_starttls(session->folder, 
3476                 SESSION(session)->server, SESSION(session)->port);
3477         if (r != MAILIMAP_NO_ERROR) {
3478                 imap_handle_error(SESSION(session), r);
3479                 debug_print("starttls err %d\n", r);
3480                 return r;
3481         }
3482         return MAILIMAP_NO_ERROR;
3483 }
3484 #endif
3485
3486 static gint imap_cmd_select(IMAPSession *session, const gchar *folder,
3487                             gint *exists, gint *recent, gint *unseen,
3488                             guint32 *uid_validity, gint *can_create_flags,
3489                             GSList **ok_flags, gboolean block)
3490 {
3491         int r;
3492
3493         r = imap_threaded_select(session->folder, folder,
3494                                  exists, recent, unseen, uid_validity, can_create_flags, ok_flags);
3495         if (r != MAILIMAP_NO_ERROR) {
3496                 imap_handle_error(SESSION(session), r);
3497                 debug_print("select err %d\n", r);
3498                 return r;
3499         }
3500         return MAILIMAP_NO_ERROR;
3501 }
3502
3503 static gint imap_cmd_close(IMAPSession *session)
3504 {
3505         int r;
3506
3507         r = imap_threaded_close(session->folder);
3508         if (r != MAILIMAP_NO_ERROR) {
3509                 imap_handle_error(SESSION(session), r);
3510                 debug_print("close err %d\n", r);
3511                 return r;
3512         }
3513         g_free(session->mbox);
3514         session->mbox = NULL;
3515         session->exists = 0;
3516         session->recent = 0;
3517         session->expunge = 0;
3518         return MAILIMAP_NO_ERROR;
3519 }
3520
3521 static gint imap_cmd_examine(IMAPSession *session, const gchar *folder,
3522                              gint *exists, gint *recent, gint *unseen,
3523                              guint32 *uid_validity, gboolean block)
3524 {
3525         int r;
3526
3527         r = imap_threaded_examine(session->folder, folder,
3528                                   exists, recent, unseen, uid_validity);
3529         if (r != MAILIMAP_NO_ERROR) {
3530                 imap_handle_error(SESSION(session), r);
3531                 debug_print("examine err %d\n", r);
3532                 
3533                 return r;
3534         }
3535         return MAILIMAP_NO_ERROR;
3536 }
3537
3538 static gint imap_cmd_create(IMAPSession *session, const gchar *folder)
3539 {
3540         int r;
3541
3542         r = imap_threaded_create(session->folder, folder);
3543         if (r != MAILIMAP_NO_ERROR) {
3544                 imap_handle_error(SESSION(session), r);
3545                 
3546                 return r;
3547         }
3548
3549         return MAILIMAP_NO_ERROR;
3550 }
3551
3552 static gint imap_cmd_rename(IMAPSession *session, const gchar *old_folder,
3553                             const gchar *new_folder)
3554 {
3555         int r;
3556
3557         r = imap_threaded_rename(session->folder, old_folder,
3558                                  new_folder);
3559         if (r != MAILIMAP_NO_ERROR) {
3560                 imap_handle_error(SESSION(session), r);
3561                 return r;
3562         }
3563
3564         return MAILIMAP_NO_ERROR;
3565 }
3566
3567 static gint imap_cmd_delete(IMAPSession *session, const gchar *folder)
3568 {
3569         int r;
3570         
3571
3572         r = imap_threaded_delete(session->folder, folder);
3573         if (r != MAILIMAP_NO_ERROR) {
3574                 imap_handle_error(SESSION(session), r);
3575                 return r;
3576         }
3577
3578         return MAILIMAP_NO_ERROR;
3579 }
3580
3581 typedef struct _fetch_data {
3582         IMAPSession *session;
3583         guint32 uid;
3584         const gchar *filename;
3585         gboolean headers;
3586         gboolean body;
3587         gboolean done;
3588 } fetch_data;
3589
3590 static void *imap_cmd_fetch_thread(void *data)
3591 {
3592         fetch_data *stuff = (fetch_data *)data;
3593         IMAPSession *session = stuff->session;
3594         guint32 uid = stuff->uid;
3595         const gchar *filename = stuff->filename;
3596         int r;
3597         
3598         if (stuff->body) {
3599                 r = imap_threaded_fetch_content(session->folder,
3600                                                uid, 1, filename);
3601         }
3602         else {
3603                 r = imap_threaded_fetch_content(session->folder,
3604                                                 uid, 0, filename);
3605         }
3606         if (r != MAILIMAP_NO_ERROR) {
3607                 imap_handle_error(SESSION(session), r);
3608                 debug_print("fetch err %d\n", r);
3609                 return GINT_TO_POINTER(MAILIMAP_ERROR_BAD_STATE);
3610         }
3611         return GINT_TO_POINTER(MAILIMAP_NO_ERROR);
3612 }
3613
3614 static gint imap_cmd_fetch(IMAPSession *session, guint32 uid,
3615                                 const gchar *filename, gboolean headers,
3616                                 gboolean body)
3617 {
3618         fetch_data *data = g_new0(fetch_data, 1);
3619         int result = 0;
3620         data->done = FALSE;
3621         data->session = session;
3622         data->uid = uid;
3623         data->filename = filename;
3624         data->headers = headers;
3625         data->body = body;
3626
3627         if (prefs_common.work_offline && 
3628             !inc_offline_should_override(FALSE,
3629                 _("Claws Mail needs network access in order "
3630                   "to access the IMAP server."))) {
3631                 g_free(data);
3632                 return -1;
3633         }
3634         statusbar_print_all(_("Fetching message..."));
3635         result = GPOINTER_TO_INT(imap_cmd_fetch_thread(data));
3636         statusbar_pop_all();
3637         g_free(data);
3638         return result;
3639 }
3640
3641
3642 static gint imap_cmd_append(IMAPSession *session, 
3643                             IMAPFolderItem *item,
3644                             const gchar *destfolder,
3645                             const gchar *file, IMAPFlags flags, 
3646                             guint32 *new_uid)
3647 {
3648         struct mailimap_flag_list * flag_list;
3649         int r;
3650         
3651         g_return_val_if_fail(file != NULL, MAILIMAP_ERROR_BAD_STATE);
3652
3653         flag_list = imap_flag_to_lep(item, flags, NULL);
3654         lock_session(session);
3655         r = imap_threaded_append(session->folder, destfolder,
3656                          file, flag_list, (int *)new_uid);
3657         mailimap_flag_list_free(flag_list);
3658
3659         if (r != MAILIMAP_NO_ERROR) {
3660                 imap_handle_error(SESSION(session), r);
3661                 debug_print("append err %d\n", r);
3662                 return r;
3663         }
3664
3665         unlock_session(session);
3666
3667         return MAILIMAP_NO_ERROR;
3668 }
3669
3670 static gint imap_cmd_copy(IMAPSession *session, struct mailimap_set * set,
3671                           const gchar *destfolder, GRelation *uid_mapping,
3672                           struct mailimap_set **source, struct mailimap_set **dest)
3673 {
3674         int r;
3675         
3676         g_return_val_if_fail(session != NULL, MAILIMAP_ERROR_BAD_STATE);
3677         g_return_val_if_fail(set != NULL, MAILIMAP_ERROR_BAD_STATE);
3678         g_return_val_if_fail(destfolder != NULL, MAILIMAP_ERROR_BAD_STATE);
3679
3680         r = imap_threaded_copy(session->folder, set, destfolder, source, dest);
3681         if (r != MAILIMAP_NO_ERROR) {
3682                 imap_handle_error(SESSION(session), r);
3683                 return r;
3684         }
3685
3686         return MAILIMAP_NO_ERROR;
3687 }
3688
3689 static gint imap_cmd_store(IMAPSession *session, 
3690                            IMAPFolderItem *item,
3691                            struct mailimap_set * set,
3692                            IMAPFlags flags, GSList *tags, int do_add)
3693 {
3694         int r;
3695         struct mailimap_flag_list * flag_list = NULL;
3696         struct mailimap_store_att_flags * store_att_flags;
3697         
3698         flag_list = imap_flag_to_lep(item, flags, tags);
3699
3700         if (do_add)
3701                 store_att_flags =
3702                         mailimap_store_att_flags_new_add_flags_silent(flag_list);
3703         else
3704                 store_att_flags =
3705                         mailimap_store_att_flags_new_remove_flags_silent(flag_list);
3706         
3707         r = imap_threaded_store(session->folder, set, store_att_flags);
3708         mailimap_store_att_flags_free(store_att_flags);
3709         if (r != MAILIMAP_NO_ERROR) {
3710                 imap_handle_error(SESSION(session), r);
3711                 return r;
3712         }
3713         
3714         return MAILIMAP_NO_ERROR;
3715 }
3716
3717 static gint imap_cmd_expunge(IMAPSession *session)
3718 {
3719         int r;
3720         
3721         if (prefs_common.work_offline && 
3722             !inc_offline_should_override(FALSE,
3723                 _("Claws Mail needs network access in order "
3724                   "to access the IMAP server."))) {
3725                 return -1;
3726         }
3727
3728         r = imap_threaded_expunge(session->folder);
3729         if (r != MAILIMAP_NO_ERROR) {
3730                 imap_handle_error(SESSION(session), r);
3731                 return r;
3732         }
3733
3734         return MAILIMAP_NO_ERROR;
3735 }
3736
3737 static void imap_path_separator_subst(gchar *str, gchar separator)
3738 {
3739         gchar *p;
3740         gboolean in_escape = FALSE;
3741
3742         if (!separator || separator == '/') return;
3743
3744         for (p = str; *p != '\0'; p++) {
3745                 if (*p == '/' && !in_escape)
3746                         *p = separator;
3747                 else if (*p == '&' && *(p + 1) != '-' && !in_escape)
3748                         in_escape = TRUE;
3749                 else if (*p == '-' && in_escape)
3750                         in_escape = FALSE;
3751         }
3752 }
3753
3754 static gboolean imap_rename_folder_func(GNode *node, gpointer data)
3755 {
3756         FolderItem *item = node->data;
3757         gchar **paths = data;
3758         const gchar *oldpath = paths[0];
3759         const gchar *newpath = paths[1];
3760         gchar *real_oldpath, *real_newpath;
3761         gchar *base;
3762         gchar *new_itempath;
3763         gint oldpathlen;
3764         IMAPSession *session = imap_session_get(item->folder);
3765
3766         oldpathlen = strlen(oldpath);
3767         if (strncmp(oldpath, item->path, oldpathlen) != 0) {
3768                 g_warning("path doesn't match: %s, %s\n", oldpath, item->path);
3769                 return TRUE;
3770         }
3771
3772         base = item->path + oldpathlen;
3773         while (*base == G_DIR_SEPARATOR) base++;
3774         if (*base == '\0')
3775                 new_itempath = g_strdup(newpath);
3776         else
3777                 new_itempath = g_strconcat(newpath, G_DIR_SEPARATOR_S, base,
3778                                            NULL);
3779
3780         real_oldpath = imap_get_real_path(session, IMAP_FOLDER(item->folder), item->path);
3781         g_free(item->path);
3782         item->path = new_itempath;
3783         
3784         real_newpath = imap_get_real_path(session, IMAP_FOLDER(item->folder), item->path);
3785         
3786         imap_threaded_subscribe(item->folder, real_oldpath, FALSE);
3787         imap_threaded_subscribe(item->folder, real_newpath, TRUE);
3788
3789         g_free(real_oldpath);
3790         g_free(real_newpath);
3791         return FALSE;
3792 }
3793
3794 static gint get_list_of_uids(IMAPSession *session, Folder *folder, IMAPFolderItem *item, GSList **msgnum_list)
3795 {
3796         GSList *uidlist, *elem;
3797         int r = -1;
3798         clist * lep_uidlist;
3799         gint ok, nummsgs = 0, lastuid_old;
3800
3801         if (session == NULL) {
3802                 return -1;
3803         }
3804
3805         ok = imap_select(session, IMAP_FOLDER(folder), FOLDER_ITEM(item),
3806                          NULL, NULL, NULL, NULL, NULL, TRUE);
3807         if (ok != MAILIMAP_NO_ERROR) {
3808                 return -1;
3809         }
3810
3811         g_slist_free(item->uid_list);
3812         item->uid_list = NULL;
3813
3814         uidlist = NULL;
3815         
3816         if (folder->account && folder->account->low_bandwidth) {
3817                 r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_SIMPLE, NULL,
3818                                  &lep_uidlist);
3819         }
3820         
3821         if (r == MAILIMAP_NO_ERROR) {
3822                 GSList * fetchuid_list =
3823                         imap_uid_list_from_lep(lep_uidlist);
3824                 mailimap_search_result_free(lep_uidlist);
3825                 
3826                 uidlist = g_slist_concat(fetchuid_list, uidlist);
3827         } else {
3828                 carray * lep_uidtab;
3829                 if (r != -1) { /* inited */
3830                         imap_handle_error(SESSION(session), r);
3831                         if (is_fatal(r))
3832                                 return -1;
3833                 }
3834                 r = imap_threaded_fetch_uid(folder, 1,
3835                                     &lep_uidtab);
3836                 if (r == MAILIMAP_NO_ERROR) {
3837                         GSList * fetchuid_list =
3838                                 imap_uid_list_from_lep_tab(lep_uidtab);
3839                         imap_fetch_uid_list_free(lep_uidtab);
3840                         uidlist = g_slist_concat(fetchuid_list, uidlist);
3841                 }
3842         }
3843         
3844         if (r != MAILIMAP_NO_ERROR) {
3845                 imap_handle_error(SESSION(session), r);
3846                 return -1;
3847         }
3848
3849         lastuid_old = item->lastuid;
3850
3851         for (elem = uidlist; elem != NULL; elem = g_slist_next(elem)) {
3852                 guint msgnum;
3853
3854                 msgnum = GPOINTER_TO_INT(elem->data);
3855
3856                 *msgnum_list = g_slist_prepend(*msgnum_list, GINT_TO_POINTER(msgnum));
3857                 item->uid_list = g_slist_prepend(item->uid_list, GINT_TO_POINTER(msgnum));
3858                 nummsgs++;
3859         }
3860         g_slist_free(uidlist);
3861
3862         unlock_session(session); /* locked from imap_get_num_list */
3863
3864         return nummsgs;
3865
3866 }
3867
3868 gint imap_get_num_list(Folder *folder, FolderItem *_item, GSList **msgnum_list, gboolean *old_uids_valid)
3869 {
3870         IMAPFolderItem *item = (IMAPFolderItem *)_item;
3871         IMAPSession *session;
3872         gint nummsgs;
3873         GSList *uidlist = NULL;
3874         gchar *dir;
3875         gboolean selected_folder;
3876         gint known_list_len = 0;
3877         debug_print("get_num_list\n");
3878         
3879         g_return_val_if_fail(folder != NULL, -1);
3880         g_return_val_if_fail(item != NULL, -1);
3881         g_return_val_if_fail(item->item.path != NULL, -1);
3882         g_return_val_if_fail(FOLDER_CLASS(folder) == &imap_class, -1);
3883         g_return_val_if_fail(folder->account != NULL, -1);
3884
3885         known_list_len = g_slist_length(item->uid_list);
3886         if (!item->should_update) {
3887                 debug_print("get_num_list: nothing to update\n");
3888                 *old_uids_valid = TRUE;
3889                 if (known_list_len == item->item.total_msgs
3890                  && known_list_len > 0) {
3891                         *msgnum_list = g_slist_copy(item->uid_list);
3892                         return known_list_len;
3893                 } else {
3894                         debug_print("don't know the list length...\n");
3895                 }
3896         }
3897
3898         if (prefs_common.work_offline && 
3899             !inc_offline_should_override(FALSE,
3900                 _("Claws Mail needs network access in order "
3901                   "to access the IMAP server."))) {
3902                 return -1;
3903         }
3904         
3905         debug_print("getting session...\n");
3906         session = imap_session_get(folder);
3907         g_return_val_if_fail(session != NULL, -1);
3908
3909         lock_session(session); /* unlocked by get_list_of_uids */
3910         if (FOLDER_ITEM(item)->path) 
3911                 statusbar_print_all(_("Scanning folder %s%c%s ..."),
3912                                       FOLDER_ITEM(item)->folder->name, 
3913                                       G_DIR_SEPARATOR,
3914                                       FOLDER_ITEM(item)->path);
3915         else
3916                 statusbar_print_all(_("Scanning folder %s ..."),
3917                                       FOLDER_ITEM(item)->folder->name);
3918
3919         selected_folder = (session->mbox != NULL) &&
3920                           (!strcmp(session->mbox, item->item.path));
3921         
3922         if (item->should_trash_cache) {
3923                 *old_uids_valid = FALSE;
3924                 debug_print("get_num_list: trashing num list\n");
3925                 debug_print("Freeing imap uid cache\n");
3926                 item->lastuid = 0;
3927                 g_slist_free(item->uid_list);
3928                 item->uid_list = NULL;
3929
3930                 imap_delete_all_cached_messages((FolderItem *)item);
3931         } else {
3932                 debug_print("get_num_list: updating num list\n");
3933                 *old_uids_valid = TRUE;
3934         }
3935
3936         nummsgs = get_list_of_uids(session, folder, item, &uidlist);
3937         /* session could be broken now, in case of fatal error */
3938