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 client_drop_sendq(cli_connect(cptr));
520 DBufClear(&(cli_recvQ(cptr)));
521 memset(cli_passwd(cptr), 0, sizeof(cli_passwd(cptr)));
522 set_snomask(cptr, 0, SNO_SET);
524 det_confs_butmask(cptr, 0);
526 if (cli_listener(cptr)) {
527 release_listener(cli_listener(cptr));
528 cli_listener(cptr) = 0;
531 for ( ; HighestFd > 0; --HighestFd) {
532 if (LocalClientArray[HighestFd])
537 int net_close_unregistered_connections(struct Client* source)
544 for (i = HighestFd; i > 0; --i) {
545 if ((cptr = LocalClientArray[i]) && !IsRegistered(cptr)) {
546 send_reply(source, RPL_CLOSING, get_client_name(source, HIDE_IP));
547 exit_client(source, cptr, &me, "Oper Closing");
554 /*----------------------------------------------------------------------------
557 * Creates a client which has just connected to us on the given fd.
558 * The sockhost field is initialized with the ip# of the host.
559 * The client is not added to the linked list of clients, it is
560 * passed off to the auth handler for dns and ident queries.
561 *--------------------------------------------------------------------------*/
562 void add_connection(struct Listener* listener, int fd) {
563 struct sockaddr_in addr;
564 struct Client *new_client;
565 time_t next_target = 0;
567 const char* const throttle_message =
568 "ERROR :Your host is trying to (re)connect too fast -- throttled\r\n";
569 /* 12345678901234567890123456789012345679012345678901234567890123456 */
571 assert(0 != listener);
575 * Removed preliminary access check. Full check is performed in m_server and
576 * m_user instead. Also connection time out help to get rid of unwanted
579 if (!os_get_peername(fd, &addr) || !os_set_nonblocking(fd)) {
580 ++ServerStats->is_ref;
586 * Add this local client to the IPcheck registry.
588 * If they're throttled, murder them, but tell them why first.
590 if (!IPcheck_local_connect(addr.sin_addr, &next_target) && !listener->server) {
591 ++ServerStats->is_ref;
592 write(fd, throttle_message, strlen(throttle_message));
597 new_client = make_client(0, ((listener->server) ?
598 STAT_UNKNOWN_SERVER : STAT_UNKNOWN_USER));
601 * Copy ascii address to 'sockhost' just in case. Then we have something
602 * valid to put into error messages...
604 ircd_ntoa_r(cli_sock_ip(new_client), (const char*) &addr.sin_addr);
605 strcpy(cli_sockhost(new_client), cli_sock_ip(new_client));
606 (cli_ip(new_client)).s_addr = addr.sin_addr.s_addr;
607 cli_port(new_client) = ntohs(addr.sin_port);
610 cli_nexttarget(new_client) = next_target;
612 cli_fd(new_client) = fd;
613 cli_listener(new_client) = listener;
614 ++listener->ref_count;
616 Count_newunknown(UserStats);
617 /* if we've made it this far we can put the client on the auth query pile */
618 start_auth(new_client);
625 * Read a 'packet' of data from a connection and process it. Read in 8k
626 * chunks to give a better performance rating (for server connections).
627 * Do some tricky stuff for client connections to make sure they don't do
628 * any flooding >:-) -avalon
630 static int read_packet(struct Client *cptr, int socket_ready)
632 unsigned int dolen = 0;
633 unsigned int length = 0;
635 if (socket_ready && !(IsUser(cptr) && DBufLength(&(cli_recvQ(cptr))) > CLIENT_FLOOD)) {
636 switch (os_recv_nonb(cli_fd(cptr), readbuf, sizeof(readbuf), &length)) {
639 cli_lasttime(cptr) = CurrentTime;
640 if (cli_lasttime(cptr) > cli_since(cptr))
641 cli_since(cptr) = cli_lasttime(cptr);
642 cli_flags(cptr) &= ~(FLAGS_PINGSENT | FLAGS_NONL);
648 cli_error(cptr) = errno;
649 /* cptr->flags |= FLAGS_DEADSOCKET; */
655 * For server connections, we process as many as we can without
656 * worrying about the time of day or anything :)
658 if (length > 0 && IsServer(cptr)) {
659 return server_dopacket(cptr, readbuf, length);
663 * Before we even think of parsing what we just read, stick
664 * it on the end of the receive queue and do it when its
667 if (length > 0 && 0 == dbuf_put(&(cli_recvQ(cptr)), readbuf, length)) {
668 return exit_client(cptr, cptr, &me, "dbuf_put fail");
670 #ifndef NOFLOODCONTROL
672 * XXX - cptr will always be a user or unregistered
674 if (IsUser(cptr) && DBufLength(&(cli_recvQ(cptr))) > CLIENT_FLOOD)
675 return exit_client(cptr, cptr, &me, "Excess Flood");
677 while (DBufLength(&(cli_recvQ(cptr))) && !NoNewLine(cptr) &&
678 (IsTrusted(cptr) || cli_since(cptr) - CurrentTime < 10))
680 while (DBufLength(&(cli_recvQ(cptr))) && !NoNewLine(cptr))
684 * If it has become registered as a Server
685 * then skip the per-message parsing below.
687 if (IsServer(cptr)) {
688 dolen = dbuf_get(&(cli_recvQ(cptr)), readbuf, sizeof(readbuf));
689 return (dolen) ? server_dopacket(cptr, readbuf, dolen) : 1;
691 dolen = dbuf_getmsg(&(cli_recvQ(cptr)), cli_buffer(cptr), BUFSIZE);
693 * Devious looking...whats it do ? well..if a client
694 * sends a *long* message without any CR or LF, then
695 * dbuf_getmsg fails and we pull it out using this
696 * loop which just gets the next 512 bytes and then
697 * deletes the rest of the buffer contents.
701 if (DBufLength(&(cli_recvQ(cptr))) < 510)
702 cli_flags(cptr) |= FLAGS_NONL;
704 DBufClear(&(cli_recvQ(cptr)));
706 else if (CPTR_KILLED == client_dopacket(cptr, dolen))
713 static int on_write_unblocked(struct Client* cptr)
716 * ...room for writing, empty some queue then...
718 cli_flags(cptr) &= ~FLAGS_BLOCKED;
719 if (IsConnecting(cptr)) {
720 if (!completed_connection(cptr))
723 else if (cli_listing(cptr) && MsgQLength(&(cli_sendQ(cptr))) < 2048)
724 list_next_channels(cptr, 64);
730 * Select / Poll Read Algorithm for ircd
732 * We need to check the file descriptors for all the different types
733 * of things that use them, so check for reads on everything but connects
734 * and writes on connects and descriptors that are blocked
736 * for each (client in local) {
737 * if (not connecting)
739 * if (connecting or blocked)
744 * for each (client in local) {
745 * if (there are descriptors to check) {
746 * if (write activity)
753 * Note we must always process data read whether or not there has been
754 * read activity or file descriptors set, since data is buffered by the client.
763 #if defined(POLLMSG) && defined(POLLIN) && defined(POLLRDNORM)
764 # define POLLREADFLAGS (POLLMSG|POLLIN|POLLRDNORM)
766 # if defined(POLLIN) && defined(POLLRDNORM)
767 # define POLLREADFLAGS (POLLIN|POLLRDNORM)
770 # define POLLREADFLAGS POLLIN
772 # if defined(POLLRDNORM)
773 # define POLLREADFLAGS POLLRDNORM
779 #if defined(POLLOUT) && defined(POLLWRNORM)
780 #define POLLWRITEFLAGS (POLLOUT|POLLWRNORM)
782 # if defined(POLLOUT)
783 # define POLLWRITEFLAGS POLLOUT
785 # if defined(POLLWRNORM)
786 # define POLLWRITEFLAGS POLLWRNORM
792 #define POLLERRORS (POLLHUP|POLLERR)
794 #define POLLERRORS POLLERR
798 * NOTE: pfd and pfd_count are local variable names in read_message
800 #define PFD_SETR(xfd) \
801 do { CHECK_ADD_PFD(xfd) pfd->events |= POLLREADFLAGS; } while(0)
802 #define PFD_SETW(xfd) \
803 do { CHECK_ADD_PFD(xfd) pfd->events |= POLLWRITEFLAGS; } while(0)
805 #define CHECK_ADD_PFD(xfd) \
806 if (pfd->fd != xfd) { \
807 pfd = &poll_fds[pfd_count++]; \
808 poll_fds[pfd_count].fd = -1; \
814 * Check all connections for new connections and input data that is to be
815 * processed. Also check for connections with data queued and whether we can
818 * Don't ever use ZERO for `delay', unless you mean to poll and then
819 * you have to have sleep/wait somewhere else in the code.--msa
821 int read_message(time_t delay)
823 struct pollfd poll_fds[MAXCONNECTIONS + 1];
825 struct Listener* listener = 0;
826 struct AuthRequest* auth = 0;
827 struct AuthRequest* auth_next = 0;
828 struct UPing* uping = 0;
829 struct UPing* uping_next = 0;
830 time_t delay2 = delay;
837 struct pollfd* res_pfd;
838 struct pollfd* uping_pfd;
842 unsigned int timeout;
851 if (-1 < ResolverFileDescriptor) {
852 PFD_SETR(ResolverFileDescriptor);
855 if (-1 < UPingFileDescriptor) {
856 PFD_SETR(UPingFileDescriptor);
860 * add uping descriptors
862 for (uping = uping_begin(); uping; uping = uping_next) {
863 uping_next = uping->next;
866 if (uping->lastsent && CurrentTime > uping->timeout) {
870 uping->index = pfd_count;
875 * add auth file descriptors
877 for (auth = AuthPollList; auth; auth = auth->next) {
878 assert(-1 < auth->fd);
879 auth->index = pfd_count;
880 if (IsAuthConnect(auth))
886 * add listener file descriptors
888 for (listener = ListenerPollList; listener; listener = listener->next) {
889 assert(-1 < listener->fd);
891 * pfd_count is incremented by PFD_SETR so we need to save the
894 listener->index = pfd_count;
895 PFD_SETR(listener->fd);
898 for (i = HighestFd; -1 < i; --i) {
899 if ((cptr = LocalClientArray[i])) {
901 if (DBufLength(&(cli_recvQ(cptr))))
903 if (DBufLength(&(cli_recvQ(cptr))) < 4088 || IsServer(cptr)) {
906 if (MsgQLength(&(cli_sendQ(cptr))) || IsConnecting(cptr) ||
907 (cli_listing(cptr) && MsgQLength(&(cli_sendQ(cptr))) < 2048)) {
913 Debug((DEBUG_INFO, "poll: %d %d", delay, delay2));
915 timeout = (IRCD_MIN(delay2, delay)) * 1000;
917 nfds = poll(poll_fds, pfd_count, timeout);
919 CurrentTime = time(0);
925 report_error(POLL_ERROR_MSG, cli_name(&me), errno);
928 server_restart("too many poll errors");
930 CurrentTime = time(0);
933 if (uping_pfd && (uping_pfd->revents & (POLLREADFLAGS | POLLERRORS))) {
938 * check uping replies
940 for (uping = uping_begin(); uping; uping = uping_next) {
941 uping_next = uping->next;
943 assert(-1 < uping->index);
944 if (poll_fds[uping->index].revents) {
949 else if (CurrentTime > uping->lastsent) {
950 uping->lastsent = CurrentTime;
956 if (res_pfd && (res_pfd->revents & (POLLREADFLAGS | POLLERRORS))) {
963 for (auth = AuthPollList; auth; auth = auth_next) {
964 auth_next = auth->next;
967 * check for any event, we only ask for one at a time
969 if (poll_fds[i].revents) {
970 if (IsAuthConnect(auth))
971 send_auth_query(auth);
973 read_auth_reply(auth);
981 for (listener = ListenerPollList; listener; listener = listener->next) {
983 if (poll_fds[i].revents) {
984 accept_connection(listener);
990 * i contains the next non-auth/non-listener index, since we put the
991 * resolver, auth and listener, file descriptors in poll_fds first,
992 * the very next one should be the start of the clients
994 pfd = &poll_fds[++i];
996 for ( ; (i < pfd_count); ++i, ++pfd) {
997 if (!(cptr = LocalClientArray[pfd->fd]))
999 read_ready = write_ready = 0;
1001 if (0 < nfds && pfd->revents) {
1004 read_ready = pfd->revents & POLLREADFLAGS;
1005 write_ready = pfd->revents & POLLWRITEFLAGS;
1007 if (pfd->revents & POLLERRORS) {
1008 if (pfd->events & POLLREADFLAGS)
1010 if (pfd->events & POLLWRITEFLAGS)
1015 if (!on_write_unblocked(cptr) || IsDead(cptr)) {
1016 const char* msg = (cli_error(cptr)) ? strerror(cli_error(cptr)) : cli_info(cptr);
1018 msg = "Unknown error";
1019 exit_client(cptr, cptr, &me, msg);
1023 length = 1; /* for fall through case */
1024 if ((!NoNewLine(cptr) || read_ready) && !IsDead(cptr)) {
1025 if (CPTR_KILLED == (length = read_packet(cptr, read_ready)))
1029 /* Bullshit, why would we want to flush sockets while using non-blocking?
1030 * This uses > 4% cpu! --Run */
1032 flush_connections(poll_cptr[i]);
1035 const char* msg = (cli_error(cptr)) ? strerror(cli_error(cptr)) : cli_info(cptr);
1037 msg = "Unknown error";
1038 exit_client(cptr, cptr, &me, (char*) msg);
1043 cli_flags(cptr) |= FLAGS_DEADSOCKET;
1045 * ...hmm, with non-blocking sockets we might get
1046 * here from quite valid reasons, although.. why
1047 * would select report "data available" when there
1048 * wasn't... So, this must be an error anyway... --msa
1049 * actually, EOF occurs when read() returns 0 and
1050 * in due course, select() returns that fd as ready
1051 * for reading even though it ends up being an EOF. -avalon
1053 Debug((DEBUG_ERROR, "READ ERROR: fd = %d %d %d", pfd->fd, errno, length));
1055 if ((IsServer(cptr) || IsHandshake(cptr)) && cli_error(cptr) == 0 && length == 0)
1056 exit_client_msg(cptr, cptr, &me, "Server %s closed the connection (%s)",
1057 cli_name(cptr), cli_serv(cptr)->last_error_msg);
1059 const char* msg = (cli_error(cptr)) ? strerror(cli_error(cptr)) : "EOF from client";
1061 msg = "Unknown error";
1062 exit_client_msg(cptr, cptr, &me, "Read error: %s", msg);
1067 #else /* USE_SELECT */
1070 * Check all connections for new connections and input data that is to be
1071 * processed. Also check for connections with data queued and whether we can
1074 * Don't ever use ZERO for `delay', unless you mean to poll and then
1075 * you have to have sleep/wait somewhere else in the code.--msa
1077 int read_message(time_t delay)
1079 struct Client* cptr;
1080 struct Listener* listener;
1081 struct AuthRequest* auth = 0;
1082 struct AuthRequest* auth_next = 0;
1083 struct UPing* uping;
1084 struct UPing* uping_next;
1086 struct timeval wait;
1087 time_t delay2 = delay;
1088 unsigned int usec = 0;
1099 FD_ZERO(&write_set);
1101 if (-1 < ResolverFileDescriptor)
1102 FD_SET(ResolverFileDescriptor, &read_set);
1103 if (-1 < UPingFileDescriptor)
1104 FD_SET(UPingFileDescriptor, &read_set);
1106 * set up uping file descriptors
1108 for (uping = uping_begin(); uping; uping = uping_next) {
1109 uping_next = uping->next;
1110 if (uping->active) {
1112 if (uping->lastsent && CurrentTime > uping->timeout) {
1116 assert(-1 < uping->fd);
1117 FD_SET(uping->fd, &read_set);
1121 * set auth file descriptors
1123 for (auth = AuthPollList; auth; auth = auth->next) {
1124 assert(-1 < auth->fd);
1125 if (IsAuthConnect(auth))
1126 FD_SET(auth->fd, &write_set);
1127 else /* if (IsAuthPending(auth)) */
1128 FD_SET(auth->fd, &read_set);
1131 * set listener file descriptors
1133 for (listener = ListenerPollList; listener; listener = listener->next) {
1134 assert(-1 < listener->fd);
1135 FD_SET(listener->fd, &read_set);
1138 for (i = HighestFd; i > -1; --i) {
1139 if ((cptr = LocalClientArray[i])) {
1140 if (DBufLength(&(cli_recvQ(cptr))))
1142 if (DBufLength(&(cli_recvq(cptr))) < 4088 || IsServer(cptr))
1143 FD_SET(i, &read_set);
1144 if (MsgQLength(&(cli_sendq(cptr))) || IsConnecting(cptr) ||
1145 (cli_listing(cptr) && MsgQLength(&(cli_sendQ(cptr))) < 2048))
1146 FD_SET(i, &write_set);
1150 wait.tv_sec = IRCD_MIN(delay2, delay);
1151 wait.tv_usec = usec;
1153 Debug((DEBUG_INFO, "select: %d %d", delay, delay2));
1155 nfds = select(FD_SETSIZE, &read_set, &write_set, 0, &wait);
1157 CurrentTime = time(0);
1164 report_error(SELECT_ERROR_MSG, cli_name(&me), errno);
1166 server_restart("too many select errors");
1168 CurrentTime = time(0);
1171 if (-1 < UPingFileDescriptor && FD_ISSET(UPingFileDescriptor, &read_set)) {
1175 for (uping = uping_begin(); uping; uping = uping_next) {
1176 uping_next = uping->next;
1177 if (uping->active) {
1178 assert(-1 < uping->fd);
1179 if (FD_ISSET(uping->fd, &read_set)) {
1184 else if (CurrentTime > uping->lastsent) {
1185 uping->lastsent = CurrentTime;
1190 if (-1 < ResolverFileDescriptor && FD_ISSET(ResolverFileDescriptor, &read_set)) {
1195 * Check fd sets for the auth fd's (if set and valid!) first
1196 * because these can not be processed using the normal loops below.
1199 for (auth = AuthPollList; auth; auth = auth_next) {
1200 auth_next = auth->next;
1201 assert(-1 < auth->fd);
1202 if (IsAuthConnect(auth) && FD_ISSET(auth->fd, &write_set)) {
1203 send_auth_query(auth);
1207 else if (FD_ISSET(auth->fd, &read_set)) {
1208 read_auth_reply(auth);
1214 * next accept connections from active listeners
1216 for (listener = ListenerPollList; listener; listener = listener->next) {
1217 assert(-1 < listener->fd);
1218 if (0 < nfds && FD_ISSET(listener->fd, &read_set))
1219 accept_connection(listener);
1222 for (i = HighestFd; -1 < i; --i) {
1223 if (!(cptr = LocalClientArray[i]))
1227 if (FD_ISSET(i, &write_set)) {
1229 if (!on_write_unblocked(cptr) || IsDead(cptr)) {
1230 const char* msg = (cli_error(cptr)) ? strerror(cli_error(cptr)) : cli_info(cptr);
1232 msg = "Unknown error";
1233 if (FD_ISSET(i, &read_set))
1235 exit_client(cptr, cptr, &me, msg);
1239 if ((read_ready = FD_ISSET(i, &read_set)))
1242 length = 1; /* for fall through case */
1243 if ((!NoNewLine(cptr) || read_ready) && !IsDead(cptr)) {
1244 if (CPTR_KILLED == (length = read_packet(cptr, read_ready)))
1248 const char* msg = (cli_error(cptr)) ? strerror(cli_error(cptr)) : cli_info(cptr);
1250 msg = "Unknown error";
1251 exit_client(cptr, cptr, &me, msg);
1258 * ...hmm, with non-blocking sockets we might get
1259 * here from quite valid reasons, although.. why
1260 * would select report "data available" when there
1261 * wasn't... So, this must be an error anyway... --msa
1262 * actually, EOF occurs when read() returns 0 and
1263 * in due course, select() returns that fd as ready
1264 * for reading even though it ends up being an EOF. -avalon
1266 Debug((DEBUG_ERROR, "READ ERROR: fd = %d %d %d", i, cli_error(cptr), length));
1268 if ((IsServer(cptr) || IsHandshake(cptr)) && cli_error(cptr) == 0 && length == 0)
1269 exit_client_msg(cptr, cptr, &me, "Server %s closed the connection (%s)",
1270 cli_name(cptr), cli_serv(cptr)->last_error_msg);
1272 const char* msg = (cli_error(cptr)) ? strerror(cli_error(cptr)) : "EOF from client";
1274 msg = "Unknown error";
1275 exit_client_msg(cptr, cptr, &me, "Read error: %s", msg);
1281 #endif /* USE_SELECT */
1284 * connect_server - start or complete a connection to another server
1285 * returns true (1) if successful, false (0) otherwise
1287 * aconf must point to a valid C:line
1288 * m_connect calls this with a valid by client and a null reply
1289 * try_connections calls this with a null by client, and a null reply
1290 * connect_dns_callback call this with a null by client, and a valid reply
1292 * XXX - if this comes from an m_connect message and a dns query needs to
1293 * be done, we loose the information about who started the connection and
1294 * it's considered an auto connect.
1296 int connect_server(struct ConfItem* aconf, struct Client* by,
1297 struct DNSReply* reply)
1299 struct Client* cptr = 0;
1302 if (aconf->dns_pending) {
1303 sendto_opmask_butone(0, SNO_OLDSNO, "Server %s connect DNS pending",
1307 Debug((DEBUG_NOTICE, "Connect to %s[@%s]", aconf->name,
1308 ircd_ntoa((const char*) &aconf->ipnum)));
1310 if ((cptr = FindClient(aconf->name))) {
1311 if (IsServer(cptr) || IsMe(cptr)) {
1312 sendto_opmask_butone(0, SNO_OLDSNO, "Server %s already present from %s",
1313 aconf->name, cli_name(cli_from(cptr)));
1314 if (by && IsUser(by) && !MyUser(by)) {
1315 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Server %s already present "
1316 "from %s", by, aconf->name, cli_name(cli_from(cptr)));
1320 else if (IsHandshake(cptr) || IsConnecting(cptr)) {
1321 if (by && IsUser(by)) {
1322 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Connection to %s already in "
1323 "progress", by, cli_name(cptr));
1329 * If we dont know the IP# for this host and itis a hostname and
1330 * not a ip# string, then try and find the appropriate host record.
1332 if (INADDR_NONE == aconf->ipnum.s_addr) {
1333 char buf[HOSTLEN + 1];
1335 if (INADDR_NONE == (aconf->ipnum.s_addr = inet_addr(aconf->host))) {
1336 struct DNSQuery query;
1339 query.callback = connect_dns_callback;
1340 host_from_uh(buf, aconf->host, HOSTLEN);
1341 buf[HOSTLEN] = '\0';
1343 reply = gethost_byname(buf, &query);
1346 aconf->dns_pending = 1;
1349 memcpy(&aconf->ipnum, reply->hp->h_addr, sizeof(struct in_addr));
1352 cptr = make_client(NULL, STAT_UNKNOWN_SERVER);
1355 cli_dns_reply(cptr) = reply;
1358 * Copy these in so we have something for error detection.
1360 ircd_strncpy(cli_name(cptr), aconf->name, HOSTLEN);
1361 ircd_strncpy(cli_sockhost(cptr), aconf->host, HOSTLEN);
1364 * Attach config entries to client here rather than in
1365 * completed_connection. This to avoid null pointer references
1367 attach_confs_byhost(cptr, aconf->host, CONF_SERVER);
1369 if (!find_conf_byhost(cli_confs(cptr), aconf->host, CONF_SERVER)) {
1370 sendto_opmask_butone(0, SNO_OLDSNO, "Host %s is not enabled for "
1371 "connecting: no C-line", aconf->name);
1372 if (by && IsUser(by) && !MyUser(by)) {
1373 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Connect to host %s failed: no "
1374 "C-line", by, aconf->name);
1376 det_confs_butmask(cptr, 0);
1381 * attempt to connect to the server in the conf line
1383 if (!connect_inet(aconf, cptr)) {
1384 if (by && IsUser(by) && !MyUser(by)) {
1385 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Couldn't connect to %s", by,
1388 det_confs_butmask(cptr, 0);
1393 * NOTE: if we're here we have a valid C:Line and the client should
1394 * have started the connection and stored the remote address/port and
1395 * ip address name in itself
1397 * The socket has been connected or connect is in progress.
1400 if (by && IsUser(by)) {
1401 sprintf_irc(cli_serv(cptr)->by, "%s%s", NumNick(by));
1402 assert(0 == cli_serv(cptr)->user);
1403 cli_serv(cptr)->user = cli_user(by);
1404 cli_user(by)->refcnt++;
1407 *(cli_serv(cptr))->by = '\0';
1408 /* strcpy(cptr->serv->by, "Auto"); */
1410 cli_serv(cptr)->up = &me;
1411 SetConnecting(cptr);
1413 if (cli_fd(cptr) > HighestFd)
1414 HighestFd = cli_fd(cptr);
1417 LocalClientArray[cli_fd(cptr)] = cptr;
1419 Count_newunknown(UserStats);
1420 /* Actually we lie, the connect hasn't succeeded yet, but we have a valid
1421 * cptr, so we register it now.
1422 * Maybe these two calls should be merged.
1424 add_client_to_list(cptr);
1426 nextping = CurrentTime;
1432 * Setup local socket structure to use for binding to.
1434 void set_virtual_host(struct in_addr addr)
1436 memset(&VirtualHost, 0, sizeof(VirtualHost));
1437 VirtualHost.sin_family = AF_INET;
1438 VirtualHost.sin_addr.s_addr = addr.s_addr;
1442 * Find the real hostname for the host running the server (or one which
1443 * matches the server's name) and its primary IP#. Hostname is stored
1444 * in the client structure passed as a pointer.
1446 void init_server_identity(void)
1448 const struct LocalConf* conf = conf_get_local();
1451 ircd_strncpy(cli_name(&me), conf->name, HOSTLEN);
1452 SetYXXServerName(&me, conf->numeric);