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) : "";
156 errmsg = "Unknown error";
158 if (EmptyString(who))
161 if (last_notice + 20 < CurrentTime) {
163 * pace error messages so opers don't get flooded by transients
165 sendto_opmask_butone(0, SNO_OLDSNO, text, who, errmsg);
166 last_notice = CurrentTime;
168 log_write(LS_SOCKET, L_ERROR, 0, text, who, errmsg);
174 * connect_dns_callback - called when resolver query finishes
175 * if the query resulted in a successful search, reply will contain
176 * a non-null pointer, otherwise reply will be null.
177 * if successful start the connection, otherwise notify opers
179 static void connect_dns_callback(void* vptr, struct DNSReply* reply)
181 struct ConfItem* aconf = (struct ConfItem*) vptr;
182 aconf->dns_pending = 0;
184 memcpy(&aconf->ipnum, reply->hp->h_addr, sizeof(struct in_addr));
185 connect_server(aconf, 0, reply);
188 sendto_opmask_butone(0, SNO_OLDSNO, "Connect to %s failed: host lookup",
193 * close_connections - closes all connections
194 * close stderr if specified
196 void close_connections(int close_stderr)
203 for (i = 3; i < MAXCONNECTIONS; ++i)
208 * init_connection_limits - initialize process fd limit to
211 int init_connection_limits(void)
213 int limit = os_set_fdlimit(MAXCONNECTIONS);
217 fprintf(stderr, "error setting max fd's to %d\n", limit);
219 else if (limit > 0) {
220 fprintf(stderr, "ircd fd table too big\nHard Limit: %d IRC max: %d\n",
221 limit, MAXCONNECTIONS);
222 fprintf(stderr, "set MAXCONNECTIONS to a smaller value");
228 * connect_inet - set up address and port and make a connection
230 static int connect_inet(struct ConfItem* aconf, struct Client* cptr)
232 static struct sockaddr_in sin;
236 * Might as well get sockhost from here, the connection is attempted
237 * with it so if it fails its useless.
239 cptr->fd = socket(AF_INET, SOCK_STREAM, 0);
240 if (-1 == cptr->fd) {
242 report_error(SOCKET_ERROR_MSG, cptr->name, errno);
245 if (cptr->fd >= MAXCLIENTS) {
246 report_error(CONNLIMIT_ERROR_MSG, cptr->name, 0);
252 * Bind to a local IP# (with unknown port - let unix decide) so
253 * we have some chance of knowing the IP# that gets used for a host
254 * with more than one IP#.
256 * No we don't bind it, not all OS's can handle connecting with
257 * an already bound socket, different ip# might occur anyway
258 * leading to a freezing select() on this side for some time.
259 * I had this on my Linux 1.1.88 --Run
263 * No, we do bind it if we have virtual host support. If we don't
264 * explicitly bind it, it will default to IN_ADDR_ANY and we lose
265 * due to the other server not allowing our base IP --smg
267 if (bind(cptr->fd, (struct sockaddr*) &VirtualHost, sizeof(VirtualHost))) {
268 report_error(BIND_ERROR_MSG, cptr->name, errno);
273 memset(&sin, 0, sizeof(sin));
274 sin.sin_family = AF_INET;
275 sin.sin_addr.s_addr = aconf->ipnum.s_addr;
276 sin.sin_port = htons(aconf->port);
278 * save connection info in client
280 cptr->ip.s_addr = aconf->ipnum.s_addr;
281 cptr->port = aconf->port;
282 ircd_ntoa_r(cptr->sock_ip, (const char*) &cptr->ip);
284 * we want a big buffer for server connections
286 if (!os_set_sockbufs(cptr->fd, SERVER_TCP_WINDOW)) {
288 report_error(SETBUFS_ERROR_MSG, cptr->name, errno);
292 * ALWAYS set sockets non-blocking
294 if (!os_set_nonblocking(cptr->fd)) {
296 report_error(NONB_ERROR_MSG, cptr->name, errno);
299 if (!os_connect_nonb(cptr->fd, &sin)) {
301 report_error(CONNECT_ERROR_MSG, cptr->name, errno);
309 * Attempt to send a sequence of bytes to the connection.
312 * < 0 Some fatal error occurred, (but not EWOULDBLOCK).
313 * This return is a request to close the socket and
316 * >= 0 No real error occurred, returns the number of
317 * bytes actually transferred. EWOULDBLOCK and other
318 * possibly similar conditions should be mapped to
319 * zero return. Upper level routine will have to
320 * decide what to do with those unwritten bytes...
322 * *NOTE* alarm calls have been preserved, so this should
323 * work equally well whether blocking or non-blocking
326 * We don't use blocking anymore, that is impossible with the
327 * net.loads today anyway. Commented out the alarms to save cpu.
330 unsigned int deliver_it(struct Client *cptr, const char *str, unsigned int len)
332 unsigned int bytes_written = 0;
335 switch (os_send_nonb(cptr->fd, str, len, &bytes_written)) {
337 cptr->flags &= ~FLAGS_BLOCKED;
339 cptr->sendB += bytes_written;
340 me.sendB += bytes_written;
341 if (cptr->sendB > 1023) {
342 cptr->sendK += (cptr->sendB >> 10);
343 cptr->sendB &= 0x03ff; /* 2^10 = 1024, 3ff = 1023 */
345 if (me.sendB > 1023) {
346 me.sendK += (me.sendB >> 10);
350 * XXX - hrmm.. set blocked here? the socket didn't
353 if (bytes_written < len)
354 cptr->flags |= FLAGS_BLOCKED;
357 cptr->flags |= FLAGS_BLOCKED;
361 cptr->flags |= FLAGS_DEADSOCKET;
364 return bytes_written;
368 void release_dns_reply(struct Client* cptr)
371 assert(MyConnect(cptr));
373 if (cptr->dns_reply) {
374 assert(0 < cptr->dns_reply->ref_count);
375 --cptr->dns_reply->ref_count;
381 * completed_connection
383 * Complete non-blocking connect()-sequence. Check access and
384 * terminate connection, if trouble detected.
386 * Return TRUE, if successfully completed
387 * FALSE, if failed and ClientExit
389 static int completed_connection(struct Client* cptr)
391 struct ConfItem *aconf;
393 struct Client *acptr;
399 * get the socket status from the fd first to check if
400 * connection actually succeeded
402 if ((cptr->error = os_get_sockerr(cptr->fd))) {
403 const char* msg = strerror(cptr->error);
405 msg = "Unknown error";
406 sendto_opmask_butone(0, SNO_OLDSNO, "Connection failed to %s: %s",
410 if (!(aconf = find_conf_byname(cptr->confs, cptr->name, CONF_SERVER))) {
411 sendto_opmask_butone(0, SNO_OLDSNO, "Lost Server Line for %s", cptr->name);
415 if (!EmptyString(aconf->passwd))
416 sendrawto_one(cptr, MSG_PASS " :%s", aconf->passwd);
419 /* dead code, already done in connect_server */
423 * Create a unique timestamp
426 for (i = HighestFd; i > -1; --i) {
427 if ((acptr = LocalClientArray[i]) &&
428 (IsServer(acptr) || IsHandshake(acptr))) {
429 if (acptr->serv->timestamp >= newts)
430 newts = acptr->serv->timestamp + 1;
433 assert(0 != cptr->serv);
435 cptr->serv->timestamp = newts;
438 * Make us timeout after twice the timeout for DNS look ups
440 cptr->lasttime = CurrentTime;
441 cptr->flags |= FLAGS_PINGSENT;
443 sendrawto_one(cptr, MSG_SERVER " %s 1 %Tu %Tu J%s %s%s :%s",
444 me.name, me.serv->timestamp, newts, MAJOR_PROTOCOL,
445 NumServCap(&me), me.info);
447 return (IsDead(cptr)) ? 0 : 1;
453 * Close the physical connection. This function must make
454 * MyConnect(cptr) == FALSE, and set cptr->from == NULL.
456 void close_connection(struct Client *cptr)
458 struct ConfItem* aconf;
460 if (IsServer(cptr)) {
461 ServerStats->is_sv++;
462 ServerStats->is_sbs += cptr->sendB;
463 ServerStats->is_sbr += cptr->receiveB;
464 ServerStats->is_sks += cptr->sendK;
465 ServerStats->is_skr += cptr->receiveK;
466 ServerStats->is_sti += CurrentTime - cptr->firsttime;
467 if (ServerStats->is_sbs > 1023) {
468 ServerStats->is_sks += (ServerStats->is_sbs >> 10);
469 ServerStats->is_sbs &= 0x3ff;
471 if (ServerStats->is_sbr > 1023) {
472 ServerStats->is_skr += (ServerStats->is_sbr >> 10);
473 ServerStats->is_sbr &= 0x3ff;
476 * If the connection has been up for a long amount of time, schedule
477 * a 'quick' reconnect, else reset the next-connect cycle.
479 if ((aconf = find_conf_exact(cptr->name, 0, cptr->sockhost, CONF_SERVER))) {
481 * Reschedule a faster reconnect, if this was a automaticly
482 * connected configuration entry. (Note that if we have had
483 * a rehash in between, the status has been changed to
484 * CONF_ILLEGAL). But only do this if it was a "good" link.
486 aconf->hold = CurrentTime;
487 aconf->hold += (aconf->hold - cptr->since > HANGONGOODLINK) ?
488 HANGONRETRYDELAY : ConfConFreq(aconf);
489 if (nextconnect > aconf->hold)
490 nextconnect = aconf->hold;
493 else if (IsUser(cptr)) {
494 ServerStats->is_cl++;
495 ServerStats->is_cbs += cptr->sendB;
496 ServerStats->is_cbr += cptr->receiveB;
497 ServerStats->is_cks += cptr->sendK;
498 ServerStats->is_ckr += cptr->receiveK;
499 ServerStats->is_cti += CurrentTime - cptr->firsttime;
500 if (ServerStats->is_cbs > 1023) {
501 ServerStats->is_cks += (ServerStats->is_cbs >> 10);
502 ServerStats->is_cbs &= 0x3ff;
504 if (ServerStats->is_cbr > 1023) {
505 ServerStats->is_ckr += (ServerStats->is_cbr >> 10);
506 ServerStats->is_cbr &= 0x3ff;
510 ServerStats->is_ni++;
513 flush_connections(cptr);
514 LocalClientArray[cptr->fd] = 0;
518 cptr->flags |= FLAGS_DEADSOCKET;
520 MsgQClear(&cptr->sendQ);
521 DBufClear(&cptr->recvQ);
522 memset(cptr->passwd, 0, sizeof(cptr->passwd));
523 set_snomask(cptr, 0, SNO_SET);
525 det_confs_butmask(cptr, 0);
527 if (cptr->listener) {
528 release_listener(cptr->listener);
532 for ( ; HighestFd > 0; --HighestFd) {
533 if (LocalClientArray[HighestFd])
538 int net_close_unregistered_connections(struct Client* source)
545 for (i = HighestFd; i > 0; --i) {
546 if ((cptr = LocalClientArray[i]) && !IsRegistered(cptr)) {
547 send_reply(source, RPL_CLOSING, get_client_name(source, HIDE_IP));
548 exit_client(source, cptr, &me, "Oper Closing");
555 /*----------------------------------------------------------------------------
558 * Creates a client which has just connected to us on the given fd.
559 * The sockhost field is initialized with the ip# of the host.
560 * The client is not added to the linked list of clients, it is
561 * passed off to the auth handler for dns and ident queries.
562 *--------------------------------------------------------------------------*/
563 void add_connection(struct Listener* listener, int fd) {
564 struct sockaddr_in addr;
565 struct Client *new_client;
566 time_t next_target = 0;
568 const char* const throttle_message =
569 "ERROR :Your host is trying to (re)connect too fast -- throttled\r\n";
570 /* 12345678901234567890123456789012345679012345678901234567890123456 */
572 assert(0 != listener);
576 * Removed preliminary access check. Full check is performed in m_server and
577 * m_user instead. Also connection time out help to get rid of unwanted
580 if (!os_get_peername(fd, &addr) || !os_set_nonblocking(fd)) {
581 ++ServerStats->is_ref;
587 * Add this local client to the IPcheck registry.
589 * If they're throttled, murder them, but tell them why first.
591 if (!IPcheck_local_connect(addr.sin_addr, &next_target) && !listener->server) {
592 ++ServerStats->is_ref;
593 write(fd, throttle_message, strlen(throttle_message));
598 new_client = make_client(0, ((listener->server) ?
599 STAT_UNKNOWN_SERVER : STAT_UNKNOWN_USER));
602 * Copy ascii address to 'sockhost' just in case. Then we have something
603 * valid to put into error messages...
605 ircd_ntoa_r(new_client->sock_ip, (const char*) &addr.sin_addr);
606 strcpy(new_client->sockhost, new_client->sock_ip);
607 new_client->ip.s_addr = addr.sin_addr.s_addr;
608 new_client->port = ntohs(addr.sin_port);
611 new_client->nexttarget = next_target;
614 new_client->listener = listener;
615 ++listener->ref_count;
617 Count_newunknown(UserStats);
618 /* if we've made it this far we can put the client on the auth query pile */
619 start_auth(new_client);
626 * Read a 'packet' of data from a connection and process it. Read in 8k
627 * chunks to give a better performance rating (for server connections).
628 * Do some tricky stuff for client connections to make sure they don't do
629 * any flooding >:-) -avalon
631 static int read_packet(struct Client *cptr, int socket_ready)
633 unsigned int dolen = 0;
634 unsigned int length = 0;
636 if (socket_ready && !(IsUser(cptr) && DBufLength(&cptr->recvQ) > CLIENT_FLOOD)) {
637 switch (os_recv_nonb(cptr->fd, readbuf, sizeof(readbuf), &length)) {
640 cptr->lasttime = CurrentTime;
641 if (cptr->lasttime > cptr->since)
642 cptr->since = cptr->lasttime;
643 cptr->flags &= ~(FLAGS_PINGSENT | FLAGS_NONL);
650 /* cptr->flags |= FLAGS_DEADSOCKET; */
656 * For server connections, we process as many as we can without
657 * worrying about the time of day or anything :)
659 if (length > 0 && IsServer(cptr)) {
660 return server_dopacket(cptr, readbuf, length);
664 * Before we even think of parsing what we just read, stick
665 * it on the end of the receive queue and do it when its
668 if (length > 0 && 0 == dbuf_put(&cptr->recvQ, readbuf, length)) {
669 return exit_client(cptr, cptr, &me, "dbuf_put fail");
671 #ifndef NOFLOODCONTROL
673 * XXX - cptr will always be a user or unregistered
675 if (IsUser(cptr) && DBufLength(&cptr->recvQ) > CLIENT_FLOOD)
676 return exit_client(cptr, cptr, &me, "Excess Flood");
678 while (DBufLength(&cptr->recvQ) && !NoNewLine(cptr) &&
679 (IsTrusted(cptr) || cptr->since - CurrentTime < 10))
681 while (DBufLength(&cptr->recvQ) && !NoNewLine(cptr))
685 * If it has become registered as a Server
686 * then skip the per-message parsing below.
688 if (IsServer(cptr)) {
689 dolen = dbuf_get(&cptr->recvQ, readbuf, sizeof(readbuf));
690 return (dolen) ? server_dopacket(cptr, readbuf, dolen) : 1;
692 dolen = dbuf_getmsg(&cptr->recvQ, cptr->buffer, BUFSIZE);
694 * Devious looking...whats it do ? well..if a client
695 * sends a *long* message without any CR or LF, then
696 * dbuf_getmsg fails and we pull it out using this
697 * loop which just gets the next 512 bytes and then
698 * deletes the rest of the buffer contents.
702 if (DBufLength(&cptr->recvQ) < 510)
703 cptr->flags |= FLAGS_NONL;
705 DBufClear(&cptr->recvQ);
707 else if (CPTR_KILLED == client_dopacket(cptr, dolen))
714 static int on_write_unblocked(struct Client* cptr)
717 * ...room for writing, empty some queue then...
719 cptr->flags &= ~FLAGS_BLOCKED;
720 if (IsConnecting(cptr)) {
721 if (!completed_connection(cptr))
724 else if (cptr->listing && MsgQLength(&cptr->sendQ) < 2048)
725 list_next_channels(cptr, 64);
731 * Select / Poll Read Algorithm for ircd
733 * We need to check the file descriptors for all the different types
734 * of things that use them, so check for reads on everything but connects
735 * and writes on connects and descriptors that are blocked
737 * for each (client in local) {
738 * if (not connecting)
740 * if (connecting or blocked)
745 * for each (client in local) {
746 * if (there are descriptors to check) {
747 * if (write activity)
754 * Note we must always process data read whether or not there has been
755 * read activity or file descriptors set, since data is buffered by the client.
764 #if defined(POLLMSG) && defined(POLLIN) && defined(POLLRDNORM)
765 # define POLLREADFLAGS (POLLMSG|POLLIN|POLLRDNORM)
767 # if defined(POLLIN) && defined(POLLRDNORM)
768 # define POLLREADFLAGS (POLLIN|POLLRDNORM)
771 # define POLLREADFLAGS POLLIN
773 # if defined(POLLRDNORM)
774 # define POLLREADFLAGS POLLRDNORM
780 #if defined(POLLOUT) && defined(POLLWRNORM)
781 #define POLLWRITEFLAGS (POLLOUT|POLLWRNORM)
783 # if defined(POLLOUT)
784 # define POLLWRITEFLAGS POLLOUT
786 # if defined(POLLWRNORM)
787 # define POLLWRITEFLAGS POLLWRNORM
793 #define POLLERRORS (POLLHUP|POLLERR)
795 #define POLLERRORS POLLERR
799 * NOTE: pfd and pfd_count are local variable names in read_message
801 #define PFD_SETR(xfd) \
802 do { CHECK_ADD_PFD(xfd) pfd->events |= POLLREADFLAGS; } while(0)
803 #define PFD_SETW(xfd) \
804 do { CHECK_ADD_PFD(xfd) pfd->events |= POLLWRITEFLAGS; } while(0)
806 #define CHECK_ADD_PFD(xfd) \
807 if (pfd->fd != xfd) { \
808 pfd = &poll_fds[pfd_count++]; \
809 poll_fds[pfd_count].fd = -1; \
815 * Check all connections for new connections and input data that is to be
816 * processed. Also check for connections with data queued and whether we can
819 * Don't ever use ZERO for `delay', unless you mean to poll and then
820 * you have to have sleep/wait somewhere else in the code.--msa
822 int read_message(time_t delay)
824 struct pollfd poll_fds[MAXCONNECTIONS + 1];
826 struct Listener* listener = 0;
827 struct AuthRequest* auth = 0;
828 struct AuthRequest* auth_next = 0;
829 struct UPing* uping = 0;
830 struct UPing* uping_next = 0;
831 time_t delay2 = delay;
838 struct pollfd* res_pfd;
839 struct pollfd* uping_pfd;
843 unsigned int timeout;
852 if (-1 < ResolverFileDescriptor) {
853 PFD_SETR(ResolverFileDescriptor);
856 if (-1 < UPingFileDescriptor) {
857 PFD_SETR(UPingFileDescriptor);
861 * add uping descriptors
863 for (uping = uping_begin(); uping; uping = uping_next) {
864 uping_next = uping->next;
867 if (uping->lastsent && CurrentTime > uping->timeout) {
871 uping->index = pfd_count;
876 * add auth file descriptors
878 for (auth = AuthPollList; auth; auth = auth->next) {
879 assert(-1 < auth->fd);
880 auth->index = pfd_count;
881 if (IsAuthConnect(auth))
887 * add listener file descriptors
889 for (listener = ListenerPollList; listener; listener = listener->next) {
890 assert(-1 < listener->fd);
892 * pfd_count is incremented by PFD_SETR so we need to save the
895 listener->index = pfd_count;
896 PFD_SETR(listener->fd);
899 for (i = HighestFd; -1 < i; --i) {
900 if ((cptr = LocalClientArray[i])) {
902 if (DBufLength(&cptr->recvQ))
904 if (DBufLength(&cptr->recvQ) < 4088 || IsServer(cptr)) {
907 if (MsgQLength(&cptr->sendQ) || IsConnecting(cptr) ||
908 (cptr->listing && MsgQLength(&cptr->sendQ) < 2048)) {
914 Debug((DEBUG_INFO, "poll: %d %d", delay, delay2));
916 timeout = (IRCD_MIN(delay2, delay)) * 1000;
918 nfds = poll(poll_fds, pfd_count, timeout);
920 CurrentTime = time(0);
926 report_error(POLL_ERROR_MSG, me.name, errno);
929 server_restart("too many poll errors");
931 CurrentTime = time(0);
934 if (uping_pfd && (uping_pfd->revents & (POLLREADFLAGS | POLLERRORS))) {
939 * check uping replies
941 for (uping = uping_begin(); uping; uping = uping_next) {
942 uping_next = uping->next;
944 assert(-1 < uping->index);
945 if (poll_fds[uping->index].revents) {
950 else if (CurrentTime > uping->lastsent) {
951 uping->lastsent = CurrentTime;
957 if (res_pfd && (res_pfd->revents & (POLLREADFLAGS | POLLERRORS))) {
964 for (auth = AuthPollList; auth; auth = auth_next) {
965 auth_next = auth->next;
968 * check for any event, we only ask for one at a time
970 if (poll_fds[i].revents) {
971 if (IsAuthConnect(auth))
972 send_auth_query(auth);
974 read_auth_reply(auth);
982 for (listener = ListenerPollList; listener; listener = listener->next) {
984 if (poll_fds[i].revents) {
985 accept_connection(listener);
991 * i contains the next non-auth/non-listener index, since we put the
992 * resolver, auth and listener, file descriptors in poll_fds first,
993 * the very next one should be the start of the clients
995 pfd = &poll_fds[++i];
997 for ( ; (i < pfd_count); ++i, ++pfd) {
998 if (!(cptr = LocalClientArray[pfd->fd]))
1000 read_ready = write_ready = 0;
1002 if (0 < nfds && pfd->revents) {
1005 read_ready = pfd->revents & POLLREADFLAGS;
1006 write_ready = pfd->revents & POLLWRITEFLAGS;
1008 if (pfd->revents & POLLERRORS) {
1009 if (pfd->events & POLLREADFLAGS)
1011 if (pfd->events & POLLWRITEFLAGS)
1016 if (!on_write_unblocked(cptr) || IsDead(cptr)) {
1017 const char* msg = (cptr->error) ? strerror(cptr->error) : cptr->info;
1019 msg = "Unknown error";
1020 exit_client(cptr, cptr, &me, msg);
1024 length = 1; /* for fall through case */
1025 if ((!NoNewLine(cptr) || read_ready) && !IsDead(cptr)) {
1026 if (CPTR_KILLED == (length = read_packet(cptr, read_ready)))
1030 /* Bullshit, why would we want to flush sockets while using non-blocking?
1031 * This uses > 4% cpu! --Run */
1033 flush_connections(poll_cptr[i]);
1036 const char* msg = (cptr->error) ? strerror(cptr->error) : cptr->info;
1038 msg = "Unknown error";
1039 exit_client(cptr, cptr, &me, (char*) msg);
1044 cptr->flags |= FLAGS_DEADSOCKET;
1046 * ...hmm, with non-blocking sockets we might get
1047 * here from quite valid reasons, although.. why
1048 * would select report "data available" when there
1049 * wasn't... So, this must be an error anyway... --msa
1050 * actually, EOF occurs when read() returns 0 and
1051 * in due course, select() returns that fd as ready
1052 * for reading even though it ends up being an EOF. -avalon
1054 Debug((DEBUG_ERROR, "READ ERROR: fd = %d %d %d", pfd->fd, errno, length));
1056 if ((IsServer(cptr) || IsHandshake(cptr)) && cptr->error == 0 && length == 0)
1057 exit_client_msg(cptr, cptr, &me, "Server %s closed the connection (%s)",
1058 cptr->name, cptr->serv->last_error_msg);
1060 const char* msg = (cptr->error) ? strerror(cptr->error) : "EOF from client";
1062 msg = "Unknown error";
1063 exit_client_msg(cptr, cptr, &me, "Read error: %s", msg);
1068 #else /* USE_SELECT */
1071 * Check all connections for new connections and input data that is to be
1072 * processed. Also check for connections with data queued and whether we can
1075 * Don't ever use ZERO for `delay', unless you mean to poll and then
1076 * you have to have sleep/wait somewhere else in the code.--msa
1078 int read_message(time_t delay)
1080 struct Client* cptr;
1081 struct Listener* listener;
1082 struct AuthRequest* auth = 0;
1083 struct AuthRequest* auth_next = 0;
1084 struct UPing* uping;
1085 struct UPing* uping_next;
1087 struct timeval wait;
1088 time_t delay2 = delay;
1089 unsigned int usec = 0;
1100 FD_ZERO(&write_set);
1102 if (-1 < ResolverFileDescriptor)
1103 FD_SET(ResolverFileDescriptor, &read_set);
1104 if (-1 < UPingFileDescriptor)
1105 FD_SET(UPingFileDescriptor, &read_set);
1107 * set up uping file descriptors
1109 for (uping = uping_begin(); uping; uping = uping_next) {
1110 uping_next = uping->next;
1111 if (uping->active) {
1113 if (uping->lastsent && CurrentTime > uping->timeout) {
1117 assert(-1 < uping->fd);
1118 FD_SET(uping->fd, &read_set);
1122 * set auth file descriptors
1124 for (auth = AuthPollList; auth; auth = auth->next) {
1125 assert(-1 < auth->fd);
1126 if (IsAuthConnect(auth))
1127 FD_SET(auth->fd, &write_set);
1128 else /* if (IsAuthPending(auth)) */
1129 FD_SET(auth->fd, &read_set);
1132 * set listener file descriptors
1134 for (listener = ListenerPollList; listener; listener = listener->next) {
1135 assert(-1 < listener->fd);
1136 FD_SET(listener->fd, &read_set);
1139 for (i = HighestFd; i > -1; --i) {
1140 if ((cptr = LocalClientArray[i])) {
1141 if (DBufLength(&cptr->recvQ))
1143 if (DBufLength(&cptr->recvQ) < 4088 || IsServer(cptr))
1144 FD_SET(i, &read_set);
1145 if (MsgQLength(&cptr->sendQ) || IsConnecting(cptr) ||
1146 (cptr->listing && MsgQLength(&cptr->sendQ) < 2048))
1147 FD_SET(i, &write_set);
1151 wait.tv_sec = IRCD_MIN(delay2, delay);
1152 wait.tv_usec = usec;
1154 Debug((DEBUG_INFO, "select: %d %d", delay, delay2));
1156 nfds = select(FD_SETSIZE, &read_set, &write_set, 0, &wait);
1158 CurrentTime = time(0);
1165 report_error(SELECT_ERROR_MSG, me.name, errno);
1167 server_restart("too many select errors");
1169 CurrentTime = time(0);
1172 if (-1 < UPingFileDescriptor && FD_ISSET(UPingFileDescriptor, &read_set)) {
1176 for (uping = uping_begin(); uping; uping = uping_next) {
1177 uping_next = uping->next;
1178 if (uping->active) {
1179 assert(-1 < uping->fd);
1180 if (FD_ISSET(uping->fd, &read_set)) {
1185 else if (CurrentTime > uping->lastsent) {
1186 uping->lastsent = CurrentTime;
1191 if (-1 < ResolverFileDescriptor && FD_ISSET(ResolverFileDescriptor, &read_set)) {
1196 * Check fd sets for the auth fd's (if set and valid!) first
1197 * because these can not be processed using the normal loops below.
1200 for (auth = AuthPollList; auth; auth = auth_next) {
1201 auth_next = auth->next;
1202 assert(-1 < auth->fd);
1203 if (IsAuthConnect(auth) && FD_ISSET(auth->fd, &write_set)) {
1204 send_auth_query(auth);
1208 else if (FD_ISSET(auth->fd, &read_set)) {
1209 read_auth_reply(auth);
1215 * next accept connections from active listeners
1217 for (listener = ListenerPollList; listener; listener = listener->next) {
1218 assert(-1 < listener->fd);
1219 if (0 < nfds && FD_ISSET(listener->fd, &read_set))
1220 accept_connection(listener);
1223 for (i = HighestFd; -1 < i; --i) {
1224 if (!(cptr = LocalClientArray[i]))
1228 if (FD_ISSET(i, &write_set)) {
1230 if (!on_write_unblocked(cptr) || IsDead(cptr)) {
1231 const char* msg = (cptr->error) ? strerror(cptr->error) : cptr->info;
1233 msg = "Unknown error";
1234 if (FD_ISSET(i, &read_set))
1236 exit_client(cptr, cptr, &me, msg);
1240 if ((read_ready = FD_ISSET(i, &read_set)))
1243 length = 1; /* for fall through case */
1244 if ((!NoNewLine(cptr) || read_ready) && !IsDead(cptr)) {
1245 if (CPTR_KILLED == (length = read_packet(cptr, read_ready)))
1249 const char* msg = (cptr->error) ? strerror(cptr->error) : cptr->info;
1251 msg = "Unknown error";
1252 exit_client(cptr, cptr, &me, msg);
1259 * ...hmm, with non-blocking sockets we might get
1260 * here from quite valid reasons, although.. why
1261 * would select report "data available" when there
1262 * wasn't... So, this must be an error anyway... --msa
1263 * actually, EOF occurs when read() returns 0 and
1264 * in due course, select() returns that fd as ready
1265 * for reading even though it ends up being an EOF. -avalon
1267 Debug((DEBUG_ERROR, "READ ERROR: fd = %d %d %d", i, cptr->error, length));
1269 if ((IsServer(cptr) || IsHandshake(cptr)) && cptr->error == 0 && length == 0)
1270 exit_client_msg(cptr, cptr, &me, "Server %s closed the connection (%s)",
1271 cptr->name, cptr->serv->last_error_msg);
1273 const char* msg = (cptr->error) ? strerror(cptr->error) : "EOF from client";
1275 msg = "Unknown error";
1276 exit_client_msg(cptr, cptr, &me, "Read error: %s", msg);
1282 #endif /* USE_SELECT */
1285 * connect_server - start or complete a connection to another server
1286 * returns true (1) if successful, false (0) otherwise
1288 * aconf must point to a valid C:line
1289 * m_connect calls this with a valid by client and a null reply
1290 * try_connections calls this with a null by client, and a null reply
1291 * connect_dns_callback call this with a null by client, and a valid reply
1293 * XXX - if this comes from an m_connect message and a dns query needs to
1294 * be done, we loose the information about who started the connection and
1295 * it's considered an auto connect.
1297 int connect_server(struct ConfItem* aconf, struct Client* by,
1298 struct DNSReply* reply)
1300 struct Client* cptr = 0;
1303 if (aconf->dns_pending) {
1304 sendto_opmask_butone(0, SNO_OLDSNO, "Server %s connect DNS pending",
1308 Debug((DEBUG_NOTICE, "Connect to %s[@%s]", aconf->name,
1309 ircd_ntoa((const char*) &aconf->ipnum)));
1311 if ((cptr = FindClient(aconf->name))) {
1312 if (IsServer(cptr) || IsMe(cptr)) {
1313 sendto_opmask_butone(0, SNO_OLDSNO, "Server %s already present from %s",
1314 aconf->name, cptr->from->name);
1315 if (by && IsUser(by) && !MyUser(by)) {
1316 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Server %s already present "
1317 "from %s", by, aconf->name, cptr->from->name);
1321 else if (IsHandshake(cptr) || IsConnecting(cptr)) {
1322 if (by && IsUser(by)) {
1323 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Connection to %s already in "
1324 "progress", by, cptr->name);
1330 * If we dont know the IP# for this host and itis a hostname and
1331 * not a ip# string, then try and find the appropriate host record.
1333 if (INADDR_NONE == aconf->ipnum.s_addr) {
1334 char buf[HOSTLEN + 1];
1336 if (INADDR_NONE == (aconf->ipnum.s_addr = inet_addr(aconf->host))) {
1337 struct DNSQuery query;
1340 query.callback = connect_dns_callback;
1341 host_from_uh(buf, aconf->host, HOSTLEN);
1342 buf[HOSTLEN] = '\0';
1344 reply = gethost_byname(buf, &query);
1347 aconf->dns_pending = 1;
1350 memcpy(&aconf->ipnum, reply->hp->h_addr, sizeof(struct in_addr));
1353 cptr = make_client(NULL, STAT_UNKNOWN_SERVER);
1356 cptr->dns_reply = reply;
1359 * Copy these in so we have something for error detection.
1361 ircd_strncpy(cptr->name, aconf->name, HOSTLEN);
1362 ircd_strncpy(cptr->sockhost, aconf->host, HOSTLEN);
1365 * Attach config entries to client here rather than in
1366 * completed_connection. This to avoid null pointer references
1368 attach_confs_byhost(cptr, aconf->host, CONF_SERVER);
1370 if (!find_conf_byhost(cptr->confs, aconf->host, CONF_SERVER)) {
1371 sendto_opmask_butone(0, SNO_OLDSNO, "Host %s is not enabled for "
1372 "connecting: no C-line", aconf->name);
1373 if (by && IsUser(by) && !MyUser(by)) {
1374 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Connect to host %s failed: no "
1375 "C-line", by, aconf->name);
1377 det_confs_butmask(cptr, 0);
1382 * attempt to connect to the server in the conf line
1384 if (!connect_inet(aconf, cptr)) {
1385 if (by && IsUser(by) && !MyUser(by)) {
1386 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Couldn't connect to %s", by,
1389 det_confs_butmask(cptr, 0);
1394 * NOTE: if we're here we have a valid C:Line and the client should
1395 * have started the connection and stored the remote address/port and
1396 * ip address name in itself
1398 * The socket has been connected or connect is in progress.
1401 if (by && IsUser(by)) {
1402 sprintf_irc(cptr->serv->by, "%s%s", NumNick(by));
1403 assert(0 == cptr->serv->user);
1404 cptr->serv->user = by->user;
1408 *cptr->serv->by = '\0';
1409 /* strcpy(cptr->serv->by, "Auto"); */
1411 cptr->serv->up = &me;
1412 SetConnecting(cptr);
1414 if (cptr->fd > HighestFd)
1415 HighestFd = cptr->fd;
1418 LocalClientArray[cptr->fd] = cptr;
1420 Count_newunknown(UserStats);
1421 /* Actually we lie, the connect hasn't succeeded yet, but we have a valid
1422 * cptr, so we register it now.
1423 * Maybe these two calls should be merged.
1425 add_client_to_list(cptr);
1427 nextping = CurrentTime;
1433 * Setup local socket structure to use for binding to.
1435 void set_virtual_host(struct in_addr addr)
1437 memset(&VirtualHost, 0, sizeof(VirtualHost));
1438 VirtualHost.sin_family = AF_INET;
1439 VirtualHost.sin_addr.s_addr = addr.s_addr;
1443 * Find the real hostname for the host running the server (or one which
1444 * matches the server's name) and its primary IP#. Hostname is stored
1445 * in the client structure passed as a pointer.
1447 void init_server_identity(void)
1449 const struct LocalConf* conf = conf_get_local();
1452 ircd_strncpy(me.name, conf->name, HOSTLEN);
1453 SetYXXServerName(&me, conf->numeric);