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