Statistics
| Revision:

root / libsylph / imap.c @ 3191

History | View | Annotate | Download (124 KB)

1
/*
2
 * LibSylph -- E-Mail client library
3
 * Copyright (C) 1999-2012 Hiroyuki Yamamoto
4
 *
5
 * This library is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU Lesser General Public
7
 * License as published by the Free Software Foundation; either
8
 * version 2.1 of the License, or (at your option) any later version.
9
 *
10
 * This library 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 GNU
13
 * Lesser General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU Lesser General Public
16
 * License along with this library; if not, write to the Free Software
17
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  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
#if HAVE_ICONV
36
#  include <iconv.h>
37
#endif
38

    
39
#include "sylmain.h"
40
#include "imap.h"
41
#include "socket.h"
42
#include "socks.h"
43
#include "ssl.h"
44
#include "recv.h"
45
#include "procmsg.h"
46
#include "procheader.h"
47
#include "folder.h"
48
#include "prefs_account.h"
49
#include "codeconv.h"
50
#include "md5_hmac.h"
51
#include "base64.h"
52
#include "utils.h"
53
#include "prefs_common.h"
54
#include "virtual.h"
55

    
56
#define IMAP4_PORT        143
57
#if USE_SSL
58
#define IMAPS_PORT        993
59
#endif
60

    
61
#define IMAP_COPY_LIMIT        200
62
#define IMAP_CMD_LIMIT        1000
63

    
64
#define QUOTE_IF_REQUIRED(out, str)                                        \
65
{                                                                        \
66
        if (*str != '"' && strpbrk(str, " \t(){}[]%&*") != NULL) {        \
67
                gchar *__tmp;                                                \
68
                gint len;                                                \
69
                                                                        \
70
                len = strlen(str) + 3;                                        \
71
                Xalloca(__tmp, len, return IMAP_ERROR);                        \
72
                g_snprintf(__tmp, len, "\"%s\"", str);                        \
73
                out = __tmp;                                                \
74
        } else {                                                        \
75
                Xstrdup_a(out, str, return IMAP_ERROR);                        \
76
        }                                                                \
77
}
78

    
79
typedef gint (*IMAPThreadFunc)                (IMAPSession        *session,
80
                                         gpointer         data);
81
typedef gint (*IMAPProgressFunc)        (IMAPSession        *session,
82
                                         gint                 count,
83
                                         gint                 total,
84
                                         gpointer         data);
85

    
86
typedef struct _IMAPRealSession
87
{
88
        IMAPSession imap_session;
89
#if USE_THREADS
90
        GThreadPool *pool;
91
        IMAPThreadFunc thread_func;
92
        gpointer thread_data;
93
        gboolean is_running;
94
        gint prog_count;
95
        gint prog_total;
96
        gint flag;
97
        gint retval;
98
#endif
99
} IMAPRealSession;
100

    
101
static GList *session_list = NULL;
102

    
103
static void imap_folder_init                (Folder                *folder,
104
                                         const gchar        *name,
105
                                         const gchar        *path);
106

    
107
static Folder        *imap_folder_new        (const gchar        *name,
108
                                         const gchar        *path);
109
static void         imap_folder_destroy        (Folder                *folder);
110

    
111
static Session *imap_session_new        (PrefsAccount        *account);
112
static gint imap_session_connect        (IMAPSession        *session);
113
static gint imap_session_reconnect        (IMAPSession        *session);
114
static void imap_session_destroy        (Session        *session);
115
/* static void imap_session_destroy_all        (void); */
116

    
117
static gint imap_search_flags                (IMAPSession        *session,
118
                                         GArray               **uids,
119
                                         GHashTable    **flags_table);
120
static gint imap_fetch_flags                (IMAPSession        *session,
121
                                         GArray               **uids,
122
                                         GHashTable    **flags_table);
123

    
124
static GSList *imap_get_msg_list        (Folder                *folder,
125
                                         FolderItem        *item,
126
                                         gboolean         use_cache);
127
static GSList *imap_get_uncached_msg_list
128
                                        (Folder                *folder,
129
                                         FolderItem        *item);
130
static gchar *imap_fetch_msg                (Folder                *folder,
131
                                         FolderItem        *item,
132
                                         gint                 uid);
133
static MsgInfo *imap_get_msginfo        (Folder                *folder,
134
                                         FolderItem        *item,
135
                                         gint                 uid);
136
static gint imap_add_msg                (Folder                *folder,
137
                                         FolderItem        *dest,
138
                                         const gchar        *file,
139
                                         MsgFlags        *flags,
140
                                         gboolean         remove_source);
141
static gint imap_add_msgs                (Folder                *folder,
142
                                         FolderItem        *dest,
143
                                         GSList                *file_list,
144
                                         gboolean         remove_source,
145
                                         gint                *first);
146
static gint imap_add_msg_msginfo        (Folder                *folder,
147
                                         FolderItem        *dest,
148
                                         MsgInfo        *msginfo,
149
                                         gboolean         remove_source);
150
static gint imap_add_msgs_msginfo        (Folder                *folder,
151
                                         FolderItem        *dest,
152
                                         GSList                *msglist,
153
                                         gboolean         remove_source,
154
                                         gint                *first);
155

    
156
static gint imap_move_msg                (Folder                *folder,
157
                                         FolderItem        *dest,
158
                                         MsgInfo        *msginfo);
159
static gint imap_move_msgs                (Folder                *folder,
160
                                         FolderItem        *dest,
161
                                         GSList                *msglist);
162
static gint imap_copy_msg                (Folder                *folder,
163
                                         FolderItem        *dest,
164
                                         MsgInfo        *msginfo);
165
static gint imap_copy_msgs                (Folder                *folder,
166
                                         FolderItem        *dest,
167
                                         GSList                *msglist);
168

    
169
static gint imap_remove_msg                (Folder                *folder,
170
                                         FolderItem        *item,
171
                                         MsgInfo        *msginfo);
172
static gint imap_remove_msgs                (Folder                *folder,
173
                                         FolderItem        *item,
174
                                         GSList                *msglist);
175
static gint imap_remove_all_msg                (Folder                *folder,
176
                                         FolderItem        *item);
177

    
178
static gboolean imap_is_msg_changed        (Folder                *folder,
179
                                         FolderItem        *item,
180
                                         MsgInfo        *msginfo);
181

    
182
static gint imap_close                        (Folder                *folder,
183
                                         FolderItem        *item);
184

    
185
static gint imap_scan_folder                (Folder                *folder,
186
                                         FolderItem        *item);
187
static gint imap_scan_tree                (Folder                *folder);
188

    
189
static gint imap_create_tree                (Folder                *folder);
190

    
191
static FolderItem *imap_create_folder        (Folder                *folder,
192
                                         FolderItem        *parent,
193
                                         const gchar        *name);
194
static gint imap_rename_folder                (Folder                *folder,
195
                                         FolderItem        *item,
196
                                         const gchar        *name);
197
static gint imap_move_folder                (Folder                *folder,
198
                                         FolderItem        *item,
199
                                         FolderItem        *new_parent);
200
static gint imap_remove_folder                (Folder                *folder,
201
                                         FolderItem        *item);
202

    
203
static IMAPSession *imap_session_get        (Folder                *folder);
204

    
205
static gint imap_greeting                (IMAPSession        *session);
206
static gint imap_auth                        (IMAPSession        *session,
207
                                         const gchar        *user,
208
                                         const gchar        *pass,
209
                                         IMAPAuthType         type);
210

    
211
static gint imap_scan_tree_recursive        (IMAPSession        *session,
212
                                         FolderItem        *item,
213
                                         GSList                *item_list);
214
static GSList *imap_get_folder_list        (IMAPSession        *session,
215
                                         FolderItem        *item);
216
static GSList *imap_parse_list                (IMAPSession        *session,
217
                                         const gchar        *real_path,
218
                                         gchar                *separator);
219
static GSList *imap_add_inter_folders        (GSList                *item_list,
220
                                         const gchar        *root_path);
221
static GSList *imap_get_part_folder_list(GSList                *item_list,
222
                                         FolderItem        *item);
223

    
224
static void imap_create_missing_folders        (Folder                        *folder);
225
static FolderItem *imap_create_special_folder
226
                                        (Folder                        *folder,
227
                                         SpecialFolderItemType         stype,
228
                                         const gchar                *name);
229

    
230
static gint imap_do_copy_msgs                (Folder                *folder,
231
                                         FolderItem        *dest, 
232
                                         GSList                *msglist,
233
                                         gboolean         remove_source);
234
static gint imap_remove_msgs_by_seq_set        (Folder                *folder,
235
                                         FolderItem        *item,
236
                                         GSList                *seq_list);
237

    
238
static GSList *imap_get_uncached_messages        (IMAPSession        *session,
239
                                                 FolderItem        *item,
240
                                                 guint32         first_uid,
241
                                                 guint32         last_uid,
242
                                                 gint                 exists,
243
                                                 gboolean         update_count);
244
static void imap_delete_cached_message                (FolderItem        *item,
245
                                                 guint32         uid);
246
static GSList *imap_delete_cached_messages        (GSList                *mlist,
247
                                                 FolderItem        *item,
248
                                                 guint32         first_uid,
249
                                                 guint32         last_uid);
250
static void imap_delete_all_cached_messages        (FolderItem        *item);
251

    
252
#if USE_SSL
253
static SockInfo *imap_open                (const gchar        *server,
254
                                         gushort         port,
255
                                         SocksInfo        *socks_info,
256
                                         SSLType         ssl_type);
257
#else
258
static SockInfo *imap_open                (const gchar        *server,
259
                                         gushort         port,
260
                                         SocksInfo        *socks_info);
261
#endif
262

    
263
static gint imap_msg_list_change_perm_flags        (GSList                *msglist,
264
                                                 MsgPermFlags         flags,
265
                                                 gboolean         is_set);
266
static gchar *imap_get_flag_str                        (IMAPFlags         flags);
267
static gint imap_set_message_flags                (IMAPSession        *session,
268
                                                 const gchar        *seq_set,
269
                                                 IMAPFlags         flags,
270
                                                 gboolean         is_set);
271
static gint imap_select                                (IMAPSession        *session,
272
                                                 IMAPFolder        *folder,
273
                                                 const gchar        *path,
274
                                                 gint                *exists,
275
                                                 gint                *recent,
276
                                                 gint                *unseen,
277
                                                 guint32        *uid_validity);
278
static gint imap_status                                (IMAPSession        *session,
279
                                                 IMAPFolder        *folder,
280
                                                 const gchar        *path,
281
                                                 gint                *messages,
282
                                                 gint                *recent,
283
                                                 guint32        *uid_next,
284
                                                 guint32        *uid_validity,
285
                                                 gint                *unseen);
286

    
287
static void imap_parse_namespace                (IMAPSession        *session,
288
                                                 IMAPFolder        *folder);
289
static void imap_get_namespace_by_list                (IMAPSession        *session,
290
                                                 IMAPFolder        *folder);
291
static IMAPNameSpace *imap_find_namespace        (IMAPFolder        *folder,
292
                                                 const gchar        *path);
293
static gchar imap_get_path_separator                (IMAPFolder        *folder,
294
                                                 const gchar        *path);
295
static gchar *imap_get_real_path                (IMAPFolder        *folder,
296
                                                 const gchar        *path);
297

    
298
static gchar *imap_parse_atom                (IMAPSession        *session,
299
                                         gchar                *src,
300
                                         gchar                *dest,
301
                                         gint                 dest_len,
302
                                         GString        *str);
303
static MsgFlags imap_parse_flags        (const gchar        *flag_str);
304
static IMAPFlags imap_parse_imap_flags        (const gchar        *flag_str);
305
static MsgInfo *imap_parse_envelope        (IMAPSession        *session,
306
                                         FolderItem        *item,
307
                                         GString        *line_str);
308

    
309
static gboolean imap_has_capability        (IMAPSession        *session,
310
                                         const gchar        *capability);
311
static void imap_capability_free        (IMAPSession        *session);
312

    
313
/* low-level IMAP4rev1 commands */
314
static gint imap_cmd_capability        (IMAPSession        *session);
315
static gint imap_cmd_authenticate
316
                                (IMAPSession        *session,
317
                                 const gchar        *user,
318
                                 const gchar        *pass,
319
                                 IMAPAuthType         type);
320
static gint imap_cmd_login        (IMAPSession        *session,
321
                                 const gchar        *user,
322
                                 const gchar        *pass);
323
static gint imap_cmd_logout        (IMAPSession        *session);
324
static gint imap_cmd_noop        (IMAPSession        *session);
325
#if USE_SSL
326
static gint imap_cmd_starttls        (IMAPSession        *session);
327
#endif
328
static gint imap_cmd_namespace        (IMAPSession        *session,
329
                                 gchar               **ns_str);
330
static gint imap_cmd_list        (IMAPSession        *session,
331
                                 const gchar        *ref,
332
                                 const gchar        *mailbox,
333
                                 GPtrArray        *argbuf);
334
static gint imap_cmd_do_select        (IMAPSession        *session,
335
                                 const gchar        *folder,
336
                                 gboolean         examine,
337
                                 gint                *exists,
338
                                 gint                *recent,
339
                                 gint                *unseen,
340
                                 guint32        *uid_validity);
341
static gint imap_cmd_select        (IMAPSession        *session,
342
                                 const gchar        *folder,
343
                                 gint                *exists,
344
                                 gint                *recent,
345
                                 gint                *unseen,
346
                                 guint32        *uid_validity);
347
static gint imap_cmd_examine        (IMAPSession        *session,
348
                                 const gchar        *folder,
349
                                 gint                *exists,
350
                                 gint                *recent,
351
                                 gint                *unseen,
352
                                 guint32        *uid_validity);
353
static gint imap_cmd_create        (IMAPSession        *session,
354
                                 const gchar        *folder);
355
static gint imap_cmd_rename        (IMAPSession        *session,
356
                                 const gchar        *oldfolder,
357
                                 const gchar        *newfolder);
358
static gint imap_cmd_delete        (IMAPSession        *session,
359
                                 const gchar        *folder);
360
static gint imap_cmd_envelope        (IMAPSession        *session,
361
                                 const gchar        *seq_set);
362
static gint imap_cmd_search        (IMAPSession        *session,
363
                                 const gchar        *criteria,
364
                                 GArray        **result);
365
static gint imap_cmd_fetch        (IMAPSession        *session,
366
                                 guint32         uid,
367
                                 const gchar        *filename);
368
static gint imap_cmd_append        (IMAPSession        *session,
369
                                 const gchar        *destfolder,
370
                                 const gchar        *file,
371
                                 IMAPFlags         flags,
372
                                 guint32        *new_uid);
373
static gint imap_cmd_copy        (IMAPSession        *session,
374
                                 const gchar        *seq_set,
375
                                 const gchar        *destfolder);
376
static gint imap_cmd_store        (IMAPSession        *session,
377
                                 const gchar        *seq_set,
378
                                 const gchar        *sub_cmd);
379
static gint imap_cmd_expunge        (IMAPSession        *session);
380
static gint imap_cmd_close        (IMAPSession        *session);
381

    
382
static gint imap_cmd_ok                (IMAPSession        *session,
383
                                 GPtrArray        *argbuf);
384
static gint imap_cmd_ok_real        (IMAPSession        *session,
385
                                 GPtrArray        *argbuf);
386
static gint imap_cmd_gen_send        (IMAPSession        *session,
387
                                 const gchar        *format, ...);
388
static gint imap_cmd_gen_recv        (IMAPSession        *session,
389
                                 gchar               **ret);
390

    
391
static gint imap_cmd_gen_recv_silent        (IMAPSession        *session,
392
                                         gchar               **ret);
393

    
394
/* misc utility functions */
395
static gchar *strchr_cpy                        (const gchar        *src,
396
                                                 gchar                 ch,
397
                                                 gchar                *dest,
398
                                                 gint                 len);
399
static gchar *get_quoted                        (const gchar        *src,
400
                                                 gchar                 ch,
401
                                                 gchar                *dest,
402
                                                 gint                 len);
403
static gchar *search_array_contain_str                (GPtrArray        *array,
404
                                                 gchar                *str);
405
static gchar *search_array_str                        (GPtrArray        *array,
406
                                                 gchar                *str);
407
static void imap_path_separator_subst                (gchar                *str,
408
                                                 gchar                 separator);
409

    
410
static gchar *imap_modified_utf7_to_utf8        (const gchar        *mutf7_str);
411
static gchar *imap_utf8_to_modified_utf7        (const gchar        *from);
412

    
413
static GSList *imap_get_seq_set_from_msglist        (GSList                *msglist,
414
                                                 gint                 limit);
415
static gint imap_seq_set_get_count                (const gchar        *seq_set);
416
static void imap_seq_set_free                        (GSList                *seq_list);
417

    
418
static GHashTable *imap_get_uid_table                (GArray                *array);
419

    
420
static gboolean imap_rename_folder_func                (GNode                *node,
421
                                                 gpointer         data);
422

    
423
#if USE_THREADS
424
static gint imap_thread_run                (IMAPSession                *session,
425
                                         IMAPThreadFunc                 func,
426
                                         gpointer                 data);
427
static gint imap_thread_run_progress        (IMAPSession                *session,
428
                                         IMAPThreadFunc                 func,
429
                                         IMAPProgressFunc         progress_func,
430
                                         gpointer                 data);
431
#endif
432

    
433
static FolderClass imap_class =
434
{
435
        F_IMAP,
436

    
437
        imap_folder_new,
438
        imap_folder_destroy,
439

    
440
        imap_scan_tree,
441
        imap_create_tree,
442

    
443
        imap_get_msg_list,
444
        imap_get_uncached_msg_list,
445
        imap_fetch_msg,
446
        imap_get_msginfo,
447
        imap_add_msg,
448
        imap_add_msgs,
449
        imap_add_msg_msginfo,
450
        imap_add_msgs_msginfo,
451
        imap_move_msg,
452
        imap_move_msgs,
453
        imap_copy_msg,
454
        imap_copy_msgs,
455
        imap_remove_msg,
456
        imap_remove_msgs,
457
        imap_remove_all_msg,
458
        imap_is_msg_changed,
459
        imap_close,
460
        imap_scan_folder,
461

    
462
        imap_create_folder,
463
        imap_rename_folder,
464
        imap_move_folder,
465
        imap_remove_folder
466
};
467

    
468

    
469
FolderClass *imap_get_class(void)
470
{
471
        return &imap_class;
472
}
473

    
474
static Folder *imap_folder_new(const gchar *name, const gchar *path)
475
{
476
        Folder *folder;
477

    
478
        folder = (Folder *)g_new0(IMAPFolder, 1);
479
        imap_folder_init(folder, name, path);
480

    
481
        return folder;
482
}
483

    
484
static void imap_folder_destroy(Folder *folder)
485
{
486
        g_return_if_fail(folder->account != NULL);
487

    
488
        if (REMOTE_FOLDER(folder)->remove_cache_on_destroy) {
489
                gchar *dir;
490

    
491
                dir = folder_get_path(folder);
492
                if (is_dir_exist(dir))
493
                        remove_dir_recursive(dir);
494
                g_free(dir);
495

    
496
                dir = g_strconcat(get_imap_cache_dir(), G_DIR_SEPARATOR_S,
497
                                  folder->account->recv_server, NULL);
498
                if (is_dir_exist(dir))
499
                        g_rmdir(dir);
500
                g_free(dir);
501
        }
502

    
503
        folder_remote_folder_destroy(REMOTE_FOLDER(folder));
504
}
505

    
506
static void imap_folder_init(Folder *folder, const gchar *name,
507
                             const gchar *path)
508
{
509
        folder->klass = imap_get_class();
510
        folder_remote_folder_init(folder, name, path);
511
}
512

    
513
static IMAPSession *imap_session_get(Folder *folder)
514
{
515
        RemoteFolder *rfolder = REMOTE_FOLDER(folder);
516
        gint ret;
517

    
518
        g_return_val_if_fail(folder != NULL, NULL);
519
        g_return_val_if_fail(FOLDER_TYPE(folder) == F_IMAP, NULL);
520
        g_return_val_if_fail(folder->account != NULL, NULL);
521

    
522
        if (!prefs_common.online_mode)
523
                return NULL;
524

    
525
        if (!rfolder->session) {
526
                rfolder->session = imap_session_new(folder->account);
527
                if (rfolder->session)
528
                        imap_parse_namespace(IMAP_SESSION(rfolder->session),
529
                                             IMAP_FOLDER(folder));
530
                return IMAP_SESSION(rfolder->session);
531
        }
532

    
533
        if (imap_is_session_active(IMAP_FOLDER(folder))) {
534
                g_warning("imap_session_get: session is busy.");
535
                return NULL;
536
        }
537

    
538
        if (time(NULL) - rfolder->session->last_access_time <
539
                SESSION_TIMEOUT_INTERVAL) {
540
                return IMAP_SESSION(rfolder->session);
541
        }
542

    
543
        if ((ret = imap_cmd_noop(IMAP_SESSION(rfolder->session))) != IMAP_SUCCESS) {
544
                if (ret == IMAP_EAGAIN) {
545
                        g_warning("imap_session_get: session is busy.");
546
                        return NULL;
547
                }
548

    
549
                log_warning(_("IMAP4 connection to %s has been"
550
                              " disconnected. Reconnecting...\n"),
551
                            folder->account->recv_server);
552
                if (imap_session_reconnect(IMAP_SESSION(rfolder->session))
553
                    == IMAP_SUCCESS)
554
                        imap_parse_namespace(IMAP_SESSION(rfolder->session),
555
                                             IMAP_FOLDER(folder));
556
                else {
557
                        session_destroy(rfolder->session);
558
                        rfolder->session = NULL;
559
                }
560
        }
561

    
562
        return IMAP_SESSION(rfolder->session);
563
}
564

    
565
static gint imap_greeting(IMAPSession *session)
566
{
567
        gchar *greeting;
568
        gint ok;
569

    
570
        if ((ok = imap_cmd_gen_recv(session, &greeting)) != IMAP_SUCCESS) {
571
                log_warning("Cannot get greeting message (%d)\n", ok);
572
                return ok;
573
        }
574

    
575
        if (greeting[0] != '*' || greeting[1] != ' ')
576
                ok = IMAP_ERROR;
577
        else if (!strncmp(greeting + 2, "OK", 2))
578
                ok = IMAP_SUCCESS;
579
        else if (!strncmp(greeting + 2, "PREAUTH", 7)) {
580
                session->authenticated = TRUE;
581
                ok = IMAP_SUCCESS;
582
        } else
583
                ok = IMAP_ERROR;
584

    
585
        g_free(greeting);
586
        return ok;
587
}
588

    
589
static gint imap_auth(IMAPSession *session, const gchar *user,
590
                      const gchar *pass, IMAPAuthType type)
