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