ViewVC Help
View File | Revision Log | Show Annotations | View Changeset | Root Listing
root/svn/ircd-hybrid/trunk/src/s_bsd.c
Revision: 8500
Committed: Thu Apr 5 13:00:49 2018 UTC (8 years, 5 months ago) by michael
Content type: text/x-csrc
File size: 18103 byte(s)
Error occurred while calculating annotation data.
Log Message:
- Killed Connection::aftype. Use Client::ip.ss.ss_family instead.

File Contents

# Content
1 /*
2 * ircd-hybrid: an advanced, lightweight Internet Relay Chat Daemon (ircd)
3 *
4 * Copyright (c) 1997-2018 ircd-hybrid development team
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
19 * USA
20 */
21
22 /*! \file s_bsd.c
23 * \brief Network functions.
24 * \version $Id$
25 */
26
27 #include "stdinc.h"
28 #include <netinet/in_systm.h>
29 #include <netinet/ip.h>
30 #include <netinet/tcp.h>
31 #include "list.h"
32 #include "fdlist.h"
33 #include "s_bsd.h"
34 #include "client.h"
35 #include "dbuf.h"
36 #include "event.h"
37 #include "irc_string.h"
38 #include "ircd.h"
39 #include "listener.h"
40 #include "numeric.h"
41 #include "packet.h"
42 #include "res.h"
43 #include "restart.h"
44 #include "conf.h"
45 #include "log.h"
46 #include "server.h"
47 #include "send.h"
48 #include "memory.h"
49 #include "user.h"
50
51
52 static const char *const comm_err_str[] =
53 {
54 [COMM_OK] = "Comm OK",
55 [COMM_ERR_BIND] = "Error during bind()",
56 [COMM_ERR_DNS] = "Error during DNS lookup",
57 [COMM_ERR_TIMEOUT] = "connect timeout",
58 [COMM_ERR_CONNECT] = "Error during connect()",
59 [COMM_ERROR] = "Comm Error"
60 };
61
62 static void comm_connect_callback(fde_t *, int);
63 static void comm_connect_timeout(fde_t *, void *);
64 static void comm_connect_dns_callback(void *, const struct irc_ssaddr *, const char *, size_t);
65 static void comm_connect_tryconnect(fde_t *, void *);
66
67
68 /* comm_get_sockerr - get the error value from the socket or the current errno
69 *
70 * Get the *real* error from the socket (well try to anyway..).
71 * This may only work when SO_DEBUG is enabled but its worth the
72 * gamble anyway.
73 */
74 int
75 comm_get_sockerr(int fd)
76 {
77 int errtmp = errno;
78 #ifdef SO_ERROR
79 int err = 0;
80 socklen_t len = sizeof(err);
81
82 if (fd > -1 && !getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &len))
83 {
84 if (err)
85 errtmp = err;
86 }
87 errno = errtmp;
88 #endif
89 return errtmp;
90 }
91
92 /*
93 * report_error - report an error from an errno.
94 * Record error to log and also send a copy to all *LOCAL* opers online.
95 *
96 * text is a *format* string for outputing error. It must
97 * contain only two '%s', the first will be replaced
98 * by the sockhost from the client_p, and the latter will
99 * be taken from sys_errlist[errno].
100 *
101 * client_p if not NULL, is the *LOCAL* client associated with
102 * the error.
103 *
104 * Cannot use perror() within daemon. stderr is closed in
105 * ircd and cannot be used. And, worse yet, it might have
106 * been reassigned to a normal connection...
107 *
108 * Actually stderr is still there IFF ircd was run with -s --Rodder
109 */
110 void
111 report_error(int level, const char *text, const char *who, int error)
112 {
113 who = (who) ? who : "";
114
115 sendto_realops_flags(UMODE_DEBUG, level, SEND_NOTICE,
116 text, who, strerror(error));
117 ilog(LOG_TYPE_IRCD, text, who, strerror(error));
118 }
119
120 /*
121 * setup_socket()
122 *
123 * Set the socket non-blocking, and other wonderful bits.
124 */
125 static void
126 setup_socket(int fd)
127 {
128 int opt = 1;
129
130 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof(opt));
131
132 #ifdef IPTOS_LOWDELAY
133 opt = IPTOS_LOWDELAY;
134 setsockopt(fd, IPPROTO_IP, IP_TOS, &opt, sizeof(opt));
135 #endif
136
137 fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK);
138 }
139
140 /*
141 * ssl_handshake - let OpenSSL initialize the protocol. Register for
142 * read/write events if necessary.
143 */
144 static void
145 ssl_handshake(fde_t *F, void *data)
146 {
147 struct Client *client_p = data;
148
149 assert(client_p);
150 assert(client_p->connection);
151 assert(client_p->connection->fd);
152 assert(client_p->connection->fd == F);
153
154 tls_handshake_status_t ret = tls_handshake(&F->ssl, TLS_ROLE_SERVER, NULL);
155 if (ret != TLS_HANDSHAKE_DONE)
156 {
157 if ((CurrentTime - client_p->connection->firsttime) > CONNECTTIMEOUT)
158 {
159 exit_client(client_p, "Timeout during TLS handshake");
160 return;
161 }
162
163 switch (ret)
164 {
165 case TLS_HANDSHAKE_WANT_WRITE:
166 comm_setselect(client_p->connection->fd, COMM_SELECT_WRITE,
167 ssl_handshake, client_p, CONNECTTIMEOUT);
168 return;
169 case TLS_HANDSHAKE_WANT_READ:
170 comm_setselect(client_p->connection->fd, COMM_SELECT_READ,
171 ssl_handshake, client_p, CONNECTTIMEOUT);
172 return;
173 default:
174 exit_client(client_p, "Error during TLS handshake");
175 return;
176 }
177 }
178
179 comm_settimeout(F, 0, NULL, NULL);
180
181 if (!tls_verify_cert(&F->ssl, ConfigServerInfo.message_digest_algorithm, &client_p->certfp))
182 ilog(LOG_TYPE_IRCD, "Client %s!%s@%s gave bad TLS client certificate",
183 client_p->name, client_p->username, client_p->host);
184
185 auth_start(client_p);
186 }
187
188 /*
189 * add_connection - creates a client which has just connected to us on
190 * the given fd. The sockhost field is initialized with the ip# of the host.
191 * An unique id is calculated now, in case it is needed for auth.
192 * The client is sent to the auth module for verification, and not put in
193 * any client list yet.
194 */
195 void
196 add_connection(struct Listener *listener, struct irc_ssaddr *irn, int fd)
197 {
198 struct Client *client_p = client_make(NULL);
199
200 client_p->connection->fd = fd_open(fd, 1, (listener->flags & LISTENER_SSL) ?
201 "Incoming SSL connection" : "Incoming connection");
202
203 /*
204 * copy address to 'sockhost' as a string, copy it to host too
205 * so we have something valid to put into error messages...
206 */
207 memcpy(&client_p->ip, irn, sizeof(client_p->ip));
208
209 getnameinfo((const struct sockaddr *)&client_p->ip,
210 client_p->ip.ss_len, client_p->sockhost,
211 sizeof(client_p->sockhost), NULL, 0, NI_NUMERICHOST);
212
213 if (client_p->sockhost[0] == ':')
214 {
215 client_p->sockhost[0] = '0';
216 memmove(client_p->sockhost + 1, client_p->sockhost, sizeof(client_p->sockhost) - 1);
217 }
218
219 strlcpy(client_p->host, client_p->sockhost, sizeof(client_p->host));
220
221 client_p->connection->listener = listener;
222 ++listener->ref_count;
223
224 if (listener->flags & LISTENER_SSL)
225 {
226 if (!tls_new(&client_p->connection->fd->ssl, fd, TLS_ROLE_SERVER))
227 {
228 SetDead(client_p);
229 exit_client(client_p, "TLS context initialization failed");
230 return;
231 }
232
233 AddFlag(client_p, FLAGS_SSL);
234 ssl_handshake(client_p->connection->fd, client_p);
235 }
236 else
237 auth_start(client_p);
238 }
239
240 /*
241 * stolen from squid - its a neat (but overused! :) routine which we
242 * can use to see whether we can ignore this errno or not. It is
243 * generally useful for non-blocking network IO related errnos.
244 * -- adrian
245 */
246 int
247 comm_ignore_errno(int ierrno)
248 {
249 switch (ierrno)
250 {
251 case EINPROGRESS:
252 case EWOULDBLOCK:
253 #if EAGAIN != EWOULDBLOCK
254 case EAGAIN:
255 #endif
256 case EALREADY:
257 case EINTR:
258 #ifdef ERESTART
259 case ERESTART:
260 #endif
261 return 1;
262 default:
263 return 0;
264 }
265 }
266
267 /*
268 * comm_settimeout() - set the socket timeout
269 *
270 * Set the timeout for the fd
271 */
272 void
273 comm_settimeout(fde_t *F, uintmax_t timeout, void (*callback)(fde_t *, void *), void *cbdata)
274 {
275 assert(F->flags.open);
276
277 F->timeout = CurrentTime + (timeout / 1000);
278 F->timeout_handler = callback;
279 F->timeout_data = cbdata;
280 }
281
282 /*
283 * comm_setflush() - set a flush function
284 *
285 * A flush function is simply a function called if found during
286 * comm_timeouts(). Its basically a second timeout, except in this case
287 * I'm too lazy to implement multiple timeout functions! :-)
288 * its kinda nice to have it separate, since this is designed for
289 * flush functions, and when comm_close() is implemented correctly
290 * with close functions, we _actually_ don't call comm_close() here ..
291 * -- originally Adrian's notes
292 * comm_close() is replaced with fd_close() in fdlist.c
293 */
294 void
295 comm_setflush(fde_t *F, uintmax_t timeout, void (*callback)(fde_t *, void *), void *cbdata)
296 {
297 assert(F->flags.open);
298
299 F->flush_timeout = CurrentTime + (timeout / 1000);
300 F->flush_handler = callback;
301 F->flush_data = cbdata;
302 }
303
304 /*
305 * comm_checktimeouts() - check the socket timeouts
306 *
307 * All this routine does is call the given callback/cbdata, without closing
308 * down the file descriptor. When close handlers have been implemented,
309 * this will happen.
310 */
311 void
312 comm_checktimeouts(void *unused)
313 {
314 void (*hdl)(fde_t *, void *);
315 void *data;
316
317 for (int fd = 0; fd <= highest_fd; ++fd)
318 {
319 fde_t *F = &fd_table[fd];
320
321 if (F->flags.open == 0)
322 continue;
323
324 /* check flush functions */
325 if (F->flush_handler && F->flush_timeout > 0 &&
326 F->flush_timeout < CurrentTime)
327 {
328 hdl = F->flush_handler;
329 data = F->flush_data;
330
331 comm_setflush(F, 0, NULL, NULL);
332 hdl(F, data);
333 }
334
335 /* check timeouts */
336 if (F->timeout_handler && F->timeout > 0 &&
337 F->timeout < CurrentTime)
338 {
339 /* Call timeout handler */
340 hdl = F->timeout_handler;
341 data = F->timeout_data;
342
343 comm_settimeout(F, 0, NULL, NULL);
344 hdl(F, data);
345 }
346 }
347 }
348
349 /*
350 * void comm_connect_tcp(int fd, const char *host, unsigned short port,
351 * struct sockaddr *clocal, int socklen,
352 * CNCB *callback, void *data, int aftype, int timeout)
353 * Input: An fd to connect with, a host and port to connect to,
354 * a local sockaddr to connect from + length(or NULL to use the
355 * default), a callback, the data to pass into the callback, the
356 * address family.
357 * Output: None.
358 * Side-effects: A non-blocking connection to the host is started, and
359 * if necessary, set up for selection. The callback given
360 * may be called now, or it may be called later.
361 */
362 void
363 comm_connect_tcp(fde_t *F, const char *host, unsigned short port, struct sockaddr *clocal,
364 int socklen, void (*callback)(fde_t *, int, void *), void *data,
365 int aftype, uintmax_t timeout)
366 {
367 struct addrinfo hints, *res;
368 char portname[PORTNAMELEN + 1];
369
370 assert(callback);
371 F->connect.callback = callback;
372 F->connect.data = data;
373
374 F->connect.hostaddr.ss.ss_family = aftype;
375 F->connect.hostaddr.ss_port = htons(port);
376
377 /* Note that we're using a passed sockaddr here. This is because
378 * generally you'll be bind()ing to a sockaddr grabbed from
379 * getsockname(), so this makes things easier.
380 * XXX If NULL is passed as local, we should later on bind() to the
381 * virtual host IP, for completeness.
382 * -- adrian
383 */
384 if (clocal && bind(F->fd, clocal, socklen) < 0)
385 {
386 /* Failure, call the callback with COMM_ERR_BIND */
387 comm_connect_callback(F, COMM_ERR_BIND);
388 return; /* ... and quit */
389 }
390
391 memset(&hints, 0, sizeof(hints));
392
393 hints.ai_family = AF_UNSPEC;
394 hints.ai_socktype = SOCK_STREAM;
395 hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
396
397 snprintf(portname, sizeof(portname), "%d", port);
398
399 /*
400 * Next, if we have been given an IP address, get the address and skip the
401 * DNS check (and head direct to comm_connect_tryconnect()).
402 */
403 if (getaddrinfo(host, portname, &hints, &res))
404 {
405 /* Send the DNS request, for the next level */
406 if (aftype == AF_INET6)
407 gethost_byname_type(comm_connect_dns_callback, F, host, T_AAAA);
408 else
409 gethost_byname_type(comm_connect_dns_callback, F, host, T_A);
410 }
411 else
412 {
413 /* We have a valid IP, so we just call tryconnect */
414 /* Make sure we actually set the timeout here .. */
415 assert(res);
416
417 memcpy(&F->connect.hostaddr, res->ai_addr, res->ai_addrlen);
418 F->connect.hostaddr.ss_len = res->ai_addrlen;
419 F->connect.hostaddr.ss.ss_family = res->ai_family;
420
421 freeaddrinfo(res);
422
423 comm_settimeout(F, timeout * 1000, comm_connect_timeout, NULL);
424 comm_connect_tryconnect(F, NULL);
425 }
426 }
427
428 /*
429 * comm_connect_callback() - call the callback, and continue with life
430 */
431 static void
432 comm_connect_callback(fde_t *F, int status)
433 {
434 void (*hdl)(fde_t *, int, void *);
435
436 /* This check is gross..but probably necessary */
437 if (F->connect.callback == NULL)
438 return;
439
440 /* Clear the connect flag + handler */
441 hdl = F->connect.callback;
442 F->connect.callback = NULL;
443
444 /* Clear the timeout handler */
445 comm_settimeout(F, 0, NULL, NULL);
446
447 /* Call the handler */
448 hdl(F, status, F->connect.data);
449 }
450
451 /*
452 * comm_connect_timeout() - this gets called when the socket connection
453 * times out. This *only* can be called once connect() is initially
454 * called ..
455 */
456 static void
457 comm_connect_timeout(fde_t *F, void *unused)
458 {
459 /* error! */
460 comm_connect_callback(F, COMM_ERR_TIMEOUT);
461 }
462
463 /*
464 * comm_connect_dns_callback() - called at the completion of the DNS request
465 *
466 * The DNS request has completed, so if we've got an error, return it,
467 * otherwise we initiate the connect()
468 */
469 static void
470 comm_connect_dns_callback(void *vptr, const struct irc_ssaddr *addr, const char *name, size_t namelength)
471 {
472 fde_t *const F = vptr;
473
474 if (!addr)
475 {
476 comm_connect_callback(F, COMM_ERR_DNS);
477 return;
478 }
479
480 /* No error, set a 30 second timeout */
481 comm_settimeout(F, 30 * 1000, comm_connect_timeout, NULL);
482
483 /* Copy over the DNS reply info so we can use it in the connect() */
484 /*
485 * Note we don't fudge the refcount here, because we aren't keeping
486 * the DNS record around, and the DNS cache is gone anyway..
487 * -- adrian
488 */
489 memcpy(&F->connect.hostaddr, addr, addr->ss_len);
490
491 /* The cast is hacky, but safe - port offset is same on v4 and v6 */
492 ((struct sockaddr_in *)&F->connect.hostaddr)->sin_port = F->connect.hostaddr.ss_port;
493 F->connect.hostaddr.ss_len = addr->ss_len;
494
495 /* Now, call the tryconnect() routine to try a connect() */
496 comm_connect_tryconnect(F, NULL);
497 }
498
499 /* static void comm_connect_tryconnect(fde_t *fd, void *unused)
500 * Input: The fd, the handler data(unused).
501 * Output: None.
502 * Side-effects: Try and connect with pending connect data for the FD. If
503 * we succeed or get a fatal error, call the callback.
504 * Otherwise, it is still blocking or something, so register
505 * to select for a write event on this FD.
506 */
507 static void
508 comm_connect_tryconnect(fde_t *F, void *unused)
509 {
510 /* This check is needed or re-entrant s_bsd_* like sigio break it. */
511 if (F->connect.callback == NULL)
512 return;
513
514 /* Try the connect() */
515 int retval = connect(F->fd, (struct sockaddr *)&F->connect.hostaddr, F->connect.hostaddr.ss_len);
516
517 /* Error? */
518 if (retval < 0)
519 {
520 /*
521 * If we get EISCONN, then we've already connect()ed the socket,
522 * which is a good thing.
523 * -- adrian
524 */
525 if (errno == EISCONN)
526 comm_connect_callback(F, COMM_OK);
527 else if (comm_ignore_errno(errno))
528 /* Ignore error? Reschedule */
529 comm_setselect(F, COMM_SELECT_WRITE, comm_connect_tryconnect, NULL, 0);
530 else
531 /* Error? Fail with COMM_ERR_CONNECT */
532 comm_connect_callback(F, COMM_ERR_CONNECT);
533 return;
534 }
535
536 /* If we get here, we've suceeded, so call with COMM_OK */
537 comm_connect_callback(F, COMM_OK);
538 }
539
540 /*
541 * comm_errorstr() - return an error string for the given error condition
542 */
543 const char *
544 comm_errstr(int error)
545 {
546 if (error < 0 || error >= COMM_ERR_MAX)
547 return "Invalid error number!";
548 return comm_err_str[error];
549 }
550
551 /*
552 * comm_open() - open a socket
553 *
554 * This is a highly highly cut down version of squid's comm_open() which
555 * for the most part emulates socket(), *EXCEPT* it fails if we're about
556 * to run out of file descriptors.
557 */
558 int
559 comm_socket(int family, int sock_type, int proto)
560 {
561 /* First, make sure we aren't going to run out of file descriptors */
562 if (number_fd >= hard_fdlimit)
563 {
564 errno = ENFILE;
565 return -1;
566 }
567
568 /*
569 * Next, we try to open the socket. We *should* drop the reserved FD
570 * limit if/when we get an error, but we can deal with that later.
571 * XXX !!! -- adrian
572 */
573 int fd = socket(family, sock_type, proto);
574 if (fd < 0)
575 return -1; /* errno will be passed through, yay.. */
576
577 setup_socket(fd);
578
579 return fd;
580 }
581
582 /*
583 * comm_accept() - accept an incoming connection
584 *
585 * This is a simple wrapper for accept() which enforces FD limits like
586 * comm_open() does. Returned fd must be either closed or tagged with
587 * fd_open (this function no longer does it).
588 */
589 int
590 comm_accept(int fd, struct irc_ssaddr *addr)
591 {
592 socklen_t addrlen = sizeof(struct irc_ssaddr);
593
594 if (number_fd >= hard_fdlimit)
595 {
596 errno = ENFILE;
597 return -1;
598 }
599
600 memset(addr, 0, sizeof(*addr));
601
602 /*
603 * Next, do the accept(). if we get an error, we should drop the
604 * reserved fd limit, but we can deal with that when comm_open()
605 * also does it. XXX -- adrian
606 */
607 int new_fd = accept(fd, (struct sockaddr *)addr, &addrlen);
608 if (new_fd < 0)
609 return -1;
610
611 remove_ipv6_mapping(addr);
612
613 setup_socket(new_fd);
614
615 /* .. and return */
616 return new_fd;
617 }
618
619 /*
620 * remove_ipv6_mapping() - Removes IPv4-In-IPv6 mapping from an address
621 * OSes with IPv6 mapping listening on both
622 * AF_INET and AF_INET6 map AF_INET connections inside AF_INET6 structures
623 *
624 */
625 void
626 remove_ipv6_mapping(struct irc_ssaddr *addr)
627 {
628 if (addr->ss.ss_family == AF_INET6)
629 {
630 if (IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)addr)->sin6_addr))
631 {
632 struct sockaddr_in6 v6;
633 struct sockaddr_in *v4 = (struct sockaddr_in *)addr;
634
635 memcpy(&v6, addr, sizeof(v6));
636 memset(v4, 0, sizeof(struct sockaddr_in));
637 memcpy(&v4->sin_addr, &v6.sin6_addr.s6_addr[12], sizeof(v4->sin_addr));
638
639 addr->ss.ss_family = AF_INET;
640 addr->ss_len = sizeof(struct sockaddr_in);
641 }
642 else
643 addr->ss_len = sizeof(struct sockaddr_in6);
644 }
645 else
646 addr->ss_len = sizeof(struct sockaddr_in);
647 }

Properties

Name Value
svn:eol-style native
svn:keywords Id