2007-04-13 [colin] 2.8.1cvs95
[claws.git] / src / pop.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2007 Hiroyuki Yamamoto and the Claws Mail team
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #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(LOG_PROTOCOL, _("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(LOG_PROTOCOL, _("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(LOG_PROTOCOL, _("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(LOG_PROTOCOL, _("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         guint32 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(LOG_PROTOCOL, _("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                 if (recv_time != RECV_TIME_NONE) {
267                         debug_print("num %d uidl %s: already got it\n", num, id);               
268                 } else {
269                         debug_print("num %d uidl %s: unknown\n", num, id);
270                 }
271
272                 partial_recv = (gint)g_hash_table_lookup(
273                                         session->partial_recv_table, id);
274
275                 if ((!session->ac_prefs->getall && recv_time != RECV_TIME_NONE)
276                 || partial_recv != POP3_TOTALLY_RECEIVED) {
277                         session->msg[num].received = 
278                                 (partial_recv != POP3_MUST_COMPLETE_RECV);
279                         session->msg[num].partial_recv = partial_recv;
280                         if (partial_recv == POP3_MUST_COMPLETE_RECV)
281                                 session->new_msg_exist = TRUE;
282                 }
283                 if (!session->new_msg_exist &&
284                     (session->ac_prefs->getall || recv_time == RECV_TIME_NONE ||
285                      session->ac_prefs->rmmail)) {
286                         session->cur_msg = num;
287                         session->new_msg_exist = TRUE;
288                 }
289         }
290
291         session->uidl_is_valid = TRUE;
292         return PS_SUCCESS;
293 }
294
295 static gint pop3_getsize_list_send(Pop3Session *session)
296 {
297         session->state = POP3_GETSIZE_LIST;
298         pop3_gen_send(session, "LIST");
299         return PS_SUCCESS;
300 }
301
302 static gint pop3_getsize_list_recv(Pop3Session *session, const gchar *data,
303                                    guint len)
304 {
305         gchar buf[POPBUFSIZE];
306         gint buf_len;
307         guint num, size;
308         const gchar *p = data;
309         const gchar *lastp = data + len;
310         const gchar *newline;
311
312         while (p < lastp) {
313                 if ((newline = memchr(p, '\r', lastp - p)) == NULL)
314                         return -1;
315                 buf_len = MIN(newline - p, sizeof(buf) - 1);
316                 memcpy(buf, p, buf_len);
317                 buf[buf_len] = '\0';
318
319                 p = newline + 1;
320                 if (p < lastp && *p == '\n') p++;
321
322                 if (sscanf(buf, "%u %u", &num, &size) != 2) {
323                         session->error_val = PS_PROTOCOL;
324                         return -1;
325                 }
326
327                 if (num > 0 && num <= session->count)
328                         session->msg[num].size = size;
329                 if (num > 0 && num < session->cur_msg)
330                         session->cur_total_bytes += size;
331         }
332
333         return PS_SUCCESS;
334 }
335
336 static gint pop3_retr_send(Pop3Session *session)
337 {
338         session->state = POP3_RETR;
339         debug_print("retrieving %d [%s]\n", session->cur_msg, 
340                 session->msg[session->cur_msg].uidl ?
341                  session->msg[session->cur_msg].uidl:" ");
342         pop3_gen_send(session, "RETR %d", session->cur_msg);
343         return PS_SUCCESS;
344 }
345
346 static gint pop3_retr_recv(Pop3Session *session, const gchar *data, guint len)
347 {
348         gchar *file;
349         gint drop_ok;
350         MailReceiveData mail_receive_data;
351
352         /* NOTE: we allocate a slightly larger buffer with a zero terminator
353          * because some plugins may think that it has a C string. */ 
354         mail_receive_data.session  = session;
355         mail_receive_data.data     = g_new0(gchar, len + 1);
356         mail_receive_data.data_len = len;
357         memcpy(mail_receive_data.data, data, len); 
358         
359         hooks_invoke(MAIL_RECEIVE_HOOKLIST, &mail_receive_data);
360
361         file = get_tmp_file();
362         if (pop3_write_msg_to_file(file, mail_receive_data.data, 
363                                    mail_receive_data.data_len, NULL) < 0) {
364                 g_free(file);
365                 g_free(mail_receive_data.data);
366                 session->error_val = PS_IOERR;
367                 return -1;
368         }
369         g_free(mail_receive_data.data);
370
371         if (session->msg[session->cur_msg].partial_recv 
372             == POP3_MUST_COMPLETE_RECV) {
373                 gchar *old_file = partial_get_filename(
374                                 session->ac_prefs->recv_server,
375                                 session->ac_prefs->userid,
376                                 session->msg[session->cur_msg].uidl);
377                 
378                 if (old_file) {
379                         partial_delete_old(old_file);
380                         g_free(old_file);
381                 }
382         } 
383
384         /* drop_ok: 0: success 1: don't receive -1: error */
385         drop_ok = session->drop_message(session, file);
386
387         g_free(file);
388         if (drop_ok < 0) {
389                 session->error_val = PS_IOERR;
390                 return -1;
391         }
392         
393         session->cur_total_bytes += session->msg[session->cur_msg].size;
394         session->cur_total_recv_bytes += session->msg[session->cur_msg].size;
395         session->cur_total_num++;
396
397         session->msg[session->cur_msg].received = TRUE;
398         session->msg[session->cur_msg].partial_recv = POP3_TOTALLY_RECEIVED;
399
400         session->msg[session->cur_msg].recv_time =
401                 drop_ok == 1 ? RECV_TIME_KEEP : session->current_time;
402
403         return PS_SUCCESS;
404 }
405
406 static gint pop3_top_send(Pop3Session *session, gint max_size)
407 {
408         gint num_lines = (max_size*1024)/82; /* consider lines to be 80 chars */
409         session->state = POP3_TOP;
410         pop3_gen_send(session, "TOP %d %d", session->cur_msg, num_lines);
411         return PS_SUCCESS;
412 }
413
414 static gint pop3_top_recv(Pop3Session *session, const gchar *data, guint len)
415 {
416         gchar *file;
417         gint drop_ok;
418         MailReceiveData mail_receive_data;
419         gchar *partial_notice = NULL;
420         
421         /* NOTE: we allocate a slightly larger buffer with a zero terminator
422          * because some plugins may think that it has a C string. */ 
423         mail_receive_data.session  = session;
424         mail_receive_data.data     = g_new0(gchar, len + 1);
425         mail_receive_data.data_len = len;
426         memcpy(mail_receive_data.data, data, len);
427         
428         hooks_invoke(MAIL_RECEIVE_HOOKLIST, &mail_receive_data);
429
430         partial_notice = g_strdup_printf("SC-Marked-For-Download: 0\n"
431                                          "SC-Partially-Retrieved: %s\n"
432                                          "SC-Account-Server: %s\n"
433                                          "SC-Account-Login: %s\n"
434                                          "SC-Message-Size: %d",
435                                          session->msg[session->cur_msg].uidl,
436                                          session->ac_prefs->recv_server,
437                                          session->ac_prefs->userid,
438                                          session->msg[session->cur_msg].size);
439         file = get_tmp_file();
440         if (pop3_write_msg_to_file(file, mail_receive_data.data,
441                                    mail_receive_data.data_len,  
442                                    partial_notice) < 0) {
443                 g_free(file);
444                 g_free(mail_receive_data.data);
445                 session->error_val = PS_IOERR;
446                 g_free(partial_notice);
447                 return -1;
448         }
449         g_free(mail_receive_data.data);
450         g_free(partial_notice);
451
452         /* drop_ok: 0: success 1: don't receive -1: error */
453         drop_ok = session->drop_message(session, file);
454         g_free(file);
455         if (drop_ok < 0) {
456                 session->error_val = PS_IOERR;
457                 return -1;
458         }
459
460         session->cur_total_bytes += session->msg[session->cur_msg].size;
461         session->cur_total_recv_bytes += session->msg[session->cur_msg].size;
462         session->cur_total_num++;
463
464         session->msg[session->cur_msg].received = TRUE;
465         session->msg[session->cur_msg].partial_recv = POP3_PARTIALLY_RECEIVED;
466         session->msg[session->cur_msg].recv_time =
467                 drop_ok == 1 ? RECV_TIME_KEEP : session->current_time;
468
469         return PS_SUCCESS;
470 }
471
472 static gint pop3_delete_send(Pop3Session *session)
473 {
474         session->state = POP3_DELETE;
475         pop3_gen_send(session, "DELE %d", session->cur_msg);
476         return PS_SUCCESS;
477 }
478
479 static gint pop3_delete_recv(Pop3Session *session)
480 {
481         session->msg[session->cur_msg].deleted = TRUE;
482         return PS_SUCCESS;
483 }
484
485 static gint pop3_logout_send(Pop3Session *session)
486 {
487         session->state = POP3_LOGOUT;
488         pop3_gen_send(session, "QUIT");
489         return PS_SUCCESS;
490 }
491
492 static void pop3_gen_send(Pop3Session *session, const gchar *format, ...)
493 {
494         gchar buf[POPBUFSIZE + 1];
495         va_list args;
496
497         va_start(args, format);
498         g_vsnprintf(buf, sizeof(buf) - 2, format, args);
499         va_end(args);
500
501         if (!g_ascii_strncasecmp(buf, "PASS ", 5))
502                 log_print(LOG_PROTOCOL, "POP3> PASS ********\n");
503         else
504                 log_print(LOG_PROTOCOL, "POP3> %s\n", buf);
505
506         session_send_msg(SESSION(session), SESSION_MSG_NORMAL, buf);
507 }
508
509 Session *pop3_session_new(PrefsAccount *account)
510 {
511         Pop3Session *session;
512
513         g_return_val_if_fail(account != NULL, NULL);
514
515         session = g_new0(Pop3Session, 1);
516
517         session_init(SESSION(session));
518
519         SESSION(session)->type = SESSION_POP3;
520
521         SESSION(session)->recv_msg = pop3_session_recv_msg;
522         SESSION(session)->recv_data_finished = pop3_session_recv_data_finished;
523         SESSION(session)->send_data_finished = NULL;
524
525         SESSION(session)->destroy = pop3_session_destroy;
526
527         session->state = POP3_READY;
528         session->ac_prefs = account;
529         session->pop_before_smtp = FALSE;
530         pop3_get_uidl_table(account, session);
531         session->current_time = time(NULL);
532         session->error_val = PS_SUCCESS;
533         session->error_msg = NULL;
534
535         return SESSION(session);
536 }
537
538 static void pop3_session_destroy(Session *session)
539 {
540         Pop3Session *pop3_session = POP3_SESSION(session);
541         gint n;
542
543         g_return_if_fail(session != NULL);
544
545         for (n = 1; n <= pop3_session->count; n++)
546                 g_free(pop3_session->msg[n].uidl);
547         g_free(pop3_session->msg);
548
549         if (pop3_session->uidl_table) {
550                 hash_free_strings(pop3_session->uidl_table);
551                 g_hash_table_destroy(pop3_session->uidl_table);
552         }
553
554         if (pop3_session->partial_recv_table) {
555                 hash_free_strings(pop3_session->partial_recv_table);
556                 g_hash_table_destroy(pop3_session->partial_recv_table);
557         }
558
559         g_free(pop3_session->greeting);
560         g_free(pop3_session->user);
561         g_free(pop3_session->pass);
562         g_free(pop3_session->error_msg);
563 }
564
565 void pop3_get_uidl_table(PrefsAccount *ac_prefs, Pop3Session *session)
566 {
567         GHashTable *table;
568         GHashTable *partial_recv_table;
569         gchar *path;
570         FILE *fp;
571         gchar buf[POPBUFSIZE];
572         gchar uidl[POPBUFSIZE];
573         time_t recv_time;
574         time_t now;
575         gint partial_recv;
576         gchar *sanitized_uid = g_strdup(ac_prefs->userid);
577         
578         subst_for_filename(sanitized_uid);
579         
580         table = g_hash_table_new(g_str_hash, g_str_equal);
581         partial_recv_table = g_hash_table_new(g_str_hash, g_str_equal);
582
583         path = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
584                            "uidl", G_DIR_SEPARATOR_S, ac_prefs->recv_server,
585                            "-", sanitized_uid, NULL);
586                            
587         g_free(sanitized_uid);
588         if ((fp = g_fopen(path, "rb")) == NULL) {
589                 if (ENOENT != errno) FILE_OP_ERROR(path, "fopen");
590                 g_free(path);
591                 path = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
592                                    "uidl-", ac_prefs->recv_server,
593                                    "-", ac_prefs->userid, NULL);
594                 if ((fp = g_fopen(path, "rb")) == NULL) {
595                         if (ENOENT != errno) FILE_OP_ERROR(path, "fopen");
596                         g_free(path);
597                         session->uidl_table = table;
598                         session->partial_recv_table = partial_recv_table;
599                         return;
600                 }
601         }
602         g_free(path);
603
604         now = time(NULL);
605
606         while (fgets(buf, sizeof(buf), fp) != NULL) {
607                 gchar tmp[POPBUFSIZE];
608                 strretchomp(buf);
609                 recv_time = RECV_TIME_NONE;
610                 partial_recv = POP3_TOTALLY_RECEIVED;
611                 
612                 if (sscanf(buf, "%s\t%ld\t%s", uidl, (long int *) &recv_time, tmp) < 3) {
613                         if (sscanf(buf, "%s\t%ld", uidl, (long int *) &recv_time) != 2) {
614                                 if (sscanf(buf, "%s", uidl) != 1)
615                                         continue;
616                                 else {
617                                         recv_time = now;
618                                         strcpy(tmp, "0");
619                                 }
620                         } else {
621                                 strcpy(tmp, "0");
622                         }
623                 }
624
625                 if (recv_time == RECV_TIME_NONE)
626                         recv_time = RECV_TIME_RECEIVED;
627                 g_hash_table_insert(table, g_strdup(uidl),
628                                     GINT_TO_POINTER(recv_time));
629                 if (strlen(tmp) == 1)
630                         partial_recv = atoi(tmp); /* totally received ?*/
631                 else
632                         partial_recv = POP3_MUST_COMPLETE_RECV;
633
634                 g_hash_table_insert(partial_recv_table, g_strdup(uidl),
635                                     GINT_TO_POINTER(partial_recv));
636         }
637
638         fclose(fp);
639         session->uidl_table = table;
640         session->partial_recv_table = partial_recv_table;
641         
642         return;
643 }
644
645 #define TRY(func) \
646 if (!(func)) \
647 { \
648         g_warning("failed to write\n"); \
649         goto err_write;                 \
650 } \
651
652 gint pop3_write_uidl_list(Pop3Session *session)
653 {
654         gchar *path, *tmp_path;
655         FILE *fp;
656         Pop3MsgInfo *msg;
657         gint n;
658         gchar *sanitized_uid = g_strdup(session->ac_prefs->userid);
659         
660         subst_for_filename(sanitized_uid);
661         
662
663         if (!session->uidl_is_valid) return 0;
664
665         path = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
666                            "uidl", G_DIR_SEPARATOR_S,
667                            session->ac_prefs->recv_server,
668                            "-", sanitized_uid, NULL);
669         tmp_path = g_strconcat(path, ".tmp", NULL);
670
671         g_free(sanitized_uid);
672
673         if ((fp = g_fopen(tmp_path, "wb")) == NULL) {
674                 FILE_OP_ERROR(tmp_path, "fopen");
675                 goto err_write;
676         }
677
678         for (n = 1; n <= session->count; n++) {
679                 msg = &session->msg[n];
680                 if (msg->uidl && msg->received &&
681                     (!msg->deleted || session->state != POP3_DONE))
682                         TRY(fprintf(fp, "%s\t%ld\t%d\n", 
683                                 msg->uidl, (long int) 
684                                 msg->recv_time, 
685                                 msg->partial_recv) 
686                             > 0);
687         }
688
689         if (fclose(fp) == EOF) {
690                 FILE_OP_ERROR(tmp_path, "fclose");
691                 fp = NULL;
692                 goto err_write;
693         }
694         fp = NULL;
695 #ifdef G_OS_WIN32
696         g_unlink(path);
697 #endif
698         if (g_rename(tmp_path, path) < 0) {
699                 FILE_OP_ERROR(path, "rename");
700                 goto err_write;
701         }
702         g_free(path);
703         g_free(tmp_path);
704         return 0;
705 err_write:
706         if (fp)
707                 fclose(fp);
708         g_free(path);
709         g_free(tmp_path);
710         return -1;
711 }
712
713 #undef TRY
714
715 static gint pop3_write_msg_to_file(const gchar *file, const gchar *data,
716                                    guint len, const gchar *prefix)
717 {
718         FILE *fp;
719         const gchar *prev, *cur;
720
721         g_return_val_if_fail(file != NULL, -1);
722
723         if ((fp = g_fopen(file, "wb")) == NULL) {
724                 FILE_OP_ERROR(file, "fopen");
725                 return -1;
726         }
727
728         if (change_file_mode_rw(fp, file) < 0)
729                 FILE_OP_ERROR(file, "chmod");
730
731         if (prefix != NULL) {
732                 fprintf(fp, "%s", prefix);
733                 fprintf(fp, "\n");
734         }
735         
736         /* +------------------+----------------+--------------------------+ *
737          * ^data              ^prev            ^cur             data+len-1^ */
738
739         prev = data;
740         while ((cur = (gchar *)my_memmem(prev, len - (prev - data), "\r\n", 2))
741                != NULL) {
742                 if ((cur > prev && fwrite(prev, 1, cur - prev, fp) < 1) ||
743                     fputc('\n', fp) == EOF) {
744                         FILE_OP_ERROR(file, "fwrite");
745                         g_warning("can't write to file: %s\n", file);
746                         fclose(fp);
747                         g_unlink(file);
748                         return -1;
749                 }
750
751                 if (cur == data + len - 1) {
752                         prev = cur + 1;
753                         break;
754                 }
755
756                 if (*(cur + 1) == '\n')
757                         prev = cur + 2;
758                 else
759                         prev = cur + 1;
760
761                 if (prev - data < len - 1 && *prev == '.' && *(prev + 1) == '.')
762                         prev++;
763
764                 if (prev - data >= len)
765                         break;
766         }
767
768         if (prev - data < len &&
769             fwrite(prev, 1, len - (prev - data), fp) < 1) {
770                 FILE_OP_ERROR(file, "fwrite");
771                 g_warning("can't write to file: %s\n", file);
772                 fclose(fp);
773                 g_unlink(file);
774                 return -1;
775         }
776         if (data[len - 1] != '\r' && data[len - 1] != '\n') {
777                 if (fputc('\n', fp) == EOF) {
778                         FILE_OP_ERROR(file, "fputc");
779                         g_warning("can't write to file: %s\n", file);
780                         fclose(fp);
781                         g_unlink(file);
782                         return -1;
783                 }
784         }
785
786         if (fclose(fp) == EOF) {
787                 FILE_OP_ERROR(file, "fclose");
788                 g_unlink(file);
789                 return -1;
790         }
791
792         return 0;
793 }
794
795 static Pop3State pop3_lookup_next(Pop3Session *session)
796 {
797         Pop3MsgInfo *msg;
798         PrefsAccount *ac = session->ac_prefs;
799         gint size;
800         gboolean size_limit_over;
801
802         for (;;) {
803                 msg = &session->msg[session->cur_msg];
804                 size = msg->size;
805                 size_limit_over =
806                     (ac->enable_size_limit &&
807                      ac->size_limit > 0 &&
808                      size > ac->size_limit * 1024);
809
810                 if (ac->rmmail &&
811                     msg->recv_time != RECV_TIME_NONE &&
812                     msg->recv_time != RECV_TIME_KEEP &&
813                     msg->partial_recv == POP3_TOTALLY_RECEIVED &&
814                     session->current_time - msg->recv_time >=
815                     ac->msg_leave_time * 24 * 60 * 60) {
816                         log_message(LOG_PROTOCOL, 
817                                         _("POP3: Deleting expired message %d [%s]\n"),
818                                         session->cur_msg, msg->uidl?msg->uidl:" ");
819                         session->cur_total_bytes += size;
820                         pop3_delete_send(session);
821                         return POP3_DELETE;
822                 }
823
824                 if (size_limit_over) {
825                         if (!msg->received && msg->partial_recv != 
826                             POP3_MUST_COMPLETE_RECV) {
827                                 pop3_top_send(session, ac->size_limit);
828                                 return POP3_TOP;
829                         } else if (msg->partial_recv == POP3_MUST_COMPLETE_RECV)
830                                 break;
831
832                         log_message(LOG_PROTOCOL, 
833                                         _("POP3: Skipping message %d [%s] (%d bytes)\n"),
834                                         session->cur_msg, msg->uidl?msg->uidl:" ", size);
835                 }
836                 
837                 if (size == 0 || msg->received || size_limit_over) {
838                         session->cur_total_bytes += size;
839                         if (session->cur_msg == session->count) {
840                                 pop3_logout_send(session);
841                                 return POP3_LOGOUT;
842                         } else
843                                 session->cur_msg++;
844                 } else
845                         break;
846         }
847
848         pop3_retr_send(session);
849         return POP3_RETR;
850 }
851
852 static Pop3ErrorValue pop3_ok(Pop3Session *session, const gchar *msg)
853 {
854         Pop3ErrorValue ok;
855
856         log_print(LOG_PROTOCOL, "POP3< %s\n", msg);
857
858         if (!strncmp(msg, "+OK", 3))
859                 ok = PS_SUCCESS;
860         else if (!strncmp(msg, "-ERR", 4)) {
861                 if (strstr(msg + 4, "lock") ||
862                     strstr(msg + 4, "Lock") ||
863                     strstr(msg + 4, "LOCK") ||
864                     strstr(msg + 4, "wait")) {
865                         log_error(LOG_PROTOCOL, _("mailbox is locked\n"));
866                         ok = PS_LOCKBUSY;
867                 } else if (strcasestr(msg + 4, "timeout")) {
868                         log_error(LOG_PROTOCOL, _("Session timeout\n"));
869                         ok = PS_ERROR;
870                 } else {
871                         switch (session->state) {
872 #if USE_OPENSSL
873                         case POP3_STLS:
874                                 log_error(LOG_PROTOCOL, _("couldn't start TLS session\n"));
875                                 ok = PS_ERROR;
876                                 break;
877 #endif
878                         case POP3_GETAUTH_USER:
879                         case POP3_GETAUTH_PASS:
880                         case POP3_GETAUTH_APOP:
881                                 log_error(LOG_PROTOCOL, _("error occurred on authentication\n"));
882                                 ok = PS_AUTHFAIL;
883                                 break;
884                         case POP3_GETRANGE_LAST:
885                         case POP3_GETRANGE_UIDL:
886                         case POP3_TOP:
887                                 log_warning(LOG_PROTOCOL, _("command not supported\n"));
888                                 ok = PS_NOTSUPPORTED;
889                                 break;
890                                 
891                         default:
892                                 log_error(LOG_PROTOCOL, _("error occurred on POP3 session\n"));
893                                 ok = PS_ERROR;
894                         }
895                 }
896
897                 g_free(session->error_msg);
898                 session->error_msg = g_strdup(msg);
899                 fprintf(stderr, "POP3: %s\n", msg);
900         } else
901                 ok = PS_PROTOCOL;
902
903         session->error_val = ok;
904         return ok;
905 }
906
907 static gint pop3_session_recv_msg(Session *session, const gchar *msg)
908 {
909         Pop3Session *pop3_session = POP3_SESSION(session);
910         Pop3ErrorValue val = PS_SUCCESS;
911         const gchar *body;
912
913         body = msg;
914         if (pop3_session->state != POP3_GETRANGE_UIDL_RECV &&
915             pop3_session->state != POP3_GETSIZE_LIST_RECV) {
916                 val = pop3_ok(pop3_session, msg);
917                 if (val != PS_SUCCESS) {
918                         if (val != PS_NOTSUPPORTED) {
919                                 pop3_session->state = POP3_ERROR;
920                                 return -1;
921                         }
922                 }
923
924                 if (*body == '+' || *body == '-')
925                         body++;
926                 while (g_ascii_isalpha(*body))
927                         body++;
928                 while (g_ascii_isspace(*body))
929                         body++;
930         }
931
932         switch (pop3_session->state) {
933         case POP3_READY:
934         case POP3_GREETING:
935                 pop3_greeting_recv(pop3_session, body);
936 #if USE_OPENSSL
937                 if (pop3_session->ac_prefs->ssl_pop == SSL_STARTTLS)
938                         pop3_stls_send(pop3_session);
939                 else
940 #endif
941                 if (pop3_session->ac_prefs->use_apop_auth)
942                         pop3_getauth_apop_send(pop3_session);
943                 else
944                         pop3_getauth_user_send(pop3_session);
945                 break;
946 #if USE_OPENSSL
947         case POP3_STLS:
948                 if (pop3_stls_recv(pop3_session) != PS_SUCCESS)
949                         return -1;
950                 if (pop3_session->ac_prefs->use_apop_auth)
951                         pop3_getauth_apop_send(pop3_session);
952                 else
953                         pop3_getauth_user_send(pop3_session);
954                 break;
955 #endif
956         case POP3_GETAUTH_USER:
957                 pop3_getauth_pass_send(pop3_session);
958                 break;
959         case POP3_GETAUTH_PASS:
960         case POP3_GETAUTH_APOP:
961                 if (!pop3_session->pop_before_smtp)
962                         pop3_getrange_stat_send(pop3_session);
963                 else
964                         pop3_logout_send(pop3_session);
965                 break;
966         case POP3_GETRANGE_STAT:
967                 if (pop3_getrange_stat_recv(pop3_session, body) < 0)
968                         return -1;
969                 if (pop3_session->count > 0)
970                         pop3_getrange_uidl_send(pop3_session);
971                 else
972                         pop3_logout_send(pop3_session);
973                 break;
974         case POP3_GETRANGE_LAST:
975                 if (val == PS_NOTSUPPORTED)
976                         pop3_session->error_val = PS_SUCCESS;
977                 else if (pop3_getrange_last_recv(pop3_session, body) < 0)
978                         return -1;
979                 if (pop3_session->cur_msg > 0)
980                         pop3_getsize_list_send(pop3_session);
981                 else
982                         pop3_logout_send(pop3_session);
983                 break;
984         case POP3_GETRANGE_UIDL:
985                 if (val == PS_NOTSUPPORTED) {
986                         pop3_session->error_val = PS_SUCCESS;
987                         pop3_getrange_last_send(pop3_session);
988                 } else {
989                         pop3_session->state = POP3_GETRANGE_UIDL_RECV;
990                         session_recv_data(session, 0, ".\r\n");
991                 }
992                 break;
993         case POP3_GETSIZE_LIST:
994                 pop3_session->state = POP3_GETSIZE_LIST_RECV;
995                 session_recv_data(session, 0, ".\r\n");
996                 break;
997         case POP3_RETR:
998                 pop3_session->state = POP3_RETR_RECV;
999                 session_recv_data(session, 0, ".\r\n");
1000                 break;
1001         case POP3_TOP:
1002                 if (val == PS_NOTSUPPORTED) {
1003                         pop3_session->error_val = PS_SUCCESS;
1004                 } else {
1005                         pop3_session->state = POP3_TOP_RECV;
1006                         session_recv_data(session, 0, ".\r\n");
1007                 }
1008                 break;
1009         case POP3_DELETE:
1010                 pop3_delete_recv(pop3_session);
1011                 if (pop3_session->cur_msg == pop3_session->count)
1012                         pop3_logout_send(pop3_session);
1013                 else {
1014                         pop3_session->cur_msg++;
1015                         if (pop3_lookup_next(pop3_session) == POP3_ERROR)
1016                                 return -1;
1017                 }
1018                 break;
1019         case POP3_LOGOUT:
1020                 pop3_session->state = POP3_DONE;
1021                 session_disconnect(session);
1022                 break;
1023         case POP3_ERROR:
1024         default:
1025                 return -1;
1026         }
1027
1028         return 0;
1029 }
1030
1031 static gint pop3_session_recv_data_finished(Session *session, guchar *data,
1032                                             guint len)
1033 {
1034         Pop3Session *pop3_session = POP3_SESSION(session);
1035         Pop3ErrorValue val = PS_SUCCESS;
1036
1037         switch (pop3_session->state) {
1038         case POP3_GETRANGE_UIDL_RECV:
1039                 val = pop3_getrange_uidl_recv(pop3_session, data, len);
1040                 if (val == PS_SUCCESS) {
1041                         if (pop3_session->new_msg_exist)
1042                                 pop3_getsize_list_send(pop3_session);
1043                         else
1044                                 pop3_logout_send(pop3_session);
1045                 } else
1046                         return -1;
1047                 break;
1048         case POP3_GETSIZE_LIST_RECV:
1049                 val = pop3_getsize_list_recv(pop3_session, data, len);
1050                 if (val == PS_SUCCESS) {
1051                         if (pop3_lookup_next(pop3_session) == POP3_ERROR)
1052                                 return -1;
1053                 } else
1054                         return -1;
1055                 break;
1056         case POP3_RETR_RECV:
1057                 if (pop3_retr_recv(pop3_session, data, len) < 0)
1058                         return -1;
1059
1060                 if (pop3_session->ac_prefs->rmmail &&
1061                     pop3_session->ac_prefs->msg_leave_time == 0 &&
1062                     pop3_session->msg[pop3_session->cur_msg].recv_time
1063                     != RECV_TIME_KEEP)
1064                         pop3_delete_send(pop3_session);
1065                 else if (pop3_session->cur_msg == pop3_session->count)
1066                         pop3_logout_send(pop3_session);
1067                 else {
1068                         pop3_session->cur_msg++;
1069                         if (pop3_lookup_next(pop3_session) == POP3_ERROR)
1070                                 return -1;
1071                 }
1072                 break;
1073         case POP3_TOP_RECV:
1074                 if (pop3_top_recv(pop3_session, data, len) < 0)
1075                         return -1;
1076
1077                 if (pop3_session->cur_msg == pop3_session->count)
1078                         pop3_logout_send(pop3_session);
1079                 else {
1080                         pop3_session->cur_msg++;
1081                         if (pop3_lookup_next(pop3_session) == POP3_ERROR)
1082                                 return -1;
1083                 }
1084                 break;
1085         case POP3_TOP:
1086                 log_warning(LOG_PROTOCOL, _("TOP command unsupported\n"));
1087                 if (pop3_session->cur_msg == pop3_session->count)
1088                         pop3_logout_send(pop3_session);
1089                 else {
1090                         pop3_session->cur_msg++;
1091                         if (pop3_lookup_next(pop3_session) == POP3_ERROR)
1092                                 return -1;
1093                 }
1094                 break;
1095         case POP3_ERROR:
1096         default:
1097                 return -1;
1098         }
1099
1100         return 0;
1101 }