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