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.
29 #include "ircd_osdep.h"
30 #include "ircd_string.h"
38 #include "querycmds.h"
46 #include "sprintf_irc.h"
52 #include <arpa/inet.h>
53 #include <arpa/nameser.h>
62 #include <sys/ioctl.h>
63 #include <sys/socket.h>
65 #include <sys/utsname.h>
72 #ifndef IN_LOOPBACKNET
73 #define IN_LOOPBACKNET 0x7f
77 #define INADDR_NONE 0xffffffff
80 struct Client* LocalClientArray[MAXCONNECTIONS];
82 static struct sockaddr_in virtualHost;
83 static char readbuf[SERVER_TCP_WINDOW];
84 static int running_in_background;
87 * report_error text constants
89 const char* const ACCEPT_ERROR_MSG = "error accepting connection for %s: %s";
90 const char* const BIND_ERROR_MSG = "bind error for %s: %s";
91 const char* const CONNECT_ERROR_MSG = "connect to host %s failed: %s";
92 const char* const CONNLIMIT_ERROR_MSG = "connect limit exceeded for %s: %s";
93 const char* const LISTEN_ERROR_MSG = "listen error for %s: %s";
94 const char* const NONB_ERROR_MSG = "error setting non-blocking for %s: %s";
95 const char* const PEERNAME_ERROR_MSG = "getpeername failed for %s: %s";
96 const char* const POLL_ERROR_MSG = "poll error for %s: %s";
97 const char* const REUSEADDR_ERROR_MSG = "error setting SO_REUSEADDR for %s: %s";
98 const char* const SELECT_ERROR_MSG = "select error for %s: %s";
99 const char* const SETBUFS_ERROR_MSG = "error setting buffer size for %s: %s";
100 const char* const SOCKET_ERROR_MSG = "error creating socket for %s: %s";
103 struct sockaddr_in vserv;
110 #ifndef NOFLOODCONTROL
111 #define NOFLOODCONTROL
115 #if !defined(USE_POLL)
116 #if FD_SETSIZE < (MAXCONNECTIONS + 4)
120 * All operating systems work when MAXCONNECTIONS <= 252.
121 * Most operating systems work when MAXCONNECTIONS <= 1020 and FD_SETSIZE is
122 * updated correctly in the system headers (on BSD systems our sys.h has
123 * defined FD_SETSIZE to MAXCONNECTIONS+4 before including the system's headers
124 * but sys/types.h might have abruptly redefined it so the check is still
125 * done), you might already need to recompile your kernel.
126 * For larger FD_SETSIZE your milage may vary (kernel patches may be needed).
127 * The check is _NOT_ done if we will not use FD_SETS at all (USE_POLL)
129 #error "FD_SETSIZE is too small or MAXCONNECTIONS too large."
135 * Cannot use perror() within daemon. stderr is closed in
136 * ircd and cannot be used. And, worse yet, it might have
137 * been reassigned to a normal connection...
143 * This a replacement for perror(). Record error to log and
144 * also send a copy to all *LOCAL* opers online.
146 * text is a *format* string for outputting error. It must
147 * contain only two '%s', the first will be replaced
148 * by the sockhost from the cptr, and the latter will
149 * be taken from sys_errlist[errno].
151 * cptr if not NULL, is the *LOCAL* client associated with
154 void report_error(const char* text, const char* who, int err)
156 static time_t last_notice = 0;
157 int errtmp = errno; /* debug may change 'errno' */
158 const char* errmsg = (err) ? strerror(err) : "";
163 if (last_notice + 20 < CurrentTime) {
165 * pace error messages so opers don't get flooded by transients
167 sendto_ops(text, who, errmsg);
168 last_notice = CurrentTime;
171 ircd_log(L_ERROR, text, who, errmsg);
173 if (!running_in_background) {
174 fprintf(stderr, text, who, errmsg);
175 fprintf(stderr, "\n");
182 * connect_dns_callback - called when resolver query finishes
183 * if the query resulted in a successful search, reply will contain
184 * a non-null pointer, otherwise reply will be null.
185 * if successful start the connection, otherwise notify opers
187 static void connect_dns_callback(void* vptr, struct DNSReply* reply)
189 struct ConfItem* aconf = (struct ConfItem*) vptr;
190 aconf->dns_pending = 0;
192 memcpy(&aconf->ipnum, reply->hp->h_addr, sizeof(struct in_addr));
193 connect_server(aconf, 0, reply);
196 sendto_ops("Connect to %s failed: host lookup", aconf->name);
201 * connect_inet - set up address and port and make a connection
203 static int connect_inet(struct ConfItem* aconf, struct Client* cptr)
205 static struct sockaddr_in sin;
209 * Might as well get sockhost from here, the connection is attempted
210 * with it so if it fails its useless.
212 cptr->fd = socket(AF_INET, SOCK_STREAM, 0);
213 if (-1 == cptr->fd) {
215 report_error(SOCKET_ERROR_MSG, cptr->name, errno);
218 if (cptr->fd >= MAXCLIENTS) {
219 report_error(CONNLIMIT_ERROR_MSG, cptr->name, 0);
225 * Bind to a local IP# (with unknown port - let unix decide) so
226 * we have some chance of knowing the IP# that gets used for a host
227 * with more than one IP#.
229 * No we don't bind it, not all OS's can handle connecting with
230 * an already bound socket, different ip# might occur anyway
231 * leading to a freezing select() on this side for some time.
232 * I had this on my Linux 1.1.88 --Run
236 * No, we do bind it if we have virtual host support. If we don't
237 * explicitly bind it, it will default to IN_ADDR_ANY and we lose
238 * due to the other server not allowing our base IP --smg
240 if (bind(cptr->fd, (struct sockaddr*) &virtualHost, sizeof(virtualHost))) {
241 report_error(BIND_ERROR_MSG, cptr->name, errno);
246 memset(&sin, 0, sizeof(sin));
247 sin.sin_family = AF_INET;
248 sin.sin_addr.s_addr = aconf->ipnum.s_addr;
249 sin.sin_port = htons(aconf->port);
251 * save connection info in client
253 cptr->ip.s_addr = aconf->ipnum.s_addr;
254 cptr->port = aconf->port;
255 ircd_ntoa_r(cptr->sock_ip, (const char*) &cptr->ip);
257 * we want a big buffer for server connections
259 if (!os_set_sockbufs(cptr->fd, SERVER_TCP_WINDOW)) {
261 report_error(SETBUFS_ERROR_MSG, cptr->name, errno);
265 * ALWAYS set sockets non-blocking
267 if (!os_set_nonblocking(cptr->fd)) {
269 report_error(NONB_ERROR_MSG, cptr->name, errno);
272 if (!os_connect_nonb(cptr->fd, &sin)) {
274 report_error(CONNECT_ERROR_MSG, cptr->name, errno);
282 * Attempt to send a sequence of bytes to the connection.
285 * < 0 Some fatal error occurred, (but not EWOULDBLOCK).
286 * This return is a request to close the socket and
289 * >= 0 No real error occurred, returns the number of
290 * bytes actually transferred. EWOULDBLOCK and other
291 * possibly similar conditions should be mapped to
292 * zero return. Upper level routine will have to
293 * decide what to do with those unwritten bytes...
295 * *NOTE* alarm calls have been preserved, so this should
296 * work equally well whether blocking or non-blocking
299 * We don't use blocking anymore, that is impossible with the
300 * net.loads today anyway. Commented out the alarms to save cpu.
303 size_t deliver_it(struct Client *cptr, const char *str, size_t len)
305 size_t bytes_written = 0;
308 switch (os_send_nonb(cptr->fd, str, len, &bytes_written)) {
310 cptr->flags &= ~FLAGS_BLOCKED;
312 cptr->sendB += bytes_written;
313 me.sendB += bytes_written;
314 if (cptr->sendB > 1023) {
315 cptr->sendK += (cptr->sendB >> 10);
316 cptr->sendB &= 0x03ff; /* 2^10 = 1024, 3ff = 1023 */
318 if (me.sendB > 1023) {
319 me.sendK += (me.sendB >> 10);
322 if (bytes_written < len)
323 cptr->flags |= FLAGS_BLOCKED;
326 cptr->flags |= FLAGS_BLOCKED;
330 cptr->flags |= FLAGS_DEADSOCKET;
333 return bytes_written;
342 int limit = os_set_fdlimit(MAXCONNECTIONS);
344 fprintf(stderr, "error setting max fd's to %d\n", limit);
347 else if (limit > 0) {
348 fprintf(stderr, "ircd fd table too big\nHard Limit: %d IRC max: %d\n",
349 limit, MAXCONNECTIONS);
350 fprintf(stderr, "set MAXCONNECTIONS to a smaller value");
354 for (fd = 3; fd < MAXCONNECTIONS; ++fd)
357 LocalClientArray[fd] = NULL;
359 LocalClientArray[2] = 0;
360 LocalClientArray[1] = 0;
361 LocalClientArray[0] = 0;
365 if (bootopt & BOOT_TTY) {
366 /* debugging is going to a tty */
370 if (!(bootopt & BOOT_DEBUG))
375 running_in_background = 1;
377 if ((fd = open("/dev/tty", O_RDWR)) > -1) {
378 ioctl(fd, TIOCNOTTY, 0);
386 void release_dns_reply(struct Client* cptr)
389 assert(MyConnect(cptr));
391 if (cptr->dns_reply) {
392 assert(0 < cptr->dns_reply->ref_count);
393 --cptr->dns_reply->ref_count;
399 * completed_connection
401 * Complete non-blocking connect()-sequence. Check access and
402 * terminate connection, if trouble detected.
404 * Return TRUE, if successfully completed
405 * FALSE, if failed and ClientExit
407 static int completed_connection(struct Client* cptr)
409 struct ConfItem *aconf;
411 struct Client *acptr;
417 * get the socket status from the fd first to check if
418 * connection actually succeeded
420 if ((cptr->error = os_get_sockerr(cptr->fd))) {
421 sendto_ops("Connection failed to %s: %s", cptr->name,
422 strerror(cptr->error));
425 if (!(aconf = find_conf_byname(cptr->confs, cptr->name, CONF_SERVER))) {
426 sendto_ops("Lost Server Line for %s", cptr->name);
429 if (!EmptyString(aconf->passwd))
430 sendto_one(cptr, "PASS :%s", aconf->passwd);
433 /* dead code, already done in connect_server */
437 * Create a unique timestamp
440 for (i = HighestFd; i > -1; --i) {
441 if ((acptr = LocalClientArray[i]) &&
442 (IsServer(acptr) || IsHandshake(acptr))) {
443 if (acptr->serv->timestamp >= newts)
444 newts = acptr->serv->timestamp + 1;
447 assert(0 != cptr->serv);
449 cptr->serv->timestamp = newts;
452 * Make us timeout after twice the timeout for DNS look ups
454 cptr->lasttime = CurrentTime;
455 cptr->flags |= FLAGS_PINGSENT;
456 sendto_one(cptr, "SERVER %s 1 " TIME_T_FMT " " TIME_T_FMT " J%s %s%s :%s",
457 me.name, me.serv->timestamp, newts, MAJOR_PROTOCOL,
458 NumServCap(&me), me.info);
460 return (IsDead(cptr)) ? 0 : 1;
466 * Close the physical connection. This function must make
467 * MyConnect(cptr) == FALSE, and set cptr->from == NULL.
469 void close_connection(struct Client *cptr)
471 struct ConfItem* aconf;
473 if (IsServer(cptr)) {
474 ServerStats->is_sv++;
475 ServerStats->is_sbs += cptr->sendB;
476 ServerStats->is_sbr += cptr->receiveB;
477 ServerStats->is_sks += cptr->sendK;
478 ServerStats->is_skr += cptr->receiveK;
479 ServerStats->is_sti += CurrentTime - cptr->firsttime;
480 if (ServerStats->is_sbs > 1023) {
481 ServerStats->is_sks += (ServerStats->is_sbs >> 10);
482 ServerStats->is_sbs &= 0x3ff;
484 if (ServerStats->is_sbr > 1023) {
485 ServerStats->is_skr += (ServerStats->is_sbr >> 10);
486 ServerStats->is_sbr &= 0x3ff;
489 * If the connection has been up for a long amount of time, schedule
490 * a 'quick' reconnect, else reset the next-connect cycle.
492 if ((aconf = find_conf_exact(cptr->name, 0, cptr->sockhost, CONF_SERVER))) {
494 * Reschedule a faster reconnect, if this was a automaticly
495 * connected configuration entry. (Note that if we have had
496 * a rehash in between, the status has been changed to
497 * CONF_ILLEGAL). But only do this if it was a "good" link.
499 aconf->hold = CurrentTime;
500 aconf->hold += (aconf->hold - cptr->since > HANGONGOODLINK) ?
501 HANGONRETRYDELAY : ConfConFreq(aconf);
502 if (nextconnect > aconf->hold)
503 nextconnect = aconf->hold;
506 else if (IsUser(cptr)) {
507 ServerStats->is_cl++;
508 ServerStats->is_cbs += cptr->sendB;
509 ServerStats->is_cbr += cptr->receiveB;
510 ServerStats->is_cks += cptr->sendK;
511 ServerStats->is_ckr += cptr->receiveK;
512 ServerStats->is_cti += CurrentTime - cptr->firsttime;
513 if (ServerStats->is_cbs > 1023) {
514 ServerStats->is_cks += (ServerStats->is_cbs >> 10);
515 ServerStats->is_cbs &= 0x3ff;
517 if (ServerStats->is_cbr > 1023) {
518 ServerStats->is_ckr += (ServerStats->is_cbr >> 10);
519 ServerStats->is_cbr &= 0x3ff;
523 ServerStats->is_ni++;
526 flush_connections(cptr);
527 LocalClientArray[cptr->fd] = 0;
531 cptr->flags |= FLAGS_DEADSOCKET;
533 DBufClear(&cptr->sendQ);
534 DBufClear(&cptr->recvQ);
535 memset(cptr->passwd, 0, sizeof(cptr->passwd));
536 set_snomask(cptr, 0, SNO_SET);
538 det_confs_butmask(cptr, 0);
540 if (cptr->listener) {
541 release_listener(cptr->listener);
545 for ( ; HighestFd > 0; --HighestFd) {
546 if (LocalClientArray[HighestFd])
551 int net_close_unregistered_connections(struct Client* source)
558 for (i = HighestFd; i > 0; --i) {
559 if ((cptr = LocalClientArray[i]) && !IsRegistered(cptr)) {
560 sendto_one(source, rpl_str(RPL_CLOSING), me.name, source->name,
561 get_client_name(source, HIDE_IP), cptr->status);
562 exit_client(source, cptr, &me, "Oper Closing");
570 * Creates a client which has just connected to us on the given fd.
571 * The sockhost field is initialized with the ip# of the host.
572 * The client is not added to the linked list of clients, it is
573 * passed off to the auth handler for dns and ident queries.
575 void add_connection(struct Listener* listener, int fd)
577 struct sockaddr_in addr;
578 struct Client* new_client;
579 time_t next_target = 0;
580 const char* const throttle_message =
581 "ERROR: Your host is trying to (re)connect too fast -- throttled\r\n";
582 /* 12345678901234567890123456789012345679012345678901234567890123456 */
584 assert(0 != listener);
586 * Removed preliminary access check. Full check is performed in
587 * m_server and m_user instead. Also connection time out help to
588 * get rid of unwanted connections.
590 if (!os_get_peername(fd, &addr) || !os_set_nonblocking(fd)) {
591 ++ServerStats->is_ref;
596 * XXX - do we really want to do this? is it needed?
598 os_disable_options(fd);
601 * Add this local client to the IPcheck registry.
602 * If it is a connection to a user port and if the site has been throttled,
605 if (!IPcheck_local_connect(addr.sin_addr, &next_target) && !listener->server) {
606 ++ServerStats->is_ref;
608 * strlen(throttle_message) == 66
610 send(fd, throttle_message, 66, 0);
615 new_client = make_client(NULL,
616 (listener->server) ? STAT_UNKNOWN_SERVER : STAT_UNKNOWN_USER);
618 * Copy ascii address to 'sockhost' just in case. Then we
619 * have something valid to put into error messages...
621 ircd_ntoa_r(new_client->sock_ip, (const char*) &addr.sin_addr);
622 strcpy(new_client->sockhost, new_client->sock_ip);
623 new_client->ip.s_addr = addr.sin_addr.s_addr;
624 new_client->port = ntohs(addr.sin_port);
627 new_client->nexttarget = next_target;
631 if (!listener->server)
632 SetIPChecked(new_client);
633 new_client->listener = listener;
634 ++listener->ref_count;
636 Count_newunknown(UserStats);
638 * if we've made it this far we can put the client on the auth query pile
640 start_auth(new_client);
646 * Read a 'packet' of data from a connection and process it. Read in 8k
647 * chunks to give a better performance rating (for server connections).
648 * Do some tricky stuff for client connections to make sure they don't do
649 * any flooding >:-) -avalon
651 static int read_packet(struct Client *cptr, int socket_ready)
656 if (socket_ready && !(IsUser(cptr) && DBufLength(&cptr->recvQ) > CLIENT_FLOOD)) {
657 switch (os_recv_nonb(cptr->fd, readbuf, sizeof(readbuf), &length)) {
660 cptr->lasttime = CurrentTime;
661 if (cptr->lasttime > cptr->since)
662 cptr->since = cptr->lasttime;
663 cptr->flags &= ~(FLAGS_PINGSENT | FLAGS_NONL);
670 /* cptr->flags |= FLAGS_DEADSOCKET; */
676 * For server connections, we process as many as we can without
677 * worrying about the time of day or anything :)
679 if (length > 0 && IsServer(cptr)) {
680 return server_dopacket(cptr, readbuf, length);
684 * Before we even think of parsing what we just read, stick
685 * it on the end of the receive queue and do it when its
688 if (length > 0 && 0 == dbuf_put(&cptr->recvQ, readbuf, length)) {
689 return exit_client(cptr, cptr, &me, "dbuf_put fail");
691 #ifndef NOFLOODCONTROL
693 * XXX - cptr will always be a user or unregistered
695 if (IsUser(cptr) && DBufLength(&cptr->recvQ) > CLIENT_FLOOD)
696 return exit_client(cptr, cptr, &me, "Excess Flood");
698 while (DBufLength(&cptr->recvQ) && !NoNewLine(cptr) &&
699 (IsTrusted(cptr) || cptr->since - CurrentTime < 10))
701 while (DBufLength(&cptr->recvQ) && !NoNewLine(cptr))
705 * If it has become registered as a Server
706 * then skip the per-message parsing below.
708 if (IsServer(cptr)) {
709 dolen = dbuf_get(&cptr->recvQ, readbuf, sizeof(readbuf));
710 return (dolen) ? server_dopacket(cptr, readbuf, dolen) : 1;
712 dolen = dbuf_getmsg(&cptr->recvQ, cptr->buffer, BUFSIZE);
714 * Devious looking...whats it do ? well..if a client
715 * sends a *long* message without any CR or LF, then
716 * dbuf_getmsg fails and we pull it out using this
717 * loop which just gets the next 512 bytes and then
718 * deletes the rest of the buffer contents.
722 if (DBufLength(&cptr->recvQ) < 510)
723 cptr->flags |= FLAGS_NONL;
725 DBufClear(&cptr->recvQ);
727 else if (CPTR_KILLED == client_dopacket(cptr, dolen))
734 static int on_write_unblocked(struct Client* cptr)
737 * ...room for writing, empty some queue then...
739 cptr->flags &= ~FLAGS_BLOCKED;
740 if (IsConnecting(cptr)) {
741 if (!completed_connection(cptr))
744 else if (cptr->listing && DBufLength(&cptr->sendQ) < 2048)
745 list_next_channels(cptr, 64);
751 * Select / Poll Read Algorithm for ircd
753 * We need to check the file descriptors for all the different types
754 * of things that use them, so check for reads on everything but connects
755 * and writes on connects and descriptors that are blocked
757 * for each (client in local) {
758 * if (not connecting)
760 * if (connecting or blocked)
765 * for each (client in local) {
766 * if (there are descriptors to check) {
767 * if (write activity)
774 * Note we must always process data read whether or not there has been
775 * read activity or file descriptors set, since data is buffered by the client.
784 #if defined(POLLMSG) && defined(POLLIN) && defined(POLLRDNORM)
785 # define POLLREADFLAGS (POLLMSG|POLLIN|POLLRDNORM)
787 # if defined(POLLIN) && defined(POLLRDNORM)
788 # define POLLREADFLAGS (POLLIN|POLLRDNORM)
791 # define POLLREADFLAGS POLLIN
793 # if defined(POLLRDNORM)
794 # define POLLREADFLAGS POLLRDNORM
800 #if defined(POLLOUT) && defined(POLLWRNORM)
801 #define POLLWRITEFLAGS (POLLOUT|POLLWRNORM)
803 # if defined(POLLOUT)
804 # define POLLWRITEFLAGS POLLOUT
806 # if defined(POLLWRNORM)
807 # define POLLWRITEFLAGS POLLWRNORM
813 #define POLLERRORS (POLLHUP|POLLERR)
815 #define POLLERRORS POLLERR
819 * NOTE: pfd and pfd_count are local variable names in read_message
821 #define PFD_SETR(xfd) \
822 do { CHECK_ADD_PFD(xfd) pfd->events |= POLLREADFLAGS; } while(0)
823 #define PFD_SETW(xfd) \
824 do { CHECK_ADD_PFD(xfd) pfd->events |= POLLWRITEFLAGS; } while(0)
826 #define CHECK_ADD_PFD(xfd) \
827 if (pfd->fd != xfd) { \
828 pfd = &poll_fds[pfd_count++]; \
829 poll_fds[pfd_count].fd = -1; \
835 * Check all connections for new connections and input data that is to be
836 * processed. Also check for connections with data queued and whether we can
839 * Don't ever use ZERO for `delay', unless you mean to poll and then
840 * you have to have sleep/wait somewhere else in the code.--msa
842 int read_message(time_t delay)
844 struct pollfd poll_fds[MAXCONNECTIONS + 1];
846 struct Listener* listener = 0;
847 struct AuthRequest* auth = 0;
848 struct AuthRequest* auth_next = 0;
850 time_t delay2 = delay;
855 struct pollfd* pfd = 0;
856 struct pollfd* res_pfd = 0;
860 unsigned long timeout;
868 if (-1 < ResolverFileDescriptor) {
869 PFD_SETR(ResolverFileDescriptor);
873 * add auth file descriptors
875 for (auth = AuthPollList; auth; auth = auth->next) {
876 assert(-1 < auth->fd);
877 auth->index = pfd_count;
878 if (IsAuthConnect(auth))
884 * add listener file descriptors
886 for (listener = ListenerPollList; listener; listener = listener->next) {
887 assert(-1 < listener->fd);
889 * pfd_count is incremented by PFD_SETR so we need to save the
892 listener->index = pfd_count;
893 PFD_SETR(listener->fd);
896 for (i = HighestFd; -1 < i; --i) {
897 if ((cptr = LocalClientArray[i])) {
899 if (DBufLength(&cptr->recvQ))
901 if (DBufLength(&cptr->recvQ) < 4088 || IsServer(cptr)) {
904 if (DBufLength(&cptr->sendQ) || IsConnecting(cptr) ||
905 (cptr->listing && DBufLength(&cptr->sendQ) < 2048)) {
911 Debug((DEBUG_INFO, "poll: %d %d", delay, delay2));
913 timeout = (IRCD_MIN(delay2, delay)) * 1000;
915 nfds = poll(poll_fds, pfd_count, timeout);
917 CurrentTime = time(0);
923 report_error(POLL_ERROR_MSG, me.name, errno);
926 server_restart("too many poll errors");
928 CurrentTime = time(0);
931 if (res_pfd && (res_pfd->revents & (POLLREADFLAGS | POLLERRORS))) {
938 for (auth = AuthPollList; auth; auth = auth_next) {
939 auth_next = auth->next;
942 * check for any event, we only ask for one at a time
944 if (poll_fds[i].revents) {
945 if (IsAuthConnect(auth))
946 send_auth_query(auth);
948 read_auth_reply(auth);
956 for (listener = ListenerPollList; listener; listener = listener->next) {
958 if (poll_fds[i].revents) {
959 accept_connection(listener);
965 * i contains the next non-auth/non-listener index, since we put the
966 * resolver, auth and listener, file descriptors in poll_fds first,
967 * the very next one should be the start of the clients
969 pfd = &poll_fds[++i];
971 for ( ; (i < pfd_count); ++i, ++pfd) {
972 if (!(cptr = LocalClientArray[pfd->fd]))
974 read_ready = write_ready = 0;
976 if (0 < nfds && pfd->revents) {
979 read_ready = pfd->revents & POLLREADFLAGS;
980 write_ready = pfd->revents & POLLWRITEFLAGS;
982 if (pfd->revents & POLLERRORS) {
983 if (pfd->events & POLLREADFLAGS)
985 if (pfd->events & POLLWRITEFLAGS)
990 if (!on_write_unblocked(cptr) || IsDead(cptr)) {
991 exit_client(cptr, cptr, &me,
992 cptr->error ? strerror(cptr->error) : LastDeadComment(cptr));
996 length = 1; /* for fall through case */
997 if ((!NoNewLine(cptr) || read_ready) && !IsDead(cptr)) {
998 if (CPTR_KILLED == (length = read_packet(cptr, read_ready)))
1002 /* Bullshit, why would we want to flush sockets while using non-blocking?
1003 * This uses > 4% cpu! --Run */
1005 flush_connections(poll_cptr[i]);
1008 exit_client(cptr, cptr, &me,
1009 cptr->error ? strerror(cptr->error) : LastDeadComment(cptr));
1014 cptr->flags |= FLAGS_DEADSOCKET;
1016 * ...hmm, with non-blocking sockets we might get
1017 * here from quite valid reasons, although.. why
1018 * would select report "data available" when there
1019 * wasn't... So, this must be an error anyway... --msa
1020 * actually, EOF occurs when read() returns 0 and
1021 * in due course, select() returns that fd as ready
1022 * for reading even though it ends up being an EOF. -avalon
1024 Debug((DEBUG_ERROR, "READ ERROR: fd = %d %d %d", pfd->fd, errno, length));
1026 if ((IsServer(cptr) || IsHandshake(cptr)) && cptr->error == 0 && length == 0)
1027 exit_client_msg(cptr, cptr, &me, "Server %s closed the connection (%s)",
1028 cptr->name, cptr->serv->last_error_msg);
1030 exit_client_msg(cptr, cptr, &me, "Read error to %s: %s",
1031 get_client_name(cptr, HIDE_IP),
1032 (cptr->error) ? strerror(cptr->error) : "EOF from client");
1036 #else /* USE_SELECT */
1039 * Check all connections for new connections and input data that is to be
1040 * processed. Also check for connections with data queued and whether we can
1043 * Don't ever use ZERO for `delay', unless you mean to poll and then
1044 * you have to have sleep/wait somewhere else in the code.--msa
1046 int read_message(time_t delay)
1048 struct Client* cptr;
1049 struct Listener* listener;
1051 struct timeval wait;
1052 time_t delay2 = delay;
1053 unsigned long usec = 0;
1057 struct AuthRequest* auth = 0;
1058 struct AuthRequest* auth_next = 0;
1066 FD_ZERO(&write_set);
1068 if (-1 < ResolverFileDescriptor)
1069 FD_SET(ResolverFileDescriptor, &read_set);
1071 * set auth file descriptors
1073 for (auth = AuthPollList; auth; auth = auth->next) {
1074 assert(-1 < auth->fd);
1075 if (IsAuthConnect(auth))
1076 FD_SET(auth->fd, &write_set);
1077 else /* if (IsAuthPending(auth)) */
1078 FD_SET(auth->fd, &read_set);
1081 * set listener file descriptors
1083 for (listener = ListenerPollList; listener; listener = listener->next) {
1084 assert(-1 < listener->fd);
1085 FD_SET(listener->fd, &read_set);
1088 for (i = HighestFd; i > -1; --i) {
1089 if ((cptr = LocalClientArray[i])) {
1090 if (DBufLength(&cptr->recvQ))
1092 if (DBufLength(&cptr->recvQ) < 4088 || IsServer(cptr))
1093 FD_SET(i, &read_set);
1094 if (DBufLength(&cptr->sendQ) || IsConnecting(cptr) ||
1095 (cptr->listing && DBufLength(&cptr->sendQ) < 2048))
1096 FD_SET(i, &write_set);
1100 wait.tv_sec = IRCD_MIN(delay2, delay);
1101 wait.tv_usec = usec;
1103 Debug((DEBUG_INFO, "select: %d %d", delay, delay2));
1105 nfds = select(FD_SETSIZE, &read_set, &write_set, 0, &wait);
1107 CurrentTime = time(0);
1114 report_error(SELECT_ERROR_MSG, me.name, errno);
1116 server_restart("too many select errors");
1118 CurrentTime = time(0);
1121 if (-1 < ResolverFileDescriptor &&
1122 FD_ISSET(ResolverFileDescriptor, &read_set)) {
1127 * Check fd sets for the auth fd's (if set and valid!) first
1128 * because these can not be processed using the normal loops below.
1131 for (auth = AuthPollList; auth; auth = auth_next) {
1132 auth_next = auth->next;
1133 assert(-1 < auth->fd);
1134 if (IsAuthConnect(auth) && FD_ISSET(auth->fd, &write_set)) {
1135 send_auth_query(auth);
1139 else if (FD_ISSET(auth->fd, &read_set)) {
1140 read_auth_reply(auth);
1146 * next accept connections from active listeners
1148 for (listener = ListenerPollList; listener; listener = listener->next) {
1149 assert(-1 < listener->fd);
1150 if (0 < nfds && FD_ISSET(listener->fd, &read_set))
1151 accept_connection(listener);
1154 for (i = HighestFd; -1 < i; --i) {
1155 if (!(cptr = LocalClientArray[i]))
1159 if (FD_ISSET(i, &write_set)) {
1161 if (!on_write_unblocked(cptr) || IsDead(cptr)) {
1162 if (FD_ISSET(i, &read_set))
1164 exit_client(cptr, cptr, &me,
1165 cptr->error ? strerror(cptr->error) : LastDeadComment(cptr));
1169 if ((read_ready = FD_ISSET(i, &read_set)))
1172 length = 1; /* for fall through case */
1173 if ((!NoNewLine(cptr) || read_ready) && !IsDead(cptr)) {
1174 if (CPTR_KILLED == (length = read_packet(cptr, read_ready)))
1178 /* Bullshit, why would we want to flush sockets while using non-blocking?
1179 * This uses > 4% cpu! --Run */
1181 flush_connections(LocalClientArray[i]);
1184 exit_client(cptr, cptr, &me,
1185 cptr->error ? strerror(cptr->error) : LastDeadComment(cptr));
1192 * ...hmm, with non-blocking sockets we might get
1193 * here from quite valid reasons, although.. why
1194 * would select report "data available" when there
1195 * wasn't... So, this must be an error anyway... --msa
1196 * actually, EOF occurs when read() returns 0 and
1197 * in due course, select() returns that fd as ready
1198 * for reading even though it ends up being an EOF. -avalon
1200 Debug((DEBUG_ERROR, "READ ERROR: fd = %d %d %d", i, cptr->error, length));
1202 if ((IsServer(cptr) || IsHandshake(cptr)) && cptr->error == 0 && length == 0)
1203 exit_client_msg(cptr, cptr, &me, "Server %s closed the connection (%s)",
1204 cptr->name, cptr->serv->last_error_msg);
1206 exit_client_msg(cptr, cptr, &me, "Read error to %s: %s",
1207 get_client_name(cptr, HIDE_IP),
1208 cptr->error ? strerror(cptr->error) : "EOF from client");
1213 #endif /* USE_SELECT */
1216 * connect_server - start or complete a connection to another server
1217 * returns true (1) if successful, false (0) otherwise
1219 * aconf must point to a valid C:line
1220 * m_connect calls this with a valid by client and a null reply
1221 * try_connections calls this with a null by client, and a null reply
1222 * connect_dns_callback call this with a null by client, and a valid reply
1224 * XXX - if this comes from an m_connect message and a dns query needs to
1225 * be done, we loose the information about who started the connection and
1226 * it's considered an auto connect.
1228 int connect_server(struct ConfItem* aconf, struct Client* by,
1229 struct DNSReply* reply)
1231 struct Client* cptr = 0;
1234 if (aconf->dns_pending) {
1235 sendto_ops("Server %s connect DNS pending");
1238 Debug((DEBUG_NOTICE, "Connect to %s[@%s]", aconf->name,
1239 ircd_ntoa((const char*) &aconf->ipnum)));
1241 if ((cptr = FindClient(aconf->name))) {
1242 if (IsServer(cptr) || IsMe(cptr)) {
1243 sendto_ops("Server %s already present from %s",
1244 aconf->name, cptr->from->name);
1245 if (by && IsUser(by) && !MyUser(by)) {
1246 sendto_one(by, "%s NOTICE %s%s :Server %s already present from %s",
1247 NumServ(&me), NumNick(by), aconf->name, cptr->from->name);
1251 else if (IsHandshake(cptr) || IsConnecting(cptr)) {
1252 if (by && IsUser(by)) {
1254 sendto_one(by, ":%s NOTICE %s :Connection to %s already in progress",
1255 me.name, by->name, cptr->name);
1257 sendto_one(by, "%s NOTICE %s%s :Connection to %s already in progress",
1258 NumServ(&me), NumNick(by), cptr->name);
1264 * If we dont know the IP# for this host and itis a hostname and
1265 * not a ip# string, then try and find the appropriate host record.
1267 if (INADDR_NONE == aconf->ipnum.s_addr) {
1268 char buf[HOSTLEN + 1];
1270 if (INADDR_NONE == (aconf->ipnum.s_addr = inet_addr(aconf->host))) {
1271 struct DNSQuery query;
1274 query.callback = connect_dns_callback;
1275 host_from_uh(buf, aconf->host, HOSTLEN);
1276 buf[HOSTLEN] = '\0';
1278 reply = gethost_byname(buf, &query);
1281 aconf->dns_pending = 1;
1284 memcpy(&aconf->ipnum, reply->hp->h_addr, sizeof(struct in_addr));
1287 cptr = make_client(NULL, STAT_UNKNOWN_SERVER);
1290 cptr->dns_reply = reply;
1293 * Copy these in so we have something for error detection.
1295 ircd_strncpy(cptr->name, aconf->name, HOSTLEN);
1296 ircd_strncpy(cptr->sockhost, aconf->host, HOSTLEN);
1299 * Attach config entries to client here rather than in
1300 * completed_connection. This to avoid null pointer references
1302 attach_confs_byhost(cptr, aconf->host, CONF_SERVER);
1304 if (!find_conf_byhost(cptr->confs, aconf->host, CONF_SERVER)) {
1305 sendto_ops("Host %s is not enabled for connecting: no C-line", aconf->name);
1306 if (by && IsUser(by) && !MyUser(by)) {
1307 sendto_one(by, "%s NOTICE %s%s :Connect to host %s failed: no C-line",
1308 NumServ(&me), NumNick(by), aconf->name);
1310 det_confs_butmask(cptr, 0);
1315 * attempt to connect to the server in the conf line
1317 if (!connect_inet(aconf, cptr)) {
1318 if (by && IsUser(by) && !MyUser(by)) {
1319 sendto_one(by, "%s NOTICE %s%s :Couldn't connect to %s",
1320 NumServ(&me), NumNick(by), cptr->name);
1322 det_confs_butmask(cptr, 0);
1327 * NOTE: if we're here we have a valid C:Line and the client should
1328 * have started the connection and stored the remote address/port and
1329 * ip address name in itself
1331 * The socket has been connected or connect is in progress.
1334 if (by && IsUser(by)) {
1335 sprintf_irc(cptr->serv->by, "%s%s", NumNick(by));
1336 assert(0 == cptr->serv->user);
1337 cptr->serv->user = by->user;
1341 *cptr->serv->by = '\0';
1342 /* strcpy(cptr->serv->by, "Auto"); */
1344 cptr->serv->up = &me;
1345 SetConnecting(cptr);
1347 if (cptr->fd > HighestFd)
1348 HighestFd = cptr->fd;
1349 LocalClientArray[cptr->fd] = cptr;
1351 Count_newunknown(UserStats);
1352 add_client_to_list(cptr);
1354 nextping = CurrentTime;
1360 * Setup local socket structure to use for binding to.
1362 void init_virtual_host(const struct ConfItem* conf)
1366 memset(&virtualHost, 0, sizeof(virtualHost));
1367 virtualHost.sin_family = AF_INET;
1368 virtualHost.sin_addr.s_addr = INADDR_ANY;
1370 if (EmptyString(conf->passwd) || 0 == strcmp(conf->passwd, "*"))
1372 virtualHost.sin_addr.s_addr = inet_addr(conf->passwd);
1374 if (INADDR_NONE == virtualHost.sin_addr.s_addr)
1375 virtualHost.sin_addr.s_addr = INADDR_ANY;
1379 * Find the real hostname for the host running the server (or one which
1380 * matches the server's name) and its primary IP#. Hostname is stored
1381 * in the client structure passed as a pointer.
1383 int init_server_identity()
1385 struct ConfItem* conf = find_me();
1387 if (!conf || EmptyString(conf->host))
1390 ircd_strncpy(me.name, conf->host, HOSTLEN);
1392 init_virtual_host(conf);