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