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