strlen checks, refactoring
[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_uidl_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", 
814                                 download);
815                         printf("buf '%s'\n", buf);
816                         if(strlen(buf) > strlen("SC-Marked-For-Download: x\n")
817                         && !strncmp(buf, "SC-Marked-For-Download:", 
818                                     strlen("SC-Marked-For-Download:"))) {
819                                 fprintf(fpnew, "%s", 
820                                  buf+strlen("SC-Marked-For-Download: x\n"));
821                                 continue;
822                         }
823                 }
824                 fprintf(fpnew, "%s", buf);
825         }
826         fclose(fpnew);
827         fclose(fp);
828         unlink(filename);
829         rename(pathnew, filename);
830         
831         g_free(pathnew);
832         return 0;
833 }
834
835 int pop3_mark_for_delete(const gchar *server, const gchar *login, 
836                          const gchar *muidl, const gchar *filename)
837 {
838         return pop3_uidl_mark_mail(server, login, muidl, filename, 
839                 DELETE_MAIL);
840 }
841
842 int pop3_mark_for_download(const gchar *server, const gchar *login, 
843                          const gchar *muidl, const gchar *filename)
844 {
845         return pop3_uidl_mark_mail(server, login, muidl, filename, 
846                 DOWNLOAD_MAIL);
847 }
848
849 gint pop3_write_uidl_list(Pop3Session *session)
850 {
851         gchar *path;
852         FILE *fp;
853         Pop3MsgInfo *msg;
854         gint n;
855
856         if (!session->uidl_is_valid) return 0;
857
858         path = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
859                            "uidl", G_DIR_SEPARATOR_S,
860                            session->ac_prefs->recv_server,
861                            "-", session->ac_prefs->userid, NULL);
862         if ((fp = fopen(path, "wb")) == NULL) {
863                 FILE_OP_ERROR(path, "fopen");
864                 g_free(path);
865                 return -1;
866         }
867
868         for (n = 1; n <= session->count; n++) {
869                 msg = &session->msg[n];
870                 if (msg->uidl && msg->received && !msg->deleted) {
871                         fprintf(fp, "%s\t%ld\t%d\n", 
872                                 msg->uidl, msg->recv_time, msg->partial_recv);
873                 }
874         }
875
876         if (fclose(fp) == EOF) FILE_OP_ERROR(path, "fclose");
877         g_free(path);
878
879         return 0;
880 }
881
882 static gint pop3_write_msg_to_file(const gchar *file, const gchar *data,
883                                    guint len, const gchar *prefix)
884 {
885         FILE *fp;
886         const gchar *prev, *cur;
887
888         g_return_val_if_fail(file != NULL, -1);
889
890         if ((fp = fopen(file, "wb")) == NULL) {
891                 FILE_OP_ERROR(file, "fopen");
892                 return -1;
893         }
894
895         if (change_file_mode_rw(fp, file) < 0)
896                 FILE_OP_ERROR(file, "chmod");
897
898         if (prefix != NULL) {
899                 fprintf(fp, prefix);
900                 fprintf(fp, "\n");
901         }
902         
903         /* +------------------+----------------+--------------------------+ *
904          * ^data              ^prev            ^cur             data+len-1^ */
905
906         prev = data;
907         while ((cur = memchr(prev, '\r', len - (prev - data))) != NULL) {
908                 if ((cur > prev && fwrite(prev, cur - prev, 1, fp) < 1) ||
909                     fputc('\n', fp) == EOF) {
910                         FILE_OP_ERROR(file, "fwrite");
911                         g_warning("can't write to file: %s\n", file);
912                         fclose(fp);
913                         unlink(file);
914                         return -1;
915                 }
916
917                 if (cur == data + len - 1) {
918                         prev = cur + 1;
919                         break;
920                 }
921
922                 if (*(cur + 1) == '\n')
923                         prev = cur + 2;
924                 else
925                         prev = cur + 1;
926
927                 if (prev - data < len - 1 && *prev == '.' && *(prev + 1) == '.')
928                         prev++;
929
930                 if (prev - data >= len)
931                         break;
932         }
933
934         if (prev - data < len &&
935             fwrite(prev, len - (prev - data), 1, fp) < 1) {
936                 FILE_OP_ERROR(file, "fwrite");
937                 g_warning("can't write to file: %s\n", file);
938                 fclose(fp);
939                 unlink(file);
940                 return -1;
941         }
942         if (data[len - 1] != '\r' && data[len - 1] != '\n') {
943                 if (fputc('\n', fp) == EOF) {
944                         FILE_OP_ERROR(file, "fputc");
945                         g_warning("can't write to file: %s\n", file);
946                         fclose(fp);
947                         unlink(file);
948                         return -1;
949                 }
950         }
951
952         if (fclose(fp) == EOF) {
953                 FILE_OP_ERROR(file, "fclose");
954                 unlink(file);
955                 return -1;
956         }
957
958         return 0;
959 }
960
961 static Pop3State pop3_lookup_next(Pop3Session *session)
962 {
963         Pop3MsgInfo *msg;
964         PrefsAccount *ac = session->ac_prefs;
965         gint size;
966         gboolean size_limit_over;
967
968         for (;;) {
969                 msg = &session->msg[session->cur_msg];
970                 size = msg->size;
971                 size_limit_over =
972                     (ac->enable_size_limit &&
973                      ac->size_limit > 0 &&
974                      size > ac->size_limit * 1024);
975
976                 if (ac->rmmail &&
977                     msg->recv_time != RECV_TIME_NONE &&
978                     msg->recv_time != RECV_TIME_KEEP &&
979                     msg->partial_recv == 0 &&
980                     session->current_time - msg->recv_time >=
981                     ac->msg_leave_time * 24 * 60 * 60) {
982                         log_message
983                                 (_("POP3: Deleting expired message "
984                                    "%d\n"), session->cur_msg);
985                         pop3_delete_send(session);
986                         return POP3_DELETE;
987                 }
988
989                 if (size_limit_over) {
990                         log_message
991                                 (_("POP3: Skipping message %d (%d bytes)\n"),
992                                    session->cur_msg, size);
993
994                         if (!msg->received && msg->partial_recv != 2) {
995                                 pop3_top_send(session, ac->size_limit);
996                                 return POP3_TOP;
997                         } else if (msg->partial_recv == 2) {
998                                 break;
999                         }
1000                 }
1001                 
1002                 if (size == 0 || msg->received || size_limit_over) {
1003                         session->cur_total_bytes += size;
1004                         if (session->cur_msg == session->count) {
1005                                 pop3_logout_send(session);
1006                                 return POP3_LOGOUT;
1007                         } else
1008                                 session->cur_msg++;
1009                 } else
1010                         break;
1011         }
1012
1013         pop3_retr_send(session);
1014         return POP3_RETR;
1015 }
1016
1017 static Pop3ErrorValue pop3_ok(Pop3Session *session, const gchar *msg)
1018 {
1019         Pop3ErrorValue ok;
1020
1021         log_print("POP3< %s\n", msg);
1022
1023         if (!strncmp(msg, "+OK", 3))
1024                 ok = PS_SUCCESS;
1025         else if (!strncmp(msg, "-ERR", 4)) {
1026                 if (strstr(msg + 4, "lock") ||
1027                     strstr(msg + 4, "Lock") ||
1028                     strstr(msg + 4, "LOCK") ||
1029                     strstr(msg + 4, "wait")) {
1030                         log_warning(_("mailbox is locked\n"));
1031                         ok = PS_LOCKBUSY;
1032                 } else if (strcasestr(msg + 4, "timeout")) {
1033                         log_warning(_("session timeout\n"));
1034                         ok = PS_ERROR;
1035                 } else {
1036                         switch (session->state) {
1037 #if USE_OPENSSL
1038                         case POP3_STLS:
1039                                 log_warning(_("can't start TLS session\n"));
1040                                 ok = PS_ERROR;
1041                                 break;
1042 #endif
1043                         case POP3_GETAUTH_USER:
1044                         case POP3_GETAUTH_PASS:
1045                         case POP3_GETAUTH_APOP:
1046                                 log_warning(_("error occurred on authentication\n"));
1047                                 ok = PS_AUTHFAIL;
1048                                 break;
1049                         case POP3_GETRANGE_LAST:
1050                         case POP3_GETRANGE_UIDL:
1051                         case POP3_TOP:
1052                                 log_warning(_("command not supported\n"));
1053                                 ok = PS_NOTSUPPORTED;
1054                                 break;
1055                                 
1056                         default:
1057                                 log_warning(_("error occurred on POP3 session\n"));
1058                                 ok = PS_ERROR;
1059                         }
1060                 }
1061
1062                 g_free(session->error_msg);
1063                 session->error_msg = g_strdup(msg);
1064                 fprintf(stderr, "POP3: %s\n", msg);
1065         } else
1066                 ok = PS_PROTOCOL;
1067
1068         session->error_val = ok;
1069         return ok;
1070 }
1071
1072 static gint pop3_session_recv_msg(Session *session, const gchar *msg)
1073 {
1074         Pop3Session *pop3_session = POP3_SESSION(session);
1075         Pop3ErrorValue val = PS_SUCCESS;
1076         const guchar *body;
1077
1078         body = msg;
1079         if (pop3_session->state != POP3_GETRANGE_UIDL_RECV &&
1080             pop3_session->state != POP3_GETSIZE_LIST_RECV) {
1081                 val = pop3_ok(pop3_session, msg);
1082                 if (val != PS_SUCCESS) {
1083                         if (val != PS_NOTSUPPORTED) {
1084                                 pop3_session->state = POP3_ERROR;
1085                                 return -1;
1086                         }
1087                 }
1088
1089                 if (*body == '+' || *body == '-')
1090                         body++;
1091                 while (isalpha(*body))
1092                         body++;
1093                 while (isspace(*body))
1094                         body++;
1095         }
1096
1097         switch (pop3_session->state) {
1098         case POP3_READY:
1099         case POP3_GREETING:
1100                 pop3_greeting_recv(pop3_session, body);
1101 #if USE_OPENSSL
1102                 if (pop3_session->ac_prefs->ssl_pop == SSL_STARTTLS)
1103                         pop3_stls_send(pop3_session);
1104                 else
1105 #endif
1106                 if (pop3_session->ac_prefs->protocol == A_APOP)
1107                         pop3_getauth_apop_send(pop3_session);
1108                 else
1109                         pop3_getauth_user_send(pop3_session);
1110                 break;
1111 #if USE_OPENSSL
1112         case POP3_STLS:
1113                 if (pop3_stls_recv(pop3_session) != PS_SUCCESS)
1114                         return -1;
1115                 if (pop3_session->ac_prefs->protocol == A_APOP)
1116                         pop3_getauth_apop_send(pop3_session);
1117                 else
1118                         pop3_getauth_user_send(pop3_session);
1119                 break;
1120 #endif
1121         case POP3_GETAUTH_USER:
1122                 pop3_getauth_pass_send(pop3_session);
1123                 break;
1124         case POP3_GETAUTH_PASS:
1125         case POP3_GETAUTH_APOP:
1126                 if (!pop3_session->pop_before_smtp)
1127                         pop3_getrange_stat_send(pop3_session);
1128                 else
1129                         pop3_logout_send(pop3_session);
1130                 break;
1131         case POP3_GETRANGE_STAT:
1132                 if (pop3_getrange_stat_recv(pop3_session, body) < 0)
1133                         return -1;
1134                 if (pop3_session->count > 0)
1135                         pop3_getrange_uidl_send(pop3_session);
1136                 else
1137                         pop3_logout_send(pop3_session);
1138                 break;
1139         case POP3_GETRANGE_LAST:
1140                 if (val == PS_NOTSUPPORTED)
1141                         pop3_session->error_val = PS_SUCCESS;
1142                 else if (pop3_getrange_last_recv(pop3_session, body) < 0)
1143                         return -1;
1144                 if (pop3_session->cur_msg > 0)
1145                         pop3_getsize_list_send(pop3_session);
1146                 else
1147                         pop3_logout_send(pop3_session);
1148                 break;
1149         case POP3_GETRANGE_UIDL:
1150                 if (val == PS_NOTSUPPORTED) {
1151                         pop3_session->error_val = PS_SUCCESS;
1152                         pop3_getrange_last_send(pop3_session);
1153                 } else {
1154                         pop3_session->state = POP3_GETRANGE_UIDL_RECV;
1155                         session_recv_data(session, 0, ".\r\n");
1156                 }
1157                 break;
1158         case POP3_GETSIZE_LIST:
1159                 pop3_session->state = POP3_GETSIZE_LIST_RECV;
1160                 session_recv_data(session, 0, ".\r\n");
1161                 break;
1162         case POP3_RETR:
1163                 pop3_session->state = POP3_RETR_RECV;
1164                 session_recv_data(session, 0, ".\r\n");
1165                 break;
1166         case POP3_TOP:
1167                 if (val == PS_NOTSUPPORTED) {
1168                         pop3_session->error_val = PS_SUCCESS;
1169                 } else {
1170                         pop3_session->state = POP3_TOP_RECV;
1171                         session_recv_data(session, 0, ".\r\n");
1172                 }
1173                 break;
1174         case POP3_DELETE:
1175                 pop3_delete_recv(pop3_session);
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_LOGOUT:
1185                 session_disconnect(session);
1186                 break;
1187         case POP3_ERROR:
1188         default:
1189                 return -1;
1190         }
1191
1192         return 0;
1193 }
1194
1195 static gint pop3_session_recv_data_finished(Session *session, guchar *data,
1196                                             guint len)
1197 {
1198         Pop3Session *pop3_session = POP3_SESSION(session);
1199         Pop3ErrorValue val = PS_SUCCESS;
1200
1201         switch (pop3_session->state) {
1202         case POP3_GETRANGE_UIDL_RECV:
1203                 val = pop3_getrange_uidl_recv(pop3_session, data, len);
1204                 if (val == PS_SUCCESS) {
1205                         if (pop3_session->new_msg_exist)
1206                                 pop3_getsize_list_send(pop3_session);
1207                         else
1208                                 pop3_logout_send(pop3_session);
1209                 } else
1210                         return -1;
1211                 break;
1212         case POP3_GETSIZE_LIST_RECV:
1213                 val = pop3_getsize_list_recv(pop3_session, data, len);
1214                 if (val == PS_SUCCESS) {
1215                         if (pop3_lookup_next(pop3_session) == POP3_ERROR)
1216                                 return -1;
1217                 } else
1218                         return -1;
1219                 break;
1220         case POP3_RETR_RECV:
1221                 if (pop3_retr_recv(pop3_session, data, len) < 0)
1222                         return -1;
1223
1224                 if (pop3_session->ac_prefs->rmmail &&
1225                     pop3_session->ac_prefs->msg_leave_time == 0 &&
1226                     pop3_session->msg[pop3_session->cur_msg].recv_time
1227                     != RECV_TIME_KEEP)
1228                         pop3_delete_send(pop3_session);
1229                 else if (pop3_session->cur_msg == pop3_session->count)
1230                         pop3_logout_send(pop3_session);
1231                 else {
1232                         pop3_session->cur_msg++;
1233                         if (pop3_lookup_next(pop3_session) == POP3_ERROR)
1234                                 return -1;
1235                 }
1236                 break;
1237         case POP3_TOP_RECV:
1238                 if (pop3_top_recv(pop3_session, data, len) < 0)
1239                         return -1;
1240
1241                 if (pop3_session->cur_msg == pop3_session->count)
1242                         pop3_logout_send(pop3_session);
1243                 else {
1244                         pop3_session->cur_msg++;
1245                         if (pop3_lookup_next(pop3_session) == POP3_ERROR)
1246                                 return -1;
1247                 }
1248                 break;
1249         case POP3_TOP:
1250                 log_warning(_("TOP command unsupported\n"));
1251                 if (pop3_session->cur_msg == pop3_session->count)
1252                         pop3_logout_send(pop3_session);
1253                 else {
1254                         pop3_session->cur_msg++;
1255                         if (pop3_lookup_next(pop3_session) == POP3_ERROR)
1256                                 return -1;
1257                 }
1258                 break;
1259         case POP3_ERROR:
1260         default:
1261                 return -1;
1262         }
1263
1264         return 0;
1265 }