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