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