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