058fe1de61ef2bf6f366aa093d780cff95bce220
[apps/madmutt.git] / pop / pop.c
1 /*
2  * Copyright notice from original mutt:
3  * Copyright (C) 2000-2002 Vsevolod Volkov <vvv@mutt.org.ua>
4  *
5  * This file is part of mutt-ng, see http://www.muttng.org/.
6  * It's licensed under the GNU General Public License,
7  * please see the file GPL in the top level source directory.
8  */
9
10 #if HAVE_CONFIG_H
11 # include "config.h"
12 #endif
13
14 #include <lib-lib/mem.h>
15 #include <lib-lib/str.h>
16 #include <lib-lib/macros.h>
17
18 #include "mutt.h"
19 #include "mx.h"
20 #include "pop.h"
21 #include "mutt_crypt.h"
22 #include "mutt_curses.h"
23
24 #include "lib/debug.h"
25
26 #include <string.h>
27 #include <unistd.h>
28
29 /* write line to file */
30 static int fetch_message (char *line, void *file)
31 {
32   FILE *f = (FILE *) file;
33
34   fputs (line, f);
35   if (fputc ('\n', f) == EOF)
36     return -1;
37
38   return 0;
39 }
40
41 /*
42  * Read header
43  * returns:
44  *  0 on success
45  * -1 - conection lost,
46  * -2 - invalid command or execution error,
47  * -3 - error writing to tempfile
48  */
49 static pop_query_status pop_read_header (POP_DATA * pop_data, HEADER * h)
50 {
51   FILE *f;
52   int index;
53   pop_query_status ret;
54   long length;
55   char buf[LONG_STRING];
56   char tempfile[_POSIX_PATH_MAX];
57
58   mutt_mktemp (tempfile);
59   if (!(f = safe_fopen (tempfile, "w+"))) {
60     mutt_perror (tempfile);
61     return PFD_FUNCT_ERROR;
62   }
63
64   snprintf (buf, sizeof (buf), "LIST %d\r\n", h->refno);
65   ret = pop_query (pop_data, buf, sizeof (buf));
66   if (ret == PQ_OK) {
67     sscanf (buf, "+OK %d %ld", &index, &length);
68
69     snprintf (buf, sizeof (buf), "TOP %d 0\r\n", h->refno);
70     ret = pop_fetch_data (pop_data, buf, NULL, fetch_message, f);
71
72     if (pop_data->cmd_top == CMD_UNKNOWN) {
73       if (ret == PQ_OK) {
74         pop_data->cmd_top = CMD_AVAILABLE;
75
76         debug_print (1, ("set TOP capability\n"));
77       }
78
79       if (ret == PQ_ERR) {
80         pop_data->cmd_top = CMD_NOT_AVAILABLE;
81
82         debug_print (1, ("unset TOP capability\n"));
83         snprintf (pop_data->err_msg, sizeof (pop_data->err_msg),
84                   _("Command TOP is not supported by server."));
85       }
86     }
87   }
88
89   switch (ret) {
90   case PQ_OK:
91     {
92       rewind (f);
93       h->env = mutt_read_rfc822_header (f, h, 0, 0);
94       h->content->length = length - h->content->offset + 1;
95       rewind (f);
96       while (!feof (f)) {
97         h->content->length--;
98         fgets (buf, sizeof (buf), f);
99       }
100       break;
101     }
102   case PQ_ERR:
103     {
104       mutt_error ("%s", pop_data->err_msg);
105       break;
106     }
107   case PFD_FUNCT_ERROR:
108     {
109       mutt_error _("Can't write header to temporary file!");
110
111       break;
112     }
113   case PQ_NOT_CONNECTED:
114     {
115       mutt_error _("Can't fetch header: Not connected!");
116       break;
117     }
118   }
119
120   fclose (f);
121   unlink (tempfile);
122   return ret;
123 }
124
125 /* parse UIDL */
126 static int fetch_uidl (char *line, void *data)
127 {
128   int i, index;
129   CONTEXT *ctx = (CONTEXT *) data;
130   POP_DATA *pop_data = (POP_DATA *) ctx->data;
131
132   sscanf (line, "%d %s", &index, line);
133   for (i = 0; i < ctx->msgcount; i++)
134     if (!str_cmp (line, ctx->hdrs[i]->data))
135       break;
136
137   if (i == ctx->msgcount) {
138     debug_print (1, ("new header %d %s\n", index, line));
139
140     if (i >= ctx->hdrmax)
141       mx_alloc_memory (ctx);
142
143     ctx->msgcount++;
144     ctx->hdrs[i] = mutt_new_header ();
145     ctx->hdrs[i]->data = m_strdup(line);
146   }
147   else if (ctx->hdrs[i]->index != index - 1)
148     pop_data->clear_cache = 1;
149
150   ctx->hdrs[i]->refno = index;
151   ctx->hdrs[i]->index = index - 1;
152
153   return 0;
154 }
155
156 /*
157  * Read headers
158  * returns:
159  *  0 on success
160  * -1 - conection lost,
161  * -2 - invalid command or execution error,
162  * -3 - error writing to tempfile
163  */
164 static int pop_fetch_headers (CONTEXT * ctx)
165 {
166   int i, old_count, new_count;
167   pop_query_status ret;
168   POP_DATA *pop_data = (POP_DATA *) ctx->data;
169
170   time (&pop_data->check_time);
171   pop_data->clear_cache = 0;
172
173   for (i = 0; i < ctx->msgcount; i++)
174     ctx->hdrs[i]->refno = -1;
175
176   old_count = ctx->msgcount;
177   ret = pop_fetch_data (pop_data, "UIDL\r\n", NULL, fetch_uidl, ctx);
178   new_count = ctx->msgcount;
179   ctx->msgcount = old_count;
180
181   if (pop_data->cmd_uidl == CMD_UNKNOWN) {
182     if (ret == PQ_OK) {
183       pop_data->cmd_uidl = CMD_AVAILABLE;
184
185       debug_print (1, ("set UIDL capability\n"));
186     }
187
188     if (ret == PQ_ERR && pop_data->cmd_uidl == CMD_UNKNOWN) {
189       pop_data->cmd_uidl = CMD_NOT_AVAILABLE;
190
191       debug_print (1, ("unset UIDL capability\n"));
192       snprintf (pop_data->err_msg, sizeof (pop_data->err_msg),
193                 _("Command UIDL is not supported by server."));
194     }
195   }
196
197   if (ret == PQ_OK) {
198     for (i = 0; i < old_count; i++)
199       if (ctx->hdrs[i]->refno == -1)
200         ctx->hdrs[i]->deleted = 1;
201
202     for (i = old_count; i < new_count; i++) {
203       mutt_message (_("Fetching message headers... [%d/%d]"),
204                     i + 1 - old_count, new_count - old_count);
205
206       ret = pop_read_header (pop_data, ctx->hdrs[i]);
207       if (ret != PQ_OK)
208         break;
209
210       ctx->msgcount++;
211     }
212
213     if (i > old_count)
214       mx_update_context (ctx, i - old_count);
215   }
216
217   if (ret != PQ_OK) {
218     for (i = ctx->msgcount; i < new_count; i++)
219       mutt_free_header (&ctx->hdrs[i]);
220     return ret;
221   }
222
223   mutt_clear_error ();
224   return (new_count - old_count);
225 }
226
227 /* open POP mailbox - fetch only headers */
228 int pop_open_mailbox (CONTEXT * ctx)
229 {
230   int ret;
231   char buf[LONG_STRING];
232   CONNECTION *conn;
233   ACCOUNT acct;
234   POP_DATA *pop_data;
235   ciss_url_t url;
236
237   if (pop_parse_path (ctx->path, &acct)) {
238     mutt_error (_("%s is an invalid POP path"), ctx->path);
239     mutt_sleep (2);
240     return -1;
241   }
242
243   mutt_account_tourl (&acct, &url);
244   url.path = NULL;
245   url_ciss_tostring (&url, buf, sizeof (buf), 0);
246   conn = mutt_conn_find (NULL, &acct);
247   if (!conn)
248     return -1;
249
250   p_delete(&ctx->path);
251   ctx->path = m_strdup(buf);
252
253   pop_data = p_new(POP_DATA, 1);
254   pop_data->conn = conn;
255   ctx->data = pop_data;
256
257   if (pop_open_connection (pop_data) < 0)
258     return -1;
259
260   conn->data = pop_data;
261
262   FOREVER {
263     if (pop_reconnect (ctx) != PQ_OK)
264       return -1;
265
266     ctx->size = pop_data->size;
267
268     mutt_message _("Fetching list of messages...");
269
270     ret = pop_fetch_headers (ctx);
271
272     if (ret >= 0)
273       return 0;
274
275     if (ret < -1) {
276       mutt_sleep (2);
277       return -1;
278     }
279   }
280 }
281
282 /* delete all cached messages */
283 static void pop_clear_cache (POP_DATA * pop_data)
284 {
285   int i;
286
287   if (!pop_data->clear_cache)
288     return;
289
290   debug_print (1, ("delete cached messages\n"));
291
292   for (i = 0; i < POP_CACHE_LEN; i++) {
293     if (pop_data->cache[i].path) {
294       unlink (pop_data->cache[i].path);
295       p_delete(&pop_data->cache[i].path);
296     }
297   }
298 }
299
300 /* close POP mailbox */
301 void pop_close_mailbox (CONTEXT * ctx)
302 {
303   POP_DATA *pop_data = (POP_DATA *) ctx->data;
304
305   if (!pop_data)
306     return;
307
308   pop_logout (ctx);
309
310   if (pop_data->status != POP_NONE)
311     mutt_socket_close (pop_data->conn);
312
313   pop_data->status = POP_NONE;
314
315   pop_data->clear_cache = 1;
316   pop_clear_cache (pop_data);
317
318   if (!pop_data->conn->data)
319     mutt_socket_free (pop_data->conn);
320
321   return;
322 }
323
324 /* fetch message from POP server */
325 int pop_fetch_message (MESSAGE * msg, CONTEXT * ctx, int msgno)
326 {
327   int ret;
328   void *uidl;
329   char buf[LONG_STRING];
330   char path[_POSIX_PATH_MAX];
331   progress_t bar;
332   POP_DATA *pop_data = (POP_DATA *) ctx->data;
333   POP_CACHE *cache;
334   HEADER *h = ctx->hdrs[msgno];
335
336   /* see if we already have the message in our cache */
337   cache = &pop_data->cache[h->index % POP_CACHE_LEN];
338
339   if (cache->path) {
340     if (cache->index == h->index) {
341       /* yes, so just return a pointer to the message */
342       msg->fp = fopen (cache->path, "r");
343       if (msg->fp)
344         return 0;
345
346       mutt_perror (cache->path);
347       mutt_sleep (2);
348       return -1;
349     }
350     else {
351       /* clear the previous entry */
352       unlink (cache->path);
353       p_delete(&cache->path);
354     }
355   }
356
357   FOREVER {
358     if (pop_reconnect (ctx) != PQ_OK)
359       return -1;
360
361     /* verify that massage index is correct */
362     if (h->refno < 0) {
363       mutt_error
364         _("The message index is incorrect. Try reopening the mailbox.");
365       mutt_sleep (2);
366       return -1;
367     }
368
369     bar.size = h->content->length + h->content->offset - 1;
370     bar.msg = _("Fetching message...");
371     mutt_progress_bar (&bar, 0);
372
373     mutt_mktemp (path);
374     msg->fp = safe_fopen (path, "w+");
375     if (!msg->fp) {
376       mutt_perror (path);
377       mutt_sleep (2);
378       return -1;
379     }
380
381     snprintf (buf, sizeof (buf), "RETR %d\r\n", h->refno);
382
383     ret = pop_fetch_data (pop_data, buf, &bar, fetch_message, msg->fp);
384     if (ret == PQ_OK)
385       break;
386
387     safe_fclose (&msg->fp);
388     unlink (path);
389
390     if (ret == PQ_ERR) {
391       mutt_error ("%s", pop_data->err_msg);
392       mutt_sleep (2);
393       return -1;
394     }
395
396     if (ret == PFD_FUNCT_ERROR) {
397       mutt_error _("Can't write message to temporary file!");
398
399       mutt_sleep (2);
400       return -1;
401     }
402   }
403
404   /* Update the header information.  Previously, we only downloaded a
405    * portion of the headers, those required for the main display.
406    */
407   cache->index = h->index;
408   cache->path = m_strdup(path);
409   rewind (msg->fp);
410   uidl = h->data;
411   mutt_free_envelope (&h->env);
412   h->env = mutt_read_rfc822_header (msg->fp, h, 0, 0);
413   h->data = uidl;
414   h->lines = 0;
415   fgets (buf, sizeof (buf), msg->fp);
416   while (!feof (msg->fp)) {
417     ctx->hdrs[msgno]->lines++;
418     fgets (buf, sizeof (buf), msg->fp);
419   }
420
421   h->content->length = ftello (msg->fp) - h->content->offset;
422
423   /* This needs to be done in case this is a multipart message */
424   if (!WithCrypto)
425     h->security = crypt_query (h->content);
426
427   mutt_clear_error ();
428   rewind (msg->fp);
429
430   return 0;
431 }
432
433 /* update POP mailbox - delete messages from server */
434 pop_query_status pop_sync_mailbox (CONTEXT * ctx, int unused, int *index_hint)
435 {
436   int i;
437   pop_query_status ret;
438   char buf[LONG_STRING];
439   POP_DATA *pop_data = (POP_DATA *) ctx->data;
440
441   pop_data->check_time = 0;
442
443   FOREVER {
444     if (pop_reconnect (ctx) != PQ_OK)
445       return PQ_NOT_CONNECTED;
446
447     mutt_message (_("Marking %d messages deleted..."), ctx->deleted);
448
449     for (i = 0, ret = 0; ret == 0 && i < ctx->msgcount; i++) {
450       if (ctx->hdrs[i]->deleted) {
451         snprintf (buf, sizeof (buf), "DELE %d\r\n", ctx->hdrs[i]->refno);
452         ret = pop_query (pop_data, buf, sizeof (buf));
453       }
454     }
455
456     if (ret == PQ_OK) {
457       strfcpy (buf, "QUIT\r\n", sizeof (buf));
458       ret = pop_query (pop_data, buf, sizeof (buf));
459     }
460
461     if (ret == PQ_OK) {
462       pop_data->clear_cache = 1;
463       pop_clear_cache (pop_data);
464       pop_data->status = POP_DISCONNECTED;
465       return PQ_OK;
466     }
467
468     if (ret == PQ_ERR) {
469       mutt_error ("%s", pop_data->err_msg);
470       mutt_sleep (2);
471       return PQ_NOT_CONNECTED;
472     }
473   }
474 }
475
476 /* Check for new messages and fetch headers */
477 int pop_check_mailbox (CONTEXT * ctx, int *index_hint, int unused)
478 {
479   int ret;
480   POP_DATA *pop_data = (POP_DATA *) ctx->data;
481
482   if ((pop_data->check_time + PopCheckTimeout) > time (NULL))
483     return 0;
484
485   pop_logout (ctx);
486
487   mutt_socket_close (pop_data->conn);
488
489   if (pop_open_connection (pop_data) < 0)
490     return -1;
491
492   ctx->size = pop_data->size;
493
494   mutt_message _("Checking for new messages...");
495
496   ret = pop_fetch_headers (ctx);
497   pop_clear_cache (pop_data);
498
499   if (ret < 0)
500     return -1;
501
502   if (ret > 0)
503     return M_NEW_MAIL;
504
505   return 0;
506 }
507
508 /* Fetch messages and save them in $spoolfile */
509 void pop_fetch_mail (void)
510 {
511   char buffer[LONG_STRING];
512   char msgbuf[SHORT_STRING];
513   char *url, *p;
514   int i, delanswer, last = 0, msgs, bytes, rset = 0;
515   pop_query_status ret;
516   CONNECTION *conn;
517   CONTEXT ctx;
518   MESSAGE *msg = NULL;
519   ACCOUNT acct;
520   POP_DATA *pop_data;
521
522   if (!PopHost) {
523     mutt_error _("POP host is not defined.");
524
525     return;
526   }
527
528   url = p = p_new(char, strlen (PopHost) + 7);
529   if (url_check_scheme (PopHost) == U_UNKNOWN) {
530     strcpy (url, "pop://");     /* __STRCPY_CHECKED__ */
531     p = strchr (url, '\0');
532   }
533   strcpy (p, PopHost);          /* __STRCPY_CHECKED__ */
534
535   ret = pop_parse_path (url, &acct);
536   p_delete(&url);
537   if (ret) {
538     mutt_error (_("%s is an invalid POP path"), PopHost);
539     return;
540   }
541
542   conn = mutt_conn_find (NULL, &acct);
543   if (!conn)
544     return;
545
546   pop_data = p_new(POP_DATA, 1);
547   pop_data->conn = conn;
548
549   if (pop_open_connection (pop_data) < 0) {
550     mutt_socket_free (pop_data->conn);
551     p_delete(&pop_data);
552     return;
553   }
554
555   conn->data = pop_data;
556
557   mutt_message _("Checking for new messages...");
558
559   /* find out how many messages are in the mailbox. */
560   strfcpy (buffer, "STAT\r\n", sizeof (buffer));
561   ret = pop_query (pop_data, buffer, sizeof (buffer));
562   if (ret == PQ_NOT_CONNECTED)
563     goto fail;
564   if (ret == PQ_ERR) {
565     mutt_error ("%s", pop_data->err_msg);
566     goto finish;
567   }
568
569   sscanf (buffer, "+OK %d %d", &msgs, &bytes);
570
571   /* only get unread messages */
572   if (msgs > 0 && option (OPTPOPLAST)) {
573     strfcpy (buffer, "LAST\r\n", sizeof (buffer));
574     ret = pop_query (pop_data, buffer, sizeof (buffer));
575     if (ret == PQ_NOT_CONNECTED)
576       goto fail;
577     if (ret == PQ_OK)
578       sscanf (buffer, "+OK %d", &last);
579   }
580
581   if (msgs <= last) {
582     mutt_message _("No new mail in POP mailbox.");
583
584     goto finish;
585   }
586
587   if (mx_open_mailbox (NONULL (Spoolfile), M_APPEND, &ctx) == NULL)
588     goto finish;
589
590   delanswer =
591     query_quadoption (OPT_POPDELETE, _("Delete messages from server?"));
592
593   snprintf (msgbuf, sizeof (msgbuf), _("Reading new messages (%d bytes)..."),
594             bytes);
595   mutt_message ("%s", msgbuf);
596
597   for (i = last + 1; i <= msgs; i++) {
598     if ((msg = mx_open_new_message (&ctx, NULL, M_ADD_FROM)) == NULL)
599       ret = -3;
600     else {
601       snprintf (buffer, sizeof (buffer), "RETR %d\r\n", i);
602       ret = pop_fetch_data (pop_data, buffer, NULL, fetch_message, msg->fp);
603       if (ret == PFD_FUNCT_ERROR)
604         rset = 1;
605
606       if (ret == PQ_OK && mx_commit_message (msg, &ctx) != 0) {
607         rset = 1;
608         ret = PFD_FUNCT_ERROR;
609       }
610
611       mx_close_message (&msg);
612     }
613
614     if (ret == PQ_OK && delanswer == M_YES) {
615       /* delete the message on the server */
616       snprintf (buffer, sizeof (buffer), "DELE %d\r\n", i);
617       ret = pop_query (pop_data, buffer, sizeof (buffer));
618     }
619
620     if (ret == PQ_NOT_CONNECTED) {
621       mx_close_mailbox (&ctx, NULL);
622       goto fail;
623     }
624     if (ret == PQ_ERR) {
625       mutt_error ("%s", pop_data->err_msg);
626       break;
627     }
628     if (ret == -3) { /* this is -3 when ret != 0, because it will keep the value from before *gna* */
629       mutt_error _("Error while writing mailbox!");
630
631       break;
632     }
633
634     mutt_message (_("%s [%d of %d messages read]"), msgbuf, i - last,
635                   msgs - last);
636   }
637
638   mx_close_mailbox (&ctx, NULL);
639
640   if (rset) {
641     /* make sure no messages get deleted */
642     strfcpy (buffer, "RSET\r\n", sizeof (buffer));
643     if (pop_query (pop_data, buffer, sizeof (buffer)) == PQ_NOT_CONNECTED)
644       goto fail;
645   }
646
647 finish:
648   /* exit gracefully */
649   strfcpy (buffer, "QUIT\r\n", sizeof (buffer));
650   if (pop_query (pop_data, buffer, sizeof (buffer)) == PQ_NOT_CONNECTED)
651     goto fail;
652   mutt_socket_close (conn);
653   p_delete(&pop_data);
654   return;
655
656 fail:
657   mutt_error _("Server closed connection!");
658   mutt_socket_close (conn);
659   p_delete(&pop_data);
660 }