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