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