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