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