ViewVC Help
View File | Revision Log | Show Annotations | View Changeset | Root Listing
root/svn/ircd-hybrid/trunk/src/s_bsd.c
Revision: 8414
Committed: Thu Mar 22 18:11:39 2018 UTC (8 years, 6 months ago) by michael
Content type: text/x-csrc
File size: 18236 byte(s)
Log Message:
- Rename some functions to comply with naming convention

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

Properties

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