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