clean up warnings wrt. returning values in functions that should return void
[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 gint imap_do_mark        (MsgInfo    *msginfo)
596 {
597     Folder     *folder = msginfo->folder->folder;
598     IMAPSession *session;
599
600     g_return_val_if_fail(folder != NULL, -1);
601     g_return_val_if_fail(folder->type == F_IMAP, -1);
602     g_return_val_if_fail(msginfo != NULL, -1);
603
604     session = imap_session_get(folder);
605     if (!session) return -1;
606     debug_print(_("imap_do_mark(): Message %s/%d is marked . %d\n"), msginfo->folder->path, msginfo->msgnum, folder->type);
607     imap_set_message_flags(session, msginfo->msgnum, msginfo->msgnum, IMAP_FLAG_FLAGGED, TRUE);
608 }
609
610 gint imap_do_unmark        (MsgInfo    *msginfo)
611 {
612     Folder     *folder = msginfo->folder->folder;
613     IMAPSession *session;
614  
615     g_return_val_if_fail(folder != NULL, -1);
616     g_return_val_if_fail(folder->type == F_IMAP, -1);
617     g_return_val_if_fail(msginfo != NULL, -1);
618  
619     session = imap_session_get(folder);
620     if (!session) return -1;
621     debug_print(_("imap_do_unmark(): Message %s/%d is unmarked . %d\n"), msginfo->folder->path, msginfo->msgnum, folder->type);
622     imap_set_message_flags(session, msginfo->msgnum, msginfo->msgnum, IMAP_FLAG_FLAGGED, FALSE);
623 }
624
625 gint imap_do_reply        (MsgInfo    *msginfo)
626 {
627     Folder     *folder = msginfo->folder->folder;
628     IMAPSession *session;
629  
630     g_return_val_if_fail(folder != NULL, -1);
631     g_return_val_if_fail(folder->type == F_IMAP, -1);
632     g_return_val_if_fail(msginfo != NULL, -1);
633  
634     session = imap_session_get(folder);
635     if (!session) return -1;
636     debug_print(_("imap_do_reply(): Message %s/%d is replied . %d\n"), msginfo->folder->path, msginfo->msgnum, folder->type);
637     imap_set_message_flags(session, msginfo->msgnum, msginfo->msgnum, IMAP_FLAG_ANSWERED, TRUE);
638 }
639
640 static gint imap_do_copy_msgs_with_dest(Folder *folder, FolderItem *dest, 
641                                         GSList *msglist,
642                                         gboolean remove_source)
643 {
644         gchar *destdir;
645         GSList *cur;
646         MsgInfo *msginfo;
647         IMAPSession *session;
648         gint ok;
649
650         g_return_val_if_fail(folder != NULL, -1);
651         g_return_val_if_fail(dest != NULL, -1);
652         g_return_val_if_fail(msglist != NULL, -1);
653
654         session = imap_session_get(folder);
655         if (!session) return -1;
656
657         destdir = imap_get_real_path(IMAP_FOLDER(folder), dest->path);
658
659         for (cur = msglist; cur != NULL; cur = cur->next) {
660                 msginfo = (MsgInfo *)cur->data;
661
662                 if (msginfo->folder == dest) {
663                         g_warning(_("the src folder is identical to the dest.\n"));
664                         continue;
665                 }
666
667                 if (remove_source)
668                         debug_print(_("Moving message %s%c%d to %s ...\n"),
669                                     msginfo->folder->path, G_DIR_SEPARATOR,
670                                     msginfo->msgnum, destdir);
671                 else
672                         debug_print(_("Copying message %s%c%d to %s ...\n"),
673                                     msginfo->folder->path, G_DIR_SEPARATOR,
674                                     msginfo->msgnum, destdir);
675
676                 ok = imap_cmd_copy(SESSION(session)->sock, msginfo->msgnum,
677                                    destdir);
678
679                 if (ok == IMAP_SUCCESS && remove_source) {
680                         imap_set_message_flags
681                                 (session, msginfo->msgnum, msginfo->msgnum,
682                                  IMAP_FLAG_DELETED, TRUE);
683                 }
684         }
685
686         if (remove_source)
687                 ok = imap_cmd_expunge(SESSION(session)->sock);
688
689         g_free(destdir);
690         statusbar_pop_all();
691
692         return IMAP_SUCCESS;
693 }
694
695 gint imap_move_msg(Folder *folder, FolderItem *dest, MsgInfo *msginfo)
696 {
697         return imap_do_copy(folder, dest, msginfo, TRUE);
698 }
699
700 gint imap_move_msgs_with_dest(Folder *folder, FolderItem *dest, 
701                               GSList *msglist)
702 {
703         return imap_do_copy_msgs_with_dest(folder, dest, msglist, TRUE);
704 }
705
706 gint imap_copy_msg(Folder *folder, FolderItem *dest, MsgInfo *msginfo)
707 {
708         return imap_do_copy(folder, dest, msginfo, FALSE);
709 }
710
711 gint imap_copy_msgs_with_dest(Folder *folder, FolderItem *dest, 
712                               GSList *msglist)
713 {
714         return imap_do_copy_msgs_with_dest(folder, dest, msglist, FALSE);
715 }
716
717 gint imap_remove_msg(Folder *folder, FolderItem *item, gint uid)
718 {
719         gint exists, recent, unseen;
720         guint32 uid_validity;
721         gint ok;
722         IMAPSession *session;
723
724         g_return_val_if_fail(folder != NULL, -1);
725         g_return_val_if_fail(folder->type == F_IMAP, -1);
726         g_return_val_if_fail(item != NULL, -1);
727
728         session = imap_session_get(folder);
729         if (!session) return -1;
730
731         ok = imap_select(session, IMAP_FOLDER(folder), item->path,
732                          &exists, &recent, &unseen, &uid_validity);
733         statusbar_pop_all();
734         if (ok != IMAP_SUCCESS)
735                 return ok;
736
737         ok = imap_set_message_flags
738                 (IMAP_SESSION(REMOTE_FOLDER(folder)->session),
739                  (guint32)uid, (guint32)uid, IMAP_FLAG_DELETED, TRUE);
740         statusbar_pop_all();
741         if (ok != IMAP_SUCCESS) {
742                 log_warning(_("can't set deleted flags: %d\n"), uid);
743                 return ok;
744         }
745
746         ok = imap_cmd_expunge(SESSION(session)->sock);
747         statusbar_pop_all();
748         if (ok != IMAP_SUCCESS) {
749                 log_warning(_("can't expunge\n"));
750                 return ok;
751         }
752
753         return IMAP_SUCCESS;
754 }
755
756 #define RETURN_VAL_IF_QUOTE_REQUIRED_FAIL(out, str) \
757 { \
758         if (*str != '"' && strchr(str, ' ')) { \
759                 gint len; \
760                 len = strlen(str) + 3; \
761                 Xalloca(out, len, return IMAP_ERROR); \
762                 g_snprintf(out, len, "\"%s\"", str); \
763         } else { \
764                 Xstrdup_a(out, str, return IMAP_ERROR); \
765         } \
766 }
767
768 #define RETURN_IF_QUOTE_REQUIRED_FAIL(out, str) \
769 { \
770         if (*str != '"' && strchr(str, ' ')) { \
771                 gint len; \
772                 len = strlen(str) + 3; \
773                 Xalloca(out, len, return); \
774                 g_snprintf(out, len, "\"%s\"", str); \
775         } else { \
776                 Xstrdup_a(out, str, return); \
777         } \
778 }
779
780
781 gint imap_remove_all_msg(Folder *folder, FolderItem *item)
782 {
783         gint exists, recent, unseen;
784         guint32 uid_validity;
785         gint ok;
786         IMAPSession *session;
787
788         g_return_val_if_fail(folder != NULL, -1);
789         g_return_val_if_fail(item != NULL, -1);
790
791         session = imap_session_get(folder);
792         if (!session) return -1;
793
794         ok = imap_select(session, IMAP_FOLDER(folder), item->path,
795                          &exists, &recent, &unseen, &uid_validity);
796         statusbar_pop_all();
797         if (ok != IMAP_SUCCESS)
798                 return ok;
799         if (exists == 0)
800                 return IMAP_SUCCESS;
801
802         imap_cmd_gen_send(SESSION(session)->sock,
803                           "STORE 1:%d +FLAGS (\\Deleted)", exists);
804         ok = imap_cmd_ok(SESSION(session)->sock, NULL);
805         statusbar_pop_all();
806         if (ok != IMAP_SUCCESS) {
807                 log_warning(_("can't set deleted flags: 1:%d\n"), exists);
808                 return ok;
809         }
810
811         ok = imap_cmd_expunge(SESSION(session)->sock);
812         statusbar_pop_all();
813         if (ok != IMAP_SUCCESS) {
814                 log_warning(_("can't expunge\n"));
815                 return ok;
816         }
817
818         return IMAP_SUCCESS;
819 }
820
821 void imap_scan_folder(Folder *folder, FolderItem *item)
822 {
823         IMAPSession *session;
824         gint messages, recent, unseen;
825         guint32 uid_validity;
826         gint ok;
827
828         g_return_if_fail(folder != NULL);
829         g_return_if_fail(item != NULL);
830
831         session = imap_session_get(folder);
832         if (!session) return;
833
834         ok = imap_status(session, IMAP_FOLDER(folder), item->path,
835                          &messages, &recent, &unseen, &uid_validity);
836         statusbar_pop_all();
837         if (ok != IMAP_SUCCESS) return;
838
839         item->new = recent;
840         item->unread = unseen;
841         item->total = messages;
842         /* item->mtime = uid_validity; */
843 }
844
845 void imap_scan_tree(Folder *folder)
846 {
847         IMAPFolder *imapfolder = IMAP_FOLDER(folder);
848         FolderItem *item, *inbox;
849         IMAPSession *session;
850         IMAPNameSpace *namespace = NULL;
851         gchar *root_folder = NULL;
852
853         g_return_if_fail(folder != NULL);
854         g_return_if_fail(folder->account != NULL);
855
856         session = imap_session_get(folder);
857         if (!session) return;
858
859         if (imapfolder->namespace && imapfolder->namespace->data)
860                 namespace = (IMAPNameSpace *)imapfolder->namespace->data;
861
862         if (folder->account->imap_dir && *folder->account->imap_dir) {
863                 gchar *imap_dir;
864                 Xstrdup_a(imap_dir, folder->account->imap_dir, return);
865                 strtailchomp(imap_dir, '/');
866                 root_folder = g_strconcat
867                         (namespace && namespace->name ? namespace->name : "",
868                          imap_dir, NULL);
869                 if (namespace && namespace->separator)
870                         subst_char(root_folder, namespace->separator, '/');
871         }
872
873         if (root_folder)
874                 debug_print("IMAP root directory: %s\n", root_folder);
875
876         folder_tree_destroy(folder);
877         item = folder_item_new(folder->name, root_folder);
878         item->folder = folder;
879         folder->node = g_node_new(item);
880         g_free(root_folder);
881
882         imap_scan_tree_recursive(session, item, namespace);
883
884         if (!folder->inbox) {
885                 inbox = folder_item_new("INBOX", "INBOX");
886                 inbox->stype = F_INBOX;
887                 folder_item_append(item, inbox);
888                 folder->inbox = inbox;
889         }
890         if (!folder->trash)
891                 imap_create_trash(folder);
892 }
893
894 static void imap_scan_tree_recursive(IMAPSession *session,
895                                      FolderItem *item,
896                                      IMAPNameSpace *namespace)
897 {
898         IMAPFolder *imapfolder;
899         FolderItem *new_item;
900         GSList *item_list, *cur;
901         gchar *real_path, *wildcard_path, *wildcard_path_;
902
903         g_return_if_fail(item != NULL);
904         g_return_if_fail(item->folder != NULL);
905         g_return_if_fail(item->no_sub == FALSE);
906
907         imapfolder = IMAP_FOLDER(item->folder);
908
909         if (item->folder->ui_func)
910                 item->folder->ui_func(item->folder, item,
911                                       item->folder->ui_func_data);
912
913         if (item->path) {
914                 real_path = imap_get_real_path(imapfolder, item->path);
915                 Xstrconcat_a(wildcard_path, real_path,"/%", return);
916                 RETURN_IF_QUOTE_REQUIRED_FAIL(wildcard_path_, wildcard_path);
917                 imap_cmd_gen_send(SESSION(session)->sock, "LIST \"\" %s",
918                                   wildcard_path_,
919                                   namespace && namespace->separator
920                                   ? namespace->separator : '/');
921                 g_free(wildcard_path);
922         } else {
923                 real_path = g_strdup(namespace && namespace->name
924                                      ? namespace->name : "");
925                 Xstrconcat_a(wildcard_path, real_path, "%", return);
926                 RETURN_IF_QUOTE_REQUIRED_FAIL(wildcard_path_, wildcard_path);
927                 imap_cmd_gen_send(SESSION(session)->sock, "LIST \"\" %s",
928                                   wildcard_path_);
929                 g_free(wildcard_path);
930         }
931
932         strtailchomp(real_path, namespace && namespace->separator
933                      ? namespace->separator : '/');
934
935         item_list = imap_parse_list(session, real_path);
936         for (cur = item_list; cur != NULL; cur = cur->next) {
937                 new_item = cur->data;
938                 if (!strcmp(new_item->path, "INBOX")) {
939                         if (!item->folder->inbox) {
940                                 new_item->stype = F_INBOX;
941                                 item->folder->inbox = new_item;
942                         } else {
943                                 folder_item_destroy(new_item);
944                                 continue;
945                         }
946                 } else if (!item->parent && !item->folder->trash) {
947                         if (!strcasecmp(g_basename(new_item->path), "Trash")) {
948                                 new_item->stype = F_TRASH;
949                                 item->folder->trash = new_item;
950                         }
951                 }
952                 folder_item_append(item, new_item);
953                 if (new_item->no_select == FALSE)
954                         imap_scan_folder(new_item->folder, new_item);
955                 if (new_item->no_sub == FALSE)
956                         imap_scan_tree_recursive(session, new_item, namespace);
957         }
958 }
959
960 static GSList *imap_parse_list(IMAPSession *session, const gchar *path)
961 {
962         gchar buf[IMAPBUFSIZE];
963         gchar flags[256];
964         gchar separator[16];
965         gchar *p;
966         gchar *name;
967         GSList *item_list = NULL;
968         GString *str;
969         FolderItem *new_item;
970
971         debug_print("getting list of %s ...\n", *path ? path : "\"\"");
972
973         str = g_string_new(NULL);
974
975         for (;;) {
976                 if (sock_gets(SESSION(session)->sock, buf, sizeof(buf)) <= 0) {
977                         log_warning(_("error occured while getting LIST.\n"));
978                         break;
979                 }
980                 strretchomp(buf);
981                 if (buf[0] != '*' || buf[1] != ' ') {
982                         log_print("IMAP4< %s\n", buf);
983                         break;
984                 }
985                 debug_print("IMAP4< %s\n", buf);
986
987                 g_string_assign(str, buf);
988                 p = str->str + 2;
989                 if (strncmp(p, "LIST ", 5) != 0) continue;
990                 p += 5;
991
992                 if (*p != '(') continue;
993                 p++;
994                 p = strchr_cpy(p, ')', flags, sizeof(flags));
995                 if (!p) continue;
996                 while (*p == ' ') p++;
997
998                 p = strchr_cpy(p, ' ', separator, sizeof(separator));
999                 if (!p) continue;
1000                 extract_quote(separator, '"');
1001                 if (!strcmp(separator, "NIL"))
1002                         separator[0] = '\0';
1003
1004                 buf[0] = '\0';
1005                 while (*p == ' ') p++;
1006                 if (*p == '{' || *p == '"')
1007                         p = imap_parse_atom(SESSION(session)->sock, p,
1008                                             buf, sizeof(buf), str);
1009                 else
1010                         strncpy2(buf, p, sizeof(buf));
1011                 strtailchomp(buf, separator[0]);
1012                 if (buf[0] == '\0') continue;
1013                 if (!strcmp(buf, path)) continue;
1014
1015                 if (separator[0] != '\0')
1016                         subst_char(buf, separator[0], '/');
1017                 name = g_basename(buf);
1018                 if (name[0] == '.') continue;
1019
1020                 new_item = folder_item_new(name, buf);
1021                 if (strcasestr(flags, "\\Noinferiors") != NULL)
1022                         new_item->no_sub = TRUE;
1023                 if (strcasestr(flags, "\\Noselect") != NULL)
1024                         new_item->no_select = TRUE;
1025
1026                 item_list = g_slist_append(item_list, new_item);
1027
1028                 debug_print("folder %s has been added.\n", buf);
1029         }
1030
1031         g_string_free(str, TRUE);
1032         statusbar_pop_all();
1033
1034         return item_list;
1035 }
1036
1037 gint imap_create_tree(Folder *folder)
1038 {
1039         FolderItem *item;
1040
1041         g_return_val_if_fail(folder != NULL, -1);
1042         g_return_val_if_fail(folder->node != NULL, -1);
1043         g_return_val_if_fail(folder->node->data != NULL, -1);
1044         g_return_val_if_fail(folder->account != NULL, -1);
1045
1046         imap_scan_tree(folder);
1047
1048         item = FOLDER_ITEM(folder->node->data);
1049
1050         if (!folder->inbox) {
1051                 FolderItem *inbox;
1052
1053                 inbox = folder_item_new("INBOX", "INBOX");
1054                 inbox->stype = F_INBOX;
1055                 folder_item_append(item, inbox);
1056                 folder->inbox = inbox;
1057         }
1058         if (!folder->trash)
1059                 imap_create_trash(folder);
1060
1061         return 0;
1062 }
1063
1064 static gint imap_create_trash(Folder *folder)
1065 {
1066         IMAPFolder *imapfolder = IMAP_FOLDER(folder);
1067         FolderItem *item;
1068         FolderItem *new_item;
1069         gchar *trash_path;
1070         gchar *imap_dir = "";
1071
1072         g_return_val_if_fail(folder != NULL, -1);
1073         g_return_val_if_fail(folder->node != NULL, -1);
1074         g_return_val_if_fail(folder->node->data != NULL, -1);
1075         g_return_val_if_fail(folder->account != NULL, -1);
1076
1077         if (folder->account->imap_dir && *folder->account->imap_dir) {
1078                 gchar *tmpdir;
1079
1080                 Xstrdup_a(tmpdir, folder->account->imap_dir, return -1);
1081                 strtailchomp(tmpdir, '/');
1082                 Xalloca(imap_dir, strlen(tmpdir) + 2, return -1);
1083                 g_snprintf(imap_dir, strlen(tmpdir) + 2, "%s%c", tmpdir, '/');
1084         }
1085
1086         if (imapfolder->namespace && imapfolder->namespace->data) {
1087                 IMAPNameSpace *namespace =
1088                         (IMAPNameSpace *)imapfolder->namespace->data;
1089
1090                 if (*namespace->name != '\0') {
1091                         gchar *name;
1092
1093                         Xstrdup_a(name, namespace->name, return -1);
1094                         subst_char(name, namespace->separator, '/');
1095                         trash_path = g_strconcat(name, imap_dir, "Trash", NULL);
1096                 } else
1097                         trash_path = g_strconcat(imap_dir, "Trash", NULL);
1098         } else
1099                 trash_path = g_strconcat(imap_dir, "Trash", NULL);
1100
1101         item = FOLDER_ITEM(folder->node->data);
1102         new_item = imap_create_folder(folder, item, trash_path);
1103
1104         if (!new_item) {
1105                 gchar *path;
1106
1107                 new_item = folder_item_new("Trash", trash_path);
1108                 folder_item_append(item, new_item);
1109
1110                 path = folder_item_get_path(new_item);
1111                 if (!is_dir_exist(path))
1112                         make_dir_hier(path);
1113                 g_free(path);
1114         } else {
1115                 g_free(new_item->name);
1116                 new_item->name = g_strdup("Trash");
1117         }
1118         new_item->stype = F_TRASH;
1119         folder->trash = new_item;
1120
1121         g_free(trash_path);
1122
1123         return 0;
1124 }
1125
1126 FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
1127                                const gchar *name)
1128 {
1129         gchar *dirpath, *imappath;
1130         IMAPSession *session;
1131         IMAPNameSpace *namespace;
1132         FolderItem *new_item;
1133         gchar *new_name;
1134         const gchar *p;
1135         gint ok;
1136
1137         g_return_val_if_fail(folder != NULL, NULL);
1138         g_return_val_if_fail(folder->account != NULL, NULL);
1139         g_return_val_if_fail(parent != NULL, NULL);
1140         g_return_val_if_fail(name != NULL, NULL);
1141
1142         session = imap_session_get(folder);
1143         if (!session) return NULL;
1144
1145         if (parent->path)
1146                 dirpath = g_strconcat(parent->path, "/", name, NULL);
1147         else if ((p = strchr(name, '/')) != NULL && *(p + 1) != '\0')
1148                 dirpath = g_strdup(name);
1149         else if (folder->account->imap_dir && *folder->account->imap_dir) {
1150                 gchar *imap_dir;
1151
1152                 Xstrdup_a(imap_dir, folder->account->imap_dir, return NULL);
1153                 strtailchomp(imap_dir, '/');
1154                 dirpath = g_strconcat(imap_dir, "/", name, NULL);
1155         } else
1156                 dirpath = g_strdup(name);
1157
1158         Xstrdup_a(imappath, dirpath, {g_free(dirpath); return NULL;});
1159         Xstrdup_a(new_name, name, {g_free(dirpath); return NULL;});
1160         namespace = imap_find_namespace(IMAP_FOLDER(folder), imappath);
1161         if (namespace && namespace->separator) {
1162                 imap_path_separator_subst(imappath, namespace->separator);
1163                 imap_path_separator_subst(new_name, namespace->separator);
1164                 strtailchomp(new_name, namespace->separator);
1165         }
1166         strtailchomp(dirpath, '/');
1167
1168         if (strcmp(name, "INBOX") != 0) {
1169                 GPtrArray *argbuf;
1170                 gint i;
1171                 gboolean exist = FALSE;
1172
1173                 argbuf = g_ptr_array_new();
1174                 ok = imap_cmd_list(SESSION(session)->sock, NULL, imappath,
1175                                    argbuf);
1176                 statusbar_pop_all();
1177                 if (ok != IMAP_SUCCESS) {
1178                         log_warning(_("can't create mailbox: LIST failed\n"));
1179                         g_free(dirpath);
1180                         g_ptr_array_free(argbuf, TRUE);
1181                         return NULL;
1182                 }
1183
1184                 for (i = 0; i < argbuf->len; i++) {
1185                         gchar *str;
1186                         str = g_ptr_array_index(argbuf, i);
1187                         if (!strncmp(str, "LIST ", 5)) {
1188                                 exist = TRUE;
1189                                 break;
1190                         }
1191                 }
1192                 g_ptr_array_free(argbuf, TRUE);
1193
1194                 if (!exist) {
1195                         ok = imap_cmd_create(SESSION(session)->sock, imappath);
1196                         statusbar_pop_all();
1197                         if (ok != IMAP_SUCCESS) {
1198                                 log_warning(_("can't create mailbox\n"));
1199                                 g_free(dirpath);
1200                                 return NULL;
1201                         }
1202                 }
1203         }
1204
1205         new_item = folder_item_new(new_name, dirpath);
1206         folder_item_append(parent, new_item);
1207         g_free(dirpath);
1208
1209         dirpath = folder_item_get_path(new_item);
1210         if (!is_dir_exist(dirpath))
1211                 make_dir_hier(dirpath);
1212         g_free(dirpath);
1213
1214         return new_item;
1215 }
1216
1217 gint imap_remove_folder(Folder *folder, FolderItem *item)
1218 {
1219         gint ok;
1220         IMAPSession *session;
1221         gchar *path;
1222         gint exists, recent, unseen;
1223         guint32 uid_validity;
1224
1225         g_return_val_if_fail(folder != NULL, -1);
1226         g_return_val_if_fail(item != NULL, -1);
1227         g_return_val_if_fail(item->path != NULL, -1);
1228
1229         session = imap_session_get(folder);
1230         if (!session) return -1;
1231
1232         path = imap_get_real_path(IMAP_FOLDER(folder), item->path);
1233
1234         ok = imap_cmd_examine(SESSION(session)->sock, "INBOX",
1235                               &exists, &recent, &unseen, &uid_validity);
1236         statusbar_pop_all();
1237         if (ok != IMAP_SUCCESS) {
1238                 g_free(path);
1239                 return -1;
1240         }
1241
1242         ok = imap_cmd_delete(SESSION(session)->sock, path);
1243         statusbar_pop_all();
1244         if (ok != IMAP_SUCCESS) {
1245                 log_warning(_("can't delete mailbox\n"));
1246                 g_free(path);
1247                 return -1;
1248         }
1249
1250         g_free(path);
1251         folder_item_remove(item);
1252
1253         return 0;
1254 }
1255
1256 static GSList *imap_get_uncached_messages(IMAPSession *session,
1257                                           FolderItem *item,
1258                                           guint32 first_uid, guint32 last_uid)
1259 {
1260         gchar *tmp;
1261         GSList *newlist = NULL;
1262         GSList *llast = NULL;
1263         GString *str;
1264         MsgInfo *msginfo;
1265
1266         g_return_val_if_fail(session != NULL, NULL);
1267         g_return_val_if_fail(item != NULL, NULL);
1268         g_return_val_if_fail(item->folder != NULL, NULL);
1269         g_return_val_if_fail(item->folder->type == F_IMAP, NULL);
1270         g_return_val_if_fail(first_uid <= last_uid, NULL);
1271
1272         if (imap_cmd_envelope(SESSION(session)->sock, first_uid, last_uid)
1273             != IMAP_SUCCESS) {
1274                 log_warning(_("can't get envelope\n"));
1275                 return NULL;
1276         }
1277
1278         str = g_string_new(NULL);
1279
1280         for (;;) {
1281                 if ((tmp = sock_getline(SESSION(session)->sock)) == NULL) {
1282                         log_warning(_("error occurred while getting envelope.\n"));
1283                         g_string_free(str, TRUE);
1284                         return newlist;
1285                 }
1286                 strretchomp(tmp);
1287                 log_print("IMAP4< %s\n", tmp);
1288                 if (tmp[0] != '*' || tmp[1] != ' ') {
1289                         g_free(tmp);
1290                         break;
1291                 }
1292                 g_string_assign(str, tmp);
1293                 g_free(tmp);
1294
1295                 msginfo = imap_parse_envelope(SESSION(session)->sock, str);
1296                 if (!msginfo) {
1297                         log_warning(_("can't parse envelope: %s\n"), str->str);
1298                         continue;
1299                 }
1300
1301                 msginfo->folder = item;
1302
1303                 if (!newlist)
1304                         llast = newlist = g_slist_append(newlist, msginfo);
1305                 else {
1306                         llast = g_slist_append(llast, msginfo);
1307                         llast = llast->next;
1308                 }
1309         }
1310
1311         g_string_free(str, TRUE);
1312
1313         return newlist;
1314 }
1315
1316 static GSList *imap_delete_cached_messages(GSList *mlist, FolderItem *item,
1317                                            guint32 first_uid, guint32 last_uid)
1318 {
1319         GSList *cur, *next;
1320         MsgInfo *msginfo;
1321         gchar *dir;
1322
1323         g_return_val_if_fail(item != NULL, mlist);
1324         g_return_val_if_fail(item->folder != NULL, mlist);
1325         g_return_val_if_fail(item->folder->type == F_IMAP, mlist);
1326
1327         debug_print(_("Deleting cached messages %d - %d ... "),
1328                     first_uid, last_uid);
1329
1330         dir = folder_item_get_path(item);
1331         remove_numbered_files(dir, first_uid, last_uid);
1332         g_free(dir);
1333
1334         for (cur = mlist; cur != NULL; ) {
1335                 next = cur->next;
1336
1337                 msginfo = (MsgInfo *)cur->data;
1338                 if (msginfo != NULL && first_uid <= msginfo->msgnum &&
1339                     msginfo->msgnum <= last_uid) {
1340                         procmsg_msginfo_free(msginfo);
1341                         mlist = g_slist_remove(mlist, msginfo);
1342                 }
1343
1344                 cur = next;
1345         }
1346
1347         debug_print(_("done.\n"));
1348
1349         return mlist;
1350 }
1351
1352 static void imap_delete_all_cached_messages(FolderItem *item)
1353 {
1354         gchar *dir;
1355
1356         g_return_if_fail(item != NULL);
1357         g_return_if_fail(item->folder != NULL);
1358         g_return_if_fail(item->folder->type == F_IMAP);
1359
1360         debug_print(_("Deleting all cached messages... "));
1361
1362         dir = folder_item_get_path(item);
1363         remove_all_numbered_files(dir);
1364         g_free(dir);
1365
1366         debug_print(_("done.\n"));
1367 }
1368
1369 #if USE_SSL
1370 static SockInfo *imap_open(const gchar *server, gushort port, gchar *buf,
1371                            gboolean use_ssl)
1372 #else
1373 static SockInfo *imap_open(const gchar *server, gushort port, gchar *buf)
1374 #endif
1375 {
1376         SockInfo *sock;
1377
1378         if ((sock = sock_connect(server, port)) == NULL) {
1379                 log_warning(_("Can't connect to IMAP4 server: %s:%d\n"),
1380                             server, port);
1381                 return NULL;
1382         }
1383
1384 #if USE_SSL
1385         if (use_ssl && !ssl_init_socket(sock)) {
1386                 sock_close(sock);
1387                 return NULL;
1388         }
1389 #endif
1390
1391         imap_cmd_count = 0;
1392
1393         if (imap_cmd_noop(sock) != IMAP_SUCCESS) {
1394                 sock_close(sock);
1395                 return NULL;
1396         }
1397
1398         return sock;
1399 }
1400
1401 #define THROW goto catch
1402
1403 static void imap_parse_namespace(IMAPSession *session, IMAPFolder *folder)
1404 {
1405         gchar *ns_str;
1406         gchar *name;
1407         gchar *separator;
1408         gchar *p;
1409         IMAPNameSpace *namespace;
1410         GList *ns_list = NULL;
1411
1412         g_return_if_fail(session != NULL);
1413         g_return_if_fail(folder != NULL);
1414
1415         if (folder->namespace != NULL) return;
1416
1417         if (imap_cmd_namespace(SESSION(session)->sock, &ns_str)
1418             != IMAP_SUCCESS) {
1419                 log_warning(_("can't get namespace\n"));
1420                 return;
1421         }
1422
1423         /* get the first element */
1424         extract_one_parenthesis_with_skip_quote(ns_str, '"', '(', ')');
1425         g_strstrip(ns_str);
1426         p = ns_str;
1427
1428         while (*p != '\0') {
1429                 /* parse ("#foo" "/") */
1430
1431                 while (*p && *p != '(') p++;
1432                 if (*p == '\0') THROW;
1433                 p++;
1434
1435                 while (*p && *p != '"') p++;
1436                 if (*p == '\0') THROW;
1437                 p++;
1438                 name = p;
1439
1440                 while (*p && *p != '"') p++;
1441                 if (*p == '\0') THROW;
1442                 *p = '\0';
1443                 p++;
1444
1445                 while (*p && isspace(*p)) p++;
1446                 if (*p == '\0') THROW;
1447                 if (strncmp(p, "NIL", 3) == 0)
1448                         separator = NULL;
1449                 else if (*p == '"') {
1450                         p++;
1451                         separator = p;
1452                         while (*p && *p != '"') p++;
1453                         if (*p == '\0') THROW;
1454                         *p = '\0';
1455                         p++;
1456                 } else THROW;
1457
1458                 while (*p && *p != ')') p++;
1459                 if (*p == '\0') THROW;
1460                 p++;
1461
1462                 namespace = g_new(IMAPNameSpace, 1);
1463                 namespace->name = g_strdup(name);
1464                 namespace->separator = separator ? separator[0] : '\0';
1465                 ns_list = g_list_append(ns_list, namespace);
1466                 IMAP_FOLDER(folder)->namespace = ns_list;
1467         }
1468
1469 catch:
1470         g_free(ns_str);
1471         return;
1472 }
1473
1474 #undef THROW
1475
1476 static IMAPNameSpace *imap_find_namespace(IMAPFolder *folder,
1477                                           const gchar *path)
1478 {
1479         IMAPNameSpace *namespace = NULL;
1480         GList *ns_list;
1481         gchar *name;
1482
1483         g_return_val_if_fail(folder != NULL, NULL);
1484         g_return_val_if_fail(path != NULL, NULL);
1485
1486         ns_list = folder->namespace;
1487
1488         for (; ns_list != NULL; ns_list = ns_list->next) {
1489                 IMAPNameSpace *tmp_ns = ns_list->data;
1490
1491                 Xstrdup_a(name, tmp_ns->name, return namespace);
1492                 if (tmp_ns->separator && tmp_ns->separator != '/')
1493                         subst_char(name, tmp_ns->separator, '/');
1494                 if (strncmp(path, name, strlen(name)) == 0)
1495                         namespace = tmp_ns;
1496         }
1497
1498         return namespace;
1499 }
1500
1501 static gchar *imap_get_real_path(IMAPFolder *folder, const gchar *path)
1502 {
1503         gchar *real_path;
1504         IMAPNameSpace *namespace;
1505
1506         g_return_val_if_fail(folder != NULL, NULL);
1507         g_return_val_if_fail(path != NULL, NULL);
1508
1509         real_path = g_strdup(path);
1510         namespace = imap_find_namespace(folder, path);
1511         if (namespace && namespace->separator)
1512                 imap_path_separator_subst(real_path, namespace->separator);
1513
1514         return real_path;
1515 }
1516
1517 static gchar *imap_parse_atom(SockInfo *sock, gchar *src,
1518                               gchar *dest, gint dest_len, GString *str)
1519 {
1520         gchar *cur_pos = src;
1521
1522         g_return_val_if_fail(str != NULL, cur_pos);
1523
1524         while (*cur_pos == ' ') cur_pos++;
1525
1526         if (!strncmp(cur_pos, "NIL", 3)) {
1527                 *dest = '\0';
1528                 cur_pos += 3;
1529         } else if (*cur_pos == '\"') {
1530                 gchar *p;
1531
1532                 p = get_quoted(cur_pos, '\"', dest, dest_len);
1533                 cur_pos = p ? p : cur_pos + 2;
1534         } else if (*cur_pos == '{') {
1535                 gchar buf[32];
1536                 gint len;
1537                 gchar *nextline;
1538
1539                 cur_pos = strchr_cpy(cur_pos + 1, '}', buf, sizeof(buf));
1540                 len = atoi(buf);
1541
1542                 if ((nextline = sock_getline(sock)) == NULL)
1543                         return cur_pos;
1544                 strretchomp(nextline);
1545                 log_print("IMAP4< %s\n", nextline);
1546                 g_string_assign(str, nextline);
1547
1548                 len = MIN(len, strlen(nextline));
1549                 memcpy(dest, nextline, MIN(len, dest_len - 1));
1550                 dest[MIN(len, dest_len - 1)] = '\0';
1551                 cur_pos = str->str + len;
1552         }
1553
1554         return cur_pos;
1555 }
1556
1557 static gchar *imap_parse_one_address(SockInfo *sock, gchar *start,
1558                                      gchar *out_from_str,
1559                                      gchar *out_fromname_str,
1560                                      GString *str)
1561 {
1562         gchar buf[IMAPBUFSIZE];
1563         gchar *userid;
1564         gchar *domain;
1565         gchar *cur_pos = start;
1566
1567         cur_pos = imap_parse_atom(sock, cur_pos, buf, sizeof(buf), str);
1568         conv_unmime_header(out_fromname_str, IMAPBUFSIZE, buf, NULL);
1569
1570         cur_pos = imap_parse_atom(sock, cur_pos, buf, sizeof(buf), str);
1571
1572         cur_pos = imap_parse_atom(sock, cur_pos, buf, sizeof(buf), str);
1573         Xstrdup_a(userid, buf, return cur_pos + 1);
1574
1575         cur_pos = imap_parse_atom(sock, cur_pos, buf, sizeof(buf), str);
1576         Xstrdup_a(domain, buf, return cur_pos + 1);
1577
1578         if (out_fromname_str[0] != '\0') {
1579                 g_snprintf(out_from_str, IMAPBUFSIZE, "\"%s\" <%s@%s>",
1580                            out_fromname_str, userid, domain);
1581         } else {
1582                 g_snprintf(out_from_str, IMAPBUFSIZE, "%s@%s",
1583                            userid, domain);
1584                 strcpy(out_fromname_str, out_from_str);
1585         }
1586
1587         while (*cur_pos == ' ') cur_pos++;
1588         g_return_val_if_fail(*cur_pos == ')', NULL);
1589
1590         return cur_pos + 1;
1591 }
1592
1593 static gchar *imap_parse_address(SockInfo *sock, gchar *start,
1594                                  gchar **out_from_str,
1595                                  gchar **out_fromname_str,
1596                                  GString *str)
1597 {
1598         gchar buf[IMAPBUFSIZE];
1599         gchar name_buf[IMAPBUFSIZE];
1600         gchar *cur_pos = start;
1601         GString *addr_str;
1602
1603         if (out_from_str)     *out_from_str     = NULL;
1604         if (out_fromname_str) *out_fromname_str = NULL;
1605         buf[0] = name_buf[0] = '\0';
1606
1607         if (!strncmp(cur_pos, "NIL", 3)) {
1608                 if (out_from_str)     *out_from_str     = g_strdup("");
1609                 if (out_fromname_str) *out_fromname_str = g_strdup("");
1610                 return cur_pos + 3;
1611         }
1612
1613         g_return_val_if_fail(*cur_pos == '(', NULL);
1614         cur_pos++;
1615
1616         addr_str = g_string_new(NULL);
1617
1618         for (;;) {
1619                 gchar ch = *cur_pos++;
1620                 if (ch == ')') break;
1621                 if (ch == '(') {
1622                         cur_pos = imap_parse_one_address
1623                                 (sock, cur_pos, buf, name_buf, str);
1624                         if (!cur_pos) {
1625                                 g_string_free(addr_str, TRUE);
1626                                 return NULL;
1627                         }
1628                         if (addr_str->str[0] != '\0')
1629                                 g_string_append(addr_str, ", ");
1630                         g_string_append(addr_str, buf);
1631                 }
1632         }
1633
1634         if (out_from_str)     *out_from_str     = g_strdup(addr_str->str);
1635         if (out_fromname_str) *out_fromname_str = g_strdup(name_buf);
1636
1637         g_string_free(addr_str, TRUE);
1638
1639         return cur_pos;
1640 }
1641
1642 static MsgFlags imap_parse_flags(const gchar *flag_str)  
1643 {
1644         const gchar *p = flag_str;
1645         MsgFlags flags;
1646
1647         flags.perm_flags = MSG_UNREAD;
1648         flags.tmp_flags  = MSG_IMAP;
1649
1650         while ((p = strchr(p, '\\')) != NULL) {
1651                 p++;
1652
1653                 if (g_strncasecmp(p, "Recent", 6) == 0) {
1654                         MSG_SET_PERM_FLAGS(flags, MSG_NEW|MSG_UNREAD);
1655                 } else if (g_strncasecmp(p, "Seen", 4) == 0) {
1656                         MSG_UNSET_PERM_FLAGS(flags, MSG_NEW|MSG_UNREAD);
1657                 } else if (g_strncasecmp(p, "Deleted", 7) == 0) {
1658                         MSG_SET_PERM_FLAGS(flags, MSG_DELETED);
1659                 } else if (g_strncasecmp(p, "Flagged", 7) == 0) {
1660                         MSG_SET_PERM_FLAGS(flags, MSG_MARKED);
1661                 }
1662         }
1663
1664         return flags;
1665 }
1666
1667 static MsgInfo *imap_parse_envelope(SockInfo *sock, GString *line_str)
1668 {
1669         MsgInfo *msginfo;
1670         gchar buf[IMAPBUFSIZE];
1671         gchar tmp[IMAPBUFSIZE];
1672         gchar *cur_pos;
1673         gint msgnum;
1674         guint32 uid = 0;
1675         size_t size = 0;
1676         gchar *date = NULL;
1677         time_t date_t = 0;
1678         gchar *subject = NULL;
1679         gchar *tmp_from;
1680         gchar *tmp_fromname;
1681         gchar *from = NULL;
1682         gchar *fromname = NULL;
1683         gchar *tmp_to;
1684         gchar *to = NULL;
1685         gchar *inreplyto = NULL;
1686         gchar *msgid = NULL;
1687         MsgFlags flags = {0, 0};
1688
1689         g_return_val_if_fail(line_str != NULL, NULL);
1690         g_return_val_if_fail(line_str->str[0] == '*' &&
1691                              line_str->str[1] == ' ', NULL);
1692
1693         cur_pos = line_str->str + 2;
1694
1695 #define PARSE_ONE_ELEMENT(ch) \
1696 { \
1697         cur_pos = strchr_cpy(cur_pos, ch, buf, sizeof(buf)); \
1698         g_return_val_if_fail(cur_pos != NULL, NULL); \
1699 }
1700
1701         PARSE_ONE_ELEMENT(' ');
1702         msgnum = atoi(buf);
1703
1704         PARSE_ONE_ELEMENT(' ');
1705         g_return_val_if_fail(!strcmp(buf, "FETCH"), NULL);
1706
1707         g_return_val_if_fail(*cur_pos == '(', NULL);
1708         cur_pos++;
1709
1710         while (*cur_pos != '\0' && *cur_pos != ')') {
1711                 while (*cur_pos == ' ') cur_pos++;
1712
1713                 if (!strncmp(cur_pos, "UID ", 4)) {
1714                         cur_pos += 4;
1715                         uid = strtoul(cur_pos, &cur_pos, 10);
1716                 } else if (!strncmp(cur_pos, "FLAGS ", 6)) {
1717                         cur_pos += 6;
1718                         g_return_val_if_fail(*cur_pos == '(', NULL);
1719                         cur_pos++;
1720                         PARSE_ONE_ELEMENT(')');
1721                         flags = imap_parse_flags(buf);
1722                 } else if (!strncmp(cur_pos, "RFC822.SIZE ", 12)) {
1723                         cur_pos += 12;
1724                         size = strtol(cur_pos, &cur_pos, 10);
1725                 } else if (!strncmp(cur_pos, "ENVELOPE ", 9)) {
1726                         cur_pos += 9;
1727                         g_return_val_if_fail(*cur_pos == '(', NULL);
1728                         cur_pos = imap_parse_atom
1729                                 (sock, cur_pos + 1, buf, sizeof(buf), line_str);
1730                         Xstrdup_a(date, buf, return NULL);
1731                         date_t = procheader_date_parse(NULL, date, 0);
1732
1733                         cur_pos = imap_parse_atom
1734                                 (sock, cur_pos, buf, sizeof(buf), line_str);
1735                         if (buf[0] != '\0') {
1736                                 conv_unmime_header(tmp, sizeof(tmp), buf, NULL);
1737                                 Xstrdup_a(subject, tmp, return NULL);
1738                         }
1739
1740                         g_return_val_if_fail(*cur_pos == ' ', NULL);
1741                         cur_pos = imap_parse_address(sock, cur_pos + 1,
1742                                                      &tmp_from, &tmp_fromname,
1743                                                      line_str);
1744                         Xstrdup_a(from, tmp_from,
1745                                   {g_free(tmp_from); g_free(tmp_fromname);
1746                                    return NULL;});
1747                         Xstrdup_a(fromname, tmp_fromname,
1748                                   {g_free(tmp_from); g_free(tmp_fromname);
1749                                    return NULL;});
1750                         g_free(tmp_from);
1751                         g_free(tmp_fromname);
1752
1753 #define SKIP_ONE_ELEMENT() \
1754 { \
1755         g_return_val_if_fail(*cur_pos == ' ', NULL); \
1756         cur_pos = imap_parse_address(sock, cur_pos + 1, NULL, NULL, \
1757                                      line_str); \
1758 }
1759
1760                         /* skip sender and reply-to */
1761                         SKIP_ONE_ELEMENT();
1762                         SKIP_ONE_ELEMENT();
1763
1764                         g_return_val_if_fail(*cur_pos == ' ', NULL);
1765                         cur_pos = imap_parse_address(sock, cur_pos + 1,
1766                                                      &tmp_to, NULL, line_str);
1767                         Xstrdup_a(to, tmp_to, {g_free(tmp_to); return NULL;});
1768                         g_free(tmp_to);
1769
1770                         /* skip Cc and Bcc */
1771                         SKIP_ONE_ELEMENT();
1772                         SKIP_ONE_ELEMENT();
1773
1774 #undef SKIP_ONE_ELEMENT
1775
1776                         g_return_val_if_fail(*cur_pos == ' ', NULL);
1777                         cur_pos = imap_parse_atom
1778                                 (sock, cur_pos, buf, sizeof(buf), line_str);
1779                         if (buf[0] != '\0') {
1780                                 eliminate_parenthesis(buf, '(', ')');
1781                                 extract_parenthesis(buf, '<', '>');
1782                                 remove_space(buf);
1783                                 Xstrdup_a(inreplyto, buf, return NULL);
1784                         }
1785
1786                         g_return_val_if_fail(*cur_pos == ' ', NULL);
1787                         cur_pos = imap_parse_atom
1788                                 (sock, cur_pos, buf, sizeof(buf), line_str);
1789                         if (buf[0] != '\0') {
1790                                 extract_parenthesis(buf, '<', '>');
1791                                 remove_space(buf);
1792                                 Xstrdup_a(msgid, buf, return NULL);
1793                         }
1794
1795                         g_return_val_if_fail(*cur_pos == ')', NULL);
1796                         cur_pos++;
1797                 } else {
1798                         g_warning("invalid FETCH response: %s\n", cur_pos);
1799                         break;
1800                 }
1801         }
1802
1803         msginfo = g_new0(MsgInfo, 1);
1804         msginfo->msgnum = uid;
1805         msginfo->size = size;
1806         msginfo->date = g_strdup(date);
1807         msginfo->date_t = date_t;
1808         msginfo->subject = g_strdup(subject);
1809         msginfo->from = g_strdup(from);
1810         msginfo->fromname = g_strdup(fromname);
1811         msginfo->to = g_strdup(to);
1812         msginfo->inreplyto = g_strdup(inreplyto);
1813         msginfo->msgid = g_strdup(msgid);
1814         msginfo->flags = flags;
1815
1816         return msginfo;
1817 }
1818
1819 static gint imap_set_message_flags(IMAPSession *session,
1820                                    guint32 first_uid,
1821                                    guint32 last_uid,
1822                                    IMAPFlags flags,
1823                                    gboolean is_set)
1824 {
1825         GString *buf;
1826         gint ok;
1827
1828         buf = g_string_new(is_set ? "+FLAGS (" : "-FLAGS (");
1829
1830         if (IMAP_IS_SEEN(flags))        g_string_append(buf, "\\Seen ");
1831         if (IMAP_IS_ANSWERED(flags))    g_string_append(buf, "\\Answered ");
1832         if (IMAP_IS_FLAGGED(flags))     g_string_append(buf, "\\Flagged ");
1833         if (IMAP_IS_DELETED(flags))     g_string_append(buf, "\\Deleted ");
1834         if (IMAP_IS_DRAFT(flags))       g_string_append(buf, "\\Draft");
1835
1836         if (buf->str[buf->len - 1] == ' ')
1837                 g_string_truncate(buf, buf->len - 1);
1838
1839         g_string_append_c(buf, ')');
1840
1841         ok = imap_cmd_store(SESSION(session)->sock, first_uid, last_uid,
1842                             buf->str);
1843         g_string_free(buf, TRUE);
1844
1845         return ok;
1846 }
1847
1848 static gint imap_select(IMAPSession *session, IMAPFolder *folder,
1849                         const gchar *path,
1850                         gint *exists, gint *recent, gint *unseen,
1851                         guint32 *uid_validity)
1852 {
1853         gchar *real_path;
1854         gint ok;
1855
1856         real_path = imap_get_real_path(folder, path);
1857         ok = imap_cmd_select(SESSION(session)->sock, real_path,
1858                              exists, recent, unseen, uid_validity);
1859         if (ok != IMAP_SUCCESS)
1860                 log_warning(_("can't select folder: %s\n"), real_path);
1861         g_free(real_path);
1862
1863         return ok;
1864 }
1865
1866 #define THROW(err) { ok = err; goto catch; }
1867
1868 static gint imap_get_uid(IMAPSession *session, gint msgnum, guint32 *uid)
1869 {
1870         gint ok;
1871         GPtrArray *argbuf;
1872         gchar *str;
1873         gint num;
1874
1875         *uid = 0;
1876         argbuf = g_ptr_array_new();
1877
1878         imap_cmd_gen_send(SESSION(session)->sock, "FETCH %d (UID)", msgnum);
1879         if ((ok = imap_cmd_ok(SESSION(session)->sock, argbuf)) != IMAP_SUCCESS)
1880                 THROW(ok);
1881
1882         str = search_array_contain_str(argbuf, "FETCH");
1883         if (!str) THROW(IMAP_ERROR);
1884
1885         if (sscanf(str, "%d FETCH (UID %d)", &num, uid) != 2 ||
1886             num != msgnum) {
1887                 g_warning("imap_get_uid(): invalid FETCH line.\n");
1888                 THROW(IMAP_ERROR);
1889         }
1890
1891 catch:
1892         ptr_array_free_strings(argbuf);
1893         g_ptr_array_free(argbuf, TRUE);
1894
1895         return ok;
1896 }
1897
1898 static gint imap_status(IMAPSession *session, IMAPFolder *folder,
1899                         const gchar *path,
1900                         gint *messages, gint *recent, gint *unseen,
1901                         guint32 *uid_validity)
1902 {
1903         gchar *real_path;
1904         gchar *real_path_;
1905         gint ok;
1906         GPtrArray *argbuf;
1907         gchar *str;
1908
1909         *messages = *recent = *unseen = *uid_validity = 0;
1910
1911         argbuf = g_ptr_array_new();
1912
1913         real_path = imap_get_real_path(folder, path);
1914         RETURN_VAL_IF_QUOTE_REQUIRED_FAIL(real_path_, real_path);
1915         imap_cmd_gen_send(SESSION(session)->sock, "STATUS %s "
1916                           "(MESSAGES RECENT UNSEEN UIDVALIDITY)", real_path_);
1917
1918         ok = imap_cmd_ok(SESSION(session)->sock, argbuf);
1919         if (ok != IMAP_SUCCESS) THROW(ok);
1920
1921         str = search_array_contain_str(argbuf, "STATUS");
1922         if (!str) THROW(IMAP_ERROR);
1923
1924         str = strchr(str, '(');
1925         if (!str) THROW(IMAP_ERROR);
1926         str++;
1927         while (*str != '\0' && *str != ')') {
1928                 while (*str == ' ') str++;
1929
1930                 if (!strncmp(str, "MESSAGES ", 9)) {
1931                         str += 9;
1932                         *messages = strtol(str, &str, 10);
1933                 } else if (!strncmp(str, "RECENT ", 7)) {
1934                         str += 7;
1935                         *recent = strtol(str, &str, 10);
1936                 } else if (!strncmp(str, "UNSEEN ", 7)) {
1937                         str += 7;
1938                         *unseen = strtol(str, &str, 10);
1939                 } else if (!strncmp(str, "UIDVALIDITY ", 12)) {
1940                         str += 12;
1941                         *uid_validity = strtoul(str, &str, 10);
1942                 } else {
1943                         g_warning("invalid STATUS response: %s\n", str);
1944                         break;
1945                 }
1946         }
1947
1948 catch:
1949         g_free(real_path);
1950         ptr_array_free_strings(argbuf);
1951         g_ptr_array_free(argbuf, TRUE);
1952
1953         return ok;
1954 }
1955
1956 #undef THROW
1957
1958
1959 /* low-level IMAP4rev1 commands */
1960
1961 static gint imap_cmd_login(SockInfo *sock,
1962                            const gchar *user, const gchar *pass)
1963 {
1964         gchar *user_, *pass_;
1965         gint ok;
1966
1967         RETURN_VAL_IF_QUOTE_REQUIRED_FAIL(user_, user);
1968         RETURN_VAL_IF_QUOTE_REQUIRED_FAIL(pass_, pass);
1969         imap_cmd_gen_send(sock, "LOGIN %s %s", user_, pass_);
1970
1971         ok = imap_cmd_ok(sock, NULL);
1972         if (ok != IMAP_SUCCESS)
1973                 log_warning(_("IMAP4 login failed.\n"));
1974
1975         return ok;
1976 }
1977
1978 static gint imap_cmd_logout(SockInfo *sock)
1979 {
1980         imap_cmd_gen_send(sock, "LOGOUT");
1981         return imap_cmd_ok(sock, NULL);
1982 }
1983
1984 static gint imap_cmd_noop(SockInfo *sock)
1985 {
1986         imap_cmd_gen_send(sock, "NOOP");
1987         return imap_cmd_ok(sock, NULL);
1988 }
1989
1990 #define THROW(err) { ok = err; goto catch; }
1991
1992 static gint imap_cmd_namespace(SockInfo *sock, gchar **ns_str)
1993 {
1994         gint ok;
1995         GPtrArray *argbuf;
1996         gchar *str;
1997
1998         argbuf = g_ptr_array_new();
1999
2000         imap_cmd_gen_send(sock, "NAMESPACE");
2001         if ((ok = imap_cmd_ok(sock, argbuf)) != IMAP_SUCCESS) THROW(ok);
2002
2003         str = search_array_contain_str(argbuf, "NAMESPACE");
2004         if (!str) THROW(IMAP_ERROR);
2005
2006         *ns_str = g_strdup(str);
2007
2008 catch:
2009         ptr_array_free_strings(argbuf);
2010         g_ptr_array_free(argbuf, TRUE);
2011
2012         return ok;
2013 }
2014
2015 #undef THROW
2016
2017 static gint imap_cmd_list(SockInfo *sock, const gchar *ref,
2018                           const gchar *mailbox, GPtrArray *argbuf)
2019 {
2020         gchar *ref_, *mailbox_;
2021
2022         if (!ref) ref = "\"\"";
2023         if (!mailbox) mailbox = "\"\"";
2024
2025         RETURN_VAL_IF_QUOTE_REQUIRED_FAIL(ref_, ref);
2026         RETURN_VAL_IF_QUOTE_REQUIRED_FAIL(mailbox_, mailbox);
2027         imap_cmd_gen_send(sock, "LIST %s %s", ref_, mailbox_);
2028
2029         return imap_cmd_ok(sock, argbuf);
2030 }
2031
2032 #define THROW goto catch
2033
2034 static gint imap_cmd_do_select(SockInfo *sock, const gchar *folder,
2035                                gboolean examine,
2036                                gint *exists, gint *recent, gint *unseen,
2037                                guint32 *uid_validity)
2038 {
2039         gint ok;
2040         gchar *resp_str;
2041         GPtrArray *argbuf;
2042         gchar *select_cmd;
2043         gchar *folder_;
2044
2045         *exists = *recent = *unseen = *uid_validity = 0;
2046         argbuf = g_ptr_array_new();
2047
2048         if (examine)
2049                 select_cmd = "EXAMINE";
2050         else
2051                 select_cmd = "SELECT";
2052
2053         RETURN_VAL_IF_QUOTE_REQUIRED_FAIL(folder_, folder);
2054         imap_cmd_gen_send(sock, "%s %s", select_cmd, folder_);
2055
2056         if ((ok = imap_cmd_ok(sock, argbuf)) != IMAP_SUCCESS) THROW;
2057
2058         resp_str = search_array_contain_str(argbuf, "EXISTS");
2059         if (resp_str) {
2060                 if (sscanf(resp_str,"%d EXISTS", exists) != 1) {
2061                         g_warning("imap_cmd_select(): invalid EXISTS line.\n");
2062                         THROW;
2063                 }
2064         }
2065
2066         resp_str = search_array_contain_str(argbuf, "RECENT");
2067         if (resp_str) {
2068                 if (sscanf(resp_str, "%d RECENT", recent) != 1) {
2069                         g_warning("imap_cmd_select(): invalid RECENT line.\n");
2070                         THROW;
2071                 }
2072         }
2073
2074         resp_str = search_array_contain_str(argbuf, "UIDVALIDITY");
2075         if (resp_str) {
2076                 if (sscanf(resp_str, "OK [UIDVALIDITY %u] ", uid_validity)
2077                     != 1) {
2078                         g_warning("imap_cmd_select(): invalid UIDVALIDITY line.\n");
2079                         THROW;
2080                 }
2081         }
2082
2083         resp_str = search_array_contain_str(argbuf, "UNSEEN");
2084         if (resp_str) {
2085                 if (sscanf(resp_str, "OK [UNSEEN %d] ", unseen) != 1) {
2086                         g_warning("imap_cmd_select(): invalid UNSEEN line.\n");
2087                         THROW;
2088                 }
2089         }
2090
2091 catch:
2092         ptr_array_free_strings(argbuf);
2093         g_ptr_array_free(argbuf, TRUE);
2094
2095         return ok;
2096 }
2097
2098 static gint imap_cmd_select(SockInfo *sock, const gchar *folder,
2099                             gint *exists, gint *recent, gint *unseen,
2100                             guint32 *uid_validity)
2101 {
2102         return imap_cmd_do_select(sock, folder, FALSE,
2103                                   exists, recent, unseen, uid_validity);
2104 }
2105
2106 static gint imap_cmd_examine(SockInfo *sock, const gchar *folder,
2107                              gint *exists, gint *recent, gint *unseen,
2108                              guint32 *uid_validity)
2109 {
2110         return imap_cmd_do_select(sock, folder, TRUE,
2111                                   exists, recent, unseen, uid_validity);
2112 }
2113
2114 #undef THROW
2115
2116 static gint imap_cmd_create(SockInfo *sock, const gchar *folder)
2117 {
2118         gchar *folder_;
2119
2120         RETURN_VAL_IF_QUOTE_REQUIRED_FAIL(folder_, folder);
2121         imap_cmd_gen_send(sock, "CREATE %s", folder_);
2122
2123         return imap_cmd_ok(sock, NULL);
2124 }
2125
2126 static gint imap_cmd_delete(SockInfo *sock, const gchar *folder)
2127 {
2128         gchar *folder_;
2129
2130         RETURN_VAL_IF_QUOTE_REQUIRED_FAIL(folder_, folder);
2131         imap_cmd_gen_send(sock, "DELETE %s", folder_);
2132
2133         return imap_cmd_ok(sock, NULL);
2134 }
2135
2136 static gint imap_cmd_fetch(SockInfo *sock, guint32 uid, const gchar *filename)
2137 {
2138         gint ok;
2139         gchar buf[IMAPBUFSIZE];
2140         gchar *cur_pos;
2141         gchar size_str[32];
2142         glong size_num;
2143
2144         g_return_val_if_fail(filename != NULL, IMAP_ERROR);
2145
2146         imap_cmd_gen_send(sock, "UID FETCH %d BODY[]", uid);
2147
2148         if (sock_gets(sock, buf, sizeof(buf)) < 0)
2149                 return IMAP_ERROR;
2150         strretchomp(buf);
2151         if (buf[0] != '*' || buf[1] != ' ')
2152                 return IMAP_ERROR;
2153         log_print("IMAP4< %s\n", buf);
2154
2155         cur_pos = strchr(buf, '{');
2156         g_return_val_if_fail(cur_pos != NULL, IMAP_ERROR);
2157         cur_pos = strchr_cpy(cur_pos + 1, '}', size_str, sizeof(size_str));
2158         g_return_val_if_fail(cur_pos != NULL, IMAP_ERROR);
2159         size_num = atol(size_str);
2160
2161         if (*cur_pos != '\0') return IMAP_ERROR;
2162
2163         if (recv_bytes_write_to_file(sock, size_num, filename) != 0)
2164                 return IMAP_ERROR;
2165
2166         if (imap_cmd_gen_recv(sock, buf, sizeof(buf)) != IMAP_SUCCESS)
2167                 return IMAP_ERROR;
2168
2169         if (buf[0] == '\0' || buf[strlen(buf) - 1] != ')')
2170                 return IMAP_ERROR;
2171
2172         ok = imap_cmd_ok(sock, NULL);
2173
2174         return ok;
2175 }
2176
2177 static gint imap_cmd_append(SockInfo *sock, const gchar *destfolder,
2178                             const gchar *file)
2179 {
2180         gint ok;
2181         gint size;
2182         gchar *destfolder_;
2183
2184         g_return_val_if_fail(file != NULL, IMAP_ERROR);
2185
2186         size = get_file_size(file);
2187         RETURN_VAL_IF_QUOTE_REQUIRED_FAIL(destfolder_, destfolder);
2188         imap_cmd_gen_send(sock, "APPEND %s {%d}", destfolder_, size);
2189         ok = imap_cmd_ok(sock, NULL);
2190         if (ok != IMAP_SUCCESS) {
2191                 log_warning(_("can't append %s to %s\n"), file, destfolder_);
2192                 return -1;
2193         }
2194
2195         return ok;
2196 }
2197
2198 static gint imap_cmd_copy(SockInfo *sock, guint32 uid, const gchar *destfolder)
2199 {
2200         gint ok;
2201         gchar *destfolder_;
2202
2203         g_return_val_if_fail(destfolder != NULL, IMAP_ERROR);
2204
2205         RETURN_VAL_IF_QUOTE_REQUIRED_FAIL(destfolder_, destfolder);
2206         imap_cmd_gen_send(sock, "UID COPY %d %s", uid, destfolder_);
2207
2208         ok = imap_cmd_ok(sock, NULL);
2209         if (ok != IMAP_SUCCESS) {
2210                 log_warning(_("can't copy %d to %s\n"), uid, destfolder_);
2211                 return -1;
2212         }
2213
2214         return ok;
2215 }
2216
2217 gint imap_cmd_envelope(SockInfo *sock, guint32 first_uid, guint32 last_uid)
2218 {
2219         imap_cmd_gen_send
2220                 (sock, "UID FETCH %d:%d (UID FLAGS RFC822.SIZE ENVELOPE)",
2221                  first_uid, last_uid);
2222
2223         return IMAP_SUCCESS;
2224 }
2225
2226 static gint imap_cmd_store(SockInfo *sock, guint32 first_uid, guint32 last_uid,
2227                            gchar *sub_cmd)
2228 {
2229         gint ok;
2230
2231         imap_cmd_gen_send(sock, "UID STORE %d:%d %s",
2232                           first_uid, last_uid, sub_cmd);
2233
2234         if ((ok = imap_cmd_ok(sock, NULL)) != IMAP_SUCCESS) {
2235                 log_warning(_("error while imap command: STORE %d:%d %s\n"),
2236                             first_uid, last_uid, sub_cmd);
2237                 return ok;
2238         }
2239
2240         return IMAP_SUCCESS;
2241 }
2242
2243 static gint imap_cmd_expunge(SockInfo *sock)
2244 {
2245         gint ok;
2246
2247         imap_cmd_gen_send(sock, "EXPUNGE");
2248         if ((ok = imap_cmd_ok(sock, NULL)) != IMAP_SUCCESS) {
2249                 log_warning(_("error while imap command: EXPUNGE\n"));
2250                 return ok;
2251         }
2252
2253         return IMAP_SUCCESS;
2254 }
2255
2256 static gint imap_cmd_ok(SockInfo *sock, GPtrArray *argbuf)
2257 {
2258         gint ok;
2259         gchar buf[IMAPBUFSIZE];
2260         gint cmd_num;
2261         gchar cmd_status[IMAPBUFSIZE];
2262
2263         while ((ok = imap_cmd_gen_recv(sock, buf, sizeof(buf)))
2264                == IMAP_SUCCESS) {
2265                 if (buf[0] == '*' && buf[1] == ' ') {
2266                         if (argbuf)
2267                                 g_ptr_array_add(argbuf, g_strdup(buf + 2));
2268                         continue;
2269                 }
2270
2271                 if (sscanf(buf, "%d %s", &cmd_num, cmd_status) < 2)
2272                         return IMAP_ERROR;
2273                 else if (cmd_num == imap_cmd_count &&
2274                          !strcmp(cmd_status, "OK")) {
2275                         if (argbuf)
2276                                 g_ptr_array_add(argbuf, g_strdup(buf));
2277                         return IMAP_SUCCESS;
2278                 } else
2279                         return IMAP_ERROR;
2280         }
2281
2282         return ok;
2283 }
2284
2285 static void imap_cmd_gen_send(SockInfo *sock, const gchar *format, ...)
2286 {
2287         gchar buf[IMAPBUFSIZE];
2288         gchar tmp[IMAPBUFSIZE];
2289         gchar *p;
2290         va_list args;
2291
2292         va_start(args, format);
2293         g_vsnprintf(tmp, sizeof(tmp), format, args);
2294         va_end(args);
2295
2296         imap_cmd_count++;
2297
2298         g_snprintf(buf, sizeof(buf), "%d %s\r\n", imap_cmd_count, tmp);
2299         if (!strncasecmp(tmp, "LOGIN ", 6) && (p = strchr(tmp + 6, ' '))) {
2300                 *p = '\0';
2301                 log_print("IMAP4> %d %s ********\n", imap_cmd_count, tmp);
2302         } else
2303                 log_print("IMAP4> %d %s\n", imap_cmd_count, tmp);
2304
2305         sock_write(sock, buf, strlen(buf));
2306 }
2307
2308 static gint imap_cmd_gen_recv(SockInfo *sock, gchar *buf, gint size)
2309 {
2310         if (sock_gets(sock, buf, size) == -1)
2311                 return IMAP_SOCKET;
2312
2313         strretchomp(buf);
2314
2315         log_print("IMAP4< %s\n", buf);
2316
2317         return IMAP_SUCCESS;
2318 }
2319
2320
2321 /* misc utility functions */
2322
2323 static gchar *strchr_cpy(const gchar *src, gchar ch, gchar *dest, gint len)
2324 {
2325         gchar *tmp;
2326
2327         dest[0] = '\0';
2328         tmp = strchr(src, ch);
2329         if (!tmp)
2330                 return NULL;
2331
2332         memcpy(dest, src, MIN(tmp - src, len - 1));
2333         dest[MIN(tmp - src, len - 1)] = '\0';
2334
2335         return tmp + 1;
2336 }
2337
2338 static gchar *get_quoted(const gchar *src, gchar ch, gchar *dest, gint len)
2339 {
2340         const gchar *p = src;
2341         gint n = 0;
2342
2343         g_return_val_if_fail(*p == ch, NULL);
2344
2345         *dest = '\0';
2346         p++;
2347
2348         while (*p != '\0' && *p != ch) {
2349                 if (n < len - 1) {
2350                         if (*p == '\\' && *(p + 1) != '\0')
2351                                 p++;
2352                         *dest++ = *p++;
2353                 } else
2354                         p++;
2355                 n++;
2356         }
2357
2358         *dest = '\0';
2359         return (gchar *)(*p == ch ? p + 1 : p);
2360 }
2361
2362 static gchar *search_array_contain_str(GPtrArray *array, gchar *str)
2363 {
2364         gint i;
2365
2366         for (i = 0; i < array->len; i++) {
2367                 gchar *tmp;
2368
2369                 tmp = g_ptr_array_index(array, i);
2370                 if (strstr(tmp, str) != NULL)
2371                         return tmp;
2372         }
2373
2374         return NULL;
2375 }
2376
2377 static void imap_path_separator_subst(gchar *str, gchar separator)
2378 {
2379         if (separator && separator != '/')
2380                 subst_char(str, '/', separator);
2381 }