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 * XXX - do we really want to do this? is it needed?
596 os_disable_options(fd);
599 * Add this local client to the IPcheck registry.
600 * If it is a connection to a user port and if the site has been throttled,
603 if (!IPcheck_local_connect(addr.sin_addr, &next_target) && !listener->server) {
604 ++ServerStats->is_ref;
606 * strlen(throttle_message) == 66
608 send(fd, throttle_message, 66, 0);
613 new_client = make_client(NULL,
614 (listener->server) ? STAT_UNKNOWN_SERVER : STAT_UNKNOWN_USER);
616 * Copy ascii address to 'sockhost' just in case. Then we
617 * have something valid to put into error messages...
619 ircd_ntoa_r(new_client->sock_ip, (const char*) &addr.sin_addr);
620 strcpy(new_client->sockhost, new_client->sock_ip);
621 new_client->ip.s_addr = addr.sin_addr.s_addr;
622 new_client->port = ntohs(addr.sin_port);
625 new_client->nexttarget = next_target;
629 if (!listener->server)
630 SetIPChecked(new_client);
631 new_client->listener = listener;
632 ++listener->ref_count;
634 Count_newunknown(UserStats);
636 * if we've made it this far we can put the client on the auth query pile
638 start_auth(new_client);
644 * Read a 'packet' of data from a connection and process it. Read in 8k
645 * chunks to give a better performance rating (for server connections).
646 * Do some tricky stuff for client connections to make sure they don't do
647 * any flooding >:-) -avalon
649 static int read_packet(struct Client *cptr, int socket_ready)
651 unsigned int dolen = 0;
652 unsigned int length = 0;
654 if (socket_ready && !(IsUser(cptr) && DBufLength(&cptr->recvQ) > CLIENT_FLOOD)) {
655 switch (os_recv_nonb(cptr->fd, readbuf, sizeof(readbuf), &length)) {
658 cptr->lasttime = CurrentTime;
659 if (cptr->lasttime > cptr->since)
660 cptr->since = cptr->lasttime;
661 cptr->flags &= ~(FLAGS_PINGSENT | FLAGS_NONL);
668 /* cptr->flags |= FLAGS_DEADSOCKET; */
674 * For server connections, we process as many as we can without
675 * worrying about the time of day or anything :)
677 if (length > 0 && IsServer(cptr)) {
678 return server_dopacket(cptr, readbuf, length);
682 * Before we even think of parsing what we just read, stick
683 * it on the end of the receive queue and do it when its
686 if (length > 0 && 0 == dbuf_put(&cptr->recvQ, readbuf, length)) {
687 return exit_client(cptr, cptr, &me, "dbuf_put fail");
689 #ifndef NOFLOODCONTROL
691 * XXX - cptr will always be a user or unregistered
693 if (IsUser(cptr) && DBufLength(&cptr->recvQ) > CLIENT_FLOOD)
694 return exit_client(cptr, cptr, &me, "Excess Flood");
696 while (DBufLength(&cptr->recvQ) && !NoNewLine(cptr) &&
697 (IsTrusted(cptr) || cptr->since - CurrentTime < 10))
699 while (DBufLength(&cptr->recvQ) && !NoNewLine(cptr))
703 * If it has become registered as a Server
704 * then skip the per-message parsing below.
706 if (IsServer(cptr)) {
707 dolen = dbuf_get(&cptr->recvQ, readbuf, sizeof(readbuf));
708 return (dolen) ? server_dopacket(cptr, readbuf, dolen) : 1;
710 dolen = dbuf_getmsg(&cptr->recvQ, cptr->buffer, BUFSIZE);
712 * Devious looking...whats it do ? well..if a client
713 * sends a *long* message without any CR or LF, then
714 * dbuf_getmsg fails and we pull it out using this
715 * loop which just gets the next 512 bytes and then
716 * deletes the rest of the buffer contents.
720 if (DBufLength(&cptr->recvQ) < 510)
721 cptr->flags |= FLAGS_NONL;
723 DBufClear(&cptr->recvQ);
725 else if (CPTR_KILLED == client_dopacket(cptr, dolen))
732 static int on_write_unblocked(struct Client* cptr)
735 * ...room for writing, empty some queue then...
737 cptr->flags &= ~FLAGS_BLOCKED;
738 if (IsConnecting(cptr)) {
739 if (!completed_connection(cptr))
742 else if (cptr->listing && DBufLength(&cptr->sendQ) < 2048)
743 list_next_channels(cptr, 64);
749 * Select / Poll Read Algorithm for ircd
751 * We need to check the file descriptors for all the different types
752 * of things that use them, so check for reads on everything but connects
753 * and writes on connects and descriptors that are blocked
755 * for each (client in local) {
756 * if (not connecting)
758 * if (connecting or blocked)
763 * for each (client in local) {
764 * if (there are descriptors to check) {
765 * if (write activity)
772 * Note we must always process data read whether or not there has been
773 * read activity or file descriptors set, since data is buffered by the client.
782 #if defined(POLLMSG) && defined(POLLIN) && defined(POLLRDNORM)
783 # define POLLREADFLAGS (POLLMSG|POLLIN|POLLRDNORM)
785 # if defined(POLLIN) && defined(POLLRDNORM)
786 # define POLLREADFLAGS (POLLIN|POLLRDNORM)
789 # define POLLREADFLAGS POLLIN
791 # if defined(POLLRDNORM)
792 # define POLLREADFLAGS POLLRDNORM
798 #if defined(POLLOUT) && defined(POLLWRNORM)
799 #define POLLWRITEFLAGS (POLLOUT|POLLWRNORM)
801 # if defined(POLLOUT)
802 # define POLLWRITEFLAGS POLLOUT
804 # if defined(POLLWRNORM)
805 # define POLLWRITEFLAGS POLLWRNORM
811 #define POLLERRORS (POLLHUP|POLLERR)
813 #define POLLERRORS POLLERR
817 * NOTE: pfd and pfd_count are local variable names in read_message
819 #define PFD_SETR(xfd) \
820 do { CHECK_ADD_PFD(xfd) pfd->events |= POLLREADFLAGS; } while(0)
821 #define PFD_SETW(xfd) \
822 do { CHECK_ADD_PFD(xfd) pfd->events |= POLLWRITEFLAGS; } while(0)
824 #define CHECK_ADD_PFD(xfd) \
825 if (pfd->fd != xfd) { \
826 pfd = &poll_fds[pfd_count++]; \
827 poll_fds[pfd_count].fd = -1; \
833 * Check all connections for new connections and input data that is to be
834 * processed. Also check for connections with data queued and whether we can
837 * Don't ever use ZERO for `delay', unless you mean to poll and then
838 * you have to have sleep/wait somewhere else in the code.--msa
840 int read_message(time_t delay)
842 struct pollfd poll_fds[MAXCONNECTIONS + 1];
844 struct Listener* listener = 0;
845 struct AuthRequest* auth = 0;
846 struct AuthRequest* auth_next = 0;
847 struct UPing* uping = 0;
848 struct UPing* uping_next = 0;
849 time_t delay2 = delay;
856 struct pollfd* res_pfd;
857 struct pollfd* uping_pfd;
861 unsigned int timeout;
870 if (-1 < ResolverFileDescriptor) {
871 PFD_SETR(ResolverFileDescriptor);
874 if (-1 < UPingFileDescriptor) {
875 PFD_SETR(UPingFileDescriptor);
879 * add uping descriptors
881 for (uping = uping_begin(); uping; uping = uping_next) {
882 uping_next = uping->next;
885 if (uping->lastsent && CurrentTime > uping->timeout) {
889 uping->index = pfd_count;
894 * add auth file descriptors
896 for (auth = AuthPollList; auth; auth = auth->next) {
897 assert(-1 < auth->fd);
898 auth->index = pfd_count;
899 if (IsAuthConnect(auth))
905 * add listener file descriptors
907 for (listener = ListenerPollList; listener; listener = listener->next) {
908 assert(-1 < listener->fd);
910 * pfd_count is incremented by PFD_SETR so we need to save the
913 listener->index = pfd_count;
914 PFD_SETR(listener->fd);
917 for (i = HighestFd; -1 < i; --i) {
918 if ((cptr = LocalClientArray[i])) {
920 if (DBufLength(&cptr->recvQ))
922 if (DBufLength(&cptr->recvQ) < 4088 || IsServer(cptr)) {
925 if (DBufLength(&cptr->sendQ) || IsConnecting(cptr) ||
926 (cptr->listing && DBufLength(&cptr->sendQ) < 2048)) {
932 Debug((DEBUG_INFO, "poll: %d %d", delay, delay2));
934 timeout = (IRCD_MIN(delay2, delay)) * 1000;
936 nfds = poll(poll_fds, pfd_count, timeout);
938 CurrentTime = time(0);
944 report_error(POLL_ERROR_MSG, me.name, errno);
947 server_restart("too many poll errors");
949 CurrentTime = time(0);
952 if (uping_pfd && (uping_pfd->revents & (POLLREADFLAGS | POLLERRORS))) {
957 * check uping replies
959 for (uping = uping_begin(); uping; uping = uping_next) {
960 uping_next = uping->next;
962 assert(-1 < uping->index);
963 if (poll_fds[uping->index].revents) {
968 else if (CurrentTime > uping->lastsent) {
969 uping->lastsent = CurrentTime;
975 if (res_pfd && (res_pfd->revents & (POLLREADFLAGS | POLLERRORS))) {
982 for (auth = AuthPollList; auth; auth = auth_next) {
983 auth_next = auth->next;
986 * check for any event, we only ask for one at a time
988 if (poll_fds[i].revents) {
989 if (IsAuthConnect(auth))
990 send_auth_query(auth);
992 read_auth_reply(auth);
1000 for (listener = ListenerPollList; listener; listener = listener->next) {
1001 i = listener->index;
1002 if (poll_fds[i].revents) {
1003 accept_connection(listener);
1009 * i contains the next non-auth/non-listener index, since we put the
1010 * resolver, auth and listener, file descriptors in poll_fds first,
1011 * the very next one should be the start of the clients
1013 pfd = &poll_fds[++i];
1015 for ( ; (i < pfd_count); ++i, ++pfd) {
1016 if (!(cptr = LocalClientArray[pfd->fd]))
1018 read_ready = write_ready = 0;
1020 if (0 < nfds && pfd->revents) {
1023 read_ready = pfd->revents & POLLREADFLAGS;
1024 write_ready = pfd->revents & POLLWRITEFLAGS;
1026 if (pfd->revents & POLLERRORS) {
1027 if (pfd->events & POLLREADFLAGS)
1029 if (pfd->events & POLLWRITEFLAGS)
1034 if (!on_write_unblocked(cptr) || IsDead(cptr)) {
1035 const char* msg = (cptr->error) ? strerror(cptr->error) : LastDeadComment(cptr);
1037 msg = "Unknown error";
1038 exit_client(cptr, cptr, &me, (char*) msg);
1042 length = 1; /* for fall through case */
1043 if ((!NoNewLine(cptr) || read_ready) && !IsDead(cptr)) {
1044 if (CPTR_KILLED == (length = read_packet(cptr, read_ready)))
1048 /* Bullshit, why would we want to flush sockets while using non-blocking?
1049 * This uses > 4% cpu! --Run */
1051 flush_connections(poll_cptr[i]);
1054 const char* msg = (cptr->error) ? strerror(cptr->error) : LastDeadComment(cptr);
1056 msg = "Unknown error";
1057 exit_client(cptr, cptr, &me, (char*) msg);
1062 cptr->flags |= FLAGS_DEADSOCKET;
1064 * ...hmm, with non-blocking sockets we might get
1065 * here from quite valid reasons, although.. why
1066 * would select report "data available" when there
1067 * wasn't... So, this must be an error anyway... --msa
1068 * actually, EOF occurs when read() returns 0 and
1069 * in due course, select() returns that fd as ready
1070 * for reading even though it ends up being an EOF. -avalon
1072 Debug((DEBUG_ERROR, "READ ERROR: fd = %d %d %d", pfd->fd, errno, length));
1074 if ((IsServer(cptr) || IsHandshake(cptr)) && cptr->error == 0 && length == 0)
1075 exit_client_msg(cptr, cptr, &me, "Server %s closed the connection (%s)",
1076 cptr->name, cptr->serv->last_error_msg);
1078 const char* msg = (cptr->error) ? strerror(cptr->error) : "EOF from client";
1080 msg = "Unknown error";
1081 exit_client_msg(cptr, cptr, &me, "Read error to %s: %s",
1082 get_client_name(cptr, HIDE_IP), msg);
1087 #else /* USE_SELECT */
1090 * Check all connections for new connections and input data that is to be
1091 * processed. Also check for connections with data queued and whether we can
1094 * Don't ever use ZERO for `delay', unless you mean to poll and then
1095 * you have to have sleep/wait somewhere else in the code.--msa
1097 int read_message(time_t delay)
1099 struct Client* cptr;
1100 struct Listener* listener;
1101 struct AuthRequest* auth = 0;
1102 struct AuthRequest* auth_next = 0;
1103 struct UPing* uping;
1104 struct UPing* uping_next;
1106 struct timeval wait;
1107 time_t delay2 = delay;
1108 unsigned int usec = 0;
1119 FD_ZERO(&write_set);
1121 if (-1 < ResolverFileDescriptor)
1122 FD_SET(ResolverFileDescriptor, &read_set);
1123 if (-1 < UPingFileDescriptor)
1124 FD_SET(UPingFileDescriptor, &read_set);
1126 * set up uping file descriptors
1128 for (uping = uping_begin(); uping; uping = uping_next) {
1129 uping_next = uping->next;
1130 if (uping->active) {
1132 if (uping->lastsent && CurrentTime > ping->timeout) {
1136 assert(-1 < uping->fd);
1137 FD_SET(uping->fd, &read_set);
1141 * set auth file descriptors
1143 for (auth = AuthPollList; auth; auth = auth->next) {
1144 assert(-1 < auth->fd);
1145 if (IsAuthConnect(auth))
1146 FD_SET(auth->fd, &write_set);
1147 else /* if (IsAuthPending(auth)) */
1148 FD_SET(auth->fd, &read_set);
1151 * set listener file descriptors
1153 for (listener = ListenerPollList; listener; listener = listener->next) {
1154 assert(-1 < listener->fd);
1155 FD_SET(listener->fd, &read_set);
1158 for (i = HighestFd; i > -1; --i) {
1159 if ((cptr = LocalClientArray[i])) {
1160 if (DBufLength(&cptr->recvQ))
1162 if (DBufLength(&cptr->recvQ) < 4088 || IsServer(cptr))
1163 FD_SET(i, &read_set);
1164 if (DBufLength(&cptr->sendQ) || IsConnecting(cptr) ||
1165 (cptr->listing && DBufLength(&cptr->sendQ) < 2048))
1166 FD_SET(i, &write_set);
1170 wait.tv_sec = IRCD_MIN(delay2, delay);
1171 wait.tv_usec = usec;
1173 Debug((DEBUG_INFO, "select: %d %d", delay, delay2));
1175 nfds = select(FD_SETSIZE, &read_set, &write_set, 0, &wait);
1177 CurrentTime = time(0);
1184 report_error(SELECT_ERROR_MSG, me.name, errno);
1186 server_restart("too many select errors");
1188 CurrentTime = time(0);
1191 if (-1 < UPingFileDescriptor && FD_ISSET(UPingFileDescriptor, &read_set)) {
1195 for (uping = uping_begin(); uping; uping = uping_next) {
1196 uping_next = uping->next;
1197 if (uping->active) {
1198 assert(-1 < uping->fd);
1199 if (FD_ISSET(uping->fd, &read_set)) {
1204 else if (CurrentTime > uping->lastsent) {
1205 uping->lastsent = CurrentTime;
1210 if (-1 < ResolverFileDescriptor && FD_ISSET(ResolverFileDescriptor, &read_set)) {
1215 * Check fd sets for the auth fd's (if set and valid!) first
1216 * because these can not be processed using the normal loops below.
1219 for (auth = AuthPollList; auth; auth = auth_next) {
1220 auth_next = auth->next;
1221 assert(-1 < auth->fd);
1222 if (IsAuthConnect(auth) && FD_ISSET(auth->fd, &write_set)) {
1223 send_auth_query(auth);
1227 else if (FD_ISSET(auth->fd, &read_set)) {
1228 read_auth_reply(auth);
1234 * next accept connections from active listeners
1236 for (listener = ListenerPollList; listener; listener = listener->next) {
1237 assert(-1 < listener->fd);
1238 if (0 < nfds && FD_ISSET(listener->fd, &read_set))
1239 accept_connection(listener);
1242 for (i = HighestFd; -1 < i; --i) {
1243 if (!(cptr = LocalClientArray[i]))
1247 if (FD_ISSET(i, &write_set)) {
1249 if (!on_write_unblocked(cptr) || IsDead(cptr)) {
1250 const char* msg = (cptr->error) ? strerror(cptr->error) : LastDeadComment(cptr);
1252 msg = "Unknown error";
1253 if (FD_ISSET(i, &read_set))
1255 exit_client(cptr, cptr, &me, msg);
1259 if ((read_ready = FD_ISSET(i, &read_set)))
1262 length = 1; /* for fall through case */
1263 if ((!NoNewLine(cptr) || read_ready) && !IsDead(cptr)) {
1264 if (CPTR_KILLED == (length = read_packet(cptr, read_ready)))
1268 /* Bullshit, why would we want to flush sockets while using non-blocking?
1269 * This uses > 4% cpu! --Run */
1271 flush_connections(LocalClientArray[i]);
1274 const char* msg = (cptr->error) ? strerror(cptr->error) : LastDeadComment(cptr);
1276 msg = "Unknown error";
1277 exit_client(cptr, cptr, &me, msg);
1284 * ...hmm, with non-blocking sockets we might get
1285 * here from quite valid reasons, although.. why
1286 * would select report "data available" when there
1287 * wasn't... So, this must be an error anyway... --msa
1288 * actually, EOF occurs when read() returns 0 and
1289 * in due course, select() returns that fd as ready
1290 * for reading even though it ends up being an EOF. -avalon
1292 Debug((DEBUG_ERROR, "READ ERROR: fd = %d %d %d", i, cptr->error, length));
1294 if ((IsServer(cptr) || IsHandshake(cptr)) && cptr->error == 0 && length == 0)
1295 exit_client_msg(cptr, cptr, &me, "Server %s closed the connection (%s)",
1296 cptr->name, cptr->serv->last_error_msg);
1298 const char* msg = (cptr->error) ? strerror(cptr->error) : "EOF from client";
1300 msg = "Unknown error";
1301 exit_client_msg(cptr, cptr, &me, "Read error to %s: %s",
1302 get_client_name(cptr, HIDE_IP), msg);
1308 #endif /* USE_SELECT */
1311 * connect_server - start or complete a connection to another server
1312 * returns true (1) if successful, false (0) otherwise
1314 * aconf must point to a valid C:line
1315 * m_connect calls this with a valid by client and a null reply
1316 * try_connections calls this with a null by client, and a null reply
1317 * connect_dns_callback call this with a null by client, and a valid reply
1319 * XXX - if this comes from an m_connect message and a dns query needs to
1320 * be done, we loose the information about who started the connection and
1321 * it's considered an auto connect.
1323 int connect_server(struct ConfItem* aconf, struct Client* by,
1324 struct DNSReply* reply)
1326 struct Client* cptr = 0;
1329 if (aconf->dns_pending) {
1330 sendto_ops("Server %s connect DNS pending");
1333 Debug((DEBUG_NOTICE, "Connect to %s[@%s]", aconf->name,
1334 ircd_ntoa((const char*) &aconf->ipnum)));
1336 if ((cptr = FindClient(aconf->name))) {
1337 if (IsServer(cptr) || IsMe(cptr)) {
1338 sendto_ops("Server %s already present from %s",
1339 aconf->name, cptr->from->name);
1340 if (by && IsUser(by) && !MyUser(by)) {
1341 sendto_one(by, "%s NOTICE %s%s :Server %s already present from %s",
1342 NumServ(&me), NumNick(by), aconf->name, cptr->from->name);
1346 else if (IsHandshake(cptr) || IsConnecting(cptr)) {
1347 if (by && IsUser(by)) {
1349 sendto_one(by, ":%s NOTICE %s :Connection to %s already in progress",
1350 me.name, by->name, cptr->name);
1352 sendto_one(by, "%s NOTICE %s%s :Connection to %s already in progress",
1353 NumServ(&me), NumNick(by), cptr->name);
1359 * If we dont know the IP# for this host and itis a hostname and
1360 * not a ip# string, then try and find the appropriate host record.
1362 if (INADDR_NONE == aconf->ipnum.s_addr) {
1363 char buf[HOSTLEN + 1];
1365 if (INADDR_NONE == (aconf->ipnum.s_addr = inet_addr(aconf->host))) {
1366 struct DNSQuery query;
1369 query.callback = connect_dns_callback;
1370 host_from_uh(buf, aconf->host, HOSTLEN);
1371 buf[HOSTLEN] = '\0';
1373 reply = gethost_byname(buf, &query);
1376 aconf->dns_pending = 1;
1379 memcpy(&aconf->ipnum, reply->hp->h_addr, sizeof(struct in_addr));
1382 cptr = make_client(NULL, STAT_UNKNOWN_SERVER);
1385 cptr->dns_reply = reply;
1388 * Copy these in so we have something for error detection.
1390 ircd_strncpy(cptr->name, aconf->name, HOSTLEN);
1391 ircd_strncpy(cptr->sockhost, aconf->host, HOSTLEN);
1394 * Attach config entries to client here rather than in
1395 * completed_connection. This to avoid null pointer references
1397 attach_confs_byhost(cptr, aconf->host, CONF_SERVER);
1399 if (!find_conf_byhost(cptr->confs, aconf->host, CONF_SERVER)) {
1400 sendto_ops("Host %s is not enabled for connecting: no C-line", aconf->name);
1401 if (by && IsUser(by) && !MyUser(by)) {
1402 sendto_one(by, "%s NOTICE %s%s :Connect to host %s failed: no C-line",
1403 NumServ(&me), NumNick(by), aconf->name);
1405 det_confs_butmask(cptr, 0);
1410 * attempt to connect to the server in the conf line
1412 if (!connect_inet(aconf, cptr)) {
1413 if (by && IsUser(by) && !MyUser(by)) {
1414 sendto_one(by, "%s NOTICE %s%s :Couldn't connect to %s",
1415 NumServ(&me), NumNick(by), cptr->name);
1417 det_confs_butmask(cptr, 0);
1422 * NOTE: if we're here we have a valid C:Line and the client should
1423 * have started the connection and stored the remote address/port and
1424 * ip address name in itself
1426 * The socket has been connected or connect is in progress.
1429 if (by && IsUser(by)) {
1430 sprintf_irc(cptr->serv->by, "%s%s", NumNick(by));
1431 assert(0 == cptr->serv->user);
1432 cptr->serv->user = by->user;
1436 *cptr->serv->by = '\0';
1437 /* strcpy(cptr->serv->by, "Auto"); */
1439 cptr->serv->up = &me;
1440 SetConnecting(cptr);
1442 if (cptr->fd > HighestFd)
1443 HighestFd = cptr->fd;
1444 LocalClientArray[cptr->fd] = cptr;
1446 Count_newunknown(UserStats);
1447 add_client_to_list(cptr);
1449 nextping = CurrentTime;
1455 * Setup local socket structure to use for binding to.
1457 void init_virtual_host(const struct ConfItem* conf)
1461 memset(&VirtualHost, 0, sizeof(VirtualHost));
1462 VirtualHost.sin_family = AF_INET;
1463 VirtualHost.sin_addr.s_addr = INADDR_ANY;
1465 if (EmptyString(conf->passwd) || 0 == strcmp(conf->passwd, "*"))
1467 VirtualHost.sin_addr.s_addr = inet_addr(conf->passwd);
1469 if (INADDR_NONE == VirtualHost.sin_addr.s_addr)
1470 VirtualHost.sin_addr.s_addr = INADDR_ANY;
1474 * Find the real hostname for the host running the server (or one which
1475 * matches the server's name) and its primary IP#. Hostname is stored
1476 * in the client structure passed as a pointer.
1478 int init_server_identity()
1480 struct ConfItem* conf = find_me();
1482 if (!conf || EmptyString(conf->host))
1485 ircd_strncpy(me.name, conf->host, HOSTLEN);
1487 init_virtual_host(conf);