simplify charset and things in the sockets API.
[apps/madmutt.git] / lib-sys / mutt_socket.c
1 /*
2  * Copyright notice from original mutt:
3  * Copyright (C) 1998 Michael R. Elkins <me@mutt.org>
4  * Copyright (C) 1999-2005 Brendan Cully <brendan@kublai.com>
5  * Copyright (C) 1999-2000 Tommi Komulainen <Tommi.Komulainen@iki.fi>
6  *
7  * This file is part of mutt-ng, see http://www.muttng.org/.
8  * It's licensed under the GNU General Public License,
9  * please see the file GPL in the top level source directory.
10  */
11
12 #if HAVE_CONFIG_H
13 # include "config.h"
14 #endif
15
16 #include <unistd.h>
17 #include <netinet/in.h>
18 #include <netdb.h>
19 #include <stdlib.h>
20 #include <fcntl.h>
21 #include <sys/types.h>
22 #include <sys/socket.h>
23 #include <string.h>
24 #include <errno.h>
25
26 #include <lib-lib/mem.h>
27 #include <lib-lib/str.h>
28 #include <lib-lib/macros.h>
29
30 #include "mutt.h"
31 #include "globals.h"
32
33 #include "unix.h"
34 #include "mutt_socket.h"
35 #include "mutt_tunnel.h"
36 #include "mutt_signal.h"
37 #include "mutt_ssl.h"
38
39 #include "mutt_idna.h"
40
41 /* support for multiple socket connections */
42 static CONNECTION *Connections = NULL;
43
44 /* forward declarations */
45 static int socket_preconnect (void);
46 static int socket_connect (int fd, struct sockaddr *sa);
47 static CONNECTION *socket_new_conn (void);
48
49 /* Wrappers */
50 int mutt_socket_open (CONNECTION * conn)
51 {
52   if (socket_preconnect ())
53     return -1;
54
55   return conn->conn_open (conn);
56 }
57
58 int mutt_socket_close (CONNECTION * conn)
59 {
60   int rc = -1;
61
62   if (conn->fd >= 0)
63     rc = conn->conn_close (conn);
64
65   conn->fd = -1;
66   conn->ssf = 0;
67
68   return rc;
69 }
70
71 int mutt_socket_read (CONNECTION * conn, char *buf, ssize_t len)
72 {
73   int rc;
74
75   if (conn->fd < 0) {
76     return -1;
77   }
78
79   rc = conn->conn_read (conn, buf, len);
80   /* EOF */
81   if (rc == 0) {
82     mutt_error (_("Connection to %s closed"), conn->account.host);
83     mutt_sleep (2);
84   }
85   if (rc <= 0)
86     mutt_socket_close (conn);
87
88   return rc;
89 }
90
91 int mutt_socket_write(CONNECTION * conn, const char *buf)
92 {
93   int rc;
94   int len;
95
96   if (conn->fd < 0) {
97     return -1;
98   }
99
100   len = m_strlen(buf);
101   if ((rc = conn->conn_write (conn, buf, len)) < 0) {
102     mutt_socket_close (conn);
103
104     return -1;
105   }
106
107   return rc;
108 }
109
110 /* simple read buffering to speed things up. */
111 int mutt_socket_readchar (CONNECTION * conn, char *c)
112 {
113   if (conn->bufpos >= conn->available) {
114     if (conn->fd >= 0)
115       conn->available =
116         conn->conn_read (conn, conn->inbuf, sizeof (conn->inbuf));
117     else {
118       return -1;
119     }
120     conn->bufpos = 0;
121     if (conn->available == 0) {
122       mutt_error (_("Connection to %s closed"), conn->account.host);
123       mutt_sleep (2);
124     }
125     if (conn->available <= 0) {
126       mutt_socket_close (conn);
127       return -1;
128     }
129   }
130   *c = conn->inbuf[conn->bufpos];
131   conn->bufpos++;
132   return 1;
133 }
134
135 int mutt_socket_readln(char *buf, ssize_t buflen, CONNECTION * conn)
136 {
137   char ch;
138   ssize_t i;
139
140   for (i = 0; i < buflen - 1; i++) {
141     if (mutt_socket_readchar (conn, &ch) != 1) {
142       buf[i] = '\0';
143       return -1;
144     }
145
146     if (ch == '\n')
147       break;
148     buf[i] = ch;
149   }
150
151   /* strip \r from \r\n termination */
152   if (i && buf[i - 1] == '\r')
153     buf[--i] = '\0';
154   else
155     buf[i] = '\0';
156
157   /* number of bytes read, not m_strlen*/
158   return i + 1;
159 }
160
161 CONNECTION *mutt_socket_head (void)
162 {
163   return Connections;
164 }
165
166 /* mutt_socket_free: remove connection from connection list and free it */
167 void mutt_socket_free (CONNECTION * conn)
168 {
169   CONNECTION *iter;
170   CONNECTION *tmp;
171
172   iter = Connections;
173
174   /* head is special case, doesn't need prev updated */
175   if (iter == conn) {
176     Connections = iter->next;
177     p_delete(&iter);
178     return;
179   }
180
181   while (iter->next) {
182     if (iter->next == conn) {
183       tmp = iter->next;
184       iter->next = tmp->next;
185       p_delete(&tmp);
186       return;
187     }
188     iter = iter->next;
189   }
190 }
191
192 /* mutt_conn_find: find a connection off the list of connections whose
193  *   account matches account. If start is not null, only search for
194  *   connections after the given connection (allows higher level socket code
195  *   to make more fine-grained searches than account info - eg in IMAP we may
196  *   wish to find a connection which is not in IMAP_SELECTED state) */
197 CONNECTION *mutt_conn_find (const CONNECTION * start, const ACCOUNT * account)
198 {
199   CONNECTION *conn;
200   ciss_url_t url;
201   char hook[LONG_STRING];
202
203   /* account isn't actually modified, since url isn't either */
204   mutt_account_tourl ((ACCOUNT *) account, &url);
205   url.path = NULL;
206   url_ciss_tostring (&url, hook, sizeof (hook), 0);
207   mutt_account_hook (hook);
208
209   conn = start ? start->next : Connections;
210   while (conn) {
211     if (mutt_account_match (account, &(conn->account)))
212       return conn;
213     conn = conn->next;
214   }
215
216   conn = socket_new_conn ();
217   memcpy (&conn->account, account, sizeof (ACCOUNT));
218
219   conn->next = Connections;
220   Connections = conn;
221
222   if (Tunnel && *Tunnel)
223     mutt_tunnel_socket_setup (conn);
224   else if (account->flags & M_ACCT_SSL) {
225 #if defined (USE_SSL) || defined (USE_GNUTLS)
226     if (mutt_ssl_socket_setup (conn) < 0) {
227       mutt_socket_free (conn);
228       return NULL;
229     }
230 #else
231     mutt_error _("SSL is unavailable.");
232
233     mutt_sleep (2);
234     mutt_socket_free (conn);
235
236     return NULL;
237 #endif
238   }
239   else {
240     conn->conn_read = raw_socket_read;
241     conn->conn_write = raw_socket_write;
242     conn->conn_open = raw_socket_open;
243     conn->conn_close = raw_socket_close;
244   }
245
246   return conn;
247 }
248
249 static int socket_preconnect (void)
250 {
251   int rc;
252   int save_errno;
253
254   if (m_strlen(Preconnect)) {
255     rc = mutt_system (Preconnect);
256     if (rc) {
257       save_errno = errno;
258       mutt_perror (_("Preconnect command failed."));
259       mutt_sleep (1);
260
261       return save_errno;
262     }
263   }
264
265   return 0;
266 }
267
268 /* socket_connect: set up to connect to a socket fd. */
269 static int socket_connect (int fd, struct sockaddr *sa)
270 {
271   int sa_size;
272   int save_errno;
273
274   if (sa->sa_family == AF_INET)
275     sa_size = sizeof (struct sockaddr_in);
276 #ifdef HAVE_GETADDRINFO
277   else if (sa->sa_family == AF_INET6)
278     sa_size = sizeof (struct sockaddr_in6);
279 #endif
280   else {
281     return -1;
282   }
283
284   if (ConnectTimeout > 0)
285     alarm (ConnectTimeout);
286
287   mutt_allow_interrupt (1);
288
289   save_errno = 0;
290
291   if (connect (fd, sa, sa_size) < 0) {
292     save_errno = errno;
293     SigInt = 0;                 /* reset in case we caught SIGINTR while in connect() */
294   }
295
296   if (ConnectTimeout > 0)
297     alarm (0);
298   mutt_allow_interrupt (0);
299
300   return save_errno;
301 }
302
303 /* socket_new_conn: allocate and initialise a new connection. */
304 static CONNECTION *socket_new_conn (void)
305 {
306   CONNECTION *conn;
307
308   conn = p_new(CONNECTION, 1);
309   conn->fd = -1;
310
311   return conn;
312 }
313
314 int raw_socket_close (CONNECTION * conn)
315 {
316   return close (conn->fd);
317 }
318
319 int raw_socket_read (CONNECTION * conn, char *buf, ssize_t len)
320 {
321   int rc;
322
323   if ((rc = read (conn->fd, buf, len)) == -1) {
324     mutt_error (_("Error talking to %s (%s)"), conn->account.host,
325                 strerror (errno));
326     mutt_sleep (2);
327   }
328
329   return rc;
330 }
331
332 int raw_socket_write (CONNECTION * conn, const char *buf, ssize_t count)
333 {
334   int rc;
335
336   if ((rc = write (conn->fd, buf, count)) == -1) {
337     mutt_error (_("Error talking to %s (%s)"), conn->account.host,
338                 strerror (errno));
339     mutt_sleep (2);
340   }
341
342   return rc;
343 }
344
345 int raw_socket_open (CONNECTION * conn)
346 {
347   int rc;
348   int fd;
349
350   char *host_idna = NULL;
351
352 #ifdef HAVE_GETADDRINFO
353 /* --- IPv4/6 --- */
354
355   /* "65536\0" */
356   char port[6];
357   struct addrinfo hints;
358   struct addrinfo *res;
359   struct addrinfo *cur;
360
361   /* we accept v4 or v6 STREAM sockets */
362   p_clear(&hints, 1);
363
364   if (option (OPTUSEIPV6))
365     hints.ai_family = AF_UNSPEC;
366   else
367     hints.ai_family = AF_INET;
368
369   hints.ai_socktype = SOCK_STREAM;
370
371   snprintf (port, sizeof (port), "%d", conn->account.port);
372
373 # ifdef HAVE_LIBIDN
374   if (idna_to_ascii_lz (conn->account.host, &host_idna, 1) != IDNA_SUCCESS) {
375     mutt_error (_("Bad IDN \"%s\"."), conn->account.host);
376     return -1;
377   }
378 # else
379   host_idna = conn->account.host;
380 # endif
381
382   mutt_message (_("Looking up %s..."), conn->account.host);
383
384
385   rc = getaddrinfo (host_idna, port, &hints, &res);
386
387 # ifdef HAVE_LIBIDN
388   p_delete(&host_idna);
389 # endif
390
391   if (rc) {
392     mutt_error (_("Could not find the host \"%s\""), conn->account.host);
393     mutt_sleep (2);
394     return -1;
395   }
396
397   mutt_message (_("Connecting to %s..."), conn->account.host);
398
399   rc = -1;
400   for (cur = res; cur != NULL; cur = cur->ai_next) {
401     fd = socket (cur->ai_family, cur->ai_socktype, cur->ai_protocol);
402     if (fd >= 0) {
403       if ((rc = socket_connect (fd, cur->ai_addr)) == 0) {
404         fcntl (fd, F_SETFD, FD_CLOEXEC);
405         conn->fd = fd;
406         break;
407       }
408       else
409         close (fd);
410     }
411   }
412
413   freeaddrinfo (res);
414
415 #else
416   /* --- IPv4 only --- */
417
418   struct sockaddr_in sin;
419   struct hostent *he;
420   int i;
421
422   p_clear(&sin, 1);
423   sin.sin_port = htons (conn->account.port);
424   sin.sin_family = AF_INET;
425
426 # ifdef HAVE_LIBIDN
427   if (idna_to_ascii_lz (conn->account.host, &host_idna, 1) != IDNA_SUCCESS) {
428     mutt_error (_("Bad IDN \"%s\"."), conn->account.host);
429     return -1;
430   }
431 # else
432   host_idna = conn->account.host;
433 # endif
434
435   mutt_message (_("Looking up %s..."), conn->account.host);
436
437   if ((he = gethostbyname (host_idna)) == NULL) {
438 # ifdef HAVE_LIBIDN
439     p_delete(&host_idna);
440 # endif
441     mutt_error (_("Could not find the host \"%s\""), conn->account.host);
442
443     return -1;
444   }
445
446 # ifdef HAVE_LIBIDN
447   p_delete(&host_idna);
448 # endif
449
450   mutt_message (_("Connecting to %s..."), conn->account.host);
451
452   rc = -1;
453   for (i = 0; he->h_addr_list[i] != NULL; i++) {
454     memcpy (&sin.sin_addr, he->h_addr_list[i], he->h_length);
455     fd = socket (PF_INET, SOCK_STREAM, IPPROTO_IP);
456
457     if (fd >= 0) {
458       if ((rc = socket_connect (fd, (struct sockaddr *) &sin)) == 0) {
459         fcntl (fd, F_SETFD, FD_CLOEXEC);
460         conn->fd = fd;
461         break;
462       }
463       else
464         close (fd);
465     }
466   }
467
468 #endif
469   if (rc) {
470     mutt_error (_("Could not connect to %s (%s)."), conn->account.host,
471                 (rc > 0) ? strerror (rc) : _("unknown error"));
472     mutt_sleep (2);
473     return -1;
474   }
475
476   return 0;
477 }