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