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