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