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