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