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