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