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