2012-11-21 [colin] 3.9.0cvs7-stable
[claws.git] / src / etpan / imap-thread.c
1 /*
2  * Claws Mail -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 2005-2012 DINH Viet Hoa and the Claws Mail team
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  * 
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #include "claws-features.h"
23 #endif
24
25 #ifdef HAVE_LIBETPAN
26
27 #include <glib.h>
28 #include <glib/gi18n.h>
29 #include "imap-thread.h"
30 #include <imap.h>
31 #include <sys/types.h>
32 #include <sys/stat.h>
33 #if (defined(__DragonFly__) || defined (__NetBSD__) || defined (__FreeBSD__) || defined (__OpenBSD__) || defined (__CYGWIN__))
34 #include <sys/socket.h>
35 #endif
36 #include <fcntl.h>
37 #ifndef G_OS_WIN32
38 #include <sys/mman.h>
39 #include <sys/wait.h>
40 #endif
41 #include <gtk/gtk.h>
42 #include <log.h>
43 #include "etpan-thread-manager.h"
44 #include "utils.h"
45 #include "mainwindow.h"
46 #include "ssl.h"
47 #include "ssl_certificate.h"
48 #include "socket.h"
49 #include "remotefolder.h"
50 #include "tags.h"
51
52 #define DISABLE_LOG_DURING_LOGIN
53
54 static struct etpan_thread_manager * thread_manager = NULL;
55 static chash * courier_workaround_hash = NULL;
56 static chash * imap_hash = NULL;
57 static chash * session_hash = NULL;
58 static guint thread_manager_signal = 0;
59 static GIOChannel * io_channel = NULL;
60
61 static void delete_imap(Folder *folder, mailimap *imap)
62 {
63         chashdatum key;
64
65         key.data = &folder;
66         key.len = sizeof(folder);
67         chash_delete(session_hash, &key, NULL);
68         
69         key.data = &imap;
70         key.len = sizeof(imap);
71         chash_delete(courier_workaround_hash, &key, NULL);
72         if (imap && imap->imap_stream) {
73                 /* we don't want libetpan to logout */
74                 mailstream_close(imap->imap_stream);
75                 imap->imap_stream = NULL;
76         }
77         debug_print("removing mailimap %p\n", imap);
78         mailimap_free(imap);    
79 }
80
81 static gboolean thread_manager_event(GIOChannel * source,
82     GIOCondition condition,
83     gpointer data)
84 {
85 #ifdef G_OS_WIN32
86         gsize bytes_read;
87         gchar ch;
88         
89         if (condition & G_IO_IN)
90                 g_io_channel_read_chars(source, &ch, 1, &bytes_read, NULL);
91 #endif
92         etpan_thread_manager_loop(thread_manager);
93         
94         return TRUE;
95 }
96
97 static void imap_logger_noop(int direction, const char * str, size_t size) 
98 {
99         /* inhibit logging */
100 }
101
102 static void imap_logger_cmd(int direction, const char * str, size_t size) 
103 {
104         gchar *buf;
105         gchar **lines;
106         int i = 0;
107
108         if (size > 8192) {
109                 log_print(LOG_PROTOCOL, "IMAP4%c [CMD data - %zd bytes]\n", direction?'>':'<', size);
110                 return;
111         }
112         buf = malloc(size+1);
113         memset(buf, 0, size+1);
114         strncpy(buf, str, size);
115         buf[size] = '\0';
116
117         if (!strncmp(buf, "<<<<<<<", 7) 
118         ||  !strncmp(buf, ">>>>>>>", 7)) {
119                 free(buf);
120                 return;
121         }
122         while (strstr(buf, "\r"))
123                 *strstr(buf, "\r") = ' ';
124         while (strlen(buf) > 0 && buf[strlen(buf)-1] == '\n')
125                 buf[strlen(buf)-1] = '\0';
126
127         lines = g_strsplit(buf, "\n", -1);
128
129         while (lines[i] && *lines[i]) {
130                 log_print(LOG_PROTOCOL, "IMAP4%c %s\n", direction?'>':'<', lines[i]);
131                 i++;
132         }
133         g_strfreev(lines);
134         free(buf);
135 }
136
137 static void imap_logger_fetch(int direction, const char * str, size_t size) 
138 {
139         gchar *buf;
140         gchar **lines;
141         int i = 0;
142
143         if (size > 128 && !direction) {
144                 log_print(LOG_PROTOCOL, "IMAP4%c [FETCH data - %zd bytes]\n", direction?'>':'<', size);
145                 return;
146         }
147         
148         buf = malloc(size+1);
149         memset(buf, 0, size+1);
150         strncpy(buf, str, size);
151         buf[size] = '\0';
152         if (!strncmp(buf, "<<<<<<<", 7) 
153         ||  !strncmp(buf, ">>>>>>>", 7)) {
154                 free(buf);
155                 return;
156         }
157         while (strstr(buf, "\r"))
158                 *strstr(buf, "\r") = ' ';
159         while (strlen(buf) > 0 && buf[strlen(buf)-1] == '\n')
160                 buf[strlen(buf)-1] = '\0';
161
162         lines = g_strsplit(buf, "\n", -1);
163
164         if (direction != 0 || (buf[0] == '*' && buf[1] == ' ') || size < 32) {
165                 while (lines[i] && *lines[i]) {
166                         log_print(LOG_PROTOCOL, "IMAP4%c %s\n", direction?'>':'<', lines[i]);
167                         i++;
168                 }
169         } else {
170                 log_print(LOG_PROTOCOL, "IMAP4%c [data - %zd bytes]\n", direction?'>':'<', size);
171         }
172         g_strfreev(lines);
173         free(buf);
174 }
175
176 static void imap_logger_uid(int direction, const char * str, size_t size) 
177 {
178         gchar *buf;
179         gchar **lines;
180         int i = 0;
181
182         if (size > 8192) {
183                 log_print(LOG_PROTOCOL, "IMAP4%c [UID data - %zd bytes]\n", direction?'>':'<', size);
184                 return;
185         }
186         buf = malloc(size+1);
187         memset(buf, 0, size+1);
188         strncpy(buf, str, size);
189         buf[size] = '\0';
190         if (!strncmp(buf, "<<<<<<<", 7) 
191         ||  !strncmp(buf, ">>>>>>>", 7)) {
192                 free(buf);
193                 return;
194         }
195         while (strstr(buf, "\r"))
196                 *strstr(buf, "\r") = ' ';
197         while (strlen(buf) > 0 && buf[strlen(buf)-1] == '\n')
198                 buf[strlen(buf)-1] = '\0';
199
200         lines = g_strsplit(buf, "\n", -1);
201
202         while (lines[i] && *lines[i]) {
203                 int llen = strlen(lines[i]);
204                 if (llen < 64)
205                         log_print(LOG_PROTOCOL, "IMAP4%c %s\n", direction?'>':'<', lines[i]);
206                 else {
207                         gchar tmp[64];
208                         strncpy2(tmp, lines[i], 63);
209                         log_print(LOG_PROTOCOL, "IMAP4%c %s[... - %d bytes more]\n", direction?'>':'<', tmp,
210                                   llen-64);
211                 }
212                 i++;
213         }
214         g_strfreev(lines);
215         free(buf);
216 }
217
218 static void imap_logger_append(int direction, const char * str, size_t size) 
219 {
220         gchar *buf;
221         gchar **lines;
222         int i = 0;
223
224         if (size > 8192) {
225                 log_print(LOG_PROTOCOL, "IMAP4%c [APPEND data - %zd bytes]\n", direction?'>':'<', size);
226                 return;
227         } else if (direction == 0 && size > 64) {
228                 log_print(LOG_PROTOCOL, "IMAP4%c [APPEND data - %zd bytes]\n", direction?'>':'<', size);
229                 return;
230         } 
231         buf = malloc(size+1);
232         memset(buf, 0, size+1);
233         strncpy(buf, str, size);
234         buf[size] = '\0';
235         if (!strncmp(buf, "<<<<<<<", 7) 
236         ||  !strncmp(buf, ">>>>>>>", 7)) {
237                 free(buf);
238                 return;
239         }
240         while (strstr(buf, "\r"))
241                 *strstr(buf, "\r") = ' ';
242         while (strlen(buf) > 0 && buf[strlen(buf)-1] == '\n')
243                 buf[strlen(buf)-1] = '\0';
244
245         lines = g_strsplit(buf, "\n", -1);
246
247         if (direction == 0 || (buf[0] == '*' && buf[1] == ' ') || size < 64) {
248                 while (lines[i] && *lines[i]) {
249                         log_print(LOG_PROTOCOL, "IMAP4%c %s\n", direction?'>':'<', lines[i]);
250                         i++;
251                 }
252         } else {
253                 log_print(LOG_PROTOCOL, "IMAP4%c [data - %zd bytes]\n", direction?'>':'<', size);
254         }
255         g_strfreev(lines);
256         free(buf);
257 }
258
259 #define ETPAN_DEFAULT_NETWORK_TIMEOUT 60
260 gboolean etpan_skip_ssl_cert_check = FALSE;
261 extern void mailsasl_ref(void);
262
263 void imap_main_init(gboolean skip_ssl_cert_check)
264 {
265         int fd_thread_manager;
266         
267         etpan_skip_ssl_cert_check = skip_ssl_cert_check;
268         mailstream_network_delay.tv_sec = ETPAN_DEFAULT_NETWORK_TIMEOUT;
269         mailstream_network_delay.tv_usec = 0;
270         
271         mailstream_debug = 1;
272         mailstream_logger = imap_logger_cmd;
273         mailsasl_ref();
274         
275         imap_hash = chash_new(CHASH_COPYKEY, CHASH_DEFAULTSIZE);
276         session_hash = chash_new(CHASH_COPYKEY, CHASH_DEFAULTSIZE);
277         courier_workaround_hash = chash_new(CHASH_COPYKEY, CHASH_DEFAULTSIZE);
278         
279         thread_manager = etpan_thread_manager_new();
280         
281         fd_thread_manager = etpan_thread_manager_get_fd(thread_manager);
282         
283 #ifndef G_OS_WIN32
284         io_channel = g_io_channel_unix_new(fd_thread_manager);
285 #else
286         io_channel = g_io_channel_win32_new_fd(fd_thread_manager);
287 #endif
288         thread_manager_signal = g_io_add_watch_full(io_channel, 0, G_IO_IN,
289                                                     thread_manager_event,
290                                                     (gpointer) NULL,
291                                                     NULL);
292 }
293
294 void imap_main_set_timeout(int sec)
295 {
296         mailstream_network_delay.tv_sec = sec;
297         mailstream_network_delay.tv_usec = 0;
298 }
299
300 void imap_main_done(gboolean have_connectivity)
301 {
302         imap_disconnect_all(have_connectivity);
303         etpan_thread_manager_stop(thread_manager);
304 #if defined(__NetBSD__) || defined(__OpenBSD__) || defined(__FreeBSD__)
305         return;
306 #endif
307         etpan_thread_manager_join(thread_manager);
308         
309         g_source_remove(thread_manager_signal);
310         g_io_channel_unref(io_channel);
311         
312         etpan_thread_manager_free(thread_manager);
313         
314         chash_free(courier_workaround_hash);
315         chash_free(session_hash);
316         chash_free(imap_hash);
317 }
318
319 void imap_init(Folder * folder)
320 {
321         struct etpan_thread * thread;
322         chashdatum key;
323         chashdatum value;
324         
325         thread = etpan_thread_manager_get_thread(thread_manager);
326         
327         key.data = &folder;
328         key.len = sizeof(folder);
329         value.data = thread;
330         value.len = 0;
331         
332         chash_set(imap_hash, &key, &value, NULL);
333 }
334
335 void imap_done(Folder * folder)
336 {
337         struct etpan_thread * thread;
338         chashdatum key;
339         chashdatum value;
340         int r;
341         
342         key.data = &folder;
343         key.len = sizeof(folder);
344         
345         r = chash_get(imap_hash, &key, &value);
346         if (r < 0)
347                 return;
348         
349         thread = value.data;
350         
351         etpan_thread_unbind(thread);
352         
353         chash_delete(imap_hash, &key, NULL);
354         
355         debug_print("remove thread");
356 }
357
358 static struct etpan_thread * get_thread(Folder * folder)
359 {
360         struct etpan_thread * thread;
361         chashdatum key;
362         chashdatum value;
363         
364         key.data = &folder;
365         key.len = sizeof(folder);
366         
367         chash_get(imap_hash, &key, &value);
368         thread = value.data;
369         
370         return thread;
371 }
372
373 static mailimap * get_imap(Folder * folder)
374 {
375         mailimap * imap;
376         chashdatum key;
377         chashdatum value;
378         int r;
379         
380         key.data = &folder;
381         key.len = sizeof(folder);
382         
383         r = chash_get(session_hash, &key, &value);
384         if (r < 0)
385                 return NULL;
386         
387         imap = value.data;
388         debug_print("found imap %p\n", imap);
389         return imap;
390 }
391
392 static gboolean cb_show_error(gpointer data)
393 {
394         mainwindow_show_error();
395         return FALSE;
396 }
397
398 static void generic_cb(int cancelled, void * result, void * callback_data)
399 {
400         struct etpan_thread_op * op;
401         
402         op = (struct etpan_thread_op *) callback_data;
403
404         debug_print("generic_cb\n");
405         if (op->imap && op->imap->imap_response_info &&
406             op->imap->imap_response_info->rsp_alert) {
407                 log_error(LOG_PROTOCOL, "IMAP4< Alert: %s\n", 
408                         op->imap->imap_response_info->rsp_alert);
409                 g_timeout_add(10, cb_show_error, NULL);
410         } 
411         op->finished = 1;
412 }
413
414 static void threaded_run(Folder * folder, void * param, void * result,
415                          void (* func)(struct etpan_thread_op * ))
416 {
417         struct etpan_thread_op * op;
418         struct etpan_thread * thread;
419         
420         imap_folder_ref(folder);
421
422         op = etpan_thread_op_new();
423         
424         op->imap = get_imap(folder);
425         op->param = param;
426         op->result = result;
427         
428         op->cancellable = 0;
429         op->run = func;
430         op->callback = generic_cb;
431         op->callback_data = op;
432         op->cleanup = NULL;
433         
434         op->finished = 0;
435         
436         thread = get_thread(folder);
437         etpan_thread_op_schedule(thread, op);
438         
439         while (!op->finished) {
440                 gtk_main_iteration();
441         }
442         
443         etpan_thread_op_free(op);
444
445         imap_folder_unref(folder);
446 }
447
448
449 /* connect */
450
451 struct connect_param {
452         mailimap * imap;
453         PrefsAccount *account;
454         const char * server;
455         int port;
456 };
457
458 struct connect_result {
459         int error;
460 };
461
462 #define CHECK_IMAP() {                                          \
463         if (!param->imap) {                                     \
464                 result->error = MAILIMAP_ERROR_BAD_STATE;       \
465                 return;                                         \
466         }                                                       \
467 }
468
469 static void connect_run(struct etpan_thread_op * op)
470 {
471         int r;
472         struct connect_param * param;
473         struct connect_result * result;
474         
475         param = op->param;
476         result = op->result;
477         
478         CHECK_IMAP();
479
480         r = mailimap_socket_connect(param->imap,
481                                     param->server, param->port);
482         
483         result->error = r;
484 }
485
486
487 int imap_threaded_connect(Folder * folder, const char * server, int port)
488 {
489         struct connect_param param;
490         struct connect_result result;
491         chashdatum key;
492         chashdatum value;
493         mailimap * imap, * oldimap;
494         
495         oldimap = get_imap(folder);
496
497         imap = mailimap_new(0, NULL);
498         
499         if (oldimap) {
500                 debug_print("deleting old imap %p\n", oldimap);
501                 delete_imap(folder, oldimap);
502         }
503         
504         key.data = &folder;
505         key.len = sizeof(folder);
506         value.data = imap;
507         value.len = 0;
508         chash_set(session_hash, &key, &value, NULL);
509         
510         param.imap = imap;
511         param.server = server;
512         param.port = port;
513         
514         refresh_resolvers();
515         threaded_run(folder, &param, &result, connect_run);
516         
517         debug_print("connect ok %i with imap %p\n", result.error, imap);
518         
519         return result.error;
520 }
521
522 static int etpan_certificate_check(const unsigned char *certificate, int len, void *data)
523 {
524 #ifdef USE_GNUTLS
525         struct connect_param *param = (struct connect_param *)data;
526         gnutls_x509_crt cert = NULL;
527         gnutls_datum tmp;
528         
529         if (certificate == NULL || len < 0) {
530                 g_warning("no cert presented.\n");
531                 return 0;
532         }
533         
534         tmp.data = malloc(len);
535         memcpy(tmp.data, certificate, len);
536         tmp.size = len;
537         gnutls_x509_crt_init(&cert);
538         if (gnutls_x509_crt_import(cert, &tmp, GNUTLS_X509_FMT_DER) < 0) {
539                 g_warning("IMAP: can't get cert\n");
540                 return 0;
541         } else if (ssl_certificate_check(cert, (guint)-1, (gchar *)param->server,
542                         (gushort)param->port) == TRUE) {
543                 gnutls_x509_crt_deinit(cert);
544                 return 0;
545         } else {
546                 gnutls_x509_crt_deinit(cert);
547                 return -1;
548         }
549 #endif
550         return 0;
551 }
552
553 static void connect_ssl_context_cb(struct mailstream_ssl_context * ssl_context, void * data)
554 {
555 #ifdef USE_GNUTLS
556         PrefsAccount *account = (PrefsAccount *)data;
557         const gchar *cert_path = NULL;
558         const gchar *password = NULL;
559         gnutls_x509_crt x509 = NULL;
560         gnutls_x509_privkey pkey = NULL;
561
562         if (account->in_ssl_client_cert_file && *account->in_ssl_client_cert_file)
563                 cert_path = account->in_ssl_client_cert_file;
564         if (account->in_ssl_client_cert_pass && *account->in_ssl_client_cert_pass)
565                 password = account->in_ssl_client_cert_pass;
566         
567         if (mailstream_ssl_set_client_certificate_data(ssl_context, NULL, 0) < 0 ||
568             mailstream_ssl_set_client_private_key_data(ssl_context, NULL, 0) < 0)
569                 debug_print("Impossible to set the client certificate.\n");
570         x509 = ssl_certificate_get_x509_from_pem_file(cert_path);
571         pkey = ssl_certificate_get_pkey_from_pem_file(cert_path);
572         if (!(x509 && pkey)) {
573                 /* try pkcs12 format */
574                 ssl_certificate_get_x509_and_pkey_from_p12_file(cert_path, password, &x509, &pkey);
575         }
576         if (x509 && pkey) {
577                 unsigned char *x509_der = NULL, *pkey_der = NULL;
578                 size_t x509_len, pkey_len;
579                 
580                 x509_len = (size_t)gnutls_i2d_X509(x509, &x509_der);
581                 pkey_len = (size_t)gnutls_i2d_PrivateKey(pkey, &pkey_der);
582                 if (x509_len > 0 && pkey_len > 0) {
583                         if (mailstream_ssl_set_client_certificate_data(ssl_context, x509_der, x509_len) < 0 ||
584                             mailstream_ssl_set_client_private_key_data(ssl_context, pkey_der, pkey_len) < 0) 
585                                 log_error(LOG_PROTOCOL, _("Impossible to set the client certificate.\n"));
586                         g_free(x509_der);
587                         g_free(pkey_der);
588                 }
589                 gnutls_x509_crt_deinit(x509);
590                 gnutls_x509_privkey_deinit(pkey);
591         }
592 #endif
593 }
594
595 static void connect_ssl_run(struct etpan_thread_op * op)
596 {
597         int r;
598         struct connect_param * param;
599         struct connect_result * result;
600         
601         param = op->param;
602         result = op->result;
603         
604         CHECK_IMAP();
605
606         r = mailimap_ssl_connect_with_callback(param->imap,
607                                                 param->server, param->port,
608                                                 connect_ssl_context_cb, param->account);
609         result->error = r;
610 }
611
612 int imap_threaded_connect_ssl(Folder * folder, const char * server, int port)
613 {
614         struct connect_param param;
615         struct connect_result result;
616         chashdatum key;
617         chashdatum value;
618         mailimap * imap, * oldimap;
619         unsigned char *certificate = NULL;
620         int cert_len;
621         
622         oldimap = get_imap(folder);
623
624         imap = mailimap_new(0, NULL);
625         
626         if (oldimap) {
627                 debug_print("deleting old imap %p\n", oldimap);
628                 delete_imap(folder, oldimap);
629         }
630
631         key.data = &folder;
632         key.len = sizeof(folder);
633         value.data = imap;
634         value.len = 0;
635         chash_set(session_hash, &key, &value, NULL);
636         
637         param.imap = imap;
638         param.server = server;
639         param.port = port;
640         param.account = folder->account;
641
642         refresh_resolvers();
643         threaded_run(folder, &param, &result, connect_ssl_run);
644
645         if ((result.error == MAILIMAP_NO_ERROR_AUTHENTICATED ||
646              result.error == MAILIMAP_NO_ERROR_NON_AUTHENTICATED) && !etpan_skip_ssl_cert_check) {
647                 cert_len = (int)mailstream_ssl_get_certificate(imap->imap_stream, &certificate);
648                 if (etpan_certificate_check(certificate, cert_len, &param) < 0)
649                         return -1;
650                 if (certificate) 
651                         free(certificate); 
652         }
653         debug_print("connect %d with imap %p\n", result.error, imap);
654         
655         return result.error;
656 }
657
658 struct capa_param {
659         mailimap * imap;
660 };
661
662 struct capa_result {
663         int error;
664         struct mailimap_capability_data *caps;
665 };
666
667 static void capability_run(struct etpan_thread_op * op)
668 {
669         int r;
670         struct capa_param * param;
671         struct capa_result * result;
672         struct mailimap_capability_data *caps;
673
674         param = op->param;
675         result = op->result;
676         
677         CHECK_IMAP();
678
679         r = mailimap_capability(param->imap, &caps);
680         
681         result->error = r;
682         result->caps = (r == 0 ? caps : NULL);
683 }
684
685
686 struct mailimap_capability_data * imap_threaded_capability(Folder *folder, int *ok)
687 {
688         struct capa_param param;
689         struct capa_result result;
690         mailimap *imap;
691         
692         imap = get_imap(folder);
693         
694         param.imap = imap;
695         
696         threaded_run(folder, &param, &result, capability_run);
697         
698         debug_print("capa %d\n", result.error);
699         
700         if (ok)
701                 *ok = result.error;
702
703         return result.caps;
704         
705 }
706         
707 struct disconnect_param {
708         mailimap * imap;
709 };
710
711 struct disconnect_result {
712         int error;
713 };
714
715 static void disconnect_run(struct etpan_thread_op * op)
716 {
717         int r;
718         struct disconnect_param * param;
719         struct disconnect_result * result;
720         
721         param = op->param;
722         result = op->result;
723         
724         CHECK_IMAP();
725
726         r = mailimap_logout(param->imap);
727         
728         result->error = r;
729 }
730
731 void imap_threaded_disconnect(Folder * folder)
732 {
733         struct connect_param param;
734         struct connect_result result;
735         mailimap * imap;
736         
737         imap = get_imap(folder);
738         if (imap == NULL) {
739                 debug_print("was disconnected\n");
740                 return;
741         }
742         
743         param.imap = imap;
744         
745         threaded_run(folder, &param, &result, disconnect_run);
746         
747         if (imap == get_imap(folder)) {
748                 debug_print("deleting old imap %p\n", imap);
749                 delete_imap(folder, imap);
750         } else {
751                 debug_print("imap already deleted %p\n", imap);
752         }
753         
754         debug_print("disconnect ok\n");
755 }
756
757
758 struct list_param {
759         mailimap * imap;
760         const char * base;
761         const char * wildcard;
762         gboolean sub_only;
763 };
764
765 struct list_result {
766         int error;
767         clist * list;
768 };
769
770 static void list_run(struct etpan_thread_op * op)
771 {
772         struct list_param * param;
773         struct list_result * result;
774         int r;
775         clist * list;
776         
777         param = op->param;
778         result = op->result;
779
780         CHECK_IMAP();
781
782         list = NULL;
783         
784         if (param->base == NULL || param->wildcard == NULL) {
785                 result->list = list;
786                 result->error = -1;
787                 debug_print("no base or wildcard (%p %p)\n", param->base, param->wildcard);
788                 return;
789         }
790         if (param->sub_only)
791                 r = mailimap_lsub(param->imap, param->base,
792                           param->wildcard, &list);
793         else
794                 r = mailimap_list(param->imap, param->base,
795                           param->wildcard, &list);
796         result->error = r;
797         result->list = list;
798         debug_print("imap list run - end\n");
799 }
800
801 int imap_threaded_list(Folder * folder, const char * base,
802                        const char * wildcard,
803                        clist ** p_result)
804 {
805         struct list_param param;
806         struct list_result result;
807         
808         debug_print("imap list - begin\n");
809         
810         param.imap = get_imap(folder);
811         param.base = base;
812         param.wildcard = wildcard;
813         param.sub_only = FALSE;
814
815         threaded_run(folder, &param, &result, list_run);
816         
817         * p_result = result.list;
818         
819         debug_print("imap list - end %p\n", result.list);
820         
821         return result.error;
822 }
823
824 int imap_threaded_lsub(Folder * folder, const char * base,
825                        const char * wildcard,
826                        clist ** p_result)
827 {
828         struct list_param param;
829         struct list_result result;
830         
831         debug_print("imap lsub - begin\n");
832         
833         param.imap = get_imap(folder);
834         param.base = base;
835         param.wildcard = wildcard;
836         param.sub_only = TRUE;
837         
838         threaded_run(folder, &param, &result, list_run);
839         
840         * p_result = result.list;
841         
842         debug_print("imap lsub - end %p\n", result.list);
843         
844         return result.error;
845 }
846
847 struct subscribe_param {
848         mailimap * imap;
849         const char * mb;
850         gboolean subscribe;
851 };
852
853 struct subscribe_result {
854         int error;
855 };
856
857 static void subscribe_run(struct etpan_thread_op * op)
858 {
859         struct subscribe_param * param;
860         struct subscribe_result * result;
861         int r;
862         
863         param = op->param;
864         result = op->result;
865
866         CHECK_IMAP();
867
868         if (param->mb == NULL) {
869                 result->error = -1;
870                 debug_print("no mb\n");
871                 return;
872         }
873         if (param->subscribe)
874                 r = mailimap_subscribe(param->imap, param->mb);
875         else
876                 r = mailimap_unsubscribe(param->imap, param->mb);
877         result->error = r;
878         debug_print("imap %ssubscribe run - end %d\n", param->subscribe?"":"un", r);
879 }
880
881 int imap_threaded_subscribe(Folder * folder, const char * mb,
882                        gboolean subscribe)
883 {
884         struct subscribe_param param;
885         struct subscribe_result result;
886         
887         debug_print("imap list - begin\n");
888         
889         param.imap = get_imap(folder);
890         param.mb = mb;
891         param.subscribe = subscribe;
892
893         threaded_run(folder, &param, &result, subscribe_run);
894         
895         return result.error;
896 }
897
898 struct login_param {
899         mailimap * imap;
900         const char * login;
901         const char * password;
902         const char * type;
903         const char * server;
904 };
905
906 struct login_result {
907         int error;
908 };
909
910 static void login_run(struct etpan_thread_op * op)
911 {
912         struct login_param * param;
913         struct login_result * result;
914         int r;
915 #ifdef DISABLE_LOG_DURING_LOGIN
916         int old_debug;
917 #endif
918         
919         param = op->param;
920         result = op->result;
921
922         CHECK_IMAP();
923
924 #ifdef DISABLE_LOG_DURING_LOGIN
925         old_debug = mailstream_debug;
926         mailstream_debug = 0;
927 #endif
928         if (!strcmp(param->type, "LOGIN"))
929                 r = mailimap_login(param->imap,
930                            param->login, param->password);
931         else if (!strcmp(param->type, "GSSAPI"))
932                 r = mailimap_authenticate(param->imap,
933                         param->type, param->server, NULL, NULL,
934                         param->login, param->login,
935                         param->password, NULL);
936         else 
937                 r = mailimap_authenticate(param->imap,
938                         param->type, NULL, NULL, NULL,
939                         param->login, param->login,
940                         param->password, NULL);
941 #ifdef DISABLE_LOG_DURING_LOGIN
942         mailstream_debug = old_debug;
943 #endif
944         
945         result->error = r;
946         if (param->imap->imap_response)
947                 imap_logger_cmd(0, param->imap->imap_response, strlen(param->imap->imap_response));
948         debug_print("imap login run - end %i\n", r);
949 }
950
951 int imap_threaded_login(Folder * folder,
952                         const char * login, const char * password,
953                         const char * type)
954 {
955         struct login_param param;
956         struct login_result result;
957         
958         debug_print("imap login - begin\n");
959         
960         param.imap = get_imap(folder);
961         param.login = login;
962         param.password = password;
963         param.type = type;
964         if (folder && folder->account)
965                 param.server = folder->account->recv_server;
966         else
967                 param.server = NULL;
968
969         threaded_run(folder, &param, &result, login_run);
970         
971         debug_print("imap login - end\n");
972         
973         return result.error;
974 }
975
976
977 struct status_param {
978         mailimap * imap;
979         const char * mb;
980         struct mailimap_status_att_list * status_att_list;
981 };
982
983 struct status_result {
984         int error;
985         struct mailimap_mailbox_data_status * data_status;
986 };
987
988 static void status_run(struct etpan_thread_op * op)
989 {
990         struct status_param * param;
991         struct status_result * result;
992         int r;
993         
994         param = op->param;
995         result = op->result;
996         
997         CHECK_IMAP();
998
999         r = mailimap_status(param->imap, param->mb,
1000                             param->status_att_list,
1001                             &result->data_status);
1002         
1003         result->error = r;
1004         debug_print("imap status run - end %i\n", r);
1005 }
1006
1007 int imap_threaded_status(Folder * folder, const char * mb,
1008                          struct mailimap_mailbox_data_status ** data_status,
1009                          guint mask)
1010 {
1011         struct status_param param;
1012         struct status_result result;
1013         struct mailimap_status_att_list * status_att_list;
1014         
1015         debug_print("imap status - begin\n");
1016         
1017         status_att_list = mailimap_status_att_list_new_empty();
1018         if (mask & 1 << 0) {
1019                 mailimap_status_att_list_add(status_att_list,
1020                                      MAILIMAP_STATUS_ATT_MESSAGES);
1021         }
1022         if (mask & 1 << 1) {
1023                 mailimap_status_att_list_add(status_att_list,
1024                                      MAILIMAP_STATUS_ATT_RECENT);
1025         }
1026         if (mask & 1 << 2) {
1027                 mailimap_status_att_list_add(status_att_list,
1028                                      MAILIMAP_STATUS_ATT_UIDNEXT);
1029         }
1030         if (mask & 1 << 3) {
1031                 mailimap_status_att_list_add(status_att_list,
1032                                      MAILIMAP_STATUS_ATT_UIDVALIDITY);
1033         }
1034         if (mask & 1 << 4) {
1035                 mailimap_status_att_list_add(status_att_list,
1036                                      MAILIMAP_STATUS_ATT_UNSEEN);
1037         }
1038         param.imap = get_imap(folder);
1039         param.mb = mb;
1040         param.status_att_list = status_att_list;
1041         
1042         threaded_run(folder, &param, &result, status_run);
1043         
1044         debug_print("imap status - end\n");
1045         
1046         * data_status = result.data_status;
1047         
1048         mailimap_status_att_list_free(status_att_list);
1049         
1050         return result.error;
1051 }
1052
1053
1054
1055 struct noop_param {
1056         mailimap * imap;
1057 };
1058
1059 struct noop_result {
1060         int error;
1061 };
1062
1063 static void noop_run(struct etpan_thread_op * op)
1064 {
1065         struct noop_param * param;
1066         struct noop_result * result;
1067         int r;
1068         
1069         param = op->param;
1070         result = op->result;
1071
1072         CHECK_IMAP();
1073
1074         r = mailimap_noop(param->imap);
1075         
1076         result->error = r;
1077         debug_print("imap noop run - end %i\n", r);
1078 }
1079
1080 int imap_threaded_noop(Folder * folder, unsigned int * p_exists, 
1081                        unsigned int *p_recent, 
1082                        unsigned int *p_expunge,
1083                        unsigned int *p_unseen,
1084                        unsigned int *p_uidnext,
1085                        unsigned int *p_uidval)
1086 {
1087         struct noop_param param;
1088         struct noop_result result;
1089         mailimap * imap;
1090         
1091         debug_print("imap noop - begin\n");
1092         
1093         imap = get_imap(folder);
1094         param.imap = imap;
1095
1096         threaded_run(folder, &param, &result, noop_run);
1097         
1098         if (result.error == 0 && imap && imap->imap_selection_info != NULL) {
1099                 * p_exists = imap->imap_selection_info->sel_exists;
1100                 * p_recent = imap->imap_selection_info->sel_recent;
1101                 * p_unseen = imap->imap_selection_info->sel_unseen;
1102                 * p_uidnext = imap->imap_selection_info->sel_uidnext;
1103                 * p_uidval = imap->imap_selection_info->sel_uidvalidity;
1104         } else {
1105                 * p_exists = 0;
1106                 * p_recent = 0;
1107                 * p_unseen = 0;
1108                 * p_uidnext = 0;
1109                 * p_uidval = 0;
1110         }
1111         if (result.error == 0 && imap && imap->imap_response_info != NULL &&
1112             imap->imap_response_info->rsp_expunged != NULL) {
1113                 * p_expunge = clist_count(imap->imap_response_info->rsp_expunged);
1114         } else {
1115                 * p_expunge = 0;
1116         }       
1117         debug_print("imap noop - end [EXISTS %d RECENT %d EXPUNGE %d UNSEEN %d UIDNEXT %d UIDVAL %d]\n",
1118                 *p_exists, *p_recent, *p_expunge, *p_unseen,
1119                 *p_uidnext, *p_uidval);
1120         
1121         return result.error;
1122 }
1123
1124
1125 struct starttls_result {
1126         int error;
1127 };
1128
1129 static void starttls_run(struct etpan_thread_op * op)
1130 {
1131         struct connect_param * param;
1132         struct starttls_result * result;
1133         int r;
1134
1135         param = op->param;
1136         result = op->result;
1137
1138         CHECK_IMAP();
1139
1140         r = mailimap_starttls(param->imap);
1141         
1142         result->error = r;
1143         debug_print("imap starttls run - end %i\n", r);
1144         
1145         if (r == 0) {
1146                 mailimap *imap = param->imap;
1147                 mailstream_low *plain_low = NULL;
1148                 mailstream_low *tls_low = NULL;
1149                 int fd = -1;
1150                 
1151                 plain_low = mailstream_get_low(imap->imap_stream);
1152                 fd = mailstream_low_get_fd(plain_low);
1153                 if (fd == -1) {
1154                         debug_print("imap starttls run - can't get fd\n");
1155                         result->error = MAILIMAP_ERROR_STREAM;
1156                         return;
1157                 }
1158
1159                 tls_low = mailstream_low_tls_open_with_callback(fd, connect_ssl_context_cb, param->account);
1160                 if (tls_low == NULL) {
1161                         debug_print("imap starttls run - can't tls_open\n");
1162                         result->error = MAILIMAP_ERROR_STREAM;
1163                         return;
1164                 }
1165                 mailstream_low_free(plain_low);
1166                 mailstream_set_low(imap->imap_stream, tls_low);
1167         }
1168 }
1169
1170 int imap_threaded_starttls(Folder * folder, const gchar *host, int port)
1171 {
1172         struct connect_param param;
1173         struct starttls_result result;
1174         int cert_len;
1175         unsigned char *certificate = NULL;
1176         
1177         debug_print("imap starttls - begin\n");
1178         
1179         param.imap = get_imap(folder);
1180         param.server = host;
1181         param.port = port;
1182         param.account = folder->account;
1183
1184         threaded_run(folder, &param, &result, starttls_run);
1185         
1186         debug_print("imap starttls - end\n");
1187
1188         if (result.error == 0 && param.imap && !etpan_skip_ssl_cert_check) {
1189                 cert_len = (int)mailstream_ssl_get_certificate(param.imap->imap_stream, &certificate);
1190                 if (etpan_certificate_check(certificate, cert_len, &param) < 0)
1191                         result.error = MAILIMAP_ERROR_STREAM;
1192                 if (certificate) 
1193                         free(certificate); 
1194         }       
1195         return result.error;
1196 }
1197
1198
1199
1200 struct create_param {
1201         mailimap * imap;
1202         const char * mb;
1203 };
1204
1205 struct create_result {
1206         int error;
1207 };
1208
1209 static void create_run(struct etpan_thread_op * op)
1210 {
1211         struct create_param * param;
1212         struct create_result * result;
1213         int r;
1214         
1215         param = op->param;
1216         result = op->result;
1217
1218         CHECK_IMAP();
1219
1220         r = mailimap_create(param->imap, param->mb);
1221         
1222         result->error = r;
1223         debug_print("imap create run - end %i\n", r);
1224 }
1225
1226 int imap_threaded_create(Folder * folder, const char * mb)
1227 {
1228         struct create_param param;
1229         struct create_result result;
1230         
1231         debug_print("imap create - begin\n");
1232         
1233         param.imap = get_imap(folder);
1234         param.mb = mb;
1235         
1236         threaded_run(folder, &param, &result, create_run);
1237         
1238         debug_print("imap create - end\n");
1239         
1240         return result.error;
1241 }
1242
1243
1244
1245
1246 struct rename_param {
1247         mailimap * imap;
1248         const char * mb;
1249         const char * new_name;
1250 };
1251
1252 struct rename_result {
1253         int error;
1254 };
1255
1256 static void rename_run(struct etpan_thread_op * op)
1257 {
1258         struct rename_param * param;
1259         struct rename_result * result;
1260         int r;
1261         
1262         param = op->param;
1263         result = op->result;
1264
1265         CHECK_IMAP();
1266
1267         r = mailimap_rename(param->imap, param->mb, param->new_name);
1268         
1269         result->error = r;
1270         debug_print("imap rename run - end %i\n", r);
1271 }
1272
1273 int imap_threaded_rename(Folder * folder,
1274                          const char * mb, const char * new_name)
1275 {
1276         struct rename_param param;
1277         struct rename_result result;
1278         
1279         debug_print("imap rename - begin\n");
1280         
1281         param.imap = get_imap(folder);
1282         param.mb = mb;
1283         param.new_name = new_name;
1284         
1285         threaded_run(folder, &param, &result, rename_run);
1286         
1287         debug_print("imap rename - end\n");
1288         
1289         return result.error;
1290 }
1291
1292
1293
1294
1295 struct delete_param {
1296         mailimap * imap;
1297         const char * mb;
1298 };
1299
1300 struct delete_result {
1301         int error;
1302 };
1303
1304 static void delete_run(struct etpan_thread_op * op)
1305 {
1306         struct delete_param * param;
1307         struct delete_result * result;
1308         int r;
1309         
1310         param = op->param;
1311         result = op->result;
1312
1313         CHECK_IMAP();
1314
1315         r = mailimap_delete(param->imap, param->mb);
1316         
1317         result->error = r;
1318         debug_print("imap delete run - end %i\n", r);
1319 }
1320
1321 int imap_threaded_delete(Folder * folder, const char * mb)
1322 {
1323         struct delete_param param;
1324         struct delete_result result;
1325         
1326         debug_print("imap delete - begin\n");
1327         
1328         param.imap = get_imap(folder);
1329         param.mb = mb;
1330         
1331         threaded_run(folder, &param, &result, delete_run);
1332         
1333         debug_print("imap delete - end\n");
1334         
1335         return result.error;
1336 }
1337
1338
1339
1340 struct select_param {
1341         mailimap * imap;
1342         const char * mb;
1343 };
1344
1345 struct select_result {
1346         int error;
1347 };
1348
1349 static void select_run(struct etpan_thread_op * op)
1350 {
1351         struct select_param * param;
1352         struct select_result * result;
1353         int r;
1354         
1355         param = op->param;
1356         result = op->result;
1357
1358         CHECK_IMAP();
1359
1360         r = mailimap_select(param->imap, param->mb);
1361         
1362         result->error = r;
1363         debug_print("imap select run - end %i\n", r);
1364 }
1365
1366 int imap_threaded_select(Folder * folder, const char * mb,
1367                          gint * exists, gint * recent, gint * unseen,
1368                          guint32 * uid_validity,gint *can_create_flags,
1369                          GSList **ok_flags)
1370 {
1371         struct select_param param;
1372         struct select_result result;
1373         mailimap * imap;
1374
1375         debug_print("imap select - begin\n");
1376         
1377         imap = get_imap(folder);
1378         param.imap = imap;
1379         param.mb = mb;
1380         
1381         threaded_run(folder, &param, &result, select_run);
1382         
1383         if (result.error != MAILIMAP_NO_ERROR)
1384                 return result.error;
1385         
1386         if (!imap || imap->imap_selection_info == NULL)
1387                 return MAILIMAP_ERROR_PARSE;
1388         
1389         * exists = imap->imap_selection_info->sel_exists;
1390         * recent = imap->imap_selection_info->sel_recent;
1391         * unseen = imap->imap_selection_info->sel_unseen;
1392         * uid_validity = imap->imap_selection_info->sel_uidvalidity;
1393         * can_create_flags = FALSE;
1394
1395         if (imap->imap_selection_info->sel_perm_flags) {
1396                 GSList *t_flags = NULL;
1397                 clistiter *cur = NULL;
1398                 if (imap->imap_selection_info->sel_perm_flags)
1399                         cur = clist_begin(imap->imap_selection_info->sel_perm_flags);
1400
1401                 for (; cur; cur = clist_next(cur)) {
1402                         struct mailimap_flag_perm *flag = (struct mailimap_flag_perm *)clist_content(cur);
1403                         if (flag->fl_type == MAILIMAP_FLAG_PERM_ALL)
1404                                 *can_create_flags = TRUE;
1405                         else if (flag->fl_flag && 
1406                                         flag->fl_flag->fl_type == 6 &&
1407                                         !strcmp(flag->fl_flag->fl_data.fl_extension, "*"))
1408                                 *can_create_flags = TRUE; 
1409                         if (flag->fl_flag && ok_flags) {
1410                                 MsgPermFlags c_flag = 0;
1411                                 switch (flag->fl_flag->fl_type) {
1412                                 case MAILIMAP_FLAG_ANSWERED:
1413                                         c_flag = IMAP_FLAG_ANSWERED;
1414                                         break;
1415                                 case MAILIMAP_FLAG_FLAGGED:
1416                                         c_flag = IMAP_FLAG_FLAGGED;
1417                                         break;
1418                                 case MAILIMAP_FLAG_DELETED:
1419                                         c_flag = IMAP_FLAG_DELETED;
1420                                         break;
1421                                 case MAILIMAP_FLAG_DRAFT:
1422                                         c_flag = IMAP_FLAG_DRAFT;
1423                                         break;
1424                                 case MAILIMAP_FLAG_SEEN:
1425                                         c_flag = IMAP_FLAG_SEEN;
1426                                         break;
1427                                 case MAILIMAP_FLAG_KEYWORD:
1428                                         if (!strcasecmp(flag->fl_flag->fl_data.fl_keyword, RTAG_FORWARDED))
1429                                                 c_flag = IMAP_FLAG_FORWARDED;
1430                                         if (!strcasecmp(flag->fl_flag->fl_data.fl_keyword, RTAG_JUNK))
1431                                                 c_flag = IMAP_FLAG_SPAM;
1432                                         if (!strcasecmp(flag->fl_flag->fl_data.fl_keyword, RTAG_NON_JUNK) ||
1433                                             !strcasecmp(flag->fl_flag->fl_data.fl_keyword, RTAG_NO_JUNK) ||
1434                                             !strcasecmp(flag->fl_flag->fl_data.fl_keyword, RTAG_NOT_JUNK))
1435                                                 c_flag = IMAP_FLAG_HAM;
1436                                         break;
1437                                 default:
1438                                         break;
1439                                 }
1440                                 if (c_flag != 0) {
1441                                         t_flags = g_slist_prepend(t_flags, 
1442                                                 GUINT_TO_POINTER(c_flag));
1443                                 }
1444                         }
1445                 }
1446                 if (ok_flags)
1447                         *ok_flags = t_flags;
1448         }
1449         debug_print("imap select - end\n");
1450         
1451         return result.error;
1452 }
1453
1454 static void close_run(struct etpan_thread_op * op)
1455 {
1456         struct select_param * param;
1457         struct select_result * result;
1458         int r;
1459         
1460         param = op->param;
1461         result = op->result;
1462
1463         CHECK_IMAP();
1464
1465         r = mailimap_close(param->imap);
1466         
1467         result->error = r;
1468         debug_print("imap close run - end %i\n", r);
1469 }
1470
1471 int imap_threaded_close(Folder * folder)
1472 {
1473         struct select_param param;
1474         struct select_result result;
1475         mailimap * imap;
1476         
1477         debug_print("imap close - begin\n");
1478         
1479         imap = get_imap(folder);
1480         param.imap = imap;
1481         
1482         threaded_run(folder, &param, &result, close_run);
1483         
1484         if (result.error != MAILIMAP_NO_ERROR)
1485                 return result.error;
1486         
1487         debug_print("imap close - end\n");
1488         
1489         return result.error;
1490 }
1491
1492 struct examine_param {
1493         mailimap * imap;
1494         const char * mb;
1495 };
1496
1497 struct examine_result {
1498         int error;
1499 };
1500
1501 static void examine_run(struct etpan_thread_op * op)
1502 {
1503         struct examine_param * param;
1504         struct examine_result * result;
1505         int r;
1506         
1507         param = op->param;
1508         result = op->result;
1509
1510         CHECK_IMAP();
1511
1512         r = mailimap_examine(param->imap, param->mb);
1513         
1514         result->error = r;
1515         debug_print("imap examine run - end %i\n", r);
1516 }
1517
1518 int imap_threaded_examine(Folder * folder, const char * mb,
1519                           gint * exists, gint * recent, gint * unseen,
1520                           guint32 * uid_validity)
1521 {
1522         struct examine_param param;
1523         struct examine_result result;
1524         mailimap * imap;
1525         
1526         debug_print("imap examine - begin\n");
1527         
1528         imap = get_imap(folder);
1529         param.imap = imap;
1530         param.mb = mb;
1531         
1532         threaded_run(folder, &param, &result, examine_run);
1533         
1534         if (result.error != MAILIMAP_NO_ERROR)
1535                 return result.error;
1536         
1537         if (!imap || imap->imap_selection_info == NULL)
1538                 return MAILIMAP_ERROR_PARSE;
1539         
1540         * exists = imap->imap_selection_info->sel_exists;
1541         * recent = imap->imap_selection_info->sel_recent;
1542         * unseen = imap->imap_selection_info->sel_unseen;
1543         * uid_validity = imap->imap_selection_info->sel_uidvalidity;
1544         
1545         debug_print("imap examine - end\n");
1546         
1547         return result.error;
1548 }
1549
1550
1551
1552
1553 struct search_param {
1554         mailimap * imap;
1555         int type;
1556         struct mailimap_set * set;
1557         IMAPSearchKey* key;
1558 };
1559
1560 struct search_result {
1561         int error;
1562         clist * search_result;
1563 };
1564
1565 static struct mailimap_set_item *sc_mailimap_set_item_copy(struct mailimap_set_item *orig)
1566 {
1567         return mailimap_set_item_new(orig->set_first, orig->set_last);
1568 }
1569
1570 static struct mailimap_set *sc_mailimap_set_copy(struct mailimap_set *orig)
1571 {
1572         clist *list = orig ? orig->set_list : NULL;
1573         clist *newlist = clist_new();
1574         clistiter *cur;
1575         
1576         if (!orig)
1577                 return NULL;
1578         for (cur = clist_begin(list); cur; cur = clist_next(cur))
1579                 clist_append(newlist, 
1580                         sc_mailimap_set_item_copy(
1581                         (struct mailimap_set_item *)clist_content(cur)));
1582         return mailimap_set_new(newlist);
1583 }
1584
1585 static void search_run(struct etpan_thread_op * op)
1586 {
1587         struct search_param * param;
1588         struct search_result * result;
1589         int r;
1590         struct mailimap_search_key * key = NULL;
1591         struct mailimap_search_key * uid_key = NULL;
1592         struct mailimap_search_key * search_type_key = NULL;
1593         clist * search_result;
1594         static const char *charset = NULL;
1595
1596         param = op->param;
1597         result = op->result;
1598
1599         CHECK_IMAP();
1600
1601         /* we copy the mailimap_set because freeing the key is recursive */
1602         if (param->set != NULL) {
1603                 uid_key = mailimap_search_key_new_uid(sc_mailimap_set_copy(param->set));
1604         } else if (param->type == IMAP_SEARCH_TYPE_SIMPLE) {
1605                 uid_key = mailimap_search_key_new_all();
1606         }
1607         switch (param->type) {
1608         case IMAP_SEARCH_TYPE_SIMPLE:
1609                 search_type_key = NULL;
1610                 break;
1611         case IMAP_SEARCH_TYPE_SEEN:
1612                 search_type_key = imap_search_new(IMAP_SEARCH_CRITERIA_READ, NULL, NULL, 0);
1613                 break;
1614         case IMAP_SEARCH_TYPE_UNSEEN:
1615                 search_type_key = imap_search_new(IMAP_SEARCH_CRITERIA_UNREAD, NULL, NULL, 0);
1616                 break;
1617         case IMAP_SEARCH_TYPE_ANSWERED:
1618                 search_type_key = imap_search_new(IMAP_SEARCH_CRITERIA_REPLIED, NULL, NULL, 0);
1619                 break;
1620         case IMAP_SEARCH_TYPE_FLAGGED:
1621                 search_type_key = imap_search_new(IMAP_SEARCH_CRITERIA_MARKED, NULL, NULL, 0);
1622                 break;
1623         case IMAP_SEARCH_TYPE_DELETED:
1624                 search_type_key = imap_search_new(IMAP_SEARCH_CRITERIA_DELETED, NULL, NULL, 0);
1625                 break;
1626         case IMAP_SEARCH_TYPE_FORWARDED:
1627                 search_type_key = imap_search_new(IMAP_SEARCH_CRITERIA_TAG, NULL, RTAG_FORWARDED, 0);
1628                 break;
1629         case IMAP_SEARCH_TYPE_SPAM:
1630                 search_type_key = imap_search_new(IMAP_SEARCH_CRITERIA_TAG, NULL, RTAG_JUNK, 0);
1631                 break;
1632         case IMAP_SEARCH_TYPE_KEYED:
1633                 charset = "UTF-8";
1634                 search_type_key = param->key;
1635                 break;
1636         }
1637         
1638         if (search_type_key != NULL) {
1639                 if (param->set != NULL) {
1640                         key = mailimap_search_key_new_multiple_empty();
1641                         mailimap_search_key_multiple_add(key, search_type_key);
1642                         mailimap_search_key_multiple_add(key, uid_key);
1643                 } else {
1644                         key = search_type_key;
1645                 }
1646         } else if (uid_key != NULL) {
1647                 key = uid_key;
1648         }
1649         
1650         if (key == NULL) {
1651                 g_warning("no key!");
1652                 result = op->result;
1653                 result->error = -1;
1654                 result->search_result = NULL;
1655         } else {
1656                 mailstream_logger = imap_logger_uid;
1657
1658                 r = mailimap_uid_search(param->imap, charset, key, &search_result);
1659
1660                 mailstream_logger = imap_logger_cmd;
1661
1662                 /* free the key (with the imapset) */
1663                 mailimap_search_key_free(key);
1664
1665                 result->error = r;
1666                 result->search_result = search_result;
1667         }
1668         debug_print("imap search run - end %i\n", result->error);
1669 }
1670
1671 int imap_threaded_search(Folder * folder, int search_type, IMAPSearchKey* key,
1672                          struct mailimap_set * set, clist ** search_result)
1673 {
1674         struct search_param param;
1675         struct search_result result;
1676         mailimap * imap;
1677         
1678         debug_print("imap search - begin\n");
1679
1680         imap = get_imap(folder);
1681         param.imap = imap;
1682         param.set = set;
1683         param.type = search_type;
1684         param.key = key;
1685
1686         threaded_run(folder, &param, &result, search_run);
1687         
1688         if (result.error != MAILIMAP_NO_ERROR)
1689                 return result.error;
1690         
1691         debug_print("imap search - end\n");
1692         
1693         * search_result = result.search_result;
1694         
1695         return result.error;
1696 }
1697
1698
1699 struct _IMAPSearchKey {
1700         struct mailimap_search_key* key;
1701 };
1702
1703 IMAPSearchKey*  imap_search_new(gint             criteria, 
1704                                 const gchar     *header,
1705                                 const gchar     *expr,
1706                                 int              value)
1707 {
1708         char* sk_bcc = NULL;
1709         struct mailimap_date* sk_before = NULL;
1710         char* sk_body = NULL;
1711         char* sk_cc = NULL;
1712         char* sk_from = NULL;
1713         char* sk_keyword = NULL;
1714         struct mailimap_date* sk_on = NULL;
1715         struct mailimap_date* sk_since = NULL;
1716         char* sk_subject = NULL;
1717         char* sk_text = NULL;
1718         char* sk_to = NULL;
1719         char* sk_unkeyword = NULL;
1720         char* sk_header_name = NULL;
1721         char* sk_header_value = NULL;
1722         uint32_t sk_larger = 0;
1723         struct mailimap_search_key* sk_not = NULL;
1724         struct mailimap_search_key* sk_or1 = NULL;
1725         struct mailimap_search_key* sk_or2 = NULL;
1726         struct mailimap_date* sk_sentbefore = NULL;
1727         struct mailimap_date* sk_senton = NULL;
1728         struct mailimap_date* sk_sentsince = NULL;
1729         uint32_t sk_smaller = 0;
1730         struct mailimap_set* sk_uid = NULL;
1731         struct mailimap_set* sk_set = NULL;
1732         clist* sk_multiple = NULL;
1733         int etpan_matcher_type;
1734
1735         switch (criteria) {
1736         case IMAP_SEARCH_CRITERIA_ALL: etpan_matcher_type = MAILIMAP_SEARCH_KEY_ALL; break;
1737         case IMAP_SEARCH_CRITERIA_READ: etpan_matcher_type = MAILIMAP_SEARCH_KEY_SEEN; break;
1738         case IMAP_SEARCH_CRITERIA_UNREAD: etpan_matcher_type = MAILIMAP_SEARCH_KEY_UNSEEN; break;
1739         case IMAP_SEARCH_CRITERIA_NEW: etpan_matcher_type = MAILIMAP_SEARCH_KEY_NEW; break;
1740         case IMAP_SEARCH_CRITERIA_MARKED: etpan_matcher_type = MAILIMAP_SEARCH_KEY_FLAGGED; break;
1741         case IMAP_SEARCH_CRITERIA_REPLIED: etpan_matcher_type = MAILIMAP_SEARCH_KEY_ANSWERED; break;
1742         case IMAP_SEARCH_CRITERIA_DELETED: etpan_matcher_type = MAILIMAP_SEARCH_KEY_DELETED; break;
1743
1744         case IMAP_SEARCH_CRITERIA_TAG:
1745                 sk_keyword = strdup(expr);
1746                 etpan_matcher_type = MAILIMAP_SEARCH_KEY_KEYWORD;
1747                 break;
1748
1749         case IMAP_SEARCH_CRITERIA_SUBJECT:
1750                 etpan_matcher_type = MAILIMAP_SEARCH_KEY_SUBJECT;
1751                 sk_subject = strdup(expr);
1752                 break;
1753
1754         case IMAP_SEARCH_CRITERIA_TO:
1755                 etpan_matcher_type = MAILIMAP_SEARCH_KEY_TO;
1756                 sk_to = strdup(expr);
1757                 break;
1758
1759         case IMAP_SEARCH_CRITERIA_CC:
1760                 etpan_matcher_type = MAILIMAP_SEARCH_KEY_CC;
1761                 sk_cc = strdup(expr);
1762                 break;
1763
1764         case IMAP_SEARCH_CRITERIA_AGE_GREATER:
1765         case IMAP_SEARCH_CRITERIA_AGE_LOWER:
1766                 {
1767                         struct tm tm;
1768                         time_t limit = time(NULL) - 60 * 60 * 24 * value;
1769
1770                         tzset();
1771                         localtime_r(&limit, &tm);
1772                         if (criteria == IMAP_SEARCH_CRITERIA_AGE_GREATER) {
1773                                 etpan_matcher_type = MAILIMAP_SEARCH_KEY_SENTBEFORE;
1774                                 sk_sentbefore = mailimap_date_new(tm.tm_mday, tm.tm_mon, tm.tm_year + 1900);
1775                         } else {
1776                                 etpan_matcher_type = MAILIMAP_SEARCH_KEY_SENTSINCE;
1777                                 sk_sentsince = mailimap_date_new(tm.tm_mday, tm.tm_mon, tm.tm_year + 1900);
1778                         }
1779                         break;
1780                 }
1781
1782         case IMAP_SEARCH_CRITERIA_BODY:
1783                 etpan_matcher_type = MAILIMAP_SEARCH_KEY_BODY;
1784                 sk_body = strdup(expr);
1785                 break;
1786
1787         case IMAP_SEARCH_CRITERIA_MESSAGE:
1788                 etpan_matcher_type = MAILIMAP_SEARCH_KEY_TEXT;
1789                 sk_text = strdup(expr);
1790                 break;
1791
1792         case IMAP_SEARCH_CRITERIA_HEADER:
1793                 etpan_matcher_type = MAILIMAP_SEARCH_KEY_HEADER;
1794                 sk_header_name = strdup(header);
1795                 sk_header_value = strdup(expr);
1796                 break;
1797
1798         case IMAP_SEARCH_CRITERIA_FROM:
1799                 etpan_matcher_type = MAILIMAP_SEARCH_KEY_FROM;
1800                 sk_from = strdup(expr);
1801                 break;
1802
1803         case IMAP_SEARCH_CRITERIA_SIZE_GREATER:
1804                 etpan_matcher_type = MAILIMAP_SEARCH_KEY_LARGER;
1805                 sk_larger = value;
1806                 break;
1807
1808         case IMAP_SEARCH_CRITERIA_SIZE_SMALLER:
1809                 etpan_matcher_type = MAILIMAP_SEARCH_KEY_SMALLER;
1810                 sk_smaller = value;
1811                 break;
1812
1813         default:
1814                 return NULL;
1815         }
1816
1817         return mailimap_search_key_new(etpan_matcher_type,
1818                 sk_bcc, sk_before, sk_body, sk_cc, sk_from, sk_keyword,
1819                 sk_on, sk_since, sk_subject, sk_text, sk_to,
1820                 sk_unkeyword, sk_header_name,sk_header_value, sk_larger,
1821                 sk_not, sk_or1, sk_or2, sk_sentbefore, sk_senton,
1822                 sk_sentsince, sk_smaller, sk_uid, sk_set, sk_multiple);
1823 }
1824
1825 IMAPSearchKey* imap_search_not(IMAPSearchKey* key)
1826 {
1827         return mailimap_search_key_new_not(key);
1828 }
1829
1830 IMAPSearchKey* imap_search_or(IMAPSearchKey* l, IMAPSearchKey* r)
1831 {
1832         return mailimap_search_key_new_or(l, r);
1833 }
1834
1835 IMAPSearchKey* imap_search_and(IMAPSearchKey* l, IMAPSearchKey* r)
1836 {
1837         IMAPSearchKey* result = mailimap_search_key_new_multiple_empty();
1838         mailimap_search_key_multiple_add(result, l);
1839         mailimap_search_key_multiple_add(result, r);
1840
1841         return result;
1842 }
1843
1844 void imap_search_free(IMAPSearchKey* key)
1845 {
1846         if (!key)
1847             return;
1848
1849         mailimap_search_key_free(key);
1850 }
1851
1852
1853
1854 static int imap_get_msg_att_info(struct mailimap_msg_att * msg_att,
1855                                  uint32_t * puid,
1856                                  char ** pheaders,
1857                                  size_t * pref_size,
1858                                  struct mailimap_msg_att_dynamic ** patt_dyn);
1859
1860 static int
1861 result_to_uid_list(clist * fetch_result, carray ** result)
1862 {
1863         clistiter * cur = NULL;
1864         int r;
1865         int res;
1866         carray * tab;
1867         
1868         tab = carray_new(128);
1869         if (tab == NULL) {
1870                 res = MAILIMAP_ERROR_MEMORY;
1871                 goto err;
1872         }
1873         
1874         if (fetch_result)
1875                 cur = clist_begin(fetch_result);
1876
1877         for(; cur != NULL ; cur = clist_next(cur)) {
1878                 struct mailimap_msg_att * msg_att;
1879                 uint32_t uid;
1880                 uint32_t * puid;
1881                 
1882                 msg_att = clist_content(cur);
1883                 
1884                 uid = 0;
1885                 imap_get_msg_att_info(msg_att, &uid, NULL, NULL, NULL);
1886                 
1887                 puid = malloc(sizeof(* puid));
1888                 if (puid == NULL) {
1889                         res = MAILIMAP_ERROR_MEMORY;
1890                         goto free_list;
1891                 }
1892                 * puid = uid;
1893                         
1894                 r = carray_add(tab, puid, NULL);
1895                 if (r < 0) {
1896                         free(puid);
1897                         res = MAILIMAP_ERROR_MEMORY;
1898                         goto free_list;
1899                 }
1900         }
1901                 
1902         * result = tab;
1903
1904         return MAILIMAP_NO_ERROR;
1905   
1906  free_list:
1907         imap_fetch_uid_list_free(tab);
1908  err:
1909         return res;
1910 }
1911
1912 static int imap_get_messages_list(mailimap * imap,
1913                                   uint32_t first_index,
1914                                   carray ** result)
1915 {
1916         carray * env_list;
1917         int r;
1918         struct mailimap_fetch_att * fetch_att;
1919         struct mailimap_fetch_type * fetch_type;
1920         struct mailimap_set * set;
1921         clist * fetch_result;
1922         int res;
1923         
1924         set = mailimap_set_new_interval(first_index, 0);
1925         if (set == NULL) {
1926                 res = MAILIMAP_ERROR_MEMORY;
1927                 goto err;
1928         }
1929
1930         fetch_type = mailimap_fetch_type_new_fetch_att_list_empty();
1931         if (fetch_type == NULL) {
1932                 res = MAILIMAP_ERROR_MEMORY;
1933                 goto free_set;
1934         }
1935
1936         fetch_att = mailimap_fetch_att_new_uid();
1937         if (fetch_att == NULL) {
1938                 res = MAILIMAP_ERROR_MEMORY;
1939                 goto free_fetch_type;
1940         }
1941
1942         r = mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
1943         if (r != MAILIMAP_NO_ERROR) {
1944                 mailimap_fetch_att_free(fetch_att);
1945                 res = MAILIMAP_ERROR_MEMORY;
1946                 goto free_fetch_type;
1947         }
1948
1949         mailstream_logger = imap_logger_fetch;
1950         
1951         r = mailimap_uid_fetch(imap, set,
1952                                fetch_type, &fetch_result);
1953
1954         mailstream_logger = imap_logger_cmd;
1955         mailimap_fetch_type_free(fetch_type);
1956         mailimap_set_free(set);
1957
1958         if (r != MAILIMAP_NO_ERROR) {
1959                 res = r;
1960                 goto err;
1961         }
1962
1963         env_list = NULL;
1964         r = result_to_uid_list(fetch_result, &env_list);
1965         mailimap_fetch_list_free(fetch_result);
1966         
1967         * result = env_list;
1968
1969         return MAILIMAP_NO_ERROR;
1970
1971  free_fetch_type:
1972         mailimap_fetch_type_free(fetch_type);
1973  free_set:
1974         mailimap_set_free(set);
1975  err:
1976         return res;
1977 }
1978
1979
1980
1981
1982 struct fetch_uid_param {
1983         mailimap * imap;
1984         uint32_t first_index;
1985 };
1986
1987 struct fetch_uid_result {
1988         int error;
1989         carray * fetch_result;
1990 };
1991
1992 static void fetch_uid_run(struct etpan_thread_op * op)
1993 {
1994         struct fetch_uid_param * param;
1995         struct fetch_uid_result * result;
1996         carray * fetch_result;
1997         int r;
1998         
1999         param = op->param;
2000         result = op->result;
2001
2002         CHECK_IMAP();
2003
2004         fetch_result = NULL;
2005         mailstream_logger = imap_logger_noop;
2006         log_print(LOG_PROTOCOL, "IMAP4- [fetching UIDs...]\n");
2007
2008         r = imap_get_messages_list(param->imap, param->first_index,
2009                                    &fetch_result);
2010         
2011         mailstream_logger = imap_logger_cmd;
2012
2013         result->error = r;
2014         result->fetch_result = fetch_result;
2015         debug_print("imap fetch_uid run - end %i\n", r);
2016 }
2017
2018 int imap_threaded_fetch_uid(Folder * folder, uint32_t first_index,
2019                             carray ** fetch_result)
2020 {
2021         struct fetch_uid_param param;
2022         struct fetch_uid_result result;
2023         mailimap * imap;
2024         
2025         debug_print("imap fetch_uid - begin\n");
2026         
2027         imap = get_imap(folder);
2028         param.imap = imap;
2029         param.first_index = first_index;
2030         
2031         threaded_run(folder, &param, &result, fetch_uid_run);
2032         
2033         if (result.error != MAILIMAP_NO_ERROR)
2034                 return result.error;
2035         
2036         debug_print("imap fetch_uid - end\n");
2037         
2038         * fetch_result = result.fetch_result;
2039         
2040         return result.error;
2041 }
2042
2043
2044 void imap_fetch_uid_list_free(carray * uid_list)
2045 {
2046         unsigned int i;
2047         
2048         for(i = 0 ; i < carray_count(uid_list) ; i ++) {
2049                 uint32_t * puid;
2050                 
2051                 puid = carray_get(uid_list, i);
2052                 free(puid);
2053         }
2054         carray_free(uid_list);
2055 }
2056
2057
2058
2059
2060 static int imap_flags_to_flags(struct mailimap_msg_att_dynamic * att_dyn, GSList **tags);
2061
2062 static int
2063 result_to_uid_flags_list(clist * fetch_result, carray ** result)
2064 {
2065         clistiter * cur = NULL;
2066         int r;
2067         int res;
2068         carray * tab;
2069         GSList *tags = NULL;
2070
2071         tab = carray_new(128);
2072         if (tab == NULL) {
2073                 res = MAILIMAP_ERROR_MEMORY;
2074                 goto err;
2075         }
2076
2077         if (fetch_result)
2078                 cur = clist_begin(fetch_result);
2079
2080         for(; cur != NULL ; cur = clist_next(cur)) {
2081                 struct mailimap_msg_att * msg_att;
2082                 uint32_t uid;
2083                 uint32_t * puid;
2084                 struct mailimap_msg_att_dynamic * att_dyn;
2085                 int flags;
2086                 int * pflags;
2087                 
2088                 tags = NULL;
2089
2090                 msg_att = clist_content(cur);
2091                 
2092                 uid = 0;
2093                 att_dyn = NULL;
2094                 imap_get_msg_att_info(msg_att, &uid, NULL, NULL, &att_dyn);
2095                 if (uid == 0)
2096                         continue;
2097                 if (att_dyn == NULL)
2098                         continue;
2099                 
2100                 flags = imap_flags_to_flags(att_dyn, &tags);
2101                 
2102                 puid = malloc(sizeof(* puid));
2103                 if (puid == NULL) {
2104                         res = MAILIMAP_ERROR_MEMORY;
2105                         goto free_list;
2106                 }
2107                 * puid = uid;
2108                 
2109                 r = carray_add(tab, puid, NULL);
2110                 if (r < 0) {
2111                         free(puid);
2112                         res = MAILIMAP_ERROR_MEMORY;
2113                         goto free_list;
2114                 }
2115                 pflags = malloc(sizeof(* pflags));
2116                 if (pflags == NULL) {
2117                         res = MAILIMAP_ERROR_MEMORY;
2118                         goto free_list;
2119                 }
2120                 * pflags = flags;
2121                 r = carray_add(tab, pflags, NULL);
2122                 if (r < 0) {
2123                         free(pflags);
2124                         res = MAILIMAP_ERROR_MEMORY;
2125                         goto free_list;
2126                 }
2127                 r = carray_add(tab, tags, NULL);
2128                 if (r < 0) {
2129                         free(pflags);
2130                         res = MAILIMAP_ERROR_MEMORY;
2131                         goto free_list;
2132                 }
2133         }
2134                 
2135         * result = tab;
2136
2137         return MAILIMAP_NO_ERROR;
2138   
2139  free_list:
2140         imap_fetch_uid_flags_list_free(tab);
2141         slist_free_strings_full(tags);
2142  err:
2143         return res;
2144 }
2145
2146 static int imap_get_messages_flags_list(mailimap * imap,
2147                                         uint32_t first_index,
2148                                         carray ** result)
2149 {
2150         carray * env_list;
2151         int r;
2152         struct mailimap_fetch_att * fetch_att;
2153         struct mailimap_fetch_type * fetch_type;
2154         struct mailimap_set * set;
2155         clist * fetch_result;
2156         int res;
2157         
2158         set = mailimap_set_new_interval(first_index, 0);
2159         if (set == NULL) {
2160                 res = MAILIMAP_ERROR_MEMORY;
2161                 goto err;
2162         }
2163
2164         fetch_type = mailimap_fetch_type_new_fetch_att_list_empty();
2165         if (fetch_type == NULL) {
2166                 res = MAILIMAP_ERROR_MEMORY;
2167                 goto free_set;
2168         }
2169
2170         fetch_att = mailimap_fetch_att_new_flags();
2171         if (fetch_att == NULL) {
2172                 res = MAILIMAP_ERROR_MEMORY;
2173                 goto free_fetch_type;
2174         }
2175         
2176         r = mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
2177         if (r != MAILIMAP_NO_ERROR) {
2178                 mailimap_fetch_att_free(fetch_att);
2179                 res = MAILIMAP_ERROR_MEMORY;
2180                 goto free_fetch_type;
2181         }
2182         
2183         fetch_att = mailimap_fetch_att_new_uid();
2184         if (fetch_att == NULL) {
2185                 res = MAILIMAP_ERROR_MEMORY;
2186                 goto free_fetch_type;
2187         }
2188
2189         r = mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
2190         if (r != MAILIMAP_NO_ERROR) {
2191                 mailimap_fetch_att_free(fetch_att);
2192                 res = MAILIMAP_ERROR_MEMORY;
2193                 goto free_fetch_type;
2194         }
2195
2196         mailstream_logger = imap_logger_fetch;
2197         
2198         r = mailimap_uid_fetch(imap, set,
2199                                fetch_type, &fetch_result);
2200
2201         mailstream_logger = imap_logger_cmd;
2202         mailimap_fetch_type_free(fetch_type);
2203         mailimap_set_free(set);
2204
2205         if (r != MAILIMAP_NO_ERROR) {
2206                 res = r;
2207                 goto err;
2208         }
2209
2210         env_list = NULL;
2211         r = result_to_uid_flags_list(fetch_result, &env_list);
2212         mailimap_fetch_list_free(fetch_result);
2213         
2214         * result = env_list;
2215
2216         return MAILIMAP_NO_ERROR;
2217
2218  free_fetch_type:
2219         mailimap_fetch_type_free(fetch_type);
2220  free_set:
2221         mailimap_set_free(set);
2222  err:
2223         return res;
2224 }
2225
2226
2227
2228 static void fetch_uid_flags_run(struct etpan_thread_op * op)
2229 {
2230         struct fetch_uid_param * param;
2231         struct fetch_uid_result * result;
2232         carray * fetch_result;
2233         int r;
2234         
2235         param = op->param;
2236         result = op->result;
2237
2238         CHECK_IMAP();
2239
2240         fetch_result = NULL;
2241         r = imap_get_messages_flags_list(param->imap, param->first_index,
2242                                          &fetch_result);
2243         
2244         result->error = r;
2245         result->fetch_result = fetch_result;
2246         debug_print("imap fetch_uid run - end %i\n", r);
2247 }
2248
2249 int imap_threaded_fetch_uid_flags(Folder * folder, uint32_t first_index,
2250                                   carray ** fetch_result)
2251 {
2252         struct fetch_uid_param param;
2253         struct fetch_uid_result result;
2254         mailimap * imap;
2255         
2256         debug_print("imap fetch_uid - begin\n");
2257         
2258         imap = get_imap(folder);
2259         param.imap = imap;
2260         param.first_index = first_index;
2261         
2262         mailstream_logger = imap_logger_noop;
2263         log_print(LOG_PROTOCOL, "IMAP4- [fetching flags...]\n");
2264
2265         threaded_run(folder, &param, &result, fetch_uid_flags_run);
2266
2267         mailstream_logger = imap_logger_cmd;
2268
2269         
2270         if (result.error != MAILIMAP_NO_ERROR)
2271                 return result.error;
2272         
2273         debug_print("imap fetch_uid - end\n");
2274         
2275         * fetch_result = result.fetch_result;
2276         
2277         return result.error;
2278 }
2279
2280
2281 void imap_fetch_uid_flags_list_free(carray * uid_flags_list)
2282 {
2283         unsigned int i;
2284         
2285         for(i = 0 ; i < carray_count(uid_flags_list) ; i += 3) {
2286                 void * data;
2287                 
2288                 data = carray_get(uid_flags_list, i);
2289                 free(data);
2290                 data = carray_get(uid_flags_list, i + 1);
2291                 free(data);
2292         }
2293         carray_free(uid_flags_list);
2294 }
2295
2296
2297
2298 static int imap_fetch(mailimap * imap,
2299                       uint32_t msg_index,
2300                       char ** result,
2301                       size_t * result_len)
2302 {
2303         int r;
2304         struct mailimap_set * set;
2305         struct mailimap_fetch_att * fetch_att;
2306         struct mailimap_fetch_type * fetch_type;
2307         clist * fetch_result;
2308         struct mailimap_msg_att * msg_att;
2309         struct mailimap_msg_att_item * msg_att_item;
2310         char * text;
2311         size_t text_length;
2312         int res;
2313         clistiter * cur;
2314         struct mailimap_section * section;
2315
2316         set = mailimap_set_new_single(msg_index);
2317         if (set == NULL) {
2318                 res = MAILIMAP_ERROR_MEMORY;
2319                 goto err;
2320         }
2321
2322         section = mailimap_section_new(NULL);
2323         if (section == NULL) {
2324                 res = MAILIMAP_ERROR_MEMORY;
2325                 goto free_set;
2326         }
2327   
2328         fetch_att = mailimap_fetch_att_new_body_peek_section(section);
2329         if (fetch_att == NULL) {
2330                 mailimap_section_free(section);
2331                 res = MAILIMAP_ERROR_MEMORY;
2332                 goto free_set;
2333         }
2334   
2335         fetch_type = mailimap_fetch_type_new_fetch_att(fetch_att);
2336         if (fetch_type == NULL) {
2337                 res = MAILIMAP_ERROR_MEMORY;
2338                 goto free_fetch_att;
2339         }
2340
2341         mailstream_logger = imap_logger_fetch;
2342         
2343         r = mailimap_uid_fetch(imap, set,
2344                                fetch_type, &fetch_result);
2345   
2346         mailstream_logger = imap_logger_cmd;
2347         
2348         mailimap_fetch_type_free(fetch_type);
2349         mailimap_set_free(set);
2350   
2351         switch (r) {
2352         case MAILIMAP_NO_ERROR:
2353                 break;
2354         default:
2355                 return r;
2356         }
2357   
2358         if (fetch_result == NULL || clist_begin(fetch_result) == NULL) {
2359                 mailimap_fetch_list_free(fetch_result);
2360                 return MAILIMAP_ERROR_FETCH;
2361         }
2362
2363         msg_att = clist_begin(fetch_result)->data;
2364
2365         text = NULL;
2366         text_length = 0;
2367
2368         if (msg_att->att_list)
2369                 cur = clist_begin(msg_att->att_list);
2370         else
2371                 cur = NULL;
2372
2373         for(; cur != NULL ; cur = clist_next(cur)) {
2374                 msg_att_item = clist_content(cur);
2375
2376                 if (msg_att_item->att_type == MAILIMAP_MSG_ATT_ITEM_STATIC) {
2377                         if (msg_att_item->att_data.att_static->att_type ==
2378                             MAILIMAP_MSG_ATT_BODY_SECTION) {
2379                                 text = msg_att_item->att_data.att_static->att_data.att_body_section->sec_body_part;
2380                                 /* detach */
2381                                 msg_att_item->att_data.att_static->att_data.att_body_section->sec_body_part = NULL;
2382                                 text_length =
2383                                         msg_att_item->att_data.att_static->att_data.att_body_section->sec_length;
2384                         }
2385                 }
2386         }
2387
2388         mailimap_fetch_list_free(fetch_result);
2389
2390         if (text == NULL)
2391                 return MAILIMAP_ERROR_FETCH;
2392
2393         * result = text;
2394         * result_len = text_length;
2395   
2396         return MAILIMAP_NO_ERROR;
2397
2398  free_fetch_att:
2399         mailimap_fetch_att_free(fetch_att);
2400  free_set:
2401         mailimap_set_free(set);
2402  err:
2403         return res;
2404 }
2405
2406 static int imap_fetch_header(mailimap * imap,
2407                              uint32_t msg_index,
2408                              char ** result,
2409                              size_t * result_len)
2410 {
2411   int r;
2412   struct mailimap_set * set;
2413   struct mailimap_fetch_att * fetch_att;
2414   struct mailimap_fetch_type * fetch_type;
2415   clist * fetch_result;
2416   struct mailimap_msg_att * msg_att;
2417   struct mailimap_msg_att_item * msg_att_item;
2418   char * text;
2419   size_t text_length;
2420   int res;
2421   clistiter * cur;
2422   struct mailimap_section * section;
2423   
2424   set = mailimap_set_new_single(msg_index);
2425   if (set == NULL) {
2426     res = MAILIMAP_ERROR_MEMORY;
2427     goto err;
2428   }
2429
2430   section = mailimap_section_new_header();
2431   if (section == NULL) {
2432     res = MAILIMAP_ERROR_MEMORY;
2433     goto free_set;
2434   }
2435   
2436   fetch_att = mailimap_fetch_att_new_body_peek_section(section);
2437   if (fetch_att == NULL) {
2438     mailimap_section_free(section);
2439     res = MAILIMAP_ERROR_MEMORY;
2440     goto free_set;
2441   }
2442   
2443   fetch_type = mailimap_fetch_type_new_fetch_att(fetch_att);
2444   if (fetch_type == NULL) {
2445     res = MAILIMAP_ERROR_MEMORY;
2446     goto free_fetch_att;
2447   }
2448
2449   mailstream_logger = imap_logger_fetch;
2450   
2451   r = mailimap_uid_fetch(imap, set, fetch_type, &fetch_result);
2452   
2453   mailstream_logger = imap_logger_cmd;
2454   mailimap_fetch_type_free(fetch_type);
2455   mailimap_set_free(set);
2456
2457   switch (r) {
2458   case MAILIMAP_NO_ERROR:
2459     break;
2460   default:
2461     return r;
2462   }
2463
2464   if (fetch_result == NULL || clist_begin(fetch_result) == NULL) {
2465     mailimap_fetch_list_free(fetch_result);
2466     return MAILIMAP_ERROR_FETCH;
2467   }
2468
2469   msg_att = clist_begin(fetch_result)->data;
2470
2471   text = NULL;
2472   text_length = 0;
2473
2474   if (msg_att->att_list)
2475      cur = clist_begin(msg_att->att_list);
2476   else
2477      cur = NULL;
2478
2479   for(; cur != NULL ; cur = clist_next(cur)) {
2480     msg_att_item = clist_content(cur);
2481
2482     if (msg_att_item->att_type == MAILIMAP_MSG_ATT_ITEM_STATIC) {
2483       if (msg_att_item->att_data.att_static->att_type ==
2484           MAILIMAP_MSG_ATT_BODY_SECTION) {
2485         text = msg_att_item->att_data.att_static->att_data.att_body_section->sec_body_part;
2486         msg_att_item->att_data.att_static->att_data.att_body_section->sec_body_part = NULL;
2487         text_length =
2488           msg_att_item->att_data.att_static->att_data.att_body_section->sec_length;
2489       }
2490     }
2491   }
2492
2493   mailimap_fetch_list_free(fetch_result);
2494
2495   if (text == NULL)
2496     return MAILIMAP_ERROR_FETCH;
2497
2498   * result = text;
2499   * result_len = text_length;
2500
2501   return MAILIMAP_NO_ERROR;
2502
2503  free_fetch_att:
2504   mailimap_fetch_att_free(fetch_att);
2505  free_set:
2506   mailimap_set_free(set);
2507  err:
2508   return res;
2509 }
2510
2511
2512
2513 struct fetch_content_param {
2514         mailimap * imap;
2515         uint32_t msg_index;
2516         const char * filename;
2517         int with_body;
2518 };
2519
2520 struct fetch_content_result {
2521         int error;
2522 };
2523
2524 static void fetch_content_run(struct etpan_thread_op * op)
2525 {
2526         struct fetch_content_param * param;
2527         struct fetch_content_result * result;
2528         char * content;
2529         size_t content_size;
2530         int r;
2531         int fd;
2532         FILE * f;
2533         
2534         param = op->param;
2535         result = op->result;
2536
2537         CHECK_IMAP();
2538
2539         content = NULL;
2540         content_size = 0;
2541         if (param->with_body)
2542                 r = imap_fetch(param->imap, param->msg_index,
2543                                &content, &content_size);
2544         else
2545                 r = imap_fetch_header(param->imap, param->msg_index,
2546                                       &content, &content_size);
2547         
2548         result->error = r;
2549         
2550         if (r == MAILIMAP_NO_ERROR) {
2551                 fd = g_open(param->filename, O_RDWR | O_CREAT, 0600);
2552                 if (fd < 0) {
2553                         result->error = MAILIMAP_ERROR_FETCH;
2554                         goto free;
2555                 }
2556                 
2557                 f = fdopen(fd, "wb");
2558                 if (f == NULL) {
2559                         result->error = MAILIMAP_ERROR_FETCH;
2560                         goto close;
2561                 }
2562                 
2563                 r = fwrite(content, 1, content_size, f);
2564                 if (r < content_size) {
2565                         result->error = MAILIMAP_ERROR_FETCH;
2566                         goto fclose;
2567                 }
2568                 
2569                 r = fclose(f);
2570                 if (r == EOF) {
2571                         result->error = MAILIMAP_ERROR_FETCH;
2572                         goto unlink;
2573                 }
2574                 goto free;
2575                 
2576         fclose:
2577                 fclose(f);
2578                 goto unlink;
2579         close:
2580                 close(fd);
2581         unlink:
2582                 claws_unlink(param->filename);
2583         
2584         free:
2585                 /* mmap_string_unref is a simple free in libetpan
2586                  * when it has MMAP_UNAVAILABLE defined */
2587                 if (mmap_string_unref(content) != 0)
2588                         free(content);
2589         }
2590         
2591         debug_print("imap fetch_content run - end %i\n", result->error);
2592 }
2593
2594 int imap_threaded_fetch_content(Folder * folder, uint32_t msg_index,
2595                                 int with_body,
2596                                 const char * filename)
2597 {
2598         struct fetch_content_param param;
2599         struct fetch_content_result result;
2600         mailimap * imap;
2601         
2602         debug_print("imap fetch_content - begin\n");
2603         
2604         imap = get_imap(folder);
2605         param.imap = imap;
2606         param.msg_index = msg_index;
2607         param.filename = filename;
2608         param.with_body = with_body;
2609         
2610         threaded_run(folder, &param, &result, fetch_content_run);
2611         
2612         if (result.error != MAILIMAP_NO_ERROR)
2613                 return result.error;
2614         
2615         debug_print("imap fetch_content - end\n");
2616         
2617         return result.error;
2618 }
2619
2620
2621
2622 static int imap_flags_to_flags(struct mailimap_msg_att_dynamic * att_dyn, GSList **s_tags)
2623 {
2624         int flags;
2625         clist * flag_list;
2626         clistiter * cur;
2627         GSList *tags = NULL;
2628
2629         flags = MSG_UNREAD;
2630         
2631         flag_list = att_dyn->att_list;
2632         if (flag_list == NULL)
2633                 return flags;
2634         
2635         for(cur = clist_begin(flag_list) ; cur != NULL ;
2636             cur = clist_next(cur)) {
2637                 struct mailimap_flag_fetch * flag_fetch;
2638                         
2639                 flag_fetch = clist_content(cur);
2640                 if (flag_fetch->fl_type == MAILIMAP_FLAG_FETCH_RECENT)
2641                         flags |= MSG_NEW;
2642                 else {
2643                         switch (flag_fetch->fl_flag->fl_type) {
2644                         case MAILIMAP_FLAG_ANSWERED:
2645                                 flags |= MSG_REPLIED;
2646                                 break;
2647                         case MAILIMAP_FLAG_FLAGGED:
2648                                 flags |= MSG_MARKED;
2649                                 break;
2650                         case MAILIMAP_FLAG_DELETED:
2651                                 flags |= MSG_DELETED;
2652                                 break;
2653                         case MAILIMAP_FLAG_SEEN:
2654                                 flags &= ~MSG_UNREAD;
2655                                 flags &= ~MSG_NEW;
2656                                 break;
2657                         case MAILIMAP_FLAG_KEYWORD:
2658                                 if (!strcasecmp(flag_fetch->fl_flag->fl_data.fl_keyword, RTAG_FORWARDED))
2659                                         flags |= MSG_FORWARDED;
2660                                 else if (!strcasecmp(flag_fetch->fl_flag->fl_data.fl_keyword, RTAG_JUNK)) 
2661                                         flags |= MSG_SPAM;
2662                                 else if (!strcasecmp(flag_fetch->fl_flag->fl_data.fl_keyword, RTAG_NON_JUNK) ||
2663                                          !strcasecmp(flag_fetch->fl_flag->fl_data.fl_keyword, RTAG_NO_JUNK) ||
2664                                          !strcasecmp(flag_fetch->fl_flag->fl_data.fl_keyword, RTAG_NOT_JUNK)) 
2665                                         flags &= ~MSG_SPAM;
2666                                 else if (s_tags)
2667                                         tags = g_slist_prepend(tags, g_strdup(flag_fetch->fl_flag->fl_data.fl_keyword));
2668                                 break;
2669                         }
2670                 }
2671         }
2672         if (s_tags)
2673                 *s_tags = tags;
2674         return flags;
2675 }
2676
2677 static int imap_get_msg_att_info(struct mailimap_msg_att * msg_att,
2678                                  uint32_t * puid,
2679                                  char ** pheaders,
2680                                  size_t * pref_size,
2681                                  struct mailimap_msg_att_dynamic ** patt_dyn)
2682 {
2683   clistiter * item_cur;
2684   uint32_t uid;
2685   char * headers;
2686   size_t ref_size;
2687   struct mailimap_msg_att_dynamic * att_dyn;
2688
2689   uid = 0;
2690   headers = NULL;
2691   ref_size = 0;
2692   att_dyn = NULL;
2693
2694   if (msg_att->att_list)
2695      item_cur = clist_begin(msg_att->att_list);
2696   else
2697      item_cur = NULL;
2698   for(; item_cur != NULL ; item_cur = clist_next(item_cur)) {
2699     struct mailimap_msg_att_item * item;
2700
2701     item = clist_content(item_cur);
2702       
2703     switch (item->att_type) {
2704     case MAILIMAP_MSG_ATT_ITEM_STATIC:
2705       switch (item->att_data.att_static->att_type) {
2706       case MAILIMAP_MSG_ATT_UID:
2707         uid = item->att_data.att_static->att_data.att_uid;
2708         break;
2709
2710       case MAILIMAP_MSG_ATT_BODY_SECTION:
2711         if (headers == NULL) {
2712           headers = item->att_data.att_static->att_data.att_body_section->sec_body_part;
2713         }
2714         break;
2715       case MAILIMAP_MSG_ATT_RFC822_SIZE:
2716               ref_size = item->att_data.att_static->att_data.att_rfc822_size;
2717               break;
2718       }
2719       break;
2720       
2721     case MAILIMAP_MSG_ATT_ITEM_DYNAMIC:
2722       if (att_dyn == NULL) {
2723         att_dyn = item->att_data.att_dyn;
2724       }
2725       break;
2726     }
2727   }
2728
2729   if (puid != NULL)
2730     * puid = uid;
2731   if (pheaders != NULL)
2732     * pheaders = headers;
2733   if (pref_size != NULL)
2734     * pref_size = ref_size;
2735   if (patt_dyn != NULL)
2736     * patt_dyn = att_dyn;
2737
2738   return MAIL_NO_ERROR;
2739 }
2740
2741 static struct imap_fetch_env_info *
2742 fetch_to_env_info(struct mailimap_msg_att * msg_att, GSList **tags)
2743 {
2744         struct imap_fetch_env_info * info;
2745         uint32_t uid;
2746         char * headers;
2747         size_t size;
2748         struct mailimap_msg_att_dynamic * att_dyn;
2749
2750         imap_get_msg_att_info(msg_att, &uid, &headers, &size,
2751                               &att_dyn);
2752         
2753         if (!headers)
2754                 return NULL;
2755         info = malloc(sizeof(* info));
2756         info->uid = uid;
2757         info->headers = strdup(headers);
2758         info->size = size;
2759         info->flags = imap_flags_to_flags(att_dyn, tags);
2760         
2761         return info;
2762 }
2763
2764 static int
2765 imap_fetch_result_to_envelop_list(clist * fetch_result,
2766                                   carray ** p_env_list)
2767 {
2768         clistiter * cur;
2769         carray * env_list;
2770
2771         env_list = carray_new(16);
2772   
2773         if (fetch_result) {
2774                 for(cur = clist_begin(fetch_result) ; cur != NULL ;
2775                     cur = clist_next(cur)) {
2776                         struct mailimap_msg_att * msg_att;
2777                         struct imap_fetch_env_info * env_info;
2778                         GSList *tags = NULL;
2779
2780                         msg_att = clist_content(cur);
2781
2782                         env_info = fetch_to_env_info(msg_att, &tags);
2783                         if (!env_info)
2784                                 return MAILIMAP_ERROR_MEMORY;
2785                         carray_add(env_list, env_info, NULL);
2786                         carray_add(env_list, tags, NULL);
2787                 }
2788                 * p_env_list = env_list;
2789         } else {
2790                 * p_env_list = NULL;
2791         }
2792
2793         return MAIL_NO_ERROR;
2794 }
2795
2796 static int imap_add_envelope_fetch_att(struct mailimap_fetch_type * fetch_type)
2797 {
2798         struct mailimap_fetch_att * fetch_att;
2799         int i;
2800         char * header;
2801         clist * hdrlist;
2802         struct mailimap_header_list * imap_hdrlist;
2803         struct mailimap_section * section;
2804         char *headers[] = {
2805                         "Date", "From", "To", "Cc", "Subject", "Message-ID",
2806                         "References", "In-Reply-To", NULL
2807                 };
2808
2809         hdrlist = clist_new();
2810         i = 0;
2811         while (headers[i] != NULL) {
2812                 header = strdup(headers[i]);
2813                 if (header == NULL || clist_append(hdrlist, header) != 0)
2814                         return MAIL_ERROR_MEMORY;
2815                 ++i;
2816         }
2817   
2818         imap_hdrlist = mailimap_header_list_new(hdrlist);
2819         section = mailimap_section_new_header_fields(imap_hdrlist);
2820         fetch_att = mailimap_fetch_att_new_body_peek_section(section);
2821         mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
2822   
2823         return MAIL_NO_ERROR;
2824 }
2825
2826 static int imap_add_header_fetch_att(struct mailimap_fetch_type * fetch_type)
2827 {
2828         struct mailimap_fetch_att * fetch_att;
2829         struct mailimap_section * section;
2830         
2831         section = mailimap_section_new_header();
2832         fetch_att = mailimap_fetch_att_new_body_peek_section(section);
2833         mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
2834         
2835         return MAIL_NO_ERROR;
2836 }
2837
2838 static int
2839 imap_get_envelopes_list(mailimap * imap, struct mailimap_set * set,
2840                         carray ** p_env_list)
2841 {
2842         struct mailimap_fetch_att * fetch_att;
2843         struct mailimap_fetch_type * fetch_type;
2844         int res;
2845         clist * fetch_result;
2846         int r;
2847         carray * env_list = NULL;
2848         chashdatum key;
2849         chashdatum value;
2850         
2851         fetch_type = mailimap_fetch_type_new_fetch_att_list_empty();
2852   
2853         /* uid */
2854         fetch_att = mailimap_fetch_att_new_uid();
2855         r = mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
2856   
2857         /* flags */
2858         fetch_att = mailimap_fetch_att_new_flags();
2859         r = mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
2860   
2861         /* rfc822 size */
2862         fetch_att = mailimap_fetch_att_new_rfc822_size();
2863         r = mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
2864   
2865         /* headers */
2866         key.data = &imap;
2867         key.len = sizeof(imap);
2868         r = chash_get(courier_workaround_hash, &key, &value);
2869         if (r < 0)
2870                 r = imap_add_envelope_fetch_att(fetch_type);
2871         else
2872                 r = imap_add_header_fetch_att(fetch_type);
2873         
2874         mailstream_logger = imap_logger_fetch;
2875         
2876         r = mailimap_uid_fetch(imap, set, fetch_type, &fetch_result);
2877         
2878         mailstream_logger = imap_logger_cmd;
2879         switch (r) {
2880         case MAILIMAP_NO_ERROR:
2881                 break;
2882         default:
2883                 mailimap_fetch_type_free(fetch_type);
2884                 debug_print("uid_fetch: %d\n", r);
2885                 return r;
2886         }
2887         
2888         if (fetch_result == NULL || clist_begin(fetch_result) == NULL) {
2889                 res = MAILIMAP_ERROR_FETCH;
2890                 debug_print("clist_begin = NULL\n");
2891                 goto err;
2892         }
2893         
2894         r = imap_fetch_result_to_envelop_list(fetch_result, &env_list);
2895         mailimap_fetch_list_free(fetch_result);
2896         
2897         if (r != MAILIMAP_NO_ERROR) {
2898                 mailimap_fetch_type_free(fetch_type);
2899                 res = MAILIMAP_ERROR_MEMORY;
2900                 debug_print("fetch_result_to_envelop_list: %d\n", res);
2901                 goto err;
2902         }
2903         
2904         mailimap_fetch_type_free(fetch_type);
2905         
2906         * p_env_list = env_list;
2907         
2908         return MAILIMAP_NO_ERROR;
2909   
2910  err:
2911         return res;
2912 }
2913
2914 struct fetch_env_param {
2915         mailimap * imap;
2916         struct mailimap_set * set;
2917 };
2918
2919 struct fetch_env_result {
2920         carray * fetch_env_result;
2921         int error;
2922 };
2923
2924 static void fetch_env_run(struct etpan_thread_op * op)
2925 {
2926         struct fetch_env_param * param;
2927         struct fetch_env_result * result;
2928         carray * env_list;
2929         int r;
2930         
2931         param = op->param;
2932         result = op->result;
2933
2934         CHECK_IMAP();
2935
2936         env_list = NULL;
2937         r = imap_get_envelopes_list(param->imap, param->set,
2938                                     &env_list);
2939         
2940         result->error = r;
2941         result->fetch_env_result = env_list;
2942         
2943         debug_print("imap fetch_env run - end %i\n", r);
2944 }
2945
2946 int imap_threaded_fetch_env(Folder * folder, struct mailimap_set * set,
2947                             carray ** p_env_list)
2948 {
2949         struct fetch_env_param param;
2950         struct fetch_env_result result;
2951         mailimap * imap;
2952         
2953         debug_print("imap fetch_env - begin\n");
2954         
2955         imap = get_imap(folder);
2956         param.imap = imap;
2957         param.set = set;
2958         
2959         threaded_run(folder, &param, &result, fetch_env_run);
2960         
2961         if (result.error != MAILIMAP_NO_ERROR) {
2962                 chashdatum key;
2963                 chashdatum value;
2964                 int r;
2965                 
2966                 key.data = &imap;
2967                 key.len = sizeof(imap);
2968                 r = chash_get(courier_workaround_hash, &key, &value);
2969                 if (r < 0) {
2970                         value.data = NULL;
2971                         value.len = 0;
2972                         chash_set(courier_workaround_hash, &key, &value, NULL);
2973                         
2974                         threaded_run(folder, &param, &result, fetch_env_run);
2975                 }
2976         }
2977         
2978         if (result.error != MAILIMAP_NO_ERROR)
2979                 return result.error;
2980         
2981         debug_print("imap fetch_env - end\n");
2982         
2983         * p_env_list = result.fetch_env_result;
2984         
2985         return result.error;
2986 }
2987
2988 void imap_fetch_env_free(carray * env_list)
2989 {
2990         unsigned int i;
2991         
2992         for(i = 0 ; i < carray_count(env_list) ; i += 2) {
2993                 struct imap_fetch_env_info * env_info;
2994                 
2995                 env_info = carray_get(env_list, i);
2996                 free(env_info->headers);
2997                 free(env_info);
2998         }
2999         carray_free(env_list);
3000 }
3001
3002
3003
3004
3005
3006 struct append_param {
3007         mailimap * imap;
3008         const char * mailbox;
3009         const char * filename;
3010         struct mailimap_flag_list * flag_list;
3011 };
3012
3013 struct append_result {
3014         int error;
3015         int uid;
3016 };
3017
3018 static void append_run(struct etpan_thread_op * op)
3019 {
3020         struct append_param * param;
3021         struct append_result * result;
3022         int r;
3023         char * data;
3024         size_t size;
3025 #ifndef G_OS_WIN32
3026         struct stat stat_buf;
3027         int fd;
3028 #endif
3029         guint32 uid = 0, val = 0;
3030         
3031         param = op->param;
3032         result = op->result;
3033         
3034         CHECK_IMAP();
3035
3036 #ifndef G_OS_WIN32
3037         r = stat(param->filename, &stat_buf);
3038         if (r < 0) {
3039                 result->error = MAILIMAP_ERROR_APPEND;
3040                 return;
3041         }
3042         size = stat_buf.st_size;
3043         
3044         fd = g_open(param->filename, O_RDONLY, 0);
3045         if (fd < 0) {
3046                 result->error = MAILIMAP_ERROR_APPEND;
3047                 return;
3048         }
3049         
3050         data = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
3051         if (data == (void *) MAP_FAILED) {
3052                 close(fd);
3053                 result->error = MAILIMAP_ERROR_APPEND;
3054                 return;
3055         }
3056 #else
3057         data = file_read_to_str_no_recode(param->filename);
3058         if (data == NULL) {
3059                 result->error = MAILIMAP_ERROR_APPEND;
3060                 return;
3061         }
3062         size = strlen(data);
3063 #endif
3064         mailstream_logger = imap_logger_append;
3065         
3066         r = mailimap_uidplus_append(param->imap, param->mailbox,
3067                             param->flag_list, NULL,
3068                             data, size, &val, &uid);
3069
3070         mailstream_logger = imap_logger_cmd;
3071         
3072 #ifndef G_OS_WIN32
3073         munmap(data, size);
3074         close(fd);
3075 #else
3076         g_free(data);
3077 #endif
3078         
3079         result->error = r;
3080         result->uid = uid;
3081         debug_print("imap append run - end %i uid %d\n", r, uid);
3082 }
3083
3084 int imap_threaded_append(Folder * folder, const char * mailbox,
3085                          const char * filename,
3086                          struct mailimap_flag_list * flag_list,
3087                          int *uid)
3088 {
3089         struct append_param param;
3090         struct append_result result;
3091         mailimap * imap;
3092         
3093         debug_print("imap append - begin\n");
3094         
3095         imap = get_imap(folder);
3096         param.imap = imap;
3097         param.mailbox = mailbox;
3098         param.filename = filename;
3099         param.flag_list = flag_list;
3100         
3101         threaded_run(folder, &param, &result, append_run);
3102         
3103         if (result.error != MAILIMAP_NO_ERROR)
3104                 return result.error;
3105         
3106         debug_print("imap append - end\n");
3107         if (uid != NULL)
3108                 *uid = result.uid;
3109
3110         return result.error;
3111 }
3112
3113
3114
3115
3116 struct expunge_param {
3117         mailimap * imap;
3118 };
3119
3120 struct expunge_result {
3121         int error;
3122 };
3123
3124 static void expunge_run(struct etpan_thread_op * op)
3125 {
3126         struct expunge_param * param;
3127         struct expunge_result * result;
3128         int r;
3129         
3130         param = op->param;
3131         result = op->result;
3132
3133         CHECK_IMAP();
3134
3135         r = mailimap_expunge(param->imap);
3136         
3137         result->error = r;
3138         debug_print("imap expunge run - end %i\n", r);
3139 }
3140
3141 int imap_threaded_expunge(Folder * folder)
3142 {
3143         struct expunge_param param;
3144         struct expunge_result result;
3145         
3146         debug_print("imap expunge - begin\n");
3147         
3148         param.imap = get_imap(folder);
3149         
3150         threaded_run(folder, &param, &result, expunge_run);
3151         
3152         debug_print("imap expunge - end\n");
3153         
3154         return result.error;
3155 }
3156
3157
3158 struct copy_param {
3159         mailimap * imap;
3160         struct mailimap_set * set;
3161         const char * mb;
3162 };
3163
3164 struct copy_result {
3165         int error;
3166         struct mailimap_set *source;
3167         struct mailimap_set *dest;
3168 };
3169
3170 static void copy_run(struct etpan_thread_op * op)
3171 {
3172         struct copy_param * param;
3173         struct copy_result * result;
3174         int r;
3175         guint32 val;
3176         struct mailimap_set *source = NULL, *dest = NULL;
3177
3178         param = op->param;
3179         result = op->result;
3180
3181         CHECK_IMAP();
3182
3183         r = mailimap_uidplus_uid_copy(param->imap, param->set, param->mb,
3184                 &val, &source, &dest);
3185         
3186         result->error = r;
3187         if (r == 0) {
3188                 result->source = source;
3189                 result->dest = dest;
3190         } else {
3191                 result->source = NULL;
3192                 result->dest = NULL;
3193         }
3194         debug_print("imap copy run - end %i\n", r);
3195 }
3196
3197 int imap_threaded_copy(Folder * folder, struct mailimap_set * set,
3198                        const char * mb, struct mailimap_set **source,
3199                        struct mailimap_set **dest)
3200 {
3201         struct copy_param param;
3202         struct copy_result result;
3203         mailimap * imap;
3204         
3205         debug_print("imap copy - begin\n");
3206         
3207         imap = get_imap(folder);
3208         param.imap = imap;
3209         param.set = set;
3210         param.mb = mb;
3211         
3212         threaded_run(folder, &param, &result, copy_run);
3213         *source = NULL;
3214         *dest = NULL;
3215         
3216         if (result.error != MAILIMAP_NO_ERROR)
3217                 return result.error;
3218         
3219         *source = result.source;
3220         *dest = result.dest;
3221
3222         debug_print("imap copy - end\n");
3223         
3224         return result.error;
3225 }
3226
3227
3228
3229 struct store_param {
3230         mailimap * imap;
3231         struct mailimap_set * set;
3232         struct mailimap_store_att_flags * store_att_flags;
3233 };
3234
3235 struct store_result {
3236         int error;
3237 };
3238
3239 static void store_run(struct etpan_thread_op * op)
3240 {
3241         struct store_param * param;
3242         struct store_result * result;
3243         int r;
3244         
3245         param = op->param;
3246         result = op->result;
3247
3248         CHECK_IMAP();
3249
3250         r = mailimap_uid_store(param->imap, param->set,
3251                                param->store_att_flags);
3252         
3253         result->error = r;
3254         
3255         debug_print("imap store run - end %i\n", r);
3256 }
3257
3258 int imap_threaded_store(Folder * folder, struct mailimap_set * set,
3259                         struct mailimap_store_att_flags * store_att_flags)
3260 {
3261         struct store_param param;
3262         struct store_result result;
3263         mailimap * imap;
3264         
3265         debug_print("imap store - begin\n");
3266         
3267         imap = get_imap(folder);
3268         param.imap = imap;
3269         param.set = set;
3270         param.store_att_flags = store_att_flags;
3271         
3272         threaded_run(folder, &param, &result, store_run);
3273         
3274         if (result.error != MAILIMAP_NO_ERROR)
3275                 return result.error;
3276         
3277         debug_print("imap store - end\n");
3278         
3279         return result.error;
3280 }
3281
3282
3283 #define ENV_BUFFER_SIZE 512
3284 #ifndef G_OS_WIN32
3285 static void do_exec_command(int fd, const char * command,
3286                             const char * servername, uint16_t port)
3287 {
3288         int i, maxopen;
3289 #ifdef SOLARIS
3290         char env_buffer[ENV_BUFFER_SIZE];
3291 #endif
3292         
3293         if (fork() > 0) {
3294                 /* Fork again to become a child of init rather than
3295                    the etpan client. */
3296                 exit(0);
3297         }
3298   
3299         if (servername)
3300                 g_setenv("ETPANSERVER", servername, TRUE);
3301         else
3302                 g_unsetenv("ETPANSERVER");
3303   
3304         if (port) {
3305                 char porttext[20];
3306                 
3307                 snprintf(porttext, sizeof(porttext), "%d", port);
3308                 g_setenv("ETPANPORT", porttext, TRUE);
3309         }
3310         else {
3311                 g_unsetenv("ETPANPORT");
3312         }
3313                 
3314         /* Not a lot we can do if there's an error other than bail. */
3315         if (dup2(fd, 0) == -1)
3316                 exit(1);
3317         if (dup2(fd, 1) == -1)
3318                 exit(1);
3319   
3320         /* Should we close stderr and reopen /dev/null? */
3321   
3322         maxopen = sysconf(_SC_OPEN_MAX);
3323         for (i=3; i < maxopen; i++)
3324                 close(i);
3325   
3326 #ifdef TIOCNOTTY
3327         /* Detach from the controlling tty if we have one. Otherwise,
3328            SSH might do something stupid like trying to use it instead
3329            of running $SSH_ASKPASS. Doh. */
3330         fd = g_open("/dev/tty", O_RDONLY, 0);
3331         if (fd != -1) {
3332                 ioctl(fd, TIOCNOTTY, NULL);
3333                 close(fd);
3334         }
3335 #endif /* TIOCNOTTY */
3336
3337         execl("/bin/sh", "/bin/sh", "-c", command, NULL);
3338   
3339         /* Eep. Shouldn't reach this */
3340         exit(1);
3341 }
3342
3343 static int subcommand_connect(const char *command,
3344                               const char *servername, uint16_t port)
3345 {
3346         /* SEB unsupported on Windows */
3347         int sockfds[2];
3348         pid_t childpid;
3349   
3350         if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockfds))
3351                 return -1;
3352   
3353         childpid = fork();
3354         if (!childpid) {
3355                 do_exec_command(sockfds[1], command, servername, port);
3356         }
3357         else if (childpid == -1) {
3358                 close(sockfds[0]);
3359                 close(sockfds[1]);
3360                 return -1;
3361         }
3362   
3363         close(sockfds[1]);
3364   
3365         /* Reap child, leaving grandchild process to run */
3366         waitpid(childpid, NULL, 0);
3367   
3368         return sockfds[0];
3369 }
3370
3371 static int socket_connect_cmd(mailimap * imap, const char * command,
3372                        const char * server, int port)
3373 {
3374         int fd;
3375         mailstream * s;
3376         int r;
3377         
3378         fd = subcommand_connect(command, server, port);
3379         if (fd < 0)
3380                 return MAILIMAP_ERROR_STREAM;
3381         
3382         s = mailstream_socket_open(fd);
3383         if (s == NULL) {
3384                 close(fd);
3385                 return MAILIMAP_ERROR_STREAM;
3386         }
3387         
3388         r = mailimap_connect(imap, s);
3389         if (r != MAILIMAP_NO_ERROR_AUTHENTICATED
3390         &&  r != MAILIMAP_NO_ERROR_NON_AUTHENTICATED) {
3391                 mailstream_close(s);
3392                 if (imap)
3393                         imap->imap_stream = NULL;
3394                 return r;
3395         }
3396         
3397         return r;
3398 }
3399
3400 /* connect cmd */
3401
3402 struct connect_cmd_param {
3403         mailimap * imap;
3404         const char * command;
3405         const char * server;
3406         int port;
3407 };
3408
3409 struct connect_cmd_result {
3410         int error;
3411 };
3412
3413 static void connect_cmd_run(struct etpan_thread_op * op)
3414 {
3415         int r;
3416         struct connect_cmd_param * param;
3417         struct connect_cmd_result * result;
3418         
3419         param = op->param;
3420         result = op->result;
3421         
3422         CHECK_IMAP();
3423
3424         r = socket_connect_cmd(param->imap, param->command,
3425                                param->server, param->port);
3426         
3427         result->error = r;
3428 }
3429
3430
3431 int imap_threaded_connect_cmd(Folder * folder, const char * command,
3432                               const char * server, int port)
3433 {
3434         struct connect_cmd_param param;
3435         struct connect_cmd_result result;
3436         chashdatum key;
3437         chashdatum value;
3438         mailimap * imap, * oldimap;
3439         
3440         oldimap = get_imap(folder);
3441
3442         imap = mailimap_new(0, NULL);
3443         
3444         if (oldimap) {
3445                 debug_print("deleting old imap %p\n", oldimap);
3446                 delete_imap(folder, oldimap);
3447         }
3448
3449         key.data = &folder;
3450         key.len = sizeof(folder);
3451         value.data = imap;
3452         value.len = 0;
3453         chash_set(session_hash, &key, &value, NULL);
3454         
3455         param.imap = imap;
3456         param.command = command;
3457         param.server = server;
3458         param.port = port;
3459         
3460         threaded_run(folder, &param, &result, connect_cmd_run);
3461         
3462         debug_print("connect_cmd ok %i with imap %p\n", result.error, imap);
3463         
3464         return result.error;
3465 }
3466 #endif /* G_OS_WIN32 */
3467
3468 void imap_threaded_cancel(Folder * folder)
3469 {
3470         mailimap * imap;
3471         
3472         imap = get_imap(folder);
3473         if (imap->imap_stream != NULL)
3474                 mailstream_cancel(imap->imap_stream);
3475 }
3476
3477 #else
3478
3479 void imap_main_init(void)
3480 {
3481 }
3482 void imap_main_done(gboolean have_connectivity)
3483 {
3484 }
3485 void imap_main_set_timeout(int sec)
3486 {
3487 }
3488
3489 void imap_threaded_cancel(Folder * folder);
3490 {
3491 }
3492
3493 #endif