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