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