2007-04-26 [hoa] 2.9.1cvs26
[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 2 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, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
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
1301
1302 struct examine_param {
1303         mailimap * imap;
1304         const char * mb;
1305 };
1306
1307 struct examine_result {
1308         int error;
1309 };
1310
1311 static void examine_run(struct etpan_thread_op * op)
1312 {
1313         struct examine_param * param;
1314         struct examine_result * result;
1315         int r;
1316         
1317         param = op->param;
1318         result = op->result;
1319
1320         CHECK_IMAP();
1321
1322         r = mailimap_examine(param->imap, param->mb);
1323         
1324         result->error = r;
1325         debug_print("imap examine run - end %i\n", r);
1326 }
1327
1328 int imap_threaded_examine(Folder * folder, const char * mb,
1329                           gint * exists, gint * recent, gint * unseen,
1330                           guint32 * uid_validity)
1331 {
1332         struct examine_param param;
1333         struct examine_result result;
1334         mailimap * imap;
1335         
1336         debug_print("imap examine - begin\n");
1337         
1338         imap = get_imap(folder);
1339         param.imap = imap;
1340         param.mb = mb;
1341         
1342         threaded_run(folder, &param, &result, examine_run);
1343         
1344         if (result.error != MAILIMAP_NO_ERROR)
1345                 return result.error;
1346         
1347         if (!imap || imap->imap_selection_info == NULL)
1348                 return MAILIMAP_ERROR_PARSE;
1349         
1350         * exists = imap->imap_selection_info->sel_exists;
1351         * recent = imap->imap_selection_info->sel_recent;
1352         * unseen = imap->imap_selection_info->sel_unseen;
1353         * uid_validity = imap->imap_selection_info->sel_uidvalidity;
1354         
1355         debug_print("imap examine - end\n");
1356         
1357         return result.error;
1358 }
1359
1360
1361
1362
1363 struct search_param {
1364         mailimap * imap;
1365         int type;
1366         struct mailimap_set * set;
1367 };
1368
1369 struct search_result {
1370         int error;
1371         clist * search_result;
1372 };
1373
1374 static struct mailimap_set_item *sc_mailimap_set_item_copy(struct mailimap_set_item *orig)
1375 {
1376         return mailimap_set_item_new(orig->set_first, orig->set_last);
1377 }
1378
1379 static struct mailimap_set *sc_mailimap_set_copy(struct mailimap_set *orig)
1380 {
1381         clist *list = orig ? orig->set_list : NULL;
1382         clist *newlist = clist_new();
1383         clistiter *cur;
1384         
1385         if (!orig)
1386                 return NULL;
1387         for (cur = clist_begin(list); cur; cur = clist_next(cur))
1388                 clist_append(newlist, 
1389                         sc_mailimap_set_item_copy(
1390                         (struct mailimap_set_item *)clist_content(cur)));
1391         return mailimap_set_new(newlist);
1392 }
1393
1394 static void search_run(struct etpan_thread_op * op)
1395 {
1396         struct search_param * param;
1397         struct search_result * result;
1398         int r;
1399         struct mailimap_search_key * key = NULL;
1400         struct mailimap_search_key * uid_key = NULL;
1401         struct mailimap_search_key * search_type_key;
1402         clist * search_result;
1403         
1404         param = op->param;
1405         result = op->result;
1406
1407         CHECK_IMAP();
1408
1409         /* we copy the mailimap_set because freeing the key is recursive */
1410         if (param->set != NULL) {
1411                 uid_key = mailimap_search_key_new_uid(sc_mailimap_set_copy(param->set));
1412         } else if (param->type == IMAP_SEARCH_TYPE_SIMPLE) {
1413                 uid_key = mailimap_search_key_new_all();
1414         }
1415         search_type_key = NULL;
1416         switch (param->type) {
1417         case IMAP_SEARCH_TYPE_SIMPLE:
1418                 search_type_key = NULL;
1419                 break;
1420                 
1421         case IMAP_SEARCH_TYPE_SEEN:
1422                 search_type_key = mailimap_search_key_new(MAILIMAP_SEARCH_KEY_SEEN,
1423                                                           NULL, NULL, NULL, NULL, NULL,
1424                                                           NULL, NULL, NULL, NULL, NULL,
1425                                                           NULL, NULL, NULL, NULL, 0,
1426                                                           NULL, NULL, NULL, NULL, NULL,
1427                                                           NULL, 0, NULL, NULL, NULL);
1428                 break;
1429                 
1430         case IMAP_SEARCH_TYPE_UNSEEN:
1431                 search_type_key = mailimap_search_key_new(MAILIMAP_SEARCH_KEY_UNSEEN,
1432                                                           NULL, NULL, NULL, NULL, NULL,
1433                                                           NULL, NULL, NULL, NULL, NULL,
1434                                                           NULL, NULL, NULL, NULL, 0,
1435                                                           NULL, NULL, NULL, NULL, NULL,
1436                                                           NULL, 0, NULL, NULL, NULL);
1437                 break;
1438                 
1439         case IMAP_SEARCH_TYPE_ANSWERED:
1440                 search_type_key = mailimap_search_key_new(MAILIMAP_SEARCH_KEY_ANSWERED,
1441                                                           NULL, NULL, NULL, NULL, NULL,
1442                                                           NULL, NULL, NULL, NULL, NULL,
1443                                                           NULL, NULL, NULL, NULL, 0,
1444                                                           NULL, NULL, NULL, NULL, NULL,
1445                                                           NULL, 0, NULL, NULL, NULL);
1446                 break;
1447                 
1448         case IMAP_SEARCH_TYPE_FLAGGED:
1449                 search_type_key = mailimap_search_key_new(MAILIMAP_SEARCH_KEY_FLAGGED,
1450                                                           NULL, NULL, NULL, NULL, NULL,
1451                                                           NULL, NULL, NULL, NULL, NULL,
1452                                                           NULL, NULL, NULL, NULL, 0,
1453                                                           NULL, NULL, NULL, NULL, NULL,
1454                                                           NULL, 0, NULL, NULL, NULL);
1455                 break;
1456         case IMAP_SEARCH_TYPE_DELETED:
1457                 search_type_key = mailimap_search_key_new(MAILIMAP_SEARCH_KEY_DELETED,
1458                                                           NULL, NULL, NULL, NULL, NULL,
1459                                                           NULL, NULL, NULL, NULL, NULL,
1460                                                           NULL, NULL, NULL, NULL, 0,
1461                                                           NULL, NULL, NULL, NULL, NULL,
1462                                                           NULL, 0, NULL, NULL, NULL);
1463                 break;
1464         }
1465         
1466         if (search_type_key != NULL) {
1467                 if (param->set != NULL) {
1468                         key = mailimap_search_key_new_multiple_empty();
1469                         mailimap_search_key_multiple_add(key, search_type_key);
1470                         mailimap_search_key_multiple_add(key, uid_key);
1471                 } else {
1472                         key = search_type_key;
1473                 }
1474         } else if (uid_key != NULL) {
1475                 key = uid_key;
1476         }
1477         
1478         if (key == NULL) {
1479                 g_warning("no key!");
1480                 result = op->result;
1481                 result->error = -1;
1482                 result->search_result = NULL;
1483         } else {
1484                 mailstream_logger = imap_logger_uid;
1485
1486                 r = mailimap_uid_search(param->imap, NULL, key, &search_result);
1487
1488                 mailstream_logger = imap_logger_cmd;
1489
1490                 /* free the key (with the imapset) */
1491                 mailimap_search_key_free(key);
1492
1493                 result->error = r;
1494                 result->search_result = search_result;
1495         }
1496         debug_print("imap search run - end %i\n", result->error);
1497 }
1498
1499 int imap_threaded_search(Folder * folder, int search_type,
1500                          struct mailimap_set * set, clist ** search_result)
1501 {
1502         struct search_param param;
1503         struct search_result result;
1504         mailimap * imap;
1505         
1506         debug_print("imap search - begin\n");
1507
1508         imap = get_imap(folder);
1509         param.imap = imap;
1510         param.set = set;
1511         param.type = search_type;
1512         
1513         threaded_run(folder, &param, &result, search_run);
1514         
1515         if (result.error != MAILIMAP_NO_ERROR)
1516                 return result.error;
1517         
1518         debug_print("imap search - end\n");
1519         
1520         * search_result = result.search_result;
1521         
1522         return result.error;
1523 }
1524
1525
1526
1527
1528 static int
1529 uid_list_to_env_list(clist * fetch_result, carray ** result)
1530 {
1531         clistiter * cur;
1532         int r;
1533         int res;
1534         carray * tab;
1535         unsigned int i;
1536         
1537         tab = carray_new(128);
1538         if (tab == NULL) {
1539                 res = MAILIMAP_ERROR_MEMORY;
1540                 goto err;
1541         }
1542         
1543         for(cur = clist_begin(fetch_result) ; cur != NULL ;
1544             cur = clist_next(cur)) {
1545                 struct mailimap_msg_att * msg_att;
1546                 clistiter * item_cur;
1547                 uint32_t uid;
1548                 size_t size;
1549                 uint32_t * puid;
1550                 
1551                 msg_att = clist_content(cur);
1552                 
1553                 uid = 0;
1554                 size = 0;
1555                 for(item_cur = clist_begin(msg_att->att_list) ;
1556                     item_cur != NULL ;
1557                     item_cur = clist_next(item_cur)) {
1558                         struct mailimap_msg_att_item * item;
1559                         
1560                         item = clist_content(item_cur);
1561                         
1562                         switch (item->att_type) {
1563                         case MAILIMAP_MSG_ATT_ITEM_STATIC:
1564                                 switch (item->att_data.att_static->att_type) {
1565                                 case MAILIMAP_MSG_ATT_UID:
1566                                         uid = item->att_data.att_static->att_data.att_uid;
1567                                         break;
1568                                 }
1569                         }
1570                 }
1571                 
1572                 puid = malloc(sizeof(* puid));
1573                 if (puid == NULL) {
1574                         res = MAILIMAP_ERROR_MEMORY;
1575                         goto free_list;
1576                 }
1577                 * puid = uid;
1578                         
1579                 r = carray_add(tab, puid, NULL);
1580                 if (r < 0) {
1581                         free(puid);
1582                         res = MAILIMAP_ERROR_MEMORY;
1583                         goto free_list;
1584                 }
1585         }
1586                 
1587         * result = tab;
1588
1589         return MAILIMAP_NO_ERROR;
1590   
1591  free_list:
1592         for(i = 0 ; i < carray_count(tab) ; i++)
1593                 mailmessage_free(carray_get(tab, i));
1594  err:
1595         return res;
1596 }
1597
1598 static int imap_get_messages_list(mailimap * imap,
1599                                   uint32_t first_index,
1600                                   carray ** result)
1601 {
1602         carray * env_list;
1603         int r;
1604         struct mailimap_fetch_att * fetch_att;
1605         struct mailimap_fetch_type * fetch_type;
1606         struct mailimap_set * set;
1607         clist * fetch_result;
1608         int res;
1609         
1610         set = mailimap_set_new_interval(first_index, 0);
1611         if (set == NULL) {
1612                 res = MAILIMAP_ERROR_MEMORY;
1613                 goto err;
1614         }
1615
1616         fetch_type = mailimap_fetch_type_new_fetch_att_list_empty();
1617         if (fetch_type == NULL) {
1618                 res = MAILIMAP_ERROR_MEMORY;
1619                 goto free_set;
1620         }
1621
1622         fetch_att = mailimap_fetch_att_new_uid();
1623         if (fetch_att == NULL) {
1624                 res = MAILIMAP_ERROR_MEMORY;
1625                 goto free_fetch_type;
1626         }
1627
1628         r = mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
1629         if (r != MAILIMAP_NO_ERROR) {
1630                 mailimap_fetch_att_free(fetch_att);
1631                 res = MAILIMAP_ERROR_MEMORY;
1632                 goto free_fetch_type;
1633         }
1634
1635         r = mailimap_uid_fetch(imap, set,
1636                                fetch_type, &fetch_result);
1637
1638         mailimap_fetch_type_free(fetch_type);
1639         mailimap_set_free(set);
1640
1641         if (r != MAILIMAP_NO_ERROR) {
1642                 res = r;
1643                 goto err;
1644         }
1645
1646         env_list = NULL;
1647         r = uid_list_to_env_list(fetch_result, &env_list);
1648         mailimap_fetch_list_free(fetch_result);
1649         
1650         * result = env_list;
1651
1652         return MAILIMAP_NO_ERROR;
1653
1654  free_fetch_type:
1655         mailimap_fetch_type_free(fetch_type);
1656  free_set:
1657         mailimap_set_free(set);
1658  err:
1659         return res;
1660 }
1661
1662
1663
1664
1665 struct fetch_uid_param {
1666         mailimap * imap;
1667         uint32_t first_index;
1668 };
1669
1670 struct fetch_uid_result {
1671         int error;
1672         carray * fetch_result;
1673 };
1674
1675 static void fetch_uid_run(struct etpan_thread_op * op)
1676 {
1677         struct fetch_uid_param * param;
1678         struct fetch_uid_result * result;
1679         carray * fetch_result;
1680         int r;
1681         
1682         param = op->param;
1683         result = op->result;
1684
1685         CHECK_IMAP();
1686
1687         fetch_result = NULL;
1688         r = imap_get_messages_list(param->imap, param->first_index,
1689                                    &fetch_result);
1690         
1691         result->error = r;
1692         result->fetch_result = fetch_result;
1693         debug_print("imap fetch_uid run - end %i\n", r);
1694 }
1695
1696 int imap_threaded_fetch_uid(Folder * folder, uint32_t first_index,
1697                             carray ** fetch_result)
1698 {
1699         struct fetch_uid_param param;
1700         struct fetch_uid_result result;
1701         mailimap * imap;
1702         
1703         debug_print("imap fetch_uid - begin\n");
1704         
1705         imap = get_imap(folder);
1706         param.imap = imap;
1707         param.first_index = first_index;
1708         
1709         threaded_run(folder, &param, &result, fetch_uid_run);
1710         
1711         if (result.error != MAILIMAP_NO_ERROR)
1712                 return result.error;
1713         
1714         debug_print("imap fetch_uid - end\n");
1715         
1716         * fetch_result = result.fetch_result;
1717         
1718         return result.error;
1719 }
1720
1721
1722 void imap_fetch_uid_list_free(carray * uid_list)
1723 {
1724         unsigned int i;
1725         
1726         for(i = 0 ; i < carray_count(uid_list) ; i ++) {
1727                 uint32_t * puid;
1728                 
1729                 puid = carray_get(uid_list, i);
1730                 free(puid);
1731         }
1732         carray_free(uid_list);
1733 }
1734
1735
1736
1737 static int imap_fetch(mailimap * imap,
1738                       uint32_t msg_index,
1739                       char ** result,
1740                       size_t * result_len)
1741 {
1742         int r;
1743         struct mailimap_set * set;
1744         struct mailimap_fetch_att * fetch_att;
1745         struct mailimap_fetch_type * fetch_type;
1746         clist * fetch_result;
1747         struct mailimap_msg_att * msg_att;
1748         struct mailimap_msg_att_item * msg_att_item;
1749         char * text;
1750         size_t text_length;
1751         int res;
1752         clistiter * cur;
1753         struct mailimap_section * section;
1754
1755         set = mailimap_set_new_single(msg_index);
1756         if (set == NULL) {
1757                 res = MAILIMAP_ERROR_MEMORY;
1758                 goto err;
1759         }
1760
1761         section = mailimap_section_new(NULL);
1762         if (section == NULL) {
1763                 res = MAILIMAP_ERROR_MEMORY;
1764                 goto free_set;
1765         }
1766   
1767         fetch_att = mailimap_fetch_att_new_body_peek_section(section);
1768         if (fetch_att == NULL) {
1769                 mailimap_section_free(section);
1770                 res = MAILIMAP_ERROR_MEMORY;
1771                 goto free_set;
1772         }
1773   
1774         fetch_type = mailimap_fetch_type_new_fetch_att(fetch_att);
1775         if (fetch_type == NULL) {
1776                 res = MAILIMAP_ERROR_MEMORY;
1777                 goto free_fetch_att;
1778         }
1779
1780         mailstream_logger = imap_logger_fetch;
1781         
1782         r = mailimap_uid_fetch(imap, set,
1783                                fetch_type, &fetch_result);
1784   
1785         mailstream_logger = imap_logger_cmd;
1786         
1787         mailimap_fetch_type_free(fetch_type);
1788         mailimap_set_free(set);
1789   
1790         switch (r) {
1791         case MAILIMAP_NO_ERROR:
1792                 break;
1793         default:
1794                 return r;
1795         }
1796   
1797         if (clist_begin(fetch_result) == NULL) {
1798                 mailimap_fetch_list_free(fetch_result);
1799                 return MAILIMAP_ERROR_FETCH;
1800         }
1801
1802         msg_att = clist_begin(fetch_result)->data;
1803
1804         text = NULL;
1805         text_length = 0;
1806
1807         for(cur = clist_begin(msg_att->att_list) ; cur != NULL ;
1808             cur = clist_next(cur)) {
1809                 msg_att_item = clist_content(cur);
1810
1811                 if (msg_att_item->att_type == MAILIMAP_MSG_ATT_ITEM_STATIC) {
1812                         if (msg_att_item->att_data.att_static->att_type ==
1813                             MAILIMAP_MSG_ATT_BODY_SECTION) {
1814                                 text = msg_att_item->att_data.att_static->att_data.att_body_section->sec_body_part;
1815                                 /* detach */
1816                                 msg_att_item->att_data.att_static->att_data.att_body_section->sec_body_part = NULL;
1817                                 text_length =
1818                                         msg_att_item->att_data.att_static->att_data.att_body_section->sec_length;
1819                         }
1820                 }
1821         }
1822
1823         mailimap_fetch_list_free(fetch_result);
1824
1825         if (text == NULL)
1826                 return MAILIMAP_ERROR_FETCH;
1827
1828         * result = text;
1829         * result_len = text_length;
1830   
1831         return MAILIMAP_NO_ERROR;
1832
1833  free_fetch_att:
1834         mailimap_fetch_att_free(fetch_att);
1835  free_set:
1836         mailimap_set_free(set);
1837  err:
1838         return res;
1839 }
1840
1841 static int imap_fetch_header(mailimap * imap,
1842                              uint32_t msg_index,
1843                              char ** result,
1844                              size_t * result_len)
1845 {
1846   int r;
1847   struct mailimap_set * set;
1848   struct mailimap_fetch_att * fetch_att;
1849   struct mailimap_fetch_type * fetch_type;
1850   clist * fetch_result;
1851   struct mailimap_msg_att * msg_att;
1852   struct mailimap_msg_att_item * msg_att_item;
1853   char * text;
1854   size_t text_length;
1855   int res;
1856   clistiter * cur;
1857   struct mailimap_section * section;
1858   
1859   set = mailimap_set_new_single(msg_index);
1860   if (set == NULL) {
1861     res = MAILIMAP_ERROR_MEMORY;
1862     goto err;
1863   }
1864
1865   section = mailimap_section_new_header();
1866   if (section == NULL) {
1867     res = MAILIMAP_ERROR_MEMORY;
1868     goto free_set;
1869   }
1870   
1871   fetch_att = mailimap_fetch_att_new_body_peek_section(section);
1872   if (fetch_att == NULL) {
1873     mailimap_section_free(section);
1874     res = MAILIMAP_ERROR_MEMORY;
1875     goto free_set;
1876   }
1877   
1878   fetch_type = mailimap_fetch_type_new_fetch_att(fetch_att);
1879   if (fetch_type == NULL) {
1880     res = MAILIMAP_ERROR_MEMORY;
1881     goto free_fetch_att;
1882   }
1883
1884   r = mailimap_uid_fetch(imap, set, fetch_type, &fetch_result);
1885   
1886   mailimap_fetch_type_free(fetch_type);
1887   mailimap_set_free(set);
1888
1889   switch (r) {
1890   case MAILIMAP_NO_ERROR:
1891     break;
1892   default:
1893     return r;
1894   }
1895
1896   if (clist_begin(fetch_result) == NULL) {
1897     mailimap_fetch_list_free(fetch_result);
1898     return MAILIMAP_ERROR_FETCH;
1899   }
1900
1901   msg_att = clist_begin(fetch_result)->data;
1902
1903   text = NULL;
1904   text_length = 0;
1905
1906   for(cur = clist_begin(msg_att->att_list) ; cur != NULL ;
1907       cur = clist_next(cur)) {
1908     msg_att_item = clist_content(cur);
1909
1910     if (msg_att_item->att_type == MAILIMAP_MSG_ATT_ITEM_STATIC) {
1911       if (msg_att_item->att_data.att_static->att_type ==
1912           MAILIMAP_MSG_ATT_BODY_SECTION) {
1913         text = msg_att_item->att_data.att_static->att_data.att_body_section->sec_body_part;
1914         msg_att_item->att_data.att_static->att_data.att_body_section->sec_body_part = NULL;
1915         text_length =
1916           msg_att_item->att_data.att_static->att_data.att_body_section->sec_length;
1917       }
1918     }
1919   }
1920
1921   mailimap_fetch_list_free(fetch_result);
1922
1923   if (text == NULL)
1924     return MAILIMAP_ERROR_FETCH;
1925
1926   * result = text;
1927   * result_len = text_length;
1928
1929   return MAILIMAP_NO_ERROR;
1930
1931  free_fetch_att:
1932   mailimap_fetch_att_free(fetch_att);
1933  free_set:
1934   mailimap_set_free(set);
1935  err:
1936   return res;
1937 }
1938
1939
1940
1941 struct fetch_content_param {
1942         mailimap * imap;
1943         uint32_t msg_index;
1944         const char * filename;
1945         int with_body;
1946 };
1947
1948 struct fetch_content_result {
1949         int error;
1950 };
1951
1952 static void fetch_content_run(struct etpan_thread_op * op)
1953 {
1954         struct fetch_content_param * param;
1955         struct fetch_content_result * result;
1956         char * content;
1957         size_t content_size;
1958         int r;
1959         int fd;
1960         FILE * f;
1961         
1962         param = op->param;
1963         result = op->result;
1964
1965         CHECK_IMAP();
1966
1967         content = NULL;
1968         content_size = 0;
1969         if (param->with_body)
1970                 r = imap_fetch(param->imap, param->msg_index,
1971                                &content, &content_size);
1972         else
1973                 r = imap_fetch_header(param->imap, param->msg_index,
1974                                       &content, &content_size);
1975         
1976         result->error = r;
1977         
1978         if (r == MAILIMAP_NO_ERROR) {
1979                 fd = open(param->filename, O_RDWR | O_CREAT, 0600);
1980                 if (fd < 0) {
1981                         result->error = MAILIMAP_ERROR_FETCH;
1982                         goto free;
1983                 }
1984                 
1985                 f = fdopen(fd, "wb");
1986                 if (f == NULL) {
1987                         result->error = MAILIMAP_ERROR_FETCH;
1988                         goto close;
1989                 }
1990                 
1991                 r = fwrite(content, 1, content_size, f);
1992                 if (r == 0) {
1993                         goto fclose;
1994                 }
1995                 
1996                 r = fclose(f);
1997                 if (r == EOF) {
1998                         g_unlink(param->filename);
1999                         goto close;
2000                 }
2001                 goto free;
2002                 
2003         fclose:
2004                 fclose(f);
2005                 goto unlink;
2006         close:
2007                 close(fd);
2008         unlink:
2009                 g_unlink(param->filename);
2010         
2011         free:
2012                 if (mmap_string_unref(content) != 0)
2013                         free(content);
2014         }
2015         
2016         debug_print("imap fetch_content run - end %i\n", r);
2017 }
2018
2019 int imap_threaded_fetch_content(Folder * folder, uint32_t msg_index,
2020                                 int with_body,
2021                                 const char * filename)
2022 {
2023         struct fetch_content_param param;
2024         struct fetch_content_result result;
2025         mailimap * imap;
2026         
2027         debug_print("imap fetch_content - begin\n");
2028         
2029         imap = get_imap(folder);
2030         param.imap = imap;
2031         param.msg_index = msg_index;
2032         param.filename = filename;
2033         param.with_body = with_body;
2034         
2035         threaded_run(folder, &param, &result, fetch_content_run);
2036         
2037         if (result.error != MAILIMAP_NO_ERROR)
2038                 return result.error;
2039         
2040         debug_print("imap fetch_content - end\n");
2041         
2042         return result.error;
2043 }
2044
2045
2046
2047 static int imap_flags_to_flags(struct mailimap_msg_att_dynamic * att_dyn)
2048 {
2049         int flags;
2050         clist * flag_list;
2051         clistiter * cur;
2052         
2053         flags = MSG_UNREAD;
2054         
2055         flag_list = att_dyn->att_list;
2056         if (flag_list == NULL)
2057                 return flags;
2058         
2059         for(cur = clist_begin(flag_list) ; cur != NULL ;
2060             cur = clist_next(cur)) {
2061                 struct mailimap_flag_fetch * flag_fetch;
2062                         
2063                 flag_fetch = clist_content(cur);
2064                 if (flag_fetch->fl_type == MAILIMAP_FLAG_FETCH_RECENT)
2065                         flags |= MSG_NEW;
2066                 else {
2067                         switch (flag_fetch->fl_flag->fl_type) {
2068                         case MAILIMAP_FLAG_ANSWERED:
2069                                 flags |= MSG_REPLIED;
2070                                 break;
2071                         case MAILIMAP_FLAG_FLAGGED:
2072                                 flags |= MSG_MARKED;
2073                                 break;
2074                         case MAILIMAP_FLAG_DELETED:
2075                                 flags |= MSG_DELETED;
2076                                 break;
2077                         case MAILIMAP_FLAG_SEEN:
2078                                 flags &= ~MSG_UNREAD;
2079                                 flags &= ~MSG_NEW;
2080                                 break;
2081                         }
2082                 }
2083         }
2084         
2085         return flags;
2086 }
2087
2088 static int imap_get_msg_att_info(struct mailimap_msg_att * msg_att,
2089                                  uint32_t * puid,
2090                                  char ** pheaders,
2091                                  size_t * pref_size,
2092                                  struct mailimap_msg_att_dynamic ** patt_dyn)
2093 {
2094   clistiter * item_cur;
2095   uint32_t uid;
2096   char * headers;
2097   size_t ref_size;
2098   struct mailimap_msg_att_dynamic * att_dyn;
2099
2100   uid = 0;
2101   headers = NULL;
2102   ref_size = 0;
2103   att_dyn = NULL;
2104
2105   for(item_cur = clist_begin(msg_att->att_list) ; item_cur != NULL ;
2106       item_cur = clist_next(item_cur)) {
2107     struct mailimap_msg_att_item * item;
2108
2109     item = clist_content(item_cur);
2110       
2111     switch (item->att_type) {
2112     case MAILIMAP_MSG_ATT_ITEM_STATIC:
2113       switch (item->att_data.att_static->att_type) {
2114       case MAILIMAP_MSG_ATT_UID:
2115         uid = item->att_data.att_static->att_data.att_uid;
2116         break;
2117
2118       case MAILIMAP_MSG_ATT_BODY_SECTION:
2119         if (headers == NULL) {
2120           headers = item->att_data.att_static->att_data.att_body_section->sec_body_part;
2121         }
2122         break;
2123       case MAILIMAP_MSG_ATT_RFC822_SIZE:
2124               ref_size = item->att_data.att_static->att_data.att_rfc822_size;
2125               break;
2126       }
2127       break;
2128       
2129     case MAILIMAP_MSG_ATT_ITEM_DYNAMIC:
2130       if (att_dyn == NULL) {
2131         att_dyn = item->att_data.att_dyn;
2132       }
2133       break;
2134     }
2135   }
2136
2137   if (puid != NULL)
2138     * puid = uid;
2139   if (pheaders != NULL)
2140     * pheaders = headers;
2141   if (pref_size != NULL)
2142     * pref_size = ref_size;
2143   if (patt_dyn != NULL)
2144     * patt_dyn = att_dyn;
2145
2146   return MAIL_NO_ERROR;
2147 }
2148
2149 static struct imap_fetch_env_info *
2150 fetch_to_env_info(struct mailimap_msg_att * msg_att)
2151 {
2152         struct imap_fetch_env_info * info;
2153         uint32_t uid;
2154         char * headers;
2155         size_t size;
2156         struct mailimap_msg_att_dynamic * att_dyn;
2157         
2158         imap_get_msg_att_info(msg_att, &uid, &headers, &size,
2159                               &att_dyn);
2160         
2161         if (!headers)
2162                 return NULL;
2163         info = malloc(sizeof(* info));
2164         info->uid = uid;
2165         info->headers = strdup(headers);
2166         info->size = size;
2167         info->flags = imap_flags_to_flags(att_dyn);
2168         
2169         return info;
2170 }
2171
2172 static int
2173 imap_fetch_result_to_envelop_list(clist * fetch_result,
2174                                   carray ** p_env_list)
2175 {
2176         clistiter * cur;
2177         unsigned int i;
2178         carray * env_list;
2179         i = 0;
2180   
2181         env_list = carray_new(16);
2182   
2183         for(cur = clist_begin(fetch_result) ; cur != NULL ;
2184             cur = clist_next(cur)) {
2185                 struct mailimap_msg_att * msg_att;
2186                 struct imap_fetch_env_info * env_info;
2187     
2188                 msg_att = clist_content(cur);
2189
2190                 env_info = fetch_to_env_info(msg_att);
2191                 if (!env_info)
2192                         return MAILIMAP_ERROR_MEMORY;
2193                 carray_add(env_list, env_info, NULL);
2194         }
2195   
2196         * p_env_list = env_list;
2197   
2198         return MAIL_NO_ERROR;
2199 }
2200
2201 static int imap_add_envelope_fetch_att(struct mailimap_fetch_type * fetch_type)
2202 {
2203         struct mailimap_fetch_att * fetch_att;
2204         int r;
2205         char * header;
2206         clist * hdrlist;
2207         struct mailimap_header_list * imap_hdrlist;
2208         struct mailimap_section * section;
2209
2210         hdrlist = clist_new();
2211   
2212         header = strdup("Date");
2213         r = clist_append(hdrlist, header);
2214         header = strdup("From");
2215         r = clist_append(hdrlist, header);
2216         header = strdup("To");
2217         r = clist_append(hdrlist, header);
2218         header = strdup("Cc");
2219         r = clist_append(hdrlist, header);
2220         header = strdup("Subject");
2221         r = clist_append(hdrlist, header);
2222         header = strdup("Message-ID");
2223         r = clist_append(hdrlist, header);
2224         header = strdup("References");
2225         r = clist_append(hdrlist, header);
2226         header = strdup("In-Reply-To");
2227         r = clist_append(hdrlist, header);
2228   
2229         imap_hdrlist = mailimap_header_list_new(hdrlist);
2230         section = mailimap_section_new_header_fields(imap_hdrlist);
2231         fetch_att = mailimap_fetch_att_new_body_peek_section(section);
2232         mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
2233   
2234         return MAIL_NO_ERROR;
2235 }
2236
2237 static int imap_add_header_fetch_att(struct mailimap_fetch_type * fetch_type)
2238 {
2239         struct mailimap_fetch_att * fetch_att;
2240         struct mailimap_section * section;
2241         
2242         section = mailimap_section_new_header();
2243         fetch_att = mailimap_fetch_att_new_body_peek_section(section);
2244         mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
2245         
2246         return MAIL_NO_ERROR;
2247 }
2248
2249 static int
2250 imap_get_envelopes_list(mailimap * imap, struct mailimap_set * set,
2251                         carray ** p_env_list)
2252 {
2253         struct mailimap_fetch_att * fetch_att;
2254         struct mailimap_fetch_type * fetch_type;
2255         int res;
2256         clist * fetch_result;
2257         int r;
2258         carray * env_list = NULL;
2259         chashdatum key;
2260         chashdatum value;
2261         
2262         fetch_type = mailimap_fetch_type_new_fetch_att_list_empty();
2263   
2264         /* uid */
2265         fetch_att = mailimap_fetch_att_new_uid();
2266         r = mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
2267   
2268         /* flags */
2269         fetch_att = mailimap_fetch_att_new_flags();
2270         r = mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
2271   
2272         /* rfc822 size */
2273         fetch_att = mailimap_fetch_att_new_rfc822_size();
2274         r = mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
2275   
2276         /* headers */
2277         key.data = &imap;
2278         key.len = sizeof(imap);
2279         r = chash_get(courier_workaround_hash, &key, &value);
2280         if (r < 0)
2281                 r = imap_add_envelope_fetch_att(fetch_type);
2282         else
2283                 r = imap_add_header_fetch_att(fetch_type);
2284         
2285         r = mailimap_uid_fetch(imap, set, fetch_type, &fetch_result);
2286         
2287         switch (r) {
2288         case MAILIMAP_NO_ERROR:
2289                 break;
2290         default:
2291                 mailimap_fetch_type_free(fetch_type);
2292                 debug_print("uid_fetch: %d\n", r);
2293                 return r;
2294         }
2295         
2296         if (clist_begin(fetch_result) == NULL) {
2297                 res = MAILIMAP_ERROR_FETCH;
2298                 debug_print("clist_begin = NULL\n");
2299                 goto err;
2300         }
2301         
2302         r = imap_fetch_result_to_envelop_list(fetch_result, &env_list);
2303         mailimap_fetch_list_free(fetch_result);
2304         
2305         if (r != MAILIMAP_NO_ERROR) {
2306                 mailimap_fetch_type_free(fetch_type);
2307                 res = MAILIMAP_ERROR_MEMORY;
2308                 debug_print("fetch_result_to_envelop_list: %d\n", res);
2309                 goto err;
2310         }
2311         
2312         mailimap_fetch_type_free(fetch_type);
2313         
2314         * p_env_list = env_list;
2315         
2316         return MAILIMAP_NO_ERROR;
2317   
2318  err:
2319         return res;
2320 }
2321
2322 struct fetch_env_param {
2323         mailimap * imap;
2324         struct mailimap_set * set;
2325 };
2326
2327 struct fetch_env_result {
2328         carray * fetch_env_result;
2329         int error;
2330 };
2331
2332 static void fetch_env_run(struct etpan_thread_op * op)
2333 {
2334         struct fetch_env_param * param;
2335         struct fetch_env_result * result;
2336         carray * env_list;
2337         int r;
2338         
2339         param = op->param;
2340         result = op->result;
2341
2342         CHECK_IMAP();
2343
2344         env_list = NULL;
2345         r = imap_get_envelopes_list(param->imap, param->set,
2346                                     &env_list);
2347         
2348         result->error = r;
2349         result->fetch_env_result = env_list;
2350         
2351         debug_print("imap fetch_env run - end %i\n", r);
2352 }
2353
2354 int imap_threaded_fetch_env(Folder * folder, struct mailimap_set * set,
2355                             carray ** p_env_list)
2356 {
2357         struct fetch_env_param param;
2358         struct fetch_env_result result;
2359         mailimap * imap;
2360         
2361         debug_print("imap fetch_env - begin\n");
2362         
2363         imap = get_imap(folder);
2364         param.imap = imap;
2365         param.set = set;
2366         
2367         threaded_run(folder, &param, &result, fetch_env_run);
2368         
2369         if (result.error != MAILIMAP_NO_ERROR) {
2370                 chashdatum key;
2371                 chashdatum value;
2372                 int r;
2373                 
2374                 key.data = &imap;
2375                 key.len = sizeof(imap);
2376                 r = chash_get(courier_workaround_hash, &key, &value);
2377                 if (r < 0) {
2378                         value.data = NULL;
2379                         value.len = 0;
2380                         chash_set(courier_workaround_hash, &key, &value, NULL);
2381                         
2382                         threaded_run(folder, &param, &result, fetch_env_run);
2383                 }
2384         }
2385         
2386         if (result.error != MAILIMAP_NO_ERROR)
2387                 return result.error;
2388         
2389         debug_print("imap fetch_env - end\n");
2390         
2391         * p_env_list = result.fetch_env_result;
2392         
2393         return result.error;
2394 }
2395
2396 void imap_fetch_env_free(carray * env_list)
2397 {
2398         unsigned int i;
2399         
2400         for(i = 0 ; i < carray_count(env_list) ; i ++) {
2401                 struct imap_fetch_env_info * env_info;
2402                 
2403                 env_info = carray_get(env_list, i);
2404                 free(env_info->headers);
2405                 free(env_info);
2406         }
2407         carray_free(env_list);
2408 }
2409
2410
2411
2412
2413
2414 struct append_param {
2415         mailimap * imap;
2416         const char * mailbox;
2417         const char * filename;
2418         struct mailimap_flag_list * flag_list;
2419 };
2420
2421 struct append_result {
2422         int error;
2423         int uid;
2424 };
2425
2426 static void append_run(struct etpan_thread_op * op)
2427 {
2428         struct append_param * param;
2429         struct append_result * result;
2430         int r;
2431         char * data;
2432         size_t size;
2433         struct stat stat_buf;
2434         int fd;
2435         guint32 uid = 0, val = 0;
2436         
2437         param = op->param;
2438         result = op->result;
2439         
2440         CHECK_IMAP();
2441
2442         r = stat(param->filename, &stat_buf);
2443         if (r < 0) {
2444                 result->error = MAILIMAP_ERROR_APPEND;
2445                 return;
2446         }
2447         size = stat_buf.st_size;
2448         
2449         fd = open(param->filename, O_RDONLY);
2450         if (fd < 0) {
2451                 result->error = MAILIMAP_ERROR_APPEND;
2452                 return;
2453         }
2454         
2455         data = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
2456         if (data == (void *) MAP_FAILED) {
2457                 close(fd);
2458                 result->error = MAILIMAP_ERROR_APPEND;
2459                 return;
2460         }
2461         
2462         mailstream_logger = imap_logger_append;
2463         
2464         r = mailimap_uidplus_append(param->imap, param->mailbox,
2465                             param->flag_list, NULL,
2466                             data, size, &val, &uid);
2467
2468         mailstream_logger = imap_logger_cmd;
2469         
2470         munmap(data, size);
2471         close(fd);
2472         
2473         result->error = r;
2474         result->uid = uid;
2475         debug_print("imap append run - end %i uid %d\n", r, uid);
2476 }
2477
2478 int imap_threaded_append(Folder * folder, const char * mailbox,
2479                          const char * filename,
2480                          struct mailimap_flag_list * flag_list,
2481                          int *uid)
2482 {
2483         struct append_param param;
2484         struct append_result result;
2485         mailimap * imap;
2486         
2487         debug_print("imap append - begin\n");
2488         
2489         imap = get_imap(folder);
2490         param.imap = imap;
2491         param.mailbox = mailbox;
2492         param.filename = filename;
2493         param.flag_list = flag_list;
2494         
2495         threaded_run(folder, &param, &result, append_run);
2496         
2497         if (result.error != MAILIMAP_NO_ERROR)
2498                 return result.error;
2499         
2500         debug_print("imap append - end\n");
2501         if (uid != NULL)
2502                 *uid = result.uid;
2503
2504         return result.error;
2505 }
2506
2507
2508
2509
2510 struct expunge_param {
2511         mailimap * imap;
2512 };
2513
2514 struct expunge_result {
2515         int error;
2516 };
2517
2518 static void expunge_run(struct etpan_thread_op * op)
2519 {
2520         struct expunge_param * param;
2521         struct expunge_result * result;
2522         int r;
2523         
2524         param = op->param;
2525         result = op->result;
2526
2527         CHECK_IMAP();
2528
2529         r = mailimap_expunge(param->imap);
2530         
2531         result->error = r;
2532         debug_print("imap expunge run - end %i\n", r);
2533 }
2534
2535 int imap_threaded_expunge(Folder * folder)
2536 {
2537         struct expunge_param param;
2538         struct expunge_result result;
2539         
2540         debug_print("imap expunge - begin\n");
2541         
2542         param.imap = get_imap(folder);
2543         
2544         threaded_run(folder, &param, &result, expunge_run);
2545         
2546         debug_print("imap expunge - end\n");
2547         
2548         return result.error;
2549 }
2550
2551
2552 struct copy_param {
2553         mailimap * imap;
2554         struct mailimap_set * set;
2555         const char * mb;
2556 };
2557
2558 struct copy_result {
2559         int error;
2560         struct mailimap_set *source;
2561         struct mailimap_set *dest;
2562 };
2563
2564 static void copy_run(struct etpan_thread_op * op)
2565 {
2566         struct copy_param * param;
2567         struct copy_result * result;
2568         int r;
2569         guint32 val;
2570         struct mailimap_set *source = NULL, *dest = NULL;
2571
2572         param = op->param;
2573         result = op->result;
2574
2575         CHECK_IMAP();
2576
2577         r = mailimap_uidplus_uid_copy(param->imap, param->set, param->mb,
2578                 &val, &source, &dest);
2579         
2580         result->error = r;
2581         if (r == 0) {
2582                 result->source = source;
2583                 result->dest = dest;
2584         } else {
2585                 result->source = NULL;
2586                 result->dest = NULL;
2587         }
2588         debug_print("imap copy run - end %i\n", r);
2589 }
2590
2591 int imap_threaded_copy(Folder * folder, struct mailimap_set * set,
2592                        const char * mb, struct mailimap_set **source,
2593                        struct mailimap_set **dest)
2594 {
2595         struct copy_param param;
2596         struct copy_result result;
2597         mailimap * imap;
2598         
2599         debug_print("imap copy - begin\n");
2600         
2601         imap = get_imap(folder);
2602         param.imap = imap;
2603         param.set = set;
2604         param.mb = mb;
2605         
2606         threaded_run(folder, &param, &result, copy_run);
2607         *source = NULL;
2608         *dest = NULL;
2609         
2610         if (result.error != MAILIMAP_NO_ERROR)
2611                 return result.error;
2612         
2613         *source = result.source;
2614         *dest = result.dest;
2615
2616         debug_print("imap copy - end\n");
2617         
2618         return result.error;
2619 }
2620
2621
2622
2623 struct store_param {
2624         mailimap * imap;
2625         struct mailimap_set * set;
2626         struct mailimap_store_att_flags * store_att_flags;
2627 };
2628
2629 struct store_result {
2630         int error;
2631 };
2632
2633 static void store_run(struct etpan_thread_op * op)
2634 {
2635         struct store_param * param;
2636         struct store_result * result;
2637         int r;
2638         
2639         param = op->param;
2640         result = op->result;
2641
2642         CHECK_IMAP();
2643
2644         r = mailimap_uid_store(param->imap, param->set,
2645                                param->store_att_flags);
2646         
2647         result->error = r;
2648         
2649         debug_print("imap store run - end %i\n", r);
2650 }
2651
2652 int imap_threaded_store(Folder * folder, struct mailimap_set * set,
2653                         struct mailimap_store_att_flags * store_att_flags)
2654 {
2655         struct store_param param;
2656         struct store_result result;
2657         mailimap * imap;
2658         
2659         debug_print("imap store - begin\n");
2660         
2661         imap = get_imap(folder);
2662         param.imap = imap;
2663         param.set = set;
2664         param.store_att_flags = store_att_flags;
2665         
2666         threaded_run(folder, &param, &result, store_run);
2667         
2668         if (result.error != MAILIMAP_NO_ERROR)
2669                 return result.error;
2670         
2671         debug_print("imap store - end\n");
2672         
2673         return result.error;
2674 }
2675
2676
2677 #define ENV_BUFFER_SIZE 512
2678
2679 static void do_exec_command(int fd, const char * command,
2680                             const char * servername, uint16_t port)
2681 {
2682         int i, maxopen;
2683 #ifdef SOLARIS
2684         char env_buffer[ENV_BUFFER_SIZE];
2685 #endif
2686         
2687         if (fork() > 0) {
2688                 /* Fork again to become a child of init rather than
2689                    the etpan client. */
2690                 exit(0);
2691         }
2692   
2693 #ifdef SOLARIS
2694         if (servername)
2695                 snprintf(env_buffer, ENV_BUFFER_SIZE,
2696                          "ETPANSERVER=%s", servername);
2697         else
2698                 snprintf(env_buffer, ENV_BUFFER_SIZE, "ETPANSERVER=");
2699         putenv(env_buffer);
2700 #else
2701         if (servername)
2702                 setenv("ETPANSERVER", servername, 1);
2703         else
2704                 unsetenv("ETPANSERVER");
2705 #endif
2706   
2707 #ifdef SOLARIS
2708         if (port)
2709                 snprintf(env_buffer, ENV_BUFFER_SIZE, "ETPANPORT=%d", port);
2710         else
2711                 snprintf(env_buffer, ENV_BUFFER_SIZE, "ETPANPORT=");
2712         putenv(env_buffer);
2713 #else
2714         if (port) {
2715                 char porttext[20];
2716                 
2717                 snprintf(porttext, sizeof(porttext), "%d", port);
2718                 setenv("ETPANPORT", porttext, 1);
2719         }
2720         else {
2721                 unsetenv("ETPANPORT");
2722         }
2723 #endif
2724                 
2725         /* Not a lot we can do if there's an error other than bail. */
2726         if (dup2(fd, 0) == -1)
2727                 exit(1);
2728         if (dup2(fd, 1) == -1)
2729                 exit(1);
2730   
2731         /* Should we close stderr and reopen /dev/null? */
2732   
2733         maxopen = sysconf(_SC_OPEN_MAX);
2734         for (i=3; i < maxopen; i++)
2735                 close(i);
2736   
2737 #ifdef TIOCNOTTY
2738         /* Detach from the controlling tty if we have one. Otherwise,
2739            SSH might do something stupid like trying to use it instead
2740            of running $SSH_ASKPASS. Doh. */
2741         fd = open("/dev/tty", O_RDONLY);
2742         if (fd != -1) {
2743                 ioctl(fd, TIOCNOTTY, NULL);
2744                 close(fd);
2745         }
2746 #endif /* TIOCNOTTY */
2747
2748         execl("/bin/sh", "/bin/sh", "-c", command, NULL);
2749   
2750         /* Eep. Shouldn't reach this */
2751         exit(1);
2752 }
2753
2754 static int subcommand_connect(const char *command,
2755                               const char *servername, uint16_t port)
2756 {
2757         /* SEB unsupported on Windows */
2758         int sockfds[2];
2759         pid_t childpid;
2760   
2761         if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockfds))
2762                 return -1;
2763   
2764         childpid = fork();
2765         if (!childpid) {
2766                 do_exec_command(sockfds[1], command, servername, port);
2767         }
2768         else if (childpid == -1) {
2769                 close(sockfds[0]);
2770                 close(sockfds[1]);
2771                 return -1;
2772         }
2773   
2774         close(sockfds[1]);
2775   
2776         /* Reap child, leaving grandchild process to run */
2777         waitpid(childpid, NULL, 0);
2778   
2779         return sockfds[0];
2780 }
2781
2782 static int socket_connect_cmd(mailimap * imap, const char * command,
2783                        const char * server, int port)
2784 {
2785         int fd;
2786         mailstream * s;
2787         int r;
2788         
2789         fd = subcommand_connect(command, server, port);
2790         if (fd < 0)
2791                 return MAILIMAP_ERROR_STREAM;
2792         
2793         s = mailstream_socket_open(fd);
2794         if (s == NULL) {
2795                 close(fd);
2796                 return MAILIMAP_ERROR_STREAM;
2797         }
2798         
2799         r = mailimap_connect(imap, s);
2800         if (r != MAILIMAP_NO_ERROR_AUTHENTICATED
2801         &&  r != MAILIMAP_NO_ERROR_NON_AUTHENTICATED) {
2802                 mailstream_close(s);
2803                 if (imap)
2804                         imap->imap_stream = NULL;
2805                 return r;
2806         }
2807         
2808         return r;
2809 }
2810
2811 /* connect cmd */
2812
2813 struct connect_cmd_param {
2814         mailimap * imap;
2815         const char * command;
2816         const char * server;
2817         int port;
2818 };
2819
2820 struct connect_cmd_result {
2821         int error;
2822 };
2823
2824 static void connect_cmd_run(struct etpan_thread_op * op)
2825 {
2826         int r;
2827         struct connect_cmd_param * param;
2828         struct connect_cmd_result * result;
2829         
2830         param = op->param;
2831         result = op->result;
2832         
2833         CHECK_IMAP();
2834
2835         r = socket_connect_cmd(param->imap, param->command,
2836                                param->server, param->port);
2837         
2838         result->error = r;
2839 }
2840
2841
2842 int imap_threaded_connect_cmd(Folder * folder, const char * command,
2843                               const char * server, int port)
2844 {
2845         struct connect_cmd_param param;
2846         struct connect_cmd_result result;
2847         chashdatum key;
2848         chashdatum value;
2849         mailimap * imap, * oldimap;
2850         
2851         oldimap = get_imap(folder);
2852
2853         imap = mailimap_new(0, NULL);
2854         
2855         if (oldimap) {
2856                 debug_print("deleting old imap %p\n", oldimap);
2857                 delete_imap(folder, oldimap);
2858         }
2859
2860         key.data = &folder;
2861         key.len = sizeof(folder);
2862         value.data = imap;
2863         value.len = 0;
2864         chash_set(session_hash, &key, &value, NULL);
2865         
2866         param.imap = imap;
2867         param.command = command;
2868         param.server = server;
2869         param.port = port;
2870         
2871         threaded_run(folder, &param, &result, connect_cmd_run);
2872         
2873         debug_print("connect_cmd ok %i with imap %p\n", result.error, imap);
2874         
2875         return result.error;
2876 }
2877
2878 void imap_threaded_cancel(Folder * folder)
2879 {
2880         mailimap * imap;
2881         
2882         imap = get_imap(folder);
2883         if (imap->imap_stream != NULL)
2884                 mailstream_cancel(imap->imap_stream);
2885 }
2886
2887 #else
2888
2889 void imap_main_init(void)
2890 {
2891 }
2892 void imap_main_done(void)
2893 {
2894 }
2895 void imap_main_set_timeout(int sec)
2896 {
2897 }
2898
2899 void imap_threaded_cancel(Folder * folder);
2900 {
2901 }
2902
2903 #endif