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