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