Copyright year updates:
[exim.git] / src / src / ip.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) University of Cambridge 1995 - 2014 */
6 /* See the file NOTICE for conditions of use and distribution. */
7
8 /* Functions for doing things with sockets. With the advent of IPv6 this has
9 got messier, so that it's worth pulling out the code into separate functions
10 that other parts of Exim can call, expecially as there are now several
11 different places in the code where sockets are used. */
12
13
14 #include "exim.h"
15
16
17 /*************************************************
18 *             Create a socket                    *
19 *************************************************/
20
21 /* Socket creation happens in a number of places so it's packaged here for
22 convenience.
23
24 Arguments:
25   type       SOCK_DGRAM or SOCK_STREAM
26   af         AF_INET or AF_INET6
27
28 Returns:     socket number or -1 on failure
29 */
30
31 int
32 ip_socket(int type, int af)
33 {
34 int sock = socket(af, type, 0);
35 if (sock < 0)
36   log_write(0, LOG_MAIN, "IPv%c socket creation failed: %s",
37     (af == AF_INET6)? '6':'4', strerror(errno));
38 return sock;
39 }
40
41
42
43
44 #if HAVE_IPV6
45 /*************************************************
46 *      Convert printing address to numeric       *
47 *************************************************/
48
49 /* This function converts the textual form of an IP address into a numeric form
50 in an appropriate structure in an IPv6 environment. The getaddrinfo() function
51 can (apparently) handle more complicated addresses (e.g. those containing
52 scopes) than inet_pton() in some environments. We use hints to tell it that the
53 input must be a numeric address.
54
55 However, apparently some operating systems (or libraries) don't support
56 getaddrinfo(), so there is a build-time option to revert to inet_pton() (which
57 does not support scopes).
58
59 Arguments:
60   address     textual form of the address
61   addr        where to copy back the answer
62
63 Returns:      nothing - failure provokes a panic-die
64 */
65
66 static void
67 ip_addrinfo(uschar *address, struct sockaddr_in6 *saddr)
68 {
69 #ifdef IPV6_USE_INET_PTON
70
71   if (inet_pton(AF_INET6, CS address, &saddr->sin6_addr) != 1)
72     log_write(0, LOG_MAIN|LOG_PANIC_DIE, "unable to parse \"%s\" as an "
73       "IP address", address);
74   saddr->sin6_family = AF_INET6;
75
76 #else
77
78   int rc;
79   struct addrinfo hints, *res;
80   memset(&hints, 0, sizeof(hints));
81   hints.ai_family = AF_INET6;
82   hints.ai_socktype = SOCK_STREAM;
83   hints.ai_flags = AI_NUMERICHOST;
84   if ((rc = getaddrinfo(CS address, NULL, &hints, &res)) != 0 || res == NULL)
85     log_write(0, LOG_MAIN|LOG_PANIC_DIE, "unable to parse \"%s\" as an "
86       "IP address: %s", address,
87       (rc == 0)? "NULL result returned" : gai_strerror(rc));
88   memcpy(saddr, res->ai_addr, res->ai_addrlen);
89   freeaddrinfo(res);
90
91 #endif
92 }
93 #endif  /* HAVE_IPV6 */
94
95
96 /*************************************************
97 *         Bind socket to interface and port      *
98 *************************************************/
99
100 /* This function binds a socket to a local interface address and port. For a
101 wildcard IPv6 bind, the address is ":".
102
103 Arguments:
104   sock           the socket
105   af             AF_INET or AF_INET6 - the socket type
106   address        the IP address, in text form
107   port           the IP port (host order)
108
109 Returns:         the result of bind()
110 */
111
112 int
113 ip_bind(int sock, int af, uschar *address, int port)
114 {
115 int s_len;
116 union sockaddr_46 sin;
117 memset(&sin, 0, sizeof(sin));
118
119 /* Setup code when using an IPv6 socket. The wildcard address is ":", to
120 ensure an IPv6 socket is used. */
121
122 #if HAVE_IPV6
123 if (af == AF_INET6)
124   {
125   if (address[0] == ':' && address[1] == 0)
126     {
127     sin.v6.sin6_family = AF_INET6;
128     sin.v6.sin6_addr = in6addr_any;
129     }
130   else
131     {
132     ip_addrinfo(address, &sin.v6);  /* Panic-dies on error */
133     }
134   sin.v6.sin6_port = htons(port);
135   s_len = sizeof(sin.v6);
136   }
137 else
138 #else     /* HAVE_IPv6 */
139 af = af;  /* Avoid compiler warning */
140 #endif    /* HAVE_IPV6 */
141
142 /* Setup code when using IPv4 socket. The wildcard address is "". */
143
144   {
145   sin.v4.sin_family = AF_INET;
146   sin.v4.sin_port = htons(port);
147   s_len = sizeof(sin.v4);
148   if (address[0] == 0)
149     sin.v4.sin_addr.s_addr = (S_ADDR_TYPE)INADDR_ANY;
150   else
151     sin.v4.sin_addr.s_addr = (S_ADDR_TYPE)inet_addr(CS address);
152   }
153
154 /* Now we can call the bind() function */
155
156 return bind(sock, (struct sockaddr *)&sin, s_len);
157 }
158
159
160
161 /*************************************************
162 *        Connect socket to remote host           *
163 *************************************************/
164
165 /* This function connects a socket to a remote address and port. The socket may
166 or may not have previously been bound to a local interface. The socket is not
167 closed, even in cases of error. It is expected that the calling function, which
168 created the socket, will be the one that closes it.
169
170 Arguments:
171   sock        the socket
172   af          AF_INET6 or AF_INET for the socket type
173   address     the remote address, in text form
174   port        the remote port
175   timeout     a timeout (zero for indefinite timeout)
176
177 Returns:      0 on success; -1 on failure, with errno set
178 */
179
180 int
181 ip_connect(int sock, int af, uschar *address, int port, int timeout)
182 {
183 struct sockaddr_in s_in4;
184 struct sockaddr *s_ptr;
185 int s_len, rc, save_errno;
186
187 /* For an IPv6 address, use an IPv6 sockaddr structure. */
188
189 #if HAVE_IPV6
190 struct sockaddr_in6 s_in6;
191 if (af == AF_INET6)
192   {
193   memset(&s_in6, 0, sizeof(s_in6));
194   ip_addrinfo(address, &s_in6);   /* Panic-dies on error */
195   s_in6.sin6_port = htons(port);
196   s_ptr = (struct sockaddr *)&s_in6;
197   s_len = sizeof(s_in6);
198   }
199 else
200 #else     /* HAVE_IPV6 */
201 af = af;  /* Avoid compiler warning */
202 #endif    /* HAVE_IPV6 */
203
204 /* For an IPv4 address, use an IPv4 sockaddr structure, even on a system with
205 IPv6 support. */
206
207   {
208   memset(&s_in4, 0, sizeof(s_in4));
209   s_in4.sin_family = AF_INET;
210   s_in4.sin_port = htons(port);
211   s_in4.sin_addr.s_addr = (S_ADDR_TYPE)inet_addr(CS address);
212   s_ptr = (struct sockaddr *)&s_in4;
213   s_len = sizeof(s_in4);
214   }
215
216 /* If no connection timeout is set, just call connect() without setting a
217 timer, thereby allowing the inbuilt OS timeout to operate. */
218
219 sigalrm_seen = FALSE;
220 if (timeout > 0) alarm(timeout);
221 rc = connect(sock, s_ptr, s_len);
222 save_errno = errno;
223 alarm(0);
224
225 /* There is a testing facility for simulating a connection timeout, as I
226 can't think of any other way of doing this. It converts a connection refused
227 into a timeout if the timeout is set to 999999. */
228
229 if (running_in_test_harness)
230   {
231   if (save_errno == ECONNREFUSED && timeout == 999999)
232     {
233     rc = -1;
234     save_errno = EINTR;
235     sigalrm_seen = TRUE;
236     }
237   }
238
239 /* Success */
240
241 if (rc >= 0) return 0;
242
243 /* A failure whose error code is "Interrupted system call" is in fact
244 an externally applied timeout if the signal handler has been run. */
245
246 errno = (save_errno == EINTR && sigalrm_seen)? ETIMEDOUT : save_errno;
247 return -1;
248 }
249
250
251 /* Create a socket and connect to host (name or number, ipv6 ok)
252    at one of port-range.
253 Arguments:
254   type          SOCK_DGRAM or SOCK_STREAM
255   af            AF_INET6 or AF_INET for the socket type
256   address       the remote address, in text form
257   portlo,porthi the remote port range
258   timeout       a timeout
259   connhost      if not NULL, host_item filled in with connection details
260   errstr        pointer for allocated string on error
261
262 Return:
263   socket fd, or -1 on failure (having allocated an error string)
264 */
265 int
266 ip_connectedsocket(int type, const uschar * hostname, int portlo, int porthi,
267         int timeout, host_item * connhost, uschar ** errstr)
268 {
269 int namelen, port;
270 host_item shost;
271 host_item *h;
272 int af = 0, fd, fd4 = -1, fd6 = -1;
273
274 shost.next = NULL;
275 shost.address = NULL;
276 shost.port = portlo;
277 shost.mx = -1;
278
279 namelen = Ustrlen(hostname);
280
281 /* Anything enclosed in [] must be an IP address. */
282
283 if (hostname[0] == '[' &&
284     hostname[namelen - 1] == ']')
285   {
286   uschar * host = string_copy(hostname);
287   host[namelen - 1] = 0;
288   host++;
289   if (string_is_ip_address(host, NULL) == 0)
290     {
291     *errstr = string_sprintf("malformed IP address \"%s\"", hostname);
292     return -1;
293     }
294   shost.name = shost.address = host;
295   }
296
297 /* Otherwise check for an unadorned IP address */
298
299 else if (string_is_ip_address(hostname, NULL) != 0)
300   shost.name = shost.address = string_copy(hostname);
301
302 /* Otherwise lookup IP address(es) from the name */
303
304 else
305   {
306   shost.name = string_copy(hostname);
307   if (host_find_byname(&shost, NULL, HOST_FIND_QUALIFY_SINGLE, NULL,
308       FALSE) != HOST_FOUND)
309     {
310     *errstr = string_sprintf("no IP address found for host %s", shost.name);
311     return -1;
312     }
313   }
314
315 /* Try to connect to the server - test each IP till one works */
316
317 for (h = &shost; h != NULL; h = h->next)
318   {
319   fd = (Ustrchr(h->address, ':') != 0)
320     ? (fd6 < 0) ? (fd6 = ip_socket(SOCK_STREAM, af = AF_INET6)) : fd6
321     : (fd4 < 0) ? (fd4 = ip_socket(SOCK_STREAM, af = AF_INET )) : fd4;
322
323   if (fd < 0)
324     {
325     *errstr = string_sprintf("failed to create socket: %s", strerror(errno));
326     goto bad;
327     }
328
329   for(port = portlo; port <= porthi; port++)
330     if (ip_connect(fd, af, h->address, port, timeout) == 0)
331       {
332       if (fd != fd6) close(fd6);
333       if (fd != fd4) close(fd4);
334       if (connhost) {
335         h->port = port;
336         *connhost = *h;
337         connhost->next = NULL;
338         }
339       return fd;
340       }
341   }
342
343 *errstr = string_sprintf("failed to connect to "
344   "%s: couldn't connect to any host", hostname, strerror(errno));
345
346 bad:
347   close(fd4); close(fd6); return -1;
348 }
349
350
351 /*************************************************
352 *         Set keepalive on a socket              *
353 *************************************************/
354
355 /* Can be called for both incoming and outgoing sockets.
356
357 Arguments:
358   sock       the socket
359   address    the remote host address, for failure logging
360   torf       true for outgoing connection, false for incoming
361
362 Returns:     nothing
363 */
364
365 void
366 ip_keepalive(int sock, uschar *address, BOOL torf)
367 {
368 int fodder = 1;
369 if (setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE,
370     (uschar *)(&fodder), sizeof(fodder)) != 0)
371   log_write(0, LOG_MAIN, "setsockopt(SO_KEEPALIVE) on connection %s %s "
372     "failed: %s", torf? "to":"from", address, strerror(errno));
373 }
374
375
376
377 /*************************************************
378 *         Receive from a socket with timeout     *
379 *************************************************/
380
381 /* The timeout is implemented using select(), and we loop to cover select()
382 getting interrupted, and the possibility of select() returning with a positive
383 result but no ready descriptor. Is this in fact possible?
384
385 Arguments:
386   sock        the socket
387   buffer      to read into
388   bufsize     the buffer size
389   timeout     the timeout
390
391 Returns:      > 0 => that much data read
392               <= 0 on error or EOF; errno set - zero for EOF
393 */
394
395 int
396 ip_recv(int sock, uschar *buffer, int buffsize, int timeout)
397 {
398 fd_set select_inset;
399 struct timeval tv;
400 int start_recv = time(NULL);
401 int rc;
402
403 /* Wait until the socket is ready */
404
405 for (;;)
406   {
407   FD_ZERO (&select_inset);
408   FD_SET (sock, &select_inset);
409   tv.tv_sec = timeout;
410   tv.tv_usec = 0;
411
412   DEBUG(D_transport) debug_printf("waiting for data on socket\n");
413   rc = select(sock + 1, (SELECT_ARG2_TYPE *)&select_inset, NULL, NULL, &tv);
414
415   /* If some interrupt arrived, just retry. We presume this to be rare,
416   but it can happen (e.g. the SIGUSR1 signal sent by exiwhat causes
417   select() to exit).
418
419   Aug 2004: Somebody set up a cron job that ran exiwhat every 2 minutes, making
420   the interrupt not at all rare. Since the timeout is typically more than 2
421   minutes, the effect was to block the timeout completely. To prevent this
422   happening again, we do an explicit time test. */
423
424   if (rc < 0 && errno == EINTR)
425     {
426     DEBUG(D_transport) debug_printf("EINTR while waiting for socket data\n");
427     if (time(NULL) - start_recv < timeout) continue;
428     DEBUG(D_transport) debug_printf("total wait time exceeds timeout\n");
429     }
430
431   /* Handle a timeout, and treat any other select error as a timeout, including
432   an EINTR when we have been in this loop for longer than timeout. */
433
434   if (rc <= 0)
435     {
436     errno = ETIMEDOUT;
437     return -1;
438     }
439
440   /* If the socket is ready, break out of the loop. */
441
442   if (FD_ISSET(sock, &select_inset)) break;
443   }
444
445 /* The socket is ready, read from it (via TLS if it's active). On EOF (i.e.
446 close down of the connection), set errno to zero; otherwise leave it alone. */
447
448 #ifdef SUPPORT_TLS
449 if (tls_out.active == sock)
450   rc = tls_read(FALSE, buffer, buffsize);
451 else if (tls_in.active == sock)
452   rc = tls_read(TRUE, buffer, buffsize);
453 else
454 #endif
455   rc = recv(sock, buffer, buffsize, 0);
456
457 if (rc > 0) return rc;
458 if (rc == 0) errno = 0;
459 return -1;
460 }
461
462
463
464
465 /*************************************************
466 *    Lookup address family of potential socket   *
467 *************************************************/
468
469 /* Given a file-descriptor, check to see if it's a socket and, if so,
470 return the address family; detects IPv4 vs IPv6.  If not a socket then
471 return -1.
472
473 The value 0 is typically AF_UNSPEC, which should not be seen on a connected
474 fd.  If the return is -1, the errno will be from getsockname(); probably
475 ENOTSOCK or ECONNRESET.
476
477 Arguments:     socket-or-not fd
478 Returns:       address family or -1
479 */
480
481 int
482 ip_get_address_family(int fd)
483 {
484 struct sockaddr_storage ss;
485 socklen_t sslen = sizeof(ss);
486
487 if (getsockname(fd, (struct sockaddr *) &ss, &sslen) < 0)
488   return -1;
489
490 return (int) ss.ss_family;
491 }
492
493
494
495
496 /*************************************************
497 *       Lookup DSCP settings for a socket        *
498 *************************************************/
499
500 struct dscp_name_tableentry {
501   const uschar *name;
502   int value;
503 };
504 /* Keep both of these tables sorted! */
505 static struct dscp_name_tableentry dscp_table[] = {
506 #ifdef IPTOS_DSCP_AF11
507     { CUS"af11", IPTOS_DSCP_AF11 },
508     { CUS"af12", IPTOS_DSCP_AF12 },
509     { CUS"af13", IPTOS_DSCP_AF13 },
510     { CUS"af21", IPTOS_DSCP_AF21 },
511     { CUS"af22", IPTOS_DSCP_AF22 },
512     { CUS"af23", IPTOS_DSCP_AF23 },
513     { CUS"af31", IPTOS_DSCP_AF31 },
514     { CUS"af32", IPTOS_DSCP_AF32 },
515     { CUS"af33", IPTOS_DSCP_AF33 },
516     { CUS"af41", IPTOS_DSCP_AF41 },
517     { CUS"af42", IPTOS_DSCP_AF42 },
518     { CUS"af43", IPTOS_DSCP_AF43 },
519     { CUS"ef", IPTOS_DSCP_EF },
520 #endif
521 #ifdef IPTOS_LOWCOST
522     { CUS"lowcost", IPTOS_LOWCOST },
523 #endif
524     { CUS"lowdelay", IPTOS_LOWDELAY },
525 #ifdef IPTOS_MINCOST
526     { CUS"mincost", IPTOS_MINCOST },
527 #endif
528     { CUS"reliability", IPTOS_RELIABILITY },
529     { CUS"throughput", IPTOS_THROUGHPUT }
530 };
531 static int dscp_table_size =
532   sizeof(dscp_table) / sizeof(struct dscp_name_tableentry);
533
534 /* DSCP values change by protocol family, and so do the options used for
535 setsockopt(); this utility does all the lookups.  It takes an unexpanded
536 option string, expands it, strips off affix whitespace, then checks if it's
537 a number.  If all of what's left is a number, then that's how the option will
538 be parsed and success/failure is a range check.  If it's not all a number,
539 then it must be a supported keyword.
540
541 Arguments:
542   dscp_name   a string, so far unvalidated
543   af          address_family in use
544   level       setsockopt level to use
545   optname     setsockopt name to use
546   dscp_value  value for dscp_name
547
548 Returns: TRUE if okay to setsockopt(), else FALSE
549
550 *level and *optname may be set even if FALSE is returned
551 */
552
553 BOOL
554 dscp_lookup(const uschar *dscp_name, int af,
555     int *level, int *optname, int *dscp_value)
556 {
557 uschar *dscp_lookup, *p;
558 int first, last;
559 long rawlong;
560
561 if (af == AF_INET)
562   {
563   *level = IPPROTO_IP;
564   *optname = IP_TOS;
565   }
566 #if HAVE_IPV6 && defined(IPV6_TCLASS)
567 else if (af == AF_INET6)
568   {
569   *level = IPPROTO_IPV6;
570   *optname = IPV6_TCLASS;
571   }
572 #endif
573 else
574   {
575   DEBUG(D_transport)
576     debug_printf("Unhandled address family %d in dscp_lookup()\n", af);
577   return FALSE;
578   }
579 if (!dscp_name)
580   {
581   DEBUG(D_transport)
582     debug_printf("[empty DSCP]\n");
583   return FALSE;
584   }
585 dscp_lookup = expand_string(US dscp_name);
586 if (dscp_lookup == NULL || *dscp_lookup == '\0')
587   return FALSE;
588
589 p = dscp_lookup + Ustrlen(dscp_lookup) - 1;
590 while (isspace(*p)) *p-- = '\0';
591 while (isspace(*dscp_lookup) && dscp_lookup < p) dscp_lookup++;
592 if (*dscp_lookup == '\0')
593   return FALSE;
594
595 rawlong = Ustrtol(dscp_lookup, &p, 0);
596 if (p != dscp_lookup && *p == '\0')
597   {
598   /* We have six bits available, which will end up shifted to fit in 0xFC mask.
599   RFC 2597 defines the values unshifted. */
600   if (rawlong < 0 || rawlong > 0x3F)
601     {
602     DEBUG(D_transport)
603       debug_printf("DSCP value %ld out of range, ignored.\n", rawlong);
604     return FALSE;
605     }
606   *dscp_value = rawlong << 2;
607   return TRUE;
608   }
609
610 first = 0;
611 last = dscp_table_size;
612 while (last > first)
613   {
614   int middle = (first + last)/2;
615   int c = Ustrcmp(dscp_lookup, dscp_table[middle].name);
616   if (c == 0)
617     {
618     *dscp_value = dscp_table[middle].value;
619     return TRUE;
620     }
621   else if (c > 0)
622     {
623     first = middle + 1;
624     }
625   else
626     {
627     last = middle;
628     }
629   }
630 return FALSE;
631 }
632
633 void
634 dscp_list_to_stream(FILE *stream)
635 {
636 int i;
637 for (i=0; i < dscp_table_size; ++i)
638   fprintf(stream, "%s\n", dscp_table[i].name);
639 }
640
641
642 /* End of ip.c */