remove most of the debug code: often makes the code unreadable, for little
[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/mem.h>
18 #include <lib-lib/file.h>
19 #include <lib-lib/str.h>
20 #include <lib-lib/macros.h>
21
22 #include <lib-ui/curses.h>
23
24 #include "mutt.h"
25 #include "mx.h"
26 #include "pop.h"
27 #include <lib-crypt/crypt.h>
28
29 /* write line to file */
30 static int fetch_message (char *line, void *file)
31 {
32   FILE *f = (FILE *) file;
33
34   fputs (line, f);
35   if (fputc ('\n', f) == EOF)
36     return -1;
37
38   return 0;
39 }
40
41 /*
42  * Read header
43  * returns:
44  *  0 on success
45  * -1 - conection lost,
46  * -2 - invalid command or execution error,
47  * -3 - error writing to tempfile
48  */
49 static pop_query_status pop_read_header (POP_DATA * pop_data, HEADER * h)
50 {
51   FILE *f;
52   int idx;
53   pop_query_status ret;
54   long length;
55   char buf[LONG_STRING];
56   char tempfile[_POSIX_PATH_MAX];
57
58   mutt_mktemp (tempfile);
59   if (!(f = safe_fopen (tempfile, "w+"))) {
60     mutt_perror (tempfile);
61     return PFD_FUNCT_ERROR;
62   }
63
64   snprintf (buf, sizeof (buf), "string_list_t %d\r\n", h->refno);
65   ret = pop_query (pop_data, buf, sizeof (buf));
66   if (ret == PQ_OK) {
67     sscanf (buf, "+OK %d %ld", &idx, &length);
68
69     snprintf (buf, sizeof (buf), "TOP %d 0\r\n", h->refno);
70     ret = pop_fetch_data (pop_data, buf, NULL, fetch_message, f);
71
72     if (pop_data->cmd_top == CMD_UNKNOWN) {
73       if (ret == PQ_OK) {
74         pop_data->cmd_top = CMD_AVAILABLE;
75       }
76
77       if (ret == PQ_ERR) {
78         pop_data->cmd_top = CMD_NOT_AVAILABLE;
79         snprintf (pop_data->err_msg, sizeof (pop_data->err_msg),
80                   _("Command TOP is not supported by server."));
81       }
82     }
83   }
84
85   switch (ret) {
86   case PQ_OK:
87     {
88       rewind (f);
89       h->env = mutt_read_rfc822_header (f, h, 0, 0);
90       h->content->length = length - h->content->offset + 1;
91       rewind (f);
92       while (!feof (f)) {
93         h->content->length--;
94         fgets (buf, sizeof (buf), f);
95       }
96       break;
97     }
98   case PQ_ERR:
99     {
100       mutt_error ("%s", pop_data->err_msg);
101       break;
102     }
103   case PFD_FUNCT_ERROR:
104     {
105       mutt_error _("Can't write header to temporary file!");
106
107       break;
108     }
109   case PQ_NOT_CONNECTED:
110     {
111       mutt_error _("Can't fetch header: Not connected!");
112       break;
113     }
114   }
115
116   fclose (f);
117   unlink (tempfile);
118   return ret;
119 }
120
121 /* parse UIDL */
122 static int fetch_uidl (char *line, void *data)
123 {
124   int i, idx;
125   CONTEXT *ctx = (CONTEXT *) data;
126   POP_DATA *pop_data = (POP_DATA *) ctx->data;
127
128   sscanf (line, "%d %s", &idx, line);
129   for (i = 0; i < ctx->msgcount; i++)
130     if (!m_strcmp(line, ctx->hdrs[i]->data))
131       break;
132
133   if (i == ctx->msgcount) {
134     if (i >= ctx->hdrmax)
135       mx_alloc_memory (ctx);
136
137     ctx->msgcount++;
138     ctx->hdrs[i] = header_new();
139     ctx->hdrs[i]->data = m_strdup(line);
140   }
141   else if (ctx->hdrs[i]->index != idx - 1)
142     pop_data->clear_cache = 1;
143
144   ctx->hdrs[i]->refno = idx;
145   ctx->hdrs[i]->index = idx - 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
180     if (ret == PQ_ERR && pop_data->cmd_uidl == CMD_UNKNOWN) {
181       pop_data->cmd_uidl = CMD_NOT_AVAILABLE;
182
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       header_delete(&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 act;
225   POP_DATA *pop_data;
226   ciss_url_t url;
227
228   if (pop_parse_path (ctx->path, &act)) {
229     mutt_error (_("%s is an invalid POP path"), ctx->path);
230     mutt_sleep (2);
231     return -1;
232   }
233
234   mutt_account_tourl (&act, &url);
235   url.path = NULL;
236   url_ciss_tostring (&url, buf, sizeof (buf), 0);
237   conn = mutt_conn_find (NULL, &act);
238   if (!conn)
239     return -1;
240
241   p_delete(&ctx->path);
242   ctx->path = m_strdup(buf);
243
244   pop_data = p_new(POP_DATA, 1);
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   for (;;) {
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   for (i = 0; i < POP_CACHE_LEN; i++) {
282     if (pop_data->cache[i].path) {
283       unlink (pop_data->cache[i].path);
284       p_delete(&pop_data->cache[i].path);
285     }
286   }
287 }
288
289 /* close POP mailbox */
290 void pop_close_mailbox (CONTEXT * ctx)
291 {
292   POP_DATA *pop_data = (POP_DATA *) ctx->data;
293
294   if (!pop_data)
295     return;
296
297   pop_logout (ctx);
298
299   if (pop_data->status != POP_NONE)
300     mutt_socket_close (pop_data->conn);
301
302   pop_data->status = POP_NONE;
303
304   pop_data->clear_cache = 1;
305   pop_clear_cache (pop_data);
306
307   if (!pop_data->conn->data)
308     mutt_socket_free (pop_data->conn);
309
310   return;
311 }
312
313 /* fetch message from POP server */
314 int pop_fetch_message (MESSAGE * msg, CONTEXT * ctx, int msgno)
315 {
316   int ret;
317   void *uidl;
318   char buf[LONG_STRING];
319   char path[_POSIX_PATH_MAX];
320   progress_t bar;
321   POP_DATA *pop_data = (POP_DATA *) ctx->data;
322   POP_CACHE *cache;
323   HEADER *h = ctx->hdrs[msgno];
324
325   /* see if we already have the message in our cache */
326   cache = &pop_data->cache[h->index % POP_CACHE_LEN];
327
328   if (cache->path) {
329     if (cache->index == h->index) {
330       /* yes, so just return a pointer to the message */
331       msg->fp = fopen (cache->path, "r");
332       if (msg->fp)
333         return 0;
334
335       mutt_perror (cache->path);
336       mutt_sleep (2);
337       return -1;
338     }
339     else {
340       /* clear the previous entry */
341       unlink (cache->path);
342       p_delete(&cache->path);
343     }
344   }
345
346   for (;;) {
347     if (pop_reconnect (ctx) != PQ_OK)
348       return -1;
349
350     /* verify that massage index is correct */
351     if (h->refno < 0) {
352       mutt_error
353         _("The message index is incorrect. Try reopening the mailbox.");
354       mutt_sleep (2);
355       return -1;
356     }
357
358     bar.size = h->content->length + h->content->offset - 1;
359     bar.msg = _("Fetching message...");
360     mutt_progress_bar (&bar, 0);
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, &bar, 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 = m_strdup(path);
398   rewind (msg->fp);
399   uidl = h->data;
400   envelope_delete(&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 = ftello (msg->fp) - h->content->offset;
411
412   /* This needs to be done in case this is a multipart message */
413   h->security = crypt_query (h->content);
414
415   mutt_clear_error ();
416   rewind (msg->fp);
417
418   return 0;
419 }
420
421 /* update POP mailbox - delete messages from server */
422 pop_query_status pop_sync_mailbox (CONTEXT * ctx,
423                                    int unused __attribute__ ((unused)),
424                                    int *index_hint __attribute__ ((unused)))
425 {
426   int i;
427   pop_query_status ret;
428   char buf[LONG_STRING];
429   POP_DATA *pop_data = (POP_DATA *) ctx->data;
430
431   pop_data->check_time = 0;
432
433   for (;;) {
434     if (pop_reconnect (ctx) != PQ_OK)
435       return PQ_NOT_CONNECTED;
436
437     mutt_message (_("Marking %d messages deleted..."), ctx->deleted);
438
439     for (i = 0, ret = 0; ret == 0 && i < ctx->msgcount; i++) {
440       if (ctx->hdrs[i]->deleted) {
441         snprintf (buf, sizeof (buf), "DELE %d\r\n", ctx->hdrs[i]->refno);
442         ret = pop_query (pop_data, buf, sizeof (buf));
443       }
444     }
445
446     if (ret == PQ_OK) {
447       m_strcpy(buf, sizeof(buf), "QUIT\r\n");
448       ret = pop_query (pop_data, buf, sizeof (buf));
449     }
450
451     if (ret == PQ_OK) {
452       pop_data->clear_cache = 1;
453       pop_clear_cache (pop_data);
454       pop_data->status = POP_DISCONNECTED;
455       return PQ_OK;
456     }
457
458     if (ret == PQ_ERR) {
459       mutt_error ("%s", pop_data->err_msg);
460       mutt_sleep (2);
461       return PQ_NOT_CONNECTED;
462     }
463   }
464 }
465
466 /* Check for new messages and fetch headers */
467 int pop_check_mailbox (CONTEXT * ctx,
468                        int *index_hint __attribute__ ((unused)),
469                        int unused __attribute__ ((unused)))
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 act;
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 = p_new(char, strlen (PopHost) + 7);
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, &act);
528   p_delete(&url);
529   if (ret) {
530     mutt_error (_("%s is an invalid POP path"), PopHost);
531     return;
532   }
533
534   conn = mutt_conn_find (NULL, &act);
535   if (!conn)
536     return;
537
538   pop_data = p_new(POP_DATA, 1);
539   pop_data->conn = conn;
540
541   if (pop_open_connection (pop_data) < 0) {
542     mutt_socket_free (pop_data->conn);
543     p_delete(&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   m_strcpy(buffer, sizeof(buffer), "STAT\r\n");
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     m_strcpy(buffer, sizeof(buffer), "LAST\r\n");
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     m_strcpy(buffer, sizeof(buffer), "RSET\r\n");
635     if (pop_query (pop_data, buffer, sizeof (buffer)) == PQ_NOT_CONNECTED)
636       goto fail;
637   }
638
639 finish:
640   /* exit gracefully */
641   m_strcpy(buffer, sizeof(buffer), "QUIT\r\n");
642   if (pop_query (pop_data, buffer, sizeof (buffer)) == PQ_NOT_CONNECTED)
643     goto fail;
644   mutt_socket_close (conn);
645   p_delete(&pop_data);
646   return;
647
648 fail:
649   mutt_error _("Server closed connection!");
650   mutt_socket_close (conn);
651   p_delete(&pop_data);
652 }