pop fixes.
[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   char buf[LONG_STRING];
458   char *inbuf;
459   char *p;
460   pop_query_status ret;
461   int chunk = 0;
462   long pos = 0;
463   ssize_t lenbuf = 0;
464
465   m_strcpy(buf, sizeof(buf), query);
466   ret = _pop_query(pop_data, buf, sizeof(buf));
467   if (ret != PQ_OK)
468     return ret;
469
470   inbuf = p_new(char, sizeof(buf));
471
472   for (;;) {
473     chunk =
474       mutt_socket_readln(buf, sizeof (buf), pop_data->conn);
475     if (chunk < 0) {
476       pop_data->status = POP_DISCONNECTED;
477       ret = PQ_NOT_CONNECTED;
478       break;
479     }
480
481     p = buf;
482     if (!lenbuf && buf[0] == '.') {
483       if (buf[1] != '.')
484         break;
485       p++;
486     }
487
488     m_strcpy(inbuf + lenbuf,sizeof(buf), p);
489     pos += chunk;
490
491     if (chunk >= ssizeof(buf)) {
492       lenbuf += strlen (p);
493     } else {
494       if (bar)
495         mutt_progress_bar (bar, pos);
496       if (ret == 0 && funct (inbuf, data) < 0)
497         ret = PFD_FUNCT_ERROR;
498       lenbuf = 0;
499     }
500
501     p_realloc(&inbuf, lenbuf + sizeof(buf));
502   }
503
504   p_delete(&inbuf);
505   return ret;
506 }
507
508 static int fetch_capa (char *line, void *data)
509 {
510   pop_data_t *pop_data = (pop_data_t *) data;
511   char *c;
512
513   if (!ascii_strncasecmp (line, "SASL", 4)) {
514     p_delete(&pop_data->auth_list);
515     c = vskipspaces(line + 4);
516     pop_data->auth_list = m_strdup(c);
517   }
518
519   else if (!ascii_strncasecmp (line, "STLS", 4))
520     pop_data->cmd_stls = CMD_AVAILABLE;
521
522   else if (!ascii_strncasecmp (line, "UIDL", 4))
523     pop_data->cmd_uidl = CMD_AVAILABLE;
524
525   else if (!ascii_strncasecmp (line, "TOP", 3))
526     pop_data->cmd_top = CMD_AVAILABLE;
527
528   return 0;
529 }
530
531 static int fetch_auth (char *line, void *data)
532 {
533   pop_data_t *pop_data = (pop_data_t *) data;
534   ssize_t auth_list_len;
535
536   if (!pop_data->auth_list) {
537     auth_list_len = m_strlen(line) + 1;
538     pop_data->auth_list = p_new(char, auth_list_len);
539   } else {
540     auth_list_len = m_strlen(pop_data->auth_list) + m_strlen(line) + 2;
541     p_realloc(&pop_data->auth_list, auth_list_len);
542     m_strcat(pop_data->auth_list, auth_list_len, " ");
543   }
544   m_strcat(pop_data->auth_list, auth_list_len, line);
545
546   return 0;
547 }
548
549 /*
550  * Get capabilities
551  *  0 - successful,
552  * -1 - conection lost,
553  * -2 - execution error.
554 */
555 static pop_query_status pop_capabilities(pop_data_t * pop_data, int mode)
556 {
557   /* don't check capabilities on reconnect */
558   if (pop_data->capabilities)
559     return 0;
560
561   /* init capabilities */
562   if (mode == 0) {
563     pop_data->cmd_capa   = CMD_NOT_AVAILABLE;
564     pop_data->cmd_stls   = CMD_NOT_AVAILABLE;
565     pop_data->cmd_uidl   = CMD_NOT_AVAILABLE;
566     pop_data->cmd_top    = CMD_NOT_AVAILABLE;
567     pop_data->cmd_user   = CMD_NOT_AVAILABLE;
568     pop_data->resp_codes = 0;
569     pop_data->expire     = 1;
570     p_delete(&pop_data->auth_list);
571   }
572
573   /* Execute CAPA command */
574   if (mode == 0 || pop_data->cmd_capa != CMD_NOT_AVAILABLE) {
575     switch (pop_fetch_data(pop_data, "CAPA\r\n", NULL, fetch_capa, pop_data)) {
576     case PQ_OK:
577       pop_data->cmd_capa = CMD_AVAILABLE;
578       break;
579     case PFD_FUNCT_ERROR:
580     case PQ_ERR:
581       pop_data->cmd_capa = CMD_NOT_AVAILABLE;
582       break;
583     case PQ_NOT_CONNECTED:
584       return PQ_NOT_CONNECTED;
585     }
586   }
587
588   /* CAPA not supported, use defaults */
589   if (mode == 0 && pop_data->cmd_capa == CMD_NOT_AVAILABLE) {
590     pop_data->cmd_uidl = CMD_UNKNOWN;
591     pop_data->cmd_top = CMD_UNKNOWN;
592
593     if (pop_fetch_data(pop_data, "AUTH\r\n", NULL, fetch_auth, pop_data) ==
594         PQ_NOT_CONNECTED)
595       return PQ_NOT_CONNECTED;
596   }
597
598   /* Check capabilities */
599   if (mode == 2) {
600     char *msg = NULL;
601
602     if (!pop_data->expire)
603       msg = _("Unable to leave messages on server.");
604     if (pop_data->cmd_top == CMD_NOT_AVAILABLE)
605       msg = _("Command TOP is not supported by server.");
606     if (pop_data->cmd_uidl == CMD_NOT_AVAILABLE)
607       msg = _("Command UIDL is not supported by server.");
608     if (msg && pop_data->cmd_capa != CMD_AVAILABLE) {
609       mutt_error (msg);
610       return PQ_ERR;
611     }
612     pop_data->capabilities = 1;
613   }
614
615   return PQ_OK;
616 }
617
618 /* given an POP mailbox name, return host, port, username and password */
619 static int pop_parse_path (const char *path, ACCOUNT * act)
620 {
621   ciss_url_t url;
622   char *c;
623   int ret = -1;
624
625   /* Defaults */
626   act->flags = 0;
627   act->port = POP_PORT;
628   act->type = M_ACCT_TYPE_POP;
629
630   c = m_strdup(path);
631   url_parse_ciss (&url, c);
632
633   if (url.scheme == U_POP || url.scheme == U_POPS) {
634     if (url.scheme == U_POPS) {
635       act->flags |= M_ACCT_SSL;
636       act->port = POP_SSL_PORT;
637     }
638
639     if ((!url.path || !*url.path) && mutt_account_fromurl (act, &url) == 0)
640       ret = 0;
641   }
642
643   p_delete(&c);
644   return ret;
645 }
646
647 /*
648  * Open connection and authenticate
649  *  0 - successful,
650  * -1 - conection lost,
651  * -2 - invalid command or execution error,
652  * -3 - authentication canceled.
653 */
654 static pop_query_status pop_open_connection (pop_data_t * pop_data)
655 {
656   pop_query_status ret;
657   int n, size;
658   char buf[LONG_STRING];
659
660   ret = pop_connect(pop_data);
661   if (ret != PQ_OK) {
662     mutt_sleep (2);
663     return ret;
664   }
665
666   ret = pop_capabilities (pop_data, 0);
667   if (ret == PQ_NOT_CONNECTED)
668     goto err_conn;
669   if (ret == PQ_ERR) {
670     mutt_sleep (2);
671     return PQ_ERR;
672   }
673
674   /* Attempt STLS if available and desired. */
675   if (!pop_data->conn->ssf && (pop_data->cmd_stls || mod_ssl.force_tls)) {
676     if (mod_ssl.force_tls)
677       pop_data->use_stls = 2;
678     if (pop_data->use_stls == 0) {
679       pop_data->use_stls = 1;
680       if (mod_ssl.starttls)
681         pop_data->use_stls = 2;
682     }
683     if (pop_data->use_stls == 2) {
684       ret = pop_query(pop_data, buf, sizeof(buf), "STLS");
685       if (ret == PQ_NOT_CONNECTED)
686         goto err_conn;
687       if (ret != PQ_OK) {
688         mutt_error ("%s", pop_data->err_msg);
689         mutt_sleep (2);
690       }
691       else if (mutt_ssl_starttls (pop_data->conn))
692       {
693         mutt_error (_("Could not negotiate TLS connection"));
694         mutt_sleep (2);
695         return PQ_ERR;
696       }
697       else {
698         /* recheck capabilities after STLS completes */
699         ret = pop_capabilities (pop_data, 1);
700         if (ret == PQ_NOT_CONNECTED)
701           goto err_conn;
702         if (ret == PQ_ERR) {
703           mutt_sleep (2);
704           return PQ_ERR;
705         }
706       }
707     }
708   }
709
710   if (mod_ssl.force_tls && !pop_data->conn->ssf) {
711     mutt_error _("Encrypted connection unavailable");
712     mutt_sleep (1);
713     return -2;
714   }
715
716   ret = pop_authenticate (pop_data);
717   if (ret == PQ_NOT_CONNECTED)
718     goto err_conn;
719   if (ret == PFD_FUNCT_ERROR)
720     mutt_clear_error ();
721   if (ret != PQ_OK)
722     return ret;
723
724   /* recheck capabilities after authentication */
725   ret = pop_capabilities (pop_data, 2);
726   if (ret == PQ_NOT_CONNECTED)
727     goto err_conn;
728   if (ret == PQ_ERR) {
729     mutt_sleep (2);
730     return PQ_ERR;
731   }
732
733   /* get total size of mailbox */
734   ret = pop_query(pop_data, buf, sizeof(buf), "STAT");
735   if (ret == PQ_NOT_CONNECTED)
736     goto err_conn;
737   if (ret == PQ_ERR) {
738     mutt_error ("%s", pop_data->err_msg);
739     mutt_sleep (2);
740     return ret;
741   }
742
743   sscanf (buf, "+OK %u %u", &n, &size);
744   pop_data->size = size;
745   return PQ_OK;
746
747 err_conn:
748   pop_data->status = POP_DISCONNECTED;
749   mutt_error _("Server closed connection!");
750
751   mutt_sleep (2);
752   return PQ_NOT_CONNECTED;
753 }
754
755 /* find message with this UIDL and set refno */
756 static int check_uidl (char *line, void *data)
757 {
758   int i, idx;
759   CONTEXT *ctx = (CONTEXT *)data;
760
761   sscanf (line, "%u %s", &idx, line);
762   for (i = 0; i < ctx->msgcount; i++) {
763     if (!m_strcmp(ctx->hdrs[i]->data, line)) {
764       ctx->hdrs[i]->refno = idx;
765       break;
766     }
767   }
768
769   return 0;
770 }
771
772 /* reconnect and verify indexes if connection was lost */
773 static pop_query_status pop_reconnect (CONTEXT * ctx)
774 {
775   pop_query_status ret;
776   pop_data_t *pop_data = (pop_data_t *) ctx->data;
777   progress_t bar;
778
779   if (pop_data->status == POP_CONNECTED)
780     return PQ_OK;
781   if (pop_data->status == POP_BYE)
782     return PQ_NOT_CONNECTED;
783
784   for (;;) {
785     mutt_socket_close (pop_data->conn);
786
787     ret = pop_open_connection(pop_data);
788     if (ret == PQ_OK) {
789       int i;
790
791       bar.msg = _("Verifying message indexes...");
792       bar.size = 0;
793       mutt_progress_bar (&bar, 0);
794
795       for (i = 0; i < ctx->msgcount; i++)
796         ctx->hdrs[i]->refno = -1;
797
798       ret = pop_fetch_data(pop_data, "UIDL\r\n", &bar, check_uidl, ctx);
799       if (ret == PQ_ERR) {
800         mutt_error ("%s", pop_data->err_msg);
801         mutt_sleep (2);
802       }
803     }
804     if (ret == PQ_OK)
805       return PQ_OK;
806
807     pop_logout (ctx);
808
809     if (ret == PQ_ERR)
810       return PQ_NOT_CONNECTED;
811
812     if (query_quadoption (OPT_POPRECONNECT,
813                           _("Connection lost. Reconnect to POP server?")) !=
814         M_YES)
815       return PQ_NOT_CONNECTED;
816   }
817 }
818
819 /* write line to file */
820 static int fetch_message (char *line, void *file)
821 {
822   FILE *f = (FILE *) file;
823
824   fputs (line, f);
825   if (fputc ('\n', f) == EOF)
826     return -1;
827
828   return 0;
829 }
830
831 /*
832  * Read header
833  * returns:
834  *  0 on success
835  * -1 - conection lost,
836  * -2 - invalid command or execution error,
837  * -3 - error writing to tempfile
838  */
839 static pop_query_status pop_read_header (pop_data_t * pop_data, HEADER * h)
840 {
841   FILE *f;
842   int idx;
843   pop_query_status ret;
844   long length;
845   char buf[LONG_STRING];
846
847   f = tmpfile();
848   if (!f) {
849     mutt_error(_("Could not create temporary file"));
850     return PFD_FUNCT_ERROR;
851   }
852
853   ret = pop_query(pop_data, buf, sizeof(buf), "LIST %d", h->refno);
854   if (ret == PQ_OK) {
855     sscanf (buf, "+OK %d %ld", &idx, &length);
856
857     snprintf (buf, sizeof (buf), "TOP %d 0\r\n", h->refno);
858     ret = pop_fetch_data(pop_data, buf, NULL, fetch_message, f);
859
860     if (pop_data->cmd_top == CMD_UNKNOWN) {
861       if (ret == PQ_OK) {
862         pop_data->cmd_top = CMD_AVAILABLE;
863       }
864
865       if (ret == PQ_ERR) {
866         pop_data->cmd_top = CMD_NOT_AVAILABLE;
867         snprintf (pop_data->err_msg, sizeof (pop_data->err_msg),
868                   _("Command TOP is not supported by server."));
869       }
870     }
871   }
872
873   switch (ret) {
874   case PQ_OK:
875     {
876       rewind (f);
877       h->env = mutt_read_rfc822_header (f, h, 0, 0);
878       h->content->length = length - h->content->offset + 1;
879       rewind (f);
880       while (!feof (f)) {
881         h->content->length--;
882         fgets (buf, sizeof (buf), f);
883       }
884       break;
885     }
886   case PQ_ERR:
887     {
888       mutt_error ("%s", pop_data->err_msg);
889       break;
890     }
891   case PFD_FUNCT_ERROR:
892     {
893       mutt_error _("Can't write header to temporary file!");
894
895       break;
896     }
897   case PQ_NOT_CONNECTED:
898     {
899       mutt_error _("Can't fetch header: Not connected!");
900       break;
901     }
902   }
903
904   m_fclose(&f);
905   return ret;
906 }
907
908 /* parse UIDL */
909 static int fetch_uidl (char *line, void *data)
910 {
911   int i, idx;
912   CONTEXT *ctx = (CONTEXT *) data;
913   pop_data_t *pop_data = (pop_data_t *) ctx->data;
914
915   sscanf (line, "%d %s", &idx, line);
916   for (i = 0; i < ctx->msgcount; i++)
917     if (!m_strcmp(line, ctx->hdrs[i]->data))
918       break;
919
920   if (i == ctx->msgcount) {
921     if (i >= ctx->hdrmax)
922       mx_alloc_memory (ctx);
923
924     ctx->msgcount++;
925     ctx->hdrs[i] = header_new();
926     ctx->hdrs[i]->data = m_strdup(line);
927   }
928   else if (ctx->hdrs[i]->index != idx - 1)
929     pop_data->clear_cache = 1;
930
931   ctx->hdrs[i]->refno = idx;
932   ctx->hdrs[i]->index = idx - 1;
933
934   return 0;
935 }
936
937 /*
938  * Read headers
939  * returns:
940  *  0 on success
941  * -1 - conection lost,
942  * -2 - invalid command or execution error,
943  * -3 - error writing to tempfile
944  */
945 static int pop_fetch_headers (CONTEXT * ctx)
946 {
947   int i, old_count, new_count;
948   pop_query_status ret;
949   pop_data_t *pop_data = (pop_data_t *) ctx->data;
950
951   time (&pop_data->check_time);
952   pop_data->clear_cache = 0;
953
954   for (i = 0; i < ctx->msgcount; i++)
955     ctx->hdrs[i]->refno = -1;
956
957   old_count = ctx->msgcount;
958   ret = pop_fetch_data(pop_data, "UIDL\r\n", NULL, fetch_uidl, ctx);
959   new_count = ctx->msgcount;
960   ctx->msgcount = old_count;
961
962   if (pop_data->cmd_uidl == CMD_UNKNOWN) {
963     if (ret == PQ_OK) {
964       pop_data->cmd_uidl = CMD_AVAILABLE;
965     }
966
967     if (ret == PQ_ERR && pop_data->cmd_uidl == CMD_UNKNOWN) {
968       pop_data->cmd_uidl = CMD_NOT_AVAILABLE;
969
970       snprintf (pop_data->err_msg, sizeof (pop_data->err_msg),
971                 _("Command UIDL is not supported by server."));
972     }
973   }
974
975   if (ret == PQ_OK) {
976     for (i = 0; i < old_count; i++)
977       if (ctx->hdrs[i]->refno == -1)
978         ctx->hdrs[i]->deleted = 1;
979
980     for (i = old_count; i < new_count; i++) {
981       mutt_message (_("Fetching message headers... [%d/%d]"),
982                     i + 1 - old_count, new_count - old_count);
983
984       ret = pop_read_header (pop_data, ctx->hdrs[i]);
985       if (ret != PQ_OK)
986         break;
987
988       ctx->msgcount++;
989     }
990
991     if (i > old_count)
992       mx_update_context (ctx, i - old_count);
993   }
994
995   if (ret != PQ_OK) {
996     for (i = ctx->msgcount; i < new_count; i++)
997       header_delete(&ctx->hdrs[i]);
998     return ret;
999   }
1000
1001   mutt_clear_error ();
1002   return (new_count - old_count);
1003 }
1004
1005 /* delete all cached messages */
1006 static void pop_clear_cache (pop_data_t * pop_data)
1007 {
1008   int i;
1009
1010   if (!pop_data->clear_cache)
1011     return;
1012
1013   for (i = 0; i < POP_CACHE_LEN; i++) {
1014     if (pop_data->cache[i].path) {
1015       unlink (pop_data->cache[i].path);
1016       p_delete(&pop_data->cache[i].path);
1017     }
1018   }
1019 }
1020
1021 /* pop_mx functions {{{ */
1022
1023 static int pop_is_magic(const char* path, struct stat* st)
1024 {
1025     url_scheme_t s = url_check_scheme(NONULL(path));
1026     return s == U_POP || s == U_POPS ? M_POP : -1;
1027 }
1028
1029 static int pop_open_mailbox (CONTEXT * ctx)
1030 {
1031   int ret;
1032   char buf[LONG_STRING];
1033   CONNECTION *conn;
1034   ACCOUNT act;
1035   pop_data_t *pop_data;
1036   ciss_url_t url;
1037
1038   if (pop_parse_path (ctx->path, &act)) {
1039     mutt_error (_("%s is an invalid POP path"), ctx->path);
1040     mutt_sleep (2);
1041     return -1;
1042   }
1043
1044   mutt_account_tourl (&act, &url);
1045   url.path = NULL;
1046   url_ciss_tostring (&url, buf, sizeof (buf), 0);
1047   conn = mutt_conn_find (NULL, &act);
1048   if (!conn)
1049     return -1;
1050
1051   p_delete(&ctx->path);
1052   ctx->path = m_strdup(buf);
1053
1054   pop_data = p_new(pop_data_t, 1);
1055   pop_data->conn = conn;
1056   ctx->data = pop_data;
1057
1058   if (pop_open_connection(pop_data) != PQ_OK)
1059     return -1;
1060
1061   conn->data = pop_data;
1062
1063   for (;;) {
1064     if (pop_reconnect (ctx) != PQ_OK)
1065       return -1;
1066
1067     mutt_message _("Fetching list of messages...");
1068     ctx->size = pop_data->size;
1069     ret = pop_fetch_headers (ctx);
1070
1071     if (ret >= 0)
1072       return 0;
1073
1074     if (ret < -1) {
1075       mutt_sleep (2);
1076       return -1;
1077     }
1078   }
1079 }
1080
1081 static int pop_acl_check(CONTEXT *ctx, int bit)
1082 {
1083     switch (bit) {
1084       case ACL_DELETE:    /* (un)deletion */
1085       case ACL_SEEN:      /* mark as read */
1086         return 1;
1087       case ACL_INSERT:    /* editing messages */
1088       case ACL_WRITE:     /* change importance */
1089       default:
1090         return 0;
1091     }
1092 }
1093
1094 static int pop_check_mailbox(CONTEXT * ctx, int *index_hint, int unused)
1095 {
1096   int ret;
1097   pop_data_t *pop_data = (pop_data_t *) ctx->data;
1098
1099   if ((pop_data->check_time + PopCheckTimeout) > time (NULL))
1100     return 0;
1101
1102   pop_logout (ctx);
1103
1104   mutt_socket_close (pop_data->conn);
1105
1106   if (pop_open_connection (pop_data) < 0)
1107     return -1;
1108
1109   mutt_message _("Checking for new messages...");
1110   ctx->size = pop_data->size;
1111   ret = pop_fetch_headers (ctx);
1112   pop_clear_cache (pop_data);
1113
1114   if (ret < 0)
1115     return -1;
1116
1117   if (ret > 0)
1118     return M_NEW_MAIL;
1119
1120   return 0;
1121 }
1122
1123 static void pop_close_mailbox (CONTEXT * ctx)
1124 {
1125   pop_data_t *pop_data = (pop_data_t *) ctx->data;
1126
1127   if (!pop_data)
1128     return;
1129
1130   pop_logout (ctx);
1131
1132   if (pop_data->status != POP_NONE)
1133     mutt_socket_close (pop_data->conn);
1134
1135   pop_data->status = POP_NONE;
1136
1137   pop_data->clear_cache = 1;
1138   pop_clear_cache (pop_data);
1139
1140   if (!pop_data->conn->data)
1141     mutt_socket_free (pop_data->conn);
1142
1143   return;
1144 }
1145
1146 static int pop_sync_mailbox(CONTEXT * ctx, int unused, int *index_hint)
1147 {
1148   int i;
1149   pop_query_status ret;
1150   char buf[LONG_STRING];
1151   pop_data_t *pop_data = (pop_data_t *) ctx->data;
1152
1153   pop_data->check_time = 0;
1154
1155   for (;;) {
1156     if (pop_reconnect (ctx) != PQ_OK)
1157       return PQ_NOT_CONNECTED;
1158
1159     mutt_message (_("Marking %d messages deleted..."), ctx->deleted);
1160
1161     for (i = 0, ret = 0; ret == 0 && i < ctx->msgcount; i++) {
1162       if (ctx->hdrs[i]->deleted) {
1163         ret = pop_query(pop_data, buf, sizeof(buf), "DELE %d",
1164                         ctx->hdrs[i]->refno);
1165       }
1166     }
1167
1168     if (ret == PQ_OK) {
1169       ret = pop_query(pop_data, buf, sizeof(buf), "QUIT");
1170     }
1171
1172     if (ret == PQ_OK) {
1173       pop_data->clear_cache = 1;
1174       pop_clear_cache (pop_data);
1175       pop_data->status = POP_DISCONNECTED;
1176       return PQ_OK;
1177     }
1178
1179     if (ret == PQ_ERR) {
1180       mutt_error ("%s", pop_data->err_msg);
1181       mutt_sleep (2);
1182       return PQ_NOT_CONNECTED;
1183     }
1184   }
1185 }
1186
1187 /* }}} */
1188
1189 mx_t const pop_mx = {
1190     M_POP,
1191     0,
1192     pop_is_magic,
1193     NULL,
1194     NULL,
1195     pop_open_mailbox,
1196     NULL,
1197     pop_acl_check,
1198     pop_check_mailbox,
1199     pop_close_mailbox,
1200     pop_sync_mailbox,
1201     NULL,
1202 };
1203
1204 /* public API {{{ */
1205
1206 void pop_fetch_mail (void)
1207 {
1208   char buffer[LONG_STRING];
1209   char msgbuf[STRING];
1210   char *url, *p;
1211   int i, delanswer, last = 0, msgs, bytes, rset = 0;
1212   pop_query_status ret;
1213   CONNECTION *conn;
1214   CONTEXT ctx;
1215   MESSAGE *msg = NULL;
1216   ACCOUNT act;
1217   pop_data_t *pop_data;
1218   ssize_t plen;
1219
1220   if (m_strisempty(PopHost)) {
1221     mutt_error _("POP host is not defined.");
1222     return;
1223   }
1224
1225   plen = m_strlen(PopHost) + 7;
1226   url  = p = p_new(char, plen);
1227   if (url_check_scheme (PopHost) == U_UNKNOWN) {
1228       snprintf(p, plen, "pop://%s", PopHost);
1229   } else {
1230       m_strcpy(p, plen, PopHost);
1231   }
1232
1233   ret = pop_parse_path (url, &act);
1234   p_delete(&url);
1235   if (ret) {
1236     mutt_error (_("%s is an invalid POP path"), PopHost);
1237     return;
1238   }
1239
1240   conn = mutt_conn_find (NULL, &act);
1241   if (!conn)
1242     return;
1243
1244   pop_data = p_new(pop_data_t, 1);
1245   pop_data->conn = conn;
1246
1247   if (pop_open_connection (pop_data) < 0) {
1248     mutt_socket_free (pop_data->conn);
1249     p_delete(&pop_data);
1250     return;
1251   }
1252
1253   conn->data = pop_data;
1254
1255   mutt_message _("Checking for new messages...");
1256
1257   /* find out how many messages are in the mailbox. */
1258   ret = pop_query(pop_data, buffer, sizeof(buffer), "STAT");
1259   if (ret == PQ_NOT_CONNECTED)
1260     goto fail;
1261   if (ret == PQ_ERR) {
1262     mutt_error ("%s", pop_data->err_msg);
1263     goto finish;
1264   }
1265
1266   sscanf (buffer, "+OK %d %d", &msgs, &bytes);
1267
1268   /* only get unread messages */
1269   if (msgs > 0 && option (OPTPOPLAST)) {
1270     ret = pop_query(pop_data, buffer, sizeof(buffer), "LAST");
1271     if (ret == PQ_NOT_CONNECTED)
1272       goto fail;
1273     if (ret == PQ_OK)
1274       sscanf (buffer, "+OK %d", &last);
1275   }
1276
1277   if (msgs <= last) {
1278     mutt_message _("No new mail in POP mailbox.");
1279
1280     goto finish;
1281   }
1282
1283   if (mx_open_mailbox (NONULL (Spoolfile), M_APPEND, &ctx) == NULL)
1284     goto finish;
1285
1286   delanswer =
1287     query_quadoption (OPT_POPDELETE, _("Delete messages from server?"));
1288
1289   snprintf (msgbuf, sizeof (msgbuf), _("Reading new messages (%d bytes)..."),
1290             bytes);
1291   mutt_message ("%s", msgbuf);
1292
1293   for (i = last + 1; i <= msgs; i++) {
1294     if ((msg = mx_open_new_message (&ctx, NULL, M_ADD_FROM)) == NULL)
1295       ret = -3;
1296     else {
1297       snprintf (buffer, sizeof (buffer), "RETR %d\r\n", i);
1298       ret = pop_fetch_data(pop_data, buffer, NULL, fetch_message, msg->fp);
1299       if (ret == PFD_FUNCT_ERROR)
1300         rset = 1;
1301
1302       if (ret == PQ_OK && mx_commit_message (msg, &ctx) != 0) {
1303         rset = 1;
1304         ret = PFD_FUNCT_ERROR;
1305       }
1306
1307       mx_close_message (&msg);
1308     }
1309
1310     if (ret == PQ_OK && delanswer == M_YES) {
1311       ret = pop_query(pop_data, buffer, sizeof(buffer), "DELE %d", i);
1312     }
1313
1314     if (ret == PQ_NOT_CONNECTED) {
1315       mx_close_mailbox (&ctx, NULL);
1316       goto fail;
1317     }
1318     if (ret == PQ_ERR) {
1319       mutt_error ("%s", pop_data->err_msg);
1320       break;
1321     }
1322     if (ret == -3) { /* this is -3 when ret != 0, because it will keep the value from before *gna* */
1323       mutt_error _("Error while writing mailbox!");
1324
1325       break;
1326     }
1327
1328     mutt_message (_("%s [%d of %d messages read]"), msgbuf, i - last,
1329                   msgs - last);
1330   }
1331
1332   mx_close_mailbox (&ctx, NULL);
1333
1334   if (rset) {
1335     /* make sure no messages get deleted */
1336     if (pop_query(pop_data, buffer, sizeof(buffer), "RSET") ==
1337         PQ_NOT_CONNECTED)
1338       goto fail;
1339   }
1340
1341 finish:
1342   if (pop_query(pop_data, buffer, sizeof(buffer), "QUIT") == PQ_NOT_CONNECTED)
1343     goto fail;
1344   mutt_socket_close (conn);
1345   p_delete(&pop_data);
1346   return;
1347
1348 fail:
1349   mutt_error _("Server closed connection!");
1350   mutt_socket_close (conn);
1351   p_delete(&pop_data);
1352 }
1353
1354 /* fetch message from POP server */
1355 int pop_fetch_message (MESSAGE * msg, CONTEXT * ctx, int msgno)
1356 {
1357   int ret;
1358   void *uidl;
1359   char buf[LONG_STRING];
1360   char path[_POSIX_PATH_MAX];
1361   progress_t bar;
1362   pop_data_t *pop_data = (pop_data_t *) ctx->data;
1363   POP_CACHE *cache;
1364   HEADER *h = ctx->hdrs[msgno];
1365
1366   /* see if we already have the message in our cache */
1367   cache = &pop_data->cache[h->index % POP_CACHE_LEN];
1368
1369   if (cache->path) {
1370     if (cache->index == h->index) {
1371       /* yes, so just return a pointer to the message */
1372       msg->fp = fopen (cache->path, "r");
1373       if (msg->fp)
1374         return 0;
1375
1376       mutt_perror (cache->path);
1377       mutt_sleep (2);
1378       return -1;
1379     }
1380     else {
1381       /* clear the previous entry */
1382       unlink (cache->path);
1383       p_delete(&cache->path);
1384     }
1385   }
1386
1387   for (;;) {
1388     if (pop_reconnect (ctx) != PQ_OK)
1389       return -1;
1390
1391     /* verify that massage index is correct */
1392     if (h->refno < 0) {
1393       mutt_error
1394         _("The message index is incorrect. Try reopening the mailbox.");
1395       mutt_sleep (2);
1396       return -1;
1397     }
1398
1399     bar.size = h->content->length + h->content->offset - 1;
1400     bar.msg = _("Fetching message...");
1401     mutt_progress_bar (&bar, 0);
1402
1403     msg->fp = m_tempfile(path, sizeof(path), NONULL(MCore.tmpdir), NULL);
1404     if (!msg->fp) {
1405       mutt_error(_("Could not create temporary file"));
1406       mutt_sleep(2);
1407       return -1;
1408     }
1409
1410     snprintf(buf, sizeof(buf), "RETR %d\r\n", h->refno);
1411     ret = pop_fetch_data(pop_data, buf, &bar, fetch_message, msg->fp);
1412     if (ret == PQ_OK)
1413       break;
1414
1415     m_fclose(&msg->fp);
1416     unlink (path);
1417
1418     if (ret == PQ_ERR) {
1419       mutt_error ("%s", pop_data->err_msg);
1420       mutt_sleep (2);
1421       return -1;
1422     }
1423
1424     if (ret == PFD_FUNCT_ERROR) {
1425       mutt_error _("Can't write message to temporary file!");
1426
1427       mutt_sleep (2);
1428       return -1;
1429     }
1430   }
1431
1432   /* Update the header information.  Previously, we only downloaded a
1433    * portion of the headers, those required for the main display.
1434    */
1435   cache->index = h->index;
1436   cache->path = m_strdup(path);
1437   rewind (msg->fp);
1438   uidl = h->data;
1439   envelope_delete(&h->env);
1440   h->env = mutt_read_rfc822_header (msg->fp, h, 0, 0);
1441   h->data = uidl;
1442   h->lines = 0;
1443   fgets (buf, sizeof (buf), msg->fp);
1444   while (!feof (msg->fp)) {
1445     ctx->hdrs[msgno]->lines++;
1446     fgets (buf, sizeof (buf), msg->fp);
1447   }
1448
1449   h->content->length = ftello (msg->fp) - h->content->offset;
1450
1451   /* This needs to be done in case this is a multipart message */
1452   h->security = crypt_query (h->content);
1453
1454   mutt_clear_error ();
1455   rewind (msg->fp);
1456
1457   return 0;
1458 }
1459
1460 /* }}} */