sync with sylpheed 0.7.0cvs33
[claws.git] / src / imap.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2002 Hiroyuki Yamamoto
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #include "defs.h"
25
26 #include <glib.h>
27 #include <stdio.h>
28 #include <string.h>
29 #include <stdlib.h>
30 #include <dirent.h>
31 #include <unistd.h>
32 #include <ctype.h>
33 #include <time.h>
34
35 #include "intl.h"
36 #include "imap.h"
37 #include "socket.h"
38 #include "ssl.h"
39 #include "recv.h"
40 #include "procmsg.h"
41 #include "procheader.h"
42 #include "folder.h"
43 #include "statusbar.h"
44 #include "prefs_account.h"
45 #include "codeconv.h"
46 #include "utils.h"
47 #include "inputdialog.h"
48
49 #define IMAP4_PORT      143
50 #if USE_SSL
51 #define IMAPS_PORT      993
52 #endif
53
54 #define QUOTE_IF_REQUIRED(out, str) \
55 { \
56         if (*str != '"' && strchr(str, ' ')) { \
57                 gchar *__tmp; \
58                 gint len; \
59  \
60                 len = strlen(str) + 3; \
61                 Xalloca(__tmp, len, return IMAP_ERROR); \
62                 g_snprintf(__tmp, len, "\"%s\"", str); \
63                 out = __tmp; \
64         } else { \
65                 Xstrdup_a(out, str, return IMAP_ERROR); \
66         } \
67 }
68
69 static GList *session_list = NULL;
70
71 static gint imap_cmd_count = 0;
72
73 static void imap_folder_init            (Folder         *folder,
74                                          const gchar    *name,
75                                          const gchar    *path);
76
77 static IMAPSession *imap_session_get    (Folder         *folder);
78
79 static gint imap_scan_tree_recursive    (IMAPSession    *session,
80                                          FolderItem     *item,
81                                          IMAPNameSpace  *namespace);
82 static GSList *imap_parse_list          (IMAPSession    *session,
83                                          const gchar    *path);
84 static gint imap_create_trash           (Folder         *folder);
85
86 static gint imap_do_copy                (Folder         *folder,
87                                          FolderItem     *dest,
88                                          MsgInfo        *msginfo,
89                                          gboolean        remove_source);
90 static gint imap_do_copy_msgs_with_dest (Folder         *folder,
91                                          FolderItem     *dest, 
92                                          GSList         *msglist,
93                                          gboolean        remove_source);
94
95 static GSList *imap_get_uncached_messages       (IMAPSession    *session,
96                                                  FolderItem     *item,
97                                                  guint32         first_uid,
98                                                  guint32         last_uid);
99 static GSList *imap_delete_cached_messages      (GSList         *mlist,
100                                                  FolderItem     *item,
101                                                  guint32         first_uid,
102                                                  guint32         last_uid);
103 static void imap_delete_all_cached_messages     (FolderItem     *item);
104
105 #if USE_SSL
106 static SockInfo *imap_open              (const gchar    *server,
107                                          gushort         port,
108                                          gboolean        use_ssl);
109 #else
110 static SockInfo *imap_open              (const gchar    *server,
111                                          gushort         port);
112 #endif
113
114 static SockInfo *imap_open_tunnel(const gchar *server,
115                                   const gchar *tunnelcmd);
116
117 static SockInfo *imap_init_sock(SockInfo *sock);
118
119 static gint imap_set_message_flags      (IMAPSession    *session,
120                                          guint32         first_uid,
121                                          guint32         last_uid,
122                                          IMAPFlags       flag,
123                                          gboolean        is_set);
124 static gint imap_select                 (IMAPSession    *session,
125                                          IMAPFolder     *folder,
126                                          const gchar    *path,
127                                          gint           *exists,
128                                          gint           *recent,
129                                          gint           *unseen,
130                                          guint32        *uid_validity);
131 static gint imap_get_uid                (IMAPSession    *session,
132                                          gint            msgnum,
133                                          guint32        *uid);
134 static gint imap_status                 (IMAPSession    *session,
135                                          IMAPFolder     *folder,
136                                          const gchar    *path,
137                                          gint           *messages,
138                                          gint           *recent,
139                                          gint           *unseen,
140                                          guint32        *uid_validity);
141
142 static void imap_parse_namespace                (IMAPSession    *session,
143                                                  IMAPFolder     *folder);
144 static IMAPNameSpace *imap_find_namespace       (IMAPFolder     *folder,
145                                                  const gchar    *path);
146 static gchar *imap_get_real_path                (IMAPFolder     *folder,
147                                                  const gchar    *path);
148
149 static gchar *imap_parse_atom           (SockInfo       *sock,
150                                          gchar          *src,
151                                          gchar          *dest,
152                                          gint            dest_len,
153                                          GString        *str);
154 static gchar *imap_parse_one_address    (SockInfo       *sock,
155                                          gchar          *start,
156                                          gchar          *out_from_str,
157                                          gchar          *out_fromname_str,
158                                          GString        *str);
159 static gchar *imap_parse_address        (SockInfo       *sock,
160                                          gchar          *start,
161                                          gchar         **out_from_str,
162                                          gchar         **out_fromname_str,
163                                          GString        *str);
164 static MsgFlags imap_parse_flags        (const gchar    *flag_str);
165 static MsgInfo *imap_parse_envelope     (SockInfo       *sock,
166                                          GString        *line_str);
167 static gint imap_greeting               (SockInfo *sock,
168                                          gboolean *is_preauth);
169
170 /* low-level IMAP4rev1 commands */
171 static gint imap_cmd_login      (SockInfo       *sock,
172                                  const gchar    *user,
173                                  const gchar    *pass);
174 static gint imap_cmd_logout     (SockInfo       *sock);
175 static gint imap_cmd_noop       (SockInfo       *sock);
176 static gint imap_cmd_namespace  (SockInfo       *sock,
177                                  gchar         **ns_str);
178 static gint imap_cmd_list       (SockInfo       *sock,
179                                  const gchar    *ref,
180                                  const gchar    *mailbox,
181                                  GPtrArray      *argbuf);
182 static gint imap_cmd_do_select  (SockInfo       *sock,
183                                  const gchar    *folder,
184                                  gboolean        examine,
185                                  gint           *exists,
186                                  gint           *recent,
187                                  gint           *unseen,
188                                  guint32        *uid_validity);
189 static gint imap_cmd_select     (SockInfo       *sock,
190                                  const gchar    *folder,
191                                  gint           *exists,
192                                  gint           *recent,
193                                  gint           *unseen,
194                                  guint32        *uid_validity);
195 static gint imap_cmd_examine    (SockInfo       *sock,
196                                  const gchar    *folder,
197                                  gint           *exists,
198                                  gint           *recent,
199                                  gint           *unseen,
200                                  guint32        *uid_validity);
201 static gint imap_cmd_create     (SockInfo       *sock,
202                                  const gchar    *folder);
203 static gint imap_cmd_delete     (SockInfo       *sock,
204                                  const gchar    *folder);
205 static gint imap_cmd_envelope   (SockInfo       *sock,
206                                  guint32         first_uid,
207                                  guint32         last_uid);
208 #if 0
209 static gint imap_cmd_search     (SockInfo       *sock,
210                                  GSList         *numlist);
211 #endif
212 static gint imap_cmd_fetch      (SockInfo       *sock,
213                                  guint32         uid,
214                                  const gchar    *filename);
215 static gint imap_cmd_append     (SockInfo       *sock,
216                                  const gchar    *destfolder,
217                                  const gchar    *file);
218 static gint imap_cmd_copy       (SockInfo       *sock,
219                                  guint32         uid,
220                                  const gchar    *destfolder);
221 static gint imap_cmd_store      (SockInfo       *sock,
222                                  guint32         first_uid,
223                                  guint32         last_uid,
224                                  gchar          *sub_cmd);
225 static gint imap_cmd_expunge    (SockInfo       *sock);
226
227 static gint imap_cmd_ok         (SockInfo       *sock,
228                                  GPtrArray      *argbuf);
229 static void imap_cmd_gen_send   (SockInfo       *sock,
230                                  const gchar    *format, ...);
231 static gint imap_cmd_gen_recv   (SockInfo       *sock,
232                                  gchar          *buf,
233                                  gint            size);
234
235 /* misc utility functions */
236 static gchar *strchr_cpy                        (const gchar    *src,
237                                                  gchar           ch,
238                                                  gchar          *dest,
239                                                  gint            len);
240 static gchar *get_quoted                        (const gchar    *src,
241                                                  gchar           ch,
242                                                  gchar          *dest,
243                                                  gint            len);
244 static gchar *search_array_contain_str          (GPtrArray      *array,
245                                                  gchar          *str);
246 static gchar *search_array_str                  (GPtrArray      *array,
247                                                  gchar          *str);
248 static gchar *search_array_starts               (GPtrArray *array,
249                                                  const gchar *str);
250 static void imap_path_separator_subst           (gchar          *str,
251                                                  gchar           separator);
252
253
254 Folder *imap_folder_new(const gchar *name, const gchar *path)
255 {
256         Folder *folder;
257
258         folder = (Folder *)g_new0(IMAPFolder, 1);
259         imap_folder_init(folder, name, path);
260
261         return folder;
262 }
263
264 void imap_folder_destroy(IMAPFolder *folder)
265 {
266         folder_remote_folder_destroy(REMOTE_FOLDER(folder));
267 }
268
269 static void imap_folder_init(Folder *folder, const gchar *name,
270                              const gchar *path)
271 {
272         folder_remote_folder_init(folder, name, path);
273
274         folder->type = F_IMAP;
275
276         folder->get_msg_list        = imap_get_msg_list;
277         folder->fetch_msg           = imap_fetch_msg;
278         folder->add_msg             = imap_add_msg;
279         folder->move_msg            = imap_move_msg;
280         folder->move_msgs_with_dest = imap_move_msgs_with_dest;
281         folder->copy_msg            = imap_copy_msg;
282         folder->copy_msgs_with_dest = imap_copy_msgs_with_dest;
283         folder->remove_msg          = imap_remove_msg;
284         folder->remove_all_msg      = imap_remove_all_msg;
285         folder->scan                = imap_scan_folder;
286         folder->scan_tree           = imap_scan_tree;
287         folder->create_tree         = imap_create_tree;
288         folder->create_folder       = imap_create_folder;
289         folder->remove_folder       = imap_remove_folder;
290 }
291
292 static IMAPSession *imap_session_get(Folder *folder)
293 {
294         RemoteFolder *rfolder = REMOTE_FOLDER(folder);
295         gushort port;
296
297         g_return_val_if_fail(folder != NULL, NULL);
298         g_return_val_if_fail(folder->type == F_IMAP, NULL);
299         g_return_val_if_fail(folder->account != NULL, NULL);
300
301 #if USE_SSL
302         port = folder->account->set_imapport ? folder->account->imapport
303                 : folder->account->ssl_imap ? IMAPS_PORT : IMAP4_PORT;
304 #else
305         port = folder->account->set_imapport ? folder->account->imapport
306                 : IMAP4_PORT;
307 #endif
308
309         if (!rfolder->session) {
310                 rfolder->session =
311                         imap_session_new(folder->account);
312                 if (rfolder->session) {
313                         imap_parse_namespace(IMAP_SESSION(rfolder->session),
314                                              IMAP_FOLDER(folder));
315                         rfolder->session->last_access_time = time(NULL);
316                 }
317                 statusbar_pop_all();
318                 return IMAP_SESSION(rfolder->session);
319         }
320
321         /* I think the point of this code is to avoid sending a
322          * keepalive if we've used the session recently and therefore
323          * think it's still alive.  Unfortunately, most of the code
324          * does not yet check for errors on the socket, and so if the
325          * connection drops we don't notice until the timeout expires.
326          * A better solution than sending a NOOP every time would be
327          * for every command to be prepared to retry until it is
328          * successfully sent. -- mbp */
329         if (time(NULL) - rfolder->session->last_access_time < SESSION_TIMEOUT) {
330                 rfolder->session->last_access_time = time(NULL);
331                 statusbar_pop_all();
332                 return IMAP_SESSION(rfolder->session);
333         }
334
335         if (imap_cmd_noop(rfolder->session->sock) != IMAP_SUCCESS) {
336                 log_warning(_("IMAP4 connection to %s:%d has been"
337                               " disconnected. Reconnecting...\n"),
338                             folder->account->recv_server, port);
339                 session_destroy(rfolder->session);
340                 rfolder->session =
341                         imap_session_new(folder->account);
342                 if (rfolder->session)
343                         imap_parse_namespace(IMAP_SESSION(rfolder->session),
344                                              IMAP_FOLDER(folder));
345         }
346
347         if (rfolder->session)
348                 rfolder->session->last_access_time = time(NULL);
349         statusbar_pop_all();
350         return IMAP_SESSION(rfolder->session);
351 }
352
353 Session *imap_session_new(const PrefsAccount *account)
354 {
355         IMAPSession *session;
356         SockInfo *imap_sock;
357         gushort port;
358         gchar *pass;
359         gboolean is_preauth;
360
361 #ifdef USE_SSL
362         /* FIXME: IMAP over SSL only... */ 
363         gboolean use_ssl;
364
365         port = account->set_imapport ? account->imapport
366                 : account->ssl_imap ? IMAPS_PORT : IMAP4_PORT;
367         use_ssl = account->ssl_imap ? TRUE : FALSE;     
368 #else
369         port = account->set_imapport ? account->imapport
370                 : IMAP4_PORT;
371 #endif
372
373         if (account->set_tunnelcmd) {
374                 log_message(_("creating tunneled IMAP4 connection\n"));
375                 if ((imap_sock = imap_open_tunnel(account->recv_server, 
376                                                   account->tunnelcmd)) == NULL)
377                         return NULL;
378         } else {
379                 g_return_val_if_fail(account->recv_server != NULL, NULL);
380
381                 log_message(_("creating IMAP4 connection to %s:%d ...\n"),
382                             account->recv_server, port);
383                 
384 #if USE_SSL
385                 if ((imap_sock = imap_open(account->recv_server, port,
386                                            use_ssl)) == NULL)
387 #else
388                 if ((imap_sock = imap_open(account->recv_server, port)) == NULL)
389 #endif
390                         return NULL;
391         }
392
393         /* Only need to log in if the connection was not PREAUTH */
394         imap_greeting(imap_sock, &is_preauth);
395         log_message("IMAP connection is %s-authenticated\n",
396                     (is_preauth) ? "pre" : "un");
397         if (!is_preauth) {
398                 g_return_val_if_fail(account->userid != NULL, NULL);
399
400                 pass = account->passwd;
401                 if (!pass) {
402                         gchar *tmp_pass;
403                         tmp_pass = input_dialog_query_password(account->recv_server, account->userid);
404                         if (!tmp_pass)
405                                 return NULL;
406                         Xstrdup_a(pass, tmp_pass, {g_free(tmp_pass); return NULL;});
407                         g_free(tmp_pass);
408                 }
409
410                 if (imap_cmd_login(imap_sock, account->userid, pass) != IMAP_SUCCESS) {
411                         imap_cmd_logout(imap_sock);
412                         sock_close(imap_sock);
413                         return NULL;
414                 }
415         }
416
417         session = g_new(IMAPSession, 1);
418         SESSION(session)->type             = SESSION_IMAP;
419         SESSION(session)->server           = g_strdup(account->recv_server);
420         SESSION(session)->sock             = imap_sock;
421         SESSION(session)->connected        = TRUE;
422         SESSION(session)->phase            = SESSION_READY;
423         SESSION(session)->last_access_time = time(NULL);
424         SESSION(session)->data             = NULL;
425         session->mbox = NULL;
426
427         session_list = g_list_append(session_list, session);
428
429         return SESSION(session);
430 }
431
432 void imap_session_destroy(IMAPSession *session)
433 {
434         sock_close(SESSION(session)->sock);
435         SESSION(session)->sock = NULL;
436
437         g_free(session->mbox);
438
439         session_list = g_list_remove(session_list, session);
440 }
441
442 void imap_session_destroy_all(void)
443 {
444         while (session_list != NULL) {
445                 IMAPSession *session = (IMAPSession *)session_list->data;
446
447                 imap_cmd_logout(SESSION(session)->sock);
448                 imap_session_destroy(session);
449         }
450 }
451
452 #define THROW goto catch
453
454 GSList *imap_get_msg_list(Folder *folder, FolderItem *item, gboolean use_cache)
455 {
456         GSList *mlist = NULL;
457         IMAPSession *session;
458         gint ok, exists = 0, recent = 0, unseen = 0;
459         guint32 uid_validity = 0;
460         guint32 first_uid = 0, last_uid = 0, begin;
461
462         g_return_val_if_fail(folder != NULL, NULL);
463         g_return_val_if_fail(item != NULL, NULL);
464         g_return_val_if_fail(folder->type == F_IMAP, NULL);
465         g_return_val_if_fail(folder->account != NULL, NULL);
466
467         session = imap_session_get(folder);
468
469         if (!session) {
470                 mlist = procmsg_read_cache(item, FALSE);
471                 item->last_num = procmsg_get_last_num_in_cache(mlist);
472                 procmsg_set_flags(mlist, item);
473                 statusbar_pop_all();
474                 return mlist;
475         }
476
477         ok = imap_select(session, IMAP_FOLDER(folder), item->path,
478                          &exists, &recent, &unseen, &uid_validity);
479         if (ok != IMAP_SUCCESS) THROW;
480         if (exists > 0) {
481                 ok = imap_get_uid(session, 1, &first_uid);
482                 if (ok != IMAP_SUCCESS) THROW;
483                 if (1 != exists) {
484                         ok = imap_get_uid(session, exists, &last_uid);
485                         if (ok != IMAP_SUCCESS) THROW;
486                 } else
487                         last_uid = first_uid;
488         } else {
489                 imap_delete_all_cached_messages(item);
490                 statusbar_pop_all();
491                 return NULL;
492         }
493
494         if (use_cache) {
495                 guint32 cache_last;
496
497                 mlist = procmsg_read_cache(item, FALSE);
498                 procmsg_set_flags(mlist, item);
499                 cache_last = procmsg_get_last_num_in_cache(mlist);
500
501                 /* calculating the range of envelope to get */
502                 if (item->mtime != uid_validity) {
503                         /* mailbox is changed (get all) */
504                         begin = first_uid;
505                 } else if (last_uid < cache_last) {
506                         /* mailbox is changed (get all) */
507                         begin = first_uid;
508                 } else if (last_uid == cache_last) {
509                         /* mailbox unchanged (get none)*/
510                         begin = 0;
511                 } else {
512                         begin = cache_last + 1;
513                 }
514
515                 item->mtime = uid_validity;
516
517                 if (first_uid > 0 && last_uid > 0) {
518                         mlist = imap_delete_cached_messages(mlist, item,
519                                                             0, first_uid - 1);
520                         mlist = imap_delete_cached_messages(mlist, item,
521                                                             last_uid + 1,
522                                                             UINT_MAX);
523                 }
524                 if (begin > 0)
525                         mlist = imap_delete_cached_messages(mlist, item,
526                                                             begin, UINT_MAX);
527         } else {
528                 imap_delete_all_cached_messages(item);
529                 begin = first_uid;
530         }
531
532         if (begin > 0 && begin <= last_uid) {
533                 GSList *newlist;
534                 newlist = imap_get_uncached_messages(session, item,
535                                                      begin, last_uid);
536                 mlist = g_slist_concat(mlist, newlist);
537         }
538
539         item->last_num = last_uid;
540
541 catch:
542         statusbar_pop_all();
543         return mlist;
544 }
545
546 #undef THROW
547
548 gchar *imap_fetch_msg(Folder *folder, FolderItem *item, gint uid)
549 {
550         gchar *path, *filename;
551         IMAPSession *session;
552         gint ok;
553
554         g_return_val_if_fail(folder != NULL, NULL);
555         g_return_val_if_fail(item != NULL, NULL);
556
557         path = folder_item_get_path(item);
558         if (!is_dir_exist(path))
559                 make_dir_hier(path);
560         filename = g_strconcat(path, G_DIR_SEPARATOR_S, itos(uid), NULL);
561         g_free(path);
562  
563         if (is_file_exist(filename)) {
564                 debug_print(_("message %d has been already cached.\n"), uid);
565                 return filename;
566         }
567
568         session = imap_session_get(folder);
569         if (!session) {
570                 g_free(filename);
571                 return NULL;
572         }
573
574         debug_print(_("getting message %d...\n"), uid);
575         ok = imap_cmd_fetch(SESSION(session)->sock, (guint32)uid, filename);
576
577         statusbar_pop_all();
578
579         if (ok != IMAP_SUCCESS) {
580                 g_warning(_("can't fetch message %d\n"), uid);
581                 g_free(filename);
582                 return NULL;
583         }
584
585         return filename;
586 }
587
588 gint imap_add_msg(Folder *folder, FolderItem *dest, const gchar *file,
589                   gboolean remove_source)
590 {
591         IMAPSession *session;
592         gint ok;
593
594         g_return_val_if_fail(folder != NULL, -1);
595         g_return_val_if_fail(dest != NULL, -1);
596         g_return_val_if_fail(file != NULL, -1);
597
598         session = imap_session_get(folder);
599         if (!session)
600                 return -1;
601
602         ok = imap_cmd_append(SESSION(session)->sock, dest->path, file);
603         if (ok != IMAP_SUCCESS) {
604                 g_warning(_("can't append message %s\n"), file);
605                 return -1;
606         }
607
608         if (remove_source) {
609                 if (unlink(file) < 0)
610                         FILE_OP_ERROR(file, "unlink");
611         }
612
613         return 0;
614 }
615
616 static gint imap_do_copy(Folder *folder, FolderItem *dest, MsgInfo *msginfo,
617                          gboolean remove_source)
618 {
619         gchar *destdir;
620         IMAPSession *session;
621         gint ok;
622
623         g_return_val_if_fail(folder != NULL, -1);
624         g_return_val_if_fail(folder->type == F_IMAP, -1);
625         g_return_val_if_fail(dest != NULL, -1);
626         g_return_val_if_fail(msginfo != NULL, -1);
627
628         session = imap_session_get(folder);
629         if (!session) return -1;
630
631         if (msginfo->folder == dest) {
632                 g_warning(_("the src folder is identical to the dest.\n"));
633                 return -1;
634         }
635
636         destdir = imap_get_real_path(IMAP_FOLDER(folder), dest->path);
637
638         if (remove_source)
639                 debug_print(_("Moving message %s%c%d to %s ...\n"),
640                             msginfo->folder->path, G_DIR_SEPARATOR,
641                             msginfo->msgnum, destdir);
642         else
643                 debug_print(_("Copying message %s%c%d to %s ...\n"),
644                             msginfo->folder->path, G_DIR_SEPARATOR,
645                             msginfo->msgnum, destdir);
646
647         ok = imap_cmd_copy(SESSION(session)->sock, msginfo->msgnum, destdir);
648
649         if (ok == IMAP_SUCCESS && remove_source) {
650                 imap_set_message_flags(session, msginfo->msgnum, msginfo->msgnum,
651                                        IMAP_FLAG_DELETED, TRUE);
652                 ok = imap_cmd_expunge(SESSION(session)->sock);
653         }
654
655         g_free(destdir);
656         statusbar_pop_all();
657
658         if (ok == IMAP_SUCCESS)
659                 return 0;
660         else
661                 return -1;
662 }
663
664 static gint imap_do_copy_msgs_with_dest(Folder *folder, FolderItem *dest, 
665                                         GSList *msglist,
666                                         gboolean remove_source)
667 {
668         gchar *destdir;
669         GSList *cur;
670         MsgInfo *msginfo;
671         IMAPSession *session;
672         gint ok = IMAP_SUCCESS;
673
674         g_return_val_if_fail(folder != NULL, -1);
675         g_return_val_if_fail(dest != NULL, -1);
676         g_return_val_if_fail(msglist != NULL, -1);
677
678         session = imap_session_get(folder);
679         if (!session) return -1;
680
681         destdir = imap_get_real_path(IMAP_FOLDER(folder), dest->path);
682
683         for (cur = msglist; cur != NULL; cur = cur->next) {
684                 msginfo = (MsgInfo *)cur->data;
685
686                 if (msginfo->folder == dest) {
687                         g_warning(_("the src folder is identical to the dest.\n"));
688                         continue;
689                 }
690
691                 if (remove_source)
692                         debug_print(_("Moving message %s%c%d to %s ...\n"),
693                                     msginfo->folder->path, G_DIR_SEPARATOR,
694                                     msginfo->msgnum, destdir);
695                 else
696                         debug_print(_("Copying message %s%c%d to %s ...\n"),
697                                     msginfo->folder->path, G_DIR_SEPARATOR,
698                                     msginfo->msgnum, destdir);
699
700                 ok = imap_cmd_copy(SESSION(session)->sock, msginfo->msgnum,
701                                    destdir);
702
703                 if (ok == IMAP_SUCCESS && remove_source) {
704                         imap_set_message_flags
705                                 (session, msginfo->msgnum, msginfo->msgnum,
706                                  IMAP_FLAG_DELETED, TRUE);
707                 }
708         }
709
710         if (remove_source)
711                 ok = imap_cmd_expunge(SESSION(session)->sock);
712
713         g_free(destdir);
714         statusbar_pop_all();
715
716         if (ok == IMAP_SUCCESS)
717                 return 0;
718         else
719                 return -1;
720 }
721
722 gint imap_move_msg(Folder *folder, FolderItem *dest, MsgInfo *msginfo)
723 {
724         return imap_do_copy(folder, dest, msginfo, TRUE);
725 }
726
727 gint imap_move_msgs_with_dest(Folder *folder, FolderItem *dest, 
728                               GSList *msglist)
729 {
730         return imap_do_copy_msgs_with_dest(folder, dest, msglist, TRUE);
731 }
732
733 gint imap_copy_msg(Folder *folder, FolderItem *dest, MsgInfo *msginfo)
734 {
735         gchar *srcfile;
736         gint ret = 0;
737
738         g_return_val_if_fail(folder != NULL, -1);
739         g_return_val_if_fail(dest != NULL, -1);
740         g_return_val_if_fail(msginfo != NULL, -1);
741         g_return_val_if_fail(msginfo->folder != NULL, -1);
742
743         if (folder == msginfo->folder->folder)
744                 return imap_do_copy(folder, dest, msginfo, FALSE);
745
746         srcfile = procmsg_get_message_file(msginfo);
747         if (!srcfile) return -1;
748
749         ret = imap_add_msg(folder, dest, srcfile, FALSE);
750
751         g_free(srcfile);
752
753         return ret;
754 }
755
756 gint imap_copy_msgs_with_dest(Folder *folder, FolderItem *dest, 
757                               GSList *msglist)
758 {
759         MsgInfo *msginfo;
760         GSList *cur;
761         gint ret = 0;
762
763         g_return_val_if_fail(folder != NULL, -1);
764         g_return_val_if_fail(dest != NULL, -1);
765         g_return_val_if_fail(msglist != NULL, -1);
766
767         msginfo = (MsgInfo *)msglist->data;
768         if (folder == msginfo->folder->folder)
769                 return imap_do_copy_msgs_with_dest
770                         (folder, dest, msglist, FALSE);
771
772         for (cur = msglist; cur != NULL; cur = cur->next) {
773                 msginfo = (MsgInfo *)msglist->data;
774                 ret = imap_copy_msg(folder, dest, msginfo);
775                 if (ret != 0) break;
776         }
777
778         return ret;
779 }
780
781 gint imap_remove_msg(Folder *folder, FolderItem *item, gint uid)
782 {
783         gint exists, recent, unseen;
784         guint32 uid_validity;
785         gint ok;
786         IMAPSession *session;
787
788         g_return_val_if_fail(folder != NULL, -1);
789         g_return_val_if_fail(folder->type == F_IMAP, -1);
790         g_return_val_if_fail(item != NULL, -1);
791
792         session = imap_session_get(folder);
793         if (!session) return -1;
794
795         ok = imap_select(session, IMAP_FOLDER(folder), item->path,
796                          &exists, &recent, &unseen, &uid_validity);
797         statusbar_pop_all();
798         if (ok != IMAP_SUCCESS)
799                 return ok;
800
801         ok = imap_set_message_flags
802                 (IMAP_SESSION(REMOTE_FOLDER(folder)->session),
803                  (guint32)uid, (guint32)uid, IMAP_FLAG_DELETED, TRUE);
804         statusbar_pop_all();
805         if (ok != IMAP_SUCCESS) {
806                 log_warning(_("can't set deleted flags: %d\n"), uid);
807                 return ok;
808         }
809
810         ok = imap_cmd_expunge(SESSION(session)->sock);
811         statusbar_pop_all();
812         if (ok != IMAP_SUCCESS) {
813                 log_warning(_("can't expunge\n"));
814                 return ok;
815         }
816
817         return IMAP_SUCCESS;
818 }
819
820 gint imap_remove_all_msg(Folder *folder, FolderItem *item)
821 {
822         gint exists, recent, unseen;
823         guint32 uid_validity;
824         gint ok;
825         IMAPSession *session;
826
827         g_return_val_if_fail(folder != NULL, -1);
828         g_return_val_if_fail(item != NULL, -1);
829
830         session = imap_session_get(folder);
831         if (!session) return -1;
832
833         ok = imap_select(session, IMAP_FOLDER(folder), item->path,
834                          &exists, &recent, &unseen, &uid_validity);
835         statusbar_pop_all();
836         if (ok != IMAP_SUCCESS)
837                 return ok;
838         if (exists == 0)
839                 return IMAP_SUCCESS;
840
841         imap_cmd_gen_send(SESSION(session)->sock,
842                           "STORE 1:%d +FLAGS (\\Deleted)", exists);
843         ok = imap_cmd_ok(SESSION(session)->sock, NULL);
844         statusbar_pop_all();
845         if (ok != IMAP_SUCCESS) {
846                 log_warning(_("can't set deleted flags: 1:%d\n"), exists);
847                 return ok;
848         }
849
850         ok = imap_cmd_expunge(SESSION(session)->sock);
851         statusbar_pop_all();
852         if (ok != IMAP_SUCCESS) {
853                 log_warning(_("can't expunge\n"));
854                 return ok;
855         }
856
857         return IMAP_SUCCESS;
858 }
859
860 void imap_scan_folder(Folder *folder, FolderItem *item)
861 {
862         IMAPSession *session;
863         gint messages, recent, unseen;
864         guint32 uid_validity;
865         gint ok;
866
867         g_return_if_fail(folder != NULL);
868         g_return_if_fail(item != NULL);
869
870         session = imap_session_get(folder);
871         if (!session) return;
872
873         ok = imap_status(session, IMAP_FOLDER(folder), item->path,
874                          &messages, &recent, &unseen, &uid_validity);
875         statusbar_pop_all();
876         if (ok != IMAP_SUCCESS) return;
877
878         item->new = recent;
879         item->unread = unseen;
880         item->total = messages;
881         /* item->mtime = uid_validity; */
882 }
883
884 void imap_scan_tree(Folder *folder)
885 {
886         IMAPFolder *imapfolder = IMAP_FOLDER(folder);
887         FolderItem *item, *inbox;
888         IMAPSession *session;
889         IMAPNameSpace *namespace = NULL;
890         gchar *root_folder = NULL;
891
892         g_return_if_fail(folder != NULL);
893         g_return_if_fail(folder->account != NULL);
894
895         session = imap_session_get(folder);
896         if (!session) return;
897
898         if (imapfolder->namespace && imapfolder->namespace->data)
899                 namespace = (IMAPNameSpace *)imapfolder->namespace->data;
900
901         if (folder->account->imap_dir && *folder->account->imap_dir) {
902                 gchar *imap_dir;
903                 Xstrdup_a(imap_dir, folder->account->imap_dir, return);
904                 strtailchomp(imap_dir, '/');
905                 root_folder = g_strconcat
906                         (namespace && namespace->name ? namespace->name : "",
907                          imap_dir, NULL);
908                 if (namespace && namespace->separator)
909                         subst_char(root_folder, namespace->separator, '/');
910         }
911
912         if (root_folder)
913                 debug_print("IMAP root directory: %s\n", root_folder);
914
915         folder_tree_destroy(folder);
916         item = folder_item_new(folder->name, root_folder);
917         item->folder = folder;
918         folder->node = g_node_new(item);
919         g_free(root_folder);
920
921         imap_scan_tree_recursive(session, item, namespace);
922
923         if (!folder->inbox) {
924                 inbox = folder_item_new("INBOX", "INBOX");
925                 inbox->stype = F_INBOX;
926                 folder_item_append(item, inbox);
927                 folder->inbox = inbox;
928         }
929         if (!folder->trash)
930                 imap_create_trash(folder);
931 }
932
933 static gint imap_scan_tree_recursive(IMAPSession *session, FolderItem *item,
934                                      IMAPNameSpace *namespace)
935 {
936         IMAPFolder *imapfolder;
937         FolderItem *new_item;
938         GSList *item_list, *cur;
939         gchar *real_path;
940         gchar *wildcard_path;
941         gchar separator = '/';
942         gchar wildcard[3];
943
944         g_return_val_if_fail(item != NULL, -1);
945         g_return_val_if_fail(item->folder != NULL, -1);
946         g_return_val_if_fail(item->no_sub == FALSE, -1);
947
948         imapfolder = IMAP_FOLDER(item->folder);
949
950         if (namespace && namespace->separator)
951                 separator = namespace->separator;
952
953         if (item->folder->ui_func)
954                 item->folder->ui_func(item->folder, item,
955                                       item->folder->ui_func_data);
956
957         if (item->path) {
958                 wildcard[0] = separator;
959                 wildcard[1] = '%';
960                 wildcard[2] = '\0';
961                 real_path = imap_get_real_path(imapfolder, item->path);
962         } else {
963                 wildcard[0] = '%';
964                 wildcard[1] = '\0';
965                 real_path = g_strdup(namespace && namespace->name
966                                      ? namespace->name : "");
967         }
968
969         Xstrcat_a(wildcard_path, real_path, wildcard,
970                   {g_free(real_path); return IMAP_ERROR;});
971         QUOTE_IF_REQUIRED(wildcard_path, wildcard_path);
972
973         imap_cmd_gen_send(SESSION(session)->sock, "LIST \"\" %s",
974                           wildcard_path);
975
976         strtailchomp(real_path, separator);
977         item_list = imap_parse_list(session, real_path);
978         g_free(real_path);
979
980         for (cur = item_list; cur != NULL; cur = cur->next) {
981                 new_item = cur->data;
982                 if (!strcmp(new_item->path, "INBOX")) {
983                         if (!item->folder->inbox) {
984                                 new_item->stype = F_INBOX;
985                                 item->folder->inbox = new_item;
986                         } else {
987                                 folder_item_destroy(new_item);
988                                 continue;
989                         }
990                 } else if (!item->parent && !item->folder->trash) {
991                         if (!strcasecmp(g_basename(new_item->path), "Trash")) {
992                                 new_item->stype = F_TRASH;
993                                 item->folder->trash = new_item;
994                         }
995                 }
996                 folder_item_append(item, new_item);
997                 if (new_item->no_select == FALSE)
998                         imap_scan_folder(new_item->folder, new_item);
999                 if (new_item->no_sub == FALSE)
1000                         imap_scan_tree_recursive(session, new_item, namespace);
1001         }
1002
1003         return IMAP_SUCCESS;
1004 }
1005
1006 static GSList *imap_parse_list(IMAPSession *session, const gchar *path)
1007 {
1008         gchar buf[IMAPBUFSIZE];
1009         gchar flags[256];
1010         gchar separator[16];
1011         gchar *p;
1012         gchar *name;
1013         GSList *item_list = NULL;
1014         GString *str;
1015         FolderItem *new_item;
1016
1017         debug_print("getting list of %s ...\n", *path ? path : "\"\"");
1018
1019         str = g_string_new(NULL);
1020
1021         for (;;) {
1022                 if (sock_gets(SESSION(session)->sock, buf, sizeof(buf)) <= 0) {
1023                         log_warning(_("error occured while getting LIST.\n"));
1024                         break;
1025                 }
1026                 strretchomp(buf);
1027                 if (buf[0] != '*' || buf[1] != ' ') {
1028                         log_print("IMAP4< %s\n", buf);
1029                         break;
1030                 }
1031                 debug_print("IMAP4< %s\n", buf);
1032
1033                 g_string_assign(str, buf);
1034                 p = str->str + 2;
1035                 if (strncmp(p, "LIST ", 5) != 0) continue;
1036                 p += 5;
1037
1038                 if (*p != '(') continue;
1039                 p++;
1040                 p = strchr_cpy(p, ')', flags, sizeof(flags));
1041                 if (!p) continue;
1042                 while (*p == ' ') p++;
1043
1044                 p = strchr_cpy(p, ' ', separator, sizeof(separator));
1045                 if (!p) continue;
1046                 extract_quote(separator, '"');
1047                 if (!strcmp(separator, "NIL"))
1048                         separator[0] = '\0';
1049
1050                 buf[0] = '\0';
1051                 while (*p == ' ') p++;
1052                 if (*p == '{' || *p == '"')
1053                         p = imap_parse_atom(SESSION(session)->sock, p,
1054                                             buf, sizeof(buf), str);
1055                 else
1056                         strncpy2(buf, p, sizeof(buf));
1057                 strtailchomp(buf, separator[0]);
1058                 if (buf[0] == '\0') continue;
1059                 if (!strcmp(buf, path)) continue;
1060
1061                 if (separator[0] != '\0')
1062                         subst_char(buf, separator[0], '/');
1063                 name = g_basename(buf);
1064                 if (name[0] == '.') continue;
1065
1066                 new_item = folder_item_new(name, buf);
1067                 if (strcasestr(flags, "\\Noinferiors") != NULL)
1068                         new_item->no_sub = TRUE;
1069                 if (strcasestr(flags, "\\Noselect") != NULL)
1070                         new_item->no_select = TRUE;
1071
1072                 item_list = g_slist_append(item_list, new_item);
1073
1074                 debug_print("folder %s has been added.\n", buf);
1075         }
1076
1077         g_string_free(str, TRUE);
1078         statusbar_pop_all();
1079
1080         return item_list;
1081 }
1082
1083 gint imap_create_tree(Folder *folder)
1084 {
1085         FolderItem *item;
1086
1087         g_return_val_if_fail(folder != NULL, -1);
1088         g_return_val_if_fail(folder->node != NULL, -1);
1089         g_return_val_if_fail(folder->node->data != NULL, -1);
1090         g_return_val_if_fail(folder->account != NULL, -1);
1091
1092         imap_scan_tree(folder);
1093
1094         item = FOLDER_ITEM(folder->node->data);
1095
1096         if (!folder->inbox) {
1097                 FolderItem *inbox;
1098
1099                 inbox = folder_item_new("INBOX", "INBOX");
1100                 inbox->stype = F_INBOX;
1101                 folder_item_append(item, inbox);
1102                 folder->inbox = inbox;
1103         }
1104         if (!folder->trash)
1105                 imap_create_trash(folder);
1106
1107         return 0;
1108 }
1109
1110 static gint imap_create_trash(Folder *folder)
1111 {
1112         IMAPFolder *imapfolder = IMAP_FOLDER(folder);
1113         FolderItem *item;
1114         FolderItem *new_item;
1115         gchar *trash_path;
1116         gchar *imap_dir = "";
1117
1118         g_return_val_if_fail(folder != NULL, -1);
1119         g_return_val_if_fail(folder->node != NULL, -1);
1120         g_return_val_if_fail(folder->node->data != NULL, -1);
1121         g_return_val_if_fail(folder->account != NULL, -1);
1122
1123         if (folder->account->imap_dir && *folder->account->imap_dir) {
1124                 gchar *tmpdir;
1125
1126                 Xstrdup_a(tmpdir, folder->account->imap_dir, return -1);
1127                 strtailchomp(tmpdir, '/');
1128                 Xalloca(imap_dir, strlen(tmpdir) + 2, return -1);
1129                 g_snprintf(imap_dir, strlen(tmpdir) + 2, "%s%c", tmpdir, '/');
1130         }
1131
1132         if (imapfolder->namespace && imapfolder->namespace->data) {
1133                 IMAPNameSpace *namespace =
1134                         (IMAPNameSpace *)imapfolder->namespace->data;
1135
1136                 if (*namespace->name != '\0') {
1137                         gchar *name;
1138
1139                         Xstrdup_a(name, namespace->name, return -1);
1140                         subst_char(name, namespace->separator, '/');
1141                         trash_path = g_strconcat(name, imap_dir, "Trash", NULL);
1142                 } else
1143                         trash_path = g_strconcat(imap_dir, "Trash", NULL);
1144         } else
1145                 trash_path = g_strconcat(imap_dir, "Trash", NULL);
1146
1147         item = FOLDER_ITEM(folder->node->data);
1148         new_item = imap_create_folder(folder, item, trash_path);
1149
1150         if (!new_item) {
1151                 gchar *path;
1152
1153                 new_item = folder_item_new("Trash", trash_path);
1154                 folder_item_append(item, new_item);
1155
1156                 path = folder_item_get_path(new_item);
1157                 if (!is_dir_exist(path))
1158                         make_dir_hier(path);
1159                 g_free(path);
1160         } else {
1161                 g_free(new_item->name);
1162                 new_item->name = g_strdup("Trash");
1163         }
1164         new_item->stype = F_TRASH;
1165         folder->trash = new_item;
1166
1167         g_free(trash_path);
1168
1169         return 0;
1170 }
1171
1172 FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
1173                                const gchar *name)
1174 {
1175         gchar *dirpath, *imappath;
1176         IMAPSession *session;
1177         IMAPNameSpace *namespace;
1178         FolderItem *new_item;
1179         gchar *new_name;
1180         const gchar *p;
1181         gint ok;
1182
1183         g_return_val_if_fail(folder != NULL, NULL);
1184         g_return_val_if_fail(folder->account != NULL, NULL);
1185         g_return_val_if_fail(parent != NULL, NULL);
1186         g_return_val_if_fail(name != NULL, NULL);
1187
1188         session = imap_session_get(folder);
1189         if (!session) return NULL;
1190
1191         if (parent->path)
1192                 dirpath = g_strconcat(parent->path, "/", name, NULL);
1193         else if ((p = strchr(name, '/')) != NULL && *(p + 1) != '\0')
1194                 dirpath = g_strdup(name);
1195         else if (folder->account->imap_dir && *folder->account->imap_dir) {
1196                 gchar *imap_dir;
1197
1198                 Xstrdup_a(imap_dir, folder->account->imap_dir, return NULL);
1199                 strtailchomp(imap_dir, '/');
1200                 dirpath = g_strconcat(imap_dir, "/", name, NULL);
1201         } else
1202                 dirpath = g_strdup(name);
1203
1204         Xstrdup_a(imappath, dirpath, {g_free(dirpath); return NULL;});
1205         Xstrdup_a(new_name, name, {g_free(dirpath); return NULL;});
1206         namespace = imap_find_namespace(IMAP_FOLDER(folder), imappath);
1207         if (namespace && namespace->separator) {
1208                 imap_path_separator_subst(imappath, namespace->separator);
1209                 imap_path_separator_subst(new_name, namespace->separator);
1210                 strtailchomp(new_name, namespace->separator);
1211         }
1212         strtailchomp(dirpath, '/');
1213
1214         if (strcmp(name, "INBOX") != 0) {
1215                 GPtrArray *argbuf;
1216                 gint i;
1217                 gboolean exist = FALSE;
1218
1219                 argbuf = g_ptr_array_new();
1220                 ok = imap_cmd_list(SESSION(session)->sock, NULL, imappath,
1221                                    argbuf);
1222                 statusbar_pop_all();
1223                 if (ok != IMAP_SUCCESS) {
1224                         log_warning(_("can't create mailbox: LIST failed\n"));
1225                         g_free(dirpath);
1226                         g_ptr_array_free(argbuf, TRUE);
1227                         return NULL;
1228                 }
1229
1230                 for (i = 0; i < argbuf->len; i++) {
1231                         gchar *str;
1232                         str = g_ptr_array_index(argbuf, i);
1233                         if (!strncmp(str, "LIST ", 5)) {
1234                                 exist = TRUE;
1235                                 break;
1236                         }
1237                 }
1238                 g_ptr_array_free(argbuf, TRUE);
1239
1240                 if (!exist) {
1241                         ok = imap_cmd_create(SESSION(session)->sock, imappath);
1242                         statusbar_pop_all();
1243                         if (ok != IMAP_SUCCESS) {
1244                                 log_warning(_("can't create mailbox\n"));
1245                                 g_free(dirpath);
1246                                 return NULL;
1247                         }
1248                 }
1249         }
1250
1251         new_item = folder_item_new(new_name, dirpath);
1252         folder_item_append(parent, new_item);
1253         g_free(dirpath);
1254
1255         dirpath = folder_item_get_path(new_item);
1256         if (!is_dir_exist(dirpath))
1257                 make_dir_hier(dirpath);
1258         g_free(dirpath);
1259
1260         return new_item;
1261 }
1262
1263 gint imap_remove_folder(Folder *folder, FolderItem *item)
1264 {
1265         gint ok;
1266         IMAPSession *session;
1267         gchar *path;
1268         gint exists, recent, unseen;
1269         guint32 uid_validity;
1270
1271         g_return_val_if_fail(folder != NULL, -1);
1272         g_return_val_if_fail(item != NULL, -1);
1273         g_return_val_if_fail(item->path != NULL, -1);
1274
1275         session = imap_session_get(folder);
1276         if (!session) return -1;
1277
1278         path = imap_get_real_path(IMAP_FOLDER(folder), item->path);
1279
1280         ok = imap_cmd_examine(SESSION(session)->sock, "INBOX",
1281                               &exists, &recent, &unseen, &uid_validity);
1282         statusbar_pop_all();
1283         if (ok != IMAP_SUCCESS) {
1284                 g_free(path);
1285                 return -1;
1286         }
1287
1288         ok = imap_cmd_delete(SESSION(session)->sock, path);
1289         statusbar_pop_all();
1290         if (ok != IMAP_SUCCESS) {
1291                 log_warning(_("can't delete mailbox\n"));
1292                 g_free(path);
1293                 return -1;
1294         }
1295
1296         g_free(path);
1297         folder_item_remove(item);
1298
1299         return 0;
1300 }
1301
1302 static GSList *imap_get_uncached_messages(IMAPSession *session,
1303                                           FolderItem *item,
1304                                           guint32 first_uid, guint32 last_uid)
1305 {
1306         gchar *tmp;
1307         GSList *newlist = NULL;
1308         GSList *llast = NULL;
1309         GString *str;
1310         MsgInfo *msginfo;
1311
1312         g_return_val_if_fail(session != NULL, NULL);
1313         g_return_val_if_fail(item != NULL, NULL);
1314         g_return_val_if_fail(item->folder != NULL, NULL);
1315         g_return_val_if_fail(item->folder->type == F_IMAP, NULL);
1316         g_return_val_if_fail(first_uid <= last_uid, NULL);
1317
1318         if (imap_cmd_envelope(SESSION(session)->sock, first_uid, last_uid)
1319             != IMAP_SUCCESS) {
1320                 log_warning(_("can't get envelope\n"));
1321                 return NULL;
1322         }
1323
1324         str = g_string_new(NULL);
1325
1326         for (;;) {
1327                 if ((tmp = sock_getline(SESSION(session)->sock)) == NULL) {
1328                         log_warning(_("error occurred while getting envelope.\n"));
1329                         g_string_free(str, TRUE);
1330                         return newlist;
1331                 }
1332                 strretchomp(tmp);
1333                 log_print("IMAP4< %s\n", tmp);
1334                 if (tmp[0] != '*' || tmp[1] != ' ') {
1335                         g_free(tmp);
1336                         break;
1337                 }
1338                 g_string_assign(str, tmp);
1339                 g_free(tmp);
1340
1341                 msginfo = imap_parse_envelope(SESSION(session)->sock, str);
1342                 if (!msginfo) {
1343                         log_warning(_("can't parse envelope: %s\n"), str->str);
1344                         continue;
1345                 }
1346
1347                 msginfo->folder = item;
1348
1349                 if (!newlist)
1350                         llast = newlist = g_slist_append(newlist, msginfo);
1351                 else {
1352                         llast = g_slist_append(llast, msginfo);
1353                         llast = llast->next;
1354                 }
1355         }
1356
1357         g_string_free(str, TRUE);
1358
1359         return newlist;
1360 }
1361
1362 static GSList *imap_delete_cached_messages(GSList *mlist, FolderItem *item,
1363                                            guint32 first_uid, guint32 last_uid)
1364 {
1365         GSList *cur, *next;
1366         MsgInfo *msginfo;
1367         gchar *dir;
1368
1369         g_return_val_if_fail(item != NULL, mlist);
1370         g_return_val_if_fail(item->folder != NULL, mlist);
1371         g_return_val_if_fail(item->folder->type == F_IMAP, mlist);
1372
1373         debug_print(_("Deleting cached messages %d - %d ... "),
1374                     first_uid, last_uid);
1375
1376         dir = folder_item_get_path(item);
1377         remove_numbered_files(dir, first_uid, last_uid);
1378         g_free(dir);
1379
1380         for (cur = mlist; cur != NULL; ) {
1381                 next = cur->next;
1382
1383                 msginfo = (MsgInfo *)cur->data;
1384                 if (msginfo != NULL && first_uid <= msginfo->msgnum &&
1385                     msginfo->msgnum <= last_uid) {
1386                         procmsg_msginfo_free(msginfo);
1387                         mlist = g_slist_remove(mlist, msginfo);
1388                 }
1389
1390                 cur = next;
1391         }
1392
1393         debug_print(_("done.\n"));
1394
1395         return mlist;
1396 }
1397
1398 static void imap_delete_all_cached_messages(FolderItem *item)
1399 {
1400         gchar *dir;
1401
1402         g_return_if_fail(item != NULL);
1403         g_return_if_fail(item->folder != NULL);
1404         g_return_if_fail(item->folder->type == F_IMAP);
1405
1406         debug_print(_("Deleting all cached messages... "));
1407
1408         dir = folder_item_get_path(item);
1409         remove_all_numbered_files(dir);
1410         g_free(dir);
1411
1412         debug_print(_("done.\n"));
1413 }
1414
1415
1416 static SockInfo *imap_open_tunnel(const gchar *server,
1417                            const gchar *tunnelcmd)
1418 {
1419         SockInfo *sock;
1420
1421         if ((sock = sock_connect_cmd(server, tunnelcmd)) == NULL)
1422                 return NULL;
1423
1424         return imap_init_sock(sock);
1425 }
1426
1427
1428 #if USE_SSL
1429 static SockInfo *imap_open(const gchar *server, gushort port,
1430                            gboolean use_ssl)
1431 #else
1432 static SockInfo *imap_open(const gchar *server, gushort port)
1433 #endif
1434 {
1435         SockInfo *sock;
1436
1437         if ((sock = sock_connect(server, port)) == NULL) {
1438                 log_warning(_("Can't connect to IMAP4 server: %s:%d\n"),
1439                             server, port);
1440                 return NULL;
1441         }
1442
1443 #if USE_SSL
1444         if (use_ssl && !ssl_init_socket(sock)) {
1445                 sock_close(sock);
1446                 return NULL;
1447         }
1448 #endif
1449
1450         return imap_init_sock(sock);
1451 }
1452
1453
1454 static SockInfo *imap_init_sock(SockInfo *sock)
1455 {
1456         imap_cmd_count = 0;
1457
1458         if (imap_cmd_noop(sock) != IMAP_SUCCESS) {
1459                 sock_close(sock);
1460                 return NULL;
1461         }
1462
1463         return sock;
1464 }
1465
1466
1467
1468 #define THROW goto catch
1469
1470 static void imap_parse_namespace(IMAPSession *session, IMAPFolder *folder)
1471 {
1472         gchar *ns_str;
1473         gchar *name;
1474         gchar *separator;
1475         gchar *p;
1476         IMAPNameSpace *namespace;
1477         GList *ns_list = NULL;
1478
1479         g_return_if_fail(session != NULL);
1480         g_return_if_fail(folder != NULL);
1481
1482         if (folder->namespace != NULL) return;
1483
1484         if (imap_cmd_namespace(SESSION(session)->sock, &ns_str)
1485             != IMAP_SUCCESS) {
1486                 log_warning(_("can't get namespace\n"));
1487                 return;
1488         }
1489
1490         /* get the first element */
1491         extract_one_parenthesis_with_skip_quote(ns_str, '"', '(', ')');
1492         g_strstrip(ns_str);
1493         p = ns_str;
1494
1495         while (*p != '\0') {
1496                 /* parse ("#foo" "/") */
1497
1498                 while (*p && *p != '(') p++;
1499                 if (*p == '\0') THROW;
1500                 p++;
1501
1502                 while (*p && *p != '"') p++;
1503                 if (*p == '\0') THROW;
1504                 p++;
1505                 name = p;
1506
1507                 while (*p && *p != '"') p++;
1508                 if (*p == '\0') THROW;
1509                 *p = '\0';
1510                 p++;
1511
1512                 while (*p && isspace(*p)) p++;
1513                 if (*p == '\0') THROW;
1514                 if (strncmp(p, "NIL", 3) == 0)
1515                         separator = NULL;
1516                 else if (*p == '"') {
1517                         p++;
1518                         separator = p;
1519                         while (*p && *p != '"') p++;
1520                         if (*p == '\0') THROW;
1521                         *p = '\0';
1522                         p++;
1523                 } else THROW;
1524
1525                 while (*p && *p != ')') p++;
1526                 if (*p == '\0') THROW;
1527                 p++;
1528
1529                 namespace = g_new(IMAPNameSpace, 1);
1530                 namespace->name = g_strdup(name);
1531                 namespace->separator = separator ? separator[0] : '\0';
1532                 ns_list = g_list_append(ns_list, namespace);
1533                 IMAP_FOLDER(folder)->namespace = ns_list;
1534         }
1535
1536 catch:
1537         g_free(ns_str);
1538         return;
1539 }
1540
1541 #undef THROW
1542
1543 static IMAPNameSpace *imap_find_namespace(IMAPFolder *folder,
1544                                           const gchar *path)
1545 {
1546         IMAPNameSpace *namespace = NULL;
1547         GList *ns_list;
1548         gchar *name;
1549
1550         g_return_val_if_fail(folder != NULL, NULL);
1551         g_return_val_if_fail(path != NULL, NULL);
1552
1553         ns_list = folder->namespace;
1554
1555         for (; ns_list != NULL; ns_list = ns_list->next) {
1556                 IMAPNameSpace *tmp_ns = ns_list->data;
1557
1558                 Xstrdup_a(name, tmp_ns->name, return namespace);
1559                 if (tmp_ns->separator && tmp_ns->separator != '/')
1560                         subst_char(name, tmp_ns->separator, '/');
1561                 if (strncmp(path, name, strlen(name)) == 0)
1562                         namespace = tmp_ns;
1563         }
1564
1565         return namespace;
1566 }
1567
1568 static gchar *imap_get_real_path(IMAPFolder *folder, const gchar *path)
1569 {
1570         gchar *real_path;
1571         IMAPNameSpace *namespace;
1572
1573         g_return_val_if_fail(folder != NULL, NULL);
1574         g_return_val_if_fail(path != NULL, NULL);
1575
1576         real_path = g_strdup(path);
1577         namespace = imap_find_namespace(folder, path);
1578         if (namespace && namespace->separator)
1579                 imap_path_separator_subst(real_path, namespace->separator);
1580
1581         return real_path;
1582 }
1583
1584 static gchar *imap_parse_atom(SockInfo *sock, gchar *src,
1585                               gchar *dest, gint dest_len, GString *str)
1586 {
1587         gchar *cur_pos = src;
1588
1589         g_return_val_if_fail(str != NULL, cur_pos);
1590
1591         while (*cur_pos == ' ') cur_pos++;
1592
1593         if (!strncmp(cur_pos, "NIL", 3)) {
1594                 *dest = '\0';
1595                 cur_pos += 3;
1596         } else if (*cur_pos == '\"') {
1597                 gchar *p;
1598
1599                 p = get_quoted(cur_pos, '\"', dest, dest_len);
1600                 cur_pos = p ? p : cur_pos + 2;
1601         } else if (*cur_pos == '{') {
1602                 gchar buf[32];
1603                 gint len;
1604                 gchar *nextline;
1605
1606                 cur_pos = strchr_cpy(cur_pos + 1, '}', buf, sizeof(buf));
1607                 len = atoi(buf);
1608
1609                 if ((nextline = sock_getline(sock)) == NULL)
1610                         return cur_pos;
1611                 strretchomp(nextline);
1612                 log_print("IMAP4< %s\n", nextline);
1613                 g_string_assign(str, nextline);
1614
1615                 len = MIN(len, strlen(nextline));
1616                 memcpy(dest, nextline, MIN(len, dest_len - 1));
1617                 dest[MIN(len, dest_len - 1)] = '\0';
1618                 cur_pos = str->str + len;
1619         }
1620
1621         return cur_pos;
1622 }
1623
1624 static gchar *imap_parse_one_address(SockInfo *sock, gchar *start,
1625                                      gchar *out_from_str,
1626                                      gchar *out_fromname_str,
1627                                      GString *str)
1628 {
1629         gchar buf[IMAPBUFSIZE];
1630         gchar *userid;
1631         gchar *domain;
1632         gchar *cur_pos = start;
1633
1634         cur_pos = imap_parse_atom(sock, cur_pos, buf, sizeof(buf), str);
1635         conv_unmime_header(out_fromname_str, IMAPBUFSIZE, buf, NULL);
1636
1637         cur_pos = imap_parse_atom(sock, cur_pos, buf, sizeof(buf), str);
1638
1639         cur_pos = imap_parse_atom(sock, cur_pos, buf, sizeof(buf), str);
1640         Xstrdup_a(userid, buf, return cur_pos + 1);
1641
1642         cur_pos = imap_parse_atom(sock, cur_pos, buf, sizeof(buf), str);
1643         Xstrdup_a(domain, buf, return cur_pos + 1);
1644
1645         if (out_fromname_str[0] != '\0') {
1646                 g_snprintf(out_from_str, IMAPBUFSIZE, "\"%s\" <%s@%s>",
1647                            out_fromname_str, userid, domain);
1648         } else {
1649                 g_snprintf(out_from_str, IMAPBUFSIZE, "%s@%s",
1650                            userid, domain);
1651                 strcpy(out_fromname_str, out_from_str);
1652         }
1653
1654         while (*cur_pos == ' ') cur_pos++;
1655         g_return_val_if_fail(*cur_pos == ')', NULL);
1656
1657         return cur_pos + 1;
1658 }
1659
1660 static gchar *imap_parse_address(SockInfo *sock, gchar *start,
1661                                  gchar **out_from_str,
1662                                  gchar **out_fromname_str,
1663                                  GString *str)
1664 {
1665         gchar buf[IMAPBUFSIZE];
1666         gchar name_buf[IMAPBUFSIZE];
1667         gchar *cur_pos = start;
1668         GString *addr_str;
1669
1670         if (out_from_str)     *out_from_str     = NULL;
1671         if (out_fromname_str) *out_fromname_str = NULL;
1672         buf[0] = name_buf[0] = '\0';
1673
1674         if (!strncmp(cur_pos, "NIL", 3)) {
1675                 if (out_from_str)     *out_from_str     = g_strdup("");
1676                 if (out_fromname_str) *out_fromname_str = g_strdup("");
1677                 return cur_pos + 3;
1678         }
1679
1680         g_return_val_if_fail(*cur_pos == '(', NULL);
1681         cur_pos++;
1682
1683         addr_str = g_string_new(NULL);
1684
1685         for (;;) {
1686                 gchar ch = *cur_pos++;
1687                 if (ch == ')') break;
1688                 if (ch == '(') {
1689                         cur_pos = imap_parse_one_address
1690                                 (sock, cur_pos, buf, name_buf, str);
1691                         if (!cur_pos) {
1692                                 g_string_free(addr_str, TRUE);
1693                                 return NULL;
1694                         }
1695                         if (addr_str->str[0] != '\0')
1696                                 g_string_append(addr_str, ", ");
1697                         g_string_append(addr_str, buf);
1698                 }
1699         }
1700
1701         if (out_from_str)     *out_from_str     = g_strdup(addr_str->str);
1702         if (out_fromname_str) *out_fromname_str = g_strdup(name_buf);
1703
1704         g_string_free(addr_str, TRUE);
1705
1706         return cur_pos;
1707 }
1708
1709 static MsgFlags imap_parse_flags(const gchar *flag_str)  
1710 {
1711         const gchar *p = flag_str;
1712         MsgFlags flags;
1713
1714         flags.perm_flags = MSG_UNREAD;
1715         flags.tmp_flags  = MSG_IMAP;
1716
1717         while ((p = strchr(p, '\\')) != NULL) {
1718                 p++;
1719
1720                 if (g_strncasecmp(p, "Recent", 6) == 0) {
1721                         MSG_SET_PERM_FLAGS(flags, MSG_NEW|MSG_UNREAD);
1722                 } else if (g_strncasecmp(p, "Seen", 4) == 0) {
1723                         MSG_UNSET_PERM_FLAGS(flags, MSG_NEW|MSG_UNREAD);
1724                 } else if (g_strncasecmp(p, "Deleted", 7) == 0) {
1725                         MSG_SET_PERM_FLAGS(flags, MSG_DELETED);
1726                 } else if (g_strncasecmp(p, "Flagged", 7) == 0) {
1727                         MSG_SET_PERM_FLAGS(flags, MSG_MARKED);
1728                 } else if (g_strncasecmp(p, "Answered", 8) == 0) {
1729                         MSG_SET_PERM_FLAGS(flags, MSG_REPLIED);
1730                 }
1731         }
1732
1733         return flags;
1734 }
1735
1736 static MsgInfo *imap_parse_envelope(SockInfo *sock, GString *line_str)
1737 {
1738         MsgInfo *msginfo;
1739         gchar buf[IMAPBUFSIZE];
1740         gchar tmp[IMAPBUFSIZE];
1741         gchar *cur_pos;
1742         gint msgnum;
1743         guint32 uid = 0;
1744         size_t size = 0;
1745         gchar *date = NULL;
1746         time_t date_t = 0;
1747         gchar *subject = NULL;
1748         gchar *tmp_from;
1749         gchar *tmp_fromname;
1750         gchar *from = NULL;
1751         gchar *fromname = NULL;
1752         gchar *tmp_to;
1753         gchar *to = NULL;
1754         gchar *inreplyto = NULL;
1755         gchar *msgid = NULL;
1756         MsgFlags flags = {0, 0};
1757
1758         g_return_val_if_fail(line_str != NULL, NULL);
1759         g_return_val_if_fail(line_str->str[0] == '*' &&
1760                              line_str->str[1] == ' ', NULL);
1761
1762         cur_pos = line_str->str + 2;
1763
1764 #define PARSE_ONE_ELEMENT(ch) \
1765 { \
1766         cur_pos = strchr_cpy(cur_pos, ch, buf, sizeof(buf)); \
1767         g_return_val_if_fail(cur_pos != NULL, NULL); \
1768 }
1769
1770         PARSE_ONE_ELEMENT(' ');
1771         msgnum = atoi(buf);
1772
1773         PARSE_ONE_ELEMENT(' ');
1774         g_return_val_if_fail(!strcmp(buf, "FETCH"), NULL);
1775
1776         g_return_val_if_fail(*cur_pos == '(', NULL);
1777         cur_pos++;
1778
1779         while (*cur_pos != '\0' && *cur_pos != ')') {
1780                 while (*cur_pos == ' ') cur_pos++;
1781
1782                 if (!strncmp(cur_pos, "UID ", 4)) {
1783                         cur_pos += 4;
1784                         uid = strtoul(cur_pos, &cur_pos, 10);
1785                 } else if (!strncmp(cur_pos, "FLAGS ", 6)) {
1786                         cur_pos += 6;
1787                         g_return_val_if_fail(*cur_pos == '(', NULL);
1788                         cur_pos++;
1789                         PARSE_ONE_ELEMENT(')');
1790                         flags = imap_parse_flags(buf);
1791                 } else if (!strncmp(cur_pos, "RFC822.SIZE ", 12)) {
1792                         cur_pos += 12;
1793                         size = strtol(cur_pos, &cur_pos, 10);
1794                 } else if (!strncmp(cur_pos, "ENVELOPE ", 9)) {
1795                         cur_pos += 9;
1796                         g_return_val_if_fail(*cur_pos == '(', NULL);
1797                         cur_pos = imap_parse_atom
1798                                 (sock, cur_pos + 1, buf, sizeof(buf), line_str);
1799                         Xstrdup_a(date, buf, return NULL);
1800                         date_t = procheader_date_parse(NULL, date, 0);
1801
1802                         cur_pos = imap_parse_atom
1803                                 (sock, cur_pos, buf, sizeof(buf), line_str);
1804                         if (buf[0] != '\0') {
1805                                 conv_unmime_header(tmp, sizeof(tmp), buf, NULL);
1806                                 Xstrdup_a(subject, tmp, return NULL);
1807                         }
1808
1809                         g_return_val_if_fail(*cur_pos == ' ', NULL);
1810                         cur_pos = imap_parse_address(sock, cur_pos + 1,
1811                                                      &tmp_from, &tmp_fromname,
1812                                                      line_str);
1813                         g_return_val_if_fail(cur_pos != NULL, NULL);
1814                         Xstrdup_a(from, tmp_from,
1815                                   {g_free(tmp_from); g_free(tmp_fromname);
1816                                    return NULL;});
1817                         Xstrdup_a(fromname, tmp_fromname,
1818                                   {g_free(tmp_from); g_free(tmp_fromname);
1819                                    return NULL;});
1820                         g_free(tmp_from);
1821                         g_free(tmp_fromname);
1822
1823 #define SKIP_ONE_ELEMENT() \
1824 { \
1825         g_return_val_if_fail(*cur_pos == ' ', NULL); \
1826         cur_pos = imap_parse_address(sock, cur_pos + 1, NULL, NULL, \
1827                                      line_str); \
1828         g_return_val_if_fail(cur_pos != NULL, NULL); \
1829 }
1830
1831                         /* skip sender and reply-to */
1832                         SKIP_ONE_ELEMENT();
1833                         SKIP_ONE_ELEMENT();
1834
1835                         g_return_val_if_fail(*cur_pos == ' ', NULL);
1836                         cur_pos = imap_parse_address(sock, cur_pos + 1,
1837                                                      &tmp_to, NULL, line_str);
1838                         g_return_val_if_fail(cur_pos != NULL, NULL);
1839                         Xstrdup_a(to, tmp_to, {g_free(tmp_to); return NULL;});
1840                         g_free(tmp_to);
1841
1842                         /* skip Cc and Bcc */
1843                         SKIP_ONE_ELEMENT();
1844                         SKIP_ONE_ELEMENT();
1845
1846 #undef SKIP_ONE_ELEMENT
1847
1848                         g_return_val_if_fail(*cur_pos == ' ', NULL);
1849                         cur_pos = imap_parse_atom
1850                                 (sock, cur_pos, buf, sizeof(buf), line_str);
1851                         g_return_val_if_fail(cur_pos != NULL, NULL);
1852                         if (buf[0] != '\0') {
1853                                 eliminate_parenthesis(buf, '(', ')');
1854                                 extract_parenthesis(buf, '<', '>');
1855                                 remove_space(buf);
1856                                 Xstrdup_a(inreplyto, buf, return NULL);
1857                         }
1858
1859                         g_return_val_if_fail(*cur_pos == ' ', NULL);
1860                         cur_pos = imap_parse_atom
1861                                 (sock, cur_pos, buf, sizeof(buf), line_str);
1862                         g_return_val_if_fail(cur_pos != NULL, NULL);
1863                         if (buf[0] != '\0') {
1864                                 extract_parenthesis(buf, '<', '>');
1865                                 remove_space(buf);
1866                                 Xstrdup_a(msgid, buf, return NULL);
1867                         }
1868
1869                         g_return_val_if_fail(*cur_pos == ')', NULL);
1870                         cur_pos++;
1871                 } else {
1872                         g_warning("invalid FETCH response: %s\n", cur_pos);
1873                         break;
1874                 }
1875         }
1876
1877         msginfo = g_new0(MsgInfo, 1);
1878         msginfo->msgnum = uid;
1879         msginfo->size = size;
1880         msginfo->date = g_strdup(date);
1881         msginfo->date_t = date_t;
1882         msginfo->subject = g_strdup(subject);
1883         msginfo->from = g_strdup(from);
1884         msginfo->fromname = g_strdup(fromname);
1885         msginfo->to = g_strdup(to);
1886         msginfo->inreplyto = g_strdup(inreplyto);
1887         msginfo->msgid = g_strdup(msgid);
1888         msginfo->flags = flags;
1889
1890         return msginfo;
1891 }
1892
1893 gint imap_msg_set_perm_flags(MsgInfo *msginfo, MsgPermFlags flags)
1894 {
1895         Folder *folder;
1896         IMAPSession *session;
1897         IMAPFlags iflags = 0;
1898         gint ok = IMAP_SUCCESS;
1899
1900         g_return_val_if_fail(msginfo != NULL, -1);
1901         g_return_val_if_fail(MSG_IS_IMAP(msginfo->flags), -1);
1902         g_return_val_if_fail(msginfo->folder != NULL, -1);
1903         g_return_val_if_fail(msginfo->folder->folder != NULL, -1);
1904
1905         folder = msginfo->folder->folder;
1906         g_return_val_if_fail(folder->type == F_IMAP, -1);
1907
1908         session = imap_session_get(folder);
1909         if (!session) return -1;
1910
1911         if (flags & MSG_MARKED)  iflags |= IMAP_FLAG_FLAGGED;
1912         if (flags & MSG_REPLIED) iflags |= IMAP_FLAG_ANSWERED;
1913         if (iflags) {
1914                 ok = imap_set_message_flags(session, msginfo->msgnum,
1915                                             msginfo->msgnum, iflags, TRUE);
1916                 if (ok != IMAP_SUCCESS) return ok;
1917         }
1918
1919         if (flags & MSG_UNREAD)
1920                 ok = imap_set_message_flags(session, msginfo->msgnum,
1921                                             msginfo->msgnum, IMAP_FLAG_SEEN,
1922                                             FALSE);
1923         return ok;
1924 }
1925
1926 gint imap_msg_unset_perm_flags(MsgInfo *msginfo, MsgPermFlags flags)
1927 {
1928         Folder *folder;
1929         IMAPSession *session;
1930         IMAPFlags iflags = 0;
1931         gint ok = IMAP_SUCCESS;
1932
1933         g_return_val_if_fail(msginfo != NULL, -1);
1934         g_return_val_if_fail(MSG_IS_IMAP(msginfo->flags), -1);
1935         g_return_val_if_fail(msginfo->folder != NULL, -1);
1936         g_return_val_if_fail(msginfo->folder->folder != NULL, -1);
1937
1938         folder = msginfo->folder->folder;
1939         g_return_val_if_fail(folder->type == F_IMAP, -1);
1940
1941         session = imap_session_get(folder);
1942         if (!session) return -1;
1943
1944         if (flags & MSG_MARKED)  iflags |= IMAP_FLAG_FLAGGED;
1945         if (flags & MSG_REPLIED) iflags |= IMAP_FLAG_ANSWERED;
1946         if (iflags) {
1947                 ok = imap_set_message_flags(session, msginfo->msgnum,
1948                                             msginfo->msgnum, iflags, FALSE);
1949                 if (ok != IMAP_SUCCESS) return ok;
1950         }
1951
1952         if (flags & MSG_UNREAD)
1953                 ok = imap_set_message_flags(session, msginfo->msgnum,
1954                                             msginfo->msgnum, IMAP_FLAG_SEEN,
1955                                             TRUE);
1956         return ok;
1957 }
1958
1959 static gint imap_set_message_flags(IMAPSession *session,
1960                                    guint32 first_uid,
1961                                    guint32 last_uid,
1962                                    IMAPFlags flags,
1963                                    gboolean is_set)
1964 {
1965         GString *buf;
1966         gint ok;
1967
1968         buf = g_string_new(is_set ? "+FLAGS (" : "-FLAGS (");
1969
1970         if (IMAP_IS_SEEN(flags))        g_string_append(buf, "\\Seen ");
1971         if (IMAP_IS_ANSWERED(flags))    g_string_append(buf, "\\Answered ");
1972         if (IMAP_IS_FLAGGED(flags))     g_string_append(buf, "\\Flagged ");
1973         if (IMAP_IS_DELETED(flags))     g_string_append(buf, "\\Deleted ");
1974         if (IMAP_IS_DRAFT(flags))       g_string_append(buf, "\\Draft");
1975
1976         if (buf->str[buf->len - 1] == ' ')
1977                 g_string_truncate(buf, buf->len - 1);
1978
1979         g_string_append_c(buf, ')');
1980
1981         ok = imap_cmd_store(SESSION(session)->sock, first_uid, last_uid,
1982                             buf->str);
1983         g_string_free(buf, TRUE);
1984
1985         return ok;
1986 }
1987
1988 static gint imap_select(IMAPSession *session, IMAPFolder *folder,
1989                         const gchar *path,
1990                         gint *exists, gint *recent, gint *unseen,
1991                         guint32 *uid_validity)
1992 {
1993         gchar *real_path;
1994         gint ok;
1995
1996         real_path = imap_get_real_path(folder, path);
1997         ok = imap_cmd_select(SESSION(session)->sock, real_path,
1998                              exists, recent, unseen, uid_validity);
1999         if (ok != IMAP_SUCCESS)
2000                 log_warning(_("can't select folder: %s\n"), real_path);
2001         g_free(real_path);
2002
2003         return ok;
2004 }
2005
2006 #define THROW(err) { ok = err; goto catch; }
2007
2008 static gint imap_get_uid(IMAPSession *session, gint msgnum, guint32 *uid)
2009 {
2010         gint ok;
2011         GPtrArray *argbuf;
2012         gchar *str;
2013         gint num;
2014
2015         *uid = 0;
2016         argbuf = g_ptr_array_new();
2017
2018         imap_cmd_gen_send(SESSION(session)->sock, "FETCH %d (UID)", msgnum);
2019         if ((ok = imap_cmd_ok(SESSION(session)->sock, argbuf)) != IMAP_SUCCESS)
2020                 THROW(ok);
2021
2022         str = search_array_contain_str(argbuf, "FETCH");
2023         if (!str) THROW(IMAP_ERROR);
2024
2025         if (sscanf(str, "%d FETCH (UID %d)", &num, uid) != 2 ||
2026             num != msgnum) {
2027                 g_warning("imap_get_uid(): invalid FETCH line.\n");
2028                 THROW(IMAP_ERROR);
2029         }
2030
2031 catch:
2032         ptr_array_free_strings(argbuf);
2033         g_ptr_array_free(argbuf, TRUE);
2034
2035         return ok;
2036 }
2037
2038 static gint imap_status(IMAPSession *session, IMAPFolder *folder,
2039                         const gchar *path,
2040                         gint *messages, gint *recent, gint *unseen,
2041                         guint32 *uid_validity)
2042 {
2043         gchar *real_path;
2044         gchar *real_path_;
2045         gint ok;
2046         GPtrArray *argbuf;
2047         gchar *str;
2048
2049         *messages = *recent = *unseen = *uid_validity = 0;
2050
2051         argbuf = g_ptr_array_new();
2052
2053         real_path = imap_get_real_path(folder, path);
2054         QUOTE_IF_REQUIRED(real_path_, real_path);
2055         imap_cmd_gen_send(SESSION(session)->sock, "STATUS %s "
2056                           "(MESSAGES RECENT UNSEEN UIDVALIDITY)", real_path_);
2057
2058         ok = imap_cmd_ok(SESSION(session)->sock, argbuf);
2059         if (ok != IMAP_SUCCESS) THROW(ok);
2060
2061         str = search_array_str(argbuf, "STATUS");
2062         if (!str) THROW(IMAP_ERROR);
2063
2064         str = strchr(str, '(');
2065         if (!str) THROW(IMAP_ERROR);
2066         str++;
2067         while (*str != '\0' && *str != ')') {
2068                 while (*str == ' ') str++;
2069
2070                 if (!strncmp(str, "MESSAGES ", 9)) {
2071                         str += 9;
2072                         *messages = strtol(str, &str, 10);
2073                 } else if (!strncmp(str, "RECENT ", 7)) {
2074                         str += 7;
2075                         *recent = strtol(str, &str, 10);
2076                 } else if (!strncmp(str, "UNSEEN ", 7)) {
2077                         str += 7;
2078                         *unseen = strtol(str, &str, 10);
2079                 } else if (!strncmp(str, "UIDVALIDITY ", 12)) {
2080                         str += 12;
2081                         *uid_validity = strtoul(str, &str, 10);
2082                 } else {
2083                         g_warning("invalid STATUS response: %s\n", str);
2084                         break;
2085                 }
2086         }
2087
2088 catch:
2089         g_free(real_path);
2090         ptr_array_free_strings(argbuf);
2091         g_ptr_array_free(argbuf, TRUE);
2092
2093         return ok;
2094 }
2095
2096 #undef THROW
2097
2098
2099 /* low-level IMAP4rev1 commands */
2100
2101 static gint imap_cmd_login(SockInfo *sock,
2102                            const gchar *user, const gchar *pass)
2103 {
2104         gchar *user_, *pass_;
2105         gint ok;
2106
2107         QUOTE_IF_REQUIRED(user_, user);
2108         QUOTE_IF_REQUIRED(pass_, pass);
2109         imap_cmd_gen_send(sock, "LOGIN %s %s", user_, pass_);
2110
2111         ok = imap_cmd_ok(sock, NULL);
2112         if (ok != IMAP_SUCCESS)
2113                 log_warning(_("IMAP4 login failed.\n"));
2114
2115         return ok;
2116 }
2117
2118 static gint imap_cmd_logout(SockInfo *sock)
2119 {
2120         imap_cmd_gen_send(sock, "LOGOUT");
2121         return imap_cmd_ok(sock, NULL);
2122 }
2123
2124 /* Send a NOOP, and examine the server's response to see whether this
2125  * connection is pre-authenticated or not. */
2126 static gint imap_greeting(SockInfo *sock, gboolean *is_preauth)
2127 {
2128         GPtrArray *argbuf;
2129         gint r;
2130
2131         imap_cmd_gen_send(sock, "NOOP");
2132         argbuf = g_ptr_array_new(); /* will hold messages sent back */
2133         r = imap_cmd_ok(sock, argbuf);
2134         *is_preauth = search_array_starts(argbuf, "PREAUTH") != NULL;
2135         
2136         return r;
2137 }
2138
2139 static gint imap_cmd_noop(SockInfo *sock)
2140 {
2141         imap_cmd_gen_send(sock, "NOOP");
2142         return imap_cmd_ok(sock, NULL);
2143 }
2144
2145 #define THROW(err) { ok = err; goto catch; }
2146
2147 static gint imap_cmd_namespace(SockInfo *sock, gchar **ns_str)
2148 {
2149         gint ok;
2150         GPtrArray *argbuf;
2151         gchar *str;
2152
2153         argbuf = g_ptr_array_new();
2154
2155         imap_cmd_gen_send(sock, "NAMESPACE");
2156         if ((ok = imap_cmd_ok(sock, argbuf)) != IMAP_SUCCESS) THROW(ok);
2157
2158         str = search_array_str(argbuf, "NAMESPACE");
2159         if (!str) THROW(IMAP_ERROR);
2160
2161         *ns_str = g_strdup(str);
2162
2163 catch:
2164         ptr_array_free_strings(argbuf);
2165         g_ptr_array_free(argbuf, TRUE);
2166
2167         return ok;
2168 }
2169
2170 #undef THROW
2171
2172 static gint imap_cmd_list(SockInfo *sock, const gchar *ref,
2173                           const gchar *mailbox, GPtrArray *argbuf)
2174 {
2175         gchar *ref_, *mailbox_;
2176
2177         if (!ref) ref = "\"\"";
2178         if (!mailbox) mailbox = "\"\"";
2179
2180         QUOTE_IF_REQUIRED(ref_, ref);
2181         QUOTE_IF_REQUIRED(mailbox_, mailbox);
2182         imap_cmd_gen_send(sock, "LIST %s %s", ref_, mailbox_);
2183
2184         return imap_cmd_ok(sock, argbuf);
2185 }
2186
2187 #define THROW goto catch
2188
2189 static gint imap_cmd_do_select(SockInfo *sock, const gchar *folder,
2190                                gboolean examine,
2191                                gint *exists, gint *recent, gint *unseen,
2192                                guint32 *uid_validity)
2193 {
2194         gint ok;
2195         gchar *resp_str;
2196         GPtrArray *argbuf;
2197         gchar *select_cmd;
2198         gchar *folder_;
2199
2200         *exists = *recent = *unseen = *uid_validity = 0;
2201         argbuf = g_ptr_array_new();
2202
2203         if (examine)
2204                 select_cmd = "EXAMINE";
2205         else
2206                 select_cmd = "SELECT";
2207
2208         QUOTE_IF_REQUIRED(folder_, folder);
2209         imap_cmd_gen_send(sock, "%s %s", select_cmd, folder_);
2210
2211         if ((ok = imap_cmd_ok(sock, argbuf)) != IMAP_SUCCESS) THROW;
2212
2213         resp_str = search_array_contain_str(argbuf, "EXISTS");
2214         if (resp_str) {
2215                 if (sscanf(resp_str,"%d EXISTS", exists) != 1) {
2216                         g_warning("imap_cmd_select(): invalid EXISTS line.\n");
2217                         THROW;
2218                 }
2219         }
2220
2221         resp_str = search_array_contain_str(argbuf, "RECENT");
2222         if (resp_str) {
2223                 if (sscanf(resp_str, "%d RECENT", recent) != 1) {
2224                         g_warning("imap_cmd_select(): invalid RECENT line.\n");
2225                         THROW;
2226                 }
2227         }
2228
2229         resp_str = search_array_contain_str(argbuf, "UIDVALIDITY");
2230         if (resp_str) {
2231                 if (sscanf(resp_str, "OK [UIDVALIDITY %u] ", uid_validity)
2232                     != 1) {
2233                         g_warning("imap_cmd_select(): invalid UIDVALIDITY line.\n");
2234                         THROW;
2235                 }
2236         }
2237
2238         resp_str = search_array_contain_str(argbuf, "UNSEEN");
2239         if (resp_str) {
2240                 if (sscanf(resp_str, "OK [UNSEEN %d] ", unseen) != 1) {
2241                         g_warning("imap_cmd_select(): invalid UNSEEN line.\n");
2242                         THROW;
2243                 }
2244         }
2245
2246 catch:
2247         ptr_array_free_strings(argbuf);
2248         g_ptr_array_free(argbuf, TRUE);
2249
2250         return ok;
2251 }
2252
2253 static gint imap_cmd_select(SockInfo *sock, const gchar *folder,
2254                             gint *exists, gint *recent, gint *unseen,
2255                             guint32 *uid_validity)
2256 {
2257         return imap_cmd_do_select(sock, folder, FALSE,
2258                                   exists, recent, unseen, uid_validity);
2259 }
2260
2261 static gint imap_cmd_examine(SockInfo *sock, const gchar *folder,
2262                              gint *exists, gint *recent, gint *unseen,
2263                              guint32 *uid_validity)
2264 {
2265         return imap_cmd_do_select(sock, folder, TRUE,
2266                                   exists, recent, unseen, uid_validity);
2267 }
2268
2269 #undef THROW
2270
2271 static gint imap_cmd_create(SockInfo *sock, const gchar *folder)
2272 {
2273         gchar *folder_;
2274
2275         QUOTE_IF_REQUIRED(folder_, folder);
2276         imap_cmd_gen_send(sock, "CREATE %s", folder_);
2277
2278         return imap_cmd_ok(sock, NULL);
2279 }
2280
2281 static gint imap_cmd_delete(SockInfo *sock, const gchar *folder)
2282 {
2283         gchar *folder_;
2284
2285         QUOTE_IF_REQUIRED(folder_, folder);
2286         imap_cmd_gen_send(sock, "DELETE %s", folder_);
2287
2288         return imap_cmd_ok(sock, NULL);
2289 }
2290
2291 static gint imap_cmd_fetch(SockInfo *sock, guint32 uid, const gchar *filename)
2292 {
2293         gint ok;
2294         gchar buf[IMAPBUFSIZE];
2295         gchar *cur_pos;
2296         gchar size_str[32];
2297         glong size_num;
2298
2299         g_return_val_if_fail(filename != NULL, IMAP_ERROR);
2300
2301         imap_cmd_gen_send(sock, "UID FETCH %d BODY[]", uid);
2302
2303         if (sock_gets(sock, buf, sizeof(buf)) < 0)
2304                 return IMAP_ERROR;
2305         strretchomp(buf);
2306         if (buf[0] != '*' || buf[1] != ' ')
2307                 return IMAP_ERROR;
2308         log_print("IMAP4< %s\n", buf);
2309
2310         cur_pos = strchr(buf, '{');
2311         g_return_val_if_fail(cur_pos != NULL, IMAP_ERROR);
2312         cur_pos = strchr_cpy(cur_pos + 1, '}', size_str, sizeof(size_str));
2313         g_return_val_if_fail(cur_pos != NULL, IMAP_ERROR);
2314         size_num = atol(size_str);
2315
2316         if (*cur_pos != '\0') return IMAP_ERROR;
2317
2318         if (recv_bytes_write_to_file(sock, size_num, filename) != 0)
2319                 return IMAP_ERROR;
2320
2321         if (imap_cmd_gen_recv(sock, buf, sizeof(buf)) != IMAP_SUCCESS)
2322                 return IMAP_ERROR;
2323
2324         if (buf[0] == '\0' || buf[strlen(buf) - 1] != ')')
2325                 return IMAP_ERROR;
2326
2327         ok = imap_cmd_ok(sock, NULL);
2328
2329         return ok;
2330 }
2331
2332 static gint imap_cmd_append(SockInfo *sock, const gchar *destfolder,
2333                             const gchar *file)
2334 {
2335         gint ok;
2336         gint size;
2337         gchar *destfolder_;
2338         gchar buf[BUFFSIZE];
2339         FILE *fp;
2340
2341         g_return_val_if_fail(file != NULL, IMAP_ERROR);
2342
2343         size = get_file_size_as_crlf(file);
2344         if ((fp = fopen(file, "r")) == NULL) {
2345                 FILE_OP_ERROR(file, "fopen");
2346                 return -1;
2347         }
2348         QUOTE_IF_REQUIRED(destfolder_, destfolder);
2349         imap_cmd_gen_send(sock, "APPEND %s (\\Seen) {%d}", destfolder_, size);
2350
2351         ok = imap_cmd_gen_recv(sock, buf, sizeof(buf));
2352         if (ok != IMAP_SUCCESS || buf[0] != '+' || buf[1] != ' ') {
2353                 log_warning(_("can't append %s to %s\n"), file, destfolder_);
2354                 fclose(fp);
2355                 return IMAP_ERROR;
2356         }
2357
2358         log_print("IMAP4> %s\n", _("(sending file...)"));
2359
2360         while (fgets(buf, sizeof(buf), fp) != NULL) {
2361                 strretchomp(buf);
2362                 if (sock_puts(sock, buf) < 0) {
2363                         fclose(fp);
2364                         sock_close(sock);
2365                         return -1;
2366                 }
2367         }
2368
2369         if (ferror(fp)) {
2370                 FILE_OP_ERROR(file, "fgets");
2371                 fclose(fp);
2372                 sock_close(sock);
2373                 return -1;
2374         }
2375
2376         sock_puts(sock, "");
2377
2378         fclose(fp);
2379         return imap_cmd_ok(sock, NULL);
2380 }
2381
2382 static gint imap_cmd_copy(SockInfo *sock, guint32 uid, const gchar *destfolder)
2383 {
2384         gint ok;
2385         gchar *destfolder_;
2386
2387         g_return_val_if_fail(destfolder != NULL, IMAP_ERROR);
2388
2389         QUOTE_IF_REQUIRED(destfolder_, destfolder);
2390         imap_cmd_gen_send(sock, "UID COPY %d %s", uid, destfolder_);
2391
2392         ok = imap_cmd_ok(sock, NULL);
2393         if (ok != IMAP_SUCCESS) {
2394                 log_warning(_("can't copy %d to %s\n"), uid, destfolder_);
2395                 return -1;
2396         }
2397
2398         return ok;
2399 }
2400
2401 gint imap_cmd_envelope(SockInfo *sock, guint32 first_uid, guint32 last_uid)
2402 {
2403         imap_cmd_gen_send
2404                 (sock, "UID FETCH %d:%d (UID FLAGS RFC822.SIZE ENVELOPE)",
2405                  first_uid, last_uid);
2406
2407         return IMAP_SUCCESS;
2408 }
2409
2410 static gint imap_cmd_store(SockInfo *sock, guint32 first_uid, guint32 last_uid,
2411                            gchar *sub_cmd)
2412 {
2413         gint ok;
2414
2415         imap_cmd_gen_send(sock, "UID STORE %d:%d %s",
2416                           first_uid, last_uid, sub_cmd);
2417
2418         if ((ok = imap_cmd_ok(sock, NULL)) != IMAP_SUCCESS) {
2419                 log_warning(_("error while imap command: STORE %d:%d %s\n"),
2420                             first_uid, last_uid, sub_cmd);
2421                 return ok;
2422         }
2423
2424         return IMAP_SUCCESS;
2425 }
2426
2427 static gint imap_cmd_expunge(SockInfo *sock)
2428 {
2429         gint ok;
2430
2431         imap_cmd_gen_send(sock, "EXPUNGE");
2432         if ((ok = imap_cmd_ok(sock, NULL)) != IMAP_SUCCESS) {
2433                 log_warning(_("error while imap command: EXPUNGE\n"));
2434                 return ok;
2435         }
2436
2437         return IMAP_SUCCESS;
2438 }
2439
2440
2441 static gint imap_cmd_ok(SockInfo *sock, GPtrArray *argbuf)
2442 {
2443         gint ok;
2444         gchar buf[IMAPBUFSIZE];
2445         gint cmd_num;
2446         gchar cmd_status[IMAPBUFSIZE];
2447
2448         while ((ok = imap_cmd_gen_recv(sock, buf, sizeof(buf)))
2449                == IMAP_SUCCESS) {
2450                 if (buf[0] == '*' && buf[1] == ' ') {
2451                         if (argbuf)
2452                                 g_ptr_array_add(argbuf, g_strdup(buf + 2));
2453                         continue;
2454                 }
2455
2456                 if (sscanf(buf, "%d %s", &cmd_num, cmd_status) < 2)
2457                         return IMAP_ERROR;
2458                 else if (cmd_num == imap_cmd_count &&
2459                          !strcmp(cmd_status, "OK")) {
2460                         if (argbuf)
2461                                 g_ptr_array_add(argbuf, g_strdup(buf));
2462                         return IMAP_SUCCESS;
2463                 } else
2464                         return IMAP_ERROR;
2465         }
2466
2467         return ok;
2468 }
2469
2470 static void imap_cmd_gen_send(SockInfo *sock, const gchar *format, ...)
2471 {
2472         gchar buf[IMAPBUFSIZE];
2473         gchar tmp[IMAPBUFSIZE];
2474         gchar *p;
2475         va_list args;
2476
2477         va_start(args, format);
2478         g_vsnprintf(tmp, sizeof(tmp), format, args);
2479         va_end(args);
2480
2481         imap_cmd_count++;
2482
2483         g_snprintf(buf, sizeof(buf), "%d %s\r\n", imap_cmd_count, tmp);
2484         if (!strncasecmp(tmp, "LOGIN ", 6) && (p = strchr(tmp + 6, ' '))) {
2485                 *p = '\0';
2486                 log_print("IMAP4> %d %s ********\n", imap_cmd_count, tmp);
2487         } else
2488                 log_print("IMAP4> %d %s\n", imap_cmd_count, tmp);
2489
2490         sock_write(sock, buf, strlen(buf));
2491 }
2492
2493 static gint imap_cmd_gen_recv(SockInfo *sock, gchar *buf, gint size)
2494 {
2495         if (sock_gets(sock, buf, size) == -1)
2496                 return IMAP_SOCKET;
2497
2498         strretchomp(buf);
2499
2500         log_print("IMAP4< %s\n", buf);
2501
2502         return IMAP_SUCCESS;
2503 }
2504
2505
2506 /* misc utility functions */
2507
2508 static gchar *strchr_cpy(const gchar *src, gchar ch, gchar *dest, gint len)
2509 {
2510         gchar *tmp;
2511
2512         dest[0] = '\0';
2513         tmp = strchr(src, ch);
2514         if (!tmp)
2515                 return NULL;
2516
2517         memcpy(dest, src, MIN(tmp - src, len - 1));
2518         dest[MIN(tmp - src, len - 1)] = '\0';
2519
2520         return tmp + 1;
2521 }
2522
2523 static gchar *get_quoted(const gchar *src, gchar ch, gchar *dest, gint len)
2524 {
2525         const gchar *p = src;
2526         gint n = 0;
2527
2528         g_return_val_if_fail(*p == ch, NULL);
2529
2530         *dest = '\0';
2531         p++;
2532
2533         while (*p != '\0' && *p != ch) {
2534                 if (n < len - 1) {
2535                         if (*p == '\\' && *(p + 1) != '\0')
2536                                 p++;
2537                         *dest++ = *p++;
2538                 } else
2539                         p++;
2540                 n++;
2541         }
2542
2543         *dest = '\0';
2544         return (gchar *)(*p == ch ? p + 1 : p);
2545 }
2546
2547 static gchar *search_array_starts(GPtrArray *array, const gchar *str)
2548 {
2549         gint i;
2550         size_t len;
2551
2552         g_return_val_if_fail(str != NULL, NULL);
2553         len = strlen(str);
2554         for (i = 0; i < array->len; i++) {
2555                 gchar *tmp;
2556                 tmp = g_ptr_array_index(array, i);
2557                 if (strncmp(tmp, str, len) == 0)
2558                         return tmp;
2559         }
2560         return NULL;
2561 }
2562
2563 static gchar *search_array_contain_str(GPtrArray *array, gchar *str)
2564 {
2565         gint i;
2566
2567         for (i = 0; i < array->len; i++) {
2568                 gchar *tmp;
2569
2570                 tmp = g_ptr_array_index(array, i);
2571                 if (strstr(tmp, str) != NULL)
2572                         return tmp;
2573         }
2574
2575         return NULL;
2576 }
2577
2578 static gchar *search_array_str(GPtrArray *array, gchar *str)
2579 {
2580         gint i;
2581         gint len;
2582
2583         len = strlen(str);
2584
2585         for (i = 0; i < array->len; i++) {
2586                 gchar *tmp;
2587
2588                 tmp = g_ptr_array_index(array, i);
2589                 if (!strncmp(tmp, str, len))
2590                         return tmp;
2591         }
2592
2593         return NULL;
2594 }
2595
2596 static void imap_path_separator_subst(gchar *str, gchar separator)
2597 {
2598         if (separator && separator != '/')
2599                 subst_char(str, '/', separator);
2600 }