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