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>
61 #include <arpa/nameser.h>
70 #include <sys/ioctl.h>
71 #include <sys/socket.h>
73 #include <sys/utsname.h>
81 #define INADDR_NONE 0xffffffff
84 struct Client* LocalClientArray[MAXCONNECTIONS];
86 struct sockaddr_in VirtualHost;
87 static char readbuf[SERVER_TCP_WINDOW];
90 * report_error text constants
92 const char* const ACCEPT_ERROR_MSG = "error accepting connection for %s: %s";
93 const char* const BIND_ERROR_MSG = "bind error for %s: %s";
94 const char* const CONNECT_ERROR_MSG = "connect to host %s failed: %s";
95 const char* const CONNLIMIT_ERROR_MSG = "connect limit exceeded for %s: %s";
96 const char* const LISTEN_ERROR_MSG = "listen error for %s: %s";
97 const char* const NONB_ERROR_MSG = "error setting non-blocking for %s: %s";
98 const char* const PEERNAME_ERROR_MSG = "getpeername failed for %s: %s";
99 const char* const POLL_ERROR_MSG = "poll error for %s: %s";
100 const char* const REGISTER_ERROR_MSG = "registering %s: %s";
101 const char* const REUSEADDR_ERROR_MSG = "error setting SO_REUSEADDR for %s: %s";
102 const char* const SELECT_ERROR_MSG = "select error for %s: %s";
103 const char* const SETBUFS_ERROR_MSG = "error setting buffer size for %s: %s";
104 const char* const SOCKET_ERROR_MSG = "error creating socket for %s: %s";
105 const char* const TOS_ERROR_MSG = "error setting TOS for %s: %s";
108 static void client_sock_callback(struct Event* ev);
109 static void client_timer_callback(struct Event* ev);
111 #if !defined(USE_POLL)
112 #if FD_SETSIZE < (MAXCONNECTIONS + 4)
116 * All operating systems work when MAXCONNECTIONS <= 252.
117 * Most operating systems work when MAXCONNECTIONS <= 1020 and FD_SETSIZE is
118 * updated correctly in the system headers (on BSD systems our sys.h has
119 * defined FD_SETSIZE to MAXCONNECTIONS+4 before including the system's headers
120 * but sys/types.h might have abruptly redefined it so the check is still
121 * done), you might already need to recompile your kernel.
122 * For larger FD_SETSIZE your milage may vary (kernel patches may be needed).
123 * The check is _NOT_ done if we will not use FD_SETS at all (USE_POLL)
125 #error "FD_SETSIZE is too small or MAXCONNECTIONS too large."
131 * Cannot use perror() within daemon. stderr is closed in
132 * ircd and cannot be used. And, worse yet, it might have
133 * been reassigned to a normal connection...
139 * This a replacement for perror(). Record error to log and
140 * also send a copy to all *LOCAL* opers online.
142 * text is a *format* string for outputting error. It must
143 * contain only two '%s', the first will be replaced
144 * by the sockhost from the cptr, and the latter will
145 * be taken from sys_errlist[errno].
147 * cptr if not NULL, is the *LOCAL* client associated with
150 void report_error(const char* text, const char* who, int err)
152 static time_t last_notice = 0;
153 int errtmp = errno; /* debug may change 'errno' */
154 const char* errmsg = (err) ? strerror(err) : "";
157 errmsg = "Unknown error";
159 if (EmptyString(who))
162 if (last_notice + 20 < CurrentTime) {
164 * pace error messages so opers don't get flooded by transients
166 sendto_opmask_butone(0, SNO_OLDSNO, text, who, errmsg);
167 last_notice = CurrentTime;
169 log_write(LS_SOCKET, L_ERROR, 0, text, who, errmsg);
175 * connect_dns_callback - called when resolver query finishes
176 * if the query resulted in a successful search, reply will contain
177 * a non-null pointer, otherwise reply will be null.
178 * if successful start the connection, otherwise notify opers
180 static void connect_dns_callback(void* vptr, struct hostent* hp)
182 struct ConfItem* aconf = (struct ConfItem*) vptr;
184 aconf->dns_pending = 0;
186 memcpy(&aconf->ipnum, hp->h_addr, sizeof(struct in_addr));
188 connect_server(aconf, 0);
191 sendto_opmask_butone(0, SNO_OLDSNO, "Connect to %s failed: host lookup",
196 * close_connections - closes all connections
197 * close stderr if specified
199 void close_connections(int close_stderr)
206 for (i = 3; i < MAXCONNECTIONS; ++i)
211 * init_connection_limits - initialize process fd limit to
214 int init_connection_limits(void)
216 int limit = os_set_fdlimit(MAXCONNECTIONS);
220 fprintf(stderr, "error setting max fd's to %d\n", limit);
222 else if (limit > 0) {
223 fprintf(stderr, "ircd fd table too big\nHard Limit: %d IRC max: %d\n",
224 limit, MAXCONNECTIONS);
225 fprintf(stderr, "set MAXCONNECTIONS to a smaller value");
231 * connect_inet - set up address and port and make a connection
233 static int connect_inet(struct ConfItem* aconf, struct Client* cptr)
235 static struct sockaddr_in sin;
240 * Might as well get sockhost from here, the connection is attempted
241 * with it so if it fails its useless.
243 cli_fd(cptr) = socket(AF_INET, SOCK_STREAM, 0);
244 if (-1 == cli_fd(cptr)) {
245 cli_error(cptr) = errno;
246 report_error(SOCKET_ERROR_MSG, cli_name(cptr), errno);
249 if (cli_fd(cptr) >= MAXCLIENTS) {
250 report_error(CONNLIMIT_ERROR_MSG, cli_name(cptr), 0);
256 * Bind to a local IP# (with unknown port - let unix decide) so
257 * we have some chance of knowing the IP# that gets used for a host
258 * with more than one IP#.
260 * No we don't bind it, not all OS's can handle connecting with
261 * an already bound socket, different ip# might occur anyway
262 * leading to a freezing select() on this side for some time.
263 * I had this on my Linux 1.1.88 --Run
267 * No, we do bind it if we have virtual host support. If we don't
268 * explicitly bind it, it will default to IN_ADDR_ANY and we lose
269 * due to the other server not allowing our base IP --smg
271 if (feature_bool(FEAT_VIRTUAL_HOST) &&
272 bind(cli_fd(cptr), (struct sockaddr*) &VirtualHost,
273 sizeof(VirtualHost))) {
274 report_error(BIND_ERROR_MSG, cli_name(cptr), errno);
280 memset(&sin, 0, sizeof(sin));
281 sin.sin_family = AF_INET;
282 sin.sin_addr.s_addr = aconf->ipnum.s_addr;
283 sin.sin_port = htons(aconf->port);
285 * save connection info in client
287 (cli_ip(cptr)).s_addr = aconf->ipnum.s_addr;
288 cli_port(cptr) = aconf->port;
289 ircd_ntoa_r(cli_sock_ip(cptr), (const char*) &(cli_ip(cptr)));
291 * we want a big buffer for server connections
293 if (!os_set_sockbufs(cli_fd(cptr), feature_int(FEAT_SOCKSENDBUF), feature_int(FEAT_SOCKRECVBUF))) {
294 cli_error(cptr) = errno;
295 report_error(SETBUFS_ERROR_MSG, cli_name(cptr), errno);
301 * ALWAYS set sockets non-blocking
303 if (!os_set_nonblocking(cli_fd(cptr))) {
304 cli_error(cptr) = errno;
305 report_error(NONB_ERROR_MSG, cli_name(cptr), errno);
310 if ((result = os_connect_nonb(cli_fd(cptr), &sin)) == IO_FAILURE) {
311 cli_error(cptr) = errno;
312 report_error(CONNECT_ERROR_MSG, cli_name(cptr), errno);
317 if (!socket_add(&(cli_socket(cptr)), client_sock_callback,
318 (void*) cli_connect(cptr),
319 (result == IO_SUCCESS) ? SS_CONNECTED : SS_CONNECTING,
320 SOCK_EVENT_READABLE, cli_fd(cptr))) {
321 cli_error(cptr) = ENFILE;
322 report_error(REGISTER_ERROR_MSG, cli_name(cptr), ENFILE);
327 cli_freeflag(cptr) |= FREEFLAG_SOCKET;
333 * Attempt to send a sequence of bytes to the connection.
336 * < 0 Some fatal error occurred, (but not EWOULDBLOCK).
337 * This return is a request to close the socket and
340 * >= 0 No real error occurred, returns the number of
341 * bytes actually transferred. EWOULDBLOCK and other
342 * possibly similar conditions should be mapped to
343 * zero return. Upper level routine will have to
344 * decide what to do with those unwritten bytes...
346 * *NOTE* alarm calls have been preserved, so this should
347 * work equally well whether blocking or non-blocking
350 * We don't use blocking anymore, that is impossible with the
351 * net.loads today anyway. Commented out the alarms to save cpu.
354 unsigned int deliver_it(struct Client *cptr, struct MsgQ *buf)
356 unsigned int bytes_written = 0;
357 unsigned int bytes_count = 0;
360 switch (os_sendv_nonb(cli_fd(cptr), buf, &bytes_count, &bytes_written)) {
362 ClrFlag(cptr, FLAG_BLOCKED);
364 cli_sendB(cptr) += bytes_written;
365 cli_sendB(&me) += bytes_written;
366 if (cli_sendB(cptr) > 1023) {
367 cli_sendK(cptr) += (cli_sendB(cptr) >> 10);
368 cli_sendB(cptr) &= 0x03ff; /* 2^10 = 1024, 3ff = 1023 */
370 if (cli_sendB(&me) > 1023) {
371 cli_sendK(&me) += (cli_sendB(&me) >> 10);
372 cli_sendB(&me) &= 0x03ff;
375 * XXX - hrmm.. set blocked here? the socket didn't
378 if (bytes_written < bytes_count)
379 SetFlag(cptr, FLAG_BLOCKED);
382 SetFlag(cptr, FLAG_BLOCKED);
385 cli_error(cptr) = errno;
386 SetFlag(cptr, FLAG_DEADSOCKET);
389 return bytes_written;
393 void release_dns_reply(struct Client* cptr)
396 assert(MyConnect(cptr));
398 if (cli_dns_reply(cptr)) {
399 MyFree(cli_dns_reply(cptr));
400 cli_dns_reply(cptr) = 0;
405 * completed_connection
407 * Complete non-blocking connect()-sequence. Check access and
408 * terminate connection, if trouble detected.
410 * Return TRUE, if successfully completed
411 * FALSE, if failed and ClientExit
413 static int completed_connection(struct Client* cptr)
415 struct ConfItem *aconf;
417 struct Client *acptr;
423 * get the socket status from the fd first to check if
424 * connection actually succeeded
426 if ((cli_error(cptr) = os_get_sockerr(cli_fd(cptr)))) {
427 const char* msg = strerror(cli_error(cptr));
429 msg = "Unknown error";
430 sendto_opmask_butone(0, SNO_OLDSNO, "Connection failed to %s: %s",
431 cli_name(cptr), msg);
434 if (!(aconf = find_conf_byname(cli_confs(cptr), cli_name(cptr), CONF_SERVER))) {
435 sendto_opmask_butone(0, SNO_OLDSNO, "Lost Server Line for %s", cli_name(cptr));
438 if (s_state(&(cli_socket(cptr))) == SS_CONNECTING)
439 socket_state(&(cli_socket(cptr)), SS_CONNECTED);
441 if (!EmptyString(aconf->passwd))
442 sendrawto_one(cptr, MSG_PASS " :%s", aconf->passwd);
445 * Create a unique timestamp
448 for (i = HighestFd; i > -1; --i) {
449 if ((acptr = LocalClientArray[i]) &&
450 (IsServer(acptr) || IsHandshake(acptr))) {
451 if (cli_serv(acptr)->timestamp >= newts)
452 newts = cli_serv(acptr)->timestamp + 1;
455 assert(0 != cli_serv(cptr));
457 cli_serv(cptr)->timestamp = newts;
460 * Make us timeout after twice the timeout for DNS look ups
462 cli_lasttime(cptr) = CurrentTime;
463 SetFlag(cptr, FLAG_PINGSENT);
465 sendrawto_one(cptr, MSG_SERVER " %s 1 %Tu %Tu J%s %s%s +%s :%s",
466 cli_name(&me), cli_serv(&me)->timestamp, newts,
467 MAJOR_PROTOCOL, NumServCap(&me),
468 feature_bool(FEAT_HUB) ? "h" : "", cli_info(&me));
470 return (IsDead(cptr)) ? 0 : 1;
476 * Close the physical connection. This function must make
477 * MyConnect(cptr) == FALSE, and set cptr->from == NULL.
479 void close_connection(struct Client *cptr)
481 struct ConfItem* aconf;
483 if (IsServer(cptr)) {
484 ServerStats->is_sv++;
485 ServerStats->is_sbs += cli_sendB(cptr);
486 ServerStats->is_sbr += cli_receiveB(cptr);
487 ServerStats->is_sks += cli_sendK(cptr);
488 ServerStats->is_skr += cli_receiveK(cptr);
489 ServerStats->is_sti += CurrentTime - cli_firsttime(cptr);
490 if (ServerStats->is_sbs > 1023) {
491 ServerStats->is_sks += (ServerStats->is_sbs >> 10);
492 ServerStats->is_sbs &= 0x3ff;
494 if (ServerStats->is_sbr > 1023) {
495 ServerStats->is_skr += (ServerStats->is_sbr >> 10);
496 ServerStats->is_sbr &= 0x3ff;
499 * If the connection has been up for a long amount of time, schedule
500 * a 'quick' reconnect, else reset the next-connect cycle.
502 if ((aconf = find_conf_exact(cli_name(cptr), 0, cli_sockhost(cptr), CONF_SERVER))) {
504 * Reschedule a faster reconnect, if this was a automaticly
505 * connected configuration entry. (Note that if we have had
506 * a rehash in between, the status has been changed to
507 * CONF_ILLEGAL). But only do this if it was a "good" link.
509 aconf->hold = CurrentTime;
510 aconf->hold += ((aconf->hold - cli_since(cptr) >
511 feature_int(FEAT_HANGONGOODLINK)) ?
512 feature_int(FEAT_HANGONRETRYDELAY) : ConfConFreq(aconf));
513 /* if (nextconnect > aconf->hold) */
514 /* nextconnect = aconf->hold; */
517 else if (IsUser(cptr)) {
518 ServerStats->is_cl++;
519 ServerStats->is_cbs += cli_sendB(cptr);
520 ServerStats->is_cbr += cli_receiveB(cptr);
521 ServerStats->is_cks += cli_sendK(cptr);
522 ServerStats->is_ckr += cli_receiveK(cptr);
523 ServerStats->is_cti += CurrentTime - cli_firsttime(cptr);
524 if (ServerStats->is_cbs > 1023) {
525 ServerStats->is_cks += (ServerStats->is_cbs >> 10);
526 ServerStats->is_cbs &= 0x3ff;
528 if (ServerStats->is_cbr > 1023) {
529 ServerStats->is_ckr += (ServerStats->is_cbr >> 10);
530 ServerStats->is_cbr &= 0x3ff;
534 ServerStats->is_ni++;
536 if (-1 < cli_fd(cptr)) {
537 flush_connections(cptr);
538 LocalClientArray[cli_fd(cptr)] = 0;
540 socket_del(&(cli_socket(cptr))); /* queue a socket delete */
543 SetFlag(cptr, FLAG_DEADSOCKET);
545 MsgQClear(&(cli_sendQ(cptr)));
546 client_drop_sendq(cli_connect(cptr));
547 DBufClear(&(cli_recvQ(cptr)));
548 memset(cli_passwd(cptr), 0, sizeof(cli_passwd(cptr)));
549 set_snomask(cptr, 0, SNO_SET);
551 det_confs_butmask(cptr, 0);
553 if (cli_listener(cptr)) {
554 release_listener(cli_listener(cptr));
555 cli_listener(cptr) = 0;
558 for ( ; HighestFd > 0; --HighestFd) {
559 if (LocalClientArray[HighestFd])
564 int net_close_unregistered_connections(struct Client* source)
571 for (i = HighestFd; i > 0; --i) {
572 if ((cptr = LocalClientArray[i]) && !IsRegistered(cptr)) {
573 send_reply(source, RPL_CLOSING, get_client_name(source, HIDE_IP));
574 exit_client(source, cptr, &me, "Oper Closing");
581 /*----------------------------------------------------------------------------
584 * Creates a client which has just connected to us on the given fd.
585 * The sockhost field is initialized with the ip# of the host.
586 * The client is not added to the linked list of clients, it is
587 * passed off to the auth handler for dns and ident queries.
588 *--------------------------------------------------------------------------*/
589 void add_connection(struct Listener* listener, int fd) {
590 struct sockaddr_in addr;
591 struct Client *new_client;
592 time_t next_target = 0;
594 const char* const throttle_message =
595 "ERROR :Your host is trying to (re)connect too fast -- throttled\r\n";
596 /* 12345678901234567890123456789012345679012345678901234567890123456 */
597 const char* const register_message =
598 "ERROR :Unable to complete your registration\r\n";
600 assert(0 != listener);
604 * Removed preliminary access check. Full check is performed in m_server and
605 * m_user instead. Also connection time out help to get rid of unwanted
608 if (!os_get_peername(fd, &addr) || !os_set_nonblocking(fd)) {
609 ++ServerStats->is_ref;
614 * Disable IP (*not* TCP) options. In particular, this makes it impossible
615 * to use source routing to connect to the server. If we didn't do this
616 * (and if intermediate networks didn't drop source-routed packets), an
617 * attacker could successfully IP spoof us...and even return the anti-spoof
618 * ping, because the options would cause the packet to be routed back to
619 * the spoofer's machine. When we disable the IP options, we delete the
620 * source route, and the normal routing takes over.
622 os_disable_options(fd);
625 * Add this local client to the IPcheck registry.
627 * If they're throttled, murder them, but tell them why first.
629 if (!IPcheck_local_connect(addr.sin_addr, &next_target) && !listener->server)
631 ++ServerStats->is_ref;
632 write(fd, throttle_message, strlen(throttle_message));
637 new_client = make_client(0, ((listener->server) ?
638 STAT_UNKNOWN_SERVER : STAT_UNKNOWN_USER));
641 * Copy ascii address to 'sockhost' just in case. Then we have something
642 * valid to put into error messages...
644 SetIPChecked(new_client);
645 ircd_ntoa_r(cli_sock_ip(new_client), (const char*) &addr.sin_addr);
646 strcpy(cli_sockhost(new_client), cli_sock_ip(new_client));
647 (cli_ip(new_client)).s_addr = addr.sin_addr.s_addr;
648 cli_port(new_client) = ntohs(addr.sin_port);
651 cli_nexttarget(new_client) = next_target;
653 cli_fd(new_client) = fd;
654 if (!socket_add(&(cli_socket(new_client)), client_sock_callback,
655 (void*) cli_connect(new_client), SS_CONNECTED, 0, fd)) {
656 ++ServerStats->is_ref;
657 write(fd, register_message, strlen(register_message));
659 cli_fd(new_client) = -1;
662 cli_freeflag(new_client) |= FREEFLAG_SOCKET;
663 cli_listener(new_client) = listener;
664 ++listener->ref_count;
666 Count_newunknown(UserStats);
667 /* if we've made it this far we can put the client on the auth query pile */
668 start_auth(new_client);
674 * Determines whether to tell the events engine we're interested in
677 void update_write(struct Client* cptr)
679 /* If there are messages that need to be sent along, or if the client
680 * is in the middle of a /list, then we need to tell the engine that
681 * we're interested in writable events--otherwise, we need to drop
684 socket_events(&(cli_socket(cptr)),
685 ((MsgQLength(&cli_sendQ(cptr)) || cli_listing(cptr)) ?
686 SOCK_ACTION_ADD : SOCK_ACTION_DEL) | SOCK_EVENT_WRITABLE);
692 * Read a 'packet' of data from a connection and process it. Read in 8k
693 * chunks to give a better performance rating (for server connections).
694 * Do some tricky stuff for client connections to make sure they don't do
695 * any flooding >:-) -avalon
697 static int read_packet(struct Client *cptr, int socket_ready)
699 unsigned int dolen = 0;
700 unsigned int length = 0;
704 DBufLength(&(cli_recvQ(cptr))) > feature_int(FEAT_CLIENT_FLOOD))) {
705 switch (os_recv_nonb(cli_fd(cptr), readbuf, sizeof(readbuf), &length)) {
710 cli_lasttime(cptr) = CurrentTime;
711 if (cli_lasttime(cptr) > cli_since(cptr))
712 cli_since(cptr) = cli_lasttime(cptr);
713 ClrFlag(cptr, FLAG_PINGSENT);
714 ClrFlag(cptr, FLAG_NONL);
720 cli_error(cptr) = errno;
721 /* SetFlag(cpt, FLAG_DEADSOCKET); */
727 * For server connections, we process as many as we can without
728 * worrying about the time of day or anything :)
730 if (length > 0 && IsServer(cptr))
731 return server_dopacket(cptr, readbuf, length);
732 else if (length > 0 && (IsHandshake(cptr) || IsConnecting(cptr)))
733 return connect_dopacket(cptr, readbuf, length);
737 * Before we even think of parsing what we just read, stick
738 * it on the end of the receive queue and do it when its
741 if (length > 0 && dbuf_put(&(cli_recvQ(cptr)), readbuf, length) == 0)
742 return exit_client(cptr, cptr, &me, "dbuf_put fail");
744 if (DBufLength(&(cli_recvQ(cptr))) > feature_int(FEAT_CLIENT_FLOOD))
745 return exit_client(cptr, cptr, &me, "Excess Flood");
747 while (DBufLength(&(cli_recvQ(cptr))) && !NoNewLine(cptr) &&
748 (IsTrusted(cptr) || cli_since(cptr) - CurrentTime < 10))
750 dolen = dbuf_getmsg(&(cli_recvQ(cptr)), cli_buffer(cptr), BUFSIZE);
752 * Devious looking...whats it do ? well..if a client
753 * sends a *long* message without any CR or LF, then
754 * dbuf_getmsg fails and we pull it out using this
755 * loop which just gets the next 512 bytes and then
756 * deletes the rest of the buffer contents.
761 if (DBufLength(&(cli_recvQ(cptr))) < 510)
762 SetFlag(cptr, FLAG_NONL);
764 DBufClear(&(cli_recvQ(cptr)));
766 else if (client_dopacket(cptr, dolen) == CPTR_KILLED)
769 * If it has become registered as a Server
770 * then skip the per-message parsing below.
772 if (IsHandshake(cptr) || IsServer(cptr))
776 dolen = dbuf_get(&(cli_recvQ(cptr)), readbuf, sizeof(readbuf));
781 if (DBufLength(&(cli_recvQ(cptr))) < 510)
782 SetFlag(cptr, FLAG_NONL);
784 DBufClear(&(cli_recvQ(cptr)));
786 else if ((IsServer(cptr) &&
787 server_dopacket(cptr, readbuf, dolen) == CPTR_KILLED) ||
789 connect_dopacket(cptr, readbuf, dolen) == CPTR_KILLED))
795 /* If there's still data to process, wait 2 seconds first */
796 if (DBufLength(&(cli_recvQ(cptr))) && !NoNewLine(cptr) &&
797 !t_onqueue(&(cli_proc(cptr))))
799 Debug((DEBUG_LIST, "Adding client process timer for %C", cptr));
800 cli_freeflag(cptr) |= FREEFLAG_TIMER;
801 timer_add(&(cli_proc(cptr)), client_timer_callback, cli_connect(cptr),
809 * connect_server - start or complete a connection to another server
810 * returns true (1) if successful, false (0) otherwise
812 * aconf must point to a valid C:line
813 * m_connect calls this with a valid by client and a null reply
814 * try_connections calls this with a null by client, and a null reply
815 * connect_dns_callback call this with a null by client, and a valid reply
817 * XXX - if this comes from an m_connect message and a dns query needs to
818 * be done, we loose the information about who started the connection and
819 * it's considered an auto connect.
821 int connect_server(struct ConfItem* aconf, struct Client* by)
823 struct Client* cptr = 0;
826 if (aconf->dns_pending) {
827 sendto_opmask_butone(0, SNO_OLDSNO, "Server %s connect DNS pending",
831 Debug((DEBUG_NOTICE, "Connect to %s[@%s]", aconf->name,
832 ircd_ntoa((const char*) &aconf->ipnum)));
834 if ((cptr = FindClient(aconf->name))) {
835 if (IsServer(cptr) || IsMe(cptr)) {
836 sendto_opmask_butone(0, SNO_OLDSNO, "Server %s already present from %s",
837 aconf->name, cli_name(cli_from(cptr)));
838 if (by && IsUser(by) && !MyUser(by)) {
839 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Server %s already present "
840 "from %s", by, aconf->name, cli_name(cli_from(cptr)));
844 else if (IsHandshake(cptr) || IsConnecting(cptr)) {
845 if (by && IsUser(by)) {
846 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Connection to %s already in "
847 "progress", by, cli_name(cptr));
853 * If we dont know the IP# for this host and itis a hostname and
854 * not a ip# string, then try and find the appropriate host record.
856 if (INADDR_NONE == aconf->ipnum.s_addr) {
857 if (INADDR_NONE == (aconf->ipnum.s_addr = inet_addr(aconf->host))) {
858 char buf[HOSTLEN + 1];
859 struct DNSQuery query;
862 query.callback = connect_dns_callback;
863 host_from_uh(buf, aconf->host, HOSTLEN);
866 gethost_byname(buf, &query);
867 aconf->dns_pending = 1;
871 cptr = make_client(NULL, STAT_UNKNOWN_SERVER);
874 * Copy these in so we have something for error detection.
876 ircd_strncpy(cli_name(cptr), aconf->name, HOSTLEN);
877 ircd_strncpy(cli_sockhost(cptr), aconf->host, HOSTLEN);
880 * Attach config entries to client here rather than in
881 * completed_connection. This to avoid null pointer references
883 attach_confs_byhost(cptr, aconf->host, CONF_SERVER);
885 if (!find_conf_byhost(cli_confs(cptr), aconf->host, CONF_SERVER)) {
886 sendto_opmask_butone(0, SNO_OLDSNO, "Host %s is not enabled for "
887 "connecting: no C-line", aconf->name);
888 if (by && IsUser(by) && !MyUser(by)) {
889 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Connect to host %s failed: no "
890 "C-line", by, aconf->name);
892 det_confs_butmask(cptr, 0);
897 * attempt to connect to the server in the conf line
899 if (!connect_inet(aconf, cptr)) {
900 if (by && IsUser(by) && !MyUser(by)) {
901 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Couldn't connect to %s", by,
904 det_confs_butmask(cptr, 0);
909 * NOTE: if we're here we have a valid C:Line and the client should
910 * have started the connection and stored the remote address/port and
911 * ip address name in itself
913 * The socket has been connected or connect is in progress.
916 if (by && IsUser(by)) {
917 ircd_snprintf(0, cli_serv(cptr)->by, sizeof(cli_serv(cptr)->by), "%s%s",
919 assert(0 == cli_serv(cptr)->user);
920 cli_serv(cptr)->user = cli_user(by);
921 cli_user(by)->refcnt++;
924 *(cli_serv(cptr))->by = '\0';
925 /* strcpy(cptr->serv->by, "Auto"); */
927 cli_serv(cptr)->up = &me;
930 if (cli_fd(cptr) > HighestFd)
931 HighestFd = cli_fd(cptr);
934 LocalClientArray[cli_fd(cptr)] = cptr;
936 Count_newunknown(UserStats);
937 /* Actually we lie, the connect hasn't succeeded yet, but we have a valid
938 * cptr, so we register it now.
939 * Maybe these two calls should be merged.
941 add_client_to_list(cptr);
943 /* nextping = CurrentTime; */
945 return (s_state(&cli_socket(cptr)) == SS_CONNECTED) ?
946 completed_connection(cptr) : 1;
950 * Setup local socket structure to use for binding to.
952 void set_virtual_host(struct in_addr addr)
954 memset(&VirtualHost, 0, sizeof(VirtualHost));
955 VirtualHost.sin_family = AF_INET;
956 VirtualHost.sin_addr.s_addr = addr.s_addr;
960 * Find the real hostname for the host running the server (or one which
961 * matches the server's name) and its primary IP#. Hostname is stored
962 * in the client structure passed as a pointer.
964 void init_server_identity(void)
966 const struct LocalConf* conf = conf_get_local();
969 ircd_strncpy(cli_name(&me), conf->name, HOSTLEN);
970 SetYXXServerName(&me, conf->numeric);
974 * Process events on a client socket
976 static void client_sock_callback(struct Event* ev)
979 struct Connection* con;
983 assert(0 != ev_socket(ev));
984 assert(0 != s_data(ev_socket(ev)));
986 con = (struct Connection*) s_data(ev_socket(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 switch (ev_type(ev)) {
996 con_freeflag(con) &= ~FREEFLAG_SOCKET;
998 if (!con_freeflag(con) && !cptr)
999 free_connection(con);
1002 case ET_CONNECT: /* socket connection completed */
1003 if (!completed_connection(cptr) || IsDead(cptr))
1004 fallback = cli_info(cptr);
1007 case ET_ERROR: /* an error occurred */
1008 fallback = cli_info(cptr);
1009 cli_error(cptr) = ev_data(ev);
1010 if (s_state(&(con_socket(con))) == SS_CONNECTING) {
1011 completed_connection(cptr);
1015 case ET_EOF: /* end of file on socket */
1016 Debug((DEBUG_ERROR, "READ ERROR: fd = %d %d", cli_fd(cptr),
1018 SetFlag(cptr, FLAG_DEADSOCKET);
1019 if ((IsServer(cptr) || IsHandshake(cptr)) && cli_error(cptr) == 0) {
1020 exit_client_msg(cptr, cptr, &me, "Server %s closed the connection (%s)",
1021 cli_name(cptr), cli_serv(cptr)->last_error_msg);
1024 fmt = "Read error: %s";
1025 fallback = "EOF from client";
1029 case ET_WRITE: /* socket is writable */
1030 ClrFlag(cptr, FLAG_BLOCKED);
1031 if (cli_listing(cptr) && MsgQLength(&(cli_sendQ(cptr))) < 2048)
1032 list_next_channels(cptr, 64);
1033 Debug((DEBUG_SEND, "Sending queued data to %C", cptr));
1037 case ET_READ: /* socket is readable */
1038 if (!IsDead(cptr)) {
1039 Debug((DEBUG_DEBUG, "Reading data from %C", cptr));
1040 if (read_packet(cptr, 1) == 0) /* error while reading packet */
1041 fallback = "EOF from client";
1047 abort(); /* unrecognized event */
1052 assert(0 == cptr || 0 == cli_connect(cptr) || con == cli_connect(cptr));
1055 const char* msg = (cli_error(cptr)) ? strerror(cli_error(cptr)) : fallback;
1057 msg = "Unknown error";
1058 exit_client_msg(cptr, cptr, &me, fmt, msg);
1063 * Process a timer on client socket
1065 static void client_timer_callback(struct Event* ev)
1067 struct Client* cptr;
1068 struct Connection* con;
1070 assert(0 != ev_timer(ev));
1071 assert(0 != t_data(ev_timer(ev)));
1072 assert(ET_DESTROY == ev_type(ev) || ET_EXPIRE == ev_type(ev));
1074 con = (struct Connection*) t_data(ev_timer(ev));
1076 assert(0 != con_client(con) || ev_type(ev) == ET_DESTROY);
1078 cptr = con_client(con);
1080 assert(0 == cptr || con == cli_connect(cptr));
1082 if (ev_type(ev)== ET_DESTROY) {
1083 con_freeflag(con) &= ~FREEFLAG_TIMER; /* timer has expired... */
1085 if (!con_freeflag(con) && !cptr)
1086 free_connection(con); /* client is being destroyed */
1088 Debug((DEBUG_LIST, "Client process timer for %C expired; processing",
1090 read_packet(cptr, 0); /* read_packet will re-add timer if needed */
1093 assert(0 == cptr || 0 == cli_connect(cptr) || con == cli_connect(cptr));