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"
61 #include <arpa/inet.h>
69 #include <sys/ioctl.h>
70 #include <sys/socket.h>
72 #include <sys/utsname.h>
79 /** Array of my own clients, indexed by file descriptor. */
80 struct Client* LocalClientArray[MAXCONNECTIONS];
81 /** Maximum file descriptor in current use. */
83 /** Default local address for outbound connections. */
84 struct irc_sockaddr VirtualHost;
85 /** Temporary buffer for reading data from a peer. */
86 static char readbuf[SERVER_TCP_WINDOW];
89 * report_error text constants
91 const char* const ACCEPT_ERROR_MSG = "error accepting connection for %s: %s";
92 const char* const BIND_ERROR_MSG = "bind error for %s: %s";
93 const char* const CONNECT_ERROR_MSG = "connect to host %s failed: %s";
94 const char* const CONNLIMIT_ERROR_MSG = "connect limit exceeded for %s: %s";
95 const char* const LISTEN_ERROR_MSG = "listen error for %s: %s";
96 const char* const NONB_ERROR_MSG = "error setting non-blocking for %s: %s";
97 const char* const PEERNAME_ERROR_MSG = "getpeername failed for %s: %s";
98 const char* const POLL_ERROR_MSG = "poll error for %s: %s";
99 const char* const REGISTER_ERROR_MSG = "registering %s: %s";
100 const char* const REUSEADDR_ERROR_MSG = "error setting SO_REUSEADDR for %s: %s";
101 const char* const SELECT_ERROR_MSG = "select error for %s: %s";
102 const char* const SETBUFS_ERROR_MSG = "error setting buffer size for %s: %s";
103 const char* const SOCKET_ERROR_MSG = "error creating socket for %s: %s";
104 const char* const TOS_ERROR_MSG = "error setting TOS for %s: %s";
107 static void client_sock_callback(struct Event* ev);
108 static void client_timer_callback(struct Event* ev);
110 #if !defined(USE_POLL)
111 #if FD_SETSIZE < (MAXCONNECTIONS + 4)
115 * All operating systems work when MAXCONNECTIONS <= 252.
116 * Most operating systems work when MAXCONNECTIONS <= 1020 and FD_SETSIZE is
117 * updated correctly in the system headers (on BSD systems our sys.h has
118 * defined FD_SETSIZE to MAXCONNECTIONS+4 before including the system's headers
119 * but sys/types.h might have abruptly redefined it so the check is still
120 * done), you might already need to recompile your kernel.
121 * For larger FD_SETSIZE your milage may vary (kernel patches may be needed).
122 * The check is _NOT_ done if we will not use FD_SETS at all (USE_POLL)
124 #error "FD_SETSIZE is too small or MAXCONNECTIONS too large."
130 * Cannot use perror() within daemon. stderr is closed in
131 * ircd and cannot be used. And, worse yet, it might have
132 * been reassigned to a normal connection...
135 /** Replacement for perror(). Record error to log. Send a copy to all
136 * *LOCAL* opers, but only if no errors were sent to them in the last
138 * @param text A *format* string for outputting error. It must contain
139 * only two '%s', the first will be replaced by the sockhost from the
140 * cptr, and the latter will be taken from sys_errlist[errno].
141 * @param who The client associated with the error.
142 * @param err The errno value to display.
144 void report_error(const char* text, const char* who, int err)
146 static time_t last_notice = 0;
147 int errtmp = errno; /* debug may change 'errno' */
148 const char* errmsg = (err) ? strerror(err) : "";
151 errmsg = "Unknown error";
153 if (EmptyString(who))
156 if (last_notice + 20 < CurrentTime) {
158 * pace error messages so opers don't get flooded by transients
160 sendto_opmask_butone(0, SNO_OLDSNO, text, who, errmsg);
161 last_notice = CurrentTime;
163 log_write(LS_SOCKET, L_ERROR, 0, text, who, errmsg);
168 /** Called when resolver query finishes. If the DNS lookup was
169 * successful, start the connection; otherwise notify opers of the
171 * @param vptr The struct ConfItem representing the Connect block.
172 * @param hp A pointer to the DNS lookup results (NULL on failure).
174 static void connect_dns_callback(void* vptr, struct DNSReply* hp)
176 struct ConfItem* aconf = (struct ConfItem*) vptr;
178 aconf->dns_pending = 0;
180 memcpy(&aconf->address, &hp->addr, sizeof(aconf->address));
182 connect_server(aconf, 0);
185 sendto_opmask_butone(0, SNO_OLDSNO, "Connect to %s failed: host lookup",
189 /** Closes all file descriptors.
190 * @param close_stderr If non-zero, also close stderr.
192 void close_connections(int close_stderr)
199 for (i = 3; i < MAXCONNECTIONS; ++i)
203 /** Initialize process fd limit to MAXCONNECTIONS.
205 int init_connection_limits(void)
207 int limit = os_set_fdlimit(MAXCONNECTIONS);
211 fprintf(stderr, "error setting max fd's to %d\n", limit);
213 else if (limit > 0) {
214 fprintf(stderr, "ircd fd table too big\nHard Limit: %d IRC max: %d\n",
215 limit, MAXCONNECTIONS);
216 fprintf(stderr, "set MAXCONNECTIONS to a smaller value");
221 /** Set up address and port and make a connection.
222 * @param aconf Provides the connection information.
223 * @param cptr Client structure for the peer.
224 * @return Non-zero on success; zero on failure.
226 static int connect_inet(struct ConfItem* aconf, struct Client* cptr)
228 const struct irc_sockaddr *local;
233 * Might as well get sockhost from here, the connection is attempted
234 * with it so if it fails its useless.
236 if (irc_in_addr_valid(&aconf->origin.addr))
237 local = &aconf->origin;
239 local = &VirtualHost;
240 cli_fd(cptr) = os_socket(local, SOCK_STREAM, cli_name(cptr));
241 if (cli_fd(cptr) < 0)
245 * save connection info in client
247 memcpy(&cli_ip(cptr), &aconf->address.addr, sizeof(cli_ip(cptr)));
248 cli_port(cptr) = aconf->address.port;
249 ircd_ntoa_r(cli_sock_ip(cptr), &cli_ip(cptr));
251 * we want a big buffer for server connections
253 if (!os_set_sockbufs(cli_fd(cptr), feature_int(FEAT_SOCKSENDBUF), feature_int(FEAT_SOCKRECVBUF))) {
254 cli_error(cptr) = errno;
255 report_error(SETBUFS_ERROR_MSG, cli_name(cptr), errno);
260 if ((result = os_connect_nonb(cli_fd(cptr), &aconf->address)) == IO_FAILURE) {
261 cli_error(cptr) = errno;
262 report_error(CONNECT_ERROR_MSG, cli_name(cptr), errno);
267 if (!socket_add(&(cli_socket(cptr)), client_sock_callback,
268 (void*) cli_connect(cptr),
269 (result == IO_SUCCESS) ? SS_CONNECTED : SS_CONNECTING,
270 SOCK_EVENT_READABLE, cli_fd(cptr))) {
271 cli_error(cptr) = ENFILE;
272 report_error(REGISTER_ERROR_MSG, cli_name(cptr), ENFILE);
277 cli_freeflag(cptr) |= FREEFLAG_SOCKET;
281 /** Attempt to send a sequence of bytes to the connection.
282 * As a side effect, updates \a cptr's FLAG_BLOCKED setting
283 * and sendB/sendK fields.
284 * @param cptr Client that should receive data.
285 * @param buf Message buffer to send to client.
286 * @return Negative on connection-fatal error; otherwise
287 * number of bytes sent.
289 unsigned int deliver_it(struct Client *cptr, struct MsgQ *buf)
291 unsigned int bytes_written = 0;
292 unsigned int bytes_count = 0;
295 switch (os_sendv_nonb(cli_fd(cptr), buf, &bytes_count, &bytes_written)) {
297 ClrFlag(cptr, FLAG_BLOCKED);
299 cli_sendB(cptr) += bytes_written;
300 cli_sendB(&me) += bytes_written;
301 if (cli_sendB(cptr) > 1023) {
302 cli_sendK(cptr) += (cli_sendB(cptr) >> 10);
303 cli_sendB(cptr) &= 0x03ff; /* 2^10 = 1024, 3ff = 1023 */
305 if (cli_sendB(&me) > 1023) {
306 cli_sendK(&me) += (cli_sendB(&me) >> 10);
307 cli_sendB(&me) &= 0x03ff;
310 * XXX - hrmm.. set blocked here? the socket didn't
313 if (bytes_written < bytes_count)
314 SetFlag(cptr, FLAG_BLOCKED);
317 SetFlag(cptr, FLAG_BLOCKED);
320 cli_error(cptr) = errno;
321 SetFlag(cptr, FLAG_DEADSOCKET);
324 return bytes_written;
327 /** Free the client's DNS reply, if any.
328 * @param cptr Client to operate on.
330 void release_dns_reply(struct Client* cptr)
333 assert(MyConnect(cptr));
335 if (cli_dns_reply(cptr)) {
336 MyFree(cli_dns_reply(cptr)->h_name);
337 MyFree(cli_dns_reply(cptr));
338 cli_dns_reply(cptr) = 0;
342 /** Complete non-blocking connect()-sequence. Check access and
343 * terminate connection, if trouble detected.
344 * @param cptr Client to which we have connected, with all Confitem structs attached.
345 * @return Zero on failure (caller should exit_client()), non-zero on success.
347 static int completed_connection(struct Client* cptr)
349 struct ConfItem *aconf;
351 struct Client *acptr;
357 * get the socket status from the fd first to check if
358 * connection actually succeeded
360 if ((cli_error(cptr) = os_get_sockerr(cli_fd(cptr)))) {
361 const char* msg = strerror(cli_error(cptr));
363 msg = "Unknown error";
364 sendto_opmask_butone(0, SNO_OLDSNO, "Connection failed to %s: %s",
365 cli_name(cptr), msg);
368 if (!(aconf = find_conf_byname(cli_confs(cptr), cli_name(cptr), CONF_SERVER))) {
369 sendto_opmask_butone(0, SNO_OLDSNO, "Lost Server Line for %s", cli_name(cptr));
372 if (s_state(&(cli_socket(cptr))) == SS_CONNECTING)
373 socket_state(&(cli_socket(cptr)), SS_CONNECTED);
375 if (!EmptyString(aconf->passwd))
376 sendrawto_one(cptr, MSG_PASS " :%s", aconf->passwd);
379 * Create a unique timestamp
382 for (i = HighestFd; i > -1; --i) {
383 if ((acptr = LocalClientArray[i]) &&
384 (IsServer(acptr) || IsHandshake(acptr))) {
385 if (cli_serv(acptr)->timestamp >= newts)
386 newts = cli_serv(acptr)->timestamp + 1;
389 assert(0 != cli_serv(cptr));
391 cli_serv(cptr)->timestamp = newts;
394 * Make us timeout after twice the timeout for DNS look ups
396 cli_lasttime(cptr) = CurrentTime;
397 SetFlag(cptr, FLAG_PINGSENT);
399 sendrawto_one(cptr, MSG_SERVER " %s 1 %Tu %Tu J%s %s%s +%s :%s",
400 cli_name(&me), cli_serv(&me)->timestamp, newts,
401 MAJOR_PROTOCOL, NumServCap(&me),
402 feature_bool(FEAT_HUB) ? "h" : "", cli_info(&me));
404 return (IsDead(cptr)) ? 0 : 1;
407 /** Close the physical connection. Side effects: MyConnect(cptr)
408 * becomes false and cptr->from becomes NULL.
409 * @param cptr Client to disconnect.
411 void close_connection(struct Client *cptr)
413 struct ConfItem* aconf;
415 if (IsServer(cptr)) {
416 ServerStats->is_sv++;
417 ServerStats->is_sbs += cli_sendB(cptr);
418 ServerStats->is_sbr += cli_receiveB(cptr);
419 ServerStats->is_sks += cli_sendK(cptr);
420 ServerStats->is_skr += cli_receiveK(cptr);
421 ServerStats->is_sti += CurrentTime - cli_firsttime(cptr);
422 if (ServerStats->is_sbs > 1023) {
423 ServerStats->is_sks += (ServerStats->is_sbs >> 10);
424 ServerStats->is_sbs &= 0x3ff;
426 if (ServerStats->is_sbr > 1023) {
427 ServerStats->is_skr += (ServerStats->is_sbr >> 10);
428 ServerStats->is_sbr &= 0x3ff;
431 * If the connection has been up for a long amount of time, schedule
432 * a 'quick' reconnect, else reset the next-connect cycle.
434 if ((aconf = find_conf_exact(cli_name(cptr), 0, cli_sockhost(cptr), CONF_SERVER))) {
436 * Reschedule a faster reconnect, if this was a automaticly
437 * connected configuration entry. (Note that if we have had
438 * a rehash in between, the status has been changed to
439 * CONF_ILLEGAL). But only do this if it was a "good" link.
441 aconf->hold = CurrentTime;
442 aconf->hold += ((aconf->hold - cli_since(cptr) >
443 feature_int(FEAT_HANGONGOODLINK)) ?
444 feature_int(FEAT_HANGONRETRYDELAY) : ConfConFreq(aconf));
445 /* if (nextconnect > aconf->hold) */
446 /* nextconnect = aconf->hold; */
449 else if (IsUser(cptr)) {
450 ServerStats->is_cl++;
451 ServerStats->is_cbs += cli_sendB(cptr);
452 ServerStats->is_cbr += cli_receiveB(cptr);
453 ServerStats->is_cks += cli_sendK(cptr);
454 ServerStats->is_ckr += cli_receiveK(cptr);
455 ServerStats->is_cti += CurrentTime - cli_firsttime(cptr);
456 if (ServerStats->is_cbs > 1023) {
457 ServerStats->is_cks += (ServerStats->is_cbs >> 10);
458 ServerStats->is_cbs &= 0x3ff;
460 if (ServerStats->is_cbr > 1023) {
461 ServerStats->is_ckr += (ServerStats->is_cbr >> 10);
462 ServerStats->is_cbr &= 0x3ff;
466 ServerStats->is_ni++;
468 if (-1 < cli_fd(cptr)) {
469 flush_connections(cptr);
470 LocalClientArray[cli_fd(cptr)] = 0;
472 socket_del(&(cli_socket(cptr))); /* queue a socket delete */
475 SetFlag(cptr, FLAG_DEADSOCKET);
477 MsgQClear(&(cli_sendQ(cptr)));
478 client_drop_sendq(cli_connect(cptr));
479 DBufClear(&(cli_recvQ(cptr)));
480 memset(cli_passwd(cptr), 0, sizeof(cli_passwd(cptr)));
481 set_snomask(cptr, 0, SNO_SET);
483 det_confs_butmask(cptr, 0);
485 if (cli_listener(cptr)) {
486 release_listener(cli_listener(cptr));
487 cli_listener(cptr) = 0;
490 for ( ; HighestFd > 0; --HighestFd) {
491 if (LocalClientArray[HighestFd])
496 /** Close all unregistered connections.
497 * @param source Oper who requested the close.
498 * @return Number of closed connections.
500 int net_close_unregistered_connections(struct Client* source)
507 for (i = HighestFd; i > 0; --i) {
508 if ((cptr = LocalClientArray[i]) && !IsRegistered(cptr)) {
509 send_reply(source, RPL_CLOSING, get_client_name(source, HIDE_IP));
510 exit_client(source, cptr, &me, "Oper Closing");
517 /** Creates a client which has just connected to us on the given fd.
518 * The sockhost field is initialized with the ip# of the host.
519 * The client is not added to the linked list of clients, it is
520 * passed off to the auth handler for dns and ident queries.
521 * @param listener Listening socket that received the connection.
522 * @param fd File descriptor of new connection.
524 void add_connection(struct Listener* listener, int fd) {
525 struct irc_sockaddr addr;
526 struct Client *new_client;
527 time_t next_target = 0;
529 const char* const throttle_message =
530 "ERROR :Your host is trying to (re)connect too fast -- throttled\r\n";
531 /* 12345678901234567890123456789012345679012345678901234567890123456 */
532 const char* const register_message =
533 "ERROR :Unable to complete your registration\r\n";
535 assert(0 != listener);
538 * Removed preliminary access check. Full check is performed in m_server and
539 * m_user instead. Also connection time out help to get rid of unwanted
542 if (!os_get_peername(fd, &addr) || !os_set_nonblocking(fd)) {
543 ++ServerStats->is_ref;
548 * Disable IP (*not* TCP) options. In particular, this makes it impossible
549 * to use source routing to connect to the server. If we didn't do this
550 * (and if intermediate networks didn't drop source-routed packets), an
551 * attacker could successfully IP spoof us...and even return the anti-spoof
552 * ping, because the options would cause the packet to be routed back to
553 * the spoofer's machine. When we disable the IP options, we delete the
554 * source route, and the normal routing takes over.
556 os_disable_options(fd);
559 * Add this local client to the IPcheck registry.
561 * If they're throttled, murder them, but tell them why first.
563 if (!IPcheck_local_connect(&addr.addr, &next_target) && !listener->server)
565 ++ServerStats->is_ref;
566 write(fd, throttle_message, strlen(throttle_message));
571 new_client = make_client(0, ((listener->server) ?
572 STAT_UNKNOWN_SERVER : STAT_UNKNOWN_USER));
575 * Copy ascii address to 'sockhost' just in case. Then we have something
576 * valid to put into error messages...
578 SetIPChecked(new_client);
579 ircd_ntoa_r(cli_sock_ip(new_client), &addr.addr);
580 strcpy(cli_sockhost(new_client), cli_sock_ip(new_client));
581 memcpy(&cli_ip(new_client), &addr.addr, sizeof(cli_ip(new_client)));
582 cli_port(new_client) = addr.port;
585 cli_nexttarget(new_client) = next_target;
587 cli_fd(new_client) = fd;
588 if (!socket_add(&(cli_socket(new_client)), client_sock_callback,
589 (void*) cli_connect(new_client), SS_CONNECTED, 0, fd)) {
590 ++ServerStats->is_ref;
591 write(fd, register_message, strlen(register_message));
593 cli_fd(new_client) = -1;
596 cli_freeflag(new_client) |= FREEFLAG_SOCKET;
597 cli_listener(new_client) = listener;
598 ++listener->ref_count;
600 Count_newunknown(UserStats);
601 /* if we've made it this far we can put the client on the auth query pile */
602 start_auth(new_client);
605 /** Determines whether to tell the events engine we're interested in
607 * @param cptr Client for which to decide this.
609 void update_write(struct Client* cptr)
611 /* If there are messages that need to be sent along, or if the client
612 * is in the middle of a /list, then we need to tell the engine that
613 * we're interested in writable events--otherwise, we need to drop
616 socket_events(&(cli_socket(cptr)),
617 ((MsgQLength(&cli_sendQ(cptr)) || cli_listing(cptr)) ?
618 SOCK_ACTION_ADD : SOCK_ACTION_DEL) | SOCK_EVENT_WRITABLE);
621 /** Read a 'packet' of data from a connection and process it. Read in
622 * 8k chunks to give a better performance rating (for server
623 * connections). Do some tricky stuff for client connections to make
624 * sure they don't do any flooding >:-) -avalon
625 * @param cptr Client from which to read data.
626 * @param socket_ready If non-zero, more data can be read from the client's socket.
627 * @return Positive number on success, zero on connection-fatal failure, negative
630 static int read_packet(struct Client *cptr, int socket_ready)
632 unsigned int dolen = 0;
633 unsigned int length = 0;
637 DBufLength(&(cli_recvQ(cptr))) > feature_int(FEAT_CLIENT_FLOOD))) {
638 switch (os_recv_nonb(cli_fd(cptr), readbuf, sizeof(readbuf), &length)) {
643 cli_lasttime(cptr) = CurrentTime;
644 if (cli_lasttime(cptr) > cli_since(cptr))
645 cli_since(cptr) = cli_lasttime(cptr);
646 ClrFlag(cptr, FLAG_PINGSENT);
647 ClrFlag(cptr, FLAG_NONL);
653 cli_error(cptr) = errno;
654 /* SetFlag(cpt, FLAG_DEADSOCKET); */
660 * For server connections, we process as many as we can without
661 * worrying about the time of day or anything :)
663 if (length > 0 && IsServer(cptr))
664 return server_dopacket(cptr, readbuf, length);
665 else if (length > 0 && (IsHandshake(cptr) || IsConnecting(cptr)))
666 return connect_dopacket(cptr, readbuf, length);
670 * Before we even think of parsing what we just read, stick
671 * it on the end of the receive queue and do it when its
674 if (length > 0 && dbuf_put(&(cli_recvQ(cptr)), readbuf, length) == 0)
675 return exit_client(cptr, cptr, &me, "dbuf_put fail");
677 if (DBufLength(&(cli_recvQ(cptr))) > feature_int(FEAT_CLIENT_FLOOD))
678 return exit_client(cptr, cptr, &me, "Excess Flood");
680 while (DBufLength(&(cli_recvQ(cptr))) && !NoNewLine(cptr) &&
681 (IsTrusted(cptr) || cli_since(cptr) - CurrentTime < 10))
683 dolen = dbuf_getmsg(&(cli_recvQ(cptr)), cli_buffer(cptr), BUFSIZE);
685 * Devious looking...whats it do ? well..if a client
686 * sends a *long* message without any CR or LF, then
687 * dbuf_getmsg fails and we pull it out using this
688 * loop which just gets the next 512 bytes and then
689 * deletes the rest of the buffer contents.
694 if (DBufLength(&(cli_recvQ(cptr))) < 510)
695 SetFlag(cptr, FLAG_NONL);
697 DBufClear(&(cli_recvQ(cptr)));
699 else if (client_dopacket(cptr, dolen) == CPTR_KILLED)
702 * If it has become registered as a Server
703 * then skip the per-message parsing below.
705 if (IsHandshake(cptr) || IsServer(cptr))
709 dolen = dbuf_get(&(cli_recvQ(cptr)), readbuf, sizeof(readbuf));
714 if (DBufLength(&(cli_recvQ(cptr))) < 510)
715 SetFlag(cptr, FLAG_NONL);
717 DBufClear(&(cli_recvQ(cptr)));
719 else if ((IsServer(cptr) &&
720 server_dopacket(cptr, readbuf, dolen) == CPTR_KILLED) ||
722 connect_dopacket(cptr, readbuf, dolen) == CPTR_KILLED))
728 /* If there's still data to process, wait 2 seconds first */
729 if (DBufLength(&(cli_recvQ(cptr))) && !NoNewLine(cptr) &&
730 !t_onqueue(&(cli_proc(cptr))))
732 Debug((DEBUG_LIST, "Adding client process timer for %C", cptr));
733 cli_freeflag(cptr) |= FREEFLAG_TIMER;
734 timer_add(&(cli_proc(cptr)), client_timer_callback, cli_connect(cptr),
741 /** Start a connection to another server.
742 * @param aconf Connect block data for target server.
743 * @param by Client who requested the connection (if any).
744 * @return Non-zero on success; zero on failure.
746 int connect_server(struct ConfItem* aconf, struct Client* by)
748 struct Client* cptr = 0;
751 if (aconf->dns_pending) {
752 sendto_opmask_butone(0, SNO_OLDSNO, "Server %s connect DNS pending",
756 Debug((DEBUG_NOTICE, "Connect to %s[@%s]", aconf->name,
757 ircd_ntoa(&aconf->address.addr)));
759 if ((cptr = FindClient(aconf->name))) {
760 if (IsServer(cptr) || IsMe(cptr)) {
761 sendto_opmask_butone(0, SNO_OLDSNO, "Server %s already present from %s",
762 aconf->name, cli_name(cli_from(cptr)));
763 if (by && IsUser(by) && !MyUser(by)) {
764 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Server %s already present "
765 "from %s", by, aconf->name, cli_name(cli_from(cptr)));
769 else if (IsHandshake(cptr) || IsConnecting(cptr)) {
770 if (by && IsUser(by)) {
771 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Connection to %s already in "
772 "progress", by, cli_name(cptr));
778 * If we dont know the IP# for this host and it is a hostname and
779 * not a ip# string, then try and find the appropriate host record.
781 if (!irc_in_addr_valid(&aconf->address.addr)
782 && !ircd_aton(&aconf->address.addr, aconf->host)) {
783 char buf[HOSTLEN + 1];
784 struct DNSQuery query;
787 query.callback = connect_dns_callback;
788 host_from_uh(buf, aconf->host, HOSTLEN);
791 gethost_byname(buf, &query);
792 aconf->dns_pending = 1;
795 cptr = make_client(NULL, STAT_UNKNOWN_SERVER);
798 * Copy these in so we have something for error detection.
800 ircd_strncpy(cli_name(cptr), aconf->name, HOSTLEN);
801 ircd_strncpy(cli_sockhost(cptr), aconf->host, HOSTLEN);
804 * Attach config entries to client here rather than in
805 * completed_connection. This to avoid null pointer references
807 attach_confs_byhost(cptr, aconf->host, CONF_SERVER);
809 if (!find_conf_byhost(cli_confs(cptr), aconf->host, CONF_SERVER)) {
810 sendto_opmask_butone(0, SNO_OLDSNO, "Host %s is not enabled for "
811 "connecting: no C-line", aconf->name);
812 if (by && IsUser(by) && !MyUser(by)) {
813 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Connect to host %s failed: no "
814 "C-line", by, aconf->name);
816 det_confs_butmask(cptr, 0);
821 * attempt to connect to the server in the conf line
823 if (!connect_inet(aconf, cptr)) {
824 if (by && IsUser(by) && !MyUser(by)) {
825 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Couldn't connect to %s", by,
828 det_confs_butmask(cptr, 0);
833 * NOTE: if we're here we have a valid C:Line and the client should
834 * have started the connection and stored the remote address/port and
835 * ip address name in itself
837 * The socket has been connected or connect is in progress.
840 if (by && IsUser(by)) {
841 ircd_snprintf(0, cli_serv(cptr)->by, sizeof(cli_serv(cptr)->by), "%s%s",
843 assert(0 == cli_serv(cptr)->user);
844 cli_serv(cptr)->user = cli_user(by);
845 cli_user(by)->refcnt++;
848 *(cli_serv(cptr))->by = '\0';
849 /* strcpy(cptr->serv->by, "Auto"); */
851 cli_serv(cptr)->up = &me;
854 if (cli_fd(cptr) > HighestFd)
855 HighestFd = cli_fd(cptr);
857 LocalClientArray[cli_fd(cptr)] = cptr;
859 Count_newunknown(UserStats);
860 /* Actually we lie, the connect hasn't succeeded yet, but we have a valid
861 * cptr, so we register it now.
862 * Maybe these two calls should be merged.
864 add_client_to_list(cptr);
866 /* nextping = CurrentTime; */
868 return (s_state(&cli_socket(cptr)) == SS_CONNECTED) ?
869 completed_connection(cptr) : 1;
872 /** Find the real hostname for the host running the server (or one which
873 * matches the server's name) and its primary IP#. Hostname is stored
874 * in the client structure passed as a pointer.
876 void init_server_identity(void)
878 const struct LocalConf* conf = conf_get_local();
881 ircd_strncpy(cli_name(&me), conf->name, HOSTLEN);
882 SetYXXServerName(&me, conf->numeric);
885 /** Process events on a client socket.
886 * @param ev Socket event structure that has a struct Connection as
887 * its associated data.
889 static void client_sock_callback(struct Event* ev)
892 struct Connection* con;
896 assert(0 != ev_socket(ev));
897 assert(0 != s_data(ev_socket(ev)));
899 con = (struct Connection*) s_data(ev_socket(ev));
901 assert(0 != con_client(con) || ev_type(ev) == ET_DESTROY);
903 cptr = con_client(con);
905 assert(0 == cptr || con == cli_connect(cptr));
907 switch (ev_type(ev)) {
909 con_freeflag(con) &= ~FREEFLAG_SOCKET;
911 if (!con_freeflag(con) && !cptr)
912 free_connection(con);
915 case ET_CONNECT: /* socket connection completed */
916 if (!completed_connection(cptr) || IsDead(cptr))
917 fallback = cli_info(cptr);
920 case ET_ERROR: /* an error occurred */
921 fallback = cli_info(cptr);
922 cli_error(cptr) = ev_data(ev);
923 if (s_state(&(con_socket(con))) == SS_CONNECTING) {
924 completed_connection(cptr);
928 case ET_EOF: /* end of file on socket */
929 Debug((DEBUG_ERROR, "READ ERROR: fd = %d %d", cli_fd(cptr),
931 SetFlag(cptr, FLAG_DEADSOCKET);
932 if ((IsServer(cptr) || IsHandshake(cptr)) && cli_error(cptr) == 0) {
933 exit_client_msg(cptr, cptr, &me, "Server %s closed the connection (%s)",
934 cli_name(cptr), cli_serv(cptr)->last_error_msg);
937 fmt = "Read error: %s";
938 fallback = "EOF from client";
942 case ET_WRITE: /* socket is writable */
943 ClrFlag(cptr, FLAG_BLOCKED);
944 if (cli_listing(cptr) && MsgQLength(&(cli_sendQ(cptr))) < 2048)
945 list_next_channels(cptr, 64);
946 Debug((DEBUG_SEND, "Sending queued data to %C", cptr));
950 case ET_READ: /* socket is readable */
952 Debug((DEBUG_DEBUG, "Reading data from %C", cptr));
953 if (read_packet(cptr, 1) == 0) /* error while reading packet */
954 fallback = "EOF from client";
959 assert(0 && "Unrecognized socket event in client_sock_callback()");
963 assert(0 == cptr || 0 == cli_connect(cptr) || con == cli_connect(cptr));
966 const char* msg = (cli_error(cptr)) ? strerror(cli_error(cptr)) : fallback;
968 msg = "Unknown error";
969 exit_client_msg(cptr, cptr, &me, fmt, msg);
973 /** Process a timer on client socket.
974 * @param ev Timer event that has a struct Connection as its
977 static void client_timer_callback(struct Event* ev)
980 struct Connection* con;
982 assert(0 != ev_timer(ev));
983 assert(0 != t_data(ev_timer(ev)));
984 assert(ET_DESTROY == ev_type(ev) || ET_EXPIRE == ev_type(ev));
986 con = (struct Connection*) t_data(ev_timer(ev));
988 assert(0 != con_client(con) || ev_type(ev) == ET_DESTROY);
990 cptr = con_client(con);
992 assert(0 == cptr || con == cli_connect(cptr));
994 if (ev_type(ev)== ET_DESTROY) {
995 con_freeflag(con) &= ~FREEFLAG_TIMER; /* timer has expired... */
997 if (!con_freeflag(con) && !cptr)
998 free_connection(con); /* client is being destroyed */
1000 Debug((DEBUG_LIST, "Client process timer for %C expired; processing",
1002 read_packet(cptr, 0); /* read_packet will re-add timer if needed */
1005 assert(0 == cptr || 0 == cli_connect(cptr) || con == cli_connect(cptr));