8e86b4605bb3a212d4594799b0d634ec5f12b245
[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                 session_destroy(SESSION(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 gint 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_val_if_fail(folder != NULL, -1);
933         g_return_val_if_fail(item != NULL, -1);
934
935         session = imap_session_get(folder);
936         if (!session) return -1;
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 -1;
942
943         item->new = unseen > 0 ? recent : 0;
944         item->unread = unseen;
945         item->total = messages;
946         /* item->mtime = uid_validity; */
947
948         return 0;
949 }
950
951 void imap_scan_tree(Folder *folder)
952 {
953         IMAPFolder *imapfolder = IMAP_FOLDER(folder);
954         FolderItem *item;
955         IMAPSession *session;
956         IMAPNameSpace *namespace = NULL;
957         gchar *root_folder = NULL;
958
959         g_return_if_fail(folder != NULL);
960         g_return_if_fail(folder->account != NULL);
961
962         session = imap_session_get(folder);
963         if (!session) return;
964
965         if (imapfolder->namespace && imapfolder->namespace->data)
966                 namespace = (IMAPNameSpace *)imapfolder->namespace->data;
967
968         if (folder->account->imap_dir && *folder->account->imap_dir) {
969                 gchar *imap_dir;
970                 Xstrdup_a(imap_dir, folder->account->imap_dir, return);
971                 strtailchomp(imap_dir, '/');
972                 root_folder = g_strconcat
973                         (namespace && namespace->name ? namespace->name : "",
974                          imap_dir, NULL);
975                 if (namespace && namespace->separator)
976                         subst_char(root_folder, namespace->separator, '/');
977         }
978
979         if (root_folder)
980                 debug_print("IMAP root directory: %s\n", root_folder);
981
982         folder_tree_destroy(folder);
983         item = folder_item_new(folder->name, root_folder);
984         item->folder = folder;
985         folder->node = g_node_new(item);
986         g_free(root_folder);
987
988         imap_scan_tree_recursive(session, item, namespace);
989
990         imap_create_missing_folders(folder);
991 }
992
993 static gint imap_scan_tree_recursive(IMAPSession *session, FolderItem *item,
994                                      IMAPNameSpace *namespace)
995 {
996         Folder *folder;
997         IMAPFolder *imapfolder;
998         FolderItem *new_item;
999         GSList *item_list, *cur;
1000         gchar *real_path;
1001         gchar *wildcard_path;
1002         gchar separator = '/';
1003         gchar wildcard[3];
1004
1005         g_return_val_if_fail(item != NULL, -1);
1006         g_return_val_if_fail(item->folder != NULL, -1);
1007         g_return_val_if_fail(item->no_sub == FALSE, -1);
1008
1009         folder = FOLDER(item->folder);
1010         imapfolder = IMAP_FOLDER(folder);
1011
1012         if (namespace && namespace->separator)
1013                 separator = namespace->separator;
1014
1015         if (item->folder->ui_func)
1016                 item->folder->ui_func(folder, item, folder->ui_func_data);
1017
1018         if (item->path) {
1019                 wildcard[0] = separator;
1020                 wildcard[1] = '%';
1021                 wildcard[2] = '\0';
1022                 real_path = imap_get_real_path(imapfolder, item->path);
1023         } else {
1024                 wildcard[0] = '%';
1025                 wildcard[1] = '\0';
1026                 real_path = g_strdup(namespace && namespace->name &&
1027                                      strncmp(namespace->name, "INBOX", 5) != 0
1028                                      ? namespace->name : "");
1029         }
1030
1031         Xstrcat_a(wildcard_path, real_path, wildcard,
1032                   {g_free(real_path); return IMAP_ERROR;});
1033         QUOTE_IF_REQUIRED(wildcard_path, wildcard_path);
1034
1035         imap_cmd_gen_send(SESSION(session)->sock, "LIST \"\" %s",
1036                           wildcard_path);
1037
1038         strtailchomp(real_path, separator);
1039         item_list = imap_parse_list(session, real_path);
1040         g_free(real_path);
1041
1042         for (cur = item_list; cur != NULL; cur = cur->next) {
1043                 new_item = cur->data;
1044                 if (!strcmp(new_item->path, "INBOX")) {
1045                         if (!folder->inbox) {
1046                                 new_item->stype = F_INBOX;
1047                                 item->folder->inbox = new_item;
1048                         } else {
1049                                 folder_item_destroy(new_item);
1050                                 continue;
1051                         }
1052                 } else if (!item->parent || item->stype == F_INBOX) {
1053                         gchar *base;
1054
1055                         base = g_basename(new_item->path);
1056
1057                         if (!folder->outbox && !strcasecmp(base, "Sent")) {
1058                                 new_item->stype = F_OUTBOX;
1059                                 folder->outbox = new_item;
1060                         } else if (!folder->draft && !strcasecmp(base, "Drafts")) {
1061                                 new_item->stype = F_DRAFT;
1062                                 folder->draft = new_item;
1063                         } else if (!folder->queue && !strcasecmp(base, "Queue")) {
1064                                 new_item->stype = F_QUEUE;
1065                                 folder->queue = new_item;
1066                         } else if (!folder->trash && !strcasecmp(base, "Trash")) {
1067                                 new_item->stype = F_TRASH;
1068                                 folder->trash = new_item;
1069                         }
1070                 }
1071                 folder_item_append(item, new_item);
1072                 if (new_item->no_select == FALSE)
1073                         imap_scan_folder(folder, new_item);
1074                 if (new_item->no_sub == FALSE)
1075                         imap_scan_tree_recursive(session, new_item, namespace);
1076         }
1077
1078         return IMAP_SUCCESS;
1079 }
1080
1081 static GSList *imap_parse_list(IMAPSession *session, const gchar *real_path)
1082 {
1083         gchar buf[IMAPBUFSIZE];
1084         gchar flags[256];
1085         gchar separator[16];
1086         gchar *p;
1087         gchar *name;
1088         gchar *loc_name, *loc_path;
1089         GSList *item_list = NULL;
1090         GString *str;
1091         FolderItem *new_item;
1092
1093         debug_print("getting list of %s ...\n",
1094                     *real_path ? real_path : "\"\"");
1095
1096         str = g_string_new(NULL);
1097
1098         for (;;) {
1099                 if (sock_gets(SESSION(session)->sock, buf, sizeof(buf)) <= 0) {
1100                         log_warning(_("error occured while getting LIST.\n"));
1101                         break;
1102                 }
1103                 strretchomp(buf);
1104                 if (buf[0] != '*' || buf[1] != ' ') {
1105                         log_print("IMAP4< %s\n", buf);
1106                         break;
1107                 }
1108                 debug_print("IMAP4< %s\n", buf);
1109
1110                 g_string_assign(str, buf);
1111                 p = str->str + 2;
1112                 if (strncmp(p, "LIST ", 5) != 0) continue;
1113                 p += 5;
1114
1115                 if (*p != '(') continue;
1116                 p++;
1117                 p = strchr_cpy(p, ')', flags, sizeof(flags));
1118                 if (!p) continue;
1119                 while (*p == ' ') p++;
1120
1121                 p = strchr_cpy(p, ' ', separator, sizeof(separator));
1122                 if (!p) continue;
1123                 extract_quote(separator, '"');
1124                 if (!strcmp(separator, "NIL"))
1125                         separator[0] = '\0';
1126
1127                 buf[0] = '\0';
1128                 while (*p == ' ') p++;
1129                 if (*p == '{' || *p == '"')
1130                         p = imap_parse_atom(SESSION(session)->sock, p,
1131                                             buf, sizeof(buf), str);
1132                 else
1133                         strncpy2(buf, p, sizeof(buf));
1134                 strtailchomp(buf, separator[0]);
1135                 if (buf[0] == '\0') continue;
1136                 if (!strcmp(buf, real_path)) continue;
1137
1138                 if (separator[0] != '\0')
1139                         subst_char(buf, separator[0], '/');
1140                 name = g_basename(buf);
1141                 if (name[0] == '.') continue;
1142
1143                 loc_name = imap_modified_utf7_to_locale(name);
1144                 loc_path = imap_modified_utf7_to_locale(buf);
1145                 new_item = folder_item_new(loc_name, loc_path);
1146                 if (strcasestr(flags, "\\Noinferiors") != NULL)
1147                         new_item->no_sub = TRUE;
1148                 if (strcmp(buf, "INBOX") != 0 &&
1149                     strcasestr(flags, "\\Noselect") != NULL)
1150                         new_item->no_select = TRUE;
1151
1152                 item_list = g_slist_append(item_list, new_item);
1153
1154                 debug_print("folder %s has been added.\n", loc_path);
1155                 g_free(loc_path);
1156                 g_free(loc_name);
1157         }
1158
1159         g_string_free(str, TRUE);
1160         statusbar_pop_all();
1161
1162         return item_list;
1163 }
1164
1165 gint imap_create_tree(Folder *folder)
1166 {
1167         g_return_val_if_fail(folder != NULL, -1);
1168         g_return_val_if_fail(folder->node != NULL, -1);
1169         g_return_val_if_fail(folder->node->data != NULL, -1);
1170         g_return_val_if_fail(folder->account != NULL, -1);
1171
1172         imap_scan_tree(folder);
1173         imap_create_missing_folders(folder);
1174
1175         return 0;
1176 }
1177
1178 static void imap_create_missing_folders(Folder *folder)
1179 {
1180         g_return_if_fail(folder != NULL);
1181
1182         if (!folder->inbox)
1183                 folder->inbox = imap_create_special_folder
1184                         (folder, F_INBOX, "INBOX");
1185 #if 0
1186         if (!folder->outbox)
1187                 folder->outbox = imap_create_special_folder
1188                         (folder, F_OUTBOX, "Sent");
1189         if (!folder->draft)
1190                 folder->draft = imap_create_special_folder
1191                         (folder, F_DRAFT, "Drafts");
1192         if (!folder->queue)
1193                 folder->queue = imap_create_special_folder
1194                         (folder, F_QUEUE, "Queue");
1195 #endif
1196         if (!folder->trash)
1197                 folder->trash = imap_create_special_folder
1198                         (folder, F_TRASH, "Trash");
1199 }
1200
1201 static FolderItem *imap_create_special_folder(Folder *folder,
1202                                               SpecialFolderItemType stype,
1203                                               const gchar *name)
1204 {
1205         FolderItem *item;
1206         FolderItem *new_item;
1207
1208         g_return_val_if_fail(folder != NULL, NULL);
1209         g_return_val_if_fail(folder->node != NULL, NULL);
1210         g_return_val_if_fail(folder->node->data != NULL, NULL);
1211         g_return_val_if_fail(folder->account != NULL, NULL);
1212         g_return_val_if_fail(name != NULL, NULL);
1213
1214         item = FOLDER_ITEM(folder->node->data);
1215         new_item = imap_create_folder(folder, item, name);
1216
1217         if (!new_item) {
1218                 g_warning(_("Can't create '%s'\n"), name);
1219                 if (!folder->inbox) return NULL;
1220
1221                 new_item = imap_create_folder(folder, folder->inbox, name);
1222                 if (!new_item)
1223                         g_warning(_("Can't create '%s' under INBOX\n"), name);
1224                 else
1225                         new_item->stype = stype;
1226         } else
1227                 new_item->stype = stype;
1228
1229         return new_item;
1230 }
1231
1232 FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
1233                                const gchar *name)
1234 {
1235         gchar *dirpath, *imap_path;
1236         IMAPSession *session;
1237         IMAPNameSpace *namespace;
1238         FolderItem *new_item;
1239         gchar *new_name;
1240         const gchar *p;
1241         gint ok;
1242
1243         g_return_val_if_fail(folder != NULL, NULL);
1244         g_return_val_if_fail(folder->account != NULL, NULL);
1245         g_return_val_if_fail(parent != NULL, NULL);
1246         g_return_val_if_fail(name != NULL, NULL);
1247
1248         session = imap_session_get(folder);
1249         if (!session) return NULL;
1250
1251         if (parent->path)
1252                 dirpath = g_strconcat(parent->path, "/", name, NULL);
1253         else if ((p = strchr(name, '/')) != NULL && *(p + 1) != '\0')
1254                 dirpath = g_strdup(name);
1255         else if (folder->account->imap_dir && *folder->account->imap_dir) {
1256                 gchar *imap_dir;
1257
1258                 Xstrdup_a(imap_dir, folder->account->imap_dir, return NULL);
1259                 strtailchomp(imap_dir, '/');
1260                 dirpath = g_strconcat(imap_dir, "/", name, NULL);
1261         } else
1262                 dirpath = g_strdup(name);
1263
1264         strtailchomp(dirpath, '/');
1265         imap_path = imap_locale_to_modified_utf7(dirpath);
1266         Xstrdup_a(new_name, name, {g_free(dirpath); return NULL;});
1267         strtailchomp(new_name, '/');
1268         namespace = imap_find_namespace(IMAP_FOLDER(folder), imap_path);
1269         if (namespace && namespace->separator) {
1270                 imap_path_separator_subst(imap_path, namespace->separator);
1271                 subst_char(new_name, '/', namespace->separator);
1272         }
1273
1274         if (strcmp(name, "INBOX") != 0) {
1275                 GPtrArray *argbuf;
1276                 gint i;
1277                 gboolean exist = FALSE;
1278
1279                 argbuf = g_ptr_array_new();
1280                 ok = imap_cmd_list(SESSION(session)->sock, NULL, imap_path,
1281                                    argbuf);
1282                 statusbar_pop_all();
1283                 if (ok != IMAP_SUCCESS) {
1284                         log_warning(_("can't create mailbox: LIST failed\n"));
1285                         g_free(imap_path);
1286                         g_free(dirpath);
1287                         g_ptr_array_free(argbuf, TRUE);
1288                         return NULL;
1289                 }
1290
1291                 for (i = 0; i < argbuf->len; i++) {
1292                         gchar *str;
1293                         str = g_ptr_array_index(argbuf, i);
1294                         if (!strncmp(str, "LIST ", 5)) {
1295                                 exist = TRUE;
1296                                 break;
1297                         }
1298                 }
1299                 g_ptr_array_free(argbuf, TRUE);
1300
1301                 if (!exist) {
1302                         ok = imap_cmd_create(SESSION(session)->sock, imap_path);
1303                         statusbar_pop_all();
1304                         if (ok != IMAP_SUCCESS) {
1305                                 log_warning(_("can't create mailbox\n"));
1306                                 g_free(imap_path);
1307                                 g_free(dirpath);
1308                                 return NULL;
1309                         }
1310                 }
1311         }
1312
1313         new_item = folder_item_new(new_name, dirpath);
1314         folder_item_append(parent, new_item);
1315         g_free(imap_path);
1316         g_free(dirpath);
1317
1318         dirpath = folder_item_get_path(new_item);
1319         if (!is_dir_exist(dirpath))
1320                 make_dir_hier(dirpath);
1321         g_free(dirpath);
1322
1323         return new_item;
1324 }
1325
1326 gint imap_rename_folder(Folder *folder, FolderItem *item, const gchar *name)
1327 {
1328         gchar *dirpath;
1329         gchar *newpath;
1330         gchar *real_oldpath;
1331         gchar *real_newpath;
1332         GNode *node;
1333         gchar *paths[2];
1334         gchar *old_cache_dir;
1335         gchar *new_cache_dir;
1336         IMAPSession *session;
1337         IMAPNameSpace *namespace;
1338         gint ok;
1339         gint exists, recent, unseen;
1340         guint32 uid_validity;
1341
1342         g_return_val_if_fail(folder != NULL, -1);
1343         g_return_val_if_fail(item != NULL, -1);
1344         g_return_val_if_fail(item->path != NULL, -1);
1345         g_return_val_if_fail(name != NULL, -1);
1346
1347         session = imap_session_get(folder);
1348         if (!session) return -1;
1349
1350         real_oldpath = imap_get_real_path(IMAP_FOLDER(folder), item->path);
1351
1352         ok = imap_cmd_examine(SESSION(session)->sock, "INBOX",
1353                               &exists, &recent, &unseen, &uid_validity);
1354         statusbar_pop_all();
1355         if (ok != IMAP_SUCCESS) {
1356                 g_free(real_oldpath);
1357                 return -1;
1358         }
1359
1360         namespace = imap_find_namespace(IMAP_FOLDER(folder), item->path);
1361         if (strchr(item->path, G_DIR_SEPARATOR)) {
1362                 dirpath = g_dirname(item->path);
1363                 newpath = g_strconcat(dirpath, G_DIR_SEPARATOR_S, name, NULL);
1364                 g_free(dirpath);
1365         } else
1366                 newpath = g_strdup(name);
1367
1368         real_newpath = imap_locale_to_modified_utf7(newpath);
1369         if (namespace && namespace->separator)
1370                 imap_path_separator_subst(real_newpath, namespace->separator);
1371
1372         ok = imap_cmd_rename(SESSION(session)->sock, real_oldpath, real_newpath);
1373         statusbar_pop_all();
1374         if (ok != IMAP_SUCCESS) {
1375                 log_warning(_("can't rename mailbox: %s to %s\n"),
1376                             real_oldpath, real_newpath);
1377                 g_free(real_oldpath);
1378                 g_free(newpath);
1379                 g_free(real_newpath);
1380                 return -1;
1381         }
1382
1383         g_free(item->name);
1384         item->name = g_strdup(name);
1385
1386         old_cache_dir = folder_item_get_path(item);
1387
1388         node = g_node_find(item->folder->node, G_PRE_ORDER, G_TRAVERSE_ALL,
1389                            item);
1390         paths[0] = g_strdup(item->path);
1391         paths[1] = newpath;
1392         g_node_traverse(node, G_PRE_ORDER, G_TRAVERSE_ALL, -1,
1393                         imap_rename_folder_func, paths);
1394
1395         if (is_dir_exist(old_cache_dir)) {
1396                 new_cache_dir = folder_item_get_path(item);
1397                 if (rename(old_cache_dir, new_cache_dir) < 0) {
1398                         FILE_OP_ERROR(old_cache_dir, "rename");
1399                 }
1400                 g_free(new_cache_dir);
1401         }
1402
1403         g_free(old_cache_dir);
1404         g_free(paths[0]);
1405         g_free(newpath);
1406         g_free(real_oldpath);
1407         g_free(real_newpath);
1408
1409         return 0;
1410 }
1411
1412 gint imap_remove_folder(Folder *folder, FolderItem *item)
1413 {
1414         gint ok;
1415         IMAPSession *session;
1416         gchar *path;
1417         gchar *cache_dir;
1418         gint exists, recent, unseen;
1419         guint32 uid_validity;
1420
1421         g_return_val_if_fail(folder != NULL, -1);
1422         g_return_val_if_fail(item != NULL, -1);
1423         g_return_val_if_fail(item->path != NULL, -1);
1424
1425         session = imap_session_get(folder);
1426         if (!session) return -1;
1427
1428         path = imap_get_real_path(IMAP_FOLDER(folder), item->path);
1429
1430         ok = imap_cmd_examine(SESSION(session)->sock, "INBOX",
1431                               &exists, &recent, &unseen, &uid_validity);
1432         statusbar_pop_all();
1433         if (ok != IMAP_SUCCESS) {
1434                 g_free(path);
1435                 return -1;
1436         }
1437
1438         ok = imap_cmd_delete(SESSION(session)->sock, path);
1439         statusbar_pop_all();
1440         if (ok != IMAP_SUCCESS) {
1441                 log_warning(_("can't delete mailbox\n"));
1442                 g_free(path);
1443                 return -1;
1444         }
1445
1446         g_free(path);
1447         cache_dir = folder_item_get_path(item);
1448         if (is_dir_exist(cache_dir) && remove_dir_recursive(cache_dir) < 0)
1449                 g_warning("can't remove directory '%s'\n", cache_dir);
1450         g_free(cache_dir);
1451         folder_item_remove(item);
1452
1453         return 0;
1454 }
1455
1456 static GSList *imap_get_uncached_messages(IMAPSession *session,
1457                                           FolderItem *item,
1458                                           guint32 first_uid, guint32 last_uid)
1459 {
1460         gchar *tmp;
1461         GSList *newlist = NULL;
1462         GSList *llast = NULL;
1463         GString *str;
1464         MsgInfo *msginfo;
1465
1466         g_return_val_if_fail(session != NULL, NULL);
1467         g_return_val_if_fail(item != NULL, NULL);
1468         g_return_val_if_fail(item->folder != NULL, NULL);
1469         g_return_val_if_fail(item->folder->type == F_IMAP, NULL);
1470         g_return_val_if_fail(first_uid <= last_uid, NULL);
1471
1472         if (imap_cmd_envelope(SESSION(session)->sock, first_uid, last_uid)
1473             != IMAP_SUCCESS) {
1474                 log_warning(_("can't get envelope\n"));
1475                 return NULL;
1476         }
1477
1478         str = g_string_new(NULL);
1479
1480         for (;;) {
1481                 if ((tmp = sock_getline(SESSION(session)->sock)) == NULL) {
1482                         log_warning(_("error occurred while getting envelope.\n"));
1483                         g_string_free(str, TRUE);
1484                         return newlist;
1485                 }
1486                 strretchomp(tmp);
1487                 log_print("IMAP4< %s\n", tmp);
1488                 if (tmp[0] != '*' || tmp[1] != ' ') {
1489                         g_free(tmp);
1490                         break;
1491                 }
1492                 if (strstr(tmp, "FETCH") == NULL) {
1493                         g_free(tmp);
1494                         continue;
1495                 }
1496                 g_string_assign(str, tmp);
1497                 g_free(tmp);
1498
1499                 msginfo = imap_parse_envelope(SESSION(session)->sock, str);
1500                 if (!msginfo) {
1501                         log_warning(_("can't parse envelope: %s\n"), str->str);
1502                         continue;
1503                 }
1504                 if (item->stype == F_QUEUE) {
1505                         MSG_SET_TMP_FLAGS(msginfo->flags, MSG_QUEUED);
1506                 } else if (item->stype == F_DRAFT) {
1507                         MSG_SET_TMP_FLAGS(msginfo->flags, MSG_DRAFT);
1508                 }
1509
1510                 msginfo->folder = item;
1511
1512                 if (!newlist)
1513                         llast = newlist = g_slist_append(newlist, msginfo);
1514                 else {
1515                         llast = g_slist_append(llast, msginfo);
1516                         llast = llast->next;
1517                 }
1518         }
1519
1520         g_string_free(str, TRUE);
1521
1522         return newlist;
1523 }
1524
1525 static GSList *imap_delete_cached_messages(GSList *mlist, FolderItem *item,
1526                                            guint32 first_uid, guint32 last_uid)
1527 {
1528         GSList *cur, *next;
1529         MsgInfo *msginfo;
1530         gchar *dir;
1531
1532         g_return_val_if_fail(item != NULL, mlist);
1533         g_return_val_if_fail(item->folder != NULL, mlist);
1534         g_return_val_if_fail(item->folder->type == F_IMAP, mlist);
1535
1536         debug_print(_("Deleting cached messages %d - %d ... "),
1537                     first_uid, last_uid);
1538
1539         dir = folder_item_get_path(item);
1540         remove_numbered_files(dir, first_uid, last_uid);
1541         g_free(dir);
1542
1543         for (cur = mlist; cur != NULL; ) {
1544                 next = cur->next;
1545
1546                 msginfo = (MsgInfo *)cur->data;
1547                 if (msginfo != NULL && first_uid <= msginfo->msgnum &&
1548                     msginfo->msgnum <= last_uid) {
1549                         procmsg_msginfo_free(msginfo);
1550                         mlist = g_slist_remove(mlist, msginfo);
1551                 }
1552
1553                 cur = next;
1554         }
1555
1556         debug_print(_("done.\n"));
1557
1558         return mlist;
1559 }
1560
1561 static void imap_delete_all_cached_messages(FolderItem *item)
1562 {
1563         gchar *dir;
1564
1565         g_return_if_fail(item != NULL);
1566         g_return_if_fail(item->folder != NULL);
1567         g_return_if_fail(item->folder->type == F_IMAP);
1568
1569         debug_print(_("Deleting all cached messages... "));
1570
1571         dir = folder_item_get_path(item);
1572         remove_all_numbered_files(dir);
1573         g_free(dir);
1574
1575         debug_print(_("done.\n"));
1576 }
1577
1578
1579 static SockInfo *imap_open_tunnel(const gchar *server,
1580                            const gchar *tunnelcmd)
1581 {
1582         SockInfo *sock;
1583
1584         if ((sock = sock_connect_cmd(server, tunnelcmd)) == NULL)
1585                 log_warning(_("Can't establish IMAP4 session with: %s\n"),
1586                             server);
1587                 return NULL;
1588
1589         return imap_init_sock(sock);
1590 }
1591
1592
1593 #if USE_SSL
1594 static SockInfo *imap_open(const gchar *server, gushort port,
1595                            gboolean use_ssl)
1596 #else
1597 static SockInfo *imap_open(const gchar *server, gushort port)
1598 #endif
1599 {
1600         SockInfo *sock;
1601
1602         if ((sock = sock_connect(server, port)) == NULL) {
1603                 log_warning(_("Can't connect to IMAP4 server: %s:%d\n"),
1604                             server, port);
1605                 return NULL;
1606         }
1607
1608 #if USE_SSL
1609         if (use_ssl && !ssl_init_socket(sock)) {
1610                 log_warning(_("Can't establish IMAP4 session with: %s:%d\n"),
1611                             server, port);
1612                 sock_close(sock);
1613                 return NULL;
1614         }
1615 #endif
1616
1617         return imap_init_sock(sock);
1618 }
1619
1620
1621 static SockInfo *imap_init_sock(SockInfo *sock)
1622 {
1623         imap_cmd_count = 0;
1624
1625         if (imap_cmd_noop(sock) != IMAP_SUCCESS) {
1626                 log_warning(_("Can't establish IMAP4 session\n"));
1627                 sock_close(sock);
1628                 return NULL;
1629         }
1630
1631         return sock;
1632 }
1633
1634 #define THROW goto catch
1635
1636 static void imap_parse_namespace(IMAPSession *session, IMAPFolder *folder)
1637 {
1638         gchar *ns_str;
1639         gchar *name;
1640         gchar *separator;
1641         gchar *p;
1642         IMAPNameSpace *namespace;
1643         GList *ns_list = NULL;
1644
1645         g_return_if_fail(session != NULL);
1646         g_return_if_fail(folder != NULL);
1647
1648         if (folder->namespace != NULL) return;
1649
1650         if (imap_cmd_namespace(SESSION(session)->sock, &ns_str)
1651             != IMAP_SUCCESS) {
1652                 log_warning(_("can't get namespace\n"));
1653                 return;
1654         }
1655
1656         /* get the first element */
1657         extract_one_parenthesis_with_skip_quote(ns_str, '"', '(', ')');
1658         g_strstrip(ns_str);
1659         p = ns_str;
1660
1661         while (*p != '\0') {
1662                 /* parse ("#foo" "/") */
1663
1664                 while (*p && *p != '(') p++;
1665                 if (*p == '\0') THROW;
1666                 p++;
1667
1668                 while (*p && *p != '"') p++;
1669                 if (*p == '\0') THROW;
1670                 p++;
1671                 name = p;
1672
1673                 while (*p && *p != '"') p++;
1674                 if (*p == '\0') THROW;
1675                 *p = '\0';
1676                 p++;
1677
1678                 while (*p && isspace(*p)) p++;
1679                 if (*p == '\0') THROW;
1680                 if (strncmp(p, "NIL", 3) == 0)
1681                         separator = NULL;
1682                 else if (*p == '"') {
1683                         p++;
1684                         separator = p;
1685                         while (*p && *p != '"') p++;
1686                         if (*p == '\0') THROW;
1687                         *p = '\0';
1688                         p++;
1689                 } else THROW;
1690
1691                 while (*p && *p != ')') p++;
1692                 if (*p == '\0') THROW;
1693                 p++;
1694
1695                 namespace = g_new(IMAPNameSpace, 1);
1696                 namespace->name = g_strdup(name);
1697                 namespace->separator = separator ? separator[0] : '\0';
1698                 ns_list = g_list_append(ns_list, namespace);
1699                 IMAP_FOLDER(folder)->namespace = ns_list;
1700         }
1701
1702 catch:
1703         g_free(ns_str);
1704         return;
1705 }
1706
1707 #undef THROW
1708
1709 static IMAPNameSpace *imap_find_namespace(IMAPFolder *folder,
1710                                           const gchar *path)
1711 {
1712         IMAPNameSpace *namespace = NULL;
1713         GList *ns_list;
1714         gchar *name;
1715
1716         g_return_val_if_fail(folder != NULL, NULL);
1717         g_return_val_if_fail(path != NULL, NULL);
1718
1719         ns_list = folder->namespace;
1720
1721         for (; ns_list != NULL; ns_list = ns_list->next) {
1722                 IMAPNameSpace *tmp_ns = ns_list->data;
1723
1724                 Xstrdup_a(name, tmp_ns->name, return namespace);
1725                 if (tmp_ns->separator && tmp_ns->separator != '/')
1726                         subst_char(name, tmp_ns->separator, '/');
1727                 if (strncmp(path, name, strlen(name)) == 0)
1728                         namespace = tmp_ns;
1729         }
1730
1731         return namespace;
1732 }
1733
1734 static gchar *imap_get_real_path(IMAPFolder *folder, const gchar *path)
1735 {
1736         gchar *real_path;
1737         IMAPNameSpace *namespace;
1738
1739         g_return_val_if_fail(folder != NULL, NULL);
1740         g_return_val_if_fail(path != NULL, NULL);
1741
1742         real_path = imap_locale_to_modified_utf7(path);
1743         namespace = imap_find_namespace(folder, path);
1744         if (namespace && namespace->separator)
1745                 imap_path_separator_subst(real_path, namespace->separator);
1746
1747         return real_path;
1748 }
1749
1750 static gchar *imap_parse_atom(SockInfo *sock, gchar *src,
1751                               gchar *dest, gint dest_len, GString *str)
1752 {
1753         gchar *cur_pos = src;
1754         gchar *nextline;
1755
1756         g_return_val_if_fail(str != NULL, cur_pos);
1757
1758         /* read the next line if the current response buffer is empty */
1759         while (isspace(*cur_pos)) cur_pos++;
1760         while (*cur_pos == '\0') {
1761                 if ((nextline = sock_getline(sock)) == NULL)
1762                         return cur_pos;
1763                 g_string_assign(str, nextline);
1764                 cur_pos = str->str;
1765                 strretchomp(nextline);
1766                 log_print("IMAP4< %s\n", nextline);
1767                 g_free(nextline);
1768
1769                 while (isspace(*cur_pos)) cur_pos++;
1770         }
1771
1772         if (!strncmp(cur_pos, "NIL", 3)) {
1773                 *dest = '\0';
1774                 cur_pos += 3;
1775         } else if (*cur_pos == '\"') {
1776                 gchar *p;
1777
1778                 p = get_quoted(cur_pos, '\"', dest, dest_len);
1779                 cur_pos = p ? p : cur_pos + 2;
1780         } else if (*cur_pos == '{') {
1781                 gchar buf[32];
1782                 gint len;
1783                 gint line_len = 0;
1784
1785                 cur_pos = strchr_cpy(cur_pos + 1, '}', buf, sizeof(buf));
1786                 len = atoi(buf);
1787
1788                 g_string_truncate(str, 0);
1789                 cur_pos = str->str;
1790
1791                 do {
1792                         if ((nextline = sock_getline(sock)) == NULL)
1793                                 return cur_pos;
1794                         line_len += strlen(nextline);
1795                         g_string_append(str, nextline);
1796                         cur_pos = str->str;
1797                         strretchomp(nextline);
1798                         log_print("IMAP4< %s\n", nextline);
1799                         g_free(nextline);
1800                 } while (line_len < len);
1801
1802                 memcpy(dest, cur_pos, MIN(len, dest_len - 1));
1803                 dest[MIN(len, dest_len - 1)] = '\0';
1804                 cur_pos += len;
1805         }
1806
1807         return cur_pos;
1808 }
1809
1810 static gchar *imap_parse_one_address(SockInfo *sock, gchar *start,
1811                                      gchar *out_from_str,
1812                                      gchar *out_fromname_str,
1813                                      GString *str)
1814 {
1815         gchar buf[IMAPBUFSIZE];
1816         gchar *userid;
1817         gchar *domain;
1818         gchar *cur_pos = start;
1819
1820         cur_pos = imap_parse_atom(sock, cur_pos, buf, sizeof(buf), str);
1821         conv_unmime_header(out_fromname_str, IMAPBUFSIZE, buf, NULL);
1822
1823         cur_pos = imap_parse_atom(sock, cur_pos, buf, sizeof(buf), str);
1824
1825         cur_pos = imap_parse_atom(sock, cur_pos, buf, sizeof(buf), str);
1826         Xstrdup_a(userid, buf, return cur_pos + 1);
1827
1828         cur_pos = imap_parse_atom(sock, cur_pos, buf, sizeof(buf), str);
1829         Xstrdup_a(domain, buf, return cur_pos + 1);
1830
1831         if (out_fromname_str[0] != '\0') {
1832                 g_snprintf(out_from_str, IMAPBUFSIZE, "\"%s\" <%s@%s>",
1833                            out_fromname_str, userid, domain);
1834         } else {
1835                 g_snprintf(out_from_str, IMAPBUFSIZE, "%s@%s",
1836                            userid, domain);
1837                 strcpy(out_fromname_str, out_from_str);
1838         }
1839
1840         while (*cur_pos == ' ') cur_pos++;
1841         g_return_val_if_fail(*cur_pos == ')', NULL);
1842
1843         return cur_pos + 1;
1844 }
1845
1846 static gchar *imap_parse_address(SockInfo *sock, gchar *start,
1847                                  gchar **out_from_str,
1848                                  gchar **out_fromname_str,
1849                                  GString *str)
1850 {
1851         gchar buf[IMAPBUFSIZE];
1852         gchar name_buf[IMAPBUFSIZE];
1853         gchar *cur_pos = start;
1854         GString *addr_str;
1855
1856         if (out_from_str)     *out_from_str     = NULL;
1857         if (out_fromname_str) *out_fromname_str = NULL;
1858         buf[0] = name_buf[0] = '\0';
1859
1860         if (!strncmp(cur_pos, "NIL", 3)) {
1861                 if (out_from_str)     *out_from_str     = g_strdup("");
1862                 if (out_fromname_str) *out_fromname_str = g_strdup("");
1863                 return cur_pos + 3;
1864         }
1865
1866         g_return_val_if_fail(*cur_pos == '(', NULL);
1867         cur_pos++;
1868
1869         addr_str = g_string_new(NULL);
1870
1871         for (;;) {
1872                 gchar ch = *cur_pos++;
1873                 if (ch == ')') break;
1874                 if (ch == '(') {
1875                         cur_pos = imap_parse_one_address
1876                                 (sock, cur_pos, buf, name_buf, str);
1877                         if (!cur_pos) {
1878                                 g_string_free(addr_str, TRUE);
1879                                 return NULL;
1880                         }
1881                         if (addr_str->str[0] != '\0')
1882                                 g_string_append(addr_str, ", ");
1883                         g_string_append(addr_str, buf);
1884                 }
1885         }
1886
1887         if (out_from_str)     *out_from_str     = g_strdup(addr_str->str);
1888         if (out_fromname_str) *out_fromname_str = g_strdup(name_buf);
1889
1890         g_string_free(addr_str, TRUE);
1891
1892         return cur_pos;
1893 }
1894
1895 static MsgFlags imap_parse_flags(const gchar *flag_str)  
1896 {
1897         const gchar *p = flag_str;
1898         MsgFlags flags;
1899
1900         flags.perm_flags = MSG_UNREAD;
1901         flags.tmp_flags  = MSG_IMAP;
1902
1903         while ((p = strchr(p, '\\')) != NULL) {
1904                 p++;
1905
1906                 if (g_strncasecmp(p, "Recent", 6) == 0 && MSG_IS_UNREAD(flags)) {
1907                         MSG_SET_PERM_FLAGS(flags, MSG_NEW);
1908                 } else if (g_strncasecmp(p, "Seen", 4) == 0) {
1909                         MSG_UNSET_PERM_FLAGS(flags, MSG_NEW|MSG_UNREAD);
1910                 } else if (g_strncasecmp(p, "Deleted", 7) == 0) {
1911                         MSG_SET_PERM_FLAGS(flags, MSG_DELETED);
1912                 } else if (g_strncasecmp(p, "Flagged", 7) == 0) {
1913                         MSG_SET_PERM_FLAGS(flags, MSG_MARKED);
1914                 } else if (g_strncasecmp(p, "Answered", 8) == 0) {
1915                         MSG_SET_PERM_FLAGS(flags, MSG_REPLIED);
1916                 }
1917         }
1918
1919         return flags;
1920 }
1921
1922 static MsgInfo *imap_parse_envelope(SockInfo *sock, GString *line_str)
1923 {
1924         MsgInfo *msginfo;
1925         gchar buf[IMAPBUFSIZE];
1926         gchar tmp[IMAPBUFSIZE];
1927         gchar *cur_pos;
1928         gint msgnum;
1929         guint32 uid = 0;
1930         size_t size = 0;
1931         gchar *date = NULL;
1932         time_t date_t = 0;
1933         gchar *subject = NULL;
1934         gchar *tmp_from;
1935         gchar *tmp_fromname;
1936         gchar *from = NULL;
1937         gchar *fromname = NULL;
1938         gchar *tmp_to;
1939         gchar *to = NULL;
1940         gchar *inreplyto = NULL;
1941         gchar *msgid = NULL;
1942         MsgFlags flags = {0, 0};
1943
1944         g_return_val_if_fail(line_str != NULL, NULL);
1945         g_return_val_if_fail(line_str->str[0] == '*' &&
1946                              line_str->str[1] == ' ', NULL);
1947
1948         cur_pos = line_str->str + 2;
1949
1950 #define PARSE_ONE_ELEMENT(ch) \
1951 { \
1952         cur_pos = strchr_cpy(cur_pos, ch, buf, sizeof(buf)); \
1953         g_return_val_if_fail(cur_pos != NULL, NULL); \
1954 }
1955
1956         PARSE_ONE_ELEMENT(' ');
1957         msgnum = atoi(buf);
1958
1959         PARSE_ONE_ELEMENT(' ');
1960         g_return_val_if_fail(!strcmp(buf, "FETCH"), NULL);
1961
1962         g_return_val_if_fail(*cur_pos == '(', NULL);
1963         cur_pos++;
1964
1965         while (*cur_pos != '\0' && *cur_pos != ')') {
1966                 while (*cur_pos == ' ') cur_pos++;
1967
1968                 if (!strncmp(cur_pos, "UID ", 4)) {
1969                         cur_pos += 4;
1970                         uid = strtoul(cur_pos, &cur_pos, 10);
1971                 } else if (!strncmp(cur_pos, "FLAGS ", 6)) {
1972                         cur_pos += 6;
1973                         g_return_val_if_fail(*cur_pos == '(', NULL);
1974                         cur_pos++;
1975                         PARSE_ONE_ELEMENT(')');
1976                         flags = imap_parse_flags(buf);
1977                 } else if (!strncmp(cur_pos, "RFC822.SIZE ", 12)) {
1978                         cur_pos += 12;
1979                         size = strtol(cur_pos, &cur_pos, 10);
1980                 } else if (!strncmp(cur_pos, "ENVELOPE ", 9)) {
1981                         cur_pos += 9;
1982                         g_return_val_if_fail(*cur_pos == '(', NULL);
1983                         cur_pos = imap_parse_atom
1984                                 (sock, cur_pos + 1, buf, sizeof(buf), line_str);
1985                         if (buf[0] != '\0') {
1986                                 Xstrdup_a(date, buf, return NULL);
1987                                 date_t = procheader_date_parse(NULL, date, 0);
1988                         }
1989
1990                         cur_pos = imap_parse_atom
1991                                 (sock, cur_pos, buf, sizeof(buf), line_str);
1992                         if (buf[0] != '\0') {
1993                                 conv_unmime_header(tmp, sizeof(tmp), buf, NULL);
1994                                 Xstrdup_a(subject, tmp, return NULL);
1995                         }
1996
1997                         g_return_val_if_fail(*cur_pos == ' ', NULL);
1998                         cur_pos = imap_parse_address(sock, cur_pos + 1,
1999                                                      &tmp_from, &tmp_fromname,
2000                                                      line_str);
2001                         g_return_val_if_fail(cur_pos != NULL, NULL);
2002                         if (tmp_from && *tmp_from != '\0')
2003                                 Xstrdup_a(from, tmp_from,
2004                                           {g_free(tmp_from);
2005                                            g_free(tmp_fromname);
2006                                            return NULL;});
2007                         if (tmp_fromname && *tmp_fromname != '\0')
2008                                 Xstrdup_a(fromname, tmp_fromname,
2009                                           {g_free(tmp_from);
2010                                            g_free(tmp_fromname);
2011                                            return NULL;});
2012                         g_free(tmp_from);
2013                         g_free(tmp_fromname);
2014
2015 #define SKIP_ONE_ELEMENT() \
2016 { \
2017         g_return_val_if_fail(*cur_pos == ' ', NULL); \
2018         cur_pos = imap_parse_address(sock, cur_pos + 1, NULL, NULL, \
2019                                      line_str); \
2020         g_return_val_if_fail(cur_pos != NULL, NULL); \
2021 }
2022
2023                         /* skip sender and reply-to */
2024                         SKIP_ONE_ELEMENT();
2025                         SKIP_ONE_ELEMENT();
2026
2027                         g_return_val_if_fail(*cur_pos == ' ', NULL);
2028                         cur_pos = imap_parse_address(sock, cur_pos + 1,
2029                                                      &tmp_to, NULL, line_str);
2030                         g_return_val_if_fail(cur_pos != NULL, NULL);
2031                         Xstrdup_a(to, tmp_to, {g_free(tmp_to); return NULL;});
2032                         g_free(tmp_to);
2033
2034                         /* skip Cc and Bcc */
2035                         SKIP_ONE_ELEMENT();
2036                         SKIP_ONE_ELEMENT();
2037
2038 #undef SKIP_ONE_ELEMENT
2039
2040                         g_return_val_if_fail(*cur_pos == ' ', NULL);
2041                         cur_pos = imap_parse_atom
2042                                 (sock, cur_pos, buf, sizeof(buf), line_str);
2043                         g_return_val_if_fail(cur_pos != NULL, NULL);
2044                         if (buf[0] != '\0') {
2045                                 eliminate_parenthesis(buf, '(', ')');
2046                                 extract_parenthesis(buf, '<', '>');
2047                                 remove_space(buf);
2048                                 Xstrdup_a(inreplyto, buf, return NULL);
2049                         }
2050
2051                         g_return_val_if_fail(*cur_pos == ' ', NULL);
2052                         cur_pos = imap_parse_atom
2053                                 (sock, cur_pos, buf, sizeof(buf), line_str);
2054                         g_return_val_if_fail(cur_pos != NULL, NULL);
2055                         if (buf[0] != '\0') {
2056                                 extract_parenthesis(buf, '<', '>');
2057                                 remove_space(buf);
2058                                 Xstrdup_a(msgid, buf, return NULL);
2059                         }
2060
2061                         g_return_val_if_fail(*cur_pos == ')', NULL);
2062                         cur_pos++;
2063                 } else {
2064                         g_warning("invalid FETCH response: %s\n", cur_pos);
2065                         break;
2066                 }
2067         }
2068
2069         msginfo = g_new0(MsgInfo, 1);
2070         msginfo->msgnum = uid;
2071         msginfo->size = size;
2072         msginfo->date = g_strdup(date);
2073         msginfo->date_t = date_t;
2074         msginfo->subject = g_strdup(subject);
2075         msginfo->from = g_strdup(from);
2076         msginfo->fromname = g_strdup(fromname);
2077         msginfo->to = g_strdup(to);
2078         msginfo->inreplyto = g_strdup(inreplyto);
2079         msginfo->msgid = g_strdup(msgid);
2080         msginfo->flags = flags;
2081
2082         return msginfo;
2083 }
2084
2085 gint imap_msg_set_perm_flags(MsgInfo *msginfo, MsgPermFlags flags)
2086 {
2087         Folder *folder;
2088         IMAPSession *session;
2089         IMAPFlags iflags = 0;
2090         gint ok = IMAP_SUCCESS;
2091
2092         g_return_val_if_fail(msginfo != NULL, -1);
2093         g_return_val_if_fail(MSG_IS_IMAP(msginfo->flags), -1);
2094         g_return_val_if_fail(msginfo->folder != NULL, -1);
2095         g_return_val_if_fail(msginfo->folder->folder != NULL, -1);
2096
2097         folder = msginfo->folder->folder;
2098         g_return_val_if_fail(folder->type == F_IMAP, -1);
2099
2100         session = imap_session_get(folder);
2101         if (!session) return -1;
2102
2103         if (flags & MSG_MARKED)  iflags |= IMAP_FLAG_FLAGGED;
2104         if (flags & MSG_REPLIED) iflags |= IMAP_FLAG_ANSWERED;
2105         if (iflags) {
2106                 ok = imap_set_message_flags(session, msginfo->msgnum,
2107                                             msginfo->msgnum, iflags, TRUE);
2108                 if (ok != IMAP_SUCCESS) return ok;
2109         }
2110
2111         if (flags & MSG_UNREAD)
2112                 ok = imap_set_message_flags(session, msginfo->msgnum,
2113                                             msginfo->msgnum, IMAP_FLAG_SEEN,
2114                                             FALSE);
2115         return ok;
2116 }
2117
2118 gint imap_msg_unset_perm_flags(MsgInfo *msginfo, MsgPermFlags flags)
2119 {
2120         Folder *folder;
2121         IMAPSession *session;
2122         IMAPFlags iflags = 0;
2123         gint ok = IMAP_SUCCESS;
2124
2125         g_return_val_if_fail(msginfo != NULL, -1);
2126         g_return_val_if_fail(MSG_IS_IMAP(msginfo->flags), -1);
2127         g_return_val_if_fail(msginfo->folder != NULL, -1);
2128         g_return_val_if_fail(msginfo->folder->folder != NULL, -1);
2129
2130         folder = msginfo->folder->folder;
2131         g_return_val_if_fail(folder->type == F_IMAP, -1);
2132
2133         session = imap_session_get(folder);
2134         if (!session) return -1;
2135
2136         if (flags & MSG_MARKED)  iflags |= IMAP_FLAG_FLAGGED;
2137         if (flags & MSG_REPLIED) iflags |= IMAP_FLAG_ANSWERED;
2138         if (iflags) {
2139                 ok = imap_set_message_flags(session, msginfo->msgnum,
2140                                             msginfo->msgnum, iflags, FALSE);
2141                 if (ok != IMAP_SUCCESS) return ok;
2142         }
2143
2144         if (flags & MSG_UNREAD)
2145                 ok = imap_set_message_flags(session, msginfo->msgnum,
2146                                             msginfo->msgnum, IMAP_FLAG_SEEN,
2147                                             TRUE);
2148         return ok;
2149 }
2150
2151 static gint imap_set_message_flags(IMAPSession *session,
2152                                    guint32 first_uid,
2153                                    guint32 last_uid,
2154                                    IMAPFlags flags,
2155                                    gboolean is_set)
2156 {
2157         GString *buf;
2158         gint ok;
2159
2160         buf = g_string_new(is_set ? "+FLAGS (" : "-FLAGS (");
2161
2162         if (IMAP_IS_SEEN(flags))        g_string_append(buf, "\\Seen ");
2163         if (IMAP_IS_ANSWERED(flags))    g_string_append(buf, "\\Answered ");
2164         if (IMAP_IS_FLAGGED(flags))     g_string_append(buf, "\\Flagged ");
2165         if (IMAP_IS_DELETED(flags))     g_string_append(buf, "\\Deleted ");
2166         if (IMAP_IS_DRAFT(flags))       g_string_append(buf, "\\Draft");
2167
2168         if (buf->str[buf->len - 1] == ' ')
2169                 g_string_truncate(buf, buf->len - 1);
2170
2171         g_string_append_c(buf, ')');
2172
2173         ok = imap_cmd_store(SESSION(session)->sock, first_uid, last_uid,
2174                             buf->str);
2175         g_string_free(buf, TRUE);
2176
2177         return ok;
2178 }
2179
2180 static gint imap_select(IMAPSession *session, IMAPFolder *folder,
2181                         const gchar *path,
2182                         gint *exists, gint *recent, gint *unseen,
2183                         guint32 *uid_validity)
2184 {
2185         gchar *real_path;
2186         gint ok;
2187
2188         real_path = imap_get_real_path(folder, path);
2189         ok = imap_cmd_select(SESSION(session)->sock, real_path,
2190                              exists, recent, unseen, uid_validity);
2191         if (ok != IMAP_SUCCESS)
2192                 log_warning(_("can't select folder: %s\n"), real_path);
2193         g_free(real_path);
2194
2195         return ok;
2196 }
2197
2198 #define THROW(err) { ok = err; goto catch; }
2199
2200 static gint imap_get_uid(IMAPSession *session, gint msgnum, guint32 *uid)
2201 {
2202         gint ok;
2203         GPtrArray *argbuf;
2204         gchar *str;
2205         gint num;
2206
2207         *uid = 0;
2208         argbuf = g_ptr_array_new();
2209
2210         imap_cmd_gen_send(SESSION(session)->sock, "FETCH %d (UID)", msgnum);
2211         if ((ok = imap_cmd_ok(SESSION(session)->sock, argbuf)) != IMAP_SUCCESS)
2212                 THROW(ok);
2213
2214         str = search_array_contain_str(argbuf, "FETCH");
2215         if (!str) THROW(IMAP_ERROR);
2216
2217         if (sscanf(str, "%d FETCH (UID %d)", &num, uid) != 2 ||
2218             num != msgnum) {
2219                 g_warning("imap_get_uid(): invalid FETCH line.\n");
2220                 THROW(IMAP_ERROR);
2221         }
2222
2223 catch:
2224         ptr_array_free_strings(argbuf);
2225         g_ptr_array_free(argbuf, TRUE);
2226
2227         return ok;
2228 }
2229
2230 static gint imap_status(IMAPSession *session, IMAPFolder *folder,
2231                         const gchar *path,
2232                         gint *messages, gint *recent, gint *unseen,
2233                         guint32 *uid_validity)
2234 {
2235         gchar *real_path;
2236         gchar *real_path_;
2237         gint ok;
2238         GPtrArray *argbuf;
2239         gchar *str;
2240
2241         *messages = *recent = *unseen = *uid_validity = 0;
2242
2243         argbuf = g_ptr_array_new();
2244
2245         real_path = imap_get_real_path(folder, path);
2246         QUOTE_IF_REQUIRED(real_path_, real_path);
2247         imap_cmd_gen_send(SESSION(session)->sock, "STATUS %s "
2248                           "(MESSAGES RECENT UNSEEN UIDVALIDITY)", real_path_);
2249
2250         ok = imap_cmd_ok(SESSION(session)->sock, argbuf);
2251         if (ok != IMAP_SUCCESS) THROW(ok);
2252
2253         str = search_array_str(argbuf, "STATUS");
2254         if (!str) THROW(IMAP_ERROR);
2255
2256         str = strchr(str, '(');
2257         if (!str) THROW(IMAP_ERROR);
2258         str++;
2259         while (*str != '\0' && *str != ')') {
2260                 while (*str == ' ') str++;
2261
2262                 if (!strncmp(str, "MESSAGES ", 9)) {
2263                         str += 9;
2264                         *messages = strtol(str, &str, 10);
2265                 } else if (!strncmp(str, "RECENT ", 7)) {
2266                         str += 7;
2267                         *recent = strtol(str, &str, 10);
2268                 } else if (!strncmp(str, "UNSEEN ", 7)) {
2269                         str += 7;
2270                         *unseen = strtol(str, &str, 10);
2271                 } else if (!strncmp(str, "UIDVALIDITY ", 12)) {
2272                         str += 12;
2273                         *uid_validity = strtoul(str, &str, 10);
2274                 } else {
2275                         g_warning("invalid STATUS response: %s\n", str);
2276                         break;
2277                 }
2278         }
2279
2280 catch:
2281         g_free(real_path);
2282         ptr_array_free_strings(argbuf);
2283         g_ptr_array_free(argbuf, TRUE);
2284
2285         return ok;
2286 }
2287
2288 #undef THROW
2289
2290
2291 /* low-level IMAP4rev1 commands */
2292
2293 static gint imap_cmd_login(SockInfo *sock,
2294                            const gchar *user, const gchar *pass)
2295 {
2296         gchar *user_, *pass_;
2297         gint ok;
2298
2299         QUOTE_IF_REQUIRED(user_, user);
2300         QUOTE_IF_REQUIRED(pass_, pass);
2301         imap_cmd_gen_send(sock, "LOGIN %s %s", user_, pass_);
2302
2303         ok = imap_cmd_ok(sock, NULL);
2304         if (ok != IMAP_SUCCESS)
2305                 log_warning(_("IMAP4 login failed.\n"));
2306
2307         return ok;
2308 }
2309
2310 static gint imap_cmd_logout(SockInfo *sock)
2311 {
2312         imap_cmd_gen_send(sock, "LOGOUT");
2313         return imap_cmd_ok(sock, NULL);
2314 }
2315
2316 /* Send a NOOP, and examine the server's response to see whether this
2317  * connection is pre-authenticated or not. */
2318 static gint imap_greeting(SockInfo *sock, gboolean *is_preauth)
2319 {
2320         GPtrArray *argbuf;
2321         gint r;
2322
2323         imap_cmd_gen_send(sock, "NOOP");
2324         argbuf = g_ptr_array_new(); /* will hold messages sent back */
2325         r = imap_cmd_ok(sock, argbuf);
2326         *is_preauth = search_array_starts(argbuf, "PREAUTH") != NULL;
2327         
2328         return r;
2329 }
2330
2331 static gint imap_cmd_noop(SockInfo *sock)
2332 {
2333         imap_cmd_gen_send(sock, "NOOP");
2334         return imap_cmd_ok(sock, NULL);
2335 }
2336
2337 #define THROW(err) { ok = err; goto catch; }
2338
2339 static gint imap_cmd_namespace(SockInfo *sock, gchar **ns_str)
2340 {
2341         gint ok;
2342         GPtrArray *argbuf;
2343         gchar *str;
2344
2345         argbuf = g_ptr_array_new();
2346
2347         imap_cmd_gen_send(sock, "NAMESPACE");
2348         if ((ok = imap_cmd_ok(sock, argbuf)) != IMAP_SUCCESS) THROW(ok);
2349
2350         str = search_array_str(argbuf, "NAMESPACE");
2351         if (!str) THROW(IMAP_ERROR);
2352
2353         *ns_str = g_strdup(str);
2354
2355 catch:
2356         ptr_array_free_strings(argbuf);
2357         g_ptr_array_free(argbuf, TRUE);
2358
2359         return ok;
2360 }
2361
2362 #undef THROW
2363
2364 static gint imap_cmd_list(SockInfo *sock, const gchar *ref,
2365                           const gchar *mailbox, GPtrArray *argbuf)
2366 {
2367         gchar *ref_, *mailbox_;
2368
2369         if (!ref) ref = "\"\"";
2370         if (!mailbox) mailbox = "\"\"";
2371
2372         QUOTE_IF_REQUIRED(ref_, ref);
2373         QUOTE_IF_REQUIRED(mailbox_, mailbox);
2374         imap_cmd_gen_send(sock, "LIST %s %s", ref_, mailbox_);
2375
2376         return imap_cmd_ok(sock, argbuf);
2377 }
2378
2379 #define THROW goto catch
2380
2381 static gint imap_cmd_do_select(SockInfo *sock, const gchar *folder,
2382                                gboolean examine,
2383                                gint *exists, gint *recent, gint *unseen,
2384                                guint32 *uid_validity)
2385 {
2386         gint ok;
2387         gchar *resp_str;
2388         GPtrArray *argbuf;
2389         gchar *select_cmd;
2390         gchar *folder_;
2391
2392         *exists = *recent = *unseen = *uid_validity = 0;
2393         argbuf = g_ptr_array_new();
2394
2395         if (examine)
2396                 select_cmd = "EXAMINE";
2397         else
2398                 select_cmd = "SELECT";
2399
2400         QUOTE_IF_REQUIRED(folder_, folder);
2401         imap_cmd_gen_send(sock, "%s %s", select_cmd, folder_);
2402
2403         if ((ok = imap_cmd_ok(sock, argbuf)) != IMAP_SUCCESS) THROW;
2404
2405         resp_str = search_array_contain_str(argbuf, "EXISTS");
2406         if (resp_str) {
2407                 if (sscanf(resp_str,"%d EXISTS", exists) != 1) {
2408                         g_warning("imap_cmd_select(): invalid EXISTS line.\n");
2409                         THROW;
2410                 }
2411         }
2412
2413         resp_str = search_array_contain_str(argbuf, "RECENT");
2414         if (resp_str) {
2415                 if (sscanf(resp_str, "%d RECENT", recent) != 1) {
2416                         g_warning("imap_cmd_select(): invalid RECENT line.\n");
2417                         THROW;
2418                 }
2419         }
2420
2421         resp_str = search_array_contain_str(argbuf, "UIDVALIDITY");
2422         if (resp_str) {
2423                 if (sscanf(resp_str, "OK [UIDVALIDITY %u] ", uid_validity)
2424                     != 1) {
2425                         g_warning("imap_cmd_select(): invalid UIDVALIDITY line.\n");
2426                         THROW;
2427                 }
2428         }
2429
2430         resp_str = search_array_contain_str(argbuf, "UNSEEN");
2431         if (resp_str) {
2432                 if (sscanf(resp_str, "OK [UNSEEN %d] ", unseen) != 1) {
2433                         g_warning("imap_cmd_select(): invalid UNSEEN line.\n");
2434                         THROW;
2435                 }
2436         }
2437
2438 catch:
2439         ptr_array_free_strings(argbuf);
2440         g_ptr_array_free(argbuf, TRUE);
2441
2442         return ok;
2443 }
2444
2445 static gint imap_cmd_select(SockInfo *sock, const gchar *folder,
2446                             gint *exists, gint *recent, gint *unseen,
2447                             guint32 *uid_validity)
2448 {
2449         return imap_cmd_do_select(sock, folder, FALSE,
2450                                   exists, recent, unseen, uid_validity);
2451 }
2452
2453 static gint imap_cmd_examine(SockInfo *sock, const gchar *folder,
2454                              gint *exists, gint *recent, gint *unseen,
2455                              guint32 *uid_validity)
2456 {
2457         return imap_cmd_do_select(sock, folder, TRUE,
2458                                   exists, recent, unseen, uid_validity);
2459 }
2460
2461 #undef THROW
2462
2463 static gint imap_cmd_create(SockInfo *sock, const gchar *folder)
2464 {
2465         gchar *folder_;
2466
2467         QUOTE_IF_REQUIRED(folder_, folder);
2468         imap_cmd_gen_send(sock, "CREATE %s", folder_);
2469
2470         return imap_cmd_ok(sock, NULL);
2471 }
2472
2473 static gint imap_cmd_rename(SockInfo *sock, const gchar *old_folder,
2474                             const gchar *new_folder)
2475 {
2476         gchar *old_folder_, *new_folder_;
2477
2478         QUOTE_IF_REQUIRED(old_folder_, old_folder);
2479         QUOTE_IF_REQUIRED(new_folder_, new_folder);
2480         imap_cmd_gen_send(sock, "RENAME %s %s", old_folder_, new_folder_);
2481
2482         return imap_cmd_ok(sock, NULL);
2483 }
2484
2485 static gint imap_cmd_delete(SockInfo *sock, const gchar *folder)
2486 {
2487         gchar *folder_;
2488
2489         QUOTE_IF_REQUIRED(folder_, folder);
2490         imap_cmd_gen_send(sock, "DELETE %s", folder_);
2491
2492         return imap_cmd_ok(sock, NULL);
2493 }
2494
2495 static gint imap_cmd_fetch(SockInfo *sock, guint32 uid, const gchar *filename)
2496 {
2497         gint ok;
2498         gchar buf[IMAPBUFSIZE];
2499         gchar *cur_pos;
2500         gchar size_str[32];
2501         glong size_num;
2502
2503         g_return_val_if_fail(filename != NULL, IMAP_ERROR);
2504
2505         imap_cmd_gen_send(sock, "UID FETCH %d BODY[]", uid);
2506
2507         while ((ok = imap_cmd_gen_recv(sock, buf, sizeof(buf)))
2508                == IMAP_SUCCESS) {
2509                 if (buf[0] != '*' || buf[1] != ' ')
2510                         return IMAP_ERROR;
2511                 if (strstr(buf, "FETCH") != NULL)
2512                         break;
2513         }
2514         if (ok != IMAP_SUCCESS)
2515                 return ok;
2516
2517         cur_pos = strchr(buf, '{');
2518         g_return_val_if_fail(cur_pos != NULL, IMAP_ERROR);
2519         cur_pos = strchr_cpy(cur_pos + 1, '}', size_str, sizeof(size_str));
2520         g_return_val_if_fail(cur_pos != NULL, IMAP_ERROR);
2521         size_num = atol(size_str);
2522
2523         if (*cur_pos != '\0') return IMAP_ERROR;
2524
2525         if (recv_bytes_write_to_file(sock, size_num, filename) != 0)
2526                 return IMAP_ERROR;
2527
2528         if (imap_cmd_gen_recv(sock, buf, sizeof(buf)) != IMAP_SUCCESS)
2529                 return IMAP_ERROR;
2530
2531         if (buf[0] == '\0' || buf[strlen(buf) - 1] != ')')
2532                 return IMAP_ERROR;
2533
2534         ok = imap_cmd_ok(sock, NULL);
2535
2536         return ok;
2537 }
2538
2539 static gint imap_cmd_append(SockInfo *sock, const gchar *destfolder,
2540                             const gchar *file)
2541 {
2542         gint ok;
2543         gint size;
2544         gchar *destfolder_;
2545         gchar buf[BUFFSIZE];
2546         FILE *fp;
2547
2548         g_return_val_if_fail(file != NULL, IMAP_ERROR);
2549
2550         size = get_file_size_as_crlf(file);
2551         if ((fp = fopen(file, "rb")) == NULL) {
2552                 FILE_OP_ERROR(file, "fopen");
2553                 return -1;
2554         }
2555         QUOTE_IF_REQUIRED(destfolder_, destfolder);
2556         imap_cmd_gen_send(sock, "APPEND %s (\\Seen) {%d}", destfolder_, size);
2557
2558         ok = imap_cmd_gen_recv(sock, buf, sizeof(buf));
2559         if (ok != IMAP_SUCCESS || buf[0] != '+' || buf[1] != ' ') {
2560                 log_warning(_("can't append %s to %s\n"), file, destfolder_);
2561                 fclose(fp);
2562                 return IMAP_ERROR;
2563         }
2564
2565         log_print("IMAP4> %s\n", _("(sending file...)"));
2566
2567         while (fgets(buf, sizeof(buf), fp) != NULL) {
2568                 strretchomp(buf);
2569                 if (sock_puts(sock, buf) < 0) {
2570                         fclose(fp);
2571                         sock_close(sock);
2572                         return -1;
2573                 }
2574         }
2575
2576         if (ferror(fp)) {
2577                 FILE_OP_ERROR(file, "fgets");
2578                 fclose(fp);
2579                 sock_close(sock);
2580                 return -1;
2581         }
2582
2583         sock_puts(sock, "");
2584
2585         fclose(fp);
2586         return imap_cmd_ok(sock, NULL);
2587 }
2588
2589 static gint imap_cmd_copy(SockInfo *sock, guint32 uid, const gchar *destfolder)
2590 {
2591         gint ok;
2592         gchar *destfolder_;
2593
2594         g_return_val_if_fail(destfolder != NULL, IMAP_ERROR);
2595
2596         QUOTE_IF_REQUIRED(destfolder_, destfolder);
2597         imap_cmd_gen_send(sock, "UID COPY %d %s", uid, destfolder_);
2598
2599         ok = imap_cmd_ok(sock, NULL);
2600         if (ok != IMAP_SUCCESS) {
2601                 log_warning(_("can't copy %d to %s\n"), uid, destfolder_);
2602                 return -1;
2603         }
2604
2605         return ok;
2606 }
2607
2608 gint imap_cmd_envelope(SockInfo *sock, guint32 first_uid, guint32 last_uid)
2609 {
2610         imap_cmd_gen_send
2611                 (sock, "UID FETCH %d:%d (UID FLAGS RFC822.SIZE ENVELOPE)",
2612                  first_uid, last_uid);
2613
2614         return IMAP_SUCCESS;
2615 }
2616
2617 static gint imap_cmd_store(SockInfo *sock, guint32 first_uid, guint32 last_uid,
2618                            gchar *sub_cmd)
2619 {
2620         gint ok;
2621
2622         imap_cmd_gen_send(sock, "UID STORE %d:%d %s",
2623                           first_uid, last_uid, sub_cmd);
2624
2625         if ((ok = imap_cmd_ok(sock, NULL)) != IMAP_SUCCESS) {
2626                 log_warning(_("error while imap command: STORE %d:%d %s\n"),
2627                             first_uid, last_uid, sub_cmd);
2628                 return ok;
2629         }
2630
2631         return IMAP_SUCCESS;
2632 }
2633
2634 static gint imap_cmd_expunge(SockInfo *sock)
2635 {
2636         gint ok;
2637
2638         imap_cmd_gen_send(sock, "EXPUNGE");
2639         if ((ok = imap_cmd_ok(sock, NULL)) != IMAP_SUCCESS) {
2640                 log_warning(_("error while imap command: EXPUNGE\n"));
2641                 return ok;
2642         }
2643
2644         return IMAP_SUCCESS;
2645 }
2646
2647 static gint imap_cmd_ok(SockInfo *sock, GPtrArray *argbuf)
2648 {
2649         gint ok;
2650         gchar buf[IMAPBUFSIZE];
2651         gint cmd_num;
2652         gchar cmd_status[IMAPBUFSIZE];
2653
2654         while ((ok = imap_cmd_gen_recv(sock, buf, sizeof(buf)))
2655                == IMAP_SUCCESS) {
2656                 if (buf[0] == '*' && buf[1] == ' ') {
2657                         if (argbuf)
2658                                 g_ptr_array_add(argbuf, g_strdup(buf + 2));
2659                         continue;
2660                 }
2661
2662                 if (sscanf(buf, "%d %s", &cmd_num, cmd_status) < 2)
2663                         return IMAP_ERROR;
2664                 else if (cmd_num == imap_cmd_count &&
2665                          !strcmp(cmd_status, "OK")) {
2666                         if (argbuf)
2667                                 g_ptr_array_add(argbuf, g_strdup(buf));
2668                         return IMAP_SUCCESS;
2669                 } else
2670                         return IMAP_ERROR;
2671         }
2672
2673         return ok;
2674 }
2675
2676 static void imap_cmd_gen_send(SockInfo *sock, const gchar *format, ...)
2677 {
2678         gchar buf[IMAPBUFSIZE];
2679         gchar tmp[IMAPBUFSIZE];
2680         gchar *p;
2681         va_list args;
2682
2683         va_start(args, format);
2684         g_vsnprintf(tmp, sizeof(tmp), format, args);
2685         va_end(args);
2686
2687         imap_cmd_count++;
2688
2689         g_snprintf(buf, sizeof(buf), "%d %s\r\n", imap_cmd_count, tmp);
2690         if (!strncasecmp(tmp, "LOGIN ", 6) && (p = strchr(tmp + 6, ' '))) {
2691                 *p = '\0';
2692                 log_print("IMAP4> %d %s ********\n", imap_cmd_count, tmp);
2693         } else
2694                 log_print("IMAP4> %d %s\n", imap_cmd_count, tmp);
2695
2696         sock_write(sock, buf, strlen(buf));
2697 }
2698
2699 static gint imap_cmd_gen_recv(SockInfo *sock, gchar *buf, gint size)
2700 {
2701         if (sock_gets(sock, buf, size) == -1)
2702                 return IMAP_SOCKET;
2703
2704         strretchomp(buf);
2705
2706         log_print("IMAP4< %s\n", buf);
2707
2708         return IMAP_SUCCESS;
2709 }
2710
2711
2712 /* misc utility functions */
2713
2714 static gchar *strchr_cpy(const gchar *src, gchar ch, gchar *dest, gint len)
2715 {
2716         gchar *tmp;
2717
2718         dest[0] = '\0';
2719         tmp = strchr(src, ch);
2720         if (!tmp)
2721                 return NULL;
2722
2723         memcpy(dest, src, MIN(tmp - src, len - 1));
2724         dest[MIN(tmp - src, len - 1)] = '\0';
2725
2726         return tmp + 1;
2727 }
2728
2729 static gchar *get_quoted(const gchar *src, gchar ch, gchar *dest, gint len)
2730 {
2731         const gchar *p = src;
2732         gint n = 0;
2733
2734         g_return_val_if_fail(*p == ch, NULL);
2735
2736         *dest = '\0';
2737         p++;
2738
2739         while (*p != '\0' && *p != ch) {
2740                 if (n < len - 1) {
2741                         if (*p == '\\' && *(p + 1) != '\0')
2742                                 p++;
2743                         *dest++ = *p++;
2744                 } else
2745                         p++;
2746                 n++;
2747         }
2748
2749         *dest = '\0';
2750         return (gchar *)(*p == ch ? p + 1 : p);
2751 }
2752
2753 static gchar *search_array_starts(GPtrArray *array, const gchar *str)
2754 {
2755         gint i;
2756         size_t len;
2757
2758         g_return_val_if_fail(str != NULL, NULL);
2759         len = strlen(str);
2760         for (i = 0; i < array->len; i++) {
2761                 gchar *tmp;
2762                 tmp = g_ptr_array_index(array, i);
2763                 if (strncmp(tmp, str, len) == 0)
2764                         return tmp;
2765         }
2766         return NULL;
2767 }
2768
2769 static gchar *search_array_contain_str(GPtrArray *array, gchar *str)
2770 {
2771         gint i;
2772
2773         for (i = 0; i < array->len; i++) {
2774                 gchar *tmp;
2775
2776                 tmp = g_ptr_array_index(array, i);
2777                 if (strstr(tmp, str) != NULL)
2778                         return tmp;
2779         }
2780
2781         return NULL;
2782 }
2783
2784 static gchar *search_array_str(GPtrArray *array, gchar *str)
2785 {
2786         gint i;
2787         gint len;
2788
2789         len = strlen(str);
2790
2791         for (i = 0; i < array->len; i++) {
2792                 gchar *tmp;
2793
2794                 tmp = g_ptr_array_index(array, i);
2795                 if (!strncmp(tmp, str, len))
2796                         return tmp;
2797         }
2798
2799         return NULL;
2800 }
2801
2802 static void imap_path_separator_subst(gchar *str, gchar separator)
2803 {
2804         gchar *p;
2805         gboolean in_escape = FALSE;
2806
2807         if (!separator || separator == '/') return;
2808
2809         for (p = str; *p != '\0'; p++) {
2810                 if (*p == '/' && !in_escape)
2811                         *p = separator;
2812                 else if (*p == '&' && *(p + 1) != '-' && !in_escape)
2813                         in_escape = TRUE;
2814                 else if (*p == '-' && in_escape)
2815                         in_escape = FALSE;
2816         }
2817 }
2818
2819 static gchar *imap_modified_utf7_to_locale(const gchar *mutf7_str)
2820 {
2821 #if !HAVE_LIBJCONV
2822         return g_strdup(mutf7_str);
2823 #else
2824         static iconv_t cd = (iconv_t)-1;
2825         static gboolean iconv_ok = TRUE;
2826         GString *norm_utf7;
2827         gchar *norm_utf7_p;
2828         size_t norm_utf7_len;
2829         const gchar *p;
2830         gchar *to_str, *to_p;
2831         size_t to_len;
2832         gboolean in_escape = FALSE;
2833
2834         if (!iconv_ok) return g_strdup(mutf7_str);
2835
2836         if (cd == (iconv_t)-1) {
2837                 cd = iconv_open(conv_get_current_charset_str(), "UTF-7");
2838                 if (cd == (iconv_t)-1) {
2839                         g_warning(_("iconv cannot convert UTF-7 to %s\n"),
2840                                   conv_get_current_charset_str());
2841                         iconv_ok = FALSE;
2842                         return g_strdup(mutf7_str);
2843                 }
2844         }
2845
2846         norm_utf7 = g_string_new(NULL);
2847
2848         for (p = mutf7_str; *p != '\0'; p++) {
2849                 /* replace: '&'  -> '+',
2850                             "&-" -> '&',
2851                             escaped ','  -> '/' */
2852                 if (!in_escape && *p == '&') {
2853                         if (*(p + 1) != '-') {
2854                                 g_string_append_c(norm_utf7, '+');
2855                                 in_escape = TRUE;
2856                         } else {
2857                                 g_string_append_c(norm_utf7, '&');
2858                                 p++;
2859                         }
2860                 } else if (in_escape && *p == ',') {
2861                         g_string_append_c(norm_utf7, '/');
2862                 } else if (in_escape && *p == '-') {
2863                         g_string_append_c(norm_utf7, '-');
2864                         in_escape = FALSE;
2865                 } else {
2866                         g_string_append_c(norm_utf7, *p);
2867                 }
2868         }
2869
2870         norm_utf7_p = norm_utf7->str;
2871         norm_utf7_len = norm_utf7->len;
2872         to_len = strlen(mutf7_str) * 5;
2873         to_p = to_str = g_malloc(to_len + 1);
2874
2875         if (iconv(cd, &norm_utf7_p, &norm_utf7_len, &to_p, &to_len) == -1) {
2876                 g_warning(_("iconv cannot convert UTF-7 to %s\n"),
2877                           conv_get_current_charset_str());
2878                 g_string_free(norm_utf7, TRUE);
2879                 g_free(to_str);
2880                 return g_strdup(mutf7_str);
2881         }
2882
2883         /* second iconv() call for flushing */
2884         iconv(cd, NULL, NULL, &to_p, &to_len);
2885         g_string_free(norm_utf7, TRUE);
2886         *to_p = '\0';
2887
2888         return to_str;
2889 #endif /* !HAVE_LIBJCONV */
2890 }
2891
2892 static gchar *imap_locale_to_modified_utf7(const gchar *from)
2893 {
2894 #if !HAVE_LIBJCONV
2895         return g_strdup(from);
2896 #else
2897         static iconv_t cd = (iconv_t)-1;
2898         static gboolean iconv_ok = TRUE;
2899         gchar *norm_utf7, *norm_utf7_p;
2900         size_t from_len, norm_utf7_len;
2901         GString *to_str;
2902         gchar *from_tmp, *to, *p;
2903         gboolean in_escape = FALSE;
2904
2905         if (!iconv_ok) return g_strdup(from);
2906
2907         if (cd == (iconv_t)-1) {
2908                 cd = iconv_open("UTF-7", conv_get_current_charset_str());
2909                 if (cd == (iconv_t)-1) {
2910                         g_warning(_("iconv cannot convert %s to UTF-7\n"),
2911                                   conv_get_current_charset_str());
2912                         iconv_ok = FALSE;
2913                         return g_strdup(from);
2914                 }
2915         }
2916
2917         Xstrdup_a(from_tmp, from, return g_strdup(from));
2918         from_len = strlen(from);
2919         norm_utf7_len = from_len * 5;
2920         Xalloca(norm_utf7, norm_utf7_len + 1, return g_strdup(from));
2921         norm_utf7_p = norm_utf7;
2922
2923 #define IS_PRINT(ch) (isprint(ch) && isascii(ch))
2924
2925         while (from_len > 0) {
2926                 if (IS_PRINT(*from_tmp)) {
2927                         /* printable ascii char */
2928                         *norm_utf7_p = *from_tmp;
2929                         norm_utf7_p++;
2930                         from_tmp++;
2931                         from_len--;
2932                 } else {
2933                         size_t mblen;
2934
2935                         /* unprintable char: convert to UTF-7 */
2936                         for (mblen = 0;
2937                              !IS_PRINT(from_tmp[mblen]) && mblen < from_len;
2938                              mblen++)
2939                                 ;
2940                         from_len -= mblen;
2941                         if (iconv(cd, &from_tmp, &mblen,
2942                                   &norm_utf7_p, &norm_utf7_len) == -1) {
2943                                 g_warning(_("iconv cannot convert %s to UTF-7\n"),
2944                                           conv_get_current_charset_str());
2945                                 return g_strdup(from);
2946                         }
2947
2948                         /* second iconv() call for flushing */
2949                         iconv(cd, NULL, NULL, &norm_utf7_p, &norm_utf7_len);
2950                 }
2951         }
2952
2953 #undef IS_PRINT
2954
2955         *norm_utf7_p = '\0';
2956         to_str = g_string_new(NULL);
2957         for (p = norm_utf7; p < norm_utf7_p; p++) {
2958                 /* replace: '&' -> "&-",
2959                             '+' -> '&',
2960                             escaped '/' -> ',' */
2961                 if (!in_escape && *p == '&') {
2962                         g_string_append(to_str, "&-");
2963                 } else if (!in_escape && *p == '+') {
2964                         g_string_append_c(to_str, '&');
2965                         in_escape = TRUE;
2966                 } else if (in_escape && *p == '/') {
2967                         g_string_append_c(to_str, ',');
2968                 } else if (in_escape && *p == '-') {
2969                         in_escape = FALSE;
2970                         g_string_append_c(to_str, '-');
2971                 } else {
2972                         g_string_append_c(to_str, *p);
2973                 }
2974         }
2975
2976         if (in_escape) {
2977                 in_escape = FALSE;
2978                 g_string_append_c(to_str, '-');
2979         }
2980
2981         to = to_str->str;
2982         g_string_free(to_str, FALSE);
2983
2984         return to;
2985 #endif
2986 }
2987
2988 static gboolean imap_rename_folder_func(GNode *node, gpointer data)
2989 {
2990         FolderItem *item = node->data;
2991         gchar **paths = data;
2992         const gchar *oldpath = paths[0];
2993         const gchar *newpath = paths[1];
2994         gchar *base;
2995         gchar *new_itempath;
2996         gint oldpathlen;
2997
2998         oldpathlen = strlen(oldpath);
2999         if (strncmp(oldpath, item->path, oldpathlen) != 0) {
3000                 g_warning("path doesn't match: %s, %s\n", oldpath, item->path);
3001                 return TRUE;
3002         }
3003
3004         base = item->path + oldpathlen;
3005         while (*base == G_DIR_SEPARATOR) base++;
3006         if (*base == '\0')
3007                 new_itempath = g_strdup(newpath);
3008         else
3009                 new_itempath = g_strconcat(newpath, G_DIR_SEPARATOR_S, base,
3010                                            NULL);
3011         g_free(item->path);
3012         item->path = new_itempath;
3013
3014         return FALSE;
3015 }