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