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.
31 #include "ircd_features.h"
32 #include "ircd_osdep.h"
33 #include "ircd_reply.h"
34 #include "ircd_string.h"
44 #include "querycmds.h"
52 #include "sprintf_irc.h"
59 #include <arpa/inet.h>
60 #include <arpa/nameser.h>
69 #include <sys/ioctl.h>
70 #include <sys/socket.h>
72 #include <sys/utsname.h>
80 #define INADDR_NONE 0xffffffff
83 struct Client* LocalClientArray[MAXCONNECTIONS];
85 struct sockaddr_in VirtualHost;
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 REUSEADDR_ERROR_MSG = "error setting SO_REUSEADDR for %s: %s";
100 const char* const SELECT_ERROR_MSG = "select error for %s: %s";
101 const char* const SETBUFS_ERROR_MSG = "error setting buffer size for %s: %s";
102 const char* const SOCKET_ERROR_MSG = "error creating socket for %s: %s";
103 const char* const TOS_ERROR_MSG = "error setting TOS for %s: %s";
106 #if !defined(USE_POLL)
107 #if FD_SETSIZE < (MAXCONNECTIONS + 4)
111 * All operating systems work when MAXCONNECTIONS <= 252.
112 * Most operating systems work when MAXCONNECTIONS <= 1020 and FD_SETSIZE is
113 * updated correctly in the system headers (on BSD systems our sys.h has
114 * defined FD_SETSIZE to MAXCONNECTIONS+4 before including the system's headers
115 * but sys/types.h might have abruptly redefined it so the check is still
116 * done), you might already need to recompile your kernel.
117 * For larger FD_SETSIZE your milage may vary (kernel patches may be needed).
118 * The check is _NOT_ done if we will not use FD_SETS at all (USE_POLL)
120 #error "FD_SETSIZE is too small or MAXCONNECTIONS too large."
126 * Cannot use perror() within daemon. stderr is closed in
127 * ircd and cannot be used. And, worse yet, it might have
128 * been reassigned to a normal connection...
134 * This a replacement for perror(). Record error to log and
135 * also send a copy to all *LOCAL* opers online.
137 * text is a *format* string for outputting error. It must
138 * contain only two '%s', the first will be replaced
139 * by the sockhost from the cptr, and the latter will
140 * be taken from sys_errlist[errno].
142 * cptr if not NULL, is the *LOCAL* client associated with
145 void report_error(const char* text, const char* who, int err)
147 static time_t last_notice = 0;
148 int errtmp = errno; /* debug may change 'errno' */
149 const char* errmsg = (err) ? strerror(err) : "";
152 errmsg = "Unknown error";
154 if (EmptyString(who))
157 if (last_notice + 20 < CurrentTime) {
159 * pace error messages so opers don't get flooded by transients
161 sendto_opmask_butone(0, SNO_OLDSNO, text, who, errmsg);
162 last_notice = CurrentTime;
164 log_write(LS_SOCKET, L_ERROR, 0, text, who, errmsg);
170 * connect_dns_callback - called when resolver query finishes
171 * if the query resulted in a successful search, reply will contain
172 * a non-null pointer, otherwise reply will be null.
173 * if successful start the connection, otherwise notify opers
175 static void connect_dns_callback(void* vptr, struct DNSReply* reply)
177 struct ConfItem* aconf = (struct ConfItem*) vptr;
178 aconf->dns_pending = 0;
180 memcpy(&aconf->ipnum, reply->hp->h_addr, sizeof(struct in_addr));
181 connect_server(aconf, 0, reply);
184 sendto_opmask_butone(0, SNO_OLDSNO, "Connect to %s failed: host lookup",
189 * close_connections - closes all connections
190 * close stderr if specified
192 void close_connections(int close_stderr)
199 for (i = 3; i < MAXCONNECTIONS; ++i)
204 * init_connection_limits - initialize process fd limit to
207 int init_connection_limits(void)
209 int limit = os_set_fdlimit(MAXCONNECTIONS);
213 fprintf(stderr, "error setting max fd's to %d\n", limit);
215 else if (limit > 0) {
216 fprintf(stderr, "ircd fd table too big\nHard Limit: %d IRC max: %d\n",
217 limit, MAXCONNECTIONS);
218 fprintf(stderr, "set MAXCONNECTIONS to a smaller value");
224 * connect_inet - set up address and port and make a connection
226 static int connect_inet(struct ConfItem* aconf, struct Client* cptr)
228 static struct sockaddr_in sin;
232 * Might as well get sockhost from here, the connection is attempted
233 * with it so if it fails its useless.
235 cli_fd(cptr) = socket(AF_INET, SOCK_STREAM, 0);
236 if (-1 == cli_fd(cptr)) {
237 cli_error(cptr) = errno;
238 report_error(SOCKET_ERROR_MSG, cli_name(cptr), errno);
241 if (cli_fd(cptr) >= MAXCLIENTS) {
242 report_error(CONNLIMIT_ERROR_MSG, cli_name(cptr), 0);
248 * Bind to a local IP# (with unknown port - let unix decide) so
249 * we have some chance of knowing the IP# that gets used for a host
250 * with more than one IP#.
252 * No we don't bind it, not all OS's can handle connecting with
253 * an already bound socket, different ip# might occur anyway
254 * leading to a freezing select() on this side for some time.
255 * I had this on my Linux 1.1.88 --Run
259 * No, we do bind it if we have virtual host support. If we don't
260 * explicitly bind it, it will default to IN_ADDR_ANY and we lose
261 * due to the other server not allowing our base IP --smg
263 if (feature_bool(FEAT_VIRTUAL_HOST) &&
264 bind(cli_fd(cptr), (struct sockaddr*) &VirtualHost,
265 sizeof(VirtualHost))) {
266 report_error(BIND_ERROR_MSG, cli_name(cptr), errno);
270 memset(&sin, 0, sizeof(sin));
271 sin.sin_family = AF_INET;
272 sin.sin_addr.s_addr = aconf->ipnum.s_addr;
273 sin.sin_port = htons(aconf->port);
275 * save connection info in client
277 (cli_ip(cptr)).s_addr = aconf->ipnum.s_addr;
278 cli_port(cptr) = aconf->port;
279 ircd_ntoa_r(cli_sock_ip(cptr), (const char*) &(cli_ip(cptr)));
281 * we want a big buffer for server connections
283 if (!os_set_sockbufs(cli_fd(cptr), SERVER_TCP_WINDOW)) {
284 cli_error(cptr) = errno;
285 report_error(SETBUFS_ERROR_MSG, cli_name(cptr), errno);
289 * ALWAYS set sockets non-blocking
291 if (!os_set_nonblocking(cli_fd(cptr))) {
292 cli_error(cptr) = errno;
293 report_error(NONB_ERROR_MSG, cli_name(cptr), errno);
296 if (!os_connect_nonb(cli_fd(cptr), &sin)) {
297 cli_error(cptr) = errno;
298 report_error(CONNECT_ERROR_MSG, cli_name(cptr), errno);
306 * Attempt to send a sequence of bytes to the connection.
309 * < 0 Some fatal error occurred, (but not EWOULDBLOCK).
310 * This return is a request to close the socket and
313 * >= 0 No real error occurred, returns the number of
314 * bytes actually transferred. EWOULDBLOCK and other
315 * possibly similar conditions should be mapped to
316 * zero return. Upper level routine will have to
317 * decide what to do with those unwritten bytes...
319 * *NOTE* alarm calls have been preserved, so this should
320 * work equally well whether blocking or non-blocking
323 * We don't use blocking anymore, that is impossible with the
324 * net.loads today anyway. Commented out the alarms to save cpu.
327 unsigned int deliver_it(struct Client *cptr, struct MsgQ *buf)
329 unsigned int bytes_written = 0;
330 unsigned int bytes_count = 0;
333 switch (os_sendv_nonb(cli_fd(cptr), buf, &bytes_count, &bytes_written)) {
335 cli_flags(cptr) &= ~FLAGS_BLOCKED;
337 cli_sendB(cptr) += bytes_written;
338 cli_sendB(&me) += bytes_written;
339 if (cli_sendB(cptr) > 1023) {
340 cli_sendK(cptr) += (cli_sendB(cptr) >> 10);
341 cli_sendB(cptr) &= 0x03ff; /* 2^10 = 1024, 3ff = 1023 */
343 if (cli_sendB(&me) > 1023) {
344 cli_sendK(&me) += (cli_sendB(&me) >> 10);
345 cli_sendB(&me) &= 0x03ff;
348 * XXX - hrmm.. set blocked here? the socket didn't
351 if (bytes_written < bytes_count)
352 cli_flags(cptr) |= FLAGS_BLOCKED;
355 cli_flags(cptr) |= FLAGS_BLOCKED;
358 cli_error(cptr) = errno;
359 cli_flags(cptr) |= FLAGS_DEADSOCKET;
362 return bytes_written;
366 void release_dns_reply(struct Client* cptr)
369 assert(MyConnect(cptr));
371 if (cli_dns_reply(cptr)) {
372 assert(0 < cli_dns_reply(cptr)->ref_count);
373 --(cli_dns_reply(cptr))->ref_count;
374 cli_dns_reply(cptr) = 0;
379 * completed_connection
381 * Complete non-blocking connect()-sequence. Check access and
382 * terminate connection, if trouble detected.
384 * Return TRUE, if successfully completed
385 * FALSE, if failed and ClientExit
387 static int completed_connection(struct Client* cptr)
389 struct ConfItem *aconf;
391 struct Client *acptr;
397 * get the socket status from the fd first to check if
398 * connection actually succeeded
400 if ((cli_error(cptr) = os_get_sockerr(cli_fd(cptr)))) {
401 const char* msg = strerror(cli_error(cptr));
403 msg = "Unknown error";
404 sendto_opmask_butone(0, SNO_OLDSNO, "Connection failed to %s: %s",
405 cli_name(cptr), msg);
408 if (!(aconf = find_conf_byname(cli_confs(cptr), cli_name(cptr), CONF_SERVER))) {
409 sendto_opmask_butone(0, SNO_OLDSNO, "Lost Server Line for %s", cli_name(cptr));
413 if (!EmptyString(aconf->passwd))
414 sendrawto_one(cptr, MSG_PASS " :%s", aconf->passwd);
417 * Create a unique timestamp
420 for (i = HighestFd; i > -1; --i) {
421 if ((acptr = LocalClientArray[i]) &&
422 (IsServer(acptr) || IsHandshake(acptr))) {
423 if (cli_serv(acptr)->timestamp >= newts)
424 newts = cli_serv(acptr)->timestamp + 1;
427 assert(0 != cli_serv(cptr));
429 cli_serv(cptr)->timestamp = newts;
432 * Make us timeout after twice the timeout for DNS look ups
434 cli_lasttime(cptr) = CurrentTime;
435 cli_flags(cptr) |= FLAGS_PINGSENT;
437 sendrawto_one(cptr, MSG_SERVER " %s 1 %Tu %Tu J%s %s%s :%s",
438 cli_name(&me), cli_serv(&me)->timestamp, newts, MAJOR_PROTOCOL,
439 NumServCap(&me), cli_info(&me));
441 return (IsDead(cptr)) ? 0 : 1;
447 * Close the physical connection. This function must make
448 * MyConnect(cptr) == FALSE, and set cptr->from == NULL.
450 void close_connection(struct Client *cptr)
452 struct ConfItem* aconf;
454 if (IsServer(cptr)) {
455 ServerStats->is_sv++;
456 ServerStats->is_sbs += cli_sendB(cptr);
457 ServerStats->is_sbr += cli_receiveB(cptr);
458 ServerStats->is_sks += cli_sendK(cptr);
459 ServerStats->is_skr += cli_receiveK(cptr);
460 ServerStats->is_sti += CurrentTime - cli_firsttime(cptr);
461 if (ServerStats->is_sbs > 1023) {
462 ServerStats->is_sks += (ServerStats->is_sbs >> 10);
463 ServerStats->is_sbs &= 0x3ff;
465 if (ServerStats->is_sbr > 1023) {
466 ServerStats->is_skr += (ServerStats->is_sbr >> 10);
467 ServerStats->is_sbr &= 0x3ff;
470 * If the connection has been up for a long amount of time, schedule
471 * a 'quick' reconnect, else reset the next-connect cycle.
473 if ((aconf = find_conf_exact(cli_name(cptr), 0, cli_sockhost(cptr), CONF_SERVER))) {
475 * Reschedule a faster reconnect, if this was a automaticly
476 * connected configuration entry. (Note that if we have had
477 * a rehash in between, the status has been changed to
478 * CONF_ILLEGAL). But only do this if it was a "good" link.
480 aconf->hold = CurrentTime;
481 aconf->hold += ((aconf->hold - cli_since(cptr) >
482 feature_int(FEAT_HANGONGOODLINK)) ?
483 feature_int(FEAT_HANGONRETRYDELAY) : ConfConFreq(aconf));
484 if (nextconnect > aconf->hold)
485 nextconnect = aconf->hold;
488 else if (IsUser(cptr)) {
489 ServerStats->is_cl++;
490 ServerStats->is_cbs += cli_sendB(cptr);
491 ServerStats->is_cbr += cli_receiveB(cptr);
492 ServerStats->is_cks += cli_sendK(cptr);
493 ServerStats->is_ckr += cli_receiveK(cptr);
494 ServerStats->is_cti += CurrentTime - cli_firsttime(cptr);
495 if (ServerStats->is_cbs > 1023) {
496 ServerStats->is_cks += (ServerStats->is_cbs >> 10);
497 ServerStats->is_cbs &= 0x3ff;
499 if (ServerStats->is_cbr > 1023) {
500 ServerStats->is_ckr += (ServerStats->is_cbr >> 10);
501 ServerStats->is_cbr &= 0x3ff;
505 ServerStats->is_ni++;
507 if (-1 < cli_fd(cptr)) {
508 flush_connections(cptr);
509 LocalClientArray[cli_fd(cptr)] = 0;
513 cli_flags(cptr) |= FLAGS_DEADSOCKET;
515 MsgQClear(&(cli_sendQ(cptr)));
516 client_drop_sendq(cli_connect(cptr));
517 DBufClear(&(cli_recvQ(cptr)));
518 memset(cli_passwd(cptr), 0, sizeof(cli_passwd(cptr)));
519 set_snomask(cptr, 0, SNO_SET);
521 det_confs_butmask(cptr, 0);
523 if (cli_listener(cptr)) {
524 release_listener(cli_listener(cptr));
525 cli_listener(cptr) = 0;
528 for ( ; HighestFd > 0; --HighestFd) {
529 if (LocalClientArray[HighestFd])
534 int net_close_unregistered_connections(struct Client* source)
541 for (i = HighestFd; i > 0; --i) {
542 if ((cptr = LocalClientArray[i]) && !IsRegistered(cptr)) {
543 send_reply(source, RPL_CLOSING, get_client_name(source, HIDE_IP));
544 exit_client(source, cptr, &me, "Oper Closing");
551 /*----------------------------------------------------------------------------
554 * Creates a client which has just connected to us on the given fd.
555 * The sockhost field is initialized with the ip# of the host.
556 * The client is not added to the linked list of clients, it is
557 * passed off to the auth handler for dns and ident queries.
558 *--------------------------------------------------------------------------*/
559 void add_connection(struct Listener* listener, int fd) {
560 struct sockaddr_in addr;
561 struct Client *new_client;
562 time_t next_target = 0;
564 const char* const throttle_message =
565 "ERROR :Your host is trying to (re)connect too fast -- throttled\r\n";
566 /* 12345678901234567890123456789012345679012345678901234567890123456 */
568 assert(0 != listener);
572 * Removed preliminary access check. Full check is performed in m_server and
573 * m_user instead. Also connection time out help to get rid of unwanted
576 if (!os_get_peername(fd, &addr) || !os_set_nonblocking(fd)) {
577 ++ServerStats->is_ref;
583 * Add this local client to the IPcheck registry.
585 * If they're throttled, murder them, but tell them why first.
587 if (!IPcheck_local_connect(addr.sin_addr, &next_target) && !listener->server) {
588 ++ServerStats->is_ref;
589 write(fd, throttle_message, strlen(throttle_message));
594 new_client = make_client(0, ((listener->server) ?
595 STAT_UNKNOWN_SERVER : STAT_UNKNOWN_USER));
598 * Copy ascii address to 'sockhost' just in case. Then we have something
599 * valid to put into error messages...
601 ircd_ntoa_r(cli_sock_ip(new_client), (const char*) &addr.sin_addr);
602 strcpy(cli_sockhost(new_client), cli_sock_ip(new_client));
603 (cli_ip(new_client)).s_addr = addr.sin_addr.s_addr;
604 cli_port(new_client) = ntohs(addr.sin_port);
607 cli_nexttarget(new_client) = next_target;
609 cli_fd(new_client) = fd;
610 cli_listener(new_client) = listener;
611 ++listener->ref_count;
613 Count_newunknown(UserStats);
614 /* if we've made it this far we can put the client on the auth query pile */
615 start_auth(new_client);
622 * Read a 'packet' of data from a connection and process it. Read in 8k
623 * chunks to give a better performance rating (for server connections).
624 * Do some tricky stuff for client connections to make sure they don't do
625 * any flooding >:-) -avalon
627 static int read_packet(struct Client *cptr, int socket_ready)
629 unsigned int dolen = 0;
630 unsigned int length = 0;
634 DBufLength(&(cli_recvQ(cptr))) > feature_int(FEAT_CLIENT_FLOOD))) {
635 switch (os_recv_nonb(cli_fd(cptr), readbuf, sizeof(readbuf), &length)) {
638 cli_lasttime(cptr) = CurrentTime;
639 if (cli_lasttime(cptr) > cli_since(cptr))
640 cli_since(cptr) = cli_lasttime(cptr);
641 cli_flags(cptr) &= ~(FLAGS_PINGSENT | FLAGS_NONL);
647 cli_error(cptr) = errno;
648 /* cptr->flags |= FLAGS_DEADSOCKET; */
654 * For server connections, we process as many as we can without
655 * worrying about the time of day or anything :)
657 if (length > 0 && IsServer(cptr)) {
658 return server_dopacket(cptr, readbuf, length);
662 * Before we even think of parsing what we just read, stick
663 * it on the end of the receive queue and do it when its
666 if (length > 0 && 0 == dbuf_put(&(cli_recvQ(cptr)), readbuf, length)) {
667 return exit_client(cptr, cptr, &me, "dbuf_put fail");
671 * XXX - cptr will always be a user or unregistered
674 DBufLength(&(cli_recvQ(cptr))) > feature_int(FEAT_CLIENT_FLOOD))
675 return exit_client(cptr, cptr, &me, "Excess Flood");
677 while (DBufLength(&(cli_recvQ(cptr))) && !NoNewLine(cptr) &&
678 (IsTrusted(cptr) || cli_since(cptr) - CurrentTime < 10))
681 * If it has become registered as a Server
682 * then skip the per-message parsing below.
684 if (IsServer(cptr)) {
685 dolen = dbuf_get(&(cli_recvQ(cptr)), readbuf, sizeof(readbuf));
686 return (dolen) ? server_dopacket(cptr, readbuf, dolen) : 1;
688 dolen = dbuf_getmsg(&(cli_recvQ(cptr)), cli_buffer(cptr), BUFSIZE);
690 * Devious looking...whats it do ? well..if a client
691 * sends a *long* message without any CR or LF, then
692 * dbuf_getmsg fails and we pull it out using this
693 * loop which just gets the next 512 bytes and then
694 * deletes the rest of the buffer contents.
698 if (DBufLength(&(cli_recvQ(cptr))) < 510)
699 cli_flags(cptr) |= FLAGS_NONL;
701 DBufClear(&(cli_recvQ(cptr)));
703 else if (CPTR_KILLED == client_dopacket(cptr, dolen))
710 static int on_write_unblocked(struct Client* cptr)
713 * ...room for writing, empty some queue then...
715 cli_flags(cptr) &= ~FLAGS_BLOCKED;
716 if (IsConnecting(cptr)) {
717 if (!completed_connection(cptr))
720 else if (cli_listing(cptr) && MsgQLength(&(cli_sendQ(cptr))) < 2048)
721 list_next_channels(cptr, 64);
727 * Select / Poll Read Algorithm for ircd
729 * We need to check the file descriptors for all the different types
730 * of things that use them, so check for reads on everything but connects
731 * and writes on connects and descriptors that are blocked
733 * for each (client in local) {
734 * if (not connecting)
736 * if (connecting or blocked)
741 * for each (client in local) {
742 * if (there are descriptors to check) {
743 * if (write activity)
750 * Note we must always process data read whether or not there has been
751 * read activity or file descriptors set, since data is buffered by the client.
760 #if defined(POLLMSG) && defined(POLLIN) && defined(POLLRDNORM)
761 # define POLLREADFLAGS (POLLMSG|POLLIN|POLLRDNORM)
763 # if defined(POLLIN) && defined(POLLRDNORM)
764 # define POLLREADFLAGS (POLLIN|POLLRDNORM)
767 # define POLLREADFLAGS POLLIN
769 # if defined(POLLRDNORM)
770 # define POLLREADFLAGS POLLRDNORM
776 #if defined(POLLOUT) && defined(POLLWRNORM)
777 #define POLLWRITEFLAGS (POLLOUT|POLLWRNORM)
779 # if defined(POLLOUT)
780 # define POLLWRITEFLAGS POLLOUT
782 # if defined(POLLWRNORM)
783 # define POLLWRITEFLAGS POLLWRNORM
789 #define POLLERRORS (POLLHUP|POLLERR)
791 #define POLLERRORS POLLERR
795 * NOTE: pfd and pfd_count are local variable names in read_message
797 #define PFD_SETR(xfd) \
798 do { CHECK_ADD_PFD(xfd) pfd->events |= POLLREADFLAGS; } while(0)
799 #define PFD_SETW(xfd) \
800 do { CHECK_ADD_PFD(xfd) pfd->events |= POLLWRITEFLAGS; } while(0)
802 #define CHECK_ADD_PFD(xfd) \
803 if (pfd->fd != xfd) { \
804 pfd = &poll_fds[pfd_count++]; \
805 poll_fds[pfd_count].fd = -1; \
811 * Check all connections for new connections and input data that is to be
812 * processed. Also check for connections with data queued and whether we can
815 * Don't ever use ZERO for `delay', unless you mean to poll and then
816 * you have to have sleep/wait somewhere else in the code.--msa
818 int read_message(time_t delay)
820 struct pollfd poll_fds[MAXCONNECTIONS + 1];
822 struct Listener* listener = 0;
823 struct AuthRequest* auth = 0;
824 struct AuthRequest* auth_next = 0;
825 struct UPing* uping = 0;
826 struct UPing* uping_next = 0;
827 time_t delay2 = delay;
834 struct pollfd* res_pfd;
835 struct pollfd* uping_pfd;
839 unsigned int timeout;
848 if (-1 < ResolverFileDescriptor) {
849 PFD_SETR(ResolverFileDescriptor);
852 if (-1 < UPingFileDescriptor) {
853 PFD_SETR(UPingFileDescriptor);
857 * add uping descriptors
859 for (uping = uping_begin(); uping; uping = uping_next) {
860 uping_next = uping->next;
863 if (uping->lastsent && CurrentTime > uping->timeout) {
867 uping->index = pfd_count;
872 * add auth file descriptors
874 for (auth = AuthPollList; auth; auth = auth->next) {
875 assert(-1 < auth->fd);
876 auth->index = pfd_count;
877 if (IsAuthConnect(auth))
883 * add listener file descriptors
885 for (listener = ListenerPollList; listener; listener = listener->next) {
886 assert(-1 < listener->fd);
888 * pfd_count is incremented by PFD_SETR so we need to save the
891 listener->index = pfd_count;
892 PFD_SETR(listener->fd);
895 for (i = HighestFd; -1 < i; --i) {
896 if ((cptr = LocalClientArray[i])) {
898 if (DBufLength(&(cli_recvQ(cptr))))
900 if (DBufLength(&(cli_recvQ(cptr))) < 4088 || IsServer(cptr)) {
903 if (MsgQLength(&(cli_sendQ(cptr))) || IsConnecting(cptr) ||
904 (cli_listing(cptr) && MsgQLength(&(cli_sendQ(cptr))) < 2048)) {
910 Debug((DEBUG_INFO, "poll: %d %d", delay, delay2));
912 timeout = (IRCD_MIN(delay2, delay)) * 1000;
914 nfds = poll(poll_fds, pfd_count, timeout);
916 CurrentTime = time(0);
922 report_error(POLL_ERROR_MSG, cli_name(&me), errno);
925 server_restart("too many poll errors");
927 CurrentTime = time(0);
930 if (uping_pfd && (uping_pfd->revents & (POLLREADFLAGS | POLLERRORS))) {
935 * check uping replies
937 for (uping = uping_begin(); uping; uping = uping_next) {
938 uping_next = uping->next;
940 assert(-1 < uping->index);
941 if (poll_fds[uping->index].revents) {
946 else if (CurrentTime > uping->lastsent) {
947 uping->lastsent = CurrentTime;
953 if (res_pfd && (res_pfd->revents & (POLLREADFLAGS | POLLERRORS))) {
960 for (auth = AuthPollList; auth; auth = auth_next) {
961 auth_next = auth->next;
964 * check for any event, we only ask for one at a time
966 if (poll_fds[i].revents) {
967 if (IsAuthConnect(auth))
968 send_auth_query(auth);
970 read_auth_reply(auth);
978 for (listener = ListenerPollList; listener; listener = listener->next) {
980 if (poll_fds[i].revents) {
981 accept_connection(listener);
987 * i contains the next non-auth/non-listener index, since we put the
988 * resolver, auth and listener, file descriptors in poll_fds first,
989 * the very next one should be the start of the clients
991 pfd = &poll_fds[++i];
993 for ( ; (i < pfd_count); ++i, ++pfd) {
994 if (!(cptr = LocalClientArray[pfd->fd]))
996 read_ready = write_ready = 0;
998 if (0 < nfds && pfd->revents) {
1001 read_ready = pfd->revents & POLLREADFLAGS;
1002 write_ready = pfd->revents & POLLWRITEFLAGS;
1004 if (pfd->revents & POLLERRORS) {
1005 if (pfd->events & POLLREADFLAGS)
1007 if (pfd->events & POLLWRITEFLAGS)
1012 if (!on_write_unblocked(cptr) || IsDead(cptr)) {
1013 const char* msg = (cli_error(cptr)) ? strerror(cli_error(cptr)) : cli_info(cptr);
1015 msg = "Unknown error";
1016 exit_client(cptr, cptr, &me, msg);
1020 length = 1; /* for fall through case */
1021 if ((!NoNewLine(cptr) || read_ready) && !IsDead(cptr)) {
1022 if (CPTR_KILLED == (length = read_packet(cptr, read_ready)))
1026 /* Bullshit, why would we want to flush sockets while using non-blocking?
1027 * This uses > 4% cpu! --Run */
1029 flush_connections(poll_cptr[i]);
1032 const char* msg = (cli_error(cptr)) ? strerror(cli_error(cptr)) : cli_info(cptr);
1034 msg = "Unknown error";
1035 exit_client(cptr, cptr, &me, (char*) msg);
1040 cli_flags(cptr) |= FLAGS_DEADSOCKET;
1042 * ...hmm, with non-blocking sockets we might get
1043 * here from quite valid reasons, although.. why
1044 * would select report "data available" when there
1045 * wasn't... So, this must be an error anyway... --msa
1046 * actually, EOF occurs when read() returns 0 and
1047 * in due course, select() returns that fd as ready
1048 * for reading even though it ends up being an EOF. -avalon
1050 Debug((DEBUG_ERROR, "READ ERROR: fd = %d %d %d", pfd->fd, errno, length));
1052 if ((IsServer(cptr) || IsHandshake(cptr)) && cli_error(cptr) == 0 && length == 0)
1053 exit_client_msg(cptr, cptr, &me, "Server %s closed the connection (%s)",
1054 cli_name(cptr), cli_serv(cptr)->last_error_msg);
1056 const char* msg = (cli_error(cptr)) ? strerror(cli_error(cptr)) : "EOF from client";
1058 msg = "Unknown error";
1059 exit_client_msg(cptr, cptr, &me, "Read error: %s", msg);
1064 #else /* USE_SELECT */
1067 * Check all connections for new connections and input data that is to be
1068 * processed. Also check for connections with data queued and whether we can
1071 * Don't ever use ZERO for `delay', unless you mean to poll and then
1072 * you have to have sleep/wait somewhere else in the code.--msa
1074 int read_message(time_t delay)
1076 struct Client* cptr;
1077 struct Listener* listener;
1078 struct AuthRequest* auth = 0;
1079 struct AuthRequest* auth_next = 0;
1080 struct UPing* uping;
1081 struct UPing* uping_next;
1083 struct timeval wait;
1084 time_t delay2 = delay;
1085 unsigned int usec = 0;
1096 FD_ZERO(&write_set);
1098 if (-1 < ResolverFileDescriptor)
1099 FD_SET(ResolverFileDescriptor, &read_set);
1100 if (-1 < UPingFileDescriptor)
1101 FD_SET(UPingFileDescriptor, &read_set);
1103 * set up uping file descriptors
1105 for (uping = uping_begin(); uping; uping = uping_next) {
1106 uping_next = uping->next;
1107 if (uping->active) {
1109 if (uping->lastsent && CurrentTime > uping->timeout) {
1113 assert(-1 < uping->fd);
1114 FD_SET(uping->fd, &read_set);
1118 * set auth file descriptors
1120 for (auth = AuthPollList; auth; auth = auth->next) {
1121 assert(-1 < auth->fd);
1122 if (IsAuthConnect(auth))
1123 FD_SET(auth->fd, &write_set);
1124 else /* if (IsAuthPending(auth)) */
1125 FD_SET(auth->fd, &read_set);
1128 * set listener file descriptors
1130 for (listener = ListenerPollList; listener; listener = listener->next) {
1131 assert(-1 < listener->fd);
1132 FD_SET(listener->fd, &read_set);
1135 for (i = HighestFd; i > -1; --i) {
1136 if ((cptr = LocalClientArray[i])) {
1137 if (DBufLength(&(cli_recvQ(cptr))))
1139 if (DBufLength(&(cli_recvQ(cptr))) < 4088 || IsServer(cptr))
1140 FD_SET(i, &read_set);
1141 if (MsgQLength(&(cli_sendQ(cptr))) || IsConnecting(cptr) ||
1142 (cli_listing(cptr) && MsgQLength(&(cli_sendQ(cptr))) < 2048))
1143 FD_SET(i, &write_set);
1147 wait.tv_sec = IRCD_MIN(delay2, delay);
1148 wait.tv_usec = usec;
1150 Debug((DEBUG_INFO, "select: %d %d", delay, delay2));
1152 nfds = select(FD_SETSIZE, &read_set, &write_set, 0, &wait);
1154 CurrentTime = time(0);
1161 report_error(SELECT_ERROR_MSG, cli_name(&me), errno);
1163 server_restart("too many select errors");
1165 CurrentTime = time(0);
1168 if (-1 < UPingFileDescriptor && FD_ISSET(UPingFileDescriptor, &read_set)) {
1172 for (uping = uping_begin(); uping; uping = uping_next) {
1173 uping_next = uping->next;
1174 if (uping->active) {
1175 assert(-1 < uping->fd);
1176 if (FD_ISSET(uping->fd, &read_set)) {
1181 else if (CurrentTime > uping->lastsent) {
1182 uping->lastsent = CurrentTime;
1187 if (-1 < ResolverFileDescriptor && FD_ISSET(ResolverFileDescriptor, &read_set)) {
1192 * Check fd sets for the auth fd's (if set and valid!) first
1193 * because these can not be processed using the normal loops below.
1196 for (auth = AuthPollList; auth; auth = auth_next) {
1197 auth_next = auth->next;
1198 assert(-1 < auth->fd);
1199 if (IsAuthConnect(auth) && FD_ISSET(auth->fd, &write_set)) {
1200 send_auth_query(auth);
1204 else if (FD_ISSET(auth->fd, &read_set)) {
1205 read_auth_reply(auth);
1211 * next accept connections from active listeners
1213 for (listener = ListenerPollList; listener; listener = listener->next) {
1214 assert(-1 < listener->fd);
1215 if (0 < nfds && FD_ISSET(listener->fd, &read_set))
1216 accept_connection(listener);
1219 for (i = HighestFd; -1 < i; --i) {
1220 if (!(cptr = LocalClientArray[i]))
1224 if (FD_ISSET(i, &write_set)) {
1226 if (!on_write_unblocked(cptr) || IsDead(cptr)) {
1227 const char* msg = (cli_error(cptr)) ? strerror(cli_error(cptr)) : cli_info(cptr);
1229 msg = "Unknown error";
1230 if (FD_ISSET(i, &read_set))
1232 exit_client(cptr, cptr, &me, msg);
1236 if ((read_ready = FD_ISSET(i, &read_set)))
1239 length = 1; /* for fall through case */
1240 if ((!NoNewLine(cptr) || read_ready) && !IsDead(cptr)) {
1241 if (CPTR_KILLED == (length = read_packet(cptr, read_ready)))
1245 const char* msg = (cli_error(cptr)) ? strerror(cli_error(cptr)) : cli_info(cptr);
1247 msg = "Unknown error";
1248 exit_client(cptr, cptr, &me, msg);
1255 * ...hmm, with non-blocking sockets we might get
1256 * here from quite valid reasons, although.. why
1257 * would select report "data available" when there
1258 * wasn't... So, this must be an error anyway... --msa
1259 * actually, EOF occurs when read() returns 0 and
1260 * in due course, select() returns that fd as ready
1261 * for reading even though it ends up being an EOF. -avalon
1263 Debug((DEBUG_ERROR, "READ ERROR: fd = %d %d %d", i, cli_error(cptr), length));
1265 if ((IsServer(cptr) || IsHandshake(cptr)) && cli_error(cptr) == 0 && length == 0)
1266 exit_client_msg(cptr, cptr, &me, "Server %s closed the connection (%s)",
1267 cli_name(cptr), cli_serv(cptr)->last_error_msg);
1269 const char* msg = (cli_error(cptr)) ? strerror(cli_error(cptr)) : "EOF from client";
1271 msg = "Unknown error";
1272 exit_client_msg(cptr, cptr, &me, "Read error: %s", msg);
1278 #endif /* USE_SELECT */
1281 * connect_server - start or complete a connection to another server
1282 * returns true (1) if successful, false (0) otherwise
1284 * aconf must point to a valid C:line
1285 * m_connect calls this with a valid by client and a null reply
1286 * try_connections calls this with a null by client, and a null reply
1287 * connect_dns_callback call this with a null by client, and a valid reply
1289 * XXX - if this comes from an m_connect message and a dns query needs to
1290 * be done, we loose the information about who started the connection and
1291 * it's considered an auto connect.
1293 int connect_server(struct ConfItem* aconf, struct Client* by,
1294 struct DNSReply* reply)
1296 struct Client* cptr = 0;
1299 if (aconf->dns_pending) {
1300 sendto_opmask_butone(0, SNO_OLDSNO, "Server %s connect DNS pending",
1304 Debug((DEBUG_NOTICE, "Connect to %s[@%s]", aconf->name,
1305 ircd_ntoa((const char*) &aconf->ipnum)));
1307 if ((cptr = FindClient(aconf->name))) {
1308 if (IsServer(cptr) || IsMe(cptr)) {
1309 sendto_opmask_butone(0, SNO_OLDSNO, "Server %s already present from %s",
1310 aconf->name, cli_name(cli_from(cptr)));
1311 if (by && IsUser(by) && !MyUser(by)) {
1312 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Server %s already present "
1313 "from %s", by, aconf->name, cli_name(cli_from(cptr)));
1317 else if (IsHandshake(cptr) || IsConnecting(cptr)) {
1318 if (by && IsUser(by)) {
1319 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Connection to %s already in "
1320 "progress", by, cli_name(cptr));
1326 * If we dont know the IP# for this host and itis a hostname and
1327 * not a ip# string, then try and find the appropriate host record.
1329 if (INADDR_NONE == aconf->ipnum.s_addr) {
1330 char buf[HOSTLEN + 1];
1332 if (INADDR_NONE == (aconf->ipnum.s_addr = inet_addr(aconf->host))) {
1333 struct DNSQuery query;
1336 query.callback = connect_dns_callback;
1337 host_from_uh(buf, aconf->host, HOSTLEN);
1338 buf[HOSTLEN] = '\0';
1340 reply = gethost_byname(buf, &query);
1343 aconf->dns_pending = 1;
1346 memcpy(&aconf->ipnum, reply->hp->h_addr, sizeof(struct in_addr));
1349 cptr = make_client(NULL, STAT_UNKNOWN_SERVER);
1352 cli_dns_reply(cptr) = reply;
1355 * Copy these in so we have something for error detection.
1357 ircd_strncpy(cli_name(cptr), aconf->name, HOSTLEN);
1358 ircd_strncpy(cli_sockhost(cptr), aconf->host, HOSTLEN);
1361 * Attach config entries to client here rather than in
1362 * completed_connection. This to avoid null pointer references
1364 attach_confs_byhost(cptr, aconf->host, CONF_SERVER);
1366 if (!find_conf_byhost(cli_confs(cptr), aconf->host, CONF_SERVER)) {
1367 sendto_opmask_butone(0, SNO_OLDSNO, "Host %s is not enabled for "
1368 "connecting: no C-line", aconf->name);
1369 if (by && IsUser(by) && !MyUser(by)) {
1370 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Connect to host %s failed: no "
1371 "C-line", by, aconf->name);
1373 det_confs_butmask(cptr, 0);
1378 * attempt to connect to the server in the conf line
1380 if (!connect_inet(aconf, cptr)) {
1381 if (by && IsUser(by) && !MyUser(by)) {
1382 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Couldn't connect to %s", by,
1385 det_confs_butmask(cptr, 0);
1390 * NOTE: if we're here we have a valid C:Line and the client should
1391 * have started the connection and stored the remote address/port and
1392 * ip address name in itself
1394 * The socket has been connected or connect is in progress.
1397 if (by && IsUser(by)) {
1398 sprintf_irc(cli_serv(cptr)->by, "%s%s", NumNick(by));
1399 assert(0 == cli_serv(cptr)->user);
1400 cli_serv(cptr)->user = cli_user(by);
1401 cli_user(by)->refcnt++;
1404 *(cli_serv(cptr))->by = '\0';
1405 /* strcpy(cptr->serv->by, "Auto"); */
1407 cli_serv(cptr)->up = &me;
1408 SetConnecting(cptr);
1410 if (cli_fd(cptr) > HighestFd)
1411 HighestFd = cli_fd(cptr);
1414 LocalClientArray[cli_fd(cptr)] = cptr;
1416 Count_newunknown(UserStats);
1417 /* Actually we lie, the connect hasn't succeeded yet, but we have a valid
1418 * cptr, so we register it now.
1419 * Maybe these two calls should be merged.
1421 add_client_to_list(cptr);
1423 nextping = CurrentTime;
1429 * Setup local socket structure to use for binding to.
1431 void set_virtual_host(struct in_addr addr)
1433 memset(&VirtualHost, 0, sizeof(VirtualHost));
1434 VirtualHost.sin_family = AF_INET;
1435 VirtualHost.sin_addr.s_addr = addr.s_addr;
1439 * Find the real hostname for the host running the server (or one which
1440 * matches the server's name) and its primary IP#. Hostname is stored
1441 * in the client structure passed as a pointer.
1443 void init_server_identity(void)
1445 const struct LocalConf* conf = conf_get_local();
1448 ircd_strncpy(cli_name(&me), conf->name, HOSTLEN);
1449 SetYXXServerName(&me, conf->numeric);