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>
74 /** Array of my own clients, indexed by file descriptor. */
75 struct Client* LocalClientArray[MAXCONNECTIONS];
76 /** Maximum file descriptor in current use. */
78 /** Default local address for outbound IPv4 connections. */
79 struct irc_sockaddr VirtualHost_v4;
80 /** Default local address for outbound IPv6 connections. */
81 struct irc_sockaddr VirtualHost_v6;
82 /** Temporary buffer for reading data from a peer. */
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 REGISTER_ERROR_MSG = "registering %s: %s";
97 const char* const REUSEADDR_ERROR_MSG = "error setting SO_REUSEADDR for %s: %s";
98 const char* const SELECT_ERROR_MSG = "select error for %s: %s";
99 const char* const SETBUFS_ERROR_MSG = "error setting buffer size for %s: %s";
100 const char* const SOCKET_ERROR_MSG = "error creating socket for %s: %s";
101 const char* const TOS_ERROR_MSG = "error setting TOS for %s: %s";
104 static void client_sock_callback(struct Event* ev);
105 static void client_timer_callback(struct Event* ev);
109 * Cannot use perror() within daemon. stderr is closed in
110 * ircd and cannot be used. And, worse yet, it might have
111 * been reassigned to a normal connection...
114 /** Replacement for perror(). Record error to log. Send a copy to all
115 * *LOCAL* opers, but only if no errors were sent to them in the last
117 * @param text A *format* string for outputting error. It must contain
118 * only two '%s', the first will be replaced by the sockhost from the
119 * cptr, and the latter will be taken from sys_errlist[errno].
120 * @param who The client associated with the error.
121 * @param err The errno value to display.
123 void report_error(const char* text, const char* who, int err)
125 static time_t last_notice = 0;
126 int errtmp = errno; /* debug may change 'errno' */
127 const char* errmsg = (err) ? strerror(err) : "";
130 errmsg = "Unknown error";
132 if (EmptyString(who))
135 if (last_notice + 20 < CurrentTime) {
137 * pace error messages so opers don't get flooded by transients
139 sendto_opmask_butone(0, SNO_OLDSNO, text, who, errmsg);
140 last_notice = CurrentTime;
142 log_write(LS_SOCKET, L_ERROR, 0, text, who, errmsg);
147 /** Called when resolver query finishes. If the DNS lookup was
148 * successful, start the connection; otherwise notify opers of the
150 * @param vptr The struct ConfItem representing the Connect block.
151 * @param hp A pointer to the DNS lookup results (NULL on failure).
153 static void connect_dns_callback(void* vptr, const struct irc_in_addr *addr, const char *h_name)
155 struct ConfItem* aconf = (struct ConfItem*) vptr;
157 aconf->dns_pending = 0;
159 memcpy(&aconf->address, addr, sizeof(aconf->address));
160 connect_server(aconf, 0);
163 sendto_opmask_butone(0, SNO_OLDSNO, "Connect to %s failed: host lookup",
167 /** Closes all file descriptors.
168 * @param close_stderr If non-zero, also close stderr.
170 void close_connections(int close_stderr)
179 for (i = 3; i < MAXCONNECTIONS; ++i)
183 /** Initialize process fd limit to MAXCONNECTIONS.
185 int init_connection_limits(void)
187 int limit = os_set_fdlimit(MAXCONNECTIONS);
191 fprintf(stderr, "error setting max fd's to %d\n", limit);
193 else if (limit > 0) {
194 fprintf(stderr, "ircd fd table too big\nHard Limit: %d IRC max: %d\n",
195 limit, MAXCONNECTIONS);
196 fprintf(stderr, "set MAXCONNECTIONS to a smaller value");
201 /** Set up address and port and make a connection.
202 * @param aconf Provides the connection information.
203 * @param cptr Client structure for the peer.
204 * @return Non-zero on success; zero on failure.
206 static int connect_inet(struct ConfItem* aconf, struct Client* cptr)
208 const struct irc_sockaddr *local;
215 * Might as well get sockhost from here, the connection is attempted
216 * with it so if it fails its useless.
218 if (irc_in_addr_valid(&aconf->origin.addr))
219 local = &aconf->origin;
220 else if (irc_in_addr_is_ipv4(&aconf->address.addr)) {
221 local = &VirtualHost_v4;
224 local = &VirtualHost_v6;
225 cli_fd(cptr) = os_socket(local, SOCK_STREAM, cli_name(cptr), family);
226 if (cli_fd(cptr) < 0)
230 * save connection info in client
232 memcpy(&cli_ip(cptr), &aconf->address.addr, sizeof(cli_ip(cptr)));
233 ircd_ntoa_r(cli_sock_ip(cptr), &cli_ip(cptr));
235 * we want a big buffer for server connections
237 if (!os_set_sockbufs(cli_fd(cptr), feature_int(FEAT_SOCKSENDBUF), feature_int(FEAT_SOCKRECVBUF))) {
238 cli_error(cptr) = errno;
239 report_error(SETBUFS_ERROR_MSG, cli_name(cptr), errno);
245 * Set the TOS bits - this is nonfatal if it doesn't stick.
247 if (!os_set_tos(cli_fd(cptr), FEAT_TOS_SERVER)) {
248 report_error(TOS_ERROR_MSG, cli_name(cptr), errno);
250 if ((result = os_connect_nonb(cli_fd(cptr), &aconf->address)) == IO_FAILURE) {
251 cli_error(cptr) = errno;
252 report_error(CONNECT_ERROR_MSG, cli_name(cptr), errno);
257 if (!socket_add(&(cli_socket(cptr)), client_sock_callback,
258 (void*) cli_connect(cptr),
259 (result == IO_SUCCESS) ? SS_CONNECTED : SS_CONNECTING,
260 SOCK_EVENT_READABLE, cli_fd(cptr))) {
261 cli_error(cptr) = ENFILE;
262 report_error(REGISTER_ERROR_MSG, cli_name(cptr), ENFILE);
267 cli_freeflag(cptr) |= FREEFLAG_SOCKET;
271 /** Attempt to send a sequence of bytes to the connection.
272 * As a side effect, updates \a cptr's FLAG_BLOCKED setting
273 * and sendB/sendK fields.
274 * @param cptr Client that should receive data.
275 * @param buf Message buffer to send to client.
276 * @return Negative on connection-fatal error; otherwise
277 * number of bytes sent.
279 unsigned int deliver_it(struct Client *cptr, struct MsgQ *buf)
281 unsigned int bytes_written = 0;
282 unsigned int bytes_count = 0;
285 switch (os_sendv_nonb(cli_fd(cptr), buf, &bytes_count, &bytes_written)) {
287 ClrFlag(cptr, FLAG_BLOCKED);
289 cli_sendB(cptr) += bytes_written;
290 cli_sendB(&me) += bytes_written;
291 /* A partial write implies that future writes will block. */
292 if (bytes_written < bytes_count)
293 SetFlag(cptr, FLAG_BLOCKED);
296 SetFlag(cptr, FLAG_BLOCKED);
299 cli_error(cptr) = errno;
300 SetFlag(cptr, FLAG_DEADSOCKET);
303 return bytes_written;
306 /** Complete non-blocking connect()-sequence. Check access and
307 * terminate connection, if trouble detected.
308 * @param cptr Client to which we have connected, with all ConfItem structs attached.
309 * @return Zero on failure (caller should exit_client()), non-zero on success.
311 static int completed_connection(struct Client* cptr)
313 struct ConfItem *aconf;
315 struct Client *acptr;
321 * get the socket status from the fd first to check if
322 * connection actually succeeded
324 if ((cli_error(cptr) = os_get_sockerr(cli_fd(cptr)))) {
325 const char* msg = strerror(cli_error(cptr));
327 msg = "Unknown error";
328 sendto_opmask_butone(0, SNO_OLDSNO, "Connection failed to %s: %s",
329 cli_name(cptr), msg);
332 if (!(aconf = find_conf_byname(cli_confs(cptr), cli_name(cptr), CONF_SERVER))) {
333 sendto_opmask_butone(0, SNO_OLDSNO, "Lost Server Line for %s", cli_name(cptr));
336 if (s_state(&(cli_socket(cptr))) == SS_CONNECTING)
337 socket_state(&(cli_socket(cptr)), SS_CONNECTED);
339 if (!EmptyString(aconf->passwd))
340 sendrawto_one(cptr, MSG_PASS " :%s", aconf->passwd);
343 * Create a unique timestamp
346 for (i = HighestFd; i > -1; --i) {
347 if ((acptr = LocalClientArray[i]) &&
348 (IsServer(acptr) || IsHandshake(acptr))) {
349 if (cli_serv(acptr)->timestamp >= newts)
350 newts = cli_serv(acptr)->timestamp + 1;
353 assert(0 != cli_serv(cptr));
355 cli_serv(cptr)->timestamp = newts;
358 * Make us timeout after twice the timeout for DNS look ups
360 cli_lasttime(cptr) = CurrentTime;
361 SetFlag(cptr, FLAG_PINGSENT);
363 sendrawto_one(cptr, MSG_SERVER " %s 1 %Tu %Tu J%s %s%s +%s6 :%s",
364 cli_name(&me), cli_serv(&me)->timestamp, newts,
365 MAJOR_PROTOCOL, NumServCap(&me),
366 feature_bool(FEAT_HUB) ? "h" : "", cli_info(&me));
368 return (IsDead(cptr)) ? 0 : 1;
371 /** Close the physical connection. Side effects: MyConnect(cptr)
372 * becomes false and cptr->from becomes NULL.
373 * @param cptr Client to disconnect.
375 void close_connection(struct Client *cptr)
377 struct ConfItem* aconf;
379 if (IsServer(cptr)) {
380 ServerStats->is_sv++;
381 ServerStats->is_sbs += cli_sendB(cptr);
382 ServerStats->is_sbr += cli_receiveB(cptr);
383 ServerStats->is_sti += CurrentTime - cli_firsttime(cptr);
385 * If the connection has been up for a long amount of time, schedule
386 * a 'quick' reconnect, else reset the next-connect cycle.
388 if ((aconf = find_conf_exact(cli_name(cptr), cptr, CONF_SERVER))) {
390 * Reschedule a faster reconnect, if this was a automatically
391 * connected configuration entry. (Note that if we have had
392 * a rehash in between, the status has been changed to
393 * CONF_ILLEGAL). But only do this if it was a "good" link.
395 aconf->hold = CurrentTime;
396 aconf->hold += ((aconf->hold - cli_since(cptr) >
397 feature_int(FEAT_HANGONGOODLINK)) ?
398 feature_int(FEAT_HANGONRETRYDELAY) : ConfConFreq(aconf));
399 /* if (nextconnect > aconf->hold) */
400 /* nextconnect = aconf->hold; */
403 else if (IsUser(cptr)) {
404 ServerStats->is_cl++;
405 ServerStats->is_cbs += cli_sendB(cptr);
406 ServerStats->is_cbr += cli_receiveB(cptr);
407 ServerStats->is_cti += CurrentTime - cli_firsttime(cptr);
410 ServerStats->is_ni++;
412 if (-1 < cli_fd(cptr)) {
413 flush_connections(cptr);
414 LocalClientArray[cli_fd(cptr)] = 0;
416 socket_del(&(cli_socket(cptr))); /* queue a socket delete */
419 SetFlag(cptr, FLAG_DEADSOCKET);
421 MsgQClear(&(cli_sendQ(cptr)));
422 client_drop_sendq(cli_connect(cptr));
423 DBufClear(&(cli_recvQ(cptr)));
424 memset(cli_passwd(cptr), 0, sizeof(cli_passwd(cptr)));
425 set_snomask(cptr, 0, SNO_SET);
427 det_confs_butmask(cptr, 0);
429 if (cli_listener(cptr)) {
430 release_listener(cli_listener(cptr));
431 cli_listener(cptr) = 0;
434 for ( ; HighestFd > 0; --HighestFd) {
435 if (LocalClientArray[HighestFd])
440 /** Close all unregistered connections.
441 * @param source Oper who requested the close.
442 * @return Number of closed connections.
444 int net_close_unregistered_connections(struct Client* source)
451 for (i = HighestFd; i > 0; --i) {
452 if ((cptr = LocalClientArray[i]) && !IsRegistered(cptr)) {
453 send_reply(source, RPL_CLOSING, get_client_name(source, HIDE_IP));
454 exit_client(source, cptr, &me, "Oper Closing");
461 /** Creates a client which has just connected to us on the given fd.
462 * The sockhost field is initialized with the ip# of the host.
463 * The client is not added to the linked list of clients, it is
464 * passed off to the auth handler for dns and ident queries.
465 * @param listener Listening socket that received the connection.
466 * @param fd File descriptor of new connection.
468 void add_connection(struct Listener* listener, int fd) {
469 struct irc_sockaddr addr;
470 struct Client *new_client;
471 time_t next_target = 0;
473 const char* const throttle_message =
474 "ERROR :Your host is trying to (re)connect too fast -- throttled\r\n";
475 /* 12345678901234567890123456789012345679012345678901234567890123456 */
476 const char* const register_message =
477 "ERROR :Unable to complete your registration\r\n";
479 assert(0 != listener);
482 * Removed preliminary access check. Full check is performed in m_server and
483 * m_user instead. Also connection time out help to get rid of unwanted
486 if (!os_get_peername(fd, &addr) || !os_set_nonblocking(fd)) {
487 ++ServerStats->is_ref;
492 * Disable IP (*not* TCP) options. In particular, this makes it impossible
493 * to use source routing to connect to the server. If we didn't do this
494 * (and if intermediate networks didn't drop source-routed packets), an
495 * attacker could successfully IP spoof us...and even return the anti-spoof
496 * ping, because the options would cause the packet to be routed back to
497 * the spoofer's machine. When we disable the IP options, we delete the
498 * source route, and the normal routing takes over.
500 os_disable_options(fd);
502 if (listener->server)
504 new_client = make_client(0, STAT_UNKNOWN_SERVER);
509 * Add this local client to the IPcheck registry.
511 * If they're throttled, murder them, but tell them why first.
513 if (!IPcheck_local_connect(&addr.addr, &next_target))
515 ++ServerStats->is_ref;
516 write(fd, throttle_message, strlen(throttle_message));
520 new_client = make_client(0, STAT_UNKNOWN_USER);
521 SetIPChecked(new_client);
525 * Copy ascii address to 'sockhost' just in case. Then we have something
526 * valid to put into error messages...
528 ircd_ntoa_r(cli_sock_ip(new_client), &addr.addr);
529 strcpy(cli_sockhost(new_client), cli_sock_ip(new_client));
530 memcpy(&cli_ip(new_client), &addr.addr, sizeof(cli_ip(new_client)));
533 cli_nexttarget(new_client) = next_target;
535 cli_fd(new_client) = fd;
536 if (!socket_add(&(cli_socket(new_client)), client_sock_callback,
537 (void*) cli_connect(new_client), SS_CONNECTED, 0, fd)) {
538 ++ServerStats->is_ref;
539 write(fd, register_message, strlen(register_message));
541 cli_fd(new_client) = -1;
544 cli_freeflag(new_client) |= FREEFLAG_SOCKET;
545 cli_listener(new_client) = listener;
546 ++listener->ref_count;
548 Count_newunknown(UserStats);
549 /* if we've made it this far we can put the client on the auth query pile */
550 start_auth(new_client);
553 /** Determines whether to tell the events engine we're interested in
555 * @param cptr Client for which to decide this.
557 void update_write(struct Client* cptr)
559 /* If there are messages that need to be sent along, or if the client
560 * is in the middle of a /list, then we need to tell the engine that
561 * we're interested in writable events--otherwise, we need to drop
564 socket_events(&(cli_socket(cptr)),
565 ((MsgQLength(&cli_sendQ(cptr)) || cli_listing(cptr)) ?
566 SOCK_ACTION_ADD : SOCK_ACTION_DEL) | SOCK_EVENT_WRITABLE);
569 /** Read a 'packet' of data from a connection and process it. Read in
570 * 8k chunks to give a better performance rating (for server
571 * connections). Do some tricky stuff for client connections to make
572 * sure they don't do any flooding >:-) -avalon
573 * @param cptr Client from which to read data.
574 * @param socket_ready If non-zero, more data can be read from the client's socket.
575 * @return Positive number on success, zero on connection-fatal failure, negative
578 static int read_packet(struct Client *cptr, int socket_ready)
580 unsigned int dolen = 0;
581 unsigned int length = 0;
585 DBufLength(&(cli_recvQ(cptr))) > feature_int(FEAT_CLIENT_FLOOD))) {
586 switch (os_recv_nonb(cli_fd(cptr), readbuf, sizeof(readbuf), &length)) {
591 cli_lasttime(cptr) = CurrentTime;
592 if (cli_lasttime(cptr) > cli_since(cptr))
593 cli_since(cptr) = cli_lasttime(cptr);
594 ClrFlag(cptr, FLAG_PINGSENT);
595 ClrFlag(cptr, FLAG_NONL);
601 cli_error(cptr) = errno;
602 /* SetFlag(cptr, FLAG_DEADSOCKET); */
608 * For server connections, we process as many as we can without
609 * worrying about the time of day or anything :)
611 if (length > 0 && IsServer(cptr))
612 return server_dopacket(cptr, readbuf, length);
613 else if (length > 0 && (IsHandshake(cptr) || IsConnecting(cptr)))
614 return connect_dopacket(cptr, readbuf, length);
618 * Before we even think of parsing what we just read, stick
619 * it on the end of the receive queue and do it when its
622 if (length > 0 && dbuf_put(&(cli_recvQ(cptr)), readbuf, length) == 0)
623 return exit_client(cptr, cptr, &me, "dbuf_put fail");
625 if (DBufLength(&(cli_recvQ(cptr))) > feature_int(FEAT_CLIENT_FLOOD))
626 return exit_client(cptr, cptr, &me, "Excess Flood");
628 while (DBufLength(&(cli_recvQ(cptr))) && !NoNewLine(cptr) &&
629 (IsTrusted(cptr) || cli_since(cptr) - CurrentTime < 10))
631 dolen = dbuf_getmsg(&(cli_recvQ(cptr)), cli_buffer(cptr), BUFSIZE);
633 * Devious looking...whats it do ? well..if a client
634 * sends a *long* message without any CR or LF, then
635 * dbuf_getmsg fails and we pull it out using this
636 * loop which just gets the next 512 bytes and then
637 * deletes the rest of the buffer contents.
642 if (DBufLength(&(cli_recvQ(cptr))) < 510)
643 SetFlag(cptr, FLAG_NONL);
645 DBufClear(&(cli_recvQ(cptr)));
647 else if (client_dopacket(cptr, dolen) == CPTR_KILLED)
650 * If it has become registered as a Server
651 * then skip the per-message parsing below.
653 if (IsHandshake(cptr) || IsServer(cptr))
657 dolen = dbuf_get(&(cli_recvQ(cptr)), readbuf, sizeof(readbuf));
662 if (DBufLength(&(cli_recvQ(cptr))) < 510)
663 SetFlag(cptr, FLAG_NONL);
665 DBufClear(&(cli_recvQ(cptr)));
667 else if ((IsServer(cptr) &&
668 server_dopacket(cptr, readbuf, dolen) == CPTR_KILLED) ||
670 connect_dopacket(cptr, readbuf, dolen) == CPTR_KILLED))
676 /* If there's still data to process, wait 2 seconds first */
677 if (DBufLength(&(cli_recvQ(cptr))) && !NoNewLine(cptr) &&
678 !t_onqueue(&(cli_proc(cptr))))
680 Debug((DEBUG_LIST, "Adding client process timer for %C", cptr));
681 cli_freeflag(cptr) |= FREEFLAG_TIMER;
682 timer_add(&(cli_proc(cptr)), client_timer_callback, cli_connect(cptr),
689 /** Start a connection to another server.
690 * @param aconf Connect block data for target server.
691 * @param by Client who requested the connection (if any).
692 * @return Non-zero on success; zero on failure.
694 int connect_server(struct ConfItem* aconf, struct Client* by)
696 struct Client* cptr = 0;
699 if (aconf->dns_pending) {
700 sendto_opmask_butone(0, SNO_OLDSNO, "Server %s connect DNS pending",
704 Debug((DEBUG_NOTICE, "Connect to %s[@%s]", aconf->name,
705 ircd_ntoa(&aconf->address.addr)));
707 if ((cptr = FindClient(aconf->name))) {
708 if (IsServer(cptr) || IsMe(cptr)) {
709 sendto_opmask_butone(0, SNO_OLDSNO, "Server %s already present from %s",
710 aconf->name, cli_name(cli_from(cptr)));
711 if (by && IsUser(by) && !MyUser(by)) {
712 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Server %s already present "
713 "from %s", by, aconf->name, cli_name(cli_from(cptr)));
717 else if (IsHandshake(cptr) || IsConnecting(cptr)) {
718 if (by && IsUser(by)) {
719 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Connection to %s already in "
720 "progress", by, cli_name(cptr));
726 * If we don't know the IP# for this host and it is a hostname and
727 * not a ip# string, then try and find the appropriate host record.
729 if (!irc_in_addr_valid(&aconf->address.addr)
730 && !ircd_aton(&aconf->address.addr, aconf->host)) {
731 char buf[HOSTLEN + 1];
733 host_from_uh(buf, aconf->host, HOSTLEN);
734 gethost_byname(buf, connect_dns_callback, aconf);
735 aconf->dns_pending = 1;
738 cptr = make_client(NULL, STAT_UNKNOWN_SERVER);
741 * Copy these in so we have something for error detection.
743 ircd_strncpy(cli_name(cptr), aconf->name, HOSTLEN);
744 ircd_strncpy(cli_sockhost(cptr), aconf->host, HOSTLEN);
747 * Attach config entries to client here rather than in
748 * completed_connection. This to avoid null pointer references
750 attach_confs_byhost(cptr, aconf->host, CONF_SERVER);
752 if (!find_conf_byhost(cli_confs(cptr), aconf->host, CONF_SERVER)) {
753 sendto_opmask_butone(0, SNO_OLDSNO, "Host %s is not enabled for "
754 "connecting: no Connect block", aconf->name);
755 if (by && IsUser(by) && !MyUser(by)) {
756 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Connect to host %s failed: no "
757 "Connect block", by, aconf->name);
759 det_confs_butmask(cptr, 0);
764 * attempt to connect to the server in the conf line
766 if (!connect_inet(aconf, cptr)) {
767 if (by && IsUser(by) && !MyUser(by)) {
768 sendcmdto_one(&me, CMD_NOTICE, by, "%C :Couldn't connect to %s", by,
771 det_confs_butmask(cptr, 0);
776 * NOTE: if we're here we have a valid C:Line and the client should
777 * have started the connection and stored the remote address/port and
778 * ip address name in itself
780 * The socket has been connected or connect is in progress.
783 if (by && IsUser(by)) {
784 ircd_snprintf(0, cli_serv(cptr)->by, sizeof(cli_serv(cptr)->by), "%s%s",
786 assert(0 == cli_serv(cptr)->user);
787 cli_serv(cptr)->user = cli_user(by);
788 cli_user(by)->refcnt++;
791 *(cli_serv(cptr))->by = '\0';
792 /* strcpy(cptr->serv->by, "Auto"); */
794 cli_serv(cptr)->up = &me;
797 if (cli_fd(cptr) > HighestFd)
798 HighestFd = cli_fd(cptr);
800 LocalClientArray[cli_fd(cptr)] = cptr;
802 Count_newunknown(UserStats);
803 /* Actually we lie, the connect hasn't succeeded yet, but we have a valid
804 * cptr, so we register it now.
805 * Maybe these two calls should be merged.
807 add_client_to_list(cptr);
809 /* nextping = CurrentTime; */
811 return (s_state(&cli_socket(cptr)) == SS_CONNECTED) ?
812 completed_connection(cptr) : 1;
815 /** Find the real hostname for the host running the server (or one which
816 * matches the server's name) and its primary IP#. Hostname is stored
817 * in the client structure passed as a pointer.
819 void init_server_identity(void)
821 const struct LocalConf* conf = conf_get_local();
824 ircd_strncpy(cli_name(&me), conf->name, HOSTLEN);
825 SetYXXServerName(&me, conf->numeric);
828 /** Process events on a client socket.
829 * @param ev Socket event structure that has a struct Connection as
830 * its associated data.
832 static void client_sock_callback(struct Event* ev)
835 struct Connection* con;
839 assert(0 != ev_socket(ev));
840 assert(0 != s_data(ev_socket(ev)));
842 con = (struct Connection*) s_data(ev_socket(ev));
844 assert(0 != con_client(con) || ev_type(ev) == ET_DESTROY);
846 cptr = con_client(con);
848 assert(0 == cptr || con == cli_connect(cptr));
850 switch (ev_type(ev)) {
852 con_freeflag(con) &= ~FREEFLAG_SOCKET;
854 if (!con_freeflag(con) && !cptr)
855 free_connection(con);
858 case ET_CONNECT: /* socket connection completed */
859 if (!completed_connection(cptr) || IsDead(cptr))
860 fallback = cli_info(cptr);
863 case ET_ERROR: /* an error occurred */
864 fallback = cli_info(cptr);
865 cli_error(cptr) = ev_data(ev);
866 if (s_state(&(con_socket(con))) == SS_CONNECTING) {
867 completed_connection(cptr);
868 /* for some reason, the os_get_sockerr() in completed_connect()
869 * can return 0 even when ev_data(ev) indicates a real error, so
870 * re-assign the client error here.
872 cli_error(cptr) = ev_data(ev);
876 case ET_EOF: /* end of file on socket */
877 Debug((DEBUG_ERROR, "READ ERROR: fd = %d %d", cli_fd(cptr),
879 SetFlag(cptr, FLAG_DEADSOCKET);
880 if ((IsServer(cptr) || IsHandshake(cptr)) && cli_error(cptr) == 0) {
881 exit_client_msg(cptr, cptr, &me, "Server %s closed the connection (%s)",
882 cli_name(cptr), cli_serv(cptr)->last_error_msg);
885 fmt = "Read error: %s";
886 fallback = "EOF from client";
890 case ET_WRITE: /* socket is writable */
891 ClrFlag(cptr, FLAG_BLOCKED);
892 if (cli_listing(cptr) && MsgQLength(&(cli_sendQ(cptr))) < 2048)
893 list_next_channels(cptr);
894 Debug((DEBUG_SEND, "Sending queued data to %C", cptr));
898 case ET_READ: /* socket is readable */
900 Debug((DEBUG_DEBUG, "Reading data from %C", cptr));
901 if (read_packet(cptr, 1) == 0) /* error while reading packet */
902 fallback = "EOF from client";
907 assert(0 && "Unrecognized socket event in client_sock_callback()");
911 assert(0 == cptr || 0 == cli_connect(cptr) || con == cli_connect(cptr));
914 const char* msg = (cli_error(cptr)) ? strerror(cli_error(cptr)) : fallback;
916 msg = "Unknown error";
917 exit_client_msg(cptr, cptr, &me, fmt, msg);
921 /** Process a timer on client socket.
922 * @param ev Timer event that has a struct Connection as its
925 static void client_timer_callback(struct Event* ev)
928 struct Connection* con;
930 assert(0 != ev_timer(ev));
931 assert(0 != t_data(ev_timer(ev)));
932 assert(ET_DESTROY == ev_type(ev) || ET_EXPIRE == ev_type(ev));
934 con = (struct Connection*) t_data(ev_timer(ev));
936 assert(0 != con_client(con) || ev_type(ev) == ET_DESTROY);
938 cptr = con_client(con);
940 assert(0 == cptr || con == cli_connect(cptr));
942 if (ev_type(ev)== ET_DESTROY) {
943 con_freeflag(con) &= ~FREEFLAG_TIMER; /* timer has expired... */
945 if (!con_freeflag(con) && !cptr)
946 free_connection(con); /* client is being destroyed */
948 Debug((DEBUG_LIST, "Client process timer for %C expired; processing",
950 read_packet(cptr, 0); /* read_packet will re-add timer if needed */
953 assert(0 == cptr || 0 == cli_connect(cptr) || con == cli_connect(cptr));