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