fd61bb4762b0dc94af94942545d5f5796958bb56
[claws.git] / src / imap.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2001 Hiroyuki Yamamoto
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #include <glib.h>
25 #include <stdio.h>
26 #include <string.h>
27 #include <stdlib.h>
28 #include <dirent.h>
29 #include <unistd.h>
30 #include <ctype.h>
31
32 #include "intl.h"
33 #include "imap.h"
34 #include "socket.h"
35 #include "recv.h"
36 #include "procmsg.h"
37 #include "procheader.h"
38 #include "folder.h"
39 #include "statusbar.h"
40 #include "prefs_account.h"
41 #include "codeconv.h"
42 #include "utils.h"
43
44 #define IMAP4_PORT      143
45
46 static GList *session_list = NULL;
47
48 static gint imap_cmd_count = 0;
49
50 static IMAPSession *imap_session_get    (Folder         *folder);
51
52 static gint imap_do_copy                (Folder         *folder,
53                                          FolderItem     *dest,
54                                          MsgInfo        *msginfo,
55                                          gboolean        remove_source);
56 static gint imap_do_copy_msgs_with_dest (Folder         *folder,
57                                          FolderItem     *dest, 
58                                          GSList         *msglist,
59                                          gboolean        remove_source);
60
61 static GSList *imap_get_uncached_messages       (IMAPSession    *session,
62                                                  FolderItem     *item,
63                                                  guint32         first_uid,
64                                                  guint32         last_uid);
65 static GSList *imap_delete_cached_messages      (GSList         *mlist,
66                                                  FolderItem     *item,
67                                                  guint32         first_uid,
68                                                  guint32         last_uid);
69 static void imap_delete_all_cached_messages     (FolderItem     *item);
70
71 static SockInfo *imap_open              (const gchar    *server,
72                                          gushort         port,
73                                          gchar          *buf);
74
75 static gint imap_set_message_flags      (IMAPSession    *session,
76                                          guint32         first_uid,
77                                          guint32         last_uid,
78                                          IMAPFlags       flag,
79                                          gboolean        is_set);
80 static gint imap_select                 (IMAPSession    *session,
81                                          IMAPFolder     *folder,
82                                          const gchar    *path,
83                                          gint           *exists,
84                                          gint           *recent,
85                                          gint           *unseen,
86                                          guint32        *uid_validity);
87 static gint imap_get_uid                (IMAPSession    *session,
88                                          gint            msgnum,
89                                          guint32        *uid);
90 #if 0
91 static gint imap_status_uidnext         (IMAPSession    *session,
92                                          IMAPFolder     *folder,
93                                          const gchar    *path,
94                                          guint32        *uid_next);
95 #endif
96
97 static void imap_parse_namespace                (IMAPSession    *session,
98                                                  IMAPFolder     *folder);
99 static IMAPNameSpace *imap_find_namespace       (IMAPFolder     *folder,
100                                                  const gchar    *path);
101
102 static gchar *imap_parse_atom           (SockInfo       *sock,
103                                          gchar          *src,
104                                          gchar          *dest,
105                                          gchar          *orig_buf);
106 static gchar *imap_parse_one_address    (SockInfo       *sock,
107                                          gchar          *start,
108                                          gchar          *out_from_str,
109                                          gchar          *out_fromname_str,
110                                          gchar          *orig_buf);
111 static gchar *imap_parse_address        (SockInfo       *sock,
112                                          gchar          *start,
113                                          gchar         **out_from_str,
114                                          gchar         **out_fromname_str,
115                                          gchar          *orig_buf);
116 static MsgFlags imap_parse_flags        (const gchar    *flag_str);
117 static MsgInfo *imap_parse_envelope     (SockInfo       *sock,
118                                          gchar          *line_str);
119
120 /* low-level IMAP4rev1 commands */
121 static gint imap_cmd_login      (SockInfo       *sock,
122                                  const gchar    *user,
123                                  const gchar    *pass);
124 static gint imap_cmd_logout     (SockInfo       *sock);
125 static gint imap_cmd_noop       (SockInfo       *sock);
126 static gint imap_cmd_namespace  (SockInfo       *sock,
127                                  gchar         **ns_str);
128 static gint imap_cmd_select     (SockInfo       *sock,
129                                  const gchar    *folder,
130                                  gint           *exists,
131                                  gint           *recent,
132                                  gint           *unseen,
133                                  guint32        *uid_validity);
134 static gint imap_cmd_status     (SockInfo       *sock,
135                                  const gchar    *folder,
136                                  const gchar    *status,
137                                  gint           *value);
138 static gint imap_cmd_create     (SockInfo       *sock,
139                                  const gchar    *folder);
140 static gint imap_cmd_delete     (SockInfo       *sock,
141                                  const gchar    *folder);
142 static gint imap_cmd_envelope   (SockInfo       *sock,
143                                  guint32         first_uid,
144                                  guint32         last_uid);
145 #if 0
146 static gint imap_cmd_search     (SockInfo       *sock,
147                                  GSList         *numlist);
148 #endif
149 static gint imap_cmd_fetch      (SockInfo       *sock,
150                                  guint32         uid,
151                                  const gchar    *filename);
152 static gint imap_cmd_append     (SockInfo       *sock,
153                                  const gchar    *destfolder,
154                                  const gchar    *file);
155 static gint imap_cmd_copy       (SockInfo       *sock,
156                                  guint32         uid,
157                                  const gchar    *destfolder);
158 static gint imap_cmd_store      (SockInfo       *sock,
159                                  guint32         first_uid,
160                                  guint32         last_uid,
161                                  gchar          *sub_cmd);
162 static gint imap_cmd_expunge    (SockInfo       *sock);
163
164 static gint imap_cmd_ok         (SockInfo       *sock,
165                                  GPtrArray      *argbuf);
166 static void imap_cmd_gen_send   (SockInfo       *sock,
167                                  const gchar    *format, ...);
168 static gint imap_cmd_gen_recv   (SockInfo       *sock,
169                                  gchar          *buf,
170                                  gint            size);
171
172 /* misc utility functions */
173 static gchar *strchr_cpy                        (const gchar    *src,
174                                                  gchar           ch,
175                                                  gchar          *dest,
176                                                  gint            len);
177 static gchar *search_array_contain_str          (GPtrArray      *array,
178                                                  gchar          *str);
179 static void imap_path_separator_subst           (gchar          *str,
180                                                  gchar           separator);
181
182 static IMAPSession *imap_session_get(Folder *folder)
183 {
184         RemoteFolder *rfolder = REMOTE_FOLDER(folder);
185
186         g_return_val_if_fail(folder != NULL, NULL);
187         g_return_val_if_fail(folder->type == F_IMAP, NULL);
188         g_return_val_if_fail(folder->account != NULL, NULL);
189
190         if (!rfolder->session) {
191                 rfolder->session =
192                         imap_session_new(folder->account->recv_server,
193                                          IMAP4_PORT,
194                                          folder->account->userid,
195                                          folder->account->passwd);
196                 if (rfolder->session)
197                         imap_parse_namespace(IMAP_SESSION(rfolder->session),
198                                              IMAP_FOLDER(folder));
199                 statusbar_pop_all();
200                 return IMAP_SESSION(rfolder->session);
201         }
202
203         if (imap_cmd_noop(rfolder->session->sock) != IMAP_SUCCESS) {
204                 log_warning(_("IMAP4 connection to %s:%d has been"
205                               " disconnected. Reconnecting...\n"),
206                             folder->account->recv_server, IMAP4_PORT);
207                 session_destroy(rfolder->session);
208                 rfolder->session =
209                         imap_session_new(folder->account->recv_server,
210                                          IMAP4_PORT, folder->account->userid,
211                                          folder->account->passwd);
212                 if (rfolder->session)
213                         imap_parse_namespace(IMAP_SESSION(rfolder->session),
214                                              IMAP_FOLDER(folder));
215         }
216
217         statusbar_pop_all();
218         return IMAP_SESSION(rfolder->session);
219 }
220
221 Session *imap_session_new(const gchar *server, gushort port,
222                           const gchar *user, const gchar *pass)
223 {
224         gchar buf[IMAPBUFSIZE];
225         IMAPSession *session;
226         SockInfo *imap_sock;
227
228         g_return_val_if_fail(server != NULL, NULL);
229
230         log_message(_("creating IMAP4 connection to %s:%d ...\n"),
231                     server, port);
232
233         if ((imap_sock = imap_open(server, port, buf)) == NULL)
234                 return NULL;
235         if (imap_cmd_login(imap_sock, user, pass) != IMAP_SUCCESS) {
236                 imap_cmd_logout(imap_sock);
237                 sock_close(imap_sock);
238                 return NULL;
239         }
240
241         session = g_new(IMAPSession, 1);
242         SESSION(session)->type      = SESSION_IMAP;
243         SESSION(session)->server    = g_strdup(server);
244         SESSION(session)->sock      = imap_sock;
245         SESSION(session)->connected = TRUE;
246         SESSION(session)->phase     = SESSION_READY;
247         SESSION(session)->data      = NULL;
248         session->mbox = NULL;
249
250         session_list = g_list_append(session_list, session);
251
252         return SESSION(session);
253 }
254
255 void imap_session_destroy(IMAPSession *session)
256 {
257         sock_close(SESSION(session)->sock);
258         SESSION(session)->sock = NULL;
259
260         g_free(session->mbox);
261
262         session_list = g_list_remove(session_list, session);
263 }
264
265 void imap_session_destroy_all(void)
266 {
267         while (session_list != NULL) {
268                 IMAPSession *session = (IMAPSession *)session_list->data;
269
270                 imap_cmd_logout(SESSION(session)->sock);
271                 imap_session_destroy(session);
272         }
273 }
274
275 #define THROW goto catch
276
277 GSList *imap_get_msg_list(Folder *folder, FolderItem *item, gboolean use_cache)
278 {
279         GSList *mlist = NULL;
280         IMAPSession *session;
281         gint ok, exists = 0, recent = 0, unseen = 0;
282         guint32 uid_validity = 0;
283         guint32 first_uid = 0, last_uid = 0, begin;
284
285         g_return_val_if_fail(folder != NULL, NULL);
286         g_return_val_if_fail(item != NULL, NULL);
287         g_return_val_if_fail(folder->type == F_IMAP, NULL);
288         g_return_val_if_fail(folder->account != NULL, NULL);
289
290         session = imap_session_get(folder);
291
292         if (!session) {
293                 mlist = procmsg_read_cache(item, FALSE);
294                 item->last_num = procmsg_get_last_num_in_cache(mlist);
295                 procmsg_set_flags(mlist, item);
296                 statusbar_pop_all();
297                 return mlist;
298         }
299
300         ok = imap_select(session, IMAP_FOLDER(folder), item->path,
301                          &exists, &recent, &unseen, &uid_validity);
302         if (ok != IMAP_SUCCESS) THROW;
303         if (exists > 0) {
304                 ok = imap_get_uid(session, 1, &first_uid);
305                 if (ok != IMAP_SUCCESS) THROW;
306                 if (1 != exists) {
307                         ok = imap_get_uid(session, exists, &last_uid);
308                         if (ok != IMAP_SUCCESS) THROW;
309                 } else
310                         last_uid = first_uid;
311         } else {
312                 imap_delete_all_cached_messages(item);
313                 statusbar_pop_all();
314                 return NULL;
315         }
316
317         if (use_cache) {
318                 guint32 cache_last;
319
320                 mlist = procmsg_read_cache(item, FALSE);
321                 procmsg_set_flags(mlist, item);
322                 cache_last = procmsg_get_last_num_in_cache(mlist);
323
324                 /* calculating the range of envelope to get */
325                 if (item->mtime != uid_validity) {
326                         /* mailbox is changed (get all) */
327                         begin = first_uid;
328                 } else if (last_uid < cache_last) {
329                         /* mailbox is changed (get all) */
330                         begin = first_uid;
331                 } else if (last_uid == cache_last) {
332                         /* mailbox unchanged (get none)*/
333                         begin = 0;
334                 } else {
335                         begin = cache_last + 1;
336                 }
337
338                 item->mtime = uid_validity;
339
340                 if (first_uid > 0 && last_uid > 0) {
341                         mlist = imap_delete_cached_messages(mlist, item,
342                                                             0, first_uid - 1);
343                         mlist = imap_delete_cached_messages(mlist, item,
344                                                             last_uid + 1,
345                                                             UINT_MAX);
346                 }
347                 if (begin > 0)
348                         mlist = imap_delete_cached_messages(mlist, item,
349                                                             begin, UINT_MAX);
350         } else {
351                 imap_delete_all_cached_messages(item);
352                 begin = first_uid;
353         }
354
355         if (begin > 0 && begin <= last_uid) {
356                 GSList *newlist;
357                 newlist = imap_get_uncached_messages(session, item,
358                                                      begin, last_uid);
359                 mlist = g_slist_concat(mlist, newlist);
360         }
361
362         item->last_num = last_uid;
363
364 catch:
365         statusbar_pop_all();
366         return mlist;
367 }
368
369 #undef THROW
370
371 gchar *imap_fetch_msg(Folder *folder, FolderItem *item, gint uid)
372 {
373         gchar *path, *filename;
374         IMAPSession *session;
375         gint ok;
376
377         g_return_val_if_fail(folder != NULL, NULL);
378         g_return_val_if_fail(item != NULL, NULL);
379
380         path = folder_item_get_path(item);
381         filename = g_strconcat(path, G_DIR_SEPARATOR_S, itos(uid), NULL);
382         g_free(path);
383  
384         if (is_file_exist(filename)) {
385                 debug_print(_("message %d has been already cached.\n"), uid);
386                 return filename;
387         }
388
389         session = imap_session_get(folder);
390         if (!session) {
391                 g_free(filename);
392                 return NULL;
393         }
394
395         debug_print(_("getting message %d...\n"), uid);
396         ok = imap_cmd_fetch(SESSION(session)->sock, (guint32)uid, filename);
397
398         statusbar_pop_all();
399
400         if (ok != IMAP_SUCCESS) {
401                 g_warning(_("can't fetch message %d\n"), uid);
402                 g_free(filename);
403                 return NULL;
404         }
405
406         return filename;
407 }
408
409 gint imap_add_msg(Folder *folder, FolderItem *dest, const gchar *file,
410                   gboolean remove_source)
411 {
412         IMAPSession *session;
413         gint ok;
414
415         g_return_val_if_fail(folder != NULL, -1);
416         g_return_val_if_fail(dest != NULL, -1);
417         g_return_val_if_fail(file != NULL, -1);
418
419         session = imap_session_get(folder);
420         if (!session)
421                 return -1;
422
423         if (dest->last_num < 0) {
424                 imap_scan_folder(folder, dest);
425                 if (dest->last_num < 0) return -1;
426         }
427
428         ok = imap_cmd_append(SESSION(session)->sock, dest->path, file);
429         if (ok != IMAP_SUCCESS) {
430                 g_warning(_("can't append message %s\n"), file);
431                 return -1;
432         }
433
434         if (remove_source) {
435                 if (unlink(file) < 0)
436                         FILE_OP_ERROR(file, "unlink");
437         }
438
439         return dest->last_num;
440 }
441
442 static gint imap_do_copy(Folder *folder, FolderItem *dest, MsgInfo *msginfo,
443                          gboolean remove_source)
444 {
445         gchar *destdir;
446         IMAPSession *session;
447         IMAPNameSpace *namespace;
448         gint ok;
449
450         g_return_val_if_fail(folder != NULL, -1);
451         g_return_val_if_fail(folder->type == F_IMAP, -1);
452         g_return_val_if_fail(dest != NULL, -1);
453         g_return_val_if_fail(msginfo != NULL, -1);
454
455         session = imap_session_get(folder);
456         if (!session) return -1;
457
458         if (msginfo->folder == dest) {
459                 g_warning(_("the src folder is identical to the dest.\n"));
460                 return -1;
461         }
462
463         Xstrdup_a(destdir, dest->path, return -1);
464         namespace = imap_find_namespace(IMAP_FOLDER(folder), destdir);
465         if (namespace && namespace->separator)
466                 imap_path_separator_subst(destdir, namespace->separator);
467
468         if (remove_source)
469                 debug_print(_("Moving message %s%c%d to %s ...\n"),
470                             msginfo->folder->path, G_DIR_SEPARATOR,
471                             msginfo->msgnum, destdir);
472         else
473                 debug_print(_("Copying message %s%c%d to %s ...\n"),
474                             msginfo->folder->path, G_DIR_SEPARATOR,
475                             msginfo->msgnum, destdir);
476
477         ok = imap_cmd_copy(SESSION(session)->sock, msginfo->msgnum, destdir);
478
479         if (ok == IMAP_SUCCESS && remove_source) {
480                 imap_set_message_flags(session, msginfo->msgnum, msginfo->msgnum,
481                                        IMAP_FLAG_DELETED, TRUE);
482                 imap_cmd_expunge(SESSION(session)->sock);
483         }
484
485         statusbar_pop_all();
486         return ok;
487 }
488
489 static gint imap_do_copy_msgs_with_dest(Folder *folder, FolderItem *dest, 
490                                         GSList *msglist,
491                                         gboolean remove_source)
492 {
493         gchar *destdir;
494         GSList *cur;
495         MsgInfo *msginfo;
496         IMAPSession *session;
497         IMAPNameSpace *namespace;
498         gint ok;
499
500         g_return_val_if_fail(folder != NULL, -1);
501         g_return_val_if_fail(dest != NULL, -1);
502         g_return_val_if_fail(msglist != NULL, -1);
503
504         session = imap_session_get(folder);
505         if (!session) return -1;
506
507         Xstrdup_a(destdir, dest->path, return -1);
508         namespace = imap_find_namespace(IMAP_FOLDER(folder), destdir);
509         if (namespace && namespace->separator)
510                 imap_path_separator_subst(destdir, namespace->separator);
511
512         for (cur = msglist; cur != NULL; cur = cur->next) {
513                 msginfo = (MsgInfo *)cur->data;
514
515                 if (msginfo->folder == dest) {
516                         g_warning(_("the src folder is identical to the dest.\n"));
517                         continue;
518                 }
519
520                 if (remove_source)
521                         debug_print(_("Moving message %s%c%d to %s ...\n"),
522                                     msginfo->folder->path, G_DIR_SEPARATOR,
523                                     msginfo->msgnum, destdir);
524                 else
525                         debug_print(_("Copying message %s%c%d to %s ...\n"),
526                                     msginfo->folder->path, G_DIR_SEPARATOR,
527                                     msginfo->msgnum, destdir);
528
529                 ok = imap_cmd_copy(SESSION(session)->sock, msginfo->msgnum,
530                                    destdir);
531
532                 if (ok == IMAP_SUCCESS && remove_source) {
533                         imap_set_message_flags
534                                 (session, msginfo->msgnum, msginfo->msgnum,
535                                  IMAP_FLAG_DELETED, TRUE);
536                 }
537         }
538
539         if (remove_source)
540                 imap_cmd_expunge(SESSION(session)->sock);
541
542         statusbar_pop_all();
543         return IMAP_SUCCESS;
544 }
545
546 gint imap_move_msg(Folder *folder, FolderItem *dest, MsgInfo *msginfo)
547 {
548         return imap_do_copy(folder, dest, msginfo, TRUE);
549 }
550
551 gint imap_move_msgs_with_dest(Folder *folder, FolderItem *dest, 
552                               GSList *msglist)
553 {
554         return imap_do_copy_msgs_with_dest(folder, dest, msglist, TRUE);
555 }
556
557 gint imap_copy_msg(Folder *folder, FolderItem *dest, MsgInfo *msginfo)
558 {
559         return imap_do_copy(folder, dest, msginfo, FALSE);
560 }
561
562 gint imap_copy_msgs_with_dest(Folder *folder, FolderItem *dest, 
563                               GSList *msglist)
564 {
565         return imap_do_copy_msgs_with_dest(folder, dest, msglist, FALSE);
566 }
567
568 gint imap_remove_msg(Folder *folder, FolderItem *item, gint uid)
569 {
570         gint exists, recent, unseen;
571         guint32 uid_validity;
572         gint ok;
573         IMAPSession *session;
574
575         g_return_val_if_fail(folder != NULL, -1);
576         g_return_val_if_fail(folder->type == F_IMAP, -1);
577         g_return_val_if_fail(item != NULL, -1);
578
579         session = imap_session_get(folder);
580         if (!session) return -1;
581
582         ok = imap_select(session, IMAP_FOLDER(folder), item->path,
583                          &exists, &recent, &unseen, &uid_validity);
584         statusbar_pop_all();
585         if (ok != IMAP_SUCCESS)
586                 return ok;
587
588         ok = imap_set_message_flags
589                 (IMAP_SESSION(REMOTE_FOLDER(folder)->session),
590                  (guint32)uid, (guint32)uid, IMAP_FLAG_DELETED, TRUE);
591         statusbar_pop_all();
592         if (ok != IMAP_SUCCESS) {
593                 log_warning(_("can't set deleted flags: %d\n"), uid);
594                 return ok;
595         }
596
597         ok = imap_cmd_expunge(SESSION(session)->sock);
598         statusbar_pop_all();
599         if (ok != IMAP_SUCCESS) {
600                 log_warning(_("can't expunge\n"));
601                 return ok;
602         }
603
604         return IMAP_SUCCESS;
605 }
606
607 gint imap_remove_all_msg(Folder *folder, FolderItem *item)
608 {
609         gint exists, recent, unseen;
610         guint32 uid_validity;
611         gint ok;
612         IMAPSession *session;
613
614         g_return_val_if_fail(folder != NULL, -1);
615         g_return_val_if_fail(item != NULL, -1);
616
617         session = imap_session_get(folder);
618         if (!session) return -1;
619
620         ok = imap_select(session, IMAP_FOLDER(folder), item->path,
621                          &exists, &recent, &unseen, &uid_validity);
622         statusbar_pop_all();
623         if (ok != IMAP_SUCCESS)
624                 return ok;
625         if (exists == 0)
626                 return IMAP_SUCCESS;
627
628         ok = imap_set_message_flags(session, 1, exists,
629                                     IMAP_FLAG_DELETED, TRUE);
630         statusbar_pop_all();
631         if (ok != IMAP_SUCCESS) {
632                 log_warning(_("can't set deleted flags: 1:%d\n"), exists);
633                 return ok;
634         }
635
636         ok = imap_cmd_expunge(SESSION(session)->sock);
637         statusbar_pop_all();
638         if (ok != IMAP_SUCCESS) {
639                 log_warning(_("can't expunge\n"));
640                 return ok;
641         }
642
643         return IMAP_SUCCESS;
644 }
645
646 void imap_scan_folder(Folder *folder, FolderItem *item)
647 {
648 }
649
650 gint imap_create_tree(Folder *folder)
651 {
652         IMAPFolder *imapfolder = IMAP_FOLDER(folder);
653         FolderItem *item;
654         FolderItem *new_item;
655         gchar *trash_path;
656
657         g_return_val_if_fail(folder != NULL, -1);
658         g_return_val_if_fail(folder->node != NULL, -1);
659         g_return_val_if_fail(folder->node->data != NULL, -1);
660
661         imap_session_get(folder);
662
663         item = FOLDER_ITEM(folder->node->data);
664
665         new_item = folder_item_new("INBOX", "INBOX");
666         new_item->stype = F_INBOX;
667         folder_item_append(item, new_item);
668         folder->inbox = new_item;
669
670         if (imapfolder->namespace && imapfolder->namespace->data) {
671                 IMAPNameSpace *namespace;
672
673                 namespace = (IMAPNameSpace *)imapfolder->namespace->data;
674                 if (*namespace->name == '\0')
675                         trash_path = g_strdup("trash");
676                 else {
677                         gchar *name;
678
679                         Xstrdup_a(name, namespace->name, return -1);
680                         strtailchomp(name, namespace->separator);
681                         trash_path = g_strdup_printf
682                                 ("%s%c%s",
683                                  name, namespace->separator, "trash");
684                 }
685         } else
686                 trash_path = g_strdup("trash");
687
688         new_item = imap_create_folder(folder, item, trash_path);
689
690         if (!new_item) {
691                 new_item = folder_item_new("Trash", trash_path);
692                 folder_item_append(item, new_item);
693         } else {
694                 g_free(new_item->name);
695                 new_item->name = g_strdup("Trash");
696         }
697         new_item->stype = F_TRASH;
698         folder->trash = new_item;
699
700         g_free(trash_path);
701         return 0;
702 }
703
704 FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
705                                const gchar *name)
706 {
707         gchar *dirpath, *imappath;
708         IMAPSession *session;
709         IMAPNameSpace *namespace;
710         FolderItem *new_item;
711         gchar *new_name;
712         gint ok;
713
714         g_return_val_if_fail(folder != NULL, NULL);
715         g_return_val_if_fail(parent != NULL, NULL);
716         g_return_val_if_fail(name != NULL, NULL);
717
718         session = imap_session_get(folder);
719         if (!session) return NULL;
720
721         if (parent->path)
722                 dirpath = g_strconcat(parent->path, G_DIR_SEPARATOR_S, name,
723                                       NULL);
724         else
725                 dirpath = g_strdup(name);
726
727         Xstrdup_a(imappath, dirpath, {g_free(dirpath); return NULL;});
728         Xstrdup_a(new_name, name, {g_free(dirpath); return NULL;});
729         namespace = imap_find_namespace(IMAP_FOLDER(folder), imappath);
730         if (namespace && namespace->separator) {
731                 imap_path_separator_subst(imappath, namespace->separator);
732                 imap_path_separator_subst(new_name, namespace->separator);
733                 strtailchomp(dirpath, '/');
734                 strtailchomp(new_name, namespace->separator);
735         }
736
737         if (strcmp(name, "INBOX") != 0) {
738                 ok = imap_cmd_status(SESSION(session)->sock, imappath,
739                                      "MESSAGES", NULL);
740                 if (ok != IMAP_SUCCESS) {
741                         ok = imap_cmd_create(SESSION(session)->sock, imappath);
742                         statusbar_pop_all();
743                         if (ok != IMAP_SUCCESS) {
744                                 log_warning(_("can't create mailbox\n"));
745                                 g_free(dirpath);
746                                 return NULL;
747                         }
748                 }
749                 statusbar_pop_all();
750         }
751
752         new_item = folder_item_new(new_name, dirpath);
753         folder_item_append(parent, new_item);
754         g_free(dirpath);
755
756         return new_item;
757 }
758
759 gint imap_remove_folder(Folder *folder, FolderItem *item)
760 {
761         gint ok;
762         IMAPSession *session;
763         IMAPNameSpace *namespace;
764         gchar *path;
765
766         g_return_val_if_fail(folder != NULL, -1);
767         g_return_val_if_fail(item != NULL, -1);
768         g_return_val_if_fail(item->path != NULL, -1);
769
770         session = imap_session_get(folder);
771         if (!session) return -1;
772
773         Xstrdup_a(path, item->path, return -1);
774         namespace = imap_find_namespace(IMAP_FOLDER(folder), path);
775         if (namespace && namespace->separator)
776                 imap_path_separator_subst(path, namespace->separator);
777
778         ok = imap_cmd_delete(SESSION(session)->sock, path);
779         statusbar_pop_all();
780         if (ok != IMAP_SUCCESS) {
781                 log_warning(_("can't delete mailbox\n"));
782                 return -1;
783         }
784
785         folder_item_remove(item);
786
787         return 0;
788 }
789
790 static GSList *imap_get_uncached_messages(IMAPSession *session,
791                                           FolderItem *item,
792                                           guint32 first_uid, guint32 last_uid)
793 {
794         gchar buf[IMAPBUFSIZE];
795         GSList *newlist = NULL;
796         GSList *llast = NULL;
797         MsgInfo *msginfo;
798
799         g_return_val_if_fail(session != NULL, NULL);
800         g_return_val_if_fail(item != NULL, NULL);
801         g_return_val_if_fail(item->folder != NULL, NULL);
802         g_return_val_if_fail(item->folder->type == F_IMAP, NULL);
803         g_return_val_if_fail(first_uid <= last_uid, NULL);
804
805         if (imap_cmd_envelope(SESSION(session)->sock, first_uid, last_uid)
806             != IMAP_SUCCESS) {
807                 log_warning(_("can't get envelope\n"));
808                 return NULL;
809         }
810
811         for (;;) {
812                 if (sock_gets(SESSION(session)->sock, buf, sizeof(buf)) < 0) {
813                         log_warning(_("error occurred while getting envelope.\n"));
814                         return newlist;
815                 }
816                 strretchomp(buf);
817                 if (buf[0] != '*' || buf[1] != ' ') break;
818
819                 msginfo = imap_parse_envelope(SESSION(session)->sock, buf);
820                 if (!msginfo) {
821                         log_warning(_("can't parse envelope: %s\n"), buf);
822                         continue;
823                 }
824
825                 msginfo->folder = item;
826
827                 if (!newlist)
828                         llast = newlist = g_slist_append(newlist, msginfo);
829                 else {
830                         llast = g_slist_append(llast, msginfo);
831                         llast = llast->next;
832                 }
833         }
834
835         return newlist;
836 }
837
838 static GSList *imap_delete_cached_messages(GSList *mlist, FolderItem *item,
839                                            guint32 first_uid, guint32 last_uid)
840 {
841         GSList *cur, *next;
842         MsgInfo *msginfo;
843         gchar *dir;
844
845         g_return_val_if_fail(item != NULL, mlist);
846         g_return_val_if_fail(item->folder != NULL, mlist);
847         g_return_val_if_fail(item->folder->type == F_IMAP, mlist);
848
849         debug_print(_("Deleting cached messages %d - %d ... "),
850                     first_uid, last_uid);
851
852         dir = folder_item_get_path(item);
853         remove_numbered_files(dir, first_uid, last_uid);
854         g_free(dir);
855
856         for (cur = mlist; cur != NULL; ) {
857                 next = cur->next;
858
859                 msginfo = (MsgInfo *)cur->data;
860                 if (msginfo != NULL && first_uid <= msginfo->msgnum &&
861                     msginfo->msgnum <= last_uid) {
862                         procmsg_msginfo_free(msginfo);
863                         mlist = g_slist_remove(mlist, msginfo);
864                 }
865
866                 cur = next;
867         }
868
869         debug_print(_("done.\n"));
870
871         return mlist;
872 }
873
874 static void imap_delete_all_cached_messages(FolderItem *item)
875 {
876         gchar *dir;
877
878         g_return_if_fail(item != NULL);
879         g_return_if_fail(item->folder != NULL);
880         g_return_if_fail(item->folder->type == F_IMAP);
881
882         debug_print(_("Deleting all cached messages... "));
883
884         dir = folder_item_get_path(item);
885         remove_all_numbered_files(dir);
886         g_free(dir);
887
888         debug_print(_("done.\n"));
889 }
890
891 static SockInfo *imap_open(const gchar *server, gushort port, gchar *buf)
892 {
893         SockInfo *sock;
894
895         if ((sock = sock_connect(server, port)) == NULL) {
896                 log_warning(_("Can't connect to IMAP4 server: %s:%d\n"),
897                             server, port);
898                 return NULL;
899         }
900
901         imap_cmd_count = 0;
902
903         if (imap_cmd_noop(sock) != IMAP_SUCCESS) {
904                 sock_close(sock);
905                 return NULL;
906         }
907
908         return sock;
909 }
910
911 #define THROW goto catch
912
913 static void imap_parse_namespace(IMAPSession *session, IMAPFolder *folder)
914 {
915         gchar *ns_str;
916         gchar *name;
917         gchar *separator;
918         gchar *p;
919         IMAPNameSpace *namespace;
920         GList *ns_list = NULL;
921
922         g_return_if_fail(session != NULL);
923         g_return_if_fail(folder != NULL);
924
925         if (folder->namespace != NULL) return;
926
927         if (imap_cmd_namespace(SESSION(session)->sock, &ns_str)
928             != IMAP_SUCCESS) {
929                 log_warning(_("can't get namespace\n"));
930                 return;
931         }
932
933         /* get the first element */
934         extract_one_parenthesis_with_skip_quote(ns_str, '"', '(', ')');
935         g_strstrip(ns_str);
936         p = ns_str;
937
938         while (*p != '\0') {
939                 /* parse ("#foo" "/") */
940
941                 while (*p && *p != '(') p++;
942                 if (*p == '\0') THROW;
943                 p++;
944
945                 while (*p && *p != '"') p++;
946                 if (*p == '\0') THROW;
947                 p++;
948                 name = p;
949
950                 while (*p && *p != '"') p++;
951                 if (*p == '\0') THROW;
952                 *p = '\0';
953                 p++;
954
955                 while (*p && isspace(*p)) p++;
956                 if (*p == '\0') THROW;
957                 if (strncmp(p, "NIL", 3) == 0)
958                         separator = NULL;
959                 else if (*p == '"') {
960                         p++;
961                         separator = p;
962                         while (*p && *p != '"') p++;
963                         if (*p == '\0') THROW;
964                         *p = '\0';
965                         p++;
966                 } else THROW;
967
968                 while (*p && *p != ')') p++;
969                 if (*p == '\0') THROW;
970                 p++;
971
972                 namespace = g_new(IMAPNameSpace, 1);
973                 namespace->name = g_strdup(name);
974                 namespace->separator = separator ? separator[0] : '\0';
975                 ns_list = g_list_append(ns_list, namespace);
976                 IMAP_FOLDER(folder)->namespace = ns_list;
977         }
978
979 catch:
980         g_free(ns_str);
981         return;
982 }
983
984 #undef THROW
985
986 static IMAPNameSpace *imap_find_namespace(IMAPFolder *folder,
987                                           const gchar *path)
988 {
989         IMAPNameSpace *namespace = NULL;
990         GList *ns_list;
991         gchar *name;
992
993         g_return_val_if_fail(folder != NULL, NULL);
994         g_return_val_if_fail(path != NULL, NULL);
995
996         ns_list = folder->namespace;
997
998         for (; ns_list != NULL; ns_list = ns_list->next) {
999                 IMAPNameSpace *tmp_ns = ns_list->data;
1000
1001                 Xstrdup_a(name, tmp_ns->name, return namespace);
1002                 if (tmp_ns->separator && tmp_ns->separator != '/')
1003                         subst_char(name, tmp_ns->separator, '/');
1004                 if (strncmp(path, name, strlen(name)) == 0)
1005                         namespace = tmp_ns;
1006         }
1007
1008         return namespace;
1009 }
1010
1011 static gchar *imap_parse_atom(SockInfo *sock, gchar *src, gchar *dest,
1012                               gchar *orig_buf)
1013 {
1014         gchar *cur_pos = src;
1015
1016         while (*cur_pos == ' ') cur_pos++;
1017
1018         if (!strncmp(cur_pos, "NIL", 3)) {
1019                 *dest = '\0';
1020                 cur_pos += 3;
1021         } else if (*cur_pos == '\"') {
1022                 gchar *p;
1023
1024                 p = strchr_cpy(cur_pos + 1, '\"', dest, IMAPBUFSIZE);
1025                 cur_pos = p ? p : cur_pos + 2;
1026         } else if (*cur_pos == '{') {
1027                 gchar buf[32];
1028                 gint len;
1029
1030                 cur_pos = strchr_cpy(cur_pos + 1, '}', buf, sizeof(buf));
1031                 len = atoi(buf);
1032
1033                 g_return_val_if_fail(orig_buf != NULL, cur_pos);
1034
1035                 if (sock_gets(sock, orig_buf, IMAPBUFSIZE) < 0)
1036                         return cur_pos;
1037                 strretchomp(orig_buf);
1038                 log_print("IMAP4< %s\n", orig_buf);
1039                 memcpy(dest, orig_buf, len);
1040                 dest[len] = '\0';
1041                 cur_pos = orig_buf + len;
1042         }
1043
1044         return cur_pos;
1045 }
1046
1047 static gchar *imap_parse_one_address(SockInfo *sock, gchar *start,
1048                                      gchar *out_from_str,
1049                                      gchar *out_fromname_str,
1050                                      gchar *orig_buf)
1051 {
1052         gchar buf[IMAPBUFSIZE];
1053         gchar *userid;
1054         gchar *domain;
1055         gchar *cur_pos = start;
1056
1057         cur_pos = imap_parse_atom(sock, cur_pos, buf, orig_buf);
1058         conv_unmime_header(out_fromname_str, IMAPBUFSIZE, buf, NULL);
1059
1060         cur_pos = imap_parse_atom(sock, cur_pos, buf, orig_buf);
1061
1062         cur_pos = imap_parse_atom(sock, cur_pos, buf, orig_buf);
1063         Xstrdup_a(userid, buf, return cur_pos + 1);
1064
1065         cur_pos = imap_parse_atom(sock, cur_pos, buf, orig_buf);
1066         Xstrdup_a(domain, buf, return cur_pos + 1);
1067
1068         if (out_fromname_str[0] != '\0') {
1069                 g_snprintf(out_from_str, IMAPBUFSIZE, "\"%s\" <%s@%s>",
1070                            out_fromname_str, userid, domain);
1071         } else {
1072                 g_snprintf(out_from_str, IMAPBUFSIZE, "%s@%s",
1073                            userid, domain);
1074                 strcpy(out_fromname_str, out_from_str);
1075         }
1076
1077         while (*cur_pos == ' ') cur_pos++;
1078
1079         g_return_val_if_fail(*cur_pos == ')', cur_pos + 1);
1080
1081         return cur_pos + 1;
1082 }
1083
1084 static gchar *imap_parse_address(SockInfo *sock, gchar *start,
1085                                  gchar **out_from_str,
1086                                  gchar **out_fromname_str,
1087                                  gchar *orig_buf)
1088 {
1089         gchar buf[IMAPBUFSIZE];
1090         gchar name_buf[IMAPBUFSIZE];
1091         gchar *cur_pos = start;
1092         gboolean first = TRUE;
1093
1094         if (out_from_str)     *out_from_str     = NULL;
1095         if (out_fromname_str) *out_fromname_str = NULL;
1096         buf[0] = name_buf[0] = '\0';
1097
1098         if (!strncmp(cur_pos, "NIL", 3)) {
1099                 if (out_from_str)     *out_from_str     = g_strdup("");
1100                 if (out_fromname_str) *out_fromname_str = g_strdup("");
1101                 return cur_pos + 3;
1102         }
1103
1104         g_return_val_if_fail(*cur_pos == '(', NULL);
1105         cur_pos++;
1106
1107         for (;;) {
1108                 gchar ch = *cur_pos++;
1109                 if (ch == ')') break;
1110                 if (ch == '(') {
1111                         if (!first) strcat(buf, ", ");
1112                         first = FALSE;
1113                         cur_pos = imap_parse_one_address
1114                                 (sock, cur_pos, buf, name_buf, orig_buf);
1115                         if (!cur_pos) return NULL;
1116                 }
1117         }
1118
1119         if (out_from_str)     *out_from_str     = g_strdup(buf);
1120         if (out_fromname_str) *out_fromname_str = g_strdup(name_buf);
1121
1122         return cur_pos;
1123 }
1124
1125 static MsgFlags imap_parse_flags(const gchar *flag_str)  
1126 {
1127         gchar buf[32];
1128         const gchar *cur_pos = flag_str;
1129         const gchar *last_pos;
1130         MsgFlags flags;
1131
1132         flags = 0;
1133         MSG_SET_FLAGS(flags, MSG_UNREAD|MSG_IMAP);
1134
1135         while (cur_pos != NULL) {
1136                 cur_pos = strchr(cur_pos, '\\');
1137                 if (cur_pos == NULL) break;
1138
1139                 last_pos = cur_pos + 1;
1140                 cur_pos = strchr_cpy(last_pos, ' ', buf, sizeof(buf));
1141                 if (cur_pos == NULL)
1142                         strncpy2(buf, last_pos, sizeof(buf));
1143
1144                 if (g_strcasecmp(buf, "Recent") == 0) {
1145                         MSG_SET_FLAGS(flags, MSG_NEW|MSG_UNREAD);
1146                 } else if (g_strcasecmp(buf, "Seen") == 0) {
1147                         MSG_UNSET_FLAGS(flags, MSG_NEW|MSG_UNREAD);
1148                 } else if (g_strcasecmp(buf, "Deleted") == 0) {
1149                         MSG_SET_FLAGS(flags, MSG_DELETED);
1150                 } else if (g_strcasecmp(buf, "Flagged") == 0) {
1151                         MSG_SET_FLAGS(flags, MSG_MARKED);
1152                 }
1153         }
1154
1155         return flags;
1156 }
1157
1158 static MsgInfo *imap_parse_envelope(SockInfo *sock, gchar *line_str)
1159 {
1160         MsgInfo *msginfo;
1161         gchar buf[IMAPBUFSIZE];
1162         gchar tmp[IMAPBUFSIZE];
1163         gchar *cur_pos;
1164         gint msgnum;
1165         guint32 uid;
1166         size_t size;
1167         gchar *date = NULL;
1168         time_t date_t;
1169         gchar *subject = NULL;
1170         gchar *tmp_from;
1171         gchar *tmp_fromname;
1172         gchar *from = NULL;
1173         gchar *fromname = NULL;
1174         gchar *tmp_to;
1175         gchar *to = NULL;
1176         gchar *inreplyto = NULL;
1177         gchar *msgid = NULL;
1178         MsgFlags flags;
1179
1180         log_print("IMAP4< %s\n", line_str);
1181
1182         g_return_val_if_fail(line_str != NULL, NULL);
1183         g_return_val_if_fail(line_str[0] == '*' && line_str[1] == ' ', NULL);
1184
1185         cur_pos = line_str + 2;
1186
1187 #define PARSE_ONE_ELEMENT(ch) \
1188 { \
1189         cur_pos = strchr_cpy(cur_pos, ch, buf, sizeof(buf)); \
1190         g_return_val_if_fail(cur_pos != NULL, NULL); \
1191 }
1192
1193         PARSE_ONE_ELEMENT(' ');
1194         msgnum = atoi(buf);
1195
1196         PARSE_ONE_ELEMENT(' ');
1197         g_return_val_if_fail(!strcmp(buf, "FETCH"), NULL);
1198
1199         g_return_val_if_fail(*cur_pos == '(', NULL);
1200         cur_pos++;
1201
1202         PARSE_ONE_ELEMENT(' ');
1203         g_return_val_if_fail(!strcmp(buf, "UID"), NULL);
1204         PARSE_ONE_ELEMENT(' ');
1205         uid = strtoul(buf, NULL, 10);
1206
1207         PARSE_ONE_ELEMENT(' ');
1208         g_return_val_if_fail(!strcmp(buf, "FLAGS"), NULL);
1209         PARSE_ONE_ELEMENT(')');
1210         g_return_val_if_fail(*buf == '(', NULL);
1211         flags = imap_parse_flags(buf + 1);
1212
1213         g_return_val_if_fail(*cur_pos == ' ', NULL);
1214         cur_pos++;
1215
1216         PARSE_ONE_ELEMENT(' ');
1217         g_return_val_if_fail(!strcmp(buf, "RFC822.SIZE"), NULL);
1218         PARSE_ONE_ELEMENT(' ');
1219         size = atoi(buf);
1220
1221         PARSE_ONE_ELEMENT(' ');
1222         g_return_val_if_fail(!strcmp(buf, "ENVELOPE"), NULL);
1223
1224         g_return_val_if_fail(*cur_pos == '(', NULL);
1225         cur_pos = imap_parse_atom(sock, cur_pos + 1, buf, line_str);
1226         Xstrdup_a(date, buf, return NULL);
1227         date_t = procheader_date_parse(NULL, date, 0);
1228
1229         cur_pos = imap_parse_atom(sock, cur_pos, buf, line_str);
1230         if (buf[0] != '\0') {
1231                 conv_unmime_header(tmp, sizeof(tmp), buf, NULL);
1232                 Xstrdup_a(subject, tmp, return NULL);
1233         }
1234
1235         g_return_val_if_fail(*cur_pos == ' ', NULL);
1236         cur_pos = imap_parse_address(sock, cur_pos + 1,
1237                                      &tmp_from, &tmp_fromname, line_str);
1238         Xstrdup_a(from, tmp_from,
1239                   {g_free(tmp_from); g_free(tmp_fromname); return NULL;});
1240         Xstrdup_a(fromname, tmp_fromname,
1241                   {g_free(tmp_from); g_free(tmp_fromname); return NULL;});
1242         g_free(tmp_from);
1243         g_free(tmp_fromname);
1244
1245 #define SKIP_ONE_ELEMENT() \
1246 { \
1247         g_return_val_if_fail(*cur_pos == ' ', NULL); \
1248         cur_pos = imap_parse_address(sock, cur_pos + 1, \
1249                                      NULL, NULL, line_str); \
1250 }
1251
1252         /* skip sender and reply-to */
1253         SKIP_ONE_ELEMENT();
1254         SKIP_ONE_ELEMENT();
1255
1256         g_return_val_if_fail(*cur_pos == ' ', NULL);
1257         cur_pos = imap_parse_address(sock, cur_pos + 1, &tmp_to, NULL, line_str);
1258         Xstrdup_a(to, tmp_to, {g_free(tmp_to); return NULL;});
1259         g_free(tmp_to);
1260
1261         /* skip Cc and Bcc */
1262         SKIP_ONE_ELEMENT();
1263         SKIP_ONE_ELEMENT();
1264
1265 #undef SKIP_ONE_ELEMENT
1266
1267         g_return_val_if_fail(*cur_pos == ' ', NULL);
1268         cur_pos = imap_parse_atom(sock, cur_pos, buf, line_str);
1269         if (buf[0] != '\0') {
1270                 eliminate_parenthesis(buf, '(', ')');
1271                 extract_parenthesis(buf, '<', '>');
1272                 remove_space(buf);
1273                 Xstrdup_a(inreplyto, buf, return NULL);
1274         }
1275
1276         g_return_val_if_fail(*cur_pos == ' ', NULL);
1277         cur_pos = imap_parse_atom(sock, cur_pos, buf, line_str);
1278         if (buf[0] != '\0') {
1279                 extract_parenthesis(buf, '<', '>');
1280                 remove_space(buf);
1281                 Xstrdup_a(msgid, buf, return NULL);
1282         }
1283
1284         msginfo = g_new0(MsgInfo, 1);
1285         msginfo->msgnum = uid;
1286         msginfo->size = size;
1287         msginfo->date = g_strdup(date);
1288         msginfo->date_t = date_t;
1289         msginfo->subject = g_strdup(subject);
1290         msginfo->from = g_strdup(from);
1291         msginfo->fromname = g_strdup(fromname);
1292         msginfo->to = g_strdup(to);
1293         msginfo->inreplyto = g_strdup(inreplyto);
1294         msginfo->msgid = g_strdup(msgid);
1295         msginfo->flags = flags;
1296
1297         return msginfo;
1298 }
1299
1300 static gint imap_set_message_flags(IMAPSession *session,
1301                                    guint32 first_uid,
1302                                    guint32 last_uid,
1303                                    IMAPFlags flags,
1304                                    gboolean is_set)
1305 {
1306         GString *buf;
1307         gint ok;
1308
1309         buf = g_string_new(is_set ? "+FLAGS (" : "-FLAGS (");
1310
1311         if (IMAP_IS_SEEN(flags))        g_string_append(buf, "\\Seen ");
1312         if (IMAP_IS_ANSWERED(flags))    g_string_append(buf, "\\Answered ");
1313         if (IMAP_IS_FLAGGED(flags))     g_string_append(buf, "\\Flagged ");
1314         if (IMAP_IS_DELETED(flags))     g_string_append(buf, "\\Deleted ");
1315         if (IMAP_IS_DRAFT(flags))       g_string_append(buf, "\\Draft");
1316
1317         if (buf->str[buf->len - 1] == ' ')
1318                 g_string_truncate(buf, buf->len - 1);
1319
1320         g_string_append_c(buf, ')');
1321
1322         ok = imap_cmd_store(SESSION(session)->sock, first_uid, last_uid,
1323                             buf->str);
1324         g_string_free(buf, TRUE);
1325
1326         return ok;
1327 }
1328
1329 static gint imap_select(IMAPSession *session, IMAPFolder *folder,
1330                         const gchar *path,
1331                         gint *exists, gint *recent, gint *unseen,
1332                         guint32 *uid_validity)
1333 {
1334         gchar *real_path;
1335         IMAPNameSpace *namespace;
1336         gint ok;
1337
1338         Xstrdup_a(real_path, path, return -1);
1339         namespace = imap_find_namespace(folder, path);
1340         if (namespace && namespace->separator)
1341                 imap_path_separator_subst(real_path, namespace->separator);
1342
1343         ok = imap_cmd_select(SESSION(session)->sock, real_path,
1344                              exists, recent, unseen, uid_validity);
1345         if (ok != IMAP_SUCCESS)
1346                 log_warning(_("can't select folder: %s\n"), real_path);
1347
1348         return ok;
1349 }
1350
1351 #define THROW(err) { ok = err; goto catch; }
1352
1353 static gint imap_get_uid(IMAPSession *session, gint msgnum, guint32 *uid)
1354 {
1355         gint ok;
1356         GPtrArray *argbuf;
1357         gchar *str;
1358         gint num;
1359
1360         *uid = 0;
1361         argbuf = g_ptr_array_new();
1362
1363         imap_cmd_gen_send(SESSION(session)->sock, "FETCH %d (UID)", msgnum);
1364         if ((ok = imap_cmd_ok(SESSION(session)->sock, argbuf)) != IMAP_SUCCESS)
1365                 THROW(ok);
1366
1367         str = search_array_contain_str(argbuf, "FETCH");
1368         if (!str) THROW(IMAP_ERROR);
1369
1370         if (sscanf(str, "%d FETCH (UID %d)", &num, uid) != 2 ||
1371             num != msgnum) {
1372                 g_warning("imap_get_uid(): invalid FETCH line.\n");
1373                 THROW(IMAP_ERROR);
1374         }
1375
1376 catch:
1377         ptr_array_free_strings(argbuf);
1378         g_ptr_array_free(argbuf, TRUE);
1379
1380         return ok;
1381 }
1382
1383 #undef THROW
1384
1385 #if 0
1386 static gint imap_status_uidnext(IMAPSession *session, IMAPFolder *folder,
1387                                 const gchar *path, guint32 *uid_next)
1388 {
1389         gchar *real_path;
1390         IMAPNameSpace *namespace;
1391         gint ok;
1392
1393         Xstrdup_a(real_path, path, return -1);
1394         namespace = imap_find_namespace(folder, path);
1395         if (namespace && namespace->separator)
1396                 imap_path_separator_subst(real_path, namespace->separator);
1397
1398         ok = imap_cmd_status(SESSION(session)->sock, real_path,
1399                              "UIDNEXT", uid_next);
1400         if (ok != IMAP_SUCCESS)
1401                 log_warning(_("can't get the next uid of folder: %s\n"),
1402                             real_path);
1403
1404         return ok;
1405 }
1406 #endif
1407
1408
1409 /* low-level IMAP4rev1 commands */
1410
1411 static gint imap_cmd_login(SockInfo *sock,
1412                            const gchar *user, const gchar *pass)
1413 {
1414         gint ok;
1415
1416         if (strchr(user, ' ') != NULL)
1417                 imap_cmd_gen_send(sock, "LOGIN \"%s\" %s", user, pass);
1418         else
1419                 imap_cmd_gen_send(sock, "LOGIN %s %s", user, pass);
1420
1421         ok = imap_cmd_ok(sock, NULL);
1422         if (ok != IMAP_SUCCESS)
1423                 log_warning(_("IMAP4 login failed.\n"));
1424
1425         return ok;
1426 }
1427
1428 static gint imap_cmd_logout(SockInfo *sock)
1429 {
1430         imap_cmd_gen_send(sock, "LOGOUT");
1431         return imap_cmd_ok(sock, NULL);
1432 }
1433
1434 static gint imap_cmd_noop(SockInfo *sock)
1435 {
1436         imap_cmd_gen_send(sock, "NOOP");
1437         return imap_cmd_ok(sock, NULL);
1438 }
1439
1440 #define THROW(err) { ok = err; goto catch; }
1441
1442 static gint imap_cmd_namespace(SockInfo *sock, gchar **ns_str)
1443 {
1444         gint ok;
1445         GPtrArray *argbuf;
1446         gchar *str;
1447
1448         argbuf = g_ptr_array_new();
1449
1450         imap_cmd_gen_send(sock, "NAMESPACE");
1451         if ((ok = imap_cmd_ok(sock, argbuf)) != IMAP_SUCCESS) THROW(ok);
1452
1453         str = search_array_contain_str(argbuf, "NAMESPACE");
1454         if (!str) THROW(IMAP_ERROR);
1455
1456         *ns_str = g_strdup(str);
1457
1458 catch:
1459         ptr_array_free_strings(argbuf);
1460         g_ptr_array_free(argbuf, TRUE);
1461
1462         return ok;
1463 }
1464
1465 #undef THROW
1466 #define THROW goto catch
1467
1468 static gint imap_cmd_select(SockInfo *sock, const gchar *folder,
1469                             gint *exists, gint *recent, gint *unseen,
1470                             guint32 *uid_validity)
1471 {
1472         gint ok;
1473         gchar *resp_str;
1474         GPtrArray *argbuf;
1475
1476         *exists = *recent = *unseen = *uid_validity = 0;
1477         argbuf = g_ptr_array_new();
1478
1479         if (strchr(folder, ' ') != NULL)
1480                 imap_cmd_gen_send(sock, "SELECT \"%s\"", folder);
1481         else
1482                 imap_cmd_gen_send(sock, "SELECT %s", folder);
1483
1484         if ((ok = imap_cmd_ok(sock, argbuf)) != IMAP_SUCCESS) THROW;
1485
1486         resp_str = search_array_contain_str(argbuf, "EXISTS");
1487         if (resp_str) {
1488                 if (sscanf(resp_str,"%d EXISTS", exists) != 1) {
1489                         g_warning("imap_select(): invalid EXISTS line.\n");
1490                         THROW;
1491                 }
1492         }
1493
1494         resp_str = search_array_contain_str(argbuf, "RECENT");
1495         if (resp_str) {
1496                 if (sscanf(resp_str, "%d RECENT", recent) != 1) {
1497                         g_warning("imap_select(): invalid RECENT line.\n");
1498                         THROW;
1499                 }
1500         }
1501
1502         resp_str = search_array_contain_str(argbuf, "UIDVALIDITY");
1503         if (resp_str) {
1504                 if (sscanf(resp_str, "OK [UIDVALIDITY %u] ", uid_validity)
1505                     != 1) {
1506                         g_warning("imap_select(): invalid UIDVALIDITY line.\n");
1507                         THROW;
1508                 }
1509         }
1510
1511         resp_str = search_array_contain_str(argbuf, "UNSEEN");
1512         if (resp_str) {
1513                 if (sscanf(resp_str, "OK [UNSEEN %d] ", unseen) != 1) {
1514                         g_warning("imap_select(): invalid UNSEEN line.\n");
1515                         THROW;
1516                 }
1517         }
1518
1519 catch:
1520         ptr_array_free_strings(argbuf);
1521         g_ptr_array_free(argbuf, TRUE);
1522
1523         return ok;
1524 }
1525
1526 static gint imap_cmd_status(SockInfo *sock, const gchar *folder,
1527                             const gchar *status, gint *value)
1528 {
1529         gint ok;
1530         GPtrArray *argbuf;
1531         gchar *str;
1532
1533         if (value) *value = 0;
1534         argbuf = g_ptr_array_new();
1535
1536         if (strchr(folder, ' ') != NULL)
1537                 imap_cmd_gen_send(sock, "STATUS \"%s\" (%s)", folder, status);
1538         else
1539                 imap_cmd_gen_send(sock, "STATUS %s (%s)", folder, status);
1540
1541         if ((ok = imap_cmd_ok(sock, argbuf)) != IMAP_SUCCESS) THROW;
1542
1543         str = search_array_contain_str(argbuf, "STATUS");
1544         if (!str) THROW;
1545         str = strchr(str, '(');
1546         if (!str) THROW;
1547         str++;
1548         if (strncmp(str, status, strlen(status)) != 0) THROW;
1549         str += strlen(status);
1550         if (*str != ' ') THROW;
1551         str++;
1552         if (value) *value = atoi(str);
1553
1554 catch:
1555         ptr_array_free_strings(argbuf);
1556         g_ptr_array_free(argbuf, TRUE);
1557
1558         return ok;
1559 }
1560
1561 #undef THROW
1562
1563 static gint imap_cmd_create(SockInfo *sock, const gchar *folder)
1564 {
1565         if (strchr(folder, ' ') != NULL)
1566                 imap_cmd_gen_send(sock, "CREATE \"%s\"", folder);
1567         else
1568                 imap_cmd_gen_send(sock, "CREATE %s", folder);
1569
1570         return imap_cmd_ok(sock, NULL);
1571 }
1572
1573 static gint imap_cmd_delete(SockInfo *sock, const gchar *folder)
1574 {
1575         if (strchr(folder, ' ') != NULL)
1576                 imap_cmd_gen_send(sock, "DELETE \"%s\"", folder);
1577         else
1578                 imap_cmd_gen_send(sock, "DELETE %s", folder);
1579
1580         return imap_cmd_ok(sock, NULL);
1581 }
1582
1583 static gint imap_cmd_fetch(SockInfo *sock, guint32 uid, const gchar *filename)
1584 {
1585         gint ok;
1586         gchar buf[IMAPBUFSIZE];
1587         gchar *cur_pos;
1588         gchar size_str[32];
1589         glong size_num;
1590
1591         g_return_val_if_fail(filename != NULL, IMAP_ERROR);
1592
1593         imap_cmd_gen_send(sock, "UID FETCH %d BODY[]", uid);
1594
1595         if (sock_gets(sock, buf, sizeof(buf)) < 0)
1596                 return IMAP_ERROR;
1597         strretchomp(buf);
1598         if (buf[0] != '*' || buf[1] != ' ')
1599                 return IMAP_ERROR;
1600         log_print("IMAP4< %s\n", buf);
1601
1602         cur_pos = strchr(buf, '{');
1603         g_return_val_if_fail(cur_pos != NULL, IMAP_ERROR);
1604         cur_pos = strchr_cpy(cur_pos + 1, '}', size_str, sizeof(size_str));
1605         g_return_val_if_fail(cur_pos != NULL, IMAP_ERROR);
1606         size_num = atol(size_str);
1607
1608         if (*cur_pos != '\0') return IMAP_ERROR;
1609
1610         if (recv_bytes_write_to_file(sock, size_num, filename) != 0)
1611                 return IMAP_ERROR;
1612
1613         if (imap_cmd_gen_recv(sock, buf, sizeof(buf)) != IMAP_SUCCESS)
1614                 return IMAP_ERROR;
1615
1616         if (buf[0] == '\0' || buf[strlen(buf) - 1] != ')')
1617                 return IMAP_ERROR;
1618
1619         ok = imap_cmd_ok(sock, NULL);
1620
1621         return ok;
1622 }
1623
1624 static gint imap_cmd_append(SockInfo *sock, const gchar *destfolder,
1625                             const gchar *file)
1626 {
1627         gint ok;
1628         gint size;
1629
1630         g_return_val_if_fail(file != NULL, IMAP_ERROR);
1631
1632         size = get_file_size(file);
1633         imap_cmd_gen_send(sock, "APPEND %s {%d}", destfolder, size);
1634         ok = imap_cmd_ok(sock, NULL);
1635         if (ok != IMAP_SUCCESS) {
1636                 log_warning(_("can't append %s to %s\n"), file, destfolder);
1637                 return -1;
1638         }
1639
1640         return ok;
1641 }
1642
1643 static gint imap_cmd_copy(SockInfo *sock, guint32 uid, const gchar *destfolder)
1644 {
1645         gint ok;
1646
1647         g_return_val_if_fail(destfolder != NULL, IMAP_ERROR);
1648
1649         if (strchr(destfolder, ' ') != NULL)
1650                 imap_cmd_gen_send(sock, "UID COPY %d \"%s\"", uid, destfolder);
1651         else
1652                 imap_cmd_gen_send(sock, "UID COPY %d %s", uid, destfolder);
1653
1654         ok = imap_cmd_ok(sock, NULL);
1655         if (ok != IMAP_SUCCESS) {
1656                 log_warning(_("can't copy %d to %s\n"), uid, destfolder);
1657                 return -1;
1658         }
1659
1660         return ok;
1661 }
1662
1663 gint imap_cmd_envelope(SockInfo *sock, guint32 first_uid, guint32 last_uid)
1664 {
1665         imap_cmd_gen_send
1666                 (sock, "UID FETCH %d:%d (UID FLAGS RFC822.SIZE ENVELOPE)",
1667                  first_uid, last_uid);
1668
1669         return IMAP_SUCCESS;
1670 }
1671
1672 static gint imap_cmd_store(SockInfo *sock, guint32 first_uid, guint32 last_uid,
1673                            gchar *sub_cmd)
1674 {
1675         gint ok;
1676
1677         imap_cmd_gen_send(sock, "UID STORE %d:%d %s",
1678                           first_uid, last_uid, sub_cmd);
1679
1680         if ((ok = imap_cmd_ok(sock, NULL)) != IMAP_SUCCESS) {
1681                 log_warning(_("error while imap command: STORE %d:%d %s\n"),
1682                             first_uid, last_uid, sub_cmd);
1683                 return ok;
1684         }
1685
1686         return IMAP_SUCCESS;
1687 }
1688
1689 static gint imap_cmd_expunge(SockInfo *sock)
1690 {
1691         gint ok;
1692
1693         imap_cmd_gen_send(sock, "EXPUNGE");
1694         if ((ok = imap_cmd_ok(sock, NULL)) != IMAP_SUCCESS) {
1695                 log_warning(_("error while imap command: EXPUNGE\n"));
1696                 return ok;
1697         }
1698
1699         return IMAP_SUCCESS;
1700 }
1701
1702 static gint imap_cmd_ok(SockInfo *sock, GPtrArray *argbuf)
1703 {
1704         gint ok;
1705         gchar buf[IMAPBUFSIZE];
1706         gint cmd_num;
1707         gchar cmd_status[IMAPBUFSIZE];
1708
1709         while ((ok = imap_cmd_gen_recv(sock, buf, sizeof(buf)))
1710                == IMAP_SUCCESS) {
1711                 if (buf[0] == '*' && buf[1] == ' ') {
1712                         if (argbuf)
1713                                 g_ptr_array_add(argbuf, g_strdup(&buf[2]));
1714                         continue;
1715                 }
1716
1717                 if (sscanf(buf, "%d %s", &cmd_num, cmd_status) < 2)
1718                         return IMAP_ERROR;
1719                 else if (cmd_num == imap_cmd_count &&
1720                          !strcmp(cmd_status, "OK")) {
1721                         if (argbuf)
1722                                 g_ptr_array_add(argbuf, g_strdup(buf));
1723                         return IMAP_SUCCESS;
1724                 } else
1725                         return IMAP_ERROR;
1726         }
1727
1728         return ok;
1729 }
1730
1731 static void imap_cmd_gen_send(SockInfo *sock, const gchar *format, ...)
1732 {
1733         gchar buf[IMAPBUFSIZE];
1734         gchar tmp[IMAPBUFSIZE];
1735         gchar *p;
1736         va_list args;
1737
1738         va_start(args, format);
1739         g_vsnprintf(tmp, sizeof(tmp), format, args);
1740         va_end(args);
1741
1742         imap_cmd_count++;
1743
1744         g_snprintf(buf, sizeof(buf), "%d %s\r\n", imap_cmd_count, tmp);
1745         if (!strncasecmp(tmp, "LOGIN ", 6) && (p = strchr(tmp + 6, ' '))) {
1746                 *p = '\0';
1747                 log_print("IMAP4> %d %s ********\n", imap_cmd_count, tmp);
1748         } else
1749                 log_print("IMAP4> %d %s\n", imap_cmd_count, tmp);
1750
1751         sock_write(sock, buf, strlen(buf));
1752 }
1753
1754 static gint imap_cmd_gen_recv(SockInfo *sock, gchar *buf, gint size)
1755 {
1756         if (sock_gets(sock, buf, size) == -1)
1757                 return IMAP_SOCKET;
1758
1759         strretchomp(buf);
1760
1761         log_print("IMAP4< %s\n", buf);
1762
1763         return IMAP_SUCCESS;
1764 }
1765
1766
1767 /* misc utility functions */
1768
1769 static gchar *strchr_cpy(const gchar *src, gchar ch, gchar *dest, gint len)
1770 {
1771         gchar *tmp;
1772
1773         dest[0] = '\0';
1774         tmp = strchr(src, ch);
1775         if (!tmp || tmp == src)
1776                 return NULL;
1777
1778         memcpy(dest, src, MIN(tmp - src, len - 1));
1779         dest[MIN(tmp - src, len - 1)] = '\0';
1780
1781         return tmp + 1;
1782 }
1783
1784 static gchar *search_array_contain_str(GPtrArray *array, gchar *str)
1785 {
1786         gint i;
1787
1788         for (i = 0; i < array->len; i++) {
1789                 gchar *tmp;
1790
1791                 tmp = g_ptr_array_index(array, i);
1792                 if (strstr(tmp, str) != NULL)
1793                         return tmp;
1794         }
1795
1796         return NULL;
1797 }
1798
1799 static void imap_path_separator_subst(gchar *str, gchar separator)
1800 {
1801         if (separator && separator != '/')
1802                 subst_char(str, '/', separator);
1803 }