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";
106 #ifndef NOFLOODCONTROL
107 #define NOFLOODCONTROL
111 #if !defined(USE_POLL)
112 #if FD_SETSIZE < (MAXCONNECTIONS + 4)
116 * All operating systems work when MAXCONNECTIONS <= 252.
117 * Most operating systems work when MAXCONNECTIONS <= 1020 and FD_SETSIZE is
118 * updated correctly in the system headers (on BSD systems our sys.h has
119 * defined FD_SETSIZE to MAXCONNECTIONS+4 before including the system's headers
120 * but sys/types.h might have abruptly redefined it so the check is still
121 * done), you might already need to recompile your kernel.
122 * For larger FD_SETSIZE your milage may vary (kernel patches may be needed).
123 * The check is _NOT_ done if we will not use FD_SETS at all (USE_POLL)
125 #error "FD_SETSIZE is too small or MAXCONNECTIONS too large."
131 * Cannot use perror() within daemon. stderr is closed in
132 * ircd and cannot be used. And, worse yet, it might have
133 * been reassigned to a normal connection...
139 * This a replacement for perror(). Record error to log and
140 * also send a copy to all *LOCAL* opers online.
142 * text is a *format* string for outputting error. It must
143 * contain only two '%s', the first will be replaced
144 * by the sockhost from the cptr, and the latter will
145 * be taken from sys_errlist[errno].
147 * cptr if not NULL, is the *LOCAL* client associated with
150 void report_error(const char* text, const char* who, int err)
152 static time_t last_notice = 0;
153 int errtmp = errno; /* debug may change 'errno' */
154 const char* errmsg = (err) ? strerror(err) : "";
157 errmsg = "Unknown error";
159 if (EmptyString(who))
162 if (last_notice + 20 < CurrentTime) {
164 * pace error messages so opers don't get flooded by transients
166 sendto_opmask_butone(0, SNO_OLDSNO, text, who, errmsg);
167 last_notice = CurrentTime;
169 log_write(LS_SOCKET, L_ERROR, 0, text, who, errmsg);
175 * connect_dns_callback - called when resolver query finishes
176 * if the query resulted in a successful search, reply will contain
177 * a non-null pointer, otherwise reply will be null.
178 * if successful start the connection, otherwise notify opers
180 static void connect_dns_callback(void* vptr, struct DNSReply* reply)
182 struct ConfItem* aconf = (struct ConfItem*) vptr;
183 aconf->dns_pending = 0;
185 memcpy(&aconf->ipnum, reply->hp->h_addr, sizeof(struct in_addr));
186 connect_server(aconf, 0, reply);
189 sendto_opmask_butone(0, SNO_OLDSNO, "Connect to %s failed: host lookup",
194 * close_connections - closes all connections
195 * close stderr if specified
197 void close_connections(int close_stderr)
204 for (i = 3; i < MAXCONNECTIONS; ++i)
209 * init_connection_limits - initialize process fd limit to
212 int init_connection_limits(void)
214 int limit = os_set_fdlimit(MAXCONNECTIONS);
218 fprintf(stderr, "error setting max fd's to %d\n", limit);
220 else if (limit > 0) {
221 fprintf(stderr, "ircd fd table too big\nHard Limit: %d IRC max: %d\n",
222 limit, MAXCONNECTIONS);
223 fprintf(stderr, "set MAXCONNECTIONS to a smaller value");
229 * connect_inet - set up address and port and make a connection
231 static int connect_inet(struct ConfItem* aconf, struct Client* cptr)
233 static struct sockaddr_in sin;
237 * Might as well get sockhost from here, the connection is attempted
238 * with it so if it fails its useless.
240 cli_fd(cptr) = socket(AF_INET, SOCK_STREAM, 0);
241 if (-1 == cli_fd(cptr)) {
242 cli_error(cptr) = errno;
243 report_error(SOCKET_ERROR_MSG, cli_name(cptr), errno);
246 if (cli_fd(cptr) >= MAXCLIENTS) {
247 report_error(CONNLIMIT_ERROR_MSG, cli_name(cptr), 0);
253 * Bind to a local IP# (with unknown port - let unix decide) so
254 * we have some chance of knowing the IP# that gets used for a host
255 * with more than one IP#.
257 * No we don't bind it, not all OS's can handle connecting with
258 * an already bound socket, different ip# might occur anyway
259 * leading to a freezing select() on this side for some time.
260 * I had this on my Linux 1.1.88 --Run
264 * No, we do bind it if we have virtual host support. If we don't
265 * explicitly bind it, it will default to IN_ADDR_ANY and we lose
266 * due to the other server not allowing our base IP --smg
268 if (bind(cli_fd(cptr), (struct sockaddr*) &VirtualHost, sizeof(VirtualHost))) {
269 report_error(BIND_ERROR_MSG, cli_name(cptr), errno);
274 memset(&sin, 0, sizeof(sin));
275 sin.sin_family = AF_INET;
276 sin.sin_addr.s_addr = aconf->ipnum.s_addr;
277 sin.sin_port = htons(aconf->port);
279 * save connection info in client
281 (cli_ip(cptr)).s_addr = aconf->ipnum.s_addr;
282 cli_port(cptr) = aconf->port;
283 ircd_ntoa_r(cli_sock_ip(cptr), (const char*) &(cli_ip(cptr)));
285 * we want a big buffer for server connections
287 if (!os_set_sockbufs(cli_fd(cptr), SERVER_TCP_WINDOW)) {
288 cli_error(cptr) = errno;
289 report_error(SETBUFS_ERROR_MSG, cli_name(cptr), errno);
293 * ALWAYS set sockets non-blocking
295 if (!os_set_nonblocking(cli_fd(cptr))) {
296 cli_error(cptr) = errno;
297 report_error(NONB_ERROR_MSG, cli_name(cptr), errno);
300 if (!os_connect_nonb(cli_fd(cptr), &sin)) {
301 cli_error(cptr) = errno;
302 report_error(CONNECT_ERROR_MSG, cli_name(cptr), errno);
310 * Attempt to send a sequence of bytes to the connection.
313 * < 0 Some fatal error occurred, (but not EWOULDBLOCK).
314 * This return is a request to close the socket and
317 * >= 0 No real error occurred, returns the number of
318 * bytes actually transferred. EWOULDBLOCK and other
319 * possibly similar conditions should be mapped to
320 * zero return. Upper level routine will have to
321 * decide what to do with those unwritten bytes...
323 * *NOTE* alarm calls have been preserved, so this should
324 * work equally well whether blocking or non-blocking
327 * We don't use blocking anymore, that is impossible with the
328 * net.loads today anyway. Commented out the alarms to save cpu.
331 unsigned int deliver_it(struct Client *cptr, struct MsgQ *buf)
333 unsigned int bytes_written = 0;
334 unsigned int bytes_count = 0;
337 switch (os_sendv_nonb(cli_fd(cptr), buf, &bytes_count, &bytes_written)) {
339 cli_flags(cptr) &= ~FLAGS_BLOCKED;
341 cli_sendB(cptr) += bytes_written;
342 cli_sendB(&me) += bytes_written;
343 if (cli_sendB(cptr) > 1023) {
344 cli_sendK(cptr) += (cli_sendB(cptr) >> 10);
345 cli_sendB(cptr) &= 0x03ff; /* 2^10 = 1024, 3ff = 1023 */
347 if (cli_sendB(&me) > 1023) {
348 cli_sendK(&me) += (cli_sendB(&me) >> 10);
349 cli_sendB(&me) &= 0x03ff;
352 * XXX - hrmm.. set blocked here? the socket didn't
355 if (bytes_written < bytes_count)
356 cli_flags(cptr) |= FLAGS_BLOCKED;
359 cli_flags(cptr) |= FLAGS_BLOCKED;
362 cli_error(cptr) = errno;
363 cli_flags(cptr) |= FLAGS_DEADSOCKET;
366 return bytes_written;
370 void release_dns_reply(struct Client* cptr)
373 assert(MyConnect(cptr));
375 if (cli_dns_reply(cptr)) {
376 assert(0 < cli_dns_reply(cptr)->ref_count);
377 --(cli_dns_reply(cptr))->ref_count;
378 cli_dns_reply(cptr) = 0;
383 * completed_connection
385 * Complete non-blocking connect()-sequence. Check access and
386 * terminate connection, if trouble detected.
388 * Return TRUE, if successfully completed
389 * FALSE, if failed and ClientExit
391 static int completed_connection(struct Client* cptr)
393 struct ConfItem *aconf;
395 struct Client *acptr;
401 * get the socket status from the fd first to check if
402 * connection actually succeeded
404 if ((cli_error(cptr) = os_get_sockerr(cli_fd(cptr)))) {
405 const char* msg = strerror(cli_error(cptr));
407 msg = "Unknown error";
408 sendto_opmask_butone(0, SNO_OLDSNO, "Connection failed to %s: %s",
409 cli_name(cptr), msg);
412 if (!(aconf = find_conf_byname(cli_confs(cptr), cli_name(cptr), CONF_SERVER))) {
413 sendto_opmask_butone(0, SNO_OLDSNO, "Lost Server Line for %s", cli_name(cptr));
417 if (!EmptyString(aconf->passwd))
418 sendrawto_one(cptr, MSG_PASS " :%s", aconf->passwd);
421 * Create a unique timestamp
424 for (i = HighestFd; i > -1; --i) {
425 if ((acptr = LocalClientArray[i]) &&
426 (IsServer(acptr) || IsHandshake(acptr))) {
427 if (cli_serv(acptr)->timestamp >= newts)
428 newts = cli_serv(acptr)->timestamp + 1;
431 assert(0 != cli_serv(cptr));
433 cli_serv(cptr)->timestamp = newts;
436 * Make us timeout after twice the timeout for DNS look ups
438 cli_lasttime(cptr) = CurrentTime;
439 cli_flags(cptr) |= FLAGS_PINGSENT;
441 sendrawto_one(cptr, MSG_SERVER " %s 1 %Tu %Tu J%s %s%s :%s",
442 cli_name(&me), cli_serv(&me)->timestamp, newts, MAJOR_PROTOCOL,
443 NumServCap(&me), cli_info(&me));
445 return (IsDead(cptr)) ? 0 : 1;
451 * Close the physical connection. This function must make
452 * MyConnect(cptr) == FALSE, and set cptr->from == NULL.
454 void close_connection(struct Client *cptr)
456 struct ConfItem* aconf;
458 if (IsServer(cptr)) {
459 ServerStats->is_sv++;
460 ServerStats->is_sbs += cli_sendB(cptr);
461 ServerStats->is_sbr += cli_receiveB(cptr);
462 ServerStats->is_sks += cli_sendK(cptr);
463 ServerStats->is_skr += cli_receiveK(cptr);
464 ServerStats->is_sti += CurrentTime - cli_firsttime(cptr);
465 if (ServerStats->is_sbs > 1023) {
466 ServerStats->is_sks += (ServerStats->is_sbs >> 10);
467 ServerStats->is_sbs &= 0x3ff;
469 if (ServerStats->is_sbr > 1023) {
470 ServerStats->is_skr += (ServerStats->is_sbr >> 10);
471 ServerStats->is_sbr &= 0x3ff;
474 * If the connection has been up for a long amount of time, schedule
475 * a 'quick' reconnect, else reset the next-connect cycle.
477 if ((aconf = find_conf_exact(cli_name(cptr), 0, cli_sockhost(cptr), CONF_SERVER))) {
479 * Reschedule a faster reconnect, if this was a automaticly
480 * connected configuration entry. (Note that if we have had
481 * a rehash in between, the status has been changed to
482 * CONF_ILLEGAL). But only do this if it was a "good" link.
484 aconf->hold = CurrentTime;
485 aconf->hold += (aconf->hold - cli_since(cptr) > HANGONGOODLINK) ?
486 HANGONRETRYDELAY : ConfConFreq(aconf);
487 if (nextconnect > aconf->hold)
488 nextconnect = aconf->hold;
491 else if (IsUser(cptr)) {
492 ServerStats->is_cl++;
493 ServerStats->is_cbs += cli_sendB(cptr);
494 ServerStats->is_cbr += cli_receiveB(cptr);
495 ServerStats->is_cks += cli_sendK(cptr);
496 ServerStats->is_ckr += cli_receiveK(cptr);
497 ServerStats->is_cti += CurrentTime - cli_firsttime(cptr);
498 if (ServerStats->is_cbs > 1023) {
499 ServerStats->is_cks += (ServerStats->is_cbs >> 10);
500 ServerStats->is_cbs &= 0x3ff;
502 if (ServerStats->is_cbr > 1023) {
503 ServerStats->is_ckr += (ServerStats->is_cbr >> 10);
504 ServerStats->is_cbr &= 0x3ff;
508 ServerStats->is_ni++;
510 if (-1 < cli_fd(cptr)) {
511 flush_connections(cptr);
512 LocalClientArray[cli_fd(cptr)] = 0;
516 cli_flags(cptr) |= FLAGS_DEADSOCKET;
518 MsgQClear(&(cli_sendQ(cptr)));
519 DBufClear(&(cli_recvQ(cptr)));
520 memset(cli_passwd(cptr), 0, sizeof(cli_passwd(cptr)));
521 set_snomask(cptr, 0, SNO_SET);
523 det_confs_butmask(cptr, 0);
525 if (cli_listener(cptr)) {
526 release_listener(cli_listener(cptr));
527 cli_listener(cptr) = 0;
530 for ( ; HighestFd > 0; --HighestFd) {
531 if (LocalClientArray[HighestFd])
536 int net_close_unregistered_connections(struct Client* source)
543 for (i = HighestFd; i > 0; --i) {
544 if ((cptr = LocalClientArray[i]) && !IsRegistered(cptr)) {
545 send_reply(source, RPL_CLOSING, get_client_name(source, HIDE_IP));
546 exit_client(source, cptr, &me, "Oper Closing");
553 /*----------------------------------------------------------------------------
556 * Creates a client which has just connected to us on the given fd.
557 * The sockhost field is initialized with the ip# of the host.
558 * The client is not added to the linked list of clients, it is
559 * passed off to the auth handler for dns and ident queries.
560 *--------------------------------------------------------------------------*/
561 void add_connection(struct Listener* listener, int fd) {
562 struct sockaddr_in addr;
563 struct Client *new_client;
564 time_t next_target = 0;
566 const char* const throttle_message =
567 "ERROR :Your host is trying to (re)connect too fast -- throttled\r\n";
568 /* 12345678901234567890123456789012345679012345678901234567890123456 */
570 assert(0 != listener);
574 * Removed preliminary access check. Full check is performed in m_server and
575 * m_user instead. Also connection time out help to get rid of unwanted
578 if (!os_get_peername(fd, &addr) || !os_set_nonblocking(fd)) {
579 ++ServerStats->is_ref;
585 * Add this local client to the IPcheck registry.
587 * If they're throttled, murder them, but tell them why first.
589 if (!IPcheck_local_connect(addr.sin_addr, &next_target) && !listener->server) {
590 ++ServerStats->is_ref;
591 write(fd, throttle_message, strlen(throttle_message));
596 new_client = make_client(0, ((listener->server) ?
597 STAT_UNKNOWN_SERVER : STAT_UNKNOWN_USER));
600 * Copy ascii address to 'sockhost' just in case. Then we have something
601 * valid to put into error messages...
603 ircd_ntoa_r(cli_sock_ip(new_client), (const char*) &addr.sin_addr);
604 strcpy(cli_sockhost(new_client), cli_sock_ip(new_client));
605 (cli_ip(new_client)).s_addr = addr.sin_addr.s_addr;
606 cli_port(new_client) = ntohs(addr.sin_port);
609 cli_nexttarget(new_client) = next_target;
611 cli_fd(new_client) = fd;
612 cli_listener(new_client) = listener;
613 ++listener->ref_count;
615 Count_newunknown(UserStats);
616 /* if we've made it this far we can put the client on the auth query pile */
617 start_auth(new_client);
624 * Read a 'packet' of data from a connection and process it. Read in 8k
625 * chunks to give a better performance rating (for server connections).
626 * Do some tricky stuff for client connections to make sure they don't do
627 * any flooding >:-) -avalon
629 static int read_packet(struct Client *cptr, int socket_ready)
631 unsigned int dolen = 0;
632 unsigned int length = 0;
634 if (socket_ready && !(IsUser(cptr) && DBufLength(&(cli_recvQ(cptr))) > CLIENT_FLOOD)) {
635 switch (os_recv_nonb(cli_fd(cptr), readbuf, sizeof(readbuf), &length)) {
638 cli_lasttime(cptr) = CurrentTime;
639 if (cli_lasttime(cptr) > cli_since(cptr))
640 cli_since(cptr) = cli_lasttime(cptr);
641 cli_flags(cptr) &= ~(FLAGS_PINGSENT | FLAGS_NONL);
647 cli_error(cptr) = errno;
648 /* cptr->flags |= FLAGS_DEADSOCKET; */
654 * For server connections, we process as many as we can without
655 * worrying about the time of day or anything :)
657 if (length > 0 && IsServer(cptr)) {
658 return server_dopacket(cptr, readbuf, length);
662 * Before we even think of parsing what we just read, stick
663 * it on the end of the receive queue and do it when its
666 if (length > 0 && 0 == dbuf_put(&(cli_recvQ(cptr)), readbuf, length)) {
667 return exit_client(cptr, cptr, &me, "dbuf_put fail");
669 #ifndef NOFLOODCONTROL
671 * XXX - cptr will always be a user or unregistered
673 if (IsUser(cptr) && DBufLength(&(cli_recvQ(cptr))) > CLIENT_FLOOD)
674 return exit_client(cptr, cptr, &me, "Excess Flood");
676 while (DBufLength(&(cli_recvQ(cptr))) && !NoNewLine(cptr) &&
677 (IsTrusted(cptr) || cli_since(cptr) - CurrentTime < 10))
679 while (DBufLength(&(cli_recvQ(cptr))) && !NoNewLine(cptr))
683 * If it has become registered as a Server
684 * then skip the per-message parsing below.
686 if (IsServer(cptr)) {
687 dolen = dbuf_get(&(cli_recvQ(cptr)), readbuf, sizeof(readbuf));
688 return (dolen) ? server_dopacket(cptr, readbuf, dolen) : 1;
690 dolen = dbuf_getmsg(&(cli_recvQ(cptr)), cli_buffer(cptr), BUFSIZE);
692 * Devious looking...whats it do ? well..if a client
693 * sends a *long* message without any CR or LF, then
694 * dbuf_getmsg fails and we pull it out using this
695 * loop which just gets the next 512 bytes and then
696 * deletes the rest of the buffer contents.
700 if (DBufLength(&(cli_recvQ(cptr))) < 510)
701 cli_flags(cptr) |= FLAGS_NONL;
703 DBufClear(&(cli_recvQ(cptr)));
705 else if (CPTR_KILLED == client_dopacket(cptr, dolen))
712 static int on_write_unblocked(struct Client* cptr)
715 * ...room for writing, empty some queue then...
717 cli_flags(cptr) &= ~FLAGS_BLOCKED;
718 if (IsConnecting(cptr)) {
719 if (!completed_connection(cptr))
722 else if (cli_listing(cptr) && MsgQLength(&(cli_sendQ(cptr))) < 2048)
723 list_next_channels(cptr, 64);
729 * Select / Poll Read Algorithm for ircd
731 * We need to check the file descriptors for all the different types
732 * of things that use them, so check for reads on everything but connects
733 * and writes on connects and descriptors that are blocked
735 * for each (client in local) {
736 * if (not connecting)
738 * if (connecting or blocked)
743 * for each (client in local) {
744 * if (there are descriptors to check) {
745 * if (write activity)
752 * Note we must always process data read whether or not there has been
753 * read activity or file descriptors set, since data is buffered by the client.
762 #if defined(POLLMSG) && defined(POLLIN) && defined(POLLRDNORM)
763 # define POLLREADFLAGS (POLLMSG|POLLIN|POLLRDNORM)
765 # if defined(POLLIN) && defined(POLLRDNORM)
766 # define POLLREADFLAGS (POLLIN|POLLRDNORM)
769 # define POLLREADFLAGS POLLIN
771 # if defined(POLLRDNORM)
772 # define POLLREADFLAGS POLLRDNORM
778 #if defined(POLLOUT) && defined(POLLWRNORM)
779 #define POLLWRITEFLAGS (POLLOUT|POLLWRNORM)
781 # if defined(POLLOUT)
782 # define POLLWRITEFLAGS POLLOUT
784 # if defined(POLLWRNORM)
785 # define POLLWRITEFLAGS POLLWRNORM
791 #define POLLERRORS (POLLHUP|POLLERR)
793 #define POLLERRORS POLLERR
797 * NOTE: pfd and pfd_count are local variable names in read_message
799 #define PFD_SETR(xfd) \
800 do { CHECK_ADD_PFD(xfd) pfd->events |= POLLREADFLAGS; } while(0)
801 #define PFD_SETW(xfd) \
802 do { CHECK_ADD_PFD(xfd) pfd->events |= POLLWRITEFLAGS; } while(0)
804 #define CHECK_ADD_PFD(xfd) \
805 if (pfd->fd != xfd) { \
806 pfd = &poll_fds[pfd_count++]; \
807 poll_fds[pfd_count].fd = -1; \
813 * Check all connections for new connections and input data that is to be
814 * processed. Also check for connections with data queued and whether we can
817 * Don't ever use ZERO for `delay', unless you mean to poll and then
818 * you have to have sleep/wait somewhere else in the code.--msa
820 int read_message(time_t delay)
822 struct pollfd poll_fds[MAXCONNECTIONS + 1];
824 struct Listener* listener = 0;
825 struct AuthRequest* auth = 0;
826 struct AuthRequest* auth_next = 0;
827 struct UPing* uping = 0;
828 struct UPing* uping_next = 0;
829 time_t delay2 = delay;
836 struct pollfd* res_pfd;
837 struct pollfd* uping_pfd;
841 unsigned int timeout;
850 if (-1 < ResolverFileDescriptor) {
851 PFD_SETR(ResolverFileDescriptor);
854 if (-1 < UPingFileDescriptor) {
855 PFD_SETR(UPingFileDescriptor);
859 * add uping descriptors
861 for (uping = uping_begin(); uping; uping = uping_next) {
862 uping_next = uping->next;
865 if (uping->lastsent && CurrentTime > uping->timeout) {
869 uping->index = pfd_count;
874 * add auth file descriptors
876 for (auth = AuthPollList; auth; auth = auth->next) {
877 assert(-1 < auth->fd);
878 auth->index = pfd_count;
879 if (IsAuthConnect(auth))
885 * add listener file descriptors
887 for (listener = ListenerPollList; listener; listener = listener->next) {
888 assert(-1 < listener->fd);
890 * pfd_count is incremented by PFD_SETR so we need to save the
893 listener->index = pfd_count;
894 PFD_SETR(listener->fd);
897 for (i = HighestFd; -1 < i; --i) {
898 if ((cptr = LocalClientArray[i])) {
900 if (DBufLength(&(cli_recvQ(cptr))))
902 if (DBufLength(&(cli_recvQ(cptr))) < 4088 || IsServer(cptr)) {
905 if (MsgQLength(&(cli_sendQ(cptr))) || IsConnecting(cptr) ||
906 (cli_listing(cptr) && MsgQLength(&(cli_sendQ(cptr))) < 2048)) {
912 Debug((DEBUG_INFO, "poll: %d %d", delay, delay2));
914 timeout = (IRCD_MIN(delay2, delay)) * 1000;
916 nfds = poll(poll_fds, pfd_count, timeout);
918 CurrentTime = time(0);
924 report_error(POLL_ERROR_MSG, cli_name(&me), errno);
927 server_restart("too many poll errors");
929 CurrentTime = time(0);
932 if (uping_pfd && (uping_pfd->revents & (POLLREADFLAGS | POLLERRORS))) {
937 * check uping replies
939 for (uping = uping_begin(); uping; uping = uping_next) {
940 uping_next = uping->next;
942 assert(-1 < uping->index);
943 if (poll_fds[uping->index].revents) {
948 else if (CurrentTime > uping->lastsent) {
949 uping->lastsent = CurrentTime;
955 if (res_pfd && (res_pfd->revents & (POLLREADFLAGS | POLLERRORS))) {
962 for (auth = AuthPollList; auth; auth = auth_next) {
963 auth_next = auth->next;
966 * check for any event, we only ask for one at a time
968 if (poll_fds[i].revents) {
969 if (IsAuthConnect(auth))
970 send_auth_query(auth);
972 read_auth_reply(auth);
980 for (listener = ListenerPollList; listener; listener = listener->next) {
982 if (poll_fds[i].revents) {
983 accept_connection(listener);
989 * i contains the next non-auth/non-listener index, since we put the
990 * resolver, auth and listener, file descriptors in poll_fds first,
991 * the very next one should be the start of the clients
993 pfd = &poll_fds[++i];
995 for ( ; (i < pfd_count); ++i, ++pfd) {
996 if (!(cptr = LocalClientArray[pfd->fd]))
998 read_ready = write_ready = 0;
1000 if (0 < nfds && pfd->revents) {
1003 read_ready = pfd->revents & POLLREADFLAGS;
1004 write_ready = pfd->revents & POLLWRITEFLAGS;
1006 if (pfd->revents & POLLERRORS) {
1007 if (pfd->events & POLLREADFLAGS)
1009 if (pfd->events & POLLWRITEFLAGS)
1014 if (!on_write_unblocked(cptr) || IsDead(cptr)) {
1015 const char* msg = (cli_error(cptr)) ? strerror(cli_error(cptr)) : cli_info(cptr);
1017 msg = "Unknown error";
1018 exit_client(cptr, cptr, &me, msg);
1022 length = 1; /* for fall through case */
1023 if ((!NoNewLine(cptr) || read_ready) && !IsDead(cptr)) {
1024 if (CPTR_KILLED == (length = read_packet(cptr, read_ready)))
1028 /* Bullshit, why would we want to flush sockets while using non-blocking?
1029 * This uses > 4% cpu! --Run */
1031 flush_connections(poll_cptr[i]);
1034 const char* msg = (cli_error(cptr)) ? strerror(cli_error(cptr)) : cli_info(cptr);
1036 msg = "Unknown error";
1037 exit_client(cptr, cptr, &me, (char*) msg);
1042 cli_flags(cptr) |= FLAGS_DEADSOCKET;
1044 * ...hmm, with non-blocking sockets we might get
1045 * here from quite valid reasons, although.. why
1046 * would select report "data available" when there
1047 * wasn't... So, this must be an error anyway... --msa
1048 * actually, EOF occurs when read() returns 0 and
1049 * in due course, select() returns that fd as ready
1050 * for reading even though it ends up being an EOF. -avalon
1052 Debug((DEBUG_ERROR, "READ ERROR: fd = %d %d %d", pfd->fd, errno, length));
1054 if ((IsServer(cptr) || IsHandshake(cptr)) && cli_error(cptr) == 0 && length == 0)
1055 exit_client_msg(cptr, cptr, &me, "Server %s closed the connection (%s)",
1056 cli_name(cptr), cli_serv(cptr)->last_error_msg);
1058 const char* msg = (cli_error(cptr)) ? strerror(cli_error(cptr)) : "EOF from client";
1060 msg = "Unknown error";
1061 exit_client_msg(cptr, cptr, &me, "Read error: %s", msg);
1066 #else /* USE_SELECT */
1069 * Check all connections for new connections and input data that is to be
1070 * processed. Also check for connections with data queued and whether we can
1073 * Don't ever use ZERO for `delay', unless you mean to poll and then
1074 * you have to have sleep/wait somewhere else in the code.--msa
1076 int read_message(time_t delay)
1078 struct Client* cptr;
1079 struct Listener* listener;
1080 struct AuthRequest* auth = 0;
1081 struct AuthRequest* auth_next = 0;
1082 struct UPing* uping;
1083 struct UPing* uping_next;
1085 struct timeval wait;
1086 time_t delay2 = delay;
1087 unsigned int usec = 0;
1098 FD_ZERO(&write_set);
1100 if (-1 < ResolverFileDescriptor)
1101 FD_SET(ResolverFileDescriptor, &read_set);
1102 if (-1 < UPingFileDescriptor)
1103 FD_SET(UPingFileDescriptor, &read_set);
1105 * set up uping file descriptors
1107 for (uping = uping_begin(); uping; uping = uping_next) {
1108 uping_next = uping->next;
1109 if (uping->active) {
1111 if (uping->lastsent && CurrentTime > uping->timeout) {
1115 assert(-1 < uping->fd);
1116 FD_SET(uping->fd, &read_set);
1120 * set auth file descriptors
1122 for (auth = AuthPollList; auth; auth = auth->next) {
1123 assert(-1 < auth->fd);
1124 if (IsAuthConnect(auth))
1125 FD_SET(auth->fd, &write_set);
1126 else /* if (IsAuthPending(auth)) */
1127 FD_SET(auth->fd, &read_set);
1130 * set listener file descriptors
1132 for (listener = ListenerPollList; listener; listener = listener->next) {
1133 assert(-1 < listener->fd);
1134 FD_SET(listener->fd, &read_set);
1137 for (i = HighestFd; i > -1; --i) {
1138 if ((cptr = LocalClientArray[i])) {
1139 if (DBufLength(&(cli_recvQ(cptr))))
1141 if (DBufLength(&(cli_recvq(cptr))) < 4088 || IsServer(cptr))
1142 FD_SET(i, &read_set);
1143 if (MsgQLength(&(cli_sendq(cptr))) || IsConnecting(cptr) ||
1144 (cli_listing(cptr) && MsgQLength(&(cli_sendQ(cptr))) < 2048))
1145 FD_SET(i, &write_set);
1149 wait.tv_sec = IRCD_MIN(delay2, delay);
1150 wait.tv_usec = usec;
1152 Debug((DEBUG_INFO, "select: %d %d", delay, delay2));
1154 nfds = select(FD_SETSIZE, &read_set, &write_set, 0, &wait);
1156 CurrentTime = time(0);
1163 report_error(SELECT_ERROR_MSG, cli_name(&me), errno);
1165 server_restart("too many select errors");
1167 CurrentTime = time(0);
1170 if (-1 < UPingFileDescriptor && FD_ISSET(UPingFileDescriptor, &read_set)) {
1174 for (uping = uping_begin(); uping; uping = uping_next) {
1175 uping_next = uping->next;
1176 if (uping->active) {
1177 assert(-1 < uping->fd);
1178 if (FD_ISSET(uping->fd, &read_set)) {
1183 else if (CurrentTime > uping->lastsent) {
1184 uping->lastsent = CurrentTime;
1189 if (-1 < ResolverFileDescriptor && FD_ISSET(ResolverFileDescriptor, &read_set)) {
1194 * Check fd sets for the auth fd's (if set and valid!) first
1195 * because these can not be processed using the normal loops below.
1198 for (auth = AuthPollList; auth; auth = auth_next) {
1199 auth_next = auth->next;
1200 assert(-1 < auth->fd);
1201 if (IsAuthConnect(auth) && FD_ISSET(auth->fd, &write_set)) {
1202 send_auth_query(auth);
1206 else if (FD_ISSET(auth->fd, &read_set)) {
1207 read_auth_reply(auth);
1213 * next accept connections from active listeners
1215 for (listener = ListenerPollList; listener; listener = listener->next) {
1216 assert(-1 < listener->fd);
1217 if (0 < nfds && FD_ISSET(listener->fd, &read_set))
1218 accept_connection(listener);
1221 for (i = HighestFd; -1 < i; --i) {
1222 if (!(cptr = LocalClientArray[i]))
1226 if (FD_ISSET(i, &write_set)) {
1228 if (!on_write_unblocked(cptr) || IsDead(cptr)) {
1229 const char* msg = (cli_error(cptr)) ? strerror(cli_error(cptr)) : cli_info(cptr);
1231 msg = "Unknown error";
1232 if (FD_ISSET(i, &read_set))
1234 exit_client(cptr, cptr, &me, msg);
1238 if ((read_ready = FD_ISSET(i, &read_set)))
1241 length = 1; /* for fall through case */
1242 if ((!NoNewLine(cptr) || read_ready) && !IsDead(cptr)) {
1243 if (CPTR_KILLED == (length = read_packet(cptr, read_ready)))
1247 const char* msg = (cli_error(cptr)) ? strerror(cli_error(cptr)) : cli_info(cptr);
1249 msg = "Unknown error";
1250 exit_client(cptr, cptr, &me, msg);
1257 * ...hmm, with non-blocking sockets we might get
1258 * here from quite valid reasons, although.. why
1259 * would select report "data available" when there
1260 * wasn't... So, this must be an error anyway... --msa
1261 * actually, EOF occurs when read() returns 0 and
1262 * in due course, select() returns that fd as ready
1263 * for reading even though it ends up being an EOF. -avalon
1265 Debug((DEBUG_ERROR, "READ ERROR: fd = %d %d %d", i, cli_error(cptr), length));
1267 if ((IsServer(cptr) || IsHandshake(cptr)) && cli_error(cptr) == 0 && length == 0)
1268 exit_client_msg(cptr, cptr, &me, "Server %s closed the connection (%s)",
1269 cli_name(cptr), cli_serv(cptr)->last_error_msg);
1271 const char* msg = (cli_error(cptr)) ? strerror(cli_error(cptr)) : "EOF from client";
1273 msg = "Unknown error";
1274 exit_client_msg(cptr, cptr, &me, "Read error: %s", msg);
1280 #endif /* USE_SELECT */
1283 * connect_server - start or complete a connection to another server
1284 * returns true (1) if successful, false (0) otherwise
1286 * aconf must point to a valid C:line
1287 * m_connect calls this with a valid by client and a null reply
1288 * try_connections calls this with a null by client, and a null reply
1289 * connect_dns_callback call this with a null by client, and a valid reply
1291 * XXX - if this comes from an m_connect message and a dns query needs to
1292 * be done, we loose the information about who started the connection and
1293 * it's considered an auto connect.
1295 int connect_server(struct ConfItem* aconf, struct Client* by,
1296 struct DNSReply* reply)
1298 struct Client* cptr = 0;
1301 if (aconf->dns_pending) {
1302 sendto_opmask_butone(0, SNO_OLDSNO, "Server %s connect DNS pending",
1306 Debug((DEBUG_NOTICE, "Connect to %s[@%s]", aconf->name,
1307 ircd_ntoa((const char*) &aconf->ipnum)));
1309 if ((cptr = FindClient(aconf->name))) {
1310 if (IsServer(cptr) || IsMe(cptr)) {
1311 sendto_opmask_butone(0, SNO_OLDSNO, "Server %s already present from %s",
1312 aconf->name, cli_name(cli_from(cptr)));
1313 if (by && IsUser(by) && !MyUser(by)) {
1314 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Server %s already present "
1315 "from %s", by, aconf->name, cli_name(cli_from(cptr)));
1319 else if (IsHandshake(cptr) || IsConnecting(cptr)) {
1320 if (by && IsUser(by)) {
1321 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Connection to %s already in "
1322 "progress", by, cli_name(cptr));
1328 * If we dont know the IP# for this host and itis a hostname and
1329 * not a ip# string, then try and find the appropriate host record.
1331 if (INADDR_NONE == aconf->ipnum.s_addr) {
1332 char buf[HOSTLEN + 1];
1334 if (INADDR_NONE == (aconf->ipnum.s_addr = inet_addr(aconf->host))) {
1335 struct DNSQuery query;
1338 query.callback = connect_dns_callback;
1339 host_from_uh(buf, aconf->host, HOSTLEN);
1340 buf[HOSTLEN] = '\0';
1342 reply = gethost_byname(buf, &query);
1345 aconf->dns_pending = 1;
1348 memcpy(&aconf->ipnum, reply->hp->h_addr, sizeof(struct in_addr));
1351 cptr = make_client(NULL, STAT_UNKNOWN_SERVER);
1354 cli_dns_reply(cptr) = reply;
1357 * Copy these in so we have something for error detection.
1359 ircd_strncpy(cli_name(cptr), aconf->name, HOSTLEN);
1360 ircd_strncpy(cli_sockhost(cptr), aconf->host, HOSTLEN);
1363 * Attach config entries to client here rather than in
1364 * completed_connection. This to avoid null pointer references
1366 attach_confs_byhost(cptr, aconf->host, CONF_SERVER);
1368 if (!find_conf_byhost(cli_confs(cptr), aconf->host, CONF_SERVER)) {
1369 sendto_opmask_butone(0, SNO_OLDSNO, "Host %s is not enabled for "
1370 "connecting: no C-line", aconf->name);
1371 if (by && IsUser(by) && !MyUser(by)) {
1372 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Connect to host %s failed: no "
1373 "C-line", by, aconf->name);
1375 det_confs_butmask(cptr, 0);
1380 * attempt to connect to the server in the conf line
1382 if (!connect_inet(aconf, cptr)) {
1383 if (by && IsUser(by) && !MyUser(by)) {
1384 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Couldn't connect to %s", by,
1387 det_confs_butmask(cptr, 0);
1392 * NOTE: if we're here we have a valid C:Line and the client should
1393 * have started the connection and stored the remote address/port and
1394 * ip address name in itself
1396 * The socket has been connected or connect is in progress.
1399 if (by && IsUser(by)) {
1400 sprintf_irc(cli_serv(cptr)->by, "%s%s", NumNick(by));
1401 assert(0 == cli_serv(cptr)->user);
1402 cli_serv(cptr)->user = cli_user(by);
1403 cli_user(by)->refcnt++;
1406 *(cli_serv(cptr))->by = '\0';
1407 /* strcpy(cptr->serv->by, "Auto"); */
1409 cli_serv(cptr)->up = &me;
1410 SetConnecting(cptr);
1412 if (cli_fd(cptr) > HighestFd)
1413 HighestFd = cli_fd(cptr);
1416 LocalClientArray[cli_fd(cptr)] = cptr;
1418 Count_newunknown(UserStats);
1419 /* Actually we lie, the connect hasn't succeeded yet, but we have a valid
1420 * cptr, so we register it now.
1421 * Maybe these two calls should be merged.
1423 add_client_to_list(cptr);
1425 nextping = CurrentTime;
1431 * Setup local socket structure to use for binding to.
1433 void set_virtual_host(struct in_addr addr)
1435 memset(&VirtualHost, 0, sizeof(VirtualHost));
1436 VirtualHost.sin_family = AF_INET;
1437 VirtualHost.sin_addr.s_addr = addr.s_addr;
1441 * Find the real hostname for the host running the server (or one which
1442 * matches the server's name) and its primary IP#. Hostname is stored
1443 * in the client structure passed as a pointer.
1445 void init_server_identity(void)
1447 const struct LocalConf* conf = conf_get_local();
1450 ircd_strncpy(cli_name(&me), conf->name, HOSTLEN);
1451 SetYXXServerName(&me, conf->numeric);