ee764c852a165e665dc9fd618bfa169b1a71da58
[claws.git] / src / imap.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2002 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 #if HAVE_LIBJCONV
35 #  include <jconv.h>
36 #endif
37
38 #include "intl.h"
39 #include "imap.h"
40 #include "socket.h"
41 #include "ssl.h"
42 #include "recv.h"
43 #include "procmsg.h"
44 #include "procheader.h"
45 #include "folder.h"
46 #include "statusbar.h"
47 #include "prefs_account.h"
48 #include "codeconv.h"
49 #include "utils.h"
50 #include "inputdialog.h"
51
52 #define IMAP4_PORT      143
53 #if USE_SSL
54 #define IMAPS_PORT      993
55 #endif
56
57 #define QUOTE_IF_REQUIRED(out, str)                             \
58 {                                                               \
59         if (*str != '"' && strpbrk(str, " \t(){}%*") != NULL) { \
60                 gchar *__tmp;                                   \
61                 gint len;                                       \
62                                                                 \
63                 len = strlen(str) + 3;                          \
64                 Xalloca(__tmp, len, return IMAP_ERROR);         \
65                 g_snprintf(__tmp, len, "\"%s\"", str);          \
66                 out = __tmp;                                    \
67         } else {                                                \
68                 Xstrdup_a(out, str, return IMAP_ERROR);         \
69         }                                                       \
70 }
71
72 static GList *session_list = NULL;
73
74 static gint imap_cmd_count = 0;
75
76 static void imap_folder_init            (Folder         *folder,
77                                          const gchar    *name,
78                                          const gchar    *path);
79
80 static IMAPSession *imap_session_get    (Folder         *folder);
81
82 static gint imap_scan_tree_recursive    (IMAPSession    *session,
83                                          FolderItem     *item);
84 static GSList *imap_parse_list          (IMAPSession    *session,
85                                          const gchar    *real_path);
86
87 static void imap_create_missing_folders (Folder                 *folder);
88 static FolderItem *imap_create_special_folder
89                                         (Folder                 *folder,
90                                          SpecialFolderItemType   stype,
91                                          const gchar            *name);
92
93 static gint imap_do_copy                (Folder         *folder,
94                                          FolderItem     *dest,
95                                          MsgInfo        *msginfo,
96                                          gboolean        remove_source);
97 static gint imap_do_copy_msgs_with_dest (Folder         *folder,
98                                          FolderItem     *dest, 
99                                          GSList         *msglist,
100                                          gboolean        remove_source);
101
102 static GSList *imap_get_uncached_messages       (IMAPSession    *session,
103                                                  FolderItem     *item,
104                                                  guint32         first_uid,
105                                                  guint32         last_uid);
106 static GSList *imap_delete_cached_messages      (GSList         *mlist,
107                                                  FolderItem     *item,
108                                                  guint32         first_uid,
109                                                  guint32         last_uid);
110 static void imap_delete_all_cached_messages     (FolderItem     *item);
111
112 #if USE_SSL
113 static SockInfo *imap_open              (const gchar    *server,
114                                          gushort         port,
115                                          SSLType         ssl_type);
116 #else
117 static SockInfo *imap_open              (const gchar    *server,
118                                          gushort         port);
119 #endif
120
121 #if USE_SSL
122 static SockInfo *imap_open_tunnel(const gchar *server,
123                                   const gchar *tunnelcmd,
124                                   SSLType ssl_type);
125 #else
126 static SockInfo *imap_open_tunnel(const gchar *server,
127                                   const gchar *tunnelcmd);
128 #endif
129
130 #if USE_SSL
131 static SockInfo *imap_init_sock(SockInfo *sock, SSLType  ssl_type);
132 #else
133 static SockInfo *imap_init_sock(SockInfo *sock);
134 #endif
135
136 static gint imap_set_message_flags      (IMAPSession    *session,
137                                          guint32         first_uid,
138                                          guint32         last_uid,
139                                          IMAPFlags       flag,
140                                          gboolean        is_set);
141 static gint imap_select                 (IMAPSession    *session,
142                                          IMAPFolder     *folder,
143                                          const gchar    *path,
144                                          gint           *exists,
145                                          gint           *recent,
146                                          gint           *unseen,
147                                          guint32        *uid_validity);
148 static gint imap_get_uid                (IMAPSession    *session,
149                                          gint            msgnum,
150                                          guint32        *uid);
151 static gint imap_status                 (IMAPSession    *session,
152                                          IMAPFolder     *folder,
153                                          const gchar    *path,
154                                          gint           *messages,
155                                          gint           *recent,
156                                          guint32        *uid_next,
157                                          guint32        *uid_validity,
158                                          gint           *unseen);
159
160 static void imap_parse_namespace                (IMAPSession    *session,
161                                                  IMAPFolder     *folder);
162 static IMAPNameSpace *imap_find_namespace       (IMAPFolder     *folder,
163                                                  const gchar    *path);
164 static gchar imap_get_path_separator            (IMAPFolder     *folder,
165                                                  const gchar    *path);
166 static gchar *imap_get_real_path                (IMAPFolder     *folder,
167                                                  const gchar    *path);
168
169 static gchar *imap_parse_atom           (SockInfo       *sock,
170                                          gchar          *src,
171                                          gchar          *dest,
172                                          gint            dest_len,
173                                          GString        *str);
174 static MsgFlags imap_parse_flags        (const gchar    *flag_str);
175 static MsgInfo *imap_parse_envelope     (SockInfo       *sock,
176                                          FolderItem     *item,
177                                          GString        *line_str);
178 static gint imap_greeting               (SockInfo *sock,
179                                          gboolean *is_preauth);
180
181 /* low-level IMAP4rev1 commands */
182 static gint imap_cmd_login      (SockInfo       *sock,
183                                  const gchar    *user,
184                                  const gchar    *pass);
185 static gint imap_cmd_logout     (SockInfo       *sock);
186 static gint imap_cmd_noop       (SockInfo       *sock);
187 static gint imap_cmd_starttls   (SockInfo       *sock);
188 static gint imap_cmd_namespace  (SockInfo       *sock,
189                                  gchar         **ns_str);
190 static gint imap_cmd_list       (SockInfo       *sock,
191                                  const gchar    *ref,
192                                  const gchar    *mailbox,
193                                  GPtrArray      *argbuf);
194 static gint imap_cmd_do_select  (SockInfo       *sock,
195                                  const gchar    *folder,
196                                  gboolean        examine,
197                                  gint           *exists,
198                                  gint           *recent,
199                                  gint           *unseen,
200                                  guint32        *uid_validity);
201 static gint imap_cmd_select     (SockInfo       *sock,
202                                  const gchar    *folder,
203                                  gint           *exists,
204                                  gint           *recent,
205                                  gint           *unseen,
206                                  guint32        *uid_validity);
207 static gint imap_cmd_examine    (SockInfo       *sock,
208                                  const gchar    *folder,
209                                  gint           *exists,
210                                  gint           *recent,
211                                  gint           *unseen,
212                                  guint32        *uid_validity);
213 static gint imap_cmd_create     (SockInfo       *sock,
214                                  const gchar    *folder);
215 static gint imap_cmd_rename     (SockInfo       *sock,
216                                  const gchar    *oldfolder,
217                                  const gchar    *newfolder);
218 static gint imap_cmd_delete     (SockInfo       *sock,
219                                  const gchar    *folder);
220 static gint imap_cmd_envelope   (SockInfo       *sock,
221                                  guint32         first_uid,
222                                  guint32         last_uid);
223 #if 0
224 static gint imap_cmd_search     (SockInfo       *sock,
225                                  GSList         *numlist);
226 #endif
227 static gint imap_cmd_fetch      (SockInfo       *sock,
228                                  guint32         uid,
229                                  const gchar    *filename);
230 static gint imap_cmd_append     (SockInfo       *sock,
231                                  const gchar    *destfolder,
232                                  const gchar    *file);
233 static gint imap_cmd_copy       (SockInfo       *sock,
234                                  guint32         uid,
235                                  const gchar    *destfolder);
236 static gint imap_cmd_store      (SockInfo       *sock,
237                                  guint32         first_uid,
238                                  guint32         last_uid,
239                                  gchar          *sub_cmd);
240 static gint imap_cmd_expunge    (SockInfo       *sock);
241
242 static gint imap_cmd_ok         (SockInfo       *sock,
243                                  GPtrArray      *argbuf);
244 static void imap_cmd_gen_send   (SockInfo       *sock,
245                                  const gchar    *format, ...);
246 static gint imap_cmd_gen_recv   (SockInfo       *sock,
247                                  gchar          *buf,
248                                  gint            size);
249
250 /* misc utility functions */
251 static gchar *strchr_cpy                        (const gchar    *src,
252                                                  gchar           ch,
253                                                  gchar          *dest,
254                                                  gint            len);
255 static gchar *get_quoted                        (const gchar    *src,
256                                                  gchar           ch,
257                                                  gchar          *dest,
258                                                  gint            len);
259 static gchar *search_array_contain_str          (GPtrArray      *array,
260                                                  gchar          *str);
261 static gchar *search_array_str                  (GPtrArray      *array,
262                                                  gchar          *str);
263 static gchar *search_array_starts               (GPtrArray *array,
264                                                  const gchar *str);
265 static void imap_path_separator_subst           (gchar          *str,
266                                                  gchar           separator);
267
268 static gchar *imap_modified_utf7_to_locale      (const gchar    *mutf7_str);
269 static gchar *imap_locale_to_modified_utf7      (const gchar    *from);
270
271 static gboolean imap_rename_folder_func         (GNode          *node,
272                                                  gpointer        data);
273 GSList *imap_get_num_list                       (Folder         *folder,
274                                                  FolderItem     *item);
275 MsgInfo *imap_fetch_msginfo                     (Folder         *folder,
276                                                  FolderItem     *item,
277                                                  gint            num);
278
279
280 Folder *imap_folder_new(const gchar *name, const gchar *path)
281 {
282         Folder *folder;
283
284         folder = (Folder *)g_new0(IMAPFolder, 1);
285         imap_folder_init(folder, name, path);
286
287         return folder;
288 }
289
290 void imap_folder_destroy(IMAPFolder *folder)
291 {
292         folder_remote_folder_destroy(REMOTE_FOLDER(folder));
293 }
294
295 static void imap_folder_init(Folder *folder, const gchar *name,
296                              const gchar *path)
297 {
298         folder_remote_folder_init(folder, name, path);
299
300         folder->type = F_IMAP;
301
302 /*
303         folder->get_msg_list        = imap_get_msg_list;
304 */
305         folder->fetch_msg           = imap_fetch_msg;
306         folder->add_msg             = imap_add_msg;
307         folder->move_msg            = imap_move_msg;
308         folder->move_msgs_with_dest = imap_move_msgs_with_dest;
309         folder->copy_msg            = imap_copy_msg;
310         folder->copy_msgs_with_dest = imap_copy_msgs_with_dest;
311         folder->remove_msg          = imap_remove_msg;
312         folder->remove_all_msg      = imap_remove_all_msg;
313         folder->is_msg_changed      = imap_is_msg_changed;
314 /*
315         folder->scan                = imap_scan_folder;
316 */
317         folder->scan_tree           = imap_scan_tree;
318         folder->create_tree         = imap_create_tree;
319         folder->create_folder       = imap_create_folder;
320         folder->rename_folder       = imap_rename_folder;
321         folder->remove_folder       = imap_remove_folder;
322
323         folder->get_num_list        = imap_get_num_list;
324         folder->fetch_msginfo       = imap_fetch_msginfo;
325 }
326
327 static IMAPSession *imap_session_get(Folder *folder)
328 {
329         RemoteFolder *rfolder = REMOTE_FOLDER(folder);
330         gushort port;
331
332         g_return_val_if_fail(folder != NULL, NULL);
333         g_return_val_if_fail(folder->type == F_IMAP, NULL);
334         g_return_val_if_fail(folder->account != NULL, NULL);
335
336 #if USE_SSL
337         port = folder->account->set_imapport ? folder->account->imapport
338                 : folder->account->ssl_imap == SSL_TUNNEL
339                 ? IMAPS_PORT : IMAP4_PORT;
340 #else
341         port = folder->account->set_imapport ? folder->account->imapport
342                 : IMAP4_PORT;
343 #endif
344
345         if (!rfolder->session) {
346                 rfolder->session =
347                         imap_session_new(folder->account);
348                 if (rfolder->session) {
349                         imap_parse_namespace(IMAP_SESSION(rfolder->session),
350                                              IMAP_FOLDER(folder));
351                         rfolder->session->last_access_time = time(NULL);
352                 }
353                 statusbar_pop_all();
354                 return IMAP_SESSION(rfolder->session);
355         }
356
357         /* I think the point of this code is to avoid sending a
358          * keepalive if we've used the session recently and therefore
359          * think it's still alive.  Unfortunately, most of the code
360          * does not yet check for errors on the socket, and so if the
361          * connection drops we don't notice until the timeout expires.
362          * A better solution than sending a NOOP every time would be
363          * for every command to be prepared to retry until it is
364          * successfully sent. -- mbp */
365         if (time(NULL) - rfolder->session->last_access_time < SESSION_TIMEOUT) {
366                 rfolder->session->last_access_time = time(NULL);
367                 statusbar_pop_all();
368                 return IMAP_SESSION(rfolder->session);
369         }
370
371         if (imap_cmd_noop(rfolder->session->sock) != IMAP_SUCCESS) {
372                 log_warning(_("IMAP4 connection to %s:%d has been"
373                               " disconnected. Reconnecting...\n"),
374                             folder->account->recv_server, port);
375                 session_destroy(rfolder->session);
376                 rfolder->session =
377                         imap_session_new(folder->account);
378                 if (rfolder->session)
379                         imap_parse_namespace(IMAP_SESSION(rfolder->session),
380                                              IMAP_FOLDER(folder));
381         }
382
383         if (rfolder->session)
384                 rfolder->session->last_access_time = time(NULL);
385         statusbar_pop_all();
386         return IMAP_SESSION(rfolder->session);
387 }
388
389 Session *imap_session_new(const PrefsAccount *account)
390 {
391         IMAPSession *session;
392         SockInfo *imap_sock;
393         gushort port;
394         gchar *pass;
395         gboolean is_preauth;
396
397 #ifdef USE_SSL
398         /* FIXME: IMAP over SSL only... */ 
399         SSLType ssl_type;
400
401         port = account->set_imapport ? account->imapport
402                 : account->ssl_imap ? IMAPS_PORT : IMAP4_PORT;
403         ssl_type = account->ssl_imap ? TRUE : FALSE;    
404 #else
405         port = account->set_imapport ? account->imapport
406                 : IMAP4_PORT;
407 #endif
408
409         if (account->set_tunnelcmd) {
410                 log_message(_("creating tunneled IMAP4 connection\n"));
411 #if USE_SSL
412                 if ((imap_sock = imap_open_tunnel(account->recv_server, 
413                                                   account->tunnelcmd,
414                                                   ssl_type)) == NULL)
415 #else
416                 if ((imap_sock = imap_open_tunnel(account->recv_server, 
417                                                   account->tunnelcmd)) == NULL)
418 #endif
419                         return NULL;
420         } else {
421                 g_return_val_if_fail(account->recv_server != NULL, NULL);
422
423                 log_message(_("creating IMAP4 connection to %s:%d ...\n"),
424                             account->recv_server, port);
425                 
426 #if USE_SSL
427                 if ((imap_sock = imap_open(account->recv_server, port,
428                                            ssl_type)) == NULL)
429 #else
430                 if ((imap_sock = imap_open(account->recv_server, port)) == NULL)
431 #endif
432                         return NULL;
433         }
434
435         /* Only need to log in if the connection was not PREAUTH */
436         imap_greeting(imap_sock, &is_preauth);
437         log_message("IMAP connection is %s-authenticated\n",
438                     (is_preauth) ? "pre" : "un");
439         if (!is_preauth) {
440                 g_return_val_if_fail(account->userid != NULL, NULL);
441
442                 pass = account->passwd;
443                 if (!pass) {
444                         gchar *tmp_pass;
445                         tmp_pass = input_dialog_query_password(account->recv_server, account->userid);
446                         if (!tmp_pass)
447                                 return NULL;
448                         Xstrdup_a(pass, tmp_pass, {g_free(tmp_pass); return NULL;});
449                         g_free(tmp_pass);
450                 }
451
452                 if (imap_cmd_login(imap_sock, account->userid, pass) != IMAP_SUCCESS) {
453                         imap_cmd_logout(imap_sock);
454                         sock_close(imap_sock);
455                         return NULL;
456                 }
457         }
458
459         session = g_new(IMAPSession, 1);
460         SESSION(session)->type             = SESSION_IMAP;
461         SESSION(session)->server           = g_strdup(account->recv_server);
462         SESSION(session)->sock             = imap_sock;
463         SESSION(session)->connected        = TRUE;
464         SESSION(session)->phase            = SESSION_READY;
465         SESSION(session)->last_access_time = time(NULL);
466         SESSION(session)->data             = NULL;
467         session->mbox = NULL;
468
469         session_list = g_list_append(session_list, session);
470
471         return SESSION(session);
472 }
473
474 void imap_session_destroy(IMAPSession *session)
475 {
476         sock_close(SESSION(session)->sock);
477         SESSION(session)->sock = NULL;
478
479         g_free(session->mbox);
480
481         session_list = g_list_remove(session_list, session);
482 }
483
484 void imap_session_destroy_all(void)
485 {
486         while (session_list != NULL) {
487                 IMAPSession *session = (IMAPSession *)session_list->data;
488
489                 imap_cmd_logout(SESSION(session)->sock);
490                 session_destroy(SESSION(session));
491         }
492 }
493
494 #define THROW goto catch
495
496 GSList *imap_get_msg_list(Folder *folder, FolderItem *item, gboolean use_cache)
497 {
498         GSList *mlist = NULL;
499         IMAPSession *session;
500         gint ok, exists = 0, recent = 0, unseen = 0;
501         guint32 uid_validity = 0;
502         guint32 first_uid = 0, last_uid = 0, begin;
503
504         g_return_val_if_fail(folder != NULL, NULL);
505         g_return_val_if_fail(item != NULL, NULL);
506         g_return_val_if_fail(folder->type == F_IMAP, NULL);
507         g_return_val_if_fail(folder->account != NULL, NULL);
508
509         session = imap_session_get(folder);
510
511         if (!session) {
512                 mlist = procmsg_read_cache(item, FALSE);
513                 item->last_num = procmsg_get_last_num_in_cache(mlist);
514                 procmsg_set_flags(mlist, item);
515                 statusbar_pop_all();
516                 return mlist;
517         }
518
519         ok = imap_select(session, IMAP_FOLDER(folder), item->path,
520                          &exists, &recent, &unseen, &uid_validity);
521         if (ok != IMAP_SUCCESS) THROW;
522         if (exists > 0) {
523                 ok = imap_get_uid(session, 1, &first_uid);
524                 if (ok != IMAP_SUCCESS) THROW;
525                 if (1 != exists) {
526                         ok = imap_get_uid(session, exists, &last_uid);
527                         if (ok != IMAP_SUCCESS) THROW;
528                 } else
529                         last_uid = first_uid;
530         } else {
531                 imap_delete_all_cached_messages(item);
532                 statusbar_pop_all();
533                 return NULL;
534         }
535
536         if (use_cache) {
537                 guint32 cache_last;
538
539                 mlist = procmsg_read_cache(item, FALSE);
540                 procmsg_set_flags(mlist, item);
541                 cache_last = procmsg_get_last_num_in_cache(mlist);
542
543                 /* calculating the range of envelope to get */
544                 if (item->mtime != uid_validity) {
545                         /* mailbox is changed (get all) */
546                         begin = first_uid;
547                 } else if (last_uid < cache_last) {
548                         /* mailbox is changed (get all) */
549                         begin = first_uid;
550                 } else if (last_uid == cache_last) {
551                         /* mailbox unchanged (get none)*/
552                         begin = 0;
553                 } else {
554                         begin = cache_last + 1;
555                 }
556
557                 item->mtime = uid_validity;
558
559                 if (first_uid > 0 && last_uid > 0) {
560                         mlist = imap_delete_cached_messages(mlist, item,
561                                                             0, first_uid - 1);
562                         mlist = imap_delete_cached_messages(mlist, item,
563                                                             last_uid + 1,
564                                                             UINT_MAX);
565                 }
566                 if (begin > 0)
567                         mlist = imap_delete_cached_messages(mlist, item,
568                                                             begin, UINT_MAX);
569         } else {
570                 imap_delete_all_cached_messages(item);
571                 begin = first_uid;
572         }
573
574         if (begin > 0 && begin <= last_uid) {
575                 GSList *newlist;
576                 newlist = imap_get_uncached_messages(session, item,
577                                                      begin, last_uid);
578                 mlist = g_slist_concat(mlist, newlist);
579         }
580
581         item->last_num = last_uid;
582
583 catch:
584         statusbar_pop_all();
585         return mlist;
586 }
587
588 #undef THROW
589
590 gchar *imap_fetch_msg(Folder *folder, FolderItem *item, gint uid)
591 {
592         gchar *path, *filename;
593         IMAPSession *session;
594         gint ok;
595
596         g_return_val_if_fail(folder != NULL, NULL);
597         g_return_val_if_fail(item != NULL, NULL);
598
599         path = folder_item_get_path(item);
600         if (!is_dir_exist(path))
601                 make_dir_hier(path);
602         filename = g_strconcat(path, G_DIR_SEPARATOR_S, itos(uid), NULL);
603         g_free(path);
604  
605         if (is_file_exist(filename)) {
606                 debug_print(_("message %d has been already cached.\n"), uid);
607                 return filename;
608         }
609
610         session = imap_session_get(folder);
611         if (!session) {
612                 g_free(filename);
613                 return NULL;
614         }
615
616         ok = imap_select(session, IMAP_FOLDER(folder), item->path,
617                          NULL, NULL, NULL, NULL);
618         statusbar_pop_all();
619         if (ok != IMAP_SUCCESS) {
620                 g_warning(_("can't select mailbox %s\n"), item->path);
621                 g_free(filename);
622                 return NULL;
623         }
624
625         debug_print(_("getting message %d...\n"), uid);
626         ok = imap_cmd_fetch(SESSION(session)->sock, (guint32)uid, filename);
627
628         statusbar_pop_all();
629
630         if (ok != IMAP_SUCCESS) {
631                 g_warning(_("can't fetch message %d\n"), uid);
632                 g_free(filename);
633                 return NULL;
634         }
635
636         return filename;
637 }
638
639 gint imap_add_msg(Folder *folder, FolderItem *dest, const gchar *file,
640                   gboolean remove_source)
641 {
642         gchar *destdir;
643         IMAPSession *session;
644         gint messages, recent, unseen;
645         guint32 uid_next, uid_validity;
646         gint ok;
647
648         g_return_val_if_fail(folder != NULL, -1);
649         g_return_val_if_fail(dest != NULL, -1);
650         g_return_val_if_fail(file != NULL, -1);
651
652         session = imap_session_get(folder);
653         if (!session) return -1;
654
655         ok = imap_status(session, IMAP_FOLDER(folder), dest->path,
656                          &messages, &recent, &uid_next, &uid_validity, &unseen);
657         statusbar_pop_all();
658         if (ok != IMAP_SUCCESS) {
659                 g_warning(_("can't append message %s\n"), file);
660                 return -1;
661         }
662
663         destdir = imap_get_real_path(IMAP_FOLDER(folder), dest->path);
664         ok = imap_cmd_append(SESSION(session)->sock, destdir, file);
665         g_free(destdir);
666
667         if (ok != IMAP_SUCCESS) {
668                 g_warning(_("can't append message %s\n"), file);
669                 return -1;
670         }
671
672         if (remove_source) {
673                 if (unlink(file) < 0)
674                         FILE_OP_ERROR(file, "unlink");
675         }
676
677         return uid_next;
678 }
679
680 static gint imap_do_copy(Folder *folder, FolderItem *dest, MsgInfo *msginfo,
681                          gboolean remove_source)
682 {
683         gchar *destdir;
684         IMAPSession *session;
685         gint messages, recent, unseen;
686         guint32 uid_next, uid_validity;
687         gint ok;
688
689         g_return_val_if_fail(folder != NULL, -1);
690         g_return_val_if_fail(folder->type == F_IMAP, -1);
691         g_return_val_if_fail(dest != NULL, -1);
692         g_return_val_if_fail(msginfo != NULL, -1);
693
694         session = imap_session_get(folder);
695         if (!session) return -1;
696
697         if (msginfo->folder == dest) {
698                 g_warning(_("the src folder is identical to the dest.\n"));
699                 return -1;
700         }
701
702         ok = imap_status(session, IMAP_FOLDER(folder), dest->path,
703                          &messages, &recent, &uid_next, &uid_validity, &unseen);
704         statusbar_pop_all();
705         if (ok != IMAP_SUCCESS) {
706                 g_warning(_("can't copy message\n"));
707                 return -1;
708         }
709
710         destdir = imap_get_real_path(IMAP_FOLDER(folder), dest->path);
711
712         if (remove_source)
713                 debug_print(_("Moving message %s%c%d to %s ...\n"),
714                             msginfo->folder->path, G_DIR_SEPARATOR,
715                             msginfo->msgnum, destdir);
716         else
717                 debug_print(_("Copying message %s%c%d to %s ...\n"),
718                             msginfo->folder->path, G_DIR_SEPARATOR,
719                             msginfo->msgnum, destdir);
720
721         ok = imap_cmd_copy(SESSION(session)->sock, msginfo->msgnum, destdir);
722
723         if (ok == IMAP_SUCCESS && remove_source) {
724                 imap_set_message_flags(session, msginfo->msgnum, msginfo->msgnum,
725                                        IMAP_FLAG_DELETED, TRUE);
726                 ok = imap_cmd_expunge(SESSION(session)->sock);
727         }
728
729         g_free(destdir);
730         statusbar_pop_all();
731
732         if (ok == IMAP_SUCCESS)
733                 return uid_next;
734         else
735                 return -1;
736 }
737
738 static gint imap_do_copy_msgs_with_dest(Folder *folder, FolderItem *dest, 
739                                         GSList *msglist,
740                                         gboolean remove_source)
741 {
742         gchar *destdir;
743         GSList *cur;
744         MsgInfo *msginfo;
745         IMAPSession *session;
746         gint ok = IMAP_SUCCESS;
747
748         g_return_val_if_fail(folder != NULL, -1);
749         g_return_val_if_fail(dest != NULL, -1);
750         g_return_val_if_fail(msglist != NULL, -1);
751
752         session = imap_session_get(folder);
753         if (!session) return -1;
754
755         destdir = imap_get_real_path(IMAP_FOLDER(folder), dest->path);
756
757         for (cur = msglist; cur != NULL; cur = cur->next) {
758                 msginfo = (MsgInfo *)cur->data;
759
760                 if (msginfo->folder == dest) {
761                         g_warning(_("the src folder is identical to the dest.\n"));
762                         continue;
763                 }
764
765                 if (remove_source)
766                         debug_print(_("Moving message %s%c%d to %s ...\n"),
767                                     msginfo->folder->path, G_DIR_SEPARATOR,
768                                     msginfo->msgnum, destdir);
769                 else
770                         debug_print(_("Copying message %s%c%d to %s ...\n"),
771                                     msginfo->folder->path, G_DIR_SEPARATOR,
772                                     msginfo->msgnum, destdir);
773
774                 ok = imap_cmd_copy(SESSION(session)->sock, msginfo->msgnum,
775                                    destdir);
776
777                 if (ok == IMAP_SUCCESS && remove_source) {
778                         imap_set_message_flags
779                                 (session, msginfo->msgnum, msginfo->msgnum,
780                                  IMAP_FLAG_DELETED, TRUE);
781                 }
782         }
783
784         if (remove_source)
785                 ok = imap_cmd_expunge(SESSION(session)->sock);
786
787         g_free(destdir);
788         statusbar_pop_all();
789
790         if (ok == IMAP_SUCCESS)
791                 return 0;
792         else
793                 return -1;
794 }
795
796 gint imap_move_msg(Folder *folder, FolderItem *dest, MsgInfo *msginfo)
797 {
798         gchar *srcfile;
799         gint ret = 0;
800
801         g_return_val_if_fail(folder != NULL, -1);
802         g_return_val_if_fail(dest != NULL, -1);
803         g_return_val_if_fail(msginfo != NULL, -1);
804         g_return_val_if_fail(msginfo->folder != NULL, -1);
805
806         if (folder == msginfo->folder->folder)
807                 return imap_do_copy(folder, dest, msginfo, TRUE);
808
809         srcfile = procmsg_get_message_file(msginfo);
810         if (!srcfile) return -1;
811
812         ret = imap_add_msg(folder, dest, srcfile, FALSE);
813         g_free(srcfile);
814
815         if (ret != -1) {
816                 if(folder_item_remove_msg(msginfo->folder, msginfo->msgnum)) {
817                         ret = -1;
818                 }
819         }
820                 
821         return ret;
822 }
823
824 gint imap_move_msgs_with_dest(Folder *folder, FolderItem *dest, 
825                               GSList *msglist)
826 {
827         MsgInfo *msginfo;
828         GSList *cur;
829         gint ret = 0;
830
831         g_return_val_if_fail(folder != NULL, -1);
832         g_return_val_if_fail(dest != NULL, -1);
833         g_return_val_if_fail(msglist != NULL, -1);
834
835         msginfo = (MsgInfo *)msglist->data;
836         if (folder == msginfo->folder->folder)
837                 return imap_do_copy_msgs_with_dest(folder, dest, msglist, TRUE);
838
839         for (cur = msglist; cur != NULL; cur = cur->next) {
840                 msginfo = (MsgInfo *)cur->data;
841                 ret = imap_move_msg(folder, dest, msginfo);
842                 if (ret == -1) break;
843         }
844
845         return ret;
846 }
847
848 gint imap_copy_msg(Folder *folder, FolderItem *dest, MsgInfo *msginfo)
849 {
850         gchar *srcfile;
851         gint ret = 0;
852
853         g_return_val_if_fail(folder != NULL, -1);
854         g_return_val_if_fail(dest != NULL, -1);
855         g_return_val_if_fail(msginfo != NULL, -1);
856         g_return_val_if_fail(msginfo->folder != NULL, -1);
857
858         if (folder == msginfo->folder->folder)
859                 return imap_do_copy(folder, dest, msginfo, FALSE);
860
861         srcfile = procmsg_get_message_file(msginfo);
862         if (!srcfile) return -1;
863
864         ret = imap_add_msg(folder, dest, srcfile, FALSE);
865
866         g_free(srcfile);
867
868         return ret;
869 }
870
871 gint imap_copy_msgs_with_dest(Folder *folder, FolderItem *dest, 
872                               GSList *msglist)
873 {
874         MsgInfo *msginfo;
875         GSList *cur;
876         gint ret = 0;
877
878         g_return_val_if_fail(folder != NULL, -1);
879         g_return_val_if_fail(dest != NULL, -1);
880         g_return_val_if_fail(msglist != NULL, -1);
881
882         msginfo = (MsgInfo *)msglist->data;
883         if (folder == msginfo->folder->folder)
884                 return imap_do_copy_msgs_with_dest
885                         (folder, dest, msglist, FALSE);
886
887         for (cur = msglist; cur != NULL; cur = cur->next) {
888                 msginfo = (MsgInfo *)cur->data;
889                 ret = imap_copy_msg(folder, dest, msginfo);
890                 if (ret == -1) break;
891         }
892
893         return ret;
894 }
895
896 gint imap_remove_msg(Folder *folder, FolderItem *item, gint uid)
897 {
898         gint exists, recent, unseen;
899         guint32 uid_validity;
900         gint ok;
901         IMAPSession *session;
902
903         g_return_val_if_fail(folder != NULL, -1);
904         g_return_val_if_fail(folder->type == F_IMAP, -1);
905         g_return_val_if_fail(item != NULL, -1);
906
907         session = imap_session_get(folder);
908         if (!session) return -1;
909
910         ok = imap_select(session, IMAP_FOLDER(folder), item->path,
911                          &exists, &recent, &unseen, &uid_validity);
912         statusbar_pop_all();
913         if (ok != IMAP_SUCCESS)
914                 return ok;
915
916         ok = imap_set_message_flags
917                 (IMAP_SESSION(REMOTE_FOLDER(folder)->session),
918                  (guint32)uid, (guint32)uid, IMAP_FLAG_DELETED, TRUE);
919         statusbar_pop_all();
920         if (ok != IMAP_SUCCESS) {
921                 log_warning(_("can't set deleted flags: %d\n"), uid);
922                 return ok;
923         }
924
925         ok = imap_cmd_expunge(SESSION(session)->sock);
926         statusbar_pop_all();
927         if (ok != IMAP_SUCCESS) {
928                 log_warning(_("can't expunge\n"));
929                 return ok;
930         }
931
932         return IMAP_SUCCESS;
933 }
934
935 gint imap_remove_all_msg(Folder *folder, FolderItem *item)
936 {
937         gint exists, recent, unseen;
938         guint32 uid_validity;
939         gint ok;
940         IMAPSession *session;
941
942         g_return_val_if_fail(folder != NULL, -1);
943         g_return_val_if_fail(item != NULL, -1);
944
945         session = imap_session_get(folder);
946         if (!session) return -1;
947
948         ok = imap_select(session, IMAP_FOLDER(folder), item->path,
949                          &exists, &recent, &unseen, &uid_validity);
950         statusbar_pop_all();
951         if (ok != IMAP_SUCCESS)
952                 return ok;
953         if (exists == 0)
954                 return IMAP_SUCCESS;
955
956         imap_cmd_gen_send(SESSION(session)->sock,
957                           "STORE 1:%d +FLAGS (\\Deleted)", exists);
958         ok = imap_cmd_ok(SESSION(session)->sock, NULL);
959         statusbar_pop_all();
960         if (ok != IMAP_SUCCESS) {
961                 log_warning(_("can't set deleted flags: 1:%d\n"), exists);
962                 return ok;
963         }
964
965         ok = imap_cmd_expunge(SESSION(session)->sock);
966         statusbar_pop_all();
967         if (ok != IMAP_SUCCESS) {
968                 log_warning(_("can't expunge\n"));
969                 return ok;
970         }
971
972         return IMAP_SUCCESS;
973 }
974
975 gboolean imap_is_msg_changed(Folder *folder, FolderItem *item, MsgInfo *msginfo)
976 {
977         /* TODO: properly implement this method */
978         return FALSE;
979 }
980
981 gint imap_scan_folder(Folder *folder, FolderItem *item)
982 {
983         IMAPSession *session;
984         gint messages, recent, unseen;
985         guint32 uid_next, uid_validity;
986         gint ok;
987
988         g_return_val_if_fail(folder != NULL, -1);
989         g_return_val_if_fail(item != NULL, -1);
990
991         session = imap_session_get(folder);
992         if (!session) return -1;
993
994         ok = imap_status(session, IMAP_FOLDER(folder), item->path,
995                          &messages, &recent, &uid_next, &uid_validity, &unseen);
996         statusbar_pop_all();
997         if (ok != IMAP_SUCCESS) return -1;
998
999         item->new = unseen > 0 ? recent : 0;
1000         item->unread = unseen;
1001         item->total = messages;
1002         item->last_num = (messages > 0 && uid_next > 0) ? uid_next - 1 : 0;
1003         /* item->mtime = uid_validity; */
1004
1005         return 0;
1006 }
1007
1008 void imap_scan_tree(Folder *folder)
1009 {
1010         FolderItem *item;
1011         IMAPSession *session;
1012         gchar *root_folder = NULL;
1013
1014         g_return_if_fail(folder != NULL);
1015         g_return_if_fail(folder->account != NULL);
1016
1017         session = imap_session_get(folder);
1018         if (!session) return;
1019
1020         if (folder->account->imap_dir && *folder->account->imap_dir) {
1021                 Xstrdup_a(root_folder, folder->account->imap_dir, return);
1022                 strtailchomp(root_folder, '/');
1023                 debug_print("IMAP root directory: %s\n", root_folder);
1024         }
1025
1026         folder_tree_destroy(folder);
1027         item = folder_item_new(folder->name, root_folder);
1028         item->folder = folder;
1029         folder->node = g_node_new(item);
1030
1031         imap_scan_tree_recursive(session, item);
1032
1033         imap_create_missing_folders(folder);
1034 }
1035
1036 static gint imap_scan_tree_recursive(IMAPSession *session, FolderItem *item)
1037 {
1038         Folder *folder;
1039         IMAPFolder *imapfolder;
1040         FolderItem *new_item;
1041         GSList *item_list, *cur;
1042         gchar *real_path;
1043         gchar *wildcard_path;
1044         gchar separator;
1045         gchar wildcard[3];
1046
1047         g_return_val_if_fail(item != NULL, -1);
1048         g_return_val_if_fail(item->folder != NULL, -1);
1049         g_return_val_if_fail(item->no_sub == FALSE, -1);
1050
1051         folder = FOLDER(item->folder);
1052         imapfolder = IMAP_FOLDER(folder);
1053
1054         separator = imap_get_path_separator(imapfolder, item->path);
1055
1056         if (item->folder->ui_func)
1057                 item->folder->ui_func(folder, item, folder->ui_func_data);
1058
1059         if (item->path) {
1060                 wildcard[0] = separator;
1061                 wildcard[1] = '%';
1062                 wildcard[2] = '\0';
1063                 real_path = imap_get_real_path(imapfolder, item->path);
1064         } else {
1065                 wildcard[0] = '%';
1066                 wildcard[1] = '\0';
1067                 real_path = g_strdup("");
1068         }
1069
1070         Xstrcat_a(wildcard_path, real_path, wildcard,
1071                   {g_free(real_path); return IMAP_ERROR;});
1072         QUOTE_IF_REQUIRED(wildcard_path, wildcard_path);
1073
1074         imap_cmd_gen_send(SESSION(session)->sock, "LIST \"\" %s",
1075                           wildcard_path);
1076
1077         strtailchomp(real_path, separator);
1078         item_list = imap_parse_list(session, real_path);
1079         g_free(real_path);
1080
1081         for (cur = item_list; cur != NULL; cur = cur->next) {
1082                 new_item = cur->data;
1083                 if (!strcmp(new_item->path, "INBOX")) {
1084                         if (!folder->inbox) {
1085                                 new_item->stype = F_INBOX;
1086                                 item->folder->inbox = new_item;
1087                         } else {
1088                                 folder_item_destroy(new_item);
1089                                 continue;
1090                         }
1091                 } else if (!item->parent || item->stype == F_INBOX) {
1092                         gchar *base;
1093
1094                         base = g_basename(new_item->path);
1095
1096                         if (!folder->outbox && !strcasecmp(base, "Sent")) {
1097                                 new_item->stype = F_OUTBOX;
1098                                 folder->outbox = new_item;
1099                         } else if (!folder->draft && !strcasecmp(base, "Drafts")) {
1100                                 new_item->stype = F_DRAFT;
1101                                 folder->draft = new_item;
1102                         } else if (!folder->queue && !strcasecmp(base, "Queue")) {
1103                                 new_item->stype = F_QUEUE;
1104                                 folder->queue = new_item;
1105                         } else if (!folder->trash && !strcasecmp(base, "Trash")) {
1106                                 new_item->stype = F_TRASH;
1107                                 folder->trash = new_item;
1108                         }
1109                 }
1110                 folder_item_append(item, new_item);
1111                 if (new_item->no_select == FALSE)
1112                         imap_scan_folder(folder, new_item);
1113                 if (new_item->no_sub == FALSE)
1114                         imap_scan_tree_recursive(session, new_item);
1115         }
1116
1117         return IMAP_SUCCESS;
1118 }
1119
1120 static GSList *imap_parse_list(IMAPSession *session, const gchar *real_path)
1121 {
1122         gchar buf[IMAPBUFSIZE];
1123         gchar flags[256];
1124         gchar separator[16];
1125         gchar *p;
1126         gchar *name;
1127         gchar *loc_name, *loc_path;
1128         GSList *item_list = NULL;
1129         GString *str;
1130         FolderItem *new_item;
1131
1132         debug_print("getting list of %s ...\n",
1133                     *real_path ? real_path : "\"\"");
1134
1135         str = g_string_new(NULL);
1136
1137         for (;;) {
1138                 if (sock_gets(SESSION(session)->sock, buf, sizeof(buf)) <= 0) {
1139                         log_warning(_("error occured while getting LIST.\n"));
1140                         break;
1141                 }
1142                 strretchomp(buf);
1143                 if (buf[0] != '*' || buf[1] != ' ') {
1144                         log_print("IMAP4< %s\n", buf);
1145                         break;
1146                 }
1147                 debug_print("IMAP4< %s\n", buf);
1148
1149                 g_string_assign(str, buf);
1150                 p = str->str + 2;
1151                 if (strncmp(p, "LIST ", 5) != 0) continue;
1152                 p += 5;
1153
1154                 if (*p != '(') continue;
1155                 p++;
1156                 p = strchr_cpy(p, ')', flags, sizeof(flags));
1157                 if (!p) continue;
1158                 while (*p == ' ') p++;
1159
1160                 p = strchr_cpy(p, ' ', separator, sizeof(separator));
1161                 if (!p) continue;
1162                 extract_quote(separator, '"');
1163                 if (!strcmp(separator, "NIL"))
1164                         separator[0] = '\0';
1165
1166                 buf[0] = '\0';
1167                 while (*p == ' ') p++;
1168                 if (*p == '{' || *p == '"')
1169                         p = imap_parse_atom(SESSION(session)->sock, p,
1170                                             buf, sizeof(buf), str);
1171                 else
1172                         strncpy2(buf, p, sizeof(buf));
1173                 strtailchomp(buf, separator[0]);
1174                 if (buf[0] == '\0') continue;
1175                 if (!strcmp(buf, real_path)) continue;
1176
1177                 if (separator[0] != '\0')
1178                         subst_char(buf, separator[0], '/');
1179                 name = g_basename(buf);
1180                 if (name[0] == '.') continue;
1181
1182                 loc_name = imap_modified_utf7_to_locale(name);
1183                 loc_path = imap_modified_utf7_to_locale(buf);
1184                 new_item = folder_item_new(loc_name, loc_path);
1185                 if (strcasestr(flags, "\\Noinferiors") != NULL)
1186                         new_item->no_sub = TRUE;
1187                 if (strcmp(buf, "INBOX") != 0 &&
1188                     strcasestr(flags, "\\Noselect") != NULL)
1189                         new_item->no_select = TRUE;
1190
1191                 item_list = g_slist_append(item_list, new_item);
1192
1193                 debug_print("folder %s has been added.\n", loc_path);
1194                 g_free(loc_path);
1195                 g_free(loc_name);
1196         }
1197
1198         g_string_free(str, TRUE);
1199         statusbar_pop_all();
1200
1201         return item_list;
1202 }
1203
1204 gint imap_create_tree(Folder *folder)
1205 {
1206         g_return_val_if_fail(folder != NULL, -1);
1207         g_return_val_if_fail(folder->node != NULL, -1);
1208         g_return_val_if_fail(folder->node->data != NULL, -1);
1209         g_return_val_if_fail(folder->account != NULL, -1);
1210
1211         imap_scan_tree(folder);
1212         imap_create_missing_folders(folder);
1213
1214         return 0;
1215 }
1216
1217 static void imap_create_missing_folders(Folder *folder)
1218 {
1219         g_return_if_fail(folder != NULL);
1220
1221         if (!folder->inbox)
1222                 folder->inbox = imap_create_special_folder
1223                         (folder, F_INBOX, "INBOX");
1224 #if 0
1225         if (!folder->outbox)
1226                 folder->outbox = imap_create_special_folder
1227                         (folder, F_OUTBOX, "Sent");
1228         if (!folder->draft)
1229                 folder->draft = imap_create_special_folder
1230                         (folder, F_DRAFT, "Drafts");
1231         if (!folder->queue)
1232                 folder->queue = imap_create_special_folder
1233                         (folder, F_QUEUE, "Queue");
1234 #endif
1235         if (!folder->trash)
1236                 folder->trash = imap_create_special_folder
1237                         (folder, F_TRASH, "Trash");
1238 }
1239
1240 static FolderItem *imap_create_special_folder(Folder *folder,
1241                                               SpecialFolderItemType stype,
1242                                               const gchar *name)
1243 {
1244         FolderItem *item;
1245         FolderItem *new_item;
1246
1247         g_return_val_if_fail(folder != NULL, NULL);
1248         g_return_val_if_fail(folder->node != NULL, NULL);
1249         g_return_val_if_fail(folder->node->data != NULL, NULL);
1250         g_return_val_if_fail(folder->account != NULL, NULL);
1251         g_return_val_if_fail(name != NULL, NULL);
1252
1253         item = FOLDER_ITEM(folder->node->data);
1254         new_item = imap_create_folder(folder, item, name);
1255
1256         if (!new_item) {
1257                 g_warning(_("Can't create '%s'\n"), name);
1258                 if (!folder->inbox) return NULL;
1259
1260                 new_item = imap_create_folder(folder, folder->inbox, name);
1261                 if (!new_item)
1262                         g_warning(_("Can't create '%s' under INBOX\n"), name);
1263                 else
1264                         new_item->stype = stype;
1265         } else
1266                 new_item->stype = stype;
1267
1268         return new_item;
1269 }
1270
1271 FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
1272                                const gchar *name)
1273 {
1274         gchar *dirpath, *imap_path;
1275         IMAPSession *session;
1276         FolderItem *new_item;
1277         gchar separator;
1278         gchar *new_name;
1279         const gchar *p;
1280         gint ok;
1281
1282         g_return_val_if_fail(folder != NULL, NULL);
1283         g_return_val_if_fail(folder->account != NULL, NULL);
1284         g_return_val_if_fail(parent != NULL, NULL);
1285         g_return_val_if_fail(name != NULL, NULL);
1286
1287         session = imap_session_get(folder);
1288         if (!session) return NULL;
1289
1290         if (!parent->parent && strcmp(name, "INBOX") == 0)
1291                 dirpath = g_strdup(name);
1292         else if (parent->path)
1293                 dirpath = g_strconcat(parent->path, "/", name, NULL);
1294         else if ((p = strchr(name, '/')) != NULL && *(p + 1) != '\0')
1295                 dirpath = g_strdup(name);
1296         else if (folder->account->imap_dir && *folder->account->imap_dir) {
1297                 gchar *imap_dir;
1298
1299                 Xstrdup_a(imap_dir, folder->account->imap_dir, return NULL);
1300                 strtailchomp(imap_dir, '/');
1301                 dirpath = g_strconcat(imap_dir, "/", name, NULL);
1302         } else
1303                 dirpath = g_strdup(name);
1304
1305         /* keep trailing directory separator to create a folder that contains
1306            sub folder */
1307         imap_path = imap_locale_to_modified_utf7(dirpath);
1308         strtailchomp(dirpath, '/');
1309         Xstrdup_a(new_name, name, {g_free(dirpath); return NULL;});
1310         strtailchomp(new_name, '/');
1311         separator = imap_get_path_separator(IMAP_FOLDER(folder), imap_path);
1312         imap_path_separator_subst(imap_path, separator);
1313         subst_char(new_name, '/', separator);
1314
1315         if (strcmp(name, "INBOX") != 0) {
1316                 GPtrArray *argbuf;
1317                 gint i;
1318                 gboolean exist = FALSE;
1319
1320                 argbuf = g_ptr_array_new();
1321                 ok = imap_cmd_list(SESSION(session)->sock, NULL, imap_path,
1322                                    argbuf);
1323                 statusbar_pop_all();
1324                 if (ok != IMAP_SUCCESS) {
1325                         log_warning(_("can't create mailbox: LIST failed\n"));
1326                         g_free(imap_path);
1327                         g_free(dirpath);
1328                         g_ptr_array_free(argbuf, TRUE);
1329                         return NULL;
1330                 }
1331
1332                 for (i = 0; i < argbuf->len; i++) {
1333                         gchar *str;
1334                         str = g_ptr_array_index(argbuf, i);
1335                         if (!strncmp(str, "LIST ", 5)) {
1336                                 exist = TRUE;
1337                                 break;
1338                         }
1339                 }
1340                 g_ptr_array_free(argbuf, TRUE);
1341
1342                 if (!exist) {
1343                         ok = imap_cmd_create(SESSION(session)->sock, imap_path);
1344                         statusbar_pop_all();
1345                         if (ok != IMAP_SUCCESS) {
1346                                 log_warning(_("can't create mailbox\n"));
1347                                 g_free(imap_path);
1348                                 g_free(dirpath);
1349                                 return NULL;
1350                         }
1351                 }
1352         }
1353
1354         new_item = folder_item_new(new_name, dirpath);
1355         folder_item_append(parent, new_item);
1356         g_free(imap_path);
1357         g_free(dirpath);
1358
1359         dirpath = folder_item_get_path(new_item);
1360         if (!is_dir_exist(dirpath))
1361                 make_dir_hier(dirpath);
1362         g_free(dirpath);
1363
1364         return new_item;
1365 }
1366
1367 gint imap_rename_folder(Folder *folder, FolderItem *item, const gchar *name)
1368 {
1369         gchar *dirpath;
1370         gchar *newpath;
1371         gchar *real_oldpath;
1372         gchar *real_newpath;
1373         GNode *node;
1374         gchar *paths[2];
1375         gchar *old_cache_dir;
1376         gchar *new_cache_dir;
1377         IMAPSession *session;
1378         gchar separator;
1379         gint ok;
1380         gint exists, recent, unseen;
1381         guint32 uid_validity;
1382
1383         g_return_val_if_fail(folder != NULL, -1);
1384         g_return_val_if_fail(item != NULL, -1);
1385         g_return_val_if_fail(item->path != NULL, -1);
1386         g_return_val_if_fail(name != NULL, -1);
1387
1388         session = imap_session_get(folder);
1389         if (!session) return -1;
1390
1391         real_oldpath = imap_get_real_path(IMAP_FOLDER(folder), item->path);
1392
1393         g_free(session->mbox);
1394         session->mbox = NULL;
1395         ok = imap_cmd_examine(SESSION(session)->sock, "INBOX",
1396                               &exists, &recent, &unseen, &uid_validity);
1397         statusbar_pop_all();
1398         if (ok != IMAP_SUCCESS) {
1399                 g_free(real_oldpath);
1400                 return -1;
1401         }
1402
1403         separator = imap_get_path_separator(IMAP_FOLDER(folder), item->path);
1404         if (strchr(item->path, G_DIR_SEPARATOR)) {
1405                 dirpath = g_dirname(item->path);
1406                 newpath = g_strconcat(dirpath, G_DIR_SEPARATOR_S, name, NULL);
1407                 g_free(dirpath);
1408         } else
1409                 newpath = g_strdup(name);
1410
1411         real_newpath = imap_locale_to_modified_utf7(newpath);
1412         imap_path_separator_subst(real_newpath, separator);
1413
1414         ok = imap_cmd_rename(SESSION(session)->sock, real_oldpath, real_newpath);
1415         statusbar_pop_all();
1416         if (ok != IMAP_SUCCESS) {
1417                 log_warning(_("can't rename mailbox: %s to %s\n"),
1418                             real_oldpath, real_newpath);
1419                 g_free(real_oldpath);
1420                 g_free(newpath);
1421                 g_free(real_newpath);
1422                 return -1;
1423         }
1424
1425         g_free(item->name);
1426         item->name = g_strdup(name);
1427
1428         old_cache_dir = folder_item_get_path(item);
1429
1430         node = g_node_find(item->folder->node, G_PRE_ORDER, G_TRAVERSE_ALL,
1431                            item);
1432         paths[0] = g_strdup(item->path);
1433         paths[1] = newpath;
1434         g_node_traverse(node, G_PRE_ORDER, G_TRAVERSE_ALL, -1,
1435                         imap_rename_folder_func, paths);
1436
1437         if (is_dir_exist(old_cache_dir)) {
1438                 new_cache_dir = folder_item_get_path(item);
1439                 if (rename(old_cache_dir, new_cache_dir) < 0) {
1440                         FILE_OP_ERROR(old_cache_dir, "rename");
1441                 }
1442                 g_free(new_cache_dir);
1443         }
1444
1445         g_free(old_cache_dir);
1446         g_free(paths[0]);
1447         g_free(newpath);
1448         g_free(real_oldpath);
1449         g_free(real_newpath);
1450
1451         return 0;
1452 }
1453
1454 gint imap_remove_folder(Folder *folder, FolderItem *item)
1455 {
1456         gint ok;
1457         IMAPSession *session;
1458         gchar *path;
1459         gchar *cache_dir;
1460         gint exists, recent, unseen;
1461         guint32 uid_validity;
1462
1463         g_return_val_if_fail(folder != NULL, -1);
1464         g_return_val_if_fail(item != NULL, -1);
1465         g_return_val_if_fail(item->path != NULL, -1);
1466
1467         session = imap_session_get(folder);
1468         if (!session) return -1;
1469
1470         path = imap_get_real_path(IMAP_FOLDER(folder), item->path);
1471
1472         ok = imap_cmd_examine(SESSION(session)->sock, "INBOX",
1473                               &exists, &recent, &unseen, &uid_validity);
1474         statusbar_pop_all();
1475         if (ok != IMAP_SUCCESS) {
1476                 g_free(path);
1477                 return -1;
1478         }
1479
1480         ok = imap_cmd_delete(SESSION(session)->sock, path);
1481         statusbar_pop_all();
1482         if (ok != IMAP_SUCCESS) {
1483                 log_warning(_("can't delete mailbox\n"));
1484                 g_free(path);
1485                 return -1;
1486         }
1487
1488         g_free(path);
1489         cache_dir = folder_item_get_path(item);
1490         if (is_dir_exist(cache_dir) && remove_dir_recursive(cache_dir) < 0)
1491                 g_warning("can't remove directory '%s'\n", cache_dir);
1492         g_free(cache_dir);
1493         folder_item_remove(item);
1494
1495         return 0;
1496 }
1497
1498 static GSList *imap_get_uncached_messages(IMAPSession *session,
1499                                           FolderItem *item,
1500                                           guint32 first_uid, guint32 last_uid)
1501 {
1502         gchar *tmp;
1503         GSList *newlist = NULL;
1504         GSList *llast = NULL;
1505         GString *str;
1506         MsgInfo *msginfo;
1507
1508         g_return_val_if_fail(session != NULL, NULL);
1509         g_return_val_if_fail(item != NULL, NULL);
1510         g_return_val_if_fail(item->folder != NULL, NULL);
1511         g_return_val_if_fail(item->folder->type == F_IMAP, NULL);
1512         g_return_val_if_fail(first_uid <= last_uid, NULL);
1513
1514         if (imap_cmd_envelope(SESSION(session)->sock, first_uid, last_uid)
1515             != IMAP_SUCCESS) {
1516                 log_warning(_("can't get envelope\n"));
1517                 return NULL;
1518         }
1519
1520         str = g_string_new(NULL);
1521
1522         for (;;) {
1523                 if ((tmp = sock_getline(SESSION(session)->sock)) == NULL) {
1524                         log_warning(_("error occurred while getting envelope.\n"));
1525                         g_string_free(str, TRUE);
1526                         return newlist;
1527                 }
1528                 strretchomp(tmp);
1529                 if (tmp[0] != '*' || tmp[1] != ' ') {
1530                         log_print("IMAP4< %s\n", tmp);
1531                         g_free(tmp);
1532                         break;
1533                 }
1534                 if (strstr(tmp, "FETCH") == NULL) {
1535                         log_print("IMAP4< %s\n", tmp);
1536                         g_free(tmp);
1537                         continue;
1538                 }
1539                 log_print("IMAP4< %s\n", tmp);
1540                 g_string_assign(str, tmp);
1541                 g_free(tmp);
1542
1543                 msginfo = imap_parse_envelope
1544                         (SESSION(session)->sock, item, str);
1545                 if (!msginfo) {
1546                         log_warning(_("can't parse envelope: %s\n"), str->str);
1547                         continue;
1548                 }
1549                 if (item->stype == F_QUEUE) {
1550                         MSG_SET_TMP_FLAGS(msginfo->flags, MSG_QUEUED);
1551                 } else if (item->stype == F_DRAFT) {
1552                         MSG_SET_TMP_FLAGS(msginfo->flags, MSG_DRAFT);
1553                 }
1554
1555                 msginfo->folder = item;
1556
1557                 if (!newlist)
1558                         llast = newlist = g_slist_append(newlist, msginfo);
1559                 else {
1560                         llast = g_slist_append(llast, msginfo);
1561                         llast = llast->next;
1562                 }
1563         }
1564
1565         g_string_free(str, TRUE);
1566
1567         return newlist;
1568 }
1569
1570 static GSList *imap_delete_cached_messages(GSList *mlist, FolderItem *item,
1571                                            guint32 first_uid, guint32 last_uid)
1572 {
1573         GSList *cur, *next;
1574         MsgInfo *msginfo;
1575         gchar *dir;
1576
1577         g_return_val_if_fail(item != NULL, mlist);
1578         g_return_val_if_fail(item->folder != NULL, mlist);
1579         g_return_val_if_fail(item->folder->type == F_IMAP, mlist);
1580
1581         debug_print(_("Deleting cached messages %u - %u ... "),
1582                     first_uid, last_uid);
1583
1584         dir = folder_item_get_path(item);
1585         remove_numbered_files(dir, first_uid, last_uid);
1586         g_free(dir);
1587
1588         for (cur = mlist; cur != NULL; ) {
1589                 next = cur->next;
1590
1591                 msginfo = (MsgInfo *)cur->data;
1592                 if (msginfo != NULL && first_uid <= msginfo->msgnum &&
1593                     msginfo->msgnum <= last_uid) {
1594                         procmsg_msginfo_free(msginfo);
1595                         mlist = g_slist_remove(mlist, msginfo);
1596                 }
1597
1598                 cur = next;
1599         }
1600
1601         debug_print(_("done.\n"));
1602
1603         return mlist;
1604 }
1605
1606 static void imap_delete_all_cached_messages(FolderItem *item)
1607 {
1608         gchar *dir;
1609
1610         g_return_if_fail(item != NULL);
1611         g_return_if_fail(item->folder != NULL);
1612         g_return_if_fail(item->folder->type == F_IMAP);
1613
1614         debug_print(_("Deleting all cached messages... "));
1615
1616         dir = folder_item_get_path(item);
1617         remove_all_numbered_files(dir);
1618         g_free(dir);
1619
1620         debug_print(_("done.\n"));
1621 }
1622
1623 #if USE_SSL
1624 static SockInfo *imap_open_tunnel(const gchar *server,
1625                            const gchar *tunnelcmd,
1626                            SSLType ssl_type)
1627 #else
1628 static SockInfo *imap_open_tunnel(const gchar *server,
1629                            const gchar *tunnelcmd)
1630 #endif
1631 {
1632         SockInfo *sock;
1633
1634         if ((sock = sock_connect_cmd(server, tunnelcmd)) == NULL)
1635                 log_warning(_("Can't establish IMAP4 session with: %s\n"),
1636                             server);
1637                 return NULL;
1638 #if USE_SSL
1639         return imap_init_sock(sock, ssl_type);
1640 #else
1641         return imap_init_sock(sock);
1642 #endif
1643 }
1644
1645
1646 #if USE_SSL
1647 static SockInfo *imap_open(const gchar *server, gushort port,
1648                            SSLType ssl_type)
1649 #else
1650 static SockInfo *imap_open(const gchar *server, gushort port)
1651 #endif
1652 {
1653         SockInfo *sock;
1654
1655         if ((sock = sock_connect(server, port)) == NULL) {
1656                 log_warning(_("Can't connect to IMAP4 server: %s:%d\n"),
1657                             server, port);
1658                 return NULL;
1659         }
1660
1661 #if USE_SSL
1662         if (ssl_type == SSL_TUNNEL && !ssl_init_socket(sock)) {
1663                 log_warning(_("Can't establish IMAP4 session with: %s:%d\n"),
1664                             server, port);
1665                 sock_close(sock);
1666                 return NULL;
1667         }
1668         return imap_init_sock(sock, ssl_type);
1669 #else
1670         return imap_init_sock(sock);
1671 #endif
1672 }
1673
1674 #if USE_SSL
1675 static SockInfo *imap_init_sock(SockInfo *sock, SSLType ssl_type)
1676 #else
1677 static SockInfo *imap_init_sock(SockInfo *sock)
1678 #endif
1679 {
1680         imap_cmd_count = 0;
1681 #if USE_SSL
1682         if (ssl_type == SSL_STARTTLS) {
1683                 gint ok;
1684
1685                 ok = imap_cmd_starttls(sock);
1686                 if (ok != IMAP_SUCCESS) {
1687                         log_warning(_("Can't start TLS session.\n"));
1688                         sock_close(sock);
1689                         return NULL;
1690                 }
1691                 if (!ssl_init_socket_with_method(sock, SSL_METHOD_TLSv1)) {
1692                         sock_close(sock);
1693                         return NULL;
1694                 }
1695         }
1696 #endif
1697
1698         if (imap_cmd_noop(sock) != IMAP_SUCCESS) {
1699                 log_warning(_("Can't establish IMAP4 session.\n"));
1700                 sock_close(sock);
1701                 return NULL;
1702         }
1703
1704         return sock;
1705 }
1706
1707 static GList *imap_parse_namespace_str(gchar *str)
1708 {
1709         gchar *p = str;
1710         gchar *name;
1711         gchar *separator;
1712         IMAPNameSpace *namespace;
1713         GList *ns_list = NULL;
1714
1715         while (*p != '\0') {
1716                 /* parse ("#foo" "/") */
1717
1718                 while (*p && *p != '(') p++;
1719                 if (*p == '\0') break;
1720                 p++;
1721
1722                 while (*p && *p != '"') p++;
1723                 if (*p == '\0') break;
1724                 p++;
1725                 name = p;
1726
1727                 while (*p && *p != '"') p++;
1728                 if (*p == '\0') break;
1729                 *p = '\0';
1730                 p++;
1731
1732                 while (*p && isspace(*p)) p++;
1733                 if (*p == '\0') break;
1734                 if (strncmp(p, "NIL", 3) == 0)
1735                         separator = NULL;
1736                 else if (*p == '"') {
1737                         p++;
1738                         separator = p;
1739                         while (*p && *p != '"') p++;
1740                         if (*p == '\0') break;
1741                         *p = '\0';
1742                         p++;
1743                 } else break;
1744
1745                 while (*p && *p != ')') p++;
1746                 if (*p == '\0') break;
1747                 p++;
1748
1749                 namespace = g_new(IMAPNameSpace, 1);
1750                 namespace->name = g_strdup(name);
1751                 namespace->separator = separator ? separator[0] : '\0';
1752                 ns_list = g_list_append(ns_list, namespace);
1753         }
1754
1755         return ns_list;
1756 }
1757
1758 static void imap_parse_namespace(IMAPSession *session, IMAPFolder *folder)
1759 {
1760         gchar *ns_str;
1761         gchar **str_array;
1762
1763         g_return_if_fail(session != NULL);
1764         g_return_if_fail(folder != NULL);
1765
1766         if (folder->ns_personal != NULL ||
1767             folder->ns_others   != NULL ||
1768             folder->ns_shared   != NULL)
1769                 return;
1770
1771         if (imap_cmd_namespace(SESSION(session)->sock, &ns_str)
1772             != IMAP_SUCCESS) {
1773                 log_warning(_("can't get namespace\n"));
1774                 return;
1775         }
1776
1777         str_array = strsplit_parenthesis(ns_str, '(', ')', 3);
1778         if (str_array[0])
1779                 folder->ns_personal = imap_parse_namespace_str(str_array[0]);
1780         if (str_array[0] && str_array[1])
1781                 folder->ns_others = imap_parse_namespace_str(str_array[1]);
1782         if (str_array[0] && str_array[1] && str_array[2])
1783                 folder->ns_shared = imap_parse_namespace_str(str_array[2]);
1784         g_strfreev(str_array);
1785         return;
1786 }
1787
1788 static IMAPNameSpace *imap_find_namespace_from_list(GList *ns_list,
1789                                                     const gchar *path)
1790 {
1791         IMAPNameSpace *namespace = NULL;
1792         gchar *tmp_path, *name;
1793
1794         if (!path) path = "";
1795
1796         Xstrcat_a(tmp_path, path, "/", return NULL);
1797
1798         for (; ns_list != NULL; ns_list = ns_list->next) {
1799                 IMAPNameSpace *tmp_ns = ns_list->data;
1800
1801                 Xstrdup_a(name, tmp_ns->name, return namespace);
1802                 if (tmp_ns->separator && tmp_ns->separator != '/')
1803                         subst_char(name, tmp_ns->separator, '/');
1804                 if (strncmp(tmp_path, name, strlen(name)) == 0)
1805                         namespace = tmp_ns;
1806         }
1807
1808         return namespace;
1809 }
1810
1811 static IMAPNameSpace *imap_find_namespace(IMAPFolder *folder,
1812                                           const gchar *path)
1813 {
1814         IMAPNameSpace *namespace;
1815
1816         g_return_val_if_fail(folder != NULL, NULL);
1817
1818         namespace = imap_find_namespace_from_list(folder->ns_personal, path);
1819         if (namespace) return namespace;
1820         namespace = imap_find_namespace_from_list(folder->ns_others, path);
1821         if (namespace) return namespace;
1822         namespace = imap_find_namespace_from_list(folder->ns_shared, path);
1823         if (namespace) return namespace;
1824
1825         return NULL;
1826 }
1827
1828 static gchar imap_get_path_separator(IMAPFolder *folder, const gchar *path)
1829 {
1830         IMAPNameSpace *namespace;
1831         gchar separator = '/';
1832
1833         namespace = imap_find_namespace(folder, path);
1834         if (namespace && namespace->separator)
1835                 separator = namespace->separator;
1836
1837         return separator;
1838 }
1839
1840 static gchar *imap_get_real_path(IMAPFolder *folder, const gchar *path)
1841 {
1842         gchar *real_path;
1843         gchar separator;
1844
1845         g_return_val_if_fail(folder != NULL, NULL);
1846         g_return_val_if_fail(path != NULL, NULL);
1847
1848         real_path = imap_locale_to_modified_utf7(path);
1849         separator = imap_get_path_separator(folder, path);
1850         imap_path_separator_subst(real_path, separator);
1851
1852         return real_path;
1853 }
1854
1855 static gchar *imap_parse_atom(SockInfo *sock, gchar *src,
1856                               gchar *dest, gint dest_len, GString *str)
1857 {
1858         gchar *cur_pos = src;
1859         gchar *nextline;
1860
1861         g_return_val_if_fail(str != NULL, cur_pos);
1862
1863         /* read the next line if the current response buffer is empty */
1864         while (isspace(*cur_pos)) cur_pos++;
1865         while (*cur_pos == '\0') {
1866                 if ((nextline = sock_getline(sock)) == NULL)
1867                         return cur_pos;
1868                 g_string_assign(str, nextline);
1869                 cur_pos = str->str;
1870                 strretchomp(nextline);
1871                 /* log_print("IMAP4< %s\n", nextline); */
1872                 debug_print("IMAP4< %s\n", nextline);
1873                 g_free(nextline);
1874
1875                 while (isspace(*cur_pos)) cur_pos++;
1876         }
1877
1878         if (!strncmp(cur_pos, "NIL", 3)) {
1879                 *dest = '\0';
1880                 cur_pos += 3;
1881         } else if (*cur_pos == '\"') {
1882                 gchar *p;
1883
1884                 p = get_quoted(cur_pos, '\"', dest, dest_len);
1885                 cur_pos = p ? p : cur_pos + 2;
1886         } else if (*cur_pos == '{') {
1887                 gchar buf[32];
1888                 gint len;
1889                 gint line_len = 0;
1890
1891                 cur_pos = strchr_cpy(cur_pos + 1, '}', buf, sizeof(buf));
1892                 len = atoi(buf);
1893
1894                 g_string_truncate(str, 0);
1895                 cur_pos = str->str;
1896
1897                 do {
1898                         if ((nextline = sock_getline(sock)) == NULL)
1899                                 return cur_pos;
1900                         line_len += strlen(nextline);
1901                         g_string_append(str, nextline);
1902                         cur_pos = str->str;
1903                         strretchomp(nextline);
1904                         /* log_print("IMAP4< %s\n", nextline); */
1905                         debug_print("IMAP4< %s\n", nextline);
1906                         g_free(nextline);
1907                 } while (line_len < len);
1908
1909                 memcpy(dest, cur_pos, MIN(len, dest_len - 1));
1910                 dest[MIN(len, dest_len - 1)] = '\0';
1911                 cur_pos += len;
1912         }
1913
1914         return cur_pos;
1915 }
1916
1917 static gchar *imap_get_header(SockInfo *sock, gchar *cur_pos, gchar **headers,
1918                               GString *str)
1919 {
1920         gchar *nextline;
1921         gchar buf[32];
1922         gint len;
1923         gint block_len = 0;
1924
1925         *headers = NULL;
1926
1927         g_return_val_if_fail(str != NULL, cur_pos);
1928
1929         while (isspace(*cur_pos)) cur_pos++;
1930
1931         g_return_val_if_fail(*cur_pos == '{', cur_pos);
1932
1933         cur_pos = strchr_cpy(cur_pos + 1, '}', buf, sizeof(buf));
1934         len = atoi(buf);
1935
1936         g_string_truncate(str, 0);
1937         cur_pos = str->str;
1938
1939         do {
1940                 if ((nextline = sock_getline(sock)) == NULL)
1941                         return cur_pos;
1942                 block_len += strlen(nextline);
1943                 g_string_append(str, nextline);
1944                 cur_pos = str->str;
1945                 strretchomp(nextline);
1946                 /* debug_print("IMAP4< %s\n", nextline); */
1947                 g_free(nextline);
1948         } while (block_len < len);
1949
1950         debug_print("IMAP4< [contents of RFC822.HEADER]\n");
1951
1952         *headers = g_strndup(cur_pos, len);
1953         cur_pos += len;
1954
1955         while (isspace(*cur_pos)) cur_pos++;
1956         while (*cur_pos == '\0') {
1957                 if ((nextline = sock_getline(sock)) == NULL)
1958                         return cur_pos;
1959                 g_string_assign(str, nextline);
1960                 cur_pos = str->str;
1961                 strretchomp(nextline);
1962                 debug_print("IMAP4< %s\n", nextline);
1963                 g_free(nextline);
1964
1965                 while (isspace(*cur_pos)) cur_pos++;
1966         }
1967
1968         return cur_pos;
1969 }
1970
1971 static MsgFlags imap_parse_flags(const gchar *flag_str)  
1972 {
1973         const gchar *p = flag_str;
1974         MsgFlags flags = {0, 0};
1975
1976         flags.perm_flags = MSG_UNREAD;
1977
1978         while ((p = strchr(p, '\\')) != NULL) {
1979                 p++;
1980
1981                 if (g_strncasecmp(p, "Recent", 6) == 0 && MSG_IS_UNREAD(flags)) {
1982                         MSG_SET_PERM_FLAGS(flags, MSG_NEW);
1983                 } else if (g_strncasecmp(p, "Seen", 4) == 0) {
1984                         MSG_UNSET_PERM_FLAGS(flags, MSG_NEW|MSG_UNREAD);
1985                 } else if (g_strncasecmp(p, "Deleted", 7) == 0) {
1986                         MSG_SET_PERM_FLAGS(flags, MSG_DELETED);
1987                 } else if (g_strncasecmp(p, "Flagged", 7) == 0) {
1988                         MSG_SET_PERM_FLAGS(flags, MSG_MARKED);
1989                 } else if (g_strncasecmp(p, "Answered", 8) == 0) {
1990                         MSG_SET_PERM_FLAGS(flags, MSG_REPLIED);
1991                 }
1992         }
1993
1994         return flags;
1995 }
1996
1997 static MsgInfo *imap_parse_envelope(SockInfo *sock, FolderItem *item,
1998                                     GString *line_str)
1999 {
2000         gchar buf[IMAPBUFSIZE];
2001         MsgInfo *msginfo = NULL;
2002         gchar *cur_pos;
2003         gint msgnum;
2004         guint32 uid = 0;
2005         size_t size = 0;
2006         MsgFlags flags = {0, 0}, imap_flags = {0, 0};
2007
2008         g_return_val_if_fail(line_str != NULL, NULL);
2009         g_return_val_if_fail(line_str->str[0] == '*' &&
2010                              line_str->str[1] == ' ', NULL);
2011
2012         MSG_SET_TMP_FLAGS(flags, MSG_IMAP);
2013         if (item->stype == F_QUEUE) {
2014                 MSG_SET_TMP_FLAGS(flags, MSG_QUEUED);
2015         } else if (item->stype == F_DRAFT) {
2016                 MSG_SET_TMP_FLAGS(flags, MSG_DRAFT);
2017         }
2018
2019         cur_pos = line_str->str + 2;
2020
2021 #define PARSE_ONE_ELEMENT(ch)                                   \
2022 {                                                               \
2023         cur_pos = strchr_cpy(cur_pos, ch, buf, sizeof(buf));    \
2024         if (cur_pos == NULL) {                                  \
2025                 g_warning("cur_pos == NULL\n");                 \
2026                 procmsg_msginfo_free(msginfo);                  \
2027                 return NULL;                                    \
2028         }                                                       \
2029 }
2030
2031         PARSE_ONE_ELEMENT(' ');
2032         msgnum = atoi(buf);
2033
2034         PARSE_ONE_ELEMENT(' ');
2035         g_return_val_if_fail(!strcmp(buf, "FETCH"), NULL);
2036
2037         g_return_val_if_fail(*cur_pos == '(', NULL);
2038         cur_pos++;
2039
2040         while (*cur_pos != '\0' && *cur_pos != ')') {
2041                 while (*cur_pos == ' ') cur_pos++;
2042
2043                 if (!strncmp(cur_pos, "UID ", 4)) {
2044                         cur_pos += 4;
2045                         uid = strtoul(cur_pos, &cur_pos, 10);
2046                 } else if (!strncmp(cur_pos, "FLAGS ", 6)) {
2047                         cur_pos += 6;
2048                         if (*cur_pos != '(') {
2049                                 g_warning("*cur_pos != '('\n");
2050                                 procmsg_msginfo_free(msginfo);
2051                                 return NULL;
2052                         }
2053                         cur_pos++;
2054                         PARSE_ONE_ELEMENT(')');
2055                         imap_flags = imap_parse_flags(buf);
2056                 } else if (!strncmp(cur_pos, "RFC822.SIZE ", 12)) {
2057                         cur_pos += 12;
2058                         size = strtol(cur_pos, &cur_pos, 10);
2059                 } else if (!strncmp(cur_pos, "RFC822.HEADER ", 14)) {
2060                         gchar *headers;
2061
2062                         cur_pos += 14;
2063                         cur_pos = imap_get_header(sock, cur_pos, &headers,
2064                                                   line_str);
2065                         msginfo = procheader_parse_str(headers, flags, FALSE, FALSE);
2066                         g_free(headers);
2067                 } else {
2068                         g_warning("invalid FETCH response: %s\n", cur_pos);
2069                         break;
2070                 }
2071         }
2072
2073         if (msginfo) {
2074                 msginfo->msgnum = uid;
2075                 msginfo->size = size;
2076                 msginfo->flags.tmp_flags |= imap_flags.tmp_flags;
2077                 msginfo->flags.perm_flags = imap_flags.perm_flags;
2078         }
2079
2080         return msginfo;
2081 }
2082
2083 gint imap_msg_set_perm_flags(MsgInfo *msginfo, MsgPermFlags flags)
2084 {
2085         Folder *folder;
2086         IMAPSession *session;
2087         IMAPFlags iflags = 0;
2088         gint ok = IMAP_SUCCESS;
2089
2090         g_return_val_if_fail(msginfo != NULL, -1);
2091         g_return_val_if_fail(MSG_IS_IMAP(msginfo->flags), -1);
2092         g_return_val_if_fail(msginfo->folder != NULL, -1);
2093         g_return_val_if_fail(msginfo->folder->folder != NULL, -1);
2094
2095         folder = msginfo->folder->folder;
2096         g_return_val_if_fail(folder->type == F_IMAP, -1);
2097
2098         session = imap_session_get(folder);
2099         if (!session) return -1;
2100
2101         if (flags & MSG_MARKED)  iflags |= IMAP_FLAG_FLAGGED;
2102         if (flags & MSG_REPLIED) iflags |= IMAP_FLAG_ANSWERED;
2103         if (iflags) {
2104                 ok = imap_set_message_flags(session, msginfo->msgnum,
2105                                             msginfo->msgnum, iflags, TRUE);
2106                 if (ok != IMAP_SUCCESS) return ok;
2107         }
2108
2109         if (flags & MSG_UNREAD)
2110                 ok = imap_set_message_flags(session, msginfo->msgnum,
2111                                             msginfo->msgnum, IMAP_FLAG_SEEN,
2112                                             FALSE);
2113         return ok;
2114 }
2115
2116 gint imap_msg_unset_perm_flags(MsgInfo *msginfo, MsgPermFlags flags)
2117 {
2118         Folder *folder;
2119         IMAPSession *session;
2120         IMAPFlags iflags = 0;
2121         gint ok = IMAP_SUCCESS;
2122
2123         g_return_val_if_fail(msginfo != NULL, -1);
2124         g_return_val_if_fail(MSG_IS_IMAP(msginfo->flags), -1);
2125         g_return_val_if_fail(msginfo->folder != NULL, -1);
2126         g_return_val_if_fail(msginfo->folder->folder != NULL, -1);
2127
2128         folder = msginfo->folder->folder;
2129         g_return_val_if_fail(folder->type == F_IMAP, -1);
2130
2131         session = imap_session_get(folder);
2132         if (!session) return -1;
2133
2134         if (flags & MSG_MARKED)  iflags |= IMAP_FLAG_FLAGGED;
2135         if (flags & MSG_REPLIED) iflags |= IMAP_FLAG_ANSWERED;
2136         if (iflags) {
2137                 ok = imap_set_message_flags(session, msginfo->msgnum,
2138                                             msginfo->msgnum, iflags, FALSE);
2139                 if (ok != IMAP_SUCCESS) return ok;
2140         }
2141
2142         if (flags & MSG_UNREAD)
2143                 ok = imap_set_message_flags(session, msginfo->msgnum,
2144                                             msginfo->msgnum, IMAP_FLAG_SEEN,
2145                                             TRUE);
2146         return ok;
2147 }
2148
2149 static gint imap_set_message_flags(IMAPSession *session,
2150                                    guint32 first_uid,
2151                                    guint32 last_uid,
2152                                    IMAPFlags flags,
2153                                    gboolean is_set)
2154 {
2155         GString *buf;
2156         gint ok;
2157
2158         buf = g_string_new(is_set ? "+FLAGS (" : "-FLAGS (");
2159
2160         if (IMAP_IS_SEEN(flags))        g_string_append(buf, "\\Seen ");
2161         if (IMAP_IS_ANSWERED(flags))    g_string_append(buf, "\\Answered ");
2162         if (IMAP_IS_FLAGGED(flags))     g_string_append(buf, "\\Flagged ");
2163         if (IMAP_IS_DELETED(flags))     g_string_append(buf, "\\Deleted ");
2164         if (IMAP_IS_DRAFT(flags))       g_string_append(buf, "\\Draft");
2165
2166         if (buf->str[buf->len - 1] == ' ')
2167                 g_string_truncate(buf, buf->len - 1);
2168
2169         g_string_append_c(buf, ')');
2170
2171         ok = imap_cmd_store(SESSION(session)->sock, first_uid, last_uid,
2172                             buf->str);
2173         g_string_free(buf, TRUE);
2174
2175         return ok;
2176 }
2177
2178 static gint imap_select(IMAPSession *session, IMAPFolder *folder,
2179                         const gchar *path,
2180                         gint *exists, gint *recent, gint *unseen,
2181                         guint32 *uid_validity)
2182 {
2183         gchar *real_path;
2184         gint ok;
2185         gint exists_, recent_, unseen_, uid_validity_;
2186
2187         if (!exists || !recent || !unseen || !uid_validity) {
2188                 if (session->mbox && strcmp(session->mbox, path) == 0)
2189                         return IMAP_SUCCESS;
2190                 exists = &exists_;
2191                 recent = &recent_;
2192                 unseen = &unseen_;
2193                 uid_validity = &uid_validity_;
2194         }
2195
2196         g_free(session->mbox);
2197         session->mbox = NULL;
2198
2199         real_path = imap_get_real_path(folder, path);
2200         ok = imap_cmd_select(SESSION(session)->sock, real_path,
2201                              exists, recent, unseen, uid_validity);
2202         if (ok != IMAP_SUCCESS)
2203                 log_warning(_("can't select folder: %s\n"), real_path);
2204         else
2205                 session->mbox = g_strdup(path);
2206         g_free(real_path);
2207
2208         return ok;
2209 }
2210
2211 #define THROW(err) { ok = err; goto catch; }
2212
2213 static gint imap_get_uid(IMAPSession *session, gint msgnum, guint32 *uid)
2214 {
2215         gint ok;
2216         GPtrArray *argbuf;
2217         gchar *str;
2218         gint num;
2219
2220         *uid = 0;
2221         argbuf = g_ptr_array_new();
2222
2223         imap_cmd_gen_send(SESSION(session)->sock, "FETCH %d (UID)", msgnum);
2224         if ((ok = imap_cmd_ok(SESSION(session)->sock, argbuf)) != IMAP_SUCCESS)
2225                 THROW(ok);
2226
2227         str = search_array_contain_str(argbuf, "FETCH");
2228         if (!str) THROW(IMAP_ERROR);
2229
2230         if (sscanf(str, "%d FETCH (UID %d)", &num, uid) != 2 ||
2231             num != msgnum) {
2232                 g_warning("imap_get_uid(): invalid FETCH line.\n");
2233                 THROW(IMAP_ERROR);
2234         }
2235
2236 catch:
2237         ptr_array_free_strings(argbuf);
2238         g_ptr_array_free(argbuf, TRUE);
2239
2240         return ok;
2241 }
2242
2243 static gint imap_status(IMAPSession *session, IMAPFolder *folder,
2244                         const gchar *path,
2245                         gint *messages, gint *recent,
2246                         guint32 *uid_next, guint32 *uid_validity,
2247                         gint *unseen)
2248 {
2249         gchar *real_path;
2250         gchar *real_path_;
2251         gint ok;
2252         GPtrArray *argbuf;
2253         gchar *str;
2254
2255         *messages = *recent = *uid_next = *uid_validity = *unseen = 0;
2256
2257         argbuf = g_ptr_array_new();
2258
2259         real_path = imap_get_real_path(folder, path);
2260         QUOTE_IF_REQUIRED(real_path_, real_path);
2261         imap_cmd_gen_send(SESSION(session)->sock, "STATUS %s "
2262                           "(MESSAGES RECENT UIDNEXT UIDVALIDITY UNSEEN)",
2263                           real_path_);
2264
2265         ok = imap_cmd_ok(SESSION(session)->sock, argbuf);
2266         if (ok != IMAP_SUCCESS) THROW(ok);
2267
2268         str = search_array_str(argbuf, "STATUS");
2269         if (!str) THROW(IMAP_ERROR);
2270
2271         str = strchr(str, '(');
2272         if (!str) THROW(IMAP_ERROR);
2273         str++;
2274         while (*str != '\0' && *str != ')') {
2275                 while (*str == ' ') str++;
2276
2277                 if (!strncmp(str, "MESSAGES ", 9)) {
2278                         str += 9;
2279                         *messages = strtol(str, &str, 10);
2280                 } else if (!strncmp(str, "RECENT ", 7)) {
2281                         str += 7;
2282                         *recent = strtol(str, &str, 10);
2283                 } else if (!strncmp(str, "UIDNEXT ", 8)) {
2284                         str += 8;
2285                         *uid_next = strtoul(str, &str, 10);
2286                 } else if (!strncmp(str, "UIDVALIDITY ", 12)) {
2287                         str += 12;
2288                         *uid_validity = strtoul(str, &str, 10);
2289                 } else if (!strncmp(str, "UNSEEN ", 7)) {
2290                         str += 7;
2291                         *unseen = strtol(str, &str, 10);
2292                 } else {
2293                         g_warning("invalid STATUS response: %s\n", str);
2294                         break;
2295                 }
2296         }
2297
2298 catch:
2299         g_free(real_path);
2300         ptr_array_free_strings(argbuf);
2301         g_ptr_array_free(argbuf, TRUE);
2302
2303         return ok;
2304 }
2305
2306 #undef THROW
2307
2308
2309 /* low-level IMAP4rev1 commands */
2310
2311 static gint imap_cmd_login(SockInfo *sock,
2312                            const gchar *user, const gchar *pass)
2313 {
2314         gchar *user_, *pass_;
2315         gint ok;
2316
2317         QUOTE_IF_REQUIRED(user_, user);
2318         QUOTE_IF_REQUIRED(pass_, pass);
2319         imap_cmd_gen_send(sock, "LOGIN %s %s", user_, pass_);
2320
2321         ok = imap_cmd_ok(sock, NULL);
2322         if (ok != IMAP_SUCCESS)
2323                 log_warning(_("IMAP4 login failed.\n"));
2324
2325         return ok;
2326 }
2327
2328 static gint imap_cmd_logout(SockInfo *sock)
2329 {
2330         imap_cmd_gen_send(sock, "LOGOUT");
2331         return imap_cmd_ok(sock, NULL);
2332 }
2333
2334 /* Send a NOOP, and examine the server's response to see whether this
2335  * connection is pre-authenticated or not. */
2336 static gint imap_greeting(SockInfo *sock, gboolean *is_preauth)
2337 {
2338         GPtrArray *argbuf;
2339         gint r;
2340
2341         imap_cmd_gen_send(sock, "NOOP");
2342         argbuf = g_ptr_array_new(); /* will hold messages sent back */
2343         r = imap_cmd_ok(sock, argbuf);
2344         *is_preauth = search_array_starts(argbuf, "PREAUTH") != NULL;
2345         
2346         return r;
2347 }
2348
2349 static gint imap_cmd_noop(SockInfo *sock)
2350 {
2351         imap_cmd_gen_send(sock, "NOOP");
2352         return imap_cmd_ok(sock, NULL);
2353 }
2354
2355 static gint imap_cmd_starttls(SockInfo *sock)
2356 {
2357         imap_cmd_gen_send(sock, "STARTTLS");
2358         return imap_cmd_ok(sock, NULL);
2359 }
2360
2361 #define THROW(err) { ok = err; goto catch; }
2362
2363 static gint imap_cmd_namespace(SockInfo *sock, gchar **ns_str)
2364 {
2365         gint ok;
2366         GPtrArray *argbuf;
2367         gchar *str;
2368
2369         argbuf = g_ptr_array_new();
2370
2371         imap_cmd_gen_send(sock, "NAMESPACE");
2372         if ((ok = imap_cmd_ok(sock, argbuf)) != IMAP_SUCCESS) THROW(ok);
2373
2374         str = search_array_str(argbuf, "NAMESPACE");
2375         if (!str) THROW(IMAP_ERROR);
2376
2377         *ns_str = g_strdup(str);
2378
2379 catch:
2380         ptr_array_free_strings(argbuf);
2381         g_ptr_array_free(argbuf, TRUE);
2382
2383         return ok;
2384 }
2385
2386 #undef THROW
2387
2388 static gint imap_cmd_list(SockInfo *sock, const gchar *ref,
2389                           const gchar *mailbox, GPtrArray *argbuf)
2390 {
2391         gchar *ref_, *mailbox_;
2392
2393         if (!ref) ref = "\"\"";
2394         if (!mailbox) mailbox = "\"\"";
2395
2396         QUOTE_IF_REQUIRED(ref_, ref);
2397         QUOTE_IF_REQUIRED(mailbox_, mailbox);
2398         imap_cmd_gen_send(sock, "LIST %s %s", ref_, mailbox_);
2399
2400         return imap_cmd_ok(sock, argbuf);
2401 }
2402
2403 #define THROW goto catch
2404
2405 static gint imap_cmd_do_select(SockInfo *sock, const gchar *folder,
2406                                gboolean examine,
2407                                gint *exists, gint *recent, gint *unseen,
2408                                guint32 *uid_validity)
2409 {
2410         gint ok;
2411         gchar *resp_str;
2412         GPtrArray *argbuf;
2413         gchar *select_cmd;
2414         gchar *folder_;
2415
2416         *exists = *recent = *unseen = *uid_validity = 0;
2417         argbuf = g_ptr_array_new();
2418
2419         if (examine)
2420                 select_cmd = "EXAMINE";
2421         else
2422                 select_cmd = "SELECT";
2423
2424         QUOTE_IF_REQUIRED(folder_, folder);
2425         imap_cmd_gen_send(sock, "%s %s", select_cmd, folder_);
2426
2427         if ((ok = imap_cmd_ok(sock, argbuf)) != IMAP_SUCCESS) THROW;
2428
2429         resp_str = search_array_contain_str(argbuf, "EXISTS");
2430         if (resp_str) {
2431                 if (sscanf(resp_str,"%d EXISTS", exists) != 1) {
2432                         g_warning("imap_cmd_select(): invalid EXISTS line.\n");
2433                         THROW;
2434                 }
2435         }
2436
2437         resp_str = search_array_contain_str(argbuf, "RECENT");
2438         if (resp_str) {
2439                 if (sscanf(resp_str, "%d RECENT", recent) != 1) {
2440                         g_warning("imap_cmd_select(): invalid RECENT line.\n");
2441                         THROW;
2442                 }
2443         }
2444
2445         resp_str = search_array_contain_str(argbuf, "UIDVALIDITY");
2446         if (resp_str) {
2447                 if (sscanf(resp_str, "OK [UIDVALIDITY %u] ", uid_validity)
2448                     != 1) {
2449                         g_warning("imap_cmd_select(): invalid UIDVALIDITY line.\n");
2450                         THROW;
2451                 }
2452         }
2453
2454         resp_str = search_array_contain_str(argbuf, "UNSEEN");
2455         if (resp_str) {
2456                 if (sscanf(resp_str, "OK [UNSEEN %d] ", unseen) != 1) {
2457                         g_warning("imap_cmd_select(): invalid UNSEEN line.\n");
2458                         THROW;
2459                 }
2460         }
2461
2462 catch:
2463         ptr_array_free_strings(argbuf);
2464         g_ptr_array_free(argbuf, TRUE);
2465
2466         return ok;
2467 }
2468
2469 static gint imap_cmd_select(SockInfo *sock, const gchar *folder,
2470                             gint *exists, gint *recent, gint *unseen,
2471                             guint32 *uid_validity)
2472 {
2473         return imap_cmd_do_select(sock, folder, FALSE,
2474                                   exists, recent, unseen, uid_validity);
2475 }
2476
2477 static gint imap_cmd_examine(SockInfo *sock, const gchar *folder,
2478                              gint *exists, gint *recent, gint *unseen,
2479                              guint32 *uid_validity)
2480 {
2481         return imap_cmd_do_select(sock, folder, TRUE,
2482                                   exists, recent, unseen, uid_validity);
2483 }
2484
2485 #undef THROW
2486
2487 static gint imap_cmd_create(SockInfo *sock, const gchar *folder)
2488 {
2489         gchar *folder_;
2490
2491         QUOTE_IF_REQUIRED(folder_, folder);
2492         imap_cmd_gen_send(sock, "CREATE %s", folder_);
2493
2494         return imap_cmd_ok(sock, NULL);
2495 }
2496
2497 static gint imap_cmd_rename(SockInfo *sock, const gchar *old_folder,
2498                             const gchar *new_folder)
2499 {
2500         gchar *old_folder_, *new_folder_;
2501
2502         QUOTE_IF_REQUIRED(old_folder_, old_folder);
2503         QUOTE_IF_REQUIRED(new_folder_, new_folder);
2504         imap_cmd_gen_send(sock, "RENAME %s %s", old_folder_, new_folder_);
2505
2506         return imap_cmd_ok(sock, NULL);
2507 }
2508
2509 static gint imap_cmd_delete(SockInfo *sock, const gchar *folder)
2510 {
2511         gchar *folder_;
2512
2513         QUOTE_IF_REQUIRED(folder_, folder);
2514         imap_cmd_gen_send(sock, "DELETE %s", folder_);
2515
2516         return imap_cmd_ok(sock, NULL);
2517 }
2518
2519 static gint imap_cmd_fetch(SockInfo *sock, guint32 uid, const gchar *filename)
2520 {
2521         gint ok;
2522         gchar buf[IMAPBUFSIZE];
2523         gchar *cur_pos;
2524         gchar size_str[32];
2525         glong size_num;
2526
2527         g_return_val_if_fail(filename != NULL, IMAP_ERROR);
2528
2529         imap_cmd_gen_send(sock, "UID FETCH %d BODY[]", uid);
2530
2531         while ((ok = imap_cmd_gen_recv(sock, buf, sizeof(buf)))
2532                == IMAP_SUCCESS) {
2533                 if (buf[0] != '*' || buf[1] != ' ')
2534                         return IMAP_ERROR;
2535                 if (strstr(buf, "FETCH") != NULL)
2536                         break;
2537         }
2538         if (ok != IMAP_SUCCESS)
2539                 return ok;
2540
2541         cur_pos = strchr(buf, '{');
2542         g_return_val_if_fail(cur_pos != NULL, IMAP_ERROR);
2543         cur_pos = strchr_cpy(cur_pos + 1, '}', size_str, sizeof(size_str));
2544         g_return_val_if_fail(cur_pos != NULL, IMAP_ERROR);
2545         size_num = atol(size_str);
2546
2547         if (*cur_pos != '\0') return IMAP_ERROR;
2548
2549         if (recv_bytes_write_to_file(sock, size_num, filename) != 0)
2550                 return IMAP_ERROR;
2551
2552         if (imap_cmd_gen_recv(sock, buf, sizeof(buf)) != IMAP_SUCCESS)
2553                 return IMAP_ERROR;
2554
2555         if (buf[0] == '\0' || buf[strlen(buf) - 1] != ')')
2556                 return IMAP_ERROR;
2557
2558         ok = imap_cmd_ok(sock, NULL);
2559
2560         return ok;
2561 }
2562
2563 static gint imap_cmd_append(SockInfo *sock, const gchar *destfolder,
2564                             const gchar *file)
2565 {
2566         gint ok;
2567         gint size;
2568         gchar *destfolder_;
2569         gchar buf[BUFFSIZE];
2570         FILE *fp;
2571
2572         g_return_val_if_fail(file != NULL, IMAP_ERROR);
2573
2574         size = get_file_size_as_crlf(file);
2575         if ((fp = fopen(file, "rb")) == NULL) {
2576                 FILE_OP_ERROR(file, "fopen");
2577                 return -1;
2578         }
2579         QUOTE_IF_REQUIRED(destfolder_, destfolder);
2580         imap_cmd_gen_send(sock, "APPEND %s (\\Seen) {%d}", destfolder_, size);
2581
2582         ok = imap_cmd_gen_recv(sock, buf, sizeof(buf));
2583         if (ok != IMAP_SUCCESS || buf[0] != '+' || buf[1] != ' ') {
2584                 log_warning(_("can't append %s to %s\n"), file, destfolder_);
2585                 fclose(fp);
2586                 return IMAP_ERROR;
2587         }
2588
2589         log_print("IMAP4> %s\n", _("(sending file...)"));
2590
2591         while (fgets(buf, sizeof(buf), fp) != NULL) {
2592                 strretchomp(buf);
2593                 if (sock_puts(sock, buf) < 0) {
2594                         fclose(fp);
2595                         sock_close(sock);
2596                         return -1;
2597                 }
2598         }
2599
2600         if (ferror(fp)) {
2601                 FILE_OP_ERROR(file, "fgets");
2602                 fclose(fp);
2603                 sock_close(sock);
2604                 return -1;
2605         }
2606
2607         sock_puts(sock, "");
2608
2609         fclose(fp);
2610         return imap_cmd_ok(sock, NULL);
2611 }
2612
2613 static gint imap_cmd_copy(SockInfo *sock, guint32 uid, const gchar *destfolder)
2614 {
2615         gint ok;
2616         gchar *destfolder_;
2617
2618         g_return_val_if_fail(destfolder != NULL, IMAP_ERROR);
2619
2620         QUOTE_IF_REQUIRED(destfolder_, destfolder);
2621         imap_cmd_gen_send(sock, "UID COPY %d %s", uid, destfolder_);
2622
2623         ok = imap_cmd_ok(sock, NULL);
2624         if (ok != IMAP_SUCCESS) {
2625                 log_warning(_("can't copy %d to %s\n"), uid, destfolder_);
2626                 return -1;
2627         }
2628
2629         return ok;
2630 }
2631
2632 gint imap_cmd_envelope(SockInfo *sock, guint32 first_uid, guint32 last_uid)
2633 {
2634         imap_cmd_gen_send
2635                 (sock, "UID FETCH %d:%d (UID FLAGS RFC822.SIZE RFC822.HEADER)",
2636                  first_uid, last_uid);
2637
2638         return IMAP_SUCCESS;
2639 }
2640
2641 static gint imap_cmd_store(SockInfo *sock, guint32 first_uid, guint32 last_uid,
2642                            gchar *sub_cmd)
2643 {
2644         gint ok;
2645
2646         imap_cmd_gen_send(sock, "UID STORE %d:%d %s",
2647                           first_uid, last_uid, sub_cmd);
2648
2649         if ((ok = imap_cmd_ok(sock, NULL)) != IMAP_SUCCESS) {
2650                 log_warning(_("error while imap command: STORE %d:%d %s\n"),
2651                             first_uid, last_uid, sub_cmd);
2652                 return ok;
2653         }
2654
2655         return IMAP_SUCCESS;
2656 }
2657
2658 static gint imap_cmd_expunge(SockInfo *sock)
2659 {
2660         gint ok;
2661
2662         imap_cmd_gen_send(sock, "EXPUNGE");
2663         if ((ok = imap_cmd_ok(sock, NULL)) != IMAP_SUCCESS) {
2664                 log_warning(_("error while imap command: EXPUNGE\n"));
2665                 return ok;
2666         }
2667
2668         return IMAP_SUCCESS;
2669 }
2670
2671 static gint imap_cmd_ok(SockInfo *sock, GPtrArray *argbuf)
2672 {
2673         gint ok;
2674         gchar buf[IMAPBUFSIZE];
2675         gint cmd_num;
2676         gchar cmd_status[IMAPBUFSIZE];
2677
2678         while ((ok = imap_cmd_gen_recv(sock, buf, sizeof(buf)))
2679                == IMAP_SUCCESS) {
2680                 if (buf[0] == '*' && buf[1] == ' ') {
2681                         if (argbuf)
2682                                 g_ptr_array_add(argbuf, g_strdup(buf + 2));
2683                         continue;
2684                 }
2685
2686                 if (sscanf(buf, "%d %s", &cmd_num, cmd_status) < 2)
2687                         return IMAP_ERROR;
2688                 else if (cmd_num == imap_cmd_count &&
2689                          !strcmp(cmd_status, "OK")) {
2690                         if (argbuf)
2691                                 g_ptr_array_add(argbuf, g_strdup(buf));
2692                         return IMAP_SUCCESS;
2693                 } else
2694                         return IMAP_ERROR;
2695         }
2696
2697         return ok;
2698 }
2699
2700 static void imap_cmd_gen_send(SockInfo *sock, const gchar *format, ...)
2701 {
2702         gchar buf[IMAPBUFSIZE];
2703         gchar tmp[IMAPBUFSIZE];
2704         gchar *p;
2705         va_list args;
2706
2707         va_start(args, format);
2708         g_vsnprintf(tmp, sizeof(tmp), format, args);
2709         va_end(args);
2710
2711         imap_cmd_count++;
2712
2713         g_snprintf(buf, sizeof(buf), "%d %s\r\n", imap_cmd_count, tmp);
2714         if (!strncasecmp(tmp, "LOGIN ", 6) && (p = strchr(tmp + 6, ' '))) {
2715                 *p = '\0';
2716                 log_print("IMAP4> %d %s ********\n", imap_cmd_count, tmp);
2717         } else
2718                 log_print("IMAP4> %d %s\n", imap_cmd_count, tmp);
2719
2720         sock_write(sock, buf, strlen(buf));
2721 }
2722
2723 static gint imap_cmd_gen_recv(SockInfo *sock, gchar *buf, gint size)
2724 {
2725         if (sock_gets(sock, buf, size) == -1)
2726                 return IMAP_SOCKET;
2727
2728         strretchomp(buf);
2729
2730         log_print("IMAP4< %s\n", buf);
2731
2732         return IMAP_SUCCESS;
2733 }
2734
2735
2736 /* misc utility functions */
2737
2738 static gchar *strchr_cpy(const gchar *src, gchar ch, gchar *dest, gint len)
2739 {
2740         gchar *tmp;
2741
2742         dest[0] = '\0';
2743         tmp = strchr(src, ch);
2744         if (!tmp)
2745                 return NULL;
2746
2747         memcpy(dest, src, MIN(tmp - src, len - 1));
2748         dest[MIN(tmp - src, len - 1)] = '\0';
2749
2750         return tmp + 1;
2751 }
2752
2753 static gchar *get_quoted(const gchar *src, gchar ch, gchar *dest, gint len)
2754 {
2755         const gchar *p = src;
2756         gint n = 0;
2757
2758         g_return_val_if_fail(*p == ch, NULL);
2759
2760         *dest = '\0';
2761         p++;
2762
2763         while (*p != '\0' && *p != ch) {
2764                 if (n < len - 1) {
2765                         if (*p == '\\' && *(p + 1) != '\0')
2766                                 p++;
2767                         *dest++ = *p++;
2768                 } else
2769                         p++;
2770                 n++;
2771         }
2772
2773         *dest = '\0';
2774         return (gchar *)(*p == ch ? p + 1 : p);
2775 }
2776
2777 static gchar *search_array_starts(GPtrArray *array, const gchar *str)
2778 {
2779         gint i;
2780         size_t len;
2781
2782         g_return_val_if_fail(str != NULL, NULL);
2783         len = strlen(str);
2784         for (i = 0; i < array->len; i++) {
2785                 gchar *tmp;
2786                 tmp = g_ptr_array_index(array, i);
2787                 if (strncmp(tmp, str, len) == 0)
2788                         return tmp;
2789         }
2790         return NULL;
2791 }
2792
2793 static gchar *search_array_contain_str(GPtrArray *array, gchar *str)
2794 {
2795         gint i;
2796
2797         for (i = 0; i < array->len; i++) {
2798                 gchar *tmp;
2799
2800                 tmp = g_ptr_array_index(array, i);
2801                 if (strstr(tmp, str) != NULL)
2802                         return tmp;
2803         }
2804
2805         return NULL;
2806 }
2807
2808 static gchar *search_array_str(GPtrArray *array, gchar *str)
2809 {
2810         gint i;
2811         gint len;
2812
2813         len = strlen(str);
2814
2815         for (i = 0; i < array->len; i++) {
2816                 gchar *tmp;
2817
2818                 tmp = g_ptr_array_index(array, i);
2819                 if (!strncmp(tmp, str, len))
2820                         return tmp;
2821         }
2822
2823         return NULL;
2824 }
2825
2826 static void imap_path_separator_subst(gchar *str, gchar separator)
2827 {
2828         gchar *p;
2829         gboolean in_escape = FALSE;
2830
2831         if (!separator || separator == '/') return;
2832
2833         for (p = str; *p != '\0'; p++) {
2834                 if (*p == '/' && !in_escape)
2835                         *p = separator;
2836                 else if (*p == '&' && *(p + 1) != '-' && !in_escape)
2837                         in_escape = TRUE;
2838                 else if (*p == '-' && in_escape)
2839                         in_escape = FALSE;
2840         }
2841 }
2842
2843 static gchar *imap_modified_utf7_to_locale(const gchar *mutf7_str)
2844 {
2845 #if !HAVE_LIBJCONV
2846         return g_strdup(mutf7_str);
2847 #else
2848         static iconv_t cd = (iconv_t)-1;
2849         static gboolean iconv_ok = TRUE;
2850         GString *norm_utf7;
2851         gchar *norm_utf7_p;
2852         size_t norm_utf7_len;
2853         const gchar *p;
2854         gchar *to_str, *to_p;
2855         size_t to_len;
2856         gboolean in_escape = FALSE;
2857
2858         if (!iconv_ok) return g_strdup(mutf7_str);
2859
2860         if (cd == (iconv_t)-1) {
2861                 cd = iconv_open(conv_get_current_charset_str(), "UTF-7");
2862                 if (cd == (iconv_t)-1) {
2863                         g_warning(_("iconv cannot convert UTF-7 to %s\n"),
2864                                   conv_get_current_charset_str());
2865                         iconv_ok = FALSE;
2866                         return g_strdup(mutf7_str);
2867                 }
2868         }
2869
2870         norm_utf7 = g_string_new(NULL);
2871
2872         for (p = mutf7_str; *p != '\0'; p++) {
2873                 /* replace: '&'  -> '+',
2874                             "&-" -> '&',
2875                             escaped ','  -> '/' */
2876                 if (!in_escape && *p == '&') {
2877                         if (*(p + 1) != '-') {
2878                                 g_string_append_c(norm_utf7, '+');
2879                                 in_escape = TRUE;
2880                         } else {
2881                                 g_string_append_c(norm_utf7, '&');
2882                                 p++;
2883                         }
2884                 } else if (in_escape && *p == ',') {
2885                         g_string_append_c(norm_utf7, '/');
2886                 } else if (in_escape && *p == '-') {
2887                         g_string_append_c(norm_utf7, '-');
2888                         in_escape = FALSE;
2889                 } else {
2890                         g_string_append_c(norm_utf7, *p);
2891                 }
2892         }
2893
2894         norm_utf7_p = norm_utf7->str;
2895         norm_utf7_len = norm_utf7->len;
2896         to_len = strlen(mutf7_str) * 5;
2897         to_p = to_str = g_malloc(to_len + 1);
2898
2899         if (iconv(cd, &norm_utf7_p, &norm_utf7_len, &to_p, &to_len) == -1) {
2900                 g_warning(_("iconv cannot convert UTF-7 to %s\n"),
2901                           conv_get_current_charset_str());
2902                 g_string_free(norm_utf7, TRUE);
2903                 g_free(to_str);
2904                 return g_strdup(mutf7_str);
2905         }
2906
2907         /* second iconv() call for flushing */
2908         iconv(cd, NULL, NULL, &to_p, &to_len);
2909         g_string_free(norm_utf7, TRUE);
2910         *to_p = '\0';
2911
2912         return to_str;
2913 #endif /* !HAVE_LIBJCONV */
2914 }
2915
2916 static gchar *imap_locale_to_modified_utf7(const gchar *from)
2917 {
2918 #if !HAVE_LIBJCONV
2919         return g_strdup(from);
2920 #else
2921         static iconv_t cd = (iconv_t)-1;
2922         static gboolean iconv_ok = TRUE;
2923         gchar *norm_utf7, *norm_utf7_p;
2924         size_t from_len, norm_utf7_len;
2925         GString *to_str;
2926         gchar *from_tmp, *to, *p;
2927         gboolean in_escape = FALSE;
2928
2929         if (!iconv_ok) return g_strdup(from);
2930
2931         if (cd == (iconv_t)-1) {
2932                 cd = iconv_open("UTF-7", conv_get_current_charset_str());
2933                 if (cd == (iconv_t)-1) {
2934                         g_warning(_("iconv cannot convert %s to UTF-7\n"),
2935                                   conv_get_current_charset_str());
2936                         iconv_ok = FALSE;
2937                         return g_strdup(from);
2938                 }
2939         }
2940
2941         Xstrdup_a(from_tmp, from, return g_strdup(from));
2942         from_len = strlen(from);
2943         norm_utf7_len = from_len * 5;
2944         Xalloca(norm_utf7, norm_utf7_len + 1, return g_strdup(from));
2945         norm_utf7_p = norm_utf7;
2946
2947 #define IS_PRINT(ch) (isprint(ch) && isascii(ch))
2948
2949         while (from_len > 0) {
2950                 if (IS_PRINT(*from_tmp)) {
2951                         /* printable ascii char */
2952                         *norm_utf7_p = *from_tmp;
2953                         norm_utf7_p++;
2954                         from_tmp++;
2955                         from_len--;
2956                 } else {
2957                         size_t mblen;
2958
2959                         /* unprintable char: convert to UTF-7 */
2960                         for (mblen = 0;
2961                              !IS_PRINT(from_tmp[mblen]) && mblen < from_len;
2962                              mblen++)
2963                                 ;
2964                         from_len -= mblen;
2965                         if (iconv(cd, &from_tmp, &mblen,
2966                                   &norm_utf7_p, &norm_utf7_len) == -1) {
2967                                 g_warning(_("iconv cannot convert %s to UTF-7\n"),
2968                                           conv_get_current_charset_str());
2969                                 return g_strdup(from);
2970                         }
2971
2972                         /* second iconv() call for flushing */
2973                         iconv(cd, NULL, NULL, &norm_utf7_p, &norm_utf7_len);
2974                 }
2975         }
2976
2977 #undef IS_PRINT
2978
2979         *norm_utf7_p = '\0';
2980         to_str = g_string_new(NULL);
2981         for (p = norm_utf7; p < norm_utf7_p; p++) {
2982                 /* replace: '&' -> "&-",
2983                             '+' -> '&',
2984                             escaped '/' -> ',' */
2985                 if (!in_escape && *p == '&') {
2986                         g_string_append(to_str, "&-");
2987                 } else if (!in_escape && *p == '+') {
2988                         g_string_append_c(to_str, '&');
2989                         in_escape = TRUE;
2990                 } else if (in_escape && *p == '/') {
2991                         g_string_append_c(to_str, ',');
2992                 } else if (in_escape && *p == '-') {
2993                         in_escape = FALSE;
2994                         g_string_append_c(to_str, '-');
2995                 } else {
2996                         g_string_append_c(to_str, *p);
2997                 }
2998         }
2999
3000         if (in_escape) {
3001                 in_escape = FALSE;
3002                 g_string_append_c(to_str, '-');
3003         }
3004
3005         to = to_str->str;
3006         g_string_free(to_str, FALSE);
3007
3008         return to;
3009 #endif
3010 }
3011
3012 static gboolean imap_rename_folder_func(GNode *node, gpointer data)
3013 {
3014         FolderItem *item = node->data;
3015         gchar **paths = data;
3016         const gchar *oldpath = paths[0];
3017         const gchar *newpath = paths[1];
3018         gchar *base;
3019         gchar *new_itempath;
3020         gint oldpathlen;
3021
3022         oldpathlen = strlen(oldpath);
3023         if (strncmp(oldpath, item->path, oldpathlen) != 0) {
3024                 g_warning("path doesn't match: %s, %s\n", oldpath, item->path);
3025                 return TRUE;
3026         }
3027
3028         base = item->path + oldpathlen;
3029         while (*base == G_DIR_SEPARATOR) base++;
3030         if (*base == '\0')
3031                 new_itempath = g_strdup(newpath);
3032         else
3033                 new_itempath = g_strconcat(newpath, G_DIR_SEPARATOR_S, base,
3034                                            NULL);
3035         g_free(item->path);
3036         item->path = new_itempath;
3037
3038         return FALSE;
3039 }
3040
3041 GSList *imap_get_num_list(Folder *folder, FolderItem *item)
3042 {
3043         IMAPSession *session;
3044         GSList *msgnum_list = NULL;
3045         gint i;
3046         gint ok, exists = 0, recent = 0, unseen = 0;
3047         guint32 uid_validity = 0;
3048         GPtrArray *argbuf;
3049         
3050         g_return_val_if_fail(folder != NULL, NULL);
3051         g_return_val_if_fail(item != NULL, NULL);
3052         g_return_val_if_fail(item->path != NULL, NULL);
3053         g_return_val_if_fail(folder->type == F_IMAP, NULL);
3054         g_return_val_if_fail(folder->account != NULL, NULL);
3055
3056         session = imap_session_get(folder);
3057         g_return_val_if_fail(session != NULL, NULL);
3058
3059         ok = imap_select(session, IMAP_FOLDER(folder), item->path,
3060                          &exists, &recent, &unseen, &uid_validity);
3061         if (ok != IMAP_SUCCESS)
3062                 return NULL;
3063
3064         argbuf = g_ptr_array_new();
3065         imap_cmd_gen_send(SESSION(session)->sock, "FETCH 1:* (UID)");
3066         ok = imap_cmd_ok(SESSION(session)->sock, argbuf);
3067         if (ok != IMAP_SUCCESS) {
3068                 ptr_array_free_strings(argbuf);
3069                 g_ptr_array_free(argbuf, TRUE);
3070                 return NULL;
3071         }
3072
3073         for(i = 0; i < argbuf->len; i++) {
3074                 int ret, msgidx, msgnum;
3075         
3076                 if((ret = sscanf(g_ptr_array_index(argbuf, i), "%d FETCH (UID %d)", &msgidx, &msgnum)) == 2) {
3077                         msgnum_list = g_slist_prepend(msgnum_list, GINT_TO_POINTER(msgnum));
3078                 }
3079         }
3080         
3081         return msgnum_list;
3082 }
3083
3084 MsgInfo *imap_fetch_msginfo(Folder *folder, FolderItem *item, gint num)
3085 {
3086         gchar *tmp;
3087         IMAPSession *session;
3088         GString *str;
3089         MsgInfo *msginfo;
3090         gint ok, exists = 0, recent = 0, unseen = 0;
3091         guint32 uid_validity = 0;
3092         
3093         g_return_val_if_fail(folder != NULL, NULL);
3094         g_return_val_if_fail(item != NULL, NULL);
3095         g_return_val_if_fail(item->folder != NULL, NULL);
3096         g_return_val_if_fail(item->folder->type == F_IMAP, NULL);
3097
3098         session = imap_session_get(folder);
3099         g_return_val_if_fail(session != NULL, NULL);
3100
3101         ok = imap_select(session, IMAP_FOLDER(folder), item->path,
3102                          &exists, &recent, &unseen, &uid_validity);
3103         if (ok != IMAP_SUCCESS)
3104                 return NULL;
3105         
3106         if (imap_cmd_envelope(SESSION(session)->sock, num, num)
3107             != IMAP_SUCCESS) {
3108                 log_warning(_("can't get envelope\n"));
3109                 return NULL;
3110         }
3111
3112         str = g_string_new(NULL);
3113
3114         if ((tmp = sock_getline(SESSION(session)->sock)) == NULL) {
3115                 log_warning(_("error occurred while getting envelope.\n"));
3116                 g_string_free(str, TRUE);
3117                 return NULL;
3118         }
3119         strretchomp(tmp);
3120         log_print("IMAP4< %s\n", tmp);
3121         g_string_assign(str, tmp);
3122         g_free(tmp);
3123
3124         msginfo = imap_parse_envelope(SESSION(session)->sock, item, str);
3125         if (!msginfo) {
3126                 log_warning(_("can't parse envelope: %s\n"), str->str);
3127         }
3128
3129         tmp = NULL;
3130         do {
3131                 g_free(tmp);
3132                 tmp = sock_getline(SESSION(session)->sock);
3133         } while (!(tmp == NULL || tmp[0] != '*' || tmp[1] != ' '));
3134         
3135         msginfo->folder = item;
3136
3137         g_string_free(str, TRUE);
3138         
3139         return msginfo;
3140 }