591
{
592
        gboolean nologin;
593
        gint ok = IMAP_AUTHFAIL;
594

    
595
        nologin = imap_has_capability(session, "LOGINDISABLED");
596

    
597
        switch (type) {
598
        case 0:
599
                if (imap_has_capability(session, "AUTH=CRAM-MD5"))
600
                        ok = imap_cmd_authenticate(session, user, pass,
601
                                                   IMAP_AUTH_CRAM_MD5);
602
                else if (imap_has_capability(session, "AUTH=PLAIN"))
603
                        ok = imap_cmd_authenticate(session, user, pass,
604
                                                   IMAP_AUTH_PLAIN);
605
                else if (nologin)
606
                        log_print(_("IMAP4 server disables LOGIN.\n"));
607
                else
608
                        ok = imap_cmd_login(session, user, pass);
609
                break;
610
        case IMAP_AUTH_LOGIN:
611
                if (nologin)
612
                        log_warning(_("IMAP4 server disables LOGIN.\n"));
613
                else
614
                        ok = imap_cmd_login(session, user, pass);
615
                break;
616
        case IMAP_AUTH_CRAM_MD5:
617
        case IMAP_AUTH_PLAIN:
618
                ok = imap_cmd_authenticate(session, user, pass, type);
619
                break;
620
        default:
621
                break;
622
        }
623

    
624
        if (ok == IMAP_SUCCESS)
625
                session->authenticated = TRUE;
626

    
627
        return ok;
628
}
629

    
630
static Session *imap_session_new(PrefsAccount *account)
631
{
632
        IMAPSession *session;
633
        gushort port;
634

    
635
        g_return_val_if_fail(account != NULL, NULL);
636
        g_return_val_if_fail(account->recv_server != NULL, NULL);
637
        g_return_val_if_fail(account->userid != NULL, NULL);
638

    
639
#if USE_SSL
640
        port = account->set_imapport ? account->imapport
641
                : account->ssl_imap == SSL_TUNNEL ? IMAPS_PORT : IMAP4_PORT;
642
#else
643
        port = account->set_imapport ? account->imapport : IMAP4_PORT;
644
#endif
645

    
646
        session = IMAP_SESSION(g_new0(IMAPRealSession, 1));
647

    
648
        session_init(SESSION(session));
649

    
650
        SESSION(session)->type             = SESSION_IMAP;
651
        SESSION(session)->sock             = NULL;
652
        SESSION(session)->server           = g_strdup(account->recv_server);
653
        SESSION(session)->port             = port;
654
#if USE_SSL
655
        SESSION(session)->ssl_type         = account->ssl_imap;
656
#endif
657
        SESSION(session)->last_access_time = time(NULL);
658
        SESSION(session)->data             = account;
659

    
660
        SESSION(session)->destroy          = imap_session_destroy;
661

    
662
        session->authenticated = FALSE;
663
        session->capability    = NULL;
664
        session->uidplus       = FALSE;
665
        session->mbox          = NULL;
666
        session->cmd_count     = 0;
667

    
668
        session_list = g_list_append(session_list, session);
669

    
670
        if (imap_session_connect(session) != IMAP_SUCCESS) {
671
                log_warning(_("Could not establish IMAP connection.\n"));
672
                session_destroy(SESSION(session));
673
                return NULL;
674
        }
675

    
676
        return SESSION(session);
677
}
678

    
679
static gint imap_session_connect(IMAPSession *session)
680
{
681
        SockInfo *sock;
682
        SocksInfo *socks_info = NULL;
683
        PrefsAccount *account;
684
        const gchar *pass;
685

    
686
        g_return_val_if_fail(session != NULL, IMAP_ERROR);
687

    
688
        account = (PrefsAccount *)(SESSION(session)->data);
689

    
690
        log_message(_("creating IMAP4 connection to %s:%d ...\n"),
691
                    SESSION(session)->server, SESSION(session)->port);
692

    
693
        pass = account->passwd;
694
        if (!pass)
695
                pass = account->tmp_pass;
696
        if (!pass) {
697
                gchar *tmp_pass;
698

    
699
                tmp_pass = input_query_password(account->recv_server,
700
                                                account->userid);
701
                if (!tmp_pass)
702
                        return IMAP_ERROR;
703

    
704
                account->tmp_pass = tmp_pass;
705
                pass = account->tmp_pass;
706
        }
707

    
708
        if (account->use_socks && account->use_socks_for_recv &&
709
            account->proxy_host) {
710
                socks_info = socks_info_new(account->socks_type, account->proxy_host, account->proxy_port, account->use_proxy_auth ? account->proxy_name : NULL, account->use_proxy_auth ? account->proxy_pass : NULL);
711
        }
712

    
713
#if USE_SSL
714
        if ((sock = imap_open(SESSION(session)->server, SESSION(session)->port,
715
                              socks_info, SESSION(session)->ssl_type)) == NULL)
716
#else
717
        if ((sock = imap_open(SESSION(session)->server, SESSION(session)->port,
718
                              socks_info))
719
            == NULL)
720
#endif
721
                return IMAP_ERROR;
722

    
723
        if (socks_info)
724
                socks_info_free(socks_info);
725

    
726
        SESSION(session)->sock = sock;
727

    
728
        if (imap_greeting(session) != IMAP_SUCCESS)
729
                return IMAP_ERROR;
730
        if (imap_cmd_capability(session) != IMAP_SUCCESS)
731
                return IMAP_ERROR;
732

    
733
        if (imap_has_capability(session, "UIDPLUS"))
734
                session->uidplus = TRUE;
735

    
736
#if USE_SSL
737
        if (account->ssl_imap == SSL_STARTTLS &&
738
            imap_has_capability(session, "STARTTLS")) {
739
                gint ok;
740

    
741
                ok = imap_cmd_starttls(session);
742
                if (ok != IMAP_SUCCESS) {
743
                        log_warning(_("Can't start TLS session.\n"));
744
                        return IMAP_ERROR;
745
                }
746
                if (!ssl_init_socket_with_method(sock, SSL_METHOD_TLSv1))
747
                        return IMAP_SOCKET;
748

    
749
                /* capability can be changed after STARTTLS */
750
                if (imap_cmd_capability(session) != IMAP_SUCCESS)
751
                        return IMAP_ERROR;
752
        }
753
#endif
754

    
755
        if (!session->authenticated &&
756
            imap_auth(session, account->userid, pass, account->imap_auth_type)
757
            != IMAP_SUCCESS) {
758
                if (account->tmp_pass) {
759
                        g_free(account->tmp_pass);
760
                        account->tmp_pass = NULL;
761
                }
762
                imap_cmd_logout(session);
763
                return IMAP_AUTHFAIL;
764
        }
765

    
766
        return IMAP_SUCCESS;
767
}
768

    
769
static gint imap_session_reconnect(IMAPSession *session)
770
{
771
        g_return_val_if_fail(session != NULL, IMAP_ERROR);
772

    
773
        session_disconnect(SESSION(session));
774

    
775
        imap_capability_free(session);
776
        session->uidplus = FALSE;
777
        g_free(session->mbox);
778
        session->mbox = NULL;
779
        session->authenticated = FALSE;
780
        SESSION(session)->state = SESSION_READY;
781

    
782
        return imap_session_connect(session);
783
}
784

    
785
static void imap_session_destroy(Session *session)
786
{
787
#if USE_THREADS
788
        IMAPRealSession *real = (IMAPRealSession *)session;
789

    
790
        if (real->pool)
791
                g_thread_pool_free(real->pool, TRUE, TRUE);
792
#endif
793
        imap_capability_free(IMAP_SESSION(session));
794
        g_free(IMAP_SESSION(session)->mbox);
795
        session_list = g_list_remove(session_list, session);
796
}
797

    
798
#if 0
799
static void imap_session_destroy_all(void)
800
{
801
        while (session_list != NULL) {
802
                IMAPSession *session = (IMAPSession *)session_list->data;
803

804
                imap_cmd_logout(session);
805
                session_destroy(SESSION(session));
806
        }
807
}
808
#endif
809

    
810
#define THROW goto catch
811

    
812
static gint imap_search_flags(IMAPSession *session, GArray **uids,
813
                              GHashTable **flags_table)
814
{
815
        gint ok;
816
        gint i;
817
        GArray *flag_uids;
818
        GHashTable *unseen_table;
819
        GHashTable *flagged_table;
820
        GHashTable *answered_table;
821
        guint32 uid;
822
        IMAPFlags flags;
823

    
824
        ok = imap_cmd_search(session, "ALL", uids);
825
        if (ok != IMAP_SUCCESS) return ok;
826

    
827
        ok = imap_cmd_search(session, "UNSEEN", &flag_uids);
828
        if (ok != IMAP_SUCCESS) {
829
                g_array_free(*uids, TRUE);
830
                return ok;
831
        }
832
        unseen_table = imap_get_uid_table(flag_uids);
833
        g_array_free(flag_uids, TRUE);
834
        ok = imap_cmd_search(session, "FLAGGED", &flag_uids);
835
        if (ok != IMAP_SUCCESS) {
836
                g_hash_table_destroy(unseen_table);
837
                g_array_free(*uids, TRUE);
838
                return ok;
839
        }
840
        flagged_table = imap_get_uid_table(flag_uids);
841
        g_array_free(flag_uids, TRUE);
842
        ok = imap_cmd_search(session, "ANSWERED", &flag_uids);
843
        if (ok != IMAP_SUCCESS) {
844
                g_hash_table_destroy(flagged_table);
845
                g_hash_table_destroy(unseen_table);
846
                g_array_free(*uids, TRUE);
847
                return ok;
848
        }
849
        answered_table = imap_get_uid_table(flag_uids);
850
        g_array_free(flag_uids, TRUE);
851

    
852
        *flags_table = g_hash_table_new(NULL, g_direct_equal);
853

    
854
        for (i = 0; i < (*uids)->len; i++) {
855
                uid = g_array_index(*uids, guint32, i);
856
                flags = IMAP_FLAG_DRAFT;
857
                if (!g_hash_table_lookup(unseen_table, GUINT_TO_POINTER(uid)))
858
                        flags |= IMAP_FLAG_SEEN;
859
                if (g_hash_table_lookup(flagged_table, GUINT_TO_POINTER(uid)))
860
                        flags |= IMAP_FLAG_FLAGGED;
861
                if (g_hash_table_lookup(answered_table, GUINT_TO_POINTER(uid)))
862
                        flags |= IMAP_FLAG_ANSWERED;
863
                g_hash_table_insert(*flags_table, GUINT_TO_POINTER(uid),
864
                                    GINT_TO_POINTER(flags));
865
        }
866

    
867
        g_hash_table_destroy(answered_table);
868
        g_hash_table_destroy(flagged_table);
869
        g_hash_table_destroy(unseen_table);
870

    
871
        return IMAP_SUCCESS;
872
}
873

    
874
static gint imap_fetch_flags(IMAPSession *session, GArray **uids,
875
                             GHashTable **flags_table)
876
{
877
        gint ok;
878
        gchar *tmp;
879
        gchar *cur_pos;
880
        gchar buf[IMAPBUFSIZE];
881
        guint32 uid;
882
        IMAPFlags flags;
883

    
884
        if (imap_cmd_gen_send(session, "UID FETCH 1:* (UID FLAGS)") != IMAP_SUCCESS)
885
                return IMAP_ERROR;
886

    
887
        *uids = g_array_new(FALSE, FALSE, sizeof(guint32));
888
        *flags_table = g_hash_table_new(NULL, g_direct_equal);
889

    
890
        log_print("IMAP4< %s\n", _("(retrieving FLAGS...)"));
891

    
892
        while ((ok = imap_cmd_gen_recv_silent(session, &tmp)) == IMAP_SUCCESS) {
893
                if (tmp[0] != '*' || tmp[1] != ' ') {
894
                        log_print("IMAP4< %s\n", tmp);
895
                        g_free(tmp);
896
                        break;
897
                }
898
                cur_pos = tmp + 2;
899

    
900
#define PARSE_ONE_ELEMENT(ch)                                        \
901
{                                                                \
902
        cur_pos = strchr_cpy(cur_pos, ch, buf, sizeof(buf));        \
903
        if (cur_pos == NULL) {                                        \
904
                g_warning("cur_pos == NULL\n");                        \
905
                g_free(tmp);                                        \
906
                g_hash_table_destroy(*flags_table);                \
907
                g_array_free(*uids, TRUE);                        \
908
                return IMAP_ERROR;                                \
909
        }                                                        \
910
}
911

    
912
                PARSE_ONE_ELEMENT(' ');
913
                PARSE_ONE_ELEMENT(' ');
914
                if (strcmp(buf, "FETCH") != 0) {
915
                        g_free(tmp);
916
                        continue;
917
                }
918
                if (*cur_pos != '(') {
919
                        g_free(tmp);
920
                        continue;
921
                }
922
                cur_pos++;
923
                uid = 0;
924
                flags = 0;
925

    
926
                while (*cur_pos != '\0' && *cur_pos != ')') {
927
                        while (*cur_pos == ' ') cur_pos++;
928

    
929
                        if (!strncmp(cur_pos, "UID ", 4)) {
930
                                cur_pos += 4;
931
                                uid = strtoul(cur_pos, &cur_pos, 10);
932
                        } else if (!strncmp(cur_pos, "FLAGS ", 6)) {
933
                                cur_pos += 6;
934
                                if (*cur_pos != '(') {
935
                                        g_warning("*cur_pos != '('\n");
936
                                        break;
937
                                }
938
                                cur_pos++;
939
                                PARSE_ONE_ELEMENT(')');
940
                                flags = imap_parse_imap_flags(buf);
941
                                flags |= IMAP_FLAG_DRAFT;
942
                        } else {
943
                                g_warning("invalid FETCH response: %s\n", cur_pos);
944
                                break;
945
                        }
946
                }
947

    
948
#undef PARSE_ONE_ELEMENT
949

    
950
                if (uid > 0) {
951
                        g_array_append_val(*uids, uid);
952
                        g_hash_table_insert(*flags_table, GUINT_TO_POINTER(uid),
953
                                            GINT_TO_POINTER(flags));
954
                }
955

    
956
                g_free(tmp);
957
        }
958

    
959
        if (ok != IMAP_SUCCESS) {
960
                g_hash_table_destroy(*flags_table);
961
                g_array_free(*uids, TRUE);
962
        }
963

    
964
        return ok;
965
}
966

    
967
static GSList *imap_get_msg_list_full(Folder *folder, FolderItem *item,
968
                                      gboolean use_cache,
969
                                      gboolean uncached_only)
970
{
971
        GSList *mlist = NULL;
972
        IMAPSession *session;
973
        gint ok, exists = 0, recent = 0, unseen = 0;
974
        guint32 uid_validity = 0;
975
        guint32 first_uid = 0, last_uid = 0;
976
        GSList *newlist = NULL;
977

    
978
        g_return_val_if_fail(folder != NULL, NULL);
979
        g_return_val_if_fail(item != NULL, NULL);
980
        g_return_val_if_fail(FOLDER_TYPE(folder) == F_IMAP, NULL);
981
        g_return_val_if_fail(folder->account != NULL, NULL);
982

    
983
        item->new = item->unread = item->total = 0;
984

    
985
        session = imap_session_get(folder);
986

    
987
        if (!session) {
988
                if (uncached_only)
989
                        return NULL;
990
                mlist = procmsg_read_cache(item, FALSE);
991
                item->last_num = procmsg_get_last_num_in_msg_list(mlist);
992
                procmsg_set_flags(mlist, item);
993
                return mlist;
994
        }
995

    
996
        ok = imap_select(session, IMAP_FOLDER(folder), item->path,
997
                         &exists, &recent, &unseen, &uid_validity);
998
        if (ok != IMAP_SUCCESS) THROW;
999

    
1000
        if (exists == 0) {
1001
                imap_delete_all_cached_messages(item);
1002
                return NULL;
1003
        }
1004

    
1005
        /* invalidate current cache if UIDVALIDITY has been changed */
1006
        if (item->mtime != uid_validity) {
1007
                debug_print("imap_get_msg_list: "
1008
                            "UIDVALIDITY has been changed.\n");
1009
                use_cache = FALSE;
1010
        }
1011

    
1012
        if (use_cache) {
1013
                GArray *uids;
1014
                GHashTable *msg_table;
1015
                GHashTable *flags_table;
1016
                guint32 cache_last;
1017
                guint32 begin = 0;
1018
                GSList *cur, *next = NULL;
1019
                MsgInfo *msginfo;
1020
                IMAPFlags imap_flags;
1021
                guint color;
1022

    
1023
                /* get cache data */
1024
                mlist = procmsg_read_cache(item, FALSE);
1025
                procmsg_set_flags(mlist, item);
1026
                cache_last = procmsg_get_last_num_in_msg_list(mlist);
1027

    
1028
                /* get all UID list and flags */
1029
#if 0
1030
                ok = imap_search_flags(session, &uids, &flags_table);
1031
                if (ok != IMAP_SUCCESS) {
1032
                        if (ok == IMAP_SOCKET || ok == IMAP_IOERR) THROW;
1033
                        ok = imap_fetch_flags(session, &uids, &flags_table);
1034
                        if (ok != IMAP_SUCCESS) THROW;
1035
                }
1036
#else
1037
                ok = imap_fetch_flags(session, &uids, &flags_table);
1038
                if (ok != IMAP_SUCCESS) THROW;
1039
#endif
1040

    
1041
                if (uids->len > 0) {
1042
                        first_uid = g_array_index(uids, guint32, 0);
1043
                        last_uid = g_array_index(uids, guint32, uids->len - 1);
1044
                } else {
1045
                        g_array_free(uids, TRUE);
1046
                        g_hash_table_destroy(flags_table);
1047
                        THROW;
1048
                }
1049

    
1050
                /* sync message flags with server */
1051
                for (cur = mlist; cur != NULL; cur = next) {
1052
                        msginfo = (MsgInfo *)cur->data;
1053
                        next = cur->next;
1054
                        imap_flags = GPOINTER_TO_INT(g_hash_table_lookup
1055
                                (flags_table,
1056
                                 GUINT_TO_POINTER(msginfo->msgnum)));
1057

    
1058
                        if (imap_flags == 0) {
1059
                                debug_print("imap_get_msg_list: "
1060
                                            "message %u has been deleted.\n",
1061
                                            msginfo->msgnum);
1062
                                imap_delete_cached_message
1063
                                        (item, msginfo->msgnum);
1064
                                if (MSG_IS_NEW(msginfo->flags))
1065
                                        item->new--;
1066
                                if (MSG_IS_UNREAD(msginfo->flags))
1067
                                        item->unread--;
1068
                                item->total--;
1069
                                mlist = g_slist_remove(mlist, msginfo);
1070
                                procmsg_msginfo_free(msginfo);
1071
                                item->cache_dirty = TRUE;
1072
                                item->mark_dirty = TRUE;
1073
                                continue;
1074
                        }
1075

    
1076
                        if (!IMAP_IS_SEEN(imap_flags)) {
1077
                                if (!MSG_IS_UNREAD(msginfo->flags)) {
1078
                                        item->unread++;
1079
                                        MSG_SET_PERM_FLAGS(msginfo->flags,
1080
                                                           MSG_UNREAD);
1081
                                        item->mark_dirty = TRUE;
1082
                                }
1083
                        } else {
1084
                                if (MSG_IS_NEW(msginfo->flags)) {
1085
                                        item->new--;
1086
                                        item->mark_dirty = TRUE;
1087
                                }
1088
                                if (MSG_IS_UNREAD(msginfo->flags)) {
1089
                                        item->unread--;
1090
                                        item->mark_dirty = TRUE;
1091
                                }
1092
                                MSG_UNSET_PERM_FLAGS(msginfo->flags,
1093
                                                     MSG_NEW|MSG_UNREAD);
1094
                        }
1095

    
1096
                        if (IMAP_IS_FLAGGED(imap_flags)) {
1097
                                if (!MSG_IS_MARKED(msginfo->flags)) {
1098
                                        MSG_SET_PERM_FLAGS(msginfo->flags,
1099
                                                           MSG_MARKED);
1100
                                        item->mark_dirty = TRUE;
1101
                                }
1102
                        } else {
1103
                                if (MSG_IS_MARKED(msginfo->flags)) {
1104
                                        MSG_UNSET_PERM_FLAGS(msginfo->flags,
1105
                                                             MSG_MARKED);
1106
                                        item->mark_dirty = TRUE;
1107
                                }
1108
                        }
1109
                        if (IMAP_IS_ANSWERED(imap_flags)) {
1110
                                if (!MSG_IS_REPLIED(msginfo->flags)) {
1111
                                        MSG_SET_PERM_FLAGS(msginfo->flags,
1112
                                                           MSG_REPLIED);
1113
                                        item->mark_dirty = TRUE;
1114
                                }
1115
                        } else {
1116
                                if (MSG_IS_REPLIED(msginfo->flags)) {
1117
                                        MSG_UNSET_PERM_FLAGS(msginfo->flags,
1118
                                                             MSG_REPLIED);
1119
                                        item->mark_dirty = TRUE;
1120
                                }
1121
                        }
1122

    
1123
                        color = IMAP_GET_COLORLABEL_VALUE(imap_flags);
1124
                        if (MSG_GET_COLORLABEL_VALUE(msginfo->flags) != color) {
1125
                                MSG_UNSET_PERM_FLAGS(msginfo->flags,
1126
                                                     MSG_CLABEL_FLAG_MASK);
1127
                                MSG_SET_COLORLABEL_VALUE(msginfo->flags, color);
1128
                                item->mark_dirty = TRUE;
1129
                        }
1130
                }
1131

    
1132
                /* check for the first new message */
1133
                msg_table = procmsg_msg_hash_table_create(mlist);
1134
                if (msg_table == NULL)
1135
                        begin = first_uid;
1136
                else {
1137
                        gint i;
1138

    
1139
                        for (i = 0; i < uids->len; i++) {
1140
                                guint32 uid;
1141

    
1142
                                uid = g_array_index(uids, guint32, i);
1143
                                if (g_hash_table_lookup
1144
                                        (msg_table, GUINT_TO_POINTER(uid))
1145
                                        == NULL) {
1146
                                        debug_print("imap_get_msg_list: "
1147
                                                    "first new UID: %u\n", uid);
1148
                                        begin = uid;
1149
                                        break;
1150
                                }
1151
                        }
1152
                        g_hash_table_destroy(msg_table);
1153
                }
1154

    
1155
                g_array_free(uids, TRUE);
1156
                g_hash_table_destroy(flags_table);
1157

    
1158
                /* remove ununsed caches */
1159
                if (first_uid > 0 && last_uid > 0) {
1160
                        mlist = imap_delete_cached_messages
1161
                                (mlist, item, 0, first_uid - 1);
1162
                        mlist = imap_delete_cached_messages
1163
                                (mlist, item, begin > 0 ? begin : last_uid + 1,
1164
                                 UINT_MAX);
1165
                }
1166

    
1167
                if (begin > 0 && begin <= last_uid) {
1168
                        newlist = imap_get_uncached_messages
1169
                                (session, item, begin, last_uid,
1170
                                 exists - item->total, TRUE);
1171
                        if (newlist) {
1172
                                item->cache_dirty = TRUE;
1173
                                item->mark_dirty = TRUE;
1174
                        }
1175
                        mlist = g_slist_concat(mlist, newlist);
1176
                }
1177
        } else {
1178
                imap_delete_all_cached_messages(item);
1179
                mlist = imap_get_uncached_messages(session, item, 0, 0, exists,
1180
                                                   TRUE);
1181
                last_uid = procmsg_get_last_num_in_msg_list(mlist);
1182
                item->cache_dirty = TRUE;
1183
                item->mark_dirty = TRUE;
1184
                newlist = mlist;
1185
        }
1186

    
1187
        if (!uncached_only)
1188
                mlist = procmsg_sort_msg_list(mlist, item->sort_key,
1189
                                              item->sort_type);
1190

    
1191
        item->last_num = last_uid;
1192

    
1193
        if (item->mark_queue)
1194
                item->mark_dirty = TRUE;
1195

    
1196
        debug_print("cache_dirty: %d, mark_dirty: %d\n",
1197
                    item->cache_dirty, item->mark_dirty);
1198

    
1199
        if (!item->opened) {
1200
                item->mtime = uid_validity;
1201
                if (item->cache_dirty)
1202
                        procmsg_write_cache_list(item, mlist);
1203
                if (item->mark_dirty)
1204
                        procmsg_write_flags_list(item, mlist);
1205
        }
1206

    
1207
catch:
1208
        if (uncached_only) {
1209
                GSList *cur;
1210

    
1211
                if (newlist == NULL) {
1212
                        procmsg_msg_list_free(mlist);
1213
                        return NULL;
1214
                }
1215
                if (mlist == newlist)
1216
                        return newlist;
1217
                for (cur = mlist; cur != NULL; cur = cur->next) {
1218
                        if (cur->next == newlist) {
1219
                                cur->next = NULL;
1220
                                procmsg_msg_list_free(mlist);
1221
                                return newlist;
1222
                        }
1223
                }
1224
                procmsg_msg_list_free(mlist);
1225
                return NULL;
1226
        }
1227

    
1228
        return mlist;
1229
}
1230

    
1231
#undef THROW
1232

    
1233
static GSList *imap_get_msg_list(Folder *folder, FolderItem *item,
1234
                                 gboolean use_cache)
