20f4006af6466e19f2daab9bbc7af164fd8d6448
[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 int pop3_msg_in_uidl_list(const gchar *server, const gchar *login, 
613                           const gchar *muidl)
614 {
615         gchar *path;
616         FILE *fp;
617         gchar buf[POPBUFSIZE];
618         gchar uidl[POPBUFSIZE];
619         time_t recv_time;
620         time_t now;
621         gint partial_recv;
622         
623         path = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
624                            "uidl", G_DIR_SEPARATOR_S, server,
625                            "-", login, NULL);
626         if ((fp = fopen(path, "rb")) == NULL) {
627                 if (ENOENT != errno) FILE_OP_ERROR(path, "fopen");
628                 g_free(path);
629                 path = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
630                                    "uidl-", server,
631                                    "-", login, NULL);
632                 if ((fp = fopen(path, "rb")) == NULL) {
633                         if (ENOENT != errno) FILE_OP_ERROR(path, "fopen");
634                         g_free(path);
635                         return FALSE;
636                 }
637         }
638         g_free(path);
639
640         now = time(NULL);
641
642         while (fgets(buf, sizeof(buf), fp) != NULL) {
643                 gchar tmp[POPBUFSIZE];
644                 strretchomp(buf);
645                 recv_time = RECV_TIME_NONE;
646                 partial_recv = 0;
647                 
648                 if (sscanf(buf, "%s\t%ld\t%s", uidl, &recv_time, &tmp) < 2) {
649                         if (sscanf(buf, "%s", uidl) != 1)
650                                 continue;
651                         else {
652                                 recv_time = now;
653                         }
654                 }
655                 if (!strcmp(uidl, muidl)) {
656                         fclose(fp);
657                         return TRUE;
658                 }
659         }
660
661         fclose(fp);     
662         return FALSE;
663 }
664
665 static gchar *pop3_get_filename_for_partial_mail(Pop3Session *session, 
666                                                  gchar *muidl)
667 {
668         gchar *path;
669         gchar *result = NULL;
670         FILE *fp;
671         gchar buf[POPBUFSIZE];
672         gchar uidl[POPBUFSIZE];
673         time_t recv_time;
674         time_t now;
675         gint partial_recv;
676         
677         path = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
678                            "uidl", G_DIR_SEPARATOR_S, 
679                            session->ac_prefs->recv_server,
680                            "-", session->ac_prefs->userid, NULL);
681         if ((fp = fopen(path, "rb")) == NULL) {
682                 if (ENOENT != errno) FILE_OP_ERROR(path, "fopen");
683                 g_free(path);
684                 path = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
685                                    "uidl-", session->ac_prefs->recv_server,
686                                    "-", session->ac_prefs->userid, NULL);
687                 if ((fp = fopen(path, "rb")) == NULL) {
688                         if (ENOENT != errno) FILE_OP_ERROR(path, "fopen");
689                         g_free(path);
690                         return result;
691                 }
692         }
693         g_free(path);
694
695         now = time(NULL);
696
697         while (fgets(buf, sizeof(buf), fp) != NULL) {
698                 gchar tmp[POPBUFSIZE];
699                 strretchomp(buf);
700                 recv_time = RECV_TIME_NONE;
701                 partial_recv = 0;
702                 
703                 if (sscanf(buf, "%s\t%ld\t%s", uidl, &recv_time, &tmp) < 2) {
704                         if (sscanf(buf, "%s", uidl) != 1)
705                                 continue;
706                         else {
707                                 recv_time = now;
708                         }
709                 }
710                 if (!strcmp(muidl, uidl)) {
711                         result = strdup(tmp);
712                         break;
713                 }
714         }
715
716         fclose(fp);
717         
718         return result;
719 }
720
721 #define DOWNLOAD_MAIL 1
722 #define DELETE_MAIL 2
723 static int pop3_mark_mail(const gchar *server, const gchar *login, 
724                           const gchar *muidl, const gchar *filename, 
725                           int download)
726 {
727         gchar *path;
728         gchar *pathnew;
729         FILE *fp;
730         FILE *fpnew;
731         gchar buf[POPBUFSIZE];
732         gchar uidl[POPBUFSIZE];
733         time_t recv_time;
734         time_t now;
735         int len;
736         int start = TRUE;
737         gchar partial_recv[POPBUFSIZE];
738         
739         path = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
740                            "uidl", G_DIR_SEPARATOR_S, server,
741                            "-", login, NULL);
742         if ((fp = fopen(path, "rb")) == NULL) {
743                 perror("fopen1");
744                 if (ENOENT != errno) FILE_OP_ERROR(path, "fopen");
745                 g_free(path);
746                 path = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
747                                    "uidl-", server,
748                                    "-", login, NULL);
749                 if ((fp = fopen(path, "rb")) == NULL) {
750                         if (ENOENT != errno) FILE_OP_ERROR(path, "fopen");
751                         g_free(path);
752                 }
753                 return -1;
754         }
755
756         pathnew = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
757                            "uidl", G_DIR_SEPARATOR_S, server,
758                            "-", login, ".new", NULL);
759         if ((fpnew = fopen(pathnew, "wb")) == NULL) {
760                 perror("fopen2");
761                 fclose(fp);
762                 g_free(pathnew);
763                 return -1;      
764         }
765         
766         now = time(NULL);
767
768         while (fgets(buf, sizeof(buf), fp) != NULL) {
769                 strretchomp(buf);
770                 recv_time = RECV_TIME_NONE;
771                 sprintf(partial_recv,"0");
772                 
773                 if (sscanf(buf, "%s\t%ld\t%s", 
774                            uidl, &recv_time, &partial_recv) < 2) {
775                         if (sscanf(buf, "%s", uidl) != 1)
776                                 continue;
777                         else {
778                                 recv_time = now;
779                         }
780                 }
781                 if (strcmp(muidl, uidl)) {
782                         fprintf(fpnew, "%s\t%ld\t%s\n", 
783                                 uidl, recv_time, partial_recv);
784                 } else {
785                         fprintf(fpnew, "%s\t%ld\t%s\n", 
786                                 uidl, recv_time, 
787                                 download==DOWNLOAD_MAIL?filename:"0");
788                 }
789         }
790         fclose(fpnew);
791         fclose(fp);
792
793         move_file(pathnew, path, TRUE);
794
795         g_free(path);
796         g_free(pathnew);
797         
798         if ((fp = fopen(filename,"rb")) == NULL) {
799                 perror("fopen3");
800                 return -1;
801         }
802         pathnew = g_strdup_printf("%s.new", filename);
803         if ((fpnew = fopen(pathnew, "wb")) == NULL) {
804                 perror("fopen4");
805                 fclose(fp);
806                 g_free(pathnew);
807                 return -1;
808         }
809         
810         while ((len = fread(buf, sizeof(gchar), sizeof(buf), fp)) > 0) {
811                 if (start) {
812                         start = FALSE;
813                         fprintf(fpnew, "SC-Marked-For-Download: %d\n", download);
814                         printf("buf '%s'\n", buf);
815                         if(!strncmp(buf, "SC-Marked-For-Download:", 
816                                     strlen("SC-Marked-For-Download:"))) {
817                                 fprintf(fpnew, "%s", buf+strlen("SC-Marked-For-Download: x\n"));
818                                 continue;
819                         }
820                 }
821                 fprintf(fpnew, "%s", buf);
822         }
823         fclose(fpnew);
824         fclose(fp);
825         unlink(filename);
826         rename(pathnew, filename);
827         
828         g_free(pathnew);
829         return 0;
830 }
831
832 int pop3_mark_for_delete(const gchar *server, const gchar *login, 
833                          const gchar *muidl, const gchar *filename)
834 {
835         return pop3_mark_mail(server, login, muidl, filename, DELETE_MAIL);
836 }
837
838 int pop3_mark_for_download(const gchar *server, const gchar *login, 
839                          const gchar *muidl, const gchar *filename)
840 {
841         return pop3_mark_mail(server, login, muidl, filename, DOWNLOAD_MAIL);
842 }
843
844 gint pop3_write_uidl_list(Pop3Session *session)
845 {
846         gchar *path;
847         FILE *fp;
848         Pop3MsgInfo *msg;
849         gint n;
850
851         if (!session->uidl_is_valid) return 0;
852
853         path = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
854                            "uidl", G_DIR_SEPARATOR_S,
855                            session->ac_prefs->recv_server,
856                            "-", session->ac_prefs->userid, NULL);
857         if ((fp = fopen(path, "wb")) == NULL) {
858                 FILE_OP_ERROR(path, "fopen");
859                 g_free(path);
860                 return -1;
861         }
862
863         for (n = 1; n <= session->count; n++) {
864                 msg = &session->msg[n];
865                 if (msg->uidl && msg->received && !msg->deleted) {
866                         fprintf(fp, "%s\t%ld\t%d\n", 
867                                 msg->uidl, msg->recv_time, msg->partial_recv);
868                 }
869         }
870
871         if (fclose(fp) == EOF) FILE_OP_ERROR(path, "fclose");
872         g_free(path);
873
874         return 0;
875 }
876
877 static gint pop3_write_msg_to_file(const gchar *file, const gchar *data,
878                                    guint len, const gchar *prefix)
879 {
880         FILE *fp;
881         const gchar *prev, *cur;
882
883         g_return_val_if_fail(file != NULL, -1);
884
885         if ((fp = fopen(file, "wb")) == NULL) {
886                 FILE_OP_ERROR(file, "fopen");
887                 return -1;
888         }
889
890         if (change_file_mode_rw(fp, file) < 0)
891                 FILE_OP_ERROR(file, "chmod");
892
893         if (prefix != NULL) {
894                 fprintf(fp, prefix);
895                 fprintf(fp, "\n");
896         }
897         
898         /* +------------------+----------------+--------------------------+ *
899          * ^data              ^prev            ^cur             data+len-1^ */
900
901         prev = data;
902         while ((cur = memchr(prev, '\r', len - (prev - data))) != NULL) {
903                 if ((cur > prev && fwrite(prev, cur - prev, 1, fp) < 1) ||
904                     fputc('\n', fp) == EOF) {
905                         FILE_OP_ERROR(file, "fwrite");
906                         g_warning("can't write to file: %s\n", file);
907                         fclose(fp);
908                         unlink(file);
909                         return -1;
910                 }
911
912                 if (cur == data + len - 1) {
913                         prev = cur + 1;
914                         break;
915                 }
916
917                 if (*(cur + 1) == '\n')
918                         prev = cur + 2;
919                 else
920                         prev = cur + 1;
921
922                 if (prev - data < len - 1 && *prev == '.' && *(prev + 1) == '.')
923                         prev++;
924
925                 if (prev - data >= len)
926                         break;
927         }
928
929         if (prev - data < len &&
930             fwrite(prev, len - (prev - data), 1, fp) < 1) {
931                 FILE_OP_ERROR(file, "fwrite");
932                 g_warning("can't write to file: %s\n", file);
933                 fclose(fp);
934                 unlink(file);
935                 return -1;
936         }
937         if (data[len - 1] != '\r' && data[len - 1] != '\n') {
938                 if (fputc('\n', fp) == EOF) {
939                         FILE_OP_ERROR(file, "fputc");
940                         g_warning("can't write to file: %s\n", file);
941                         fclose(fp);
942                         unlink(file);
943                         return -1;
944                 }
945         }
946
947         if (fclose(fp) == EOF) {
948                 FILE_OP_ERROR(file, "fclose");
949                 unlink(file);
950                 return -1;
951         }
952
953         return 0;
954 }
955
956 static Pop3State pop3_lookup_next(Pop3Session *session)
957 {
958         Pop3MsgInfo *msg;
959         PrefsAccount *ac = session->ac_prefs;
960         gint size;
961         gboolean size_limit_over;
962
963         for (;;) {
964                 msg = &session->msg[session->cur_msg];
965                 size = msg->size;
966                 size_limit_over =
967                     (ac->enable_size_limit &&
968                      ac->size_limit > 0 &&
969                      size > ac->size_limit * 1024);
970
971                 if (ac->rmmail &&
972                     msg->recv_time != RECV_TIME_NONE &&
973                     msg->recv_time != RECV_TIME_KEEP &&
974                     msg->partial_recv == 0 &&
975                     session->current_time - msg->recv_time >=
976                     ac->msg_leave_time * 24 * 60 * 60) {
977                         log_message
978                                 (_("POP3: Deleting expired message "
979                                    "%d\n"), session->cur_msg);
980                         pop3_delete_send(session);
981                         return POP3_DELETE;
982                 }
983
984                 if (size_limit_over) {
985                         log_message
986                                 (_("POP3: Skipping message %d (%d bytes)\n"),
987                                    session->cur_msg, size);
988
989                         if (!msg->received && msg->partial_recv != 2) {
990                                 pop3_top_send(session, ac->size_limit);
991                                 return POP3_TOP;
992                         } else if (msg->partial_recv == 2) {
993                                 break;
994                         }
995                 }
996                 
997                 if (size == 0 || msg->received || size_limit_over) {
998                         session->cur_total_bytes += size;
999                         if (session->cur_msg == session->count) {
1000                                 pop3_logout_send(session);
1001                                 return POP3_LOGOUT;
1002                         } else
1003                                 session->cur_msg++;
1004                 } else
1005                         break;
1006         }
1007
1008         pop3_retr_send(session);
1009         return POP3_RETR;
1010 }
1011
1012 static Pop3ErrorValue pop3_ok(Pop3Session *session, const gchar *msg)
1013 {
1014         Pop3ErrorValue ok;
1015
1016         log_print("POP3< %s\n", msg);
1017
1018         if (!strncmp(msg, "+OK", 3))
1019                 ok = PS_SUCCESS;
1020         else if (!strncmp(msg, "-ERR", 4)) {
1021                 if (strstr(msg + 4, "lock") ||
1022                     strstr(msg + 4, "Lock") ||
1023                     strstr(msg + 4, "LOCK") ||
1024                     strstr(msg + 4, "wait")) {
1025                         log_warning(_("mailbox is locked\n"));
1026                         ok = PS_LOCKBUSY;
1027                 } else if (strcasestr(msg + 4, "timeout")) {
1028                         log_warning(_("session timeout\n"));
1029                         ok = PS_ERROR;
1030                 } else {
1031                         switch (session->state) {
1032 #if USE_OPENSSL
1033                         case POP3_STLS:
1034                                 log_warning(_("can't start TLS session\n"));
1035                                 ok = PS_ERROR;
1036                                 break;
1037 #endif
1038                         case POP3_GETAUTH_USER:
1039                         case POP3_GETAUTH_PASS:
1040                         case POP3_GETAUTH_APOP:
1041                                 log_warning(_("error occurred on authentication\n"));
1042                                 ok = PS_AUTHFAIL;
1043                                 break;
1044                         case POP3_GETRANGE_LAST:
1045                         case POP3_GETRANGE_UIDL:
1046                         case POP3_TOP:
1047                                 log_warning(_("command not supported\n"));
1048                                 ok = PS_NOTSUPPORTED;
1049                                 break;
1050                                 
1051                         default:
1052                                 log_warning(_("error occurred on POP3 session\n"));
1053                                 ok = PS_ERROR;
1054                         }
1055                 }
1056
1057                 g_free(session->error_msg);
1058                 session->error_msg = g_strdup(msg);
1059                 fprintf(stderr, "POP3: %s\n", msg);
1060         } else
1061                 ok = PS_PROTOCOL;
1062
1063         session->error_val = ok;
1064         return ok;
1065 }
1066
1067 static gint pop3_session_recv_msg(Session *session, const gchar *msg)
1068 {
1069         Pop3Session *pop3_session = POP3_SESSION(session);
1070         Pop3ErrorValue val = PS_SUCCESS;
1071         const guchar *body;
1072
1073         body = msg;
1074         if (pop3_session->state != POP3_GETRANGE_UIDL_RECV &&
1075             pop3_session->state != POP3_GETSIZE_LIST_RECV) {
1076                 val = pop3_ok(pop3_session, msg);
1077                 if (val != PS_SUCCESS) {
1078                         if (val != PS_NOTSUPPORTED) {
1079                                 pop3_session->state = POP3_ERROR;
1080                                 return -1;
1081                         }
1082                 }
1083
1084                 if (*body == '+' || *body == '-')
1085                         body++;
1086                 while (isalpha(*body))
1087                         body++;
1088                 while (isspace(*body))
1089                         body++;
1090         }
1091
1092         switch (pop3_session->state) {
1093         case POP3_READY:
1094         case POP3_GREETING:
1095                 pop3_greeting_recv(pop3_session, body);
1096 #if USE_OPENSSL
1097                 if (pop3_session->ac_prefs->ssl_pop == SSL_STARTTLS)
1098                         pop3_stls_send(pop3_session);
1099                 else
1100 #endif
1101                 if (pop3_session->ac_prefs->protocol == A_APOP)
1102                         pop3_getauth_apop_send(pop3_session);
1103                 else
1104                         pop3_getauth_user_send(pop3_session);
1105                 break;
1106 #if USE_OPENSSL
1107         case POP3_STLS:
1108                 if (pop3_stls_recv(pop3_session) != PS_SUCCESS)
1109                         return -1;
1110                 if (pop3_session->ac_prefs->protocol == A_APOP)
1111                         pop3_getauth_apop_send(pop3_session);
1112                 else
1113                         pop3_getauth_user_send(pop3_session);
1114                 break;
1115 #endif
1116         case POP3_GETAUTH_USER:
1117                 pop3_getauth_pass_send(pop3_session);
1118                 break;
1119         case POP3_GETAUTH_PASS:
1120         case POP3_GETAUTH_APOP:
1121                 if (!pop3_session->pop_before_smtp)
1122                         pop3_getrange_stat_send(pop3_session);
1123                 else
1124                         pop3_logout_send(pop3_session);
1125                 break;
1126         case POP3_GETRANGE_STAT:
1127                 if (pop3_getrange_stat_recv(pop3_session, body) < 0)
1128                         return -1;
1129                 if (pop3_session->count > 0)
1130                         pop3_getrange_uidl_send(pop3_session);
1131                 else
1132                         pop3_logout_send(pop3_session);
1133                 break;
1134         case POP3_GETRANGE_LAST:
1135                 if (val == PS_NOTSUPPORTED)
1136                         pop3_session->error_val = PS_SUCCESS;
1137                 else if (pop3_getrange_last_recv(pop3_session, body) < 0)
1138                         return -1;
1139                 if (pop3_session->cur_msg > 0)
1140                         pop3_getsize_list_send(pop3_session);
1141                 else
1142                         pop3_logout_send(pop3_session);
1143                 break;
1144         case POP3_GETRANGE_UIDL:
1145                 if (val == PS_NOTSUPPORTED) {
1146                         pop3_session->error_val = PS_SUCCESS;
1147                         pop3_getrange_last_send(pop3_session);
1148                 } else {
1149                         pop3_session->state = POP3_GETRANGE_UIDL_RECV;
1150                         session_recv_data(session, 0, ".\r\n");
1151                 }
1152                 break;
1153         case POP3_GETSIZE_LIST:
1154                 pop3_session->state = POP3_GETSIZE_LIST_RECV;
1155                 session_recv_data(session, 0, ".\r\n");
1156                 break;
1157         case POP3_RETR:
1158                 pop3_session->state = POP3_RETR_RECV;
1159                 session_recv_data(session, 0, ".\r\n");
1160                 break;
1161         case POP3_TOP:
1162                 if (val == PS_NOTSUPPORTED) {
1163                         pop3_session->error_val = PS_SUCCESS;
1164                 } else {
1165                         pop3_session->state = POP3_TOP_RECV;
1166                         session_recv_data(session, 0, ".\r\n");
1167                 }
1168                 break;
1169         case POP3_DELETE:
1170                 pop3_delete_recv(pop3_session);
1171                 if (pop3_session->cur_msg == pop3_session->count)
1172                         pop3_logout_send(pop3_session);
1173                 else {
1174                         pop3_session->cur_msg++;
1175                         if (pop3_lookup_next(pop3_session) == POP3_ERROR)
1176                                 return -1;
1177                 }
1178                 break;
1179         case POP3_LOGOUT:
1180                 session_disconnect(session);
1181                 break;
1182         case POP3_ERROR:
1183         default:
1184                 return -1;
1185         }
1186
1187         return 0;
1188 }
1189
1190 static gint pop3_session_recv_data_finished(Session *session, guchar *data,
1191                                             guint len)
1192 {
1193         Pop3Session *pop3_session = POP3_SESSION(session);
1194         Pop3ErrorValue val = PS_SUCCESS;
1195
1196         switch (pop3_session->state) {
1197         case POP3_GETRANGE_UIDL_RECV:
1198                 val = pop3_getrange_uidl_recv(pop3_session, data, len);
1199                 if (val == PS_SUCCESS) {
1200                         if (pop3_session->new_msg_exist)
1201                                 pop3_getsize_list_send(pop3_session);
1202                         else
1203                                 pop3_logout_send(pop3_session);
1204                 } else
1205                         return -1;
1206                 break;
1207         case POP3_GETSIZE_LIST_RECV:
1208                 val = pop3_getsize_list_recv(pop3_session, data, len);
1209                 if (val == PS_SUCCESS) {
1210                         if (pop3_lookup_next(pop3_session) == POP3_ERROR)
1211                                 return -1;
1212                 } else
1213                         return -1;
1214                 break;
1215         case POP3_RETR_RECV:
1216                 if (pop3_retr_recv(pop3_session, data, len) < 0)
1217                         return -1;
1218
1219                 if (pop3_session->ac_prefs->rmmail &&
1220                     pop3_session->ac_prefs->msg_leave_time == 0 &&
1221                     pop3_session->msg[pop3_session->cur_msg].recv_time
1222                     != RECV_TIME_KEEP)
1223                         pop3_delete_send(pop3_session);
1224                 else if (pop3_session->cur_msg == pop3_session->count)
1225                         pop3_logout_send(pop3_session);
1226                 else {
1227                         pop3_session->cur_msg++;
1228                         if (pop3_lookup_next(pop3_session) == POP3_ERROR)
1229                                 return -1;
1230                 }
1231                 break;
1232         case POP3_TOP_RECV:
1233                 if (pop3_top_recv(pop3_session, data, len) < 0)
1234                         return -1;
1235
1236                 if (pop3_session->cur_msg == pop3_session->count)
1237                         pop3_logout_send(pop3_session);
1238                 else {
1239                         pop3_session->cur_msg++;
1240                         if (pop3_lookup_next(pop3_session) == POP3_ERROR)
1241                                 return -1;
1242                 }
1243                 break;
1244         case POP3_TOP:
1245                 log_warning(_("TOP command unsupported\n"));
1246                 if (pop3_session->cur_msg == pop3_session->count)
1247                         pop3_logout_send(pop3_session);
1248                 else {
1249                         pop3_session->cur_msg++;
1250                         if (pop3_lookup_next(pop3_session) == POP3_ERROR)
1251                                 return -1;
1252                 }
1253                 break;
1254         case POP3_ERROR:
1255         default:
1256                 return -1;
1257         }
1258
1259         return 0;
1260 }