use m_strdup and m_strlen that are inlined for efficiency
[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 <lib-lib/mem.h>
15 #include <lib-lib/str.h>
16 #include <lib-lib/macros.h>
17
18 #include "mutt.h"
19 #include "ascii.h"
20 #include "mx.h"
21 #include "url.h"
22 #include "pop.h"
23 #if defined (USE_SSL) || defined (USE_GNUTLS)
24 # include "mutt_ssl.h"
25 #endif
26
27 #include "lib/debug.h"
28
29 #include <string.h>
30 #include <unistd.h>
31 #include <ctype.h>
32
33 /* given an POP mailbox name, return host, port, username and password */
34 int pop_parse_path (const char *path, ACCOUNT * acct)
35 {
36   ciss_url_t url;
37   char *c;
38   int ret = -1;
39
40   /* Defaults */
41   acct->flags = 0;
42   acct->port = POP_PORT;
43   acct->type = M_ACCT_TYPE_POP;
44
45   c = m_strdup(path);
46   url_parse_ciss (&url, c);
47
48   if (url.scheme == U_POP || url.scheme == U_POPS) {
49     if (url.scheme == U_POPS) {
50       acct->flags |= M_ACCT_SSL;
51       acct->port = POP_SSL_PORT;
52     }
53
54     if ((!url.path || !*url.path) && mutt_account_fromurl (acct, &url) == 0)
55       ret = 0;
56   }
57
58   p_delete(&c);
59   return ret;
60 }
61
62 /* Copy error message to err_msg buffer */
63 void pop_error (POP_DATA * pop_data, char *msg)
64 {
65   char *t, *c, *c2;
66
67   t = strchr (pop_data->err_msg, '\0');
68   c = msg;
69
70   if (!str_ncmp (msg, "-ERR ", 5)) {
71     c2 = msg + 5;
72     SKIPWS (c2);
73
74     if (*c2)
75       c = c2;
76   }
77
78   strfcpy (t, c, sizeof (pop_data->err_msg) - strlen (pop_data->err_msg));
79   str_skip_trailws (pop_data->err_msg);
80 }
81
82 /* Parse CAPA output */
83 static int fetch_capa (char *line, void *data)
84 {
85   POP_DATA *pop_data = (POP_DATA *) data;
86   char *c;
87
88   if (!ascii_strncasecmp (line, "SASL", 4)) {
89     p_delete(&pop_data->auth_list);
90     c = line + 4;
91     SKIPWS (c);
92     pop_data->auth_list = m_strdup(c);
93   }
94
95   else if (!ascii_strncasecmp (line, "STLS", 4))
96     pop_data->cmd_stls = CMD_AVAILABLE;
97
98   else if (!ascii_strncasecmp (line, "USER", 4))
99     pop_data->cmd_user = CMD_AVAILABLE;
100
101   else if (!ascii_strncasecmp (line, "UIDL", 4))
102     pop_data->cmd_uidl = CMD_AVAILABLE;
103
104   else if (!ascii_strncasecmp (line, "TOP", 3))
105     pop_data->cmd_top = CMD_AVAILABLE;
106
107   return 0;
108 }
109
110 /* Fetch list of the authentication mechanisms */
111 static int fetch_auth (char *line, void *data)
112 {
113   POP_DATA *pop_data = (POP_DATA *) data;
114
115   if (!pop_data->auth_list) {
116     pop_data->auth_list = p_new(char, strlen(line) + 1);
117   } else {
118     p_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     p_delete(&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 PFD_FUNCT_ERROR:
164     case PQ_ERR:
165       {
166         pop_data->cmd_capa = CMD_NOT_AVAILABLE;
167         break;
168       }
169     case PQ_NOT_CONNECTED:
170       return PQ_NOT_CONNECTED;
171     }
172   }
173
174   /* CAPA not supported, use defaults */
175   if (mode == 0 && pop_data->cmd_capa == CMD_NOT_AVAILABLE) {
176     pop_data->cmd_user = CMD_UNKNOWN;
177     pop_data->cmd_uidl = CMD_UNKNOWN;
178     pop_data->cmd_top = CMD_UNKNOWN;
179
180     strfcpy (buf, "AUTH\r\n", sizeof (buf));
181     if (pop_fetch_data (pop_data, buf, NULL, fetch_auth, pop_data) == PQ_NOT_CONNECTED)
182       return PQ_NOT_CONNECTED;
183   }
184
185   /* Check capabilities */
186   if (mode == 2) {
187     char *msg = NULL;
188
189     if (!pop_data->expire)
190       msg = _("Unable to leave messages on server.");
191     if (pop_data->cmd_top == CMD_NOT_AVAILABLE)
192       msg = _("Command TOP is not supported by server.");
193     if (pop_data->cmd_uidl == CMD_NOT_AVAILABLE)
194       msg = _("Command UIDL is not supported by server.");
195     if (msg && pop_data->cmd_capa != CMD_AVAILABLE) {
196       mutt_error (msg);
197       return PQ_ERR;
198     }
199     pop_data->capabilities = 1;
200   }
201
202   return PQ_OK;
203 }
204
205 /*
206  * Open connection
207  *  0 - successful,
208  * -1 - conection lost,
209  * -2 - invalid response.
210 */
211 pop_query_status pop_connect (POP_DATA * pop_data)
212 {
213   char buf[LONG_STRING];
214
215   pop_data->status = POP_NONE;
216   if (mutt_socket_open (pop_data->conn) < 0 ||
217       mutt_socket_readln (buf, sizeof (buf), pop_data->conn) < 0) {
218     mutt_error (_("Error connecting to server: %s"),
219                 pop_data->conn->account.host);
220     return PQ_NOT_CONNECTED;
221   }
222
223   pop_data->status = POP_CONNECTED;
224
225   if (str_ncmp (buf, "+OK", 3)) {
226     *pop_data->err_msg = '\0';
227     pop_error (pop_data, buf);
228     mutt_error ("%s", pop_data->err_msg);
229     return PQ_ERR;
230   }
231
232   pop_apop_timestamp (pop_data, buf);
233
234   return PQ_OK;
235 }
236
237 /*
238  * Open connection and authenticate
239  *  0 - successful,
240  * -1 - conection lost,
241  * -2 - invalid command or execution error,
242  * -3 - authentication canceled.
243 */
244 pop_query_status pop_open_connection (POP_DATA * pop_data)
245 {
246   pop_query_status ret;
247   unsigned int n, size;
248   char buf[LONG_STRING];
249
250   ret = pop_connect (pop_data);
251   if (ret != PQ_OK) {
252     mutt_sleep (2);
253     return ret;
254   }
255
256   ret = pop_capabilities (pop_data, 0);
257   if (ret == PQ_NOT_CONNECTED)
258     goto err_conn;
259   if (ret == PQ_ERR) {
260     mutt_sleep (2);
261     return PQ_ERR;
262   }
263
264 #if (defined(USE_SSL) || defined(USE_GNUTLS))
265   /* Attempt STLS if available and desired. */
266   if (!pop_data->conn->ssf && (pop_data->cmd_stls || option(OPTSSLFORCETLS))) {
267     if (option (OPTSSLFORCETLS))
268       pop_data->use_stls = 2;
269     if (pop_data->use_stls == 0) {
270       ret = query_quadoption (OPT_SSLSTARTTLS,
271                               _("Secure connection with TLS?"));
272       if (ret == -1)
273         return PQ_ERR;
274       pop_data->use_stls = 1;
275       if (ret == M_YES)
276         pop_data->use_stls = 2;
277     }
278     if (pop_data->use_stls == 2) {
279       strfcpy (buf, "STLS\r\n", sizeof (buf));
280       ret = pop_query (pop_data, buf, sizeof (buf));
281       if (ret == PQ_NOT_CONNECTED)
282         goto err_conn;
283       if (ret != PQ_OK) {
284         mutt_error ("%s", pop_data->err_msg);
285         mutt_sleep (2);
286       }
287 #if defined (USE_SSL) || defined (USE_GNUTLS)
288       else if (mutt_ssl_starttls (pop_data->conn))
289 #endif
290       {
291         mutt_error (_("Could not negotiate TLS connection"));
292         mutt_sleep (2);
293         return PQ_ERR;
294       }
295       else {
296         /* recheck capabilities after STLS completes */
297         ret = pop_capabilities (pop_data, 1);
298         if (ret == PQ_NOT_CONNECTED)
299           goto err_conn;
300         if (ret == PQ_ERR) {
301           mutt_sleep (2);
302           return PQ_ERR;
303         }
304       }
305     }
306   }
307
308   if (option(OPTSSLFORCETLS) && !pop_data->conn->ssf) {
309     mutt_error _("Encrypted connection unavailable");
310     mutt_sleep (1);
311     return -2;
312   }
313 #endif
314
315   ret = pop_authenticate (pop_data);
316   if (ret == PQ_NOT_CONNECTED)
317     goto err_conn;
318   if (ret == PFD_FUNCT_ERROR)
319     mutt_clear_error ();
320   if (ret != PQ_OK)
321     return ret;
322
323   /* recheck capabilities after authentication */
324   ret = pop_capabilities (pop_data, 2);
325   if (ret == PQ_NOT_CONNECTED)
326     goto err_conn;
327   if (ret == PQ_ERR) {
328     mutt_sleep (2);
329     return PQ_ERR;
330   }
331
332   /* get total size of mailbox */
333   strfcpy (buf, "STAT\r\n", sizeof (buf));
334   ret = pop_query (pop_data, buf, sizeof (buf));
335   if (ret == PQ_NOT_CONNECTED)
336     goto err_conn;
337   if (ret == PQ_ERR) {
338     mutt_error ("%s", pop_data->err_msg);
339     mutt_sleep (2);
340     return ret;
341   }
342
343   sscanf (buf, "+OK %u %u", &n, &size);
344   pop_data->size = size;
345   return PQ_OK;
346
347 err_conn:
348   pop_data->status = POP_DISCONNECTED;
349   mutt_error _("Server closed connection!");
350
351   mutt_sleep (2);
352   return PQ_NOT_CONNECTED;
353 }
354
355 /* logout from POP server */
356 void pop_logout (CONTEXT * ctx)
357 {
358   pop_query_status ret = 0;
359   char buf[LONG_STRING];
360   POP_DATA *pop_data = (POP_DATA *) ctx->data;
361
362   if (pop_data->status == POP_CONNECTED) {
363     mutt_message _("Closing connection to POP server...");
364
365     if (ctx->readonly) {
366       strfcpy (buf, "RSET\r\n", sizeof (buf));
367       ret = pop_query (pop_data, buf, sizeof (buf));
368     }
369
370     if (ret != PQ_NOT_CONNECTED) {
371       strfcpy (buf, "QUIT\r\n", sizeof (buf));
372       pop_query (pop_data, buf, sizeof (buf));
373     }
374
375     mutt_clear_error ();
376   }
377
378   pop_data->status = POP_DISCONNECTED;
379   return;
380 }
381
382 /*
383  * Send data from buffer and receive answer to the same buffer
384  *  0 - successful,
385  * -1 - conection lost,
386  * -2 - invalid command or execution error.
387 */
388 pop_query_status pop_query_d (POP_DATA * pop_data, char *buf, size_t buflen, const char *msg)
389 {
390   int dbg = M_SOCK_LOG_CMD;
391   char *c;
392
393   if (pop_data->status != POP_CONNECTED)
394     return PQ_NOT_CONNECTED;
395
396 #ifdef DEBUG
397   /* print msg instaed of real command */
398   if (msg) {
399     dbg = M_SOCK_LOG_FULL;
400     debug_print (M_SOCK_LOG_CMD, ("> %s", msg));
401   }
402 #endif
403
404   mutt_socket_write_d (pop_data->conn, buf, dbg);
405
406   c = strpbrk (buf, " \r\n");
407   *c = '\0';
408   snprintf (pop_data->err_msg, sizeof (pop_data->err_msg), "%s: ", buf);
409
410   if (mutt_socket_readln (buf, buflen, pop_data->conn) < 0) {
411     pop_data->status = POP_DISCONNECTED;
412     return PQ_NOT_CONNECTED;
413   }
414   if (!str_ncmp (buf, "+OK", 3))
415     return PQ_OK;
416
417   pop_error (pop_data, buf);
418   return PQ_ERR;
419 }
420
421 /*
422  * This function calls  funct(*line, *data)  for each received line,
423  * funct(NULL, *data)  if  rewind(*data)  needs, exits when fail or done.
424  * Returned codes:
425  *  0 - successful,
426  * -1 - conection lost,
427  * -2 - invalid command or execution error,
428  * -3 - error in funct(*line, *data)
429  */
430 pop_query_status pop_fetch_data (POP_DATA * pop_data, const char *query, progress_t* bar,
431                     int (*funct) (char *, void *), void *data)
432 {
433   char buf[LONG_STRING];
434   char *inbuf;
435   char *p;
436   pop_query_status ret;
437   int chunk = 0;
438   long pos = 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 = p_new(char, 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     pos += chunk;
467
468     if (chunk >= sizeof (buf)) {
469       lenbuf += strlen (p);
470     }
471     else {
472       if (bar)
473         mutt_progress_bar (bar, pos);
474       if (ret == 0 && funct (inbuf, data) < 0)
475         ret = PFD_FUNCT_ERROR;
476       lenbuf = 0;
477     }
478
479     p_realloc(&inbuf, lenbuf + sizeof(buf));
480   }
481
482   p_delete(&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   progress_t bar;
510
511   if (pop_data->status == POP_CONNECTED)
512     return PQ_OK;
513   if (pop_data->status == POP_BYE)
514     return PQ_NOT_CONNECTED;
515
516   FOREVER {
517     mutt_socket_close (pop_data->conn);
518
519     ret = pop_open_connection (pop_data);
520     if (ret == PQ_OK) {
521       int i;
522
523       bar.msg = _("Verifying message indexes...");
524       bar.size = 0;
525       mutt_progress_bar (&bar, 0);
526
527       for (i = 0; i < ctx->msgcount; i++)
528         ctx->hdrs[i]->refno = -1;
529
530       ret = pop_fetch_data(pop_data, "UIDL\r\n", &bar, check_uidl, ctx);
531       if (ret == PQ_ERR) {
532         mutt_error ("%s", pop_data->err_msg);
533         mutt_sleep (2);
534       }
535     }
536     if (ret == PQ_OK)
537       return PQ_OK;
538
539     pop_logout (ctx);
540
541     if (ret == PQ_ERR)
542       return PQ_NOT_CONNECTED;
543
544     if (query_quadoption (OPT_POPRECONNECT,
545                           _("Connection lost. Reconnect to POP server?")) !=
546         M_YES)
547       return PQ_NOT_CONNECTED;
548   }
549 }