2012-09-16 [mones] 3.8.1cvs60
[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 };
1558
1559 struct search_result {
1560         int error;
1561         clist * search_result;
1562 };
1563
1564 static struct mailimap_set_item *sc_mailimap_set_item_copy(struct mailimap_set_item *orig)
1565 {
1566         return mailimap_set_item_new(orig->set_first, orig->set_last);
1567 }
1568
1569 static struct mailimap_set *sc_mailimap_set_copy(struct mailimap_set *orig)
1570 {
1571         clist *list = orig ? orig->set_list : NULL;
1572         clist *newlist = clist_new();
1573         clistiter *cur;
1574         
1575         if (!orig)
1576                 return NULL;
1577         for (cur = clist_begin(list); cur; cur = clist_next(cur))
1578                 clist_append(newlist, 
1579                         sc_mailimap_set_item_copy(
1580                         (struct mailimap_set_item *)clist_content(cur)));
1581         return mailimap_set_new(newlist);
1582 }
1583
1584 static void search_run(struct etpan_thread_op * op)
1585 {
1586         struct search_param * param;
1587         struct search_result * result;
1588         int r;
1589         struct mailimap_search_key * key = NULL;
1590         struct mailimap_search_key * uid_key = NULL;
1591         struct mailimap_search_key * search_type_key;
1592         clist * search_result;
1593         
1594         param = op->param;
1595         result = op->result;
1596
1597         CHECK_IMAP();
1598
1599         /* we copy the mailimap_set because freeing the key is recursive */
1600         if (param->set != NULL) {
1601                 uid_key = mailimap_search_key_new_uid(sc_mailimap_set_copy(param->set));
1602         } else if (param->type == IMAP_SEARCH_TYPE_SIMPLE) {
1603                 uid_key = mailimap_search_key_new_all();
1604         }
1605         search_type_key = NULL;
1606         switch (param->type) {
1607         case IMAP_SEARCH_TYPE_SIMPLE:
1608                 search_type_key = NULL;
1609                 break;
1610                 
1611         case IMAP_SEARCH_TYPE_SEEN:
1612                 search_type_key = mailimap_search_key_new(MAILIMAP_SEARCH_KEY_SEEN,
1613                                                           NULL, NULL, NULL, NULL, NULL,
1614                                                           NULL, NULL, NULL, NULL, NULL,
1615                                                           NULL, NULL, NULL, NULL, 0,
1616                                                           NULL, NULL, NULL, NULL, NULL,
1617                                                           NULL, 0, NULL, NULL, NULL);
1618                 break;
1619                 
1620         case IMAP_SEARCH_TYPE_UNSEEN:
1621                 search_type_key = mailimap_search_key_new(MAILIMAP_SEARCH_KEY_UNSEEN,
1622                                                           NULL, NULL, NULL, NULL, NULL,
1623                                                           NULL, NULL, NULL, NULL, NULL,
1624                                                           NULL, NULL, NULL, NULL, 0,
1625                                                           NULL, NULL, NULL, NULL, NULL,
1626                                                           NULL, 0, NULL, NULL, NULL);
1627                 break;
1628                 
1629         case IMAP_SEARCH_TYPE_ANSWERED:
1630                 search_type_key = mailimap_search_key_new(MAILIMAP_SEARCH_KEY_ANSWERED,
1631                                                           NULL, NULL, NULL, NULL, NULL,
1632                                                           NULL, NULL, NULL, NULL, NULL,
1633                                                           NULL, NULL, NULL, NULL, 0,
1634                                                           NULL, NULL, NULL, NULL, NULL,
1635                                                           NULL, 0, NULL, NULL, NULL);
1636                 break;
1637                 
1638         case IMAP_SEARCH_TYPE_FLAGGED:
1639                 search_type_key = mailimap_search_key_new(MAILIMAP_SEARCH_KEY_FLAGGED,
1640                                                           NULL, NULL, NULL, NULL, NULL,
1641                                                           NULL, NULL, NULL, NULL, NULL,
1642                                                           NULL, NULL, NULL, NULL, 0,
1643                                                           NULL, NULL, NULL, NULL, NULL,
1644                                                           NULL, 0, NULL, NULL, NULL);
1645                 break;
1646         case IMAP_SEARCH_TYPE_DELETED:
1647                 search_type_key = mailimap_search_key_new(MAILIMAP_SEARCH_KEY_DELETED,
1648                                                           NULL, NULL, NULL, NULL, NULL,
1649                                                           NULL, NULL, NULL, NULL, NULL,
1650                                                           NULL, NULL, NULL, NULL, 0,
1651                                                           NULL, NULL, NULL, NULL, NULL,
1652                                                           NULL, 0, NULL, NULL, NULL);
1653                 break;
1654         case IMAP_SEARCH_TYPE_FORWARDED:
1655                 search_type_key = mailimap_search_key_new(MAILIMAP_SEARCH_KEY_KEYWORD,
1656                                                           NULL, NULL, NULL, NULL, NULL,
1657                                                           strdup(RTAG_FORWARDED), NULL, NULL, NULL, NULL,
1658                                                           NULL, NULL, NULL, NULL, 0,
1659                                                           NULL, NULL, NULL, NULL, NULL,
1660                                                           NULL, 0, NULL, NULL, NULL);
1661                 break;
1662         case IMAP_SEARCH_TYPE_SPAM:
1663                 search_type_key = mailimap_search_key_new(MAILIMAP_SEARCH_KEY_KEYWORD,
1664                                                           NULL, NULL, NULL, NULL, NULL,
1665                                                           strdup(RTAG_JUNK), NULL, NULL, NULL, NULL,
1666                                                           NULL, NULL, NULL, NULL, 0,
1667                                                           NULL, NULL, NULL, NULL, NULL,
1668                                                           NULL, 0, NULL, NULL, NULL);
1669                 break;
1670         }
1671         
1672         if (search_type_key != NULL) {
1673                 if (param->set != NULL) {
1674                         key = mailimap_search_key_new_multiple_empty();
1675                         mailimap_search_key_multiple_add(key, search_type_key);
1676                         mailimap_search_key_multiple_add(key, uid_key);
1677                 } else {
1678                         key = search_type_key;
1679                 }
1680         } else if (uid_key != NULL) {
1681                 key = uid_key;
1682         }
1683         
1684         if (key == NULL) {
1685                 g_warning("no key!");
1686                 result = op->result;
1687                 result->error = -1;
1688                 result->search_result = NULL;
1689         } else {
1690                 mailstream_logger = imap_logger_uid;
1691
1692                 r = mailimap_uid_search(param->imap, NULL, key, &search_result);
1693
1694                 mailstream_logger = imap_logger_cmd;
1695
1696                 /* free the key (with the imapset) */
1697                 mailimap_search_key_free(key);
1698
1699                 result->error = r;
1700                 result->search_result = search_result;
1701         }
1702         debug_print("imap search run - end %i\n", result->error);
1703 }
1704
1705 int imap_threaded_search(Folder * folder, int search_type,
1706                          struct mailimap_set * set, clist ** search_result)
1707 {
1708         struct search_param param;
1709         struct search_result result;
1710         mailimap * imap;
1711         
1712         debug_print("imap search - begin\n");
1713
1714         imap = get_imap(folder);
1715         param.imap = imap;
1716         param.set = set;
1717         param.type = search_type;
1718         
1719         threaded_run(folder, &param, &result, search_run);
1720         
1721         if (result.error != MAILIMAP_NO_ERROR)
1722                 return result.error;
1723         
1724         debug_print("imap search - end\n");
1725         
1726         * search_result = result.search_result;
1727         
1728         return result.error;
1729 }
1730
1731
1732
1733 static int imap_get_msg_att_info(struct mailimap_msg_att * msg_att,
1734                                  uint32_t * puid,
1735                                  char ** pheaders,
1736                                  size_t * pref_size,
1737                                  struct mailimap_msg_att_dynamic ** patt_dyn);
1738
1739 static int
1740 result_to_uid_list(clist * fetch_result, carray ** result)
1741 {
1742         clistiter * cur = NULL;
1743         int r;
1744         int res;
1745         carray * tab;
1746         
1747         tab = carray_new(128);
1748         if (tab == NULL) {
1749                 res = MAILIMAP_ERROR_MEMORY;
1750                 goto err;
1751         }
1752         
1753         if (fetch_result)
1754                 cur = clist_begin(fetch_result);
1755
1756         for(; cur != NULL ; cur = clist_next(cur)) {
1757                 struct mailimap_msg_att * msg_att;
1758                 uint32_t uid;
1759                 uint32_t * puid;
1760                 
1761                 msg_att = clist_content(cur);
1762                 
1763                 uid = 0;
1764                 imap_get_msg_att_info(msg_att, &uid, NULL, NULL, NULL);
1765                 
1766                 puid = malloc(sizeof(* puid));
1767                 if (puid == NULL) {
1768                         res = MAILIMAP_ERROR_MEMORY;
1769                         goto free_list;
1770                 }
1771                 * puid = uid;
1772                         
1773                 r = carray_add(tab, puid, NULL);
1774                 if (r < 0) {
1775                         free(puid);
1776                         res = MAILIMAP_ERROR_MEMORY;
1777                         goto free_list;
1778                 }
1779         }
1780                 
1781         * result = tab;
1782
1783         return MAILIMAP_NO_ERROR;
1784   
1785  free_list:
1786         imap_fetch_uid_list_free(tab);
1787  err:
1788         return res;
1789 }
1790
1791 static int imap_get_messages_list(mailimap * imap,
1792                                   uint32_t first_index,
1793                                   carray ** result)
1794 {
1795         carray * env_list;
1796         int r;
1797         struct mailimap_fetch_att * fetch_att;
1798         struct mailimap_fetch_type * fetch_type;
1799         struct mailimap_set * set;
1800         clist * fetch_result;
1801         int res;
1802         
1803         set = mailimap_set_new_interval(first_index, 0);
1804         if (set == NULL) {
1805                 res = MAILIMAP_ERROR_MEMORY;
1806                 goto err;
1807         }
1808
1809         fetch_type = mailimap_fetch_type_new_fetch_att_list_empty();
1810         if (fetch_type == NULL) {
1811                 res = MAILIMAP_ERROR_MEMORY;
1812                 goto free_set;
1813         }
1814
1815         fetch_att = mailimap_fetch_att_new_uid();
1816         if (fetch_att == NULL) {
1817                 res = MAILIMAP_ERROR_MEMORY;
1818                 goto free_fetch_type;
1819         }
1820
1821         r = mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
1822         if (r != MAILIMAP_NO_ERROR) {
1823                 mailimap_fetch_att_free(fetch_att);
1824                 res = MAILIMAP_ERROR_MEMORY;
1825                 goto free_fetch_type;
1826         }
1827
1828         mailstream_logger = imap_logger_fetch;
1829         
1830         r = mailimap_uid_fetch(imap, set,
1831                                fetch_type, &fetch_result);
1832
1833         mailstream_logger = imap_logger_cmd;
1834         mailimap_fetch_type_free(fetch_type);
1835         mailimap_set_free(set);
1836
1837         if (r != MAILIMAP_NO_ERROR) {
1838                 res = r;
1839                 goto err;
1840         }
1841
1842         env_list = NULL;
1843         r = result_to_uid_list(fetch_result, &env_list);
1844         mailimap_fetch_list_free(fetch_result);
1845         
1846         * result = env_list;
1847
1848         return MAILIMAP_NO_ERROR;
1849
1850  free_fetch_type:
1851         mailimap_fetch_type_free(fetch_type);
1852  free_set:
1853         mailimap_set_free(set);
1854  err:
1855         return res;
1856 }
1857
1858
1859
1860
1861 struct fetch_uid_param {
1862         mailimap * imap;
1863         uint32_t first_index;
1864 };
1865
1866 struct fetch_uid_result {
1867         int error;
1868         carray * fetch_result;
1869 };
1870
1871 static void fetch_uid_run(struct etpan_thread_op * op)
1872 {
1873         struct fetch_uid_param * param;
1874         struct fetch_uid_result * result;
1875         carray * fetch_result;
1876         int r;
1877         
1878         param = op->param;
1879         result = op->result;
1880
1881         CHECK_IMAP();
1882
1883         fetch_result = NULL;
1884         mailstream_logger = imap_logger_noop;
1885         log_print(LOG_PROTOCOL, "IMAP4- [fetching UIDs...]\n");
1886
1887         r = imap_get_messages_list(param->imap, param->first_index,
1888                                    &fetch_result);
1889         
1890         mailstream_logger = imap_logger_cmd;
1891
1892         result->error = r;
1893         result->fetch_result = fetch_result;
1894         debug_print("imap fetch_uid run - end %i\n", r);
1895 }
1896
1897 int imap_threaded_fetch_uid(Folder * folder, uint32_t first_index,
1898                             carray ** fetch_result)
1899 {
1900         struct fetch_uid_param param;
1901         struct fetch_uid_result result;
1902         mailimap * imap;
1903         
1904         debug_print("imap fetch_uid - begin\n");
1905         
1906         imap = get_imap(folder);
1907         param.imap = imap;
1908         param.first_index = first_index;
1909         
1910         threaded_run(folder, &param, &result, fetch_uid_run);
1911         
1912         if (result.error != MAILIMAP_NO_ERROR)
1913                 return result.error;
1914         
1915         debug_print("imap fetch_uid - end\n");
1916         
1917         * fetch_result = result.fetch_result;
1918         
1919         return result.error;
1920 }
1921
1922
1923 void imap_fetch_uid_list_free(carray * uid_list)
1924 {
1925         unsigned int i;
1926         
1927         for(i = 0 ; i < carray_count(uid_list) ; i ++) {
1928                 uint32_t * puid;
1929                 
1930                 puid = carray_get(uid_list, i);
1931                 free(puid);
1932         }
1933         carray_free(uid_list);
1934 }
1935
1936
1937
1938
1939 static int imap_flags_to_flags(struct mailimap_msg_att_dynamic * att_dyn, GSList **tags);
1940
1941 static int
1942 result_to_uid_flags_list(clist * fetch_result, carray ** result)
1943 {
1944         clistiter * cur = NULL;
1945         int r;
1946         int res;
1947         carray * tab;
1948         GSList *tags = NULL;
1949
1950         tab = carray_new(128);
1951         if (tab == NULL) {
1952                 res = MAILIMAP_ERROR_MEMORY;
1953                 goto err;
1954         }
1955
1956         if (fetch_result)
1957                 cur = clist_begin(fetch_result);
1958
1959         for(; cur != NULL ; cur = clist_next(cur)) {
1960                 struct mailimap_msg_att * msg_att;
1961                 uint32_t uid;
1962                 uint32_t * puid;
1963                 struct mailimap_msg_att_dynamic * att_dyn;
1964                 int flags;
1965                 int * pflags;
1966                 
1967                 tags = NULL;
1968
1969                 msg_att = clist_content(cur);
1970                 
1971                 uid = 0;
1972                 att_dyn = NULL;
1973                 imap_get_msg_att_info(msg_att, &uid, NULL, NULL, &att_dyn);
1974                 if (uid == 0)
1975                         continue;
1976                 if (att_dyn == NULL)
1977                         continue;
1978                 
1979                 flags = imap_flags_to_flags(att_dyn, &tags);
1980                 
1981                 puid = malloc(sizeof(* puid));
1982                 if (puid == NULL) {
1983                         res = MAILIMAP_ERROR_MEMORY;
1984                         goto free_list;
1985                 }
1986                 * puid = uid;
1987                 
1988                 r = carray_add(tab, puid, NULL);
1989                 if (r < 0) {
1990                         free(puid);
1991                         res = MAILIMAP_ERROR_MEMORY;
1992                         goto free_list;
1993                 }
1994                 pflags = malloc(sizeof(* pflags));
1995                 if (pflags == NULL) {
1996                         res = MAILIMAP_ERROR_MEMORY;
1997                         goto free_list;
1998                 }
1999                 * pflags = flags;
2000                 r = carray_add(tab, pflags, NULL);
2001                 if (r < 0) {
2002                         free(pflags);
2003                         res = MAILIMAP_ERROR_MEMORY;
2004                         goto free_list;
2005                 }
2006                 r = carray_add(tab, tags, NULL);
2007                 if (r < 0) {
2008                         free(pflags);
2009                         res = MAILIMAP_ERROR_MEMORY;
2010                         goto free_list;
2011                 }
2012         }
2013                 
2014         * result = tab;
2015
2016         return MAILIMAP_NO_ERROR;
2017   
2018  free_list:
2019         imap_fetch_uid_flags_list_free(tab);
2020         slist_free_strings(tags);
2021         g_slist_free(tags);
2022  err:
2023         return res;
2024 }
2025
2026 static int imap_get_messages_flags_list(mailimap * imap,
2027                                         uint32_t first_index,
2028                                         carray ** result)
2029 {
2030         carray * env_list;
2031         int r;
2032         struct mailimap_fetch_att * fetch_att;
2033         struct mailimap_fetch_type * fetch_type;
2034         struct mailimap_set * set;
2035         clist * fetch_result;
2036         int res;
2037         
2038         set = mailimap_set_new_interval(first_index, 0);
2039         if (set == NULL) {
2040                 res = MAILIMAP_ERROR_MEMORY;
2041                 goto err;
2042         }
2043
2044         fetch_type = mailimap_fetch_type_new_fetch_att_list_empty();
2045         if (fetch_type == NULL) {
2046                 res = MAILIMAP_ERROR_MEMORY;
2047                 goto free_set;
2048         }
2049
2050         fetch_att = mailimap_fetch_att_new_flags();
2051         if (fetch_att == NULL) {
2052                 res = MAILIMAP_ERROR_MEMORY;
2053                 goto free_fetch_type;
2054         }
2055         
2056         r = mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
2057         if (r != MAILIMAP_NO_ERROR) {
2058                 mailimap_fetch_att_free(fetch_att);
2059                 res = MAILIMAP_ERROR_MEMORY;
2060                 goto free_fetch_type;
2061         }
2062         
2063         fetch_att = mailimap_fetch_att_new_uid();
2064         if (fetch_att == NULL) {
2065                 res = MAILIMAP_ERROR_MEMORY;
2066                 goto free_fetch_type;
2067         }
2068
2069         r = mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
2070         if (r != MAILIMAP_NO_ERROR) {
2071                 mailimap_fetch_att_free(fetch_att);
2072                 res = MAILIMAP_ERROR_MEMORY;
2073                 goto free_fetch_type;
2074         }
2075
2076         mailstream_logger = imap_logger_fetch;
2077         
2078         r = mailimap_uid_fetch(imap, set,
2079                                fetch_type, &fetch_result);
2080
2081         mailstream_logger = imap_logger_cmd;
2082         mailimap_fetch_type_free(fetch_type);
2083         mailimap_set_free(set);
2084
2085         if (r != MAILIMAP_NO_ERROR) {
2086                 res = r;
2087                 goto err;
2088         }
2089
2090         env_list = NULL;
2091         r = result_to_uid_flags_list(fetch_result, &env_list);
2092         mailimap_fetch_list_free(fetch_result);
2093         
2094         * result = env_list;
2095
2096         return MAILIMAP_NO_ERROR;
2097
2098  free_fetch_type:
2099         mailimap_fetch_type_free(fetch_type);
2100  free_set:
2101         mailimap_set_free(set);
2102  err:
2103         return res;
2104 }
2105
2106
2107
2108 static void fetch_uid_flags_run(struct etpan_thread_op * op)
2109 {
2110         struct fetch_uid_param * param;
2111         struct fetch_uid_result * result;
2112         carray * fetch_result;
2113         int r;
2114         
2115         param = op->param;
2116         result = op->result;
2117
2118         CHECK_IMAP();
2119
2120         fetch_result = NULL;
2121         r = imap_get_messages_flags_list(param->imap, param->first_index,
2122                                          &fetch_result);
2123         
2124         result->error = r;
2125         result->fetch_result = fetch_result;
2126         debug_print("imap fetch_uid run - end %i\n", r);
2127 }
2128
2129 int imap_threaded_fetch_uid_flags(Folder * folder, uint32_t first_index,
2130                                   carray ** fetch_result)
2131 {
2132         struct fetch_uid_param param;
2133         struct fetch_uid_result result;
2134         mailimap * imap;
2135         
2136         debug_print("imap fetch_uid - begin\n");
2137         
2138         imap = get_imap(folder);
2139         param.imap = imap;
2140         param.first_index = first_index;
2141         
2142         mailstream_logger = imap_logger_noop;
2143         log_print(LOG_PROTOCOL, "IMAP4- [fetching flags...]\n");
2144
2145         threaded_run(folder, &param, &result, fetch_uid_flags_run);
2146
2147         mailstream_logger = imap_logger_cmd;
2148
2149         
2150         if (result.error != MAILIMAP_NO_ERROR)
2151                 return result.error;
2152         
2153         debug_print("imap fetch_uid - end\n");
2154         
2155         * fetch_result = result.fetch_result;
2156         
2157         return result.error;
2158 }
2159
2160
2161 void imap_fetch_uid_flags_list_free(carray * uid_flags_list)
2162 {
2163         unsigned int i;
2164         
2165         for(i = 0 ; i < carray_count(uid_flags_list) ; i += 3) {
2166                 void * data;
2167                 
2168                 data = carray_get(uid_flags_list, i);
2169                 free(data);
2170                 data = carray_get(uid_flags_list, i + 1);
2171                 free(data);
2172         }
2173         carray_free(uid_flags_list);
2174 }
2175
2176
2177
2178 static int imap_fetch(mailimap * imap,
2179                       uint32_t msg_index,
2180                       char ** result,
2181                       size_t * result_len)
2182 {
2183         int r;
2184         struct mailimap_set * set;
2185         struct mailimap_fetch_att * fetch_att;
2186         struct mailimap_fetch_type * fetch_type;
2187         clist * fetch_result;
2188         struct mailimap_msg_att * msg_att;
2189         struct mailimap_msg_att_item * msg_att_item;
2190         char * text;
2191         size_t text_length;
2192         int res;
2193         clistiter * cur;
2194         struct mailimap_section * section;
2195
2196         set = mailimap_set_new_single(msg_index);
2197         if (set == NULL) {
2198                 res = MAILIMAP_ERROR_MEMORY;
2199                 goto err;
2200         }
2201
2202         section = mailimap_section_new(NULL);
2203         if (section == NULL) {
2204                 res = MAILIMAP_ERROR_MEMORY;
2205                 goto free_set;
2206         }
2207   
2208         fetch_att = mailimap_fetch_att_new_body_peek_section(section);
2209         if (fetch_att == NULL) {
2210                 mailimap_section_free(section);
2211                 res = MAILIMAP_ERROR_MEMORY;
2212                 goto free_set;
2213         }
2214   
2215         fetch_type = mailimap_fetch_type_new_fetch_att(fetch_att);
2216         if (fetch_type == NULL) {
2217                 res = MAILIMAP_ERROR_MEMORY;
2218                 goto free_fetch_att;
2219         }
2220
2221         mailstream_logger = imap_logger_fetch;
2222         
2223         r = mailimap_uid_fetch(imap, set,
2224                                fetch_type, &fetch_result);
2225   
2226         mailstream_logger = imap_logger_cmd;
2227         
2228         mailimap_fetch_type_free(fetch_type);
2229         mailimap_set_free(set);
2230   
2231         switch (r) {
2232         case MAILIMAP_NO_ERROR:
2233                 break;
2234         default:
2235                 return r;
2236         }
2237   
2238         if (fetch_result == NULL || clist_begin(fetch_result) == NULL) {
2239                 mailimap_fetch_list_free(fetch_result);
2240                 return MAILIMAP_ERROR_FETCH;
2241         }
2242
2243         msg_att = clist_begin(fetch_result)->data;
2244
2245         text = NULL;
2246         text_length = 0;
2247
2248         if (msg_att->att_list)
2249                 cur = clist_begin(msg_att->att_list);
2250         else
2251                 cur = NULL;
2252
2253         for(; cur != NULL ; cur = clist_next(cur)) {
2254                 msg_att_item = clist_content(cur);
2255
2256                 if (msg_att_item->att_type == MAILIMAP_MSG_ATT_ITEM_STATIC) {
2257                         if (msg_att_item->att_data.att_static->att_type ==
2258                             MAILIMAP_MSG_ATT_BODY_SECTION) {
2259                                 text = msg_att_item->att_data.att_static->att_data.att_body_section->sec_body_part;
2260                                 /* detach */
2261                                 msg_att_item->att_data.att_static->att_data.att_body_section->sec_body_part = NULL;
2262                                 text_length =
2263                                         msg_att_item->att_data.att_static->att_data.att_body_section->sec_length;
2264                         }
2265                 }
2266         }
2267
2268         mailimap_fetch_list_free(fetch_result);
2269
2270         if (text == NULL)
2271                 return MAILIMAP_ERROR_FETCH;
2272
2273         * result = text;
2274         * result_len = text_length;
2275   
2276         return MAILIMAP_NO_ERROR;
2277
2278  free_fetch_att:
2279         mailimap_fetch_att_free(fetch_att);
2280  free_set:
2281         mailimap_set_free(set);
2282  err:
2283         return res;
2284 }
2285
2286 static int imap_fetch_header(mailimap * imap,
2287                              uint32_t msg_index,
2288                              char ** result,
2289                              size_t * result_len)
2290 {
2291   int r;
2292   struct mailimap_set * set;
2293   struct mailimap_fetch_att * fetch_att;
2294   struct mailimap_fetch_type * fetch_type;
2295   clist * fetch_result;
2296   struct mailimap_msg_att * msg_att;
2297   struct mailimap_msg_att_item * msg_att_item;
2298   char * text;
2299   size_t text_length;
2300   int res;
2301   clistiter * cur;
2302   struct mailimap_section * section;
2303   
2304   set = mailimap_set_new_single(msg_index);
2305   if (set == NULL) {
2306     res = MAILIMAP_ERROR_MEMORY;
2307     goto err;
2308   }
2309
2310   section = mailimap_section_new_header();
2311   if (section == NULL) {
2312     res = MAILIMAP_ERROR_MEMORY;
2313     goto free_set;
2314   }
2315   
2316   fetch_att = mailimap_fetch_att_new_body_peek_section(section);
2317   if (fetch_att == NULL) {
2318     mailimap_section_free(section);
2319     res = MAILIMAP_ERROR_MEMORY;
2320     goto free_set;
2321   }
2322   
2323   fetch_type = mailimap_fetch_type_new_fetch_att(fetch_att);
2324   if (fetch_type == NULL) {
2325     res = MAILIMAP_ERROR_MEMORY;
2326     goto free_fetch_att;
2327   }
2328
2329   mailstream_logger = imap_logger_fetch;
2330   
2331   r = mailimap_uid_fetch(imap, set, fetch_type, &fetch_result);
2332   
2333   mailstream_logger = imap_logger_cmd;
2334   mailimap_fetch_type_free(fetch_type);
2335   mailimap_set_free(set);
2336
2337   switch (r) {
2338   case MAILIMAP_NO_ERROR:
2339     break;
2340   default:
2341     return r;
2342   }
2343
2344   if (fetch_result == NULL || clist_begin(fetch_result) == NULL) {
2345     mailimap_fetch_list_free(fetch_result);
2346     return MAILIMAP_ERROR_FETCH;
2347   }
2348
2349   msg_att = clist_begin(fetch_result)->data;
2350
2351   text = NULL;
2352   text_length = 0;
2353
2354   if (msg_att->att_list)
2355      cur = clist_begin(msg_att->att_list);
2356   else
2357      cur = NULL;
2358
2359   for(; cur != NULL ; cur = clist_next(cur)) {
2360     msg_att_item = clist_content(cur);
2361
2362     if (msg_att_item->att_type == MAILIMAP_MSG_ATT_ITEM_STATIC) {
2363       if (msg_att_item->att_data.att_static->att_type ==
2364           MAILIMAP_MSG_ATT_BODY_SECTION) {
2365         text = msg_att_item->att_data.att_static->att_data.att_body_section->sec_body_part;
2366         msg_att_item->att_data.att_static->att_data.att_body_section->sec_body_part = NULL;
2367         text_length =
2368           msg_att_item->att_data.att_static->att_data.att_body_section->sec_length;
2369       }
2370     }
2371   }
2372
2373   mailimap_fetch_list_free(fetch_result);
2374
2375   if (text == NULL)
2376     return MAILIMAP_ERROR_FETCH;
2377
2378   * result = text;
2379   * result_len = text_length;
2380
2381   return MAILIMAP_NO_ERROR;
2382
2383  free_fetch_att:
2384   mailimap_fetch_att_free(fetch_att);
2385  free_set:
2386   mailimap_set_free(set);
2387  err:
2388   return res;
2389 }
2390
2391
2392
2393 struct fetch_content_param {
2394         mailimap * imap;
2395         uint32_t msg_index;
2396         const char * filename;
2397         int with_body;
2398 };
2399
2400 struct fetch_content_result {
2401         int error;
2402 };
2403
2404 static void fetch_content_run(struct etpan_thread_op * op)
2405 {
2406         struct fetch_content_param * param;
2407         struct fetch_content_result * result;
2408         char * content;
2409         size_t content_size;
2410         int r;
2411         int fd;
2412         FILE * f;
2413         
2414         param = op->param;
2415         result = op->result;
2416
2417         CHECK_IMAP();
2418
2419         content = NULL;
2420         content_size = 0;
2421         if (param->with_body)
2422                 r = imap_fetch(param->imap, param->msg_index,
2423                                &content, &content_size);
2424         else
2425                 r = imap_fetch_header(param->imap, param->msg_index,
2426                                       &content, &content_size);
2427         
2428         result->error = r;
2429         
2430         if (r == MAILIMAP_NO_ERROR) {
2431                 fd = g_open(param->filename, O_RDWR | O_CREAT, 0600);
2432                 if (fd < 0) {
2433                         result->error = MAILIMAP_ERROR_FETCH;
2434                         goto free;
2435                 }
2436                 
2437                 f = fdopen(fd, "wb");
2438                 if (f == NULL) {
2439                         result->error = MAILIMAP_ERROR_FETCH;
2440                         goto close;
2441                 }
2442                 
2443                 r = fwrite(content, 1, content_size, f);
2444                 if (r < content_size) {
2445                         result->error = MAILIMAP_ERROR_FETCH;
2446                         goto fclose;
2447                 }
2448                 
2449                 r = fclose(f);
2450                 if (r == EOF) {
2451                         result->error = MAILIMAP_ERROR_FETCH;
2452                         goto unlink;
2453                 }
2454                 goto free;
2455                 
2456         fclose:
2457                 fclose(f);
2458                 goto unlink;
2459         close:
2460                 close(fd);
2461         unlink:
2462                 claws_unlink(param->filename);
2463         
2464         free:
2465                 /* mmap_string_unref is a simple free in libetpan
2466                  * when it has MMAP_UNAVAILABLE defined */
2467                 if (mmap_string_unref(content) != 0)
2468                         free(content);
2469         }
2470         
2471         debug_print("imap fetch_content run - end %i\n", result->error);
2472 }
2473
2474 int imap_threaded_fetch_content(Folder * folder, uint32_t msg_index,
2475                                 int with_body,
2476                                 const char * filename)
2477 {
2478         struct fetch_content_param param;
2479         struct fetch_content_result result;
2480         mailimap * imap;
2481         
2482         debug_print("imap fetch_content - begin\n");
2483         
2484         imap = get_imap(folder);
2485         param.imap = imap;
2486         param.msg_index = msg_index;
2487         param.filename = filename;
2488         param.with_body = with_body;
2489         
2490         threaded_run(folder, &param, &result, fetch_content_run);
2491         
2492         if (result.error != MAILIMAP_NO_ERROR)
2493                 return result.error;
2494         
2495         debug_print("imap fetch_content - end\n");
2496         
2497         return result.error;
2498 }
2499
2500
2501
2502 static int imap_flags_to_flags(struct mailimap_msg_att_dynamic * att_dyn, GSList **s_tags)
2503 {
2504         int flags;
2505         clist * flag_list;
2506         clistiter * cur;
2507         GSList *tags = NULL;
2508
2509         flags = MSG_UNREAD;
2510         
2511         flag_list = att_dyn->att_list;
2512         if (flag_list == NULL)
2513                 return flags;
2514         
2515         for(cur = clist_begin(flag_list) ; cur != NULL ;
2516             cur = clist_next(cur)) {
2517                 struct mailimap_flag_fetch * flag_fetch;
2518                         
2519                 flag_fetch = clist_content(cur);
2520                 if (flag_fetch->fl_type == MAILIMAP_FLAG_FETCH_RECENT)
2521                         flags |= MSG_NEW;
2522                 else {
2523                         switch (flag_fetch->fl_flag->fl_type) {
2524                         case MAILIMAP_FLAG_ANSWERED:
2525                                 flags |= MSG_REPLIED;
2526                                 break;
2527                         case MAILIMAP_FLAG_FLAGGED:
2528                                 flags |= MSG_MARKED;
2529                                 break;
2530                         case MAILIMAP_FLAG_DELETED:
2531                                 flags |= MSG_DELETED;
2532                                 break;
2533                         case MAILIMAP_FLAG_SEEN:
2534                                 flags &= ~MSG_UNREAD;
2535                                 flags &= ~MSG_NEW;
2536                                 break;
2537                         case MAILIMAP_FLAG_KEYWORD:
2538                                 if (!strcasecmp(flag_fetch->fl_flag->fl_data.fl_keyword, RTAG_FORWARDED))
2539                                         flags |= MSG_FORWARDED;
2540                                 else if (!strcasecmp(flag_fetch->fl_flag->fl_data.fl_keyword, RTAG_JUNK)) 
2541                                         flags |= MSG_SPAM;
2542                                 else if (!strcasecmp(flag_fetch->fl_flag->fl_data.fl_keyword, RTAG_NON_JUNK) ||
2543                                          !strcasecmp(flag_fetch->fl_flag->fl_data.fl_keyword, RTAG_NO_JUNK) ||
2544                                          !strcasecmp(flag_fetch->fl_flag->fl_data.fl_keyword, RTAG_NOT_JUNK)) 
2545                                         flags &= ~MSG_SPAM;
2546                                 else if (s_tags)
2547                                         tags = g_slist_prepend(tags, g_strdup(flag_fetch->fl_flag->fl_data.fl_keyword));
2548                                 break;
2549                         }
2550                 }
2551         }
2552         if (s_tags)
2553                 *s_tags = tags;
2554         return flags;
2555 }
2556
2557 static int imap_get_msg_att_info(struct mailimap_msg_att * msg_att,
2558                                  uint32_t * puid,
2559                                  char ** pheaders,
2560                                  size_t * pref_size,
2561                                  struct mailimap_msg_att_dynamic ** patt_dyn)
2562 {
2563   clistiter * item_cur;
2564   uint32_t uid;
2565   char * headers;
2566   size_t ref_size;
2567   struct mailimap_msg_att_dynamic * att_dyn;
2568
2569   uid = 0;
2570   headers = NULL;
2571   ref_size = 0;
2572   att_dyn = NULL;
2573
2574   if (msg_att->att_list)
2575      item_cur = clist_begin(msg_att->att_list);
2576   else
2577      item_cur = NULL;
2578   for(; item_cur != NULL ; item_cur = clist_next(item_cur)) {
2579     struct mailimap_msg_att_item * item;
2580
2581     item = clist_content(item_cur);
2582       
2583     switch (item->att_type) {
2584     case MAILIMAP_MSG_ATT_ITEM_STATIC:
2585       switch (item->att_data.att_static->att_type) {
2586       case MAILIMAP_MSG_ATT_UID:
2587         uid = item->att_data.att_static->att_data.att_uid;
2588         break;
2589
2590       case MAILIMAP_MSG_ATT_BODY_SECTION:
2591         if (headers == NULL) {
2592           headers = item->att_data.att_static->att_data.att_body_section->sec_body_part;
2593         }
2594         break;
2595       case MAILIMAP_MSG_ATT_RFC822_SIZE:
2596               ref_size = item->att_data.att_static->att_data.att_rfc822_size;
2597               break;
2598       }
2599       break;
2600       
2601     case MAILIMAP_MSG_ATT_ITEM_DYNAMIC:
2602       if (att_dyn == NULL) {
2603         att_dyn = item->att_data.att_dyn;
2604       }
2605       break;
2606     }
2607   }
2608
2609   if (puid != NULL)
2610     * puid = uid;
2611   if (pheaders != NULL)
2612     * pheaders = headers;
2613   if (pref_size != NULL)
2614     * pref_size = ref_size;
2615   if (patt_dyn != NULL)
2616     * patt_dyn = att_dyn;
2617
2618   return MAIL_NO_ERROR;
2619 }
2620
2621 static struct imap_fetch_env_info *
2622 fetch_to_env_info(struct mailimap_msg_att * msg_att, GSList **tags)
2623 {
2624         struct imap_fetch_env_info * info;
2625         uint32_t uid;
2626         char * headers;
2627         size_t size;
2628         struct mailimap_msg_att_dynamic * att_dyn;
2629
2630         imap_get_msg_att_info(msg_att, &uid, &headers, &size,
2631                               &att_dyn);
2632         
2633         if (!headers)
2634                 return NULL;
2635         info = malloc(sizeof(* info));
2636         info->uid = uid;
2637         info->headers = strdup(headers);
2638         info->size = size;
2639         info->flags = imap_flags_to_flags(att_dyn, tags);
2640         
2641         return info;
2642 }
2643
2644 static int
2645 imap_fetch_result_to_envelop_list(clist * fetch_result,
2646                                   carray ** p_env_list)
2647 {
2648         clistiter * cur;
2649         carray * env_list;
2650
2651         env_list = carray_new(16);
2652   
2653         if (fetch_result) {
2654                 for(cur = clist_begin(fetch_result) ; cur != NULL ;
2655                     cur = clist_next(cur)) {
2656                         struct mailimap_msg_att * msg_att;
2657                         struct imap_fetch_env_info * env_info;
2658                         GSList *tags = NULL;
2659
2660                         msg_att = clist_content(cur);
2661
2662                         env_info = fetch_to_env_info(msg_att, &tags);
2663                         if (!env_info)
2664                                 return MAILIMAP_ERROR_MEMORY;
2665                         carray_add(env_list, env_info, NULL);
2666                         carray_add(env_list, tags, NULL);
2667                 }
2668                 * p_env_list = env_list;
2669         } else {
2670                 * p_env_list = NULL;
2671         }
2672
2673         return MAIL_NO_ERROR;
2674 }
2675
2676 static int imap_add_envelope_fetch_att(struct mailimap_fetch_type * fetch_type)
2677 {
2678         struct mailimap_fetch_att * fetch_att;
2679         int i;
2680         char * header;
2681         clist * hdrlist;
2682         struct mailimap_header_list * imap_hdrlist;
2683         struct mailimap_section * section;
2684         char *headers[] = {
2685                         "Date", "From", "To", "Cc", "Subject", "Message-ID",
2686                         "References", "In-Reply-To", NULL
2687                 };
2688
2689         hdrlist = clist_new();
2690         i = 0;
2691         while (headers[i] != NULL) {
2692                 header = strdup(headers[i]);
2693                 if (header == NULL || clist_append(hdrlist, header) != 0)
2694                         return MAIL_ERROR_MEMORY;
2695                 ++i;
2696         }
2697   
2698         imap_hdrlist = mailimap_header_list_new(hdrlist);
2699         section = mailimap_section_new_header_fields(imap_hdrlist);
2700         fetch_att = mailimap_fetch_att_new_body_peek_section(section);
2701         mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
2702   
2703         return MAIL_NO_ERROR;
2704 }
2705
2706 static int imap_add_header_fetch_att(struct mailimap_fetch_type * fetch_type)
2707 {
2708         struct mailimap_fetch_att * fetch_att;
2709         struct mailimap_section * section;
2710         
2711         section = mailimap_section_new_header();
2712         fetch_att = mailimap_fetch_att_new_body_peek_section(section);
2713         mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
2714         
2715         return MAIL_NO_ERROR;
2716 }
2717
2718 static int
2719 imap_get_envelopes_list(mailimap * imap, struct mailimap_set * set,
2720                         carray ** p_env_list)
2721 {
2722         struct mailimap_fetch_att * fetch_att;
2723         struct mailimap_fetch_type * fetch_type;
2724         int res;
2725         clist * fetch_result;
2726         int r;
2727         carray * env_list = NULL;
2728         chashdatum key;
2729         chashdatum value;
2730         
2731         fetch_type = mailimap_fetch_type_new_fetch_att_list_empty();
2732   
2733         /* uid */
2734         fetch_att = mailimap_fetch_att_new_uid();
2735         r = mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
2736   
2737         /* flags */
2738         fetch_att = mailimap_fetch_att_new_flags();
2739         r = mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
2740   
2741         /* rfc822 size */
2742         fetch_att = mailimap_fetch_att_new_rfc822_size();
2743         r = mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
2744   
2745         /* headers */
2746         key.data = &imap;
2747         key.len = sizeof(imap);
2748         r = chash_get(courier_workaround_hash, &key, &value);
2749         if (r < 0)
2750                 r = imap_add_envelope_fetch_att(fetch_type);
2751         else
2752                 r = imap_add_header_fetch_att(fetch_type);
2753         
2754         mailstream_logger = imap_logger_fetch;
2755         
2756         r = mailimap_uid_fetch(imap, set, fetch_type, &fetch_result);
2757         
2758         mailstream_logger = imap_logger_cmd;
2759         switch (r) {
2760         case MAILIMAP_NO_ERROR:
2761                 break;
2762         default:
2763                 mailimap_fetch_type_free(fetch_type);
2764                 debug_print("uid_fetch: %d\n", r);
2765                 return r;
2766         }
2767         
2768         if (fetch_result == NULL || clist_begin(fetch_result) == NULL) {
2769                 res = MAILIMAP_ERROR_FETCH;
2770                 debug_print("clist_begin = NULL\n");
2771                 goto err;
2772         }
2773         
2774         r = imap_fetch_result_to_envelop_list(fetch_result, &env_list);
2775         mailimap_fetch_list_free(fetch_result);
2776         
2777         if (r != MAILIMAP_NO_ERROR) {
2778                 mailimap_fetch_type_free(fetch_type);
2779                 res = MAILIMAP_ERROR_MEMORY;
2780                 debug_print("fetch_result_to_envelop_list: %d\n", res);
2781                 goto err;
2782         }
2783         
2784         mailimap_fetch_type_free(fetch_type);
2785         
2786         * p_env_list = env_list;
2787         
2788         return MAILIMAP_NO_ERROR;
2789   
2790  err:
2791         return res;
2792 }
2793
2794 struct fetch_env_param {
2795         mailimap * imap;
2796         struct mailimap_set * set;
2797 };
2798
2799 struct fetch_env_result {
2800         carray * fetch_env_result;
2801         int error;
2802 };
2803
2804 static void fetch_env_run(struct etpan_thread_op * op)
2805 {
2806         struct fetch_env_param * param;
2807         struct fetch_env_result * result;
2808         carray * env_list;
2809         int r;
2810         
2811         param = op->param;
2812         result = op->result;
2813
2814         CHECK_IMAP();
2815
2816         env_list = NULL;
2817         r = imap_get_envelopes_list(param->imap, param->set,
2818                                     &env_list);
2819         
2820         result->error = r;
2821         result->fetch_env_result = env_list;
2822         
2823         debug_print("imap fetch_env run - end %i\n", r);
2824 }
2825
2826 int imap_threaded_fetch_env(Folder * folder, struct mailimap_set * set,
2827                             carray ** p_env_list)
2828 {
2829         struct fetch_env_param param;
2830         struct fetch_env_result result;
2831         mailimap * imap;
2832         
2833         debug_print("imap fetch_env - begin\n");
2834         
2835         imap = get_imap(folder);
2836         param.imap = imap;
2837         param.set = set;
2838         
2839         threaded_run(folder, &param, &result, fetch_env_run);
2840         
2841         if (result.error != MAILIMAP_NO_ERROR) {
2842                 chashdatum key;
2843                 chashdatum value;
2844                 int r;
2845                 
2846                 key.data = &imap;
2847                 key.len = sizeof(imap);
2848                 r = chash_get(courier_workaround_hash, &key, &value);
2849                 if (r < 0) {
2850                         value.data = NULL;
2851                         value.len = 0;
2852                         chash_set(courier_workaround_hash, &key, &value, NULL);
2853                         
2854                         threaded_run(folder, &param, &result, fetch_env_run);
2855                 }
2856         }
2857         
2858         if (result.error != MAILIMAP_NO_ERROR)
2859                 return result.error;
2860         
2861         debug_print("imap fetch_env - end\n");
2862         
2863         * p_env_list = result.fetch_env_result;
2864         
2865         return result.error;
2866 }
2867
2868 void imap_fetch_env_free(carray * env_list)
2869 {
2870         unsigned int i;
2871         
2872         for(i = 0 ; i < carray_count(env_list) ; i += 2) {
2873                 struct imap_fetch_env_info * env_info;
2874                 
2875                 env_info = carray_get(env_list, i);
2876                 free(env_info->headers);
2877                 free(env_info);
2878         }
2879         carray_free(env_list);
2880 }
2881
2882
2883
2884
2885
2886 struct append_param {
2887         mailimap * imap;
2888         const char * mailbox;
2889         const char * filename;
2890         struct mailimap_flag_list * flag_list;
2891 };
2892
2893 struct append_result {
2894         int error;
2895         int uid;
2896 };
2897
2898 static void append_run(struct etpan_thread_op * op)
2899 {
2900         struct append_param * param;
2901         struct append_result * result;
2902         int r;
2903         char * data;
2904         size_t size;
2905 #ifndef G_OS_WIN32
2906         struct stat stat_buf;
2907         int fd;
2908 #endif
2909         guint32 uid = 0, val = 0;
2910         
2911         param = op->param;
2912         result = op->result;
2913         
2914         CHECK_IMAP();
2915
2916 #ifndef G_OS_WIN32
2917         r = stat(param->filename, &stat_buf);
2918         if (r < 0) {
2919                 result->error = MAILIMAP_ERROR_APPEND;
2920                 return;
2921         }
2922         size = stat_buf.st_size;
2923         
2924         fd = g_open(param->filename, O_RDONLY, 0);
2925         if (fd < 0) {
2926                 result->error = MAILIMAP_ERROR_APPEND;
2927                 return;
2928         }
2929         
2930         data = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
2931         if (data == (void *) MAP_FAILED) {
2932                 close(fd);
2933                 result->error = MAILIMAP_ERROR_APPEND;
2934                 return;
2935         }
2936 #else
2937         data = file_read_to_str_no_recode(param->filename);
2938         if (data == NULL) {
2939                 result->error = MAILIMAP_ERROR_APPEND;
2940                 return;
2941         }
2942         size = strlen(data);
2943 #endif
2944         mailstream_logger = imap_logger_append;
2945         
2946         r = mailimap_uidplus_append(param->imap, param->mailbox,
2947                             param->flag_list, NULL,
2948                             data, size, &val, &uid);
2949
2950         mailstream_logger = imap_logger_cmd;
2951         
2952 #ifndef G_OS_WIN32
2953         munmap(data, size);
2954         close(fd);
2955 #else
2956         g_free(data);
2957 #endif
2958         
2959         result->error = r;
2960         result->uid = uid;
2961         debug_print("imap append run - end %i uid %d\n", r, uid);
2962 }
2963
2964 int imap_threaded_append(Folder * folder, const char * mailbox,
2965                          const char * filename,
2966                          struct mailimap_flag_list * flag_list,
2967                          int *uid)
2968 {
2969         struct append_param param;
2970         struct append_result result;
2971         mailimap * imap;
2972         
2973         debug_print("imap append - begin\n");
2974         
2975         imap = get_imap(folder);
2976         param.imap = imap;
2977         param.mailbox = mailbox;
2978         param.filename = filename;
2979         param.flag_list = flag_list;
2980         
2981         threaded_run(folder, &param, &result, append_run);
2982         
2983         if (result.error != MAILIMAP_NO_ERROR)
2984                 return result.error;
2985         
2986         debug_print("imap append - end\n");
2987         if (uid != NULL)
2988                 *uid = result.uid;
2989
2990         return result.error;
2991 }
2992
2993
2994
2995
2996 struct expunge_param {
2997         mailimap * imap;
2998 };
2999
3000 struct expunge_result {
3001         int error;
3002 };
3003
3004 static void expunge_run(struct etpan_thread_op * op)
3005 {
3006         struct expunge_param * param;
3007         struct expunge_result * result;
3008         int r;
3009         
3010         param = op->param;
3011         result = op->result;
3012
3013         CHECK_IMAP();
3014
3015         r = mailimap_expunge(param->imap);
3016         
3017         result->error = r;
3018         debug_print("imap expunge run - end %i\n", r);
3019 }
3020
3021 int imap_threaded_expunge(Folder * folder)
3022 {
3023         struct expunge_param param;
3024         struct expunge_result result;
3025         
3026         debug_print("imap expunge - begin\n");
3027         
3028         param.imap = get_imap(folder);
3029         
3030         threaded_run(folder, &param, &result, expunge_run);
3031         
3032         debug_print("imap expunge - end\n");
3033         
3034         return result.error;
3035 }
3036
3037
3038 struct copy_param {
3039         mailimap * imap;
3040         struct mailimap_set * set;
3041         const char * mb;
3042 };
3043
3044 struct copy_result {
3045         int error;
3046         struct mailimap_set *source;
3047         struct mailimap_set *dest;
3048 };
3049
3050 static void copy_run(struct etpan_thread_op * op)
3051 {
3052         struct copy_param * param;
3053         struct copy_result * result;
3054         int r;
3055         guint32 val;
3056         struct mailimap_set *source = NULL, *dest = NULL;
3057
3058         param = op->param;
3059         result = op->result;
3060
3061         CHECK_IMAP();
3062
3063         r = mailimap_uidplus_uid_copy(param->imap, param->set, param->mb,
3064                 &val, &source, &dest);
3065         
3066         result->error = r;
3067         if (r == 0) {
3068                 result->source = source;
3069                 result->dest = dest;
3070         } else {
3071                 result->source = NULL;
3072                 result->dest = NULL;
3073         }
3074         debug_print("imap copy run - end %i\n", r);
3075 }
3076
3077 int imap_threaded_copy(Folder * folder, struct mailimap_set * set,
3078                        const char * mb, struct mailimap_set **source,
3079                        struct mailimap_set **dest)
3080 {
3081         struct copy_param param;
3082         struct copy_result result;
3083         mailimap * imap;
3084         
3085         debug_print("imap copy - begin\n");
3086         
3087         imap = get_imap(folder);
3088         param.imap = imap;
3089         param.set = set;
3090         param.mb = mb;
3091         
3092         threaded_run(folder, &param, &result, copy_run);
3093         *source = NULL;
3094         *dest = NULL;
3095         
3096         if (result.error != MAILIMAP_NO_ERROR)
3097                 return result.error;
3098         
3099         *source = result.source;
3100         *dest = result.dest;
3101
3102         debug_print("imap copy - end\n");
3103         
3104         return result.error;
3105 }
3106
3107
3108
3109 struct store_param {
3110         mailimap * imap;
3111         struct mailimap_set * set;
3112         struct mailimap_store_att_flags * store_att_flags;
3113 };
3114
3115 struct store_result {
3116         int error;
3117 };
3118
3119 static void store_run(struct etpan_thread_op * op)
3120 {
3121         struct store_param * param;
3122         struct store_result * result;
3123         int r;
3124         
3125         param = op->param;
3126         result = op->result;
3127
3128         CHECK_IMAP();
3129
3130         r = mailimap_uid_store(param->imap, param->set,
3131                                param->store_att_flags);
3132         
3133         result->error = r;
3134         
3135         debug_print("imap store run - end %i\n", r);
3136 }
3137
3138 int imap_threaded_store(Folder * folder, struct mailimap_set * set,
3139                         struct mailimap_store_att_flags * store_att_flags)
3140 {
3141         struct store_param param;
3142         struct store_result result;
3143         mailimap * imap;
3144         
3145         debug_print("imap store - begin\n");
3146         
3147         imap = get_imap(folder);
3148         param.imap = imap;
3149         param.set = set;
3150         param.store_att_flags = store_att_flags;
3151         
3152         threaded_run(folder, &param, &result, store_run);
3153         
3154         if (result.error != MAILIMAP_NO_ERROR)
3155                 return result.error;
3156         
3157         debug_print("imap store - end\n");
3158         
3159         return result.error;
3160 }
3161
3162
3163 #define ENV_BUFFER_SIZE 512
3164 #ifndef G_OS_WIN32
3165 static void do_exec_command(int fd, const char * command,
3166                             const char * servername, uint16_t port)
3167 {
3168         int i, maxopen;
3169 #ifdef SOLARIS
3170         char env_buffer[ENV_BUFFER_SIZE];
3171 #endif
3172         
3173         if (fork() > 0) {
3174                 /* Fork again to become a child of init rather than
3175                    the etpan client. */
3176                 exit(0);
3177         }
3178   
3179         if (servername)
3180                 g_setenv("ETPANSERVER", servername, TRUE);
3181         else
3182                 g_unsetenv("ETPANSERVER");
3183   
3184         if (port) {
3185                 char porttext[20];
3186                 
3187                 snprintf(porttext, sizeof(porttext), "%d", port);
3188                 g_setenv("ETPANPORT", porttext, TRUE);
3189         }
3190         else {
3191                 g_unsetenv("ETPANPORT");
3192         }
3193                 
3194         /* Not a lot we can do if there's an error other than bail. */
3195         if (dup2(fd, 0) == -1)
3196                 exit(1);
3197         if (dup2(fd, 1) == -1)
3198                 exit(1);
3199   
3200         /* Should we close stderr and reopen /dev/null? */
3201   
3202         maxopen = sysconf(_SC_OPEN_MAX);
3203         for (i=3; i < maxopen; i++)
3204                 close(i);
3205   
3206 #ifdef TIOCNOTTY
3207         /* Detach from the controlling tty if we have one. Otherwise,
3208            SSH might do something stupid like trying to use it instead
3209            of running $SSH_ASKPASS. Doh. */
3210         fd = g_open("/dev/tty", O_RDONLY, 0);
3211         if (fd != -1) {
3212                 ioctl(fd, TIOCNOTTY, NULL);
3213                 close(fd);
3214         }
3215 #endif /* TIOCNOTTY */
3216
3217         execl("/bin/sh", "/bin/sh", "-c", command, NULL);
3218   
3219         /* Eep. Shouldn't reach this */
3220         exit(1);
3221 }
3222
3223 static int subcommand_connect(const char *command,
3224                               const char *servername, uint16_t port)
3225 {
3226         /* SEB unsupported on Windows */
3227         int sockfds[2];
3228         pid_t childpid;
3229   
3230         if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockfds))
3231                 return -1;
3232   
3233         childpid = fork();
3234         if (!childpid) {
3235                 do_exec_command(sockfds[1], command, servername, port);
3236         }
3237         else if (childpid == -1) {
3238                 close(sockfds[0]);
3239                 close(sockfds[1]);
3240                 return -1;
3241         }
3242   
3243         close(sockfds[1]);
3244   
3245         /* Reap child, leaving grandchild process to run */
3246         waitpid(childpid, NULL, 0);
3247   
3248         return sockfds[0];
3249 }
3250
3251 static int socket_connect_cmd(mailimap * imap, const char * command,
3252                        const char * server, int port)
3253 {
3254         int fd;
3255         mailstream * s;
3256         int r;
3257         
3258         fd = subcommand_connect(command, server, port);
3259         if (fd < 0)
3260                 return MAILIMAP_ERROR_STREAM;
3261         
3262         s = mailstream_socket_open(fd);
3263         if (s == NULL) {
3264                 close(fd);
3265                 return MAILIMAP_ERROR_STREAM;
3266         }
3267         
3268         r = mailimap_connect(imap, s);
3269         if (r != MAILIMAP_NO_ERROR_AUTHENTICATED
3270         &&  r != MAILIMAP_NO_ERROR_NON_AUTHENTICATED) {
3271                 mailstream_close(s);
3272                 if (imap)
3273                         imap->imap_stream = NULL;
3274                 return r;
3275         }
3276         
3277         return r;
3278 }
3279
3280 /* connect cmd */
3281
3282 struct connect_cmd_param {
3283         mailimap * imap;
3284         const char * command;
3285         const char * server;
3286         int port;
3287 };
3288
3289 struct connect_cmd_result {
3290         int error;
3291 };
3292
3293 static void connect_cmd_run(struct etpan_thread_op * op)
3294 {
3295         int r;
3296         struct connect_cmd_param * param;
3297         struct connect_cmd_result * result;
3298         
3299         param = op->param;
3300         result = op->result;
3301         
3302         CHECK_IMAP();
3303
3304         r = socket_connect_cmd(param->imap, param->command,
3305                                param->server, param->port);
3306         
3307         result->error = r;
3308 }
3309
3310
3311 int imap_threaded_connect_cmd(Folder * folder, const char * command,
3312                               const char * server, int port)
3313 {
3314         struct connect_cmd_param param;
3315         struct connect_cmd_result result;
3316         chashdatum key;
3317         chashdatum value;
3318         mailimap * imap, * oldimap;
3319         
3320         oldimap = get_imap(folder);
3321
3322         imap = mailimap_new(0, NULL);
3323         
3324         if (oldimap) {
3325                 debug_print("deleting old imap %p\n", oldimap);
3326                 delete_imap(folder, oldimap);
3327         }
3328
3329         key.data = &folder;
3330         key.len = sizeof(folder);
3331         value.data = imap;
3332         value.len = 0;
3333         chash_set(session_hash, &key, &value, NULL);
3334         
3335         param.imap = imap;
3336         param.command = command;
3337         param.server = server;
3338         param.port = port;
3339         
3340         threaded_run(folder, &param, &result, connect_cmd_run);
3341         
3342         debug_print("connect_cmd ok %i with imap %p\n", result.error, imap);
3343         
3344         return result.error;
3345 }
3346 #endif /* G_OS_WIN32 */
3347
3348 void imap_threaded_cancel(Folder * folder)
3349 {
3350         mailimap * imap;
3351         
3352         imap = get_imap(folder);
3353         if (imap->imap_stream != NULL)
3354                 mailstream_cancel(imap->imap_stream);
3355 }
3356
3357 #else
3358
3359 void imap_main_init(void)
3360 {
3361 }
3362 void imap_main_done(gboolean have_connectivity)
3363 {
3364 }
3365 void imap_main_set_timeout(int sec)
3366 {
3367 }
3368
3369 void imap_threaded_cancel(Folder * folder);
3370 {
3371 }
3372
3373 #endif