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