2 * IRC - Internet Relay Chat, ircd/s_bsd.c
3 * Copyright (C) 1990 Jarkko Oikarinen and
4 * University of Oulu, Computing Center
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 1, or (at your option)
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.
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., 675 Mass Ave, Cambridge, MA 02139, USA.
21 * @brief Functions that now (or in the past) relied on BSD APIs.
32 #include "ircd_alloc.h"
34 #include "ircd_features.h"
35 #include "ircd_osdep.h"
36 #include "ircd_reply.h"
37 #include "ircd_snprintf.h"
38 #include "ircd_string.h"
48 #include "querycmds.h"
62 /* #include <assert.h> -- Now using assert in ircd_log.h */
69 #include <sys/ioctl.h>
70 #include <sys/socket.h>
72 #include <sys/utsname.h>
75 /** Array of my own clients, indexed by file descriptor. */
76 struct Client* LocalClientArray[MAXCONNECTIONS];
77 /** Maximum file descriptor in current use. */
79 /** Default local address for outbound IPv4 connections. */
80 struct irc_sockaddr VirtualHost_v4;
81 /** Default local address for outbound IPv6 connections. */
82 struct irc_sockaddr VirtualHost_v6;
83 /** Temporary buffer for reading data from a peer. */
84 static char readbuf[SERVER_TCP_WINDOW];
87 * report_error text constants
89 const char* const ACCEPT_ERROR_MSG = "error accepting connection for %s: %s";
90 const char* const BIND_ERROR_MSG = "bind error for %s: %s";
91 const char* const CONNECT_ERROR_MSG = "connect to host %s failed: %s";
92 const char* const CONNLIMIT_ERROR_MSG = "connect limit exceeded for %s: %s";
93 const char* const LISTEN_ERROR_MSG = "listen error for %s: %s";
94 const char* const NONB_ERROR_MSG = "error setting non-blocking for %s: %s";
95 const char* const PEERNAME_ERROR_MSG = "getpeername failed for %s: %s";
96 const char* const POLL_ERROR_MSG = "poll error for %s: %s";
97 const char* const REGISTER_ERROR_MSG = "registering %s: %s";
98 const char* const REUSEADDR_ERROR_MSG = "error setting SO_REUSEADDR for %s: %s";
99 const char* const SELECT_ERROR_MSG = "select error for %s: %s";
100 const char* const SETBUFS_ERROR_MSG = "error setting buffer size for %s: %s";
101 const char* const SOCKET_ERROR_MSG = "error creating socket for %s: %s";
102 const char* const TOS_ERROR_MSG = "error setting TOS for %s: %s";
105 static void client_sock_callback(struct Event* ev);
106 static void client_timer_callback(struct Event* ev);
110 * Cannot use perror() within daemon. stderr is closed in
111 * ircd and cannot be used. And, worse yet, it might have
112 * been reassigned to a normal connection...
115 /** Replacement for perror(). Record error to log. Send a copy to all
116 * *LOCAL* opers, but only if no errors were sent to them in the last
118 * @param text A *format* string for outputting error. It must contain
119 * only two '%s', the first will be replaced by the sockhost from the
120 * cptr, and the latter will be taken from sys_errlist[errno].
121 * @param who The client associated with the error.
122 * @param err The errno value to display.
124 void report_error(const char* text, const char* who, int err)
126 static time_t last_notice = 0;
127 int errtmp = errno; /* debug may change 'errno' */
128 const char* errmsg = (err) ? strerror(err) : "";
131 errmsg = "Unknown error";
133 if (EmptyString(who))
136 sendto_opmask_butone_ratelimited(0, SNO_OLDSNO, &last_notice, text, who, errmsg);
137 log_write(LS_SOCKET, L_ERROR, 0, text, who, errmsg);
142 /** Called when resolver query finishes. If the DNS lookup was
143 * successful, start the connection; otherwise notify opers of the
145 * @param vptr The struct ConfItem representing the Connect block.
146 * @param hp A pointer to the DNS lookup results (NULL on failure).
148 static void connect_dns_callback(void* vptr, const struct irc_in_addr *addr, const char *h_name)
150 struct ConfItem* aconf = (struct ConfItem*) vptr;
152 aconf->dns_pending = 0;
154 memcpy(&aconf->address, addr, sizeof(aconf->address));
155 connect_server(aconf, 0);
158 sendto_opmask_butone(0, SNO_OLDSNO, "Connect to %s failed: host lookup",
162 /** Closes all file descriptors.
163 * @param close_stderr If non-zero, also close stderr.
165 void close_connections(int close_stderr)
174 for (i = 3; i < MAXCONNECTIONS; ++i)
178 /** Initialize process fd limit to MAXCONNECTIONS.
180 int init_connection_limits(void)
182 int limit = os_set_fdlimit(MAXCONNECTIONS);
186 fprintf(stderr, "error setting max fds to %d: %s\n", limit, strerror(errno));
188 else if (limit > 0) {
189 fprintf(stderr, "ircd fd table too big\nHard Limit: %d IRC max: %d\n",
190 limit, MAXCONNECTIONS);
191 fprintf(stderr, "set MAXCONNECTIONS to a smaller value");
196 /** Set up address and port and make a connection.
197 * @param aconf Provides the connection information.
198 * @param cptr Client structure for the peer.
199 * @return Non-zero on success; zero on failure.
201 static int connect_inet(struct ConfItem* aconf, struct Client* cptr)
203 const struct irc_sockaddr *local;
210 * Might as well get sockhost from here, the connection is attempted
211 * with it so if it fails its useless.
213 if (irc_in_addr_valid(&aconf->origin.addr))
214 local = &aconf->origin;
215 else if (irc_in_addr_is_ipv4(&aconf->address.addr)) {
216 local = &VirtualHost_v4;
219 local = &VirtualHost_v6;
220 cli_fd(cptr) = os_socket(local, SOCK_STREAM, cli_name(cptr), family);
221 if (cli_fd(cptr) < 0)
225 * save connection info in client
227 memcpy(&cli_ip(cptr), &aconf->address.addr, sizeof(cli_ip(cptr)));
228 ircd_ntoa_r(cli_sock_ip(cptr), &cli_ip(cptr));
230 * we want a big buffer for server connections
232 if (!os_set_sockbufs(cli_fd(cptr), feature_int(FEAT_SOCKSENDBUF), feature_int(FEAT_SOCKRECVBUF))) {
233 cli_error(cptr) = errno;
234 report_error(SETBUFS_ERROR_MSG, cli_name(cptr), errno);
240 * Set the TOS bits - this is nonfatal if it doesn't stick.
242 if (!os_set_tos(cli_fd(cptr), feature_int(FEAT_TOS_SERVER))) {
243 report_error(TOS_ERROR_MSG, cli_name(cptr), errno);
245 if ((result = os_connect_nonb(cli_fd(cptr), &aconf->address)) == IO_FAILURE) {
246 cli_error(cptr) = errno;
247 report_error(CONNECT_ERROR_MSG, cli_name(cptr), errno);
253 if (!socket_add(&(cli_socket(cptr)), client_sock_callback,
254 (void*) cli_connect(cptr),
255 (result == IO_SUCCESS) ? SS_CONNECTED : SS_CONNECTING,
256 SOCK_EVENT_READABLE, cli_fd(cptr))) {
257 cli_error(cptr) = ENFILE;
258 report_error(REGISTER_ERROR_MSG, cli_name(cptr), ENFILE);
265 struct SSLConnection *ssl = ssl_create_connect(cli_fd(cptr), cptr, SSLData_Client);
266 cli_connect(cptr)->con_ssl = ssl;
267 if(ssl_handshake(ssl)) {
268 unsigned int events = 0;
269 if(ssl_wantread(ssl))
270 events |= SOCK_EVENT_READABLE;
271 if(ssl_wantwrite(ssl))
272 events |= SOCK_EVENT_WRITABLE;
273 socket_events(&(cli_socket(cptr)), SOCK_ACTION_SET | events);
278 cli_freeflag(cptr) |= FREEFLAG_SOCKET;
282 /** Attempt to send a sequence of bytes to the connection.
283 * As a side effect, updates \a cptr's FLAG_BLOCKED setting
284 * and sendB/sendK fields.
285 * @param cptr Client that should receive data.
286 * @param buf Message buffer to send to client.
287 * @return Negative on connection-fatal error; otherwise
288 * number of bytes sent.
290 unsigned int deliver_it(struct Client *cptr, struct MsgQ *buf)
292 unsigned int bytes_written = 0;
293 unsigned int bytes_count = 0;
297 if(cli_connect(cptr)->con_ssl) {
298 result = ssl_send_encrypt(cli_connect(cptr)->con_ssl, buf, &bytes_count, &bytes_written);
300 result = os_sendv_nonb(cli_fd(cptr), buf, &bytes_count, &bytes_written);
305 ClrFlag(cptr, FLAG_BLOCKED);
307 cli_sendB(cptr) += bytes_written;
308 cli_sendB(&me) += bytes_written;
309 /* A partial write implies that future writes will block. */
310 if (bytes_written < bytes_count)
311 SetFlag(cptr, FLAG_BLOCKED);
314 SetFlag(cptr, FLAG_BLOCKED);
317 cli_error(cptr) = errno;
318 SetFlag(cptr, FLAG_DEADSOCKET);
321 return bytes_written;
324 /** Complete non-blocking connect()-sequence. Check access and
325 * terminate connection, if trouble detected.
326 * @param cptr Client to which we have connected, with all ConfItem structs attached.
327 * @return Zero on failure (caller should exit_client()), non-zero on success.
329 int completed_connection(struct Client* cptr)
331 struct ConfItem *aconf;
333 struct Client *acptr;
339 * get the socket status from the fd first to check if
340 * connection actually succeeded
342 if ((cli_error(cptr) = os_get_sockerr(cli_fd(cptr)))) {
343 const char* msg = strerror(cli_error(cptr));
345 msg = "Unknown error";
346 sendto_opmask_butone(0, SNO_OLDSNO, "Connection failed to %s: %s",
347 cli_name(cptr), msg);
350 if (!(aconf = find_conf_byname(cli_confs(cptr), cli_name(cptr), CONF_SERVER))) {
351 sendto_opmask_butone(0, SNO_OLDSNO, "Lost Server Line for %s", cli_name(cptr));
354 if (s_state(&(cli_socket(cptr))) == SS_CONNECTING)
355 socket_state(&(cli_socket(cptr)), SS_CONNECTED);
357 if (!EmptyString(aconf->passwd))
358 sendrawto_one(cptr, MSG_PASS " :%s", aconf->passwd);
361 * Create a unique timestamp
364 for (i = HighestFd; i > -1; --i) {
365 if ((acptr = LocalClientArray[i]) &&
366 (IsServer(acptr) || IsHandshake(acptr))) {
367 if (cli_serv(acptr)->timestamp >= newts)
368 newts = cli_serv(acptr)->timestamp + 1;
371 assert(0 != cli_serv(cptr));
373 cli_serv(cptr)->timestamp = newts;
376 * Make us timeout after twice the timeout for DNS look ups
378 cli_lasttime(cptr) = CurrentTime;
381 sendrawto_one(cptr, MSG_SERVER " %s 1 %Tu %Tu J%s %s%s +%s6 :%s",
382 cli_name(&me), cli_serv(&me)->timestamp, newts,
383 MAJOR_PROTOCOL, NumServCap(&me),
384 feature_bool(FEAT_HUB) ? "h" : "", cli_info(&me));
386 return (IsDead(cptr)) ? 0 : 1;
389 /** Close the physical connection. Side effects: MyConnect(cptr)
390 * becomes false and cptr->from becomes NULL.
391 * @param cptr Client to disconnect.
393 void close_connection(struct Client *cptr)
395 struct ConfItem* aconf;
397 if (IsServer(cptr)) {
398 ServerStats->is_sv++;
399 ServerStats->is_sbs += cli_sendB(cptr);
400 ServerStats->is_sbr += cli_receiveB(cptr);
401 ServerStats->is_sti += CurrentTime - cli_firsttime(cptr);
403 * If the connection has been up for a long amount of time, schedule
404 * a 'quick' reconnect, else reset the next-connect cycle.
406 if ((aconf = find_conf_exact(cli_name(cptr), cptr, CONF_SERVER))) {
408 * Reschedule a faster reconnect, if this was a automatically
409 * connected configuration entry. (Note that if we have had
410 * a rehash in between, the status has been changed to
411 * CONF_ILLEGAL). But only do this if it was a "good" link.
413 aconf->hold = CurrentTime;
414 aconf->hold += ((aconf->hold - cli_since(cptr) >
415 feature_int(FEAT_HANGONGOODLINK)) ?
416 feature_int(FEAT_HANGONRETRYDELAY) : ConfConFreq(aconf));
417 /* if (nextconnect > aconf->hold) */
418 /* nextconnect = aconf->hold; */
421 else if (IsUser(cptr)) {
422 ServerStats->is_cl++;
423 ServerStats->is_cbs += cli_sendB(cptr);
424 ServerStats->is_cbr += cli_receiveB(cptr);
425 ServerStats->is_cti += CurrentTime - cli_firsttime(cptr);
428 ServerStats->is_ni++;
430 if(cli_connect(cptr)->con_ssl) {
431 ssl_free_connection(cli_connect(cptr)->con_ssl);
432 cli_connect(cptr)->con_ssl = NULL;
435 if (-1 < cli_fd(cptr)) {
436 flush_connections(cptr);
437 LocalClientArray[cli_fd(cptr)] = 0;
439 socket_del(&(cli_socket(cptr))); /* queue a socket delete */
442 SetFlag(cptr, FLAG_DEADSOCKET);
444 MsgQClear(&(cli_sendQ(cptr)));
445 client_drop_sendq(cli_connect(cptr));
446 DBufClear(&(cli_recvQ(cptr)));
447 memset(cli_passwd(cptr), 0, sizeof(cli_passwd(cptr)));
448 set_snomask(cptr, 0, SNO_SET);
450 det_confs_butmask(cptr, 0);
452 if (cli_listener(cptr)) {
453 release_listener(cli_listener(cptr));
454 cli_listener(cptr) = 0;
457 for ( ; HighestFd > 0; --HighestFd) {
458 if (LocalClientArray[HighestFd])
463 /** Close all unregistered connections.
464 * @param source Oper who requested the close.
465 * @return Number of closed connections.
467 int net_close_unregistered_connections(struct Client* source)
474 for (i = HighestFd; i > 0; --i) {
475 if ((cptr = LocalClientArray[i]) && !IsRegistered(cptr)) {
476 send_reply(source, RPL_CLOSING, get_client_name(source, HIDE_IP));
477 exit_client(source, cptr, &me, "Oper Closing");
484 /** Creates a client which has just connected to us on the given fd.
485 * The sockhost field is initialized with the ip# of the host.
486 * The client is not added to the linked list of clients, it is
487 * passed off to the auth handler for dns and ident queries.
488 * @param listener Listening socket that received the connection.
489 * @param fd File descriptor of new connection.
491 void add_connection(struct Listener* listener, int fd) {
492 struct irc_sockaddr addr;
493 struct Client *new_client;
494 time_t next_target = 0;
496 const char* const throttle_message =
497 "ERROR :Your host is trying to (re)connect too fast -- throttled\r\n";
498 /* 12345678901234567890123456789012345679012345678901234567890123456 */
499 const char* const register_message =
500 "ERROR :Unable to complete your registration\r\n";
502 assert(0 != listener);
505 * Removed preliminary access check. Full check is performed in m_server and
506 * m_user instead. Also connection time out help to get rid of unwanted
509 if (!os_get_peername(fd, &addr) || !os_set_nonblocking(fd)) {
510 ++ServerStats->is_ref;
515 * Disable IP (*not* TCP) options. In particular, this makes it impossible
516 * to use source routing to connect to the server. If we didn't do this
517 * (and if intermediate networks didn't drop source-routed packets), an
518 * attacker could successfully IP spoof us...and even return the anti-spoof
519 * ping, because the options would cause the packet to be routed back to
520 * the spoofer's machine. When we disable the IP options, we delete the
521 * source route, and the normal routing takes over.
523 os_disable_options(fd);
525 if (listener_server(listener))
527 new_client = make_client(0, STAT_UNKNOWN_SERVER);
532 * Add this local client to the IPcheck registry.
534 * If they're throttled, murder them, but tell them why first.
536 if (!IPcheck_local_connect(&addr.addr, &next_target))
538 ++ServerStats->is_ref;
539 write(fd, throttle_message, strlen(throttle_message));
543 new_client = make_client(0, STAT_UNKNOWN_USER);
544 SetIPChecked(new_client);
548 * Copy ascii address to 'sockhost' just in case. Then we have something
549 * valid to put into error messages...
551 ircd_ntoa_r(cli_sock_ip(new_client), &addr.addr);
552 strcpy(cli_sockhost(new_client), cli_sock_ip(new_client));
553 memcpy(&cli_ip(new_client), &addr.addr, sizeof(cli_ip(new_client)));
556 cli_nexttarget(new_client) = next_target;
558 cli_fd(new_client) = fd;
559 if (!socket_add(&(cli_socket(new_client)), client_sock_callback,
560 (void*) cli_connect(new_client), SS_CONNECTED, 0, fd)) {
561 ++ServerStats->is_ref;
562 write(fd, register_message, strlen(register_message));
564 cli_fd(new_client) = -1;
567 cli_freeflag(new_client) |= FREEFLAG_SOCKET;
568 cli_listener(new_client) = listener;
569 ++listener->ref_count;
571 Count_newunknown(UserStats);
573 if(listener_ssl(listener)) {
574 struct Connection* con = cli_connect(new_client);
575 con->con_ssl = ssl_start_handshake_listener(listener->ssl_listener, fd, new_client, SSLData_Client);
576 unsigned int events = 0;
577 if(ssl_wantread(con->con_ssl))
578 events |= SOCK_EVENT_READABLE;
579 if(ssl_wantwrite(con->con_ssl))
580 events |= SOCK_EVENT_WRITABLE;
581 socket_events(&(cli_socket(new_client)), SOCK_ACTION_SET | events);
583 /* if we've made it this far we can put the client on the auth query pile */
584 start_auth(new_client);
588 /** Determines whether to tell the events engine we're interested in
590 * @param cptr Client for which to decide this.
592 void update_write(struct Client* cptr)
594 /* If there are messages that need to be sent along, or if the client
595 * is in the middle of a /list, then we need to tell the engine that
596 * we're interested in writable events--otherwise, we need to drop
599 socket_events(&(cli_socket(cptr)),
600 ((MsgQLength(&cli_sendQ(cptr)) || cli_listing(cptr)) ?
601 SOCK_ACTION_ADD : SOCK_ACTION_DEL) | SOCK_EVENT_WRITABLE);
604 /** Read a 'packet' of data from a connection and process it. Read in
605 * 8k chunks to give a better performance rating (for server
606 * connections). Do some tricky stuff for client connections to make
607 * sure they don't do any flooding >:-) -avalon
608 * @param cptr Client from which to read data.
609 * @param socket_ready If non-zero, more data can be read from the client's socket.
610 * @return Positive number on success, zero on connection-fatal failure, negative
613 static int read_packet(struct Client *cptr, int socket_ready)
615 unsigned int dolen = 0;
616 unsigned int length = 0;
620 DBufLength(&(cli_recvQ(cptr))) > feature_int(FEAT_CLIENT_FLOOD))) {
622 /* Handle SSL Sockets
625 if(cli_connect(cptr)->con_ssl) {
626 recvret = ssl_recv_decrypt(cli_connect(cptr)->con_ssl, readbuf, sizeof(readbuf), &length);
628 recvret = os_recv_nonb(cli_fd(cptr), readbuf, sizeof(readbuf), &length);
634 cli_lasttime(cptr) = CurrentTime;
636 ClrFlag(cptr, FLAG_NONL);
637 if (cli_lasttime(cptr) > cli_since(cptr))
638 cli_since(cptr) = cli_lasttime(cptr);
644 cli_error(cptr) = errno;
645 /* SetFlag(cptr, FLAG_DEADSOCKET); */
651 * For server connections, we process as many as we can without
652 * worrying about the time of day or anything :)
654 if (length > 0 && IsServer(cptr))
655 return server_dopacket(cptr, readbuf, length);
656 else if (length > 0 && (IsHandshake(cptr) || IsConnecting(cptr)))
657 return connect_dopacket(cptr, readbuf, length);
661 * Before we even think of parsing what we just read, stick
662 * it on the end of the receive queue and do it when its
665 if (length > 0 && dbuf_put(&(cli_recvQ(cptr)), readbuf, length) == 0)
666 return exit_client(cptr, cptr, &me, "dbuf_put fail");
668 int HasUnlimitFlood = HasPriv(cptr, PRIV_UNLIMIT_FLOOD);
670 if (DBufLength(&(cli_recvQ(cptr))) > feature_int(FEAT_CLIENT_FLOOD) && !HasUnlimitFlood)
671 return exit_client(cptr, cptr, &me, "Excess Flood");
673 while (DBufLength(&(cli_recvQ(cptr))) && !NoNewLine(cptr) &&
674 (IsTrusted(cptr) || cli_since(cptr) - CurrentTime < 10 || HasUnlimitFlood))
676 dolen = dbuf_getmsg(&(cli_recvQ(cptr)), cli_buffer(cptr), BUFSIZE);
678 * Devious looking...whats it do ? well..if a client
679 * sends a *long* message without any CR or LF, then
680 * dbuf_getmsg fails and we pull it out using this
681 * loop which just gets the next 512 bytes and then
682 * deletes the rest of the buffer contents.
687 if (DBufLength(&(cli_recvQ(cptr))) < 510)
688 SetFlag(cptr, FLAG_NONL);
691 /* More than 512 bytes in the line - drop the input and yell
694 DBufClear(&(cli_recvQ(cptr)));
695 send_reply(cptr, ERR_INPUTTOOLONG);
698 else if (client_dopacket(cptr, dolen) == CPTR_KILLED)
701 * If it has become registered as a Server
702 * then skip the per-message parsing below.
704 if (IsHandshake(cptr) || IsServer(cptr))
708 dolen = dbuf_get(&(cli_recvQ(cptr)), readbuf, sizeof(readbuf));
713 if (DBufLength(&(cli_recvQ(cptr))) < 510)
714 SetFlag(cptr, FLAG_NONL);
716 DBufClear(&(cli_recvQ(cptr)));
718 else if ((IsServer(cptr) &&
719 server_dopacket(cptr, readbuf, dolen) == CPTR_KILLED) ||
721 connect_dopacket(cptr, readbuf, dolen) == CPTR_KILLED))
727 /* If there's still data to process, wait 2 seconds first */
728 if (DBufLength(&(cli_recvQ(cptr))) && !NoNewLine(cptr) &&
729 !t_onqueue(&(cli_proc(cptr))))
731 Debug((DEBUG_LIST, "Adding client process timer for %C", cptr));
732 cli_freeflag(cptr) |= FREEFLAG_TIMER;
733 timer_add(&(cli_proc(cptr)), client_timer_callback, cli_connect(cptr),
740 /** Start a connection to another server.
741 * @param aconf Connect block data for target server.
742 * @param by Client who requested the connection (if any).
743 * @return Non-zero on success; zero on failure.
745 int connect_server(struct ConfItem* aconf, struct Client* by)
747 struct Client* cptr = 0;
750 if (aconf->dns_pending) {
751 sendto_opmask_butone(0, SNO_OLDSNO, "Server %s connect DNS pending",
755 Debug((DEBUG_NOTICE, "Connect to %s[@%s]", aconf->name,
756 ircd_ntoa(&aconf->address.addr)));
758 if ((cptr = FindClient(aconf->name))) {
759 if (IsServer(cptr) || IsMe(cptr)) {
760 sendto_opmask_butone(0, SNO_OLDSNO, "Server %s already present from %s",
761 aconf->name, cli_name(cli_from(cptr)));
762 if (by && IsUser(by) && !MyUser(by)) {
763 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Server %s already present "
764 "from %s", by, aconf->name, cli_name(cli_from(cptr)));
768 else if (IsHandshake(cptr) || IsConnecting(cptr)) {
769 if (by && IsUser(by)) {
770 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Connection to %s already in "
771 "progress", by, cli_name(cptr));
777 * If we don't know the IP# for this host and it is a hostname and
778 * not a ip# string, then try and find the appropriate host record.
780 if (!irc_in_addr_valid(&aconf->address.addr)
781 && !ircd_aton(&aconf->address.addr, aconf->host)) {
782 char buf[HOSTLEN + 1];
784 host_from_uh(buf, aconf->host, HOSTLEN);
785 gethost_byname(buf, connect_dns_callback, aconf);
786 aconf->dns_pending = 1;
789 cptr = make_client(NULL, STAT_UNKNOWN_SERVER);
792 * Copy these in so we have something for error detection.
794 ircd_strncpy(cli_name(cptr), aconf->name, HOSTLEN);
795 ircd_strncpy(cli_sockhost(cptr), aconf->host, HOSTLEN);
798 * Attach config entries to client here rather than in
799 * completed_connection. This to avoid null pointer references
801 attach_confs_byhost(cptr, aconf->host, CONF_SERVER);
803 if (!find_conf_byhost(cli_confs(cptr), aconf->host, CONF_SERVER)) {
804 sendto_opmask_butone(0, SNO_OLDSNO, "Host %s is not enabled for "
805 "connecting: no Connect block", aconf->name);
806 if (by && IsUser(by) && !MyUser(by)) {
807 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Connect to host %s failed: no "
808 "Connect block", by, aconf->name);
810 det_confs_butmask(cptr, 0);
815 * attempt to connect to the server in the conf line
817 if (!connect_inet(aconf, cptr)) {
818 if (by && IsUser(by) && !MyUser(by)) {
819 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Couldn't connect to %s", by,
822 det_confs_butmask(cptr, 0);
827 * NOTE: if we're here we have a valid C:Line and the client should
828 * have started the connection and stored the remote address/port and
829 * ip address name in itself
831 * The socket has been connected or connect is in progress.
834 if (by && IsUser(by)) {
835 ircd_snprintf(0, cli_serv(cptr)->by, sizeof(cli_serv(cptr)->by), "%s%s",
837 assert(0 == cli_serv(cptr)->user);
838 cli_serv(cptr)->user = cli_user(by);
839 cli_user(by)->refcnt++;
842 *(cli_serv(cptr))->by = '\0';
843 /* strcpy(cptr->serv->by, "Auto"); */
845 cli_serv(cptr)->up = &me;
848 if (cli_fd(cptr) > HighestFd)
849 HighestFd = cli_fd(cptr);
851 LocalClientArray[cli_fd(cptr)] = cptr;
853 Count_newunknown(UserStats);
854 /* Actually we lie, the connect hasn't succeeded yet, but we have a valid
855 * cptr, so we register it now.
856 * Maybe these two calls should be merged.
858 add_client_to_list(cptr);
860 /* nextping = CurrentTime; */
862 return (s_state(&cli_socket(cptr)) == SS_CONNECTED) ?
863 completed_connection(cptr) : 1;
866 /** Find the real hostname for the host running the server (or one which
867 * matches the server's name) and its primary IP#. Hostname is stored
868 * in the client structure passed as a pointer.
870 void init_server_identity(void)
872 const struct LocalConf* conf = conf_get_local();
875 ircd_strncpy(cli_name(&me), conf->name, HOSTLEN);
876 SetYXXServerName(&me, conf->numeric);
879 /** Process events on a client socket.
880 * @param ev Socket event structure that has a struct Connection as
881 * its associated data.
883 static void client_sock_callback(struct Event* ev)
886 struct Connection* con;
890 assert(0 != ev_socket(ev));
891 assert(0 != s_data(ev_socket(ev)));
893 con = (struct Connection*) s_data(ev_socket(ev));
895 assert(0 != con_client(con) || ev_type(ev) == ET_DESTROY);
897 cptr = con_client(con);
899 assert(0 == cptr || con == cli_connect(cptr));
901 switch (ev_type(ev)) {
903 con_freeflag(con) &= ~FREEFLAG_SOCKET;
905 if (!con_freeflag(con) && !cptr)
906 free_connection(con);
909 case ET_CONNECT: /* socket connection completed */
910 if(cli_connect(cptr)->con_ssl) {
911 ssl_start_handshake_connect(cli_connect(cptr)->con_ssl);
913 else if (!completed_connection(cptr) || IsDead(cptr))
914 fallback = cli_info(cptr);
917 case ET_ERROR: /* an error occurred */
918 fallback = cli_info(cptr);
919 cli_error(cptr) = ev_data(ev);
920 /* If the OS told us we have a bad file descriptor, we should
921 * record that for future reference.
923 if (cli_error(cptr) == EBADF)
925 if (s_state(&(con_socket(con))) == SS_CONNECTING) {
926 completed_connection(cptr);
927 /* for some reason, the os_get_sockerr() in completed_connect()
928 * can return 0 even when ev_data(ev) indicates a real error, so
929 * re-assign the client error here.
931 cli_error(cptr) = ev_data(ev);
935 case ET_EOF: /* end of file on socket */
936 Debug((DEBUG_ERROR, "READ ERROR: fd = %d %d", cli_fd(cptr),
938 SetFlag(cptr, FLAG_DEADSOCKET);
939 if ((IsServer(cptr) || IsHandshake(cptr)) && cli_error(cptr) == 0) {
940 exit_client_msg(cptr, cptr, &me, "Server %s closed the connection (%s)",
941 cli_name(cptr), cli_serv(cptr)->last_error_msg);
944 fmt = "Read error: %s";
945 fallback = "EOF from client";
949 case ET_WRITE: /* socket is writable */
950 ClrFlag(cptr, FLAG_BLOCKED);
951 if (cli_listing(cptr) && MsgQLength(&(cli_sendQ(cptr))) < 2048)
952 list_next_channels(cptr);
953 Debug((DEBUG_SEND, "Sending queued data to %C", cptr));
957 case ET_READ: /* socket is readable */
959 Debug((DEBUG_DEBUG, "Reading data from %C", cptr));
960 if (read_packet(cptr, 1) == 0) /* error while reading packet */
961 fallback = "EOF from client";
966 assert(0 && "Unrecognized socket event in client_sock_callback()");
970 assert(0 == cptr || 0 == cli_connect(cptr) || con == cli_connect(cptr));
973 const char* msg = (cli_error(cptr)) ? strerror(cli_error(cptr)) : fallback;
975 msg = "Unknown error";
976 exit_client_msg(cptr, cptr, &me, fmt, msg);
980 /** Process a timer on client socket.
981 * @param ev Timer event that has a struct Connection as its
984 static void client_timer_callback(struct Event* ev)
987 struct Connection* con;
989 assert(0 != ev_timer(ev));
990 assert(0 != t_data(ev_timer(ev)));
991 assert(ET_DESTROY == ev_type(ev) || ET_EXPIRE == ev_type(ev));
993 con = (struct Connection*) t_data(ev_timer(ev));
995 assert(0 != con_client(con) || ev_type(ev) == ET_DESTROY);
997 cptr = con_client(con);
999 assert(0 == cptr || con == cli_connect(cptr));
1001 if (ev_type(ev)== ET_DESTROY) {
1002 con_freeflag(con) &= ~FREEFLAG_TIMER; /* timer has expired... */
1004 if (!con_freeflag(con) && !cptr)
1005 free_connection(con); /* client is being destroyed */
1007 Debug((DEBUG_LIST, "Client process timer for %C expired; processing",
1009 read_packet(cptr, 0); /* read_packet will re-add timer if needed */
1012 assert(0 == cptr || 0 == cli_connect(cptr) || con == cli_connect(cptr));