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