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