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 cptr->fd = socket(AF_INET, SOCK_STREAM, 0);
241 if (-1 == cptr->fd) {
243 report_error(SOCKET_ERROR_MSG, cptr->name, errno);
246 if (cptr->fd >= MAXCLIENTS) {
247 report_error(CONNLIMIT_ERROR_MSG, cptr->name, 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(cptr->fd, (struct sockaddr*) &VirtualHost, sizeof(VirtualHost))) {
269 report_error(BIND_ERROR_MSG, cptr->name, 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 cptr->ip.s_addr = aconf->ipnum.s_addr;
282 cptr->port = aconf->port;
283 ircd_ntoa_r(cptr->sock_ip, (const char*) &cptr->ip);
285 * we want a big buffer for server connections
287 if (!os_set_sockbufs(cptr->fd, SERVER_TCP_WINDOW)) {
289 report_error(SETBUFS_ERROR_MSG, cptr->name, errno);
293 * ALWAYS set sockets non-blocking
295 if (!os_set_nonblocking(cptr->fd)) {
297 report_error(NONB_ERROR_MSG, cptr->name, errno);
300 if (!os_connect_nonb(cptr->fd, &sin)) {
302 report_error(CONNECT_ERROR_MSG, cptr->name, 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(cptr->fd, buf, &bytes_count, &bytes_written)) {
339 cptr->flags &= ~FLAGS_BLOCKED;
341 cptr->sendB += bytes_written;
342 me.sendB += bytes_written;
343 if (cptr->sendB > 1023) {
344 cptr->sendK += (cptr->sendB >> 10);
345 cptr->sendB &= 0x03ff; /* 2^10 = 1024, 3ff = 1023 */
347 if (me.sendB > 1023) {
348 me.sendK += (me.sendB >> 10);
352 * XXX - hrmm.. set blocked here? the socket didn't
355 if (bytes_written < bytes_count)
356 cptr->flags |= FLAGS_BLOCKED;
359 cptr->flags |= FLAGS_BLOCKED;
363 cptr->flags |= FLAGS_DEADSOCKET;
366 return bytes_written;
370 void release_dns_reply(struct Client* cptr)
373 assert(MyConnect(cptr));
375 if (cptr->dns_reply) {
376 assert(0 < cptr->dns_reply->ref_count);
377 --cptr->dns_reply->ref_count;
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 ((cptr->error = os_get_sockerr(cptr->fd))) {
405 const char* msg = strerror(cptr->error);
407 msg = "Unknown error";
408 sendto_opmask_butone(0, SNO_OLDSNO, "Connection failed to %s: %s",
412 if (!(aconf = find_conf_byname(cptr->confs, cptr->name, CONF_SERVER))) {
413 sendto_opmask_butone(0, SNO_OLDSNO, "Lost Server Line for %s", cptr->name);
417 if (!EmptyString(aconf->passwd))
418 sendrawto_one(cptr, MSG_PASS " :%s", aconf->passwd);
421 /* dead code, already done in connect_server */
425 * Create a unique timestamp
428 for (i = HighestFd; i > -1; --i) {
429 if ((acptr = LocalClientArray[i]) &&
430 (IsServer(acptr) || IsHandshake(acptr))) {
431 if (acptr->serv->timestamp >= newts)
432 newts = acptr->serv->timestamp + 1;
435 assert(0 != cptr->serv);
437 cptr->serv->timestamp = newts;
440 * Make us timeout after twice the timeout for DNS look ups
442 cptr->lasttime = CurrentTime;
443 cptr->flags |= FLAGS_PINGSENT;
445 sendrawto_one(cptr, MSG_SERVER " %s 1 %Tu %Tu J%s %s%s :%s",
446 me.name, me.serv->timestamp, newts, MAJOR_PROTOCOL,
447 NumServCap(&me), me.info);
449 return (IsDead(cptr)) ? 0 : 1;
455 * Close the physical connection. This function must make
456 * MyConnect(cptr) == FALSE, and set cptr->from == NULL.
458 void close_connection(struct Client *cptr)
460 struct ConfItem* aconf;
462 if (IsServer(cptr)) {
463 ServerStats->is_sv++;
464 ServerStats->is_sbs += cptr->sendB;
465 ServerStats->is_sbr += cptr->receiveB;
466 ServerStats->is_sks += cptr->sendK;
467 ServerStats->is_skr += cptr->receiveK;
468 ServerStats->is_sti += CurrentTime - cptr->firsttime;
469 if (ServerStats->is_sbs > 1023) {
470 ServerStats->is_sks += (ServerStats->is_sbs >> 10);
471 ServerStats->is_sbs &= 0x3ff;
473 if (ServerStats->is_sbr > 1023) {
474 ServerStats->is_skr += (ServerStats->is_sbr >> 10);
475 ServerStats->is_sbr &= 0x3ff;
478 * If the connection has been up for a long amount of time, schedule
479 * a 'quick' reconnect, else reset the next-connect cycle.
481 if ((aconf = find_conf_exact(cptr->name, 0, cptr->sockhost, CONF_SERVER))) {
483 * Reschedule a faster reconnect, if this was a automaticly
484 * connected configuration entry. (Note that if we have had
485 * a rehash in between, the status has been changed to
486 * CONF_ILLEGAL). But only do this if it was a "good" link.
488 aconf->hold = CurrentTime;
489 aconf->hold += (aconf->hold - cptr->since > HANGONGOODLINK) ?
490 HANGONRETRYDELAY : ConfConFreq(aconf);
491 if (nextconnect > aconf->hold)
492 nextconnect = aconf->hold;
495 else if (IsUser(cptr)) {
496 ServerStats->is_cl++;
497 ServerStats->is_cbs += cptr->sendB;
498 ServerStats->is_cbr += cptr->receiveB;
499 ServerStats->is_cks += cptr->sendK;
500 ServerStats->is_ckr += cptr->receiveK;
501 ServerStats->is_cti += CurrentTime - cptr->firsttime;
502 if (ServerStats->is_cbs > 1023) {
503 ServerStats->is_cks += (ServerStats->is_cbs >> 10);
504 ServerStats->is_cbs &= 0x3ff;
506 if (ServerStats->is_cbr > 1023) {
507 ServerStats->is_ckr += (ServerStats->is_cbr >> 10);
508 ServerStats->is_cbr &= 0x3ff;
512 ServerStats->is_ni++;
515 flush_connections(cptr);
516 LocalClientArray[cptr->fd] = 0;
520 cptr->flags |= FLAGS_DEADSOCKET;
522 MsgQClear(&cptr->sendQ);
523 DBufClear(&cptr->recvQ);
524 memset(cptr->passwd, 0, sizeof(cptr->passwd));
525 set_snomask(cptr, 0, SNO_SET);
527 det_confs_butmask(cptr, 0);
529 if (cptr->listener) {
530 release_listener(cptr->listener);
534 for ( ; HighestFd > 0; --HighestFd) {
535 if (LocalClientArray[HighestFd])
540 int net_close_unregistered_connections(struct Client* source)
547 for (i = HighestFd; i > 0; --i) {
548 if ((cptr = LocalClientArray[i]) && !IsRegistered(cptr)) {
549 send_reply(source, RPL_CLOSING, get_client_name(source, HIDE_IP));
550 exit_client(source, cptr, &me, "Oper Closing");
557 /*----------------------------------------------------------------------------
560 * Creates a client which has just connected to us on the given fd.
561 * The sockhost field is initialized with the ip# of the host.
562 * The client is not added to the linked list of clients, it is
563 * passed off to the auth handler for dns and ident queries.
564 *--------------------------------------------------------------------------*/
565 void add_connection(struct Listener* listener, int fd) {
566 struct sockaddr_in addr;
567 struct Client *new_client;
568 time_t next_target = 0;
570 const char* const throttle_message =
571 "ERROR :Your host is trying to (re)connect too fast -- throttled\r\n";
572 /* 12345678901234567890123456789012345679012345678901234567890123456 */
574 assert(0 != listener);
578 * Removed preliminary access check. Full check is performed in m_server and
579 * m_user instead. Also connection time out help to get rid of unwanted
582 if (!os_get_peername(fd, &addr) || !os_set_nonblocking(fd)) {
583 ++ServerStats->is_ref;
589 * Add this local client to the IPcheck registry.
591 * If they're throttled, murder them, but tell them why first.
593 if (!IPcheck_local_connect(addr.sin_addr, &next_target) && !listener->server) {
594 ++ServerStats->is_ref;
595 write(fd, throttle_message, strlen(throttle_message));
600 new_client = make_client(0, ((listener->server) ?
601 STAT_UNKNOWN_SERVER : STAT_UNKNOWN_USER));
604 * Copy ascii address to 'sockhost' just in case. Then we have something
605 * valid to put into error messages...
607 ircd_ntoa_r(new_client->sock_ip, (const char*) &addr.sin_addr);
608 strcpy(new_client->sockhost, new_client->sock_ip);
609 new_client->ip.s_addr = addr.sin_addr.s_addr;
610 new_client->port = ntohs(addr.sin_port);
613 new_client->nexttarget = next_target;
616 new_client->listener = listener;
617 ++listener->ref_count;
619 Count_newunknown(UserStats);
620 /* if we've made it this far we can put the client on the auth query pile */
621 start_auth(new_client);
628 * Read a 'packet' of data from a connection and process it. Read in 8k
629 * chunks to give a better performance rating (for server connections).
630 * Do some tricky stuff for client connections to make sure they don't do
631 * any flooding >:-) -avalon
633 static int read_packet(struct Client *cptr, int socket_ready)
635 unsigned int dolen = 0;
636 unsigned int length = 0;
638 if (socket_ready && !(IsUser(cptr) && DBufLength(&cptr->recvQ) > CLIENT_FLOOD)) {
639 switch (os_recv_nonb(cptr->fd, readbuf, sizeof(readbuf), &length)) {
642 cptr->lasttime = CurrentTime;
643 if (cptr->lasttime > cptr->since)
644 cptr->since = cptr->lasttime;
645 cptr->flags &= ~(FLAGS_PINGSENT | FLAGS_NONL);
652 /* cptr->flags |= FLAGS_DEADSOCKET; */
658 * For server connections, we process as many as we can without
659 * worrying about the time of day or anything :)
661 if (length > 0 && IsServer(cptr)) {
662 return server_dopacket(cptr, readbuf, length);
666 * Before we even think of parsing what we just read, stick
667 * it on the end of the receive queue and do it when its
670 if (length > 0 && 0 == dbuf_put(&cptr->recvQ, readbuf, length)) {
671 return exit_client(cptr, cptr, &me, "dbuf_put fail");
673 #ifndef NOFLOODCONTROL
675 * XXX - cptr will always be a user or unregistered
677 if (IsUser(cptr) && DBufLength(&cptr->recvQ) > CLIENT_FLOOD)
678 return exit_client(cptr, cptr, &me, "Excess Flood");
680 while (DBufLength(&cptr->recvQ) && !NoNewLine(cptr) &&
681 (IsTrusted(cptr) || cptr->since - CurrentTime < 10))
683 while (DBufLength(&cptr->recvQ) && !NoNewLine(cptr))
687 * If it has become registered as a Server
688 * then skip the per-message parsing below.
690 if (IsServer(cptr)) {
691 dolen = dbuf_get(&cptr->recvQ, readbuf, sizeof(readbuf));
692 return (dolen) ? server_dopacket(cptr, readbuf, dolen) : 1;
694 dolen = dbuf_getmsg(&cptr->recvQ, cptr->buffer, BUFSIZE);
696 * Devious looking...whats it do ? well..if a client
697 * sends a *long* message without any CR or LF, then
698 * dbuf_getmsg fails and we pull it out using this
699 * loop which just gets the next 512 bytes and then
700 * deletes the rest of the buffer contents.
704 if (DBufLength(&cptr->recvQ) < 510)
705 cptr->flags |= FLAGS_NONL;
707 DBufClear(&cptr->recvQ);
709 else if (CPTR_KILLED == client_dopacket(cptr, dolen))
716 static int on_write_unblocked(struct Client* cptr)
719 * ...room for writing, empty some queue then...
721 cptr->flags &= ~FLAGS_BLOCKED;
722 if (IsConnecting(cptr)) {
723 if (!completed_connection(cptr))
726 else if (cptr->listing && MsgQLength(&cptr->sendQ) < 2048)
727 list_next_channels(cptr, 64);
733 * Select / Poll Read Algorithm for ircd
735 * We need to check the file descriptors for all the different types
736 * of things that use them, so check for reads on everything but connects
737 * and writes on connects and descriptors that are blocked
739 * for each (client in local) {
740 * if (not connecting)
742 * if (connecting or blocked)
747 * for each (client in local) {
748 * if (there are descriptors to check) {
749 * if (write activity)
756 * Note we must always process data read whether or not there has been
757 * read activity or file descriptors set, since data is buffered by the client.
766 #if defined(POLLMSG) && defined(POLLIN) && defined(POLLRDNORM)
767 # define POLLREADFLAGS (POLLMSG|POLLIN|POLLRDNORM)
769 # if defined(POLLIN) && defined(POLLRDNORM)
770 # define POLLREADFLAGS (POLLIN|POLLRDNORM)
773 # define POLLREADFLAGS POLLIN
775 # if defined(POLLRDNORM)
776 # define POLLREADFLAGS POLLRDNORM
782 #if defined(POLLOUT) && defined(POLLWRNORM)
783 #define POLLWRITEFLAGS (POLLOUT|POLLWRNORM)
785 # if defined(POLLOUT)
786 # define POLLWRITEFLAGS POLLOUT
788 # if defined(POLLWRNORM)
789 # define POLLWRITEFLAGS POLLWRNORM
795 #define POLLERRORS (POLLHUP|POLLERR)
797 #define POLLERRORS POLLERR
801 * NOTE: pfd and pfd_count are local variable names in read_message
803 #define PFD_SETR(xfd) \
804 do { CHECK_ADD_PFD(xfd) pfd->events |= POLLREADFLAGS; } while(0)
805 #define PFD_SETW(xfd) \
806 do { CHECK_ADD_PFD(xfd) pfd->events |= POLLWRITEFLAGS; } while(0)
808 #define CHECK_ADD_PFD(xfd) \
809 if (pfd->fd != xfd) { \
810 pfd = &poll_fds[pfd_count++]; \
811 poll_fds[pfd_count].fd = -1; \
817 * Check all connections for new connections and input data that is to be
818 * processed. Also check for connections with data queued and whether we can
821 * Don't ever use ZERO for `delay', unless you mean to poll and then
822 * you have to have sleep/wait somewhere else in the code.--msa
824 int read_message(time_t delay)
826 struct pollfd poll_fds[MAXCONNECTIONS + 1];
828 struct Listener* listener = 0;
829 struct AuthRequest* auth = 0;
830 struct AuthRequest* auth_next = 0;
831 struct UPing* uping = 0;
832 struct UPing* uping_next = 0;
833 time_t delay2 = delay;
840 struct pollfd* res_pfd;
841 struct pollfd* uping_pfd;
845 unsigned int timeout;
854 if (-1 < ResolverFileDescriptor) {
855 PFD_SETR(ResolverFileDescriptor);
858 if (-1 < UPingFileDescriptor) {
859 PFD_SETR(UPingFileDescriptor);
863 * add uping descriptors
865 for (uping = uping_begin(); uping; uping = uping_next) {
866 uping_next = uping->next;
869 if (uping->lastsent && CurrentTime > uping->timeout) {
873 uping->index = pfd_count;
878 * add auth file descriptors
880 for (auth = AuthPollList; auth; auth = auth->next) {
881 assert(-1 < auth->fd);
882 auth->index = pfd_count;
883 if (IsAuthConnect(auth))
889 * add listener file descriptors
891 for (listener = ListenerPollList; listener; listener = listener->next) {
892 assert(-1 < listener->fd);
894 * pfd_count is incremented by PFD_SETR so we need to save the
897 listener->index = pfd_count;
898 PFD_SETR(listener->fd);
901 for (i = HighestFd; -1 < i; --i) {
902 if ((cptr = LocalClientArray[i])) {
904 if (DBufLength(&cptr->recvQ))
906 if (DBufLength(&cptr->recvQ) < 4088 || IsServer(cptr)) {
909 if (MsgQLength(&cptr->sendQ) || IsConnecting(cptr) ||
910 (cptr->listing && MsgQLength(&cptr->sendQ) < 2048)) {
916 Debug((DEBUG_INFO, "poll: %d %d", delay, delay2));
918 timeout = (IRCD_MIN(delay2, delay)) * 1000;
920 nfds = poll(poll_fds, pfd_count, timeout);
922 CurrentTime = time(0);
928 report_error(POLL_ERROR_MSG, me.name, errno);
931 server_restart("too many poll errors");
933 CurrentTime = time(0);
936 if (uping_pfd && (uping_pfd->revents & (POLLREADFLAGS | POLLERRORS))) {
941 * check uping replies
943 for (uping = uping_begin(); uping; uping = uping_next) {
944 uping_next = uping->next;
946 assert(-1 < uping->index);
947 if (poll_fds[uping->index].revents) {
952 else if (CurrentTime > uping->lastsent) {
953 uping->lastsent = CurrentTime;
959 if (res_pfd && (res_pfd->revents & (POLLREADFLAGS | POLLERRORS))) {
966 for (auth = AuthPollList; auth; auth = auth_next) {
967 auth_next = auth->next;
970 * check for any event, we only ask for one at a time
972 if (poll_fds[i].revents) {
973 if (IsAuthConnect(auth))
974 send_auth_query(auth);
976 read_auth_reply(auth);
984 for (listener = ListenerPollList; listener; listener = listener->next) {
986 if (poll_fds[i].revents) {
987 accept_connection(listener);
993 * i contains the next non-auth/non-listener index, since we put the
994 * resolver, auth and listener, file descriptors in poll_fds first,
995 * the very next one should be the start of the clients
997 pfd = &poll_fds[++i];
999 for ( ; (i < pfd_count); ++i, ++pfd) {
1000 if (!(cptr = LocalClientArray[pfd->fd]))
1002 read_ready = write_ready = 0;
1004 if (0 < nfds && pfd->revents) {
1007 read_ready = pfd->revents & POLLREADFLAGS;
1008 write_ready = pfd->revents & POLLWRITEFLAGS;
1010 if (pfd->revents & POLLERRORS) {
1011 if (pfd->events & POLLREADFLAGS)
1013 if (pfd->events & POLLWRITEFLAGS)
1018 if (!on_write_unblocked(cptr) || IsDead(cptr)) {
1019 const char* msg = (cptr->error) ? strerror(cptr->error) : cptr->info;
1021 msg = "Unknown error";
1022 exit_client(cptr, cptr, &me, msg);
1026 length = 1; /* for fall through case */
1027 if ((!NoNewLine(cptr) || read_ready) && !IsDead(cptr)) {
1028 if (CPTR_KILLED == (length = read_packet(cptr, read_ready)))
1032 /* Bullshit, why would we want to flush sockets while using non-blocking?
1033 * This uses > 4% cpu! --Run */
1035 flush_connections(poll_cptr[i]);
1038 const char* msg = (cptr->error) ? strerror(cptr->error) : cptr->info;
1040 msg = "Unknown error";
1041 exit_client(cptr, cptr, &me, (char*) msg);
1046 cptr->flags |= FLAGS_DEADSOCKET;
1048 * ...hmm, with non-blocking sockets we might get
1049 * here from quite valid reasons, although.. why
1050 * would select report "data available" when there
1051 * wasn't... So, this must be an error anyway... --msa
1052 * actually, EOF occurs when read() returns 0 and
1053 * in due course, select() returns that fd as ready
1054 * for reading even though it ends up being an EOF. -avalon
1056 Debug((DEBUG_ERROR, "READ ERROR: fd = %d %d %d", pfd->fd, errno, length));
1058 if ((IsServer(cptr) || IsHandshake(cptr)) && cptr->error == 0 && length == 0)
1059 exit_client_msg(cptr, cptr, &me, "Server %s closed the connection (%s)",
1060 cptr->name, cptr->serv->last_error_msg);
1062 const char* msg = (cptr->error) ? strerror(cptr->error) : "EOF from client";
1064 msg = "Unknown error";
1065 exit_client_msg(cptr, cptr, &me, "Read error: %s", msg);
1070 #else /* USE_SELECT */
1073 * Check all connections for new connections and input data that is to be
1074 * processed. Also check for connections with data queued and whether we can
1077 * Don't ever use ZERO for `delay', unless you mean to poll and then
1078 * you have to have sleep/wait somewhere else in the code.--msa
1080 int read_message(time_t delay)
1082 struct Client* cptr;
1083 struct Listener* listener;
1084 struct AuthRequest* auth = 0;
1085 struct AuthRequest* auth_next = 0;
1086 struct UPing* uping;
1087 struct UPing* uping_next;
1089 struct timeval wait;
1090 time_t delay2 = delay;
1091 unsigned int usec = 0;
1102 FD_ZERO(&write_set);
1104 if (-1 < ResolverFileDescriptor)
1105 FD_SET(ResolverFileDescriptor, &read_set);
1106 if (-1 < UPingFileDescriptor)
1107 FD_SET(UPingFileDescriptor, &read_set);
1109 * set up uping file descriptors
1111 for (uping = uping_begin(); uping; uping = uping_next) {
1112 uping_next = uping->next;
1113 if (uping->active) {
1115 if (uping->lastsent && CurrentTime > uping->timeout) {
1119 assert(-1 < uping->fd);
1120 FD_SET(uping->fd, &read_set);
1124 * set auth file descriptors
1126 for (auth = AuthPollList; auth; auth = auth->next) {
1127 assert(-1 < auth->fd);
1128 if (IsAuthConnect(auth))
1129 FD_SET(auth->fd, &write_set);
1130 else /* if (IsAuthPending(auth)) */
1131 FD_SET(auth->fd, &read_set);
1134 * set listener file descriptors
1136 for (listener = ListenerPollList; listener; listener = listener->next) {
1137 assert(-1 < listener->fd);
1138 FD_SET(listener->fd, &read_set);
1141 for (i = HighestFd; i > -1; --i) {
1142 if ((cptr = LocalClientArray[i])) {
1143 if (DBufLength(&cptr->recvQ))
1145 if (DBufLength(&cptr->recvQ) < 4088 || IsServer(cptr))
1146 FD_SET(i, &read_set);
1147 if (MsgQLength(&cptr->sendQ) || IsConnecting(cptr) ||
1148 (cptr->listing && MsgQLength(&cptr->sendQ) < 2048))
1149 FD_SET(i, &write_set);
1153 wait.tv_sec = IRCD_MIN(delay2, delay);
1154 wait.tv_usec = usec;
1156 Debug((DEBUG_INFO, "select: %d %d", delay, delay2));
1158 nfds = select(FD_SETSIZE, &read_set, &write_set, 0, &wait);
1160 CurrentTime = time(0);
1167 report_error(SELECT_ERROR_MSG, me.name, errno);
1169 server_restart("too many select errors");
1171 CurrentTime = time(0);
1174 if (-1 < UPingFileDescriptor && FD_ISSET(UPingFileDescriptor, &read_set)) {
1178 for (uping = uping_begin(); uping; uping = uping_next) {
1179 uping_next = uping->next;
1180 if (uping->active) {
1181 assert(-1 < uping->fd);
1182 if (FD_ISSET(uping->fd, &read_set)) {
1187 else if (CurrentTime > uping->lastsent) {
1188 uping->lastsent = CurrentTime;
1193 if (-1 < ResolverFileDescriptor && FD_ISSET(ResolverFileDescriptor, &read_set)) {
1198 * Check fd sets for the auth fd's (if set and valid!) first
1199 * because these can not be processed using the normal loops below.
1202 for (auth = AuthPollList; auth; auth = auth_next) {
1203 auth_next = auth->next;
1204 assert(-1 < auth->fd);
1205 if (IsAuthConnect(auth) && FD_ISSET(auth->fd, &write_set)) {
1206 send_auth_query(auth);
1210 else if (FD_ISSET(auth->fd, &read_set)) {
1211 read_auth_reply(auth);
1217 * next accept connections from active listeners
1219 for (listener = ListenerPollList; listener; listener = listener->next) {
1220 assert(-1 < listener->fd);
1221 if (0 < nfds && FD_ISSET(listener->fd, &read_set))
1222 accept_connection(listener);
1225 for (i = HighestFd; -1 < i; --i) {
1226 if (!(cptr = LocalClientArray[i]))
1230 if (FD_ISSET(i, &write_set)) {
1232 if (!on_write_unblocked(cptr) || IsDead(cptr)) {
1233 const char* msg = (cptr->error) ? strerror(cptr->error) : cptr->info;
1235 msg = "Unknown error";
1236 if (FD_ISSET(i, &read_set))
1238 exit_client(cptr, cptr, &me, msg);
1242 if ((read_ready = FD_ISSET(i, &read_set)))
1245 length = 1; /* for fall through case */
1246 if ((!NoNewLine(cptr) || read_ready) && !IsDead(cptr)) {
1247 if (CPTR_KILLED == (length = read_packet(cptr, read_ready)))
1251 const char* msg = (cptr->error) ? strerror(cptr->error) : cptr->info;
1253 msg = "Unknown error";
1254 exit_client(cptr, cptr, &me, msg);
1261 * ...hmm, with non-blocking sockets we might get
1262 * here from quite valid reasons, although.. why
1263 * would select report "data available" when there
1264 * wasn't... So, this must be an error anyway... --msa
1265 * actually, EOF occurs when read() returns 0 and
1266 * in due course, select() returns that fd as ready
1267 * for reading even though it ends up being an EOF. -avalon
1269 Debug((DEBUG_ERROR, "READ ERROR: fd = %d %d %d", i, cptr->error, length));
1271 if ((IsServer(cptr) || IsHandshake(cptr)) && cptr->error == 0 && length == 0)
1272 exit_client_msg(cptr, cptr, &me, "Server %s closed the connection (%s)",
1273 cptr->name, cptr->serv->last_error_msg);
1275 const char* msg = (cptr->error) ? strerror(cptr->error) : "EOF from client";
1277 msg = "Unknown error";
1278 exit_client_msg(cptr, cptr, &me, "Read error: %s", msg);
1284 #endif /* USE_SELECT */
1287 * connect_server - start or complete a connection to another server
1288 * returns true (1) if successful, false (0) otherwise
1290 * aconf must point to a valid C:line
1291 * m_connect calls this with a valid by client and a null reply
1292 * try_connections calls this with a null by client, and a null reply
1293 * connect_dns_callback call this with a null by client, and a valid reply
1295 * XXX - if this comes from an m_connect message and a dns query needs to
1296 * be done, we loose the information about who started the connection and
1297 * it's considered an auto connect.
1299 int connect_server(struct ConfItem* aconf, struct Client* by,
1300 struct DNSReply* reply)
1302 struct Client* cptr = 0;
1305 if (aconf->dns_pending) {
1306 sendto_opmask_butone(0, SNO_OLDSNO, "Server %s connect DNS pending",
1310 Debug((DEBUG_NOTICE, "Connect to %s[@%s]", aconf->name,
1311 ircd_ntoa((const char*) &aconf->ipnum)));
1313 if ((cptr = FindClient(aconf->name))) {
1314 if (IsServer(cptr) || IsMe(cptr)) {
1315 sendto_opmask_butone(0, SNO_OLDSNO, "Server %s already present from %s",
1316 aconf->name, cptr->from->name);
1317 if (by && IsUser(by) && !MyUser(by)) {
1318 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Server %s already present "
1319 "from %s", by, aconf->name, cptr->from->name);
1323 else if (IsHandshake(cptr) || IsConnecting(cptr)) {
1324 if (by && IsUser(by)) {
1325 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Connection to %s already in "
1326 "progress", by, cptr->name);
1332 * If we dont know the IP# for this host and itis a hostname and
1333 * not a ip# string, then try and find the appropriate host record.
1335 if (INADDR_NONE == aconf->ipnum.s_addr) {
1336 char buf[HOSTLEN + 1];
1338 if (INADDR_NONE == (aconf->ipnum.s_addr = inet_addr(aconf->host))) {
1339 struct DNSQuery query;
1342 query.callback = connect_dns_callback;
1343 host_from_uh(buf, aconf->host, HOSTLEN);
1344 buf[HOSTLEN] = '\0';
1346 reply = gethost_byname(buf, &query);
1349 aconf->dns_pending = 1;
1352 memcpy(&aconf->ipnum, reply->hp->h_addr, sizeof(struct in_addr));
1355 cptr = make_client(NULL, STAT_UNKNOWN_SERVER);
1358 cptr->dns_reply = reply;
1361 * Copy these in so we have something for error detection.
1363 ircd_strncpy(cptr->name, aconf->name, HOSTLEN);
1364 ircd_strncpy(cptr->sockhost, aconf->host, HOSTLEN);
1367 * Attach config entries to client here rather than in
1368 * completed_connection. This to avoid null pointer references
1370 attach_confs_byhost(cptr, aconf->host, CONF_SERVER);
1372 if (!find_conf_byhost(cptr->confs, aconf->host, CONF_SERVER)) {
1373 sendto_opmask_butone(0, SNO_OLDSNO, "Host %s is not enabled for "
1374 "connecting: no C-line", aconf->name);
1375 if (by && IsUser(by) && !MyUser(by)) {
1376 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Connect to host %s failed: no "
1377 "C-line", by, aconf->name);
1379 det_confs_butmask(cptr, 0);
1384 * attempt to connect to the server in the conf line
1386 if (!connect_inet(aconf, cptr)) {
1387 if (by && IsUser(by) && !MyUser(by)) {
1388 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Couldn't connect to %s", by,
1391 det_confs_butmask(cptr, 0);
1396 * NOTE: if we're here we have a valid C:Line and the client should
1397 * have started the connection and stored the remote address/port and
1398 * ip address name in itself
1400 * The socket has been connected or connect is in progress.
1403 if (by && IsUser(by)) {
1404 sprintf_irc(cptr->serv->by, "%s%s", NumNick(by));
1405 assert(0 == cptr->serv->user);
1406 cptr->serv->user = by->user;
1410 *cptr->serv->by = '\0';
1411 /* strcpy(cptr->serv->by, "Auto"); */
1413 cptr->serv->up = &me;
1414 SetConnecting(cptr);
1416 if (cptr->fd > HighestFd)
1417 HighestFd = cptr->fd;
1420 LocalClientArray[cptr->fd] = cptr;
1422 Count_newunknown(UserStats);
1423 /* Actually we lie, the connect hasn't succeeded yet, but we have a valid
1424 * cptr, so we register it now.
1425 * Maybe these two calls should be merged.
1427 add_client_to_list(cptr);
1429 nextping = CurrentTime;
1435 * Setup local socket structure to use for binding to.
1437 void set_virtual_host(struct in_addr addr)
1439 memset(&VirtualHost, 0, sizeof(VirtualHost));
1440 VirtualHost.sin_family = AF_INET;
1441 VirtualHost.sin_addr.s_addr = addr.s_addr;
1445 * Find the real hostname for the host running the server (or one which
1446 * matches the server's name) and its primary IP#. Hostname is stored
1447 * in the client structure passed as a pointer.
1449 void init_server_identity(void)
1451 const struct LocalConf* conf = conf_get_local();
1454 ircd_strncpy(me.name, conf->name, HOSTLEN);
1455 SetYXXServerName(&me, conf->numeric);