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"
53 #include <arpa/inet.h>
54 #include <arpa/nameser.h>
63 #include <sys/ioctl.h>
64 #include <sys/socket.h>
66 #include <sys/utsname.h>
74 #define INADDR_NONE 0xffffffff
77 struct Client* LocalClientArray[MAXCONNECTIONS];
79 struct sockaddr_in VirtualHost;
80 static char readbuf[SERVER_TCP_WINDOW];
83 * report_error text constants
85 const char* const ACCEPT_ERROR_MSG = "error accepting connection for %s: %s";
86 const char* const BIND_ERROR_MSG = "bind error for %s: %s";
87 const char* const CONNECT_ERROR_MSG = "connect to host %s failed: %s";
88 const char* const CONNLIMIT_ERROR_MSG = "connect limit exceeded for %s: %s";
89 const char* const LISTEN_ERROR_MSG = "listen error for %s: %s";
90 const char* const NONB_ERROR_MSG = "error setting non-blocking for %s: %s";
91 const char* const PEERNAME_ERROR_MSG = "getpeername failed for %s: %s";
92 const char* const POLL_ERROR_MSG = "poll error for %s: %s";
93 const char* const REUSEADDR_ERROR_MSG = "error setting SO_REUSEADDR for %s: %s";
94 const char* const SELECT_ERROR_MSG = "select error for %s: %s";
95 const char* const SETBUFS_ERROR_MSG = "error setting buffer size for %s: %s";
96 const char* const SOCKET_ERROR_MSG = "error creating socket for %s: %s";
103 #ifndef NOFLOODCONTROL
104 #define NOFLOODCONTROL
108 #if !defined(USE_POLL)
109 #if FD_SETSIZE < (MAXCONNECTIONS + 4)
113 * All operating systems work when MAXCONNECTIONS <= 252.
114 * Most operating systems work when MAXCONNECTIONS <= 1020 and FD_SETSIZE is
115 * updated correctly in the system headers (on BSD systems our sys.h has
116 * defined FD_SETSIZE to MAXCONNECTIONS+4 before including the system's headers
117 * but sys/types.h might have abruptly redefined it so the check is still
118 * done), you might already need to recompile your kernel.
119 * For larger FD_SETSIZE your milage may vary (kernel patches may be needed).
120 * The check is _NOT_ done if we will not use FD_SETS at all (USE_POLL)
122 #error "FD_SETSIZE is too small or MAXCONNECTIONS too large."
128 * Cannot use perror() within daemon. stderr is closed in
129 * ircd and cannot be used. And, worse yet, it might have
130 * been reassigned to a normal connection...
136 * This a replacement for perror(). Record error to log and
137 * also send a copy to all *LOCAL* opers online.
139 * text is a *format* string for outputting error. It must
140 * contain only two '%s', the first will be replaced
141 * by the sockhost from the cptr, and the latter will
142 * be taken from sys_errlist[errno].
144 * cptr if not NULL, is the *LOCAL* client associated with
147 void report_error(const char* text, const char* who, int err)
149 static time_t last_notice = 0;
150 int errtmp = errno; /* debug may change 'errno' */
151 const char* errmsg = (err) ? strerror(err) : "";
153 errmsg = "Unknown error";
155 if (EmptyString(who))
158 if (last_notice + 20 < CurrentTime) {
160 * pace error messages so opers don't get flooded by transients
162 sendto_ops(text, who, errmsg);
163 last_notice = CurrentTime;
165 ircd_log(L_ERROR, text, who, errmsg);
171 * connect_dns_callback - called when resolver query finishes
172 * if the query resulted in a successful search, reply will contain
173 * a non-null pointer, otherwise reply will be null.
174 * if successful start the connection, otherwise notify opers
176 static void connect_dns_callback(void* vptr, struct DNSReply* reply)
178 struct ConfItem* aconf = (struct ConfItem*) vptr;
179 aconf->dns_pending = 0;
181 memcpy(&aconf->ipnum, reply->hp->h_addr, sizeof(struct in_addr));
182 connect_server(aconf, 0, reply);
185 sendto_ops("Connect to %s failed: host lookup", aconf->name);
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 cptr->fd = socket(AF_INET, SOCK_STREAM, 0);
236 if (-1 == cptr->fd) {
238 report_error(SOCKET_ERROR_MSG, cptr->name, errno);
241 if (cptr->fd >= MAXCLIENTS) {
242 report_error(CONNLIMIT_ERROR_MSG, cptr->name, 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 (bind(cptr->fd, (struct sockaddr*) &VirtualHost, sizeof(VirtualHost))) {
264 report_error(BIND_ERROR_MSG, cptr->name, errno);
269 memset(&sin, 0, sizeof(sin));
270 sin.sin_family = AF_INET;
271 sin.sin_addr.s_addr = aconf->ipnum.s_addr;
272 sin.sin_port = htons(aconf->port);
274 * save connection info in client
276 cptr->ip.s_addr = aconf->ipnum.s_addr;
277 cptr->port = aconf->port;
278 ircd_ntoa_r(cptr->sock_ip, (const char*) &cptr->ip);
280 * we want a big buffer for server connections
282 if (!os_set_sockbufs(cptr->fd, SERVER_TCP_WINDOW)) {
284 report_error(SETBUFS_ERROR_MSG, cptr->name, errno);
288 * ALWAYS set sockets non-blocking
290 if (!os_set_nonblocking(cptr->fd)) {
292 report_error(NONB_ERROR_MSG, cptr->name, errno);
295 if (!os_connect_nonb(cptr->fd, &sin)) {
297 report_error(CONNECT_ERROR_MSG, cptr->name, errno);
305 * Attempt to send a sequence of bytes to the connection.
308 * < 0 Some fatal error occurred, (but not EWOULDBLOCK).
309 * This return is a request to close the socket and
312 * >= 0 No real error occurred, returns the number of
313 * bytes actually transferred. EWOULDBLOCK and other
314 * possibly similar conditions should be mapped to
315 * zero return. Upper level routine will have to
316 * decide what to do with those unwritten bytes...
318 * *NOTE* alarm calls have been preserved, so this should
319 * work equally well whether blocking or non-blocking
322 * We don't use blocking anymore, that is impossible with the
323 * net.loads today anyway. Commented out the alarms to save cpu.
326 unsigned int deliver_it(struct Client *cptr, const char *str, unsigned int len)
328 unsigned int bytes_written = 0;
331 switch (os_send_nonb(cptr->fd, str, len, &bytes_written)) {
333 cptr->flags &= ~FLAGS_BLOCKED;
335 cptr->sendB += bytes_written;
336 me.sendB += bytes_written;
337 if (cptr->sendB > 1023) {
338 cptr->sendK += (cptr->sendB >> 10);
339 cptr->sendB &= 0x03ff; /* 2^10 = 1024, 3ff = 1023 */
341 if (me.sendB > 1023) {
342 me.sendK += (me.sendB >> 10);
345 if (bytes_written < len)
346 cptr->flags |= FLAGS_BLOCKED;
349 cptr->flags |= FLAGS_BLOCKED;
353 cptr->flags |= FLAGS_DEADSOCKET;
356 return bytes_written;
360 void release_dns_reply(struct Client* cptr)
363 assert(MyConnect(cptr));
365 if (cptr->dns_reply) {
366 assert(0 < cptr->dns_reply->ref_count);
367 --cptr->dns_reply->ref_count;
373 * completed_connection
375 * Complete non-blocking connect()-sequence. Check access and
376 * terminate connection, if trouble detected.
378 * Return TRUE, if successfully completed
379 * FALSE, if failed and ClientExit
381 static int completed_connection(struct Client* cptr)
383 struct ConfItem *aconf;
385 struct Client *acptr;
391 * get the socket status from the fd first to check if
392 * connection actually succeeded
394 if ((cptr->error = os_get_sockerr(cptr->fd))) {
395 const char* msg = strerror(cptr->error);
397 msg = "Unknown error";
398 sendto_ops("Connection failed to %s: %s", cptr->name, msg);
401 if (!(aconf = find_conf_byname(cptr->confs, cptr->name, CONF_SERVER))) {
402 sendto_ops("Lost Server Line for %s", cptr->name);
405 if (!EmptyString(aconf->passwd))
406 sendto_one(cptr, "PASS :%s", aconf->passwd);
409 /* dead code, already done in connect_server */
413 * Create a unique timestamp
416 for (i = HighestFd; i > -1; --i) {
417 if ((acptr = LocalClientArray[i]) &&
418 (IsServer(acptr) || IsHandshake(acptr))) {
419 if (acptr->serv->timestamp >= newts)
420 newts = acptr->serv->timestamp + 1;
423 assert(0 != cptr->serv);
425 cptr->serv->timestamp = newts;
428 * Make us timeout after twice the timeout for DNS look ups
430 cptr->lasttime = CurrentTime;
431 cptr->flags |= FLAGS_PINGSENT;
432 sendto_one(cptr, "SERVER %s 1 " TIME_T_FMT " " TIME_T_FMT " J%s %s%s :%s",
433 me.name, me.serv->timestamp, newts, MAJOR_PROTOCOL,
434 NumServCap(&me), me.info);
436 return (IsDead(cptr)) ? 0 : 1;
442 * Close the physical connection. This function must make
443 * MyConnect(cptr) == FALSE, and set cptr->from == NULL.
445 void close_connection(struct Client *cptr)
447 struct ConfItem* aconf;
449 if (IsServer(cptr)) {
450 ServerStats->is_sv++;
451 ServerStats->is_sbs += cptr->sendB;
452 ServerStats->is_sbr += cptr->receiveB;
453 ServerStats->is_sks += cptr->sendK;
454 ServerStats->is_skr += cptr->receiveK;
455 ServerStats->is_sti += CurrentTime - cptr->firsttime;
456 if (ServerStats->is_sbs > 1023) {
457 ServerStats->is_sks += (ServerStats->is_sbs >> 10);
458 ServerStats->is_sbs &= 0x3ff;
460 if (ServerStats->is_sbr > 1023) {
461 ServerStats->is_skr += (ServerStats->is_sbr >> 10);
462 ServerStats->is_sbr &= 0x3ff;
465 * If the connection has been up for a long amount of time, schedule
466 * a 'quick' reconnect, else reset the next-connect cycle.
468 if ((aconf = find_conf_exact(cptr->name, 0, cptr->sockhost, CONF_SERVER))) {
470 * Reschedule a faster reconnect, if this was a automaticly
471 * connected configuration entry. (Note that if we have had
472 * a rehash in between, the status has been changed to
473 * CONF_ILLEGAL). But only do this if it was a "good" link.
475 aconf->hold = CurrentTime;
476 aconf->hold += (aconf->hold - cptr->since > HANGONGOODLINK) ?
477 HANGONRETRYDELAY : ConfConFreq(aconf);
478 if (nextconnect > aconf->hold)
479 nextconnect = aconf->hold;
482 else if (IsUser(cptr)) {
483 ServerStats->is_cl++;
484 ServerStats->is_cbs += cptr->sendB;
485 ServerStats->is_cbr += cptr->receiveB;
486 ServerStats->is_cks += cptr->sendK;
487 ServerStats->is_ckr += cptr->receiveK;
488 ServerStats->is_cti += CurrentTime - cptr->firsttime;
489 if (ServerStats->is_cbs > 1023) {
490 ServerStats->is_cks += (ServerStats->is_cbs >> 10);
491 ServerStats->is_cbs &= 0x3ff;
493 if (ServerStats->is_cbr > 1023) {
494 ServerStats->is_ckr += (ServerStats->is_cbr >> 10);
495 ServerStats->is_cbr &= 0x3ff;
499 ServerStats->is_ni++;
502 flush_connections(cptr);
503 LocalClientArray[cptr->fd] = 0;
507 cptr->flags |= FLAGS_DEADSOCKET;
509 DBufClear(&cptr->sendQ);
510 DBufClear(&cptr->recvQ);
511 memset(cptr->passwd, 0, sizeof(cptr->passwd));
512 set_snomask(cptr, 0, SNO_SET);
514 det_confs_butmask(cptr, 0);
516 if (cptr->listener) {
517 release_listener(cptr->listener);
521 for ( ; HighestFd > 0; --HighestFd) {
522 if (LocalClientArray[HighestFd])
527 int net_close_unregistered_connections(struct Client* source)
534 for (i = HighestFd; i > 0; --i) {
535 if ((cptr = LocalClientArray[i]) && !IsRegistered(cptr)) {
536 sendto_one(source, rpl_str(RPL_CLOSING), me.name, source->name,
537 get_client_name(source, HIDE_IP), cptr->status);
538 exit_client(source, cptr, &me, "Oper Closing");
546 * Creates a client which has just connected to us on the given fd.
547 * The sockhost field is initialized with the ip# of the host.
548 * The client is not added to the linked list of clients, it is
549 * passed off to the auth handler for dns and ident queries.
551 void add_connection(struct Listener* listener, int fd)
553 struct sockaddr_in addr;
554 struct Client* new_client;
555 time_t next_target = 0;
556 const char* const throttle_message =
557 "ERROR: Your host is trying to (re)connect too fast -- throttled\r\n";
558 /* 12345678901234567890123456789012345679012345678901234567890123456 */
560 assert(0 != listener);
562 * Removed preliminary access check. Full check is performed in
563 * m_server and m_user instead. Also connection time out help to
564 * get rid of unwanted connections.
566 if (!os_get_peername(fd, &addr) || !os_set_nonblocking(fd)) {
567 ++ServerStats->is_ref;
572 * Add this local client to the IPcheck registry.
573 * If it is a connection to a user port and if the site has been throttled,
576 if (!IPcheck_local_connect(addr.sin_addr, &next_target) && !listener->server) {
577 ++ServerStats->is_ref;
579 * strlen(throttle_message) == 66
581 send(fd, throttle_message, 66, 0);
586 new_client = make_client(NULL,
587 (listener->server) ? STAT_UNKNOWN_SERVER : STAT_UNKNOWN_USER);
589 * Copy ascii address to 'sockhost' just in case. Then we
590 * have something valid to put into error messages...
592 ircd_ntoa_r(new_client->sock_ip, (const char*) &addr.sin_addr);
593 strcpy(new_client->sockhost, new_client->sock_ip);
594 new_client->ip.s_addr = addr.sin_addr.s_addr;
595 new_client->port = ntohs(addr.sin_port);
598 new_client->nexttarget = next_target;
602 if (!listener->server)
603 SetIPChecked(new_client);
604 new_client->listener = listener;
605 ++listener->ref_count;
607 Count_newunknown(UserStats);
609 * if we've made it this far we can put the client on the auth query pile
611 start_auth(new_client);
617 * Read a 'packet' of data from a connection and process it. Read in 8k
618 * chunks to give a better performance rating (for server connections).
619 * Do some tricky stuff for client connections to make sure they don't do
620 * any flooding >:-) -avalon
622 static int read_packet(struct Client *cptr, int socket_ready)
624 unsigned int dolen = 0;
625 unsigned int length = 0;
627 if (socket_ready && !(IsUser(cptr) && DBufLength(&cptr->recvQ) > CLIENT_FLOOD)) {
628 switch (os_recv_nonb(cptr->fd, readbuf, sizeof(readbuf), &length)) {
631 cptr->lasttime = CurrentTime;
632 if (cptr->lasttime > cptr->since)
633 cptr->since = cptr->lasttime;
634 cptr->flags &= ~(FLAGS_PINGSENT | FLAGS_NONL);
641 /* cptr->flags |= FLAGS_DEADSOCKET; */
647 * For server connections, we process as many as we can without
648 * worrying about the time of day or anything :)
650 if (length > 0 && IsServer(cptr)) {
651 return server_dopacket(cptr, readbuf, length);
655 * Before we even think of parsing what we just read, stick
656 * it on the end of the receive queue and do it when its
659 if (length > 0 && 0 == dbuf_put(&cptr->recvQ, readbuf, length)) {
660 return exit_client(cptr, cptr, &me, "dbuf_put fail");
662 #ifndef NOFLOODCONTROL
664 * XXX - cptr will always be a user or unregistered
666 if (IsUser(cptr) && DBufLength(&cptr->recvQ) > CLIENT_FLOOD)
667 return exit_client(cptr, cptr, &me, "Excess Flood");
669 while (DBufLength(&cptr->recvQ) && !NoNewLine(cptr) &&
670 (IsTrusted(cptr) || cptr->since - CurrentTime < 10))
672 while (DBufLength(&cptr->recvQ) && !NoNewLine(cptr))
676 * If it has become registered as a Server
677 * then skip the per-message parsing below.
679 if (IsServer(cptr)) {
680 dolen = dbuf_get(&cptr->recvQ, readbuf, sizeof(readbuf));
681 return (dolen) ? server_dopacket(cptr, readbuf, dolen) : 1;
683 dolen = dbuf_getmsg(&cptr->recvQ, cptr->buffer, BUFSIZE);
685 * Devious looking...whats it do ? well..if a client
686 * sends a *long* message without any CR or LF, then
687 * dbuf_getmsg fails and we pull it out using this
688 * loop which just gets the next 512 bytes and then
689 * deletes the rest of the buffer contents.
693 if (DBufLength(&cptr->recvQ) < 510)
694 cptr->flags |= FLAGS_NONL;
696 DBufClear(&cptr->recvQ);
698 else if (CPTR_KILLED == client_dopacket(cptr, dolen))
705 static int on_write_unblocked(struct Client* cptr)
708 * ...room for writing, empty some queue then...
710 cptr->flags &= ~FLAGS_BLOCKED;
711 if (IsConnecting(cptr)) {
712 if (!completed_connection(cptr))
715 else if (cptr->listing && DBufLength(&cptr->sendQ) < 2048)
716 list_next_channels(cptr, 64);
722 * Select / Poll Read Algorithm for ircd
724 * We need to check the file descriptors for all the different types
725 * of things that use them, so check for reads on everything but connects
726 * and writes on connects and descriptors that are blocked
728 * for each (client in local) {
729 * if (not connecting)
731 * if (connecting or blocked)
736 * for each (client in local) {
737 * if (there are descriptors to check) {
738 * if (write activity)
745 * Note we must always process data read whether or not there has been
746 * read activity or file descriptors set, since data is buffered by the client.
755 #if defined(POLLMSG) && defined(POLLIN) && defined(POLLRDNORM)
756 # define POLLREADFLAGS (POLLMSG|POLLIN|POLLRDNORM)
758 # if defined(POLLIN) && defined(POLLRDNORM)
759 # define POLLREADFLAGS (POLLIN|POLLRDNORM)
762 # define POLLREADFLAGS POLLIN
764 # if defined(POLLRDNORM)
765 # define POLLREADFLAGS POLLRDNORM
771 #if defined(POLLOUT) && defined(POLLWRNORM)
772 #define POLLWRITEFLAGS (POLLOUT|POLLWRNORM)
774 # if defined(POLLOUT)
775 # define POLLWRITEFLAGS POLLOUT
777 # if defined(POLLWRNORM)
778 # define POLLWRITEFLAGS POLLWRNORM
784 #define POLLERRORS (POLLHUP|POLLERR)
786 #define POLLERRORS POLLERR
790 * NOTE: pfd and pfd_count are local variable names in read_message
792 #define PFD_SETR(xfd) \
793 do { CHECK_ADD_PFD(xfd) pfd->events |= POLLREADFLAGS; } while(0)
794 #define PFD_SETW(xfd) \
795 do { CHECK_ADD_PFD(xfd) pfd->events |= POLLWRITEFLAGS; } while(0)
797 #define CHECK_ADD_PFD(xfd) \
798 if (pfd->fd != xfd) { \
799 pfd = &poll_fds[pfd_count++]; \
800 poll_fds[pfd_count].fd = -1; \
806 * Check all connections for new connections and input data that is to be
807 * processed. Also check for connections with data queued and whether we can
810 * Don't ever use ZERO for `delay', unless you mean to poll and then
811 * you have to have sleep/wait somewhere else in the code.--msa
813 int read_message(time_t delay)
815 struct pollfd poll_fds[MAXCONNECTIONS + 1];
817 struct Listener* listener = 0;
818 struct AuthRequest* auth = 0;
819 struct AuthRequest* auth_next = 0;
820 struct UPing* uping = 0;
821 struct UPing* uping_next = 0;
822 time_t delay2 = delay;
829 struct pollfd* res_pfd;
830 struct pollfd* uping_pfd;
834 unsigned int timeout;
843 if (-1 < ResolverFileDescriptor) {
844 PFD_SETR(ResolverFileDescriptor);
847 if (-1 < UPingFileDescriptor) {
848 PFD_SETR(UPingFileDescriptor);
852 * add uping descriptors
854 for (uping = uping_begin(); uping; uping = uping_next) {
855 uping_next = uping->next;
858 if (uping->lastsent && CurrentTime > uping->timeout) {
862 uping->index = pfd_count;
867 * add auth file descriptors
869 for (auth = AuthPollList; auth; auth = auth->next) {
870 assert(-1 < auth->fd);
871 auth->index = pfd_count;
872 if (IsAuthConnect(auth))
878 * add listener file descriptors
880 for (listener = ListenerPollList; listener; listener = listener->next) {
881 assert(-1 < listener->fd);
883 * pfd_count is incremented by PFD_SETR so we need to save the
886 listener->index = pfd_count;
887 PFD_SETR(listener->fd);
890 for (i = HighestFd; -1 < i; --i) {
891 if ((cptr = LocalClientArray[i])) {
893 if (DBufLength(&cptr->recvQ))
895 if (DBufLength(&cptr->recvQ) < 4088 || IsServer(cptr)) {
898 if (DBufLength(&cptr->sendQ) || IsConnecting(cptr) ||
899 (cptr->listing && DBufLength(&cptr->sendQ) < 2048)) {
905 Debug((DEBUG_INFO, "poll: %d %d", delay, delay2));
907 timeout = (IRCD_MIN(delay2, delay)) * 1000;
909 nfds = poll(poll_fds, pfd_count, timeout);
911 CurrentTime = time(0);
917 report_error(POLL_ERROR_MSG, me.name, errno);
920 server_restart("too many poll errors");
922 CurrentTime = time(0);
925 if (uping_pfd && (uping_pfd->revents & (POLLREADFLAGS | POLLERRORS))) {
930 * check uping replies
932 for (uping = uping_begin(); uping; uping = uping_next) {
933 uping_next = uping->next;
935 assert(-1 < uping->index);
936 if (poll_fds[uping->index].revents) {
941 else if (CurrentTime > uping->lastsent) {
942 uping->lastsent = CurrentTime;
948 if (res_pfd && (res_pfd->revents & (POLLREADFLAGS | POLLERRORS))) {
955 for (auth = AuthPollList; auth; auth = auth_next) {
956 auth_next = auth->next;
959 * check for any event, we only ask for one at a time
961 if (poll_fds[i].revents) {
962 if (IsAuthConnect(auth))
963 send_auth_query(auth);
965 read_auth_reply(auth);
973 for (listener = ListenerPollList; listener; listener = listener->next) {
975 if (poll_fds[i].revents) {
976 accept_connection(listener);
982 * i contains the next non-auth/non-listener index, since we put the
983 * resolver, auth and listener, file descriptors in poll_fds first,
984 * the very next one should be the start of the clients
986 pfd = &poll_fds[++i];
988 for ( ; (i < pfd_count); ++i, ++pfd) {
989 if (!(cptr = LocalClientArray[pfd->fd]))
991 read_ready = write_ready = 0;
993 if (0 < nfds && pfd->revents) {
996 read_ready = pfd->revents & POLLREADFLAGS;
997 write_ready = pfd->revents & POLLWRITEFLAGS;
999 if (pfd->revents & POLLERRORS) {
1000 if (pfd->events & POLLREADFLAGS)
1002 if (pfd->events & POLLWRITEFLAGS)
1007 if (!on_write_unblocked(cptr) || IsDead(cptr)) {
1008 const char* msg = (cptr->error) ? strerror(cptr->error) : cptr->info;
1010 msg = "Unknown error";
1011 exit_client(cptr, cptr, &me, msg);
1015 length = 1; /* for fall through case */
1016 if ((!NoNewLine(cptr) || read_ready) && !IsDead(cptr)) {
1017 if (CPTR_KILLED == (length = read_packet(cptr, read_ready)))
1021 /* Bullshit, why would we want to flush sockets while using non-blocking?
1022 * This uses > 4% cpu! --Run */
1024 flush_connections(poll_cptr[i]);
1027 const char* msg = (cptr->error) ? strerror(cptr->error) : cptr->info;
1029 msg = "Unknown error";
1030 exit_client(cptr, cptr, &me, (char*) msg);
1035 cptr->flags |= FLAGS_DEADSOCKET;
1037 * ...hmm, with non-blocking sockets we might get
1038 * here from quite valid reasons, although.. why
1039 * would select report "data available" when there
1040 * wasn't... So, this must be an error anyway... --msa
1041 * actually, EOF occurs when read() returns 0 and
1042 * in due course, select() returns that fd as ready
1043 * for reading even though it ends up being an EOF. -avalon
1045 Debug((DEBUG_ERROR, "READ ERROR: fd = %d %d %d", pfd->fd, errno, length));
1047 if ((IsServer(cptr) || IsHandshake(cptr)) && cptr->error == 0 && length == 0)
1048 exit_client_msg(cptr, cptr, &me, "Server %s closed the connection (%s)",
1049 cptr->name, cptr->serv->last_error_msg);
1051 const char* msg = (cptr->error) ? strerror(cptr->error) : "EOF from client";
1053 msg = "Unknown error";
1054 exit_client_msg(cptr, cptr, &me, "Read error: %s",
1060 #else /* USE_SELECT */
1063 * Check all connections for new connections and input data that is to be
1064 * processed. Also check for connections with data queued and whether we can
1067 * Don't ever use ZERO for `delay', unless you mean to poll and then
1068 * you have to have sleep/wait somewhere else in the code.--msa
1070 int read_message(time_t delay)
1072 struct Client* cptr;
1073 struct Listener* listener;
1074 struct AuthRequest* auth = 0;
1075 struct AuthRequest* auth_next = 0;
1076 struct UPing* uping;
1077 struct UPing* uping_next;
1079 struct timeval wait;
1080 time_t delay2 = delay;
1081 unsigned int usec = 0;
1092 FD_ZERO(&write_set);
1094 if (-1 < ResolverFileDescriptor)
1095 FD_SET(ResolverFileDescriptor, &read_set);
1096 if (-1 < UPingFileDescriptor)
1097 FD_SET(UPingFileDescriptor, &read_set);
1099 * set up uping file descriptors
1101 for (uping = uping_begin(); uping; uping = uping_next) {
1102 uping_next = uping->next;
1103 if (uping->active) {
1105 if (uping->lastsent && CurrentTime > uping->timeout) {
1109 assert(-1 < uping->fd);
1110 FD_SET(uping->fd, &read_set);
1114 * set auth file descriptors
1116 for (auth = AuthPollList; auth; auth = auth->next) {
1117 assert(-1 < auth->fd);
1118 if (IsAuthConnect(auth))
1119 FD_SET(auth->fd, &write_set);
1120 else /* if (IsAuthPending(auth)) */
1121 FD_SET(auth->fd, &read_set);
1124 * set listener file descriptors
1126 for (listener = ListenerPollList; listener; listener = listener->next) {
1127 assert(-1 < listener->fd);
1128 FD_SET(listener->fd, &read_set);
1131 for (i = HighestFd; i > -1; --i) {
1132 if ((cptr = LocalClientArray[i])) {
1133 if (DBufLength(&cptr->recvQ))
1135 if (DBufLength(&cptr->recvQ) < 4088 || IsServer(cptr))
1136 FD_SET(i, &read_set);
1137 if (DBufLength(&cptr->sendQ) || IsConnecting(cptr) ||
1138 (cptr->listing && DBufLength(&cptr->sendQ) < 2048))
1139 FD_SET(i, &write_set);
1143 wait.tv_sec = IRCD_MIN(delay2, delay);
1144 wait.tv_usec = usec;
1146 Debug((DEBUG_INFO, "select: %d %d", delay, delay2));
1148 nfds = select(FD_SETSIZE, &read_set, &write_set, 0, &wait);
1150 CurrentTime = time(0);
1157 report_error(SELECT_ERROR_MSG, me.name, errno);
1159 server_restart("too many select errors");
1161 CurrentTime = time(0);
1164 if (-1 < UPingFileDescriptor && FD_ISSET(UPingFileDescriptor, &read_set)) {
1168 for (uping = uping_begin(); uping; uping = uping_next) {
1169 uping_next = uping->next;
1170 if (uping->active) {
1171 assert(-1 < uping->fd);
1172 if (FD_ISSET(uping->fd, &read_set)) {
1177 else if (CurrentTime > uping->lastsent) {
1178 uping->lastsent = CurrentTime;
1183 if (-1 < ResolverFileDescriptor && FD_ISSET(ResolverFileDescriptor, &read_set)) {
1188 * Check fd sets for the auth fd's (if set and valid!) first
1189 * because these can not be processed using the normal loops below.
1192 for (auth = AuthPollList; auth; auth = auth_next) {
1193 auth_next = auth->next;
1194 assert(-1 < auth->fd);
1195 if (IsAuthConnect(auth) && FD_ISSET(auth->fd, &write_set)) {
1196 send_auth_query(auth);
1200 else if (FD_ISSET(auth->fd, &read_set)) {
1201 read_auth_reply(auth);
1207 * next accept connections from active listeners
1209 for (listener = ListenerPollList; listener; listener = listener->next) {
1210 assert(-1 < listener->fd);
1211 if (0 < nfds && FD_ISSET(listener->fd, &read_set))
1212 accept_connection(listener);
1215 for (i = HighestFd; -1 < i; --i) {
1216 if (!(cptr = LocalClientArray[i]))
1220 if (FD_ISSET(i, &write_set)) {
1222 if (!on_write_unblocked(cptr) || IsDead(cptr)) {
1223 const char* msg = (cptr->error) ? strerror(cptr->error) : cptr->info;
1225 msg = "Unknown error";
1226 if (FD_ISSET(i, &read_set))
1228 exit_client(cptr, cptr, &me, msg);
1232 if ((read_ready = FD_ISSET(i, &read_set)))
1235 length = 1; /* for fall through case */
1236 if ((!NoNewLine(cptr) || read_ready) && !IsDead(cptr)) {
1237 if (CPTR_KILLED == (length = read_packet(cptr, read_ready)))
1241 /* Bullshit, why would we want to flush sockets while using non-blocking?
1242 * This uses > 4% cpu! --Run */
1244 flush_connections(LocalClientArray[i]);
1247 const char* msg = (cptr->error) ? strerror(cptr->error) : cptr->info;
1249 msg = "Unknown error";
1250 exit_client(cptr, cptr, &me, msg);
1257 * ...hmm, with non-blocking sockets we might get
1258 * here from quite valid reasons, although.. why
1259 * would select report "data available" when there
1260 * wasn't... So, this must be an error anyway... --msa
1261 * actually, EOF occurs when read() returns 0 and
1262 * in due course, select() returns that fd as ready
1263 * for reading even though it ends up being an EOF. -avalon
1265 Debug((DEBUG_ERROR, "READ ERROR: fd = %d %d %d", i, cptr->error, length));
1267 if ((IsServer(cptr) || IsHandshake(cptr)) && cptr->error == 0 && length == 0)
1268 exit_client_msg(cptr, cptr, &me, "Server %s closed the connection (%s)",
1269 cptr->name, cptr->serv->last_error_msg);
1271 const char* msg = (cptr->error) ? strerror(cptr->error) : "EOF from client";
1273 msg = "Unknown error";
1274 exit_client_msg(cptr, cptr, &me, "Read error: %s",
1281 #endif /* USE_SELECT */
1284 * connect_server - start or complete a connection to another server
1285 * returns true (1) if successful, false (0) otherwise
1287 * aconf must point to a valid C:line
1288 * m_connect calls this with a valid by client and a null reply
1289 * try_connections calls this with a null by client, and a null reply
1290 * connect_dns_callback call this with a null by client, and a valid reply
1292 * XXX - if this comes from an m_connect message and a dns query needs to
1293 * be done, we loose the information about who started the connection and
1294 * it's considered an auto connect.
1296 int connect_server(struct ConfItem* aconf, struct Client* by,
1297 struct DNSReply* reply)
1299 struct Client* cptr = 0;
1302 if (aconf->dns_pending) {
1303 sendto_ops("Server %s connect DNS pending");
1306 Debug((DEBUG_NOTICE, "Connect to %s[@%s]", aconf->name,
1307 ircd_ntoa((const char*) &aconf->ipnum)));
1309 if ((cptr = FindClient(aconf->name))) {
1310 if (IsServer(cptr) || IsMe(cptr)) {
1311 sendto_ops("Server %s already present from %s",
1312 aconf->name, cptr->from->name);
1313 if (by && IsUser(by) && !MyUser(by)) {
1314 sendto_one(by, "%s NOTICE %s%s :Server %s already present from %s",
1315 NumServ(&me), NumNick(by), aconf->name, cptr->from->name);
1319 else if (IsHandshake(cptr) || IsConnecting(cptr)) {
1320 if (by && IsUser(by)) {
1322 sendto_one(by, ":%s NOTICE %s :Connection to %s already in progress",
1323 me.name, by->name, cptr->name);
1325 sendto_one(by, "%s NOTICE %s%s :Connection to %s already in progress",
1326 NumServ(&me), NumNick(by), cptr->name);
1332 * If we dont know the IP# for this host and itis a hostname and
1333 * not a ip# string, then try and find the appropriate host record.
1335 if (INADDR_NONE == aconf->ipnum.s_addr) {
1336 char buf[HOSTLEN + 1];
1338 if (INADDR_NONE == (aconf->ipnum.s_addr = inet_addr(aconf->host))) {
1339 struct DNSQuery query;
1342 query.callback = connect_dns_callback;
1343 host_from_uh(buf, aconf->host, HOSTLEN);
1344 buf[HOSTLEN] = '\0';
1346 reply = gethost_byname(buf, &query);
1349 aconf->dns_pending = 1;
1352 memcpy(&aconf->ipnum, reply->hp->h_addr, sizeof(struct in_addr));
1355 cptr = make_client(NULL, STAT_UNKNOWN_SERVER);
1358 cptr->dns_reply = reply;
1361 * Copy these in so we have something for error detection.
1363 ircd_strncpy(cptr->name, aconf->name, HOSTLEN);
1364 ircd_strncpy(cptr->sockhost, aconf->host, HOSTLEN);
1367 * Attach config entries to client here rather than in
1368 * completed_connection. This to avoid null pointer references
1370 attach_confs_byhost(cptr, aconf->host, CONF_SERVER);
1372 if (!find_conf_byhost(cptr->confs, aconf->host, CONF_SERVER)) {
1373 sendto_ops("Host %s is not enabled for connecting: no C-line", aconf->name);
1374 if (by && IsUser(by) && !MyUser(by)) {
1375 sendto_one(by, "%s NOTICE %s%s :Connect to host %s failed: no C-line",
1376 NumServ(&me), NumNick(by), aconf->name);
1378 det_confs_butmask(cptr, 0);
1383 * attempt to connect to the server in the conf line
1385 if (!connect_inet(aconf, cptr)) {
1386 if (by && IsUser(by) && !MyUser(by)) {
1387 sendto_one(by, "%s NOTICE %s%s :Couldn't connect to %s",
1388 NumServ(&me), NumNick(by), cptr->name);
1390 det_confs_butmask(cptr, 0);
1395 * NOTE: if we're here we have a valid C:Line and the client should
1396 * have started the connection and stored the remote address/port and
1397 * ip address name in itself
1399 * The socket has been connected or connect is in progress.
1402 if (by && IsUser(by)) {
1403 sprintf_irc(cptr->serv->by, "%s%s", NumNick(by));
1404 assert(0 == cptr->serv->user);
1405 cptr->serv->user = by->user;
1409 *cptr->serv->by = '\0';
1410 /* strcpy(cptr->serv->by, "Auto"); */
1412 cptr->serv->up = &me;
1413 SetConnecting(cptr);
1415 if (cptr->fd > HighestFd)
1416 HighestFd = cptr->fd;
1417 LocalClientArray[cptr->fd] = cptr;
1419 Count_newunknown(UserStats);
1420 add_client_to_list(cptr);
1422 nextping = CurrentTime;
1428 * Setup local socket structure to use for binding to.
1430 void init_virtual_host(const struct ConfItem* conf)
1434 memset(&VirtualHost, 0, sizeof(VirtualHost));
1435 VirtualHost.sin_family = AF_INET;
1436 VirtualHost.sin_addr.s_addr = INADDR_ANY;
1438 if (EmptyString(conf->passwd) || 0 == strcmp(conf->passwd, "*"))
1440 VirtualHost.sin_addr.s_addr = inet_addr(conf->passwd);
1442 if (INADDR_NONE == VirtualHost.sin_addr.s_addr)
1443 VirtualHost.sin_addr.s_addr = INADDR_ANY;
1447 * Find the real hostname for the host running the server (or one which
1448 * matches the server's name) and its primary IP#. Hostname is stored
1449 * in the client structure passed as a pointer.
1451 int init_server_identity()
1453 struct ConfItem* conf = find_me();
1455 if (!conf || EmptyString(conf->host))
1458 ircd_strncpy(me.name, conf->host, HOSTLEN);
1460 init_virtual_host(conf);