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