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