1235
{
1236
        return imap_get_msg_list_full(folder, item, use_cache, FALSE);
1237
}
1238

    
1239
static GSList *imap_get_uncached_msg_list(Folder *folder, FolderItem *item)
1240
{
1241
        return imap_get_msg_list_full(folder, item, TRUE, TRUE);
1242
}
1243

    
1244
static gchar *imap_fetch_msg(Folder *folder, FolderItem *item, gint uid)
1245
{
1246
        gchar *path, *filename;
1247
        IMAPSession *session;
1248
        gchar nstr[16];
1249
        guint32 uid32 = (guint32)uid;
1250
        gint ok;
1251

    
1252
        g_return_val_if_fail(folder != NULL, NULL);
1253
        g_return_val_if_fail(item != NULL, NULL);
1254

    
1255
        path = folder_item_get_path(item);
1256
        if (!is_dir_exist(path))
1257
                make_dir_hier(path);
1258
        g_snprintf(nstr, sizeof(nstr), "%u", uid32);
1259
        filename = g_strconcat(path, G_DIR_SEPARATOR_S, nstr, NULL);
1260
        g_free(path);
1261

    
1262
        if (is_file_exist(filename) && get_file_size(filename) > 0) {
1263
                debug_print("message %u has been already cached.\n", uid32);
1264
                return filename;
1265
        }
1266

    
1267
        session = imap_session_get(folder);
1268
        if (!session) {
1269
                g_free(filename);
1270
                return NULL;
1271
        }
1272

    
1273
        ok = imap_select(session, IMAP_FOLDER(folder), item->path,
1274
                         NULL, NULL, NULL, NULL);
1275
        if (ok != IMAP_SUCCESS) {
1276
                g_warning("can't select mailbox %s\n", item->path);
1277
                g_free(filename);
1278
                return NULL;
1279
        }
1280

    
1281
        status_print(_("Getting message %u"), uid32);
1282
        debug_print("getting message %u...\n", uid32);
1283
        ok = imap_cmd_fetch(session, uid32, filename);
1284

    
1285
        if (ok != IMAP_SUCCESS) {
1286
                g_warning("can't fetch message %u\n", uid32);
1287
                g_free(filename);
1288
                return NULL;
1289
        }
1290

    
1291
        return filename;
1292
}
1293

    
1294
static MsgInfo *imap_get_msginfo(Folder *folder, FolderItem *item, gint uid)
1295
{
1296
        IMAPSession *session;
1297
        GSList *list;
1298
        MsgInfo *msginfo = NULL;
1299
        gint ok;
1300

    
1301
        g_return_val_if_fail(folder != NULL, NULL);
1302
        g_return_val_if_fail(item != NULL, NULL);
1303

    
1304
        session = imap_session_get(folder);
1305
        g_return_val_if_fail(session != NULL, NULL);
1306

    
1307
        ok = imap_select(session, IMAP_FOLDER(folder), item->path,
1308
                         NULL, NULL, NULL, NULL);
1309
        if (ok != IMAP_SUCCESS)
1310
                return NULL;
1311

    
1312
        list = imap_get_uncached_messages(session, item, uid, uid, 0, FALSE);
1313
        if (list) {
1314
                msginfo = (MsgInfo *)list->data;
1315
                list->data = NULL;
1316
        }
1317
        procmsg_msg_list_free(list);
1318

    
1319
        return msginfo;
1320
}
1321

    
1322
static gint imap_add_msg(Folder *folder, FolderItem *dest, const gchar *file,
1323
                         MsgFlags *flags, gboolean remove_source)
1324
{
1325
        GSList file_list;
1326
        MsgFileInfo fileinfo;
1327

    
1328
        g_return_val_if_fail(file != NULL, -1);
1329

    
1330
        fileinfo.file = (gchar *)file;
1331
        fileinfo.flags = flags;
1332
        file_list.data = &fileinfo;
1333
        file_list.next = NULL;
1334

    
1335
        return imap_add_msgs(folder, dest, &file_list, remove_source, NULL);
1336
}
1337

    
1338
static gint imap_add_msgs(Folder *folder, FolderItem *dest, GSList *file_list,
1339
                          gboolean remove_source, gint *first)
1340
{
1341
        gchar *destdir;
1342
        IMAPSession *session;
1343
        gint messages, recent, unseen;
1344
        guint32 uid_next, uid_validity;
1345
        guint32 last_uid = 0;
1346
        GSList *cur;
1347
        MsgFileInfo *fileinfo;
1348
        gint count = 1;
1349
        gint total;
1350
        gint ok;
1351
        GTimeVal tv_prev, tv_cur;
1352

    
1353
        g_return_val_if_fail(folder != NULL, -1);
1354
        g_return_val_if_fail(dest != NULL, -1);
1355
        g_return_val_if_fail(file_list != NULL, -1);
1356

    
1357
        session = imap_session_get(folder);
1358
        if (!session) return -1;
1359

    
1360
        g_get_current_time(&tv_prev);
1361
        ui_update();
1362

    
1363
        ok = imap_status(session, IMAP_FOLDER(folder), dest->path,
1364
                         &messages, &recent, &uid_next, &uid_validity, &unseen);
1365
        if (ok != IMAP_SUCCESS) {
1366
                g_warning("can't append messages\n");
1367
                return -1;
1368
        }
1369

    
1370
        destdir = imap_get_real_path(IMAP_FOLDER(folder), dest->path);
1371

    
1372
        if (!session->uidplus)
1373
                last_uid = uid_next - 1;
1374
        if (first)
1375
                *first = uid_next;
1376

    
1377
        total = g_slist_length(file_list);
1378

    
1379
        for (cur = file_list; cur != NULL; cur = cur->next) {
1380
                IMAPFlags iflags = 0;
1381
                guint32 new_uid = 0;
1382

    
1383
                fileinfo = (MsgFileInfo *)cur->data;
1384

    
1385
                if (fileinfo->flags) {
1386
                        if (MSG_IS_MARKED(*fileinfo->flags))
1387
                                iflags |= IMAP_FLAG_FLAGGED;
1388
                        if (MSG_IS_REPLIED(*fileinfo->flags))
1389
                                iflags |= IMAP_FLAG_ANSWERED;
1390
                        if (!MSG_IS_UNREAD(*fileinfo->flags))
1391
                                iflags |= IMAP_FLAG_SEEN;
1392
                }
1393

    
1394
                if (dest->stype == F_OUTBOX ||
1395
                    dest->stype == F_QUEUE  ||
1396
                    dest->stype == F_DRAFT)
1397
                        iflags |= IMAP_FLAG_SEEN;
1398

    
1399
                g_get_current_time(&tv_cur);
1400
                if (tv_cur.tv_sec > tv_prev.tv_sec ||
1401
                    tv_cur.tv_usec - tv_prev.tv_usec >
1402
                    PROGRESS_UPDATE_INTERVAL * 1000) {
1403
                        status_print(_("Appending messages to %s (%d / %d)"),
1404
                                     dest->path, count, total);
1405
                        progress_show(count, total);
1406
                        ui_update();
1407
                        tv_prev = tv_cur;
1408
                }
1409
                ++count;
1410

    
1411
                ok = imap_cmd_append(session, destdir, fileinfo->file, iflags,
1412
                                     &new_uid);
1413

    
1414
                if (ok != IMAP_SUCCESS) {
1415
                        g_warning("can't append message %s\n", fileinfo->file);
1416
                        g_free(destdir);
1417
                        progress_show(0, 0);
1418
                        return -1;
1419
                }
1420

    
1421
                if (syl_app_get())
1422
                        g_signal_emit_by_name(syl_app_get(), "add-msg", dest, fileinfo->file, new_uid);
1423

    
1424
                if (!session->uidplus)
1425
                        last_uid++;
1426
                else if (last_uid < new_uid)
1427
                        last_uid = new_uid;
1428

    
1429
                dest->last_num = last_uid;
1430
                dest->total++;
1431
                dest->updated = TRUE;
1432

    
1433
                if (fileinfo->flags) {
1434
                        if (MSG_IS_UNREAD(*fileinfo->flags))
1435
                                dest->unread++;
1436
                } else
1437
                        dest->unread++;
1438
        }
1439

    
1440
        progress_show(0, 0);
1441
        g_free(destdir);
1442

    
1443
        if (remove_source) {
1444
                for (cur = file_list; cur != NULL; cur = cur->next) {
1445
                        fileinfo = (MsgFileInfo *)cur->data;
1446
                        if (g_unlink(fileinfo->file) < 0)
1447
                                 FILE_OP_ERROR(fileinfo->file, "unlink");
1448
                }
1449
        }
1450

    
1451
        return last_uid;
1452
}
1453

    
1454
static gint imap_add_msg_msginfo(Folder *folder, FolderItem *dest,
1455
                                 MsgInfo *msginfo, gboolean remove_source)
1456
{
1457
        GSList msglist;
1458

    
1459
        g_return_val_if_fail(msginfo != NULL, -1);
1460

    
1461
        msglist.data = msginfo;
1462
        msglist.next = NULL;
1463

    
1464
        return imap_add_msgs_msginfo(folder, dest, &msglist, remove_source,
1465
                                     NULL);
1466
}
1467

    
1468
static gint imap_add_msgs_msginfo(Folder *folder, FolderItem *dest,
1469
                                  GSList *msglist, gboolean remove_source,
1470
                                  gint *first)
1471
{
1472
        GSList *file_list;
1473
        gint ret;
1474

    
1475
        file_list = procmsg_get_message_file_list(msglist);
1476
        g_return_val_if_fail(file_list != NULL, -1);
1477

    
1478
        ret = imap_add_msgs(folder, dest, file_list, remove_source, first);
1479

    
1480
        procmsg_message_file_list_free(file_list);
1481

    
1482
        return ret;
1483
}
1484

    
1485
static gint imap_do_copy_msgs(Folder *folder, FolderItem *dest, GSList *msglist,
1486
                              gboolean remove_source)
1487
{
1488
        FolderItem *src;
1489
        gchar *destdir;
1490
        GSList *seq_list, *cur;
1491
        MsgInfo *msginfo;
1492
        IMAPSession *session;
1493
        gint count = 0, total;
1494
        gint ok = IMAP_SUCCESS;
1495

    
1496
        g_return_val_if_fail(folder != NULL, -1);
1497
        g_return_val_if_fail(dest != NULL, -1);
1498
        g_return_val_if_fail(msglist != NULL, -1);
1499

    
1500
        session = imap_session_get(folder);
1501
        if (!session) return -1;
1502

    
1503
        ui_update();
1504

    
1505
        msginfo = (MsgInfo *)msglist->data;
1506

    
1507
        src = msginfo->folder;
1508
        if (src == dest) {
1509
                g_warning("the src folder is identical to the dest.\n");
1510
                return -1;
1511
        }
1512

    
1513
        ok = imap_select(session, IMAP_FOLDER(folder), src->path,
1514
                         NULL, NULL, NULL, NULL);
1515
        if (ok != IMAP_SUCCESS)
1516
                return ok;
1517

    
1518
        destdir = imap_get_real_path(IMAP_FOLDER(folder), dest->path);
1519

    
1520
        total = g_slist_length(msglist);
1521
        seq_list = imap_get_seq_set_from_msglist(msglist, IMAP_COPY_LIMIT);
1522

    
1523
        for (cur = seq_list; cur != NULL; cur = cur->next) {
1524
                gchar *seq_set = (gchar *)cur->data;
1525

    
1526
                count += imap_seq_set_get_count(seq_set);
1527

    
1528
                if (remove_source) {
1529
                        status_print(_("Moving messages %s to %s ..."),
1530
                                     seq_set, dest->path);
1531
                        debug_print("Moving message %s/[%s] to %s ...\n",
1532
                                    src->path, seq_set, dest->path);
1533
                } else {
1534
                        status_print(_("Copying messages %s to %s ..."),
1535
                                     seq_set, dest->path);
1536
                        debug_print("Copying message %s/[%s] to %s ...\n",
1537
                                    src->path, seq_set, dest->path);
1538
                }
1539
                progress_show(count, total);
1540
                ui_update();
1541

    
1542
                ok = imap_cmd_copy(session, seq_set, destdir);
1543
                if (ok != IMAP_SUCCESS) {
1544
                        imap_seq_set_free(seq_list);
1545
                        progress_show(0, 0);
1546
                        return -1;
1547
                }
1548
        }
1549

    
1550
        progress_show(0, 0);
1551

    
1552
        dest->updated = TRUE;
1553

    
1554
        imap_seq_set_free(seq_list);
1555
        g_free(destdir);
1556

    
1557
        for (cur = msglist; cur != NULL; cur = cur->next) {
1558
                msginfo = (MsgInfo *)cur->data;
1559

    
1560
                if (syl_app_get())
1561
                        g_signal_emit_by_name(syl_app_get(), "add-msg", dest, NULL, 0);
1562

    
1563
                dest->total++;
1564
                if (MSG_IS_NEW(msginfo->flags))
1565
                        dest->new++;
1566
                if (MSG_IS_UNREAD(msginfo->flags))
1567
                        dest->unread++;
1568
        }
1569

    
1570
        if (remove_source) {
1571
                ok = imap_remove_msgs(folder, src, msglist);
1572
                if (ok != IMAP_SUCCESS)
1573
                        return ok;
1574
        }
1575

    
1576
        if (ok == IMAP_SUCCESS)
1577
                return 0;
1578
        else
1579
                return -1;
1580
}
1581

    
1582
static gint imap_move_msg(Folder *folder, FolderItem *dest, MsgInfo *msginfo)
1583
{
1584
        GSList msglist;
1585

    
1586
        g_return_val_if_fail(msginfo != NULL, -1);
1587

    
1588
        msglist.data = msginfo;
1589
        msglist.next = NULL;
1590

    
1591
        return imap_move_msgs(folder, dest, &msglist);
1592
}
1593

    
1594
static gint imap_move_msgs(Folder *folder, FolderItem *dest, GSList *msglist)
1595
{
1596
        MsgInfo *msginfo;
1597
        GSList *file_list;
1598
        gint ret = 0;
1599

    
1600
        g_return_val_if_fail(folder != NULL, -1);
1601
        g_return_val_if_fail(dest != NULL, -1);
1602
        g_return_val_if_fail(msglist != NULL, -1);
1603

    
1604
        msginfo = (MsgInfo *)msglist->data;
1605
        g_return_val_if_fail(msginfo->folder != NULL, -1);
1606

    
1607
        if (folder == msginfo->folder->folder)
1608
                return imap_do_copy_msgs(folder, dest, msglist, TRUE);
1609

    
1610
        file_list = procmsg_get_message_file_list(msglist);
1611
        g_return_val_if_fail(file_list != NULL, -1);
1612

    
1613
        ret = imap_add_msgs(folder, dest, file_list, FALSE, NULL);
1614

    
1615
        procmsg_message_file_list_free(file_list);
1616

    
1617
        if (ret != -1)
1618
                ret = folder_item_remove_msgs(msginfo->folder, msglist);
1619

    
1620
        return ret;
1621
}
1622

    
1623
static gint imap_copy_msg(Folder *folder, FolderItem *dest, MsgInfo *msginfo)
1624
{
1625
        GSList msglist;
1626

    
1627
        g_return_val_if_fail(msginfo != NULL, -1);
1628

    
1629
        msglist.data = msginfo;
1630
        msglist.next = NULL;
1631

    
1632
        return imap_copy_msgs(folder, dest, &msglist);
1633
}
1634

    
1635
static gint imap_copy_msgs(Folder *folder, FolderItem *dest, GSList *msglist)
1636
{
1637
        MsgInfo *msginfo;
1638
        GSList *file_list;
1639
        gint ret;
1640

    
1641
        g_return_val_if_fail(folder != NULL, -1);
1642
        g_return_val_if_fail(dest != NULL, -1);
1643
        g_return_val_if_fail(msglist != NULL, -1);
1644

    
1645
        msginfo = (MsgInfo *)msglist->data;
1646
        g_return_val_if_fail(msginfo->folder != NULL, -1);
1647

    
1648
        if (folder == msginfo->folder->folder)
1649
                return imap_do_copy_msgs(folder, dest, msglist, FALSE);
1650

    
1651
        file_list = procmsg_get_message_file_list(msglist);
1652
        g_return_val_if_fail(file_list != NULL, -1);
1653

    
1654
        ret = imap_add_msgs(folder, dest, file_list, FALSE, NULL);
1655

    
1656
        procmsg_message_file_list_free(file_list);
1657

    
1658
        return ret;
1659
}
1660

    
1661
static gint imap_remove_msgs_by_seq_set(Folder *folder, FolderItem *item,
1662
                                        GSList *seq_list)
1663
{
1664
        gint ok;
1665
        IMAPSession *session;
1666
        GSList *cur;
1667

    
1668
        g_return_val_if_fail(seq_list != NULL, -1);
1669

    
1670
        session = imap_session_get(folder);
1671
        if (!session) return -1;
1672

    
1673
        for (cur = seq_list; cur != NULL; cur = cur->next) {
1674
                gchar *seq_set = (gchar *)cur->data;
1675

    
1676
                status_print(_("Removing messages %s"), seq_set);
1677
                ui_update();
1678

    
1679
                ok = imap_set_message_flags(session, seq_set, IMAP_FLAG_DELETED,
1680
                                            TRUE);
1681
                if (ok != IMAP_SUCCESS) {
1682
                        log_warning(_("can't set deleted flags: %s\n"),
1683
                                    seq_set);
1684
                        return ok;
1685
                }
1686
        }
1687

    
1688
        ok = imap_cmd_expunge(session);
1689
        if (ok != IMAP_SUCCESS) {
1690
                log_warning(_("can't expunge\n"));
1691
        } else {
1692
                /* for some broken IMAP servers */
1693
                ok = imap_cmd_noop(session);
1694
        }
1695

    
1696
        item->updated = TRUE;
1697

    
1698
        return ok;
1699
}
1700

    
1701
static gint imap_remove_msg(Folder *folder, FolderItem *item, MsgInfo *msginfo)
1702
{
1703
        GSList msglist;
1704

    
1705
        g_return_val_if_fail(msginfo != NULL, -1);
1706

    
1707
        msglist.data = msginfo;
1708
        msglist.next = NULL;
1709

    
1710
        return imap_remove_msgs(folder, item, &msglist);
1711
}
1712

    
1713
static gint imap_remove_msgs(Folder *folder, FolderItem *item, GSList *msglist)
1714
{
1715
        gint ok;
1716
        IMAPSession *session;
1717
        GSList *seq_list, *cur;
1718
        gchar *dir;
1719
        gboolean dir_exist;
1720

    
1721
        g_return_val_if_fail(folder != NULL, -1);
1722
        g_return_val_if_fail(FOLDER_TYPE(folder) == F_IMAP, -1);
1723
        g_return_val_if_fail(item != NULL, -1);
1724
        g_return_val_if_fail(msglist != NULL, -1);
1725

    
1726
        session = imap_session_get(folder);
1727
        if (!session) return -1;
1728

    
1729
        ok = imap_select(session, IMAP_FOLDER(folder), item->path,
1730
                         NULL, NULL, NULL, NULL);
1731
        if (ok != IMAP_SUCCESS)
1732
                return ok;
1733

    
1734
        seq_list = imap_get_seq_set_from_msglist(msglist, 0);
1735
        ok = imap_remove_msgs_by_seq_set(folder, item, seq_list);
1736
        imap_seq_set_free(seq_list);
1737
        if (ok != IMAP_SUCCESS)
1738
                return ok;
1739

    
1740
        dir = folder_item_get_path(item);
1741
        dir_exist = is_dir_exist(dir);
1742
        for (cur = msglist; cur != NULL; cur = cur->next) {
1743
                MsgInfo *msginfo = (MsgInfo *)cur->data;
1744
                guint32 uid = msginfo->msgnum;
1745

    
1746
                if (syl_app_get())
1747
                        g_signal_emit_by_name(syl_app_get(), "remove-msg", item, NULL, uid);
1748

    
1749
                if (dir_exist)
1750
                        remove_numbered_files(dir, uid, uid);
1751
                item->total--;
1752
                if (MSG_IS_NEW(msginfo->flags))
1753
                        item->new--;
1754
                if (MSG_IS_UNREAD(msginfo->flags))
1755
                        item->unread--;
1756
                MSG_SET_TMP_FLAGS(msginfo->flags, MSG_INVALID);
1757
        }
1758
        g_free(dir);
1759

    
1760
        return IMAP_SUCCESS;
1761
}
1762

    
1763
static gint imap_remove_all_msg(Folder *folder, FolderItem *item)
1764
{
1765
        gint ok;
1766
        IMAPSession *session;
1767
        gchar *dir;
1768

    
1769
        g_return_val_if_fail(folder != NULL, -1);
1770
        g_return_val_if_fail(item != NULL, -1);
1771

    
1772
        session = imap_session_get(folder);
1773
        if (!session) return -1;
1774

    
1775
        ok = imap_select(session, IMAP_FOLDER(folder), item->path,
1776
                         NULL, NULL, NULL, NULL);
1777
        if (ok != IMAP_SUCCESS)
1778
                return ok;
1779

    
1780
        status_print(_("Removing all messages in %s"), item->path);
1781
        ui_update();
1782

    
1783
        ok = imap_cmd_gen_send(session, "STORE 1:* +FLAGS.SILENT (\\Deleted)");
1784
        if (ok != IMAP_SUCCESS) {
1785
                log_warning(_("can't set deleted flags: 1:*\n"));
1786
                return ok;
1787
        }
1788
        ok = imap_cmd_ok(session, NULL);
1789
        if (ok != IMAP_SUCCESS) {
1790
                log_warning(_("can't set deleted flags: 1:*\n"));
1791
                return ok;
1792
        }
1793

    
1794
        ok = imap_cmd_expunge(session);
1795
        if (ok != IMAP_SUCCESS) {
1796
                log_warning(_("can't expunge\n"));
1797
                return ok;
1798
        }
1799

    
1800
        if (syl_app_get())
1801
                g_signal_emit_by_name(syl_app_get(), "remove-all-msg", item);
1802

    
1803
        item->new = item->unread = item->total = 0;
1804
        item->updated = TRUE;
1805

    
1806
        dir = folder_item_get_path(item);
1807
        if (is_dir_exist(dir))
1808
                remove_all_numbered_files(dir);
1809
        g_free(dir);
1810

    
1811
        return IMAP_SUCCESS;
1812
}
1813

    
1814
static gboolean imap_is_msg_changed(Folder *folder, FolderItem *item,
1815
                                    MsgInfo *msginfo)
