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];
81 static int running_in_background;
84 * report_error text constants
86 const char* const ACCEPT_ERROR_MSG = "error accepting connection for %s: %s";
87 const char* const BIND_ERROR_MSG = "bind error for %s: %s";
88 const char* const CONNECT_ERROR_MSG = "connect to host %s failed: %s";
89 const char* const CONNLIMIT_ERROR_MSG = "connect limit exceeded for %s: %s";
90 const char* const LISTEN_ERROR_MSG = "listen error for %s: %s";
91 const char* const NONB_ERROR_MSG = "error setting non-blocking for %s: %s";
92 const char* const PEERNAME_ERROR_MSG = "getpeername failed for %s: %s";
93 const char* const POLL_ERROR_MSG = "poll error for %s: %s";
94 const char* const REUSEADDR_ERROR_MSG = "error setting SO_REUSEADDR for %s: %s";
95 const char* const SELECT_ERROR_MSG = "select error for %s: %s";
96 const char* const SETBUFS_ERROR_MSG = "error setting buffer size for %s: %s";
97 const char* const SOCKET_ERROR_MSG = "error creating socket for %s: %s";
104 #ifndef NOFLOODCONTROL
105 #define NOFLOODCONTROL
109 #if !defined(USE_POLL)
110 #if FD_SETSIZE < (MAXCONNECTIONS + 4)
114 * All operating systems work when MAXCONNECTIONS <= 252.
115 * Most operating systems work when MAXCONNECTIONS <= 1020 and FD_SETSIZE is
116 * updated correctly in the system headers (on BSD systems our sys.h has
117 * defined FD_SETSIZE to MAXCONNECTIONS+4 before including the system's headers
118 * but sys/types.h might have abruptly redefined it so the check is still
119 * done), you might already need to recompile your kernel.
120 * For larger FD_SETSIZE your milage may vary (kernel patches may be needed).
121 * The check is _NOT_ done if we will not use FD_SETS at all (USE_POLL)
123 #error "FD_SETSIZE is too small or MAXCONNECTIONS too large."
129 * Cannot use perror() within daemon. stderr is closed in
130 * ircd and cannot be used. And, worse yet, it might have
131 * been reassigned to a normal connection...
137 * This a replacement for perror(). Record error to log and
138 * also send a copy to all *LOCAL* opers online.
140 * text is a *format* string for outputting error. It must
141 * contain only two '%s', the first will be replaced
142 * by the sockhost from the cptr, and the latter will
143 * be taken from sys_errlist[errno].
145 * cptr if not NULL, is the *LOCAL* client associated with
148 void report_error(const char* text, const char* who, int err)
150 static time_t last_notice = 0;
151 int errtmp = errno; /* debug may change 'errno' */
152 const char* errmsg = (err) ? strerror(err) : "";
154 errmsg = "Unknown error";
159 if (last_notice + 20 < CurrentTime) {
161 * pace error messages so opers don't get flooded by transients
163 sendto_ops(text, who, errmsg);
164 last_notice = CurrentTime;
167 ircd_log(L_ERROR, text, who, errmsg);
169 if (!running_in_background) {
170 fprintf(stderr, text, who, errmsg);
171 fprintf(stderr, "\n");
178 * connect_dns_callback - called when resolver query finishes
179 * if the query resulted in a successful search, reply will contain
180 * a non-null pointer, otherwise reply will be null.
181 * if successful start the connection, otherwise notify opers
183 static void connect_dns_callback(void* vptr, struct DNSReply* reply)
185 struct ConfItem* aconf = (struct ConfItem*) vptr;
186 aconf->dns_pending = 0;
188 memcpy(&aconf->ipnum, reply->hp->h_addr, sizeof(struct in_addr));
189 connect_server(aconf, 0, reply);
192 sendto_ops("Connect to %s failed: host lookup", aconf->name);
197 * connect_inet - set up address and port and make a connection
199 static int connect_inet(struct ConfItem* aconf, struct Client* cptr)
201 static struct sockaddr_in sin;
205 * Might as well get sockhost from here, the connection is attempted
206 * with it so if it fails its useless.
208 cptr->fd = socket(AF_INET, SOCK_STREAM, 0);
209 if (-1 == cptr->fd) {
211 report_error(SOCKET_ERROR_MSG, cptr->name, errno);
214 if (cptr->fd >= MAXCLIENTS) {
215 report_error(CONNLIMIT_ERROR_MSG, cptr->name, 0);
221 * Bind to a local IP# (with unknown port - let unix decide) so
222 * we have some chance of knowing the IP# that gets used for a host
223 * with more than one IP#.
225 * No we don't bind it, not all OS's can handle connecting with
226 * an already bound socket, different ip# might occur anyway
227 * leading to a freezing select() on this side for some time.
228 * I had this on my Linux 1.1.88 --Run
232 * No, we do bind it if we have virtual host support. If we don't
233 * explicitly bind it, it will default to IN_ADDR_ANY and we lose
234 * due to the other server not allowing our base IP --smg
236 if (bind(cptr->fd, (struct sockaddr*) &VirtualHost, sizeof(VirtualHost))) {
237 report_error(BIND_ERROR_MSG, cptr->name, errno);
242 memset(&sin, 0, sizeof(sin));
243 sin.sin_family = AF_INET;
244 sin.sin_addr.s_addr = aconf->ipnum.s_addr;
245 sin.sin_port = htons(aconf->port);
247 * save connection info in client
249 cptr->ip.s_addr = aconf->ipnum.s_addr;
250 cptr->port = aconf->port;
251 ircd_ntoa_r(cptr->sock_ip, (const char*) &cptr->ip);
253 * we want a big buffer for server connections
255 if (!os_set_sockbufs(cptr->fd, SERVER_TCP_WINDOW)) {
257 report_error(SETBUFS_ERROR_MSG, cptr->name, errno);
261 * ALWAYS set sockets non-blocking
263 if (!os_set_nonblocking(cptr->fd)) {
265 report_error(NONB_ERROR_MSG, cptr->name, errno);
268 if (!os_connect_nonb(cptr->fd, &sin)) {
270 report_error(CONNECT_ERROR_MSG, cptr->name, errno);
278 * Attempt to send a sequence of bytes to the connection.
281 * < 0 Some fatal error occurred, (but not EWOULDBLOCK).
282 * This return is a request to close the socket and
285 * >= 0 No real error occurred, returns the number of
286 * bytes actually transferred. EWOULDBLOCK and other
287 * possibly similar conditions should be mapped to
288 * zero return. Upper level routine will have to
289 * decide what to do with those unwritten bytes...
291 * *NOTE* alarm calls have been preserved, so this should
292 * work equally well whether blocking or non-blocking
295 * We don't use blocking anymore, that is impossible with the
296 * net.loads today anyway. Commented out the alarms to save cpu.
299 unsigned int deliver_it(struct Client *cptr, const char *str, unsigned int len)
301 unsigned int bytes_written = 0;
304 switch (os_send_nonb(cptr->fd, str, len, &bytes_written)) {
306 cptr->flags &= ~FLAGS_BLOCKED;
308 cptr->sendB += bytes_written;
309 me.sendB += bytes_written;
310 if (cptr->sendB > 1023) {
311 cptr->sendK += (cptr->sendB >> 10);
312 cptr->sendB &= 0x03ff; /* 2^10 = 1024, 3ff = 1023 */
314 if (me.sendB > 1023) {
315 me.sendK += (me.sendB >> 10);
318 if (bytes_written < len)
319 cptr->flags |= FLAGS_BLOCKED;
322 cptr->flags |= FLAGS_BLOCKED;
326 cptr->flags |= FLAGS_DEADSOCKET;
329 return bytes_written;
338 int limit = os_set_fdlimit(MAXCONNECTIONS);
340 fprintf(stderr, "error setting max fd's to %d\n", limit);
343 else if (limit > 0) {
344 fprintf(stderr, "ircd fd table too big\nHard Limit: %d IRC max: %d\n",
345 limit, MAXCONNECTIONS);
346 fprintf(stderr, "set MAXCONNECTIONS to a smaller value");
350 for (fd = 3; fd < MAXCONNECTIONS; ++fd)
353 LocalClientArray[fd] = NULL;
355 LocalClientArray[2] = 0;
356 LocalClientArray[1] = 0;
357 LocalClientArray[0] = 0;
361 if (bootopt & BOOT_TTY) {
362 /* debugging is going to a tty */
366 if (!(bootopt & BOOT_DEBUG))
371 running_in_background = 1;
373 if ((fd = open("/dev/tty", O_RDWR)) > -1) {
374 ioctl(fd, TIOCNOTTY, 0);
382 void release_dns_reply(struct Client* cptr)
385 assert(MyConnect(cptr));
387 if (cptr->dns_reply) {
388 assert(0 < cptr->dns_reply->ref_count);
389 --cptr->dns_reply->ref_count;
395 * completed_connection
397 * Complete non-blocking connect()-sequence. Check access and
398 * terminate connection, if trouble detected.
400 * Return TRUE, if successfully completed
401 * FALSE, if failed and ClientExit
403 static int completed_connection(struct Client* cptr)
405 struct ConfItem *aconf;
407 struct Client *acptr;
413 * get the socket status from the fd first to check if
414 * connection actually succeeded
416 if ((cptr->error = os_get_sockerr(cptr->fd))) {
417 const char* msg = strerror(cptr->error);
419 msg = "Unknown error";
420 sendto_ops("Connection failed to %s: %s", cptr->name, msg);
423 if (!(aconf = find_conf_byname(cptr->confs, cptr->name, CONF_SERVER))) {
424 sendto_ops("Lost Server Line for %s", cptr->name);
427 if (!EmptyString(aconf->passwd))
428 sendto_one(cptr, "PASS :%s", aconf->passwd);
431 /* dead code, already done in connect_server */
435 * Create a unique timestamp
438 for (i = HighestFd; i > -1; --i) {
439 if ((acptr = LocalClientArray[i]) &&
440 (IsServer(acptr) || IsHandshake(acptr))) {
441 if (acptr->serv->timestamp >= newts)
442 newts = acptr->serv->timestamp + 1;
445 assert(0 != cptr->serv);
447 cptr->serv->timestamp = newts;
450 * Make us timeout after twice the timeout for DNS look ups
452 cptr->lasttime = CurrentTime;
453 cptr->flags |= FLAGS_PINGSENT;
454 sendto_one(cptr, "SERVER %s 1 " TIME_T_FMT " " TIME_T_FMT " J%s %s%s :%s",
455 me.name, me.serv->timestamp, newts, MAJOR_PROTOCOL,
456 NumServCap(&me), me.info);
458 return (IsDead(cptr)) ? 0 : 1;
464 * Close the physical connection. This function must make
465 * MyConnect(cptr) == FALSE, and set cptr->from == NULL.
467 void close_connection(struct Client *cptr)
469 struct ConfItem* aconf;
471 if (IsServer(cptr)) {
472 ServerStats->is_sv++;
473 ServerStats->is_sbs += cptr->sendB;
474 ServerStats->is_sbr += cptr->receiveB;
475 ServerStats->is_sks += cptr->sendK;
476 ServerStats->is_skr += cptr->receiveK;
477 ServerStats->is_sti += CurrentTime - cptr->firsttime;
478 if (ServerStats->is_sbs > 1023) {
479 ServerStats->is_sks += (ServerStats->is_sbs >> 10);
480 ServerStats->is_sbs &= 0x3ff;
482 if (ServerStats->is_sbr > 1023) {
483 ServerStats->is_skr += (ServerStats->is_sbr >> 10);
484 ServerStats->is_sbr &= 0x3ff;
487 * If the connection has been up for a long amount of time, schedule
488 * a 'quick' reconnect, else reset the next-connect cycle.
490 if ((aconf = find_conf_exact(cptr->name, 0, cptr->sockhost, CONF_SERVER))) {
492 * Reschedule a faster reconnect, if this was a automaticly
493 * connected configuration entry. (Note that if we have had
494 * a rehash in between, the status has been changed to
495 * CONF_ILLEGAL). But only do this if it was a "good" link.
497 aconf->hold = CurrentTime;
498 aconf->hold += (aconf->hold - cptr->since > HANGONGOODLINK) ?
499 HANGONRETRYDELAY : ConfConFreq(aconf);
500 if (nextconnect > aconf->hold)
501 nextconnect = aconf->hold;
504 else if (IsUser(cptr)) {
505 ServerStats->is_cl++;
506 ServerStats->is_cbs += cptr->sendB;
507 ServerStats->is_cbr += cptr->receiveB;
508 ServerStats->is_cks += cptr->sendK;
509 ServerStats->is_ckr += cptr->receiveK;
510 ServerStats->is_cti += CurrentTime - cptr->firsttime;
511 if (ServerStats->is_cbs > 1023) {
512 ServerStats->is_cks += (ServerStats->is_cbs >> 10);
513 ServerStats->is_cbs &= 0x3ff;
515 if (ServerStats->is_cbr > 1023) {
516 ServerStats->is_ckr += (ServerStats->is_cbr >> 10);
517 ServerStats->is_cbr &= 0x3ff;
521 ServerStats->is_ni++;
524 flush_connections(cptr);
525 LocalClientArray[cptr->fd] = 0;
529 cptr->flags |= FLAGS_DEADSOCKET;
531 DBufClear(&cptr->sendQ);
532 DBufClear(&cptr->recvQ);
533 memset(cptr->passwd, 0, sizeof(cptr->passwd));
534 set_snomask(cptr, 0, SNO_SET);
536 det_confs_butmask(cptr, 0);
538 if (cptr->listener) {
539 release_listener(cptr->listener);
543 for ( ; HighestFd > 0; --HighestFd) {
544 if (LocalClientArray[HighestFd])
549 int net_close_unregistered_connections(struct Client* source)
556 for (i = HighestFd; i > 0; --i) {
557 if ((cptr = LocalClientArray[i]) && !IsRegistered(cptr)) {
558 sendto_one(source, rpl_str(RPL_CLOSING), me.name, source->name,
559 get_client_name(source, HIDE_IP), cptr->status);
560 exit_client(source, cptr, &me, "Oper Closing");
568 * Creates a client which has just connected to us on the given fd.
569 * The sockhost field is initialized with the ip# of the host.
570 * The client is not added to the linked list of clients, it is
571 * passed off to the auth handler for dns and ident queries.
573 void add_connection(struct Listener* listener, int fd)
575 struct sockaddr_in addr;
576 struct Client* new_client;
577 time_t next_target = 0;
578 const char* const throttle_message =
579 "ERROR: Your host is trying to (re)connect too fast -- throttled\r\n";
580 /* 12345678901234567890123456789012345679012345678901234567890123456 */
582 assert(0 != listener);
584 * Removed preliminary access check. Full check is performed in
585 * m_server and m_user instead. Also connection time out help to
586 * get rid of unwanted connections.
588 if (!os_get_peername(fd, &addr) || !os_set_nonblocking(fd)) {
589 ++ServerStats->is_ref;
594 * Add this local client to the IPcheck registry.
595 * If it is a connection to a user port and if the site has been throttled,
598 if (!IPcheck_local_connect(addr.sin_addr, &next_target) && !listener->server) {
599 ++ServerStats->is_ref;
601 * strlen(throttle_message) == 66
603 send(fd, throttle_message, 66, 0);
608 new_client = make_client(NULL,
609 (listener->server) ? STAT_UNKNOWN_SERVER : STAT_UNKNOWN_USER);
611 * Copy ascii address to 'sockhost' just in case. Then we
612 * have something valid to put into error messages...
614 ircd_ntoa_r(new_client->sock_ip, (const char*) &addr.sin_addr);
615 strcpy(new_client->sockhost, new_client->sock_ip);
616 new_client->ip.s_addr = addr.sin_addr.s_addr;
617 new_client->port = ntohs(addr.sin_port);
620 new_client->nexttarget = next_target;
624 if (!listener->server)
625 SetIPChecked(new_client);
626 new_client->listener = listener;
627 ++listener->ref_count;
629 Count_newunknown(UserStats);
631 * if we've made it this far we can put the client on the auth query pile
633 start_auth(new_client);
639 * Read a 'packet' of data from a connection and process it. Read in 8k
640 * chunks to give a better performance rating (for server connections).
641 * Do some tricky stuff for client connections to make sure they don't do
642 * any flooding >:-) -avalon
644 static int read_packet(struct Client *cptr, int socket_ready)
646 unsigned int dolen = 0;
647 unsigned int length = 0;
649 if (socket_ready && !(IsUser(cptr) && DBufLength(&cptr->recvQ) > CLIENT_FLOOD)) {
650 switch (os_recv_nonb(cptr->fd, readbuf, sizeof(readbuf), &length)) {
653 cptr->lasttime = CurrentTime;
654 if (cptr->lasttime > cptr->since)
655 cptr->since = cptr->lasttime;
656 cptr->flags &= ~(FLAGS_PINGSENT | FLAGS_NONL);
663 /* cptr->flags |= FLAGS_DEADSOCKET; */
669 * For server connections, we process as many as we can without
670 * worrying about the time of day or anything :)
672 if (length > 0 && IsServer(cptr)) {
673 return server_dopacket(cptr, readbuf, length);
677 * Before we even think of parsing what we just read, stick
678 * it on the end of the receive queue and do it when its
681 if (length > 0 && 0 == dbuf_put(&cptr->recvQ, readbuf, length)) {
682 return exit_client(cptr, cptr, &me, "dbuf_put fail");
684 #ifndef NOFLOODCONTROL
686 * XXX - cptr will always be a user or unregistered
688 if (IsUser(cptr) && DBufLength(&cptr->recvQ) > CLIENT_FLOOD)
689 return exit_client(cptr, cptr, &me, "Excess Flood");
691 while (DBufLength(&cptr->recvQ) && !NoNewLine(cptr) &&
692 (IsTrusted(cptr) || cptr->since - CurrentTime < 10))
694 while (DBufLength(&cptr->recvQ) && !NoNewLine(cptr))
698 * If it has become registered as a Server
699 * then skip the per-message parsing below.
701 if (IsServer(cptr)) {
702 dolen = dbuf_get(&cptr->recvQ, readbuf, sizeof(readbuf));
703 return (dolen) ? server_dopacket(cptr, readbuf, dolen) : 1;
705 dolen = dbuf_getmsg(&cptr->recvQ, cptr->buffer, BUFSIZE);
707 * Devious looking...whats it do ? well..if a client
708 * sends a *long* message without any CR or LF, then
709 * dbuf_getmsg fails and we pull it out using this
710 * loop which just gets the next 512 bytes and then
711 * deletes the rest of the buffer contents.
715 if (DBufLength(&cptr->recvQ) < 510)
716 cptr->flags |= FLAGS_NONL;
718 DBufClear(&cptr->recvQ);
720 else if (CPTR_KILLED == client_dopacket(cptr, dolen))
727 static int on_write_unblocked(struct Client* cptr)
730 * ...room for writing, empty some queue then...
732 cptr->flags &= ~FLAGS_BLOCKED;
733 if (IsConnecting(cptr)) {
734 if (!completed_connection(cptr))
737 else if (cptr->listing && DBufLength(&cptr->sendQ) < 2048)
738 list_next_channels(cptr, 64);
744 * Select / Poll Read Algorithm for ircd
746 * We need to check the file descriptors for all the different types
747 * of things that use them, so check for reads on everything but connects
748 * and writes on connects and descriptors that are blocked
750 * for each (client in local) {
751 * if (not connecting)
753 * if (connecting or blocked)
758 * for each (client in local) {
759 * if (there are descriptors to check) {
760 * if (write activity)
767 * Note we must always process data read whether or not there has been
768 * read activity or file descriptors set, since data is buffered by the client.
777 #if defined(POLLMSG) && defined(POLLIN) && defined(POLLRDNORM)
778 # define POLLREADFLAGS (POLLMSG|POLLIN|POLLRDNORM)
780 # if defined(POLLIN) && defined(POLLRDNORM)
781 # define POLLREADFLAGS (POLLIN|POLLRDNORM)
784 # define POLLREADFLAGS POLLIN
786 # if defined(POLLRDNORM)
787 # define POLLREADFLAGS POLLRDNORM
793 #if defined(POLLOUT) && defined(POLLWRNORM)
794 #define POLLWRITEFLAGS (POLLOUT|POLLWRNORM)
796 # if defined(POLLOUT)
797 # define POLLWRITEFLAGS POLLOUT
799 # if defined(POLLWRNORM)
800 # define POLLWRITEFLAGS POLLWRNORM
806 #define POLLERRORS (POLLHUP|POLLERR)
808 #define POLLERRORS POLLERR
812 * NOTE: pfd and pfd_count are local variable names in read_message
814 #define PFD_SETR(xfd) \
815 do { CHECK_ADD_PFD(xfd) pfd->events |= POLLREADFLAGS; } while(0)
816 #define PFD_SETW(xfd) \
817 do { CHECK_ADD_PFD(xfd) pfd->events |= POLLWRITEFLAGS; } while(0)
819 #define CHECK_ADD_PFD(xfd) \
820 if (pfd->fd != xfd) { \
821 pfd = &poll_fds[pfd_count++]; \
822 poll_fds[pfd_count].fd = -1; \
828 * Check all connections for new connections and input data that is to be
829 * processed. Also check for connections with data queued and whether we can
832 * Don't ever use ZERO for `delay', unless you mean to poll and then
833 * you have to have sleep/wait somewhere else in the code.--msa
835 int read_message(time_t delay)
837 struct pollfd poll_fds[MAXCONNECTIONS + 1];
839 struct Listener* listener = 0;
840 struct AuthRequest* auth = 0;
841 struct AuthRequest* auth_next = 0;
842 struct UPing* uping = 0;
843 struct UPing* uping_next = 0;
844 time_t delay2 = delay;
851 struct pollfd* res_pfd;
852 struct pollfd* uping_pfd;
856 unsigned int timeout;
865 if (-1 < ResolverFileDescriptor) {
866 PFD_SETR(ResolverFileDescriptor);
869 if (-1 < UPingFileDescriptor) {
870 PFD_SETR(UPingFileDescriptor);
874 * add uping descriptors
876 for (uping = uping_begin(); uping; uping = uping_next) {
877 uping_next = uping->next;
880 if (uping->lastsent && CurrentTime > uping->timeout) {
884 uping->index = pfd_count;
889 * add auth file descriptors
891 for (auth = AuthPollList; auth; auth = auth->next) {
892 assert(-1 < auth->fd);
893 auth->index = pfd_count;
894 if (IsAuthConnect(auth))
900 * add listener file descriptors
902 for (listener = ListenerPollList; listener; listener = listener->next) {
903 assert(-1 < listener->fd);
905 * pfd_count is incremented by PFD_SETR so we need to save the
908 listener->index = pfd_count;
909 PFD_SETR(listener->fd);
912 for (i = HighestFd; -1 < i; --i) {
913 if ((cptr = LocalClientArray[i])) {
915 if (DBufLength(&cptr->recvQ))
917 if (DBufLength(&cptr->recvQ) < 4088 || IsServer(cptr)) {
920 if (DBufLength(&cptr->sendQ) || IsConnecting(cptr) ||
921 (cptr->listing && DBufLength(&cptr->sendQ) < 2048)) {
927 Debug((DEBUG_INFO, "poll: %d %d", delay, delay2));
929 timeout = (IRCD_MIN(delay2, delay)) * 1000;
931 nfds = poll(poll_fds, pfd_count, timeout);
933 CurrentTime = time(0);
939 report_error(POLL_ERROR_MSG, me.name, errno);
942 server_restart("too many poll errors");
944 CurrentTime = time(0);
947 if (uping_pfd && (uping_pfd->revents & (POLLREADFLAGS | POLLERRORS))) {
952 * check uping replies
954 for (uping = uping_begin(); uping; uping = uping_next) {
955 uping_next = uping->next;
957 assert(-1 < uping->index);
958 if (poll_fds[uping->index].revents) {
963 else if (CurrentTime > uping->lastsent) {
964 uping->lastsent = CurrentTime;
970 if (res_pfd && (res_pfd->revents & (POLLREADFLAGS | POLLERRORS))) {
977 for (auth = AuthPollList; auth; auth = auth_next) {
978 auth_next = auth->next;
981 * check for any event, we only ask for one at a time
983 if (poll_fds[i].revents) {
984 if (IsAuthConnect(auth))
985 send_auth_query(auth);
987 read_auth_reply(auth);
995 for (listener = ListenerPollList; listener; listener = listener->next) {
997 if (poll_fds[i].revents) {
998 accept_connection(listener);
1004 * i contains the next non-auth/non-listener index, since we put the
1005 * resolver, auth and listener, file descriptors in poll_fds first,
1006 * the very next one should be the start of the clients
1008 pfd = &poll_fds[++i];
1010 for ( ; (i < pfd_count); ++i, ++pfd) {
1011 if (!(cptr = LocalClientArray[pfd->fd]))
1013 read_ready = write_ready = 0;
1015 if (0 < nfds && pfd->revents) {
1018 read_ready = pfd->revents & POLLREADFLAGS;
1019 write_ready = pfd->revents & POLLWRITEFLAGS;
1021 if (pfd->revents & POLLERRORS) {
1022 if (pfd->events & POLLREADFLAGS)
1024 if (pfd->events & POLLWRITEFLAGS)
1029 if (!on_write_unblocked(cptr) || IsDead(cptr)) {
1030 const char* msg = (cptr->error) ? strerror(cptr->error) : cptr->info;
1032 msg = "Unknown error";
1033 exit_client(cptr, cptr, &me, msg);
1037 length = 1; /* for fall through case */
1038 if ((!NoNewLine(cptr) || read_ready) && !IsDead(cptr)) {
1039 if (CPTR_KILLED == (length = read_packet(cptr, read_ready)))
1043 /* Bullshit, why would we want to flush sockets while using non-blocking?
1044 * This uses > 4% cpu! --Run */
1046 flush_connections(poll_cptr[i]);
1049 const char* msg = (cptr->error) ? strerror(cptr->error) : cptr->info;
1051 msg = "Unknown error";
1052 exit_client(cptr, cptr, &me, (char*) msg);
1057 cptr->flags |= FLAGS_DEADSOCKET;
1059 * ...hmm, with non-blocking sockets we might get
1060 * here from quite valid reasons, although.. why
1061 * would select report "data available" when there
1062 * wasn't... So, this must be an error anyway... --msa
1063 * actually, EOF occurs when read() returns 0 and
1064 * in due course, select() returns that fd as ready
1065 * for reading even though it ends up being an EOF. -avalon
1067 Debug((DEBUG_ERROR, "READ ERROR: fd = %d %d %d", pfd->fd, errno, length));
1069 if ((IsServer(cptr) || IsHandshake(cptr)) && cptr->error == 0 && length == 0)
1070 exit_client_msg(cptr, cptr, &me, "Server %s closed the connection (%s)",
1071 cptr->name, cptr->serv->last_error_msg);
1073 const char* msg = (cptr->error) ? strerror(cptr->error) : "EOF from client";
1075 msg = "Unknown error";
1076 exit_client_msg(cptr, cptr, &me, "Read error to %s: %s",
1077 get_client_name(cptr, HIDE_IP), msg);
1082 #else /* USE_SELECT */
1085 * Check all connections for new connections and input data that is to be
1086 * processed. Also check for connections with data queued and whether we can
1089 * Don't ever use ZERO for `delay', unless you mean to poll and then
1090 * you have to have sleep/wait somewhere else in the code.--msa
1092 int read_message(time_t delay)
1094 struct Client* cptr;
1095 struct Listener* listener;
1096 struct AuthRequest* auth = 0;
1097 struct AuthRequest* auth_next = 0;
1098 struct UPing* uping;
1099 struct UPing* uping_next;
1101 struct timeval wait;
1102 time_t delay2 = delay;
1103 unsigned int usec = 0;
1114 FD_ZERO(&write_set);
1116 if (-1 < ResolverFileDescriptor)
1117 FD_SET(ResolverFileDescriptor, &read_set);
1118 if (-1 < UPingFileDescriptor)
1119 FD_SET(UPingFileDescriptor, &read_set);
1121 * set up uping file descriptors
1123 for (uping = uping_begin(); uping; uping = uping_next) {
1124 uping_next = uping->next;
1125 if (uping->active) {
1127 if (uping->lastsent && CurrentTime > uping->timeout) {
1131 assert(-1 < uping->fd);
1132 FD_SET(uping->fd, &read_set);
1136 * set auth file descriptors
1138 for (auth = AuthPollList; auth; auth = auth->next) {
1139 assert(-1 < auth->fd);
1140 if (IsAuthConnect(auth))
1141 FD_SET(auth->fd, &write_set);
1142 else /* if (IsAuthPending(auth)) */
1143 FD_SET(auth->fd, &read_set);
1146 * set listener file descriptors
1148 for (listener = ListenerPollList; listener; listener = listener->next) {
1149 assert(-1 < listener->fd);
1150 FD_SET(listener->fd, &read_set);
1153 for (i = HighestFd; i > -1; --i) {
1154 if ((cptr = LocalClientArray[i])) {
1155 if (DBufLength(&cptr->recvQ))
1157 if (DBufLength(&cptr->recvQ) < 4088 || IsServer(cptr))
1158 FD_SET(i, &read_set);
1159 if (DBufLength(&cptr->sendQ) || IsConnecting(cptr) ||
1160 (cptr->listing && DBufLength(&cptr->sendQ) < 2048))
1161 FD_SET(i, &write_set);
1165 wait.tv_sec = IRCD_MIN(delay2, delay);
1166 wait.tv_usec = usec;
1168 Debug((DEBUG_INFO, "select: %d %d", delay, delay2));
1170 nfds = select(FD_SETSIZE, &read_set, &write_set, 0, &wait);
1172 CurrentTime = time(0);
1179 report_error(SELECT_ERROR_MSG, me.name, errno);
1181 server_restart("too many select errors");
1183 CurrentTime = time(0);
1186 if (-1 < UPingFileDescriptor && FD_ISSET(UPingFileDescriptor, &read_set)) {
1190 for (uping = uping_begin(); uping; uping = uping_next) {
1191 uping_next = uping->next;
1192 if (uping->active) {
1193 assert(-1 < uping->fd);
1194 if (FD_ISSET(uping->fd, &read_set)) {
1199 else if (CurrentTime > uping->lastsent) {
1200 uping->lastsent = CurrentTime;
1205 if (-1 < ResolverFileDescriptor && FD_ISSET(ResolverFileDescriptor, &read_set)) {
1210 * Check fd sets for the auth fd's (if set and valid!) first
1211 * because these can not be processed using the normal loops below.
1214 for (auth = AuthPollList; auth; auth = auth_next) {
1215 auth_next = auth->next;
1216 assert(-1 < auth->fd);
1217 if (IsAuthConnect(auth) && FD_ISSET(auth->fd, &write_set)) {
1218 send_auth_query(auth);
1222 else if (FD_ISSET(auth->fd, &read_set)) {
1223 read_auth_reply(auth);
1229 * next accept connections from active listeners
1231 for (listener = ListenerPollList; listener; listener = listener->next) {
1232 assert(-1 < listener->fd);
1233 if (0 < nfds && FD_ISSET(listener->fd, &read_set))
1234 accept_connection(listener);
1237 for (i = HighestFd; -1 < i; --i) {
1238 if (!(cptr = LocalClientArray[i]))
1242 if (FD_ISSET(i, &write_set)) {
1244 if (!on_write_unblocked(cptr) || IsDead(cptr)) {
1245 const char* msg = (cptr->error) ? strerror(cptr->error) : cptr->info;
1247 msg = "Unknown error";
1248 if (FD_ISSET(i, &read_set))
1250 exit_client(cptr, cptr, &me, msg);
1254 if ((read_ready = FD_ISSET(i, &read_set)))
1257 length = 1; /* for fall through case */
1258 if ((!NoNewLine(cptr) || read_ready) && !IsDead(cptr)) {
1259 if (CPTR_KILLED == (length = read_packet(cptr, read_ready)))
1263 /* Bullshit, why would we want to flush sockets while using non-blocking?
1264 * This uses > 4% cpu! --Run */
1266 flush_connections(LocalClientArray[i]);
1269 const char* msg = (cptr->error) ? strerror(cptr->error) : cptr->info;
1271 msg = "Unknown error";
1272 exit_client(cptr, cptr, &me, msg);
1279 * ...hmm, with non-blocking sockets we might get
1280 * here from quite valid reasons, although.. why
1281 * would select report "data available" when there
1282 * wasn't... So, this must be an error anyway... --msa
1283 * actually, EOF occurs when read() returns 0 and
1284 * in due course, select() returns that fd as ready
1285 * for reading even though it ends up being an EOF. -avalon
1287 Debug((DEBUG_ERROR, "READ ERROR: fd = %d %d %d", i, cptr->error, length));
1289 if ((IsServer(cptr) || IsHandshake(cptr)) && cptr->error == 0 && length == 0)
1290 exit_client_msg(cptr, cptr, &me, "Server %s closed the connection (%s)",
1291 cptr->name, cptr->serv->last_error_msg);
1293 const char* msg = (cptr->error) ? strerror(cptr->error) : "EOF from client";
1295 msg = "Unknown error";
1296 exit_client_msg(cptr, cptr, &me, "Read error to %s: %s",
1297 get_client_name(cptr, HIDE_IP), msg);
1303 #endif /* USE_SELECT */
1306 * connect_server - start or complete a connection to another server
1307 * returns true (1) if successful, false (0) otherwise
1309 * aconf must point to a valid C:line
1310 * m_connect calls this with a valid by client and a null reply
1311 * try_connections calls this with a null by client, and a null reply
1312 * connect_dns_callback call this with a null by client, and a valid reply
1314 * XXX - if this comes from an m_connect message and a dns query needs to
1315 * be done, we loose the information about who started the connection and
1316 * it's considered an auto connect.
1318 int connect_server(struct ConfItem* aconf, struct Client* by,
1319 struct DNSReply* reply)
1321 struct Client* cptr = 0;
1324 if (aconf->dns_pending) {
1325 sendto_ops("Server %s connect DNS pending");
1328 Debug((DEBUG_NOTICE, "Connect to %s[@%s]", aconf->name,
1329 ircd_ntoa((const char*) &aconf->ipnum)));
1331 if ((cptr = FindClient(aconf->name))) {
1332 if (IsServer(cptr) || IsMe(cptr)) {
1333 sendto_ops("Server %s already present from %s",
1334 aconf->name, cptr->from->name);
1335 if (by && IsUser(by) && !MyUser(by)) {
1336 sendto_one(by, "%s NOTICE %s%s :Server %s already present from %s",
1337 NumServ(&me), NumNick(by), aconf->name, cptr->from->name);
1341 else if (IsHandshake(cptr) || IsConnecting(cptr)) {
1342 if (by && IsUser(by)) {
1344 sendto_one(by, ":%s NOTICE %s :Connection to %s already in progress",
1345 me.name, by->name, cptr->name);
1347 sendto_one(by, "%s NOTICE %s%s :Connection to %s already in progress",
1348 NumServ(&me), NumNick(by), cptr->name);
1354 * If we dont know the IP# for this host and itis a hostname and
1355 * not a ip# string, then try and find the appropriate host record.
1357 if (INADDR_NONE == aconf->ipnum.s_addr) {
1358 char buf[HOSTLEN + 1];
1360 if (INADDR_NONE == (aconf->ipnum.s_addr = inet_addr(aconf->host))) {
1361 struct DNSQuery query;
1364 query.callback = connect_dns_callback;
1365 host_from_uh(buf, aconf->host, HOSTLEN);
1366 buf[HOSTLEN] = '\0';
1368 reply = gethost_byname(buf, &query);
1371 aconf->dns_pending = 1;
1374 memcpy(&aconf->ipnum, reply->hp->h_addr, sizeof(struct in_addr));
1377 cptr = make_client(NULL, STAT_UNKNOWN_SERVER);
1380 cptr->dns_reply = reply;
1383 * Copy these in so we have something for error detection.
1385 ircd_strncpy(cptr->name, aconf->name, HOSTLEN);
1386 ircd_strncpy(cptr->sockhost, aconf->host, HOSTLEN);
1389 * Attach config entries to client here rather than in
1390 * completed_connection. This to avoid null pointer references
1392 attach_confs_byhost(cptr, aconf->host, CONF_SERVER);
1394 if (!find_conf_byhost(cptr->confs, aconf->host, CONF_SERVER)) {
1395 sendto_ops("Host %s is not enabled for connecting: no C-line", aconf->name);
1396 if (by && IsUser(by) && !MyUser(by)) {
1397 sendto_one(by, "%s NOTICE %s%s :Connect to host %s failed: no C-line",
1398 NumServ(&me), NumNick(by), aconf->name);
1400 det_confs_butmask(cptr, 0);
1405 * attempt to connect to the server in the conf line
1407 if (!connect_inet(aconf, cptr)) {
1408 if (by && IsUser(by) && !MyUser(by)) {
1409 sendto_one(by, "%s NOTICE %s%s :Couldn't connect to %s",
1410 NumServ(&me), NumNick(by), cptr->name);
1412 det_confs_butmask(cptr, 0);
1417 * NOTE: if we're here we have a valid C:Line and the client should
1418 * have started the connection and stored the remote address/port and
1419 * ip address name in itself
1421 * The socket has been connected or connect is in progress.
1424 if (by && IsUser(by)) {
1425 sprintf_irc(cptr->serv->by, "%s%s", NumNick(by));
1426 assert(0 == cptr->serv->user);
1427 cptr->serv->user = by->user;
1431 *cptr->serv->by = '\0';
1432 /* strcpy(cptr->serv->by, "Auto"); */
1434 cptr->serv->up = &me;
1435 SetConnecting(cptr);
1437 if (cptr->fd > HighestFd)
1438 HighestFd = cptr->fd;
1439 LocalClientArray[cptr->fd] = cptr;
1441 Count_newunknown(UserStats);
1442 add_client_to_list(cptr);
1444 nextping = CurrentTime;
1450 * Setup local socket structure to use for binding to.
1452 void init_virtual_host(const struct ConfItem* conf)
1456 memset(&VirtualHost, 0, sizeof(VirtualHost));
1457 VirtualHost.sin_family = AF_INET;
1458 VirtualHost.sin_addr.s_addr = INADDR_ANY;
1460 if (EmptyString(conf->passwd) || 0 == strcmp(conf->passwd, "*"))
1462 VirtualHost.sin_addr.s_addr = inet_addr(conf->passwd);
1464 if (INADDR_NONE == VirtualHost.sin_addr.s_addr)
1465 VirtualHost.sin_addr.s_addr = INADDR_ANY;
1469 * Find the real hostname for the host running the server (or one which
1470 * matches the server's name) and its primary IP#. Hostname is stored
1471 * in the client structure passed as a pointer.
1473 int init_server_identity()
1475 struct ConfItem* conf = find_me();
1477 if (!conf || EmptyString(conf->host))
1480 ircd_strncpy(me.name, conf->host, HOSTLEN);
1482 init_virtual_host(conf);