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