2005-01-07 [paul] 0.9.13cvs29
[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 <stdio.h>
26 #include <string.h>
27 #include <stdarg.h>
28 #include <ctype.h>
29 #include <unistd.h>
30 #include <time.h>
31 #include <errno.h>
32
33 #include "intl.h"
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_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         
567         table = g_hash_table_new(g_str_hash, g_str_equal);
568         partial_recv_table = g_hash_table_new(g_str_hash, g_str_equal);
569
570         path = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
571                            "uidl", G_DIR_SEPARATOR_S, ac_prefs->recv_server,
572                            "-", ac_prefs->userid, NULL);
573         if ((fp = fopen(path, "rb")) == NULL) {
574                 if (ENOENT != errno) FILE_OP_ERROR(path, "fopen");
575                 g_free(path);
576                 path = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
577                                    "uidl-", ac_prefs->recv_server,
578                                    "-", ac_prefs->userid, NULL);
579                 if ((fp = fopen(path, "rb")) == NULL) {
580                         if (ENOENT != errno) FILE_OP_ERROR(path, "fopen");
581                         g_free(path);
582                         session->uidl_table = table;
583                         session->partial_recv_table = partial_recv_table;
584                         return;
585                 }
586         }
587         g_free(path);
588
589         now = time(NULL);
590
591         while (fgets(buf, sizeof(buf), fp) != NULL) {
592                 gchar tmp[POPBUFSIZE];
593                 strretchomp(buf);
594                 recv_time = RECV_TIME_NONE;
595                 partial_recv = POP3_TOTALLY_RECEIVED;
596                 
597                 if (sscanf(buf, "%s\t%ld\t%s", uidl, &recv_time, tmp) < 3) {
598                         if (sscanf(buf, "%s\t%ld", uidl, &recv_time) != 2) {
599                                 if (sscanf(buf, "%s", uidl) != 1)
600                                         continue;
601                                 else {
602                                         recv_time = now;
603                                         strcpy(tmp, "0");
604                                 }
605                         } else {
606                                 strcpy(tmp, "0");
607                         }
608                 }
609
610                 if (recv_time == RECV_TIME_NONE)
611                         recv_time = RECV_TIME_RECEIVED;
612                 g_hash_table_insert(table, g_strdup(uidl),
613                                     GINT_TO_POINTER(recv_time));
614                 if (strlen(tmp) == 1)
615                         partial_recv = atoi(tmp); /* totally received ?*/
616                 else
617                         partial_recv = POP3_MUST_COMPLETE_RECV;
618
619                 g_hash_table_insert(partial_recv_table, g_strdup(uidl),
620                                     GINT_TO_POINTER(partial_recv));
621         }
622
623         fclose(fp);
624         session->uidl_table = table;
625         session->partial_recv_table = partial_recv_table;
626         
627         return;
628 }
629
630 gint pop3_write_uidl_list(Pop3Session *session)
631 {
632         gchar *path;
633         FILE *fp;
634         Pop3MsgInfo *msg;
635         gint n;
636
637         if (!session->uidl_is_valid) return 0;
638
639         path = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
640                            "uidl", G_DIR_SEPARATOR_S,
641                            session->ac_prefs->recv_server,
642                            "-", session->ac_prefs->userid, NULL);
643         if ((fp = fopen(path, "wb")) == NULL) {
644                 FILE_OP_ERROR(path, "fopen");
645                 g_free(path);
646                 return -1;
647         }
648
649         for (n = 1; n <= session->count; n++) {
650                 msg = &session->msg[n];
651                 if (msg->uidl && msg->received &&
652                     (!msg->deleted || session->state != POP3_DONE))
653                         fprintf(fp, "%s\t%ld\t%d\n", 
654                                 msg->uidl, msg->recv_time, msg->partial_recv);
655         }
656
657         if (fclose(fp) == EOF) FILE_OP_ERROR(path, "fclose");
658         g_free(path);
659
660         return 0;
661 }
662
663 static gint pop3_write_msg_to_file(const gchar *file, const gchar *data,
664                                    guint len, const gchar *prefix)
665 {
666         FILE *fp;
667         const gchar *prev, *cur;
668
669         g_return_val_if_fail(file != NULL, -1);
670
671         if ((fp = fopen(file, "wb")) == NULL) {
672                 FILE_OP_ERROR(file, "fopen");
673                 return -1;
674         }
675
676         if (change_file_mode_rw(fp, file) < 0)
677                 FILE_OP_ERROR(file, "chmod");
678
679         if (prefix != NULL) {
680                 fprintf(fp, "%s", prefix);
681                 fprintf(fp, "\n");
682         }
683         
684         /* +------------------+----------------+--------------------------+ *
685          * ^data              ^prev            ^cur             data+len-1^ */
686
687         prev = data;
688         while ((cur = (gchar *)my_memmem(prev, len - (prev - data), "\r\n", 2))
689                != NULL) {
690                 if ((cur > prev && fwrite(prev, cur - prev, 1, fp) < 1) ||
691                     fputc('\n', fp) == EOF) {
692                         FILE_OP_ERROR(file, "fwrite");
693                         g_warning("can't write to file: %s\n", file);
694                         fclose(fp);
695                         unlink(file);
696                         return -1;
697                 }
698
699                 if (cur == data + len - 1) {
700                         prev = cur + 1;
701                         break;
702                 }
703
704                 if (*(cur + 1) == '\n')
705                         prev = cur + 2;
706                 else
707                         prev = cur + 1;
708
709                 if (prev - data < len - 1 && *prev == '.' && *(prev + 1) == '.')
710                         prev++;
711
712                 if (prev - data >= len)
713                         break;
714         }
715
716         if (prev - data < len &&
717             fwrite(prev, len - (prev - data), 1, fp) < 1) {
718                 FILE_OP_ERROR(file, "fwrite");
719                 g_warning("can't write to file: %s\n", file);
720                 fclose(fp);
721                 unlink(file);
722                 return -1;
723         }
724         if (data[len - 1] != '\r' && data[len - 1] != '\n') {
725                 if (fputc('\n', fp) == EOF) {
726                         FILE_OP_ERROR(file, "fputc");
727                         g_warning("can't write to file: %s\n", file);
728                         fclose(fp);
729                         unlink(file);
730                         return -1;
731                 }
732         }
733
734         if (fclose(fp) == EOF) {
735                 FILE_OP_ERROR(file, "fclose");
736                 unlink(file);
737                 return -1;
738         }
739
740         return 0;
741 }
742
743 static Pop3State pop3_lookup_next(Pop3Session *session)
744 {
745         Pop3MsgInfo *msg;
746         PrefsAccount *ac = session->ac_prefs;
747         gint size;
748         gboolean size_limit_over;
749
750         for (;;) {
751                 msg = &session->msg[session->cur_msg];
752                 size = msg->size;
753                 size_limit_over =
754                     (ac->enable_size_limit &&
755                      ac->size_limit > 0 &&
756                      size > ac->size_limit * 1024);
757
758                 if (ac->rmmail &&
759                     msg->recv_time != RECV_TIME_NONE &&
760                     msg->recv_time != RECV_TIME_KEEP &&
761                     msg->partial_recv == POP3_TOTALLY_RECEIVED &&
762                     session->current_time - msg->recv_time >=
763                     ac->msg_leave_time * 24 * 60 * 60) {
764                         log_message
765                                 (_("POP3: Deleting expired message "
766                                    "%d\n"), session->cur_msg);
767                         pop3_delete_send(session);
768                         return POP3_DELETE;
769                 }
770
771                 if (size_limit_over) {
772                         if (!msg->received && msg->partial_recv != 
773                             POP3_MUST_COMPLETE_RECV) {
774                                 pop3_top_send(session, ac->size_limit);
775                                 return POP3_TOP;
776                         } else if (msg->partial_recv == POP3_MUST_COMPLETE_RECV)
777                                 break;
778
779                         log_message
780                                 (_("POP3: Skipping message %d (%d bytes)\n"),
781                                    session->cur_msg, size);
782                 }
783                 
784                 if (size == 0 || msg->received || size_limit_over) {
785                         session->cur_total_bytes += size;
786                         if (session->cur_msg == session->count) {
787                                 pop3_logout_send(session);
788                                 return POP3_LOGOUT;
789                         } else
790                                 session->cur_msg++;
791                 } else
792                         break;
793         }
794
795         pop3_retr_send(session);
796         return POP3_RETR;
797 }
798
799 static Pop3ErrorValue pop3_ok(Pop3Session *session, const gchar *msg)
800 {
801         Pop3ErrorValue ok;
802
803         log_print("POP3< %s\n", msg);
804
805         if (!strncmp(msg, "+OK", 3))
806                 ok = PS_SUCCESS;
807         else if (!strncmp(msg, "-ERR", 4)) {
808                 if (strstr(msg + 4, "lock") ||
809                     strstr(msg + 4, "Lock") ||
810                     strstr(msg + 4, "LOCK") ||
811                     strstr(msg + 4, "wait")) {
812                         log_error(_("mailbox is locked\n"));
813                         ok = PS_LOCKBUSY;
814                 } else if (strcasestr(msg + 4, "timeout")) {
815                         log_error(_("Session timeout\n"));
816                         ok = PS_ERROR;
817                 } else {
818                         switch (session->state) {
819 #if USE_OPENSSL
820                         case POP3_STLS:
821                                 log_error(_("can't start TLS session\n"));
822                                 ok = PS_ERROR;
823                                 break;
824 #endif
825                         case POP3_GETAUTH_USER:
826                         case POP3_GETAUTH_PASS:
827                         case POP3_GETAUTH_APOP:
828                                 log_error(_("error occurred on authentication\n"));
829                                 ok = PS_AUTHFAIL;
830                                 break;
831                         case POP3_GETRANGE_LAST:
832                         case POP3_GETRANGE_UIDL:
833                         case POP3_TOP:
834                                 log_warning(_("command not supported\n"));
835                                 ok = PS_NOTSUPPORTED;
836                                 break;
837                                 
838                         default:
839                                 log_error(_("error occurred on POP3 session\n"));
840                                 ok = PS_ERROR;
841                         }
842                 }
843
844                 g_free(session->error_msg);
845                 session->error_msg = g_strdup(msg);
846                 fprintf(stderr, "POP3: %s\n", msg);
847         } else
848                 ok = PS_PROTOCOL;
849
850         session->error_val = ok;
851         return ok;
852 }
853
854 static gint pop3_session_recv_msg(Session *session, const gchar *msg)
855 {
856         Pop3Session *pop3_session = POP3_SESSION(session);
857         Pop3ErrorValue val = PS_SUCCESS;
858         const guchar *body;
859
860         body = msg;
861         if (pop3_session->state != POP3_GETRANGE_UIDL_RECV &&
862             pop3_session->state != POP3_GETSIZE_LIST_RECV) {
863                 val = pop3_ok(pop3_session, msg);
864                 if (val != PS_SUCCESS) {
865                         if (val != PS_NOTSUPPORTED) {
866                                 pop3_session->state = POP3_ERROR;
867                                 return -1;
868                         }
869                 }
870
871                 if (*body == '+' || *body == '-')
872                         body++;
873                 while (isalpha(*body))
874                         body++;
875                 while (isspace(*body))
876                         body++;
877         }
878
879         switch (pop3_session->state) {
880         case POP3_READY:
881         case POP3_GREETING:
882                 pop3_greeting_recv(pop3_session, body);
883 #if USE_OPENSSL
884                 if (pop3_session->ac_prefs->ssl_pop == SSL_STARTTLS)
885                         pop3_stls_send(pop3_session);
886                 else
887 #endif
888                 if (pop3_session->ac_prefs->use_apop_auth)
889                         pop3_getauth_apop_send(pop3_session);
890                 else
891                         pop3_getauth_user_send(pop3_session);
892                 break;
893 #if USE_OPENSSL
894         case POP3_STLS:
895                 if (pop3_stls_recv(pop3_session) != PS_SUCCESS)
896                         return -1;
897                 if (pop3_session->ac_prefs->use_apop_auth)
898                         pop3_getauth_apop_send(pop3_session);
899                 else
900                         pop3_getauth_user_send(pop3_session);
901                 break;
902 #endif
903         case POP3_GETAUTH_USER:
904                 pop3_getauth_pass_send(pop3_session);
905                 break;
906         case POP3_GETAUTH_PASS:
907         case POP3_GETAUTH_APOP:
908                 if (!pop3_session->pop_before_smtp)
909                         pop3_getrange_stat_send(pop3_session);
910                 else
911                         pop3_logout_send(pop3_session);
912                 break;
913         case POP3_GETRANGE_STAT:
914                 if (pop3_getrange_stat_recv(pop3_session, body) < 0)
915                         return -1;
916                 if (pop3_session->count > 0)
917                         pop3_getrange_uidl_send(pop3_session);
918                 else
919                         pop3_logout_send(pop3_session);
920                 break;
921         case POP3_GETRANGE_LAST:
922                 if (val == PS_NOTSUPPORTED)
923                         pop3_session->error_val = PS_SUCCESS;
924                 else if (pop3_getrange_last_recv(pop3_session, body) < 0)
925                         return -1;
926                 if (pop3_session->cur_msg > 0)
927                         pop3_getsize_list_send(pop3_session);
928                 else
929                         pop3_logout_send(pop3_session);
930                 break;
931         case POP3_GETRANGE_UIDL:
932                 if (val == PS_NOTSUPPORTED) {
933                         pop3_session->error_val = PS_SUCCESS;
934                         pop3_getrange_last_send(pop3_session);
935                 } else {
936                         pop3_session->state = POP3_GETRANGE_UIDL_RECV;
937                         session_recv_data(session, 0, ".\r\n");
938                 }
939                 break;
940         case POP3_GETSIZE_LIST:
941                 pop3_session->state = POP3_GETSIZE_LIST_RECV;
942                 session_recv_data(session, 0, ".\r\n");
943                 break;
944         case POP3_RETR:
945                 pop3_session->state = POP3_RETR_RECV;
946                 session_recv_data(session, 0, ".\r\n");
947                 break;
948         case POP3_TOP:
949                 if (val == PS_NOTSUPPORTED) {
950                         pop3_session->error_val = PS_SUCCESS;
951                 } else {
952                         pop3_session->state = POP3_TOP_RECV;
953                         session_recv_data(session, 0, ".\r\n");
954                 }
955                 break;
956         case POP3_DELETE:
957                 pop3_delete_recv(pop3_session);
958                 if (pop3_session->cur_msg == pop3_session->count)
959                         pop3_logout_send(pop3_session);
960                 else {
961                         pop3_session->cur_msg++;
962                         if (pop3_lookup_next(pop3_session) == POP3_ERROR)
963                                 return -1;
964                 }
965                 break;
966         case POP3_LOGOUT:
967                 pop3_session->state = POP3_DONE;
968                 session_disconnect(session);
969                 break;
970         case POP3_ERROR:
971         default:
972                 return -1;
973         }
974
975         return 0;
976 }
977
978 static gint pop3_session_recv_data_finished(Session *session, guchar *data,
979                                             guint len)
980 {
981         Pop3Session *pop3_session = POP3_SESSION(session);
982         Pop3ErrorValue val = PS_SUCCESS;
983
984         switch (pop3_session->state) {
985         case POP3_GETRANGE_UIDL_RECV:
986                 val = pop3_getrange_uidl_recv(pop3_session, data, len);
987                 if (val == PS_SUCCESS) {
988                         if (pop3_session->new_msg_exist)
989                                 pop3_getsize_list_send(pop3_session);
990                         else
991                                 pop3_logout_send(pop3_session);
992                 } else
993                         return -1;
994                 break;
995         case POP3_GETSIZE_LIST_RECV:
996                 val = pop3_getsize_list_recv(pop3_session, data, len);
997                 if (val == PS_SUCCESS) {
998                         if (pop3_lookup_next(pop3_session) == POP3_ERROR)
999                                 return -1;
1000                 } else
1001                         return -1;
1002                 break;
1003         case POP3_RETR_RECV:
1004                 if (pop3_retr_recv(pop3_session, data, len) < 0)
1005                         return -1;
1006
1007                 if (pop3_session->ac_prefs->rmmail &&
1008                     pop3_session->ac_prefs->msg_leave_time == 0 &&
1009                     pop3_session->msg[pop3_session->cur_msg].recv_time
1010                     != RECV_TIME_KEEP)
1011                         pop3_delete_send(pop3_session);
1012                 else if (pop3_session->cur_msg == pop3_session->count)
1013                         pop3_logout_send(pop3_session);
1014                 else {
1015                         pop3_session->cur_msg++;
1016                         if (pop3_lookup_next(pop3_session) == POP3_ERROR)
1017                                 return -1;
1018                 }
1019                 break;
1020         case POP3_TOP_RECV:
1021                 if (pop3_top_recv(pop3_session, data, len) < 0)
1022                         return -1;
1023
1024                 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:
1033                 log_warning(_("TOP command unsupported\n"));
1034                 if (pop3_session->cur_msg == pop3_session->count)
1035                         pop3_logout_send(pop3_session);
1036                 else {
1037                         pop3_session->cur_msg++;
1038                         if (pop3_lookup_next(pop3_session) == POP3_ERROR)
1039                                 return -1;
1040                 }
1041                 break;
1042         case POP3_ERROR:
1043         default:
1044                 return -1;
1045         }
1046
1047         return 0;
1048 }