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