1816
{
1817
        /* TODO: properly implement this method */
1818
        return FALSE;
1819
}
1820

    
1821
static gint imap_close(Folder *folder, FolderItem *item)
1822
{
1823
        gint ok;
1824
        IMAPSession *session;
1825

    
1826
        g_return_val_if_fail(folder != NULL, -1);
1827

    
1828
        if (!item->path) return 0;
1829

    
1830
        if (!REMOTE_FOLDER(folder)->session)
1831
                return 0;
1832

    
1833
        session = imap_session_get(folder);
1834
        if (!session) return -1;
1835

    
1836
        if (session->mbox) {
1837
                if (strcmp2(session->mbox, item->path) != 0) return -1;
1838

    
1839
                ok = imap_cmd_close(session);
1840
                if (ok != IMAP_SUCCESS)
1841
                        log_warning(_("can't close folder\n"));
1842

    
1843
                g_free(session->mbox);
1844
                session->mbox = NULL;
1845

    
1846
                return ok;
1847
        } else
1848
                return 0;
1849
}
1850

    
1851
static gint imap_scan_folder(Folder *folder, FolderItem *item)
1852
{
1853
        IMAPSession *session;
1854
        gint messages, recent, unseen;
1855
        guint32 uid_next, uid_validity;
1856
        gint ok;
1857

    
1858
        g_return_val_if_fail(folder != NULL, -1);
1859
        g_return_val_if_fail(item != NULL, -1);
1860

    
1861
        session = imap_session_get(folder);
1862
        if (!session) return -1;
1863

    
1864
        ok = imap_status(session, IMAP_FOLDER(folder), item->path,
1865
                         &messages, &recent, &uid_next, &uid_validity, &unseen);
1866
        if (ok != IMAP_SUCCESS) return -1;
1867

    
1868
        item->new = unseen > 0 ? recent : 0;
1869
        item->unread = unseen;
1870
        item->total = messages;
1871
        item->last_num = (messages > 0 && uid_next > 0) ? uid_next - 1 : 0;
1872
        /* item->mtime = uid_validity; */
1873
        item->updated = TRUE;
1874

    
1875
        return 0;
1876
}
1877

    
1878
static gint imap_scan_tree(Folder *folder)
1879
{
1880
        FolderItem *item = NULL;
1881
        IMAPSession *session;
1882
        gchar *root_folder = NULL;
1883
        GSList *item_list, *cur;
1884

    
1885
        g_return_val_if_fail(folder != NULL, -1);
1886
        g_return_val_if_fail(folder->account != NULL, -1);
1887

    
1888
        session = imap_session_get(folder);
1889
        if (!session) {
1890
                if (!folder->node) {
1891
                        folder_tree_destroy(folder);
1892
                        item = folder_item_new(folder->name, NULL);
1893
                        item->folder = folder;
1894
                        folder->node = item->node = g_node_new(item);
1895
                }
1896
                return -1;
1897
        }
1898

    
1899
        if (folder->account->imap_dir && *folder->account->imap_dir) {
1900
                gchar *real_path;
1901
                GPtrArray *argbuf;
1902
                gint ok;
1903

    
1904
                Xstrdup_a(root_folder, folder->account->imap_dir, return -1);
1905
                extract_quote(root_folder, '"');
1906
                subst_char(root_folder,
1907
                           imap_get_path_separator(IMAP_FOLDER(folder),
1908
                                                   root_folder),
1909
                           '/');
1910
                strtailchomp(root_folder, '/');
1911
                real_path = imap_get_real_path
1912
                        (IMAP_FOLDER(folder), root_folder);
1913
                debug_print("IMAP root directory: %s\n", real_path);
1914

    
1915
                /* check if root directory exist */
1916
                argbuf = g_ptr_array_new();
1917
                ok = imap_cmd_list(session, NULL, real_path, argbuf);
1918
                if (ok != IMAP_SUCCESS ||
1919
                    search_array_str(argbuf, "LIST ") == NULL) {
1920
                        log_warning(_("root folder %s not exist\n"), real_path);
1921
                        g_ptr_array_free(argbuf, TRUE);
1922
                        g_free(real_path);
1923
                        return -1;
1924
                }
1925
                g_ptr_array_free(argbuf, TRUE);
1926
                g_free(real_path);
1927
        }
1928

    
1929
        if (folder->node)
1930
                item = FOLDER_ITEM(folder->node->data);
1931
        if (!item || ((item->path || root_folder) &&
1932
                      strcmp2(item->path, root_folder) != 0)) {
1933
                folder_tree_destroy(folder);
1934
                item = folder_item_new(folder->name, root_folder);
1935
                item->folder = folder;
1936
                folder->node = item->node = g_node_new(item);
1937
        }
1938

    
1939
        item_list = imap_get_folder_list(session, item);
1940
        imap_scan_tree_recursive(session, item, item_list);
1941
        imap_create_missing_folders(folder);
1942

    
1943
        for (cur = item_list; cur != NULL; cur = cur->next)
1944
                folder_item_destroy(FOLDER_ITEM(cur->data));
1945
        g_slist_free(item_list);
1946

    
1947
        return 0;
1948
}
1949

    
1950
static gint imap_scan_tree_recursive(IMAPSession *session, FolderItem *item,
1951
                                     GSList *item_list)
1952
{
1953
        Folder *folder;
1954
        FolderItem *new_item;
1955
        GSList *part_list, *cur;
1956
        GNode *node;
1957

    
1958
        g_return_val_if_fail(item != NULL, -1);
1959
        g_return_val_if_fail(item->folder != NULL, -1);
1960
        g_return_val_if_fail(item->no_sub == FALSE, -1);
1961

    
1962
        folder = item->folder;
1963

    
1964
        part_list = imap_get_part_folder_list(item_list, item);
1965

    
1966
        node = item->node->children;
1967
        while (node != NULL) {
1968
                FolderItem *old_item = FOLDER_ITEM(node->data);
1969
                GNode *next = node->next;
1970

    
1971
                new_item = NULL;
1972

    
1973
                for (cur = part_list; cur != NULL; cur = cur->next) {
1974
                        FolderItem *cur_item = FOLDER_ITEM(cur->data);
1975
                        if (!strcmp2(old_item->path, cur_item->path)) {
1976
                                new_item = cur_item;
1977
                                break;
1978
                        }
1979
                }
1980
                if (!new_item) {
1981
                        if (old_item->stype != F_VIRTUAL) {
1982
                                debug_print("folder '%s' not found. removing...\n", old_item->path);
1983
                                folder_item_remove(old_item);
1984
                        }
1985
                } else if (old_item->stype == F_VIRTUAL) {
1986
                                debug_print("IMAP4 folder found at the location of virtual folder '%s'. removing virtual folder...\n", old_item->path);
1987
                                virtual_get_class()->remove_folder
1988
                                        (folder, old_item);
1989
                } else {
1990
                        old_item->no_sub = new_item->no_sub;
1991
                        old_item->no_select = new_item->no_select;
1992
                        if (old_item->no_select == TRUE)
1993
                                old_item->new = old_item->unread =
1994
                                        old_item->total = 0;
1995
                        if (old_item->no_sub == TRUE && node->children) {
1996
                                debug_print("folder '%s' doesn't have "
1997
                                            "subfolders. removing...\n",
1998
                                            old_item->path);
1999
                                folder_item_remove_children(old_item);
2000
                        }
2001
                }
2002

    
2003
                node = next;
2004
        }
2005

    
2006
        for (cur = part_list; cur != NULL; cur = cur->next) {
2007
                FolderItem *cur_item = FOLDER_ITEM(cur->data);
2008
                new_item = NULL;
2009
                for (node = item->node->children; node != NULL;
2010
                     node = node->next) {
2011
                        if (!strcmp2(FOLDER_ITEM(node->data)->path,
2012
                                     cur_item->path)) {
2013
                                new_item = FOLDER_ITEM(node->data);
2014
                                cur_item = NULL;
2015
                                break;
2016
                        }
2017
                }
2018
                if (!new_item) {
2019
                        new_item = folder_item_copy(cur_item);
2020
                        debug_print("new folder '%s' found.\n", new_item->path);
2021
                        folder_item_append(item, new_item);
2022
                }
2023

    
2024
                if (!g_ascii_strcasecmp(new_item->path, "INBOX")) {
2025
                        new_item->stype = F_INBOX;
2026
                        folder->inbox = new_item;
2027
                } else if (!item->parent || item->stype == F_INBOX) {
2028
                        const gchar *base;
2029

    
2030
                        base = g_basename(new_item->path);
2031

    
2032
                        if (!folder->outbox &&
2033
                            !g_ascii_strcasecmp(base, "Sent")) {
2034
                                new_item->stype = F_OUTBOX;
2035
                                folder->outbox = new_item;
2036
                        } else if (!folder->draft &&
2037
                                   !g_ascii_strcasecmp(base, "Drafts")) {
2038
                                new_item->stype = F_DRAFT;
2039
                                folder->draft = new_item;
2040
                        } else if (!folder->queue &&
2041
                                   !g_ascii_strcasecmp(base, "Queue")) {
2042
                                new_item->stype = F_QUEUE;
2043
                                folder->queue = new_item;
2044
                        } else if (!folder->trash &&
2045
                                   !g_ascii_strcasecmp(base, "Trash")) {
2046
                                new_item->stype = F_TRASH;
2047
                                folder->trash = new_item;
2048
                        }
2049
                }
2050

    
2051
#if 0
2052
                if (new_item->no_select == FALSE)
2053
                        imap_scan_folder(folder, new_item);
2054
#endif
2055
                if (new_item->no_sub == FALSE)
2056
                        imap_scan_tree_recursive(session, new_item, item_list);
2057
        }
2058

    
2059
        g_slist_free(part_list);
2060

    
2061
        return IMAP_SUCCESS;
2062
}
2063

    
2064
static GSList *imap_get_folder_list(IMAPSession *session, FolderItem *item)
2065
{
2066
        Folder *folder;
2067
        IMAPFolder *imapfolder;
2068
        gchar *real_path;
2069
        gchar *wildcard_path;
2070
        gchar separator;
2071
        GSList *item_list = NULL;
2072

    
2073
        folder = item->folder;
2074
        imapfolder = IMAP_FOLDER(folder);
2075

    
2076
        separator = imap_get_path_separator(imapfolder, item->path);
2077

    
2078
        if (folder->ui_func)
2079
                folder->ui_func(folder, item, folder->ui_func_data);
2080

    
2081
        if (item->path) {
2082
                real_path = imap_get_real_path(imapfolder, item->path);
2083
                strtailchomp(real_path, separator);
2084
                wildcard_path = g_strdup_printf("%s%c*", real_path, separator);
2085
        } else {
2086
                real_path = g_strdup("");
2087
                wildcard_path = g_strdup("*");
2088
        }
2089

    
2090
        if (imap_cmd_gen_send(session, "LIST \"\" \"%s\"", wildcard_path) == IMAP_SUCCESS) {
2091
                item_list = imap_parse_list(session, real_path, NULL);
2092
                item_list = imap_add_inter_folders(item_list, item->path);
2093
        }
2094
        g_free(real_path);
2095
        g_free(wildcard_path);
2096

    
2097
        return item_list;
2098
}
2099

    
2100
static GSList *imap_parse_list(IMAPSession *session, const gchar *real_path,
2101
                               gchar *separator)
2102
{
2103
        gchar buf[IMAPBUFSIZE];
2104
        gchar flags[256];
2105
        gchar separator_str[16];
2106
        gchar *p;
2107
        const gchar *name;
2108
        gchar *loc_name, *loc_path;
2109
        GSList *item_list = NULL;
2110
        GString *str;
2111
        FolderItem *new_item;
2112

    
2113
        debug_print("getting list of %s ...\n",
2114
                    *real_path ? real_path : "\"\"");
2115

    
2116
        str = g_string_new(NULL);
2117

    
2118
        for (;;) {
2119
                if (sock_gets(SESSION(session)->sock, buf, sizeof(buf)) <= 0) {
2120
                        log_warning(_("error occurred while getting LIST.\n"));
2121
                        break;
2122
                }
2123
                strretchomp(buf);
2124
                if (buf[0] != '*' || buf[1] != ' ') {
2125
                        log_print("IMAP4< %s\n", buf);
2126
                        if (sscanf(buf, "%*d %16s", buf) < 1 ||
2127
                            strcmp(buf, "OK") != 0)
2128
                                log_warning(_("error occurred while getting LIST.\n"));
2129
                                
2130
                        break;
2131
                }
2132
                debug_print("IMAP4< %s\n", buf);
2133

    
2134
                g_string_assign(str, buf);
2135
                p = str->str + 2;
2136
                if (strncmp(p, "LIST ", 5) != 0) continue;
2137
                p += 5;
2138

    
2139
                if (*p != '(') continue;
2140
                p++;
2141
                p = strchr_cpy(p, ')', flags, sizeof(flags));
2142
                if (!p) continue;
2143
                while (*p == ' ') p++;
2144

    
2145
                p = strchr_cpy(p, ' ', separator_str, sizeof(separator_str));
2146
                if (!p) continue;
2147
                extract_quote(separator_str, '"');
2148
                if (!strcmp(separator_str, "NIL"))
2149
                        separator_str[0] = '\0';
2150
                if (separator)
2151
                        *separator = separator_str[0];
2152

    
2153
                buf[0] = '\0';
2154
                while (*p == ' ') p++;
2155
                if ((*p == '~' && *(p + 1) == '{') || *p == '{' || *p == '"')
2156
                        p = imap_parse_atom(session, p, buf, sizeof(buf), str);
2157
                else
2158
                        strncpy2(buf, p, sizeof(buf));
2159
                strtailchomp(buf, separator_str[0]);
2160
                if (buf[0] == '\0') continue;
2161
                if (!strcmp(buf, real_path)) continue;
2162

    
2163
                if (separator_str[0] != '\0')
2164
                        subst_char(buf, separator_str[0], '/');
2165
                name = g_basename(buf);
2166
                if (name[0] == '.') continue;
2167

    
2168
                loc_name = imap_modified_utf7_to_utf8(name);
2169
                loc_path = imap_modified_utf7_to_utf8(buf);
2170
                new_item = folder_item_new(loc_name, loc_path);
2171
                if (strcasestr(flags, "\\Noinferiors") != NULL)
2172
                        new_item->no_sub = TRUE;
2173
                if (g_ascii_strcasecmp(buf, "INBOX") != 0 &&
2174
                    strcasestr(flags, "\\Noselect") != NULL)
2175
                        new_item->no_select = TRUE;
2176

    
2177
                item_list = g_slist_prepend(item_list, new_item);
2178

    
2179
                debug_print("folder '%s' found.\n", loc_path);
2180
                g_free(loc_path);
2181
                g_free(loc_name);
2182
        }
2183

    
2184
        g_string_free(str, TRUE);
2185

    
2186
        item_list = g_slist_reverse(item_list);
2187
        return item_list;
2188
}
2189

    
2190
static GSList *imap_add_inter_folders(GSList *item_list, const gchar *root_path)
2191
{
2192
        FolderItem *item;
2193
        GSList *cur;
2194
        GSList *add_list = NULL;
2195
        GHashTable *exist;
2196
        const gchar *p;
2197
        gint root_path_len = 0;
2198

    
2199
        if (root_path)
2200
                root_path_len = strlen(root_path);
2201

    
2202
        exist = g_hash_table_new(g_str_hash, g_str_equal);
2203

    
2204
        for (cur = item_list; cur != NULL; cur = cur->next) {
2205
                item = FOLDER_ITEM(cur->data);
2206

    
2207
                if (root_path_len > 0 &&
2208
                    strncmp(root_path, item->path, root_path_len) != 0)
2209
                        continue;
2210
                p = item->path + root_path_len;
2211
                if (root_path_len > 0 && *p != '/') continue;
2212
                while (*p == '/') p++;
2213
                if (*p == '\0') continue;
2214
                g_hash_table_insert(exist, (gpointer)p, GINT_TO_POINTER(1));
2215
        }
2216

    
2217
        for (cur = item_list; cur != NULL; cur = cur->next) {
2218
                const gchar *q, *r;
2219
                gchar *parent, *full_parent;
2220
                FolderItem *new_item;
2221

    
2222
                item = FOLDER_ITEM(cur->data);
2223

    
2224
                if (root_path_len > 0 &&
2225
                    strncmp(root_path, item->path, root_path_len) != 0)
2226
                        continue;
2227
                p = item->path + root_path_len;
2228
                if (root_path_len > 0 && *p != '/') continue;
2229
                while (*p == '/') p++;
2230
                if (*p == '\0') continue;
2231

    
2232
                q = p;
2233
                while ((q = strchr(q, '/')) != NULL) {
2234
                        parent = g_strndup(p, q - p);
2235
                        if (!g_hash_table_lookup(exist, parent)) {
2236
                                if (root_path_len > 0)
2237
                                        full_parent = g_strconcat
2238
                                                (root_path, "/", parent, NULL);
2239
                                else
2240
                                        full_parent = g_strdup(parent);
2241
                                new_item = folder_item_new(g_basename(parent),
2242
                                                           full_parent);
2243
                                new_item->no_select = TRUE;
2244
                                add_list = g_slist_prepend(add_list, new_item);
2245
                                r = new_item->path + root_path_len;
2246
                                while (*r == '/') r++;
2247
                                g_hash_table_insert(exist, (gpointer)r,
2248
                                                    GINT_TO_POINTER(1));
2249
                                debug_print("intermediate folder '%s' added\n",
2250
                                            full_parent);
2251
                                g_free(full_parent);
2252
                        }
2253
                        g_free(parent);
2254
                        while (*q == '/') q++;
2255
                }
2256
        }
2257

    
2258
        g_hash_table_destroy(exist);
2259

    
2260
        add_list = g_slist_reverse(add_list);
2261
        item_list = g_slist_concat(item_list, add_list);
2262

    
2263
        return item_list;
2264
}
2265

    
2266
static GSList *imap_get_part_folder_list(GSList *item_list, FolderItem *item)
2267
{
2268
        FolderItem *cur_item;
2269
        GSList *part_list = NULL, *cur;
2270
        gint len;
2271

    
2272
        if (!item->path) {
2273
                debug_print("imap_get_part_folder_list(): get root folders\n");
2274
                for (cur = item_list; cur != NULL; cur = cur->next) {
2275
                        cur_item = FOLDER_ITEM(cur->data);
2276

    
2277
                        if (!strchr(cur_item->path, '/')) {
2278
                                part_list = g_slist_prepend(part_list,
2279
                                                            cur_item);
2280
                                debug_print("append '%s'\n", cur_item->path);
2281
                        }
2282
                }
2283
                part_list = g_slist_reverse(part_list);
2284
                return part_list;
2285
        }
2286

    
2287
        len = strlen(item->path);
2288
        debug_print("imap_get_part_folder_list(): get folders under '%s'\n",
2289
                    item->path);
2290

    
2291
        for (cur = item_list; cur != NULL; cur = cur->next) {
2292
                cur_item = FOLDER_ITEM(cur->data);
2293

    
2294
                if (!strncmp(cur_item->path, item->path, len) &&
2295
                    cur_item->path[len] == '/' &&
2296
                    !strchr(cur_item->path + len + 1, '/')) {
2297
                        part_list = g_slist_prepend(part_list, cur_item);
2298
                        debug_print("append '%s'\n", cur_item->path);
2299
                }
2300
        }
2301

    
2302
        part_list = g_slist_reverse(part_list);
2303
        return part_list;
2304
}
2305

    
2306
static gint imap_create_tree(Folder *folder)
2307
{
2308
        g_return_val_if_fail(folder != NULL, -1);
2309
        g_return_val_if_fail(folder->node != NULL, -1);
2310
        g_return_val_if_fail(folder->node->data != NULL, -1);
2311
        g_return_val_if_fail(folder->account != NULL, -1);
2312

    
2313
        if (imap_scan_tree(folder) < 0)
2314
                return -1;
2315
        imap_create_missing_folders(folder);
2316

    
2317
        return 0;
2318
}
2319

    
2320
static void imap_create_missing_folders(Folder *folder)
2321
{
2322
        g_return_if_fail(folder != NULL);
2323

    
2324
        if (!folder->inbox)
2325
                folder->inbox = imap_create_special_folder
2326
                        (folder, F_INBOX, "INBOX");
2327
#if 0
2328
        if (!folder->outbox)
2329
                folder->outbox = imap_create_special_folder
2330
                        (folder, F_OUTBOX, "Sent");
2331
        if (!folder->draft)
2332
                folder->draft = imap_create_special_folder
2333
                        (folder, F_DRAFT, "Drafts");
2334
        if (!folder->queue)
2335
                folder->queue = imap_create_special_folder
2336
                        (folder, F_QUEUE, "Queue");
2337
#endif
2338
        if (!folder->trash)
2339
                folder->trash = imap_create_special_folder
2340
                        (folder, F_TRASH, "Trash");
2341
}
2342

    
2343
static FolderItem *imap_create_special_folder(Folder *folder,
2344
                                              SpecialFolderItemType stype,
2345
                                              const gchar *name)
2346
{
2347
        FolderItem *item;
2348
        FolderItem *new_item;
2349

    
2350
        g_return_val_if_fail(folder != NULL, NULL);
2351
        g_return_val_if_fail(folder->node != NULL, NULL);
2352
        g_return_val_if_fail(folder->node->data != NULL, NULL);
2353
        g_return_val_if_fail(folder->account != NULL, NULL);
2354
        g_return_val_if_fail(name != NULL, NULL);
2355

    
2356
        item = FOLDER_ITEM(folder->node->data);
2357
        new_item = imap_create_folder(folder, item, name);
2358

    
2359
        if (!new_item) {
2360
                g_warning(_("Can't create '%s'\n"), name);
2361
                if (!folder->inbox) return NULL;
2362

    
2363
                new_item = imap_create_folder(folder, folder->inbox, name);
2364
                if (!new_item)
2365
                        g_warning(_("Can't create '%s' under INBOX\n"), name);
2366
                else
2367
                        new_item->stype = stype;
2368
        } else
2369
                new_item->stype = stype;
2370

    
2371
        return new_item;
2372
}
2373

    
2374
static FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
2375
                                      const gchar *name)
2376
{
2377
        gchar *dirpath, *imap_path;
2378
        IMAPSession *session;
2379
        FolderItem *new_item;
2380
        gchar separator;
2381
        gchar *new_name;
2382
        const gchar *p;
2383
        gboolean no_sub = FALSE, no_select = FALSE;
2384
        gint ok;
2385

    
2386
        g_return_val_if_fail(folder != NULL, NULL);
2387
        g_return_val_if_fail(folder->account != NULL, NULL);
2388
        g_return_val_if_fail(parent != NULL, NULL);
2389
        g_return_val_if_fail(name != NULL, NULL);
2390

    
2391
        session = imap_session_get(folder);
2392
        if (!session) return NULL;
2393

    
2394
        if (!parent->parent && g_ascii_strcasecmp(name, "INBOX") == 0)
2395
                dirpath = g_strdup(name);
2396
        else if (parent->path)
2397
                dirpath = g_strconcat(parent->path, "/", name, NULL);
2398
        else if ((p = strchr(name, '/')) != NULL && *(p + 1) != '\0')
2399
                dirpath = g_strdup(name);
2400
        else if (folder->account->imap_dir && *folder->account->imap_dir) {
2401
                gchar *imap_dir;
2402

    
2403
                Xstrdup_a(imap_dir, folder->account->imap_dir, return NULL);
2404
                strtailchomp(imap_dir, '/');
2405
                dirpath = g_strconcat(imap_dir, "/", name, NULL);
2406
        } else
2407
                dirpath = g_strdup(name);
2408

    
2409
        /* keep trailing directory separator to create a folder that contains
2410
           sub folder */
2411
        imap_path = imap_utf8_to_modified_utf7(dirpath);
2412
        strtailchomp(dirpath, '/');
2413
        Xstrdup_a(new_name, name, {g_free(dirpath); return NULL;});
2414
        strtailchomp(new_name, '/');
2415
        separator = imap_get_path_separator(IMAP_FOLDER(folder), imap_path);
2416
        imap_path_separator_subst(imap_path, separator);
2417
        subst_char(new_name, '/', separator);
2418

    
2419
        if (g_ascii_strcasecmp(name, "INBOX") != 0) {
2420
                GPtrArray *argbuf;
2421
                gint i;
2422
                gboolean exist = FALSE;
2423

    
2424
                argbuf = g_ptr_array_new();
2425
                ok = imap_cmd_list(session, NULL, imap_path, argbuf);
2426
                if (ok != IMAP_SUCCESS) {
2427
                        log_warning(_("can't create mailbox: LIST failed\n"));
2428
                        g_free(imap_path);
2429
                        g_free(dirpath);
2430
                        g_ptr_array_free(argbuf, TRUE);
2431
                        return NULL;
2432
                }
2433

    
2434
                for (i = 0; i < argbuf->len; i++) {
2435
                        gchar *str;
2436
                        str = g_ptr_array_index(argbuf, i);
2437
                        if (!strncmp(str, "LIST ", 5)) {
2438
                                exist = TRUE;
2439
                                if (strcasestr(str + 5, "\\Noinferiors"))
2440
                                        no_sub = TRUE;
2441
                                if (strcasestr(str + 5, "\\Noselect"))
2442
                                        no_select = TRUE;
2443
                                break;
2444
                        }
2445
                }
2446

    
2447
                if (!exist) {
2448
                        ok = imap_cmd_create(session, imap_path);
2449
                        if (ok != IMAP_SUCCESS) {
2450
                                log_warning(_("can't create mailbox\n"));
2451
                                g_free(imap_path);
2452
                                g_free(dirpath);
2453
                                return NULL;
2454
                        }
2455

    
2456
                        g_ptr_array_free(argbuf, TRUE);
2457
                        argbuf = g_ptr_array_new();
2458
                        ok = imap_cmd_list(session, NULL, imap_path, argbuf);
2459
                        if (ok != IMAP_SUCCESS) {
2460
                                log_warning("LIST failed\n");
2461
                                g_free(imap_path);
2462
                                g_free(dirpath);
2463
                                g_ptr_array_free(argbuf, TRUE);
2464
                                return NULL;
2465
                        }
2466

    
2467
                        for (i = 0; i < argbuf->len; i++) {
2468
                                gchar *str;
2469
                                str = g_ptr_array_index(argbuf, i);
2470
                                if (!strncmp(str, "LIST ", 5)) {
2471
                                        if (strcasestr(str + 5, "\\Noinferiors"))
2472
                                                no_sub = TRUE;
2473
                                        if (strcasestr(str + 5, "\\Noselect"))
2474
                                                no_select = TRUE;
2475
                                        break;
2476
                                }
2477
                        }
2478
                }
2479

    
2480
                g_ptr_array_free(argbuf, TRUE);
2481
        }
2482

    
2483
        new_item = folder_item_new(new_name, dirpath);
2484
        new_item->no_sub = no_sub;
2485
        new_item->no_select = no_select;
2486
        folder_item_append(parent, new_item);
2487
        g_free(imap_path);
2488
        g_free(dirpath);
2489

    
2490
        dirpath = folder_item_get_path(new_item);
2491
        if (!is_dir_exist(dirpath))
2492
                make_dir_hier(dirpath);
2493
        g_free(dirpath);
2494

    
2495
        return new_item;
2496
}
2497

    
2498
static gint imap_rename_folder_real(Folder *folder, FolderItem *item,
2499
                                    FolderItem *new_parent, const gchar *name)
