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