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