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