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