2500
{
2501
        gchar *newpath;
2502
        gchar *real_oldpath;
2503
        gchar *real_newpath;
2504
        gchar *paths[2];
2505
        gchar *old_cache_dir;
2506
        gchar *new_cache_dir;
2507
        IMAPSession *session;
2508
        gchar separator;
2509
        gint ok;
2510
        gint exists, recent, unseen;
2511
        guint32 uid_validity;
2512
        gchar *old_id, *new_id;
2513

    
2514
        g_return_val_if_fail(folder != NULL, -1);
2515
        g_return_val_if_fail(item != NULL, -1);
2516
        g_return_val_if_fail(folder == item->folder, -1);
2517
        g_return_val_if_fail(item->path != NULL, -1);
2518
        g_return_val_if_fail(new_parent != NULL || name != NULL, -1);
2519
        if (new_parent) {
2520
                g_return_val_if_fail(item != new_parent, -1);
2521
                g_return_val_if_fail(item->parent != new_parent, -1);
2522
                g_return_val_if_fail(item->folder == new_parent->folder, -1);
2523
                if (g_node_is_ancestor(item->node, new_parent->node)) {
2524
                        g_warning("folder to be moved is ancestor of new parent\n");
2525
                        return -1;
2526
                }
2527
        }
2528

    
2529
        session = imap_session_get(folder);
2530
        if (!session) return -1;
2531

    
2532
        real_oldpath = imap_get_real_path(IMAP_FOLDER(folder), item->path);
2533

    
2534
        g_free(session->mbox);
2535
        session->mbox = NULL;
2536
        ok = imap_cmd_examine(session, "INBOX",
2537
                              &exists, &recent, &unseen, &uid_validity);
2538
        if (ok != IMAP_SUCCESS) {
2539
                g_free(real_oldpath);
2540
                return -1;
2541
        }
2542

    
2543
        separator = imap_get_path_separator(IMAP_FOLDER(folder), item->path);
2544
        if (new_parent) {
2545
                if (name) {
2546
                        if (new_parent->path)
2547
                                newpath = g_strconcat(new_parent->path,
2548
                                                      "/", name, NULL);
2549
                        else
2550
                                newpath = g_strdup(name);
2551
                } else {
2552
                        gchar *name_;
2553

    
2554
                        name_ = g_path_get_basename(item->path);
2555
                        if (new_parent->path)
2556
                                newpath = g_strconcat(new_parent->path,
2557
                                                      "/", name_, NULL);
2558
                        else
2559
                                newpath = g_strdup(name_);
2560
                        AUTORELEASE_STR(name_, );
2561
                        name = name_;
2562
                }
2563
        } else {
2564
                if (strchr(item->path, '/')) {
2565
                        gchar *dirpath;
2566

    
2567
                        dirpath = g_dirname(item->path);
2568
                        newpath = g_strconcat(dirpath, "/", name, NULL);
2569
                        g_free(dirpath);
2570
                } else
2571
                        newpath = g_strdup(name);
2572
        }
2573

    
2574
        real_newpath = imap_utf8_to_modified_utf7(newpath);
2575
        imap_path_separator_subst(real_newpath, separator);
2576

    
2577
        ok = imap_cmd_rename(session, real_oldpath, real_newpath);
2578
        if (ok != IMAP_SUCCESS) {
2579
                log_warning(_("can't rename mailbox: %s to %s\n"),
2580
                            real_oldpath, real_newpath);
2581
                g_free(real_oldpath);
2582
                g_free(newpath);
2583
                g_free(real_newpath);
2584
                return -1;
2585
        }
2586

    
2587
        old_id = folder_item_get_identifier(item);
2588

    
2589
        if (new_parent) {
2590
                g_node_unlink(item->node);
2591
                g_node_append(new_parent->node, item->node);
2592
                item->parent = new_parent;
2593
        }
2594

    
2595
        g_free(item->name);
2596
        item->name = g_strdup(name);
2597

    
2598
        old_cache_dir = folder_item_get_path(item);
2599

    
2600
        paths[0] = g_strdup(item->path);
2601
        paths[1] = newpath;
2602
        g_node_traverse(item->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1,
2603
                        imap_rename_folder_func, paths);
2604

    
2605
        if (is_dir_exist(old_cache_dir)) {
2606
                new_cache_dir = folder_item_get_path(item);
2607
                if (g_rename(old_cache_dir, new_cache_dir) < 0) {
2608
                        FILE_OP_ERROR(old_cache_dir, "rename");
2609
                }
2610
                g_free(new_cache_dir);
2611
        }
2612

    
2613
        g_free(old_cache_dir);
2614
        g_free(paths[0]);
2615
        g_free(newpath);
2616
        g_free(real_oldpath);
2617
        g_free(real_newpath);
2618

    
2619
        new_id = folder_item_get_identifier(item);
2620
        if (syl_app_get())
2621
                g_signal_emit_by_name(syl_app_get(), "move-folder", item,
2622
                                      old_id, new_id);
2623
        g_free(new_id);
2624
        g_free(old_id);
2625

    
2626
        return 0;
2627
}
2628

    
2629
static gint imap_rename_folder(Folder *folder, FolderItem *item,
2630
                               const gchar *name)
2631
{
2632
        return imap_rename_folder_real(folder, item, NULL, name);
2633
}
2634

    
2635
static gint imap_move_folder(Folder *folder, FolderItem *item,
2636
                             FolderItem *new_parent)
2637
{
2638
        return imap_rename_folder_real(folder, item, new_parent, NULL);
2639
}
2640

    
2641
static gint imap_remove_folder(Folder *folder, FolderItem *item)
2642
{
2643
        gint ok;
2644
        IMAPSession *session;
2645
        gchar *path;
2646
        gchar *cache_dir;
2647
        gint exists, recent, unseen;
2648
        guint32 uid_validity;
2649

    
2650
        g_return_val_if_fail(folder != NULL, -1);
2651
        g_return_val_if_fail(item != NULL, -1);
2652
        g_return_val_if_fail(item->path != NULL, -1);
2653

    
2654
        session = imap_session_get(folder);
2655
        if (!session) return -1;
2656

    
2657
        path = imap_get_real_path(IMAP_FOLDER(folder), item->path);
2658

    
2659
        ok = imap_cmd_examine(session, "INBOX",
2660
                              &exists, &recent, &unseen, &uid_validity);
2661
        if (ok != IMAP_SUCCESS) {
2662
                g_free(path);
2663
                return -1;
2664
        }
2665

    
2666
        ok = imap_cmd_delete(session, path);
2667
        if (ok != IMAP_SUCCESS) {
2668
                log_warning(_("can't delete mailbox\n"));
2669
                g_free(path);
2670
                return -1;
2671
        }
2672

    
2673
        g_free(path);
2674
        cache_dir = folder_item_get_path(item);
2675
        if (is_dir_exist(cache_dir) && remove_dir_recursive(cache_dir) < 0)
2676
                g_warning("can't remove directory '%s'\n", cache_dir);
2677
        g_free(cache_dir);
2678

    
2679
        if (syl_app_get())
2680
                g_signal_emit_by_name(syl_app_get(), "remove-folder", item);
2681
        folder_item_remove(item);
2682

    
2683
        return 0;
2684
}
2685

    
2686
typedef struct _IMAPGetData
2687
{
2688
        FolderItem *item;
2689
        gint exists;
2690
        gboolean update_count;
2691
        GSList *newlist;
2692
} IMAPGetData;
2693

    
2694
static gint imap_get_uncached_messages_progress_func(IMAPSession *session,
2695
                                                     gint count, gint total,
2696
                                                     gpointer data)
2697
{
2698
        status_print(_("Getting message headers (%d / %d)"), count, total);
2699
        progress_show(count, total);
2700
#ifndef USE_THREADS
2701
        ui_update();
2702
#endif
2703
        return 0;
2704
}
2705

    
2706
static gint imap_get_uncached_messages_func(IMAPSession *session, gpointer data)
2707
{
2708
        gchar *tmp;
2709
        GSList *newlist = NULL;
2710
        GSList *llast = NULL;
2711
        GString *str;
2712
        MsgInfo *msginfo;
2713
        gint count = 1;
2714
        GTimeVal tv_prev, tv_cur;
2715
        IMAPGetData *get_data = (IMAPGetData *)data;
2716
        FolderItem *item = get_data->item;
2717
        gint exists = get_data->exists;
2718
        gboolean update_count = get_data->update_count;
2719

    
2720
        g_get_current_time(&tv_prev);
2721
#ifndef USE_THREADS
2722
        ui_update();
2723
#endif
2724

    
2725
#if USE_THREADS
2726
        ((IMAPRealSession *)session)->prog_total = exists;
2727
#endif
2728

    
2729
        str = g_string_new(NULL);
2730

    
2731
        for (;;) {
2732
                if (exists > 0 && count <= exists) {
2733
                        g_get_current_time(&tv_cur);
2734
                        if (tv_cur.tv_sec > tv_prev.tv_sec ||
2735
                            tv_cur.tv_usec - tv_prev.tv_usec >
2736
                            PROGRESS_UPDATE_INTERVAL * 1000) {
2737
#if USE_THREADS
2738
                                ((IMAPRealSession *)session)->prog_count = count;
2739
                                g_main_context_wakeup(NULL);
2740
#else
2741
                                imap_get_uncached_messages_progress_func
2742
                                        (session, count, exists, data);
2743
#endif
2744
                                tv_prev = tv_cur;
2745
                        }
2746
                }
2747
                ++count;
2748

    
2749
                if (sock_getline(SESSION(session)->sock, &tmp) < 0) {
2750
                        log_warning(_("error occurred while getting envelope.\n"));
2751
                        g_string_free(str, TRUE);
2752
                        return IMAP_SOCKET;
2753
                }
2754
                strretchomp(tmp);
2755
                if (tmp[0] != '*' || tmp[1] != ' ') {
2756
                        log_print("IMAP4< %s\n", tmp);
2757
                        g_free(tmp);
2758
                        break;
2759
                }
2760
                if (strstr(tmp, "FETCH") == NULL) {
2761
                        log_print("IMAP4< %s\n", tmp);
2762
                        g_free(tmp);
2763
                        continue;
2764
                }
2765
                log_print("IMAP4< %s\n", tmp);
2766
                g_string_assign(str, tmp);
2767
                g_free(tmp);
2768

    
2769
                msginfo = imap_parse_envelope(session, item, str);
2770
                if (!msginfo) {
2771
                        log_warning(_("can't parse envelope: %s\n"), str->str);
2772
                        continue;
2773
                }
2774
                if (update_count) {
2775
                        if (MSG_IS_NEW(msginfo->flags))
2776
                                item->new++;
2777
                        if (MSG_IS_UNREAD(msginfo->flags))
2778
                                item->unread++;
2779
                }
2780
                if (item->stype == F_QUEUE) {
2781
                        MSG_SET_TMP_FLAGS(msginfo->flags, MSG_QUEUED);
2782
                } else if (item->stype == F_DRAFT) {
2783
                        MSG_SET_TMP_FLAGS(msginfo->flags, MSG_DRAFT);
2784
                }
2785

    
2786
                msginfo->folder = item;
2787

    
2788
                if (!newlist)
2789
                        llast = newlist = g_slist_append(newlist, msginfo);
2790
                else {
2791
                        llast = g_slist_append(llast, msginfo);
2792
                        llast = llast->next;
2793
                }
2794

    
2795
                if (update_count)
2796
                        item->total++;
2797
        }
2798

    
2799
        g_string_free(str, TRUE);
2800

    
2801
        session_set_access_time(SESSION(session));
2802

    
2803
        get_data->newlist = newlist;
2804
        return IMAP_SUCCESS;
2805
}
2806

    
2807
static GSList *imap_get_uncached_messages(IMAPSession *session,
2808
                                          FolderItem *item,
2809
                                          guint32 first_uid, guint32 last_uid,
2810
                                          gint exists, gboolean update_count)
2811
{
2812
        IMAPGetData get_data = {item, exists, update_count, NULL};
2813
        gchar seq_set[22];
2814
        gint ok;
2815

    
2816
        g_return_val_if_fail(session != NULL, NULL);
2817
        g_return_val_if_fail(item != NULL, NULL);
2818
        g_return_val_if_fail(item->folder != NULL, NULL);
2819
        g_return_val_if_fail(FOLDER_TYPE(item->folder) == F_IMAP, NULL);
2820
        g_return_val_if_fail(first_uid <= last_uid, NULL);
2821

    
2822
        if (first_uid == 0 && last_uid == 0)
2823
                strcpy(seq_set, "1:*");
2824
        else
2825
                g_snprintf(seq_set, sizeof(seq_set), "%u:%u",
2826
                           first_uid, last_uid);
2827
        if (imap_cmd_envelope(session, seq_set) != IMAP_SUCCESS) {
2828
                log_warning(_("can't get envelope\n"));
2829
                return NULL;
2830
        }
2831

    
2832
#if USE_THREADS
2833
        ok = imap_thread_run_progress(session, imap_get_uncached_messages_func,
2834
                                      imap_get_uncached_messages_progress_func,
2835
                                      &get_data);
2836
#else
2837
        ok = imap_get_uncached_messages_func(session, &get_data);
2838
#endif
2839

    
2840
        progress_show(0, 0);
2841
        return get_data.newlist;
2842
}
2843

    
2844
static void imap_delete_cached_message(FolderItem *item, guint32 uid)
2845
{
2846
        gchar *dir;
2847
        gchar *file;
2848

    
2849
        g_return_if_fail(item != NULL);
2850
        g_return_if_fail(item->folder != NULL);
2851
        g_return_if_fail(FOLDER_TYPE(item->folder) == F_IMAP);
2852

    
2853
        dir = folder_item_get_path(item);
2854
        file = g_strdup_printf("%s%c%u", dir, G_DIR_SEPARATOR, uid);
2855

    
2856
        debug_print("Deleting cached message: %s\n", file);
2857

    
2858
        g_unlink(file);
2859

    
2860
        g_free(file);
2861
        g_free(dir);
2862
}
2863

    
2864
static GSList *imap_delete_cached_messages(GSList *mlist, FolderItem *item,
2865
                                           guint32 first_uid, guint32 last_uid)
2866
{
2867
        GSList *cur, *next;
2868
        MsgInfo *msginfo;
2869
        gchar *dir;
2870

    
2871
        g_return_val_if_fail(item != NULL, mlist);
2872
        g_return_val_if_fail(item->folder != NULL, mlist);
2873
        g_return_val_if_fail(FOLDER_TYPE(item->folder) == F_IMAP, mlist);
2874

    
2875
        if (first_uid == 0 && last_uid == 0)
2876
                return mlist;
2877

    
2878
        debug_print("Deleting cached messages %u - %u ... ",
2879
                    first_uid, last_uid);
2880

    
2881
        dir = folder_item_get_path(item);
2882
        if (is_dir_exist(dir))
2883
                remove_numbered_files(dir, first_uid, last_uid);
2884
        g_free(dir);
2885

    
2886
        for (cur = mlist; cur != NULL; ) {
2887
                next = cur->next;
2888

    
2889
                msginfo = (MsgInfo *)cur->data;
2890
                if (msginfo != NULL && first_uid <= msginfo->msgnum &&
2891
                    msginfo->msgnum <= last_uid) {
2892
                        procmsg_msginfo_free(msginfo);
2893
                        mlist = g_slist_remove(mlist, msginfo);
2894
                }
2895

    
2896
                cur = next;
2897
        }
2898

    
2899
        debug_print("done.\n");
2900

    
2901
        return mlist;
2902
}
2903

    
2904
static void imap_delete_all_cached_messages(FolderItem *item)
2905
{
2906
        gchar *dir;
2907

    
2908
        g_return_if_fail(item != NULL);
2909
        g_return_if_fail(item->folder != NULL);
2910
        g_return_if_fail(FOLDER_TYPE(item->folder) == F_IMAP);
2911

    
2912
        debug_print("Deleting all cached messages... ");
2913

    
2914
        dir = folder_item_get_path(item);
2915
        if (is_dir_exist(dir))
2916
                remove_all_numbered_files(dir);
2917
        g_free(dir);
2918

    
2919
        debug_print("done.\n");
2920
}
2921

    
2922
#if USE_SSL
2923
static SockInfo *imap_open(const gchar *server, gushort port,
2924
                           SocksInfo *socks_info, SSLType ssl_type)
2925
#else
2926
static SockInfo *imap_open(const gchar *server, gushort port,
2927
                           SocksInfo *socks_info)
2928
#endif
2929
{
2930
        SockInfo *sock = NULL;
2931
        const gchar *server_;
2932
        gushort port_;
2933
#if USE_THREADS
2934
        gint conn_id;
2935
#endif
2936

    
2937
        if (socks_info) {
2938
                server_ = socks_info->proxy_host;
2939
                port_ = socks_info->proxy_port;
2940
        } else {
2941
                server_ = server;
2942
                port_ = port;
2943
        }
2944

    
2945
#if USE_THREADS
2946
        if ((conn_id = sock_connect_async_thread(server_, port_)) < 0 ||
2947
            sock_connect_async_thread_wait(conn_id, &sock) < 0) {
2948
                log_warning(_("Can't connect to IMAP4 server: %s:%d\n"),
2949
                            server, port);
2950
                return NULL;
2951
        }
2952
#else
2953
        if ((sock = sock_connect(server_, port_)) == NULL) {
2954
                log_warning(_("Can't connect to IMAP4 server: %s:%d\n"),
2955
                            server, port);
2956
                return NULL;
2957
        }
2958
#endif
2959

    
2960
        if (socks_info) {
2961
                if (socks_connect(sock, server, port, socks_info) < 0) {
2962
                        log_warning("Can't establish SOCKS connection: %s:%d\n",
2963
                                    server, port);
2964
                        sock_close(sock);
2965
                        return NULL;
2966
                }
2967
        }
2968

    
2969
#if USE_SSL
2970
        if (ssl_type == SSL_TUNNEL && !ssl_init_socket(sock)) {
2971
                log_warning(_("Can't establish IMAP4 session with: %s:%d\n"),
2972
                            server, port);
2973
                sock_close(sock);
2974
                return NULL;
2975
        }
2976
#endif
2977

    
2978
        return sock;
2979
}
2980

    
2981
static GList *imap_parse_namespace_str(gchar *str)
2982
{
2983
        gchar *p = str;
2984
        gchar *name;
2985
        gchar *separator;
2986
        IMAPNameSpace *namespace;
2987
        GList *ns_list = NULL;
2988

    
2989
        while (*p != '\0') {
2990
                /* parse ("#foo" "/") */
2991

    
2992
                while (*p && *p != '(') p++;
2993
                if (*p == '\0') break;
2994
                p++;
2995

    
2996
                while (*p && *p != '"') p++;
2997
                if (*p == '\0') break;
2998
                p++;
2999
                name = p;
3000

    
3001
                while (*p && *p != '"') p++;
3002
                if (*p == '\0') break;
3003
                *p = '\0';
3004
                p++;
3005

    
3006
                while (*p && g_ascii_isspace(*p)) p++;
3007
                if (*p == '\0') break;
3008
                if (strncmp(p, "NIL", 3) == 0)
3009
                        separator = NULL;
3010
                else if (*p == '"') {
3011
                        p++;
3012
                        separator = p;
3013
                        while (*p && *p != '"') p++;
3014
                        if (*p == '\0') break;
3015
                        *p = '\0';
3016
                        p++;
3017
                } else break;
3018

    
3019
                while (*p && *p != ')') p++;
3020
                if (*p == '\0') break;
3021
                p++;
3022

    
3023
                namespace = g_new(IMAPNameSpace, 1);
3024
                namespace->name = g_strdup(name);
3025
                namespace->separator = separator ? separator[0] : '\0';
3026
                ns_list = g_list_append(ns_list, namespace);
3027
        }
3028

    
3029
        return ns_list;
3030
}
3031

    
3032
static void imap_parse_namespace(IMAPSession *session, IMAPFolder *folder)
3033
{
3034
        gchar *ns_str = NULL;
3035
        gchar **str_array;
3036

    
3037
        g_return_if_fail(session != NULL);
3038
        g_return_if_fail(folder != NULL);
3039

    
3040
        if (folder->ns_personal != NULL ||
3041
            folder->ns_others   != NULL ||
3042
            folder->ns_shared   != NULL)
3043
                return;
3044

    
3045
        if (imap_cmd_namespace(session, &ns_str) != IMAP_SUCCESS) {
3046
                log_warning(_("can't get namespace\n"));
3047
                imap_get_namespace_by_list(session, folder);
3048
                return;
3049
        }
3050

    
3051
        str_array = strsplit_parenthesis(ns_str, '(', ')', 3);
3052
        if (str_array[0])
3053
                folder->ns_personal = imap_parse_namespace_str(str_array[0]);
3054
        if (str_array[0] && str_array[1])
3055
                folder->ns_others = imap_parse_namespace_str(str_array[1]);
3056
        if (str_array[0] && str_array[1] && str_array[2])
3057
                folder->ns_shared = imap_parse_namespace_str(str_array[2]);
3058
        g_strfreev(str_array);
3059
        g_free(ns_str);
3060
}
3061

    
3062
static void imap_get_namespace_by_list(IMAPSession *session, IMAPFolder *folder)
3063
{
3064
        GSList *item_list, *cur;
3065
        gchar separator = '\0';
3066
        IMAPNameSpace *namespace;
3067

    
3068
        g_return_if_fail(session != NULL);
3069
        g_return_if_fail(folder != NULL);
3070

    
3071
        if (folder->ns_personal != NULL ||
3072
            folder->ns_others   != NULL ||
3073
            folder->ns_shared   != NULL)
3074
                return;
3075

    
3076
        if (imap_cmd_gen_send(session, "LIST \"\" \"\"") != IMAP_SUCCESS)
3077
                return;
3078
        item_list = imap_parse_list(session, "", &separator);
3079
        for (cur = item_list; cur != NULL; cur = cur->next)
3080
                folder_item_destroy(FOLDER_ITEM(cur->data));
3081
        g_slist_free(item_list);
3082

    
3083
        namespace = g_new(IMAPNameSpace, 1);
3084
        namespace->name = g_strdup("");
3085
        namespace->separator = separator;
3086
        folder->ns_personal = g_list_append(NULL, namespace);
3087
}
3088

    
3089
static IMAPNameSpace *imap_find_namespace_from_list(GList *ns_list,
3090
                                                    const gchar *path)
3091
{
3092
        IMAPNameSpace *namespace = NULL;
3093
        gchar *tmp_path, *name;
3094

    
3095
        if (!path) path = "";
3096

    
3097
        for (; ns_list != NULL; ns_list = ns_list->next) {
3098
                IMAPNameSpace *tmp_ns = ns_list->data;
3099

    
3100
                Xstrcat_a(tmp_path, path, "/", return namespace);
3101
                Xstrdup_a(name, tmp_ns->name, return namespace);
3102
                if (tmp_ns->separator && tmp_ns->separator != '/') {
3103
                        subst_char(tmp_path, tmp_ns->separator, '/');
3104
                        subst_char(name, tmp_ns->separator, '/');
3105
                }
3106
                if (strncmp(tmp_path, name, strlen(name)) == 0)
3107
                        namespace = tmp_ns;
3108
        }
3109

    
3110
        return namespace;
3111
}
3112

    
3113
static IMAPNameSpace *imap_find_namespace(IMAPFolder *folder,
3114
                                          const gchar *path)
