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"
41 #include "querycmds.h"
49 #include "sprintf_irc.h"
56 #include <arpa/inet.h>
57 #include <arpa/nameser.h>
66 #include <sys/ioctl.h>
67 #include <sys/socket.h>
69 #include <sys/utsname.h>
77 #define INADDR_NONE 0xffffffff
80 struct Client* LocalClientArray[MAXCONNECTIONS];
82 struct sockaddr_in VirtualHost;
83 static char readbuf[SERVER_TCP_WINDOW];
86 * report_error text constants
88 const char* const ACCEPT_ERROR_MSG = "error accepting connection for %s: %s";
89 const char* const BIND_ERROR_MSG = "bind error for %s: %s";
90 const char* const CONNECT_ERROR_MSG = "connect to host %s failed: %s";
91 const char* const CONNLIMIT_ERROR_MSG = "connect limit exceeded for %s: %s";
92 const char* const LISTEN_ERROR_MSG = "listen error for %s: %s";
93 const char* const NONB_ERROR_MSG = "error setting non-blocking for %s: %s";
94 const char* const PEERNAME_ERROR_MSG = "getpeername failed for %s: %s";
95 const char* const POLL_ERROR_MSG = "poll error for %s: %s";
96 const char* const REUSEADDR_ERROR_MSG = "error setting SO_REUSEADDR for %s: %s";
97 const char* const SELECT_ERROR_MSG = "select error for %s: %s";
98 const char* const SETBUFS_ERROR_MSG = "error setting buffer size for %s: %s";
99 const char* const SOCKET_ERROR_MSG = "error creating socket for %s: %s";
100 const char* const TOS_ERROR_MSG = "error setting TOS for %s: %s";
107 #ifndef NOFLOODCONTROL
108 #define NOFLOODCONTROL
112 #if !defined(USE_POLL)
113 #if FD_SETSIZE < (MAXCONNECTIONS + 4)
117 * All operating systems work when MAXCONNECTIONS <= 252.
118 * Most operating systems work when MAXCONNECTIONS <= 1020 and FD_SETSIZE is
119 * updated correctly in the system headers (on BSD systems our sys.h has
120 * defined FD_SETSIZE to MAXCONNECTIONS+4 before including the system's headers
121 * but sys/types.h might have abruptly redefined it so the check is still
122 * done), you might already need to recompile your kernel.
123 * For larger FD_SETSIZE your milage may vary (kernel patches may be needed).
124 * The check is _NOT_ done if we will not use FD_SETS at all (USE_POLL)
126 #error "FD_SETSIZE is too small or MAXCONNECTIONS too large."
132 * Cannot use perror() within daemon. stderr is closed in
133 * ircd and cannot be used. And, worse yet, it might have
134 * been reassigned to a normal connection...
140 * This a replacement for perror(). Record error to log and
141 * also send a copy to all *LOCAL* opers online.
143 * text is a *format* string for outputting error. It must
144 * contain only two '%s', the first will be replaced
145 * by the sockhost from the cptr, and the latter will
146 * be taken from sys_errlist[errno].
148 * cptr if not NULL, is the *LOCAL* client associated with
151 void report_error(const char* text, const char* who, int err)
153 static time_t last_notice = 0;
154 int errtmp = errno; /* debug may change 'errno' */
155 const char* errmsg = (err) ? strerror(err) : "";
158 errmsg = "Unknown error";
160 if (EmptyString(who))
163 if (last_notice + 20 < CurrentTime) {
165 * pace error messages so opers don't get flooded by transients
167 sendto_opmask_butone(0, SNO_OLDSNO, text, who, errmsg);
168 last_notice = CurrentTime;
170 log_write(LS_SOCKET, L_ERROR, 0, text, who, errmsg);
176 * connect_dns_callback - called when resolver query finishes
177 * if the query resulted in a successful search, reply will contain
178 * a non-null pointer, otherwise reply will be null.
179 * if successful start the connection, otherwise notify opers
181 static void connect_dns_callback(void* vptr, struct DNSReply* reply)
183 struct ConfItem* aconf = (struct ConfItem*) vptr;
184 aconf->dns_pending = 0;
186 memcpy(&aconf->ipnum, reply->hp->h_addr, sizeof(struct in_addr));
187 connect_server(aconf, 0, reply);
190 sendto_opmask_butone(0, SNO_OLDSNO, "Connect to %s failed: host lookup",
195 * close_connections - closes all connections
196 * close stderr if specified
198 void close_connections(int close_stderr)
205 for (i = 3; i < MAXCONNECTIONS; ++i)
210 * init_connection_limits - initialize process fd limit to
213 int init_connection_limits(void)
215 int limit = os_set_fdlimit(MAXCONNECTIONS);
219 fprintf(stderr, "error setting max fd's to %d\n", limit);
221 else if (limit > 0) {
222 fprintf(stderr, "ircd fd table too big\nHard Limit: %d IRC max: %d\n",
223 limit, MAXCONNECTIONS);
224 fprintf(stderr, "set MAXCONNECTIONS to a smaller value");
230 * connect_inet - set up address and port and make a connection
232 static int connect_inet(struct ConfItem* aconf, struct Client* cptr)
234 static struct sockaddr_in sin;
238 * Might as well get sockhost from here, the connection is attempted
239 * with it so if it fails its useless.
241 cli_fd(cptr) = socket(AF_INET, SOCK_STREAM, 0);
242 if (-1 == cli_fd(cptr)) {
243 cli_error(cptr) = errno;
244 report_error(SOCKET_ERROR_MSG, cli_name(cptr), errno);
247 if (cli_fd(cptr) >= MAXCLIENTS) {
248 report_error(CONNLIMIT_ERROR_MSG, cli_name(cptr), 0);
254 * Bind to a local IP# (with unknown port - let unix decide) so
255 * we have some chance of knowing the IP# that gets used for a host
256 * with more than one IP#.
258 * No we don't bind it, not all OS's can handle connecting with
259 * an already bound socket, different ip# might occur anyway
260 * leading to a freezing select() on this side for some time.
261 * I had this on my Linux 1.1.88 --Run
265 * No, we do bind it if we have virtual host support. If we don't
266 * explicitly bind it, it will default to IN_ADDR_ANY and we lose
267 * due to the other server not allowing our base IP --smg
269 if (bind(cli_fd(cptr), (struct sockaddr*) &VirtualHost, sizeof(VirtualHost))) {
270 report_error(BIND_ERROR_MSG, cli_name(cptr), errno);
275 memset(&sin, 0, sizeof(sin));
276 sin.sin_family = AF_INET;
277 sin.sin_addr.s_addr = aconf->ipnum.s_addr;
278 sin.sin_port = htons(aconf->port);
280 * save connection info in client
282 (cli_ip(cptr)).s_addr = aconf->ipnum.s_addr;
283 cli_port(cptr) = aconf->port;
284 ircd_ntoa_r(cli_sock_ip(cptr), (const char*) &(cli_ip(cptr)));
286 * we want a big buffer for server connections
288 if (!os_set_sockbufs(cli_fd(cptr), SERVER_TCP_WINDOW)) {
289 cli_error(cptr) = errno;
290 report_error(SETBUFS_ERROR_MSG, cli_name(cptr), errno);
294 * ALWAYS set sockets non-blocking
296 if (!os_set_nonblocking(cli_fd(cptr))) {
297 cli_error(cptr) = errno;
298 report_error(NONB_ERROR_MSG, cli_name(cptr), errno);
301 if (!os_connect_nonb(cli_fd(cptr), &sin)) {
302 cli_error(cptr) = errno;
303 report_error(CONNECT_ERROR_MSG, cli_name(cptr), errno);
311 * Attempt to send a sequence of bytes to the connection.
314 * < 0 Some fatal error occurred, (but not EWOULDBLOCK).
315 * This return is a request to close the socket and
318 * >= 0 No real error occurred, returns the number of
319 * bytes actually transferred. EWOULDBLOCK and other
320 * possibly similar conditions should be mapped to
321 * zero return. Upper level routine will have to
322 * decide what to do with those unwritten bytes...
324 * *NOTE* alarm calls have been preserved, so this should
325 * work equally well whether blocking or non-blocking
328 * We don't use blocking anymore, that is impossible with the
329 * net.loads today anyway. Commented out the alarms to save cpu.
332 unsigned int deliver_it(struct Client *cptr, struct MsgQ *buf)
334 unsigned int bytes_written = 0;
335 unsigned int bytes_count = 0;
338 switch (os_sendv_nonb(cli_fd(cptr), buf, &bytes_count, &bytes_written)) {
340 cli_flags(cptr) &= ~FLAGS_BLOCKED;
342 cli_sendB(cptr) += bytes_written;
343 cli_sendB(&me) += bytes_written;
344 if (cli_sendB(cptr) > 1023) {
345 cli_sendK(cptr) += (cli_sendB(cptr) >> 10);
346 cli_sendB(cptr) &= 0x03ff; /* 2^10 = 1024, 3ff = 1023 */
348 if (cli_sendB(&me) > 1023) {
349 cli_sendK(&me) += (cli_sendB(&me) >> 10);
350 cli_sendB(&me) &= 0x03ff;
353 * XXX - hrmm.. set blocked here? the socket didn't
356 if (bytes_written < bytes_count)
357 cli_flags(cptr) |= FLAGS_BLOCKED;
360 cli_flags(cptr) |= FLAGS_BLOCKED;
363 cli_error(cptr) = errno;
364 cli_flags(cptr) |= FLAGS_DEADSOCKET;
367 return bytes_written;
371 void release_dns_reply(struct Client* cptr)
374 assert(MyConnect(cptr));
376 if (cli_dns_reply(cptr)) {
377 assert(0 < cli_dns_reply(cptr)->ref_count);
378 --(cli_dns_reply(cptr))->ref_count;
379 cli_dns_reply(cptr) = 0;
384 * completed_connection
386 * Complete non-blocking connect()-sequence. Check access and
387 * terminate connection, if trouble detected.
389 * Return TRUE, if successfully completed
390 * FALSE, if failed and ClientExit
392 static int completed_connection(struct Client* cptr)
394 struct ConfItem *aconf;
396 struct Client *acptr;
402 * get the socket status from the fd first to check if
403 * connection actually succeeded
405 if ((cli_error(cptr) = os_get_sockerr(cli_fd(cptr)))) {
406 const char* msg = strerror(cli_error(cptr));
408 msg = "Unknown error";
409 sendto_opmask_butone(0, SNO_OLDSNO, "Connection failed to %s: %s",
410 cli_name(cptr), msg);
413 if (!(aconf = find_conf_byname(cli_confs(cptr), cli_name(cptr), CONF_SERVER))) {
414 sendto_opmask_butone(0, SNO_OLDSNO, "Lost Server Line for %s", cli_name(cptr));
418 if (!EmptyString(aconf->passwd))
419 sendrawto_one(cptr, MSG_PASS " :%s", aconf->passwd);
422 * Create a unique timestamp
425 for (i = HighestFd; i > -1; --i) {
426 if ((acptr = LocalClientArray[i]) &&
427 (IsServer(acptr) || IsHandshake(acptr))) {
428 if (cli_serv(acptr)->timestamp >= newts)
429 newts = cli_serv(acptr)->timestamp + 1;
432 assert(0 != cli_serv(cptr));
434 cli_serv(cptr)->timestamp = newts;
437 * Make us timeout after twice the timeout for DNS look ups
439 cli_lasttime(cptr) = CurrentTime;
440 cli_flags(cptr) |= FLAGS_PINGSENT;
442 sendrawto_one(cptr, MSG_SERVER " %s 1 %Tu %Tu J%s %s%s :%s",
443 cli_name(&me), cli_serv(&me)->timestamp, newts, MAJOR_PROTOCOL,
444 NumServCap(&me), cli_info(&me));
446 return (IsDead(cptr)) ? 0 : 1;
452 * Close the physical connection. This function must make
453 * MyConnect(cptr) == FALSE, and set cptr->from == NULL.
455 void close_connection(struct Client *cptr)
457 struct ConfItem* aconf;
459 if (IsServer(cptr)) {
460 ServerStats->is_sv++;
461 ServerStats->is_sbs += cli_sendB(cptr);
462 ServerStats->is_sbr += cli_receiveB(cptr);
463 ServerStats->is_sks += cli_sendK(cptr);
464 ServerStats->is_skr += cli_receiveK(cptr);
465 ServerStats->is_sti += CurrentTime - cli_firsttime(cptr);
466 if (ServerStats->is_sbs > 1023) {
467 ServerStats->is_sks += (ServerStats->is_sbs >> 10);
468 ServerStats->is_sbs &= 0x3ff;
470 if (ServerStats->is_sbr > 1023) {
471 ServerStats->is_skr += (ServerStats->is_sbr >> 10);
472 ServerStats->is_sbr &= 0x3ff;
475 * If the connection has been up for a long amount of time, schedule
476 * a 'quick' reconnect, else reset the next-connect cycle.
478 if ((aconf = find_conf_exact(cli_name(cptr), 0, cli_sockhost(cptr), CONF_SERVER))) {
480 * Reschedule a faster reconnect, if this was a automaticly
481 * connected configuration entry. (Note that if we have had
482 * a rehash in between, the status has been changed to
483 * CONF_ILLEGAL). But only do this if it was a "good" link.
485 aconf->hold = CurrentTime;
486 aconf->hold += (aconf->hold - cli_since(cptr) > HANGONGOODLINK) ?
487 HANGONRETRYDELAY : ConfConFreq(aconf);
488 if (nextconnect > aconf->hold)
489 nextconnect = aconf->hold;
492 else if (IsUser(cptr)) {
493 ServerStats->is_cl++;
494 ServerStats->is_cbs += cli_sendB(cptr);
495 ServerStats->is_cbr += cli_receiveB(cptr);
496 ServerStats->is_cks += cli_sendK(cptr);
497 ServerStats->is_ckr += cli_receiveK(cptr);
498 ServerStats->is_cti += CurrentTime - cli_firsttime(cptr);
499 if (ServerStats->is_cbs > 1023) {
500 ServerStats->is_cks += (ServerStats->is_cbs >> 10);
501 ServerStats->is_cbs &= 0x3ff;
503 if (ServerStats->is_cbr > 1023) {
504 ServerStats->is_ckr += (ServerStats->is_cbr >> 10);
505 ServerStats->is_cbr &= 0x3ff;
509 ServerStats->is_ni++;
511 if (-1 < cli_fd(cptr)) {
512 flush_connections(cptr);
513 LocalClientArray[cli_fd(cptr)] = 0;
517 cli_flags(cptr) |= FLAGS_DEADSOCKET;
519 MsgQClear(&(cli_sendQ(cptr)));
520 client_drop_sendq(cli_connect(cptr));
521 DBufClear(&(cli_recvQ(cptr)));
522 memset(cli_passwd(cptr), 0, sizeof(cli_passwd(cptr)));
523 set_snomask(cptr, 0, SNO_SET);
525 det_confs_butmask(cptr, 0);
527 if (cli_listener(cptr)) {
528 release_listener(cli_listener(cptr));
529 cli_listener(cptr) = 0;
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(cli_sock_ip(new_client), (const char*) &addr.sin_addr);
606 strcpy(cli_sockhost(new_client), cli_sock_ip(new_client));
607 (cli_ip(new_client)).s_addr = addr.sin_addr.s_addr;
608 cli_port(new_client) = ntohs(addr.sin_port);
611 cli_nexttarget(new_client) = next_target;
613 cli_fd(new_client) = fd;
614 cli_listener(new_client) = 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(&(cli_recvQ(cptr))) > CLIENT_FLOOD)) {
637 switch (os_recv_nonb(cli_fd(cptr), readbuf, sizeof(readbuf), &length)) {
640 cli_lasttime(cptr) = CurrentTime;
641 if (cli_lasttime(cptr) > cli_since(cptr))
642 cli_since(cptr) = cli_lasttime(cptr);
643 cli_flags(cptr) &= ~(FLAGS_PINGSENT | FLAGS_NONL);
649 cli_error(cptr) = errno;
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(&(cli_recvQ(cptr)), 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(&(cli_recvQ(cptr))) > CLIENT_FLOOD)
676 return exit_client(cptr, cptr, &me, "Excess Flood");
678 while (DBufLength(&(cli_recvQ(cptr))) && !NoNewLine(cptr) &&
679 (IsTrusted(cptr) || cli_since(cptr) - CurrentTime < 10))
681 while (DBufLength(&(cli_recvQ(cptr))) && !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(&(cli_recvQ(cptr)), readbuf, sizeof(readbuf));
690 return (dolen) ? server_dopacket(cptr, readbuf, dolen) : 1;
692 dolen = dbuf_getmsg(&(cli_recvQ(cptr)), cli_buffer(cptr), 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(&(cli_recvQ(cptr))) < 510)
703 cli_flags(cptr) |= FLAGS_NONL;
705 DBufClear(&(cli_recvQ(cptr)));
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 cli_flags(cptr) &= ~FLAGS_BLOCKED;
720 if (IsConnecting(cptr)) {
721 if (!completed_connection(cptr))
724 else if (cli_listing(cptr) && MsgQLength(&(cli_sendQ(cptr))) < 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(&(cli_recvQ(cptr))))
904 if (DBufLength(&(cli_recvQ(cptr))) < 4088 || IsServer(cptr)) {
907 if (MsgQLength(&(cli_sendQ(cptr))) || IsConnecting(cptr) ||
908 (cli_listing(cptr) && MsgQLength(&(cli_sendQ(cptr))) < 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, cli_name(&me), 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 = (cli_error(cptr)) ? strerror(cli_error(cptr)) : cli_info(cptr);
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 = (cli_error(cptr)) ? strerror(cli_error(cptr)) : cli_info(cptr);
1038 msg = "Unknown error";
1039 exit_client(cptr, cptr, &me, (char*) msg);
1044 cli_flags(cptr) |= 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)) && cli_error(cptr) == 0 && length == 0)
1057 exit_client_msg(cptr, cptr, &me, "Server %s closed the connection (%s)",
1058 cli_name(cptr), cli_serv(cptr)->last_error_msg);
1060 const char* msg = (cli_error(cptr)) ? strerror(cli_error(cptr)) : "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(&(cli_recvQ(cptr))))
1143 if (DBufLength(&(cli_recvq(cptr))) < 4088 || IsServer(cptr))
1144 FD_SET(i, &read_set);
1145 if (MsgQLength(&(cli_sendq(cptr))) || IsConnecting(cptr) ||
1146 (cli_listing(cptr) && MsgQLength(&(cli_sendQ(cptr))) < 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, cli_name(&me), 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 = (cli_error(cptr)) ? strerror(cli_error(cptr)) : cli_info(cptr);
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 = (cli_error(cptr)) ? strerror(cli_error(cptr)) : cli_info(cptr);
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, cli_error(cptr), length));
1269 if ((IsServer(cptr) || IsHandshake(cptr)) && cli_error(cptr) == 0 && length == 0)
1270 exit_client_msg(cptr, cptr, &me, "Server %s closed the connection (%s)",
1271 cli_name(cptr), cli_serv(cptr)->last_error_msg);
1273 const char* msg = (cli_error(cptr)) ? strerror(cli_error(cptr)) : "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, cli_name(cli_from(cptr)));
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, cli_name(cli_from(cptr)));
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, cli_name(cptr));
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 cli_dns_reply(cptr) = reply;
1359 * Copy these in so we have something for error detection.
1361 ircd_strncpy(cli_name(cptr), aconf->name, HOSTLEN);
1362 ircd_strncpy(cli_sockhost(cptr), 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(cli_confs(cptr), 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(cli_serv(cptr)->by, "%s%s", NumNick(by));
1403 assert(0 == cli_serv(cptr)->user);
1404 cli_serv(cptr)->user = cli_user(by);
1405 cli_user(by)->refcnt++;
1408 *(cli_serv(cptr))->by = '\0';
1409 /* strcpy(cptr->serv->by, "Auto"); */
1411 cli_serv(cptr)->up = &me;
1412 SetConnecting(cptr);
1414 if (cli_fd(cptr) > HighestFd)
1415 HighestFd = cli_fd(cptr);
1418 LocalClientArray[cli_fd(cptr)] = 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(cli_name(&me), conf->name, HOSTLEN);
1453 SetYXXServerName(&me, conf->numeric);