sync with 0.7.4cvs49
[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                 log_print("IMAP4< %s\n", tmp);
1501                 if (tmp[0] != '*' || tmp[1] != ' ') {
1502                         g_free(tmp);
1503                         break;
1504                 }
1505                 if (strstr(tmp, "FETCH") == NULL) {
1506                         g_free(tmp);
1507                         continue;
1508                 }
1509                 g_string_assign(str, tmp);
1510                 g_free(tmp);
1511
1512                 msginfo = imap_parse_envelope(SESSION(session)->sock, str);
1513                 if (!msginfo) {
1514                         log_warning(_("can't parse envelope: %s\n"), str->str);
1515                         continue;
1516                 }
1517                 if (item->stype == F_QUEUE) {
1518                         MSG_SET_TMP_FLAGS(msginfo->flags, MSG_QUEUED);
1519                 } else if (item->stype == F_DRAFT) {
1520                         MSG_SET_TMP_FLAGS(msginfo->flags, MSG_DRAFT);
1521                 }
1522
1523                 msginfo->folder = item;
1524
1525                 if (!newlist)
1526                         llast = newlist = g_slist_append(newlist, msginfo);
1527                 else {
1528                         llast = g_slist_append(llast, msginfo);
1529                         llast = llast->next;
1530                 }
1531         }
1532
1533         g_string_free(str, TRUE);
1534
1535         return newlist;
1536 }
1537
1538 static GSList *imap_delete_cached_messages(GSList *mlist, FolderItem *item,
1539                                            guint32 first_uid, guint32 last_uid)
1540 {
1541         GSList *cur, *next;
1542         MsgInfo *msginfo;
1543         gchar *dir;
1544
1545         g_return_val_if_fail(item != NULL, mlist);
1546         g_return_val_if_fail(item->folder != NULL, mlist);
1547         g_return_val_if_fail(item->folder->type == F_IMAP, mlist);
1548
1549         debug_print(_("Deleting cached messages %d - %d ... "),
1550                     first_uid, last_uid);
1551
1552         dir = folder_item_get_path(item);
1553         remove_numbered_files(dir, first_uid, last_uid);
1554         g_free(dir);
1555
1556         for (cur = mlist; cur != NULL; ) {
1557                 next = cur->next;
1558
1559                 msginfo = (MsgInfo *)cur->data;
1560                 if (msginfo != NULL && first_uid <= msginfo->msgnum &&
1561                     msginfo->msgnum <= last_uid) {
1562                         procmsg_msginfo_free(msginfo);
1563                         mlist = g_slist_remove(mlist, msginfo);
1564                 }
1565
1566                 cur = next;
1567         }
1568
1569         debug_print(_("done.\n"));
1570
1571         return mlist;
1572 }
1573
1574 static void imap_delete_all_cached_messages(FolderItem *item)
1575 {
1576         gchar *dir;
1577
1578         g_return_if_fail(item != NULL);
1579         g_return_if_fail(item->folder != NULL);
1580         g_return_if_fail(item->folder->type == F_IMAP);
1581
1582         debug_print(_("Deleting all cached messages... "));
1583
1584         dir = folder_item_get_path(item);
1585         remove_all_numbered_files(dir);
1586         g_free(dir);
1587
1588         debug_print(_("done.\n"));
1589 }
1590
1591
1592 static SockInfo *imap_open_tunnel(const gchar *server,
1593                            const gchar *tunnelcmd)
1594 {
1595         SockInfo *sock;
1596
1597         if ((sock = sock_connect_cmd(server, tunnelcmd)) == NULL)
1598                 log_warning(_("Can't establish IMAP4 session with: %s\n"),
1599                             server);
1600                 return NULL;
1601
1602         return imap_init_sock(sock);
1603 }
1604
1605
1606 #if USE_SSL
1607 static SockInfo *imap_open(const gchar *server, gushort port,
1608                            gboolean use_ssl)
1609 #else
1610 static SockInfo *imap_open(const gchar *server, gushort port)
1611 #endif
1612 {
1613         SockInfo *sock;
1614
1615         if ((sock = sock_connect(server, port)) == NULL) {
1616                 log_warning(_("Can't connect to IMAP4 server: %s:%d\n"),
1617                             server, port);
1618                 return NULL;
1619         }
1620
1621 #if USE_SSL
1622         if (use_ssl && !ssl_init_socket(sock)) {
1623                 log_warning(_("Can't establish IMAP4 session with: %s:%d\n"),
1624                             server, port);
1625                 sock_close(sock);
1626                 return NULL;
1627         }
1628 #endif
1629
1630         return imap_init_sock(sock);
1631 }
1632
1633
1634 static SockInfo *imap_init_sock(SockInfo *sock)
1635 {
1636         imap_cmd_count = 0;
1637
1638         if (imap_cmd_noop(sock) != IMAP_SUCCESS) {
1639                 log_warning(_("Can't establish IMAP4 session\n"));
1640                 sock_close(sock);
1641                 return NULL;
1642         }
1643
1644         return sock;
1645 }
1646
1647 #define THROW goto catch
1648
1649 static void imap_parse_namespace(IMAPSession *session, IMAPFolder *folder)
1650 {
1651         gchar *ns_str;
1652         gchar *name;
1653         gchar *separator;
1654         gchar *p;
1655         IMAPNameSpace *namespace;
1656         GList *ns_list = NULL;
1657
1658         g_return_if_fail(session != NULL);
1659         g_return_if_fail(folder != NULL);
1660
1661         if (folder->namespace != NULL) return;
1662
1663         if (imap_cmd_namespace(SESSION(session)->sock, &ns_str)
1664             != IMAP_SUCCESS) {
1665                 log_warning(_("can't get namespace\n"));
1666                 return;
1667         }
1668
1669         /* get the first element */
1670         extract_one_parenthesis_with_skip_quote(ns_str, '"', '(', ')');
1671         g_strstrip(ns_str);
1672         p = ns_str;
1673
1674         while (*p != '\0') {
1675                 /* parse ("#foo" "/") */
1676
1677                 while (*p && *p != '(') p++;
1678                 if (*p == '\0') THROW;
1679                 p++;
1680
1681                 while (*p && *p != '"') p++;
1682                 if (*p == '\0') THROW;
1683                 p++;
1684                 name = p;
1685
1686                 while (*p && *p != '"') p++;
1687                 if (*p == '\0') THROW;
1688                 *p = '\0';
1689                 p++;
1690
1691                 while (*p && isspace(*p)) p++;
1692                 if (*p == '\0') THROW;
1693                 if (strncmp(p, "NIL", 3) == 0)
1694                         separator = NULL;
1695                 else if (*p == '"') {
1696                         p++;
1697                         separator = p;
1698                         while (*p && *p != '"') p++;
1699                         if (*p == '\0') THROW;
1700                         *p = '\0';
1701                         p++;
1702                 } else THROW;
1703
1704                 while (*p && *p != ')') p++;
1705                 if (*p == '\0') THROW;
1706                 p++;
1707
1708                 namespace = g_new(IMAPNameSpace, 1);
1709                 namespace->name = g_strdup(name);
1710                 namespace->separator = separator ? separator[0] : '\0';
1711                 ns_list = g_list_append(ns_list, namespace);
1712                 IMAP_FOLDER(folder)->namespace = ns_list;
1713         }
1714
1715 catch:
1716         g_free(ns_str);
1717         return;
1718 }
1719
1720 #undef THROW
1721
1722 static IMAPNameSpace *imap_find_namespace(IMAPFolder *folder,
1723                                           const gchar *path)
1724 {
1725         IMAPNameSpace *namespace = NULL;
1726         GList *ns_list;
1727         gchar *name;
1728
1729         g_return_val_if_fail(folder != NULL, NULL);
1730         g_return_val_if_fail(path != NULL, NULL);
1731
1732         ns_list = folder->namespace;
1733
1734         for (; ns_list != NULL; ns_list = ns_list->next) {
1735                 IMAPNameSpace *tmp_ns = ns_list->data;
1736
1737                 Xstrdup_a(name, tmp_ns->name, return namespace);
1738                 if (tmp_ns->separator && tmp_ns->separator != '/')
1739                         subst_char(name, tmp_ns->separator, '/');
1740                 if (strncmp(path, name, strlen(name)) == 0)
1741                         namespace = tmp_ns;
1742         }
1743
1744         return namespace;
1745 }
1746
1747 static gchar *imap_get_real_path(IMAPFolder *folder, const gchar *path)
1748 {
1749         gchar *real_path;
1750         IMAPNameSpace *namespace;
1751
1752         g_return_val_if_fail(folder != NULL, NULL);
1753         g_return_val_if_fail(path != NULL, NULL);
1754
1755         real_path = imap_locale_to_modified_utf7(path);
1756         namespace = imap_find_namespace(folder, path);
1757         if (namespace && namespace->separator)
1758                 imap_path_separator_subst(real_path, namespace->separator);
1759
1760         return real_path;
1761 }
1762
1763 static gchar *imap_parse_atom(SockInfo *sock, gchar *src,
1764                               gchar *dest, gint dest_len, GString *str)
1765 {
1766         gchar *cur_pos = src;
1767         gchar *nextline;
1768
1769         g_return_val_if_fail(str != NULL, cur_pos);
1770
1771         /* read the next line if the current response buffer is empty */
1772         while (isspace(*cur_pos)) cur_pos++;
1773         while (*cur_pos == '\0') {
1774                 if ((nextline = sock_getline(sock)) == NULL)
1775                         return cur_pos;
1776                 g_string_assign(str, nextline);
1777                 cur_pos = str->str;
1778                 strretchomp(nextline);
1779                 log_print("IMAP4< %s\n", nextline);
1780                 g_free(nextline);
1781
1782                 while (isspace(*cur_pos)) cur_pos++;
1783         }
1784
1785         if (!strncmp(cur_pos, "NIL", 3)) {
1786                 *dest = '\0';
1787                 cur_pos += 3;
1788         } else if (*cur_pos == '\"') {
1789                 gchar *p;
1790
1791                 p = get_quoted(cur_pos, '\"', dest, dest_len);
1792                 cur_pos = p ? p : cur_pos + 2;
1793         } else if (*cur_pos == '{') {
1794                 gchar buf[32];
1795                 gint len;
1796                 gint line_len = 0;
1797
1798                 cur_pos = strchr_cpy(cur_pos + 1, '}', buf, sizeof(buf));
1799                 len = atoi(buf);
1800
1801                 g_string_truncate(str, 0);
1802                 cur_pos = str->str;
1803
1804                 do {
1805                         if ((nextline = sock_getline(sock)) == NULL)
1806                                 return cur_pos;
1807                         line_len += strlen(nextline);
1808                         g_string_append(str, nextline);
1809                         cur_pos = str->str;
1810                         strretchomp(nextline);
1811                         log_print("IMAP4< %s\n", nextline);
1812                         g_free(nextline);
1813                 } while (line_len < len);
1814
1815                 memcpy(dest, cur_pos, MIN(len, dest_len - 1));
1816                 dest[MIN(len, dest_len - 1)] = '\0';
1817                 cur_pos += len;
1818         }
1819
1820         return cur_pos;
1821 }
1822
1823 static gchar *imap_parse_one_address(SockInfo *sock, gchar *start,
1824                                      gchar *out_from_str,
1825                                      gchar *out_fromname_str,
1826                                      GString *str)
1827 {
1828         gchar buf[IMAPBUFSIZE];
1829         gchar *userid;
1830         gchar *domain;
1831         gchar *cur_pos = start;
1832
1833         cur_pos = imap_parse_atom(sock, cur_pos, buf, sizeof(buf), str);
1834         conv_unmime_header(out_fromname_str, IMAPBUFSIZE, buf, NULL);
1835
1836         cur_pos = imap_parse_atom(sock, cur_pos, buf, sizeof(buf), str);
1837
1838         cur_pos = imap_parse_atom(sock, cur_pos, buf, sizeof(buf), str);
1839         Xstrdup_a(userid, buf, return cur_pos + 1);
1840
1841         cur_pos = imap_parse_atom(sock, cur_pos, buf, sizeof(buf), str);
1842         Xstrdup_a(domain, buf, return cur_pos + 1);
1843
1844         if (out_fromname_str[0] != '\0') {
1845                 g_snprintf(out_from_str, IMAPBUFSIZE, "\"%s\" <%s@%s>",
1846                            out_fromname_str, userid, domain);
1847         } else {
1848                 g_snprintf(out_from_str, IMAPBUFSIZE, "%s@%s",
1849                            userid, domain);
1850                 strcpy(out_fromname_str, out_from_str);
1851         }
1852
1853         while (*cur_pos == ' ') cur_pos++;
1854         g_return_val_if_fail(*cur_pos == ')', NULL);
1855
1856         return cur_pos + 1;
1857 }
1858
1859 static gchar *imap_parse_address(SockInfo *sock, gchar *start,
1860                                  gchar **out_from_str,
1861                                  gchar **out_fromname_str,
1862                                  GString *str)
1863 {
1864         gchar buf[IMAPBUFSIZE];
1865         gchar name_buf[IMAPBUFSIZE];
1866         gchar *cur_pos = start;
1867         GString *addr_str;
1868
1869         if (out_from_str)     *out_from_str     = NULL;
1870         if (out_fromname_str) *out_fromname_str = NULL;
1871         buf[0] = name_buf[0] = '\0';
1872
1873         if (!strncmp(cur_pos, "NIL", 3)) {
1874                 if (out_from_str)     *out_from_str     = g_strdup("");
1875                 if (out_fromname_str) *out_fromname_str = g_strdup("");
1876                 return cur_pos + 3;
1877         }
1878
1879         g_return_val_if_fail(*cur_pos == '(', NULL);
1880         cur_pos++;
1881
1882         addr_str = g_string_new(NULL);
1883
1884         for (;;) {
1885                 gchar ch = *cur_pos++;
1886                 if (ch == ')') break;
1887                 if (ch == '(') {
1888                         cur_pos = imap_parse_one_address
1889                                 (sock, cur_pos, buf, name_buf, str);
1890                         if (!cur_pos) {
1891                                 g_string_free(addr_str, TRUE);
1892                                 return NULL;
1893                         }
1894                         if (addr_str->str[0] != '\0')
1895                                 g_string_append(addr_str, ", ");
1896                         g_string_append(addr_str, buf);
1897                 }
1898         }
1899
1900         if (out_from_str)     *out_from_str     = g_strdup(addr_str->str);
1901         if (out_fromname_str) *out_fromname_str = g_strdup(name_buf);
1902
1903         g_string_free(addr_str, TRUE);
1904
1905         return cur_pos;
1906 }
1907
1908 static MsgFlags imap_parse_flags(const gchar *flag_str)  
1909 {
1910         const gchar *p = flag_str;
1911         MsgFlags flags;
1912
1913         flags.perm_flags = MSG_UNREAD;
1914         flags.tmp_flags  = MSG_IMAP;
1915
1916         while ((p = strchr(p, '\\')) != NULL) {
1917                 p++;
1918
1919                 if (g_strncasecmp(p, "Recent", 6) == 0 && MSG_IS_UNREAD(flags)) {
1920                         MSG_SET_PERM_FLAGS(flags, MSG_NEW);
1921                 } else if (g_strncasecmp(p, "Seen", 4) == 0) {
1922                         MSG_UNSET_PERM_FLAGS(flags, MSG_NEW|MSG_UNREAD);
1923                 } else if (g_strncasecmp(p, "Deleted", 7) == 0) {
1924                         MSG_SET_PERM_FLAGS(flags, MSG_DELETED);
1925                 } else if (g_strncasecmp(p, "Flagged", 7) == 0) {
1926                         MSG_SET_PERM_FLAGS(flags, MSG_MARKED);
1927                 } else if (g_strncasecmp(p, "Answered", 8) == 0) {
1928                         MSG_SET_PERM_FLAGS(flags, MSG_REPLIED);
1929                 }
1930         }
1931
1932         return flags;
1933 }
1934
1935 static MsgInfo *imap_parse_envelope(SockInfo *sock, GString *line_str)
1936 {
1937         MsgInfo *msginfo;
1938         gchar buf[IMAPBUFSIZE];
1939         gchar tmp[IMAPBUFSIZE];
1940         gchar *cur_pos;
1941         gint msgnum;
1942         guint32 uid = 0;
1943         size_t size = 0;
1944         gchar *date = NULL;
1945         time_t date_t = 0;
1946         gchar *subject = NULL;
1947         gchar *tmp_from;
1948         gchar *tmp_fromname;
1949         gchar *from = NULL;
1950         gchar *fromname = NULL;
1951         gchar *tmp_to;
1952         gchar *to = NULL;
1953         gchar *inreplyto = NULL;
1954         gchar *msgid = NULL;
1955         MsgFlags flags = {0, 0};
1956
1957         g_return_val_if_fail(line_str != NULL, NULL);
1958         g_return_val_if_fail(line_str->str[0] == '*' &&
1959                              line_str->str[1] == ' ', NULL);
1960
1961         cur_pos = line_str->str + 2;
1962
1963 #define PARSE_ONE_ELEMENT(ch) \
1964 { \
1965         cur_pos = strchr_cpy(cur_pos, ch, buf, sizeof(buf)); \
1966         g_return_val_if_fail(cur_pos != NULL, NULL); \
1967 }
1968
1969         PARSE_ONE_ELEMENT(' ');
1970         msgnum = atoi(buf);
1971
1972         PARSE_ONE_ELEMENT(' ');
1973         g_return_val_if_fail(!strcmp(buf, "FETCH"), NULL);
1974
1975         g_return_val_if_fail(*cur_pos == '(', NULL);
1976         cur_pos++;
1977
1978         while (*cur_pos != '\0' && *cur_pos != ')') {
1979                 while (*cur_pos == ' ') cur_pos++;
1980
1981                 if (!strncmp(cur_pos, "UID ", 4)) {
1982                         cur_pos += 4;
1983                         uid = strtoul(cur_pos, &cur_pos, 10);
1984                 } else if (!strncmp(cur_pos, "FLAGS ", 6)) {
1985                         cur_pos += 6;
1986                         g_return_val_if_fail(*cur_pos == '(', NULL);
1987                         cur_pos++;
1988                         PARSE_ONE_ELEMENT(')');
1989                         flags = imap_parse_flags(buf);
1990                 } else if (!strncmp(cur_pos, "RFC822.SIZE ", 12)) {
1991                         cur_pos += 12;
1992                         size = strtol(cur_pos, &cur_pos, 10);
1993                 } else if (!strncmp(cur_pos, "ENVELOPE ", 9)) {
1994                         cur_pos += 9;
1995                         g_return_val_if_fail(*cur_pos == '(', NULL);
1996                         cur_pos = imap_parse_atom
1997                                 (sock, cur_pos + 1, buf, sizeof(buf), line_str);
1998                         if (buf[0] != '\0') {
1999                                 Xstrdup_a(date, buf, return NULL);
2000                                 date_t = procheader_date_parse(NULL, date, 0);
2001                         }
2002
2003                         cur_pos = imap_parse_atom
2004                                 (sock, cur_pos, buf, sizeof(buf), line_str);
2005                         if (buf[0] != '\0') {
2006                                 conv_unmime_header(tmp, sizeof(tmp), buf, NULL);
2007                                 Xstrdup_a(subject, tmp, return NULL);
2008                         }
2009
2010                         g_return_val_if_fail(*cur_pos == ' ', NULL);
2011                         cur_pos = imap_parse_address(sock, cur_pos + 1,
2012                                                      &tmp_from, &tmp_fromname,
2013                                                      line_str);
2014                         g_return_val_if_fail(cur_pos != NULL, NULL);
2015                         if (tmp_from && *tmp_from != '\0')
2016                                 Xstrdup_a(from, tmp_from,
2017                                           {g_free(tmp_from);
2018                                            g_free(tmp_fromname);
2019                                            return NULL;});
2020                         if (tmp_fromname && *tmp_fromname != '\0')
2021                                 Xstrdup_a(fromname, tmp_fromname,
2022                                           {g_free(tmp_from);
2023                                            g_free(tmp_fromname);
2024                                            return NULL;});
2025                         g_free(tmp_from);
2026                         g_free(tmp_fromname);
2027
2028 #define SKIP_ONE_ELEMENT() \
2029 { \
2030         g_return_val_if_fail(*cur_pos == ' ', NULL); \
2031         cur_pos = imap_parse_address(sock, cur_pos + 1, NULL, NULL, \
2032                                      line_str); \
2033         g_return_val_if_fail(cur_pos != NULL, NULL); \
2034 }
2035
2036                         /* skip sender and reply-to */
2037                         SKIP_ONE_ELEMENT();
2038                         SKIP_ONE_ELEMENT();
2039
2040                         g_return_val_if_fail(*cur_pos == ' ', NULL);
2041                         cur_pos = imap_parse_address(sock, cur_pos + 1,
2042                                                      &tmp_to, NULL, line_str);
2043                         g_return_val_if_fail(cur_pos != NULL, NULL);
2044                         Xstrdup_a(to, tmp_to, {g_free(tmp_to); return NULL;});
2045                         g_free(tmp_to);
2046
2047                         /* skip Cc and Bcc */
2048                         SKIP_ONE_ELEMENT();
2049                         SKIP_ONE_ELEMENT();
2050
2051 #undef SKIP_ONE_ELEMENT
2052
2053                         g_return_val_if_fail(*cur_pos == ' ', NULL);
2054                         cur_pos = imap_parse_atom
2055                                 (sock, cur_pos, buf, sizeof(buf), line_str);
2056                         g_return_val_if_fail(cur_pos != NULL, NULL);
2057                         if (buf[0] != '\0') {
2058                                 eliminate_parenthesis(buf, '(', ')');
2059                                 extract_parenthesis(buf, '<', '>');
2060                                 remove_space(buf);
2061                                 Xstrdup_a(inreplyto, buf, return NULL);
2062                         }
2063
2064                         g_return_val_if_fail(*cur_pos == ' ', NULL);
2065                         cur_pos = imap_parse_atom
2066                                 (sock, cur_pos, buf, sizeof(buf), line_str);
2067                         g_return_val_if_fail(cur_pos != NULL, NULL);
2068                         if (buf[0] != '\0') {
2069                                 extract_parenthesis(buf, '<', '>');
2070                                 remove_space(buf);
2071                                 Xstrdup_a(msgid, buf, return NULL);
2072                         }
2073
2074                         g_return_val_if_fail(*cur_pos == ')', NULL);
2075                         cur_pos++;
2076                 } else {
2077                         g_warning("invalid FETCH response: %s\n", cur_pos);
2078                         break;
2079                 }
2080         }
2081
2082         msginfo = g_new0(MsgInfo, 1);
2083         msginfo->msgnum = uid;
2084         msginfo->size = size;
2085         msginfo->date = g_strdup(date);
2086         msginfo->date_t = date_t;
2087         msginfo->subject = g_strdup(subject);
2088         msginfo->from = g_strdup(from);
2089         msginfo->fromname = g_strdup(fromname);
2090         msginfo->to = g_strdup(to);
2091         msginfo->inreplyto = g_strdup(inreplyto);
2092         msginfo->msgid = g_strdup(msgid);
2093         msginfo->flags = flags;
2094
2095         return msginfo;
2096 }
2097
2098 gint imap_msg_set_perm_flags(MsgInfo *msginfo, MsgPermFlags flags)
2099 {
2100         Folder *folder;
2101         IMAPSession *session;
2102         IMAPFlags iflags = 0;
2103         gint ok = IMAP_SUCCESS;
2104
2105         g_return_val_if_fail(msginfo != NULL, -1);
2106         g_return_val_if_fail(MSG_IS_IMAP(msginfo->flags), -1);
2107         g_return_val_if_fail(msginfo->folder != NULL, -1);
2108         g_return_val_if_fail(msginfo->folder->folder != NULL, -1);
2109
2110         folder = msginfo->folder->folder;
2111         g_return_val_if_fail(folder->type == F_IMAP, -1);
2112
2113         session = imap_session_get(folder);
2114         if (!session) return -1;
2115
2116         if (flags & MSG_MARKED)  iflags |= IMAP_FLAG_FLAGGED;
2117         if (flags & MSG_REPLIED) iflags |= IMAP_FLAG_ANSWERED;
2118         if (iflags) {
2119                 ok = imap_set_message_flags(session, msginfo->msgnum,
2120                                             msginfo->msgnum, iflags, TRUE);
2121                 if (ok != IMAP_SUCCESS) return ok;
2122         }
2123
2124         if (flags & MSG_UNREAD)
2125                 ok = imap_set_message_flags(session, msginfo->msgnum,
2126                                             msginfo->msgnum, IMAP_FLAG_SEEN,
2127                                             FALSE);
2128         return ok;
2129 }
2130
2131 gint imap_msg_unset_perm_flags(MsgInfo *msginfo, MsgPermFlags flags)
2132 {
2133         Folder *folder;
2134         IMAPSession *session;
2135         IMAPFlags iflags = 0;
2136         gint ok = IMAP_SUCCESS;
2137
2138         g_return_val_if_fail(msginfo != NULL, -1);
2139         g_return_val_if_fail(MSG_IS_IMAP(msginfo->flags), -1);
2140         g_return_val_if_fail(msginfo->folder != NULL, -1);
2141         g_return_val_if_fail(msginfo->folder->folder != NULL, -1);
2142
2143         folder = msginfo->folder->folder;
2144         g_return_val_if_fail(folder->type == F_IMAP, -1);
2145
2146         session = imap_session_get(folder);
2147         if (!session) return -1;
2148
2149         if (flags & MSG_MARKED)  iflags |= IMAP_FLAG_FLAGGED;
2150         if (flags & MSG_REPLIED) iflags |= IMAP_FLAG_ANSWERED;
2151         if (iflags) {
2152                 ok = imap_set_message_flags(session, msginfo->msgnum,
2153                                             msginfo->msgnum, iflags, FALSE);
2154                 if (ok != IMAP_SUCCESS) return ok;
2155         }
2156
2157         if (flags & MSG_UNREAD)
2158                 ok = imap_set_message_flags(session, msginfo->msgnum,
2159                                             msginfo->msgnum, IMAP_FLAG_SEEN,
2160                                             TRUE);
2161         return ok;
2162 }
2163
2164 static gint imap_set_message_flags(IMAPSession *session,
2165                                    guint32 first_uid,
2166                                    guint32 last_uid,
2167                                    IMAPFlags flags,
2168                                    gboolean is_set)
2169 {
2170         GString *buf;
2171         gint ok;
2172
2173         buf = g_string_new(is_set ? "+FLAGS (" : "-FLAGS (");
2174
2175         if (IMAP_IS_SEEN(flags))        g_string_append(buf, "\\Seen ");
2176         if (IMAP_IS_ANSWERED(flags))    g_string_append(buf, "\\Answered ");
2177         if (IMAP_IS_FLAGGED(flags))     g_string_append(buf, "\\Flagged ");
2178         if (IMAP_IS_DELETED(flags))     g_string_append(buf, "\\Deleted ");
2179         if (IMAP_IS_DRAFT(flags))       g_string_append(buf, "\\Draft");
2180
2181         if (buf->str[buf->len - 1] == ' ')
2182                 g_string_truncate(buf, buf->len - 1);
2183
2184         g_string_append_c(buf, ')');
2185
2186         ok = imap_cmd_store(SESSION(session)->sock, first_uid, last_uid,
2187                             buf->str);
2188         g_string_free(buf, TRUE);
2189
2190         return ok;
2191 }
2192
2193 static gint imap_select(IMAPSession *session, IMAPFolder *folder,
2194                         const gchar *path,
2195                         gint *exists, gint *recent, gint *unseen,
2196                         guint32 *uid_validity)
2197 {
2198         gchar *real_path;
2199         gint ok;
2200         gint exists_, recent_, unseen_, uid_validity_;
2201
2202         if (!exists || !recent || !unseen || !uid_validity) {
2203                 if (session->mbox && strcmp(session->mbox, path) == 0)
2204                         return IMAP_SUCCESS;
2205                 exists = &exists_;
2206                 recent = &recent_;
2207                 unseen = &unseen_;
2208                 uid_validity = &uid_validity_;
2209         }
2210
2211         g_free(session->mbox);
2212         session->mbox = NULL;
2213
2214         real_path = imap_get_real_path(folder, path);
2215         ok = imap_cmd_select(SESSION(session)->sock, real_path,
2216                              exists, recent, unseen, uid_validity);
2217         if (ok != IMAP_SUCCESS)
2218                 log_warning(_("can't select folder: %s\n"), real_path);
2219         else
2220                 session->mbox = g_strdup(path);
2221         g_free(real_path);
2222
2223         return ok;
2224 }
2225
2226 #define THROW(err) { ok = err; goto catch; }
2227
2228 static gint imap_get_uid(IMAPSession *session, gint msgnum, guint32 *uid)
2229 {
2230         gint ok;
2231         GPtrArray *argbuf;
2232         gchar *str;
2233         gint num;
2234
2235         *uid = 0;
2236         argbuf = g_ptr_array_new();
2237
2238         imap_cmd_gen_send(SESSION(session)->sock, "FETCH %d (UID)", msgnum);
2239         if ((ok = imap_cmd_ok(SESSION(session)->sock, argbuf)) != IMAP_SUCCESS)
2240                 THROW(ok);
2241
2242         str = search_array_contain_str(argbuf, "FETCH");
2243         if (!str) THROW(IMAP_ERROR);
2244
2245         if (sscanf(str, "%d FETCH (UID %d)", &num, uid) != 2 ||
2246             num != msgnum) {
2247                 g_warning("imap_get_uid(): invalid FETCH line.\n");
2248                 THROW(IMAP_ERROR);
2249         }
2250
2251 catch:
2252         ptr_array_free_strings(argbuf);
2253         g_ptr_array_free(argbuf, TRUE);
2254
2255         return ok;
2256 }
2257
2258 static gint imap_status(IMAPSession *session, IMAPFolder *folder,
2259                         const gchar *path,
2260                         gint *messages, gint *recent,
2261                         guint32 *uid_next, guint32 *uid_validity,
2262                         gint *unseen)
2263 {
2264         gchar *real_path;
2265         gchar *real_path_;
2266         gint ok;
2267         GPtrArray *argbuf;
2268         gchar *str;
2269
2270         *messages = *recent = *uid_next = *uid_validity = *unseen = 0;
2271
2272         argbuf = g_ptr_array_new();
2273
2274         real_path = imap_get_real_path(folder, path);
2275         QUOTE_IF_REQUIRED(real_path_, real_path);
2276         imap_cmd_gen_send(SESSION(session)->sock, "STATUS %s "
2277                           "(MESSAGES RECENT UIDNEXT UIDVALIDITY UNSEEN)",
2278                           real_path_);
2279
2280         ok = imap_cmd_ok(SESSION(session)->sock, argbuf);
2281         if (ok != IMAP_SUCCESS) THROW(ok);
2282
2283         str = search_array_str(argbuf, "STATUS");
2284         if (!str) THROW(IMAP_ERROR);
2285
2286         str = strchr(str, '(');
2287         if (!str) THROW(IMAP_ERROR);
2288         str++;
2289         while (*str != '\0' && *str != ')') {
2290                 while (*str == ' ') str++;
2291
2292                 if (!strncmp(str, "MESSAGES ", 9)) {
2293                         str += 9;
2294                         *messages = strtol(str, &str, 10);
2295                 } else if (!strncmp(str, "RECENT ", 7)) {
2296                         str += 7;
2297                         *recent = strtol(str, &str, 10);
2298                 } else if (!strncmp(str, "UIDNEXT ", 8)) {
2299                         str += 8;
2300                         *uid_next = strtoul(str, &str, 10);
2301                 } else if (!strncmp(str, "UIDVALIDITY ", 12)) {
2302                         str += 12;
2303                         *uid_validity = strtoul(str, &str, 10);
2304                 } else if (!strncmp(str, "UNSEEN ", 7)) {
2305                         str += 7;
2306                         *unseen = strtol(str, &str, 10);
2307                 } else {
2308                         g_warning("invalid STATUS response: %s\n", str);
2309                         break;
2310                 }
2311         }
2312
2313 catch:
2314         g_free(real_path);
2315         ptr_array_free_strings(argbuf);
2316         g_ptr_array_free(argbuf, TRUE);
2317
2318         return ok;
2319 }
2320
2321 #undef THROW
2322
2323
2324 /* low-level IMAP4rev1 commands */
2325
2326 static gint imap_cmd_login(SockInfo *sock,
2327                            const gchar *user, const gchar *pass)
2328 {
2329         gchar *user_, *pass_;
2330         gint ok;
2331
2332         QUOTE_IF_REQUIRED(user_, user);
2333         QUOTE_IF_REQUIRED(pass_, pass);
2334         imap_cmd_gen_send(sock, "LOGIN %s %s", user_, pass_);
2335
2336         ok = imap_cmd_ok(sock, NULL);
2337         if (ok != IMAP_SUCCESS)
2338                 log_warning(_("IMAP4 login failed.\n"));
2339
2340         return ok;
2341 }
2342
2343 static gint imap_cmd_logout(SockInfo *sock)
2344 {
2345         imap_cmd_gen_send(sock, "LOGOUT");
2346         return imap_cmd_ok(sock, NULL);
2347 }
2348
2349 /* Send a NOOP, and examine the server's response to see whether this
2350  * connection is pre-authenticated or not. */
2351 static gint imap_greeting(SockInfo *sock, gboolean *is_preauth)
2352 {
2353         GPtrArray *argbuf;
2354         gint r;
2355
2356         imap_cmd_gen_send(sock, "NOOP");
2357         argbuf = g_ptr_array_new(); /* will hold messages sent back */
2358         r = imap_cmd_ok(sock, argbuf);
2359         *is_preauth = search_array_starts(argbuf, "PREAUTH") != NULL;
2360         
2361         return r;
2362 }
2363
2364 static gint imap_cmd_noop(SockInfo *sock)
2365 {
2366         imap_cmd_gen_send(sock, "NOOP");
2367         return imap_cmd_ok(sock, NULL);
2368 }
2369
2370 #define THROW(err) { ok = err; goto catch; }
2371
2372 static gint imap_cmd_namespace(SockInfo *sock, gchar **ns_str)
2373 {
2374         gint ok;
2375         GPtrArray *argbuf;
2376         gchar *str;
2377
2378         argbuf = g_ptr_array_new();
2379
2380         imap_cmd_gen_send(sock, "NAMESPACE");
2381         if ((ok = imap_cmd_ok(sock, argbuf)) != IMAP_SUCCESS) THROW(ok);
2382
2383         str = search_array_str(argbuf, "NAMESPACE");
2384         if (!str) THROW(IMAP_ERROR);
2385
2386         *ns_str = g_strdup(str);
2387
2388 catch:
2389         ptr_array_free_strings(argbuf);
2390         g_ptr_array_free(argbuf, TRUE);
2391
2392         return ok;
2393 }
2394
2395 #undef THROW
2396
2397 static gint imap_cmd_list(SockInfo *sock, const gchar *ref,
2398                           const gchar *mailbox, GPtrArray *argbuf)
2399 {
2400         gchar *ref_, *mailbox_;
2401
2402         if (!ref) ref = "\"\"";
2403         if (!mailbox) mailbox = "\"\"";
2404
2405         QUOTE_IF_REQUIRED(ref_, ref);
2406         QUOTE_IF_REQUIRED(mailbox_, mailbox);
2407         imap_cmd_gen_send(sock, "LIST %s %s", ref_, mailbox_);
2408
2409         return imap_cmd_ok(sock, argbuf);
2410 }
2411
2412 #define THROW goto catch
2413
2414 static gint imap_cmd_do_select(SockInfo *sock, const gchar *folder,
2415                                gboolean examine,
2416                                gint *exists, gint *recent, gint *unseen,
2417                                guint32 *uid_validity)
2418 {
2419         gint ok;
2420         gchar *resp_str;
2421         GPtrArray *argbuf;
2422         gchar *select_cmd;
2423         gchar *folder_;
2424
2425         *exists = *recent = *unseen = *uid_validity = 0;
2426         argbuf = g_ptr_array_new();
2427
2428         if (examine)
2429                 select_cmd = "EXAMINE";
2430         else
2431                 select_cmd = "SELECT";
2432
2433         QUOTE_IF_REQUIRED(folder_, folder);
2434         imap_cmd_gen_send(sock, "%s %s", select_cmd, folder_);
2435
2436         if ((ok = imap_cmd_ok(sock, argbuf)) != IMAP_SUCCESS) THROW;
2437
2438         resp_str = search_array_contain_str(argbuf, "EXISTS");
2439         if (resp_str) {
2440                 if (sscanf(resp_str,"%d EXISTS", exists) != 1) {
2441                         g_warning("imap_cmd_select(): invalid EXISTS line.\n");
2442                         THROW;
2443                 }
2444         }
2445
2446         resp_str = search_array_contain_str(argbuf, "RECENT");
2447         if (resp_str) {
2448                 if (sscanf(resp_str, "%d RECENT", recent) != 1) {
2449                         g_warning("imap_cmd_select(): invalid RECENT line.\n");
2450                         THROW;
2451                 }
2452         }
2453
2454         resp_str = search_array_contain_str(argbuf, "UIDVALIDITY");
2455         if (resp_str) {
2456                 if (sscanf(resp_str, "OK [UIDVALIDITY %u] ", uid_validity)
2457                     != 1) {
2458                         g_warning("imap_cmd_select(): invalid UIDVALIDITY line.\n");
2459                         THROW;
2460                 }
2461         }
2462
2463         resp_str = search_array_contain_str(argbuf, "UNSEEN");
2464         if (resp_str) {
2465                 if (sscanf(resp_str, "OK [UNSEEN %d] ", unseen) != 1) {
2466                         g_warning("imap_cmd_select(): invalid UNSEEN line.\n");
2467                         THROW;
2468                 }
2469         }
2470
2471 catch:
2472         ptr_array_free_strings(argbuf);
2473         g_ptr_array_free(argbuf, TRUE);
2474
2475         return ok;
2476 }
2477
2478 static gint imap_cmd_select(SockInfo *sock, const gchar *folder,
2479                             gint *exists, gint *recent, gint *unseen,
2480                             guint32 *uid_validity)
2481 {
2482         return imap_cmd_do_select(sock, folder, FALSE,
2483                                   exists, recent, unseen, uid_validity);
2484 }
2485
2486 static gint imap_cmd_examine(SockInfo *sock, const gchar *folder,
2487                              gint *exists, gint *recent, gint *unseen,
2488                              guint32 *uid_validity)
2489 {
2490         return imap_cmd_do_select(sock, folder, TRUE,
2491                                   exists, recent, unseen, uid_validity);
2492 }
2493
2494 #undef THROW
2495
2496 static gint imap_cmd_create(SockInfo *sock, const gchar *folder)
2497 {
2498         gchar *folder_;
2499
2500         QUOTE_IF_REQUIRED(folder_, folder);
2501         imap_cmd_gen_send(sock, "CREATE %s", folder_);
2502
2503         return imap_cmd_ok(sock, NULL);
2504 }
2505
2506 static gint imap_cmd_rename(SockInfo *sock, const gchar *old_folder,
2507                             const gchar *new_folder)
2508 {
2509         gchar *old_folder_, *new_folder_;
2510
2511         QUOTE_IF_REQUIRED(old_folder_, old_folder);
2512         QUOTE_IF_REQUIRED(new_folder_, new_folder);
2513         imap_cmd_gen_send(sock, "RENAME %s %s", old_folder_, new_folder_);
2514
2515         return imap_cmd_ok(sock, NULL);
2516 }
2517
2518 static gint imap_cmd_delete(SockInfo *sock, const gchar *folder)
2519 {
2520         gchar *folder_;
2521
2522         QUOTE_IF_REQUIRED(folder_, folder);
2523         imap_cmd_gen_send(sock, "DELETE %s", folder_);
2524
2525         return imap_cmd_ok(sock, NULL);
2526 }
2527
2528 static gint imap_cmd_fetch(SockInfo *sock, guint32 uid, const gchar *filename)
2529 {
2530         gint ok;
2531         gchar buf[IMAPBUFSIZE];
2532         gchar *cur_pos;
2533         gchar size_str[32];
2534         glong size_num;
2535
2536         g_return_val_if_fail(filename != NULL, IMAP_ERROR);
2537
2538         imap_cmd_gen_send(sock, "UID FETCH %d BODY[]", uid);
2539
2540         while ((ok = imap_cmd_gen_recv(sock, buf, sizeof(buf)))
2541                == IMAP_SUCCESS) {
2542                 if (buf[0] != '*' || buf[1] != ' ')
2543                         return IMAP_ERROR;
2544                 if (strstr(buf, "FETCH") != NULL)
2545                         break;
2546         }
2547         if (ok != IMAP_SUCCESS)
2548                 return ok;
2549
2550         cur_pos = strchr(buf, '{');
2551         g_return_val_if_fail(cur_pos != NULL, IMAP_ERROR);
2552         cur_pos = strchr_cpy(cur_pos + 1, '}', size_str, sizeof(size_str));
2553         g_return_val_if_fail(cur_pos != NULL, IMAP_ERROR);
2554         size_num = atol(size_str);
2555
2556         if (*cur_pos != '\0') return IMAP_ERROR;
2557
2558         if (recv_bytes_write_to_file(sock, size_num, filename) != 0)
2559                 return IMAP_ERROR;
2560
2561         if (imap_cmd_gen_recv(sock, buf, sizeof(buf)) != IMAP_SUCCESS)
2562                 return IMAP_ERROR;
2563
2564         if (buf[0] == '\0' || buf[strlen(buf) - 1] != ')')
2565                 return IMAP_ERROR;
2566
2567         ok = imap_cmd_ok(sock, NULL);
2568
2569         return ok;
2570 }
2571
2572 static gint imap_cmd_append(SockInfo *sock, const gchar *destfolder,
2573                             const gchar *file)
2574 {
2575         gint ok;
2576         gint size;
2577         gchar *destfolder_;
2578         gchar buf[BUFFSIZE];
2579         FILE *fp;
2580
2581         g_return_val_if_fail(file != NULL, IMAP_ERROR);
2582
2583         size = get_file_size_as_crlf(file);
2584         if ((fp = fopen(file, "rb")) == NULL) {
2585                 FILE_OP_ERROR(file, "fopen");
2586                 return -1;
2587         }
2588         QUOTE_IF_REQUIRED(destfolder_, destfolder);
2589         imap_cmd_gen_send(sock, "APPEND %s (\\Seen) {%d}", destfolder_, size);
2590
2591         ok = imap_cmd_gen_recv(sock, buf, sizeof(buf));
2592         if (ok != IMAP_SUCCESS || buf[0] != '+' || buf[1] != ' ') {
2593                 log_warning(_("can't append %s to %s\n"), file, destfolder_);
2594                 fclose(fp);
2595                 return IMAP_ERROR;
2596         }
2597
2598         log_print("IMAP4> %s\n", _("(sending file...)"));
2599
2600         while (fgets(buf, sizeof(buf), fp) != NULL) {
2601                 strretchomp(buf);
2602                 if (sock_puts(sock, buf) < 0) {
2603                         fclose(fp);
2604                         sock_close(sock);
2605                         return -1;
2606                 }
2607         }
2608
2609         if (ferror(fp)) {
2610                 FILE_OP_ERROR(file, "fgets");
2611                 fclose(fp);
2612                 sock_close(sock);
2613                 return -1;
2614         }
2615
2616         sock_puts(sock, "");
2617
2618         fclose(fp);
2619         return imap_cmd_ok(sock, NULL);
2620 }
2621
2622 static gint imap_cmd_copy(SockInfo *sock, guint32 uid, const gchar *destfolder)
2623 {
2624         gint ok;
2625         gchar *destfolder_;
2626
2627         g_return_val_if_fail(destfolder != NULL, IMAP_ERROR);
2628
2629         QUOTE_IF_REQUIRED(destfolder_, destfolder);
2630         imap_cmd_gen_send(sock, "UID COPY %d %s", uid, destfolder_);
2631
2632         ok = imap_cmd_ok(sock, NULL);
2633         if (ok != IMAP_SUCCESS) {
2634                 log_warning(_("can't copy %d to %s\n"), uid, destfolder_);
2635                 return -1;
2636         }
2637
2638         return ok;
2639 }
2640
2641 gint imap_cmd_envelope(SockInfo *sock, guint32 first_uid, guint32 last_uid)
2642 {
2643         imap_cmd_gen_send
2644                 (sock, "UID FETCH %d:%d (UID FLAGS RFC822.SIZE ENVELOPE)",
2645                  first_uid, last_uid);
2646
2647         return IMAP_SUCCESS;
2648 }
2649
2650 static gint imap_cmd_store(SockInfo *sock, guint32 first_uid, guint32 last_uid,
2651                            gchar *sub_cmd)
2652 {
2653         gint ok;
2654
2655         imap_cmd_gen_send(sock, "UID STORE %d:%d %s",
2656                           first_uid, last_uid, sub_cmd);
2657
2658         if ((ok = imap_cmd_ok(sock, NULL)) != IMAP_SUCCESS) {
2659                 log_warning(_("error while imap command: STORE %d:%d %s\n"),
2660                             first_uid, last_uid, sub_cmd);
2661                 return ok;
2662         }
2663
2664         return IMAP_SUCCESS;
2665 }
2666
2667 static gint imap_cmd_expunge(SockInfo *sock)
2668 {
2669         gint ok;
2670
2671         imap_cmd_gen_send(sock, "EXPUNGE");
2672         if ((ok = imap_cmd_ok(sock, NULL)) != IMAP_SUCCESS) {
2673                 log_warning(_("error while imap command: EXPUNGE\n"));
2674                 return ok;
2675         }
2676
2677         return IMAP_SUCCESS;
2678 }
2679
2680 static gint imap_cmd_ok(SockInfo *sock, GPtrArray *argbuf)
2681 {
2682         gint ok;
2683         gchar buf[IMAPBUFSIZE];
2684         gint cmd_num;
2685         gchar cmd_status[IMAPBUFSIZE];
2686
2687         while ((ok = imap_cmd_gen_recv(sock, buf, sizeof(buf)))
2688                == IMAP_SUCCESS) {
2689                 if (buf[0] == '*' && buf[1] == ' ') {
2690                         if (argbuf)
2691                                 g_ptr_array_add(argbuf, g_strdup(buf + 2));
2692                         continue;
2693                 }
2694
2695                 if (sscanf(buf, "%d %s", &cmd_num, cmd_status) < 2)
2696                         return IMAP_ERROR;
2697                 else if (cmd_num == imap_cmd_count &&
2698                          !strcmp(cmd_status, "OK")) {
2699                         if (argbuf)
2700                                 g_ptr_array_add(argbuf, g_strdup(buf));
2701                         return IMAP_SUCCESS;
2702                 } else
2703                         return IMAP_ERROR;
2704         }
2705
2706         return ok;
2707 }
2708
2709 static void imap_cmd_gen_send(SockInfo *sock, const gchar *format, ...)
2710 {
2711         gchar buf[IMAPBUFSIZE];
2712         gchar tmp[IMAPBUFSIZE];
2713         gchar *p;
2714         va_list args;
2715
2716         va_start(args, format);
2717         g_vsnprintf(tmp, sizeof(tmp), format, args);
2718         va_end(args);
2719
2720         imap_cmd_count++;
2721
2722         g_snprintf(buf, sizeof(buf), "%d %s\r\n", imap_cmd_count, tmp);
2723         if (!strncasecmp(tmp, "LOGIN ", 6) && (p = strchr(tmp + 6, ' '))) {
2724                 *p = '\0';
2725                 log_print("IMAP4> %d %s ********\n", imap_cmd_count, tmp);
2726         } else
2727                 log_print("IMAP4> %d %s\n", imap_cmd_count, tmp);
2728
2729         sock_write(sock, buf, strlen(buf));
2730 }
2731
2732 static gint imap_cmd_gen_recv(SockInfo *sock, gchar *buf, gint size)
2733 {
2734         if (sock_gets(sock, buf, size) == -1)
2735                 return IMAP_SOCKET;
2736
2737         strretchomp(buf);
2738
2739         log_print("IMAP4< %s\n", buf);
2740
2741         return IMAP_SUCCESS;
2742 }
2743
2744
2745 /* misc utility functions */
2746
2747 static gchar *strchr_cpy(const gchar *src, gchar ch, gchar *dest, gint len)
2748 {
2749         gchar *tmp;
2750
2751         dest[0] = '\0';
2752         tmp = strchr(src, ch);
2753         if (!tmp)
2754                 return NULL;
2755
2756         memcpy(dest, src, MIN(tmp - src, len - 1));
2757         dest[MIN(tmp - src, len - 1)] = '\0';
2758
2759         return tmp + 1;
2760 }
2761
2762 static gchar *get_quoted(const gchar *src, gchar ch, gchar *dest, gint len)
2763 {
2764         const gchar *p = src;
2765         gint n = 0;
2766
2767         g_return_val_if_fail(*p == ch, NULL);
2768
2769         *dest = '\0';
2770         p++;
2771
2772         while (*p != '\0' && *p != ch) {
2773                 if (n < len - 1) {
2774                         if (*p == '\\' && *(p + 1) != '\0')
2775                                 p++;
2776                         *dest++ = *p++;
2777                 } else
2778                         p++;
2779                 n++;
2780         }
2781
2782         *dest = '\0';
2783         return (gchar *)(*p == ch ? p + 1 : p);
2784 }
2785
2786 static gchar *search_array_starts(GPtrArray *array, const gchar *str)
2787 {
2788         gint i;
2789         size_t len;
2790
2791         g_return_val_if_fail(str != NULL, NULL);
2792         len = strlen(str);
2793         for (i = 0; i < array->len; i++) {
2794                 gchar *tmp;
2795                 tmp = g_ptr_array_index(array, i);
2796                 if (strncmp(tmp, str, len) == 0)
2797                         return tmp;
2798         }
2799         return NULL;
2800 }
2801
2802 static gchar *search_array_contain_str(GPtrArray *array, gchar *str)
2803 {
2804         gint i;
2805
2806         for (i = 0; i < array->len; i++) {
2807                 gchar *tmp;
2808
2809                 tmp = g_ptr_array_index(array, i);
2810                 if (strstr(tmp, str) != NULL)
2811                         return tmp;
2812         }
2813
2814         return NULL;
2815 }
2816
2817 static gchar *search_array_str(GPtrArray *array, gchar *str)
2818 {
2819         gint i;
2820         gint len;
2821
2822         len = strlen(str);
2823
2824         for (i = 0; i < array->len; i++) {
2825                 gchar *tmp;
2826
2827                 tmp = g_ptr_array_index(array, i);
2828                 if (!strncmp(tmp, str, len))
2829                         return tmp;
2830         }
2831
2832         return NULL;
2833 }
2834
2835 static void imap_path_separator_subst(gchar *str, gchar separator)
2836 {
2837         gchar *p;
2838         gboolean in_escape = FALSE;
2839
2840         if (!separator || separator == '/') return;
2841
2842         for (p = str; *p != '\0'; p++) {
2843                 if (*p == '/' && !in_escape)
2844                         *p = separator;
2845                 else if (*p == '&' && *(p + 1) != '-' && !in_escape)
2846                         in_escape = TRUE;
2847                 else if (*p == '-' && in_escape)
2848                         in_escape = FALSE;
2849         }
2850 }
2851
2852 static gchar *imap_modified_utf7_to_locale(const gchar *mutf7_str)
2853 {
2854 #if !HAVE_LIBJCONV
2855         return g_strdup(mutf7_str);
2856 #else
2857         static iconv_t cd = (iconv_t)-1;
2858         static gboolean iconv_ok = TRUE;
2859         GString *norm_utf7;
2860         gchar *norm_utf7_p;
2861         size_t norm_utf7_len;
2862         const gchar *p;
2863         gchar *to_str, *to_p;
2864         size_t to_len;
2865         gboolean in_escape = FALSE;
2866
2867         if (!iconv_ok) return g_strdup(mutf7_str);
2868
2869         if (cd == (iconv_t)-1) {
2870                 cd = iconv_open(conv_get_current_charset_str(), "UTF-7");
2871                 if (cd == (iconv_t)-1) {
2872                         g_warning(_("iconv cannot convert UTF-7 to %s\n"),
2873                                   conv_get_current_charset_str());
2874                         iconv_ok = FALSE;
2875                         return g_strdup(mutf7_str);
2876                 }
2877         }
2878
2879         norm_utf7 = g_string_new(NULL);
2880
2881         for (p = mutf7_str; *p != '\0'; p++) {
2882                 /* replace: '&'  -> '+',
2883                             "&-" -> '&',
2884                             escaped ','  -> '/' */
2885                 if (!in_escape && *p == '&') {
2886                         if (*(p + 1) != '-') {
2887                                 g_string_append_c(norm_utf7, '+');
2888                                 in_escape = TRUE;
2889                         } else {
2890                                 g_string_append_c(norm_utf7, '&');
2891                                 p++;
2892                         }
2893                 } else if (in_escape && *p == ',') {
2894                         g_string_append_c(norm_utf7, '/');
2895                 } else if (in_escape && *p == '-') {
2896                         g_string_append_c(norm_utf7, '-');
2897                         in_escape = FALSE;
2898                 } else {
2899                         g_string_append_c(norm_utf7, *p);
2900                 }
2901         }
2902
2903         norm_utf7_p = norm_utf7->str;
2904         norm_utf7_len = norm_utf7->len;
2905         to_len = strlen(mutf7_str) * 5;
2906         to_p = to_str = g_malloc(to_len + 1);
2907
2908         if (iconv(cd, &norm_utf7_p, &norm_utf7_len, &to_p, &to_len) == -1) {
2909                 g_warning(_("iconv cannot convert UTF-7 to %s\n"),
2910                           conv_get_current_charset_str());
2911                 g_string_free(norm_utf7, TRUE);
2912                 g_free(to_str);
2913                 return g_strdup(mutf7_str);
2914         }
2915
2916         /* second iconv() call for flushing */
2917         iconv(cd, NULL, NULL, &to_p, &to_len);
2918         g_string_free(norm_utf7, TRUE);
2919         *to_p = '\0';
2920
2921         return to_str;
2922 #endif /* !HAVE_LIBJCONV */
2923 }
2924
2925 static gchar *imap_locale_to_modified_utf7(const gchar *from)
2926 {
2927 #if !HAVE_LIBJCONV
2928         return g_strdup(from);
2929 #else
2930         static iconv_t cd = (iconv_t)-1;
2931         static gboolean iconv_ok = TRUE;
2932         gchar *norm_utf7, *norm_utf7_p;
2933         size_t from_len, norm_utf7_len;
2934         GString *to_str;
2935         gchar *from_tmp, *to, *p;
2936         gboolean in_escape = FALSE;
2937
2938         if (!iconv_ok) return g_strdup(from);
2939
2940         if (cd == (iconv_t)-1) {
2941                 cd = iconv_open("UTF-7", conv_get_current_charset_str());
2942                 if (cd == (iconv_t)-1) {
2943                         g_warning(_("iconv cannot convert %s to UTF-7\n"),
2944                                   conv_get_current_charset_str());
2945                         iconv_ok = FALSE;
2946                         return g_strdup(from);
2947                 }
2948         }
2949
2950         Xstrdup_a(from_tmp, from, return g_strdup(from));
2951         from_len = strlen(from);
2952         norm_utf7_len = from_len * 5;
2953         Xalloca(norm_utf7, norm_utf7_len + 1, return g_strdup(from));
2954         norm_utf7_p = norm_utf7;
2955
2956 #define IS_PRINT(ch) (isprint(ch) && isascii(ch))
2957
2958         while (from_len > 0) {
2959                 if (IS_PRINT(*from_tmp)) {
2960                         /* printable ascii char */
2961                         *norm_utf7_p = *from_tmp;
2962                         norm_utf7_p++;
2963                         from_tmp++;
2964                         from_len--;
2965                 } else {
2966                         size_t mblen;
2967
2968                         /* unprintable char: convert to UTF-7 */
2969                         for (mblen = 0;
2970                              !IS_PRINT(from_tmp[mblen]) && mblen < from_len;
2971                              mblen++)
2972                                 ;
2973                         from_len -= mblen;
2974                         if (iconv(cd, &from_tmp, &mblen,
2975                                   &norm_utf7_p, &norm_utf7_len) == -1) {
2976                                 g_warning(_("iconv cannot convert %s to UTF-7\n"),
2977                                           conv_get_current_charset_str());
2978                                 return g_strdup(from);
2979                         }
2980
2981                         /* second iconv() call for flushing */
2982                         iconv(cd, NULL, NULL, &norm_utf7_p, &norm_utf7_len);
2983                 }
2984         }
2985
2986 #undef IS_PRINT
2987
2988         *norm_utf7_p = '\0';
2989         to_str = g_string_new(NULL);
2990         for (p = norm_utf7; p < norm_utf7_p; p++) {
2991                 /* replace: '&' -> "&-",
2992                             '+' -> '&',
2993                             escaped '/' -> ',' */
2994                 if (!in_escape && *p == '&') {
2995                         g_string_append(to_str, "&-");
2996                 } else if (!in_escape && *p == '+') {
2997                         g_string_append_c(to_str, '&');
2998                         in_escape = TRUE;
2999                 } else if (in_escape && *p == '/') {
3000                         g_string_append_c(to_str, ',');
3001                 } else if (in_escape && *p == '-') {
3002                         in_escape = FALSE;
3003                         g_string_append_c(to_str, '-');
3004                 } else {
3005                         g_string_append_c(to_str, *p);
3006                 }
3007         }
3008
3009         if (in_escape) {
3010                 in_escape = FALSE;
3011                 g_string_append_c(to_str, '-');
3012         }
3013
3014         to = to_str->str;
3015         g_string_free(to_str, FALSE);
3016
3017         return to;
3018 #endif
3019 }
3020
3021 static gboolean imap_rename_folder_func(GNode *node, gpointer data)
3022 {
3023         FolderItem *item = node->data;
3024         gchar **paths = data;
3025         const gchar *oldpath = paths[0];
3026         const gchar *newpath = paths[1];
3027         gchar *base;
3028         gchar *new_itempath;
3029         gint oldpathlen;
3030
3031         oldpathlen = strlen(oldpath);
3032         if (strncmp(oldpath, item->path, oldpathlen) != 0) {
3033                 g_warning("path doesn't match: %s, %s\n", oldpath, item->path);
3034                 return TRUE;
3035         }
3036
3037         base = item->path + oldpathlen;
3038         while (*base == G_DIR_SEPARATOR) base++;
3039         if (*base == '\0')
3040                 new_itempath = g_strdup(newpath);
3041         else
3042                 new_itempath = g_strconcat(newpath, G_DIR_SEPARATOR_S, base,
3043                                            NULL);
3044         g_free(item->path);
3045         item->path = new_itempath;
3046
3047         return FALSE;
3048 }