edddafd5e767aa0e6d99924b16adc2a6f1711fd6
[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 ok;
686
687         g_return_val_if_fail(folder != NULL, -1);
688         g_return_val_if_fail(folder->type == F_IMAP, -1);
689         g_return_val_if_fail(dest != NULL, -1);
690         g_return_val_if_fail(msginfo != NULL, -1);
691
692         session = imap_session_get(folder);
693         if (!session) return -1;
694
695         if (msginfo->folder == dest) {
696                 g_warning(_("the src folder is identical to the dest.\n"));
697                 return -1;
698         }
699
700         destdir = imap_get_real_path(IMAP_FOLDER(folder), dest->path);
701
702         if (remove_source)
703                 debug_print(_("Moving message %s%c%d to %s ...\n"),
704                             msginfo->folder->path, G_DIR_SEPARATOR,
705                             msginfo->msgnum, destdir);
706         else
707                 debug_print(_("Copying message %s%c%d to %s ...\n"),
708                             msginfo->folder->path, G_DIR_SEPARATOR,
709                             msginfo->msgnum, destdir);
710
711         ok = imap_cmd_copy(SESSION(session)->sock, msginfo->msgnum, destdir);
712
713         if (ok == IMAP_SUCCESS && remove_source) {
714                 imap_set_message_flags(session, msginfo->msgnum, msginfo->msgnum,
715                                        IMAP_FLAG_DELETED, TRUE);
716                 ok = imap_cmd_expunge(SESSION(session)->sock);
717         }
718
719         g_free(destdir);
720         statusbar_pop_all();
721
722         if (ok == IMAP_SUCCESS)
723                 return 0;
724         else
725                 return -1;
726 }
727
728 static gint imap_do_copy_msgs_with_dest(Folder *folder, FolderItem *dest, 
729                                         GSList *msglist,
730                                         gboolean remove_source)
731 {
732         gchar *destdir;
733         GSList *cur;
734         MsgInfo *msginfo;
735         IMAPSession *session;
736         gint ok = IMAP_SUCCESS;
737
738         g_return_val_if_fail(folder != NULL, -1);
739         g_return_val_if_fail(dest != NULL, -1);
740         g_return_val_if_fail(msglist != NULL, -1);
741
742         session = imap_session_get(folder);
743         if (!session) return -1;
744
745         destdir = imap_get_real_path(IMAP_FOLDER(folder), dest->path);
746
747         for (cur = msglist; cur != NULL; cur = cur->next) {
748                 msginfo = (MsgInfo *)cur->data;
749
750                 if (msginfo->folder == dest) {
751                         g_warning(_("the src folder is identical to the dest.\n"));
752                         continue;
753                 }
754
755                 if (remove_source)
756                         debug_print(_("Moving message %s%c%d to %s ...\n"),
757                                     msginfo->folder->path, G_DIR_SEPARATOR,
758                                     msginfo->msgnum, destdir);
759                 else
760                         debug_print(_("Copying message %s%c%d to %s ...\n"),
761                                     msginfo->folder->path, G_DIR_SEPARATOR,
762                                     msginfo->msgnum, destdir);
763
764                 ok = imap_cmd_copy(SESSION(session)->sock, msginfo->msgnum,
765                                    destdir);
766
767                 if (ok == IMAP_SUCCESS && remove_source) {
768                         imap_set_message_flags
769                                 (session, msginfo->msgnum, msginfo->msgnum,
770                                  IMAP_FLAG_DELETED, TRUE);
771                 }
772         }
773
774         if (remove_source)
775                 ok = imap_cmd_expunge(SESSION(session)->sock);
776
777         g_free(destdir);
778         statusbar_pop_all();
779
780         if (ok == IMAP_SUCCESS)
781                 return 0;
782         else
783                 return -1;
784 }
785
786 gint imap_move_msg(Folder *folder, FolderItem *dest, MsgInfo *msginfo)
787 {
788         gchar *srcfile;
789         gint ret = 0;
790
791         g_return_val_if_fail(folder != NULL, -1);
792         g_return_val_if_fail(dest != NULL, -1);
793         g_return_val_if_fail(msginfo != NULL, -1);
794         g_return_val_if_fail(msginfo->folder != NULL, -1);
795
796         if (folder == msginfo->folder->folder)
797                 return imap_do_copy(folder, dest, msginfo, TRUE);
798
799         srcfile = procmsg_get_message_file(msginfo);
800         if (!srcfile) return -1;
801
802         ret = imap_add_msg(folder, dest, srcfile, FALSE);
803         g_free(srcfile);
804
805         if (ret != -1)
806                 ret = folder_item_remove_msg(msginfo->folder, msginfo->msgnum);
807
808         return ret;
809 }
810
811 gint imap_move_msgs_with_dest(Folder *folder, FolderItem *dest, 
812                               GSList *msglist)
813 {
814         MsgInfo *msginfo;
815         GSList *cur;
816         gint ret = 0;
817
818         g_return_val_if_fail(folder != NULL, -1);
819         g_return_val_if_fail(dest != NULL, -1);
820         g_return_val_if_fail(msglist != NULL, -1);
821
822         msginfo = (MsgInfo *)msglist->data;
823         if (folder == msginfo->folder->folder)
824                 return imap_do_copy_msgs_with_dest(folder, dest, msglist, TRUE);
825
826         for (cur = msglist; cur != NULL; cur = cur->next) {
827                 msginfo = (MsgInfo *)cur->data;
828                 ret = imap_move_msg(folder, dest, msginfo);
829                 if (ret == -1) break;
830         }
831
832         return ret;
833 }
834
835 gint imap_copy_msg(Folder *folder, FolderItem *dest, MsgInfo *msginfo)
836 {
837         gchar *srcfile;
838         gint ret = 0;
839
840         g_return_val_if_fail(folder != NULL, -1);
841         g_return_val_if_fail(dest != NULL, -1);
842         g_return_val_if_fail(msginfo != NULL, -1);
843         g_return_val_if_fail(msginfo->folder != NULL, -1);
844
845         if (folder == msginfo->folder->folder)
846                 return imap_do_copy(folder, dest, msginfo, FALSE);
847
848         srcfile = procmsg_get_message_file(msginfo);
849         if (!srcfile) return -1;
850
851         ret = imap_add_msg(folder, dest, srcfile, FALSE);
852
853         g_free(srcfile);
854
855         return ret;
856 }
857
858 gint imap_copy_msgs_with_dest(Folder *folder, FolderItem *dest, 
859                               GSList *msglist)
860 {
861         MsgInfo *msginfo;
862         GSList *cur;
863         gint ret = 0;
864
865         g_return_val_if_fail(folder != NULL, -1);
866         g_return_val_if_fail(dest != NULL, -1);
867         g_return_val_if_fail(msglist != NULL, -1);
868
869         msginfo = (MsgInfo *)msglist->data;
870         if (folder == msginfo->folder->folder)
871                 return imap_do_copy_msgs_with_dest
872                         (folder, dest, msglist, FALSE);
873
874         for (cur = msglist; cur != NULL; cur = cur->next) {
875                 msginfo = (MsgInfo *)cur->data;
876                 ret = imap_copy_msg(folder, dest, msginfo);
877                 if (ret == -1) break;
878         }
879
880         return ret;
881 }
882
883 gint imap_remove_msg(Folder *folder, FolderItem *item, gint uid)
884 {
885         gint exists, recent, unseen;
886         guint32 uid_validity;
887         gint ok;
888         IMAPSession *session;
889
890         g_return_val_if_fail(folder != NULL, -1);
891         g_return_val_if_fail(folder->type == F_IMAP, -1);
892         g_return_val_if_fail(item != NULL, -1);
893
894         session = imap_session_get(folder);
895         if (!session) return -1;
896
897         ok = imap_select(session, IMAP_FOLDER(folder), item->path,
898                          &exists, &recent, &unseen, &uid_validity);
899         statusbar_pop_all();
900         if (ok != IMAP_SUCCESS)
901                 return ok;
902
903         ok = imap_set_message_flags
904                 (IMAP_SESSION(REMOTE_FOLDER(folder)->session),
905                  (guint32)uid, (guint32)uid, IMAP_FLAG_DELETED, TRUE);
906         statusbar_pop_all();
907         if (ok != IMAP_SUCCESS) {
908                 log_warning(_("can't set deleted flags: %d\n"), uid);
909                 return ok;
910         }
911
912         ok = imap_cmd_expunge(SESSION(session)->sock);
913         statusbar_pop_all();
914         if (ok != IMAP_SUCCESS) {
915                 log_warning(_("can't expunge\n"));
916                 return ok;
917         }
918
919         return IMAP_SUCCESS;
920 }
921
922 gint imap_remove_all_msg(Folder *folder, FolderItem *item)
923 {
924         gint exists, recent, unseen;
925         guint32 uid_validity;
926         gint ok;
927         IMAPSession *session;
928
929         g_return_val_if_fail(folder != NULL, -1);
930         g_return_val_if_fail(item != NULL, -1);
931
932         session = imap_session_get(folder);
933         if (!session) return -1;
934
935         ok = imap_select(session, IMAP_FOLDER(folder), item->path,
936                          &exists, &recent, &unseen, &uid_validity);
937         statusbar_pop_all();
938         if (ok != IMAP_SUCCESS)
939                 return ok;
940         if (exists == 0)
941                 return IMAP_SUCCESS;
942
943         imap_cmd_gen_send(SESSION(session)->sock,
944                           "STORE 1:%d +FLAGS (\\Deleted)", exists);
945         ok = imap_cmd_ok(SESSION(session)->sock, NULL);
946         statusbar_pop_all();
947         if (ok != IMAP_SUCCESS) {
948                 log_warning(_("can't set deleted flags: 1:%d\n"), exists);
949                 return ok;
950         }
951
952         ok = imap_cmd_expunge(SESSION(session)->sock);
953         statusbar_pop_all();
954         if (ok != IMAP_SUCCESS) {
955                 log_warning(_("can't expunge\n"));
956                 return ok;
957         }
958
959         return IMAP_SUCCESS;
960 }
961
962 gboolean imap_is_msg_changed(Folder *folder, FolderItem *item, MsgInfo *msginfo)
963 {
964         /* TODO: properly implement this method */
965         return FALSE;
966 }
967
968 gint imap_scan_folder(Folder *folder, FolderItem *item)
969 {
970         IMAPSession *session;
971         gint messages, recent, unseen;
972         guint32 uid_next, uid_validity;
973         gint ok;
974
975         g_return_val_if_fail(folder != NULL, -1);
976         g_return_val_if_fail(item != NULL, -1);
977
978         session = imap_session_get(folder);
979         if (!session) return -1;
980
981         ok = imap_status(session, IMAP_FOLDER(folder), item->path,
982                          &messages, &recent, &uid_next, &uid_validity, &unseen);
983         statusbar_pop_all();
984         if (ok != IMAP_SUCCESS) return -1;
985
986         item->new = unseen > 0 ? recent : 0;
987         item->unread = unseen;
988         item->total = messages;
989         item->last_num = (messages > 0 && uid_next > 0) ? uid_next - 1 : 0;
990         /* item->mtime = uid_validity; */
991
992         return 0;
993 }
994
995 void imap_scan_tree(Folder *folder)
996 {
997         FolderItem *item;
998         IMAPSession *session;
999         gchar *root_folder = NULL;
1000
1001         g_return_if_fail(folder != NULL);
1002         g_return_if_fail(folder->account != NULL);
1003
1004         session = imap_session_get(folder);
1005         if (!session) return;
1006
1007         if (folder->account->imap_dir && *folder->account->imap_dir) {
1008                 Xstrdup_a(root_folder, folder->account->imap_dir, return);
1009                 strtailchomp(root_folder, '/');
1010                 debug_print("IMAP root directory: %s\n", root_folder);
1011         }
1012
1013         folder_tree_destroy(folder);
1014         item = folder_item_new(folder->name, root_folder);
1015         item->folder = folder;
1016         folder->node = g_node_new(item);
1017
1018         imap_scan_tree_recursive(session, item);
1019
1020         imap_create_missing_folders(folder);
1021 }
1022
1023 static gint imap_scan_tree_recursive(IMAPSession *session, FolderItem *item)
1024 {
1025         Folder *folder;
1026         IMAPFolder *imapfolder;
1027         FolderItem *new_item;
1028         GSList *item_list, *cur;
1029         gchar *real_path;
1030         gchar *wildcard_path;
1031         gchar separator;
1032         gchar wildcard[3];
1033
1034         g_return_val_if_fail(item != NULL, -1);
1035         g_return_val_if_fail(item->folder != NULL, -1);
1036         g_return_val_if_fail(item->no_sub == FALSE, -1);
1037
1038         folder = FOLDER(item->folder);
1039         imapfolder = IMAP_FOLDER(folder);
1040
1041         separator = imap_get_path_separator(imapfolder, item->path);
1042
1043         if (item->folder->ui_func)
1044                 item->folder->ui_func(folder, item, folder->ui_func_data);
1045
1046         if (item->path) {
1047                 wildcard[0] = separator;
1048                 wildcard[1] = '%';
1049                 wildcard[2] = '\0';
1050                 real_path = imap_get_real_path(imapfolder, item->path);
1051         } else {
1052                 wildcard[0] = '%';
1053                 wildcard[1] = '\0';
1054                 real_path = g_strdup("");
1055         }
1056
1057         Xstrcat_a(wildcard_path, real_path, wildcard,
1058                   {g_free(real_path); return IMAP_ERROR;});
1059         QUOTE_IF_REQUIRED(wildcard_path, wildcard_path);
1060
1061         imap_cmd_gen_send(SESSION(session)->sock, "LIST \"\" %s",
1062                           wildcard_path);
1063
1064         strtailchomp(real_path, separator);
1065         item_list = imap_parse_list(session, real_path);
1066         g_free(real_path);
1067
1068         for (cur = item_list; cur != NULL; cur = cur->next) {
1069                 new_item = cur->data;
1070                 if (!strcmp(new_item->path, "INBOX")) {
1071                         if (!folder->inbox) {
1072                                 new_item->stype = F_INBOX;
1073                                 item->folder->inbox = new_item;
1074                         } else {
1075                                 folder_item_destroy(new_item);
1076                                 continue;
1077                         }
1078                 } else if (!item->parent || item->stype == F_INBOX) {
1079                         gchar *base;
1080
1081                         base = g_basename(new_item->path);
1082
1083                         if (!folder->outbox && !strcasecmp(base, "Sent")) {
1084                                 new_item->stype = F_OUTBOX;
1085                                 folder->outbox = new_item;
1086                         } else if (!folder->draft && !strcasecmp(base, "Drafts")) {
1087                                 new_item->stype = F_DRAFT;
1088                                 folder->draft = new_item;
1089                         } else if (!folder->queue && !strcasecmp(base, "Queue")) {
1090                                 new_item->stype = F_QUEUE;
1091                                 folder->queue = new_item;
1092                         } else if (!folder->trash && !strcasecmp(base, "Trash")) {
1093                                 new_item->stype = F_TRASH;
1094                                 folder->trash = new_item;
1095                         }
1096                 }
1097                 folder_item_append(item, new_item);
1098                 if (new_item->no_select == FALSE)
1099                         imap_scan_folder(folder, new_item);
1100                 if (new_item->no_sub == FALSE)
1101                         imap_scan_tree_recursive(session, new_item);
1102         }
1103
1104         return IMAP_SUCCESS;
1105 }
1106
1107 static GSList *imap_parse_list(IMAPSession *session, const gchar *real_path)
1108 {
1109         gchar buf[IMAPBUFSIZE];
1110         gchar flags[256];
1111         gchar separator[16];
1112         gchar *p;
1113         gchar *name;
1114         gchar *loc_name, *loc_path;
1115         GSList *item_list = NULL;
1116         GString *str;
1117         FolderItem *new_item;
1118
1119         debug_print("getting list of %s ...\n",
1120                     *real_path ? real_path : "\"\"");
1121
1122         str = g_string_new(NULL);
1123
1124         for (;;) {
1125                 if (sock_gets(SESSION(session)->sock, buf, sizeof(buf)) <= 0) {
1126                         log_warning(_("error occured while getting LIST.\n"));
1127                         break;
1128                 }
1129                 strretchomp(buf);
1130                 if (buf[0] != '*' || buf[1] != ' ') {
1131                         log_print("IMAP4< %s\n", buf);
1132                         break;
1133                 }
1134                 debug_print("IMAP4< %s\n", buf);
1135
1136                 g_string_assign(str, buf);
1137                 p = str->str + 2;
1138                 if (strncmp(p, "LIST ", 5) != 0) continue;
1139                 p += 5;
1140
1141                 if (*p != '(') continue;
1142                 p++;
1143                 p = strchr_cpy(p, ')', flags, sizeof(flags));
1144                 if (!p) continue;
1145                 while (*p == ' ') p++;
1146
1147                 p = strchr_cpy(p, ' ', separator, sizeof(separator));
1148                 if (!p) continue;
1149                 extract_quote(separator, '"');
1150                 if (!strcmp(separator, "NIL"))
1151                         separator[0] = '\0';
1152
1153                 buf[0] = '\0';
1154                 while (*p == ' ') p++;
1155                 if (*p == '{' || *p == '"')
1156                         p = imap_parse_atom(SESSION(session)->sock, p,
1157                                             buf, sizeof(buf), str);
1158                 else
1159                         strncpy2(buf, p, sizeof(buf));
1160                 strtailchomp(buf, separator[0]);
1161                 if (buf[0] == '\0') continue;
1162                 if (!strcmp(buf, real_path)) continue;
1163
1164                 if (separator[0] != '\0')
1165                         subst_char(buf, separator[0], '/');
1166                 name = g_basename(buf);
1167                 if (name[0] == '.') continue;
1168
1169                 loc_name = imap_modified_utf7_to_locale(name);
1170                 loc_path = imap_modified_utf7_to_locale(buf);
1171                 new_item = folder_item_new(loc_name, loc_path);
1172                 if (strcasestr(flags, "\\Noinferiors") != NULL)
1173                         new_item->no_sub = TRUE;
1174                 if (strcmp(buf, "INBOX") != 0 &&
1175                     strcasestr(flags, "\\Noselect") != NULL)
1176                         new_item->no_select = TRUE;
1177
1178                 item_list = g_slist_append(item_list, new_item);
1179
1180                 debug_print("folder %s has been added.\n", loc_path);
1181                 g_free(loc_path);
1182                 g_free(loc_name);
1183         }
1184
1185         g_string_free(str, TRUE);
1186         statusbar_pop_all();
1187
1188         return item_list;
1189 }
1190
1191 gint imap_create_tree(Folder *folder)
1192 {
1193         g_return_val_if_fail(folder != NULL, -1);
1194         g_return_val_if_fail(folder->node != NULL, -1);
1195         g_return_val_if_fail(folder->node->data != NULL, -1);
1196         g_return_val_if_fail(folder->account != NULL, -1);
1197
1198         imap_scan_tree(folder);
1199         imap_create_missing_folders(folder);
1200
1201         return 0;
1202 }
1203
1204 static void imap_create_missing_folders(Folder *folder)
1205 {
1206         g_return_if_fail(folder != NULL);
1207
1208         if (!folder->inbox)
1209                 folder->inbox = imap_create_special_folder
1210                         (folder, F_INBOX, "INBOX");
1211 #if 0
1212         if (!folder->outbox)
1213                 folder->outbox = imap_create_special_folder
1214                         (folder, F_OUTBOX, "Sent");
1215         if (!folder->draft)
1216                 folder->draft = imap_create_special_folder
1217                         (folder, F_DRAFT, "Drafts");
1218         if (!folder->queue)
1219                 folder->queue = imap_create_special_folder
1220                         (folder, F_QUEUE, "Queue");
1221 #endif
1222         if (!folder->trash)
1223                 folder->trash = imap_create_special_folder
1224                         (folder, F_TRASH, "Trash");
1225 }
1226
1227 static FolderItem *imap_create_special_folder(Folder *folder,
1228                                               SpecialFolderItemType stype,
1229                                               const gchar *name)
1230 {
1231         FolderItem *item;
1232         FolderItem *new_item;
1233
1234         g_return_val_if_fail(folder != NULL, NULL);
1235         g_return_val_if_fail(folder->node != NULL, NULL);
1236         g_return_val_if_fail(folder->node->data != NULL, NULL);
1237         g_return_val_if_fail(folder->account != NULL, NULL);
1238         g_return_val_if_fail(name != NULL, NULL);
1239
1240         item = FOLDER_ITEM(folder->node->data);
1241         new_item = imap_create_folder(folder, item, name);
1242
1243         if (!new_item) {
1244                 g_warning(_("Can't create '%s'\n"), name);
1245                 if (!folder->inbox) return NULL;
1246
1247                 new_item = imap_create_folder(folder, folder->inbox, name);
1248                 if (!new_item)
1249                         g_warning(_("Can't create '%s' under INBOX\n"), name);
1250                 else
1251                         new_item->stype = stype;
1252         } else
1253                 new_item->stype = stype;
1254
1255         return new_item;
1256 }
1257
1258 FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
1259                                const gchar *name)
1260 {
1261         gchar *dirpath, *imap_path;
1262         IMAPSession *session;
1263         FolderItem *new_item;
1264         gchar separator;
1265         gchar *new_name;
1266         const gchar *p;
1267         gint ok;
1268
1269         g_return_val_if_fail(folder != NULL, NULL);
1270         g_return_val_if_fail(folder->account != NULL, NULL);
1271         g_return_val_if_fail(parent != NULL, NULL);
1272         g_return_val_if_fail(name != NULL, NULL);
1273
1274         session = imap_session_get(folder);
1275         if (!session) return NULL;
1276
1277         if (!parent->parent && strcmp(name, "INBOX") == 0)
1278                 dirpath = g_strdup(name);
1279         else if (parent->path)
1280                 dirpath = g_strconcat(parent->path, "/", name, NULL);
1281         else if ((p = strchr(name, '/')) != NULL && *(p + 1) != '\0')
1282                 dirpath = g_strdup(name);
1283         else if (folder->account->imap_dir && *folder->account->imap_dir) {
1284                 gchar *imap_dir;
1285
1286                 Xstrdup_a(imap_dir, folder->account->imap_dir, return NULL);
1287                 strtailchomp(imap_dir, '/');
1288                 dirpath = g_strconcat(imap_dir, "/", name, NULL);
1289         } else
1290                 dirpath = g_strdup(name);
1291
1292         /* keep trailing directory separator to create a folder that contains
1293            sub folder */
1294         imap_path = imap_locale_to_modified_utf7(dirpath);
1295         strtailchomp(dirpath, '/');
1296         Xstrdup_a(new_name, name, {g_free(dirpath); return NULL;});
1297         strtailchomp(new_name, '/');
1298         separator = imap_get_path_separator(IMAP_FOLDER(folder), imap_path);
1299         imap_path_separator_subst(imap_path, separator);
1300         subst_char(new_name, '/', separator);
1301
1302         if (strcmp(name, "INBOX") != 0) {
1303                 GPtrArray *argbuf;
1304                 gint i;
1305                 gboolean exist = FALSE;
1306
1307                 argbuf = g_ptr_array_new();
1308                 ok = imap_cmd_list(SESSION(session)->sock, NULL, imap_path,
1309                                    argbuf);
1310                 statusbar_pop_all();
1311                 if (ok != IMAP_SUCCESS) {
1312                         log_warning(_("can't create mailbox: LIST failed\n"));
1313                         g_free(imap_path);
1314                         g_free(dirpath);
1315                         g_ptr_array_free(argbuf, TRUE);
1316                         return NULL;
1317                 }
1318
1319                 for (i = 0; i < argbuf->len; i++) {
1320                         gchar *str;
1321                         str = g_ptr_array_index(argbuf, i);
1322                         if (!strncmp(str, "LIST ", 5)) {
1323                                 exist = TRUE;
1324                                 break;
1325                         }
1326                 }
1327                 g_ptr_array_free(argbuf, TRUE);
1328
1329                 if (!exist) {
1330                         ok = imap_cmd_create(SESSION(session)->sock, imap_path);
1331                         statusbar_pop_all();
1332                         if (ok != IMAP_SUCCESS) {
1333                                 log_warning(_("can't create mailbox\n"));
1334                                 g_free(imap_path);
1335                                 g_free(dirpath);
1336                                 return NULL;
1337                         }
1338                 }
1339         }
1340
1341         new_item = folder_item_new(new_name, dirpath);
1342         folder_item_append(parent, new_item);
1343         g_free(imap_path);
1344         g_free(dirpath);
1345
1346         dirpath = folder_item_get_path(new_item);
1347         if (!is_dir_exist(dirpath))
1348                 make_dir_hier(dirpath);
1349         g_free(dirpath);
1350
1351         return new_item;
1352 }
1353
1354 gint imap_rename_folder(Folder *folder, FolderItem *item, const gchar *name)
1355 {
1356         gchar *dirpath;
1357         gchar *newpath;
1358         gchar *real_oldpath;
1359         gchar *real_newpath;
1360         GNode *node;
1361         gchar *paths[2];
1362         gchar *old_cache_dir;
1363         gchar *new_cache_dir;
1364         IMAPSession *session;
1365         gchar separator;
1366         gint ok;
1367         gint exists, recent, unseen;
1368         guint32 uid_validity;
1369
1370         g_return_val_if_fail(folder != NULL, -1);
1371         g_return_val_if_fail(item != NULL, -1);
1372         g_return_val_if_fail(item->path != NULL, -1);
1373         g_return_val_if_fail(name != NULL, -1);
1374
1375         session = imap_session_get(folder);
1376         if (!session) return -1;
1377
1378         real_oldpath = imap_get_real_path(IMAP_FOLDER(folder), item->path);
1379
1380         g_free(session->mbox);
1381         session->mbox = NULL;
1382         ok = imap_cmd_examine(SESSION(session)->sock, "INBOX",
1383                               &exists, &recent, &unseen, &uid_validity);
1384         statusbar_pop_all();
1385         if (ok != IMAP_SUCCESS) {
1386                 g_free(real_oldpath);
1387                 return -1;
1388         }
1389
1390         separator = imap_get_path_separator(IMAP_FOLDER(folder), item->path);
1391         if (strchr(item->path, G_DIR_SEPARATOR)) {
1392                 dirpath = g_dirname(item->path);
1393                 newpath = g_strconcat(dirpath, G_DIR_SEPARATOR_S, name, NULL);
1394                 g_free(dirpath);
1395         } else
1396                 newpath = g_strdup(name);
1397
1398         real_newpath = imap_locale_to_modified_utf7(newpath);
1399         imap_path_separator_subst(real_newpath, separator);
1400
1401         ok = imap_cmd_rename(SESSION(session)->sock, real_oldpath, real_newpath);
1402         statusbar_pop_all();
1403         if (ok != IMAP_SUCCESS) {
1404                 log_warning(_("can't rename mailbox: %s to %s\n"),
1405                             real_oldpath, real_newpath);
1406                 g_free(real_oldpath);
1407                 g_free(newpath);
1408                 g_free(real_newpath);
1409                 return -1;
1410         }
1411
1412         g_free(item->name);
1413         item->name = g_strdup(name);
1414
1415         old_cache_dir = folder_item_get_path(item);
1416
1417         node = g_node_find(item->folder->node, G_PRE_ORDER, G_TRAVERSE_ALL,
1418                            item);
1419         paths[0] = g_strdup(item->path);
1420         paths[1] = newpath;
1421         g_node_traverse(node, G_PRE_ORDER, G_TRAVERSE_ALL, -1,
1422                         imap_rename_folder_func, paths);
1423
1424         if (is_dir_exist(old_cache_dir)) {
1425                 new_cache_dir = folder_item_get_path(item);
1426                 if (rename(old_cache_dir, new_cache_dir) < 0) {
1427                         FILE_OP_ERROR(old_cache_dir, "rename");
1428                 }
1429                 g_free(new_cache_dir);
1430         }
1431
1432         g_free(old_cache_dir);
1433         g_free(paths[0]);
1434         g_free(newpath);
1435         g_free(real_oldpath);
1436         g_free(real_newpath);
1437
1438         return 0;
1439 }
1440
1441 gint imap_remove_folder(Folder *folder, FolderItem *item)
1442 {
1443         gint ok;
1444         IMAPSession *session;
1445         gchar *path;
1446         gchar *cache_dir;
1447         gint exists, recent, unseen;
1448         guint32 uid_validity;
1449
1450         g_return_val_if_fail(folder != NULL, -1);
1451         g_return_val_if_fail(item != NULL, -1);
1452         g_return_val_if_fail(item->path != NULL, -1);
1453
1454         session = imap_session_get(folder);
1455         if (!session) return -1;
1456
1457         path = imap_get_real_path(IMAP_FOLDER(folder), item->path);
1458
1459         ok = imap_cmd_examine(SESSION(session)->sock, "INBOX",
1460                               &exists, &recent, &unseen, &uid_validity);
1461         statusbar_pop_all();
1462         if (ok != IMAP_SUCCESS) {
1463                 g_free(path);
1464                 return -1;
1465         }
1466
1467         ok = imap_cmd_delete(SESSION(session)->sock, path);
1468         statusbar_pop_all();
1469         if (ok != IMAP_SUCCESS) {
1470                 log_warning(_("can't delete mailbox\n"));
1471                 g_free(path);
1472                 return -1;
1473         }
1474
1475         g_free(path);
1476         cache_dir = folder_item_get_path(item);
1477         if (is_dir_exist(cache_dir) && remove_dir_recursive(cache_dir) < 0)
1478                 g_warning("can't remove directory '%s'\n", cache_dir);
1479         g_free(cache_dir);
1480         folder_item_remove(item);
1481
1482         return 0;
1483 }
1484
1485 static GSList *imap_get_uncached_messages(IMAPSession *session,
1486                                           FolderItem *item,
1487                                           guint32 first_uid, guint32 last_uid)
1488 {
1489         gchar *tmp;
1490         GSList *newlist = NULL;
1491         GSList *llast = NULL;
1492         GString *str;
1493         MsgInfo *msginfo;
1494
1495         g_return_val_if_fail(session != NULL, NULL);
1496         g_return_val_if_fail(item != NULL, NULL);
1497         g_return_val_if_fail(item->folder != NULL, NULL);
1498         g_return_val_if_fail(item->folder->type == F_IMAP, NULL);
1499         g_return_val_if_fail(first_uid <= last_uid, NULL);
1500
1501         if (imap_cmd_envelope(SESSION(session)->sock, first_uid, last_uid)
1502             != IMAP_SUCCESS) {
1503                 log_warning(_("can't get envelope\n"));
1504                 return NULL;
1505         }
1506
1507         str = g_string_new(NULL);
1508
1509         for (;;) {
1510                 if ((tmp = sock_getline(SESSION(session)->sock)) == NULL) {
1511                         log_warning(_("error occurred while getting envelope.\n"));
1512                         g_string_free(str, TRUE);
1513                         return newlist;
1514                 }
1515                 strretchomp(tmp);
1516                 if (tmp[0] != '*' || tmp[1] != ' ') {
1517                         log_print("IMAP4< %s\n", tmp);
1518                         g_free(tmp);
1519                         break;
1520                 }
1521                 if (strstr(tmp, "FETCH") == NULL) {
1522                         log_print("IMAP4< %s\n", tmp);
1523                         g_free(tmp);
1524                         continue;
1525                 }
1526                 log_print("IMAP4< %s\n", tmp);
1527                 g_string_assign(str, tmp);
1528                 g_free(tmp);
1529
1530                 msginfo = imap_parse_envelope
1531                         (SESSION(session)->sock, item, str);
1532                 if (!msginfo) {
1533                         log_warning(_("can't parse envelope: %s\n"), str->str);
1534                         continue;
1535                 }
1536                 if (item->stype == F_QUEUE) {
1537                         MSG_SET_TMP_FLAGS(msginfo->flags, MSG_QUEUED);
1538                 } else if (item->stype == F_DRAFT) {
1539                         MSG_SET_TMP_FLAGS(msginfo->flags, MSG_DRAFT);
1540                 }
1541
1542                 msginfo->folder = item;
1543
1544                 if (!newlist)
1545                         llast = newlist = g_slist_append(newlist, msginfo);
1546                 else {
1547                         llast = g_slist_append(llast, msginfo);
1548                         llast = llast->next;
1549                 }
1550         }
1551
1552         g_string_free(str, TRUE);
1553
1554         return newlist;
1555 }
1556
1557 static GSList *imap_delete_cached_messages(GSList *mlist, FolderItem *item,
1558                                            guint32 first_uid, guint32 last_uid)
1559 {
1560         GSList *cur, *next;
1561         MsgInfo *msginfo;
1562         gchar *dir;
1563
1564         g_return_val_if_fail(item != NULL, mlist);
1565         g_return_val_if_fail(item->folder != NULL, mlist);
1566         g_return_val_if_fail(item->folder->type == F_IMAP, mlist);
1567
1568         debug_print(_("Deleting cached messages %u - %u ... "),
1569                     first_uid, last_uid);
1570
1571         dir = folder_item_get_path(item);
1572         remove_numbered_files(dir, first_uid, last_uid);
1573         g_free(dir);
1574
1575         for (cur = mlist; cur != NULL; ) {
1576                 next = cur->next;
1577
1578                 msginfo = (MsgInfo *)cur->data;
1579                 if (msginfo != NULL && first_uid <= msginfo->msgnum &&
1580                     msginfo->msgnum <= last_uid) {
1581                         procmsg_msginfo_free(msginfo);
1582                         mlist = g_slist_remove(mlist, msginfo);
1583                 }
1584
1585                 cur = next;
1586         }
1587
1588         debug_print(_("done.\n"));
1589
1590         return mlist;
1591 }
1592
1593 static void imap_delete_all_cached_messages(FolderItem *item)
1594 {
1595         gchar *dir;
1596
1597         g_return_if_fail(item != NULL);
1598         g_return_if_fail(item->folder != NULL);
1599         g_return_if_fail(item->folder->type == F_IMAP);
1600
1601         debug_print(_("Deleting all cached messages... "));
1602
1603         dir = folder_item_get_path(item);
1604         remove_all_numbered_files(dir);
1605         g_free(dir);
1606
1607         debug_print(_("done.\n"));
1608 }
1609
1610 #if USE_SSL
1611 static SockInfo *imap_open_tunnel(const gchar *server,
1612                            const gchar *tunnelcmd,
1613                            SSLType ssl_type)
1614 #else
1615 static SockInfo *imap_open_tunnel(const gchar *server,
1616                            const gchar *tunnelcmd)
1617 #endif
1618 {
1619         SockInfo *sock;
1620
1621         if ((sock = sock_connect_cmd(server, tunnelcmd)) == NULL)
1622                 log_warning(_("Can't establish IMAP4 session with: %s\n"),
1623                             server);
1624                 return NULL;
1625 #if USE_SSL
1626         return imap_init_sock(sock, ssl_type);
1627 #else
1628         return imap_init_sock(sock);
1629 #endif
1630 }
1631
1632
1633 #if USE_SSL
1634 static SockInfo *imap_open(const gchar *server, gushort port,
1635                            SSLType ssl_type)
1636 #else
1637 static SockInfo *imap_open(const gchar *server, gushort port)
1638 #endif
1639 {
1640         SockInfo *sock;
1641
1642         if ((sock = sock_connect(server, port)) == NULL) {
1643                 log_warning(_("Can't connect to IMAP4 server: %s:%d\n"),
1644                             server, port);
1645                 return NULL;
1646         }
1647
1648 #if USE_SSL
1649         if (ssl_type == SSL_TUNNEL && !ssl_init_socket(sock)) {
1650                 log_warning(_("Can't establish IMAP4 session with: %s:%d\n"),
1651                             server, port);
1652                 sock_close(sock);
1653                 return NULL;
1654         }
1655         return imap_init_sock(sock, ssl_type);
1656 #else
1657         return imap_init_sock(sock);
1658 #endif
1659 }
1660
1661 #if USE_SSL
1662 static SockInfo *imap_init_sock(SockInfo *sock, SSLType ssl_type)
1663 #else
1664 static SockInfo *imap_init_sock(SockInfo *sock)
1665 #endif
1666 {
1667         imap_cmd_count = 0;
1668 #if USE_SSL
1669         if (ssl_type == SSL_STARTTLS) {
1670                 gint ok;
1671
1672                 ok = imap_cmd_starttls(sock);
1673                 if (ok != IMAP_SUCCESS) {
1674                         log_warning(_("Can't start TLS session.\n"));
1675                         sock_close(sock);
1676                         return NULL;
1677                 }
1678                 if (!ssl_init_socket_with_method(sock, SSL_METHOD_TLSv1)) {
1679                         sock_close(sock);
1680                         return NULL;
1681                 }
1682         }
1683 #endif
1684
1685         if (imap_cmd_noop(sock) != IMAP_SUCCESS) {
1686                 log_warning(_("Can't establish IMAP4 session.\n"));
1687                 sock_close(sock);
1688                 return NULL;
1689         }
1690
1691         return sock;
1692 }
1693
1694 static GList *imap_parse_namespace_str(gchar *str)
1695 {
1696         gchar *p = str;
1697         gchar *name;
1698         gchar *separator;
1699         IMAPNameSpace *namespace;
1700         GList *ns_list = NULL;
1701
1702         while (*p != '\0') {
1703                 /* parse ("#foo" "/") */
1704
1705                 while (*p && *p != '(') p++;
1706                 if (*p == '\0') break;
1707                 p++;
1708
1709                 while (*p && *p != '"') p++;
1710                 if (*p == '\0') break;
1711                 p++;
1712                 name = p;
1713
1714                 while (*p && *p != '"') p++;
1715                 if (*p == '\0') break;
1716                 *p = '\0';
1717                 p++;
1718
1719                 while (*p && isspace(*p)) p++;
1720                 if (*p == '\0') break;
1721                 if (strncmp(p, "NIL", 3) == 0)
1722                         separator = NULL;
1723                 else if (*p == '"') {
1724                         p++;
1725                         separator = p;
1726                         while (*p && *p != '"') p++;
1727                         if (*p == '\0') break;
1728                         *p = '\0';
1729                         p++;
1730                 } else break;
1731
1732                 while (*p && *p != ')') p++;
1733                 if (*p == '\0') break;
1734                 p++;
1735
1736                 namespace = g_new(IMAPNameSpace, 1);
1737                 namespace->name = g_strdup(name);
1738                 namespace->separator = separator ? separator[0] : '\0';
1739                 ns_list = g_list_append(ns_list, namespace);
1740         }
1741
1742         return ns_list;
1743 }
1744
1745 static void imap_parse_namespace(IMAPSession *session, IMAPFolder *folder)
1746 {
1747         gchar *ns_str;
1748         gchar **str_array;
1749
1750         g_return_if_fail(session != NULL);
1751         g_return_if_fail(folder != NULL);
1752
1753         if (folder->ns_personal != NULL ||
1754             folder->ns_others   != NULL ||
1755             folder->ns_shared   != NULL)
1756                 return;
1757
1758         if (imap_cmd_namespace(SESSION(session)->sock, &ns_str)
1759             != IMAP_SUCCESS) {
1760                 log_warning(_("can't get namespace\n"));
1761                 return;
1762         }
1763
1764         str_array = strsplit_parenthesis(ns_str, '(', ')', 3);
1765         if (str_array[0])
1766                 folder->ns_personal = imap_parse_namespace_str(str_array[0]);
1767         if (str_array[0] && str_array[1])
1768                 folder->ns_others = imap_parse_namespace_str(str_array[1]);
1769         if (str_array[0] && str_array[1] && str_array[2])
1770                 folder->ns_shared = imap_parse_namespace_str(str_array[2]);
1771         g_strfreev(str_array);
1772         return;
1773 }
1774
1775 static IMAPNameSpace *imap_find_namespace_from_list(GList *ns_list,
1776                                                     const gchar *path)
1777 {
1778         IMAPNameSpace *namespace = NULL;
1779         gchar *tmp_path, *name;
1780
1781         if (!path) path = "";
1782
1783         Xstrcat_a(tmp_path, path, "/", return NULL);
1784
1785         for (; ns_list != NULL; ns_list = ns_list->next) {
1786                 IMAPNameSpace *tmp_ns = ns_list->data;
1787
1788                 Xstrdup_a(name, tmp_ns->name, return namespace);
1789                 if (tmp_ns->separator && tmp_ns->separator != '/')
1790                         subst_char(name, tmp_ns->separator, '/');
1791                 if (strncmp(tmp_path, name, strlen(name)) == 0)
1792                         namespace = tmp_ns;
1793         }
1794
1795         return namespace;
1796 }
1797
1798 static IMAPNameSpace *imap_find_namespace(IMAPFolder *folder,
1799                                           const gchar *path)
1800 {
1801         IMAPNameSpace *namespace;
1802
1803         g_return_val_if_fail(folder != NULL, NULL);
1804
1805         namespace = imap_find_namespace_from_list(folder->ns_personal, path);
1806         if (namespace) return namespace;
1807         namespace = imap_find_namespace_from_list(folder->ns_others, path);
1808         if (namespace) return namespace;
1809         namespace = imap_find_namespace_from_list(folder->ns_shared, path);
1810         if (namespace) return namespace;
1811
1812         return NULL;
1813 }
1814
1815 static gchar imap_get_path_separator(IMAPFolder *folder, const gchar *path)
1816 {
1817         IMAPNameSpace *namespace;
1818         gchar separator = '/';
1819
1820         namespace = imap_find_namespace(folder, path);
1821         if (namespace && namespace->separator)
1822                 separator = namespace->separator;
1823
1824         return separator;
1825 }
1826
1827 static gchar *imap_get_real_path(IMAPFolder *folder, const gchar *path)
1828 {
1829         gchar *real_path;
1830         gchar separator;
1831
1832         g_return_val_if_fail(folder != NULL, NULL);
1833         g_return_val_if_fail(path != NULL, NULL);
1834
1835         real_path = imap_locale_to_modified_utf7(path);
1836         separator = imap_get_path_separator(folder, path);
1837         imap_path_separator_subst(real_path, separator);
1838
1839         return real_path;
1840 }
1841
1842 static gchar *imap_parse_atom(SockInfo *sock, gchar *src,
1843                               gchar *dest, gint dest_len, GString *str)
1844 {
1845         gchar *cur_pos = src;
1846         gchar *nextline;
1847
1848         g_return_val_if_fail(str != NULL, cur_pos);
1849
1850         /* read the next line if the current response buffer is empty */
1851         while (isspace(*cur_pos)) cur_pos++;
1852         while (*cur_pos == '\0') {
1853                 if ((nextline = sock_getline(sock)) == NULL)
1854                         return cur_pos;
1855                 g_string_assign(str, nextline);
1856                 cur_pos = str->str;
1857                 strretchomp(nextline);
1858                 /* log_print("IMAP4< %s\n", nextline); */
1859                 debug_print("IMAP4< %s\n", nextline);
1860                 g_free(nextline);
1861
1862                 while (isspace(*cur_pos)) cur_pos++;
1863         }
1864
1865         if (!strncmp(cur_pos, "NIL", 3)) {
1866                 *dest = '\0';
1867                 cur_pos += 3;
1868         } else if (*cur_pos == '\"') {
1869                 gchar *p;
1870
1871                 p = get_quoted(cur_pos, '\"', dest, dest_len);
1872                 cur_pos = p ? p : cur_pos + 2;
1873         } else if (*cur_pos == '{') {
1874                 gchar buf[32];
1875                 gint len;
1876                 gint line_len = 0;
1877
1878                 cur_pos = strchr_cpy(cur_pos + 1, '}', buf, sizeof(buf));
1879                 len = atoi(buf);
1880
1881                 g_string_truncate(str, 0);
1882                 cur_pos = str->str;
1883
1884                 do {
1885                         if ((nextline = sock_getline(sock)) == NULL)
1886                                 return cur_pos;
1887                         line_len += strlen(nextline);
1888                         g_string_append(str, nextline);
1889                         cur_pos = str->str;
1890                         strretchomp(nextline);
1891                         /* log_print("IMAP4< %s\n", nextline); */
1892                         debug_print("IMAP4< %s\n", nextline);
1893                         g_free(nextline);
1894                 } while (line_len < len);
1895
1896                 memcpy(dest, cur_pos, MIN(len, dest_len - 1));
1897                 dest[MIN(len, dest_len - 1)] = '\0';
1898                 cur_pos += len;
1899         }
1900
1901         return cur_pos;
1902 }
1903
1904 static gchar *imap_get_header(SockInfo *sock, gchar *cur_pos, gchar **headers,
1905                               GString *str)
1906 {
1907         gchar *nextline;
1908         gchar buf[32];
1909         gint len;
1910         gint block_len = 0;
1911
1912         *headers = NULL;
1913
1914         g_return_val_if_fail(str != NULL, cur_pos);
1915
1916         while (isspace(*cur_pos)) cur_pos++;
1917
1918         g_return_val_if_fail(*cur_pos == '{', cur_pos);
1919
1920         cur_pos = strchr_cpy(cur_pos + 1, '}', buf, sizeof(buf));
1921         len = atoi(buf);
1922
1923         g_string_truncate(str, 0);
1924         cur_pos = str->str;
1925
1926         do {
1927                 if ((nextline = sock_getline(sock)) == NULL)
1928                         return cur_pos;
1929                 block_len += strlen(nextline);
1930                 g_string_append(str, nextline);
1931                 cur_pos = str->str;
1932                 strretchomp(nextline);
1933                 /* debug_print("IMAP4< %s\n", nextline); */
1934                 g_free(nextline);
1935         } while (block_len < len);
1936
1937         debug_print("IMAP4< [contents of RFC822.HEADER]\n");
1938
1939         *headers = g_strndup(cur_pos, len);
1940         cur_pos += len;
1941
1942         while (isspace(*cur_pos)) cur_pos++;
1943         while (*cur_pos == '\0') {
1944                 if ((nextline = sock_getline(sock)) == NULL)
1945                         return cur_pos;
1946                 g_string_assign(str, nextline);
1947                 cur_pos = str->str;
1948                 strretchomp(nextline);
1949                 debug_print("IMAP4< %s\n", nextline);
1950                 g_free(nextline);
1951
1952                 while (isspace(*cur_pos)) cur_pos++;
1953         }
1954
1955         return cur_pos;
1956 }
1957
1958 static MsgFlags imap_parse_flags(const gchar *flag_str)  
1959 {
1960         const gchar *p = flag_str;
1961         MsgFlags flags = {0, 0};
1962
1963         flags.perm_flags = MSG_UNREAD;
1964
1965         while ((p = strchr(p, '\\')) != NULL) {
1966                 p++;
1967
1968                 if (g_strncasecmp(p, "Recent", 6) == 0 && MSG_IS_UNREAD(flags)) {
1969                         MSG_SET_PERM_FLAGS(flags, MSG_NEW);
1970                 } else if (g_strncasecmp(p, "Seen", 4) == 0) {
1971                         MSG_UNSET_PERM_FLAGS(flags, MSG_NEW|MSG_UNREAD);
1972                 } else if (g_strncasecmp(p, "Deleted", 7) == 0) {
1973                         MSG_SET_PERM_FLAGS(flags, MSG_DELETED);
1974                 } else if (g_strncasecmp(p, "Flagged", 7) == 0) {
1975                         MSG_SET_PERM_FLAGS(flags, MSG_MARKED);
1976                 } else if (g_strncasecmp(p, "Answered", 8) == 0) {
1977                         MSG_SET_PERM_FLAGS(flags, MSG_REPLIED);
1978                 }
1979         }
1980
1981         return flags;
1982 }
1983
1984 static MsgInfo *imap_parse_envelope(SockInfo *sock, FolderItem *item,
1985                                     GString *line_str)
1986 {
1987         gchar buf[IMAPBUFSIZE];
1988         MsgInfo *msginfo = NULL;
1989         gchar *cur_pos;
1990         gint msgnum;
1991         guint32 uid = 0;
1992         size_t size = 0;
1993         MsgFlags flags = {0, 0}, imap_flags = {0, 0};
1994
1995         g_return_val_if_fail(line_str != NULL, NULL);
1996         g_return_val_if_fail(line_str->str[0] == '*' &&
1997                              line_str->str[1] == ' ', NULL);
1998
1999         MSG_SET_TMP_FLAGS(flags, MSG_IMAP);
2000         if (item->stype == F_QUEUE) {
2001                 MSG_SET_TMP_FLAGS(flags, MSG_QUEUED);
2002         } else if (item->stype == F_DRAFT) {
2003                 MSG_SET_TMP_FLAGS(flags, MSG_DRAFT);
2004         }
2005
2006         cur_pos = line_str->str + 2;
2007
2008 #define PARSE_ONE_ELEMENT(ch)                                   \
2009 {                                                               \
2010         cur_pos = strchr_cpy(cur_pos, ch, buf, sizeof(buf));    \
2011         if (cur_pos == NULL) {                                  \
2012                 g_warning("cur_pos == NULL\n");                 \
2013                 procmsg_msginfo_free(msginfo);                  \
2014                 return NULL;                                    \
2015         }                                                       \
2016 }
2017
2018         PARSE_ONE_ELEMENT(' ');
2019         msgnum = atoi(buf);
2020
2021         PARSE_ONE_ELEMENT(' ');
2022         g_return_val_if_fail(!strcmp(buf, "FETCH"), NULL);
2023
2024         g_return_val_if_fail(*cur_pos == '(', NULL);
2025         cur_pos++;
2026
2027         while (*cur_pos != '\0' && *cur_pos != ')') {
2028                 while (*cur_pos == ' ') cur_pos++;
2029
2030                 if (!strncmp(cur_pos, "UID ", 4)) {
2031                         cur_pos += 4;
2032                         uid = strtoul(cur_pos, &cur_pos, 10);
2033                 } else if (!strncmp(cur_pos, "FLAGS ", 6)) {
2034                         cur_pos += 6;
2035                         if (*cur_pos != '(') {
2036                                 g_warning("*cur_pos != '('\n");
2037                                 procmsg_msginfo_free(msginfo);
2038                                 return NULL;
2039                         }
2040                         cur_pos++;
2041                         PARSE_ONE_ELEMENT(')');
2042                         imap_flags = imap_parse_flags(buf);
2043                 } else if (!strncmp(cur_pos, "RFC822.SIZE ", 12)) {
2044                         cur_pos += 12;
2045                         size = strtol(cur_pos, &cur_pos, 10);
2046                 } else if (!strncmp(cur_pos, "RFC822.HEADER ", 14)) {
2047                         gchar *headers;
2048
2049                         cur_pos += 14;
2050                         cur_pos = imap_get_header(sock, cur_pos, &headers,
2051                                                   line_str);
2052                         msginfo = procheader_parse_str(headers, flags, FALSE, FALSE);
2053                         g_free(headers);
2054                 } else {
2055                         g_warning("invalid FETCH response: %s\n", cur_pos);
2056                         break;
2057                 }
2058         }
2059
2060         if (msginfo) {
2061                 msginfo->msgnum = uid;
2062                 msginfo->size = size;
2063                 msginfo->flags.tmp_flags |= imap_flags.tmp_flags;
2064                 msginfo->flags.perm_flags = imap_flags.perm_flags;
2065         }
2066
2067         return msginfo;
2068 }
2069
2070 gint imap_msg_set_perm_flags(MsgInfo *msginfo, MsgPermFlags flags)
2071 {
2072         Folder *folder;
2073         IMAPSession *session;
2074         IMAPFlags iflags = 0;
2075         gint ok = IMAP_SUCCESS;
2076
2077         g_return_val_if_fail(msginfo != NULL, -1);
2078         g_return_val_if_fail(MSG_IS_IMAP(msginfo->flags), -1);
2079         g_return_val_if_fail(msginfo->folder != NULL, -1);
2080         g_return_val_if_fail(msginfo->folder->folder != NULL, -1);
2081
2082         folder = msginfo->folder->folder;
2083         g_return_val_if_fail(folder->type == F_IMAP, -1);
2084
2085         session = imap_session_get(folder);
2086         if (!session) return -1;
2087
2088         if (flags & MSG_MARKED)  iflags |= IMAP_FLAG_FLAGGED;
2089         if (flags & MSG_REPLIED) iflags |= IMAP_FLAG_ANSWERED;
2090         if (iflags) {
2091                 ok = imap_set_message_flags(session, msginfo->msgnum,
2092                                             msginfo->msgnum, iflags, TRUE);
2093                 if (ok != IMAP_SUCCESS) return ok;
2094         }
2095
2096         if (flags & MSG_UNREAD)
2097                 ok = imap_set_message_flags(session, msginfo->msgnum,
2098                                             msginfo->msgnum, IMAP_FLAG_SEEN,
2099                                             FALSE);
2100         return ok;
2101 }
2102
2103 gint imap_msg_unset_perm_flags(MsgInfo *msginfo, MsgPermFlags flags)
2104 {
2105         Folder *folder;
2106         IMAPSession *session;
2107         IMAPFlags iflags = 0;
2108         gint ok = IMAP_SUCCESS;
2109
2110         g_return_val_if_fail(msginfo != NULL, -1);
2111         g_return_val_if_fail(MSG_IS_IMAP(msginfo->flags), -1);
2112         g_return_val_if_fail(msginfo->folder != NULL, -1);
2113         g_return_val_if_fail(msginfo->folder->folder != NULL, -1);
2114
2115         folder = msginfo->folder->folder;
2116         g_return_val_if_fail(folder->type == F_IMAP, -1);
2117
2118         session = imap_session_get(folder);
2119         if (!session) return -1;
2120
2121         if (flags & MSG_MARKED)  iflags |= IMAP_FLAG_FLAGGED;
2122         if (flags & MSG_REPLIED) iflags |= IMAP_FLAG_ANSWERED;
2123         if (iflags) {
2124                 ok = imap_set_message_flags(session, msginfo->msgnum,
2125                                             msginfo->msgnum, iflags, FALSE);
2126                 if (ok != IMAP_SUCCESS) return ok;
2127         }
2128
2129         if (flags & MSG_UNREAD)
2130                 ok = imap_set_message_flags(session, msginfo->msgnum,
2131                                             msginfo->msgnum, IMAP_FLAG_SEEN,
2132                                             TRUE);
2133         return ok;
2134 }
2135
2136 static gint imap_set_message_flags(IMAPSession *session,
2137                                    guint32 first_uid,
2138                                    guint32 last_uid,
2139                                    IMAPFlags flags,
2140                                    gboolean is_set)
2141 {
2142         GString *buf;
2143         gint ok;
2144
2145         buf = g_string_new(is_set ? "+FLAGS (" : "-FLAGS (");
2146
2147         if (IMAP_IS_SEEN(flags))        g_string_append(buf, "\\Seen ");
2148         if (IMAP_IS_ANSWERED(flags))    g_string_append(buf, "\\Answered ");
2149         if (IMAP_IS_FLAGGED(flags))     g_string_append(buf, "\\Flagged ");
2150         if (IMAP_IS_DELETED(flags))     g_string_append(buf, "\\Deleted ");
2151         if (IMAP_IS_DRAFT(flags))       g_string_append(buf, "\\Draft");
2152
2153         if (buf->str[buf->len - 1] == ' ')
2154                 g_string_truncate(buf, buf->len - 1);
2155
2156         g_string_append_c(buf, ')');
2157
2158         ok = imap_cmd_store(SESSION(session)->sock, first_uid, last_uid,
2159                             buf->str);
2160         g_string_free(buf, TRUE);
2161
2162         return ok;
2163 }
2164
2165 static gint imap_select(IMAPSession *session, IMAPFolder *folder,
2166                         const gchar *path,
2167                         gint *exists, gint *recent, gint *unseen,
2168                         guint32 *uid_validity)
2169 {
2170         gchar *real_path;
2171         gint ok;
2172         gint exists_, recent_, unseen_, uid_validity_;
2173
2174         if (!exists || !recent || !unseen || !uid_validity) {
2175                 if (session->mbox && strcmp(session->mbox, path) == 0)
2176                         return IMAP_SUCCESS;
2177                 exists = &exists_;
2178                 recent = &recent_;
2179                 unseen = &unseen_;
2180                 uid_validity = &uid_validity_;
2181         }
2182
2183         g_free(session->mbox);
2184         session->mbox = NULL;
2185
2186         real_path = imap_get_real_path(folder, path);
2187         ok = imap_cmd_select(SESSION(session)->sock, real_path,
2188                              exists, recent, unseen, uid_validity);
2189         if (ok != IMAP_SUCCESS)
2190                 log_warning(_("can't select folder: %s\n"), real_path);
2191         else
2192                 session->mbox = g_strdup(path);
2193         g_free(real_path);
2194
2195         return ok;
2196 }
2197
2198 #define THROW(err) { ok = err; goto catch; }
2199
2200 static gint imap_get_uid(IMAPSession *session, gint msgnum, guint32 *uid)
2201 {
2202         gint ok;
2203         GPtrArray *argbuf;
2204         gchar *str;
2205         gint num;
2206
2207         *uid = 0;
2208         argbuf = g_ptr_array_new();
2209
2210         imap_cmd_gen_send(SESSION(session)->sock, "FETCH %d (UID)", msgnum);
2211         if ((ok = imap_cmd_ok(SESSION(session)->sock, argbuf)) != IMAP_SUCCESS)
2212                 THROW(ok);
2213
2214         str = search_array_contain_str(argbuf, "FETCH");
2215         if (!str) THROW(IMAP_ERROR);
2216
2217         if (sscanf(str, "%d FETCH (UID %d)", &num, uid) != 2 ||
2218             num != msgnum) {
2219                 g_warning("imap_get_uid(): invalid FETCH line.\n");
2220                 THROW(IMAP_ERROR);
2221         }
2222
2223 catch:
2224         ptr_array_free_strings(argbuf);
2225         g_ptr_array_free(argbuf, TRUE);
2226
2227         return ok;
2228 }
2229
2230 static gint imap_status(IMAPSession *session, IMAPFolder *folder,
2231                         const gchar *path,
2232                         gint *messages, gint *recent,
2233                         guint32 *uid_next, guint32 *uid_validity,
2234                         gint *unseen)
2235 {
2236         gchar *real_path;
2237         gchar *real_path_;
2238         gint ok;
2239         GPtrArray *argbuf;
2240         gchar *str;
2241
2242         *messages = *recent = *uid_next = *uid_validity = *unseen = 0;
2243
2244         argbuf = g_ptr_array_new();
2245
2246         real_path = imap_get_real_path(folder, path);
2247         QUOTE_IF_REQUIRED(real_path_, real_path);
2248         imap_cmd_gen_send(SESSION(session)->sock, "STATUS %s "
2249                           "(MESSAGES RECENT UIDNEXT UIDVALIDITY UNSEEN)",
2250                           real_path_);
2251
2252         ok = imap_cmd_ok(SESSION(session)->sock, argbuf);
2253         if (ok != IMAP_SUCCESS) THROW(ok);
2254
2255         str = search_array_str(argbuf, "STATUS");
2256         if (!str) THROW(IMAP_ERROR);
2257
2258         str = strchr(str, '(');
2259         if (!str) THROW(IMAP_ERROR);
2260         str++;
2261         while (*str != '\0' && *str != ')') {
2262                 while (*str == ' ') str++;
2263
2264                 if (!strncmp(str, "MESSAGES ", 9)) {
2265                         str += 9;
2266                         *messages = strtol(str, &str, 10);
2267                 } else if (!strncmp(str, "RECENT ", 7)) {
2268                         str += 7;
2269                         *recent = strtol(str, &str, 10);
2270                 } else if (!strncmp(str, "UIDNEXT ", 8)) {
2271                         str += 8;
2272                         *uid_next = strtoul(str, &str, 10);
2273                 } else if (!strncmp(str, "UIDVALIDITY ", 12)) {
2274                         str += 12;
2275                         *uid_validity = strtoul(str, &str, 10);
2276                 } else if (!strncmp(str, "UNSEEN ", 7)) {
2277                         str += 7;
2278                         *unseen = strtol(str, &str, 10);
2279                 } else {
2280                         g_warning("invalid STATUS response: %s\n", str);
2281                         break;
2282                 }
2283         }
2284
2285 catch:
2286         g_free(real_path);
2287         ptr_array_free_strings(argbuf);
2288         g_ptr_array_free(argbuf, TRUE);
2289
2290         return ok;
2291 }
2292
2293 #undef THROW
2294
2295
2296 /* low-level IMAP4rev1 commands */
2297
2298 static gint imap_cmd_login(SockInfo *sock,
2299                            const gchar *user, const gchar *pass)
2300 {
2301         gchar *user_, *pass_;
2302         gint ok;
2303
2304         QUOTE_IF_REQUIRED(user_, user);
2305         QUOTE_IF_REQUIRED(pass_, pass);
2306         imap_cmd_gen_send(sock, "LOGIN %s %s", user_, pass_);
2307
2308         ok = imap_cmd_ok(sock, NULL);
2309         if (ok != IMAP_SUCCESS)
2310                 log_warning(_("IMAP4 login failed.\n"));
2311
2312         return ok;
2313 }
2314
2315 static gint imap_cmd_logout(SockInfo *sock)
2316 {
2317         imap_cmd_gen_send(sock, "LOGOUT");
2318         return imap_cmd_ok(sock, NULL);
2319 }
2320
2321 /* Send a NOOP, and examine the server's response to see whether this
2322  * connection is pre-authenticated or not. */
2323 static gint imap_greeting(SockInfo *sock, gboolean *is_preauth)
2324 {
2325         GPtrArray *argbuf;
2326         gint r;
2327
2328         imap_cmd_gen_send(sock, "NOOP");
2329         argbuf = g_ptr_array_new(); /* will hold messages sent back */
2330         r = imap_cmd_ok(sock, argbuf);
2331         *is_preauth = search_array_starts(argbuf, "PREAUTH") != NULL;
2332         
2333         return r;
2334 }
2335
2336 static gint imap_cmd_noop(SockInfo *sock)
2337 {
2338         imap_cmd_gen_send(sock, "NOOP");
2339         return imap_cmd_ok(sock, NULL);
2340 }
2341
2342 static gint imap_cmd_starttls(SockInfo *sock)
2343 {
2344         imap_cmd_gen_send(sock, "STARTTLS");
2345         return imap_cmd_ok(sock, NULL);
2346 }
2347
2348 #define THROW(err) { ok = err; goto catch; }
2349
2350 static gint imap_cmd_namespace(SockInfo *sock, gchar **ns_str)
2351 {
2352         gint ok;
2353         GPtrArray *argbuf;
2354         gchar *str;
2355
2356         argbuf = g_ptr_array_new();
2357
2358         imap_cmd_gen_send(sock, "NAMESPACE");
2359         if ((ok = imap_cmd_ok(sock, argbuf)) != IMAP_SUCCESS) THROW(ok);
2360
2361         str = search_array_str(argbuf, "NAMESPACE");
2362         if (!str) THROW(IMAP_ERROR);
2363
2364         *ns_str = g_strdup(str);
2365
2366 catch:
2367         ptr_array_free_strings(argbuf);
2368         g_ptr_array_free(argbuf, TRUE);
2369
2370         return ok;
2371 }
2372
2373 #undef THROW
2374
2375 static gint imap_cmd_list(SockInfo *sock, const gchar *ref,
2376                           const gchar *mailbox, GPtrArray *argbuf)
2377 {
2378         gchar *ref_, *mailbox_;
2379
2380         if (!ref) ref = "\"\"";
2381         if (!mailbox) mailbox = "\"\"";
2382
2383         QUOTE_IF_REQUIRED(ref_, ref);
2384         QUOTE_IF_REQUIRED(mailbox_, mailbox);
2385         imap_cmd_gen_send(sock, "LIST %s %s", ref_, mailbox_);
2386
2387         return imap_cmd_ok(sock, argbuf);
2388 }
2389
2390 #define THROW goto catch
2391
2392 static gint imap_cmd_do_select(SockInfo *sock, const gchar *folder,
2393                                gboolean examine,
2394                                gint *exists, gint *recent, gint *unseen,
2395                                guint32 *uid_validity)
2396 {
2397         gint ok;
2398         gchar *resp_str;
2399         GPtrArray *argbuf;
2400         gchar *select_cmd;
2401         gchar *folder_;
2402
2403         *exists = *recent = *unseen = *uid_validity = 0;
2404         argbuf = g_ptr_array_new();
2405
2406         if (examine)
2407                 select_cmd = "EXAMINE";
2408         else
2409                 select_cmd = "SELECT";
2410
2411         QUOTE_IF_REQUIRED(folder_, folder);
2412         imap_cmd_gen_send(sock, "%s %s", select_cmd, folder_);
2413
2414         if ((ok = imap_cmd_ok(sock, argbuf)) != IMAP_SUCCESS) THROW;
2415
2416         resp_str = search_array_contain_str(argbuf, "EXISTS");
2417         if (resp_str) {
2418                 if (sscanf(resp_str,"%d EXISTS", exists) != 1) {
2419                         g_warning("imap_cmd_select(): invalid EXISTS line.\n");
2420                         THROW;
2421                 }
2422         }
2423
2424         resp_str = search_array_contain_str(argbuf, "RECENT");
2425         if (resp_str) {
2426                 if (sscanf(resp_str, "%d RECENT", recent) != 1) {
2427                         g_warning("imap_cmd_select(): invalid RECENT line.\n");
2428                         THROW;
2429                 }
2430         }
2431
2432         resp_str = search_array_contain_str(argbuf, "UIDVALIDITY");
2433         if (resp_str) {
2434                 if (sscanf(resp_str, "OK [UIDVALIDITY %u] ", uid_validity)
2435                     != 1) {
2436                         g_warning("imap_cmd_select(): invalid UIDVALIDITY line.\n");
2437                         THROW;
2438                 }
2439         }
2440
2441         resp_str = search_array_contain_str(argbuf, "UNSEEN");
2442         if (resp_str) {
2443                 if (sscanf(resp_str, "OK [UNSEEN %d] ", unseen) != 1) {
2444                         g_warning("imap_cmd_select(): invalid UNSEEN line.\n");
2445                         THROW;
2446                 }
2447         }
2448
2449 catch:
2450         ptr_array_free_strings(argbuf);
2451         g_ptr_array_free(argbuf, TRUE);
2452
2453         return ok;
2454 }
2455
2456 static gint imap_cmd_select(SockInfo *sock, const gchar *folder,
2457                             gint *exists, gint *recent, gint *unseen,
2458                             guint32 *uid_validity)
2459 {
2460         return imap_cmd_do_select(sock, folder, FALSE,
2461                                   exists, recent, unseen, uid_validity);
2462 }
2463
2464 static gint imap_cmd_examine(SockInfo *sock, const gchar *folder,
2465                              gint *exists, gint *recent, gint *unseen,
2466                              guint32 *uid_validity)
2467 {
2468         return imap_cmd_do_select(sock, folder, TRUE,
2469                                   exists, recent, unseen, uid_validity);
2470 }
2471
2472 #undef THROW
2473
2474 static gint imap_cmd_create(SockInfo *sock, const gchar *folder)
2475 {
2476         gchar *folder_;
2477
2478         QUOTE_IF_REQUIRED(folder_, folder);
2479         imap_cmd_gen_send(sock, "CREATE %s", folder_);
2480
2481         return imap_cmd_ok(sock, NULL);
2482 }
2483
2484 static gint imap_cmd_rename(SockInfo *sock, const gchar *old_folder,
2485                             const gchar *new_folder)
2486 {
2487         gchar *old_folder_, *new_folder_;
2488
2489         QUOTE_IF_REQUIRED(old_folder_, old_folder);
2490         QUOTE_IF_REQUIRED(new_folder_, new_folder);
2491         imap_cmd_gen_send(sock, "RENAME %s %s", old_folder_, new_folder_);
2492
2493         return imap_cmd_ok(sock, NULL);
2494 }
2495
2496 static gint imap_cmd_delete(SockInfo *sock, const gchar *folder)
2497 {
2498         gchar *folder_;
2499
2500         QUOTE_IF_REQUIRED(folder_, folder);
2501         imap_cmd_gen_send(sock, "DELETE %s", folder_);
2502
2503         return imap_cmd_ok(sock, NULL);
2504 }
2505
2506 static gint imap_cmd_fetch(SockInfo *sock, guint32 uid, const gchar *filename)
2507 {
2508         gint ok;
2509         gchar buf[IMAPBUFSIZE];
2510         gchar *cur_pos;
2511         gchar size_str[32];
2512         glong size_num;
2513
2514         g_return_val_if_fail(filename != NULL, IMAP_ERROR);
2515
2516         imap_cmd_gen_send(sock, "UID FETCH %d BODY[]", uid);
2517
2518         while ((ok = imap_cmd_gen_recv(sock, buf, sizeof(buf)))
2519                == IMAP_SUCCESS) {
2520                 if (buf[0] != '*' || buf[1] != ' ')
2521                         return IMAP_ERROR;
2522                 if (strstr(buf, "FETCH") != NULL)
2523                         break;
2524         }
2525         if (ok != IMAP_SUCCESS)
2526                 return ok;
2527
2528         cur_pos = strchr(buf, '{');
2529         g_return_val_if_fail(cur_pos != NULL, IMAP_ERROR);
2530         cur_pos = strchr_cpy(cur_pos + 1, '}', size_str, sizeof(size_str));
2531         g_return_val_if_fail(cur_pos != NULL, IMAP_ERROR);
2532         size_num = atol(size_str);
2533
2534         if (*cur_pos != '\0') return IMAP_ERROR;
2535
2536         if (recv_bytes_write_to_file(sock, size_num, filename) != 0)
2537                 return IMAP_ERROR;
2538
2539         if (imap_cmd_gen_recv(sock, buf, sizeof(buf)) != IMAP_SUCCESS)
2540                 return IMAP_ERROR;
2541
2542         if (buf[0] == '\0' || buf[strlen(buf) - 1] != ')')
2543                 return IMAP_ERROR;
2544
2545         ok = imap_cmd_ok(sock, NULL);
2546
2547         return ok;
2548 }
2549
2550 static gint imap_cmd_append(SockInfo *sock, const gchar *destfolder,
2551                             const gchar *file)
2552 {
2553         gint ok;
2554         gint size;
2555         gchar *destfolder_;
2556         gchar buf[BUFFSIZE];
2557         FILE *fp;
2558
2559         g_return_val_if_fail(file != NULL, IMAP_ERROR);
2560
2561         size = get_file_size_as_crlf(file);
2562         if ((fp = fopen(file, "rb")) == NULL) {
2563                 FILE_OP_ERROR(file, "fopen");
2564                 return -1;
2565         }
2566         QUOTE_IF_REQUIRED(destfolder_, destfolder);
2567         imap_cmd_gen_send(sock, "APPEND %s (\\Seen) {%d}", destfolder_, size);
2568
2569         ok = imap_cmd_gen_recv(sock, buf, sizeof(buf));
2570         if (ok != IMAP_SUCCESS || buf[0] != '+' || buf[1] != ' ') {
2571                 log_warning(_("can't append %s to %s\n"), file, destfolder_);
2572                 fclose(fp);
2573                 return IMAP_ERROR;
2574         }
2575
2576         log_print("IMAP4> %s\n", _("(sending file...)"));
2577
2578         while (fgets(buf, sizeof(buf), fp) != NULL) {
2579                 strretchomp(buf);
2580                 if (sock_puts(sock, buf) < 0) {
2581                         fclose(fp);
2582                         sock_close(sock);
2583                         return -1;
2584                 }
2585         }
2586
2587         if (ferror(fp)) {
2588                 FILE_OP_ERROR(file, "fgets");
2589                 fclose(fp);
2590                 sock_close(sock);
2591                 return -1;
2592         }
2593
2594         sock_puts(sock, "");
2595
2596         fclose(fp);
2597         return imap_cmd_ok(sock, NULL);
2598 }
2599
2600 static gint imap_cmd_copy(SockInfo *sock, guint32 uid, const gchar *destfolder)
2601 {
2602         gint ok;
2603         gchar *destfolder_;
2604
2605         g_return_val_if_fail(destfolder != NULL, IMAP_ERROR);
2606
2607         QUOTE_IF_REQUIRED(destfolder_, destfolder);
2608         imap_cmd_gen_send(sock, "UID COPY %d %s", uid, destfolder_);
2609
2610         ok = imap_cmd_ok(sock, NULL);
2611         if (ok != IMAP_SUCCESS) {
2612                 log_warning(_("can't copy %d to %s\n"), uid, destfolder_);
2613                 return -1;
2614         }
2615
2616         return ok;
2617 }
2618
2619 gint imap_cmd_envelope(SockInfo *sock, guint32 first_uid, guint32 last_uid)
2620 {
2621         imap_cmd_gen_send
2622                 (sock, "UID FETCH %d:%d (UID FLAGS RFC822.SIZE RFC822.HEADER)",
2623                  first_uid, last_uid);
2624
2625         return IMAP_SUCCESS;
2626 }
2627
2628 static gint imap_cmd_store(SockInfo *sock, guint32 first_uid, guint32 last_uid,
2629                            gchar *sub_cmd)
2630 {
2631         gint ok;
2632
2633         imap_cmd_gen_send(sock, "UID STORE %d:%d %s",
2634                           first_uid, last_uid, sub_cmd);
2635
2636         if ((ok = imap_cmd_ok(sock, NULL)) != IMAP_SUCCESS) {
2637                 log_warning(_("error while imap command: STORE %d:%d %s\n"),
2638                             first_uid, last_uid, sub_cmd);
2639                 return ok;
2640         }
2641
2642         return IMAP_SUCCESS;
2643 }
2644
2645 static gint imap_cmd_expunge(SockInfo *sock)
2646 {
2647         gint ok;
2648
2649         imap_cmd_gen_send(sock, "EXPUNGE");
2650         if ((ok = imap_cmd_ok(sock, NULL)) != IMAP_SUCCESS) {
2651                 log_warning(_("error while imap command: EXPUNGE\n"));
2652                 return ok;
2653         }
2654
2655         return IMAP_SUCCESS;
2656 }
2657
2658 static gint imap_cmd_ok(SockInfo *sock, GPtrArray *argbuf)
2659 {
2660         gint ok;
2661         gchar buf[IMAPBUFSIZE];
2662         gint cmd_num;
2663         gchar cmd_status[IMAPBUFSIZE];
2664
2665         while ((ok = imap_cmd_gen_recv(sock, buf, sizeof(buf)))
2666                == IMAP_SUCCESS) {
2667                 if (buf[0] == '*' && buf[1] == ' ') {
2668                         if (argbuf)
2669                                 g_ptr_array_add(argbuf, g_strdup(buf + 2));
2670                         continue;
2671                 }
2672
2673                 if (sscanf(buf, "%d %s", &cmd_num, cmd_status) < 2)
2674                         return IMAP_ERROR;
2675                 else if (cmd_num == imap_cmd_count &&
2676                          !strcmp(cmd_status, "OK")) {
2677                         if (argbuf)
2678                                 g_ptr_array_add(argbuf, g_strdup(buf));
2679                         return IMAP_SUCCESS;
2680                 } else
2681                         return IMAP_ERROR;
2682         }
2683
2684         return ok;
2685 }
2686
2687 static void imap_cmd_gen_send(SockInfo *sock, const gchar *format, ...)
2688 {
2689         gchar buf[IMAPBUFSIZE];
2690         gchar tmp[IMAPBUFSIZE];
2691         gchar *p;
2692         va_list args;
2693
2694         va_start(args, format);
2695         g_vsnprintf(tmp, sizeof(tmp), format, args);
2696         va_end(args);
2697
2698         imap_cmd_count++;
2699
2700         g_snprintf(buf, sizeof(buf), "%d %s\r\n", imap_cmd_count, tmp);
2701         if (!strncasecmp(tmp, "LOGIN ", 6) && (p = strchr(tmp + 6, ' '))) {
2702                 *p = '\0';
2703                 log_print("IMAP4> %d %s ********\n", imap_cmd_count, tmp);
2704         } else
2705                 log_print("IMAP4> %d %s\n", imap_cmd_count, tmp);
2706
2707         sock_write(sock, buf, strlen(buf));
2708 }
2709
2710 static gint imap_cmd_gen_recv(SockInfo *sock, gchar *buf, gint size)
2711 {
2712         if (sock_gets(sock, buf, size) == -1)
2713                 return IMAP_SOCKET;
2714
2715         strretchomp(buf);
2716
2717         log_print("IMAP4< %s\n", buf);
2718
2719         return IMAP_SUCCESS;
2720 }
2721
2722
2723 /* misc utility functions */
2724
2725 static gchar *strchr_cpy(const gchar *src, gchar ch, gchar *dest, gint len)
2726 {
2727         gchar *tmp;
2728
2729         dest[0] = '\0';
2730         tmp = strchr(src, ch);
2731         if (!tmp)
2732                 return NULL;
2733
2734         memcpy(dest, src, MIN(tmp - src, len - 1));
2735         dest[MIN(tmp - src, len - 1)] = '\0';
2736
2737         return tmp + 1;
2738 }
2739
2740 static gchar *get_quoted(const gchar *src, gchar ch, gchar *dest, gint len)
2741 {
2742         const gchar *p = src;
2743         gint n = 0;
2744
2745         g_return_val_if_fail(*p == ch, NULL);
2746
2747         *dest = '\0';
2748         p++;
2749
2750         while (*p != '\0' && *p != ch) {
2751                 if (n < len - 1) {
2752                         if (*p == '\\' && *(p + 1) != '\0')
2753                                 p++;
2754                         *dest++ = *p++;
2755                 } else
2756                         p++;
2757                 n++;
2758         }
2759
2760         *dest = '\0';
2761         return (gchar *)(*p == ch ? p + 1 : p);
2762 }
2763
2764 static gchar *search_array_starts(GPtrArray *array, const gchar *str)
2765 {
2766         gint i;
2767         size_t len;
2768
2769         g_return_val_if_fail(str != NULL, NULL);
2770         len = strlen(str);
2771         for (i = 0; i < array->len; i++) {
2772                 gchar *tmp;
2773                 tmp = g_ptr_array_index(array, i);
2774                 if (strncmp(tmp, str, len) == 0)
2775                         return tmp;
2776         }
2777         return NULL;
2778 }
2779
2780 static gchar *search_array_contain_str(GPtrArray *array, gchar *str)
2781 {
2782         gint i;
2783
2784         for (i = 0; i < array->len; i++) {
2785                 gchar *tmp;
2786
2787                 tmp = g_ptr_array_index(array, i);
2788                 if (strstr(tmp, str) != NULL)
2789                         return tmp;
2790         }
2791
2792         return NULL;
2793 }
2794
2795 static gchar *search_array_str(GPtrArray *array, gchar *str)
2796 {
2797         gint i;
2798         gint len;
2799
2800         len = strlen(str);
2801
2802         for (i = 0; i < array->len; i++) {
2803                 gchar *tmp;
2804
2805                 tmp = g_ptr_array_index(array, i);
2806                 if (!strncmp(tmp, str, len))
2807                         return tmp;
2808         }
2809
2810         return NULL;
2811 }
2812
2813 static void imap_path_separator_subst(gchar *str, gchar separator)
2814 {
2815         gchar *p;
2816         gboolean in_escape = FALSE;
2817
2818         if (!separator || separator == '/') return;
2819
2820         for (p = str; *p != '\0'; p++) {
2821                 if (*p == '/' && !in_escape)
2822                         *p = separator;
2823                 else if (*p == '&' && *(p + 1) != '-' && !in_escape)
2824                         in_escape = TRUE;
2825                 else if (*p == '-' && in_escape)
2826                         in_escape = FALSE;
2827         }
2828 }
2829
2830 static gchar *imap_modified_utf7_to_locale(const gchar *mutf7_str)
2831 {
2832 #if !HAVE_LIBJCONV
2833         return g_strdup(mutf7_str);
2834 #else
2835         static iconv_t cd = (iconv_t)-1;
2836         static gboolean iconv_ok = TRUE;
2837         GString *norm_utf7;
2838         gchar *norm_utf7_p;
2839         size_t norm_utf7_len;
2840         const gchar *p;
2841         gchar *to_str, *to_p;
2842         size_t to_len;
2843         gboolean in_escape = FALSE;
2844
2845         if (!iconv_ok) return g_strdup(mutf7_str);
2846
2847         if (cd == (iconv_t)-1) {
2848                 cd = iconv_open(conv_get_current_charset_str(), "UTF-7");
2849                 if (cd == (iconv_t)-1) {
2850                         g_warning(_("iconv cannot convert UTF-7 to %s\n"),
2851                                   conv_get_current_charset_str());
2852                         iconv_ok = FALSE;
2853                         return g_strdup(mutf7_str);
2854                 }
2855         }
2856
2857         norm_utf7 = g_string_new(NULL);
2858
2859         for (p = mutf7_str; *p != '\0'; p++) {
2860                 /* replace: '&'  -> '+',
2861                             "&-" -> '&',
2862                             escaped ','  -> '/' */
2863                 if (!in_escape && *p == '&') {
2864                         if (*(p + 1) != '-') {
2865                                 g_string_append_c(norm_utf7, '+');
2866                                 in_escape = TRUE;
2867                         } else {
2868                                 g_string_append_c(norm_utf7, '&');
2869                                 p++;
2870                         }
2871                 } else if (in_escape && *p == ',') {
2872                         g_string_append_c(norm_utf7, '/');
2873                 } else if (in_escape && *p == '-') {
2874                         g_string_append_c(norm_utf7, '-');
2875                         in_escape = FALSE;
2876                 } else {
2877                         g_string_append_c(norm_utf7, *p);
2878                 }
2879         }
2880
2881         norm_utf7_p = norm_utf7->str;
2882         norm_utf7_len = norm_utf7->len;
2883         to_len = strlen(mutf7_str) * 5;
2884         to_p = to_str = g_malloc(to_len + 1);
2885
2886         if (iconv(cd, &norm_utf7_p, &norm_utf7_len, &to_p, &to_len) == -1) {
2887                 g_warning(_("iconv cannot convert UTF-7 to %s\n"),
2888                           conv_get_current_charset_str());
2889                 g_string_free(norm_utf7, TRUE);
2890                 g_free(to_str);
2891                 return g_strdup(mutf7_str);
2892         }
2893
2894         /* second iconv() call for flushing */
2895         iconv(cd, NULL, NULL, &to_p, &to_len);
2896         g_string_free(norm_utf7, TRUE);
2897         *to_p = '\0';
2898
2899         return to_str;
2900 #endif /* !HAVE_LIBJCONV */
2901 }
2902
2903 static gchar *imap_locale_to_modified_utf7(const gchar *from)
2904 {
2905 #if !HAVE_LIBJCONV
2906         return g_strdup(from);
2907 #else
2908         static iconv_t cd = (iconv_t)-1;
2909         static gboolean iconv_ok = TRUE;
2910         gchar *norm_utf7, *norm_utf7_p;
2911         size_t from_len, norm_utf7_len;
2912         GString *to_str;
2913         gchar *from_tmp, *to, *p;
2914         gboolean in_escape = FALSE;
2915
2916         if (!iconv_ok) return g_strdup(from);
2917
2918         if (cd == (iconv_t)-1) {
2919                 cd = iconv_open("UTF-7", conv_get_current_charset_str());
2920                 if (cd == (iconv_t)-1) {
2921                         g_warning(_("iconv cannot convert %s to UTF-7\n"),
2922                                   conv_get_current_charset_str());
2923                         iconv_ok = FALSE;
2924                         return g_strdup(from);
2925                 }
2926         }
2927
2928         Xstrdup_a(from_tmp, from, return g_strdup(from));
2929         from_len = strlen(from);
2930         norm_utf7_len = from_len * 5;
2931         Xalloca(norm_utf7, norm_utf7_len + 1, return g_strdup(from));
2932         norm_utf7_p = norm_utf7;
2933
2934 #define IS_PRINT(ch) (isprint(ch) && isascii(ch))
2935
2936         while (from_len > 0) {
2937                 if (IS_PRINT(*from_tmp)) {
2938                         /* printable ascii char */
2939                         *norm_utf7_p = *from_tmp;
2940                         norm_utf7_p++;
2941                         from_tmp++;
2942                         from_len--;
2943                 } else {
2944                         size_t mblen;
2945
2946                         /* unprintable char: convert to UTF-7 */
2947                         for (mblen = 0;
2948                              !IS_PRINT(from_tmp[mblen]) && mblen < from_len;
2949                              mblen++)
2950                                 ;
2951                         from_len -= mblen;
2952                         if (iconv(cd, &from_tmp, &mblen,
2953                                   &norm_utf7_p, &norm_utf7_len) == -1) {
2954                                 g_warning(_("iconv cannot convert %s to UTF-7\n"),
2955                                           conv_get_current_charset_str());
2956                                 return g_strdup(from);
2957                         }
2958
2959                         /* second iconv() call for flushing */
2960                         iconv(cd, NULL, NULL, &norm_utf7_p, &norm_utf7_len);
2961                 }
2962         }
2963
2964 #undef IS_PRINT
2965
2966         *norm_utf7_p = '\0';
2967         to_str = g_string_new(NULL);
2968         for (p = norm_utf7; p < norm_utf7_p; p++) {
2969                 /* replace: '&' -> "&-",
2970                             '+' -> '&',
2971                             escaped '/' -> ',' */
2972                 if (!in_escape && *p == '&') {
2973                         g_string_append(to_str, "&-");
2974                 } else if (!in_escape && *p == '+') {
2975                         g_string_append_c(to_str, '&');
2976                         in_escape = TRUE;
2977                 } else if (in_escape && *p == '/') {
2978                         g_string_append_c(to_str, ',');
2979                 } else if (in_escape && *p == '-') {
2980                         in_escape = FALSE;
2981                         g_string_append_c(to_str, '-');
2982                 } else {
2983                         g_string_append_c(to_str, *p);
2984                 }
2985         }
2986
2987         if (in_escape) {
2988                 in_escape = FALSE;
2989                 g_string_append_c(to_str, '-');
2990         }
2991
2992         to = to_str->str;
2993         g_string_free(to_str, FALSE);
2994
2995         return to;
2996 #endif
2997 }
2998
2999 static gboolean imap_rename_folder_func(GNode *node, gpointer data)
3000 {
3001         FolderItem *item = node->data;
3002         gchar **paths = data;
3003         const gchar *oldpath = paths[0];
3004         const gchar *newpath = paths[1];
3005         gchar *base;
3006         gchar *new_itempath;
3007         gint oldpathlen;
3008
3009         oldpathlen = strlen(oldpath);
3010         if (strncmp(oldpath, item->path, oldpathlen) != 0) {
3011                 g_warning("path doesn't match: %s, %s\n", oldpath, item->path);
3012                 return TRUE;
3013         }
3014
3015         base = item->path + oldpathlen;
3016         while (*base == G_DIR_SEPARATOR) base++;
3017         if (*base == '\0')
3018                 new_itempath = g_strdup(newpath);
3019         else
3020                 new_itempath = g_strconcat(newpath, G_DIR_SEPARATOR_S, base,
3021                                            NULL);
3022         g_free(item->path);
3023         item->path = new_itempath;
3024
3025         return FALSE;
3026 }
3027
3028 GSList *imap_get_num_list(Folder *folder, FolderItem *item)
3029 {
3030         IMAPSession *session;
3031         GSList *msgnum_list = NULL;
3032         gint i;
3033         gint ok, exists = 0, recent = 0, unseen = 0;
3034         guint32 uid_validity = 0;
3035         guint32 uid = 0;
3036
3037         g_return_val_if_fail(folder != NULL, NULL);
3038         g_return_val_if_fail(item != NULL, NULL);
3039         g_return_val_if_fail(item->path != NULL, NULL);
3040         g_return_val_if_fail(folder->type == F_IMAP, NULL);
3041         g_return_val_if_fail(folder->account != NULL, NULL);
3042
3043         session = imap_session_get(folder);
3044         g_return_val_if_fail(session != NULL, NULL);
3045
3046         ok = imap_select(session, IMAP_FOLDER(folder), item->path,
3047                          &exists, &recent, &unseen, &uid_validity);
3048         if (ok != IMAP_SUCCESS)
3049                 return NULL;
3050
3051         for(i = 1; i <= exists; i++) {
3052                 ok = imap_get_uid(session, i, &uid);
3053                 if (ok != IMAP_SUCCESS)
3054                         return msgnum_list;
3055                 msgnum_list = g_slist_prepend(msgnum_list, GINT_TO_POINTER(uid));
3056         }
3057         
3058         return msgnum_list;
3059 }
3060
3061 MsgInfo *imap_fetch_msginfo (Folder *folder, FolderItem *item, gint num)
3062 {
3063         gchar *tmp;
3064         IMAPSession *session;
3065         GString *str;
3066         MsgInfo *msginfo;
3067         
3068         g_return_val_if_fail(folder != NULL, NULL);
3069         g_return_val_if_fail(item != NULL, NULL);
3070         g_return_val_if_fail(item->folder != NULL, NULL);
3071         g_return_val_if_fail(item->folder->type == F_IMAP, NULL);
3072
3073         session = imap_session_get(folder);
3074         g_return_val_if_fail(session != NULL, NULL);
3075
3076         if (imap_cmd_envelope(SESSION(session)->sock, num, num)
3077             != IMAP_SUCCESS) {
3078                 log_warning(_("can't get envelope\n"));
3079                 return NULL;
3080         }
3081
3082         str = g_string_new(NULL);
3083
3084         if ((tmp = sock_getline(SESSION(session)->sock)) == NULL) {
3085                 log_warning(_("error occurred while getting envelope.\n"));
3086                 g_string_free(str, TRUE);
3087                 return NULL;
3088         }
3089         strretchomp(tmp);
3090         log_print("IMAP4< %s\n", tmp);
3091         g_string_assign(str, tmp);
3092         g_free(tmp);
3093
3094         msginfo = imap_parse_envelope(SESSION(session)->sock, item, str);
3095         if (!msginfo) {
3096                 log_warning(_("can't parse envelope: %s\n"), str->str);
3097         }
3098
3099         tmp = NULL;
3100         do {
3101                 g_free(tmp);
3102                 tmp = sock_getline(SESSION(session)->sock);
3103         } while (!(tmp == NULL || tmp[0] != '*' || tmp[1] != ' '));
3104         
3105         msginfo->folder = item;
3106
3107         g_string_free(str, TRUE);
3108         
3109         return msginfo;
3110 }