2cd84f08fef33f2b7295e4a4cd479911e9c34c3f
[apps/madmutt.git] / pop / pop_lib.c
1 /*
2  * Copyright notice from original mutt:
3  * Copyright (C) 2000-2003 Vsevolod Volkov <vvv@mutt.org.ua>
4  *
5  * This file is part of mutt-ng, see http://www.muttng.org/.
6  * It's licensed under the GNU General Public License,
7  * please see the file GPL in the top level source directory.
8  */
9
10 #if HAVE_CONFIG_H
11 # include "config.h"
12 #endif
13
14 #include "mutt.h"
15 #include "mx.h"
16 #include "url.h"
17 #include "pop.h"
18 #ifdef USE_SSL
19 # include "mutt_ssl.h"
20 #endif
21
22 #include "lib/mem.h"
23 #include "lib/intl.h"
24 #include "lib/debug.h"
25 #include "lib/str.h"
26
27 #include <string.h>
28 #include <unistd.h>
29 #include <ctype.h>
30
31 /* given an POP mailbox name, return host, port, username and password */
32 int pop_parse_path (const char *path, ACCOUNT * acct)
33 {
34   ciss_url_t url;
35   char *c;
36   int ret = -1;
37
38   /* Defaults */
39   acct->flags = 0;
40   acct->port = POP_PORT;
41   acct->type = M_ACCT_TYPE_POP;
42
43   c = str_dup (path);
44   url_parse_ciss (&url, c);
45
46   if (url.scheme == U_POP || url.scheme == U_POPS) {
47     if (url.scheme == U_POPS) {
48       acct->flags |= M_ACCT_SSL;
49       acct->port = POP_SSL_PORT;
50     }
51
52     if ((!url.path || !*url.path) && mutt_account_fromurl (acct, &url) == 0)
53       ret = 0;
54   }
55
56   FREE (&c);
57   return ret;
58 }
59
60 /* Copy error message to err_msg buffer */
61 void pop_error (POP_DATA * pop_data, char *msg)
62 {
63   char *t, *c, *c2;
64
65   t = strchr (pop_data->err_msg, '\0');
66   c = msg;
67
68   if (!str_ncmp (msg, "-ERR ", 5)) {
69     c2 = msg + 5;
70     SKIPWS (c2);
71
72     if (*c2)
73       c = c2;
74   }
75
76   strfcpy (t, c, sizeof (pop_data->err_msg) - strlen (pop_data->err_msg));
77   str_skip_trailws (pop_data->err_msg);
78 }
79
80 /* Parse CAPA output */
81 static int fetch_capa (char *line, void *data)
82 {
83   POP_DATA *pop_data = (POP_DATA *) data;
84   char *c;
85
86   if (!ascii_strncasecmp (line, "SASL", 4)) {
87     FREE (&pop_data->auth_list);
88     c = line + 4;
89     SKIPWS (c);
90     pop_data->auth_list = str_dup (c);
91   }
92
93   else if (!ascii_strncasecmp (line, "STLS", 4))
94     pop_data->cmd_stls = CMD_AVAILABLE;
95
96   else if (!ascii_strncasecmp (line, "USER", 4))
97     pop_data->cmd_user = CMD_AVAILABLE;
98
99   else if (!ascii_strncasecmp (line, "UIDL", 4))
100     pop_data->cmd_uidl = CMD_AVAILABLE;
101
102   else if (!ascii_strncasecmp (line, "TOP", 3))
103     pop_data->cmd_top = CMD_AVAILABLE;
104
105   return 0;
106 }
107
108 /* Fetch list of the authentication mechanisms */
109 static int fetch_auth (char *line, void *data)
110 {
111   POP_DATA *pop_data = (POP_DATA *) data;
112
113   if (!pop_data->auth_list) {
114     pop_data->auth_list = safe_malloc (strlen (line) + 1);
115     *pop_data->auth_list = '\0';
116   }
117   else {
118     safe_realloc (&pop_data->auth_list,
119                   strlen (pop_data->auth_list) + strlen (line) + 2);
120     strcat (pop_data->auth_list, " ");  /* __STRCAT_CHECKED__ */
121   }
122   strcat (pop_data->auth_list, line);   /* __STRCAT_CHECKED__ */
123
124   return 0;
125 }
126
127 /*
128  * Get capabilities
129  *  0 - successful,
130  * -1 - conection lost,
131  * -2 - execution error.
132 */
133 static pop_query_status pop_capabilities (POP_DATA * pop_data, int mode)
134 {
135   char buf[LONG_STRING];
136
137   /* don't check capabilities on reconnect */
138   if (pop_data->capabilities)
139     return 0;
140
141   /* init capabilities */
142   if (mode == 0) {
143     pop_data->cmd_capa = CMD_NOT_AVAILABLE;
144     pop_data->cmd_stls = CMD_NOT_AVAILABLE;
145     pop_data->cmd_user = CMD_NOT_AVAILABLE;
146     pop_data->cmd_uidl = CMD_NOT_AVAILABLE;
147     pop_data->cmd_top = CMD_NOT_AVAILABLE;
148     pop_data->resp_codes = 0;
149     pop_data->expire = 1;
150     pop_data->login_delay = 0;
151     FREE (&pop_data->auth_list);
152   }
153
154   /* Execute CAPA command */
155   if (mode == 0 || pop_data->cmd_capa != CMD_NOT_AVAILABLE) {
156     strfcpy (buf, "CAPA\r\n", sizeof (buf));
157     switch (pop_fetch_data (pop_data, buf, NULL, fetch_capa, pop_data)) {
158     case PQ_OK:
159       {
160         pop_data->cmd_capa = CMD_AVAILABLE;
161         break;
162       }
163     case PQ_ERR:
164       {
165         pop_data->cmd_capa = CMD_NOT_AVAILABLE;
166         break;
167       }
168     case PQ_NOT_CONNECTED:
169       return PQ_NOT_CONNECTED;
170     }
171   }
172
173   /* CAPA not supported, use defaults */
174   if (mode == 0 && pop_data->cmd_capa == CMD_NOT_AVAILABLE) {
175     pop_data->cmd_user = CMD_UNKNOWN;
176     pop_data->cmd_uidl = CMD_UNKNOWN;
177     pop_data->cmd_top = CMD_UNKNOWN;
178
179     strfcpy (buf, "AUTH\r\n", sizeof (buf));
180     if (pop_fetch_data (pop_data, buf, NULL, fetch_auth, pop_data) == PQ_NOT_CONNECTED)
181       return PQ_NOT_CONNECTED;
182   }
183
184   /* Check capabilities */
185   if (mode == 2) {
186     char *msg = NULL;
187
188     if (!pop_data->expire)
189       msg = _("Unable to leave messages on server.");
190     if (pop_data->cmd_top == CMD_NOT_AVAILABLE)
191       msg = _("Command TOP is not supported by server.");
192     if (pop_data->cmd_uidl == CMD_NOT_AVAILABLE)
193       msg = _("Command UIDL is not supported by server.");
194     if (msg && pop_data->cmd_capa != CMD_AVAILABLE) {
195       mutt_error (msg);
196       return PQ_ERR;
197     }
198     pop_data->capabilities = 1;
199   }
200
201   return PQ_OK;
202 }
203
204 /*
205  * Open connection
206  *  0 - successful,
207  * -1 - conection lost,
208  * -2 - invalid response.
209 */
210 pop_query_status pop_connect (POP_DATA * pop_data)
211 {
212   char buf[LONG_STRING];
213
214   pop_data->status = POP_NONE;
215   if (mutt_socket_open (pop_data->conn) < 0 ||
216       mutt_socket_readln (buf, sizeof (buf), pop_data->conn) < 0) {
217     mutt_error (_("Error connecting to server: %s"),
218                 pop_data->conn->account.host);
219     return PQ_NOT_CONNECTED;
220   }
221
222   pop_data->status = POP_CONNECTED;
223
224   if (str_ncmp (buf, "+OK", 3)) {
225     *pop_data->err_msg = '\0';
226     pop_error (pop_data, buf);
227     mutt_error ("%s", pop_data->err_msg);
228     return PQ_ERR;
229   }
230
231   pop_apop_timestamp (pop_data, buf);
232
233   return PQ_OK;
234 }
235
236 /*
237  * Open connection and authenticate
238  *  0 - successful,
239  * -1 - conection lost,
240  * -2 - invalid command or execution error,
241  * -3 - authentication canceled.
242 */
243 pop_query_status pop_open_connection (POP_DATA * pop_data)
244 {
245   pop_query_status ret;
246   unsigned int n, size;
247   char buf[LONG_STRING];
248
249   ret = pop_connect (pop_data);
250   if (ret != PQ_OK) {
251     mutt_sleep (2);
252     return ret;
253   }
254
255   ret = pop_capabilities (pop_data, 0);
256   if (ret == PQ_NOT_CONNECTED)
257     goto err_conn;
258   if (ret == PQ_ERR) {
259     mutt_sleep (2);
260     return PQ_ERR;
261   }
262
263 #if (defined(USE_SSL) || defined(USE_GNUTLS))
264   /* Attempt STLS if available and desired. */
265   if (!pop_data->conn->ssf && (pop_data->cmd_stls || option(OPTSSLFORCETLS))) {
266     if (option (OPTSSLFORCETLS))
267       pop_data->use_stls = 2;
268     if (pop_data->use_stls == 0) {
269       ret = query_quadoption (OPT_SSLSTARTTLS,
270                               _("Secure connection with TLS?"));
271       if (ret == -1)
272         return PQ_ERR;
273       pop_data->use_stls = 1;
274       if (ret == M_YES)
275         pop_data->use_stls = 2;
276     }
277     if (pop_data->use_stls == 2) {
278       strfcpy (buf, "STLS\r\n", sizeof (buf));
279       ret = pop_query (pop_data, buf, sizeof (buf));
280       if (ret == PQ_NOT_CONNECTED)
281         goto err_conn;
282       if (ret != PQ_OK) {
283         mutt_error ("%s", pop_data->err_msg);
284         mutt_sleep (2);
285       }
286 #ifdef USE_SSL
287       else if (mutt_ssl_starttls (pop_data->conn))
288 #elif USE_GNUTLS
289       else if (mutt_gnutls_starttls (pop_data->conn))
290 #endif
291       {
292         mutt_error (_("Could not negotiate TLS connection"));
293         mutt_sleep (2);
294         return PQ_ERR;
295       }
296       else {
297         /* recheck capabilities after STLS completes */
298         ret = pop_capabilities (pop_data, 1);
299         if (ret == PQ_NOT_CONNECTED)
300           goto err_conn;
301         if (ret == PQ_ERR) {
302           mutt_sleep (2);
303           return PQ_ERR;
304         }
305       }
306     }
307   }
308
309   if (option(OPTSSLFORCETLS) && !pop_data->conn->ssf) {
310     mutt_error _("Encrypted connection unavailable");
311     mutt_sleep (1);
312     return -2;
313   }
314 #endif
315
316   ret = pop_authenticate (pop_data);
317   if (ret == PQ_NOT_CONNECTED)
318     goto err_conn;
319   if (ret == PFD_FUNCT_ERROR)
320     mutt_clear_error ();
321   if (ret != PQ_OK)
322     return ret;
323
324   /* recheck capabilities after authentication */
325   ret = pop_capabilities (pop_data, 2);
326   if (ret == PQ_NOT_CONNECTED)
327     goto err_conn;
328   if (ret == PQ_ERR) {
329     mutt_sleep (2);
330     return PQ_ERR;
331   }
332
333   /* get total size of mailbox */
334   strfcpy (buf, "STAT\r\n", sizeof (buf));
335   ret = pop_query (pop_data, buf, sizeof (buf));
336   if (ret == PQ_NOT_CONNECTED)
337     goto err_conn;
338   if (ret == PQ_ERR) {
339     mutt_error ("%s", pop_data->err_msg);
340     mutt_sleep (2);
341     return ret;
342   }
343
344   sscanf (buf, "+OK %u %u", &n, &size);
345   pop_data->size = size;
346   return PQ_OK;
347
348 err_conn:
349   pop_data->status = POP_DISCONNECTED;
350   mutt_error _("Server closed connection!");
351
352   mutt_sleep (2);
353   return PQ_NOT_CONNECTED;
354 }
355
356 /* logout from POP server */
357 void pop_logout (CONTEXT * ctx)
358 {
359   pop_query_status ret = 0;
360   char buf[LONG_STRING];
361   POP_DATA *pop_data = (POP_DATA *) ctx->data;
362
363   if (pop_data->status == POP_CONNECTED) {
364     mutt_message _("Closing connection to POP server...");
365
366     if (ctx->readonly) {
367       strfcpy (buf, "RSET\r\n", sizeof (buf));
368       ret = pop_query (pop_data, buf, sizeof (buf));
369     }
370
371     if (ret != PQ_NOT_CONNECTED) {
372       strfcpy (buf, "QUIT\r\n", sizeof (buf));
373       pop_query (pop_data, buf, sizeof (buf));
374     }
375
376     mutt_clear_error ();
377   }
378
379   pop_data->status = POP_DISCONNECTED;
380   return;
381 }
382
383 /*
384  * Send data from buffer and receive answer to the same buffer
385  *  0 - successful,
386  * -1 - conection lost,
387  * -2 - invalid command or execution error.
388 */
389 pop_query_status pop_query_d (POP_DATA * pop_data, char *buf, size_t buflen, char *msg)
390 {
391   int dbg = M_SOCK_LOG_CMD;
392   char *c;
393
394   if (pop_data->status != POP_CONNECTED)
395     return PQ_NOT_CONNECTED;
396
397 #ifdef DEBUG
398   /* print msg instaed of real command */
399   if (msg) {
400     dbg = M_SOCK_LOG_FULL;
401     debug_print (M_SOCK_LOG_CMD, ("> %s", msg));
402   }
403 #endif
404
405   mutt_socket_write_d (pop_data->conn, buf, dbg);
406
407   c = strpbrk (buf, " \r\n");
408   *c = '\0';
409   snprintf (pop_data->err_msg, sizeof (pop_data->err_msg), "%s: ", buf);
410
411   if (mutt_socket_readln (buf, buflen, pop_data->conn) < 0) {
412     pop_data->status = POP_DISCONNECTED;
413     return PQ_NOT_CONNECTED;
414   }
415   if (!str_ncmp (buf, "+OK", 3))
416     return PQ_OK;
417
418   pop_error (pop_data, buf);
419   return PQ_ERR;
420 }
421
422 /*
423  * This function calls  funct(*line, *data)  for each received line,
424  * funct(NULL, *data)  if  rewind(*data)  needs, exits when fail or done.
425  * Returned codes:
426  *  0 - successful,
427  * -1 - conection lost,
428  * -2 - invalid command or execution error,
429  * -3 - error in funct(*line, *data)
430  */
431 pop_query_status pop_fetch_data (POP_DATA * pop_data, char *query, char *msg,
432                     int (*funct) (char *, void *), void *data)
433 {
434   char buf[LONG_STRING];
435   char *inbuf;
436   char *p;
437   pop_query_status ret;
438   int chunk, line = 0;
439   size_t lenbuf = 0;
440
441   strfcpy (buf, query, sizeof (buf));
442   ret = pop_query (pop_data, buf, sizeof (buf));
443   if (ret != PQ_OK)
444     return ret;
445
446   inbuf = safe_malloc (sizeof (buf));
447
448   FOREVER {
449     chunk =
450       mutt_socket_readln_d (buf, sizeof (buf), pop_data->conn,
451                             M_SOCK_LOG_HDR);
452     if (chunk < 0) {
453       pop_data->status = POP_DISCONNECTED;
454       ret = PQ_NOT_CONNECTED;
455       break;
456     }
457
458     p = buf;
459     if (!lenbuf && buf[0] == '.') {
460       if (buf[1] != '.')
461         break;
462       p++;
463     }
464
465     strfcpy (inbuf + lenbuf, p, sizeof (buf));
466
467     if (chunk >= sizeof (buf)) {
468       lenbuf += strlen (p);
469     }
470     else {
471       line++;
472       if (msg && ReadInc && (line % ReadInc == 0))
473         mutt_message ("%s %d", msg, line);
474       if (ret == 0 && funct (inbuf, data) < 0)
475         ret = PFD_FUNCT_ERROR;
476       lenbuf = 0;
477     }
478
479     safe_realloc (&inbuf, lenbuf + sizeof (buf));
480   }
481
482   FREE (&inbuf);
483   return ret;
484 }
485
486 /* find message with this UIDL and set refno */
487 static int check_uidl (char *line, void *data)
488 {
489   int i;
490   unsigned int index;
491   CONTEXT *ctx = (CONTEXT *) data;
492
493   sscanf (line, "%u %s", &index, line);
494   for (i = 0; i < ctx->msgcount; i++) {
495     if (!str_cmp (ctx->hdrs[i]->data, line)) {
496       ctx->hdrs[i]->refno = index;
497       break;
498     }
499   }
500
501   return 0;
502 }
503
504 /* reconnect and verify indexes if connection was lost */
505 pop_query_status pop_reconnect (CONTEXT * ctx)
506 {
507   pop_query_status ret;
508   POP_DATA *pop_data = (POP_DATA *) ctx->data;
509
510   if (pop_data->status == POP_CONNECTED)
511     return PQ_OK;
512   if (pop_data->status == POP_BYE)
513     return PQ_NOT_CONNECTED;
514
515   FOREVER {
516     mutt_socket_close (pop_data->conn);
517
518     ret = pop_open_connection (pop_data);
519     if (ret == PQ_OK) {
520       char *msg = _("Verifying message indexes...");
521       int i;
522
523       for (i = 0; i < ctx->msgcount; i++)
524         ctx->hdrs[i]->refno = -1;
525
526       mutt_message (msg);
527
528       ret = pop_fetch_data (pop_data, "UIDL\r\n", msg, check_uidl, ctx);
529       if (ret == PQ_ERR) {
530         mutt_error ("%s", pop_data->err_msg);
531         mutt_sleep (2);
532       }
533     }
534     if (ret == PQ_OK)
535       return PQ_OK;
536
537     pop_logout (ctx);
538
539     if (ret == PQ_ERR)
540       return PQ_NOT_CONNECTED;
541
542     if (query_quadoption (OPT_POPRECONNECT,
543                           _("Connection lost. Reconnect to POP server?")) !=
544         M_YES)
545       return PQ_NOT_CONNECTED;
546   }
547 }