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.
30 #include "ircd_alloc.h"
32 #include "ircd_features.h"
33 #include "ircd_osdep.h"
34 #include "ircd_reply.h"
35 #include "ircd_snprintf.h"
36 #include "ircd_string.h"
46 #include "querycmds.h"
60 #include <arpa/inet.h>
68 #include <sys/ioctl.h>
69 #include <sys/socket.h>
71 #include <sys/utsname.h>
78 struct Client* LocalClientArray[MAXCONNECTIONS];
80 struct irc_sockaddr VirtualHost;
81 static char readbuf[SERVER_TCP_WINDOW];
84 * report_error text constants
86 const char* const ACCEPT_ERROR_MSG = "error accepting connection for %s: %s";
87 const char* const BIND_ERROR_MSG = "bind error for %s: %s";
88 const char* const CONNECT_ERROR_MSG = "connect to host %s failed: %s";
89 const char* const CONNLIMIT_ERROR_MSG = "connect limit exceeded for %s: %s";
90 const char* const LISTEN_ERROR_MSG = "listen error for %s: %s";
91 const char* const NONB_ERROR_MSG = "error setting non-blocking for %s: %s";
92 const char* const PEERNAME_ERROR_MSG = "getpeername failed for %s: %s";
93 const char* const POLL_ERROR_MSG = "poll error for %s: %s";
94 const char* const REGISTER_ERROR_MSG = "registering %s: %s";
95 const char* const REUSEADDR_ERROR_MSG = "error setting SO_REUSEADDR for %s: %s";
96 const char* const SELECT_ERROR_MSG = "select error for %s: %s";
97 const char* const SETBUFS_ERROR_MSG = "error setting buffer size for %s: %s";
98 const char* const SOCKET_ERROR_MSG = "error creating socket for %s: %s";
99 const char* const TOS_ERROR_MSG = "error setting TOS for %s: %s";
102 static void client_sock_callback(struct Event* ev);
103 static void client_timer_callback(struct Event* ev);
105 #if !defined(USE_POLL)
106 #if FD_SETSIZE < (MAXCONNECTIONS + 4)
110 * All operating systems work when MAXCONNECTIONS <= 252.
111 * Most operating systems work when MAXCONNECTIONS <= 1020 and FD_SETSIZE is
112 * updated correctly in the system headers (on BSD systems our sys.h has
113 * defined FD_SETSIZE to MAXCONNECTIONS+4 before including the system's headers
114 * but sys/types.h might have abruptly redefined it so the check is still
115 * done), you might already need to recompile your kernel.
116 * For larger FD_SETSIZE your milage may vary (kernel patches may be needed).
117 * The check is _NOT_ done if we will not use FD_SETS at all (USE_POLL)
119 #error "FD_SETSIZE is too small or MAXCONNECTIONS too large."
125 * Cannot use perror() within daemon. stderr is closed in
126 * ircd and cannot be used. And, worse yet, it might have
127 * been reassigned to a normal connection...
133 * This a replacement for perror(). Record error to log and
134 * also send a copy to all *LOCAL* opers online.
136 * text is a *format* string for outputting error. It must
137 * contain only two '%s', the first will be replaced
138 * by the sockhost from the cptr, and the latter will
139 * be taken from sys_errlist[errno].
141 * cptr if not NULL, is the *LOCAL* client associated with
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);
169 * connect_dns_callback - called when resolver query finishes
170 * if the query resulted in a successful search, reply will contain
171 * a non-null pointer, otherwise reply will be null.
172 * if successful start the connection, otherwise notify opers
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",
190 * close_connections - closes all connections
191 * close stderr if specified
193 void close_connections(int close_stderr)
200 for (i = 3; i < MAXCONNECTIONS; ++i)
205 * init_connection_limits - initialize process fd limit to
208 int init_connection_limits(void)
210 int limit = os_set_fdlimit(MAXCONNECTIONS);
214 fprintf(stderr, "error setting max fd's to %d\n", limit);
216 else if (limit > 0) {
217 fprintf(stderr, "ircd fd table too big\nHard Limit: %d IRC max: %d\n",
218 limit, MAXCONNECTIONS);
219 fprintf(stderr, "set MAXCONNECTIONS to a smaller value");
225 * connect_inet - set up address and port and make a connection
227 static int connect_inet(struct ConfItem* aconf, struct Client* cptr)
233 * Might as well get sockhost from here, the connection is attempted
234 * with it so if it fails its useless.
236 cli_fd(cptr) = os_socket((feature_bool(FEAT_VIRTUAL_HOST) ? &VirtualHost : NULL), SOCK_STREAM, cli_name(cptr));
237 if (cli_fd(cptr) < 0)
241 * save connection info in client
243 memcpy(&cli_ip(cptr), &aconf->address.addr, sizeof(cli_ip(cptr)));
244 cli_port(cptr) = aconf->address.port;
245 ircd_ntoa_r(cli_sock_ip(cptr), &cli_ip(cptr));
247 * we want a big buffer for server connections
249 if (!os_set_sockbufs(cli_fd(cptr), feature_int(FEAT_SOCKSENDBUF), feature_int(FEAT_SOCKRECVBUF))) {
250 cli_error(cptr) = errno;
251 report_error(SETBUFS_ERROR_MSG, cli_name(cptr), errno);
256 if ((result = os_connect_nonb(cli_fd(cptr), &aconf->address)) == IO_FAILURE) {
257 cli_error(cptr) = errno;
258 report_error(CONNECT_ERROR_MSG, cli_name(cptr), errno);
263 if (!socket_add(&(cli_socket(cptr)), client_sock_callback,
264 (void*) cli_connect(cptr),
265 (result == IO_SUCCESS) ? SS_CONNECTED : SS_CONNECTING,
266 SOCK_EVENT_READABLE, cli_fd(cptr))) {
267 cli_error(cptr) = ENFILE;
268 report_error(REGISTER_ERROR_MSG, cli_name(cptr), ENFILE);
273 cli_freeflag(cptr) |= FREEFLAG_SOCKET;
279 * Attempt to send a sequence of bytes to the connection.
282 * < 0 Some fatal error occurred, (but not EWOULDBLOCK).
283 * This return is a request to close the socket and
286 * >= 0 No real error occurred, returns the number of
287 * bytes actually transferred. EWOULDBLOCK and other
288 * possibly similar conditions should be mapped to
289 * zero return. Upper level routine will have to
290 * decide what to do with those unwritten bytes...
292 * *NOTE* alarm calls have been preserved, so this should
293 * work equally well whether blocking or non-blocking
296 * We don't use blocking anymore, that is impossible with the
297 * net.loads today anyway. Commented out the alarms to save cpu.
300 unsigned int deliver_it(struct Client *cptr, struct MsgQ *buf)
302 unsigned int bytes_written = 0;
303 unsigned int bytes_count = 0;
306 switch (os_sendv_nonb(cli_fd(cptr), buf, &bytes_count, &bytes_written)) {
308 ClrFlag(cptr, FLAG_BLOCKED);
310 cli_sendB(cptr) += bytes_written;
311 cli_sendB(&me) += bytes_written;
312 if (cli_sendB(cptr) > 1023) {
313 cli_sendK(cptr) += (cli_sendB(cptr) >> 10);
314 cli_sendB(cptr) &= 0x03ff; /* 2^10 = 1024, 3ff = 1023 */
316 if (cli_sendB(&me) > 1023) {
317 cli_sendK(&me) += (cli_sendB(&me) >> 10);
318 cli_sendB(&me) &= 0x03ff;
321 * XXX - hrmm.. set blocked here? the socket didn't
324 if (bytes_written < bytes_count)
325 SetFlag(cptr, FLAG_BLOCKED);
328 SetFlag(cptr, FLAG_BLOCKED);
331 cli_error(cptr) = errno;
332 SetFlag(cptr, FLAG_DEADSOCKET);
335 return bytes_written;
339 void release_dns_reply(struct Client* cptr)
342 assert(MyConnect(cptr));
344 if (cli_dns_reply(cptr)) {
345 MyFree(cli_dns_reply(cptr)->h_name);
346 MyFree(cli_dns_reply(cptr));
347 cli_dns_reply(cptr) = 0;
352 * completed_connection
354 * Complete non-blocking connect()-sequence. Check access and
355 * terminate connection, if trouble detected.
357 * Return TRUE, if successfully completed
358 * FALSE, if failed and ClientExit
360 static int completed_connection(struct Client* cptr)
362 struct ConfItem *aconf;
364 struct Client *acptr;
370 * get the socket status from the fd first to check if
371 * connection actually succeeded
373 if ((cli_error(cptr) = os_get_sockerr(cli_fd(cptr)))) {
374 const char* msg = strerror(cli_error(cptr));
376 msg = "Unknown error";
377 sendto_opmask_butone(0, SNO_OLDSNO, "Connection failed to %s: %s",
378 cli_name(cptr), msg);
381 if (!(aconf = find_conf_byname(cli_confs(cptr), cli_name(cptr), CONF_SERVER))) {
382 sendto_opmask_butone(0, SNO_OLDSNO, "Lost Server Line for %s", cli_name(cptr));
385 if (s_state(&(cli_socket(cptr))) == SS_CONNECTING)
386 socket_state(&(cli_socket(cptr)), SS_CONNECTED);
388 if (!EmptyString(aconf->passwd))
389 sendrawto_one(cptr, MSG_PASS " :%s", aconf->passwd);
392 * Create a unique timestamp
395 for (i = HighestFd; i > -1; --i) {
396 if ((acptr = LocalClientArray[i]) &&
397 (IsServer(acptr) || IsHandshake(acptr))) {
398 if (cli_serv(acptr)->timestamp >= newts)
399 newts = cli_serv(acptr)->timestamp + 1;
402 assert(0 != cli_serv(cptr));
404 cli_serv(cptr)->timestamp = newts;
407 * Make us timeout after twice the timeout for DNS look ups
409 cli_lasttime(cptr) = CurrentTime;
410 SetFlag(cptr, FLAG_PINGSENT);
412 sendrawto_one(cptr, MSG_SERVER " %s 1 %Tu %Tu J%s %s%s +%s :%s",
413 cli_name(&me), cli_serv(&me)->timestamp, newts,
414 MAJOR_PROTOCOL, NumServCap(&me),
415 feature_bool(FEAT_HUB) ? "h" : "", cli_info(&me));
417 return (IsDead(cptr)) ? 0 : 1;
423 * Close the physical connection. This function must make
424 * MyConnect(cptr) == FALSE, and set cptr->from == NULL.
426 void close_connection(struct Client *cptr)
428 struct ConfItem* aconf;
430 if (IsServer(cptr)) {
431 ServerStats->is_sv++;
432 ServerStats->is_sbs += cli_sendB(cptr);
433 ServerStats->is_sbr += cli_receiveB(cptr);
434 ServerStats->is_sks += cli_sendK(cptr);
435 ServerStats->is_skr += cli_receiveK(cptr);
436 ServerStats->is_sti += CurrentTime - cli_firsttime(cptr);
437 if (ServerStats->is_sbs > 1023) {
438 ServerStats->is_sks += (ServerStats->is_sbs >> 10);
439 ServerStats->is_sbs &= 0x3ff;
441 if (ServerStats->is_sbr > 1023) {
442 ServerStats->is_skr += (ServerStats->is_sbr >> 10);
443 ServerStats->is_sbr &= 0x3ff;
446 * If the connection has been up for a long amount of time, schedule
447 * a 'quick' reconnect, else reset the next-connect cycle.
449 if ((aconf = find_conf_exact(cli_name(cptr), 0, cli_sockhost(cptr), CONF_SERVER))) {
451 * Reschedule a faster reconnect, if this was a automaticly
452 * connected configuration entry. (Note that if we have had
453 * a rehash in between, the status has been changed to
454 * CONF_ILLEGAL). But only do this if it was a "good" link.
456 aconf->hold = CurrentTime;
457 aconf->hold += ((aconf->hold - cli_since(cptr) >
458 feature_int(FEAT_HANGONGOODLINK)) ?
459 feature_int(FEAT_HANGONRETRYDELAY) : ConfConFreq(aconf));
460 /* if (nextconnect > aconf->hold) */
461 /* nextconnect = aconf->hold; */
464 else if (IsUser(cptr)) {
465 ServerStats->is_cl++;
466 ServerStats->is_cbs += cli_sendB(cptr);
467 ServerStats->is_cbr += cli_receiveB(cptr);
468 ServerStats->is_cks += cli_sendK(cptr);
469 ServerStats->is_ckr += cli_receiveK(cptr);
470 ServerStats->is_cti += CurrentTime - cli_firsttime(cptr);
471 if (ServerStats->is_cbs > 1023) {
472 ServerStats->is_cks += (ServerStats->is_cbs >> 10);
473 ServerStats->is_cbs &= 0x3ff;
475 if (ServerStats->is_cbr > 1023) {
476 ServerStats->is_ckr += (ServerStats->is_cbr >> 10);
477 ServerStats->is_cbr &= 0x3ff;
481 ServerStats->is_ni++;
483 if (-1 < cli_fd(cptr)) {
484 flush_connections(cptr);
485 LocalClientArray[cli_fd(cptr)] = 0;
487 socket_del(&(cli_socket(cptr))); /* queue a socket delete */
490 SetFlag(cptr, FLAG_DEADSOCKET);
492 MsgQClear(&(cli_sendQ(cptr)));
493 client_drop_sendq(cli_connect(cptr));
494 DBufClear(&(cli_recvQ(cptr)));
495 memset(cli_passwd(cptr), 0, sizeof(cli_passwd(cptr)));
496 set_snomask(cptr, 0, SNO_SET);
498 det_confs_butmask(cptr, 0);
500 if (cli_listener(cptr)) {
501 release_listener(cli_listener(cptr));
502 cli_listener(cptr) = 0;
505 for ( ; HighestFd > 0; --HighestFd) {
506 if (LocalClientArray[HighestFd])
511 int net_close_unregistered_connections(struct Client* source)
518 for (i = HighestFd; i > 0; --i) {
519 if ((cptr = LocalClientArray[i]) && !IsRegistered(cptr)) {
520 send_reply(source, RPL_CLOSING, get_client_name(source, HIDE_IP));
521 exit_client(source, cptr, &me, "Oper Closing");
528 /*----------------------------------------------------------------------------
531 * Creates a client which has just connected to us on the given fd.
532 * The sockhost field is initialized with the ip# of the host.
533 * The client is not added to the linked list of clients, it is
534 * passed off to the auth handler for dns and ident queries.
535 *--------------------------------------------------------------------------*/
536 void add_connection(struct Listener* listener, int fd) {
537 struct irc_sockaddr addr;
538 struct Client *new_client;
539 time_t next_target = 0;
541 const char* const throttle_message =
542 "ERROR :Your host is trying to (re)connect too fast -- throttled\r\n";
543 /* 12345678901234567890123456789012345679012345678901234567890123456 */
544 const char* const register_message =
545 "ERROR :Unable to complete your registration\r\n";
547 assert(0 != listener);
550 * Removed preliminary access check. Full check is performed in m_server and
551 * m_user instead. Also connection time out help to get rid of unwanted
554 if (!os_get_peername(fd, &addr) || !os_set_nonblocking(fd)) {
555 ++ServerStats->is_ref;
560 * Disable IP (*not* TCP) options. In particular, this makes it impossible
561 * to use source routing to connect to the server. If we didn't do this
562 * (and if intermediate networks didn't drop source-routed packets), an
563 * attacker could successfully IP spoof us...and even return the anti-spoof
564 * ping, because the options would cause the packet to be routed back to
565 * the spoofer's machine. When we disable the IP options, we delete the
566 * source route, and the normal routing takes over.
568 os_disable_options(fd);
571 * Add this local client to the IPcheck registry.
573 * If they're throttled, murder them, but tell them why first.
575 if (!IPcheck_local_connect(&addr.addr, &next_target) && !listener->server)
577 ++ServerStats->is_ref;
578 write(fd, throttle_message, strlen(throttle_message));
583 new_client = make_client(0, ((listener->server) ?
584 STAT_UNKNOWN_SERVER : STAT_UNKNOWN_USER));
587 * Copy ascii address to 'sockhost' just in case. Then we have something
588 * valid to put into error messages...
590 SetIPChecked(new_client);
591 ircd_ntoa_r(cli_sock_ip(new_client), &addr.addr);
592 strcpy(cli_sockhost(new_client), cli_sock_ip(new_client));
593 memcpy(&cli_ip(new_client), &addr.addr, sizeof(cli_ip(new_client)));
594 cli_port(new_client) = addr.port;
597 cli_nexttarget(new_client) = next_target;
599 cli_fd(new_client) = fd;
600 if (!socket_add(&(cli_socket(new_client)), client_sock_callback,
601 (void*) cli_connect(new_client), SS_CONNECTED, 0, fd)) {
602 ++ServerStats->is_ref;
603 write(fd, register_message, strlen(register_message));
605 cli_fd(new_client) = -1;
608 cli_freeflag(new_client) |= FREEFLAG_SOCKET;
609 cli_listener(new_client) = listener;
610 ++listener->ref_count;
612 Count_newunknown(UserStats);
613 /* if we've made it this far we can put the client on the auth query pile */
614 start_auth(new_client);
620 * Determines whether to tell the events engine we're interested in
623 void update_write(struct Client* cptr)
625 /* If there are messages that need to be sent along, or if the client
626 * is in the middle of a /list, then we need to tell the engine that
627 * we're interested in writable events--otherwise, we need to drop
630 socket_events(&(cli_socket(cptr)),
631 ((MsgQLength(&cli_sendQ(cptr)) || cli_listing(cptr)) ?
632 SOCK_ACTION_ADD : SOCK_ACTION_DEL) | SOCK_EVENT_WRITABLE);
638 * Read a 'packet' of data from a connection and process it. Read in 8k
639 * chunks to give a better performance rating (for server connections).
640 * Do some tricky stuff for client connections to make sure they don't do
641 * any flooding >:-) -avalon
643 static int read_packet(struct Client *cptr, int socket_ready)
645 unsigned int dolen = 0;
646 unsigned int length = 0;
650 DBufLength(&(cli_recvQ(cptr))) > feature_int(FEAT_CLIENT_FLOOD))) {
651 switch (os_recv_nonb(cli_fd(cptr), readbuf, sizeof(readbuf), &length)) {
656 cli_lasttime(cptr) = CurrentTime;
657 if (cli_lasttime(cptr) > cli_since(cptr))
658 cli_since(cptr) = cli_lasttime(cptr);
659 ClrFlag(cptr, FLAG_PINGSENT);
660 ClrFlag(cptr, FLAG_NONL);
666 cli_error(cptr) = errno;
667 /* SetFlag(cpt, FLAG_DEADSOCKET); */
673 * For server connections, we process as many as we can without
674 * worrying about the time of day or anything :)
676 if (length > 0 && IsServer(cptr))
677 return server_dopacket(cptr, readbuf, length);
678 else if (length > 0 && (IsHandshake(cptr) || IsConnecting(cptr)))
679 return connect_dopacket(cptr, readbuf, length);
683 * Before we even think of parsing what we just read, stick
684 * it on the end of the receive queue and do it when its
687 if (length > 0 && dbuf_put(&(cli_recvQ(cptr)), readbuf, length) == 0)
688 return exit_client(cptr, cptr, &me, "dbuf_put fail");
690 if (DBufLength(&(cli_recvQ(cptr))) > feature_int(FEAT_CLIENT_FLOOD))
691 return exit_client(cptr, cptr, &me, "Excess Flood");
693 while (DBufLength(&(cli_recvQ(cptr))) && !NoNewLine(cptr) &&
694 (IsTrusted(cptr) || cli_since(cptr) - CurrentTime < 10))
696 dolen = dbuf_getmsg(&(cli_recvQ(cptr)), cli_buffer(cptr), BUFSIZE);
698 * Devious looking...whats it do ? well..if a client
699 * sends a *long* message without any CR or LF, then
700 * dbuf_getmsg fails and we pull it out using this
701 * loop which just gets the next 512 bytes and then
702 * deletes the rest of the buffer contents.
707 if (DBufLength(&(cli_recvQ(cptr))) < 510)
708 SetFlag(cptr, FLAG_NONL);
710 DBufClear(&(cli_recvQ(cptr)));
712 else if (client_dopacket(cptr, dolen) == CPTR_KILLED)
715 * If it has become registered as a Server
716 * then skip the per-message parsing below.
718 if (IsHandshake(cptr) || IsServer(cptr))
722 dolen = dbuf_get(&(cli_recvQ(cptr)), readbuf, sizeof(readbuf));
727 if (DBufLength(&(cli_recvQ(cptr))) < 510)
728 SetFlag(cptr, FLAG_NONL);
730 DBufClear(&(cli_recvQ(cptr)));
732 else if ((IsServer(cptr) &&
733 server_dopacket(cptr, readbuf, dolen) == CPTR_KILLED) ||
735 connect_dopacket(cptr, readbuf, dolen) == CPTR_KILLED))
741 /* If there's still data to process, wait 2 seconds first */
742 if (DBufLength(&(cli_recvQ(cptr))) && !NoNewLine(cptr) &&
743 !t_onqueue(&(cli_proc(cptr))))
745 Debug((DEBUG_LIST, "Adding client process timer for %C", cptr));
746 cli_freeflag(cptr) |= FREEFLAG_TIMER;
747 timer_add(&(cli_proc(cptr)), client_timer_callback, cli_connect(cptr),
755 * connect_server - start or complete a connection to another server
756 * returns true (1) if successful, false (0) otherwise
758 * aconf must point to a valid C:line
759 * m_connect calls this with a valid by client and a null reply
760 * try_connections calls this with a null by client, and a null reply
761 * connect_dns_callback call this with a null by client, and a valid reply
763 * XXX - if this comes from an m_connect message and a dns query needs to
764 * be done, we loose the information about who started the connection and
765 * it's considered an auto connect.
767 int connect_server(struct ConfItem* aconf, struct Client* by)
769 struct Client* cptr = 0;
772 if (aconf->dns_pending) {
773 sendto_opmask_butone(0, SNO_OLDSNO, "Server %s connect DNS pending",
777 Debug((DEBUG_NOTICE, "Connect to %s[@%s]", aconf->name,
778 ircd_ntoa(&aconf->address.addr)));
780 if ((cptr = FindClient(aconf->name))) {
781 if (IsServer(cptr) || IsMe(cptr)) {
782 sendto_opmask_butone(0, SNO_OLDSNO, "Server %s already present from %s",
783 aconf->name, cli_name(cli_from(cptr)));
784 if (by && IsUser(by) && !MyUser(by)) {
785 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Server %s already present "
786 "from %s", by, aconf->name, cli_name(cli_from(cptr)));
790 else if (IsHandshake(cptr) || IsConnecting(cptr)) {
791 if (by && IsUser(by)) {
792 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Connection to %s already in "
793 "progress", by, cli_name(cptr));
799 * If we dont know the IP# for this host and it is a hostname and
800 * not a ip# string, then try and find the appropriate host record.
802 if (!irc_in_addr_valid(&aconf->address.addr)
803 && !ircd_aton(&aconf->address.addr, aconf->host)) {
804 char buf[HOSTLEN + 1];
805 struct DNSQuery query;
808 query.callback = connect_dns_callback;
809 host_from_uh(buf, aconf->host, HOSTLEN);
812 gethost_byname(buf, &query);
813 aconf->dns_pending = 1;
816 cptr = make_client(NULL, STAT_UNKNOWN_SERVER);
819 * Copy these in so we have something for error detection.
821 ircd_strncpy(cli_name(cptr), aconf->name, HOSTLEN);
822 ircd_strncpy(cli_sockhost(cptr), aconf->host, HOSTLEN);
825 * Attach config entries to client here rather than in
826 * completed_connection. This to avoid null pointer references
828 attach_confs_byhost(cptr, aconf->host, CONF_SERVER);
830 if (!find_conf_byhost(cli_confs(cptr), aconf->host, CONF_SERVER)) {
831 sendto_opmask_butone(0, SNO_OLDSNO, "Host %s is not enabled for "
832 "connecting: no C-line", aconf->name);
833 if (by && IsUser(by) && !MyUser(by)) {
834 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Connect to host %s failed: no "
835 "C-line", by, aconf->name);
837 det_confs_butmask(cptr, 0);
842 * attempt to connect to the server in the conf line
844 if (!connect_inet(aconf, cptr)) {
845 if (by && IsUser(by) && !MyUser(by)) {
846 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Couldn't connect to %s", by,
849 det_confs_butmask(cptr, 0);
854 * NOTE: if we're here we have a valid C:Line and the client should
855 * have started the connection and stored the remote address/port and
856 * ip address name in itself
858 * The socket has been connected or connect is in progress.
861 if (by && IsUser(by)) {
862 ircd_snprintf(0, cli_serv(cptr)->by, sizeof(cli_serv(cptr)->by), "%s%s",
864 assert(0 == cli_serv(cptr)->user);
865 cli_serv(cptr)->user = cli_user(by);
866 cli_user(by)->refcnt++;
869 *(cli_serv(cptr))->by = '\0';
870 /* strcpy(cptr->serv->by, "Auto"); */
872 cli_serv(cptr)->up = &me;
875 if (cli_fd(cptr) > HighestFd)
876 HighestFd = cli_fd(cptr);
879 LocalClientArray[cli_fd(cptr)] = cptr;
881 Count_newunknown(UserStats);
882 /* Actually we lie, the connect hasn't succeeded yet, but we have a valid
883 * cptr, so we register it now.
884 * Maybe these two calls should be merged.
886 add_client_to_list(cptr);
888 /* nextping = CurrentTime; */
890 return (s_state(&cli_socket(cptr)) == SS_CONNECTED) ?
891 completed_connection(cptr) : 1;
895 * Setup local socket structure to use for binding to.
897 void set_virtual_host(const struct irc_in_addr *addr)
899 memset(&VirtualHost, 0, sizeof(VirtualHost));
900 memcpy(&VirtualHost.addr, addr, sizeof(VirtualHost.addr));
904 * Find the real hostname for the host running the server (or one which
905 * matches the server's name) and its primary IP#. Hostname is stored
906 * in the client structure passed as a pointer.
908 void init_server_identity(void)
910 const struct LocalConf* conf = conf_get_local();
913 ircd_strncpy(cli_name(&me), conf->name, HOSTLEN);
914 SetYXXServerName(&me, conf->numeric);
918 * Process events on a client socket
920 static void client_sock_callback(struct Event* ev)
923 struct Connection* con;
927 assert(0 != ev_socket(ev));
928 assert(0 != s_data(ev_socket(ev)));
930 con = (struct Connection*) s_data(ev_socket(ev));
932 assert(0 != con_client(con) || ev_type(ev) == ET_DESTROY);
934 cptr = con_client(con);
936 assert(0 == cptr || con == cli_connect(cptr));
938 switch (ev_type(ev)) {
940 con_freeflag(con) &= ~FREEFLAG_SOCKET;
942 if (!con_freeflag(con) && !cptr)
943 free_connection(con);
946 case ET_CONNECT: /* socket connection completed */
947 if (!completed_connection(cptr) || IsDead(cptr))
948 fallback = cli_info(cptr);
951 case ET_ERROR: /* an error occurred */
952 fallback = cli_info(cptr);
953 cli_error(cptr) = ev_data(ev);
954 if (s_state(&(con_socket(con))) == SS_CONNECTING) {
955 completed_connection(cptr);
959 case ET_EOF: /* end of file on socket */
960 Debug((DEBUG_ERROR, "READ ERROR: fd = %d %d", cli_fd(cptr),
962 SetFlag(cptr, FLAG_DEADSOCKET);
963 if ((IsServer(cptr) || IsHandshake(cptr)) && cli_error(cptr) == 0) {
964 exit_client_msg(cptr, cptr, &me, "Server %s closed the connection (%s)",
965 cli_name(cptr), cli_serv(cptr)->last_error_msg);
968 fmt = "Read error: %s";
969 fallback = "EOF from client";
973 case ET_WRITE: /* socket is writable */
974 ClrFlag(cptr, FLAG_BLOCKED);
975 if (cli_listing(cptr) && MsgQLength(&(cli_sendQ(cptr))) < 2048)
976 list_next_channels(cptr, 64);
977 Debug((DEBUG_SEND, "Sending queued data to %C", cptr));
981 case ET_READ: /* socket is readable */
983 Debug((DEBUG_DEBUG, "Reading data from %C", cptr));
984 if (read_packet(cptr, 1) == 0) /* error while reading packet */
985 fallback = "EOF from client";
991 abort(); /* unrecognized event */
996 assert(0 == cptr || 0 == cli_connect(cptr) || con == cli_connect(cptr));
999 const char* msg = (cli_error(cptr)) ? strerror(cli_error(cptr)) : fallback;
1001 msg = "Unknown error";
1002 exit_client_msg(cptr, cptr, &me, fmt, msg);
1007 * Process a timer on client socket
1009 static void client_timer_callback(struct Event* ev)
1011 struct Client* cptr;
1012 struct Connection* con;
1014 assert(0 != ev_timer(ev));
1015 assert(0 != t_data(ev_timer(ev)));
1016 assert(ET_DESTROY == ev_type(ev) || ET_EXPIRE == ev_type(ev));
1018 con = (struct Connection*) t_data(ev_timer(ev));
1020 assert(0 != con_client(con) || ev_type(ev) == ET_DESTROY);
1022 cptr = con_client(con);
1024 assert(0 == cptr || con == cli_connect(cptr));
1026 if (ev_type(ev)== ET_DESTROY) {
1027 con_freeflag(con) &= ~FREEFLAG_TIMER; /* timer has expired... */
1029 if (!con_freeflag(con) && !cptr)
1030 free_connection(con); /* client is being destroyed */
1032 Debug((DEBUG_LIST, "Client process timer for %C expired; processing",
1034 read_packet(cptr, 0); /* read_packet will re-add timer if needed */
1037 assert(0 == cptr || 0 == cli_connect(cptr) || con == cli_connect(cptr));