I don't understand how I missed that before...
[apps/madmutt.git] / 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 #include <lib-lib/lib-lib.h>
11
12 #include <sasl/sasl.h>
13 #include <sasl/saslutil.h>
14
15 #include <lib-sys/mutt_socket.h>
16 #include <lib-ui/curses.h>
17
18 #include "crypt.h"
19 #include "mutt.h"
20 #include "mutt_sasl.h"
21 #include "pop.h"
22
23 #define POP_PORT            110
24 #define POP_SSL_PORT        995
25 #define POP_CACHE_LEN        10
26 /* maximal length of the server response (RFC1939) */
27 #define POP_CMD_RESPONSE    512
28
29 enum {
30     /* Status */
31     POP_NONE = 0,
32     POP_CONNECTED,
33     POP_DISCONNECTED,
34     POP_BYE
35 };
36
37 typedef enum {
38     POP_A_SUCCESS = 0,
39     POP_A_SOCKET,
40     POP_A_FAILURE,
41     POP_A_UNAVAIL
42 } pop_auth_res_t;
43
44 typedef struct {
45   int index;
46   char *path;
47 } POP_CACHE;
48
49 typedef enum {
50     /* pop_fetch_data uses pop_query_status and this return value */
51     PFD_FUNCT_ERROR = -3,
52     PQ_ERR = -2,
53     PQ_NOT_CONNECTED = -1,
54     PQ_OK = 0
55 } pop_query_status;
56
57 typedef enum {
58     CMD_NOT_AVAILABLE = 0,
59     CMD_AVAILABLE,
60     CMD_UNKNOWN /* unknown whether it is available or not */
61 } cmd_status;
62
63 typedef struct {
64     CONNECTION *conn;
65
66     unsigned status       : 2;
67     unsigned capabilities : 1;
68     unsigned use_stls     : 2;
69     cmd_status cmd_capa   : 2;      /* optional command CAPA */
70     cmd_status cmd_stls   : 2;      /* optional command STLS */
71     cmd_status cmd_uidl   : 2;      /* optional command UIDL */
72     cmd_status cmd_top    : 2;      /* optional command TOP  */
73     cmd_status cmd_user   : 2;      /* optional command USER */
74     unsigned resp_codes   : 1;      /* server supports extended response codes */
75     unsigned expire       : 1;      /* expire is greater than 0 */
76     unsigned clear_cache  : 1;
77
78     ssize_t size;
79     time_t check_time;
80     char *auth_list;              /* list of auth mechanisms */
81     char *timestamp;
82     char err_msg[POP_CMD_RESPONSE];
83     POP_CACHE cache[POP_CACHE_LEN];
84 } pop_data_t;
85
86 /* pop low level functions {{{ */
87
88 static void pop_error(pop_data_t *pop_data, const char *msg)
89 {
90     if (!m_strncmp(msg, "-ERR ", 5)) {
91         const char *s = skipspaces(msg + 5);
92         if (*s)
93             msg = s;
94     }
95
96     m_strcat(pop_data->err_msg, sizeof(pop_data->err_msg), msg);
97     m_strrtrim(pop_data->err_msg);
98 }
99
100 /*
101  * Send data from buffer and receive answer to the same buffer
102  *  0 - successful,
103  * -1 - conection lost,
104  * -2 - invalid command or execution error.
105 */
106 static pop_query_status _pop_query(pop_data_t *pop_data, char *buf, ssize_t buflen)
107 {
108     if (pop_data->status != POP_CONNECTED)
109         return PQ_NOT_CONNECTED;
110
111     mutt_socket_write(pop_data->conn, buf);
112     snprintf(pop_data->err_msg, sizeof(pop_data->err_msg), "%.*s: ",
113              (int)(strpbrk(buf, " \r\n") - buf), buf);
114
115     if (mutt_socket_readln(buf, buflen, pop_data->conn) < 0) {
116         pop_data->status = POP_DISCONNECTED;
117         return PQ_NOT_CONNECTED;
118     }
119     if (!m_strncmp(buf, "+OK", 3))
120         return PQ_OK;
121
122     pop_error(pop_data, buf);
123     return PQ_ERR;
124 }
125 #define pop_query(pd, b, l, fmt, ...) \
126     (snprintf(b, l, fmt "\r\n", ##__VA_ARGS__), _pop_query(pd, b, l))
127
128 /*
129  * Open connection
130  *  0 - successful,
131  * -1 - conection lost,
132  * -2 - invalid response.
133 */
134 static pop_query_status pop_connect(pop_data_t * pop_data)
135 {
136     char buf[LONG_STRING];
137     const char *p, *q;
138
139     if (mutt_socket_open(pop_data->conn) < 0
140     ||  mutt_socket_readln(buf, sizeof(buf), pop_data->conn) < 0)
141     {
142         mutt_error(_("Error connecting to server: %s"),
143                    pop_data->conn->account.host);
144         pop_data->status = POP_NONE;
145         return PQ_NOT_CONNECTED;
146     }
147
148     pop_data->status = POP_CONNECTED;
149     if (m_strncmp(buf, "+OK", 3)) {
150         pop_data->err_msg[0] = '\0';
151         pop_error(pop_data, buf);
152         mutt_error("%s", pop_data->err_msg);
153         return PQ_ERR;
154     }
155
156     p_delete(&pop_data->timestamp);
157     if ((p = strchr(buf, '<')) && (q = strchr(p, '>'))) {
158         pop_data->timestamp = p_dupstr(p, q + 1 - p);
159     }
160     return PQ_OK;
161 }
162
163 static void pop_logout (CONTEXT * ctx)
164 {
165   pop_query_status ret = 0;
166   char buf[LONG_STRING];
167   pop_data_t *pop_data = (pop_data_t *) ctx->data;
168
169   if (pop_data->status == POP_CONNECTED) {
170     mutt_message _("Closing connection to POP server...");
171
172     if (ctx->readonly) {
173       ret = pop_query(pop_data, buf, sizeof(buf), "RSET");
174     }
175
176     if (ret != PQ_NOT_CONNECTED) {
177       pop_query(pop_data, buf, sizeof(buf), "QUIT");
178     }
179
180     mutt_clear_error ();
181   }
182
183   pop_data->status = POP_DISCONNECTED;
184   return;
185 }
186
187 /* }}} */
188 /* Authentication {{{ */
189
190 static pop_auth_res_t pop_auth_sasl(pop_data_t *pop_data, const char *method)
191 {
192     sasl_conn_t *saslconn;
193     sasl_interact_t *interaction = NULL;
194
195     char buf[LONG_STRING], inbuf[LONG_STRING];
196     const char *mech, *pc = NULL;
197     unsigned int len, olen;
198     unsigned char client_start;
199     int rc;
200
201     if (mutt_sasl_client_new(pop_data->conn, &saslconn) < 0) {
202         return POP_A_FAILURE;
203     }
204
205     if (!method)
206         method = pop_data->auth_list;
207
208     for (;;) {
209         rc = sasl_client_start(saslconn, method, &interaction, &pc, &olen,
210                                &mech);
211         if (rc != SASL_INTERACT)
212             break;
213         mutt_sasl_interact(interaction);
214     }
215
216     if (rc != SASL_OK && rc != SASL_CONTINUE) {
217         return POP_A_UNAVAIL;
218     }
219
220     client_start = (olen > 0);
221     mutt_message(_("Authenticating (SASL)..."));
222     snprintf(buf, sizeof (buf), "AUTH %s", mech);
223     olen = strlen (buf);
224
225     /* looping protocol */
226     for (;;) {
227         m_strcpy(buf + olen, sizeof(buf) - olen, "\r\n");
228         mutt_socket_write(pop_data->conn, buf);
229         if (mutt_socket_readln(inbuf, sizeof(inbuf), pop_data->conn) < 0) {
230             sasl_dispose(&saslconn);
231             pop_data->status = POP_DISCONNECTED;
232             return POP_A_SOCKET;
233         }
234
235         if (rc != SASL_CONTINUE)
236             break;
237
238         if (!m_strncmp(inbuf, "+ ", 2)
239         &&   sasl_decode64(inbuf, strlen(inbuf),
240                            buf, sizeof(buf) - 1, &len) != SASL_OK)
241         {
242             goto bail;
243         }
244
245         if (!client_start) {
246             for (;;) {
247                 rc = sasl_client_step(saslconn, buf, len, &interaction, &pc,
248                                       &olen);
249                 if (rc != SASL_INTERACT)
250                     break;
251                 mutt_sasl_interact(interaction);
252             }
253         } else {
254             client_start = 0;
255         }
256
257         if (rc != SASL_CONTINUE && (olen == 0 || rc != SASL_OK))
258             break;
259
260         /* send out response, or line break if none needed */
261         if (pc) {
262             if (sasl_encode64(pc, olen, buf, sizeof(buf), &olen) != SASL_OK) {
263                 goto bail;
264             }
265             p_delete((char **)&pc);
266         }
267     }
268
269     if (rc != SASL_OK)
270         goto bail;
271
272     if (!m_strncmp(inbuf, "+OK", 3)) {
273         mutt_sasl_setup_conn(pop_data->conn, saslconn);
274         return POP_A_SUCCESS;
275     }
276
277   bail:
278     sasl_dispose(&saslconn);
279     p_delete((char **)&pc);
280
281     /* terminate SASL session if the last responce is not +OK nor -ERR */
282     if (!m_strncmp(inbuf, "+ ", 2)) {
283         if (pop_query(pop_data, buf, sizeof(buf), "*") == PQ_NOT_CONNECTED)
284             return POP_A_SOCKET;
285     }
286
287     mutt_error(_("SASL authentication failed."));
288     mutt_sleep(2);
289
290     return POP_A_FAILURE;
291 }
292
293 static pop_auth_res_t pop_auth_apop(pop_data_t *pop_data, const char *method)
294 {
295     MD5_CTX mdContext;
296     unsigned char digest[16];
297     char hash[33];
298     char buf[LONG_STRING];
299     int i;
300
301     if (!pop_data->timestamp)
302         return POP_A_UNAVAIL;
303
304     mutt_message _("Authenticating (APOP)...");
305
306     /* Compute the authentication hash to send to the server */
307     MD5Init(&mdContext);
308     MD5Update(&mdContext, (unsigned char *)pop_data->timestamp,
309               strlen(pop_data->timestamp));
310     MD5Update(&mdContext, (unsigned char *)pop_data->conn->account.pass,
311               strlen(pop_data->conn->account.pass));
312     MD5Final(digest, &mdContext);
313
314     for (i = 0; i < countof(digest); i++)
315         sprintf(hash + 2 * i, "%02x", digest[i]);
316
317     switch (pop_query(pop_data, buf, sizeof(buf), "APOP %s %s",
318                       pop_data->conn->account.user, hash))
319     {
320       case PQ_OK:
321         return POP_A_SUCCESS;
322       case PQ_NOT_CONNECTED:
323         return POP_A_SOCKET;
324       default:
325         mutt_error("%s %s", _("APOP authentication failed."), pop_data->err_msg);
326         mutt_sleep(2);
327         return POP_A_FAILURE;
328     }
329 }
330
331 static pop_auth_res_t pop_auth_user(pop_data_t *pop_data, const char *method)
332 {
333     char buf[LONG_STRING];
334     pop_query_status ret;
335
336     if (pop_data->cmd_user == CMD_NOT_AVAILABLE)
337         return POP_A_UNAVAIL;
338
339     mutt_message _("Authenticating (USER)...");
340     ret = pop_query(pop_data, buf, sizeof(buf), "USER %s",
341                     pop_data->conn->account.user);
342
343     if (pop_data->cmd_user == CMD_UNKNOWN) {
344         if (ret == PQ_OK)
345             pop_data->cmd_user = CMD_AVAILABLE;
346         if (ret == PQ_ERR)
347             pop_data->cmd_user = CMD_NOT_AVAILABLE;
348     }
349
350     if (ret == PQ_OK) {
351         ret = pop_query(pop_data, buf, sizeof(buf), "PASS %s",
352                         pop_data->conn->account.pass);
353     }
354
355     switch (ret) {
356       case PQ_OK:
357         return POP_A_SUCCESS;
358       case PQ_NOT_CONNECTED:
359         return POP_A_SOCKET;
360       default:
361         mutt_error("%s %s", _("USER authentication failed."), pop_data->err_msg);
362         mutt_sleep(2);
363         return POP_A_FAILURE;
364     }
365 }
366
367 typedef struct {
368     pop_auth_res_t (*do_auth)(pop_data_t *, const char *);
369     const char *method;
370 } pop_auth_t;
371
372 static pop_query_status pop_authenticate (pop_data_t * pop_data)
373 {
374     static pop_auth_t const pop_authenticators[] = {
375         {pop_auth_sasl, NULL},
376         {pop_auth_apop, "apop"},
377         {pop_auth_user, "user"},
378         {NULL, NULL}
379     };
380
381     ACCOUNT *act = &pop_data->conn->account;
382     const pop_auth_t *auth;
383     int attempts = 0;
384
385     if (mutt_account_getuser(act) || !act->user[0]
386     ||  mutt_account_getpass(act) || !act->pass[0])
387     {
388         return PFD_FUNCT_ERROR;
389     }
390
391     if (!m_strisempty(PopAuthenticators)) {
392         const char *p, *q;
393         char buf[STRING];
394
395         for (p = PopAuthenticators; ; p = q) {
396             while (*p == ':')
397                 p++;
398             if (!*p)
399                 break;
400
401             q = strchrnul(p, ':');
402             m_strncpy(buf, sizeof(buf), p, q - p);
403
404             for (auth = pop_authenticators; auth->do_auth; auth++) {
405                 if (auth->method && ascii_strcasecmp(auth->method, buf))
406                     continue;
407
408                 switch (auth->do_auth(pop_data, buf)) {
409                   case POP_A_SUCCESS:
410                     return PQ_OK;
411                   case POP_A_SOCKET:
412                     return PQ_NOT_CONNECTED;
413                   case POP_A_UNAVAIL:
414                     break;
415                   case POP_A_FAILURE:
416                     attempts++;
417                     break;
418                 }
419             }
420         }
421     } else {
422         for (auth = pop_authenticators; auth->do_auth; auth++) {
423             switch (auth->do_auth(pop_data, auth->method)) {
424               case POP_A_SUCCESS:
425                 return PQ_OK;
426               case POP_A_SOCKET:
427                 return PQ_NOT_CONNECTED;
428               case POP_A_UNAVAIL:
429                 break;
430               case POP_A_FAILURE:
431                 attempts++;
432                 break;
433             }
434         }
435     }
436
437     if (!attempts)
438         mutt_error(_("No authenticators available"));
439     return PQ_ERR;
440 }
441
442 /* }}} */
443
444 /*
445  * This function calls  funct(*line, *data)  for each received line,
446  * funct(NULL, *data)  if  rewind(*data)  needs, exits when fail or done.
447  * Returned codes:
448  *  0 - successful,
449  * -1 - conection lost,
450  * -2 - invalid command or execution error,
451  * -3 - error in funct(*line, *data)
452  */
453 static pop_query_status
454 pop_fetch_data(pop_data_t *pop_data, const char *query, progress_t *bar,
455                int (*funct)(char *, void *), void *data)
456 {
457     pop_query_status ret;
458     char buf[LONG_STRING];
459     buffer_t inbuf;
460     ssize_t pos = 0;
461
462     buffer_init(&inbuf);
463
464     m_strcpy(buf, sizeof(buf), query);
465     ret = _pop_query(pop_data, buf, sizeof(buf));
466     if (ret != PQ_OK)
467         return ret;
468
469     for (;;) {
470         int dot = 0;
471
472         if (mutt_socket_readln2(&inbuf, pop_data->conn) < 0) {
473             pop_data->status = POP_DISCONNECTED;
474             ret = PQ_NOT_CONNECTED;
475             break;
476         }
477
478         if (bar) {
479             mutt_progress_bar(bar, pos += inbuf.len);
480         }
481
482         if (inbuf.data[0] == '.') {
483             if (inbuf.data[1] != '.')
484                 break;
485             dot = 1;
486         }
487
488         if (funct(inbuf.data + dot, data) < 0) {
489             buffer_wipe(&inbuf);
490             ret = PFD_FUNCT_ERROR;
491             break;
492         }
493
494         buffer_reset(&inbuf);
495     }
496
497     buffer_wipe(&inbuf);
498     return ret;
499 }
500
501 static int fetch_capa (char *line, void *data)
502 {
503   pop_data_t *pop_data = (pop_data_t *) data;
504   char *c;
505
506   if (!ascii_strncasecmp (line, "SASL", 4)) {
507     p_delete(&pop_data->auth_list);
508     c = vskipspaces(line + 4);
509     pop_data->auth_list = m_strdup(c);
510   }
511
512   else if (!ascii_strncasecmp (line, "STLS", 4))
513     pop_data->cmd_stls = CMD_AVAILABLE;
514
515   else if (!ascii_strncasecmp (line, "UIDL", 4))
516     pop_data->cmd_uidl = CMD_AVAILABLE;
517
518   else if (!ascii_strncasecmp (line, "TOP", 3))
519     pop_data->cmd_top = CMD_AVAILABLE;
520
521   return 0;
522 }
523
524 static int fetch_auth (char *line, void *data)
525 {
526   pop_data_t *pop_data = (pop_data_t *) data;
527   ssize_t auth_list_len;
528
529   if (!pop_data->auth_list) {
530     auth_list_len = m_strlen(line) + 1;
531     pop_data->auth_list = p_new(char, auth_list_len);
532   } else {
533     auth_list_len = m_strlen(pop_data->auth_list) + m_strlen(line) + 2;
534     p_realloc(&pop_data->auth_list, auth_list_len);
535     m_strcat(pop_data->auth_list, auth_list_len, " ");
536   }
537   m_strcat(pop_data->auth_list, auth_list_len, line);
538
539   return 0;
540 }
541
542 /*
543  * Get capabilities
544  *  0 - successful,
545  * -1 - conection lost,
546  * -2 - execution error.
547 */
548 static pop_query_status pop_capabilities(pop_data_t * pop_data, int mode)
549 {
550   /* don't check capabilities on reconnect */
551   if (pop_data->capabilities)
552     return 0;
553
554   /* init capabilities */
555   if (mode == 0) {
556     pop_data->cmd_capa   = CMD_NOT_AVAILABLE;
557     pop_data->cmd_stls   = CMD_NOT_AVAILABLE;
558     pop_data->cmd_uidl   = CMD_NOT_AVAILABLE;
559     pop_data->cmd_top    = CMD_NOT_AVAILABLE;
560     pop_data->cmd_user   = CMD_NOT_AVAILABLE;
561     pop_data->resp_codes = 0;
562     pop_data->expire     = 1;
563     p_delete(&pop_data->auth_list);
564   }
565
566   /* Execute CAPA command */
567   if (mode == 0 || pop_data->cmd_capa != CMD_NOT_AVAILABLE) {
568     switch (pop_fetch_data(pop_data, "CAPA\r\n", NULL, fetch_capa, pop_data)) {
569     case PQ_OK:
570       pop_data->cmd_capa = CMD_AVAILABLE;
571       break;
572     case PFD_FUNCT_ERROR:
573     case PQ_ERR:
574       pop_data->cmd_capa = CMD_NOT_AVAILABLE;
575       break;
576     case PQ_NOT_CONNECTED:
577       return PQ_NOT_CONNECTED;
578     }
579   }
580
581   /* CAPA not supported, use defaults */
582   if (mode == 0 && pop_data->cmd_capa == CMD_NOT_AVAILABLE) {
583     pop_data->cmd_uidl = CMD_UNKNOWN;
584     pop_data->cmd_top = CMD_UNKNOWN;
585
586     if (pop_fetch_data(pop_data, "AUTH\r\n", NULL, fetch_auth, pop_data) ==
587         PQ_NOT_CONNECTED)
588       return PQ_NOT_CONNECTED;
589   }
590
591   /* Check capabilities */
592   if (mode == 2) {
593     char *msg = NULL;
594
595     if (!pop_data->expire)
596       msg = _("Unable to leave messages on server.");
597     if (pop_data->cmd_top == CMD_NOT_AVAILABLE)
598       msg = _("Command TOP is not supported by server.");
599     if (pop_data->cmd_uidl == CMD_NOT_AVAILABLE)
600       msg = _("Command UIDL is not supported by server.");
601     if (msg && pop_data->cmd_capa != CMD_AVAILABLE) {
602       mutt_error (msg);
603       return PQ_ERR;
604     }
605     pop_data->capabilities = 1;
606   }
607
608   return PQ_OK;
609 }
610
611 /* given an POP mailbox name, return host, port, username and password */
612 static int pop_parse_path (const char *path, ACCOUNT * act)
613 {
614   ciss_url_t url;
615   char *c;
616   int ret = -1;
617
618   /* Defaults */
619   act->flags = 0;
620   act->port = POP_PORT;
621   act->type = M_ACCT_TYPE_POP;
622
623   c = m_strdup(path);
624   url_parse_ciss (&url, c);
625
626   if (url.scheme == U_POP || url.scheme == U_POPS) {
627     if (url.scheme == U_POPS) {
628       act->flags |= M_ACCT_SSL;
629       act->port = POP_SSL_PORT;
630     }
631
632     if ((!url.path || !*url.path) && mutt_account_fromurl (act, &url) == 0)
633       ret = 0;
634   }
635
636   p_delete(&c);
637   return ret;
638 }
639
640 /*
641  * Open connection and authenticate
642  *  0 - successful,
643  * -1 - conection lost,
644  * -2 - invalid command or execution error,
645  * -3 - authentication canceled.
646 */
647 static pop_query_status pop_open_connection (pop_data_t * pop_data)
648 {
649   pop_query_status ret;
650   int n, size;
651   char buf[LONG_STRING];
652
653   ret = pop_connect(pop_data);
654   if (ret != PQ_OK) {
655     mutt_sleep (2);
656     return ret;
657   }
658
659   ret = pop_capabilities (pop_data, 0);
660   if (ret == PQ_NOT_CONNECTED)
661     goto err_conn;
662   if (ret == PQ_ERR) {
663     mutt_sleep (2);
664     return PQ_ERR;
665   }
666
667   /* Attempt STLS if available and desired. */
668   if (!pop_data->conn->ssf && (pop_data->cmd_stls || mod_ssl.force_tls)) {
669     if (mod_ssl.force_tls)
670       pop_data->use_stls = 2;
671     if (pop_data->use_stls == 0) {
672       pop_data->use_stls = 1;
673       if (mod_ssl.starttls)
674         pop_data->use_stls = 2;
675     }
676     if (pop_data->use_stls == 2) {
677       ret = pop_query(pop_data, buf, sizeof(buf), "STLS");
678       if (ret == PQ_NOT_CONNECTED)
679         goto err_conn;
680       if (ret != PQ_OK) {
681         mutt_error ("%s", pop_data->err_msg);
682         mutt_sleep (2);
683       }
684       else if (mutt_ssl_starttls (pop_data->conn))
685       {
686         mutt_error (_("Could not negotiate TLS connection"));
687         mutt_sleep (2);
688         return PQ_ERR;
689       }
690       else {
691         /* recheck capabilities after STLS completes */
692         ret = pop_capabilities (pop_data, 1);
693         if (ret == PQ_NOT_CONNECTED)
694           goto err_conn;
695         if (ret == PQ_ERR) {
696           mutt_sleep (2);
697           return PQ_ERR;
698         }
699       }
700     }
701   }
702
703   if (mod_ssl.force_tls && !pop_data->conn->ssf) {
704     mutt_error _("Encrypted connection unavailable");
705     mutt_sleep (1);
706     return -2;
707   }
708
709   ret = pop_authenticate (pop_data);
710   if (ret == PQ_NOT_CONNECTED)
711     goto err_conn;
712   if (ret == PFD_FUNCT_ERROR)
713     mutt_clear_error ();
714   if (ret != PQ_OK)
715     return ret;
716
717   /* recheck capabilities after authentication */
718   ret = pop_capabilities (pop_data, 2);
719   if (ret == PQ_NOT_CONNECTED)
720     goto err_conn;
721   if (ret == PQ_ERR) {
722     mutt_sleep (2);
723     return PQ_ERR;
724   }
725
726   /* get total size of mailbox */
727   ret = pop_query(pop_data, buf, sizeof(buf), "STAT");
728   if (ret == PQ_NOT_CONNECTED)
729     goto err_conn;
730   if (ret == PQ_ERR) {
731     mutt_error ("%s", pop_data->err_msg);
732     mutt_sleep (2);
733     return ret;
734   }
735
736   sscanf (buf, "+OK %u %u", &n, &size);
737   pop_data->size = size;
738   return PQ_OK;
739
740 err_conn:
741   pop_data->status = POP_DISCONNECTED;
742   mutt_error _("Server closed connection!");
743
744   mutt_sleep (2);
745   return PQ_NOT_CONNECTED;
746 }
747
748 /* find message with this UIDL and set refno */
749 static int check_uidl (char *line, void *data)
750 {
751   int i, idx;
752   CONTEXT *ctx = (CONTEXT *)data;
753
754   sscanf (line, "%u %s", &idx, line);
755   for (i = 0; i < ctx->msgcount; i++) {
756     if (!m_strcmp(ctx->hdrs[i]->data, line)) {
757       ctx->hdrs[i]->refno = idx;
758       break;
759     }
760   }
761
762   return 0;
763 }
764
765 /* reconnect and verify indexes if connection was lost */
766 static pop_query_status pop_reconnect (CONTEXT * ctx)
767 {
768   pop_query_status ret;
769   pop_data_t *pop_data = (pop_data_t *) ctx->data;
770   progress_t bar;
771
772   if (pop_data->status == POP_CONNECTED)
773     return PQ_OK;
774   if (pop_data->status == POP_BYE)
775     return PQ_NOT_CONNECTED;
776
777   for (;;) {
778     mutt_socket_close (pop_data->conn);
779
780     ret = pop_open_connection(pop_data);
781     if (ret == PQ_OK) {
782       int i;
783
784       bar.msg = _("Verifying message indexes...");
785       bar.size = 0;
786       mutt_progress_bar (&bar, 0);
787
788       for (i = 0; i < ctx->msgcount; i++)
789         ctx->hdrs[i]->refno = -1;
790
791       ret = pop_fetch_data(pop_data, "UIDL\r\n", &bar, check_uidl, ctx);
792       if (ret == PQ_ERR) {
793         mutt_error ("%s", pop_data->err_msg);
794         mutt_sleep (2);
795       }
796     }
797     if (ret == PQ_OK)
798       return PQ_OK;
799
800     pop_logout (ctx);
801
802     if (ret == PQ_ERR)
803       return PQ_NOT_CONNECTED;
804
805     if (query_quadoption (OPT_POPRECONNECT,
806                           _("Connection lost. Reconnect to POP server?")) !=
807         M_YES)
808       return PQ_NOT_CONNECTED;
809   }
810 }
811
812 /* write line to file */
813 static int fetch_message (char *line, void *file)
814 {
815   FILE *f = (FILE *) file;
816
817   fputs (line, f);
818   if (fputc ('\n', f) == EOF)
819     return -1;
820
821   return 0;
822 }
823
824 /*
825  * Read header
826  * returns:
827  *  0 on success
828  * -1 - conection lost,
829  * -2 - invalid command or execution error,
830  * -3 - error writing to tempfile
831  */
832 static pop_query_status pop_read_header (pop_data_t * pop_data, HEADER * h)
833 {
834   FILE *f;
835   int idx;
836   pop_query_status ret;
837   long length;
838   char buf[LONG_STRING];
839
840   f = tmpfile();
841   if (!f) {
842     mutt_error(_("Could not create temporary file"));
843     return PFD_FUNCT_ERROR;
844   }
845
846   ret = pop_query(pop_data, buf, sizeof(buf), "LIST %d", h->refno);
847   if (ret == PQ_OK) {
848     sscanf (buf, "+OK %d %ld", &idx, &length);
849
850     snprintf (buf, sizeof (buf), "TOP %d 0\r\n", h->refno);
851     ret = pop_fetch_data(pop_data, buf, NULL, fetch_message, f);
852
853     if (pop_data->cmd_top == CMD_UNKNOWN) {
854       if (ret == PQ_OK) {
855         pop_data->cmd_top = CMD_AVAILABLE;
856       }
857
858       if (ret == PQ_ERR) {
859         pop_data->cmd_top = CMD_NOT_AVAILABLE;
860         snprintf (pop_data->err_msg, sizeof (pop_data->err_msg),
861                   _("Command TOP is not supported by server."));
862       }
863     }
864   }
865
866   switch (ret) {
867   case PQ_OK:
868     {
869       rewind (f);
870       h->env = mutt_read_rfc822_header (f, h, 0, 0);
871       h->content->length = length - h->content->offset + 1;
872       rewind (f);
873       while (!feof (f)) {
874         h->content->length--;
875         fgets (buf, sizeof (buf), f);
876       }
877       break;
878     }
879   case PQ_ERR:
880     {
881       mutt_error ("%s", pop_data->err_msg);
882       break;
883     }
884   case PFD_FUNCT_ERROR:
885     {
886       mutt_error _("Can't write header to temporary file!");
887
888       break;
889     }
890   case PQ_NOT_CONNECTED:
891     {
892       mutt_error _("Can't fetch header: Not connected!");
893       break;
894     }
895   }
896
897   m_fclose(&f);
898   return ret;
899 }
900
901 /* parse UIDL */
902 static int fetch_uidl (char *line, void *data)
903 {
904   int i, idx;
905   CONTEXT *ctx = (CONTEXT *) data;
906   pop_data_t *pop_data = (pop_data_t *) ctx->data;
907
908   sscanf (line, "%d %s", &idx, line);
909   for (i = 0; i < ctx->msgcount; i++)
910     if (!m_strcmp(line, ctx->hdrs[i]->data))
911       break;
912
913   if (i == ctx->msgcount) {
914     if (i >= ctx->hdrmax)
915       mx_alloc_memory (ctx);
916
917     ctx->msgcount++;
918     ctx->hdrs[i] = header_new();
919     ctx->hdrs[i]->data = m_strdup(line);
920   }
921   else if (ctx->hdrs[i]->index != idx - 1)
922     pop_data->clear_cache = 1;
923
924   ctx->hdrs[i]->refno = idx;
925   ctx->hdrs[i]->index = idx - 1;
926
927   return 0;
928 }
929
930 /*
931  * Read headers
932  * returns:
933  *  0 on success
934  * -1 - conection lost,
935  * -2 - invalid command or execution error,
936  * -3 - error writing to tempfile
937  */
938 static int pop_fetch_headers (CONTEXT * ctx)
939 {
940   int i, old_count, new_count;
941   pop_query_status ret;
942   pop_data_t *pop_data = (pop_data_t *) ctx->data;
943
944   time (&pop_data->check_time);
945   pop_data->clear_cache = 0;
946
947   for (i = 0; i < ctx->msgcount; i++)
948     ctx->hdrs[i]->refno = -1;
949
950   old_count = ctx->msgcount;
951   ret = pop_fetch_data(pop_data, "UIDL\r\n", NULL, fetch_uidl, ctx);
952   new_count = ctx->msgcount;
953   ctx->msgcount = old_count;
954
955   if (pop_data->cmd_uidl == CMD_UNKNOWN) {
956     if (ret == PQ_OK) {
957       pop_data->cmd_uidl = CMD_AVAILABLE;
958     }
959
960     if (ret == PQ_ERR && pop_data->cmd_uidl == CMD_UNKNOWN) {
961       pop_data->cmd_uidl = CMD_NOT_AVAILABLE;
962
963       snprintf (pop_data->err_msg, sizeof (pop_data->err_msg),
964                 _("Command UIDL is not supported by server."));
965     }
966   }
967
968   if (ret == PQ_OK) {
969     for (i = 0; i < old_count; i++)
970       if (ctx->hdrs[i]->refno == -1)
971         ctx->hdrs[i]->deleted = 1;
972
973     for (i = old_count; i < new_count; i++) {
974       mutt_message (_("Fetching message headers... [%d/%d]"),
975                     i + 1 - old_count, new_count - old_count);
976
977       ret = pop_read_header (pop_data, ctx->hdrs[i]);
978       if (ret != PQ_OK)
979         break;
980
981       ctx->msgcount++;
982     }
983
984     if (i > old_count)
985       mx_update_context (ctx, i - old_count);
986   }
987
988   if (ret != PQ_OK) {
989     for (i = ctx->msgcount; i < new_count; i++)
990       header_delete(&ctx->hdrs[i]);
991     return ret;
992   }
993
994   mutt_clear_error ();
995   return (new_count - old_count);
996 }
997
998 /* delete all cached messages */
999 static void pop_clear_cache (pop_data_t * pop_data)
1000 {
1001   int i;
1002
1003   if (!pop_data->clear_cache)
1004     return;
1005
1006   for (i = 0; i < POP_CACHE_LEN; i++) {
1007     if (pop_data->cache[i].path) {
1008       unlink (pop_data->cache[i].path);
1009       p_delete(&pop_data->cache[i].path);
1010     }
1011   }
1012 }
1013
1014 /* pop_mx functions {{{ */
1015
1016 static int pop_is_magic(const char* path, struct stat* st)
1017 {
1018     url_scheme_t s = url_check_scheme(NONULL(path));
1019     return s == U_POP || s == U_POPS ? M_POP : -1;
1020 }
1021
1022 static int pop_open_mailbox (CONTEXT * ctx)
1023 {
1024   int ret;
1025   char buf[LONG_STRING];
1026   CONNECTION *conn;
1027   ACCOUNT act;
1028   pop_data_t *pop_data;
1029   ciss_url_t url;
1030
1031   if (pop_parse_path (ctx->path, &act)) {
1032     mutt_error (_("%s is an invalid POP path"), ctx->path);
1033     mutt_sleep (2);
1034     return -1;
1035   }
1036
1037   mutt_account_tourl (&act, &url);
1038   url.path = NULL;
1039   url_ciss_tostring (&url, buf, sizeof (buf), 0);
1040   conn = mutt_conn_find (NULL, &act);
1041   if (!conn)
1042     return -1;
1043
1044   p_delete(&ctx->path);
1045   ctx->path = m_strdup(buf);
1046
1047   pop_data = p_new(pop_data_t, 1);
1048   pop_data->conn = conn;
1049   ctx->data = pop_data;
1050
1051   if (pop_open_connection(pop_data) != PQ_OK)
1052     return -1;
1053
1054   conn->data = pop_data;
1055
1056   for (;;) {
1057     if (pop_reconnect (ctx) != PQ_OK)
1058       return -1;
1059
1060     mutt_message _("Fetching list of messages...");
1061     ctx->size = pop_data->size;
1062     ret = pop_fetch_headers (ctx);
1063
1064     if (ret >= 0)
1065       return 0;
1066
1067     if (ret < -1) {
1068       mutt_sleep (2);
1069       return -1;
1070     }
1071   }
1072 }
1073
1074 static int pop_acl_check(CONTEXT *ctx, int bit)
1075 {
1076     switch (bit) {
1077       case ACL_DELETE:    /* (un)deletion */
1078       case ACL_SEEN:      /* mark as read */
1079         return 1;
1080       case ACL_INSERT:    /* editing messages */
1081       case ACL_WRITE:     /* change importance */
1082       default:
1083         return 0;
1084     }
1085 }
1086
1087 static int pop_check_mailbox(CONTEXT * ctx, int *index_hint, int unused)
1088 {
1089   int ret;
1090   pop_data_t *pop_data = (pop_data_t *) ctx->data;
1091
1092   if ((pop_data->check_time + PopCheckTimeout) > time (NULL))
1093     return 0;
1094
1095   pop_logout (ctx);
1096
1097   mutt_socket_close (pop_data->conn);
1098
1099   if (pop_open_connection (pop_data) < 0)
1100     return -1;
1101
1102   mutt_message _("Checking for new messages...");
1103   ctx->size = pop_data->size;
1104   ret = pop_fetch_headers (ctx);
1105   pop_clear_cache (pop_data);
1106
1107   if (ret < 0)
1108     return -1;
1109
1110   if (ret > 0)
1111     return M_NEW_MAIL;
1112
1113   return 0;
1114 }
1115
1116 static void pop_close_mailbox (CONTEXT * ctx)
1117 {
1118   pop_data_t *pop_data = (pop_data_t *) ctx->data;
1119
1120   if (!pop_data)
1121     return;
1122
1123   pop_logout (ctx);
1124
1125   if (pop_data->status != POP_NONE)
1126     mutt_socket_close (pop_data->conn);
1127
1128   pop_data->status = POP_NONE;
1129
1130   pop_data->clear_cache = 1;
1131   pop_clear_cache (pop_data);
1132
1133   if (!pop_data->conn->data)
1134     mutt_socket_free (pop_data->conn);
1135
1136   return;
1137 }
1138
1139 static int pop_sync_mailbox(CONTEXT * ctx, int unused, int *index_hint)
1140 {
1141   int i;
1142   pop_query_status ret;
1143   char buf[LONG_STRING];
1144   pop_data_t *pop_data = (pop_data_t *) ctx->data;
1145
1146   pop_data->check_time = 0;
1147
1148   for (;;) {
1149     if (pop_reconnect (ctx) != PQ_OK)
1150       return PQ_NOT_CONNECTED;
1151
1152     mutt_message (_("Marking %d messages deleted..."), ctx->deleted);
1153
1154     for (i = 0, ret = 0; ret == 0 && i < ctx->msgcount; i++) {
1155       if (ctx->hdrs[i]->deleted) {
1156         ret = pop_query(pop_data, buf, sizeof(buf), "DELE %d",
1157                         ctx->hdrs[i]->refno);
1158       }
1159     }
1160
1161     if (ret == PQ_OK) {
1162       ret = pop_query(pop_data, buf, sizeof(buf), "QUIT");
1163     }
1164
1165     if (ret == PQ_OK) {
1166       pop_data->clear_cache = 1;
1167       pop_clear_cache (pop_data);
1168       pop_data->status = POP_DISCONNECTED;
1169       return PQ_OK;
1170     }
1171
1172     if (ret == PQ_ERR) {
1173       mutt_error ("%s", pop_data->err_msg);
1174       mutt_sleep (2);
1175       return PQ_NOT_CONNECTED;
1176     }
1177   }
1178 }
1179
1180 /* }}} */
1181
1182 mx_t const pop_mx = {
1183     M_POP,
1184     0,
1185     pop_is_magic,
1186     NULL,
1187     NULL,
1188     pop_open_mailbox,
1189     NULL,
1190     pop_acl_check,
1191     pop_check_mailbox,
1192     pop_close_mailbox,
1193     pop_sync_mailbox,
1194     NULL,
1195 };
1196
1197 /* public API {{{ */
1198
1199 void pop_fetch_mail (void)
1200 {
1201   char buffer[LONG_STRING];
1202   char msgbuf[STRING];
1203   char *url, *p;
1204   int i, delanswer, last = 0, msgs, bytes, rset = 0;
1205   pop_query_status ret;
1206   CONNECTION *conn;
1207   CONTEXT ctx;
1208   MESSAGE *msg = NULL;
1209   ACCOUNT act;
1210   pop_data_t *pop_data;
1211   ssize_t plen;
1212
1213   if (m_strisempty(PopHost)) {
1214     mutt_error _("POP host is not defined.");
1215     return;
1216   }
1217
1218   plen = m_strlen(PopHost) + 7;
1219   url  = p = p_new(char, plen);
1220   if (url_check_scheme (PopHost) == U_UNKNOWN) {
1221       snprintf(p, plen, "pop://%s", PopHost);
1222   } else {
1223       m_strcpy(p, plen, PopHost);
1224   }
1225
1226   ret = pop_parse_path (url, &act);
1227   p_delete(&url);
1228   if (ret) {
1229     mutt_error (_("%s is an invalid POP path"), PopHost);
1230     return;
1231   }
1232
1233   conn = mutt_conn_find (NULL, &act);
1234   if (!conn)
1235     return;
1236
1237   pop_data = p_new(pop_data_t, 1);
1238   pop_data->conn = conn;
1239
1240   if (pop_open_connection (pop_data) < 0) {
1241     mutt_socket_free (pop_data->conn);
1242     p_delete(&pop_data);
1243     return;
1244   }
1245
1246   conn->data = pop_data;
1247
1248   mutt_message _("Checking for new messages...");
1249
1250   /* find out how many messages are in the mailbox. */
1251   ret = pop_query(pop_data, buffer, sizeof(buffer), "STAT");
1252   if (ret == PQ_NOT_CONNECTED)
1253     goto fail;
1254   if (ret == PQ_ERR) {
1255     mutt_error ("%s", pop_data->err_msg);
1256     goto finish;
1257   }
1258
1259   sscanf (buffer, "+OK %d %d", &msgs, &bytes);
1260
1261   /* only get unread messages */
1262   if (msgs > 0 && option (OPTPOPLAST)) {
1263     ret = pop_query(pop_data, buffer, sizeof(buffer), "LAST");
1264     if (ret == PQ_NOT_CONNECTED)
1265       goto fail;
1266     if (ret == PQ_OK)
1267       sscanf (buffer, "+OK %d", &last);
1268   }
1269
1270   if (msgs <= last) {
1271     mutt_message _("No new mail in POP mailbox.");
1272
1273     goto finish;
1274   }
1275
1276   if (mx_open_mailbox (NONULL (Spoolfile), M_APPEND, &ctx) == NULL)
1277     goto finish;
1278
1279   delanswer =
1280     query_quadoption (OPT_POPDELETE, _("Delete messages from server?"));
1281
1282   snprintf (msgbuf, sizeof (msgbuf), _("Reading new messages (%d bytes)..."),
1283             bytes);
1284   mutt_message ("%s", msgbuf);
1285
1286   for (i = last + 1; i <= msgs; i++) {
1287     if ((msg = mx_open_new_message (&ctx, NULL, M_ADD_FROM)) == NULL)
1288       ret = -3;
1289     else {
1290       snprintf (buffer, sizeof (buffer), "RETR %d\r\n", i);
1291       ret = pop_fetch_data(pop_data, buffer, NULL, fetch_message, msg->fp);
1292       if (ret == PFD_FUNCT_ERROR)
1293         rset = 1;
1294
1295       if (ret == PQ_OK && mx_commit_message (msg, &ctx) != 0) {
1296         rset = 1;
1297         ret = PFD_FUNCT_ERROR;
1298       }
1299
1300       mx_close_message (&msg);
1301     }
1302
1303     if (ret == PQ_OK && delanswer == M_YES) {
1304       ret = pop_query(pop_data, buffer, sizeof(buffer), "DELE %d", i);
1305     }
1306
1307     if (ret == PQ_NOT_CONNECTED) {
1308       mx_close_mailbox (&ctx, NULL);
1309       goto fail;
1310     }
1311     if (ret == PQ_ERR) {
1312       mutt_error ("%s", pop_data->err_msg);
1313       break;
1314     }
1315     if (ret == -3) { /* this is -3 when ret != 0, because it will keep the value from before *gna* */
1316       mutt_error _("Error while writing mailbox!");
1317
1318       break;
1319     }
1320
1321     mutt_message (_("%s [%d of %d messages read]"), msgbuf, i - last,
1322                   msgs - last);
1323   }
1324
1325   mx_close_mailbox (&ctx, NULL);
1326
1327   if (rset) {
1328     /* make sure no messages get deleted */
1329     if (pop_query(pop_data, buffer, sizeof(buffer), "RSET") ==
1330         PQ_NOT_CONNECTED)
1331       goto fail;
1332   }
1333
1334 finish:
1335   if (pop_query(pop_data, buffer, sizeof(buffer), "QUIT") == PQ_NOT_CONNECTED)
1336     goto fail;
1337   mutt_socket_close (conn);
1338   p_delete(&pop_data);
1339   return;
1340
1341 fail:
1342   mutt_error _("Server closed connection!");
1343   mutt_socket_close (conn);
1344   p_delete(&pop_data);
1345 }
1346
1347 /* fetch message from POP server */
1348 int pop_fetch_message (MESSAGE * msg, CONTEXT * ctx, int msgno)
1349 {
1350   int ret;
1351   void *uidl;
1352   char buf[LONG_STRING];
1353   char path[_POSIX_PATH_MAX];
1354   progress_t bar;
1355   pop_data_t *pop_data = (pop_data_t *) ctx->data;
1356   POP_CACHE *cache;
1357   HEADER *h = ctx->hdrs[msgno];
1358
1359   /* see if we already have the message in our cache */
1360   cache = &pop_data->cache[h->index % POP_CACHE_LEN];
1361
1362   if (cache->path) {
1363     if (cache->index == h->index) {
1364       /* yes, so just return a pointer to the message */
1365       msg->fp = fopen (cache->path, "r");
1366       if (msg->fp)
1367         return 0;
1368
1369       mutt_perror (cache->path);
1370       mutt_sleep (2);
1371       return -1;
1372     }
1373     else {
1374       /* clear the previous entry */
1375       unlink (cache->path);
1376       p_delete(&cache->path);
1377     }
1378   }
1379
1380   for (;;) {
1381     if (pop_reconnect (ctx) != PQ_OK)
1382       return -1;
1383
1384     /* verify that massage index is correct */
1385     if (h->refno < 0) {
1386       mutt_error
1387         _("The message index is incorrect. Try reopening the mailbox.");
1388       mutt_sleep (2);
1389       return -1;
1390     }
1391
1392     bar.size = h->content->length + h->content->offset - 1;
1393     bar.msg = _("Fetching message...");
1394     mutt_progress_bar (&bar, 0);
1395
1396     msg->fp = m_tempfile(path, sizeof(path), NONULL(MCore.tmpdir), NULL);
1397     if (!msg->fp) {
1398       mutt_error(_("Could not create temporary file"));
1399       mutt_sleep(2);
1400       return -1;
1401     }
1402
1403     snprintf(buf, sizeof(buf), "RETR %d\r\n", h->refno);
1404     ret = pop_fetch_data(pop_data, buf, &bar, fetch_message, msg->fp);
1405     if (ret == PQ_OK)
1406       break;
1407
1408     m_fclose(&msg->fp);
1409     unlink (path);
1410
1411     if (ret == PQ_ERR) {
1412       mutt_error ("%s", pop_data->err_msg);
1413       mutt_sleep (2);
1414       return -1;
1415     }
1416
1417     if (ret == PFD_FUNCT_ERROR) {
1418       mutt_error _("Can't write message to temporary file!");
1419
1420       mutt_sleep (2);
1421       return -1;
1422     }
1423   }
1424
1425   /* Update the header information.  Previously, we only downloaded a
1426    * portion of the headers, those required for the main display.
1427    */
1428   cache->index = h->index;
1429   cache->path = m_strdup(path);
1430   rewind (msg->fp);
1431   uidl = h->data;
1432   envelope_delete(&h->env);
1433   h->env = mutt_read_rfc822_header (msg->fp, h, 0, 0);
1434   h->data = uidl;
1435   h->lines = 0;
1436   fgets (buf, sizeof (buf), msg->fp);
1437   while (!feof (msg->fp)) {
1438     ctx->hdrs[msgno]->lines++;
1439     fgets (buf, sizeof (buf), msg->fp);
1440   }
1441
1442   h->content->length = ftello (msg->fp) - h->content->offset;
1443
1444   /* This needs to be done in case this is a multipart message */
1445   h->security = crypt_query (h->content);
1446
1447   mutt_clear_error ();
1448   rewind (msg->fp);
1449
1450   return 0;
1451 }
1452
1453 /* }}} */