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_reply.h"
31 #include "ircd_string.h"
40 #include "querycmds.h"
48 #include "sprintf_irc.h"
55 #include <arpa/inet.h>
56 #include <arpa/nameser.h>
65 #include <sys/ioctl.h>
66 #include <sys/socket.h>
68 #include <sys/utsname.h>
76 #define INADDR_NONE 0xffffffff
79 struct Client* LocalClientArray[MAXCONNECTIONS];
81 struct sockaddr_in VirtualHost;
82 static char readbuf[SERVER_TCP_WINDOW];
85 * report_error text constants
87 const char* const ACCEPT_ERROR_MSG = "error accepting connection for %s: %s";
88 const char* const BIND_ERROR_MSG = "bind error for %s: %s";
89 const char* const CONNECT_ERROR_MSG = "connect to host %s failed: %s";
90 const char* const CONNLIMIT_ERROR_MSG = "connect limit exceeded for %s: %s";
91 const char* const LISTEN_ERROR_MSG = "listen error for %s: %s";
92 const char* const NONB_ERROR_MSG = "error setting non-blocking for %s: %s";
93 const char* const PEERNAME_ERROR_MSG = "getpeername failed for %s: %s";
94 const char* const POLL_ERROR_MSG = "poll error for %s: %s";
95 const char* const REUSEADDR_ERROR_MSG = "error setting SO_REUSEADDR for %s: %s";
96 const char* const SELECT_ERROR_MSG = "select error for %s: %s";
97 const char* const SETBUFS_ERROR_MSG = "error setting buffer size for %s: %s";
98 const char* const SOCKET_ERROR_MSG = "error creating socket for %s: %s";
105 #ifndef NOFLOODCONTROL
106 #define NOFLOODCONTROL
110 #if !defined(USE_POLL)
111 #if FD_SETSIZE < (MAXCONNECTIONS + 4)
115 * All operating systems work when MAXCONNECTIONS <= 252.
116 * Most operating systems work when MAXCONNECTIONS <= 1020 and FD_SETSIZE is
117 * updated correctly in the system headers (on BSD systems our sys.h has
118 * defined FD_SETSIZE to MAXCONNECTIONS+4 before including the system's headers
119 * but sys/types.h might have abruptly redefined it so the check is still
120 * done), you might already need to recompile your kernel.
121 * For larger FD_SETSIZE your milage may vary (kernel patches may be needed).
122 * The check is _NOT_ done if we will not use FD_SETS at all (USE_POLL)
124 #error "FD_SETSIZE is too small or MAXCONNECTIONS too large."
130 * Cannot use perror() within daemon. stderr is closed in
131 * ircd and cannot be used. And, worse yet, it might have
132 * been reassigned to a normal connection...
138 * This a replacement for perror(). Record error to log and
139 * also send a copy to all *LOCAL* opers online.
141 * text is a *format* string for outputting error. It must
142 * contain only two '%s', the first will be replaced
143 * by the sockhost from the cptr, and the latter will
144 * be taken from sys_errlist[errno].
146 * cptr if not NULL, is the *LOCAL* client associated with
149 void report_error(const char* text, const char* who, int err)
151 static time_t last_notice = 0;
152 int errtmp = errno; /* debug may change 'errno' */
153 const char* errmsg = (err) ? strerror(err) : "";
155 errmsg = "Unknown error";
157 if (EmptyString(who))
160 if (last_notice + 20 < CurrentTime) {
162 * pace error messages so opers don't get flooded by transients
164 sendto_opmask_butone(0, SNO_OLDSNO, text, who, errmsg);
165 last_notice = CurrentTime;
167 ircd_log(L_ERROR, text, who, errmsg);
173 * connect_dns_callback - called when resolver query finishes
174 * if the query resulted in a successful search, reply will contain
175 * a non-null pointer, otherwise reply will be null.
176 * if successful start the connection, otherwise notify opers
178 static void connect_dns_callback(void* vptr, struct DNSReply* reply)
180 struct ConfItem* aconf = (struct ConfItem*) vptr;
181 aconf->dns_pending = 0;
183 memcpy(&aconf->ipnum, reply->hp->h_addr, sizeof(struct in_addr));
184 connect_server(aconf, 0, reply);
187 sendto_opmask_butone(0, SNO_OLDSNO, "Connect to %s failed: host lookup",
192 * close_connections - closes all connections
193 * close stderr if specified
195 void close_connections(int close_stderr)
202 for (i = 3; i < MAXCONNECTIONS; ++i)
207 * init_connection_limits - initialize process fd limit to
210 int init_connection_limits(void)
212 int limit = os_set_fdlimit(MAXCONNECTIONS);
216 fprintf(stderr, "error setting max fd's to %d\n", limit);
218 else if (limit > 0) {
219 fprintf(stderr, "ircd fd table too big\nHard Limit: %d IRC max: %d\n",
220 limit, MAXCONNECTIONS);
221 fprintf(stderr, "set MAXCONNECTIONS to a smaller value");
227 * connect_inet - set up address and port and make a connection
229 static int connect_inet(struct ConfItem* aconf, struct Client* cptr)
231 static struct sockaddr_in sin;
235 * Might as well get sockhost from here, the connection is attempted
236 * with it so if it fails its useless.
238 cptr->fd = socket(AF_INET, SOCK_STREAM, 0);
239 if (-1 == cptr->fd) {
241 report_error(SOCKET_ERROR_MSG, cptr->name, errno);
244 if (cptr->fd >= MAXCLIENTS) {
245 report_error(CONNLIMIT_ERROR_MSG, cptr->name, 0);
251 * Bind to a local IP# (with unknown port - let unix decide) so
252 * we have some chance of knowing the IP# that gets used for a host
253 * with more than one IP#.
255 * No we don't bind it, not all OS's can handle connecting with
256 * an already bound socket, different ip# might occur anyway
257 * leading to a freezing select() on this side for some time.
258 * I had this on my Linux 1.1.88 --Run
262 * No, we do bind it if we have virtual host support. If we don't
263 * explicitly bind it, it will default to IN_ADDR_ANY and we lose
264 * due to the other server not allowing our base IP --smg
266 if (bind(cptr->fd, (struct sockaddr*) &VirtualHost, sizeof(VirtualHost))) {
267 report_error(BIND_ERROR_MSG, cptr->name, errno);
272 memset(&sin, 0, sizeof(sin));
273 sin.sin_family = AF_INET;
274 sin.sin_addr.s_addr = aconf->ipnum.s_addr;
275 sin.sin_port = htons(aconf->port);
277 * save connection info in client
279 cptr->ip.s_addr = aconf->ipnum.s_addr;
280 cptr->port = aconf->port;
281 ircd_ntoa_r(cptr->sock_ip, (const char*) &cptr->ip);
283 * we want a big buffer for server connections
285 if (!os_set_sockbufs(cptr->fd, SERVER_TCP_WINDOW)) {
287 report_error(SETBUFS_ERROR_MSG, cptr->name, errno);
291 * ALWAYS set sockets non-blocking
293 if (!os_set_nonblocking(cptr->fd)) {
295 report_error(NONB_ERROR_MSG, cptr->name, errno);
298 if (!os_connect_nonb(cptr->fd, &sin)) {
300 report_error(CONNECT_ERROR_MSG, cptr->name, errno);
308 * Attempt to send a sequence of bytes to the connection.
311 * < 0 Some fatal error occurred, (but not EWOULDBLOCK).
312 * This return is a request to close the socket and
315 * >= 0 No real error occurred, returns the number of
316 * bytes actually transferred. EWOULDBLOCK and other
317 * possibly similar conditions should be mapped to
318 * zero return. Upper level routine will have to
319 * decide what to do with those unwritten bytes...
321 * *NOTE* alarm calls have been preserved, so this should
322 * work equally well whether blocking or non-blocking
325 * We don't use blocking anymore, that is impossible with the
326 * net.loads today anyway. Commented out the alarms to save cpu.
329 unsigned int deliver_it(struct Client *cptr, const char *str, unsigned int len)
331 unsigned int bytes_written = 0;
334 switch (os_send_nonb(cptr->fd, str, len, &bytes_written)) {
336 cptr->flags &= ~FLAGS_BLOCKED;
338 cptr->sendB += bytes_written;
339 me.sendB += bytes_written;
340 if (cptr->sendB > 1023) {
341 cptr->sendK += (cptr->sendB >> 10);
342 cptr->sendB &= 0x03ff; /* 2^10 = 1024, 3ff = 1023 */
344 if (me.sendB > 1023) {
345 me.sendK += (me.sendB >> 10);
348 if (bytes_written < len)
349 cptr->flags |= FLAGS_BLOCKED;
352 cptr->flags |= FLAGS_BLOCKED;
356 cptr->flags |= FLAGS_DEADSOCKET;
359 return bytes_written;
363 void release_dns_reply(struct Client* cptr)
366 assert(MyConnect(cptr));
368 if (cptr->dns_reply) {
369 assert(0 < cptr->dns_reply->ref_count);
370 --cptr->dns_reply->ref_count;
376 * completed_connection
378 * Complete non-blocking connect()-sequence. Check access and
379 * terminate connection, if trouble detected.
381 * Return TRUE, if successfully completed
382 * FALSE, if failed and ClientExit
384 static int completed_connection(struct Client* cptr)
386 struct ConfItem *aconf;
388 struct Client *acptr;
394 * get the socket status from the fd first to check if
395 * connection actually succeeded
397 if ((cptr->error = os_get_sockerr(cptr->fd))) {
398 const char* msg = strerror(cptr->error);
400 msg = "Unknown error";
401 sendto_opmask_butone(0, SNO_OLDSNO, "Connection failed to %s: %s",
405 if (!(aconf = find_conf_byname(cptr->confs, cptr->name, CONF_SERVER))) {
406 sendto_opmask_butone(0, SNO_OLDSNO, "Lost Server Line for %s", cptr->name);
410 if (!EmptyString(aconf->passwd))
411 sendrawto_one(cptr, MSG_PASS " :%s", aconf->passwd);
414 /* dead code, already done in connect_server */
418 * Create a unique timestamp
421 for (i = HighestFd; i > -1; --i) {
422 if ((acptr = LocalClientArray[i]) &&
423 (IsServer(acptr) || IsHandshake(acptr))) {
424 if (acptr->serv->timestamp >= newts)
425 newts = acptr->serv->timestamp + 1;
428 assert(0 != cptr->serv);
430 cptr->serv->timestamp = newts;
433 * Make us timeout after twice the timeout for DNS look ups
435 cptr->lasttime = CurrentTime;
436 cptr->flags |= FLAGS_PINGSENT;
438 sendrawto_one(cptr, MSG_SERVER " %s 1 %Tu %Tu J%s %s%s :%s",
439 me.name, me.serv->timestamp, newts, MAJOR_PROTOCOL,
440 NumServCap(&me), me.info);
442 return (IsDead(cptr)) ? 0 : 1;
448 * Close the physical connection. This function must make
449 * MyConnect(cptr) == FALSE, and set cptr->from == NULL.
451 void close_connection(struct Client *cptr)
453 struct ConfItem* aconf;
455 if (IsServer(cptr)) {
456 ServerStats->is_sv++;
457 ServerStats->is_sbs += cptr->sendB;
458 ServerStats->is_sbr += cptr->receiveB;
459 ServerStats->is_sks += cptr->sendK;
460 ServerStats->is_skr += cptr->receiveK;
461 ServerStats->is_sti += CurrentTime - cptr->firsttime;
462 if (ServerStats->is_sbs > 1023) {
463 ServerStats->is_sks += (ServerStats->is_sbs >> 10);
464 ServerStats->is_sbs &= 0x3ff;
466 if (ServerStats->is_sbr > 1023) {
467 ServerStats->is_skr += (ServerStats->is_sbr >> 10);
468 ServerStats->is_sbr &= 0x3ff;
471 * If the connection has been up for a long amount of time, schedule
472 * a 'quick' reconnect, else reset the next-connect cycle.
474 if ((aconf = find_conf_exact(cptr->name, 0, cptr->sockhost, CONF_SERVER))) {
476 * Reschedule a faster reconnect, if this was a automaticly
477 * connected configuration entry. (Note that if we have had
478 * a rehash in between, the status has been changed to
479 * CONF_ILLEGAL). But only do this if it was a "good" link.
481 aconf->hold = CurrentTime;
482 aconf->hold += (aconf->hold - cptr->since > HANGONGOODLINK) ?
483 HANGONRETRYDELAY : ConfConFreq(aconf);
484 if (nextconnect > aconf->hold)
485 nextconnect = aconf->hold;
488 else if (IsUser(cptr)) {
489 ServerStats->is_cl++;
490 ServerStats->is_cbs += cptr->sendB;
491 ServerStats->is_cbr += cptr->receiveB;
492 ServerStats->is_cks += cptr->sendK;
493 ServerStats->is_ckr += cptr->receiveK;
494 ServerStats->is_cti += CurrentTime - cptr->firsttime;
495 if (ServerStats->is_cbs > 1023) {
496 ServerStats->is_cks += (ServerStats->is_cbs >> 10);
497 ServerStats->is_cbs &= 0x3ff;
499 if (ServerStats->is_cbr > 1023) {
500 ServerStats->is_ckr += (ServerStats->is_cbr >> 10);
501 ServerStats->is_cbr &= 0x3ff;
505 ServerStats->is_ni++;
508 flush_connections(cptr);
509 LocalClientArray[cptr->fd] = 0;
513 cptr->flags |= FLAGS_DEADSOCKET;
515 DBufClear(&cptr->sendQ);
516 DBufClear(&cptr->recvQ);
517 memset(cptr->passwd, 0, sizeof(cptr->passwd));
518 set_snomask(cptr, 0, SNO_SET);
520 det_confs_butmask(cptr, 0);
522 if (cptr->listener) {
523 release_listener(cptr->listener);
527 for ( ; HighestFd > 0; --HighestFd) {
528 if (LocalClientArray[HighestFd])
533 int net_close_unregistered_connections(struct Client* source)
540 for (i = HighestFd; i > 0; --i) {
541 if ((cptr = LocalClientArray[i]) && !IsRegistered(cptr)) {
542 send_reply(source, RPL_CLOSING, get_client_name(source, HIDE_IP));
543 exit_client(source, cptr, &me, "Oper Closing");
551 * Creates a client which has just connected to us on the given fd.
552 * The sockhost field is initialized with the ip# of the host.
553 * The client is not added to the linked list of clients, it is
554 * passed off to the auth handler for dns and ident queries.
556 void add_connection(struct Listener* listener, int fd)
558 struct sockaddr_in addr;
559 struct Client* new_client;
560 time_t next_target = 0;
561 const char* const throttle_message =
562 "ERROR: Your host is trying to (re)connect too fast -- throttled\r\n";
563 /* 12345678901234567890123456789012345679012345678901234567890123456 */
565 assert(0 != listener);
567 * Removed preliminary access check. Full check is performed in
568 * m_server and m_user instead. Also connection time out help to
569 * get rid of unwanted connections.
571 if (!os_get_peername(fd, &addr) || !os_set_nonblocking(fd)) {
572 ++ServerStats->is_ref;
577 * Add this local client to the IPcheck registry.
578 * If it is a connection to a user port and if the site has been throttled,
581 if (!IPcheck_local_connect(addr.sin_addr, &next_target) && !listener->server) {
584 snprintf(buff,"\n%s [%i connections active]\n",
586 IPcheck_nr(addr.sin_addr));
588 send(fd,buff,strlen(buff));
591 * strlen(throttle_message) == 66
593 * strlen is slow, so we use the constant here.
595 send(fd, throttle_message, 66, 0);
598 ++ServerStats->is_ref;
602 new_client = make_client(0,
603 (listener->server) ? STAT_UNKNOWN_SERVER : STAT_UNKNOWN_USER);
605 * Copy ascii address to 'sockhost' just in case. Then we
606 * have something valid to put into error messages...
608 ircd_ntoa_r(new_client->sock_ip, (const char*) &addr.sin_addr);
609 strcpy(new_client->sockhost, new_client->sock_ip);
610 new_client->ip.s_addr = addr.sin_addr.s_addr;
611 new_client->port = ntohs(addr.sin_port);
614 new_client->nexttarget = next_target;
618 if (!listener->server)
619 SetIPChecked(new_client);
620 new_client->listener = listener;
621 ++listener->ref_count;
623 Count_newunknown(UserStats);
625 * if we've made it this far we can put the client on the auth query pile
627 start_auth(new_client);
633 * Read a 'packet' of data from a connection and process it. Read in 8k
634 * chunks to give a better performance rating (for server connections).
635 * Do some tricky stuff for client connections to make sure they don't do
636 * any flooding >:-) -avalon
638 static int read_packet(struct Client *cptr, int socket_ready)
640 unsigned int dolen = 0;
641 unsigned int length = 0;
643 if (socket_ready && !(IsUser(cptr) && DBufLength(&cptr->recvQ) > CLIENT_FLOOD)) {
644 switch (os_recv_nonb(cptr->fd, readbuf, sizeof(readbuf), &length)) {
647 cptr->lasttime = CurrentTime;
648 if (cptr->lasttime > cptr->since)
649 cptr->since = cptr->lasttime;
650 cptr->flags &= ~(FLAGS_PINGSENT | FLAGS_NONL);
657 /* cptr->flags |= FLAGS_DEADSOCKET; */
663 * For server connections, we process as many as we can without
664 * worrying about the time of day or anything :)
666 if (length > 0 && IsServer(cptr)) {
667 return server_dopacket(cptr, readbuf, length);
671 * Before we even think of parsing what we just read, stick
672 * it on the end of the receive queue and do it when its
675 if (length > 0 && 0 == dbuf_put(&cptr->recvQ, readbuf, length)) {
676 return exit_client(cptr, cptr, &me, "dbuf_put fail");
678 #ifndef NOFLOODCONTROL
680 * XXX - cptr will always be a user or unregistered
682 if (IsUser(cptr) && DBufLength(&cptr->recvQ) > CLIENT_FLOOD)
683 return exit_client(cptr, cptr, &me, "Excess Flood");
685 while (DBufLength(&cptr->recvQ) && !NoNewLine(cptr) &&
686 (IsTrusted(cptr) || cptr->since - CurrentTime < 10))
688 while (DBufLength(&cptr->recvQ) && !NoNewLine(cptr))
692 * If it has become registered as a Server
693 * then skip the per-message parsing below.
695 if (IsServer(cptr)) {
696 dolen = dbuf_get(&cptr->recvQ, readbuf, sizeof(readbuf));
697 return (dolen) ? server_dopacket(cptr, readbuf, dolen) : 1;
699 dolen = dbuf_getmsg(&cptr->recvQ, cptr->buffer, BUFSIZE);
701 * Devious looking...whats it do ? well..if a client
702 * sends a *long* message without any CR or LF, then
703 * dbuf_getmsg fails and we pull it out using this
704 * loop which just gets the next 512 bytes and then
705 * deletes the rest of the buffer contents.
709 if (DBufLength(&cptr->recvQ) < 510)
710 cptr->flags |= FLAGS_NONL;
712 DBufClear(&cptr->recvQ);
714 else if (CPTR_KILLED == client_dopacket(cptr, dolen))
721 static int on_write_unblocked(struct Client* cptr)
724 * ...room for writing, empty some queue then...
726 cptr->flags &= ~FLAGS_BLOCKED;
727 if (IsConnecting(cptr)) {
728 if (!completed_connection(cptr))
731 else if (cptr->listing && DBufLength(&cptr->sendQ) < 2048)
732 list_next_channels(cptr, 64);
738 * Select / Poll Read Algorithm for ircd
740 * We need to check the file descriptors for all the different types
741 * of things that use them, so check for reads on everything but connects
742 * and writes on connects and descriptors that are blocked
744 * for each (client in local) {
745 * if (not connecting)
747 * if (connecting or blocked)
752 * for each (client in local) {
753 * if (there are descriptors to check) {
754 * if (write activity)
761 * Note we must always process data read whether or not there has been
762 * read activity or file descriptors set, since data is buffered by the client.
771 #if defined(POLLMSG) && defined(POLLIN) && defined(POLLRDNORM)
772 # define POLLREADFLAGS (POLLMSG|POLLIN|POLLRDNORM)
774 # if defined(POLLIN) && defined(POLLRDNORM)
775 # define POLLREADFLAGS (POLLIN|POLLRDNORM)
778 # define POLLREADFLAGS POLLIN
780 # if defined(POLLRDNORM)
781 # define POLLREADFLAGS POLLRDNORM
787 #if defined(POLLOUT) && defined(POLLWRNORM)
788 #define POLLWRITEFLAGS (POLLOUT|POLLWRNORM)
790 # if defined(POLLOUT)
791 # define POLLWRITEFLAGS POLLOUT
793 # if defined(POLLWRNORM)
794 # define POLLWRITEFLAGS POLLWRNORM
800 #define POLLERRORS (POLLHUP|POLLERR)
802 #define POLLERRORS POLLERR
806 * NOTE: pfd and pfd_count are local variable names in read_message
808 #define PFD_SETR(xfd) \
809 do { CHECK_ADD_PFD(xfd) pfd->events |= POLLREADFLAGS; } while(0)
810 #define PFD_SETW(xfd) \
811 do { CHECK_ADD_PFD(xfd) pfd->events |= POLLWRITEFLAGS; } while(0)
813 #define CHECK_ADD_PFD(xfd) \
814 if (pfd->fd != xfd) { \
815 pfd = &poll_fds[pfd_count++]; \
816 poll_fds[pfd_count].fd = -1; \
822 * Check all connections for new connections and input data that is to be
823 * processed. Also check for connections with data queued and whether we can
826 * Don't ever use ZERO for `delay', unless you mean to poll and then
827 * you have to have sleep/wait somewhere else in the code.--msa
829 int read_message(time_t delay)
831 struct pollfd poll_fds[MAXCONNECTIONS + 1];
833 struct Listener* listener = 0;
834 struct AuthRequest* auth = 0;
835 struct AuthRequest* auth_next = 0;
836 struct UPing* uping = 0;
837 struct UPing* uping_next = 0;
838 time_t delay2 = delay;
845 struct pollfd* res_pfd;
846 struct pollfd* uping_pfd;
850 unsigned int timeout;
859 if (-1 < ResolverFileDescriptor) {
860 PFD_SETR(ResolverFileDescriptor);
863 if (-1 < UPingFileDescriptor) {
864 PFD_SETR(UPingFileDescriptor);
868 * add uping descriptors
870 for (uping = uping_begin(); uping; uping = uping_next) {
871 uping_next = uping->next;
874 if (uping->lastsent && CurrentTime > uping->timeout) {
878 uping->index = pfd_count;
883 * add auth file descriptors
885 for (auth = AuthPollList; auth; auth = auth->next) {
886 assert(-1 < auth->fd);
887 auth->index = pfd_count;
888 if (IsAuthConnect(auth))
894 * add listener file descriptors
896 for (listener = ListenerPollList; listener; listener = listener->next) {
897 assert(-1 < listener->fd);
899 * pfd_count is incremented by PFD_SETR so we need to save the
902 listener->index = pfd_count;
903 PFD_SETR(listener->fd);
906 for (i = HighestFd; -1 < i; --i) {
907 if ((cptr = LocalClientArray[i])) {
909 if (DBufLength(&cptr->recvQ))
911 if (DBufLength(&cptr->recvQ) < 4088 || IsServer(cptr)) {
914 if (DBufLength(&cptr->sendQ) || IsConnecting(cptr) ||
915 (cptr->listing && DBufLength(&cptr->sendQ) < 2048)) {
921 Debug((DEBUG_INFO, "poll: %d %d", delay, delay2));
923 timeout = (IRCD_MIN(delay2, delay)) * 1000;
925 nfds = poll(poll_fds, pfd_count, timeout);
927 CurrentTime = time(0);
933 report_error(POLL_ERROR_MSG, me.name, errno);
936 server_restart("too many poll errors");
938 CurrentTime = time(0);
941 if (uping_pfd && (uping_pfd->revents & (POLLREADFLAGS | POLLERRORS))) {
946 * check uping replies
948 for (uping = uping_begin(); uping; uping = uping_next) {
949 uping_next = uping->next;
951 assert(-1 < uping->index);
952 if (poll_fds[uping->index].revents) {
957 else if (CurrentTime > uping->lastsent) {
958 uping->lastsent = CurrentTime;
964 if (res_pfd && (res_pfd->revents & (POLLREADFLAGS | POLLERRORS))) {
971 for (auth = AuthPollList; auth; auth = auth_next) {
972 auth_next = auth->next;
975 * check for any event, we only ask for one at a time
977 if (poll_fds[i].revents) {
978 if (IsAuthConnect(auth))
979 send_auth_query(auth);
981 read_auth_reply(auth);
989 for (listener = ListenerPollList; listener; listener = listener->next) {
991 if (poll_fds[i].revents) {
992 accept_connection(listener);
998 * i contains the next non-auth/non-listener index, since we put the
999 * resolver, auth and listener, file descriptors in poll_fds first,
1000 * the very next one should be the start of the clients
1002 pfd = &poll_fds[++i];
1004 for ( ; (i < pfd_count); ++i, ++pfd) {
1005 if (!(cptr = LocalClientArray[pfd->fd]))
1007 read_ready = write_ready = 0;
1009 if (0 < nfds && pfd->revents) {
1012 read_ready = pfd->revents & POLLREADFLAGS;
1013 write_ready = pfd->revents & POLLWRITEFLAGS;
1015 if (pfd->revents & POLLERRORS) {
1016 if (pfd->events & POLLREADFLAGS)
1018 if (pfd->events & POLLWRITEFLAGS)
1023 if (!on_write_unblocked(cptr) || IsDead(cptr)) {
1024 const char* msg = (cptr->error) ? strerror(cptr->error) : cptr->info;
1026 msg = "Unknown error";
1027 exit_client(cptr, cptr, &me, msg);
1031 length = 1; /* for fall through case */
1032 if ((!NoNewLine(cptr) || read_ready) && !IsDead(cptr)) {
1033 if (CPTR_KILLED == (length = read_packet(cptr, read_ready)))
1037 /* Bullshit, why would we want to flush sockets while using non-blocking?
1038 * This uses > 4% cpu! --Run */
1040 flush_connections(poll_cptr[i]);
1043 const char* msg = (cptr->error) ? strerror(cptr->error) : cptr->info;
1045 msg = "Unknown error";
1046 exit_client(cptr, cptr, &me, (char*) msg);
1051 cptr->flags |= FLAGS_DEADSOCKET;
1053 * ...hmm, with non-blocking sockets we might get
1054 * here from quite valid reasons, although.. why
1055 * would select report "data available" when there
1056 * wasn't... So, this must be an error anyway... --msa
1057 * actually, EOF occurs when read() returns 0 and
1058 * in due course, select() returns that fd as ready
1059 * for reading even though it ends up being an EOF. -avalon
1061 Debug((DEBUG_ERROR, "READ ERROR: fd = %d %d %d", pfd->fd, errno, length));
1063 if ((IsServer(cptr) || IsHandshake(cptr)) && cptr->error == 0 && length == 0)
1064 exit_client_msg(cptr, cptr, &me, "Server %s closed the connection (%s)",
1065 cptr->name, cptr->serv->last_error_msg);
1067 const char* msg = (cptr->error) ? strerror(cptr->error) : "EOF from client";
1069 msg = "Unknown error";
1070 exit_client_msg(cptr, cptr, &me, "Read error: %s",
1076 #else /* USE_SELECT */
1079 * Check all connections for new connections and input data that is to be
1080 * processed. Also check for connections with data queued and whether we can
1083 * Don't ever use ZERO for `delay', unless you mean to poll and then
1084 * you have to have sleep/wait somewhere else in the code.--msa
1086 int read_message(time_t delay)
1088 struct Client* cptr;
1089 struct Listener* listener;
1090 struct AuthRequest* auth = 0;
1091 struct AuthRequest* auth_next = 0;
1092 struct UPing* uping;
1093 struct UPing* uping_next;
1095 struct timeval wait;
1096 time_t delay2 = delay;
1097 unsigned int usec = 0;
1108 FD_ZERO(&write_set);
1110 if (-1 < ResolverFileDescriptor)
1111 FD_SET(ResolverFileDescriptor, &read_set);
1112 if (-1 < UPingFileDescriptor)
1113 FD_SET(UPingFileDescriptor, &read_set);
1115 * set up uping file descriptors
1117 for (uping = uping_begin(); uping; uping = uping_next) {
1118 uping_next = uping->next;
1119 if (uping->active) {
1121 if (uping->lastsent && CurrentTime > uping->timeout) {
1125 assert(-1 < uping->fd);
1126 FD_SET(uping->fd, &read_set);
1130 * set auth file descriptors
1132 for (auth = AuthPollList; auth; auth = auth->next) {
1133 assert(-1 < auth->fd);
1134 if (IsAuthConnect(auth))
1135 FD_SET(auth->fd, &write_set);
1136 else /* if (IsAuthPending(auth)) */
1137 FD_SET(auth->fd, &read_set);
1140 * set listener file descriptors
1142 for (listener = ListenerPollList; listener; listener = listener->next) {
1143 assert(-1 < listener->fd);
1144 FD_SET(listener->fd, &read_set);
1147 for (i = HighestFd; i > -1; --i) {
1148 if ((cptr = LocalClientArray[i])) {
1149 if (DBufLength(&cptr->recvQ))
1151 if (DBufLength(&cptr->recvQ) < 4088 || IsServer(cptr))
1152 FD_SET(i, &read_set);
1153 if (DBufLength(&cptr->sendQ) || IsConnecting(cptr) ||
1154 (cptr->listing && DBufLength(&cptr->sendQ) < 2048))
1155 FD_SET(i, &write_set);
1159 wait.tv_sec = IRCD_MIN(delay2, delay);
1160 wait.tv_usec = usec;
1162 Debug((DEBUG_INFO, "select: %d %d", delay, delay2));
1164 nfds = select(FD_SETSIZE, &read_set, &write_set, 0, &wait);
1166 CurrentTime = time(0);
1173 report_error(SELECT_ERROR_MSG, me.name, errno);
1175 server_restart("too many select errors");
1177 CurrentTime = time(0);
1180 if (-1 < UPingFileDescriptor && FD_ISSET(UPingFileDescriptor, &read_set)) {
1184 for (uping = uping_begin(); uping; uping = uping_next) {
1185 uping_next = uping->next;
1186 if (uping->active) {
1187 assert(-1 < uping->fd);
1188 if (FD_ISSET(uping->fd, &read_set)) {
1193 else if (CurrentTime > uping->lastsent) {
1194 uping->lastsent = CurrentTime;
1199 if (-1 < ResolverFileDescriptor && FD_ISSET(ResolverFileDescriptor, &read_set)) {
1204 * Check fd sets for the auth fd's (if set and valid!) first
1205 * because these can not be processed using the normal loops below.
1208 for (auth = AuthPollList; auth; auth = auth_next) {
1209 auth_next = auth->next;
1210 assert(-1 < auth->fd);
1211 if (IsAuthConnect(auth) && FD_ISSET(auth->fd, &write_set)) {
1212 send_auth_query(auth);
1216 else if (FD_ISSET(auth->fd, &read_set)) {
1217 read_auth_reply(auth);
1223 * next accept connections from active listeners
1225 for (listener = ListenerPollList; listener; listener = listener->next) {
1226 assert(-1 < listener->fd);
1227 if (0 < nfds && FD_ISSET(listener->fd, &read_set))
1228 accept_connection(listener);
1231 for (i = HighestFd; -1 < i; --i) {
1232 if (!(cptr = LocalClientArray[i]))
1236 if (FD_ISSET(i, &write_set)) {
1238 if (!on_write_unblocked(cptr) || IsDead(cptr)) {
1239 const char* msg = (cptr->error) ? strerror(cptr->error) : cptr->info;
1241 msg = "Unknown error";
1242 if (FD_ISSET(i, &read_set))
1244 exit_client(cptr, cptr, &me, msg);
1248 if ((read_ready = FD_ISSET(i, &read_set)))
1251 length = 1; /* for fall through case */
1252 if ((!NoNewLine(cptr) || read_ready) && !IsDead(cptr)) {
1253 if (CPTR_KILLED == (length = read_packet(cptr, read_ready)))
1257 /* Bullshit, why would we want to flush sockets while using non-blocking?
1258 * This uses > 4% cpu! --Run */
1260 flush_connections(LocalClientArray[i]);
1263 const char* msg = (cptr->error) ? strerror(cptr->error) : cptr->info;
1265 msg = "Unknown error";
1266 exit_client(cptr, cptr, &me, msg);
1273 * ...hmm, with non-blocking sockets we might get
1274 * here from quite valid reasons, although.. why
1275 * would select report "data available" when there
1276 * wasn't... So, this must be an error anyway... --msa
1277 * actually, EOF occurs when read() returns 0 and
1278 * in due course, select() returns that fd as ready
1279 * for reading even though it ends up being an EOF. -avalon
1281 Debug((DEBUG_ERROR, "READ ERROR: fd = %d %d %d", i, cptr->error, length));
1283 if ((IsServer(cptr) || IsHandshake(cptr)) && cptr->error == 0 && length == 0)
1284 exit_client_msg(cptr, cptr, &me, "Server %s closed the connection (%s)",
1285 cptr->name, cptr->serv->last_error_msg);
1287 const char* msg = (cptr->error) ? strerror(cptr->error) : "EOF from client";
1289 msg = "Unknown error";
1290 exit_client_msg(cptr, cptr, &me, "Read error: %s",
1297 #endif /* USE_SELECT */
1300 * connect_server - start or complete a connection to another server
1301 * returns true (1) if successful, false (0) otherwise
1303 * aconf must point to a valid C:line
1304 * m_connect calls this with a valid by client and a null reply
1305 * try_connections calls this with a null by client, and a null reply
1306 * connect_dns_callback call this with a null by client, and a valid reply
1308 * XXX - if this comes from an m_connect message and a dns query needs to
1309 * be done, we loose the information about who started the connection and
1310 * it's considered an auto connect.
1312 int connect_server(struct ConfItem* aconf, struct Client* by,
1313 struct DNSReply* reply)
1315 struct Client* cptr = 0;
1318 if (aconf->dns_pending) {
1319 sendto_opmask_butone(0, SNO_OLDSNO, "Server %s connect DNS pending",
1323 Debug((DEBUG_NOTICE, "Connect to %s[@%s]", aconf->name,
1324 ircd_ntoa((const char*) &aconf->ipnum)));
1326 if ((cptr = FindClient(aconf->name))) {
1327 if (IsServer(cptr) || IsMe(cptr)) {
1328 sendto_opmask_butone(0, SNO_OLDSNO, "Server %s already present from %s",
1329 aconf->name, cptr->from->name);
1330 if (by && IsUser(by) && !MyUser(by)) {
1331 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Server %s already present "
1332 "from %s", by, aconf->name, cptr->from->name);
1336 else if (IsHandshake(cptr) || IsConnecting(cptr)) {
1337 if (by && IsUser(by)) {
1338 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Connection to %s already in "
1339 "progress", by, cptr->name);
1345 * If we dont know the IP# for this host and itis a hostname and
1346 * not a ip# string, then try and find the appropriate host record.
1348 if (INADDR_NONE == aconf->ipnum.s_addr) {
1349 char buf[HOSTLEN + 1];
1351 if (INADDR_NONE == (aconf->ipnum.s_addr = inet_addr(aconf->host))) {
1352 struct DNSQuery query;
1355 query.callback = connect_dns_callback;
1356 host_from_uh(buf, aconf->host, HOSTLEN);
1357 buf[HOSTLEN] = '\0';
1359 reply = gethost_byname(buf, &query);
1362 aconf->dns_pending = 1;
1365 memcpy(&aconf->ipnum, reply->hp->h_addr, sizeof(struct in_addr));
1368 cptr = make_client(NULL, STAT_UNKNOWN_SERVER);
1371 cptr->dns_reply = reply;
1374 * Copy these in so we have something for error detection.
1376 ircd_strncpy(cptr->name, aconf->name, HOSTLEN);
1377 ircd_strncpy(cptr->sockhost, aconf->host, HOSTLEN);
1380 * Attach config entries to client here rather than in
1381 * completed_connection. This to avoid null pointer references
1383 attach_confs_byhost(cptr, aconf->host, CONF_SERVER);
1385 if (!find_conf_byhost(cptr->confs, aconf->host, CONF_SERVER)) {
1386 sendto_opmask_butone(0, SNO_OLDSNO, "Host %s is not enabled for "
1387 "connecting: no C-line", aconf->name);
1388 if (by && IsUser(by) && !MyUser(by)) {
1389 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Connect to host %s failed: no "
1390 "C-line", by, aconf->name);
1392 det_confs_butmask(cptr, 0);
1397 * attempt to connect to the server in the conf line
1399 if (!connect_inet(aconf, cptr)) {
1400 if (by && IsUser(by) && !MyUser(by)) {
1401 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Couldn't connect to %s", by,
1404 det_confs_butmask(cptr, 0);
1409 * NOTE: if we're here we have a valid C:Line and the client should
1410 * have started the connection and stored the remote address/port and
1411 * ip address name in itself
1413 * The socket has been connected or connect is in progress.
1416 if (by && IsUser(by)) {
1417 sprintf_irc(cptr->serv->by, "%s%s", NumNick(by));
1418 assert(0 == cptr->serv->user);
1419 cptr->serv->user = by->user;
1423 *cptr->serv->by = '\0';
1424 /* strcpy(cptr->serv->by, "Auto"); */
1426 cptr->serv->up = &me;
1427 SetConnecting(cptr);
1429 if (cptr->fd > HighestFd)
1430 HighestFd = cptr->fd;
1431 LocalClientArray[cptr->fd] = cptr;
1433 Count_newunknown(UserStats);
1434 add_client_to_list(cptr);
1436 nextping = CurrentTime;
1442 * Setup local socket structure to use for binding to.
1444 void init_virtual_host(const struct ConfItem* conf)
1448 memset(&VirtualHost, 0, sizeof(VirtualHost));
1449 VirtualHost.sin_family = AF_INET;
1450 VirtualHost.sin_addr.s_addr = INADDR_ANY;
1452 if (EmptyString(conf->passwd) || 0 == strcmp(conf->passwd, "*"))
1454 VirtualHost.sin_addr.s_addr = inet_addr(conf->passwd);
1456 if (INADDR_NONE == VirtualHost.sin_addr.s_addr)
1457 VirtualHost.sin_addr.s_addr = INADDR_ANY;
1461 * Find the real hostname for the host running the server (or one which
1462 * matches the server's name) and its primary IP#. Hostname is stored
1463 * in the client structure passed as a pointer.
1465 int init_server_identity()
1467 struct ConfItem* conf = find_me();
1469 if (!conf || EmptyString(conf->host))
1472 ircd_strncpy(me.name, conf->host, HOSTLEN);
1474 init_virtual_host(conf);