sort out some prototypes, put them where they belong.
[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 <string.h>
15 #include <unistd.h>
16
17 #include <lib-lib/lib-lib.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 /* write line to file */
27 static int fetch_message (char *line, void *file)
28 {
29   FILE *f = (FILE *) file;
30
31   fputs (line, f);
32   if (fputc ('\n', f) == EOF)
33     return -1;
34
35   return 0;
36 }
37
38 /*
39  * Read header
40  * returns:
41  *  0 on success
42  * -1 - conection lost,
43  * -2 - invalid command or execution error,
44  * -3 - error writing to tempfile
45  */
46 static pop_query_status pop_read_header (POP_DATA * pop_data, HEADER * h)
47 {
48   FILE *f;
49   int idx;
50   pop_query_status ret;
51   long length;
52   char buf[LONG_STRING];
53   char tempfile[_POSIX_PATH_MAX];
54
55   mutt_mktemp (tempfile);
56   if (!(f = safe_fopen (tempfile, "w+"))) {
57     mutt_perror (tempfile);
58     return PFD_FUNCT_ERROR;
59   }
60
61   snprintf (buf, sizeof (buf), "string_list_t %d\r\n", h->refno);
62   ret = pop_query (pop_data, buf, sizeof (buf));
63   if (ret == PQ_OK) {
64     sscanf (buf, "+OK %d %ld", &idx, &length);
65
66     snprintf (buf, sizeof (buf), "TOP %d 0\r\n", h->refno);
67     ret = pop_fetch_data (pop_data, buf, NULL, fetch_message, f);
68
69     if (pop_data->cmd_top == CMD_UNKNOWN) {
70       if (ret == PQ_OK) {
71         pop_data->cmd_top = CMD_AVAILABLE;
72       }
73
74       if (ret == PQ_ERR) {
75         pop_data->cmd_top = CMD_NOT_AVAILABLE;
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   case PQ_NOT_CONNECTED:
107     {
108       mutt_error _("Can't fetch header: Not connected!");
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, idx;
122   CONTEXT *ctx = (CONTEXT *) data;
123   POP_DATA *pop_data = (POP_DATA *) ctx->data;
124
125   sscanf (line, "%d %s", &idx, line);
126   for (i = 0; i < ctx->msgcount; i++)
127     if (!m_strcmp(line, ctx->hdrs[i]->data))
128       break;
129
130   if (i == ctx->msgcount) {
131     if (i >= ctx->hdrmax)
132       mx_alloc_memory (ctx);
133
134     ctx->msgcount++;
135     ctx->hdrs[i] = header_new();
136     ctx->hdrs[i]->data = m_strdup(line);
137   }
138   else if (ctx->hdrs[i]->index != idx - 1)
139     pop_data->clear_cache = 1;
140
141   ctx->hdrs[i]->refno = idx;
142   ctx->hdrs[i]->index = idx - 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
177     if (ret == PQ_ERR && pop_data->cmd_uidl == CMD_UNKNOWN) {
178       pop_data->cmd_uidl = CMD_NOT_AVAILABLE;
179
180       snprintf (pop_data->err_msg, sizeof (pop_data->err_msg),
181                 _("Command UIDL is not supported by server."));
182     }
183   }
184
185   if (ret == PQ_OK) {
186     for (i = 0; i < old_count; i++)
187       if (ctx->hdrs[i]->refno == -1)
188         ctx->hdrs[i]->deleted = 1;
189
190     for (i = old_count; i < new_count; i++) {
191       mutt_message (_("Fetching message headers... [%d/%d]"),
192                     i + 1 - old_count, new_count - old_count);
193
194       ret = pop_read_header (pop_data, ctx->hdrs[i]);
195       if (ret != PQ_OK)
196         break;
197
198       ctx->msgcount++;
199     }
200
201     if (i > old_count)
202       mx_update_context (ctx, i - old_count);
203   }
204
205   if (ret != PQ_OK) {
206     for (i = ctx->msgcount; i < new_count; i++)
207       header_delete(&ctx->hdrs[i]);
208     return ret;
209   }
210
211   mutt_clear_error ();
212   return (new_count - old_count);
213 }
214
215 /* open POP mailbox - fetch only headers */
216 int pop_open_mailbox (CONTEXT * ctx)
217 {
218   int ret;
219   char buf[LONG_STRING];
220   CONNECTION *conn;
221   ACCOUNT act;
222   POP_DATA *pop_data;
223   ciss_url_t url;
224
225   if (pop_parse_path (ctx->path, &act)) {
226     mutt_error (_("%s is an invalid POP path"), ctx->path);
227     mutt_sleep (2);
228     return -1;
229   }
230
231   mutt_account_tourl (&act, &url);
232   url.path = NULL;
233   url_ciss_tostring (&url, buf, sizeof (buf), 0);
234   conn = mutt_conn_find (NULL, &act);
235   if (!conn)
236     return -1;
237
238   p_delete(&ctx->path);
239   ctx->path = m_strdup(buf);
240
241   pop_data = p_new(POP_DATA, 1);
242   pop_data->conn = conn;
243   ctx->data = pop_data;
244
245   if (pop_open_connection (pop_data) < 0)
246     return -1;
247
248   conn->data = pop_data;
249
250   for (;;) {
251     if (pop_reconnect (ctx) != PQ_OK)
252       return -1;
253
254     ctx->size = pop_data->size;
255
256     mutt_message _("Fetching list of messages...");
257
258     ret = pop_fetch_headers (ctx);
259
260     if (ret >= 0)
261       return 0;
262
263     if (ret < -1) {
264       mutt_sleep (2);
265       return -1;
266     }
267   }
268 }
269
270 /* delete all cached messages */
271 static void pop_clear_cache (POP_DATA * pop_data)
272 {
273   int i;
274
275   if (!pop_data->clear_cache)
276     return;
277
278   for (i = 0; i < POP_CACHE_LEN; i++) {
279     if (pop_data->cache[i].path) {
280       unlink (pop_data->cache[i].path);
281       p_delete(&pop_data->cache[i].path);
282     }
283   }
284 }
285
286 /* close POP mailbox */
287 void pop_close_mailbox (CONTEXT * ctx)
288 {
289   POP_DATA *pop_data = (POP_DATA *) ctx->data;
290
291   if (!pop_data)
292     return;
293
294   pop_logout (ctx);
295
296   if (pop_data->status != POP_NONE)
297     mutt_socket_close (pop_data->conn);
298
299   pop_data->status = POP_NONE;
300
301   pop_data->clear_cache = 1;
302   pop_clear_cache (pop_data);
303
304   if (!pop_data->conn->data)
305     mutt_socket_free (pop_data->conn);
306
307   return;
308 }
309
310 /* fetch message from POP server */
311 int pop_fetch_message (MESSAGE * msg, CONTEXT * ctx, int msgno)
312 {
313   int ret;
314   void *uidl;
315   char buf[LONG_STRING];
316   char path[_POSIX_PATH_MAX];
317   progress_t bar;
318   POP_DATA *pop_data = (POP_DATA *) ctx->data;
319   POP_CACHE *cache;
320   HEADER *h = ctx->hdrs[msgno];
321
322   /* see if we already have the message in our cache */
323   cache = &pop_data->cache[h->index % POP_CACHE_LEN];
324
325   if (cache->path) {
326     if (cache->index == h->index) {
327       /* yes, so just return a pointer to the message */
328       msg->fp = fopen (cache->path, "r");
329       if (msg->fp)
330         return 0;
331
332       mutt_perror (cache->path);
333       mutt_sleep (2);
334       return -1;
335     }
336     else {
337       /* clear the previous entry */
338       unlink (cache->path);
339       p_delete(&cache->path);
340     }
341   }
342
343   for (;;) {
344     if (pop_reconnect (ctx) != PQ_OK)
345       return -1;
346
347     /* verify that massage index is correct */
348     if (h->refno < 0) {
349       mutt_error
350         _("The message index is incorrect. Try reopening the mailbox.");
351       mutt_sleep (2);
352       return -1;
353     }
354
355     bar.size = h->content->length + h->content->offset - 1;
356     bar.msg = _("Fetching message...");
357     mutt_progress_bar (&bar, 0);
358
359     mutt_mktemp (path);
360     msg->fp = safe_fopen (path, "w+");
361     if (!msg->fp) {
362       mutt_perror (path);
363       mutt_sleep (2);
364       return -1;
365     }
366
367     snprintf (buf, sizeof (buf), "RETR %d\r\n", h->refno);
368
369     ret = pop_fetch_data (pop_data, buf, &bar, fetch_message, msg->fp);
370     if (ret == PQ_OK)
371       break;
372
373     safe_fclose (&msg->fp);
374     unlink (path);
375
376     if (ret == PQ_ERR) {
377       mutt_error ("%s", pop_data->err_msg);
378       mutt_sleep (2);
379       return -1;
380     }
381
382     if (ret == PFD_FUNCT_ERROR) {
383       mutt_error _("Can't write message to temporary file!");
384
385       mutt_sleep (2);
386       return -1;
387     }
388   }
389
390   /* Update the header information.  Previously, we only downloaded a
391    * portion of the headers, those required for the main display.
392    */
393   cache->index = h->index;
394   cache->path = m_strdup(path);
395   rewind (msg->fp);
396   uidl = h->data;
397   envelope_delete(&h->env);
398   h->env = mutt_read_rfc822_header (msg->fp, h, 0, 0);
399   h->data = uidl;
400   h->lines = 0;
401   fgets (buf, sizeof (buf), msg->fp);
402   while (!feof (msg->fp)) {
403     ctx->hdrs[msgno]->lines++;
404     fgets (buf, sizeof (buf), msg->fp);
405   }
406
407   h->content->length = ftello (msg->fp) - h->content->offset;
408
409   /* This needs to be done in case this is a multipart message */
410   h->security = crypt_query (h->content);
411
412   mutt_clear_error ();
413   rewind (msg->fp);
414
415   return 0;
416 }
417
418 /* update POP mailbox - delete messages from server */
419 pop_query_status pop_sync_mailbox (CONTEXT * ctx,
420                                    int unused __attribute__ ((unused)),
421                                    int *index_hint __attribute__ ((unused)))
422 {
423   int i;
424   pop_query_status ret;
425   char buf[LONG_STRING];
426   POP_DATA *pop_data = (POP_DATA *) ctx->data;
427
428   pop_data->check_time = 0;
429
430   for (;;) {
431     if (pop_reconnect (ctx) != PQ_OK)
432       return PQ_NOT_CONNECTED;
433
434     mutt_message (_("Marking %d messages deleted..."), ctx->deleted);
435
436     for (i = 0, ret = 0; ret == 0 && i < ctx->msgcount; i++) {
437       if (ctx->hdrs[i]->deleted) {
438         snprintf (buf, sizeof (buf), "DELE %d\r\n", ctx->hdrs[i]->refno);
439         ret = pop_query (pop_data, buf, sizeof (buf));
440       }
441     }
442
443     if (ret == PQ_OK) {
444       m_strcpy(buf, sizeof(buf), "QUIT\r\n");
445       ret = pop_query (pop_data, buf, sizeof (buf));
446     }
447
448     if (ret == PQ_OK) {
449       pop_data->clear_cache = 1;
450       pop_clear_cache (pop_data);
451       pop_data->status = POP_DISCONNECTED;
452       return PQ_OK;
453     }
454
455     if (ret == PQ_ERR) {
456       mutt_error ("%s", pop_data->err_msg);
457       mutt_sleep (2);
458       return PQ_NOT_CONNECTED;
459     }
460   }
461 }
462
463 /* Check for new messages and fetch headers */
464 int pop_check_mailbox (CONTEXT * ctx,
465                        int *index_hint __attribute__ ((unused)),
466                        int unused __attribute__ ((unused)))
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 act;
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 = p_new(char, strlen (PopHost) + 7);
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, &act);
525   p_delete(&url);
526   if (ret) {
527     mutt_error (_("%s is an invalid POP path"), PopHost);
528     return;
529   }
530
531   conn = mutt_conn_find (NULL, &act);
532   if (!conn)
533     return;
534
535   pop_data = p_new(POP_DATA, 1);
536   pop_data->conn = conn;
537
538   if (pop_open_connection (pop_data) < 0) {
539     mutt_socket_free (pop_data->conn);
540     p_delete(&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   m_strcpy(buffer, sizeof(buffer), "STAT\r\n");
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     m_strcpy(buffer, sizeof(buffer), "LAST\r\n");
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     m_strcpy(buffer, sizeof(buffer), "RSET\r\n");
632     if (pop_query (pop_data, buffer, sizeof (buffer)) == PQ_NOT_CONNECTED)
633       goto fail;
634   }
635
636 finish:
637   /* exit gracefully */
638   m_strcpy(buffer, sizeof(buffer), "QUIT\r\n");
639   if (pop_query (pop_data, buffer, sizeof (buffer)) == PQ_NOT_CONNECTED)
640     goto fail;
641   mutt_socket_close (conn);
642   p_delete(&pop_data);
643   return;
644
645 fail:
646   mutt_error _("Server closed connection!");
647   mutt_socket_close (conn);
648   p_delete(&pop_data);
649 }