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