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_features.h"
30 #include "ircd_osdep.h"
31 #include "ircd_reply.h"
32 #include "ircd_string.h"
42 #include "querycmds.h"
50 #include "sprintf_irc.h"
57 #include <arpa/inet.h>
58 #include <arpa/nameser.h>
67 #include <sys/ioctl.h>
68 #include <sys/socket.h>
70 #include <sys/utsname.h>
78 #define INADDR_NONE 0xffffffff
81 struct Client* LocalClientArray[MAXCONNECTIONS];
83 struct sockaddr_in VirtualHost;
84 static char readbuf[SERVER_TCP_WINDOW];
87 * report_error text constants
89 const char* const ACCEPT_ERROR_MSG = "error accepting connection for %s: %s";
90 const char* const BIND_ERROR_MSG = "bind error for %s: %s";
91 const char* const CONNECT_ERROR_MSG = "connect to host %s failed: %s";
92 const char* const CONNLIMIT_ERROR_MSG = "connect limit exceeded for %s: %s";
93 const char* const LISTEN_ERROR_MSG = "listen error for %s: %s";
94 const char* const NONB_ERROR_MSG = "error setting non-blocking for %s: %s";
95 const char* const PEERNAME_ERROR_MSG = "getpeername failed for %s: %s";
96 const char* const POLL_ERROR_MSG = "poll error for %s: %s";
97 const char* const REUSEADDR_ERROR_MSG = "error setting SO_REUSEADDR for %s: %s";
98 const char* const SELECT_ERROR_MSG = "select error for %s: %s";
99 const char* const SETBUFS_ERROR_MSG = "error setting buffer size for %s: %s";
100 const char* const SOCKET_ERROR_MSG = "error creating socket for %s: %s";
101 const char* const TOS_ERROR_MSG = "error setting TOS for %s: %s";
104 #if !defined(USE_POLL)
105 #if FD_SETSIZE < (MAXCONNECTIONS + 4)
109 * All operating systems work when MAXCONNECTIONS <= 252.
110 * Most operating systems work when MAXCONNECTIONS <= 1020 and FD_SETSIZE is
111 * updated correctly in the system headers (on BSD systems our sys.h has
112 * defined FD_SETSIZE to MAXCONNECTIONS+4 before including the system's headers
113 * but sys/types.h might have abruptly redefined it so the check is still
114 * done), you might already need to recompile your kernel.
115 * For larger FD_SETSIZE your milage may vary (kernel patches may be needed).
116 * The check is _NOT_ done if we will not use FD_SETS at all (USE_POLL)
118 #error "FD_SETSIZE is too small or MAXCONNECTIONS too large."
124 * Cannot use perror() within daemon. stderr is closed in
125 * ircd and cannot be used. And, worse yet, it might have
126 * been reassigned to a normal connection...
132 * This a replacement for perror(). Record error to log and
133 * also send a copy to all *LOCAL* opers online.
135 * text is a *format* string for outputting error. It must
136 * contain only two '%s', the first will be replaced
137 * by the sockhost from the cptr, and the latter will
138 * be taken from sys_errlist[errno].
140 * cptr if not NULL, is the *LOCAL* client associated with
143 void report_error(const char* text, const char* who, int err)
145 static time_t last_notice = 0;
146 int errtmp = errno; /* debug may change 'errno' */
147 const char* errmsg = (err) ? strerror(err) : "";
150 errmsg = "Unknown error";
152 if (EmptyString(who))
155 if (last_notice + 20 < CurrentTime) {
157 * pace error messages so opers don't get flooded by transients
159 sendto_opmask_butone(0, SNO_OLDSNO, text, who, errmsg);
160 last_notice = CurrentTime;
162 log_write(LS_SOCKET, L_ERROR, 0, text, who, errmsg);
168 * connect_dns_callback - called when resolver query finishes
169 * if the query resulted in a successful search, reply will contain
170 * a non-null pointer, otherwise reply will be null.
171 * if successful start the connection, otherwise notify opers
173 static void connect_dns_callback(void* vptr, struct DNSReply* reply)
175 struct ConfItem* aconf = (struct ConfItem*) vptr;
176 aconf->dns_pending = 0;
178 memcpy(&aconf->ipnum, reply->hp->h_addr, sizeof(struct in_addr));
179 connect_server(aconf, 0, reply);
182 sendto_opmask_butone(0, SNO_OLDSNO, "Connect to %s failed: host lookup",
187 * close_connections - closes all connections
188 * close stderr if specified
190 void close_connections(int close_stderr)
197 for (i = 3; i < MAXCONNECTIONS; ++i)
202 * init_connection_limits - initialize process fd limit to
205 int init_connection_limits(void)
207 int limit = os_set_fdlimit(MAXCONNECTIONS);
211 fprintf(stderr, "error setting max fd's to %d\n", limit);
213 else if (limit > 0) {
214 fprintf(stderr, "ircd fd table too big\nHard Limit: %d IRC max: %d\n",
215 limit, MAXCONNECTIONS);
216 fprintf(stderr, "set MAXCONNECTIONS to a smaller value");
222 * connect_inet - set up address and port and make a connection
224 static int connect_inet(struct ConfItem* aconf, struct Client* cptr)
226 static struct sockaddr_in sin;
230 * Might as well get sockhost from here, the connection is attempted
231 * with it so if it fails its useless.
233 cli_fd(cptr) = socket(AF_INET, SOCK_STREAM, 0);
234 if (-1 == cli_fd(cptr)) {
235 cli_error(cptr) = errno;
236 report_error(SOCKET_ERROR_MSG, cli_name(cptr), errno);
239 if (cli_fd(cptr) >= MAXCLIENTS) {
240 report_error(CONNLIMIT_ERROR_MSG, cli_name(cptr), 0);
246 * Bind to a local IP# (with unknown port - let unix decide) so
247 * we have some chance of knowing the IP# that gets used for a host
248 * with more than one IP#.
250 * No we don't bind it, not all OS's can handle connecting with
251 * an already bound socket, different ip# might occur anyway
252 * leading to a freezing select() on this side for some time.
253 * I had this on my Linux 1.1.88 --Run
257 * No, we do bind it if we have virtual host support. If we don't
258 * explicitly bind it, it will default to IN_ADDR_ANY and we lose
259 * due to the other server not allowing our base IP --smg
261 if (feature_bool(FEAT_VIRTUAL_HOST) &&
262 bind(cli_fd(cptr), (struct sockaddr*) &VirtualHost,
263 sizeof(VirtualHost))) {
264 report_error(BIND_ERROR_MSG, cli_name(cptr), errno);
268 memset(&sin, 0, sizeof(sin));
269 sin.sin_family = AF_INET;
270 sin.sin_addr.s_addr = aconf->ipnum.s_addr;
271 sin.sin_port = htons(aconf->port);
273 * save connection info in client
275 (cli_ip(cptr)).s_addr = aconf->ipnum.s_addr;
276 cli_port(cptr) = aconf->port;
277 ircd_ntoa_r(cli_sock_ip(cptr), (const char*) &(cli_ip(cptr)));
279 * we want a big buffer for server connections
281 if (!os_set_sockbufs(cli_fd(cptr), SERVER_TCP_WINDOW)) {
282 cli_error(cptr) = errno;
283 report_error(SETBUFS_ERROR_MSG, cli_name(cptr), errno);
287 * ALWAYS set sockets non-blocking
289 if (!os_set_nonblocking(cli_fd(cptr))) {
290 cli_error(cptr) = errno;
291 report_error(NONB_ERROR_MSG, cli_name(cptr), errno);
294 if (!os_connect_nonb(cli_fd(cptr), &sin)) {
295 cli_error(cptr) = errno;
296 report_error(CONNECT_ERROR_MSG, cli_name(cptr), errno);
304 * Attempt to send a sequence of bytes to the connection.
307 * < 0 Some fatal error occurred, (but not EWOULDBLOCK).
308 * This return is a request to close the socket and
311 * >= 0 No real error occurred, returns the number of
312 * bytes actually transferred. EWOULDBLOCK and other
313 * possibly similar conditions should be mapped to
314 * zero return. Upper level routine will have to
315 * decide what to do with those unwritten bytes...
317 * *NOTE* alarm calls have been preserved, so this should
318 * work equally well whether blocking or non-blocking
321 * We don't use blocking anymore, that is impossible with the
322 * net.loads today anyway. Commented out the alarms to save cpu.
325 unsigned int deliver_it(struct Client *cptr, struct MsgQ *buf)
327 unsigned int bytes_written = 0;
328 unsigned int bytes_count = 0;
331 switch (os_sendv_nonb(cli_fd(cptr), buf, &bytes_count, &bytes_written)) {
333 cli_flags(cptr) &= ~FLAGS_BLOCKED;
335 cli_sendB(cptr) += bytes_written;
336 cli_sendB(&me) += bytes_written;
337 if (cli_sendB(cptr) > 1023) {
338 cli_sendK(cptr) += (cli_sendB(cptr) >> 10);
339 cli_sendB(cptr) &= 0x03ff; /* 2^10 = 1024, 3ff = 1023 */
341 if (cli_sendB(&me) > 1023) {
342 cli_sendK(&me) += (cli_sendB(&me) >> 10);
343 cli_sendB(&me) &= 0x03ff;
346 * XXX - hrmm.. set blocked here? the socket didn't
349 if (bytes_written < bytes_count)
350 cli_flags(cptr) |= FLAGS_BLOCKED;
353 cli_flags(cptr) |= FLAGS_BLOCKED;
356 cli_error(cptr) = errno;
357 cli_flags(cptr) |= FLAGS_DEADSOCKET;
360 return bytes_written;
364 void release_dns_reply(struct Client* cptr)
367 assert(MyConnect(cptr));
369 if (cli_dns_reply(cptr)) {
370 assert(0 < cli_dns_reply(cptr)->ref_count);
371 --(cli_dns_reply(cptr))->ref_count;
372 cli_dns_reply(cptr) = 0;
377 * completed_connection
379 * Complete non-blocking connect()-sequence. Check access and
380 * terminate connection, if trouble detected.
382 * Return TRUE, if successfully completed
383 * FALSE, if failed and ClientExit
385 static int completed_connection(struct Client* cptr)
387 struct ConfItem *aconf;
389 struct Client *acptr;
395 * get the socket status from the fd first to check if
396 * connection actually succeeded
398 if ((cli_error(cptr) = os_get_sockerr(cli_fd(cptr)))) {
399 const char* msg = strerror(cli_error(cptr));
401 msg = "Unknown error";
402 sendto_opmask_butone(0, SNO_OLDSNO, "Connection failed to %s: %s",
403 cli_name(cptr), msg);
406 if (!(aconf = find_conf_byname(cli_confs(cptr), cli_name(cptr), CONF_SERVER))) {
407 sendto_opmask_butone(0, SNO_OLDSNO, "Lost Server Line for %s", cli_name(cptr));
411 if (!EmptyString(aconf->passwd))
412 sendrawto_one(cptr, MSG_PASS " :%s", aconf->passwd);
415 * Create a unique timestamp
418 for (i = HighestFd; i > -1; --i) {
419 if ((acptr = LocalClientArray[i]) &&
420 (IsServer(acptr) || IsHandshake(acptr))) {
421 if (cli_serv(acptr)->timestamp >= newts)
422 newts = cli_serv(acptr)->timestamp + 1;
425 assert(0 != cli_serv(cptr));
427 cli_serv(cptr)->timestamp = newts;
430 * Make us timeout after twice the timeout for DNS look ups
432 cli_lasttime(cptr) = CurrentTime;
433 cli_flags(cptr) |= FLAGS_PINGSENT;
435 sendrawto_one(cptr, MSG_SERVER " %s 1 %Tu %Tu J%s %s%s :%s",
436 cli_name(&me), cli_serv(&me)->timestamp, newts, MAJOR_PROTOCOL,
437 NumServCap(&me), cli_info(&me));
439 return (IsDead(cptr)) ? 0 : 1;
445 * Close the physical connection. This function must make
446 * MyConnect(cptr) == FALSE, and set cptr->from == NULL.
448 void close_connection(struct Client *cptr)
450 struct ConfItem* aconf;
452 if (IsServer(cptr)) {
453 ServerStats->is_sv++;
454 ServerStats->is_sbs += cli_sendB(cptr);
455 ServerStats->is_sbr += cli_receiveB(cptr);
456 ServerStats->is_sks += cli_sendK(cptr);
457 ServerStats->is_skr += cli_receiveK(cptr);
458 ServerStats->is_sti += CurrentTime - cli_firsttime(cptr);
459 if (ServerStats->is_sbs > 1023) {
460 ServerStats->is_sks += (ServerStats->is_sbs >> 10);
461 ServerStats->is_sbs &= 0x3ff;
463 if (ServerStats->is_sbr > 1023) {
464 ServerStats->is_skr += (ServerStats->is_sbr >> 10);
465 ServerStats->is_sbr &= 0x3ff;
468 * If the connection has been up for a long amount of time, schedule
469 * a 'quick' reconnect, else reset the next-connect cycle.
471 if ((aconf = find_conf_exact(cli_name(cptr), 0, cli_sockhost(cptr), CONF_SERVER))) {
473 * Reschedule a faster reconnect, if this was a automaticly
474 * connected configuration entry. (Note that if we have had
475 * a rehash in between, the status has been changed to
476 * CONF_ILLEGAL). But only do this if it was a "good" link.
478 aconf->hold = CurrentTime;
479 aconf->hold += ((aconf->hold - cli_since(cptr) >
480 feature_int(FEAT_HANGONGOODLINK)) ?
481 feature_int(FEAT_HANGONRETRYDELAY) : ConfConFreq(aconf));
482 if (nextconnect > aconf->hold)
483 nextconnect = aconf->hold;
486 else if (IsUser(cptr)) {
487 ServerStats->is_cl++;
488 ServerStats->is_cbs += cli_sendB(cptr);
489 ServerStats->is_cbr += cli_receiveB(cptr);
490 ServerStats->is_cks += cli_sendK(cptr);
491 ServerStats->is_ckr += cli_receiveK(cptr);
492 ServerStats->is_cti += CurrentTime - cli_firsttime(cptr);
493 if (ServerStats->is_cbs > 1023) {
494 ServerStats->is_cks += (ServerStats->is_cbs >> 10);
495 ServerStats->is_cbs &= 0x3ff;
497 if (ServerStats->is_cbr > 1023) {
498 ServerStats->is_ckr += (ServerStats->is_cbr >> 10);
499 ServerStats->is_cbr &= 0x3ff;
503 ServerStats->is_ni++;
505 if (-1 < cli_fd(cptr)) {
506 flush_connections(cptr);
507 LocalClientArray[cli_fd(cptr)] = 0;
511 cli_flags(cptr) |= FLAGS_DEADSOCKET;
513 MsgQClear(&(cli_sendQ(cptr)));
514 client_drop_sendq(cli_connect(cptr));
515 DBufClear(&(cli_recvQ(cptr)));
516 memset(cli_passwd(cptr), 0, sizeof(cli_passwd(cptr)));
517 set_snomask(cptr, 0, SNO_SET);
519 det_confs_butmask(cptr, 0);
521 if (cli_listener(cptr)) {
522 release_listener(cli_listener(cptr));
523 cli_listener(cptr) = 0;
526 for ( ; HighestFd > 0; --HighestFd) {
527 if (LocalClientArray[HighestFd])
532 int net_close_unregistered_connections(struct Client* source)
539 for (i = HighestFd; i > 0; --i) {
540 if ((cptr = LocalClientArray[i]) && !IsRegistered(cptr)) {
541 send_reply(source, RPL_CLOSING, get_client_name(source, HIDE_IP));
542 exit_client(source, cptr, &me, "Oper Closing");
549 /*----------------------------------------------------------------------------
552 * Creates a client which has just connected to us on the given fd.
553 * The sockhost field is initialized with the ip# of the host.
554 * The client is not added to the linked list of clients, it is
555 * passed off to the auth handler for dns and ident queries.
556 *--------------------------------------------------------------------------*/
557 void add_connection(struct Listener* listener, int fd) {
558 struct sockaddr_in addr;
559 struct Client *new_client;
560 time_t next_target = 0;
562 const char* const throttle_message =
563 "ERROR :Your host is trying to (re)connect too fast -- throttled\r\n";
564 /* 12345678901234567890123456789012345679012345678901234567890123456 */
566 assert(0 != listener);
570 * Removed preliminary access check. Full check is performed in m_server and
571 * m_user instead. Also connection time out help to get rid of unwanted
574 if (!os_get_peername(fd, &addr) || !os_set_nonblocking(fd)) {
575 ++ServerStats->is_ref;
581 * Add this local client to the IPcheck registry.
583 * If they're throttled, murder them, but tell them why first.
585 if (!IPcheck_local_connect(addr.sin_addr, &next_target) && !listener->server) {
586 ++ServerStats->is_ref;
587 write(fd, throttle_message, strlen(throttle_message));
592 new_client = make_client(0, ((listener->server) ?
593 STAT_UNKNOWN_SERVER : STAT_UNKNOWN_USER));
596 * Copy ascii address to 'sockhost' just in case. Then we have something
597 * valid to put into error messages...
599 ircd_ntoa_r(cli_sock_ip(new_client), (const char*) &addr.sin_addr);
600 strcpy(cli_sockhost(new_client), cli_sock_ip(new_client));
601 (cli_ip(new_client)).s_addr = addr.sin_addr.s_addr;
602 cli_port(new_client) = ntohs(addr.sin_port);
605 cli_nexttarget(new_client) = next_target;
607 cli_fd(new_client) = fd;
608 cli_listener(new_client) = listener;
609 ++listener->ref_count;
611 Count_newunknown(UserStats);
612 /* if we've made it this far we can put the client on the auth query pile */
613 start_auth(new_client);
620 * Read a 'packet' of data from a connection and process it. Read in 8k
621 * chunks to give a better performance rating (for server connections).
622 * Do some tricky stuff for client connections to make sure they don't do
623 * any flooding >:-) -avalon
625 static int read_packet(struct Client *cptr, int socket_ready)
627 unsigned int dolen = 0;
628 unsigned int length = 0;
632 DBufLength(&(cli_recvQ(cptr))) > feature_int(FEAT_CLIENT_FLOOD))) {
633 switch (os_recv_nonb(cli_fd(cptr), readbuf, sizeof(readbuf), &length)) {
636 cli_lasttime(cptr) = CurrentTime;
637 if (cli_lasttime(cptr) > cli_since(cptr))
638 cli_since(cptr) = cli_lasttime(cptr);
639 cli_flags(cptr) &= ~(FLAGS_PINGSENT | FLAGS_NONL);
645 cli_error(cptr) = errno;
646 /* cptr->flags |= FLAGS_DEADSOCKET; */
652 * For server connections, we process as many as we can without
653 * worrying about the time of day or anything :)
655 if (length > 0 && IsServer(cptr)) {
656 return server_dopacket(cptr, readbuf, length);
660 * Before we even think of parsing what we just read, stick
661 * it on the end of the receive queue and do it when its
664 if (length > 0 && 0 == dbuf_put(&(cli_recvQ(cptr)), readbuf, length)) {
665 return exit_client(cptr, cptr, &me, "dbuf_put fail");
669 * XXX - cptr will always be a user or unregistered
672 DBufLength(&(cli_recvQ(cptr))) > feature_int(FEAT_CLIENT_FLOOD))
673 return exit_client(cptr, cptr, &me, "Excess Flood");
675 while (DBufLength(&(cli_recvQ(cptr))) && !NoNewLine(cptr) &&
676 (IsTrusted(cptr) || cli_since(cptr) - CurrentTime < 10))
679 * If it has become registered as a Server
680 * then skip the per-message parsing below.
682 if (IsServer(cptr)) {
683 dolen = dbuf_get(&(cli_recvQ(cptr)), readbuf, sizeof(readbuf));
684 return (dolen) ? server_dopacket(cptr, readbuf, dolen) : 1;
686 dolen = dbuf_getmsg(&(cli_recvQ(cptr)), cli_buffer(cptr), BUFSIZE);
688 * Devious looking...whats it do ? well..if a client
689 * sends a *long* message without any CR or LF, then
690 * dbuf_getmsg fails and we pull it out using this
691 * loop which just gets the next 512 bytes and then
692 * deletes the rest of the buffer contents.
696 if (DBufLength(&(cli_recvQ(cptr))) < 510)
697 cli_flags(cptr) |= FLAGS_NONL;
699 DBufClear(&(cli_recvQ(cptr)));
701 else if (CPTR_KILLED == client_dopacket(cptr, dolen))
708 static int on_write_unblocked(struct Client* cptr)
711 * ...room for writing, empty some queue then...
713 cli_flags(cptr) &= ~FLAGS_BLOCKED;
714 if (IsConnecting(cptr)) {
715 if (!completed_connection(cptr))
718 else if (cli_listing(cptr) && MsgQLength(&(cli_sendQ(cptr))) < 2048)
719 list_next_channels(cptr, 64);
725 * Select / Poll Read Algorithm for ircd
727 * We need to check the file descriptors for all the different types
728 * of things that use them, so check for reads on everything but connects
729 * and writes on connects and descriptors that are blocked
731 * for each (client in local) {
732 * if (not connecting)
734 * if (connecting or blocked)
739 * for each (client in local) {
740 * if (there are descriptors to check) {
741 * if (write activity)
748 * Note we must always process data read whether or not there has been
749 * read activity or file descriptors set, since data is buffered by the client.
758 #if defined(POLLMSG) && defined(POLLIN) && defined(POLLRDNORM)
759 # define POLLREADFLAGS (POLLMSG|POLLIN|POLLRDNORM)
761 # if defined(POLLIN) && defined(POLLRDNORM)
762 # define POLLREADFLAGS (POLLIN|POLLRDNORM)
765 # define POLLREADFLAGS POLLIN
767 # if defined(POLLRDNORM)
768 # define POLLREADFLAGS POLLRDNORM
774 #if defined(POLLOUT) && defined(POLLWRNORM)
775 #define POLLWRITEFLAGS (POLLOUT|POLLWRNORM)
777 # if defined(POLLOUT)
778 # define POLLWRITEFLAGS POLLOUT
780 # if defined(POLLWRNORM)
781 # define POLLWRITEFLAGS POLLWRNORM
787 #define POLLERRORS (POLLHUP|POLLERR)
789 #define POLLERRORS POLLERR
793 * NOTE: pfd and pfd_count are local variable names in read_message
795 #define PFD_SETR(xfd) \
796 do { CHECK_ADD_PFD(xfd) pfd->events |= POLLREADFLAGS; } while(0)
797 #define PFD_SETW(xfd) \
798 do { CHECK_ADD_PFD(xfd) pfd->events |= POLLWRITEFLAGS; } while(0)
800 #define CHECK_ADD_PFD(xfd) \
801 if (pfd->fd != xfd) { \
802 pfd = &poll_fds[pfd_count++]; \
803 poll_fds[pfd_count].fd = -1; \
809 * Check all connections for new connections and input data that is to be
810 * processed. Also check for connections with data queued and whether we can
813 * Don't ever use ZERO for `delay', unless you mean to poll and then
814 * you have to have sleep/wait somewhere else in the code.--msa
816 int read_message(time_t delay)
818 struct pollfd poll_fds[MAXCONNECTIONS + 1];
820 struct Listener* listener = 0;
821 struct AuthRequest* auth = 0;
822 struct AuthRequest* auth_next = 0;
823 struct UPing* uping = 0;
824 struct UPing* uping_next = 0;
825 time_t delay2 = delay;
832 struct pollfd* res_pfd;
833 struct pollfd* uping_pfd;
837 unsigned int timeout;
846 if (-1 < ResolverFileDescriptor) {
847 PFD_SETR(ResolverFileDescriptor);
850 if (-1 < UPingFileDescriptor) {
851 PFD_SETR(UPingFileDescriptor);
855 * add uping descriptors
857 for (uping = uping_begin(); uping; uping = uping_next) {
858 uping_next = uping->next;
861 if (uping->lastsent && CurrentTime > uping->timeout) {
865 uping->index = pfd_count;
870 * add auth file descriptors
872 for (auth = AuthPollList; auth; auth = auth->next) {
873 assert(-1 < auth->fd);
874 auth->index = pfd_count;
875 if (IsAuthConnect(auth))
881 * add listener file descriptors
883 for (listener = ListenerPollList; listener; listener = listener->next) {
884 assert(-1 < listener->fd);
886 * pfd_count is incremented by PFD_SETR so we need to save the
889 listener->index = pfd_count;
890 PFD_SETR(listener->fd);
893 for (i = HighestFd; -1 < i; --i) {
894 if ((cptr = LocalClientArray[i])) {
896 if (DBufLength(&(cli_recvQ(cptr))))
898 if (DBufLength(&(cli_recvQ(cptr))) < 4088 || IsServer(cptr)) {
901 if (MsgQLength(&(cli_sendQ(cptr))) || IsConnecting(cptr) ||
902 (cli_listing(cptr) && MsgQLength(&(cli_sendQ(cptr))) < 2048)) {
908 Debug((DEBUG_INFO, "poll: %d %d", delay, delay2));
910 timeout = (IRCD_MIN(delay2, delay)) * 1000;
912 nfds = poll(poll_fds, pfd_count, timeout);
914 CurrentTime = time(0);
920 report_error(POLL_ERROR_MSG, cli_name(&me), errno);
923 server_restart("too many poll errors");
925 CurrentTime = time(0);
928 if (uping_pfd && (uping_pfd->revents & (POLLREADFLAGS | POLLERRORS))) {
933 * check uping replies
935 for (uping = uping_begin(); uping; uping = uping_next) {
936 uping_next = uping->next;
938 assert(-1 < uping->index);
939 if (poll_fds[uping->index].revents) {
944 else if (CurrentTime > uping->lastsent) {
945 uping->lastsent = CurrentTime;
951 if (res_pfd && (res_pfd->revents & (POLLREADFLAGS | POLLERRORS))) {
958 for (auth = AuthPollList; auth; auth = auth_next) {
959 auth_next = auth->next;
962 * check for any event, we only ask for one at a time
964 if (poll_fds[i].revents) {
965 if (IsAuthConnect(auth))
966 send_auth_query(auth);
968 read_auth_reply(auth);
976 for (listener = ListenerPollList; listener; listener = listener->next) {
978 if (poll_fds[i].revents) {
979 accept_connection(listener);
985 * i contains the next non-auth/non-listener index, since we put the
986 * resolver, auth and listener, file descriptors in poll_fds first,
987 * the very next one should be the start of the clients
989 pfd = &poll_fds[++i];
991 for ( ; (i < pfd_count); ++i, ++pfd) {
992 if (!(cptr = LocalClientArray[pfd->fd]))
994 read_ready = write_ready = 0;
996 if (0 < nfds && pfd->revents) {
999 read_ready = pfd->revents & POLLREADFLAGS;
1000 write_ready = pfd->revents & POLLWRITEFLAGS;
1002 if (pfd->revents & POLLERRORS) {
1003 if (pfd->events & POLLREADFLAGS)
1005 if (pfd->events & POLLWRITEFLAGS)
1010 if (!on_write_unblocked(cptr) || IsDead(cptr)) {
1011 const char* msg = (cli_error(cptr)) ? strerror(cli_error(cptr)) : cli_info(cptr);
1013 msg = "Unknown error";
1014 exit_client(cptr, cptr, &me, msg);
1018 length = 1; /* for fall through case */
1019 if ((!NoNewLine(cptr) || read_ready) && !IsDead(cptr)) {
1020 if (CPTR_KILLED == (length = read_packet(cptr, read_ready)))
1024 /* Bullshit, why would we want to flush sockets while using non-blocking?
1025 * This uses > 4% cpu! --Run */
1027 flush_connections(poll_cptr[i]);
1030 const char* msg = (cli_error(cptr)) ? strerror(cli_error(cptr)) : cli_info(cptr);
1032 msg = "Unknown error";
1033 exit_client(cptr, cptr, &me, (char*) msg);
1038 cli_flags(cptr) |= FLAGS_DEADSOCKET;
1040 * ...hmm, with non-blocking sockets we might get
1041 * here from quite valid reasons, although.. why
1042 * would select report "data available" when there
1043 * wasn't... So, this must be an error anyway... --msa
1044 * actually, EOF occurs when read() returns 0 and
1045 * in due course, select() returns that fd as ready
1046 * for reading even though it ends up being an EOF. -avalon
1048 Debug((DEBUG_ERROR, "READ ERROR: fd = %d %d %d", pfd->fd, errno, length));
1050 if ((IsServer(cptr) || IsHandshake(cptr)) && cli_error(cptr) == 0 && length == 0)
1051 exit_client_msg(cptr, cptr, &me, "Server %s closed the connection (%s)",
1052 cli_name(cptr), cli_serv(cptr)->last_error_msg);
1054 const char* msg = (cli_error(cptr)) ? strerror(cli_error(cptr)) : "EOF from client";
1056 msg = "Unknown error";
1057 exit_client_msg(cptr, cptr, &me, "Read error: %s", msg);
1062 #else /* USE_SELECT */
1065 * Check all connections for new connections and input data that is to be
1066 * processed. Also check for connections with data queued and whether we can
1069 * Don't ever use ZERO for `delay', unless you mean to poll and then
1070 * you have to have sleep/wait somewhere else in the code.--msa
1072 int read_message(time_t delay)
1074 struct Client* cptr;
1075 struct Listener* listener;
1076 struct AuthRequest* auth = 0;
1077 struct AuthRequest* auth_next = 0;
1078 struct UPing* uping;
1079 struct UPing* uping_next;
1081 struct timeval wait;
1082 time_t delay2 = delay;
1083 unsigned int usec = 0;
1094 FD_ZERO(&write_set);
1096 if (-1 < ResolverFileDescriptor)
1097 FD_SET(ResolverFileDescriptor, &read_set);
1098 if (-1 < UPingFileDescriptor)
1099 FD_SET(UPingFileDescriptor, &read_set);
1101 * set up uping file descriptors
1103 for (uping = uping_begin(); uping; uping = uping_next) {
1104 uping_next = uping->next;
1105 if (uping->active) {
1107 if (uping->lastsent && CurrentTime > uping->timeout) {
1111 assert(-1 < uping->fd);
1112 FD_SET(uping->fd, &read_set);
1116 * set auth file descriptors
1118 for (auth = AuthPollList; auth; auth = auth->next) {
1119 assert(-1 < auth->fd);
1120 if (IsAuthConnect(auth))
1121 FD_SET(auth->fd, &write_set);
1122 else /* if (IsAuthPending(auth)) */
1123 FD_SET(auth->fd, &read_set);
1126 * set listener file descriptors
1128 for (listener = ListenerPollList; listener; listener = listener->next) {
1129 assert(-1 < listener->fd);
1130 FD_SET(listener->fd, &read_set);
1133 for (i = HighestFd; i > -1; --i) {
1134 if ((cptr = LocalClientArray[i])) {
1135 if (DBufLength(&(cli_recvQ(cptr))))
1137 if (DBufLength(&(cli_recvq(cptr))) < 4088 || IsServer(cptr))
1138 FD_SET(i, &read_set);
1139 if (MsgQLength(&(cli_sendq(cptr))) || IsConnecting(cptr) ||
1140 (cli_listing(cptr) && MsgQLength(&(cli_sendQ(cptr))) < 2048))
1141 FD_SET(i, &write_set);
1145 wait.tv_sec = IRCD_MIN(delay2, delay);
1146 wait.tv_usec = usec;
1148 Debug((DEBUG_INFO, "select: %d %d", delay, delay2));
1150 nfds = select(FD_SETSIZE, &read_set, &write_set, 0, &wait);
1152 CurrentTime = time(0);
1159 report_error(SELECT_ERROR_MSG, cli_name(&me), errno);
1161 server_restart("too many select errors");
1163 CurrentTime = time(0);
1166 if (-1 < UPingFileDescriptor && FD_ISSET(UPingFileDescriptor, &read_set)) {
1170 for (uping = uping_begin(); uping; uping = uping_next) {
1171 uping_next = uping->next;
1172 if (uping->active) {
1173 assert(-1 < uping->fd);
1174 if (FD_ISSET(uping->fd, &read_set)) {
1179 else if (CurrentTime > uping->lastsent) {
1180 uping->lastsent = CurrentTime;
1185 if (-1 < ResolverFileDescriptor && FD_ISSET(ResolverFileDescriptor, &read_set)) {
1190 * Check fd sets for the auth fd's (if set and valid!) first
1191 * because these can not be processed using the normal loops below.
1194 for (auth = AuthPollList; auth; auth = auth_next) {
1195 auth_next = auth->next;
1196 assert(-1 < auth->fd);
1197 if (IsAuthConnect(auth) && FD_ISSET(auth->fd, &write_set)) {
1198 send_auth_query(auth);
1202 else if (FD_ISSET(auth->fd, &read_set)) {
1203 read_auth_reply(auth);
1209 * next accept connections from active listeners
1211 for (listener = ListenerPollList; listener; listener = listener->next) {
1212 assert(-1 < listener->fd);
1213 if (0 < nfds && FD_ISSET(listener->fd, &read_set))
1214 accept_connection(listener);
1217 for (i = HighestFd; -1 < i; --i) {
1218 if (!(cptr = LocalClientArray[i]))
1222 if (FD_ISSET(i, &write_set)) {
1224 if (!on_write_unblocked(cptr) || IsDead(cptr)) {
1225 const char* msg = (cli_error(cptr)) ? strerror(cli_error(cptr)) : cli_info(cptr);
1227 msg = "Unknown error";
1228 if (FD_ISSET(i, &read_set))
1230 exit_client(cptr, cptr, &me, msg);
1234 if ((read_ready = FD_ISSET(i, &read_set)))
1237 length = 1; /* for fall through case */
1238 if ((!NoNewLine(cptr) || read_ready) && !IsDead(cptr)) {
1239 if (CPTR_KILLED == (length = read_packet(cptr, read_ready)))
1243 const char* msg = (cli_error(cptr)) ? strerror(cli_error(cptr)) : cli_info(cptr);
1245 msg = "Unknown error";
1246 exit_client(cptr, cptr, &me, msg);
1253 * ...hmm, with non-blocking sockets we might get
1254 * here from quite valid reasons, although.. why
1255 * would select report "data available" when there
1256 * wasn't... So, this must be an error anyway... --msa
1257 * actually, EOF occurs when read() returns 0 and
1258 * in due course, select() returns that fd as ready
1259 * for reading even though it ends up being an EOF. -avalon
1261 Debug((DEBUG_ERROR, "READ ERROR: fd = %d %d %d", i, cli_error(cptr), length));
1263 if ((IsServer(cptr) || IsHandshake(cptr)) && cli_error(cptr) == 0 && length == 0)
1264 exit_client_msg(cptr, cptr, &me, "Server %s closed the connection (%s)",
1265 cli_name(cptr), cli_serv(cptr)->last_error_msg);
1267 const char* msg = (cli_error(cptr)) ? strerror(cli_error(cptr)) : "EOF from client";
1269 msg = "Unknown error";
1270 exit_client_msg(cptr, cptr, &me, "Read error: %s", msg);
1276 #endif /* USE_SELECT */
1279 * connect_server - start or complete a connection to another server
1280 * returns true (1) if successful, false (0) otherwise
1282 * aconf must point to a valid C:line
1283 * m_connect calls this with a valid by client and a null reply
1284 * try_connections calls this with a null by client, and a null reply
1285 * connect_dns_callback call this with a null by client, and a valid reply
1287 * XXX - if this comes from an m_connect message and a dns query needs to
1288 * be done, we loose the information about who started the connection and
1289 * it's considered an auto connect.
1291 int connect_server(struct ConfItem* aconf, struct Client* by,
1292 struct DNSReply* reply)
1294 struct Client* cptr = 0;
1297 if (aconf->dns_pending) {
1298 sendto_opmask_butone(0, SNO_OLDSNO, "Server %s connect DNS pending",
1302 Debug((DEBUG_NOTICE, "Connect to %s[@%s]", aconf->name,
1303 ircd_ntoa((const char*) &aconf->ipnum)));
1305 if ((cptr = FindClient(aconf->name))) {
1306 if (IsServer(cptr) || IsMe(cptr)) {
1307 sendto_opmask_butone(0, SNO_OLDSNO, "Server %s already present from %s",
1308 aconf->name, cli_name(cli_from(cptr)));
1309 if (by && IsUser(by) && !MyUser(by)) {
1310 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Server %s already present "
1311 "from %s", by, aconf->name, cli_name(cli_from(cptr)));
1315 else if (IsHandshake(cptr) || IsConnecting(cptr)) {
1316 if (by && IsUser(by)) {
1317 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Connection to %s already in "
1318 "progress", by, cli_name(cptr));
1324 * If we dont know the IP# for this host and itis a hostname and
1325 * not a ip# string, then try and find the appropriate host record.
1327 if (INADDR_NONE == aconf->ipnum.s_addr) {
1328 char buf[HOSTLEN + 1];
1330 if (INADDR_NONE == (aconf->ipnum.s_addr = inet_addr(aconf->host))) {
1331 struct DNSQuery query;
1334 query.callback = connect_dns_callback;
1335 host_from_uh(buf, aconf->host, HOSTLEN);
1336 buf[HOSTLEN] = '\0';
1338 reply = gethost_byname(buf, &query);
1341 aconf->dns_pending = 1;
1344 memcpy(&aconf->ipnum, reply->hp->h_addr, sizeof(struct in_addr));
1347 cptr = make_client(NULL, STAT_UNKNOWN_SERVER);
1350 cli_dns_reply(cptr) = reply;
1353 * Copy these in so we have something for error detection.
1355 ircd_strncpy(cli_name(cptr), aconf->name, HOSTLEN);
1356 ircd_strncpy(cli_sockhost(cptr), aconf->host, HOSTLEN);
1359 * Attach config entries to client here rather than in
1360 * completed_connection. This to avoid null pointer references
1362 attach_confs_byhost(cptr, aconf->host, CONF_SERVER);
1364 if (!find_conf_byhost(cli_confs(cptr), aconf->host, CONF_SERVER)) {
1365 sendto_opmask_butone(0, SNO_OLDSNO, "Host %s is not enabled for "
1366 "connecting: no C-line", aconf->name);
1367 if (by && IsUser(by) && !MyUser(by)) {
1368 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Connect to host %s failed: no "
1369 "C-line", by, aconf->name);
1371 det_confs_butmask(cptr, 0);
1376 * attempt to connect to the server in the conf line
1378 if (!connect_inet(aconf, cptr)) {
1379 if (by && IsUser(by) && !MyUser(by)) {
1380 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Couldn't connect to %s", by,
1383 det_confs_butmask(cptr, 0);
1388 * NOTE: if we're here we have a valid C:Line and the client should
1389 * have started the connection and stored the remote address/port and
1390 * ip address name in itself
1392 * The socket has been connected or connect is in progress.
1395 if (by && IsUser(by)) {
1396 sprintf_irc(cli_serv(cptr)->by, "%s%s", NumNick(by));
1397 assert(0 == cli_serv(cptr)->user);
1398 cli_serv(cptr)->user = cli_user(by);
1399 cli_user(by)->refcnt++;
1402 *(cli_serv(cptr))->by = '\0';
1403 /* strcpy(cptr->serv->by, "Auto"); */
1405 cli_serv(cptr)->up = &me;
1406 SetConnecting(cptr);
1408 if (cli_fd(cptr) > HighestFd)
1409 HighestFd = cli_fd(cptr);
1412 LocalClientArray[cli_fd(cptr)] = cptr;
1414 Count_newunknown(UserStats);
1415 /* Actually we lie, the connect hasn't succeeded yet, but we have a valid
1416 * cptr, so we register it now.
1417 * Maybe these two calls should be merged.
1419 add_client_to_list(cptr);
1421 nextping = CurrentTime;
1427 * Setup local socket structure to use for binding to.
1429 void set_virtual_host(struct in_addr addr)
1431 memset(&VirtualHost, 0, sizeof(VirtualHost));
1432 VirtualHost.sin_family = AF_INET;
1433 VirtualHost.sin_addr.s_addr = addr.s_addr;
1437 * Find the real hostname for the host running the server (or one which
1438 * matches the server's name) and its primary IP#. Hostname is stored
1439 * in the client structure passed as a pointer.
1441 void init_server_identity(void)
1443 const struct LocalConf* conf = conf_get_local();
1446 ircd_strncpy(cli_name(&me), conf->name, HOSTLEN);
1447 SetYXXServerName(&me, conf->numeric);