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