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