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