3115
{
3116
        IMAPNameSpace *namespace;
3117

    
3118
        g_return_val_if_fail(folder != NULL, NULL);
3119

    
3120
        namespace = imap_find_namespace_from_list(folder->ns_personal, path);
3121
        if (namespace) return namespace;
3122
        namespace = imap_find_namespace_from_list(folder->ns_others, path);
3123
        if (namespace) return namespace;
3124
        namespace = imap_find_namespace_from_list(folder->ns_shared, path);
3125
        if (namespace) return namespace;
3126

    
3127
        return NULL;
3128
}
3129

    
3130
static gchar imap_get_path_separator(IMAPFolder *folder, const gchar *path)
3131
{
3132
        IMAPNameSpace *namespace;
3133
        gchar separator = '/';
3134

    
3135
        namespace = imap_find_namespace(folder, path);
3136
        if (namespace && namespace->separator)
3137
                separator = namespace->separator;
3138

    
3139
        return separator;
3140
}
3141

    
3142
static gchar *imap_get_real_path(IMAPFolder *folder, const gchar *path)
3143
{
3144
        gchar *real_path;
3145
        gchar separator;
3146

    
3147
        g_return_val_if_fail(folder != NULL, NULL);
3148
        g_return_val_if_fail(path != NULL, NULL);
3149

    
3150
        real_path = imap_utf8_to_modified_utf7(path);
3151
        separator = imap_get_path_separator(folder, path);
3152
        imap_path_separator_subst(real_path, separator);
3153

    
3154
        return real_path;
3155
}
3156

    
3157
static gchar *imap_parse_atom(IMAPSession *session, gchar *src,
3158
                              gchar *dest, gint dest_len, GString *str)
3159
{
3160
        gchar *cur_pos = src;
3161
        gchar *nextline;
3162

    
3163
        g_return_val_if_fail(str != NULL, cur_pos);
3164

    
3165
        /* read the next line if the current response buffer is empty */
3166
        while (g_ascii_isspace(*cur_pos)) cur_pos++;
3167
        while (*cur_pos == '\0') {
3168
                if (sock_getline(SESSION(session)->sock, &nextline) < 0)
3169
                        return cur_pos;
3170
                g_string_assign(str, nextline);
3171
                cur_pos = str->str;
3172
                strretchomp(nextline);
3173
                /* log_print("IMAP4< %s\n", nextline); */
3174
                debug_print("IMAP4< %s\n", nextline);
3175
                g_free(nextline);
3176

    
3177
                while (g_ascii_isspace(*cur_pos)) cur_pos++;
3178
        }
3179

    
3180
        if (*cur_pos == '~' && *(cur_pos + 1) == '{')
3181
                cur_pos++;
3182

    
3183
        if (!strncmp(cur_pos, "NIL", 3)) {
3184
                *dest = '\0';
3185
                cur_pos += 3;
3186
        } else if (*cur_pos == '\"') {
3187
                gchar *p;
3188

    
3189
                p = get_quoted(cur_pos, '\"', dest, dest_len);
3190
                cur_pos = p ? p : cur_pos + 2;
3191
        } else if (*cur_pos == '{') {
3192
                gchar buf[32];
3193
                gint len;
3194
                gint block_len = 0;
3195

    
3196
                cur_pos = strchr_cpy(cur_pos + 1, '}', buf, sizeof(buf));
3197
                len = atoi(buf);
3198
                g_return_val_if_fail(len >= 0, cur_pos);
3199

    
3200
                g_string_truncate(str, 0);
3201
                cur_pos = str->str;
3202

    
3203
                do {
3204
                        gint cur_len;
3205

    
3206
                        cur_len = sock_getline(SESSION(session)->sock,
3207
                                               &nextline);
3208
                        if (cur_len < 0)
3209
                                return cur_pos;
3210
                        block_len += cur_len;
3211
                        subst_null(nextline, cur_len, ' ');
3212
                        g_string_append(str, nextline);
3213
                        cur_pos = str->str;
3214
                        strretchomp(nextline);
3215
                        /* log_print("IMAP4< %s\n", nextline); */
3216
                        debug_print("IMAP4< %s\n", nextline);
3217
                        g_free(nextline);
3218
                } while (block_len < len);
3219

    
3220
                memcpy(dest, cur_pos, MIN(len, dest_len - 1));
3221
                dest[MIN(len, dest_len - 1)] = '\0';
3222
                cur_pos += len;
3223
        }
3224

    
3225
        return cur_pos;
3226
}
3227

    
3228
static gchar *imap_get_header(IMAPSession *session, gchar *cur_pos,
3229
                              gchar **headers, GString *str)
3230
{
3231
        gchar *nextline;
3232
        gchar buf[IMAPBUFSIZE];
3233
        gint len;
3234
        gint block_len = 0;
3235

    
3236
        *headers = NULL;
3237

    
3238
        g_return_val_if_fail(str != NULL, cur_pos);
3239

    
3240
        while (g_ascii_isspace(*cur_pos)) cur_pos++;
3241
        if (*cur_pos == '~' && *(cur_pos + 1) == '{')
3242
                cur_pos++;
3243

    
3244
        if (*cur_pos == '"') {
3245
                cur_pos = strchr_cpy(cur_pos + 1, '"', buf, sizeof(buf));
3246
                if (!cur_pos)
3247
                        return NULL;
3248
                len = strlen(buf);
3249
                *headers = g_strdup(buf);
3250
                while (g_ascii_isspace(*cur_pos)) cur_pos++;
3251
                return cur_pos;
3252
        }
3253

    
3254
        g_return_val_if_fail(*cur_pos == '{', cur_pos);
3255

    
3256
        cur_pos = strchr_cpy(cur_pos + 1, '}', buf, sizeof(buf));
3257
        len = atoi(buf);
3258
        g_return_val_if_fail(len >= 0, cur_pos);
3259

    
3260
        g_string_truncate(str, 0);
3261
        cur_pos = str->str;
3262

    
3263
        do {
3264
                gint cur_len;
3265

    
3266
                cur_len = sock_getline(SESSION(session)->sock, &nextline);
3267
                if (cur_len < 0)
3268
                        return cur_pos;
3269
                block_len += cur_len;
3270
                subst_null(nextline, cur_len, ' ');
3271
                g_string_append(str, nextline);
3272
                cur_pos = str->str;
3273
                /* strretchomp(nextline); */
3274
                /* debug_print("IMAP4< %s\n", nextline); */
3275
                g_free(nextline);
3276
        } while (block_len < len);
3277

    
3278
        debug_print("IMAP4< [contents of RFC822.HEADER]\n");
3279

    
3280
        *headers = g_strndup(cur_pos, len);
3281
        cur_pos += len;
3282

    
3283
        while (g_ascii_isspace(*cur_pos)) cur_pos++;
3284
        while (*cur_pos == '\0') {
3285
                if (sock_getline(SESSION(session)->sock, &nextline) < 0)
3286
                        return cur_pos;
3287
                g_string_assign(str, nextline);
3288
                cur_pos = str->str;
3289
                strretchomp(nextline);
3290
                debug_print("IMAP4< %s\n", nextline);
3291
                g_free(nextline);
3292

    
3293
                while (g_ascii_isspace(*cur_pos)) cur_pos++;
3294
        }
3295

    
3296
        return cur_pos;
3297
}
3298

    
3299
static MsgFlags imap_parse_flags(const gchar *flag_str)  
3300
{
3301
        const gchar *p = flag_str;
3302
        MsgFlags flags = {0, 0};
3303

    
3304
        flags.perm_flags = MSG_UNREAD;
3305

    
3306
        while (*p != '\0') {
3307
                if (g_ascii_strncasecmp(p, "\\Recent", 7) == 0 &&
3308
                    MSG_IS_UNREAD(flags)) {
3309
                        MSG_SET_PERM_FLAGS(flags, MSG_NEW);
3310
                } else if (g_ascii_strncasecmp(p, "\\Seen", 5) == 0) {
3311
                        MSG_UNSET_PERM_FLAGS(flags, MSG_NEW|MSG_UNREAD);
3312
                } else if (g_ascii_strncasecmp(p, "\\Deleted", 8) == 0) {
3313
                        MSG_SET_PERM_FLAGS(flags, MSG_DELETED);
3314
                } else if (g_ascii_strncasecmp(p, "\\Flagged", 8) == 0) {
3315
                        MSG_SET_PERM_FLAGS(flags, MSG_MARKED);
3316
                } else if (g_ascii_strncasecmp(p, "\\Answered", 9) == 0) {
3317
                        MSG_SET_PERM_FLAGS(flags, MSG_REPLIED);
3318
                } else if (g_ascii_strncasecmp(p, "$label", 6) == 0) {
3319
                        /* color labels */
3320
                        if (*(p + 6) >= '1' && *(p + 6) <= '7') {
3321
                                guint color = *(p + 6) - '1' + 1;
3322
                                MSG_UNSET_PERM_FLAGS(flags,
3323
                                                     MSG_CLABEL_FLAG_MASK);
3324
                                MSG_SET_COLORLABEL_VALUE(flags, color);
3325
                        }
3326
                }
3327

    
3328
                while (*p && !g_ascii_isspace(*p)) p++;
3329
                while (g_ascii_isspace(*p)) p++;
3330
        }
3331

    
3332
        return flags;
3333
}
3334

    
3335
static IMAPFlags imap_parse_imap_flags(const gchar *flag_str)  
3336
{
3337
        const gchar *p = flag_str;
3338
        IMAPFlags flags = 0;
3339

    
3340
        while (*p != '\0') {
3341
                if (g_ascii_strncasecmp(p, "\\Seen", 5) == 0) {
3342
                        flags |= IMAP_FLAG_SEEN;
3343
                } else if (g_ascii_strncasecmp(p, "\\Deleted", 8) == 0) {
3344
                        flags |= IMAP_FLAG_DELETED;
3345
                } else if (g_ascii_strncasecmp(p, "\\Flagged", 8) == 0) {
3346
                        flags |= IMAP_FLAG_FLAGGED;
3347
                } else if (g_ascii_strncasecmp(p, "\\Answered", 9) == 0) {
3348
                        flags |= IMAP_FLAG_ANSWERED;
3349
                } else if (g_ascii_strncasecmp(p, "$label", 6) == 0) {
3350
                        /* color labels */
3351
                        if (*(p + 6) >= '1' && *(p + 6) <= '7') {
3352
                                guint color = *(p + 6) - '1' + 1;
3353
                                MSG_UNSET_FLAGS(flags, MSG_CLABEL_FLAG_MASK);
3354
                                IMAP_SET_COLORLABEL_VALUE(flags, color);
3355
                        }
3356
                }
3357

    
3358
                while (*p && !g_ascii_isspace(*p)) p++;
3359
                while (g_ascii_isspace(*p)) p++;
3360
        }
3361

    
3362
        return flags;
3363
}
3364

    
3365
static MsgInfo *imap_parse_envelope(IMAPSession *session, FolderItem *item,
3366
                                    GString *line_str)
3367
{
3368
        gchar buf[IMAPBUFSIZE];
3369
        MsgInfo *msginfo = NULL;
3370
        gchar *cur_pos;
3371
        gint msgnum;
3372
        guint32 uid = 0;
3373
        size_t size = 0;
3374
        MsgFlags flags = {0, 0}, imap_flags = {0, 0};
3375

    
3376
        g_return_val_if_fail(line_str != NULL, NULL);
3377
        g_return_val_if_fail(line_str->str[0] == '*' &&
3378
                             line_str->str[1] == ' ', NULL);
3379

    
3380
        MSG_SET_TMP_FLAGS(flags, MSG_IMAP);
3381
        if (item->stype == F_QUEUE) {
3382
                MSG_SET_TMP_FLAGS(flags, MSG_QUEUED);
3383
        } else if (item->stype == F_DRAFT) {
3384
                MSG_SET_TMP_FLAGS(flags, MSG_DRAFT);
3385
        }
3386

    
3387
        cur_pos = line_str->str + 2;
3388

    
3389
#define PARSE_ONE_ELEMENT(ch)                                        \
3390
{                                                                \
3391
        cur_pos = strchr_cpy(cur_pos, ch, buf, sizeof(buf));        \
3392
        if (cur_pos == NULL) {                                        \
3393
                g_warning("cur_pos == NULL\n");                        \
3394
                procmsg_msginfo_free(msginfo);                        \
3395
                return NULL;                                        \
3396
        }                                                        \
3397
}
3398

    
3399
        PARSE_ONE_ELEMENT(' ');
3400
        msgnum = atoi(buf);
3401

    
3402
        PARSE_ONE_ELEMENT(' ');
3403
        g_return_val_if_fail(!strcmp(buf, "FETCH"), NULL);
3404

    
3405
        g_return_val_if_fail(*cur_pos == '(', NULL);
3406
        cur_pos++;
3407

    
3408
        while (*cur_pos != '\0' && *cur_pos != ')') {
3409
                while (*cur_pos == ' ') cur_pos++;
3410

    
3411
                if (!strncmp(cur_pos, "UID ", 4)) {
3412
                        cur_pos += 4;
3413
                        uid = strtoul(cur_pos, &cur_pos, 10);
3414
                } else if (!strncmp(cur_pos, "FLAGS ", 6)) {
3415
                        cur_pos += 6;
3416
                        if (*cur_pos != '(') {
3417
                                g_warning("FLAGS: *cur_pos != '('\n");
3418
                                procmsg_msginfo_free(msginfo);
3419
                                return NULL;
3420
                        }
3421
                        cur_pos++;
3422
                        PARSE_ONE_ELEMENT(')');
3423
                        imap_flags = imap_parse_flags(buf);
3424
                } else if (!strncmp(cur_pos, "RFC822.SIZE ", 12)) {
3425
                        cur_pos += 12;
3426
                        size = strtol(cur_pos, &cur_pos, 10);
3427
                } else if (!strncmp(cur_pos, "RFC822.HEADER", 13)) {
3428
                        gchar *headers;
3429

    
3430
                        cur_pos += 13;
3431
                        cur_pos = imap_get_header(session, cur_pos, &headers,
3432
                                                  line_str);
3433
                        if (cur_pos == NULL) {
3434
                                g_warning("RFC822.HEADER: cur_pos == NULL\n");
3435
                                procmsg_msginfo_free(msginfo);
3436
                                return NULL;
3437
                        }
3438
                        if (!msginfo)
3439
                                msginfo = procheader_parse_str(headers, flags, FALSE);
3440
                        g_free(headers);
3441
                } else {
3442
                        g_warning("invalid FETCH response: %s\n", cur_pos);
3443
                        break;
3444
                }
3445
        }
3446

    
3447
#undef PARSE_ONE_ELEMENT
3448

    
3449
        if (msginfo) {
3450
                msginfo->msgnum = uid;
3451
                msginfo->size = size;
3452
                msginfo->flags.tmp_flags |= imap_flags.tmp_flags;
3453
                msginfo->flags.perm_flags = imap_flags.perm_flags;
3454
        }
3455

    
3456
        return msginfo;
3457
}
3458

    
3459
static gint imap_msg_list_change_perm_flags(GSList *msglist, MsgPermFlags flags,
3460
                                            gboolean is_set)
3461
{
3462
        Folder *folder;
3463
        IMAPSession *session;
3464
        IMAPFlags iflags = 0;
3465
        MsgInfo *msginfo;
3466
        GSList *seq_list, *cur;
3467
        gint ok = IMAP_SUCCESS;
3468

    
3469
        if (msglist == NULL) return IMAP_SUCCESS;
3470

    
3471
        msginfo = (MsgInfo *)msglist->data;
3472
        g_return_val_if_fail(msginfo != NULL, -1);
3473

    
3474
        g_return_val_if_fail(MSG_IS_IMAP(msginfo->flags), -1);
3475
        g_return_val_if_fail(msginfo->folder != NULL, -1);
3476
        g_return_val_if_fail(msginfo->folder->folder != NULL, -1);
3477

    
3478
        folder = msginfo->folder->folder;
3479
        g_return_val_if_fail(FOLDER_TYPE(folder) == F_IMAP, -1);
3480

    
3481
        session = imap_session_get(folder);
3482
        if (!session) return -1;
3483

    
3484
        ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder->path,
3485
                         NULL, NULL, NULL, NULL);
3486
        if (ok != IMAP_SUCCESS)
3487
                return ok;
3488

    
3489
        seq_list = imap_get_seq_set_from_msglist(msglist, 0);
3490

    
3491
        if (flags & MSG_MARKED)  iflags |= IMAP_FLAG_FLAGGED;
3492
        if (flags & MSG_REPLIED) iflags |= IMAP_FLAG_ANSWERED;
3493

    
3494
        for (cur = seq_list; cur != NULL; cur = cur->next) {
3495
                gchar *seq_set = (gchar *)cur->data;
3496

    
3497
                if (iflags) {
3498
                        ok = imap_set_message_flags(session, seq_set, iflags,
3499
                                                    is_set);
3500
                        if (ok != IMAP_SUCCESS) break;
3501
                }
3502

    
3503
                if (flags & MSG_UNREAD) {
3504
                        ok = imap_set_message_flags(session, seq_set,
3505
                                                    IMAP_FLAG_SEEN, !is_set);
3506
                        if (ok != IMAP_SUCCESS) break;
3507
                }
3508
        }
3509

    
3510
        imap_seq_set_free(seq_list);
3511

    
3512
        return ok;
3513
}
3514

    
3515
gint imap_msg_set_perm_flags(MsgInfo *msginfo, MsgPermFlags flags)
3516
{
3517
        GSList msglist;
3518

    
3519
        msglist.data = msginfo;
3520
        msglist.next = NULL;
3521

    
3522
        return imap_msg_list_change_perm_flags(&msglist, flags, TRUE);
3523
}
3524

    
3525
gint imap_msg_unset_perm_flags(MsgInfo *msginfo, MsgPermFlags flags)
3526
{
3527
        GSList msglist;
3528

    
3529
        msglist.data = msginfo;
3530
        msglist.next = NULL;
3531

    
3532
        return imap_msg_list_change_perm_flags(&msglist, flags, FALSE);
3533
}
3534

    
3535
gint imap_msg_list_set_perm_flags(GSList *msglist, MsgPermFlags flags)
3536
{
3537
        return imap_msg_list_change_perm_flags(msglist, flags, TRUE);
3538
}
3539

    
3540
gint imap_msg_list_unset_perm_flags(GSList *msglist, MsgPermFlags flags)
3541
{
3542
        return imap_msg_list_change_perm_flags(msglist, flags, FALSE);
3543
}
3544

    
3545
gint imap_msg_list_set_colorlabel_flags(GSList *msglist, guint color)
3546
{
3547
        Folder *folder;
3548
        IMAPSession *session;
3549
        IMAPFlags iflags = 0;
3550
        MsgInfo *msginfo;
3551
        GSList *seq_list, *cur;
3552
        gint ok = IMAP_SUCCESS;
3553

    
3554
        if (msglist == NULL) return IMAP_SUCCESS;
3555

    
3556
        msginfo = (MsgInfo *)msglist->data;
3557
        g_return_val_if_fail(msginfo != NULL, -1);
3558

    
3559
        g_return_val_if_fail(MSG_IS_IMAP(msginfo->flags), -1);
3560
        g_return_val_if_fail(msginfo->folder != NULL, -1);
3561
        g_return_val_if_fail(msginfo->folder->folder != NULL, -1);
3562

    
3563
        folder = msginfo->folder->folder;
3564
        g_return_val_if_fail(FOLDER_TYPE(folder) == F_IMAP, -1);
3565

    
3566
        session = imap_session_get(folder);
3567
        if (!session) return -1;
3568

    
3569
        ok = imap_select(session, IMAP_FOLDER(folder), msginfo->folder->path,
3570
                         NULL, NULL, NULL, NULL);
3571
        if (ok != IMAP_SUCCESS)
3572
                return ok;
3573

    
3574
        seq_list = imap_get_seq_set_from_msglist(msglist, 0);
3575

    
3576
        IMAP_SET_COLORLABEL_VALUE(iflags, color);
3577

    
3578
        for (cur = seq_list; cur != NULL; cur = cur->next) {
3579
                gchar *seq_set = (gchar *)cur->data;
3580

    
3581
                ok = imap_cmd_store(session, seq_set,
3582
                                    "-FLAGS.SILENT ($label1 $label2 $label3 $label4 $label5 $label6 $label7)");
3583
                if (ok != IMAP_SUCCESS) break;
3584

    
3585
                if (iflags) {
3586
                        ok = imap_set_message_flags(session, seq_set, iflags,
3587
                                                    TRUE);
3588
                        if (ok != IMAP_SUCCESS) break;
3589
                }
3590
        }
3591

    
3592
        imap_seq_set_free(seq_list);
3593

    
3594
        return ok;
3595
}
3596

    
3597
static gchar *imap_get_flag_str(IMAPFlags flags)
3598
{
3599
        GString *str;
3600
        gchar *ret;
3601
        guint color;
3602

    
3603
        str = g_string_new(NULL);
3604

    
3605
        if (IMAP_IS_SEEN(flags))        g_string_append(str, "\\Seen ");
3606
        if (IMAP_IS_ANSWERED(flags))        g_string_append(str, "\\Answered ");
3607
        if (IMAP_IS_FLAGGED(flags))        g_string_append(str, "\\Flagged ");
3608
        if (IMAP_IS_DELETED(flags))        g_string_append(str, "\\Deleted ");
3609
        if (IMAP_IS_DRAFT(flags))        g_string_append(str, "\\Draft ");
3610

    
3611
        if ((color = IMAP_GET_COLORLABEL_VALUE(flags)) != 0) {
3612
                g_string_append_printf(str, "$label%u", color);
3613
        }
3614

    
3615
        if (str->len > 0 && str->str[str->len - 1] == ' ')
3616
                g_string_truncate(str, str->len - 1);
3617

    
3618
        ret = str->str;
3619
        g_string_free(str, FALSE);
3620

    
3621
        return ret;
3622
}
3623

    
3624
static gint imap_set_message_flags(IMAPSession *session,
3625
                                   const gchar *seq_set,
3626
                                   IMAPFlags flags,
3627
                                   gboolean is_set)
3628
{
3629
        gchar *cmd;
3630
        gchar *flag_str;
3631
        gint ok;
3632

    
3633
        flag_str = imap_get_flag_str(flags);
3634
        cmd = g_strconcat(is_set ? "+FLAGS.SILENT (" : "-FLAGS.SILENT (",
3635
                          flag_str, ")", NULL);
3636
        g_free(flag_str);
3637

    
3638
        ok = imap_cmd_store(session, seq_set, cmd);
3639
        g_free(cmd);
3640

    
3641
        return ok;
3642
}
3643

    
3644
static gint imap_select(IMAPSession *session, IMAPFolder *folder,
3645
                        const gchar *path,
3646
                        gint *exists, gint *recent, gint *unseen,
3647
                        guint32 *uid_validity)
3648
{
3649
        gchar *real_path;
3650
        gint ok;
3651
        gint exists_, recent_, unseen_;
3652
        guint32 uid_validity_;
3653

    
3654
        if (!exists || !recent || !unseen || !uid_validity) {
3655
                if (session->mbox && strcmp(session->mbox, path) == 0)
3656
                        return IMAP_SUCCESS;
3657
                exists = &exists_;
3658
                recent = &recent_;
3659
                unseen = &unseen_;
3660
                uid_validity = &uid_validity_;
3661
        }
3662

    
3663
        g_free(session->mbox);
3664
        session->mbox = NULL;
3665

    
3666
        real_path = imap_get_real_path(folder, path);
3667
        ok = imap_cmd_select(session, real_path,
3668
                             exists, recent, unseen, uid_validity);
3669
        if (ok != IMAP_SUCCESS)
3670
                log_warning(_("can't select folder: %s\n"), real_path);
3671
        else
3672
                session->mbox = g_strdup(path);
3673
        g_free(real_path);
3674

    
3675
        return ok;
3676
}
3677

    
3678
#define THROW(err) { ok = err; goto catch; }
3679

    
3680
static gint imap_status(IMAPSession *session, IMAPFolder *folder,
3681
                        const gchar *path,
3682
                        gint *messages, gint *recent,
3683
                        guint32 *uid_next, guint32 *uid_validity,
3684
                        gint *unseen)
