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.
21 * @brief Functions that now (or in the past) relied on BSD APIs.
32 #include "ircd_alloc.h"
34 #include "ircd_features.h"
35 #include "ircd_osdep.h"
36 #include "ircd_reply.h"
37 #include "ircd_snprintf.h"
38 #include "ircd_string.h"
48 #include "querycmds.h"
61 /* #include <assert.h> -- Now using assert in ircd_log.h */
68 #include <sys/ioctl.h>
69 #include <sys/socket.h>
71 #include <sys/utsname.h>
78 /** Array of my own clients, indexed by file descriptor. */
79 struct Client* LocalClientArray[MAXCONNECTIONS];
80 /** Maximum file descriptor in current use. */
82 /** Default local address for outbound IPv4 connections. */
83 struct irc_sockaddr VirtualHost_v4;
84 /** Default local address for outbound IPv6 connections. */
85 struct irc_sockaddr VirtualHost_v6;
86 /** Temporary buffer for reading data from a peer. */
87 static char readbuf[SERVER_TCP_WINDOW];
90 * report_error text constants
92 const char* const ACCEPT_ERROR_MSG = "error accepting connection for %s: %s";
93 const char* const BIND_ERROR_MSG = "bind error for %s: %s";
94 const char* const CONNECT_ERROR_MSG = "connect to host %s failed: %s";
95 const char* const CONNLIMIT_ERROR_MSG = "connect limit exceeded for %s: %s";
96 const char* const LISTEN_ERROR_MSG = "listen error for %s: %s";
97 const char* const NONB_ERROR_MSG = "error setting non-blocking for %s: %s";
98 const char* const PEERNAME_ERROR_MSG = "getpeername failed for %s: %s";
99 const char* const POLL_ERROR_MSG = "poll error for %s: %s";
100 const char* const REGISTER_ERROR_MSG = "registering %s: %s";
101 const char* const REUSEADDR_ERROR_MSG = "error setting SO_REUSEADDR for %s: %s";
102 const char* const SELECT_ERROR_MSG = "select error for %s: %s";
103 const char* const SETBUFS_ERROR_MSG = "error setting buffer size for %s: %s";
104 const char* const SOCKET_ERROR_MSG = "error creating socket for %s: %s";
105 const char* const TOS_ERROR_MSG = "error setting TOS for %s: %s";
108 static void client_sock_callback(struct Event* ev);
109 static void client_timer_callback(struct Event* ev);
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 mileage 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...
136 /** Replacement for perror(). Record error to log. Send a copy to all
137 * *LOCAL* opers, but only if no errors were sent to them in the last
139 * @param text A *format* string for outputting error. It must contain
140 * only two '%s', the first will be replaced by the sockhost from the
141 * cptr, and the latter will be taken from sys_errlist[errno].
142 * @param who The client associated with the error.
143 * @param err The errno value to display.
145 void report_error(const char* text, const char* who, int err)
147 static time_t last_notice = 0;
148 int errtmp = errno; /* debug may change 'errno' */
149 const char* errmsg = (err) ? strerror(err) : "";
152 errmsg = "Unknown error";
154 if (EmptyString(who))
157 if (last_notice + 20 < CurrentTime) {
159 * pace error messages so opers don't get flooded by transients
161 sendto_opmask_butone(0, SNO_OLDSNO, text, who, errmsg);
162 last_notice = CurrentTime;
164 log_write(LS_SOCKET, L_ERROR, 0, text, who, errmsg);
169 /** Called when resolver query finishes. If the DNS lookup was
170 * successful, start the connection; otherwise notify opers of the
172 * @param vptr The struct ConfItem representing the Connect block.
173 * @param hp A pointer to the DNS lookup results (NULL on failure).
175 static void connect_dns_callback(void* vptr, struct DNSReply* hp)
177 struct ConfItem* aconf = (struct ConfItem*) vptr;
179 aconf->dns_pending = 0;
181 memcpy(&aconf->address, &hp->addr, sizeof(aconf->address));
183 connect_server(aconf, 0);
186 sendto_opmask_butone(0, SNO_OLDSNO, "Connect to %s failed: host lookup",
190 /** Closes all file descriptors.
191 * @param close_stderr If non-zero, also close stderr.
193 void close_connections(int close_stderr)
202 for (i = 3; i < MAXCONNECTIONS; ++i)
206 /** Initialize process fd limit to MAXCONNECTIONS.
208 int init_connection_limits(void)
210 int limit = os_set_fdlimit(MAXCONNECTIONS);
214 fprintf(stderr, "error setting max fd's to %d\n", limit);
216 else if (limit > 0) {
217 fprintf(stderr, "ircd fd table too big\nHard Limit: %d IRC max: %d\n",
218 limit, MAXCONNECTIONS);
219 fprintf(stderr, "set MAXCONNECTIONS to a smaller value");
224 /** Set up address and port and make a connection.
225 * @param aconf Provides the connection information.
226 * @param cptr Client structure for the peer.
227 * @return Non-zero on success; zero on failure.
229 static int connect_inet(struct ConfItem* aconf, struct Client* cptr)
231 const struct irc_sockaddr *local;
236 * Might as well get sockhost from here, the connection is attempted
237 * with it so if it fails its useless.
239 if (irc_in_addr_valid(&aconf->origin.addr))
240 local = &aconf->origin;
241 else if (irc_in_addr_is_ipv4(&aconf->address.addr))
242 local = &VirtualHost_v4;
244 local = &VirtualHost_v6;
245 cli_fd(cptr) = os_socket(local, SOCK_STREAM, cli_name(cptr));
246 if (cli_fd(cptr) < 0)
250 * save connection info in client
252 memcpy(&cli_ip(cptr), &aconf->address.addr, sizeof(cli_ip(cptr)));
253 ircd_ntoa_r(cli_sock_ip(cptr), &cli_ip(cptr));
255 * we want a big buffer for server connections
257 if (!os_set_sockbufs(cli_fd(cptr), feature_int(FEAT_SOCKSENDBUF), feature_int(FEAT_SOCKRECVBUF))) {
258 cli_error(cptr) = errno;
259 report_error(SETBUFS_ERROR_MSG, cli_name(cptr), errno);
265 * Set the TOS bits - this is nonfatal if it doesn't stick.
267 if (!os_set_tos(cli_fd(cptr), FEAT_TOS_SERVER)) {
268 report_error(TOS_ERROR_MSG, cli_name(cptr), errno);
270 if ((result = os_connect_nonb(cli_fd(cptr), &aconf->address)) == IO_FAILURE) {
271 cli_error(cptr) = errno;
272 report_error(CONNECT_ERROR_MSG, cli_name(cptr), errno);
277 if (!socket_add(&(cli_socket(cptr)), client_sock_callback,
278 (void*) cli_connect(cptr),
279 (result == IO_SUCCESS) ? SS_CONNECTED : SS_CONNECTING,
280 SOCK_EVENT_READABLE, cli_fd(cptr))) {
281 cli_error(cptr) = ENFILE;
282 report_error(REGISTER_ERROR_MSG, cli_name(cptr), ENFILE);
287 cli_freeflag(cptr) |= FREEFLAG_SOCKET;
291 /** Attempt to send a sequence of bytes to the connection.
292 * As a side effect, updates \a cptr's FLAG_BLOCKED setting
293 * and sendB/sendK fields.
294 * @param cptr Client that should receive data.
295 * @param buf Message buffer to send to client.
296 * @return Negative on connection-fatal error; otherwise
297 * number of bytes sent.
299 unsigned int deliver_it(struct Client *cptr, struct MsgQ *buf)
301 unsigned int bytes_written = 0;
302 unsigned int bytes_count = 0;
305 switch (os_sendv_nonb(cli_fd(cptr), buf, &bytes_count, &bytes_written)) {
307 ClrFlag(cptr, FLAG_BLOCKED);
309 cli_sendB(cptr) += bytes_written;
310 cli_sendB(&me) += bytes_written;
311 /* A partial write implies that future writes will block. */
312 if (bytes_written < bytes_count)
313 SetFlag(cptr, FLAG_BLOCKED);
316 SetFlag(cptr, FLAG_BLOCKED);
319 cli_error(cptr) = errno;
320 SetFlag(cptr, FLAG_DEADSOCKET);
323 return bytes_written;
326 /** Free the client's DNS reply, if any.
327 * @param cptr Client to operate on.
329 void release_dns_reply(struct Client* cptr)
332 assert(MyConnect(cptr));
334 if (cli_dns_reply(cptr)) {
335 MyFree(cli_dns_reply(cptr)->h_name);
336 MyFree(cli_dns_reply(cptr));
337 cli_dns_reply(cptr) = 0;
341 /** Complete non-blocking connect()-sequence. Check access and
342 * terminate connection, if trouble detected.
343 * @param cptr Client to which we have connected, with all ConfItem structs attached.
344 * @return Zero on failure (caller should exit_client()), non-zero on success.
346 static int completed_connection(struct Client* cptr)
348 struct ConfItem *aconf;
350 struct Client *acptr;
356 * get the socket status from the fd first to check if
357 * connection actually succeeded
359 if ((cli_error(cptr) = os_get_sockerr(cli_fd(cptr)))) {
360 const char* msg = strerror(cli_error(cptr));
362 msg = "Unknown error";
363 sendto_opmask_butone(0, SNO_OLDSNO, "Connection failed to %s: %s",
364 cli_name(cptr), msg);
367 if (!(aconf = find_conf_byname(cli_confs(cptr), cli_name(cptr), CONF_SERVER))) {
368 sendto_opmask_butone(0, SNO_OLDSNO, "Lost Server Line for %s", cli_name(cptr));
371 if (s_state(&(cli_socket(cptr))) == SS_CONNECTING)
372 socket_state(&(cli_socket(cptr)), SS_CONNECTED);
374 if (!EmptyString(aconf->passwd))
375 sendrawto_one(cptr, MSG_PASS " :%s", aconf->passwd);
378 * Create a unique timestamp
381 for (i = HighestFd; i > -1; --i) {
382 if ((acptr = LocalClientArray[i]) &&
383 (IsServer(acptr) || IsHandshake(acptr))) {
384 if (cli_serv(acptr)->timestamp >= newts)
385 newts = cli_serv(acptr)->timestamp + 1;
388 assert(0 != cli_serv(cptr));
390 cli_serv(cptr)->timestamp = newts;
393 * Make us timeout after twice the timeout for DNS look ups
395 cli_lasttime(cptr) = CurrentTime;
396 SetFlag(cptr, FLAG_PINGSENT);
398 sendrawto_one(cptr, MSG_SERVER " %s 1 %Tu %Tu J%s %s%s +%s6 :%s",
399 cli_name(&me), cli_serv(&me)->timestamp, newts,
400 MAJOR_PROTOCOL, NumServCap(&me),
401 feature_bool(FEAT_HUB) ? "h" : "", cli_info(&me));
403 return (IsDead(cptr)) ? 0 : 1;
406 /** Close the physical connection. Side effects: MyConnect(cptr)
407 * becomes false and cptr->from becomes NULL.
408 * @param cptr Client to disconnect.
410 void close_connection(struct Client *cptr)
412 struct ConfItem* aconf;
414 if (IsServer(cptr)) {
415 ServerStats->is_sv++;
416 ServerStats->is_sbs += cli_sendB(cptr);
417 ServerStats->is_sbr += cli_receiveB(cptr);
418 ServerStats->is_sti += CurrentTime - cli_firsttime(cptr);
420 * If the connection has been up for a long amount of time, schedule
421 * a 'quick' reconnect, else reset the next-connect cycle.
423 if ((aconf = find_conf_exact(cli_name(cptr), cptr, CONF_SERVER))) {
425 * Reschedule a faster reconnect, if this was a automatically
426 * connected configuration entry. (Note that if we have had
427 * a rehash in between, the status has been changed to
428 * CONF_ILLEGAL). But only do this if it was a "good" link.
430 aconf->hold = CurrentTime;
431 aconf->hold += ((aconf->hold - cli_since(cptr) >
432 feature_int(FEAT_HANGONGOODLINK)) ?
433 feature_int(FEAT_HANGONRETRYDELAY) : ConfConFreq(aconf));
434 /* if (nextconnect > aconf->hold) */
435 /* nextconnect = aconf->hold; */
438 else if (IsUser(cptr)) {
439 ServerStats->is_cl++;
440 ServerStats->is_cbs += cli_sendB(cptr);
441 ServerStats->is_cbr += cli_receiveB(cptr);
442 ServerStats->is_cti += CurrentTime - cli_firsttime(cptr);
445 ServerStats->is_ni++;
447 if (-1 < cli_fd(cptr)) {
448 flush_connections(cptr);
449 LocalClientArray[cli_fd(cptr)] = 0;
451 socket_del(&(cli_socket(cptr))); /* queue a socket delete */
454 SetFlag(cptr, FLAG_DEADSOCKET);
456 MsgQClear(&(cli_sendQ(cptr)));
457 client_drop_sendq(cli_connect(cptr));
458 DBufClear(&(cli_recvQ(cptr)));
459 memset(cli_passwd(cptr), 0, sizeof(cli_passwd(cptr)));
460 set_snomask(cptr, 0, SNO_SET);
462 det_confs_butmask(cptr, 0);
464 if (cli_listener(cptr)) {
465 release_listener(cli_listener(cptr));
466 cli_listener(cptr) = 0;
469 for ( ; HighestFd > 0; --HighestFd) {
470 if (LocalClientArray[HighestFd])
475 /** Close all unregistered connections.
476 * @param source Oper who requested the close.
477 * @return Number of closed connections.
479 int net_close_unregistered_connections(struct Client* source)
486 for (i = HighestFd; i > 0; --i) {
487 if ((cptr = LocalClientArray[i]) && !IsRegistered(cptr)) {
488 send_reply(source, RPL_CLOSING, get_client_name(source, HIDE_IP));
489 exit_client(source, cptr, &me, "Oper Closing");
496 /** Creates a client which has just connected to us on the given fd.
497 * The sockhost field is initialized with the ip# of the host.
498 * The client is not added to the linked list of clients, it is
499 * passed off to the auth handler for dns and ident queries.
500 * @param listener Listening socket that received the connection.
501 * @param fd File descriptor of new connection.
503 void add_connection(struct Listener* listener, int fd) {
504 struct irc_sockaddr addr;
505 struct Client *new_client;
506 time_t next_target = 0;
508 const char* const throttle_message =
509 "ERROR :Your host is trying to (re)connect too fast -- throttled\r\n";
510 /* 12345678901234567890123456789012345679012345678901234567890123456 */
511 const char* const register_message =
512 "ERROR :Unable to complete your registration\r\n";
514 assert(0 != listener);
517 * Removed preliminary access check. Full check is performed in m_server and
518 * m_user instead. Also connection time out help to get rid of unwanted
521 if (!os_get_peername(fd, &addr) || !os_set_nonblocking(fd)) {
522 ++ServerStats->is_ref;
527 * Disable IP (*not* TCP) options. In particular, this makes it impossible
528 * to use source routing to connect to the server. If we didn't do this
529 * (and if intermediate networks didn't drop source-routed packets), an
530 * attacker could successfully IP spoof us...and even return the anti-spoof
531 * ping, because the options would cause the packet to be routed back to
532 * the spoofer's machine. When we disable the IP options, we delete the
533 * source route, and the normal routing takes over.
535 os_disable_options(fd);
538 * Add this local client to the IPcheck registry.
540 * If they're throttled, murder them, but tell them why first.
542 if (!IPcheck_local_connect(&addr.addr, &next_target) && !listener->server)
544 ++ServerStats->is_ref;
545 write(fd, throttle_message, strlen(throttle_message));
550 new_client = make_client(0, ((listener->server) ?
551 STAT_UNKNOWN_SERVER : STAT_UNKNOWN_USER));
554 * Copy ascii address to 'sockhost' just in case. Then we have something
555 * valid to put into error messages...
557 SetIPChecked(new_client);
558 ircd_ntoa_r(cli_sock_ip(new_client), &addr.addr);
559 strcpy(cli_sockhost(new_client), cli_sock_ip(new_client));
560 memcpy(&cli_ip(new_client), &addr.addr, sizeof(cli_ip(new_client)));
563 cli_nexttarget(new_client) = next_target;
565 cli_fd(new_client) = fd;
566 if (!socket_add(&(cli_socket(new_client)), client_sock_callback,
567 (void*) cli_connect(new_client), SS_CONNECTED, 0, fd)) {
568 ++ServerStats->is_ref;
569 write(fd, register_message, strlen(register_message));
571 cli_fd(new_client) = -1;
574 cli_freeflag(new_client) |= FREEFLAG_SOCKET;
575 cli_listener(new_client) = listener;
576 ++listener->ref_count;
578 Count_newunknown(UserStats);
579 /* if we've made it this far we can put the client on the auth query pile */
580 start_auth(new_client);
583 /** Determines whether to tell the events engine we're interested in
585 * @param cptr Client for which to decide this.
587 void update_write(struct Client* cptr)
589 /* If there are messages that need to be sent along, or if the client
590 * is in the middle of a /list, then we need to tell the engine that
591 * we're interested in writable events--otherwise, we need to drop
594 socket_events(&(cli_socket(cptr)),
595 ((MsgQLength(&cli_sendQ(cptr)) || cli_listing(cptr)) ?
596 SOCK_ACTION_ADD : SOCK_ACTION_DEL) | SOCK_EVENT_WRITABLE);
599 /** Read a 'packet' of data from a connection and process it. Read in
600 * 8k chunks to give a better performance rating (for server
601 * connections). Do some tricky stuff for client connections to make
602 * sure they don't do any flooding >:-) -avalon
603 * @param cptr Client from which to read data.
604 * @param socket_ready If non-zero, more data can be read from the client's socket.
605 * @return Positive number on success, zero on connection-fatal failure, negative
608 static int read_packet(struct Client *cptr, int socket_ready)
610 unsigned int dolen = 0;
611 unsigned int length = 0;
615 DBufLength(&(cli_recvQ(cptr))) > feature_int(FEAT_CLIENT_FLOOD))) {
616 switch (os_recv_nonb(cli_fd(cptr), readbuf, sizeof(readbuf), &length)) {
621 cli_lasttime(cptr) = CurrentTime;
622 if (cli_lasttime(cptr) > cli_since(cptr))
623 cli_since(cptr) = cli_lasttime(cptr);
624 ClrFlag(cptr, FLAG_PINGSENT);
625 ClrFlag(cptr, FLAG_NONL);
631 cli_error(cptr) = errno;
632 /* SetFlag(cptr, FLAG_DEADSOCKET); */
638 * For server connections, we process as many as we can without
639 * worrying about the time of day or anything :)
641 if (length > 0 && IsServer(cptr))
642 return server_dopacket(cptr, readbuf, length);
643 else if (length > 0 && (IsHandshake(cptr) || IsConnecting(cptr)))
644 return connect_dopacket(cptr, readbuf, length);
648 * Before we even think of parsing what we just read, stick
649 * it on the end of the receive queue and do it when its
652 if (length > 0 && dbuf_put(&(cli_recvQ(cptr)), readbuf, length) == 0)
653 return exit_client(cptr, cptr, &me, "dbuf_put fail");
655 if (DBufLength(&(cli_recvQ(cptr))) > feature_int(FEAT_CLIENT_FLOOD))
656 return exit_client(cptr, cptr, &me, "Excess Flood");
658 while (DBufLength(&(cli_recvQ(cptr))) && !NoNewLine(cptr) &&
659 (IsTrusted(cptr) || cli_since(cptr) - CurrentTime < 10))
661 dolen = dbuf_getmsg(&(cli_recvQ(cptr)), cli_buffer(cptr), BUFSIZE);
663 * Devious looking...whats it do ? well..if a client
664 * sends a *long* message without any CR or LF, then
665 * dbuf_getmsg fails and we pull it out using this
666 * loop which just gets the next 512 bytes and then
667 * deletes the rest of the buffer contents.
672 if (DBufLength(&(cli_recvQ(cptr))) < 510)
673 SetFlag(cptr, FLAG_NONL);
675 DBufClear(&(cli_recvQ(cptr)));
677 else if (client_dopacket(cptr, dolen) == CPTR_KILLED)
680 * If it has become registered as a Server
681 * then skip the per-message parsing below.
683 if (IsHandshake(cptr) || IsServer(cptr))
687 dolen = dbuf_get(&(cli_recvQ(cptr)), readbuf, sizeof(readbuf));
692 if (DBufLength(&(cli_recvQ(cptr))) < 510)
693 SetFlag(cptr, FLAG_NONL);
695 DBufClear(&(cli_recvQ(cptr)));
697 else if ((IsServer(cptr) &&
698 server_dopacket(cptr, readbuf, dolen) == CPTR_KILLED) ||
700 connect_dopacket(cptr, readbuf, dolen) == CPTR_KILLED))
706 /* If there's still data to process, wait 2 seconds first */
707 if (DBufLength(&(cli_recvQ(cptr))) && !NoNewLine(cptr) &&
708 !t_onqueue(&(cli_proc(cptr))))
710 Debug((DEBUG_LIST, "Adding client process timer for %C", cptr));
711 cli_freeflag(cptr) |= FREEFLAG_TIMER;
712 timer_add(&(cli_proc(cptr)), client_timer_callback, cli_connect(cptr),
719 /** Start a connection to another server.
720 * @param aconf Connect block data for target server.
721 * @param by Client who requested the connection (if any).
722 * @return Non-zero on success; zero on failure.
724 int connect_server(struct ConfItem* aconf, struct Client* by)
726 struct Client* cptr = 0;
729 if (aconf->dns_pending) {
730 sendto_opmask_butone(0, SNO_OLDSNO, "Server %s connect DNS pending",
734 Debug((DEBUG_NOTICE, "Connect to %s[@%s]", aconf->name,
735 ircd_ntoa(&aconf->address.addr)));
737 if ((cptr = FindClient(aconf->name))) {
738 if (IsServer(cptr) || IsMe(cptr)) {
739 sendto_opmask_butone(0, SNO_OLDSNO, "Server %s already present from %s",
740 aconf->name, cli_name(cli_from(cptr)));
741 if (by && IsUser(by) && !MyUser(by)) {
742 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Server %s already present "
743 "from %s", by, aconf->name, cli_name(cli_from(cptr)));
747 else if (IsHandshake(cptr) || IsConnecting(cptr)) {
748 if (by && IsUser(by)) {
749 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Connection to %s already in "
750 "progress", by, cli_name(cptr));
756 * If we don't know the IP# for this host and it is a hostname and
757 * not a ip# string, then try and find the appropriate host record.
759 if (!irc_in_addr_valid(&aconf->address.addr)
760 && !ircd_aton(&aconf->address.addr, aconf->host)) {
761 char buf[HOSTLEN + 1];
762 struct DNSQuery query;
765 query.callback = connect_dns_callback;
766 host_from_uh(buf, aconf->host, HOSTLEN);
769 gethost_byname(buf, &query);
770 aconf->dns_pending = 1;
773 cptr = make_client(NULL, STAT_UNKNOWN_SERVER);
776 * Copy these in so we have something for error detection.
778 ircd_strncpy(cli_name(cptr), aconf->name, HOSTLEN);
779 ircd_strncpy(cli_sockhost(cptr), aconf->host, HOSTLEN);
782 * Attach config entries to client here rather than in
783 * completed_connection. This to avoid null pointer references
785 attach_confs_byhost(cptr, aconf->host, CONF_SERVER);
787 if (!find_conf_byhost(cli_confs(cptr), aconf->host, CONF_SERVER)) {
788 sendto_opmask_butone(0, SNO_OLDSNO, "Host %s is not enabled for "
789 "connecting: no C-line", aconf->name);
790 if (by && IsUser(by) && !MyUser(by)) {
791 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Connect to host %s failed: no "
792 "C-line", by, aconf->name);
794 det_confs_butmask(cptr, 0);
799 * attempt to connect to the server in the conf line
801 if (!connect_inet(aconf, cptr)) {
802 if (by && IsUser(by) && !MyUser(by)) {
803 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Couldn't connect to %s", by,
806 det_confs_butmask(cptr, 0);
811 * NOTE: if we're here we have a valid C:Line and the client should
812 * have started the connection and stored the remote address/port and
813 * ip address name in itself
815 * The socket has been connected or connect is in progress.
818 if (by && IsUser(by)) {
819 ircd_snprintf(0, cli_serv(cptr)->by, sizeof(cli_serv(cptr)->by), "%s%s",
821 assert(0 == cli_serv(cptr)->user);
822 cli_serv(cptr)->user = cli_user(by);
823 cli_user(by)->refcnt++;
826 *(cli_serv(cptr))->by = '\0';
827 /* strcpy(cptr->serv->by, "Auto"); */
829 cli_serv(cptr)->up = &me;
832 if (cli_fd(cptr) > HighestFd)
833 HighestFd = cli_fd(cptr);
835 LocalClientArray[cli_fd(cptr)] = cptr;
837 Count_newunknown(UserStats);
838 /* Actually we lie, the connect hasn't succeeded yet, but we have a valid
839 * cptr, so we register it now.
840 * Maybe these two calls should be merged.
842 add_client_to_list(cptr);
844 /* nextping = CurrentTime; */
846 return (s_state(&cli_socket(cptr)) == SS_CONNECTED) ?
847 completed_connection(cptr) : 1;
850 /** Find the real hostname for the host running the server (or one which
851 * matches the server's name) and its primary IP#. Hostname is stored
852 * in the client structure passed as a pointer.
854 void init_server_identity(void)
856 const struct LocalConf* conf = conf_get_local();
859 ircd_strncpy(cli_name(&me), conf->name, HOSTLEN);
860 SetYXXServerName(&me, conf->numeric);
863 /** Process events on a client socket.
864 * @param ev Socket event structure that has a struct Connection as
865 * its associated data.
867 static void client_sock_callback(struct Event* ev)
870 struct Connection* con;
874 assert(0 != ev_socket(ev));
875 assert(0 != s_data(ev_socket(ev)));
877 con = (struct Connection*) s_data(ev_socket(ev));
879 assert(0 != con_client(con) || ev_type(ev) == ET_DESTROY);
881 cptr = con_client(con);
883 assert(0 == cptr || con == cli_connect(cptr));
885 switch (ev_type(ev)) {
887 con_freeflag(con) &= ~FREEFLAG_SOCKET;
889 if (!con_freeflag(con) && !cptr)
890 free_connection(con);
893 case ET_CONNECT: /* socket connection completed */
894 if (!completed_connection(cptr) || IsDead(cptr))
895 fallback = cli_info(cptr);
898 case ET_ERROR: /* an error occurred */
899 fallback = cli_info(cptr);
900 cli_error(cptr) = ev_data(ev);
901 if (s_state(&(con_socket(con))) == SS_CONNECTING) {
902 completed_connection(cptr);
906 case ET_EOF: /* end of file on socket */
907 Debug((DEBUG_ERROR, "READ ERROR: fd = %d %d", cli_fd(cptr),
909 SetFlag(cptr, FLAG_DEADSOCKET);
910 if ((IsServer(cptr) || IsHandshake(cptr)) && cli_error(cptr) == 0) {
911 exit_client_msg(cptr, cptr, &me, "Server %s closed the connection (%s)",
912 cli_name(cptr), cli_serv(cptr)->last_error_msg);
915 fmt = "Read error: %s";
916 fallback = "EOF from client";
920 case ET_WRITE: /* socket is writable */
921 ClrFlag(cptr, FLAG_BLOCKED);
922 if (cli_listing(cptr) && MsgQLength(&(cli_sendQ(cptr))) < 2048)
923 list_next_channels(cptr);
924 Debug((DEBUG_SEND, "Sending queued data to %C", cptr));
928 case ET_READ: /* socket is readable */
930 Debug((DEBUG_DEBUG, "Reading data from %C", cptr));
931 if (read_packet(cptr, 1) == 0) /* error while reading packet */
932 fallback = "EOF from client";
937 assert(0 && "Unrecognized socket event in client_sock_callback()");
941 assert(0 == cptr || 0 == cli_connect(cptr) || con == cli_connect(cptr));
944 const char* msg = (cli_error(cptr)) ? strerror(cli_error(cptr)) : fallback;
946 msg = "Unknown error";
947 exit_client_msg(cptr, cptr, &me, fmt, msg);
951 /** Process a timer on client socket.
952 * @param ev Timer event that has a struct Connection as its
955 static void client_timer_callback(struct Event* ev)
958 struct Connection* con;
960 assert(0 != ev_timer(ev));
961 assert(0 != t_data(ev_timer(ev)));
962 assert(ET_DESTROY == ev_type(ev) || ET_EXPIRE == ev_type(ev));
964 con = (struct Connection*) t_data(ev_timer(ev));
966 assert(0 != con_client(con) || ev_type(ev) == ET_DESTROY);
968 cptr = con_client(con);
970 assert(0 == cptr || con == cli_connect(cptr));
972 if (ev_type(ev)== ET_DESTROY) {
973 con_freeflag(con) &= ~FREEFLAG_TIMER; /* timer has expired... */
975 if (!con_freeflag(con) && !cptr)
976 free_connection(con); /* client is being destroyed */
978 Debug((DEBUG_LIST, "Client process timer for %C expired; processing",
980 read_packet(cptr, 0); /* read_packet will re-add timer if needed */
983 assert(0 == cptr || 0 == cli_connect(cptr) || con == cli_connect(cptr));