2007-08-19 [colin] 2.10.0cvs135
[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
1500         unlock_session(session);
1501         if (ok == IMAP_SUCCESS)
1502                 return last_num;
1503         else
1504                 return -1;
1505 }
1506
1507 static gint imap_copy_msg(Folder *folder, FolderItem *dest, MsgInfo *msginfo)
1508 {
1509         GSList msglist;
1510
1511         g_return_val_if_fail(msginfo != NULL, -1);
1512
1513         msglist.data = msginfo;
1514         msglist.next = NULL;
1515
1516         return imap_copy_msgs(folder, dest, &msglist, NULL);
1517 }
1518
1519 static gint imap_copy_msgs(Folder *folder, FolderItem *dest, 
1520                     MsgInfoList *msglist, GRelation *relation)
1521 {
1522         MsgInfo *msginfo;
1523         gint ret;
1524
1525         g_return_val_if_fail(folder != NULL, -1);
1526         g_return_val_if_fail(dest != NULL, -1);
1527         g_return_val_if_fail(msglist != NULL, -1);
1528
1529         msginfo = (MsgInfo *)msglist->data;
1530         g_return_val_if_fail(msginfo->folder != NULL, -1);
1531
1532         ret = imap_do_copy_msgs(folder, dest, msglist, relation);
1533         return ret;
1534 }
1535
1536
1537 static gint imap_do_remove_msgs(Folder *folder, FolderItem *dest, 
1538                                 MsgInfoList *msglist, GRelation *relation)
1539 {
1540         gchar *destdir, *dir;
1541         GSList *numlist = NULL, *cur;
1542         MsgInfo *msginfo;
1543         IMAPSession *session;
1544         gint ok = IMAP_SUCCESS;
1545         GRelation *uid_mapping;
1546         
1547         g_return_val_if_fail(folder != NULL, -1);
1548         g_return_val_if_fail(dest != NULL, -1);
1549         g_return_val_if_fail(msglist != NULL, -1);
1550
1551         debug_print("getting session...\n");
1552         session = imap_session_get(folder);
1553         if (!session) {
1554                 return -1;
1555         }
1556
1557         msginfo = (MsgInfo *)msglist->data;
1558
1559         ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder->path,
1560                          NULL, NULL, NULL, NULL, FALSE);
1561         if (ok != IMAP_SUCCESS) {
1562                 unlock_session(session);
1563                 return ok;
1564         }
1565
1566         destdir = imap_get_real_path(session, IMAP_FOLDER(folder), dest->path);
1567         for (cur = msglist; cur; cur = cur->next) {
1568                 msginfo = (MsgInfo *)cur->data;
1569                 if (!MSG_IS_DELETED(msginfo->flags))
1570                         numlist = g_slist_prepend(numlist, GINT_TO_POINTER(msginfo->msgnum));
1571         }
1572         numlist = g_slist_reverse(numlist);
1573
1574         uid_mapping = g_relation_new(2);
1575         g_relation_index(uid_mapping, 0, g_direct_hash, g_direct_equal);
1576
1577         ok = imap_set_message_flags
1578                 (session, numlist, IMAP_FLAG_DELETED, TRUE);
1579         if (ok != IMAP_SUCCESS) {
1580                 log_warning(LOG_PROTOCOL, _("can't set deleted flags\n"));
1581                 unlock_session(session);
1582                 return ok;
1583         }
1584         ok = imap_cmd_expunge(session);
1585         if (ok != IMAP_SUCCESS) {
1586                 log_warning(LOG_PROTOCOL, _("can't expunge\n"));
1587                 unlock_session(session);
1588                 return ok;
1589         }
1590         
1591         dir = folder_item_get_path(msginfo->folder);
1592         if (is_dir_exist(dir)) {
1593                 for (cur = msglist; cur; cur = cur->next) {
1594                         msginfo = (MsgInfo *)cur->data;
1595                         remove_numbered_files(dir, msginfo->msgnum, msginfo->msgnum);
1596                 }
1597         }
1598         g_free(dir);
1599
1600         g_relation_destroy(uid_mapping);
1601         g_slist_free(numlist);
1602
1603         g_free(destdir);
1604         unlock_session(session);
1605         if (ok == IMAP_SUCCESS)
1606                 return 0;
1607         else
1608                 return -1;
1609 }
1610
1611 static gint imap_remove_msgs(Folder *folder, FolderItem *dest, 
1612                     MsgInfoList *msglist, GRelation *relation)
1613 {
1614         MsgInfo *msginfo;
1615
1616         g_return_val_if_fail(folder != NULL, -1);
1617         g_return_val_if_fail(dest != NULL, -1);
1618         if (msglist == NULL)
1619                 return 0;
1620
1621         msginfo = (MsgInfo *)msglist->data;
1622         g_return_val_if_fail(msginfo->folder != NULL, -1);
1623
1624         return imap_do_remove_msgs(folder, dest, msglist, relation);
1625 }
1626
1627 static gint imap_remove_all_msg(Folder *folder, FolderItem *item)
1628 {
1629         GSList *list = folder_item_get_msg_list(item);
1630         gint res = imap_remove_msgs(folder, item, list, NULL);
1631         procmsg_msg_list_free(list);
1632         return res;
1633 }
1634
1635 static gboolean imap_is_msg_changed(Folder *folder, FolderItem *item,
1636                                     MsgInfo *msginfo)
1637 {
1638         /* TODO: properly implement this method */
1639         return FALSE;
1640 }
1641
1642 static gint imap_close(Folder *folder, FolderItem *item)
1643 {
1644         return 0;
1645 }
1646
1647 gint imap_scan_tree_real(Folder *folder, gboolean subs_only)
1648 {
1649         FolderItem *item = NULL;
1650         IMAPSession *session;
1651         gchar *root_folder = NULL;
1652
1653         g_return_val_if_fail(folder != NULL, -1);
1654         g_return_val_if_fail(folder->account != NULL, -1);
1655
1656         debug_print("getting session...\n");
1657         session = imap_session_get(folder);
1658         if (!session) {
1659                 if (!folder->node) {
1660                         folder_tree_destroy(folder);
1661                         item = folder_item_new(folder, folder->name, NULL);
1662                         item->folder = folder;
1663                         folder->node = item->node = g_node_new(item);
1664                 }
1665                 return -1;
1666         }
1667
1668         if (folder->account->imap_dir && *folder->account->imap_dir) {
1669                 gchar *real_path;
1670                 int r;
1671                 clist * lep_list;
1672
1673                 Xstrdup_a(root_folder, folder->account->imap_dir, {unlock_session(session);return -1;});
1674                 extract_quote(root_folder, '"');
1675                 subst_char(root_folder,
1676                            imap_get_path_separator(session, IMAP_FOLDER(folder),
1677                                                    root_folder),
1678                            '/');
1679                 strtailchomp(root_folder, '/');
1680                 real_path = imap_get_real_path
1681                         (session, IMAP_FOLDER(folder), root_folder);
1682                 debug_print("IMAP root directory: %s\n", real_path);
1683
1684                 /* check if root directory exist */
1685
1686                 r = imap_threaded_list(session->folder, "", real_path,
1687                                        &lep_list);
1688                 if ((r != MAILIMAP_NO_ERROR) || (clist_count(lep_list) == 0)) {
1689                         if (!folder->node) {
1690                                 item = folder_item_new(folder, folder->name, NULL);
1691                                 item->folder = folder;
1692                                 folder->node = item->node = g_node_new(item);
1693                         }
1694                         unlock_session(session);
1695                         return -1;
1696                 }
1697                 mailimap_list_result_free(lep_list);
1698                                 
1699                 g_free(real_path);
1700         }
1701
1702         if (folder->node)
1703                 item = FOLDER_ITEM(folder->node->data);
1704                 
1705         if (item && !item->path && root_folder) {
1706                 item->path = g_strdup(root_folder);
1707         }
1708
1709         if (!item || ((item->path || root_folder) &&
1710                       strcmp2(item->path, root_folder) != 0)) {
1711                 folder_tree_destroy(folder);
1712                 item = folder_item_new(folder, folder->name, root_folder);
1713                 item->folder = folder;
1714                 folder->node = item->node = g_node_new(item);
1715         }
1716
1717         imap_scan_tree_recursive(session, FOLDER_ITEM(folder->node->data), subs_only);
1718         imap_create_missing_folders(folder);
1719         unlock_session(session);
1720
1721         return 0;
1722 }
1723
1724 static gint imap_scan_tree(Folder *folder)
1725 {
1726         gboolean subs_only = FALSE;
1727         if (folder->account) {
1728                 debug_print(" scanning only subs %d\n", folder->account->imap_subsonly);
1729                 subs_only = folder->account->imap_subsonly;
1730         }
1731         return imap_scan_tree_real(folder, subs_only);
1732 }
1733
1734 static gint imap_scan_tree_recursive(IMAPSession *session, FolderItem *item, gboolean subs_only)
1735 {
1736         Folder *folder;
1737         IMAPFolder *imapfolder;
1738         FolderItem *new_item;
1739         GSList *item_list, *cur;
1740         GNode *node;
1741         gchar *real_path;
1742         gchar *wildcard_path;
1743         gchar separator;
1744         gchar wildcard[3];
1745         clist * lep_list;
1746         int r;
1747         
1748         g_return_val_if_fail(item != NULL, -1);
1749         g_return_val_if_fail(item->folder != NULL, -1);
1750         g_return_val_if_fail(item->no_sub == FALSE, -1);
1751
1752         folder = item->folder;
1753         imapfolder = IMAP_FOLDER(folder);
1754
1755         separator = imap_get_path_separator(session, imapfolder, item->path);
1756
1757         if (folder->ui_func)
1758                 folder->ui_func(folder, item, folder->ui_func_data);
1759
1760         if (item->path) {
1761                 wildcard[0] = separator;
1762                 wildcard[1] = '%';
1763                 wildcard[2] = '\0';
1764                 real_path = imap_get_real_path(session, imapfolder, item->path);
1765         } else {
1766                 wildcard[0] = '%';
1767                 wildcard[1] = '\0';
1768                 real_path = g_strdup("");
1769         }
1770
1771         Xstrcat_a(wildcard_path, real_path, wildcard,
1772                   {g_free(real_path); return IMAP_ERROR;});
1773         lep_list = NULL;
1774         
1775         if (subs_only)
1776                 r = imap_threaded_lsub(folder, "", wildcard_path, &lep_list);
1777         else
1778                 r = imap_threaded_list(folder, "", wildcard_path, &lep_list);
1779
1780         if (r != MAILIMAP_NO_ERROR) {
1781                 item_list = NULL;
1782         }
1783         else {
1784                 item_list = imap_list_from_lep(imapfolder,
1785                                                lep_list, real_path, FALSE);
1786                 mailimap_list_result_free(lep_list);
1787         }
1788         
1789         g_free(real_path);
1790
1791         node = item->node->children;
1792         while (node != NULL) {
1793                 FolderItem *old_item = FOLDER_ITEM(node->data);
1794                 GNode *next = node->next;
1795
1796                 new_item = NULL;
1797                 for (cur = item_list; cur != NULL; cur = cur->next) {
1798                         FolderItem *cur_item = FOLDER_ITEM(cur->data);
1799                         if (!strcmp2(old_item->path, cur_item->path)) {
1800                                 new_item = cur_item;
1801                                 break;
1802                         }
1803                 }
1804                 if (!new_item) {
1805                         if (old_item && old_item->path && !strcmp(old_item->path, "INBOX")) {
1806                                 debug_print("not removing INBOX\n");
1807                         } else {
1808                                 debug_print("folder '%s' not found. removing...\n",
1809                                             old_item->path);
1810                                 folder_item_remove(old_item);
1811                         }
1812                 } else {
1813                         old_item->no_sub = new_item->no_sub;
1814                         old_item->no_select = new_item->no_select;
1815                         if (old_item->no_sub == TRUE && node->children) {
1816                                 debug_print("folder '%s' doesn't have "
1817                                             "subfolders. removing...\n",
1818                                             old_item->path);
1819                                 folder_item_remove_children(old_item);
1820                         }
1821                 }
1822
1823                 node = next;
1824         }
1825
1826         for (cur = item_list; cur != NULL; cur = cur->next) {
1827                 FolderItem *cur_item = FOLDER_ITEM(cur->data);
1828                 new_item = NULL;
1829
1830                 for (node = item->node->children; node != NULL;
1831                      node = node->next) {
1832                         if (!strcmp2(FOLDER_ITEM(node->data)->path,
1833                                      cur_item->path)) {
1834                                 new_item = FOLDER_ITEM(node->data);
1835                                 folder_item_destroy(cur_item);
1836                                 cur_item = NULL;
1837                                 break;
1838                         }
1839                 }
1840                 if (!new_item) {
1841                         new_item = cur_item;
1842                         debug_print("new folder '%s' found.\n", new_item->path);
1843                         folder_item_append(item, new_item);
1844                 }
1845
1846                 if (!strcmp(new_item->path, "INBOX")) {
1847                         new_item->stype = F_INBOX;
1848                         folder->inbox = new_item;
1849                 } else if (!folder_item_parent(item) || item->stype == F_INBOX) {
1850                         gchar *base;
1851
1852                         base = g_path_get_basename(new_item->path);
1853
1854                         if (!folder->outbox && !g_ascii_strcasecmp(base, "Sent")) {
1855                                 new_item->stype = F_OUTBOX;
1856                                 folder->outbox = new_item;
1857                         } else if (!folder->draft && !g_ascii_strcasecmp(base, "Drafts")) {
1858                                 new_item->stype = F_DRAFT;
1859                                 folder->draft = new_item;
1860                         } else if (!folder->queue && !g_ascii_strcasecmp(base, "Queue")) {
1861                                 new_item->stype = F_QUEUE;
1862                                 folder->queue = new_item;
1863                         } else if (!folder->trash && !g_ascii_strcasecmp(base, "Trash")) {
1864                                 new_item->stype = F_TRASH;
1865                                 folder->trash = new_item;
1866                         }
1867                         g_free(base);
1868                 }
1869
1870                 if (new_item->no_sub == FALSE)
1871                         imap_scan_tree_recursive(session, new_item, subs_only);
1872         }
1873
1874         g_slist_free(item_list);
1875
1876         return IMAP_SUCCESS;
1877 }
1878
1879 GList *imap_scan_subtree(Folder *folder, FolderItem *item, gboolean unsubs_only, gboolean recursive)
1880 {
1881         IMAPSession *session = imap_session_get(folder);
1882         gchar *real_path;
1883         gchar *wildcard_path;
1884         gchar separator;
1885         gchar wildcard[3];
1886         clist * lep_list;
1887         GSList *item_list = NULL, *cur;
1888         GList *child_list = NULL, *tmplist = NULL;
1889         GSList *sub_list = NULL;
1890         int r;
1891
1892         if (!session)
1893                 return NULL;
1894
1895         separator = imap_get_path_separator(session, IMAP_FOLDER(folder), item->path);
1896
1897         if (item->path) {
1898                 wildcard[0] = separator;
1899                 wildcard[1] = '%';
1900                 wildcard[2] = '\0';
1901                 real_path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path);
1902         } else {
1903                 wildcard[0] = '%';
1904                 wildcard[1] = '\0';
1905                 real_path = g_strdup("");
1906         }
1907
1908         Xstrcat_a(wildcard_path, real_path, wildcard,
1909                   {g_free(real_path); return NULL;});
1910         lep_list = NULL;
1911         
1912         if (unsubs_only)
1913                 statusbar_print_all(_("Looking for unsubscribed folders in %s..."), 
1914                                 item->path?item->path:item->name);
1915         else
1916                 statusbar_print_all(_("Looking for subfolders of %s..."), 
1917                                 item->path?item->path:item->name);
1918
1919         r = imap_threaded_list(folder, "", wildcard_path, &lep_list);
1920         if (r) {
1921                 statusbar_pop_all();
1922                 return NULL;
1923         }
1924         item_list = imap_list_from_lep(IMAP_FOLDER(folder),
1925                                lep_list, real_path, FALSE);
1926         mailimap_list_result_free(lep_list);
1927
1928         for (cur = item_list; cur != NULL; cur = cur->next) {
1929                 FolderItem *cur_item = FOLDER_ITEM(cur->data);
1930                 if (recursive) {
1931                         tmplist = imap_scan_subtree(folder, cur_item, 
1932                                         unsubs_only, recursive);
1933                         if (tmplist)
1934                                 child_list = g_list_concat(child_list, tmplist);
1935                 }
1936                 child_list = g_list_prepend(child_list,
1937                                 imap_get_real_path(session, 
1938                                         IMAP_FOLDER(folder), cur_item->path));
1939                 
1940                 folder_item_destroy(cur_item);
1941         }
1942         child_list = g_list_reverse(child_list);
1943         g_slist_free(item_list);
1944
1945         if (unsubs_only) {
1946                 r = imap_threaded_lsub(folder, "", wildcard_path, &lep_list);
1947                 if (r) {
1948                         statusbar_pop_all();
1949                         return NULL;
1950                 }
1951                 sub_list = imap_list_from_lep(IMAP_FOLDER(folder),
1952                                        lep_list, real_path, FALSE);
1953                 mailimap_list_result_free(lep_list);
1954
1955                 for (cur = sub_list; cur != NULL; cur = cur->next) {
1956                         FolderItem *cur_item = FOLDER_ITEM(cur->data);
1957                         GList *oldlitem = NULL;
1958                         gchar *tmp = imap_get_real_path(session, 
1959                                         IMAP_FOLDER(folder), cur_item->path);
1960                         folder_item_destroy(cur_item);
1961                         oldlitem = g_list_find_custom(
1962                                         child_list, tmp, (GCompareFunc)strcmp2);
1963                         if (oldlitem) {
1964                                 child_list = g_list_remove_link(child_list, oldlitem);
1965                                 g_free(oldlitem->data);
1966                                 g_list_free(oldlitem);
1967                         }
1968                         g_free(tmp);
1969                 }
1970         }
1971
1972         statusbar_pop_all();
1973
1974         return child_list;
1975 }
1976
1977 static gint imap_create_tree(Folder *folder)
1978 {
1979         g_return_val_if_fail(folder != NULL, -1);
1980         g_return_val_if_fail(folder->node != NULL, -1);
1981         g_return_val_if_fail(folder->node->data != NULL, -1);
1982         g_return_val_if_fail(folder->account != NULL, -1);
1983
1984         imap_scan_tree(folder);
1985         imap_create_missing_folders(folder);
1986
1987         return 0;
1988 }
1989
1990 static void imap_create_missing_folders(Folder *folder)
1991 {
1992         g_return_if_fail(folder != NULL);
1993
1994         if (!folder->inbox)
1995                 folder->inbox = imap_create_special_folder
1996                         (folder, F_INBOX, "INBOX");
1997         if (!folder->trash)
1998                 folder->trash = imap_create_special_folder
1999                         (folder, F_TRASH, "Trash");
2000         if (!folder->queue)
2001                 folder->queue = imap_create_special_folder
2002                         (folder, F_QUEUE, "Queue");
2003         if (!folder->outbox)
2004                 folder->outbox = imap_create_special_folder
2005                         (folder, F_OUTBOX, "Sent");
2006         if (!folder->draft)
2007                 folder->draft = imap_create_special_folder
2008                         (folder, F_DRAFT, "Drafts");
2009 }
2010
2011 static FolderItem *imap_create_special_folder(Folder *folder,
2012                                               SpecialFolderItemType stype,
2013                                               const gchar *name)
2014 {
2015         FolderItem *item;
2016         FolderItem *new_item;
2017
2018         g_return_val_if_fail(folder != NULL, NULL);
2019         g_return_val_if_fail(folder->node != NULL, NULL);
2020         g_return_val_if_fail(folder->node->data != NULL, NULL);
2021         g_return_val_if_fail(folder->account != NULL, NULL);
2022         g_return_val_if_fail(name != NULL, NULL);
2023
2024         item = FOLDER_ITEM(folder->node->data);
2025         new_item = imap_create_folder(folder, item, name);
2026
2027         if (!new_item) {
2028                 g_warning("Can't create '%s'\n", name);
2029                 if (!folder->inbox) return NULL;
2030
2031                 new_item = imap_create_folder(folder, folder->inbox, name);
2032                 if (!new_item)
2033                         g_warning("Can't create '%s' under INBOX\n", name);
2034                 else
2035                         new_item->stype = stype;
2036         } else
2037                 new_item->stype = stype;
2038
2039         return new_item;
2040 }
2041
2042 static gchar *imap_folder_get_path(Folder *folder)
2043 {
2044         gchar *folder_path;
2045
2046         g_return_val_if_fail(folder != NULL, NULL);
2047         g_return_val_if_fail(folder->account != NULL, NULL);
2048
2049         folder_path = g_strconcat(get_imap_cache_dir(),
2050                                   G_DIR_SEPARATOR_S,
2051                                   folder->account->recv_server,
2052                                   G_DIR_SEPARATOR_S,
2053                                   folder->account->userid,
2054                                   NULL);
2055
2056         return folder_path;
2057 }
2058
2059 static gchar *imap_item_get_path(Folder *folder, FolderItem *item)
2060 {
2061         gchar *folder_path, *path;
2062
2063         g_return_val_if_fail(folder != NULL, NULL);
2064         g_return_val_if_fail(item != NULL, NULL);
2065         folder_path = imap_folder_get_path(folder);
2066
2067         g_return_val_if_fail(folder_path != NULL, NULL);
2068         if (folder_path[0] == G_DIR_SEPARATOR) {
2069                 if (item->path)
2070                         path = g_strconcat(folder_path, G_DIR_SEPARATOR_S,
2071                                            item->path, NULL);
2072                 else
2073                         path = g_strdup(folder_path);
2074         } else {
2075                 if (item->path)
2076                         path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
2077                                            folder_path, G_DIR_SEPARATOR_S,
2078                                            item->path, NULL);
2079                 else
2080                         path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
2081                                            folder_path, NULL);
2082         }
2083         g_free(folder_path);
2084
2085         return path;
2086 }
2087
2088 static FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
2089                                const gchar *name)
2090 {
2091         gchar *dirpath, *imap_path;
2092         IMAPSession *session;
2093         FolderItem *new_item;
2094         gchar separator;
2095         gchar *new_name;
2096         const gchar *p;
2097         gint ok;
2098         gboolean no_select = FALSE, no_sub = FALSE;
2099         gboolean exist = FALSE;
2100         
2101         g_return_val_if_fail(folder != NULL, NULL);
2102         g_return_val_if_fail(folder->account != NULL, NULL);
2103         g_return_val_if_fail(parent != NULL, NULL);
2104         g_return_val_if_fail(name != NULL, NULL);
2105
2106         debug_print("getting session...\n");
2107         session = imap_session_get(folder);
2108         if (!session) {
2109                 return NULL;
2110         }
2111
2112         if (!folder_item_parent(parent) && strcmp(name, "INBOX") == 0) {
2113                 dirpath = g_strdup(name);
2114         }else if (parent->path)
2115                 dirpath = g_strconcat(parent->path, "/", name, NULL);
2116         else if ((p = strchr(name, '/')) != NULL && *(p + 1) != '\0')
2117                 dirpath = g_strdup(name);
2118         else if (folder->account->imap_dir && *folder->account->imap_dir) {
2119                 gchar *imap_dir;
2120
2121                 Xstrdup_a(imap_dir, folder->account->imap_dir, {unlock_session(session);return NULL;});
2122                 strtailchomp(imap_dir, '/');
2123                 dirpath = g_strconcat(imap_dir, "/", name, NULL);
2124         } else
2125                 dirpath = g_strdup(name);
2126                 
2127         
2128
2129         /* keep trailing directory separator to create a folder that contains
2130            sub folder */
2131         imap_path = imap_utf8_to_modified_utf7(dirpath);
2132
2133         strtailchomp(dirpath, '/');
2134         Xstrdup_a(new_name, name, {
2135                 g_free(dirpath); 
2136                 unlock_session(session);                
2137                 return NULL;});
2138
2139         separator = imap_get_path_separator(session, IMAP_FOLDER(folder), imap_path);
2140         imap_path_separator_subst(imap_path, separator);
2141         /* remove trailing / for display */
2142         strtailchomp(new_name, '/');
2143
2144         if (strcmp(dirpath, "INBOX") != 0) {
2145                 GPtrArray *argbuf;
2146                 int r;
2147                 clist * lep_list;
2148                 
2149                 argbuf = g_ptr_array_new();
2150                 r = imap_threaded_list(folder, "", imap_path, &lep_list);
2151                 if (r != MAILIMAP_NO_ERROR) {
2152                         log_warning(LOG_PROTOCOL, _("can't create mailbox: LIST failed\n"));
2153                         g_free(imap_path);
2154                         g_free(dirpath);
2155                         ptr_array_free_strings(argbuf);
2156                         g_ptr_array_free(argbuf, TRUE);
2157                         unlock_session(session);
2158                         return NULL;
2159                 }
2160                 
2161                 if (clist_count(lep_list) > 0)
2162                         exist = TRUE;
2163                 mailimap_list_result_free(lep_list);
2164                 lep_list = NULL;
2165                 if (!exist) {
2166                         ok = imap_cmd_create(session, imap_path);
2167                         if (ok != IMAP_SUCCESS) {
2168                                 log_warning(LOG_PROTOCOL, _("can't create mailbox\n"));
2169                                 g_free(imap_path);
2170                                 g_free(dirpath);
2171                                 unlock_session(session);
2172                                 return NULL;
2173                         }
2174                         r = imap_threaded_list(folder, "", imap_path, &lep_list);
2175                         if (r == MAILIMAP_NO_ERROR) {
2176                                 GSList *item_list = imap_list_from_lep(IMAP_FOLDER(folder),
2177                                                lep_list, dirpath, TRUE);
2178                                 if (item_list) {
2179                                         FolderItem *cur_item = FOLDER_ITEM(item_list->data);
2180                                         no_select = cur_item->no_select;
2181                                         no_sub = cur_item->no_sub;
2182                                         g_slist_free(item_list);
2183                                 } 
2184                                 mailimap_list_result_free(lep_list);
2185                         }
2186                 }
2187                 imap_threaded_subscribe(folder, imap_path, TRUE);
2188         } else {
2189                 clist *lep_list;
2190                 int r;
2191                 /* just get flags */
2192                 r = imap_threaded_list(folder, "", "INBOX", &lep_list);
2193                 if (r == MAILIMAP_NO_ERROR) {
2194                         GSList *item_list = imap_list_from_lep(IMAP_FOLDER(folder),
2195                                        lep_list, dirpath, TRUE);
2196                         if (item_list) {
2197                                 FolderItem *cur_item = FOLDER_ITEM(item_list->data);
2198                                 no_select = cur_item->no_select;
2199                                 no_sub = cur_item->no_sub;
2200                                 g_slist_free(item_list);
2201                         } 
2202                         mailimap_list_result_free(lep_list);
2203                 }
2204         }
2205
2206         new_item = folder_item_new(folder, new_name, dirpath);
2207         new_item->no_select = no_select;
2208         new_item->no_sub = no_sub;
2209         folder_item_append(parent, new_item);
2210         g_free(imap_path);
2211         g_free(dirpath);
2212
2213         dirpath = folder_item_get_path(new_item);
2214         if (!is_dir_exist(dirpath))
2215                 make_dir_hier(dirpath);
2216         g_free(dirpath);
2217         unlock_session(session);
2218
2219         if (exist) {
2220                 /* folder existed, scan it */
2221                 imap_scan_required(folder, new_item);
2222                 folder_item_scan_full(new_item, FALSE);
2223         }
2224
2225         return new_item;
2226 }
2227
2228 static gint imap_rename_folder(Folder *folder, FolderItem *item,
2229                                const gchar *name)
2230 {
2231         gchar *dirpath;
2232         gchar *newpath;
2233         gchar *real_oldpath;
2234         gchar *real_newpath;
2235         gchar *paths[2];
2236         gchar *old_cache_dir;
2237         gchar *new_cache_dir;
2238         IMAPSession *session;
2239         gchar separator;
2240         gint ok;
2241         gint exists, recent, unseen;
2242         guint32 uid_validity;
2243
2244         g_return_val_if_fail(folder != NULL, -1);
2245         g_return_val_if_fail(item != NULL, -1);
2246         g_return_val_if_fail(item->path != NULL, -1);
2247         g_return_val_if_fail(name != NULL, -1);
2248
2249         debug_print("getting session...\n");
2250         session = imap_session_get(folder);
2251         if (!session) {
2252                 return -1;
2253         }
2254
2255         if (strchr(name, imap_get_path_separator(session, IMAP_FOLDER(folder), item->path)) != NULL) {
2256                 g_warning(_("New folder name must not contain the namespace "
2257                             "path separator"));
2258                 unlock_session(session);
2259                 return -1;
2260         }
2261
2262         real_oldpath = imap_get_real_path(session, IMAP_FOLDER(folder), item->path);
2263
2264         g_free(session->mbox);
2265         session->mbox = NULL;
2266         session->exists = 0;
2267         session->recent = 0;
2268         session->expunge = 0;
2269         ok = imap_cmd_examine(session, "INBOX",
2270                               &exists, &recent, &unseen, &uid_validity, FALSE);
2271         if (ok != IMAP_SUCCESS) {
2272                 g_free(real_oldpath);
2273                 unlock_session(session);
2274                 return -1;
2275         }
2276
2277         separator = imap_get_path_separator(session, IMAP_FOLDER(folder), item->path);
2278         if (strchr(item->path, G_DIR_SEPARATOR)) {
2279                 dirpath = g_path_get_dirname(item->path);
2280                 newpath = g_strconcat(dirpath, G_DIR_SEPARATOR_S, name, NULL);
2281                 g_free(dirpath);
2282         } else
2283                 newpath = g_strdup(name);
2284
2285         real_newpath = imap_utf8_to_modified_utf7(newpath);
2286         imap_path_separator_subst(real_newpath, separator);
2287
2288         ok = imap_cmd_rename(session, real_oldpath, real_newpath);
2289         if (ok != IMAP_SUCCESS) {
2290                 log_warning(LOG_PROTOCOL, _("can't rename mailbox: %s to %s\n"),
2291                             real_oldpath, real_newpath);
2292                 g_free(real_oldpath);
2293                 g_free(newpath);
2294                 g_free(real_newpath);
2295                 unlock_session(session);
2296                 return -1;
2297         }
2298         g_free(item->name);
2299         item->name = g_strdup(name);
2300
2301         old_cache_dir = folder_item_get_path(item);
2302
2303         paths[0] = g_strdup(item->path);
2304         paths[1] = newpath;
2305         g_node_traverse(item->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1,
2306                         imap_rename_folder_func, paths);
2307
2308         if (is_dir_exist(old_cache_dir)) {
2309                 new_cache_dir = folder_item_get_path(item);
2310                 if (rename(old_cache_dir, new_cache_dir) < 0) {
2311                         FILE_OP_ERROR(old_cache_dir, "rename");
2312                 }
2313                 g_free(new_cache_dir);
2314         }
2315
2316         g_free(old_cache_dir);
2317         g_free(paths[0]);
2318         g_free(newpath);
2319         g_free(real_oldpath);
2320         g_free(real_newpath);
2321         unlock_session(session);
2322         return 0;
2323 }
2324
2325 gint imap_subscribe(Folder *folder, FolderItem *item, gchar *rpath, gboolean sub)
2326 {
2327         gchar *path;
2328         gint r = -1;
2329         IMAPSession *session;
2330         debug_print("getting session...\n");
2331
2332         session = imap_session_get(folder);
2333         if (!session) {
2334                 return -1;
2335         }
2336         if (item && item->path) {
2337                 path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path);
2338                 if (!path)
2339                         return -1;
2340                 if (!strcmp(path, "INBOX") && sub == FALSE)
2341                         return -1;
2342                 debug_print("%ssubscribing %s\n", sub?"":"un", path);
2343                 r = imap_threaded_subscribe(folder, path, sub);
2344                 g_free(path);
2345         } else if (rpath) {
2346                 r = imap_threaded_subscribe(folder, rpath, sub);
2347         } else
2348                 return -1;
2349         return r;
2350 }
2351
2352 static gint imap_remove_folder_real(Folder *folder, FolderItem *item)
2353 {
2354         gint ok;
2355         IMAPSession *session;
2356         gchar *path;
2357         gchar *cache_dir;
2358         gboolean selected_folder;
2359
2360         g_return_val_if_fail(folder != NULL, -1);
2361         g_return_val_if_fail(item != NULL, -1);
2362         g_return_val_if_fail(item->path != NULL, -1);
2363
2364         debug_print("getting session...\n");
2365         session = imap_session_get(folder);
2366         if (!session) {
2367                 return -1;
2368         }
2369         path = imap_get_real_path(session, IMAP_FOLDER(folder), item->path);
2370
2371         imap_threaded_subscribe(folder, path, FALSE);
2372
2373         selected_folder = (session->mbox != NULL) &&
2374                           (!strcmp(session->mbox, item->path));
2375         if (selected_folder) {
2376                 ok = imap_cmd_close(session);
2377                 if (ok != MAILIMAP_NO_ERROR) {
2378                         debug_print("close err %d\n", ok);
2379                         return IMAP_ERROR;
2380                 }
2381         }
2382         ok = imap_cmd_delete(session, path);
2383         if (ok != IMAP_SUCCESS) {
2384                 gchar *tmp = g_strdup_printf("%s%c", path, 
2385                                 imap_get_path_separator(session, IMAP_FOLDER(folder), path));
2386                 g_free(path);
2387                 path = tmp;
2388                 ok = imap_cmd_delete(session, path);
2389         }
2390
2391         if (ok != IMAP_SUCCESS) {
2392                 log_warning(LOG_PROTOCOL, _("can't delete mailbox\n"));
2393                 g_free(path);
2394                 unlock_session(session);
2395                 return -1;
2396         }
2397
2398         g_free(path);
2399         cache_dir = folder_item_get_path(item);
2400         if (is_dir_exist(cache_dir) && remove_dir_recursive(cache_dir) < 0)
2401                 g_warning("can't remove directory '%s'\n", cache_dir);
2402         g_free(cache_dir);
2403         folder_item_remove(item);
2404         unlock_session(session);
2405         return 0;
2406 }
2407
2408 static gint imap_remove_folder(Folder *folder, FolderItem *item)
2409 {
2410         GNode *node, *next;
2411
2412         g_return_val_if_fail(item != NULL, -1);
2413         g_return_val_if_fail(item->folder != NULL, -1);
2414         g_return_val_if_fail(item->node != NULL, -1);
2415
2416         node = item->node->children;
2417         while (node != NULL) {
2418                 next = node->next;
2419                 if (imap_remove_folder(folder, FOLDER_ITEM(node->data)) < 0)
2420                         return -1;
2421                 node = next;
2422         }
2423         debug_print("IMAP removing %s\n", item->path);
2424
2425         if (imap_remove_all_msg(folder, item) < 0)
2426                 return -1;
2427         return imap_remove_folder_real(folder, item);
2428 }
2429
2430 typedef struct _uncached_data {
2431         IMAPSession *session;
2432         FolderItem *item;
2433         MsgNumberList *numlist;
2434         guint cur;
2435         guint total;
2436         gboolean done;
2437 } uncached_data;
2438
2439 static void *imap_get_uncached_messages_thread(void *data)
2440 {
2441         uncached_data *stuff = (uncached_data *)data;
2442         IMAPSession *session = stuff->session;
2443         FolderItem *item = stuff->item;
2444         MsgNumberList *numlist = stuff->numlist;
2445         
2446         GSList *newlist = NULL;
2447         GSList *llast = NULL;
2448         GSList *seq_list, *cur;
2449
2450         debug_print("uncached_messages\n");
2451         
2452         if (session == NULL || item == NULL || item->folder == NULL
2453             || FOLDER_CLASS(item->folder) != &imap_class) {
2454                 stuff->done = TRUE;
2455                 return NULL;
2456         }
2457         
2458         seq_list = imap_get_lep_set_from_numlist(numlist);
2459         debug_print("get msgs info\n");
2460         for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
2461                 struct mailimap_set * imapset;
2462                 unsigned int i;
2463                 int r;
2464                 carray * env_list;
2465                 int count;
2466                 
2467                 if (session->cancelled)
2468                         break;
2469                 
2470                 imapset = cur->data;
2471                 
2472                 r = imap_threaded_fetch_env(session->folder,
2473                                             imapset, &env_list);
2474                 if (r != MAILIMAP_NO_ERROR)
2475                         continue;
2476                 
2477                 session_set_access_time(SESSION(session));
2478
2479                 count = 0;
2480                 for(i = 0 ; i < carray_count(env_list) ; i ++) {
2481                         struct imap_fetch_env_info * info;
2482                         MsgInfo * msginfo;
2483                         
2484                         info = carray_get(env_list, i);
2485                         msginfo = imap_envelope_from_lep(info, item);
2486                         if (msginfo == NULL)
2487                                 continue;
2488                         msginfo->folder = item;
2489                         if (!newlist)
2490                                 llast = newlist = g_slist_append(newlist, msginfo);
2491                         else {
2492                                 llast = g_slist_append(llast, msginfo);
2493                                 llast = llast->next;
2494                         }
2495                         count ++;
2496                 }
2497                 
2498                 imap_fetch_env_free(env_list);
2499         }
2500         
2501         for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
2502                 struct mailimap_set * imapset;
2503                 
2504                 imapset = cur->data;
2505                 mailimap_set_free(imapset);
2506         }
2507         
2508         session_set_access_time(SESSION(session));
2509         stuff->done = TRUE;
2510         return newlist;
2511 }
2512
2513 #define MAX_MSG_NUM 50
2514
2515 static GSList *imap_get_uncached_messages(IMAPSession *session,
2516                                         FolderItem *item,
2517                                         MsgNumberList *numlist)
2518 {
2519         GSList *result = NULL;
2520         GSList * cur;
2521         uncached_data *data = g_new0(uncached_data, 1);
2522         int finished;
2523         
2524         finished = 0;
2525         cur = numlist;
2526         data->total = g_slist_length(numlist);
2527         debug_print("messages list : %i\n", data->total);
2528
2529         while (cur != NULL) {
2530                 GSList * partial_result;
2531                 int count;
2532                 GSList * newlist;
2533                 GSList * llast;
2534                 
2535                 llast = NULL;
2536                 count = 0;
2537                 newlist = NULL;
2538                 while (count < MAX_MSG_NUM) {
2539                         void * p;
2540                         
2541                         p = cur->data;
2542                         
2543                         if (newlist == NULL)
2544                                 llast = newlist = g_slist_append(newlist, p);
2545                         else {
2546                                 llast = g_slist_append(llast, p);
2547                                 llast = llast->next;
2548                         }
2549                         count ++;
2550                         
2551                         cur = cur->next;
2552                         if (cur == NULL)
2553                                 break;
2554                 }
2555                 
2556                 data->done = FALSE;
2557                 data->session = session;
2558                 data->item = item;
2559                 data->numlist = newlist;
2560                 data->cur += count;
2561                 
2562                 if (prefs_common.work_offline && 
2563                     !inc_offline_should_override(FALSE,
2564                         _("Claws Mail needs network access in order "
2565                           "to access the IMAP server."))) {
2566                         g_free(data);
2567                         return NULL;
2568                 }
2569                 
2570                 partial_result =
2571                         (GSList *)imap_get_uncached_messages_thread(data);
2572                 
2573                 statusbar_progress_all(data->cur,data->total, 1);
2574                 
2575                 g_slist_free(newlist);
2576                 
2577                 result = g_slist_concat(result, partial_result);
2578         }
2579         g_free(data);
2580         
2581         statusbar_progress_all(0,0,0);
2582         statusbar_pop_all();
2583         
2584         return result;
2585 }
2586
2587 static void imap_delete_all_cached_messages(FolderItem *item)
2588 {
2589         gchar *dir;
2590
2591         g_return_if_fail(item != NULL);
2592         g_return_if_fail(item->folder != NULL);
2593         g_return_if_fail(FOLDER_CLASS(item->folder) == &imap_class);
2594
2595         debug_print("Deleting all cached messages...\n");
2596
2597         dir = folder_item_get_path(item);
2598         if (is_dir_exist(dir))
2599                 remove_all_numbered_files(dir);
2600         g_free(dir);
2601
2602         debug_print("done.\n");
2603 }
2604
2605 gchar imap_get_path_separator_for_item(FolderItem *item)
2606 {
2607         Folder *folder = NULL;
2608         IMAPFolder *imap_folder = NULL;
2609         IMAPSession *session = NULL;
2610         gchar result = '/';
2611         
2612         if (!item)
2613                 return '/';
2614         folder = item->folder;
2615         
2616         if (!folder)
2617                 return '/';
2618         
2619         imap_folder = IMAP_FOLDER(folder);
2620         
2621         if (!imap_folder)
2622                 return '/';
2623         
2624         debug_print("getting session...");
2625         session = imap_session_get(FOLDER(folder));
2626         result = imap_get_path_separator(session, imap_folder, item->path);
2627         unlock_session(session);
2628         return result;
2629 }
2630
2631 static gchar imap_refresh_path_separator(IMAPSession *session, IMAPFolder *folder, const gchar *subfolder)
2632 {
2633         clist * lep_list;
2634         int r;
2635         gchar separator = '\0';
2636         
2637         g_return_val_if_fail(session != NULL, '/');
2638         r = imap_threaded_list((Folder *)folder, "", subfolder, &lep_list);
2639         
2640         if (r != MAILIMAP_NO_ERROR) {
2641                 log_warning(LOG_PROTOCOL, _("LIST failed\n"));
2642                 return '\0';
2643         }
2644
2645         if (clist_count(lep_list) > 0) {
2646                 clistiter * iter = clist_begin(lep_list); 
2647                 struct mailimap_mailbox_list * mb;
2648                 mb = clist_content(iter);
2649
2650                 separator = mb->mb_delimiter;
2651                 debug_print("got separator: %c\n", folder->last_seen_separator);
2652         }
2653         mailimap_list_result_free(lep_list);
2654         return separator;
2655 }
2656
2657 static gchar imap_get_path_separator(IMAPSession *session, IMAPFolder *folder, const gchar *path)
2658 {
2659         gchar separator = '/';
2660
2661         if (folder->last_seen_separator == 0) {
2662                 folder->last_seen_separator = imap_refresh_path_separator(session, folder, "");
2663         }
2664
2665         if (folder->last_seen_separator == 0) {
2666                 folder->last_seen_separator = imap_refresh_path_separator(session, folder, "INBOX");
2667         }
2668
2669         if (folder->last_seen_separator != 0) {
2670                 debug_print("using separator: %c\n", folder->last_seen_separator);
2671                 return folder->last_seen_separator;
2672         }
2673
2674         return separator;
2675 }
2676
2677 static gchar *imap_get_real_path(IMAPSession *session, IMAPFolder *folder, const gchar *path)
2678 {
2679         gchar *real_path;
2680         gchar separator;
2681
2682         g_return_val_if_fail(folder != NULL, NULL);
2683         g_return_val_if_fail(path != NULL, NULL);
2684
2685         real_path = imap_utf8_to_modified_utf7(path);
2686         separator = imap_get_path_separator(session, folder, path);
2687         imap_path_separator_subst(real_path, separator);
2688
2689         return real_path;
2690 }
2691
2692 static gint imap_set_message_flags(IMAPSession *session,
2693                                    MsgNumberList *numlist,
2694                                    IMAPFlags flags,
2695                                    gboolean is_set)
2696 {
2697         gint ok = 0;
2698         GSList *seq_list;
2699         GSList * cur;
2700
2701         seq_list = imap_get_lep_set_from_numlist(numlist);
2702         
2703         for(cur = seq_list ; cur != NULL ; cur = g_slist_next(cur)) {
2704                 struct mailimap_set * imapset;
2705                 
2706                 imapset = cur->data;
2707                 
2708                 ok = imap_cmd_store(session, imapset,
2709                                     flags, is_set);
2710         }
2711         
2712         imap_lep_set_free(seq_list);
2713         
2714         return IMAP_SUCCESS;
2715 }
2716
2717 typedef struct _select_data {
2718         IMAPSession *session;
2719         gchar *real_path;
2720         gint *exists;
2721         gint *recent;
2722         gint *unseen;
2723         guint32 *uid_validity;
2724         gboolean done;
2725 } select_data;
2726
2727 static gint imap_select(IMAPSession *session, IMAPFolder *folder,
2728                         const gchar *path,
2729                         gint *exists, gint *recent, gint *unseen,
2730                         guint32 *uid_validity, gboolean block)
2731 {
2732         gchar *real_path;
2733         gint ok;
2734         gint exists_, recent_, unseen_;
2735         guint32 uid_validity_;
2736         
2737         if (!exists && !recent && !unseen && !uid_validity) {
2738                 if (session->mbox && strcmp(session->mbox, path) == 0)
2739                         return IMAP_SUCCESS;
2740         }
2741         if (!exists)
2742                 exists = &exists_;
2743         if (!recent)
2744                 recent = &recent_;
2745         if (!unseen)
2746                 unseen = &unseen_;
2747         if (!uid_validity)
2748                 uid_validity = &uid_validity_;
2749
2750         g_free(session->mbox);
2751         session->mbox = NULL;
2752         session->exists = 0;
2753         session->recent = 0;
2754         session->expunge = 0;
2755
2756         real_path = imap_get_real_path(session, folder, path);
2757
2758         ok = imap_cmd_select(session, real_path,
2759                              exists, recent, unseen, uid_validity, block);
2760         if (ok != IMAP_SUCCESS)
2761                 log_warning(LOG_PROTOCOL, _("can't select folder: %s\n"), real_path);
2762         else {
2763                 session->mbox = g_strdup(path);
2764                 session->folder_content_changed = FALSE;
2765                 session->exists = *exists;
2766                 session->recent = *recent;
2767                 session->expunge = 0;
2768                 session->unseen = *unseen;
2769                 session->uid_validity = *uid_validity;
2770                 debug_print("select: exists %d recent %d expunge %d uid_validity %d\n", 
2771                         session->exists, session->recent, session->expunge,
2772                         session->uid_validity);
2773         }
2774         g_free(real_path);
2775
2776         return ok;
2777 }
2778
2779 static gint imap_status(IMAPSession *session, IMAPFolder *folder,
2780                         const gchar *path, IMAPFolderItem *item,
2781                         gint *messages,
2782                         guint32 *uid_next, guint32 *uid_validity,
2783                         gint *unseen, gboolean block)
2784 {
2785         int r;
2786         clistiter * iter;
2787         struct mailimap_mailbox_data_status * data_status;
2788         int got_values;
2789         gchar *real_path;
2790         guint mask = 0;
2791         
2792         real_path = imap_get_real_path(session, folder, path);
2793
2794         if (messages) {
2795                 mask |= 1 << 0;
2796                 *messages = 0;
2797         }
2798         if (uid_next) {
2799                 mask |= 1 << 2;
2800                 *uid_next = 0;
2801         }
2802         if (uid_validity) {
2803                 mask |= 1 << 3;
2804                 *uid_validity = 0;
2805         }
2806         if (unseen) {
2807                 mask |= 1 << 4;
2808                 *unseen = 0;
2809         }
2810         
2811         if (session->mbox != NULL &&
2812             !strcmp(session->mbox, item->item.path)) {
2813                 r = imap_cmd_close(session);
2814                 if (r != MAILIMAP_NO_ERROR) {
2815                         debug_print("close err %d\n", r);
2816                         return IMAP_ERROR;
2817                 }
2818         }
2819         
2820         r = imap_threaded_status(FOLDER(folder), real_path, 
2821                 &data_status, mask);
2822
2823         g_free(real_path);
2824         if (r != MAILIMAP_NO_ERROR) {
2825                 debug_print("status err %d\n", r);
2826                 return IMAP_ERROR;
2827         }
2828         
2829         if (data_status->st_info_list == NULL) {
2830                 mailimap_mailbox_data_status_free(data_status);
2831                 debug_print("status->st_info_list == NULL\n");
2832                 return IMAP_ERROR;
2833         }
2834         
2835         got_values = 0;
2836         for(iter = clist_begin(data_status->st_info_list) ; iter != NULL ;
2837             iter = clist_next(iter)) {
2838                 struct mailimap_status_info * info;             
2839                 
2840                 info = clist_content(iter);
2841                 switch (info->st_att) {
2842                 case MAILIMAP_STATUS_ATT_MESSAGES:
2843                         if (messages) {
2844                                 * messages = info->st_value;
2845                                 got_values |= 1 << 0;
2846                         }
2847                         break;
2848                         
2849                 case MAILIMAP_STATUS_ATT_UIDNEXT:
2850                         if (uid_next) {
2851                                 * uid_next = info->st_value;
2852                                 got_values |= 1 << 2;
2853                         }
2854                         break;
2855                         
2856                 case MAILIMAP_STATUS_ATT_UIDVALIDITY:
2857                         if (uid_validity) {
2858                                 * uid_validity = info->st_value;
2859                                 got_values |= 1 << 3;
2860                         }
2861                         break;
2862                         
2863                 case MAILIMAP_STATUS_ATT_UNSEEN:
2864                         if (unseen) {
2865                                 * unseen = info->st_value;
2866                                 got_values |= 1 << 4;
2867                         }
2868                         break;
2869                 }
2870         }
2871         mailimap_mailbox_data_status_free(data_status);
2872         
2873         if (got_values != mask) {
2874                 g_warning("status: incomplete values received (%d)\n", got_values);
2875         }
2876         return IMAP_SUCCESS;
2877 }
2878
2879 static void imap_free_capabilities(IMAPSession *session)
2880 {
2881         slist_free_strings(session->capability);
2882         g_slist_free(session->capability);
2883         session->capability = NULL;
2884 }
2885
2886 /* low-level IMAP4rev1 commands */
2887
2888 static gint imap_cmd_login(IMAPSession *session,
2889                            const gchar *user, const gchar *pass,
2890                            const gchar *type)
2891 {
2892         int r;
2893         gint ok;
2894
2895         if (!strcmp(type, "LOGIN") && imap_has_capability(session, "LOGINDISABLED")) {
2896                 gint ok = IMAP_ERROR;
2897                 if (imap_has_capability(session, "STARTTLS")) {
2898 #if USE_OPENSSL
2899                         log_warning(LOG_PROTOCOL, _("Server requires TLS to log in.\n"));
2900                         ok = imap_cmd_starttls(session);
2901                         if (ok != IMAP_SUCCESS) {
2902                                 log_warning(LOG_PROTOCOL, _("Can't start TLS session.\n"));
2903                                 return IMAP_ERROR;
2904                         } else {
2905                                 /* refresh capas */
2906                                 imap_free_capabilities(session);
2907                                 if (imap_get_capabilities(session) != MAILIMAP_NO_ERROR) {
2908                                         log_warning(LOG_PROTOCOL, _("Can't refresh capabilities.\n"));
2909                                         return IMAP_ERROR;
2910                                 }
2911                         }
2912 #else           
2913                         log_error(LOG_PROTOCOL, _("Connection to %s failed: "
2914                                         "server requires TLS, but Claws Mail "
2915                                         "has been compiled without OpenSSL "
2916                                         "support.\n"),
2917                                         SESSION(session)->server);
2918                         return IMAP_ERROR;
2919 #endif
2920                 } else {
2921                         log_error(LOG_PROTOCOL, _("Server logins are disabled.\n"));
2922                         return IMAP_ERROR;
2923                 }
2924         }
2925
2926         log_print(LOG_PROTOCOL, "IMAP4> Logging %s to %s using %s\n", 
2927                         user,
2928                         SESSION(session)->server,
2929                         type);
2930         r = imap_threaded_login(session->folder, user, pass, type);
2931         if (r != MAILIMAP_NO_ERROR) {
2932                 log_print(LOG_PROTOCOL, "IMAP4< Error logging in to %s\n",
2933                                 SESSION(session)->server);
2934                 ok = IMAP_ERROR;
2935         } else {
2936                 log_print(LOG_PROTOCOL, "IMAP4< Login to %s successful\n",
2937                                 SESSION(session)->server);
2938                 ok = IMAP_SUCCESS;
2939         }
2940         return ok;
2941 }
2942
2943 static gint imap_cmd_noop(IMAPSession *session)
2944 {
2945         int r;
2946         unsigned int exists, recent, expunge, unseen, uidnext, uidval;
2947         
2948         r = imap_threaded_noop(session->folder, &exists, &recent, &expunge, &unseen, &uidnext, &uidval);
2949         if (r != MAILIMAP_NO_ERROR) {
2950                 debug_print("noop err %d\n", r);
2951                 return IMAP_ERROR;
2952         }
2953
2954         session->folder_content_changed = FALSE;
2955
2956         if ((exists && exists != session->exists)
2957          || (recent && recent != session->recent)
2958          || (expunge && expunge != session->expunge)
2959          || (unseen && unseen != session->unseen)) {
2960                 session->folder_content_changed = TRUE;
2961         }
2962         if (uidnext != 0 && uidnext != session->uid_next) {
2963                 session->uid_next = uidnext;
2964                 session->folder_content_changed = TRUE;
2965         }
2966         if (uidval != 0 && uidval != session->uid_validity) {
2967                 session->uid_validity = uidval;
2968                 session->folder_content_changed = TRUE;
2969         }
2970
2971         session->exists = exists;
2972         session->recent = recent;
2973         session->expunge = expunge;
2974         session->unseen = unseen;
2975
2976         session_set_access_time(SESSION(session));
2977
2978         return IMAP_SUCCESS;
2979 }
2980
2981 #if USE_OPENSSL
2982 static gint imap_cmd_starttls(IMAPSession *session)
2983 {
2984         int r;
2985         
2986         r = imap_threaded_starttls(session->folder, 
2987                 SESSION(session)->server, SESSION(session)->port);
2988         if (r != MAILIMAP_NO_ERROR) {
2989                 debug_print("starttls err %d\n", r);
2990                 return IMAP_ERROR;
2991         }
2992         return IMAP_SUCCESS;
2993 }
2994 #endif
2995
2996 static gint imap_cmd_select(IMAPSession *session, const gchar *folder,
2997                             gint *exists, gint *recent, gint *unseen,
2998                             guint32 *uid_validity, gboolean block)
2999 {
3000         int r;
3001
3002         r = imap_threaded_select(session->folder, folder,
3003                                  exists, recent, unseen, uid_validity);
3004         if (r != MAILIMAP_NO_ERROR) {
3005                 debug_print("select err %d\n", r);
3006                 return IMAP_ERROR;
3007         }
3008         return IMAP_SUCCESS;
3009 }
3010
3011 static gint imap_cmd_close(IMAPSession *session)
3012 {
3013         int r;
3014
3015         r = imap_threaded_close(session->folder);
3016         if (r != MAILIMAP_NO_ERROR) {
3017                 debug_print("close err %d\n", r);
3018                 return IMAP_ERROR;
3019         }
3020         g_free(session->mbox);
3021         session->mbox = NULL;
3022         session->exists = 0;
3023         session->recent = 0;
3024         session->expunge = 0;
3025         return IMAP_SUCCESS;
3026 }
3027
3028 static gint imap_cmd_examine(IMAPSession *session, const gchar *folder,
3029                              gint *exists, gint *recent, gint *unseen,
3030                              guint32 *uid_validity, gboolean block)
3031 {
3032         int r;
3033
3034         r = imap_threaded_examine(session->folder, folder,
3035                                   exists, recent, unseen, uid_validity);
3036         if (r != MAILIMAP_NO_ERROR) {
3037                 debug_print("examine err %d\n", r);
3038                 
3039                 return IMAP_ERROR;
3040         }
3041         return IMAP_SUCCESS;
3042 }
3043
3044 static gint imap_cmd_create(IMAPSession *session, const gchar *folder)
3045 {
3046         int r;
3047
3048         r = imap_threaded_create(session->folder, folder);
3049         if (r != MAILIMAP_NO_ERROR) {
3050                 
3051                 return IMAP_ERROR;
3052         }
3053
3054         return IMAP_SUCCESS;
3055 }
3056
3057 static gint imap_cmd_rename(IMAPSession *session, const gchar *old_folder,
3058                             const gchar *new_folder)
3059 {
3060         int r;
3061
3062         r = imap_threaded_rename(session->folder, old_folder,
3063                                  new_folder);
3064         if (r != MAILIMAP_NO_ERROR) {
3065                 
3066                 return IMAP_ERROR;
3067         }
3068
3069         return IMAP_SUCCESS;
3070 }
3071
3072 static gint imap_cmd_delete(IMAPSession *session, const gchar *folder)
3073 {
3074         int r;
3075         
3076
3077         r = imap_threaded_delete(session->folder, folder);
3078         if (r != MAILIMAP_NO_ERROR) {
3079                 
3080                 return IMAP_ERROR;
3081         }
3082
3083         return IMAP_SUCCESS;
3084 }
3085
3086 typedef struct _fetch_data {
3087         IMAPSession *session;
3088         guint32 uid;
3089         const gchar *filename;
3090         gboolean headers;
3091         gboolean body;
3092         gboolean done;
3093 } fetch_data;
3094
3095 static void *imap_cmd_fetch_thread(void *data)
3096 {
3097         fetch_data *stuff = (fetch_data *)data;
3098         IMAPSession *session = stuff->session;
3099         guint32 uid = stuff->uid;
3100         const gchar *filename = stuff->filename;
3101         int r;
3102         
3103         if (stuff->body) {
3104                 r = imap_threaded_fetch_content(session->folder,
3105                                                uid, 1, filename);
3106         }
3107         else {
3108                 r = imap_threaded_fetch_content(session->folder,
3109                                                 uid, 0, filename);
3110         }
3111         if (r != MAILIMAP_NO_ERROR) {
3112                 debug_print("fetch err %d\n", r);
3113                 return GINT_TO_POINTER(IMAP_ERROR);
3114         }
3115         return GINT_TO_POINTER(IMAP_SUCCESS);
3116 }
3117
3118 static gint imap_cmd_fetch(IMAPSession *session, guint32 uid,
3119                                 const gchar *filename, gboolean headers,
3120                                 gboolean body)
3121 {
3122         fetch_data *data = g_new0(fetch_data, 1);
3123         int result = 0;
3124         data->done = FALSE;
3125         data->session = session;
3126         data->uid = uid;
3127         data->filename = filename;
3128         data->headers = headers;
3129         data->body = body;
3130
3131         if (prefs_common.work_offline && 
3132             !inc_offline_should_override(FALSE,
3133                 _("Claws Mail needs network access in order "
3134                   "to access the IMAP server."))) {
3135                 g_free(data);
3136                 return -1;
3137         }
3138         statusbar_print_all(_("Fetching message..."));
3139         result = GPOINTER_TO_INT(imap_cmd_fetch_thread(data));
3140         statusbar_pop_all();
3141         g_free(data);
3142         return result;
3143 }
3144
3145
3146 static gint imap_cmd_append(IMAPSession *session, const gchar *destfolder,
3147                             const gchar *file, IMAPFlags flags, 
3148                             guint32 *new_uid)
3149 {
3150         struct mailimap_flag_list * flag_list;
3151         int r;
3152         
3153         g_return_val_if_fail(file != NULL, IMAP_ERROR);
3154
3155         flag_list = imap_flag_to_lep(flags);
3156         r = imap_threaded_append(session->folder, destfolder,
3157                          file, flag_list, (int *)new_uid);
3158         mailimap_flag_list_free(flag_list);
3159
3160         if (r != MAILIMAP_NO_ERROR) {
3161                 debug_print("append err %d\n", r);
3162                 return IMAP_ERROR;
3163         }
3164         return IMAP_SUCCESS;
3165 }
3166
3167 static gint imap_cmd_copy(IMAPSession *session, struct mailimap_set * set,
3168                           const gchar *destfolder, GRelation *uid_mapping,
3169                           struct mailimap_set **source, struct mailimap_set **dest)
3170 {
3171         int r;
3172         
3173         g_return_val_if_fail(session != NULL, IMAP_ERROR);
3174         g_return_val_if_fail(set != NULL, IMAP_ERROR);
3175         g_return_val_if_fail(destfolder != NULL, IMAP_ERROR);
3176
3177         r = imap_threaded_copy(session->folder, set, destfolder, source, dest);
3178         if (r != MAILIMAP_NO_ERROR) {
3179                 
3180                 return IMAP_ERROR;
3181         }
3182
3183         return IMAP_SUCCESS;
3184 }
3185
3186 static gint imap_cmd_store(IMAPSession *session, struct mailimap_set * set,
3187                            IMAPFlags flags, int do_add)
3188 {
3189         int r;
3190         struct mailimap_flag_list * flag_list;
3191         struct mailimap_store_att_flags * store_att_flags;
3192         
3193         flag_list = imap_flag_to_lep(flags);
3194         
3195         if (do_add)
3196                 store_att_flags =
3197                         mailimap_store_att_flags_new_add_flags_silent(flag_list);
3198         else
3199                 store_att_flags =
3200                         mailimap_store_att_flags_new_remove_flags_silent(flag_list);
3201         
3202         r = imap_threaded_store(session->folder, set, store_att_flags);
3203         mailimap_store_att_flags_free(store_att_flags);
3204         if (r != MAILIMAP_NO_ERROR) {
3205                 
3206                 return IMAP_ERROR;
3207         }
3208         
3209         return IMAP_SUCCESS;
3210 }
3211
3212 static gint imap_cmd_expunge(IMAPSession *session)
3213 {
3214         int r;
3215         
3216         if (prefs_common.work_offline && 
3217             !inc_offline_should_override(FALSE,
3218                 _("Claws Mail needs network access in order "
3219                   "to access the IMAP server."))) {
3220                 return -1;
3221         }
3222
3223         r = imap_threaded_expunge(session->folder);
3224         if (r != MAILIMAP_NO_ERROR) {
3225                 
3226                 return IMAP_ERROR;
3227         }
3228
3229         return IMAP_SUCCESS;
3230 }
3231
3232 static void imap_path_separator_subst(gchar *str, gchar separator)
3233 {
3234         gchar *p;
3235         gboolean in_escape = FALSE;
3236
3237         if (!separator || separator == '/') return;
3238
3239         for (p = str; *p != '\0'; p++) {
3240                 if (*p == '/' && !in_escape)
3241                         *p = separator;
3242                 else if (*p == '&' && *(p + 1) != '-' && !in_escape)
3243                         in_escape = TRUE;
3244                 else if (*p == '-' && in_escape)
3245                         in_escape = FALSE;
3246         }
3247 }
3248
3249 static gchar *imap_modified_utf7_to_utf8(const gchar *mutf7_str)
3250 {
3251         static iconv_t cd = (iconv_t)-1;
3252         static gboolean iconv_ok = TRUE;
3253         GString *norm_utf7;
3254         gchar *norm_utf7_p;
3255         size_t norm_utf7_len;
3256         const gchar *p;
3257         gchar *to_str, *to_p;
3258         size_t to_len;
3259         gboolean in_escape = FALSE;
3260
3261         if (!iconv_ok) return g_strdup(mutf7_str);
3262
3263         if (cd == (iconv_t)-1) {
3264                 cd = iconv_open(CS_INTERNAL, CS_UTF_7);
3265                 if (cd == (iconv_t)-1) {
3266                         g_warning("iconv cannot convert UTF-7 to %s\n",
3267                                   CS_INTERNAL);
3268                         iconv_ok = FALSE;
3269                         return g_strdup(mutf7_str);
3270                 }
3271         }
3272
3273         /* modified UTF-7 to normal UTF-7 conversion */
3274         norm_utf7 = g_string_new(NULL);
3275
3276         for (p = mutf7_str; *p != '\0'; p++) {
3277                 /* replace: '&'  -> '+',
3278                             "&-" -> '&',
3279                             escaped ','  -> '/' */
3280                 if (!in_escape && *p == '&') {
3281                         if (*(p + 1) != '-') {
3282                                 g_string_append_c(norm_utf7, '+');
3283                                 in_escape = TRUE;
3284                         } else {
3285                                 g_string_append_c(norm_utf7, '&');
3286                                 p++;
3287                         }
3288                 } else if (in_escape && *p == ',') {
3289                         g_string_append_c(norm_utf7, '/');
3290                 } else if (in_escape && *p == '-') {
3291                         g_string_append_c(norm_utf7, '-');
3292                         in_escape = FALSE;
3293                 } else {
3294                         g_string_append_c(norm_utf7, *p);
3295                 }
3296         }
3297
3298         norm_utf7_p = norm_utf7->str;
3299         norm_utf7_len = norm_utf7->len;
3300         to_len = strlen(mutf7_str) * 5;
3301         to_p = to_str = g_malloc(to_len + 1);
3302
3303         if (iconv(cd, (ICONV_CONST gchar **)&norm_utf7_p, &norm_utf7_len,
3304                   &to_p, &to_len) == -1) {
3305                 g_warning(_("iconv cannot convert UTF-7 to %s\n"),
3306                           conv_get_locale_charset_str());
3307                 g_string_free(norm_utf7, TRUE);
3308                 g_free(to_str);
3309                 return g_strdup(mutf7_str);
3310         }
3311
3312         /* second iconv() call for flushing */
3313         iconv(cd, NULL, NULL, &to_p, &to_len);
3314         g_string_free(norm_utf7, TRUE);
3315         *to_p = '\0';
3316
3317         return to_str;
3318 }
3319
3320 static gchar *imap_utf8_to_modified_utf7(const gchar *from)
3321 {
3322         static iconv_t cd = (iconv_t)-1;
3323         static gboolean iconv_ok = TRUE;
3324         gchar *norm_utf7, *norm_utf7_p;
3325         size_t from_len, norm_utf7_len;
3326         GString *to_str;
3327         gchar *from_tmp, *to, *p;
3328         gboolean in_escape = FALSE;
3329
3330         if (!iconv_ok) return g_strdup(from);
3331
3332         if (cd == (iconv_t)-1) {
3333                 cd = iconv_open(CS_UTF_7, CS_INTERNAL);
3334                 if (cd == (iconv_t)-1) {
3335                         g_warning(_("iconv cannot convert %s to UTF-7\n"),
3336                                   CS_INTERNAL);
3337                         iconv_ok = FALSE;
3338                         return g_strdup(from);
3339                 }
3340         }
3341
3342         /* UTF-8 to normal UTF-7 conversion */
3343         Xstrdup_a(from_tmp, from, return g_strdup(from));
3344         from_len = strlen(from);
3345         norm_utf7_len = from_len * 5;
3346         Xalloca(norm_utf7, norm_utf7_len + 1, return g_strdup(from));
3347         norm_utf7_p = norm_utf7;
3348
3349 #define IS_PRINT(ch) (isprint(ch) && IS_ASCII(ch))
3350
3351         while (from_len > 0) {
3352                 if (*from_tmp == '+') {
3353                         *norm_utf7_p++ = '+';
3354                         *norm_utf7_p++ = '-';
3355                         norm_utf7_len -= 2;
3356                         from_tmp++;
3357                         from_len--;
3358                 } else if (IS_PRINT(*(guchar *)from_tmp)) {
3359                         /* printable ascii char */
3360                         *norm_utf7_p = *from_tmp;
3361                         norm_utf7_p++;
3362                         norm_utf7_len--;
3363                         from_tmp++;
3364                         from_len--;
3365                 } else {
3366                         size_t conv_len = 0;
3367
3368                         /* unprintable char: convert to UTF-7 */
3369                         p = from_tmp;
3370                         while (!IS_PRINT(*(guchar *)p) && conv_len < from_len) {
3371                                 conv_len += g_utf8_skip[*(guchar *)p];
3372                                 p += g_utf8_skip[*(guchar *)p];
3373                         }
3374
3375                         from_len -= conv_len;
3376                         if (iconv(cd, (ICONV_CONST gchar **)&from_tmp,
3377                                   &conv_len,
3378                                   &norm_utf7_p, &norm_utf7_len) == -1) {
3379                                 g_warning(_("iconv cannot convert UTF-8 to UTF-7\n"));
3380                                 return g_strdup(from);
3381                         }
3382
3383                         /* second iconv() call for flushing */
3384                         iconv(cd, NULL, NULL, &norm_utf7_p, &norm_utf7_len);
3385                 }
3386         }
3387
3388 #undef IS_PRINT
3389
3390         *norm_utf7_p = '\0';
3391         to_str = g_string_new(NULL);
3392         for (p = norm_utf7; p < norm_utf7_p; p++) {
3393                 /* replace: '&' -> "&-",
3394                             '+' -> '&',
3395                             "+-" -> '+',
3396                             BASE64 '/' -> ',' */
3397                 if (!in_escape && *p == '&') {
3398                         g_string_append(to_str, "&-");
3399                 } else if (!in_escape && *p == '+') {
3400                         if (*(p + 1) == '-') {
3401                                 g_string_append_c(to_str, '+');
3402                                 p++;
3403                         } else {
3404                                 g_string_append_c(to_str, '&');
3405                                 in_escape = TRUE;
3406                         }
3407                 } else if (in_escape && *p == '/') {
3408                         g_string_append_c(to_str, ',');
3409                 } else if (in_escape && *p == '-') {