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