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