3685
{
3686
        gchar *real_path;
3687
        gchar *real_path_;
3688
        gint ok;
3689
        GPtrArray *argbuf = NULL;
3690
        gchar *str;
3691

    
3692
        if (messages && recent && uid_next && uid_validity && unseen) {
3693
                *messages = *recent = *uid_next = *uid_validity = *unseen = 0;
3694
                argbuf = g_ptr_array_new();
3695
        }
3696

    
3697
        real_path = imap_get_real_path(folder, path);
3698
        QUOTE_IF_REQUIRED(real_path_, real_path);
3699
        ok = imap_cmd_gen_send(session, "STATUS %s "
3700
                               "(MESSAGES RECENT UIDNEXT UIDVALIDITY UNSEEN)",
3701
                               real_path_);
3702
        if (ok != IMAP_SUCCESS) {
3703
                log_warning("error on sending imap command: STATUS\n");
3704
                THROW(ok);
3705
        }
3706
        ok = imap_cmd_ok(session, argbuf);
3707
        if (ok != IMAP_SUCCESS)
3708
                log_warning(_("error on imap command: STATUS\n"));
3709
        if (ok != IMAP_SUCCESS || !argbuf) THROW(ok);
3710

    
3711
        str = search_array_str(argbuf, "STATUS");
3712
        if (!str) THROW(IMAP_ERROR);
3713

    
3714
        str = strchr(str, '(');
3715
        if (!str) THROW(IMAP_ERROR);
3716
        str++;
3717
        while (*str != '\0' && *str != ')') {
3718
                while (*str == ' ') str++;
3719

    
3720
                if (!strncmp(str, "MESSAGES ", 9)) {
3721
                        str += 9;
3722
                        *messages = strtol(str, &str, 10);
3723
                } else if (!strncmp(str, "RECENT ", 7)) {
3724
                        str += 7;
3725
                        *recent = strtol(str, &str, 10);
3726
                } else if (!strncmp(str, "UIDNEXT ", 8)) {
3727
                        str += 8;
3728
                        *uid_next = strtoul(str, &str, 10);
3729
                } else if (!strncmp(str, "UIDVALIDITY ", 12)) {
3730
                        str += 12;
3731
                        *uid_validity = strtoul(str, &str, 10);
3732
                } else if (!strncmp(str, "UNSEEN ", 7)) {
3733
                        str += 7;
3734
                        *unseen = strtol(str, &str, 10);
3735
                } else {
3736
                        g_warning("invalid STATUS response: %s\n", str);
3737
                        break;
3738
                }
3739
        }
3740

    
3741
catch:
3742
        g_free(real_path);
3743
        if (argbuf) {
3744
                ptr_array_free_strings(argbuf);
3745
                g_ptr_array_free(argbuf, TRUE);
3746
        }
3747

    
3748
        return ok;
3749
}
3750

    
3751
#undef THROW
3752

    
3753
static gboolean imap_has_capability(IMAPSession        *session,
3754
                                    const gchar *capability)
3755
{
3756
        gchar **p;
3757

    
3758
        for (p = session->capability; *p != NULL; ++p) {
3759
                if (!g_ascii_strcasecmp(*p, capability))
3760
                        return TRUE;
3761
        }
3762

    
3763
        return FALSE;
3764
}
3765

    
3766
static void imap_capability_free(IMAPSession *session)
3767
{
3768
        if (session->capability) {
3769
                g_strfreev(session->capability);
3770
                session->capability = NULL;
3771
        }
3772
}
3773

    
3774

    
3775
/* low-level IMAP4rev1 commands */
3776

    
3777
#define THROW(err) { ok = err; goto catch; }
3778

    
3779
static gint imap_cmd_capability(IMAPSession *session)
3780
{
3781
        gint ok;
3782
        GPtrArray *argbuf;
3783
        gchar *capability;
3784

    
3785
        argbuf = g_ptr_array_new();
3786

    
3787
        if ((ok = imap_cmd_gen_send(session, "CAPABILITY")) != IMAP_SUCCESS)
3788
                THROW(ok);
3789
        if ((ok = imap_cmd_ok(session, argbuf)) != IMAP_SUCCESS) THROW(ok);
3790

    
3791
        capability = search_array_str(argbuf, "CAPABILITY ");
3792
        if (!capability) THROW(IMAP_ERROR);
3793

    
3794
        capability += strlen("CAPABILITY ");
3795

    
3796
        imap_capability_free(session);
3797
        session->capability = g_strsplit(capability, " ", -1);
3798

    
3799
catch:
3800
        ptr_array_free_strings(argbuf);
3801
        g_ptr_array_free(argbuf, TRUE);
3802

    
3803
        return ok;
3804
}
3805

    
3806
#undef THROW
3807

    
3808
static gint imap_cmd_auth_plain(IMAPSession *session, const gchar *user,
3809
                                const gchar *pass)
3810
{
3811
        gchar *p;
3812
        gchar *response;
3813
        gchar *response64;
3814
        gint ok;
3815

    
3816
        p = response = g_malloc(strlen(user) * 2 + 2 + strlen(pass) + 1);
3817
        strcpy(p, user);
3818
        p += strlen(user) + 1;
3819
        strcpy(p, user);
3820
        p += strlen(user) + 1;
3821
        strcpy(p, pass);
3822
        p += strlen(pass);
3823

    
3824
        response64 = g_malloc((p - response) * 2 + 1);
3825
        base64_encode(response64, (guchar *)response, p - response);
3826
        g_free(response);
3827

    
3828
        log_print("IMAP4> ****************\n");
3829
        sock_puts(SESSION(session)->sock, response64);
3830
        ok = imap_cmd_ok(session, NULL);
3831
        if (ok != IMAP_SUCCESS)
3832
                log_warning(_("IMAP4 authentication failed.\n"));
3833
        g_free(response64);
3834

    
3835
        return ok;
3836
}
3837

    
3838
static gint imap_cmd_auth_cram_md5(IMAPSession *session, const gchar *user,
3839
                                   const gchar *pass, const gchar *challenge64)
3840
{
3841
        gchar *challenge;
3842
        gint challenge_len;
3843
        gchar hexdigest[33];
3844
        gchar *response;
3845
        gchar *response64;
3846
        gint ok;
3847

    
3848
        challenge = g_malloc(strlen(challenge64 + 2) + 1);
3849
        challenge_len = base64_decode((guchar *)challenge, challenge64 + 2, -1);
3850
        challenge[challenge_len] = '\0';
3851
        log_print("IMAP< [Decoded: %s]\n", challenge);
3852

    
3853
        md5_hex_hmac(hexdigest, (guchar *)challenge, challenge_len,
3854
                     (guchar *)pass, strlen(pass));
3855
        g_free(challenge);
3856

    
3857
        response = g_strdup_printf("%s %s", user, hexdigest);
3858
        log_print("IMAP> [Encoded: %s]\n", response);
3859
        response64 = g_malloc((strlen(response) + 3) * 2 + 1);
3860
        base64_encode(response64, (guchar *)response, strlen(response));
3861
        g_free(response);
3862

    
3863
        log_print("IMAP> %s\n", response64);
3864
        sock_puts(SESSION(session)->sock, response64);
3865
        ok = imap_cmd_ok(session, NULL);
3866
        if (ok != IMAP_SUCCESS)
3867
                log_warning(_("IMAP4 authentication failed.\n"));
3868

    
3869
        return ok;
3870
}
3871

    
3872
static gint imap_cmd_authenticate(IMAPSession *session, const gchar *user,
3873
                                  const gchar *pass, IMAPAuthType type)
3874
{
3875
        gchar *auth_type;
3876
        gint ok;
3877
        gchar *buf = NULL;
3878

    
3879
        g_return_val_if_fail((type == 0 || type == IMAP_AUTH_CRAM_MD5 ||
3880
                              type == IMAP_AUTH_PLAIN), IMAP_ERROR);
3881

    
3882
        if (type == IMAP_AUTH_PLAIN)
3883
                auth_type = "PLAIN";
3884
        else
3885
                auth_type = "CRAM-MD5";
3886

    
3887
        ok = imap_cmd_gen_send(session, "AUTHENTICATE %s", auth_type);
3888
        if (ok != IMAP_SUCCESS) {
3889
                g_free(buf);
3890
                return ok;
3891
        }
3892
        ok = imap_cmd_gen_recv(session, &buf);
3893
        if (ok != IMAP_SUCCESS || buf[0] != '+') {
3894
                g_free(buf);
3895
                return IMAP_ERROR;
3896
        }
3897

    
3898
        if (type == IMAP_AUTH_PLAIN)
3899
                ok = imap_cmd_auth_plain(session, user, pass);
3900
        else
3901
                ok = imap_cmd_auth_cram_md5(session, user, pass, buf);
3902

    
3903
        g_free(buf);
3904

    
3905
        return ok;
3906
}
3907

    
3908
static gint imap_cmd_login(IMAPSession *session,
3909
                           const gchar *user, const gchar *pass)
3910
{
3911
        gchar *user_, *pass_;
3912
        gint ok;
3913

    
3914
        QUOTE_IF_REQUIRED(user_, user);
3915
        QUOTE_IF_REQUIRED(pass_, pass);
3916
        ok = imap_cmd_gen_send(session, "LOGIN %s %s", user_, pass_);
3917
        if (ok == IMAP_SUCCESS)
3918
                ok = imap_cmd_ok(session, NULL);
3919
        if (ok != IMAP_SUCCESS)
3920
                log_warning(_("IMAP4 login failed.\n"));
3921

    
3922
        return ok;
3923
}
3924

    
3925
static gint imap_cmd_logout(IMAPSession *session)
3926
{
3927
        if (imap_cmd_gen_send(session, "LOGOUT") != IMAP_SUCCESS)
3928
                return IMAP_ERROR;
3929
        return imap_cmd_ok(session, NULL);
3930
}
3931

    
3932
static gint imap_cmd_noop(IMAPSession *session)
3933
{
3934
        gint ret;
3935

    
3936
        ret = imap_cmd_gen_send(session, "NOOP");
3937
        if (ret != IMAP_SUCCESS)
3938
                return ret;
3939
        return imap_cmd_ok(session, NULL);
3940
}
3941

    
3942
#if USE_SSL
3943
static gint imap_cmd_starttls(IMAPSession *session)
3944
{
3945
        if (imap_cmd_gen_send(session, "STARTTLS") != IMAP_SUCCESS)
3946
                return IMAP_ERROR;
3947
        return imap_cmd_ok(session, NULL);
3948
}
3949
#endif
3950

    
3951
#define THROW(err) { ok = err; goto catch; }
3952

    
3953
static gint imap_cmd_namespace(IMAPSession *session, gchar **ns_str)
3954
{
3955
        gint ok;
3956
        GPtrArray *argbuf;
3957
        gchar *str;
3958

    
3959
        argbuf = g_ptr_array_new();
3960

    
3961
        if ((ok = imap_cmd_gen_send(session, "NAMESPACE")) != IMAP_SUCCESS)
3962
                THROW(ok);
3963
        if ((ok = imap_cmd_ok(session, argbuf)) != IMAP_SUCCESS) THROW(ok);
3964

    
3965
        str = search_array_str(argbuf, "NAMESPACE");
3966
        if (!str) THROW(IMAP_ERROR);
3967

    
3968
        *ns_str = g_strdup(str);
3969

    
3970
catch:
3971
        ptr_array_free_strings(argbuf);
3972
        g_ptr_array_free(argbuf, TRUE);
3973

    
3974
        return ok;
3975
}
3976

    
3977
#undef THROW
3978

    
3979
static gint imap_cmd_list(IMAPSession *session, const gchar *ref,
3980
                          const gchar *mailbox, GPtrArray *argbuf)
3981
{
3982
        gchar *ref_, *mailbox_;
3983

    
3984
        if (!ref) ref = "\"\"";
3985
        if (!mailbox) mailbox = "\"\"";
3986

    
3987
        QUOTE_IF_REQUIRED(ref_, ref);
3988
        QUOTE_IF_REQUIRED(mailbox_, mailbox);
3989
        if (imap_cmd_gen_send(session, "LIST %s %s", ref_, mailbox_) != IMAP_SUCCESS)
3990
                return IMAP_ERROR;
3991

    
3992
        return imap_cmd_ok(session, argbuf);
3993
}
3994

    
3995
#define THROW goto catch
3996

    
3997
static gint imap_cmd_do_select(IMAPSession *session, const gchar *folder,
3998
                               gboolean examine,
3999
                               gint *exists, gint *recent, gint *unseen,
4000
                               guint32 *uid_validity)
4001
{
4002
        gint ok;
4003
        gchar *resp_str;
4004
        GPtrArray *argbuf;
4005
        gchar *select_cmd;
4006
        gchar *folder_;
4007
        guint uid_validity_;
4008

    
4009
        *exists = *recent = *unseen = *uid_validity = 0;
4010
        argbuf = g_ptr_array_new();
4011

    
4012
        if (examine)
4013
                select_cmd = "EXAMINE";
4014
        else
4015
                select_cmd = "SELECT";
4016

    
4017
        QUOTE_IF_REQUIRED(folder_, folder);
4018
        if ((ok = imap_cmd_gen_send(session, "%s %s", select_cmd, folder_)) != IMAP_SUCCESS)
4019
                THROW;
4020

    
4021
        if ((ok = imap_cmd_ok(session, argbuf)) != IMAP_SUCCESS) THROW;
4022

    
4023
        resp_str = search_array_contain_str(argbuf, "EXISTS");
4024
        if (resp_str) {
4025
                if (sscanf(resp_str,"%d EXISTS", exists) != 1) {
4026
                        g_warning("imap_cmd_select(): invalid EXISTS line.\n");
4027
                        THROW;
4028
                }
4029
        }
4030

    
4031
        resp_str = search_array_contain_str(argbuf, "RECENT");
4032
        if (resp_str) {
4033
                if (sscanf(resp_str, "%d RECENT", recent) != 1) {
4034
                        g_warning("imap_cmd_select(): invalid RECENT line.\n");
4035
                        THROW;
4036
                }
4037
        }
4038

    
4039
        resp_str = search_array_contain_str(argbuf, "UIDVALIDITY");
4040
        if (resp_str) {
4041
                if (sscanf(resp_str, "OK [UIDVALIDITY %u] ", &uid_validity_)
4042
                    != 1) {
4043
                        g_warning("imap_cmd_select(): invalid UIDVALIDITY line.\n");
4044
                        THROW;
4045
                }
4046
                *uid_validity = uid_validity_;
4047
        }
4048

    
4049
        resp_str = search_array_contain_str(argbuf, "UNSEEN");
4050
        if (resp_str) {
4051
                if (sscanf(resp_str, "OK [UNSEEN %d] ", unseen) != 1) {
4052
                        g_warning("imap_cmd_select(): invalid UNSEEN line.\n");
4053
                        THROW;
4054
                }
4055
        }
4056

    
4057
catch:
4058
        ptr_array_free_strings(argbuf);
4059
        g_ptr_array_free(argbuf, TRUE);
4060

    
4061
        return ok;
4062
}
4063

    
4064
static gint imap_cmd_select(IMAPSession *session, const gchar *folder,
4065
                            gint *exists, gint *recent, gint *unseen,
4066
                            guint32 *uid_validity)
4067
{
4068
        return imap_cmd_do_select(session, folder, FALSE,
4069
                                  exists, recent, unseen, uid_validity);
4070
}
4071

    
4072
static gint imap_cmd_examine(IMAPSession *session, const gchar *folder,
4073
                             gint *exists, gint *recent, gint *unseen,
4074
                             guint32 *uid_validity)
4075
{
4076
        return imap_cmd_do_select(session, folder, TRUE,
4077
                                  exists, recent, unseen, uid_validity);
4078
}
4079

    
4080
#undef THROW
4081

    
4082
static gint imap_cmd_create(IMAPSession *session, const gchar *folder)
4083
{
4084
        gchar *folder_;
4085

    
4086
        QUOTE_IF_REQUIRED(folder_, folder);
4087
        if (imap_cmd_gen_send(session, "CREATE %s", folder_) != IMAP_SUCCESS)
4088
                return IMAP_ERROR;
4089

    
4090
        return imap_cmd_ok(session, NULL);
4091
}
4092

    
4093
static gint imap_cmd_rename(IMAPSession *session, const gchar *old_folder,
4094
                            const gchar *new_folder)
4095
{
4096
        gchar *old_folder_, *new_folder_;
4097

    
4098
        QUOTE_IF_REQUIRED(old_folder_, old_folder);
4099
        QUOTE_IF_REQUIRED(new_folder_, new_folder);
4100
        if (imap_cmd_gen_send(session, "RENAME %s %s", old_folder_, new_folder_) != IMAP_SUCCESS)
4101
                return IMAP_ERROR;
4102

    
4103
        return imap_cmd_ok(session, NULL);
4104
}
4105

    
4106
static gint imap_cmd_delete(IMAPSession *session, const gchar *folder)
4107
{
4108
        gchar *folder_;
4109

    
4110
        QUOTE_IF_REQUIRED(folder_, folder);
4111
        if (imap_cmd_gen_send(session, "DELETE %s", folder_) != IMAP_SUCCESS)
4112
                return IMAP_ERROR;
4113

    
4114
        return imap_cmd_ok(session, NULL);
4115
}
4116

    
4117
#define THROW(err) { ok = err; goto catch; }
4118

    
4119
static gint imap_cmd_search(IMAPSession *session, const gchar *criteria,
4120
                            GArray **result)
4121
{
4122
        gint ok;
4123
        GPtrArray *argbuf;
4124
        GArray *array;
4125
        gchar *str;
4126
        gchar *p, *ep;
4127
        gint i;
4128
        guint32 uid;
4129

    
4130
        g_return_val_if_fail(criteria != NULL, IMAP_ERROR);
4131
        g_return_val_if_fail(result != NULL, IMAP_ERROR);
4132

    
4133
        argbuf = g_ptr_array_new();
4134

    
4135
        if ((ok = imap_cmd_gen_send(session, "UID SEARCH %s", criteria)) != IMAP_SUCCESS)
4136
                THROW(ok);
4137
        if ((ok = imap_cmd_ok(session, argbuf)) != IMAP_SUCCESS) THROW(ok);
4138

    
4139
        array = g_array_new(FALSE, FALSE, sizeof(guint32));
4140

    
4141
        for (i = 0; i < argbuf->len; i++) {
4142
                str = g_ptr_array_index(argbuf, i);
4143
                if (strncmp(str, "SEARCH", 6) != 0)
4144
                        continue;
4145

    
4146
                p = str + 6;
4147
                while (*p != '\0') {
4148
                        uid = strtoul(p, &ep, 10);
4149
                        if (p < ep && uid > 0) {
4150
                                g_array_append_val(array, uid);
4151
                                p = ep;
4152
                        } else
4153
                                break;
4154
                }
4155
        }
4156

    
4157
        *result = array;
4158

    
4159
catch:
4160
        ptr_array_free_strings(argbuf);
4161
        g_ptr_array_free(argbuf, TRUE);
4162

    
4163
        return ok;
4164
}
4165

    
4166
typedef struct _IMAPCmdFetchData
4167
{
4168
        guint32 uid;
4169
        const gchar *filename;
4170
} IMAPCmdFetchData;
4171

    
4172
#define THROW(err) { ok = err; goto catch; }
4173

    
4174
static gint imap_cmd_fetch_func(IMAPSession *session, gpointer data)
4175
{
4176
        const gchar *filename = ((IMAPCmdFetchData *)data)->filename;
4177
        gint ok;
4178
        gchar *buf;
4179
        gchar *cur_pos;
4180
        gchar size_str[32];
4181
        glong size_num;
4182
        gint ret;
4183

    
4184
        while ((ok = imap_cmd_gen_recv(session, &buf)) == IMAP_SUCCESS) {
4185
                if (buf[0] != '*' || buf[1] != ' ') {
4186
                        g_free(buf);
4187
                        return IMAP_ERROR;
4188
                }
4189
                if (strstr(buf, "FETCH") != NULL && strstr(buf, "BODY") != NULL)
4190
                        break;
4191
                g_free(buf);
4192
        }
4193
        if (ok != IMAP_SUCCESS)
4194
                THROW(ok);
4195

    
4196
#define RETURN_ERROR_IF_FAIL(cond)                        \
4197
        if (!(cond)) {                                        \
4198
                g_free(buf);                                \
4199
                ok = imap_cmd_ok_real(session, NULL);        \
4200
                THROW(IMAP_ERROR);                        \
4201
        }
4202

    
4203
        cur_pos = strchr(buf, '{');
4204
        RETURN_ERROR_IF_FAIL(cur_pos != NULL);
4205
        cur_pos = strchr_cpy(cur_pos + 1, '}', size_str, sizeof(size_str));
4206
        RETURN_ERROR_IF_FAIL(cur_pos != NULL);
4207
        size_num = atol(size_str);
4208
        RETURN_ERROR_IF_FAIL(size_num >= 0);
4209

    
4210
        RETURN_ERROR_IF_FAIL(*cur_pos == '\0');
4211

    
4212
#undef RETURN_ERROR_IF_FAIL
4213

    
4214
        g_free(buf);
4215

    
4216
        if ((ret = recv_bytes_write_to_file(SESSION(session)->sock,
4217
                                            size_num, filename)) != 0) {
4218
                if (ret == -2)
4219
                        THROW(IMAP_SOCKET);
4220
        }
4221

    
4222
        if (imap_cmd_gen_recv(session, &buf) != IMAP_SUCCESS)
4223
                THROW(IMAP_ERROR);
4224

    
4225
        if (buf[0] == '\0' || buf[strlen(buf) - 1] != ')') {
4226
                g_free(buf);
4227
                THROW(IMAP_ERROR);
4228
        }
4229
        g_free(buf);
4230

    
4231
        ok = imap_cmd_ok_real(session, NULL);
4232

    
4233
        if (ret != 0)
4234
                THROW(IMAP_ERROR);
4235

    
4236
catch:
4237
        return ok;
4238
}
4239

    
4240
#undef THROW
4241

    
4242
static gint imap_cmd_fetch(IMAPSession *session, guint32 uid,
4243
                           const gchar *filename)
