Fix bug #3009 ‘"Rebuild folder tree" causes SIGSEGV if a directory name isn't valid...
[claws.git] / src / pop.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2012 Hiroyuki Yamamoto and the Claws Mail team
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  * 
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #include "claws-features.h"
23 #endif
24
25 #include <glib.h>
26 #include <glib/gi18n.h>
27 #include <stdio.h>
28 #include <string.h>
29 #include <stdarg.h>
30 #include <ctype.h>
31 #include <unistd.h>
32 #include <time.h>
33 #include <errno.h>
34
35 #include "pop.h"
36 #include "md5.h"
37 #include "prefs_account.h"
38 #include "utils.h"
39 #include "recv.h"
40 #include "partial_download.h"
41 #include "log.h"
42 #include "hooks.h"
43
44 static gint pop3_greeting_recv          (Pop3Session *session,
45                                          const gchar *msg);
46 static gint pop3_getauth_user_send      (Pop3Session *session);
47 static gint pop3_getauth_pass_send      (Pop3Session *session);
48 static gint pop3_getauth_apop_send      (Pop3Session *session);
49 #ifdef USE_GNUTLS
50 static gint pop3_stls_send              (Pop3Session *session);
51 static gint pop3_stls_recv              (Pop3Session *session);
52 #endif
53 static gint pop3_getrange_stat_send     (Pop3Session *session);
54 static gint pop3_getrange_stat_recv     (Pop3Session *session,
55                                          const gchar *msg);
56 static gint pop3_getrange_last_send     (Pop3Session *session);
57 static gint pop3_getrange_last_recv     (Pop3Session *session,
58                                          const gchar *msg);
59 static gint pop3_getrange_uidl_send     (Pop3Session *session);
60 static gint pop3_getrange_uidl_recv     (Pop3Session *session,
61                                          const gchar *data,
62                                          guint        len);
63 static gint pop3_getsize_list_send      (Pop3Session *session);
64 static gint pop3_getsize_list_recv      (Pop3Session *session,
65                                          const gchar *data,
66                                          guint        len);
67 static gint pop3_retr_send              (Pop3Session *session);
68 static gint pop3_retr_recv              (Pop3Session *session,
69                                          const gchar *data,
70                                          guint        len);
71 static gint pop3_delete_send            (Pop3Session *session);
72 static gint pop3_delete_recv            (Pop3Session *session);
73 static gint pop3_logout_send            (Pop3Session *session);
74
75 static void pop3_gen_send               (Pop3Session    *session,
76                                          const gchar    *format, ...);
77
78 static void pop3_session_destroy        (Session        *session);
79
80 static gint pop3_write_msg_to_file      (const gchar    *file,
81                                          const gchar    *data,
82                                          guint           len,
83                                          const gchar    *prefix);
84
85 static Pop3State pop3_lookup_next       (Pop3Session    *session);
86 static Pop3ErrorValue pop3_ok           (Pop3Session    *session,
87                                          const gchar    *msg);
88
89 static gint pop3_session_recv_msg               (Session        *session,
90                                                  const gchar    *msg);
91 static gint pop3_session_recv_data_finished     (Session        *session,
92                                                  guchar         *data,
93                                                  guint           len);
94 static void pop3_get_uidl_table(PrefsAccount *ac_prefs, Pop3Session *session);
95
96 static gint pop3_greeting_recv(Pop3Session *session, const gchar *msg)
97 {
98         session->state = POP3_GREETING;
99
100         session->greeting = g_strdup(msg);
101         return PS_SUCCESS;
102 }
103
104 #ifdef USE_GNUTLS
105 static gint pop3_stls_send(Pop3Session *session)
106 {
107         session->state = POP3_STLS;
108         pop3_gen_send(session, "STLS");
109         return PS_SUCCESS;
110 }
111
112 static gint pop3_stls_recv(Pop3Session *session)
113 {
114         if (session_start_tls(SESSION(session)) < 0) {
115                 session->error_val = PS_SOCKET;
116                 return -1;
117         }
118         return PS_SUCCESS;
119 }
120 #endif /* USE_GNUTLS */
121
122 static gint pop3_getauth_user_send(Pop3Session *session)
123 {
124         cm_return_val_if_fail(session->user != NULL, -1);
125
126         session->state = POP3_GETAUTH_USER;
127         pop3_gen_send(session, "USER %s", session->user);
128         return PS_SUCCESS;
129 }
130
131 static gint pop3_getauth_pass_send(Pop3Session *session)
132 {
133         cm_return_val_if_fail(session->pass != NULL, -1);
134
135         session->state = POP3_GETAUTH_PASS;
136         pop3_gen_send(session, "PASS %s", session->pass);
137         return PS_SUCCESS;
138 }
139
140 static gint pop3_getauth_apop_send(Pop3Session *session)
141 {
142         gchar *start, *end;
143         gchar *apop_str;
144         gchar md5sum[33];
145
146         cm_return_val_if_fail(session->user != NULL, -1);
147         cm_return_val_if_fail(session->pass != NULL, -1);
148
149         session->state = POP3_GETAUTH_APOP;
150
151         if ((start = strchr(session->greeting, '<')) == NULL) {
152                 log_error(LOG_PROTOCOL, _("Required APOP timestamp not found "
153                             "in greeting\n"));
154                 session->error_val = PS_PROTOCOL;
155                 return -1;
156         }
157
158         if ((end = strchr(start, '>')) == NULL || end == start + 1) {
159                 log_error(LOG_PROTOCOL, _("Timestamp syntax error in greeting\n"));
160                 session->error_val = PS_PROTOCOL;
161                 return -1;
162         }
163         *(end + 1) = '\0';
164
165         if (!is_ascii_str(start)) {
166                 log_error(LOG_PROTOCOL, _("Timestamp syntax error in greeting (not ASCII)\n"));
167                 session->error_val = PS_PROTOCOL;
168                 return -1;
169         }
170
171         apop_str = g_strconcat(start, session->pass, NULL);
172         md5_hex_digest(md5sum, apop_str);
173         g_free(apop_str);
174
175         pop3_gen_send(session, "APOP %s %s", session->user, md5sum);
176
177         return PS_SUCCESS;
178 }
179
180 static gint pop3_getrange_stat_send(Pop3Session *session)
181 {
182         session->state = POP3_GETRANGE_STAT;
183         pop3_gen_send(session, "STAT");
184         return PS_SUCCESS;
185 }
186
187 static gint pop3_getrange_stat_recv(Pop3Session *session, const gchar *msg)
188 {
189         if (sscanf(msg, "%d %d", &session->count, &session->total_bytes) != 2) {
190                 log_error(LOG_PROTOCOL, _("POP3 protocol error\n"));
191                 session->error_val = PS_PROTOCOL;
192                 return -1;
193         } else {
194                 if (session->count == 0) {
195                         session->uidl_is_valid = TRUE;
196                 } else {
197                         session->msg = g_new0(Pop3MsgInfo, session->count + 1);
198                         session->cur_msg = 1;
199                 }
200         }
201
202         return PS_SUCCESS;
203 }
204
205 static gint pop3_getrange_last_send(Pop3Session *session)
206 {
207         session->state = POP3_GETRANGE_LAST;
208         pop3_gen_send(session, "LAST");
209         return PS_SUCCESS;
210 }
211
212 static gint pop3_getrange_last_recv(Pop3Session *session, const gchar *msg)
213 {
214         gint last;
215
216         if (sscanf(msg, "%d", &last) == 0) {
217                 log_warning(LOG_PROTOCOL, _("POP3 protocol error\n"));
218                 session->error_val = PS_PROTOCOL;
219                 return -1;
220         } else {
221                 if (session->count > last) {
222                         session->new_msg_exist = TRUE;
223                         session->cur_msg = last + 1;
224                 } else
225                         session->cur_msg = 0;
226         }
227
228         return PS_SUCCESS;
229 }
230
231 static gint pop3_getrange_uidl_send(Pop3Session *session)
232 {
233         session->state = POP3_GETRANGE_UIDL;
234         pop3_gen_send(session, "UIDL");
235         return PS_SUCCESS;
236 }
237
238 static gint pop3_getrange_uidl_recv(Pop3Session *session, const gchar *data,
239                                     guint len)
240 {
241         gchar id[IDLEN + 1];
242         gchar buf[POPBUFSIZE];
243         gint buf_len;
244         guint32 num;
245         time_t recv_time;
246         gint partial_recv;
247         const gchar *p = data;
248         const gchar *lastp = data + len;
249         const gchar *newline;
250
251         while (p < lastp) {
252                 if ((newline = memchr(p, '\r', lastp - p)) == NULL)
253                         return -1;
254                 buf_len = MIN(newline - p, sizeof(buf) - 1);
255                 memcpy(buf, p, buf_len);
256                 buf[buf_len] = '\0';
257
258                 p = newline + 1;
259                 if (p < lastp && *p == '\n') p++;
260
261                 if (sscanf(buf, "%d %" Xstr(IDLEN) "s", &num, id) != 2 ||
262                     num <= 0 || num > session->count) {
263                         log_warning(LOG_PROTOCOL, _("invalid UIDL response: %s\n"), buf);
264                         continue;
265                 }
266
267                 session->msg[num].uidl = g_strdup(id);
268
269                 recv_time = (time_t)(GPOINTER_TO_INT(g_hash_table_lookup(
270                                         session->uidl_table, id)));
271                 session->msg[num].recv_time = recv_time;
272
273                 if (recv_time != RECV_TIME_NONE) {
274                         debug_print("num %d uidl %s: already got it\n", num, id);               
275                 } else {
276                         debug_print("num %d uidl %s: unknown\n", num, id);
277                 }
278
279                 partial_recv = (gint)(GPOINTER_TO_INT(g_hash_table_lookup(
280                                         session->partial_recv_table, id)));
281
282                 if (recv_time != RECV_TIME_NONE
283                 || partial_recv != POP3_TOTALLY_RECEIVED) {
284                         session->msg[num].received = 
285                                 (partial_recv != POP3_MUST_COMPLETE_RECV);
286                         session->msg[num].partial_recv = partial_recv;
287                         if (partial_recv == POP3_MUST_COMPLETE_RECV)
288                                 session->new_msg_exist = TRUE;
289                 }
290                 if (!session->new_msg_exist &&
291                     (recv_time == RECV_TIME_NONE ||
292                      session->ac_prefs->rmmail)) {
293                         session->cur_msg = num;
294                         session->new_msg_exist = TRUE;
295                 }
296         }
297
298         session->uidl_is_valid = TRUE;
299         return PS_SUCCESS;
300 }
301
302 static gint pop3_getsize_list_send(Pop3Session *session)
303 {
304         session->state = POP3_GETSIZE_LIST;
305         pop3_gen_send(session, "LIST");
306         return PS_SUCCESS;
307 }
308
309 static gint pop3_getsize_list_recv(Pop3Session *session, const gchar *data,
310                                    guint len)
311 {
312         gchar buf[POPBUFSIZE];
313         gint buf_len;
314         guint num, size;
315         const gchar *p = data;
316         const gchar *lastp = data + len;
317         const gchar *newline;
318
319         while (p < lastp) {
320                 if ((newline = memchr(p, '\r', lastp - p)) == NULL)
321                         return -1;
322                 buf_len = MIN(newline - p, sizeof(buf) - 1);
323                 memcpy(buf, p, buf_len);
324                 buf[buf_len] = '\0';
325
326                 p = newline + 1;
327                 if (p < lastp && *p == '\n') p++;
328
329                 if (sscanf(buf, "%u %u", &num, &size) != 2) {
330                         session->error_val = PS_PROTOCOL;
331                         return -1;
332                 }
333
334                 if (num > 0 && num <= session->count)
335                         session->msg[num].size = size;
336                 if (num > 0 && num < session->cur_msg)
337                         session->cur_total_bytes += size;
338         }
339
340         return PS_SUCCESS;
341 }
342
343 static gint pop3_retr_send(Pop3Session *session)
344 {
345         session->state = POP3_RETR;
346         debug_print("retrieving %d [%s]\n", session->cur_msg, 
347                 session->msg[session->cur_msg].uidl ?
348                  session->msg[session->cur_msg].uidl:" ");
349         pop3_gen_send(session, "RETR %d", session->cur_msg);
350         return PS_SUCCESS;
351 }
352
353 static gint pop3_retr_recv(Pop3Session *session, const gchar *data, guint len)
354 {
355         gchar *file;
356         gint drop_ok;
357         MailReceiveData mail_receive_data;
358
359         /* NOTE: we allocate a slightly larger buffer with a zero terminator
360          * because some plugins may think that it has a C string. */ 
361         mail_receive_data.session  = session;
362         mail_receive_data.data     = g_new0(gchar, len + 1);
363         mail_receive_data.data_len = len;
364         memcpy(mail_receive_data.data, data, len); 
365         
366         hooks_invoke(MAIL_RECEIVE_HOOKLIST, &mail_receive_data);
367
368         file = get_tmp_file();
369         if (pop3_write_msg_to_file(file, mail_receive_data.data, 
370                                    mail_receive_data.data_len, NULL) < 0) {
371                 g_free(file);
372                 g_free(mail_receive_data.data);
373                 session->error_val = PS_IOERR;
374                 return -1;
375         }
376         g_free(mail_receive_data.data);
377
378         if (session->msg[session->cur_msg].partial_recv 
379             == POP3_MUST_COMPLETE_RECV) {
380                 gchar *old_file = partial_get_filename(
381                                 session->ac_prefs->recv_server,
382                                 session->ac_prefs->userid,
383                                 session->msg[session->cur_msg].uidl);
384                 
385                 if (old_file) {
386                         partial_delete_old(old_file);
387                         g_free(old_file);
388                 }
389         } 
390
391         /* drop_ok: 0: success 1: don't receive -1: error */
392         drop_ok = session->drop_message(session, file);
393
394         g_free(file);
395         if (drop_ok < 0) {
396                 session->error_val = PS_IOERR;
397                 return -1;
398         }
399         
400         session->cur_total_bytes += session->msg[session->cur_msg].size;
401         session->cur_total_recv_bytes += session->msg[session->cur_msg].size;
402         session->cur_total_num++;
403
404         session->msg[session->cur_msg].received = TRUE;
405         session->msg[session->cur_msg].partial_recv = POP3_TOTALLY_RECEIVED;
406
407         session->msg[session->cur_msg].recv_time =
408                 drop_ok == 1 ? RECV_TIME_KEEP : session->current_time;
409
410         return PS_SUCCESS;
411 }
412
413 static gint pop3_top_send(Pop3Session *session, gint max_size)
414 {
415         gint num_lines = (max_size*1024)/82; /* consider lines to be 80 chars */
416         session->state = POP3_TOP;
417         pop3_gen_send(session, "TOP %d %d", session->cur_msg, num_lines);
418         return PS_SUCCESS;
419 }
420
421 static gint pop3_top_recv(Pop3Session *session, const gchar *data, guint len)
422 {
423         gchar *file;
424         gint drop_ok;
425         MailReceiveData mail_receive_data;
426         gchar *partial_notice = NULL;
427         
428         /* NOTE: we allocate a slightly larger buffer with a zero terminator
429          * because some plugins may think that it has a C string. */ 
430         mail_receive_data.session  = session;
431         mail_receive_data.data     = g_new0(gchar, len + 1);
432         mail_receive_data.data_len = len;
433         memcpy(mail_receive_data.data, data, len);
434         
435         hooks_invoke(MAIL_RECEIVE_HOOKLIST, &mail_receive_data);
436
437         partial_notice = g_strdup_printf("SC-Marked-For-Download: 0\n"
438                                          "SC-Partially-Retrieved: %s\n"
439                                          "SC-Account-Server: %s\n"
440                                          "SC-Account-Login: %s\n"
441                                          "SC-Message-Size: %d",
442                                          session->msg[session->cur_msg].uidl,
443                                          session->ac_prefs->recv_server,
444                                          session->ac_prefs->userid,
445                                          session->msg[session->cur_msg].size);
446         file = get_tmp_file();
447         if (pop3_write_msg_to_file(file, mail_receive_data.data,
448                                    mail_receive_data.data_len,  
449                                    partial_notice) < 0) {
450                 g_free(file);
451                 g_free(mail_receive_data.data);
452                 session->error_val = PS_IOERR;
453                 g_free(partial_notice);
454                 return -1;
455         }
456         g_free(mail_receive_data.data);
457         g_free(partial_notice);
458
459         /* drop_ok: 0: success 1: don't receive -1: error */
460         drop_ok = session->drop_message(session, file);
461         g_free(file);
462         if (drop_ok < 0) {
463                 session->error_val = PS_IOERR;
464                 return -1;
465         }
466
467         session->cur_total_bytes += session->msg[session->cur_msg].size;
468         session->cur_total_recv_bytes += session->msg[session->cur_msg].size;
469         session->cur_total_num++;
470
471         session->msg[session->cur_msg].received = TRUE;
472         session->msg[session->cur_msg].partial_recv = POP3_PARTIALLY_RECEIVED;
473         session->msg[session->cur_msg].recv_time =
474                 drop_ok == 1 ? RECV_TIME_KEEP : session->current_time;
475
476         return PS_SUCCESS;
477 }
478
479 static gint pop3_delete_send(Pop3Session *session)
480 {
481         session->state = POP3_DELETE;
482         pop3_gen_send(session, "DELE %d", session->cur_msg);
483         return PS_SUCCESS;
484 }
485
486 static gint pop3_delete_recv(Pop3Session *session)
487 {
488         session->msg[session->cur_msg].deleted = TRUE;
489         return PS_SUCCESS;
490 }
491
492 static gint pop3_logout_send(Pop3Session *session)
493 {
494         session->state = POP3_LOGOUT;
495         pop3_gen_send(session, "QUIT");
496         return PS_SUCCESS;
497 }
498
499 static void pop3_gen_send(Pop3Session *session, const gchar *format, ...)
500 {
501         gchar buf[POPBUFSIZE + 1];
502         va_list args;
503
504         va_start(args, format);
505         g_vsnprintf(buf, sizeof(buf) - 2, format, args);
506         va_end(args);
507
508         if (!g_ascii_strncasecmp(buf, "PASS ", 5))
509                 log_print(LOG_PROTOCOL, "POP3> PASS ********\n");
510         else
511                 log_print(LOG_PROTOCOL, "POP3> %s\n", buf);
512
513         session_send_msg(SESSION(session), SESSION_MSG_NORMAL, buf);
514 }
515
516 Session *pop3_session_new(PrefsAccount *account)
517 {
518         Pop3Session *session;
519
520         cm_return_val_if_fail(account != NULL, NULL);
521
522         session = g_new0(Pop3Session, 1);
523
524         session_init(SESSION(session), account, FALSE);
525
526         SESSION(session)->type = SESSION_POP3;
527
528         SESSION(session)->recv_msg = pop3_session_recv_msg;
529         SESSION(session)->recv_data_finished = pop3_session_recv_data_finished;
530         SESSION(session)->send_data_finished = NULL;
531
532         SESSION(session)->destroy = pop3_session_destroy;
533
534         session->state = POP3_READY;
535         session->ac_prefs = account;
536         session->pop_before_smtp = FALSE;
537         pop3_get_uidl_table(account, session);
538         session->current_time = time(NULL);
539         session->error_val = PS_SUCCESS;
540         session->error_msg = NULL;
541
542         return SESSION(session);
543 }
544
545 static void pop3_session_destroy(Session *session)
546 {
547         Pop3Session *pop3_session = POP3_SESSION(session);
548         gint n;
549
550         cm_return_if_fail(session != NULL);
551
552         for (n = 1; n <= pop3_session->count; n++)
553                 g_free(pop3_session->msg[n].uidl);
554         g_free(pop3_session->msg);
555
556         if (pop3_session->uidl_table) {
557                 hash_free_strings(pop3_session->uidl_table);
558                 g_hash_table_destroy(pop3_session->uidl_table);
559         }
560
561         if (pop3_session->partial_recv_table) {
562                 hash_free_strings(pop3_session->partial_recv_table);
563                 g_hash_table_destroy(pop3_session->partial_recv_table);
564         }
565
566         g_free(pop3_session->greeting);
567         g_free(pop3_session->user);
568         g_free(pop3_session->pass);
569         g_free(pop3_session->error_msg);
570 }
571
572 static void pop3_get_uidl_table(PrefsAccount *ac_prefs, Pop3Session *session)
573 {
574         GHashTable *table;
575         GHashTable *partial_recv_table;
576         gchar *path;
577         FILE *fp;
578         gchar buf[POPBUFSIZE];
579         gchar uidl[POPBUFSIZE];
580         time_t recv_time;
581         time_t now;
582         gint partial_recv;
583         gchar *sanitized_uid = g_strdup(ac_prefs->userid);
584         
585         subst_for_filename(sanitized_uid);
586         
587         table = g_hash_table_new(g_str_hash, g_str_equal);
588         partial_recv_table = g_hash_table_new(g_str_hash, g_str_equal);
589
590         path = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
591                            "uidl", G_DIR_SEPARATOR_S, ac_prefs->recv_server,
592                            "-", sanitized_uid, NULL);
593                            
594         g_free(sanitized_uid);
595         if ((fp = g_fopen(path, "rb")) == NULL) {
596                 if (ENOENT != errno) FILE_OP_ERROR(path, "fopen");
597                 g_free(path);
598                 path = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
599                                    "uidl-", ac_prefs->recv_server,
600                                    "-", ac_prefs->userid, NULL);
601                 if ((fp = g_fopen(path, "rb")) == NULL) {
602                         if (ENOENT != errno) FILE_OP_ERROR(path, "fopen");
603                         g_free(path);
604                         session->uidl_table = table;
605                         session->partial_recv_table = partial_recv_table;
606                         return;
607                 }
608         }
609         g_free(path);
610
611         now = time(NULL);
612
613         while (fgets(buf, sizeof(buf), fp) != NULL) {
614                 gchar tmp[POPBUFSIZE];
615                 strretchomp(buf);
616                 recv_time = RECV_TIME_NONE;
617                 partial_recv = POP3_TOTALLY_RECEIVED;
618                 
619                 if (sscanf(buf, "%s\t%ld\t%s", uidl, (long int *) &recv_time, tmp) < 3) {
620                         if (sscanf(buf, "%s\t%ld", uidl, (long int *) &recv_time) != 2) {
621                                 if (sscanf(buf, "%s", uidl) != 1)
622                                         continue;
623                                 else {
624                                         recv_time = now;
625                                         strcpy(tmp, "0");
626                                 }
627                         } else {
628                                 strcpy(tmp, "0");
629                         }
630                 }
631
632                 if (recv_time == RECV_TIME_NONE)
633                         recv_time = RECV_TIME_RECEIVED;
634                 g_hash_table_insert(table, g_strdup(uidl),
635                                     GINT_TO_POINTER(recv_time));
636                 if (strlen(tmp) == 1)
637                         partial_recv = atoi(tmp); /* totally received ?*/
638                 else
639                         partial_recv = POP3_MUST_COMPLETE_RECV;
640
641                 g_hash_table_insert(partial_recv_table, g_strdup(uidl),
642                                     GINT_TO_POINTER(partial_recv));
643         }
644
645         fclose(fp);
646         session->uidl_table = table;
647         session->partial_recv_table = partial_recv_table;
648         
649         return;
650 }
651
652 #define TRY(func) \
653 if (!(func)) \
654 { \
655         g_warning("failed to write\n"); \
656         goto err_write;                 \
657 } \
658
659 gint pop3_write_uidl_list(Pop3Session *session)
660 {
661         gchar *path, *tmp_path;
662         FILE *fp;
663         Pop3MsgInfo *msg;
664         gint n;
665         gchar *sanitized_uid = g_strdup(session->ac_prefs->userid);
666         
667         subst_for_filename(sanitized_uid);
668
669         if (!session->uidl_is_valid) {
670                 g_free(sanitized_uid);
671                 return 0;
672         }
673
674         path = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
675                            "uidl", G_DIR_SEPARATOR_S,
676                            session->ac_prefs->recv_server,
677                            "-", sanitized_uid, NULL);
678         tmp_path = g_strconcat(path, ".tmp", NULL);
679
680         g_free(sanitized_uid);
681
682         if ((fp = g_fopen(tmp_path, "wb")) == NULL) {
683                 FILE_OP_ERROR(tmp_path, "fopen");
684                 goto err_write;
685         }
686
687         for (n = 1; n <= session->count; n++) {
688                 msg = &session->msg[n];
689                 if (msg->uidl && msg->received &&
690                     (!msg->deleted || session->state != POP3_DONE))
691                         TRY(fprintf(fp, "%s\t%ld\t%d\n", 
692                                 msg->uidl, (long int) 
693                                 msg->recv_time, 
694                                 msg->partial_recv) 
695                             > 0);
696         }
697
698         if (fclose(fp) == EOF) {
699                 FILE_OP_ERROR(tmp_path, "fclose");
700                 fp = NULL;
701                 goto err_write;
702         }
703         fp = NULL;
704 #ifdef G_OS_WIN32
705         claws_unlink(path);
706 #endif
707         if (g_rename(tmp_path, path) < 0) {
708                 FILE_OP_ERROR(path, "rename");
709                 goto err_write;
710         }
711         g_free(path);
712         g_free(tmp_path);
713         return 0;
714 err_write:
715         if (fp)
716                 fclose(fp);
717         g_free(path);
718         g_free(tmp_path);
719         return -1;
720 }
721
722 #undef TRY
723
724 static gint pop3_write_msg_to_file(const gchar *file, const gchar *data,
725                                    guint len, const gchar *prefix)
726 {
727         FILE *fp;
728         const gchar *prev, *cur;
729
730         cm_return_val_if_fail(file != NULL, -1);
731
732         if ((fp = g_fopen(file, "wb")) == NULL) {
733                 FILE_OP_ERROR(file, "fopen");
734                 return -1;
735         }
736
737         if (change_file_mode_rw(fp, file) < 0)
738                 FILE_OP_ERROR(file, "chmod");
739
740         if (prefix != NULL) {
741                 if (fprintf(fp, "%s\n", prefix) < 0) {
742                         FILE_OP_ERROR(file, "fprintf");
743                         fclose(fp);
744                         claws_unlink(file);
745                         return -1;
746                 }
747         }
748         
749         /* +------------------+----------------+--------------------------+ *
750          * ^data              ^prev            ^cur             data+len-1^ */
751
752         prev = data;
753         while ((cur = (gchar *)my_memmem(prev, len - (prev - data), "\r\n", 2))
754                != NULL) {
755                 if ((cur > prev && fwrite(prev, 1, cur - prev, fp) < 1) ||
756                     fputc('\n', fp) == EOF) {
757                         FILE_OP_ERROR(file, "fwrite");
758                         g_warning("can't write to file: %s\n", file);
759                         fclose(fp);
760                         claws_unlink(file);
761                         return -1;
762                 }
763
764                 if (cur == data + len - 1) {
765                         prev = cur + 1;
766                         break;
767                 }
768
769                 if (*(cur + 1) == '\n')
770                         prev = cur + 2;
771                 else
772                         prev = cur + 1;
773
774                 if (prev - data < len - 1 && *prev == '.' && *(prev + 1) == '.')
775                         prev++;
776
777                 if (prev - data >= len)
778                         break;
779         }
780
781         if (prev - data < len &&
782             fwrite(prev, 1, len - (prev - data), fp) < 1) {
783                 FILE_OP_ERROR(file, "fwrite");
784                 g_warning("can't write to file: %s\n", file);
785                 fclose(fp);
786                 claws_unlink(file);
787                 return -1;
788         }
789         if (data[len - 1] != '\r' && data[len - 1] != '\n') {
790                 if (fputc('\n', fp) == EOF) {
791                         FILE_OP_ERROR(file, "fputc");
792                         g_warning("can't write to file: %s\n", file);
793                         fclose(fp);
794                         claws_unlink(file);
795                         return -1;
796                 }
797         }
798
799         if (fclose(fp) == EOF) {
800                 FILE_OP_ERROR(file, "fclose");
801                 claws_unlink(file);
802                 return -1;
803         }
804
805         return 0;
806 }
807
808 static Pop3State pop3_lookup_next(Pop3Session *session)
809 {
810         Pop3MsgInfo *msg;
811         PrefsAccount *ac = session->ac_prefs;
812         gint size;
813         gboolean size_limit_over;
814
815         for (;;) {
816                 msg = &session->msg[session->cur_msg];
817                 size = msg->size;
818                 size_limit_over =
819                     (ac->enable_size_limit &&
820                      ac->size_limit > 0 &&
821                      size > ac->size_limit * 1024);
822
823                 if (ac->rmmail &&
824                     msg->recv_time != RECV_TIME_NONE &&
825                     msg->recv_time != RECV_TIME_KEEP &&
826                     msg->partial_recv == POP3_TOTALLY_RECEIVED &&
827                     session->current_time - msg->recv_time >=
828                     ((ac->msg_leave_time * 24 * 60 * 60) +
829                      (ac->msg_leave_hour * 60 * 60))) {
830                         log_message(LOG_PROTOCOL, 
831                                         _("POP3: Deleting expired message %d [%s]\n"),
832                                         session->cur_msg, msg->uidl?msg->uidl:" ");
833                         session->cur_total_bytes += size;
834                         pop3_delete_send(session);
835                         return POP3_DELETE;
836                 }
837
838                 if (size_limit_over) {
839                         if (!msg->received && msg->partial_recv != 
840                             POP3_MUST_COMPLETE_RECV) {
841                                 pop3_top_send(session, ac->size_limit);
842                                 return POP3_TOP;
843                         } else if (msg->partial_recv == POP3_MUST_COMPLETE_RECV)
844                                 break;
845
846                         log_message(LOG_PROTOCOL, 
847                                         _("POP3: Skipping message %d [%s] (%d bytes)\n"),
848                                         session->cur_msg, msg->uidl?msg->uidl:" ", size);
849                 }
850                 
851                 if (size == 0 || msg->received || size_limit_over) {
852                         session->cur_total_bytes += size;
853                         if (session->cur_msg == session->count) {
854                                 pop3_logout_send(session);
855                                 return POP3_LOGOUT;
856                         } else
857                                 session->cur_msg++;
858                 } else
859                         break;
860         }
861
862         pop3_retr_send(session);
863         return POP3_RETR;
864 }
865
866 static Pop3ErrorValue pop3_ok(Pop3Session *session, const gchar *msg)
867 {
868         Pop3ErrorValue ok;
869
870         log_print(LOG_PROTOCOL, "POP3< %s\n", msg);
871
872         if (!strncmp(msg, "+OK", 3))
873                 ok = PS_SUCCESS;
874         else if (!strncmp(msg, "-ERR", 4)) {
875                 if (strstr(msg + 4, "lock") ||
876                     strstr(msg + 4, "Lock") ||
877                     strstr(msg + 4, "LOCK") ||
878                     strstr(msg + 4, "wait")) {
879                         log_error(LOG_PROTOCOL, _("mailbox is locked\n"));
880                         ok = PS_LOCKBUSY;
881                 } else if (strcasestr(msg + 4, "timeout")) {
882                         log_error(LOG_PROTOCOL, _("Session timeout\n"));
883                         ok = PS_ERROR;
884                 } else {
885                         switch (session->state) {
886 #ifdef USE_GNUTLS
887                         case POP3_STLS:
888                                 log_error(LOG_PROTOCOL, _("couldn't start TLS session\n"));
889                                 ok = PS_ERROR;
890                                 break;
891 #endif
892                         case POP3_GETAUTH_USER:
893                         case POP3_GETAUTH_PASS:
894                         case POP3_GETAUTH_APOP:
895                                 log_error(LOG_PROTOCOL, _("error occurred on authentication\n"));
896                                 ok = PS_AUTHFAIL;
897                                 break;
898                         case POP3_GETRANGE_LAST:
899                         case POP3_GETRANGE_UIDL:
900                         case POP3_TOP:
901                                 log_warning(LOG_PROTOCOL, _("command not supported\n"));
902                                 ok = PS_NOTSUPPORTED;
903                                 break;
904                                 
905                         default:
906                                 log_error(LOG_PROTOCOL, _("error occurred on POP3 session\n"));
907                                 ok = PS_ERROR;
908                         }
909                 }
910
911                 g_free(session->error_msg);
912                 session->error_msg = g_strdup(msg);
913                 g_printerr("POP3: %s\n", msg);
914         } else
915                 ok = PS_PROTOCOL;
916
917         session->error_val = ok;
918         return ok;
919 }
920
921 static gint pop3_session_recv_msg(Session *session, const gchar *msg)
922 {
923         Pop3Session *pop3_session = POP3_SESSION(session);
924         Pop3ErrorValue val = PS_SUCCESS;
925         const gchar *body;
926
927         body = msg;
928         if (pop3_session->state != POP3_GETRANGE_UIDL_RECV &&
929             pop3_session->state != POP3_GETSIZE_LIST_RECV) {
930                 val = pop3_ok(pop3_session, msg);
931                 if (val != PS_SUCCESS) {
932                         if (val != PS_NOTSUPPORTED) {
933                                 pop3_session->state = POP3_ERROR;
934                                 return -1;
935                         }
936                 }
937
938                 if (*body == '+' || *body == '-')
939                         body++;
940                 while (g_ascii_isalpha(*body))
941                         body++;
942                 while (g_ascii_isspace(*body))
943                         body++;
944         }
945
946         switch (pop3_session->state) {
947         case POP3_READY:
948         case POP3_GREETING:
949                 pop3_greeting_recv(pop3_session, body);
950 #ifdef USE_GNUTLS
951                 if (pop3_session->ac_prefs->ssl_pop == SSL_STARTTLS)
952                         val = pop3_stls_send(pop3_session);
953                 else
954 #endif
955                 if (pop3_session->ac_prefs->use_apop_auth)
956                         val = pop3_getauth_apop_send(pop3_session);
957                 else
958                         val = pop3_getauth_user_send(pop3_session);
959                 break;
960 #ifdef USE_GNUTLS
961         case POP3_STLS:
962                 if (pop3_stls_recv(pop3_session) != PS_SUCCESS)
963                         return -1;
964                 if (pop3_session->ac_prefs->use_apop_auth)
965                         val = pop3_getauth_apop_send(pop3_session);
966                 else
967                         val = pop3_getauth_user_send(pop3_session);
968                 break;
969 #endif
970         case POP3_GETAUTH_USER:
971                 val = pop3_getauth_pass_send(pop3_session);
972                 break;
973         case POP3_GETAUTH_PASS:
974         case POP3_GETAUTH_APOP:
975                 if (!pop3_session->pop_before_smtp)
976                         val = pop3_getrange_stat_send(pop3_session);
977                 else
978                         val = pop3_logout_send(pop3_session);
979                 break;
980         case POP3_GETRANGE_STAT:
981                 if (pop3_getrange_stat_recv(pop3_session, body) < 0)
982                         return -1;
983                 if (pop3_session->count > 0)
984                         val = pop3_getrange_uidl_send(pop3_session);
985                 else
986                         val = pop3_logout_send(pop3_session);
987                 break;
988         case POP3_GETRANGE_LAST:
989                 if (val == PS_NOTSUPPORTED)
990                         pop3_session->error_val = PS_SUCCESS;
991                 else if (pop3_getrange_last_recv(pop3_session, body) < 0)
992                         return -1;
993                 if (pop3_session->cur_msg > 0)
994                         val = pop3_getsize_list_send(pop3_session);
995                 else
996                         val = pop3_logout_send(pop3_session);
997                 break;
998         case POP3_GETRANGE_UIDL:
999                 if (val == PS_NOTSUPPORTED) {
1000                         pop3_session->error_val = PS_SUCCESS;
1001                         val = pop3_getrange_last_send(pop3_session);
1002                 } else {
1003                         pop3_session->state = POP3_GETRANGE_UIDL_RECV;
1004                         session_recv_data(session, 0, ".\r\n");
1005                 }
1006                 break;
1007         case POP3_GETSIZE_LIST:
1008                 pop3_session->state = POP3_GETSIZE_LIST_RECV;
1009                 session_recv_data(session, 0, ".\r\n");
1010                 break;
1011         case POP3_RETR:
1012                 pop3_session->state = POP3_RETR_RECV;
1013                 session_recv_data(session, 0, ".\r\n");
1014                 break;
1015         case POP3_TOP:
1016                 if (val == PS_NOTSUPPORTED) {
1017                         pop3_session->error_val = PS_SUCCESS;
1018                 } else {
1019                         pop3_session->state = POP3_TOP_RECV;
1020                         session_recv_data(session, 0, ".\r\n");
1021                 }
1022                 break;
1023         case POP3_DELETE:
1024                 pop3_delete_recv(pop3_session);
1025                 if (pop3_session->cur_msg == pop3_session->count)
1026                         val = pop3_logout_send(pop3_session);
1027                 else {
1028                         pop3_session->cur_msg++;
1029                         if (pop3_lookup_next(pop3_session) == POP3_ERROR)
1030                                 return -1;
1031                 }
1032                 break;
1033         case POP3_LOGOUT:
1034                 pop3_session->state = POP3_DONE;
1035                 session_disconnect(session);
1036                 break;
1037         case POP3_ERROR:
1038         default:
1039                 return -1;
1040         }
1041
1042         return val == PS_SUCCESS?0:-1;
1043 }
1044
1045 static gint pop3_session_recv_data_finished(Session *session, guchar *data,
1046                                             guint len)
1047 {
1048         Pop3Session *pop3_session = POP3_SESSION(session);
1049         Pop3ErrorValue val = PS_SUCCESS;
1050
1051         switch (pop3_session->state) {
1052         case POP3_GETRANGE_UIDL_RECV:
1053                 val = pop3_getrange_uidl_recv(pop3_session, data, len);
1054                 if (val == PS_SUCCESS) {
1055                         if (pop3_session->new_msg_exist)
1056                                 pop3_getsize_list_send(pop3_session);
1057                         else
1058                                 pop3_logout_send(pop3_session);
1059                 } else
1060                         return -1;
1061                 break;
1062         case POP3_GETSIZE_LIST_RECV:
1063                 val = pop3_getsize_list_recv(pop3_session, data, len);
1064                 if (val == PS_SUCCESS) {
1065                         if (pop3_lookup_next(pop3_session) == POP3_ERROR)
1066                                 return -1;
1067                 } else
1068                         return -1;
1069                 break;
1070         case POP3_RETR_RECV:
1071                 if (pop3_retr_recv(pop3_session, data, len) < 0)
1072                         return -1;
1073
1074                 if (pop3_session->ac_prefs->rmmail &&
1075                     pop3_session->ac_prefs->msg_leave_time == 0 &&
1076                     pop3_session->ac_prefs->msg_leave_hour == 0 &&
1077                     pop3_session->msg[pop3_session->cur_msg].recv_time
1078                     != RECV_TIME_KEEP)
1079                         pop3_delete_send(pop3_session);
1080                 else if (pop3_session->cur_msg == pop3_session->count)
1081                         pop3_logout_send(pop3_session);
1082                 else {
1083                         pop3_session->cur_msg++;
1084                         if (pop3_lookup_next(pop3_session) == POP3_ERROR)
1085                                 return -1;
1086                 }
1087                 break;
1088         case POP3_TOP_RECV:
1089                 if (pop3_top_recv(pop3_session, data, len) < 0)
1090                         return -1;
1091
1092                 if (pop3_session->cur_msg == pop3_session->count)
1093                         pop3_logout_send(pop3_session);
1094                 else {
1095                         pop3_session->cur_msg++;
1096                         if (pop3_lookup_next(pop3_session) == POP3_ERROR)
1097                                 return -1;
1098                 }
1099                 break;
1100         case POP3_TOP:
1101                 log_warning(LOG_PROTOCOL, _("TOP command unsupported\n"));
1102                 if (pop3_session->cur_msg == pop3_session->count)
1103                         pop3_logout_send(pop3_session);
1104                 else {
1105                         pop3_session->cur_msg++;
1106                         if (pop3_lookup_next(pop3_session) == POP3_ERROR)
1107                                 return -1;
1108                 }
1109                 break;
1110         case POP3_ERROR:
1111         default:
1112                 return -1;
1113         }
1114
1115         return 0;
1116 }