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