4244
{
4245
        gint ok;
4246
        IMAPCmdFetchData fetch_data = {uid, filename};
4247

    
4248
        g_return_val_if_fail(filename != NULL, IMAP_ERROR);
4249

    
4250
        ok = imap_cmd_gen_send(session, "UID FETCH %u BODY.PEEK[]", uid);
4251
        if (ok != IMAP_SUCCESS)
4252
                return ok;
4253

    
4254
#if USE_THREADS
4255
        ok = imap_thread_run(session, imap_cmd_fetch_func, &fetch_data);
4256
#else
4257
        ok = imap_cmd_fetch_func(session, &fetch_data);
4258
#endif
4259

    
4260
        return ok;
4261
}
4262

    
4263
static void imap_get_date_time(gchar *buf, size_t len, time_t timer)
4264
{
4265
        static gchar monthstr[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
4266
        struct tm *lt;
4267
        gchar date_time[64];
4268
        gchar tz[6];
4269

    
4270
        lt = localtime(&timer);
4271
        if (lt && lt->tm_mon >= 0 && lt->tm_mon < 12) {
4272
                strftime(date_time, sizeof(date_time), "%d-___-%Y %H:%M:%S",
4273
                         lt);
4274
                tzoffset_buf(tz, &timer);
4275
                memcpy(date_time + 3, monthstr + lt->tm_mon * 3, 3);
4276
                g_snprintf(buf, len, "%s %s", date_time, tz);
4277
        }
4278
}
4279

    
4280
static gint imap_cmd_append(IMAPSession *session, const gchar *destfolder,
4281
                            const gchar *file, IMAPFlags flags,
4282
                            guint32 *new_uid)
4283
{
4284
        gint ok;
4285
        MsgInfo *msginfo;
4286
        MsgFlags flags_ = {0, 0};
4287
        gchar date_time[64] = "";
4288
        gint size;
4289
        gchar *destfolder_;
4290
        gchar *flag_str;
4291
        guint new_uid_;
4292
        gchar *ret = NULL;
4293
        gchar buf[BUFFSIZE];
4294
        FILE *fp;
4295
        FILE *tmp;
4296
        size_t read_len;
4297
        GPtrArray *argbuf;
4298
        gchar *resp_str;
4299

    
4300
        g_return_val_if_fail(file != NULL, IMAP_ERROR);
4301

    
4302
        if ((fp = g_fopen(file, "rb")) == NULL) {
4303
                FILE_OP_ERROR(file, "fopen");
4304
                return -1;
4305
        }
4306

    
4307
        /* use Date: header as received date */
4308
        msginfo = procheader_parse_stream(fp, flags_, FALSE);
4309
        imap_get_date_time(date_time, sizeof(date_time), msginfo->date_t);
4310
        procmsg_msginfo_free(msginfo);
4311

    
4312
        rewind(fp);
4313
        tmp = canonicalize_file_stream(fp, &size);
4314
        fclose(fp);
4315
        if (!tmp)
4316
                return -1;
4317

    
4318
        QUOTE_IF_REQUIRED(destfolder_, destfolder);
4319
        flag_str = imap_get_flag_str(flags);
4320
        if (date_time[0])
4321
                ok = imap_cmd_gen_send(session, "APPEND %s (%s) \"%s\" {%d}",
4322
                                       destfolder_, flag_str, date_time, size);
4323
        else
4324
                ok = imap_cmd_gen_send(session, "APPEND %s (%s) {%d}",
4325
                                       destfolder_, flag_str, size);
4326
        g_free(flag_str);
4327
        if (ok != IMAP_SUCCESS) {
4328
                log_warning(_("can't append %s to %s\n"), file, destfolder_);
4329
                fclose(tmp);
4330
                return ok;
4331
        }
4332

    
4333
        ok = imap_cmd_gen_recv(session, &ret);
4334
        if (ok != IMAP_SUCCESS || ret[0] != '+') {
4335
                log_warning(_("can't append %s to %s\n"), file, destfolder_);
4336
                g_free(ret);
4337
                fclose(tmp);
4338
                return IMAP_ERROR;
4339
        }
4340
        g_free(ret);
4341

    
4342
        log_print("IMAP4> %s\n", _("(sending file...)"));
4343

    
4344
        while ((read_len = fread(buf, 1, sizeof(buf), tmp)) > 0) {
4345
                if (read_len < sizeof(buf) && ferror(tmp))
4346
                        break;
4347
                if (sock_write_all(SESSION(session)->sock, buf, read_len) < 0) {
4348
                        fclose(tmp);
4349
                        return -1;
4350
                }
4351
        }
4352

    
4353
        if (ferror(tmp)) {
4354
                FILE_OP_ERROR(file, "fread");
4355
                fclose(tmp);
4356
                return -1;
4357
        }
4358

    
4359
        sock_puts(SESSION(session)->sock, "");
4360

    
4361
        fclose(tmp);
4362

    
4363
        if (new_uid != NULL)
4364
                *new_uid = 0;
4365

    
4366
        if (new_uid != NULL && session->uidplus) {
4367
                argbuf = g_ptr_array_new();
4368

    
4369
                ok = imap_cmd_ok(session, argbuf);
4370
                if (ok != IMAP_SUCCESS)
4371
                        log_warning(_("can't append message to %s\n"),
4372
                                    destfolder_);
4373
                else if (argbuf->len > 0) {
4374
                        resp_str = g_ptr_array_index(argbuf, argbuf->len - 1);
4375
                        if (resp_str &&
4376
                            sscanf(resp_str, "%*u OK [APPENDUID %*u %u]",
4377
                                   &new_uid_) == 1) {
4378
                                *new_uid = new_uid_;
4379
                        }
4380
                }
4381

    
4382
                ptr_array_free_strings(argbuf);
4383
                g_ptr_array_free(argbuf, TRUE);
4384
        } else
4385
                ok = imap_cmd_ok(session, NULL);
4386

    
4387
        return ok;
4388
}
4389

    
4390
static gint imap_cmd_copy(IMAPSession *session, const gchar *seq_set,
4391
                          const gchar *destfolder)
4392
{
4393
        gint ok;
4394
        gchar *destfolder_;
4395

    
4396
        g_return_val_if_fail(destfolder != NULL, IMAP_ERROR);
4397

    
4398
        QUOTE_IF_REQUIRED(destfolder_, destfolder);
4399
        ok = imap_cmd_gen_send(session, "UID COPY %s %s", seq_set, destfolder_);
4400
        if (ok == IMAP_SUCCESS)
4401
                ok = imap_cmd_ok(session, NULL);
4402
        if (ok != IMAP_SUCCESS) {
4403
                log_warning(_("can't copy %s to %s\n"), seq_set, destfolder_);
4404
                return -1;
4405
        }
4406

    
4407
        return ok;
4408
}
4409

    
4410
gint imap_cmd_envelope(IMAPSession *session, const gchar *seq_set)
4411
{
4412
        return imap_cmd_gen_send
4413
                (session, "UID FETCH %s (UID FLAGS RFC822.SIZE RFC822.HEADER)",
4414
                 seq_set);
4415
}
4416

    
4417
static gint imap_cmd_store(IMAPSession *session, const gchar *seq_set,
4418
                           const gchar *sub_cmd)
4419
{
4420
        gint ok;
4421

    
4422
        ok = imap_cmd_gen_send(session, "UID STORE %s %s", seq_set, sub_cmd);
4423
        if (ok == IMAP_SUCCESS)
4424
                ok = imap_cmd_ok(session, NULL);
4425
        if (ok != IMAP_SUCCESS) {
4426
                log_warning(_("error while imap command: STORE %s %s\n"),
4427
                            seq_set, sub_cmd);
4428
                return ok;
4429
        }
4430

    
4431
        return IMAP_SUCCESS;
4432
}
4433

    
4434
static gint imap_cmd_expunge(IMAPSession *session)
4435
{
4436
        gint ok;
4437

    
4438
        ok = imap_cmd_gen_send(session, "EXPUNGE");
4439
        if (ok == IMAP_SUCCESS)
4440
                ok = imap_cmd_ok(session, NULL);
4441
        if (ok != IMAP_SUCCESS) {
4442
                log_warning(_("error while imap command: EXPUNGE\n"));
4443
                return ok;
4444
        }
4445

    
4446
        return IMAP_SUCCESS;
4447
}
4448

    
4449
static gint imap_cmd_close(IMAPSession *session)
4450
{
4451
        gint ok;
4452

    
4453
        ok = imap_cmd_gen_send(session, "CLOSE");
4454
        if (ok == IMAP_SUCCESS)
4455
                ok = imap_cmd_ok(session, NULL);
4456
        if (ok != IMAP_SUCCESS)
4457
                log_warning(_("error while imap command: CLOSE\n"));
4458

    
4459
        return ok;
4460
}
4461

    
4462
static gint imap_cmd_ok_real(IMAPSession *session, GPtrArray *argbuf)
4463
{
4464
        gint ok;
4465
        gchar *buf;
4466
        gint cmd_num;
4467
        gchar cmd_status[IMAPBUFSIZE + 1];
4468
        GString *str;
4469
        gchar *p;
4470
        gchar obuf[32];
4471
        gint len;
4472
        gchar *literal;
4473

    
4474
        str = g_string_sized_new(256);
4475

    
4476
        //g_usleep(800000);
4477
        while ((ok = imap_cmd_gen_recv(session, &buf)) == IMAP_SUCCESS) {
4478
                g_string_append(str, buf);
4479

    
4480
                if ((p = strrchr_with_skip_quote(buf, '"', '{'))) {
4481
                        /* literal */
4482
                        p = strchr_cpy(p + 1, '}', obuf, sizeof(obuf));
4483
                        len = atoi(obuf);
4484
                        if (len < 0 || p == NULL || *p != '\0') {
4485
                                g_free(buf);
4486
                                ok = IMAP_ERROR;
4487
                                break;
4488
                        }
4489

    
4490
                        literal = recv_bytes(SESSION(session)->sock, len);
4491
                        if (!literal) {
4492
                                g_free(buf);
4493
                                ok = IMAP_SOCKET;
4494
                                break;
4495
                        }
4496
                        if (memchr(literal, '\n', len))
4497
                                log_print("IMAP4< (literal: %d bytes)\n", len);
4498
                        else
4499
                                log_print("IMAP4< %s\n", literal);
4500

    
4501
                        g_string_append(str, "\r\n");
4502
                        g_string_append_len(str, literal, len);
4503
                        g_free(literal);
4504
                        g_free(buf);
4505
                        continue;
4506
                }
4507

    
4508
                g_free(buf);
4509

    
4510
                if (str->str[0] == '*' && str->str[1] == ' ') {
4511
                        if (argbuf)
4512
                                g_ptr_array_add(argbuf, g_strdup(str->str + 2));
4513

    
4514
                        g_string_truncate(str, 0);
4515
                        continue;
4516
                } else if (sscanf(str->str, "%d %" Xstr(IMAPBUFSIZE) "s",
4517
                           &cmd_num, cmd_status) < 2) {
4518
                        ok = IMAP_ERROR;
4519
                } else if (cmd_num == session->cmd_count &&
4520
                           !strcmp(cmd_status, "OK")) {
4521
                        if (argbuf)
4522
                                g_ptr_array_add(argbuf, g_strdup(str->str));
4523
                } else {
4524
                        ok = IMAP_ERROR;
4525
                }
4526

    
4527
                break;
4528
        }
4529

    
4530
        g_string_free(str, TRUE);
4531
        return ok;
4532
}
4533

    
4534
#if USE_THREADS
4535
static gint imap_cmd_ok_func(IMAPSession *session, gpointer data)
4536
{
4537
        GPtrArray *argbuf = (GPtrArray *)data;
4538
        gint ok;
4539

    
4540
        ok = imap_cmd_ok_real(session, argbuf);
4541
        return ok;
4542
}
4543
#endif
4544

    
4545
static gint imap_cmd_ok(IMAPSession *session, GPtrArray *argbuf)
4546
{
4547
#if USE_THREADS
4548
        return imap_thread_run(session, imap_cmd_ok_func, argbuf);
4549
#else
4550
        return imap_cmd_ok_real(session, argbuf);
4551
#endif
4552
}
4553

    
4554
static gint imap_cmd_gen_send(IMAPSession *session, const gchar *format, ...)
4555
{
4556
        IMAPRealSession *real = (IMAPRealSession *)session;
4557
        gchar buf[IMAPBUFSIZE];
4558
        gchar tmp[IMAPBUFSIZE];
4559
        gchar *p;
4560
        va_list args;
4561

    
4562
        va_start(args, format);
4563
        g_vsnprintf(tmp, sizeof(tmp), format, args);
4564
        va_end(args);
4565

    
4566
#if USE_THREADS
4567
        if (real->is_running) {
4568
                g_warning("imap_cmd_gen_send: cannot send command because another command is already running.");
4569
                return IMAP_EAGAIN;
4570
        }
4571
#endif
4572

    
4573
        session->cmd_count++;
4574

    
4575
        g_snprintf(buf, sizeof(buf), "%d %s\r\n", session->cmd_count, tmp);
4576
        if (!g_ascii_strncasecmp(tmp, "LOGIN ", 6) &&
4577
            (p = strchr(tmp + 6, ' '))) {
4578
                *p = '\0';
4579
                log_print("IMAP4> %d %s ********\n", session->cmd_count, tmp);
4580
        } else
4581
                log_print("IMAP4> %d %s\n", session->cmd_count, tmp);
4582

    
4583
        sock_write_all(SESSION(session)->sock, buf, strlen(buf));
4584

    
4585
        return IMAP_SUCCESS;
4586
}
4587

    
4588
static gint imap_cmd_gen_recv(IMAPSession *session, gchar **ret)
4589
{
4590
        gint len;
4591

    
4592
        if ((len = sock_getline(SESSION(session)->sock, ret)) < 0)
4593
                return IMAP_SOCKET;
4594

    
4595
        strretchomp(*ret);
4596

    
4597
        if (len > 1000) {
4598
                gchar *str;
4599

    
4600
                str = trim_string(*ret, 1000);
4601
                log_print("IMAP4< %s\n", str);
4602
                g_free(str);
4603
        } else
4604
                log_print("IMAP4< %s\n", *ret);
4605

    
4606
        session_set_access_time(SESSION(session));
4607

    
4608
        return IMAP_SUCCESS;
4609
}
4610

    
4611
static gint imap_cmd_gen_recv_silent(IMAPSession *session, gchar **ret)
4612
{
4613
        gint len;
4614

    
4615
        if ((len = sock_getline(SESSION(session)->sock, ret)) < 0)
4616
                return IMAP_SOCKET;
4617

    
4618
        strretchomp(*ret);
4619

    
4620
        session_set_access_time(SESSION(session));
4621

    
4622
        return IMAP_SUCCESS;
4623
}
4624

    
4625

    
4626
/* misc utility functions */
4627

    
4628
static gchar *strchr_cpy(const gchar *src, gchar ch, gchar *dest, gint len)
4629
{
4630
        gchar *tmp;
4631

    
4632
        dest[0] = '\0';
4633
        tmp = strchr(src, ch);
4634
        if (!tmp)
4635
                return NULL;
4636

    
4637
        memcpy(dest, src, MIN(tmp - src, len - 1));
4638
        dest[MIN(tmp - src, len - 1)] = '\0';
4639

    
4640
        return tmp + 1;
4641
}
4642

    
4643
static gchar *get_quoted(const gchar *src, gchar ch, gchar *dest, gint len)
4644
{
4645
        const gchar *p = src;
4646
        gint n = 0;
4647

    
4648
        g_return_val_if_fail(*p == ch, NULL);
4649

    
4650
        *dest = '\0';
4651
        p++;
4652

    
4653
        while (*p != '\0' && *p != ch) {
4654
                if (n < len - 1) {
4655
                        if (*p == '\\' && *(p + 1) != '\0')
4656
                                p++;
4657
                        *dest++ = *p++;
4658
                } else
4659
                        p++;
4660
                n++;
4661
        }
4662

    
4663
        *dest = '\0';
4664
        return (gchar *)(*p == ch ? p + 1 : p);
4665
}
4666

    
4667
static gchar *search_array_contain_str(GPtrArray *array, gchar *str)
4668
{
4669
        gint i;
4670

    
4671
        for (i = 0; i < array->len; i++) {
4672
                gchar *tmp;
4673

    
4674
                tmp = g_ptr_array_index(array, i);
4675
                if (strstr(tmp, str) != NULL)
4676
                        return tmp;
4677
        }
4678

    
4679
        return NULL;
4680
}
4681

    
4682
static gchar *search_array_str(GPtrArray *array, gchar *str)
4683
{
4684
        gint i;
4685
        gint len;
4686

    
4687
        len = strlen(str);
4688

    
4689
        for (i = 0; i < array->len; i++) {
4690
                gchar *tmp;
4691

    
4692
                tmp = g_ptr_array_index(array, i);
4693
                if (!strncmp(tmp, str, len))
4694
                        return tmp;
4695
        }
4696

    
4697
        return NULL;
4698
}
4699

    
4700
static void imap_path_separator_subst(gchar *str, gchar separator)
4701
{
4702
        gchar *p;
4703
        gboolean in_escape = FALSE;
4704

    
4705
        if (!separator || separator == '/') return;
4706

    
4707
        for (p = str; *p != '\0'; p++) {
4708
                if (*p == '/' && !in_escape)
4709
                        *p = separator;
4710
                else if (*p == '&' && *(p + 1) != '-' && !in_escape)
4711
                        in_escape = TRUE;
4712
                else if (*p == '-' && in_escape)
4713
                        in_escape = FALSE;
4714
        }
4715
}
4716

    
4717
static gchar *imap_modified_utf7_to_utf8(const gchar *mutf7_str)
4718
{
4719
        static iconv_t cd = (iconv_t)-1;
4720
        static gboolean iconv_ok = TRUE;
4721
        GString *norm_utf7;
4722
        gchar *norm_utf7_p;
4723
        size_t norm_utf7_len;
4724
        const gchar *p;
4725
        gchar *to_str, *to_p;
4726
        size_t to_len;
4727
        gboolean in_escape = FALSE;
4728

    
4729
        if (!iconv_ok) return g_strdup(mutf7_str);
4730

    
4731
        if (cd == (iconv_t)-1) {
4732
                cd = iconv_open(CS_INTERNAL, CS_UTF_7);
4733
                if (cd == (iconv_t)-1) {
4734
                        g_warning("iconv cannot convert UTF-7 to %s\n",
4735
                                  CS_INTERNAL);
4736
                        iconv_ok = FALSE;
4737
                        return g_strdup(mutf7_str);
4738
                }
4739
        }
4740

    
4741
        /* modified UTF-7 to normal UTF-7 conversion */
4742
        norm_utf7 = g_string_new(NULL);
4743

    
4744
        for (p = mutf7_str; *p != '\0'; p++) {
4745
                /* replace: '&'  -> '+',
4746
                            "&-" -> '&',
4747
                            "+"  -> "+-",
4748
                            escaped ','  -> '/' */
4749
                if (!in_escape && *p == '&') {
4750
                        if (*(p + 1) != '-') {
4751
                                g_string_append_c(norm_utf7, '+');
4752
                                in_escape = TRUE;
4753
                        } else {
4754
                                g_string_append_c(norm_utf7, '&');
4755
                                p++;
4756
                        }
4757
                } else if (!in_escape && *p == '+') {
4758
                        g_string_append(norm_utf7, "+-");
4759
                } else if (in_escape && *p == ',') {
4760
                        g_string_append_c(norm_utf7, '/');
4761
                } else if (in_escape && *p == '-') {
4762
                        g_string_append_c(norm_utf7, '-');
4763
                        in_escape = FALSE;
4764
                } else {
4765
                        g_string_append_c(norm_utf7, *p);
4766
                }
4767
        }
4768

    
4769
        /* somehow iconv() returns error when the last of the string is "+-" */
4770
        g_string_append_c(norm_utf7, '\n');
4771
        norm_utf7_p = norm_utf7->str;
4772
        norm_utf7_len = norm_utf7->len;
4773
        to_len = strlen(mutf7_str) * 5;
4774
        to_p = to_str = g_malloc(to_len + 1);
4775

    
4776
        if (iconv(cd, (ICONV_CONST gchar **)&norm_utf7_p, &norm_utf7_len,
4777
                  &to_p, &to_len) == -1) {
4778
                g_warning(_("iconv cannot convert UTF-7 to %s\n"), CS_INTERNAL);
4779
                g_string_free(norm_utf7, TRUE);
4780
                g_free(to_str);
4781
                return g_strdup(mutf7_str);
4782
        }
4783

    
4784
        /* second iconv() call for flushing */
4785
        iconv(cd, NULL, NULL, &to_p, &to_len);
4786
        g_string_free(norm_utf7, TRUE);
4787
        *to_p = '\0';
4788
        strretchomp(to_str);
4789

    
4790
        return to_str;
4791
}
4792

    
4793
static gchar *imap_utf8_to_modified_utf7(const gchar *from)
4794
{
4795
        static iconv_t cd = (iconv_t)-1;
4796
        static gboolean iconv_ok = TRUE;
4797
        gchar *norm_utf7, *norm_utf7_p;
4798
        size_t from_len, norm_utf7_len;
4799
        GString *to_str;
4800
        const gchar *from_tmp;
4801
        const gchar *p;
4802
        gchar *to;
4803
        gboolean in_escape = FALSE;
4804

    
4805
        if (!iconv_ok) return g_strdup(from);
4806

    
4807
        if (cd == (iconv_t)-1) {
4808
                cd = iconv_open(CS_UTF_7, CS_INTERNAL);
4809
                if (cd == (iconv_t)-1) {
4810
                        g_warning(_("iconv cannot convert %s to UTF-7\n"),
4811
                                  CS_INTERNAL);
4812
                        iconv_ok = FALSE;
4813
                        return g_strdup(from);
4814
                }
4815
        }
4816

    
4817
        /* UTF-8 to normal UTF-7 conversion */
4818
        from_tmp = from;
4819
        from_len = strlen(from);
4820
        norm_utf7_len = from_len * 5;
4821
        norm_utf7 = g_malloc(norm_utf7_len + 1);
4822
        norm_utf7_p = norm_utf7;
4823

    
4824
        while (from_len > 0) {
4825
                if (*from_tmp == '+') {
4826
                        *norm_utf7_p++ = '+';
4827
                        *norm_utf7_p++ = '-';
4828
                        norm_utf7_len -= 2;
4829
                        from_tmp++;
4830
                        from_len--;
4831
                } else if (g_ascii_isprint(*from_tmp)) {
4832
                        /* printable ascii char */
4833
                        *norm_utf7_p = *from_tmp;
4834
                        norm_utf7_p++;
4835
                        norm_utf7_len--;
4836
                        from_tmp++;
4837
                        from_len--;
4838
                } else {
4839
                        size_t conv_len = 0;
4840

    
4841
                        /* unprintable char: convert to UTF-7 */
4842
                        p = from_tmp;
4843
                        while (!g_ascii_isprint(*p) && conv_len < from_len) {
4844
                                conv_len += g_utf8_skip[*(guchar *)p];
4845
                                p += g_utf8_skip[*(guchar *)p];
4846
                        }
4847

    
4848
                        from_len -= conv_len;
4849
                        if (iconv(cd, (ICONV_CONST gchar **)&from_tmp,
4850
                                  &conv_len,
4851
                                  &norm_utf7_p, &norm_utf7_len) == -1) {
4852
                                g_warning("iconv cannot convert %s to UTF-7\n",
4853
                                          CS_INTERNAL);
4854
                                g_free(norm_utf7);
4855
                                return g_strdup(from);
4856
                        }
4857

    
4858
                        /* second iconv() call for flushing */
4859
                        iconv(cd, NULL, NULL, &norm_utf7_p, &norm_utf7_len);
4860
                }
4861
        }
4862

    
4863
        *norm_utf7_p = '\0';
4864
        to_str = g_string_new(NULL);
4865
        for (p = norm_utf7; p < norm_utf7_p; p++) {
4866
                /* replace: '&' -> "&-",
4867
                            '+' -> '&',
4868
                            "+-" -> '+',
4869
                            BASE64 '/' -> ',' */
4870
                if (!in_escape && *p == '&') {
4871
                        g_string_append(to_str, "&-");
4872
                } else if (!in_escape && *p == '+') {
4873
                        if (*(p + 1) == '-') {
4874
                                g_string_append_c(to_str, '+');
4875
                                p++;
4876
                        } else {
4877
                                g_string_append_c(to_str, '&');
4878
                                in_escape = TRUE;
4879
                        }
4880
                } else if (in_escape && *p == '/') {
4881
                        g_string_append_c(to_str, ',');
4882
                } else if (in_escape && *p == '-') {
4883
                        g_string_append_c(to_str, '-');
4884
                        in_escape = FALSE;
4885
                } else {
4886
                        g_string_append_c(to_str, *p);
4887
                }
4888
        }
4889

    
4890
        if (in_escape) {
4891
                in_escape = FALSE;
4892
                g_string_append_c(to_str, '-');
4893
        }
4894

    
4895
        to = g_string_free(to_str, FALSE);
4896
        g_free(norm_utf7);
4897

    
4898
        return to;
4899
}
4900

    
4901
static GSList *imap_get_seq_set_from_msglist(GSList *msglist, gint limit)
4902
{
4903
        GString *str;
4904
        GSList *sorted_list, *cur;
4905
        guint first, last, next;
4906
        gchar *ret_str;
4907
        GSList *ret_list = NULL;
4908
        gint count = 0;
4909

    
4910
        if (msglist == NULL)
4911
                return NULL;
4912

    
4913
        str = g_string_sized_new(256);
4914

    
4915
        sorted_list = g_slist_copy(msglist);
4916
        sorted_list = procmsg_sort_msg_list(sorted_list, SORT_BY_NUMBER,
4917
                                            SORT_ASCENDING);
4918

    
4919
        first = ((MsgInfo *)sorted_list->data)->msgnum;
4920

    
4921
        for (cur = sorted_list; cur != NULL; cur = cur->next) {
4922
                ++count;
4923
                last = ((MsgInfo *)cur->data)->msgnum;
4924
                if (cur->next)
4925
                        next = ((MsgInfo *)cur->next->data)->msgnum;
4926
                else
4927
                        next = 0;
4928

    
4929
                if (limit > 0 && count >= limit) {
4930
                        if (str->len > 0)
4931
                                g_string_append_c(str, ',');
4932
                        if (first == last)
4933
                                g_string_sprintfa(str, "%u", first);
4934
                        else
4935
                                g_string_sprintfa(str, "%u:%u", first, last);
4936

    
4937
                        first = next;
4938

    
4939
                        ret_str = g_strdup(str->str);
4940
                        ret_list = g_slist_append(ret_list, ret_str);
4941
                        g_string_truncate(str, 0);
4942
                        count = 0;
4943
                        continue;
4944
                }
4945

    
4946
                if (last + 1 != next || next == 0) {
4947
                        if (str-&g