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) : "";
160 errmsg = "Unknown error";
165 if (last_notice + 20 < CurrentTime) {
167 * pace error messages so opers don't get flooded by transients
169 sendto_ops(text, who, errmsg);
170 last_notice = CurrentTime;
173 ircd_log(L_ERROR, text, who, errmsg);
175 if (!running_in_background) {
176 fprintf(stderr, text, who, errmsg);
177 fprintf(stderr, "\n");
184 * connect_dns_callback - called when resolver query finishes
185 * if the query resulted in a successful search, reply will contain
186 * a non-null pointer, otherwise reply will be null.
187 * if successful start the connection, otherwise notify opers
189 static void connect_dns_callback(void* vptr, struct DNSReply* reply)
191 struct ConfItem* aconf = (struct ConfItem*) vptr;
192 aconf->dns_pending = 0;
194 memcpy(&aconf->ipnum, reply->hp->h_addr, sizeof(struct in_addr));
195 connect_server(aconf, 0, reply);
198 sendto_ops("Connect to %s failed: host lookup", aconf->name);
203 * connect_inet - set up address and port and make a connection
205 static int connect_inet(struct ConfItem* aconf, struct Client* cptr)
207 static struct sockaddr_in sin;
211 * Might as well get sockhost from here, the connection is attempted
212 * with it so if it fails its useless.
214 cptr->fd = socket(AF_INET, SOCK_STREAM, 0);
215 if (-1 == cptr->fd) {
217 report_error(SOCKET_ERROR_MSG, cptr->name, errno);
220 if (cptr->fd >= MAXCLIENTS) {
221 report_error(CONNLIMIT_ERROR_MSG, cptr->name, 0);
227 * Bind to a local IP# (with unknown port - let unix decide) so
228 * we have some chance of knowing the IP# that gets used for a host
229 * with more than one IP#.
231 * No we don't bind it, not all OS's can handle connecting with
232 * an already bound socket, different ip# might occur anyway
233 * leading to a freezing select() on this side for some time.
234 * I had this on my Linux 1.1.88 --Run
238 * No, we do bind it if we have virtual host support. If we don't
239 * explicitly bind it, it will default to IN_ADDR_ANY and we lose
240 * due to the other server not allowing our base IP --smg
242 if (bind(cptr->fd, (struct sockaddr*) &virtualHost, sizeof(virtualHost))) {
243 report_error(BIND_ERROR_MSG, cptr->name, errno);
248 memset(&sin, 0, sizeof(sin));
249 sin.sin_family = AF_INET;
250 sin.sin_addr.s_addr = aconf->ipnum.s_addr;
251 sin.sin_port = htons(aconf->port);
253 * save connection info in client
255 cptr->ip.s_addr = aconf->ipnum.s_addr;
256 cptr->port = aconf->port;
257 ircd_ntoa_r(cptr->sock_ip, (const char*) &cptr->ip);
259 * we want a big buffer for server connections
261 if (!os_set_sockbufs(cptr->fd, SERVER_TCP_WINDOW)) {
263 report_error(SETBUFS_ERROR_MSG, cptr->name, errno);
267 * ALWAYS set sockets non-blocking
269 if (!os_set_nonblocking(cptr->fd)) {
271 report_error(NONB_ERROR_MSG, cptr->name, errno);
274 if (!os_connect_nonb(cptr->fd, &sin)) {
276 report_error(CONNECT_ERROR_MSG, cptr->name, errno);
284 * Attempt to send a sequence of bytes to the connection.
287 * < 0 Some fatal error occurred, (but not EWOULDBLOCK).
288 * This return is a request to close the socket and
291 * >= 0 No real error occurred, returns the number of
292 * bytes actually transferred. EWOULDBLOCK and other
293 * possibly similar conditions should be mapped to
294 * zero return. Upper level routine will have to
295 * decide what to do with those unwritten bytes...
297 * *NOTE* alarm calls have been preserved, so this should
298 * work equally well whether blocking or non-blocking
301 * We don't use blocking anymore, that is impossible with the
302 * net.loads today anyway. Commented out the alarms to save cpu.
305 unsigned int deliver_it(struct Client *cptr, const char *str, unsigned int len)
307 unsigned int bytes_written = 0;
310 switch (os_send_nonb(cptr->fd, str, len, &bytes_written)) {
312 cptr->flags &= ~FLAGS_BLOCKED;
314 cptr->sendB += bytes_written;
315 me.sendB += bytes_written;
316 if (cptr->sendB > 1023) {
317 cptr->sendK += (cptr->sendB >> 10);
318 cptr->sendB &= 0x03ff; /* 2^10 = 1024, 3ff = 1023 */
320 if (me.sendB > 1023) {
321 me.sendK += (me.sendB >> 10);
324 if (bytes_written < len)
325 cptr->flags |= FLAGS_BLOCKED;
328 cptr->flags |= FLAGS_BLOCKED;
332 cptr->flags |= FLAGS_DEADSOCKET;
335 return bytes_written;
344 int limit = os_set_fdlimit(MAXCONNECTIONS);
346 fprintf(stderr, "error setting max fd's to %d\n", limit);
349 else if (limit > 0) {
350 fprintf(stderr, "ircd fd table too big\nHard Limit: %d IRC max: %d\n",
351 limit, MAXCONNECTIONS);
352 fprintf(stderr, "set MAXCONNECTIONS to a smaller value");
356 for (fd = 3; fd < MAXCONNECTIONS; ++fd)
359 LocalClientArray[fd] = NULL;
361 LocalClientArray[2] = 0;
362 LocalClientArray[1] = 0;
363 LocalClientArray[0] = 0;
367 if (bootopt & BOOT_TTY) {
368 /* debugging is going to a tty */
372 if (!(bootopt & BOOT_DEBUG))
377 running_in_background = 1;
379 if ((fd = open("/dev/tty", O_RDWR)) > -1) {
380 ioctl(fd, TIOCNOTTY, 0);
388 void release_dns_reply(struct Client* cptr)
391 assert(MyConnect(cptr));
393 if (cptr->dns_reply) {
394 assert(0 < cptr->dns_reply->ref_count);
395 --cptr->dns_reply->ref_count;
401 * completed_connection
403 * Complete non-blocking connect()-sequence. Check access and
404 * terminate connection, if trouble detected.
406 * Return TRUE, if successfully completed
407 * FALSE, if failed and ClientExit
409 static int completed_connection(struct Client* cptr)
411 struct ConfItem *aconf;
413 struct Client *acptr;
419 * get the socket status from the fd first to check if
420 * connection actually succeeded
422 if ((cptr->error = os_get_sockerr(cptr->fd))) {
423 const char* msg = strerror(cptr->error);
425 msg = "Unknown error";
426 sendto_ops("Connection failed to %s: %s", cptr->name, msg);
429 if (!(aconf = find_conf_byname(cptr->confs, cptr->name, CONF_SERVER))) {
430 sendto_ops("Lost Server Line for %s", cptr->name);
433 if (!EmptyString(aconf->passwd))
434 sendto_one(cptr, "PASS :%s", aconf->passwd);
437 /* dead code, already done in connect_server */
441 * Create a unique timestamp
444 for (i = HighestFd; i > -1; --i) {
445 if ((acptr = LocalClientArray[i]) &&
446 (IsServer(acptr) || IsHandshake(acptr))) {
447 if (acptr->serv->timestamp >= newts)
448 newts = acptr->serv->timestamp + 1;
451 assert(0 != cptr->serv);
453 cptr->serv->timestamp = newts;
456 * Make us timeout after twice the timeout for DNS look ups
458 cptr->lasttime = CurrentTime;
459 cptr->flags |= FLAGS_PINGSENT;
460 sendto_one(cptr, "SERVER %s 1 " TIME_T_FMT " " TIME_T_FMT " J%s %s%s :%s",
461 me.name, me.serv->timestamp, newts, MAJOR_PROTOCOL,
462 NumServCap(&me), me.info);
464 return (IsDead(cptr)) ? 0 : 1;
470 * Close the physical connection. This function must make
471 * MyConnect(cptr) == FALSE, and set cptr->from == NULL.
473 void close_connection(struct Client *cptr)
475 struct ConfItem* aconf;
477 if (IsServer(cptr)) {
478 ServerStats->is_sv++;
479 ServerStats->is_sbs += cptr->sendB;
480 ServerStats->is_sbr += cptr->receiveB;
481 ServerStats->is_sks += cptr->sendK;
482 ServerStats->is_skr += cptr->receiveK;
483 ServerStats->is_sti += CurrentTime - cptr->firsttime;
484 if (ServerStats->is_sbs > 1023) {
485 ServerStats->is_sks += (ServerStats->is_sbs >> 10);
486 ServerStats->is_sbs &= 0x3ff;
488 if (ServerStats->is_sbr > 1023) {
489 ServerStats->is_skr += (ServerStats->is_sbr >> 10);
490 ServerStats->is_sbr &= 0x3ff;
493 * If the connection has been up for a long amount of time, schedule
494 * a 'quick' reconnect, else reset the next-connect cycle.
496 if ((aconf = find_conf_exact(cptr->name, 0, cptr->sockhost, CONF_SERVER))) {
498 * Reschedule a faster reconnect, if this was a automaticly
499 * connected configuration entry. (Note that if we have had
500 * a rehash in between, the status has been changed to
501 * CONF_ILLEGAL). But only do this if it was a "good" link.
503 aconf->hold = CurrentTime;
504 aconf->hold += (aconf->hold - cptr->since > HANGONGOODLINK) ?
505 HANGONRETRYDELAY : ConfConFreq(aconf);
506 if (nextconnect > aconf->hold)
507 nextconnect = aconf->hold;
510 else if (IsUser(cptr)) {
511 ServerStats->is_cl++;
512 ServerStats->is_cbs += cptr->sendB;
513 ServerStats->is_cbr += cptr->receiveB;
514 ServerStats->is_cks += cptr->sendK;
515 ServerStats->is_ckr += cptr->receiveK;
516 ServerStats->is_cti += CurrentTime - cptr->firsttime;
517 if (ServerStats->is_cbs > 1023) {
518 ServerStats->is_cks += (ServerStats->is_cbs >> 10);
519 ServerStats->is_cbs &= 0x3ff;
521 if (ServerStats->is_cbr > 1023) {
522 ServerStats->is_ckr += (ServerStats->is_cbr >> 10);
523 ServerStats->is_cbr &= 0x3ff;
527 ServerStats->is_ni++;
530 flush_connections(cptr);
531 LocalClientArray[cptr->fd] = 0;
535 cptr->flags |= FLAGS_DEADSOCKET;
537 DBufClear(&cptr->sendQ);
538 DBufClear(&cptr->recvQ);
539 memset(cptr->passwd, 0, sizeof(cptr->passwd));
540 set_snomask(cptr, 0, SNO_SET);
542 det_confs_butmask(cptr, 0);
544 if (cptr->listener) {
545 release_listener(cptr->listener);
549 for ( ; HighestFd > 0; --HighestFd) {
550 if (LocalClientArray[HighestFd])
555 int net_close_unregistered_connections(struct Client* source)
562 for (i = HighestFd; i > 0; --i) {
563 if ((cptr = LocalClientArray[i]) && !IsRegistered(cptr)) {
564 sendto_one(source, rpl_str(RPL_CLOSING), me.name, source->name,
565 get_client_name(source, HIDE_IP), cptr->status);
566 exit_client(source, cptr, &me, "Oper Closing");
574 * Creates a client which has just connected to us on the given fd.
575 * The sockhost field is initialized with the ip# of the host.
576 * The client is not added to the linked list of clients, it is
577 * passed off to the auth handler for dns and ident queries.
579 void add_connection(struct Listener* listener, int fd)
581 struct sockaddr_in addr;
582 struct Client* new_client;
583 time_t next_target = 0;
584 const char* const throttle_message =
585 "ERROR: Your host is trying to (re)connect too fast -- throttled\r\n";
586 /* 12345678901234567890123456789012345679012345678901234567890123456 */
588 assert(0 != listener);
590 * Removed preliminary access check. Full check is performed in
591 * m_server and m_user instead. Also connection time out help to
592 * get rid of unwanted connections.
594 if (!os_get_peername(fd, &addr) || !os_set_nonblocking(fd)) {
595 ++ServerStats->is_ref;
600 * XXX - do we really want to do this? is it needed?
602 os_disable_options(fd);
605 * Add this local client to the IPcheck registry.
606 * If it is a connection to a user port and if the site has been throttled,
609 if (!IPcheck_local_connect(addr.sin_addr, &next_target) && !listener->server) {
610 ++ServerStats->is_ref;
612 * strlen(throttle_message) == 66
614 send(fd, throttle_message, 66, 0);
619 new_client = make_client(NULL,
620 (listener->server) ? STAT_UNKNOWN_SERVER : STAT_UNKNOWN_USER);
622 * Copy ascii address to 'sockhost' just in case. Then we
623 * have something valid to put into error messages...
625 ircd_ntoa_r(new_client->sock_ip, (const char*) &addr.sin_addr);
626 strcpy(new_client->sockhost, new_client->sock_ip);
627 new_client->ip.s_addr = addr.sin_addr.s_addr;
628 new_client->port = ntohs(addr.sin_port);
631 new_client->nexttarget = next_target;
635 if (!listener->server)
636 SetIPChecked(new_client);
637 new_client->listener = listener;
638 ++listener->ref_count;
640 Count_newunknown(UserStats);
642 * if we've made it this far we can put the client on the auth query pile
644 start_auth(new_client);
650 * Read a 'packet' of data from a connection and process it. Read in 8k
651 * chunks to give a better performance rating (for server connections).
652 * Do some tricky stuff for client connections to make sure they don't do
653 * any flooding >:-) -avalon
655 static int read_packet(struct Client *cptr, int socket_ready)
657 unsigned int dolen = 0;
658 unsigned int length = 0;
660 if (socket_ready && !(IsUser(cptr) && DBufLength(&cptr->recvQ) > CLIENT_FLOOD)) {
661 switch (os_recv_nonb(cptr->fd, readbuf, sizeof(readbuf), &length)) {
664 cptr->lasttime = CurrentTime;
665 if (cptr->lasttime > cptr->since)
666 cptr->since = cptr->lasttime;
667 cptr->flags &= ~(FLAGS_PINGSENT | FLAGS_NONL);
674 /* cptr->flags |= FLAGS_DEADSOCKET; */
680 * For server connections, we process as many as we can without
681 * worrying about the time of day or anything :)
683 if (length > 0 && IsServer(cptr)) {
684 return server_dopacket(cptr, readbuf, length);
688 * Before we even think of parsing what we just read, stick
689 * it on the end of the receive queue and do it when its
692 if (length > 0 && 0 == dbuf_put(&cptr->recvQ, readbuf, length)) {
693 return exit_client(cptr, cptr, &me, "dbuf_put fail");
695 #ifndef NOFLOODCONTROL
697 * XXX - cptr will always be a user or unregistered
699 if (IsUser(cptr) && DBufLength(&cptr->recvQ) > CLIENT_FLOOD)
700 return exit_client(cptr, cptr, &me, "Excess Flood");
702 while (DBufLength(&cptr->recvQ) && !NoNewLine(cptr) &&
703 (IsTrusted(cptr) || cptr->since - CurrentTime < 10))
705 while (DBufLength(&cptr->recvQ) && !NoNewLine(cptr))
709 * If it has become registered as a Server
710 * then skip the per-message parsing below.
712 if (IsServer(cptr)) {
713 dolen = dbuf_get(&cptr->recvQ, readbuf, sizeof(readbuf));
714 return (dolen) ? server_dopacket(cptr, readbuf, dolen) : 1;
716 dolen = dbuf_getmsg(&cptr->recvQ, cptr->buffer, BUFSIZE);
718 * Devious looking...whats it do ? well..if a client
719 * sends a *long* message without any CR or LF, then
720 * dbuf_getmsg fails and we pull it out using this
721 * loop which just gets the next 512 bytes and then
722 * deletes the rest of the buffer contents.
726 if (DBufLength(&cptr->recvQ) < 510)
727 cptr->flags |= FLAGS_NONL;
729 DBufClear(&cptr->recvQ);
731 else if (CPTR_KILLED == client_dopacket(cptr, dolen))
738 static int on_write_unblocked(struct Client* cptr)
741 * ...room for writing, empty some queue then...
743 cptr->flags &= ~FLAGS_BLOCKED;
744 if (IsConnecting(cptr)) {
745 if (!completed_connection(cptr))
748 else if (cptr->listing && DBufLength(&cptr->sendQ) < 2048)
749 list_next_channels(cptr, 64);
755 * Select / Poll Read Algorithm for ircd
757 * We need to check the file descriptors for all the different types
758 * of things that use them, so check for reads on everything but connects
759 * and writes on connects and descriptors that are blocked
761 * for each (client in local) {
762 * if (not connecting)
764 * if (connecting or blocked)
769 * for each (client in local) {
770 * if (there are descriptors to check) {
771 * if (write activity)
778 * Note we must always process data read whether or not there has been
779 * read activity or file descriptors set, since data is buffered by the client.
788 #if defined(POLLMSG) && defined(POLLIN) && defined(POLLRDNORM)
789 # define POLLREADFLAGS (POLLMSG|POLLIN|POLLRDNORM)
791 # if defined(POLLIN) && defined(POLLRDNORM)
792 # define POLLREADFLAGS (POLLIN|POLLRDNORM)
795 # define POLLREADFLAGS POLLIN
797 # if defined(POLLRDNORM)
798 # define POLLREADFLAGS POLLRDNORM
804 #if defined(POLLOUT) && defined(POLLWRNORM)
805 #define POLLWRITEFLAGS (POLLOUT|POLLWRNORM)
807 # if defined(POLLOUT)
808 # define POLLWRITEFLAGS POLLOUT
810 # if defined(POLLWRNORM)
811 # define POLLWRITEFLAGS POLLWRNORM
817 #define POLLERRORS (POLLHUP|POLLERR)
819 #define POLLERRORS POLLERR
823 * NOTE: pfd and pfd_count are local variable names in read_message
825 #define PFD_SETR(xfd) \
826 do { CHECK_ADD_PFD(xfd) pfd->events |= POLLREADFLAGS; } while(0)
827 #define PFD_SETW(xfd) \
828 do { CHECK_ADD_PFD(xfd) pfd->events |= POLLWRITEFLAGS; } while(0)
830 #define CHECK_ADD_PFD(xfd) \
831 if (pfd->fd != xfd) { \
832 pfd = &poll_fds[pfd_count++]; \
833 poll_fds[pfd_count].fd = -1; \
839 * Check all connections for new connections and input data that is to be
840 * processed. Also check for connections with data queued and whether we can
843 * Don't ever use ZERO for `delay', unless you mean to poll and then
844 * you have to have sleep/wait somewhere else in the code.--msa
846 int read_message(time_t delay)
848 struct pollfd poll_fds[MAXCONNECTIONS + 1];
850 struct Listener* listener = 0;
851 struct AuthRequest* auth = 0;
852 struct AuthRequest* auth_next = 0;
854 time_t delay2 = delay;
859 struct pollfd* pfd = 0;
860 struct pollfd* res_pfd = 0;
864 unsigned int timeout;
872 if (-1 < ResolverFileDescriptor) {
873 PFD_SETR(ResolverFileDescriptor);
877 * add auth file descriptors
879 for (auth = AuthPollList; auth; auth = auth->next) {
880 assert(-1 < auth->fd);
881 auth->index = pfd_count;
882 if (IsAuthConnect(auth))
888 * add listener file descriptors
890 for (listener = ListenerPollList; listener; listener = listener->next) {
891 assert(-1 < listener->fd);
893 * pfd_count is incremented by PFD_SETR so we need to save the
896 listener->index = pfd_count;
897 PFD_SETR(listener->fd);
900 for (i = HighestFd; -1 < i; --i) {
901 if ((cptr = LocalClientArray[i])) {
903 if (DBufLength(&cptr->recvQ))
905 if (DBufLength(&cptr->recvQ) < 4088 || IsServer(cptr)) {
908 if (DBufLength(&cptr->sendQ) || IsConnecting(cptr) ||
909 (cptr->listing && DBufLength(&cptr->sendQ) < 2048)) {
915 Debug((DEBUG_INFO, "poll: %d %d", delay, delay2));
917 timeout = (IRCD_MIN(delay2, delay)) * 1000;
919 nfds = poll(poll_fds, pfd_count, timeout);
921 CurrentTime = time(0);
927 report_error(POLL_ERROR_MSG, me.name, errno);
930 server_restart("too many poll errors");
932 CurrentTime = time(0);
935 if (res_pfd && (res_pfd->revents & (POLLREADFLAGS | POLLERRORS))) {
942 for (auth = AuthPollList; auth; auth = auth_next) {
943 auth_next = auth->next;
946 * check for any event, we only ask for one at a time
948 if (poll_fds[i].revents) {
949 if (IsAuthConnect(auth))
950 send_auth_query(auth);
952 read_auth_reply(auth);
960 for (listener = ListenerPollList; listener; listener = listener->next) {
962 if (poll_fds[i].revents) {
963 accept_connection(listener);
969 * i contains the next non-auth/non-listener index, since we put the
970 * resolver, auth and listener, file descriptors in poll_fds first,
971 * the very next one should be the start of the clients
973 pfd = &poll_fds[++i];
975 for ( ; (i < pfd_count); ++i, ++pfd) {
976 if (!(cptr = LocalClientArray[pfd->fd]))
978 read_ready = write_ready = 0;
980 if (0 < nfds && pfd->revents) {
983 read_ready = pfd->revents & POLLREADFLAGS;
984 write_ready = pfd->revents & POLLWRITEFLAGS;
986 if (pfd->revents & POLLERRORS) {
987 if (pfd->events & POLLREADFLAGS)
989 if (pfd->events & POLLWRITEFLAGS)
994 if (!on_write_unblocked(cptr) || IsDead(cptr)) {
995 const char* msg = (cptr->error) ? strerror(cptr->error) : LastDeadComment(cptr);
997 msg = "Unknown error";
998 exit_client(cptr, cptr, &me, (char*) msg);
1002 length = 1; /* for fall through case */
1003 if ((!NoNewLine(cptr) || read_ready) && !IsDead(cptr)) {
1004 if (CPTR_KILLED == (length = read_packet(cptr, read_ready)))
1008 /* Bullshit, why would we want to flush sockets while using non-blocking?
1009 * This uses > 4% cpu! --Run */
1011 flush_connections(poll_cptr[i]);
1014 const char* msg = (cptr->error) ? strerror(cptr->error) : LastDeadComment(cptr);
1016 msg = "Unknown error";
1017 exit_client(cptr, cptr, &me, (char*) msg);
1022 cptr->flags |= FLAGS_DEADSOCKET;
1024 * ...hmm, with non-blocking sockets we might get
1025 * here from quite valid reasons, although.. why
1026 * would select report "data available" when there
1027 * wasn't... So, this must be an error anyway... --msa
1028 * actually, EOF occurs when read() returns 0 and
1029 * in due course, select() returns that fd as ready
1030 * for reading even though it ends up being an EOF. -avalon
1032 Debug((DEBUG_ERROR, "READ ERROR: fd = %d %d %d", pfd->fd, errno, length));
1034 if ((IsServer(cptr) || IsHandshake(cptr)) && cptr->error == 0 && length == 0)
1035 exit_client_msg(cptr, cptr, &me, "Server %s closed the connection (%s)",
1036 cptr->name, cptr->serv->last_error_msg);
1038 const char* msg = (cptr->error) ? strerror(cptr->error) : "EOF from client";
1040 msg = "Unknown error";
1041 exit_client_msg(cptr, cptr, &me, "Read error to %s: %s",
1042 get_client_name(cptr, HIDE_IP), msg);
1047 #else /* USE_SELECT */
1050 * Check all connections for new connections and input data that is to be
1051 * processed. Also check for connections with data queued and whether we can
1054 * Don't ever use ZERO for `delay', unless you mean to poll and then
1055 * you have to have sleep/wait somewhere else in the code.--msa
1057 int read_message(time_t delay)
1059 struct Client* cptr;
1060 struct Listener* listener;
1062 struct timeval wait;
1063 time_t delay2 = delay;
1064 unsigned int usec = 0;
1068 struct AuthRequest* auth = 0;
1069 struct AuthRequest* auth_next = 0;
1077 FD_ZERO(&write_set);
1079 if (-1 < ResolverFileDescriptor)
1080 FD_SET(ResolverFileDescriptor, &read_set);
1082 * set auth file descriptors
1084 for (auth = AuthPollList; auth; auth = auth->next) {
1085 assert(-1 < auth->fd);
1086 if (IsAuthConnect(auth))
1087 FD_SET(auth->fd, &write_set);
1088 else /* if (IsAuthPending(auth)) */
1089 FD_SET(auth->fd, &read_set);
1092 * set listener file descriptors
1094 for (listener = ListenerPollList; listener; listener = listener->next) {
1095 assert(-1 < listener->fd);
1096 FD_SET(listener->fd, &read_set);
1099 for (i = HighestFd; i > -1; --i) {
1100 if ((cptr = LocalClientArray[i])) {
1101 if (DBufLength(&cptr->recvQ))
1103 if (DBufLength(&cptr->recvQ) < 4088 || IsServer(cptr))
1104 FD_SET(i, &read_set);
1105 if (DBufLength(&cptr->sendQ) || IsConnecting(cptr) ||
1106 (cptr->listing && DBufLength(&cptr->sendQ) < 2048))
1107 FD_SET(i, &write_set);
1111 wait.tv_sec = IRCD_MIN(delay2, delay);
1112 wait.tv_usec = usec;
1114 Debug((DEBUG_INFO, "select: %d %d", delay, delay2));
1116 nfds = select(FD_SETSIZE, &read_set, &write_set, 0, &wait);
1118 CurrentTime = time(0);
1125 report_error(SELECT_ERROR_MSG, me.name, errno);
1127 server_restart("too many select errors");
1129 CurrentTime = time(0);
1132 if (-1 < ResolverFileDescriptor &&
1133 FD_ISSET(ResolverFileDescriptor, &read_set)) {
1138 * Check fd sets for the auth fd's (if set and valid!) first
1139 * because these can not be processed using the normal loops below.
1142 for (auth = AuthPollList; auth; auth = auth_next) {
1143 auth_next = auth->next;
1144 assert(-1 < auth->fd);
1145 if (IsAuthConnect(auth) && FD_ISSET(auth->fd, &write_set)) {
1146 send_auth_query(auth);
1150 else if (FD_ISSET(auth->fd, &read_set)) {
1151 read_auth_reply(auth);
1157 * next accept connections from active listeners
1159 for (listener = ListenerPollList; listener; listener = listener->next) {
1160 assert(-1 < listener->fd);
1161 if (0 < nfds && FD_ISSET(listener->fd, &read_set))
1162 accept_connection(listener);
1165 for (i = HighestFd; -1 < i; --i) {
1166 if (!(cptr = LocalClientArray[i]))
1170 if (FD_ISSET(i, &write_set)) {
1172 if (!on_write_unblocked(cptr) || IsDead(cptr)) {
1173 const char* msg = (cptr->error) ? strerror(cptr->error) : LastDeadComment(cptr);
1175 msg = "Unknown error";
1176 if (FD_ISSET(i, &read_set))
1178 exit_client(cptr, cptr, &me, msg);
1182 if ((read_ready = FD_ISSET(i, &read_set)))
1185 length = 1; /* for fall through case */
1186 if ((!NoNewLine(cptr) || read_ready) && !IsDead(cptr)) {
1187 if (CPTR_KILLED == (length = read_packet(cptr, read_ready)))
1191 /* Bullshit, why would we want to flush sockets while using non-blocking?
1192 * This uses > 4% cpu! --Run */
1194 flush_connections(LocalClientArray[i]);
1197 const char* msg = (cptr->error) ? strerror(cptr->error) : LastDeadComment(cptr);
1199 msg = "Unknown error";
1200 exit_client(cptr, cptr, &me, msg);
1207 * ...hmm, with non-blocking sockets we might get
1208 * here from quite valid reasons, although.. why
1209 * would select report "data available" when there
1210 * wasn't... So, this must be an error anyway... --msa
1211 * actually, EOF occurs when read() returns 0 and
1212 * in due course, select() returns that fd as ready
1213 * for reading even though it ends up being an EOF. -avalon
1215 Debug((DEBUG_ERROR, "READ ERROR: fd = %d %d %d", i, cptr->error, length));
1217 if ((IsServer(cptr) || IsHandshake(cptr)) && cptr->error == 0 && length == 0)
1218 exit_client_msg(cptr, cptr, &me, "Server %s closed the connection (%s)",
1219 cptr->name, cptr->serv->last_error_msg);
1221 const char* msg = (cptr->error) ? strerror(cptr->error) : "EOF from client";
1223 msg = "Unknown error";
1224 exit_client_msg(cptr, cptr, &me, "Read error to %s: %s",
1225 get_client_name(cptr, HIDE_IP), msg);
1231 #endif /* USE_SELECT */
1234 * connect_server - start or complete a connection to another server
1235 * returns true (1) if successful, false (0) otherwise
1237 * aconf must point to a valid C:line
1238 * m_connect calls this with a valid by client and a null reply
1239 * try_connections calls this with a null by client, and a null reply
1240 * connect_dns_callback call this with a null by client, and a valid reply
1242 * XXX - if this comes from an m_connect message and a dns query needs to
1243 * be done, we loose the information about who started the connection and
1244 * it's considered an auto connect.
1246 int connect_server(struct ConfItem* aconf, struct Client* by,
1247 struct DNSReply* reply)
1249 struct Client* cptr = 0;
1252 if (aconf->dns_pending) {
1253 sendto_ops("Server %s connect DNS pending");
1256 Debug((DEBUG_NOTICE, "Connect to %s[@%s]", aconf->name,
1257 ircd_ntoa((const char*) &aconf->ipnum)));
1259 if ((cptr = FindClient(aconf->name))) {
1260 if (IsServer(cptr) || IsMe(cptr)) {
1261 sendto_ops("Server %s already present from %s",
1262 aconf->name, cptr->from->name);
1263 if (by && IsUser(by) && !MyUser(by)) {
1264 sendto_one(by, "%s NOTICE %s%s :Server %s already present from %s",
1265 NumServ(&me), NumNick(by), aconf->name, cptr->from->name);
1269 else if (IsHandshake(cptr) || IsConnecting(cptr)) {
1270 if (by && IsUser(by)) {
1272 sendto_one(by, ":%s NOTICE %s :Connection to %s already in progress",
1273 me.name, by->name, cptr->name);
1275 sendto_one(by, "%s NOTICE %s%s :Connection to %s already in progress",
1276 NumServ(&me), NumNick(by), cptr->name);
1282 * If we dont know the IP# for this host and itis a hostname and
1283 * not a ip# string, then try and find the appropriate host record.
1285 if (INADDR_NONE == aconf->ipnum.s_addr) {
1286 char buf[HOSTLEN + 1];
1288 if (INADDR_NONE == (aconf->ipnum.s_addr = inet_addr(aconf->host))) {
1289 struct DNSQuery query;
1292 query.callback = connect_dns_callback;
1293 host_from_uh(buf, aconf->host, HOSTLEN);
1294 buf[HOSTLEN] = '\0';
1296 reply = gethost_byname(buf, &query);
1299 aconf->dns_pending = 1;
1302 memcpy(&aconf->ipnum, reply->hp->h_addr, sizeof(struct in_addr));
1305 cptr = make_client(NULL, STAT_UNKNOWN_SERVER);
1308 cptr->dns_reply = reply;
1311 * Copy these in so we have something for error detection.
1313 ircd_strncpy(cptr->name, aconf->name, HOSTLEN);
1314 ircd_strncpy(cptr->sockhost, aconf->host, HOSTLEN);
1317 * Attach config entries to client here rather than in
1318 * completed_connection. This to avoid null pointer references
1320 attach_confs_byhost(cptr, aconf->host, CONF_SERVER);
1322 if (!find_conf_byhost(cptr->confs, aconf->host, CONF_SERVER)) {
1323 sendto_ops("Host %s is not enabled for connecting: no C-line", aconf->name);
1324 if (by && IsUser(by) && !MyUser(by)) {
1325 sendto_one(by, "%s NOTICE %s%s :Connect to host %s failed: no C-line",
1326 NumServ(&me), NumNick(by), aconf->name);
1328 det_confs_butmask(cptr, 0);
1333 * attempt to connect to the server in the conf line
1335 if (!connect_inet(aconf, cptr)) {
1336 if (by && IsUser(by) && !MyUser(by)) {
1337 sendto_one(by, "%s NOTICE %s%s :Couldn't connect to %s",
1338 NumServ(&me), NumNick(by), cptr->name);
1340 det_confs_butmask(cptr, 0);
1345 * NOTE: if we're here we have a valid C:Line and the client should
1346 * have started the connection and stored the remote address/port and
1347 * ip address name in itself
1349 * The socket has been connected or connect is in progress.
1352 if (by && IsUser(by)) {
1353 sprintf_irc(cptr->serv->by, "%s%s", NumNick(by));
1354 assert(0 == cptr->serv->user);
1355 cptr->serv->user = by->user;
1359 *cptr->serv->by = '\0';
1360 /* strcpy(cptr->serv->by, "Auto"); */
1362 cptr->serv->up = &me;
1363 SetConnecting(cptr);
1365 if (cptr->fd > HighestFd)
1366 HighestFd = cptr->fd;
1367 LocalClientArray[cptr->fd] = cptr;
1369 Count_newunknown(UserStats);
1370 add_client_to_list(cptr);
1372 nextping = CurrentTime;
1378 * Setup local socket structure to use for binding to.
1380 void init_virtual_host(const struct ConfItem* conf)
1384 memset(&virtualHost, 0, sizeof(virtualHost));
1385 virtualHost.sin_family = AF_INET;
1386 virtualHost.sin_addr.s_addr = INADDR_ANY;
1388 if (EmptyString(conf->passwd) || 0 == strcmp(conf->passwd, "*"))
1390 virtualHost.sin_addr.s_addr = inet_addr(conf->passwd);
1392 if (INADDR_NONE == virtualHost.sin_addr.s_addr)
1393 virtualHost.sin_addr.s_addr = INADDR_ANY;
1397 * Find the real hostname for the host running the server (or one which
1398 * matches the server's name) and its primary IP#. Hostname is stored
1399 * in the client structure passed as a pointer.
1401 int init_server_identity()
1403 struct ConfItem* conf = find_me();
1405 if (!conf || EmptyString(conf->host))
1408 ircd_strncpy(me.name, conf->host, HOSTLEN);
1410 init_virtual_host(conf);