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