2004-12-02 [paul] 0.9.12cvs180
[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         mail_receive_data.session = session;
343         mail_receive_data.data = g_strndup(data, len);
344         hooks_invoke(MAIL_RECEIVE_HOOKLIST, &mail_receive_data);
345
346         file = get_tmp_file();
347         if (pop3_write_msg_to_file(file, mail_receive_data.data,
348                 strlen(mail_receive_data.data), NULL) < 0) {
349                 g_free(file);
350                 g_free(mail_receive_data.data);
351                 session->error_val = PS_IOERR;
352                 return -1;
353         }
354         g_free(mail_receive_data.data);
355
356         if (session->msg[session->cur_msg].partial_recv 
357             == POP3_MUST_COMPLETE_RECV) {
358                 gchar *old_file = partial_get_filename(
359                                 session->ac_prefs->recv_server,
360                                 session->ac_prefs->userid,
361                                 session->msg[session->cur_msg].uidl);
362                 
363                 if (old_file) {
364                         partial_delete_old(old_file);
365                         g_free(old_file);
366                 }
367         } 
368
369         /* drop_ok: 0: success 1: don't receive -1: error */
370         drop_ok = session->drop_message(session, file);
371
372         g_free(file);
373         if (drop_ok < 0) {
374                 session->error_val = PS_IOERR;
375                 return -1;
376         }
377         
378         session->cur_total_bytes += session->msg[session->cur_msg].size;
379         session->cur_total_recv_bytes += session->msg[session->cur_msg].size;
380         session->cur_total_num++;
381
382         session->msg[session->cur_msg].received = TRUE;
383         session->msg[session->cur_msg].partial_recv = POP3_TOTALLY_RECEIVED;
384
385         session->msg[session->cur_msg].recv_time =
386                 drop_ok == 1 ? RECV_TIME_KEEP : session->current_time;
387
388         return PS_SUCCESS;
389 }
390
391 static gint pop3_top_send(Pop3Session *session, gint max_size)
392 {
393         gint num_lines = (max_size*1024)/82; /* consider lines to be 80 chars */
394         session->state = POP3_TOP;
395         pop3_gen_send(session, "TOP %d %d", session->cur_msg, num_lines);
396         return PS_SUCCESS;
397 }
398
399 static gint pop3_top_recv(Pop3Session *session, const gchar *data, guint len)
400 {
401         gchar *file;
402         gint drop_ok;
403         MailReceiveData mail_receive_data;
404         gchar *partial_notice = NULL;
405         
406         mail_receive_data.session = session;
407         mail_receive_data.data = g_strndup(data, len);
408         hooks_invoke(MAIL_RECEIVE_HOOKLIST, &mail_receive_data);
409
410         partial_notice = g_strdup_printf("SC-Marked-For-Download: 0\n"
411                                          "SC-Partially-Retrieved: %s\n"
412                                          "SC-Account-Server: %s\n"
413                                          "SC-Account-Login: %s\n"
414                                          "SC-Message-Size: %d",
415                                          session->msg[session->cur_msg].uidl,
416                                          session->ac_prefs->recv_server,
417                                          session->ac_prefs->userid,
418                                          session->msg[session->cur_msg].size);
419         file = get_tmp_file();
420         if (pop3_write_msg_to_file(file, mail_receive_data.data,
421                 strlen(mail_receive_data.data), partial_notice) < 0) {
422                 g_free(file);
423                 g_free(mail_receive_data.data);
424                 session->error_val = PS_IOERR;
425                 g_free(partial_notice);
426                 return -1;
427         }
428         g_free(mail_receive_data.data);
429         g_free(partial_notice);
430
431         /* drop_ok: 0: success 1: don't receive -1: error */
432         drop_ok = session->drop_message(session, file);
433         g_free(file);
434         if (drop_ok < 0) {
435                 session->error_val = PS_IOERR;
436                 return -1;
437         }
438
439         session->cur_total_bytes += session->msg[session->cur_msg].size;
440         session->cur_total_recv_bytes += session->msg[session->cur_msg].size;
441         session->cur_total_num++;
442
443         session->msg[session->cur_msg].received = TRUE;
444         session->msg[session->cur_msg].partial_recv = POP3_PARTIALLY_RECEIVED;
445         session->msg[session->cur_msg].recv_time =
446                 drop_ok == 1 ? RECV_TIME_KEEP : session->current_time;
447
448         return PS_SUCCESS;
449 }
450
451 static gint pop3_delete_send(Pop3Session *session)
452 {
453         session->state = POP3_DELETE;
454         pop3_gen_send(session, "DELE %d", session->cur_msg);
455         return PS_SUCCESS;
456 }
457
458 static gint pop3_delete_recv(Pop3Session *session)
459 {
460         session->msg[session->cur_msg].deleted = TRUE;
461         return PS_SUCCESS;
462 }
463
464 static gint pop3_logout_send(Pop3Session *session)
465 {
466         session->state = POP3_LOGOUT;
467         pop3_gen_send(session, "QUIT");
468         return PS_SUCCESS;
469 }
470
471 static void pop3_gen_send(Pop3Session *session, const gchar *format, ...)
472 {
473         gchar buf[POPBUFSIZE + 1];
474         va_list args;
475
476         va_start(args, format);
477         g_vsnprintf(buf, sizeof(buf) - 2, format, args);
478         va_end(args);
479
480         if (!g_strncasecmp(buf, "PASS ", 5))
481                 log_print("POP3> PASS ********\n");
482         else
483                 log_print("POP3> %s\n", buf);
484
485         session_send_msg(SESSION(session), SESSION_MSG_NORMAL, buf);
486 }
487
488 Session *pop3_session_new(PrefsAccount *account)
489 {
490         Pop3Session *session;
491
492         g_return_val_if_fail(account != NULL, NULL);
493
494         session = g_new0(Pop3Session, 1);
495
496         session_init(SESSION(session));
497
498         SESSION(session)->type = SESSION_POP3;
499
500         SESSION(session)->recv_msg = pop3_session_recv_msg;
501         SESSION(session)->recv_data_finished = pop3_session_recv_data_finished;
502         SESSION(session)->send_data_finished = NULL;
503
504         SESSION(session)->destroy = pop3_session_destroy;
505
506         session->state = POP3_READY;
507         session->ac_prefs = account;
508         session->pop_before_smtp = FALSE;
509         pop3_get_uidl_table(account, session);
510         session->current_time = time(NULL);
511         session->error_val = PS_SUCCESS;
512         session->error_msg = NULL;
513
514         return SESSION(session);
515 }
516
517 static void pop3_session_destroy(Session *session)
518 {
519         Pop3Session *pop3_session = POP3_SESSION(session);
520         gint n;
521
522         g_return_if_fail(session != NULL);
523
524         for (n = 1; n <= pop3_session->count; n++)
525                 g_free(pop3_session->msg[n].uidl);
526         g_free(pop3_session->msg);
527
528         if (pop3_session->uidl_table) {
529                 hash_free_strings(pop3_session->uidl_table);
530                 g_hash_table_destroy(pop3_session->uidl_table);
531         }
532
533         if (pop3_session->partial_recv_table) {
534                 hash_free_strings(pop3_session->partial_recv_table);
535                 g_hash_table_destroy(pop3_session->partial_recv_table);
536         }
537
538         g_free(pop3_session->greeting);
539         g_free(pop3_session->user);
540         g_free(pop3_session->pass);
541         g_free(pop3_session->error_msg);
542 }
543
544 void pop3_get_uidl_table(PrefsAccount *ac_prefs, Pop3Session *session)
545 {
546         GHashTable *table;
547         GHashTable *partial_recv_table;
548         gchar *path;
549         FILE *fp;
550         gchar buf[POPBUFSIZE];
551         gchar uidl[POPBUFSIZE];
552         time_t recv_time;
553         time_t now;
554         gint partial_recv;
555         
556         table = g_hash_table_new(g_str_hash, g_str_equal);
557         partial_recv_table = g_hash_table_new(g_str_hash, g_str_equal);
558
559         path = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
560                            "uidl", G_DIR_SEPARATOR_S, ac_prefs->recv_server,
561                            "-", ac_prefs->userid, NULL);
562         if ((fp = fopen(path, "rb")) == NULL) {
563                 if (ENOENT != errno) FILE_OP_ERROR(path, "fopen");
564                 g_free(path);
565                 path = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
566                                    "uidl-", ac_prefs->recv_server,
567                                    "-", ac_prefs->userid, NULL);
568                 if ((fp = fopen(path, "rb")) == NULL) {
569                         if (ENOENT != errno) FILE_OP_ERROR(path, "fopen");
570                         g_free(path);
571                         session->uidl_table = table;
572                         session->partial_recv_table = partial_recv_table;
573                         return;
574                 }
575         }
576         g_free(path);
577
578         now = time(NULL);
579
580         while (fgets(buf, sizeof(buf), fp) != NULL) {
581                 gchar tmp[POPBUFSIZE];
582                 strretchomp(buf);
583                 recv_time = RECV_TIME_NONE;
584                 partial_recv = POP3_TOTALLY_RECEIVED;
585                 
586                 if (sscanf(buf, "%s\t%ld\t%s", uidl, &recv_time, tmp) < 3) {
587                         if (sscanf(buf, "%s\t%ld", uidl, &recv_time) != 2) {
588                                 if (sscanf(buf, "%s", uidl) != 1)
589                                         continue;
590                                 else {
591                                         recv_time = now;
592                                         strcpy(tmp, "0");
593                                 }
594                         } else {
595                                 strcpy(tmp, "0");
596                         }
597                 }
598
599                 if (recv_time == RECV_TIME_NONE)
600                         recv_time = RECV_TIME_RECEIVED;
601                 g_hash_table_insert(table, g_strdup(uidl),
602                                     GINT_TO_POINTER(recv_time));
603                 if (strlen(tmp) == 1)
604                         partial_recv = atoi(tmp); /* totally received ?*/
605                 else
606                         partial_recv = POP3_MUST_COMPLETE_RECV;
607
608                 g_hash_table_insert(partial_recv_table, g_strdup(uidl),
609                                     GINT_TO_POINTER(partial_recv));
610         }
611
612         fclose(fp);
613         session->uidl_table = table;
614         session->partial_recv_table = partial_recv_table;
615         
616         return;
617 }
618
619 gint pop3_write_uidl_list(Pop3Session *session)
620 {
621         gchar *path;
622         FILE *fp;
623         Pop3MsgInfo *msg;
624         gint n;
625
626         if (!session->uidl_is_valid) return 0;
627
628         path = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
629                            "uidl", G_DIR_SEPARATOR_S,
630                            session->ac_prefs->recv_server,
631                            "-", session->ac_prefs->userid, NULL);
632         if ((fp = fopen(path, "wb")) == NULL) {
633                 FILE_OP_ERROR(path, "fopen");
634                 g_free(path);
635                 return -1;
636         }
637
638         for (n = 1; n <= session->count; n++) {
639                 msg = &session->msg[n];
640                 if (msg->uidl && msg->received && !msg->deleted) {
641                         fprintf(fp, "%s\t%ld\t%d\n", 
642                                 msg->uidl, msg->recv_time, msg->partial_recv);
643                 }
644         }
645
646         if (fclose(fp) == EOF) FILE_OP_ERROR(path, "fclose");
647         g_free(path);
648
649         return 0;
650 }
651
652 static gint pop3_write_msg_to_file(const gchar *file, const gchar *data,
653                                    guint len, const gchar *prefix)
654 {
655         FILE *fp;
656         const gchar *prev, *cur;
657
658         g_return_val_if_fail(file != NULL, -1);
659
660         if ((fp = fopen(file, "wb")) == NULL) {
661                 FILE_OP_ERROR(file, "fopen");
662                 return -1;
663         }
664
665         if (change_file_mode_rw(fp, file) < 0)
666                 FILE_OP_ERROR(file, "chmod");
667
668         if (prefix != NULL) {
669                 fprintf(fp, "%s", prefix);
670                 fprintf(fp, "\n");
671         }
672         
673         /* +------------------+----------------+--------------------------+ *
674          * ^data              ^prev            ^cur             data+len-1^ */
675
676         prev = data;
677         while ((cur = (gchar *)my_memmem(prev, len - (prev - data), "\r\n", 2))
678                != NULL) {
679                 if ((cur > prev && fwrite(prev, cur - prev, 1, fp) < 1) ||
680                     fputc('\n', fp) == EOF) {
681                         FILE_OP_ERROR(file, "fwrite");
682                         g_warning("can't write to file: %s\n", file);
683                         fclose(fp);
684                         unlink(file);
685                         return -1;
686                 }
687
688                 if (cur == data + len - 1) {
689                         prev = cur + 1;
690                         break;
691                 }
692
693                 if (*(cur + 1) == '\n')
694                         prev = cur + 2;
695                 else
696                         prev = cur + 1;
697
698                 if (prev - data < len - 1 && *prev == '.' && *(prev + 1) == '.')
699                         prev++;
700
701                 if (prev - data >= len)
702                         break;
703         }
704
705         if (prev - data < len &&
706             fwrite(prev, len - (prev - data), 1, fp) < 1) {
707                 FILE_OP_ERROR(file, "fwrite");
708                 g_warning("can't write to file: %s\n", file);
709                 fclose(fp);
710                 unlink(file);
711                 return -1;
712         }
713         if (data[len - 1] != '\r' && data[len - 1] != '\n') {
714                 if (fputc('\n', fp) == EOF) {
715                         FILE_OP_ERROR(file, "fputc");
716                         g_warning("can't write to file: %s\n", file);
717                         fclose(fp);
718                         unlink(file);
719                         return -1;
720                 }
721         }
722
723         if (fclose(fp) == EOF) {
724                 FILE_OP_ERROR(file, "fclose");
725                 unlink(file);
726                 return -1;
727         }
728
729         return 0;
730 }
731
732 static Pop3State pop3_lookup_next(Pop3Session *session)
733 {
734         Pop3MsgInfo *msg;
735         PrefsAccount *ac = session->ac_prefs;
736         gint size;
737         gboolean size_limit_over;
738
739         for (;;) {
740                 msg = &session->msg[session->cur_msg];
741                 size = msg->size;
742                 size_limit_over =
743                     (ac->enable_size_limit &&
744                      ac->size_limit > 0 &&
745                      size > ac->size_limit * 1024);
746
747                 if (ac->rmmail &&
748                     msg->recv_time != RECV_TIME_NONE &&
749                     msg->recv_time != RECV_TIME_KEEP &&
750                     msg->partial_recv == POP3_TOTALLY_RECEIVED &&
751                     session->current_time - msg->recv_time >=
752                     ac->msg_leave_time * 24 * 60 * 60) {
753                         log_message
754                                 (_("POP3: Deleting expired message "
755                                    "%d\n"), session->cur_msg);
756                         pop3_delete_send(session);
757                         return POP3_DELETE;
758                 }
759
760                 if (size_limit_over) {
761                         if (!msg->received && msg->partial_recv != 
762                             POP3_MUST_COMPLETE_RECV) {
763                                 pop3_top_send(session, ac->size_limit);
764                                 return POP3_TOP;
765                         } else if (msg->partial_recv == POP3_MUST_COMPLETE_RECV)
766                                 break;
767
768                         log_message
769                                 (_("POP3: Skipping message %d (%d bytes)\n"),
770                                    session->cur_msg, size);
771                 }
772                 
773                 if (size == 0 || msg->received || size_limit_over) {
774                         session->cur_total_bytes += size;
775                         if (session->cur_msg == session->count) {
776                                 pop3_logout_send(session);
777                                 return POP3_LOGOUT;
778                         } else
779                                 session->cur_msg++;
780                 } else
781                         break;
782         }
783
784         pop3_retr_send(session);
785         return POP3_RETR;
786 }
787
788 static Pop3ErrorValue pop3_ok(Pop3Session *session, const gchar *msg)
789 {
790         Pop3ErrorValue ok;
791
792         log_print("POP3< %s\n", msg);
793
794         if (!strncmp(msg, "+OK", 3))
795                 ok = PS_SUCCESS;
796         else if (!strncmp(msg, "-ERR", 4)) {
797                 if (strstr(msg + 4, "lock") ||
798                     strstr(msg + 4, "Lock") ||
799                     strstr(msg + 4, "LOCK") ||
800                     strstr(msg + 4, "wait")) {
801                         log_error(_("mailbox is locked\n"));
802                         ok = PS_LOCKBUSY;
803                 } else if (strcasestr(msg + 4, "timeout")) {
804                         log_error(_("Session timeout\n"));
805                         ok = PS_ERROR;
806                 } else {
807                         switch (session->state) {
808 #if USE_OPENSSL
809                         case POP3_STLS:
810                                 log_error(_("can't start TLS session\n"));
811                                 ok = PS_ERROR;
812                                 break;
813 #endif
814                         case POP3_GETAUTH_USER:
815                         case POP3_GETAUTH_PASS:
816                         case POP3_GETAUTH_APOP:
817                                 log_error(_("error occurred on authentication\n"));
818                                 ok = PS_AUTHFAIL;
819                                 break;
820                         case POP3_GETRANGE_LAST:
821                         case POP3_GETRANGE_UIDL:
822                         case POP3_TOP:
823                                 log_warning(_("command not supported\n"));
824                                 ok = PS_NOTSUPPORTED;
825                                 break;
826                                 
827                         default:
828                                 log_error(_("error occurred on POP3 session\n"));
829                                 ok = PS_ERROR;
830                         }
831                 }
832
833                 g_free(session->error_msg);
834                 session->error_msg = g_strdup(msg);
835                 fprintf(stderr, "POP3: %s\n", msg);
836         } else
837                 ok = PS_PROTOCOL;
838
839         session->error_val = ok;
840         return ok;
841 }
842
843 static gint pop3_session_recv_msg(Session *session, const gchar *msg)
844 {
845         Pop3Session *pop3_session = POP3_SESSION(session);
846         Pop3ErrorValue val = PS_SUCCESS;
847         const guchar *body;
848
849         body = msg;
850         if (pop3_session->state != POP3_GETRANGE_UIDL_RECV &&
851             pop3_session->state != POP3_GETSIZE_LIST_RECV) {
852                 val = pop3_ok(pop3_session, msg);
853                 if (val != PS_SUCCESS) {
854                         if (val != PS_NOTSUPPORTED) {
855                                 pop3_session->state = POP3_ERROR;
856                                 return -1;
857                         }
858                 }
859
860                 if (*body == '+' || *body == '-')
861                         body++;
862                 while (isalpha(*body))
863                         body++;
864                 while (isspace(*body))
865                         body++;
866         }
867
868         switch (pop3_session->state) {
869         case POP3_READY:
870         case POP3_GREETING:
871                 pop3_greeting_recv(pop3_session, body);
872 #if USE_OPENSSL
873                 if (pop3_session->ac_prefs->ssl_pop == SSL_STARTTLS)
874                         pop3_stls_send(pop3_session);
875                 else
876 #endif
877                 if (pop3_session->ac_prefs->use_apop_auth)
878                         pop3_getauth_apop_send(pop3_session);
879                 else
880                         pop3_getauth_user_send(pop3_session);
881                 break;
882 #if USE_OPENSSL
883         case POP3_STLS:
884                 if (pop3_stls_recv(pop3_session) != PS_SUCCESS)
885                         return -1;
886                 if (pop3_session->ac_prefs->use_apop_auth)
887                         pop3_getauth_apop_send(pop3_session);
888                 else
889                         pop3_getauth_user_send(pop3_session);
890                 break;
891 #endif
892         case POP3_GETAUTH_USER:
893                 pop3_getauth_pass_send(pop3_session);
894                 break;
895         case POP3_GETAUTH_PASS:
896         case POP3_GETAUTH_APOP:
897                 if (!pop3_session->pop_before_smtp)
898                         pop3_getrange_stat_send(pop3_session);
899                 else
900                         pop3_logout_send(pop3_session);
901                 break;
902         case POP3_GETRANGE_STAT:
903                 if (pop3_getrange_stat_recv(pop3_session, body) < 0)
904                         return -1;
905                 if (pop3_session->count > 0)
906                         pop3_getrange_uidl_send(pop3_session);
907                 else
908                         pop3_logout_send(pop3_session);
909                 break;
910         case POP3_GETRANGE_LAST:
911                 if (val == PS_NOTSUPPORTED)
912                         pop3_session->error_val = PS_SUCCESS;
913                 else if (pop3_getrange_last_recv(pop3_session, body) < 0)
914                         return -1;
915                 if (pop3_session->cur_msg > 0)
916                         pop3_getsize_list_send(pop3_session);
917                 else
918                         pop3_logout_send(pop3_session);
919                 break;
920         case POP3_GETRANGE_UIDL:
921                 if (val == PS_NOTSUPPORTED) {
922                         pop3_session->error_val = PS_SUCCESS;
923                         pop3_getrange_last_send(pop3_session);
924                 } else {
925                         pop3_session->state = POP3_GETRANGE_UIDL_RECV;
926                         session_recv_data(session, 0, ".\r\n");
927                 }
928                 break;
929         case POP3_GETSIZE_LIST:
930                 pop3_session->state = POP3_GETSIZE_LIST_RECV;
931                 session_recv_data(session, 0, ".\r\n");
932                 break;
933         case POP3_RETR:
934                 pop3_session->state = POP3_RETR_RECV;
935                 session_recv_data(session, 0, ".\r\n");
936                 break;
937         case POP3_TOP:
938                 if (val == PS_NOTSUPPORTED) {
939                         pop3_session->error_val = PS_SUCCESS;
940                 } else {
941                         pop3_session->state = POP3_TOP_RECV;
942                         session_recv_data(session, 0, ".\r\n");
943                 }
944                 break;
945         case POP3_DELETE:
946                 pop3_delete_recv(pop3_session);
947                 if (pop3_session->cur_msg == pop3_session->count)
948                         pop3_logout_send(pop3_session);
949                 else {
950                         pop3_session->cur_msg++;
951                         if (pop3_lookup_next(pop3_session) == POP3_ERROR)
952                                 return -1;
953                 }
954                 break;
955         case POP3_LOGOUT:
956                 session_disconnect(session);
957                 break;
958         case POP3_ERROR:
959         default:
960                 return -1;
961         }
962
963         return 0;
964 }
965
966 static gint pop3_session_recv_data_finished(Session *session, guchar *data,
967                                             guint len)
968 {
969         Pop3Session *pop3_session = POP3_SESSION(session);
970         Pop3ErrorValue val = PS_SUCCESS;
971
972         switch (pop3_session->state) {
973         case POP3_GETRANGE_UIDL_RECV:
974                 val = pop3_getrange_uidl_recv(pop3_session, data, len);
975                 if (val == PS_SUCCESS) {
976                         if (pop3_session->new_msg_exist)
977                                 pop3_getsize_list_send(pop3_session);
978                         else
979                                 pop3_logout_send(pop3_session);
980                 } else
981                         return -1;
982                 break;
983         case POP3_GETSIZE_LIST_RECV:
984                 val = pop3_getsize_list_recv(pop3_session, data, len);
985                 if (val == PS_SUCCESS) {
986                         if (pop3_lookup_next(pop3_session) == POP3_ERROR)
987                                 return -1;
988                 } else
989                         return -1;
990                 break;
991         case POP3_RETR_RECV:
992                 if (pop3_retr_recv(pop3_session, data, len) < 0)
993                         return -1;
994
995                 if (pop3_session->ac_prefs->rmmail &&
996                     pop3_session->ac_prefs->msg_leave_time == 0 &&
997                     pop3_session->msg[pop3_session->cur_msg].recv_time
998                     != RECV_TIME_KEEP)
999                         pop3_delete_send(pop3_session);
1000                 else if (pop3_session->cur_msg == pop3_session->count)
1001                         pop3_logout_send(pop3_session);
1002                 else {
1003                         pop3_session->cur_msg++;
1004                         if (pop3_lookup_next(pop3_session) == POP3_ERROR)
1005                                 return -1;
1006                 }
1007                 break;
1008         case POP3_TOP_RECV:
1009                 if (pop3_top_recv(pop3_session, data, len) < 0)
1010                         return -1;
1011
1012                 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:
1021                 log_warning(_("TOP command unsupported\n"));
1022                 if (pop3_session->cur_msg == pop3_session->count)
1023                         pop3_logout_send(pop3_session);
1024                 else {
1025                         pop3_session->cur_msg++;
1026                         if (pop3_lookup_next(pop3_session) == POP3_ERROR)
1027                                 return -1;
1028                 }
1029                 break;
1030         case POP3_ERROR:
1031         default:
1032                 return -1;
1033         }
1034
1035         return 0;
1036 }