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