2008-08-28 [wwp] 3.5.0cvs81
[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), account, FALSE);
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         claws_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                         claws_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                         claws_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                 claws_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                         claws_unlink(file);
792                         return -1;
793                 }
794         }
795
796         if (fclose(fp) == EOF) {
797                 FILE_OP_ERROR(file, "fclose");
798                 claws_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                      (ac->msg_leave_hour * 60 * 60))) {
827                         log_message(LOG_PROTOCOL, 
828                                         _("POP3: Deleting expired message %d [%s]\n"),
829                                         session->cur_msg, msg->uidl?msg->uidl:" ");
830                         session->cur_total_bytes += size;
831                         pop3_delete_send(session);
832                         return POP3_DELETE;
833                 }
834
835                 if (size_limit_over) {
836                         if (!msg->received && msg->partial_recv != 
837                             POP3_MUST_COMPLETE_RECV) {
838                                 pop3_top_send(session, ac->size_limit);
839                                 return POP3_TOP;
840                         } else if (msg->partial_recv == POP3_MUST_COMPLETE_RECV)
841                                 break;
842
843                         log_message(LOG_PROTOCOL, 
844                                         _("POP3: Skipping message %d [%s] (%d bytes)\n"),
845                                         session->cur_msg, msg->uidl?msg->uidl:" ", size);
846                 }
847                 
848                 if (size == 0 || msg->received || size_limit_over) {
849                         session->cur_total_bytes += size;
850                         if (session->cur_msg == session->count) {
851                                 pop3_logout_send(session);
852                                 return POP3_LOGOUT;
853                         } else
854                                 session->cur_msg++;
855                 } else
856                         break;
857         }
858
859         pop3_retr_send(session);
860         return POP3_RETR;
861 }
862
863 static Pop3ErrorValue pop3_ok(Pop3Session *session, const gchar *msg)
864 {
865         Pop3ErrorValue ok;
866
867         log_print(LOG_PROTOCOL, "POP3< %s\n", msg);
868
869         if (!strncmp(msg, "+OK", 3))
870                 ok = PS_SUCCESS;
871         else if (!strncmp(msg, "-ERR", 4)) {
872                 if (strstr(msg + 4, "lock") ||
873                     strstr(msg + 4, "Lock") ||
874                     strstr(msg + 4, "LOCK") ||
875                     strstr(msg + 4, "wait")) {
876                         log_error(LOG_PROTOCOL, _("mailbox is locked\n"));
877                         ok = PS_LOCKBUSY;
878                 } else if (strcasestr(msg + 4, "timeout")) {
879                         log_error(LOG_PROTOCOL, _("Session timeout\n"));
880                         ok = PS_ERROR;
881                 } else {
882                         switch (session->state) {
883 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
884                         case POP3_STLS:
885                                 log_error(LOG_PROTOCOL, _("couldn't start TLS session\n"));
886                                 ok = PS_ERROR;
887                                 break;
888 #endif
889                         case POP3_GETAUTH_USER:
890                         case POP3_GETAUTH_PASS:
891                         case POP3_GETAUTH_APOP:
892                                 log_error(LOG_PROTOCOL, _("error occurred on authentication\n"));
893                                 ok = PS_AUTHFAIL;
894                                 break;
895                         case POP3_GETRANGE_LAST:
896                         case POP3_GETRANGE_UIDL:
897                         case POP3_TOP:
898                                 log_warning(LOG_PROTOCOL, _("command not supported\n"));
899                                 ok = PS_NOTSUPPORTED;
900                                 break;
901                                 
902                         default:
903                                 log_error(LOG_PROTOCOL, _("error occurred on POP3 session\n"));
904                                 ok = PS_ERROR;
905                         }
906                 }
907
908                 g_free(session->error_msg);
909                 session->error_msg = g_strdup(msg);
910                 g_printerr("POP3: %s\n", msg);
911         } else
912                 ok = PS_PROTOCOL;
913
914         session->error_val = ok;
915         return ok;
916 }
917
918 static gint pop3_session_recv_msg(Session *session, const gchar *msg)
919 {
920         Pop3Session *pop3_session = POP3_SESSION(session);
921         Pop3ErrorValue val = PS_SUCCESS;
922         const gchar *body;
923
924         body = msg;
925         if (pop3_session->state != POP3_GETRANGE_UIDL_RECV &&
926             pop3_session->state != POP3_GETSIZE_LIST_RECV) {
927                 val = pop3_ok(pop3_session, msg);
928                 if (val != PS_SUCCESS) {
929                         if (val != PS_NOTSUPPORTED) {
930                                 pop3_session->state = POP3_ERROR;
931                                 return -1;
932                         }
933                 }
934
935                 if (*body == '+' || *body == '-')
936                         body++;
937                 while (g_ascii_isalpha(*body))
938                         body++;
939                 while (g_ascii_isspace(*body))
940                         body++;
941         }
942
943         switch (pop3_session->state) {
944         case POP3_READY:
945         case POP3_GREETING:
946                 pop3_greeting_recv(pop3_session, body);
947 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
948                 if (pop3_session->ac_prefs->ssl_pop == SSL_STARTTLS)
949                         val = pop3_stls_send(pop3_session);
950                 else
951 #endif
952                 if (pop3_session->ac_prefs->use_apop_auth)
953                         val = pop3_getauth_apop_send(pop3_session);
954                 else
955                         val = pop3_getauth_user_send(pop3_session);
956                 break;
957 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
958         case POP3_STLS:
959                 if (pop3_stls_recv(pop3_session) != PS_SUCCESS)
960                         return -1;
961                 if (pop3_session->ac_prefs->use_apop_auth)
962                         val = pop3_getauth_apop_send(pop3_session);
963                 else
964                         val = pop3_getauth_user_send(pop3_session);
965                 break;
966 #endif
967         case POP3_GETAUTH_USER:
968                 val = pop3_getauth_pass_send(pop3_session);
969                 break;
970         case POP3_GETAUTH_PASS:
971         case POP3_GETAUTH_APOP:
972                 if (!pop3_session->pop_before_smtp)
973                         val = pop3_getrange_stat_send(pop3_session);
974                 else
975                         val = pop3_logout_send(pop3_session);
976                 break;
977         case POP3_GETRANGE_STAT:
978                 if (pop3_getrange_stat_recv(pop3_session, body) < 0)
979                         return -1;
980                 if (pop3_session->count > 0)
981                         val = pop3_getrange_uidl_send(pop3_session);
982                 else
983                         val = pop3_logout_send(pop3_session);
984                 break;
985         case POP3_GETRANGE_LAST:
986                 if (val == PS_NOTSUPPORTED)
987                         pop3_session->error_val = PS_SUCCESS;
988                 else if (pop3_getrange_last_recv(pop3_session, body) < 0)
989                         return -1;
990                 if (pop3_session->cur_msg > 0)
991                         val = pop3_getsize_list_send(pop3_session);
992                 else
993                         val = pop3_logout_send(pop3_session);
994                 break;
995         case POP3_GETRANGE_UIDL:
996                 if (val == PS_NOTSUPPORTED) {
997                         pop3_session->error_val = PS_SUCCESS;
998                         val = pop3_getrange_last_send(pop3_session);
999                 } else {
1000                         pop3_session->state = POP3_GETRANGE_UIDL_RECV;
1001                         session_recv_data(session, 0, ".\r\n");
1002                 }
1003                 break;
1004         case POP3_GETSIZE_LIST:
1005                 pop3_session->state = POP3_GETSIZE_LIST_RECV;
1006                 session_recv_data(session, 0, ".\r\n");
1007                 break;
1008         case POP3_RETR:
1009                 pop3_session->state = POP3_RETR_RECV;
1010                 session_recv_data(session, 0, ".\r\n");
1011                 break;
1012         case POP3_TOP:
1013                 if (val == PS_NOTSUPPORTED) {
1014                         pop3_session->error_val = PS_SUCCESS;
1015                 } else {
1016                         pop3_session->state = POP3_TOP_RECV;
1017                         session_recv_data(session, 0, ".\r\n");
1018                 }
1019                 break;
1020         case POP3_DELETE:
1021                 pop3_delete_recv(pop3_session);
1022                 if (pop3_session->cur_msg == pop3_session->count)
1023                         val = pop3_logout_send(pop3_session);
1024                 else {
1025                         pop3_session->cur_msg++;
1026                         if (pop3_lookup_next(pop3_session) == POP3_ERROR)
1027                                 return -1;
1028                 }
1029                 break;
1030         case POP3_LOGOUT:
1031                 pop3_session->state = POP3_DONE;
1032                 session_disconnect(session);
1033                 break;
1034         case POP3_ERROR:
1035         default:
1036                 return -1;
1037         }
1038
1039         return val == PS_SUCCESS?0:-1;
1040 }
1041
1042 static gint pop3_session_recv_data_finished(Session *session, guchar *data,
1043                                             guint len)
1044 {
1045         Pop3Session *pop3_session = POP3_SESSION(session);
1046         Pop3ErrorValue val = PS_SUCCESS;
1047
1048         switch (pop3_session->state) {
1049         case POP3_GETRANGE_UIDL_RECV:
1050                 val = pop3_getrange_uidl_recv(pop3_session, data, len);
1051                 if (val == PS_SUCCESS) {
1052                         if (pop3_session->new_msg_exist)
1053                                 pop3_getsize_list_send(pop3_session);
1054                         else
1055                                 pop3_logout_send(pop3_session);
1056                 } else
1057                         return -1;
1058                 break;
1059         case POP3_GETSIZE_LIST_RECV:
1060                 val = pop3_getsize_list_recv(pop3_session, data, len);
1061                 if (val == PS_SUCCESS) {
1062                         if (pop3_lookup_next(pop3_session) == POP3_ERROR)
1063                                 return -1;
1064                 } else
1065                         return -1;
1066                 break;
1067         case POP3_RETR_RECV:
1068                 if (pop3_retr_recv(pop3_session, data, len) < 0)
1069                         return -1;
1070
1071                 if (pop3_session->ac_prefs->rmmail &&
1072                     pop3_session->ac_prefs->msg_leave_time == 0 &&
1073                     pop3_session->ac_prefs->msg_leave_hour == 0 &&
1074                     pop3_session->msg[pop3_session->cur_msg].recv_time
1075                     != RECV_TIME_KEEP)
1076                         pop3_delete_send(pop3_session);
1077                 else 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_RECV:
1086                 if (pop3_top_recv(pop3_session, data, len) < 0)
1087                         return -1;
1088
1089                 if (pop3_session->cur_msg == pop3_session->count)
1090                         pop3_logout_send(pop3_session);
1091                 else {
1092                         pop3_session->cur_msg++;
1093                         if (pop3_lookup_next(pop3_session) == POP3_ERROR)
1094                                 return -1;
1095                 }
1096                 break;
1097         case POP3_TOP:
1098                 log_warning(LOG_PROTOCOL, _("TOP command unsupported\n"));
1099                 if (pop3_session->cur_msg == pop3_session->count)
1100                         pop3_logout_send(pop3_session);
1101                 else {
1102                         pop3_session->cur_msg++;
1103                         if (pop3_lookup_next(pop3_session) == POP3_ERROR)
1104                                 return -1;
1105                 }
1106                 break;
1107         case POP3_ERROR:
1108         default:
1109                 return -1;
1110         }
1111
1112         return 0;
1113 }