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