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