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