2 * ngIRCd -- The Next Generation IRC Daemon
3 * Copyright (c)2001-2014 Alexander Barton (alex@barton.de) and Contributors.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 * Please read the file COPYING, README and AUTHORS for more information.
20 * Connection management
35 #include <sys/socket.h>
37 #include <sys/types.h>
39 #include <netinet/in.h>
41 #ifdef HAVE_NETINET_IP_H
42 # ifdef HAVE_NETINET_IN_SYSTM_H
43 # include <netinet/in_systm.h>
45 # include <netinet/ip.h>
49 # include <tcpd.h> /* for TCP Wrappers */
57 # include "conn-encoding.h"
61 #include "conn-func.h"
64 #include "ng_ipaddr.h"
68 #define SERVER_WAIT (NONE - 1)
70 #define MAX_COMMANDS 3
71 #define MAX_COMMANDS_SERVER_MIN 10
72 #define MAX_COMMANDS_SERVICE 10
74 #define SD_LISTEN_FDS_START 3
76 static bool Handle_Write PARAMS(( CONN_ID Idx ));
77 static bool Conn_Write PARAMS(( CONN_ID Idx, char *Data, size_t Len ));
78 static int New_Connection PARAMS(( int Sock, bool IsSSL ));
79 static CONN_ID Socket2Index PARAMS(( int Sock ));
80 static void Read_Request PARAMS(( CONN_ID Idx ));
81 static unsigned int Handle_Buffer PARAMS(( CONN_ID Idx ));
82 static void Check_Connections PARAMS(( void ));
83 static void Check_Servers PARAMS(( void ));
84 static void Init_Conn_Struct PARAMS(( CONN_ID Idx ));
85 static bool Init_Socket PARAMS(( int Sock ));
86 static void New_Server PARAMS(( int Server, ng_ipaddr_t *dest ));
87 static void Simple_Message PARAMS(( int Sock, const char *Msg ));
88 static int NewListener PARAMS(( const char *listen_addr, UINT16 Port ));
89 static void Account_Connection PARAMS((void));
91 static array My_Listeners;
92 static array My_ConnArray;
93 static size_t NumConnections, NumConnectionsMax, NumConnectionsAccepted;
96 int allow_severity = LOG_INFO;
97 int deny_severity = LOG_ERR;
100 static void server_login PARAMS((CONN_ID idx));
103 extern struct SSLOptions Conf_SSLOptions;
104 static void cb_connserver_login_ssl PARAMS((int sock, short what));
105 static void cb_clientserver_ssl PARAMS((int sock, short what));
107 static void cb_Read_Resolver_Result PARAMS((int sock, UNUSED short what));
108 static void cb_Connect_to_Server PARAMS((int sock, UNUSED short what));
109 static void cb_clientserver PARAMS((int sock, short what));
115 * Get number of sockets available from systemd(8).
117 * ngIRCd needs to implement its own sd_listen_fds(3) function and can't
118 * use the one provided by systemd itself, because the sockets will be
119 * used in a forked child process with a new PID, and this would trigger
120 * an error in the standard implementation.
122 * @return Number of sockets available, -1 if sockets have already been
123 * initialized, or 0 when no sockets have been passed.
126 my_sd_listen_fds(void)
131 /* Check if LISTEN_PID exists; but we ignore the result, because
132 * normally ngircd forks a child before checking this, and therefore
133 * the PID set in the environment is always wrong ... */
134 e = getenv("LISTEN_PID");
138 e = getenv("LISTEN_FDS");
143 unsetenv("LISTEN_FDS");
151 * IO callback for listening sockets: handle new connections. This callback
152 * gets called when a new non-SSL connection should be accepted.
154 * @param sock Socket descriptor.
155 * @param irrelevant (ignored IO specification)
158 cb_listen(int sock, short irrelevant)
161 (void) New_Connection(sock, false);
167 * IO callback for listening SSL sockets: handle new connections. This callback
168 * gets called when a new SSL-enabled connection should be accepted.
170 * @param sock Socket descriptor.
171 * @param irrelevant (ignored IO specification)
174 cb_listen_ssl(int sock, short irrelevant)
179 fd = New_Connection(sock, true);
182 io_event_setcb(My_Connections[fd].sock, cb_clientserver_ssl);
188 * IO callback for new outgoing non-SSL server connections.
190 * @param sock Socket descriptor.
191 * @param what IO specification (IO_WANTREAD/IO_WANTWRITE/...).
194 cb_connserver(int sock, UNUSED short what)
196 int res, err, server;
198 CONN_ID idx = Socket2Index( sock );
201 LogDebug("cb_connserver wants to write on unknown socket?!");
206 assert(what & IO_WANTWRITE);
208 /* Make sure that the server is still configured; it could have been
209 * removed in the meantime! */
210 server = Conf_GetServer(idx);
212 Log(LOG_ERR, "Connection on socket %d to \"%s\" aborted!",
213 sock, My_Connections[idx].host);
214 Conn_Close(idx, "Connection aborted", NULL, false);
218 /* connect() finished, get result. */
219 sock_len = (socklen_t)sizeof(err);
220 res = getsockopt(My_Connections[idx].sock, SOL_SOCKET, SO_ERROR,
222 assert(sock_len == sizeof(err));
224 /* Error while connecting? */
225 if ((res != 0) || (err != 0)) {
227 Log(LOG_CRIT, "getsockopt (connection %d): %s!",
228 idx, strerror(errno));
231 "Can't connect socket to \"%s:%d\" (connection %d): %s!",
232 My_Connections[idx].host, Conf_Server[server].port,
235 Conn_Close(idx, "Can't connect", NULL, false);
237 if (ng_ipaddr_af(&Conf_Server[server].dst_addr[0])) {
238 /* more addresses to try... */
239 New_Server(server, &Conf_Server[server].dst_addr[0]);
240 /* connection to dst_addr[0] is now in progress, so
241 * remove this address... */
242 Conf_Server[server].dst_addr[0] =
243 Conf_Server[server].dst_addr[1];
244 memset(&Conf_Server[server].dst_addr[1], 0,
245 sizeof(Conf_Server[server].dst_addr[1]));
250 /* connect() succeeded, remove all additional addresses */
251 memset(&Conf_Server[server].dst_addr, 0,
252 sizeof(Conf_Server[server].dst_addr));
254 Conn_OPTION_DEL( &My_Connections[idx], CONN_ISCONNECTING );
256 if ( Conn_OPTION_ISSET( &My_Connections[idx], CONN_SSL_CONNECT )) {
257 io_event_setcb( sock, cb_connserver_login_ssl );
258 io_event_add( sock, IO_WANTWRITE|IO_WANTREAD );
267 * Login to a remote server.
269 * @param idx Connection index.
272 server_login(CONN_ID idx)
275 "Connection %d (socket %d) with \"%s:%d\" established. Now logging in ...",
276 idx, My_Connections[idx].sock, My_Connections[idx].host,
277 Conf_Server[Conf_GetServer(idx)].port);
279 io_event_setcb( My_Connections[idx].sock, cb_clientserver);
280 io_event_add( My_Connections[idx].sock, IO_WANTREAD|IO_WANTWRITE);
282 /* Send PASS and SERVER command to peer */
283 Conn_WriteStr( idx, "PASS %s %s", Conf_Server[Conf_GetServer( idx )].pwd_out, NGIRCd_ProtoID );
284 Conn_WriteStr( idx, "SERVER %s :%s", Conf_ServerName, Conf_ServerInfo );
290 * IO callback for new outgoing SSL-enabled server connections.
292 * @param sock Socket descriptor.
293 * @param unused (ignored IO specification)
296 cb_connserver_login_ssl(int sock, short unused)
298 CONN_ID idx = Socket2Index(sock);
306 switch (ConnSSL_Connect( &My_Connections[idx])) {
308 case 0: LogDebug("ConnSSL_Connect: not ready");
311 Log(LOG_ERR, "SSL connection on socket %d failed!", sock);
312 Conn_Close(idx, "Can't connect", NULL, false);
316 Log( LOG_INFO, "SSL connection %d with \"%s:%d\" established.", idx,
317 My_Connections[idx].host, Conf_Server[Conf_GetServer( idx )].port );
325 * IO callback for established non-SSL client and server connections.
327 * @param sock Socket descriptor.
328 * @param what IO specification (IO_WANTREAD/IO_WANTWRITE/...).
331 cb_clientserver(int sock, short what)
333 CONN_ID idx = Socket2Index(sock);
342 if (what & IO_WANTREAD
343 || (Conn_OPTION_ISSET(&My_Connections[idx], CONN_SSL_WANT_WRITE))) {
344 /* if TLS layer needs to write additional data, call
345 * Read_Request() instead so that SSL/TLS can continue */
349 if (what & IO_WANTREAD)
352 if (what & IO_WANTWRITE)
359 * IO callback for new SSL-enabled client and server connections.
361 * @param sock Socket descriptor.
362 * @param what IO specification (IO_WANTREAD/IO_WANTWRITE/...).
365 cb_clientserver_ssl(int sock, UNUSED short what)
367 CONN_ID idx = Socket2Index(sock);
376 switch (ConnSSL_Accept(&My_Connections[idx])) {
380 return; /* EAGAIN: callback will be invoked again by IO layer */
383 "SSL accept error, closing socket", "SSL accept error",
388 io_event_setcb(sock, cb_clientserver); /* SSL handshake completed */
394 * Initialize connection module.
401 Pool_Size = CONNECTION_POOL;
402 if ((Conf_MaxConnections > 0) &&
403 (Pool_Size > Conf_MaxConnections))
404 Pool_Size = Conf_MaxConnections;
406 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)Pool_Size)) {
407 Log(LOG_EMERG, "Can't allocate memory! [Conn_Init]");
411 /* FIXME: My_Connetions/Pool_Size is needed by other parts of the
412 * code; remove them! */
413 My_Connections = (CONNECTION*) array_start(&My_ConnArray);
415 LogDebug("Allocated connection pool for %d items (%ld bytes).",
416 array_length(&My_ConnArray, sizeof(CONNECTION)),
417 array_bytes(&My_ConnArray));
419 assert(array_length(&My_ConnArray, sizeof(CONNECTION)) >= (size_t)Pool_Size);
421 array_free( &My_Listeners );
423 for (i = 0; i < Pool_Size; i++)
429 * Clean up connection module.
436 Conn_ExitListeners();
438 LogDebug("Shutting down all connections ..." );
439 for( idx = 0; idx < Pool_Size; idx++ ) {
440 if( My_Connections[idx].sock > NONE ) {
441 Conn_Close( idx, NULL, NGIRCd_SignalRestart ?
442 "Server going down (restarting)":"Server going down", true );
446 array_free(&My_ConnArray);
447 My_Connections = NULL;
449 io_library_shutdown();
454 * Close all sockets (file descriptors) of open connections.
455 * This is useful in forked child processes, for example, to make sure that
456 * they don't hold connections open that the main process wants to close.
459 Conn_CloseAllSockets(int ExceptOf)
463 for(idx = 0; idx < Pool_Size; idx++) {
464 if(My_Connections[idx].sock > NONE &&
465 My_Connections[idx].sock != ExceptOf)
466 close(My_Connections[idx].sock);
472 * Initialize listening ports.
474 * @param a Array containing the ports the daemon should listen on.
475 * @param listen_addr Address the socket should listen on (can be "0.0.0.0").
476 * @param func IO callback function to register.
477 * @returns Number of listening sockets created.
480 Init_Listeners(array *a, const char *listen_addr, void (*func)(int,short))
482 unsigned int created = 0;
487 len = array_length(a, sizeof (UINT16));
488 port = array_start(a);
490 fd = NewListener(listen_addr, *port);
495 if (!io_event_create( fd, IO_WANTREAD, func )) {
497 "io_event_create(): Can't add fd %d (port %u): %s!",
498 fd, (unsigned int) *port, strerror(errno));
511 * Initialize all listening sockets.
513 * @returns Number of created listening sockets
516 Conn_InitListeners( void )
518 /* Initialize ports on which the server should accept connections */
519 unsigned int created = 0;
520 char *af_str, *copy, *listen_addr;
521 int count, fd, i, addr_len;
524 assert(Conf_ListenAddress);
526 count = my_sd_listen_fds();
529 "Not re-initializing listening sockets of systemd(8) ...");
533 /* systemd(8) passed sockets to us, so don't try to initialize
534 * listening sockets on our own but use the passed ones */
535 LogDebug("Initializing %d systemd sockets ...", count);
536 for (i = 0; i < count; i++) {
537 fd = SD_LISTEN_FDS_START + i;
538 addr_len = (int)sizeof(addr);
539 getsockname(fd, (struct sockaddr *)&addr, (socklen_t*)&addr_len);
541 if (addr.sin4.sin_family != AF_INET && addr.sin4.sin_family != AF_INET6)
543 if (addr.sin4.sin_family != AF_INET)
546 /* Socket is of unsupported type! For example, systemd passed in
547 * an IPv6 socket but ngIRCd isn't compiled with IPv6 support. */
548 switch (addr.sin4.sin_family)
550 case AF_UNSPEC: af_str = "AF_UNSPEC"; break;
551 case AF_UNIX: af_str = "AF_UNIX"; break;
552 case AF_INET: af_str = "AF_INET"; break;
554 case AF_INET6: af_str = "AF_INET6"; break;
557 case AF_NETLINK: af_str = "AF_NETLINK"; break;
559 default: af_str = "unknown"; break;
562 "Socket %d is of unsupported type \"%s\" (%d), have to ignore it!",
563 fd, af_str, addr.sin4.sin_family);
569 if (!io_event_create(fd, IO_WANTREAD, cb_listen)) {
571 "io_event_create(): Can't add fd %d: %s!",
572 fd, strerror(errno));
576 "Initialized socket %d from systemd(8): %s:%d.", fd,
577 ng_ipaddr_tostr(&addr), ng_ipaddr_getport(&addr));
583 /* not using systemd socket activation, initialize listening sockets: */
585 /* can't use Conf_ListenAddress directly, see below */
586 copy = strdup(Conf_ListenAddress);
588 Log(LOG_CRIT, "Cannot copy %s: %s", Conf_ListenAddress,
592 listen_addr = strtok(copy, ",");
594 while (listen_addr) {
595 ngt_TrimStr(listen_addr);
597 created += Init_Listeners(&Conf_ListenPorts,
598 listen_addr, cb_listen);
600 created += Init_Listeners(&Conf_SSLOptions.ListenPorts,
601 listen_addr, cb_listen_ssl);
605 listen_addr = strtok(NULL, ",");
608 /* Can't free() Conf_ListenAddress here: on REHASH, if the config file
609 * cannot be re-loaded, we'd end up with a NULL Conf_ListenAddress.
610 * Instead, free() takes place in conf.c, before the config file
611 * is being parsed. */
615 } /* Conn_InitListeners */
619 * Shut down all listening sockets.
622 Conn_ExitListeners( void )
624 /* Close down all listening sockets */
628 /* Get number of listening sockets to shut down. There can be none
629 * if ngIRCd has been "socket activated" by systemd. */
630 arraylen = array_length(&My_Listeners, sizeof (int));
635 "Shutting down all listening sockets (%d total) ...", arraylen);
636 fd = array_start(&My_Listeners);
641 LogDebug("Listening socket %d closed.", *fd );
644 array_free(&My_Listeners);
645 } /* Conn_ExitListeners */
649 * Bind a socket to a specific (source) address.
651 * @param addr Address structure.
652 * @param listen_addrstr Source address as string.
653 * @param Port Port number.
654 * @returns true on success, false otherwise.
657 InitSinaddrListenAddr(ng_ipaddr_t *addr, const char *listen_addrstr, UINT16 Port)
661 ret = ng_ipaddr_init(addr, listen_addrstr, Port);
663 assert(listen_addrstr);
664 Log(LOG_CRIT, "Can't bind to [%s]:%u: can't convert ip address \"%s\"!",
665 listen_addrstr, Port, listen_addrstr);
672 * Set a socket to "IPv6 only". If the given socket doesn't belong to the
673 * AF_INET6 family, or the operating system doesn't support this functionality,
674 * this function retruns silently.
676 * @param af Address family of the socket.
677 * @param sock Socket handle.
680 set_v6_only(int af, int sock)
682 #if defined(IPV6_V6ONLY) && defined(WANT_IPV6)
688 if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, (socklen_t)sizeof(on)))
689 Log(LOG_ERR, "Could not set IPV6_V6ONLY: %s", strerror(errno));
698 * Initialize new listening port.
700 * @param listen_addr Local address to bind the socet to (can be 0.0.0.0).
701 * @param Port Port number on which the new socket should be listening.
702 * @returns file descriptor of the socket or -1 on failure.
705 NewListener(const char *listen_addr, UINT16 Port)
707 /* Create new listening socket on specified port */
711 if (!InitSinaddrListenAddr(&addr, listen_addr, Port))
714 af = ng_ipaddr_af(&addr);
715 sock = socket(af, SOCK_STREAM, 0);
717 Log(LOG_CRIT, "Can't create socket (af %d) : %s!", af,
722 set_v6_only(af, sock);
724 if (!Init_Socket(sock))
727 if (bind(sock, (struct sockaddr *)&addr, ng_ipaddr_salen(&addr)) != 0) {
728 Log(LOG_CRIT, "Can't bind socket to address %s:%d - %s!",
729 ng_ipaddr_tostr(&addr), Port, strerror(errno));
734 if (listen(sock, 10) != 0) {
735 Log(LOG_CRIT, "Can't listen on socket: %s!", strerror(errno));
740 /* keep fd in list so we can close it when ngircd restarts/shuts down */
741 if (!array_catb(&My_Listeners, (char *)&sock, sizeof(int))) {
742 Log(LOG_CRIT, "Can't add socket to My_Listeners array: %s!",
748 Log(LOG_INFO, "Now listening on [%s]:%d (socket %d).",
749 ng_ipaddr_tostr(&addr), Port, sock);
757 * Check if SSL library needs to read SSL-protocol related data.
759 * SSL/TLS connections require extra treatment:
760 * When either CONN_SSL_WANT_WRITE or CONN_SSL_WANT_READ is set, we
761 * need to take care of that first, before checking read/write buffers.
762 * For instance, while we might have data in our write buffer, the
763 * TLS/SSL protocol might need to read internal data first for TLS/SSL
766 * If this function returns true, such a condition is met and we have
767 * to reverse the condition (check for read even if we've data to write,
768 * do not check for read but writeability even if write-buffer is empty).
770 * @param c Connection to check.
771 * @returns true if SSL-library has to read protocol data.
774 SSL_WantRead(const CONNECTION *c)
776 if (Conn_OPTION_ISSET(c, CONN_SSL_WANT_READ)) {
777 io_event_add(c->sock, IO_WANTREAD);
784 * Check if SSL library needs to write SSL-protocol related data.
786 * Please see description of SSL_WantRead() for full description!
788 * @param c Connection to check.
789 * @returns true if SSL-library has to write protocol data.
792 SSL_WantWrite(const CONNECTION *c)
794 if (Conn_OPTION_ISSET(c, CONN_SSL_WANT_WRITE)) {
795 io_event_add(c->sock, IO_WANTWRITE);
805 * "Main Loop": Loop until shutdown or restart is signalled.
807 * This function loops until a shutdown or restart of ngIRCd is signalled and
808 * calls io_dispatch() to check for readable and writable sockets every second.
809 * It checks for status changes on pending connections (e. g. when a hostname
810 * has been resolved), checks for "penalties" and timeouts, and handles the
817 unsigned int wdatalen, bytes_processed;
821 while (!NGIRCd_SignalQuit && !NGIRCd_SignalRestart) {
824 /* Check configured servers and established links */
828 /* Expire outdated class/list items */
831 /* Look for non-empty read buffers ... */
832 for (i = 0; i < Pool_Size; i++) {
833 if ((My_Connections[i].sock > NONE)
834 && (array_bytes(&My_Connections[i].rbuf) > 0)) {
835 /* ... and try to handle the received data */
836 bytes_processed = Handle_Buffer(i);
837 /* if we processed data, and there might be
838 * more commands in the input buffer, do not
839 * try to read any more data now */
840 if (bytes_processed &&
841 array_bytes(&My_Connections[i].rbuf) > 2) {
843 ("Throttling connection %d: command limit reached!",
845 Conn_SetPenalty(i, 1);
850 /* Look for non-empty write buffers ... */
851 for (i = 0; i < Pool_Size; i++) {
852 if (My_Connections[i].sock <= NONE)
855 wdatalen = (unsigned int)array_bytes(&My_Connections[i].wbuf);
858 array_bytes(&My_Connections[i].zip.wbuf) > 0)
864 if (SSL_WantRead(&My_Connections[i]))
867 io_event_add(My_Connections[i].sock,
872 /* Check from which sockets we possibly could read ... */
873 for (i = 0; i < Pool_Size; i++) {
874 if (My_Connections[i].sock <= NONE)
877 if (SSL_WantWrite(&My_Connections[i]))
878 continue; /* TLS/SSL layer needs to write data; deal with this first */
880 if (Proc_InProgress(&My_Connections[i].proc_stat)) {
881 /* Wait for completion of forked subprocess
882 * and ignore the socket in the meantime ... */
883 io_event_del(My_Connections[i].sock,
888 if (Conn_OPTION_ISSET(&My_Connections[i], CONN_ISCONNECTING))
889 /* Wait for completion of connect() ... */
892 if (My_Connections[i].delaytime > t) {
893 /* There is a "penalty time" set: ignore socket! */
894 io_event_del(My_Connections[i].sock,
899 io_event_add(My_Connections[i].sock, IO_WANTREAD);
902 /* Set the timeout for reading from the network to 1 second,
903 * which is the granularity with witch we handle "penalty
904 * times" for example.
905 * Note: tv_sec/usec are undefined(!) after io_dispatch()
906 * returns, so we have to set it before each call to it! */
910 /* Wait for activity ... */
911 i = io_dispatch(&tv);
912 if (i == -1 && errno != EINTR) {
913 Log(LOG_EMERG, "Conn_Handler(): io_dispatch(): %s!",
915 Log(LOG_ALERT, "%s exiting due to fatal errors!",
920 /* Should ngIRCd timeout when idle? */
921 if (Conf_IdleTimeout > 0 && NumConnectionsAccepted > 0
922 && idle_t > 0 && time(NULL) - idle_t >= Conf_IdleTimeout) {
923 LogDebug("Server idle timeout reached: %d second%s. Initiating shutdown ...",
925 Conf_IdleTimeout == 1 ? "" : "s");
926 NGIRCd_SignalQuit = true;
930 if (NGIRCd_SignalQuit)
931 Log(LOG_NOTICE | LOG_snotice, "Server going down NOW!");
932 else if (NGIRCd_SignalRestart)
933 Log(LOG_NOTICE | LOG_snotice, "Server restarting NOW!");
938 * Write a text string into the socket of a connection.
940 * This function automatically appends CR+LF to the string and validates that
941 * the result is a valid IRC message (oversized messages are shortened, for
942 * example). Then it calls the Conn_Write() function to do the actual sending.
944 * @param Idx Index fo the connection.
945 * @param Format Format string, see printf().
946 * @returns true on success, false otherwise.
950 Conn_WriteStr(CONN_ID Idx, const char *Format, ...)
953 Conn_WriteStr(Idx, Format, va_alist)
959 char buffer[COMMAND_LEN];
968 assert( Idx > NONE );
969 assert( Format != NULL );
972 va_start( ap, Format );
976 r = vsnprintf(buffer, COMMAND_LEN - 2, Format, ap);
977 if (r >= COMMAND_LEN - 2 || r == -1) {
979 * The string that should be written to the socket is longer
980 * than the allowed size of COMMAND_LEN bytes (including both
981 * the CR and LF characters). This can be caused by the
982 * IRC_WriteXXX() functions when the prefix of this server had
983 * to be added to an already "quite long" command line which
984 * has been received from a regular IRC client, for example.
986 * We are not allowed to send such "oversized" messages to
987 * other servers and clients, see RFC 2812 2.3 and 2813 3.3
988 * ("these messages SHALL NOT exceed 512 characters in length,
989 * counting all characters including the trailing CR-LF").
991 * So we have a big problem here: we should send more bytes
992 * to the network than we are allowed to and we don't know
993 * the originator (any more). The "old" behavior of blaming
994 * the receiver ("next hop") is a bad idea (it could be just
995 * an other server only routing the message!), so the only
996 * option left is to shorten the string and to hope that the
997 * result is still somewhat useful ...
1000 * C99 states that vsnprintf() "returns the number of characters
1001 * that would have been printed if the n were unlimited"; but
1002 * according to the Linux manual page "glibc until 2.0.6 would
1003 * return -1 when the output was truncated" -- so we have to
1004 * handle both cases ...
1008 strcpy (buffer + sizeof(buffer) - strlen(CUT_TXTSUFFIX) - 2 - 1,
1013 ptr = strchr(buffer + 1, ':');
1016 message = Conn_EncodingTo(Idx, ptr);
1018 strlcpy(ptr, message, sizeof(buffer) - (ptr - buffer));
1024 Log(LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer);
1027 len = strlcat( buffer, "\r\n", sizeof( buffer ));
1028 ok = Conn_Write(Idx, buffer, len);
1029 My_Connections[Idx].msg_out++;
1033 } /* Conn_WriteStr */
1036 Conn_Password( CONN_ID Idx )
1038 assert( Idx > NONE );
1039 if (My_Connections[Idx].pwd == NULL)
1042 return My_Connections[Idx].pwd;
1043 } /* Conn_Password */
1046 Conn_SetPassword( CONN_ID Idx, const char *Pwd )
1048 assert( Idx > NONE );
1050 if (My_Connections[Idx].pwd)
1051 free(My_Connections[Idx].pwd);
1053 My_Connections[Idx].pwd = strdup(Pwd);
1054 if (My_Connections[Idx].pwd == NULL) {
1055 Log(LOG_EMERG, "Can't allocate memory! [Conn_SetPassword]");
1058 } /* Conn_SetPassword */
1061 * Append Data to the outbound write buffer of a connection.
1063 * @param Idx Index of the connection.
1064 * @param Data pointer to the data.
1065 * @param Len length of Data.
1066 * @returns true on success, false otherwise.
1069 Conn_Write( CONN_ID Idx, char *Data, size_t Len )
1072 size_t writebuf_limit = WRITEBUFFER_MAX_LEN;
1073 assert( Idx > NONE );
1074 assert( Data != NULL );
1077 /* Is the socket still open? A previous call to Conn_Write()
1078 * may have closed the connection due to a fatal error.
1079 * In this case it is sufficient to return an error, as well. */
1080 if (My_Connections[Idx].sock <= NONE) {
1081 LogDebug("Skipped write on closed socket (connection %d).", Idx);
1085 /* Make sure that there still exists a CLIENT structure associated
1086 * with this connection and check if this is a server or not: */
1087 c = Conn_GetClient(Idx);
1089 /* Servers do get special write buffer limits, so they can
1090 * generate all the messages that are required while peering. */
1091 if (Client_Type(c) == CLIENT_SERVER)
1092 writebuf_limit = WRITEBUFFER_SLINK_LEN;
1094 LogDebug("Write on socket without client (connection %d)!?", Idx);
1097 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
1099 * Zip_Buffer() does all the dirty work for us: it flushes
1100 * the (pre-)compression buffers if required and handles
1101 * all error conditions. */
1102 if (!Zip_Buffer(Idx, Data, Len))
1108 /* Uncompressed link:
1109 * Check if outbound buffer has enough space for the data. */
1110 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
1111 WRITEBUFFER_FLUSH_LEN) {
1112 /* Buffer is full, flush it. Handle_Write deals with
1113 * low-level errors, if any. */
1114 if (!Handle_Write(Idx))
1118 /* When the write buffer is still too big after flushing it,
1119 * the connection will be killed. */
1120 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
1123 "Write buffer space exhausted (connection %d, limit is %lu bytes, %lu bytes new, %lu bytes pending)",
1124 Idx, writebuf_limit, Len,
1125 (unsigned long)array_bytes(&My_Connections[Idx].wbuf));
1126 Conn_Close(Idx, "Write buffer space exhausted", NULL, false);
1130 /* Copy data to write buffer */
1131 if (!array_catb(&My_Connections[Idx].wbuf, Data, Len))
1134 My_Connections[Idx].bytes_out += Len;
1137 /* Adjust global write counter */
1145 * Shut down a connection.
1147 * @param Idx Connection index.
1148 * @param LogMsg Message to write to the log or NULL. If no LogMsg
1149 * is given, the FwdMsg is logged.
1150 * @param FwdMsg Message to forward to remote servers.
1151 * @param InformClient If true, inform the client on the connection which is
1152 * to be shut down of the reason (FwdMsg) and send
1153 * connection statistics before disconnecting it.
1156 Conn_Close( CONN_ID Idx, const char *LogMsg, const char *FwdMsg, bool InformClient )
1158 /* Close connection. Open pipes of asynchronous resolver
1159 * sub-processes are closed down. */
1165 double in_z_k, out_z_k;
1169 assert( Idx > NONE );
1171 /* Is this link already shutting down? */
1172 if( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ISCLOSING )) {
1173 /* Conn_Close() has been called recursively for this link;
1174 * probable reason: Handle_Write() failed -- see below. */
1175 LogDebug("Recursive request to close connection %d!", Idx );
1179 assert( My_Connections[Idx].sock > NONE );
1181 /* Mark link as "closing" */
1182 Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCLOSING );
1184 port = ng_ipaddr_getport(&My_Connections[Idx].addr);
1185 Log(LOG_INFO, "Shutting down connection %d (%s) with \"%s:%d\" ...", Idx,
1186 LogMsg ? LogMsg : FwdMsg, My_Connections[Idx].host, port);
1188 /* Search client, if any */
1189 c = Conn_GetClient( Idx );
1191 /* Should the client be informed? */
1194 /* Send statistics to client if registered as user: */
1195 if ((c != NULL) && (Client_Type(c) == CLIENT_USER)) {
1197 ":%s NOTICE %s :%sConnection statistics: client %.1f kb, server %.1f kb.",
1198 Client_ID(Client_ThisServer()), Client_ID(c),
1200 (double)My_Connections[Idx].bytes_in / 1024,
1201 (double)My_Connections[Idx].bytes_out / 1024);
1204 /* Send ERROR to client (see RFC 2812, section 3.1.7) */
1206 Conn_WriteStr(Idx, "ERROR :%s", FwdMsg);
1208 Conn_WriteStr(Idx, "ERROR :Closing connection");
1211 /* Try to write out the write buffer. Note: Handle_Write() eventually
1212 * removes the CLIENT structure associated with this connection if an
1213 * error occurs! So we have to re-check if there is still an valid
1214 * CLIENT structure after calling Handle_Write() ...*/
1215 (void)Handle_Write( Idx );
1217 /* Search client, if any (re-check!) */
1218 c = Conn_GetClient( Idx );
1220 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_SSL )) {
1221 LogDebug("SSL connection %d shutting down ...", Idx);
1222 ConnSSL_Free(&My_Connections[Idx]);
1225 /* Shut down socket */
1226 if (! io_close(My_Connections[Idx].sock)) {
1227 /* Oops, we can't close the socket!? This is ... ugly! */
1229 "Error closing connection %d (socket %d) with %s:%d - %s! (ignored)",
1230 Idx, My_Connections[Idx].sock, My_Connections[Idx].host,
1231 port, strerror(errno));
1234 /* Mark socket as invalid: */
1235 My_Connections[Idx].sock = NONE;
1237 /* If there is still a client, unregister it now */
1239 Client_Destroy(c, LogMsg, FwdMsg, true);
1241 /* Calculate statistics and log information */
1242 in_k = (double)My_Connections[Idx].bytes_in / 1024;
1243 out_k = (double)My_Connections[Idx].bytes_out / 1024;
1245 if (Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP)) {
1246 in_z_k = (double)My_Connections[Idx].zip.bytes_in / 1024;
1247 out_z_k = (double)My_Connections[Idx].zip.bytes_out / 1024;
1248 /* Make sure that no division by zero can occur during
1249 * the calculation of in_p and out_p: in_z_k and out_z_k
1250 * are non-zero, that's guaranteed by the protocol until
1251 * compression can be enabled. */
1256 in_p = (int)(( in_k * 100 ) / in_z_k );
1257 out_p = (int)(( out_k * 100 ) / out_z_k );
1259 "Connection %d with \"%s:%d\" closed (in: %.1fk/%.1fk/%d%%, out: %.1fk/%.1fk/%d%%).",
1260 Idx, My_Connections[Idx].host, port,
1261 in_k, in_z_k, in_p, out_k, out_z_k, out_p);
1267 "Connection %d with \"%s:%d\" closed (in: %.1fk, out: %.1fk).",
1268 Idx, My_Connections[Idx].host, port,
1272 /* Servers: Modify time of next connect attempt? */
1273 Conf_UnsetServer( Idx );
1276 /* Clean up zlib, if link was compressed */
1277 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
1278 inflateEnd( &My_Connections[Idx].zip.in );
1279 deflateEnd( &My_Connections[Idx].zip.out );
1280 array_free(&My_Connections[Idx].zip.rbuf);
1281 array_free(&My_Connections[Idx].zip.wbuf);
1285 array_free(&My_Connections[Idx].rbuf);
1286 array_free(&My_Connections[Idx].wbuf);
1287 if (My_Connections[Idx].pwd != NULL)
1288 free(My_Connections[Idx].pwd);
1290 /* Clean up connection structure (=free it) */
1291 Init_Conn_Struct( Idx );
1293 assert(NumConnections > 0);
1296 LogDebug("Shutdown of connection %d completed, %ld connection%s left.",
1297 Idx, NumConnections, NumConnections != 1 ? "s" : "");
1299 idle_t = NumConnections > 0 ? 0 : time(NULL);
1304 * Get current number of connections.
1306 * @returns Number of current connections.
1311 return NumConnections;
1316 * Get number of maximum simultaneous connections.
1318 * @returns Number of maximum simultaneous connections.
1323 return NumConnectionsMax;
1324 } /* Conn_CountMax */
1328 * Get number of connections accepted since the daemon startet.
1330 * @returns Number of connections accepted.
1333 Conn_CountAccepted(void)
1335 return NumConnectionsAccepted;
1336 } /* Conn_CountAccepted */
1340 * Synchronize established connections and configured server structures
1341 * after a configuration update and store the correct connection IDs, if any.
1344 Conn_SyncServerStruct(void)
1350 for (i = 0; i < Pool_Size; i++) {
1351 if (My_Connections[i].sock == NONE)
1355 client = Conn_GetClient(i);
1356 if (!client || Client_Type(client) != CLIENT_SERVER)
1359 for (c = 0; c < MAX_SERVERS; c++) {
1360 /* Configured server? */
1361 if (!Conf_Server[c].host[0])
1364 if (strcasecmp(Conf_Server[c].name, Client_ID(client)) == 0)
1365 Conf_Server[c].conn_id = i;
1368 } /* SyncServerStruct */
1372 * Get IP address string of a connection.
1374 * @param Idx Connection index.
1375 * @return Pointer to a global buffer containing the IP address as string.
1378 Conn_GetIPAInfo(CONN_ID Idx)
1381 return ng_ipaddr_tostr(&My_Connections[Idx].addr);
1386 * Send out data of write buffer; connect new sockets.
1388 * @param Idx Connection index.
1389 * @returns true on success, false otherwise.
1392 Handle_Write( CONN_ID Idx )
1397 assert( Idx > NONE );
1398 if ( My_Connections[Idx].sock < 0 ) {
1399 LogDebug("Handle_Write() on closed socket, connection %d", Idx);
1402 assert( My_Connections[Idx].sock > NONE );
1404 wdatalen = array_bytes(&My_Connections[Idx].wbuf );
1407 if (wdatalen == 0) {
1408 /* Write buffer is empty, so we try to flush the compression
1409 * buffer and get some data to work with from there :-) */
1410 if (!Zip_Flush(Idx))
1413 /* Now the write buffer most probably has changed: */
1414 wdatalen = array_bytes(&My_Connections[Idx].wbuf);
1418 if (wdatalen == 0) {
1419 /* Still no data, fine. */
1420 io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
1426 ("Handle_Write() called for connection %d, %ld bytes pending ...",
1431 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_SSL )) {
1432 len = ConnSSL_Write(&My_Connections[Idx], array_start(&My_Connections[Idx].wbuf), wdatalen);
1436 len = write(My_Connections[Idx].sock,
1437 array_start(&My_Connections[Idx].wbuf), wdatalen );
1440 if (errno == EAGAIN || errno == EINTR)
1443 if (!Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ISCLOSING))
1445 "Write error on connection %d (socket %d): %s!",
1446 Idx, My_Connections[Idx].sock, strerror(errno));
1448 LogDebug("Recursive write error on connection %d (socket %d): %s!",
1449 Idx, My_Connections[Idx].sock, strerror(errno));
1450 Conn_Close(Idx, "Write error", NULL, false);
1454 /* move any data not yet written to beginning */
1455 array_moveleft(&My_Connections[Idx].wbuf, 1, (size_t)len);
1458 } /* Handle_Write */
1462 * Count established connections to a specific IP address.
1464 * @returns Number of established connections.
1467 Count_Connections(ng_ipaddr_t *a)
1472 for (i = 0; i < Pool_Size; i++) {
1473 if (My_Connections[i].sock <= NONE)
1475 if (ng_ipaddr_ipequal(&My_Connections[i].addr, a))
1479 } /* Count_Connections */
1483 * Initialize new client connection on a listening socket.
1485 * @param Sock Listening socket descriptor.
1486 * @param IsSSL true if this socket expects SSL-encrypted data.
1487 * @returns Accepted socket descriptor or -1 on error.
1490 New_Connection(int Sock, UNUSED bool IsSSL)
1493 struct request_info req;
1495 ng_ipaddr_t new_addr;
1496 char ip_str[NG_INET_ADDRSTRLEN];
1497 int new_sock, new_sock_len;
1501 assert(Sock > NONE);
1503 LogDebug("Accepting new connection on socket %d ...", Sock);
1505 new_sock_len = (int)sizeof(new_addr);
1506 new_sock = accept(Sock, (struct sockaddr *)&new_addr,
1507 (socklen_t *)&new_sock_len);
1509 Log(LOG_CRIT, "Can't accept connection: %s!", strerror(errno));
1512 NumConnectionsAccepted++;
1514 if (!ng_ipaddr_tostr_r(&new_addr, ip_str)) {
1515 Log(LOG_CRIT, "fd %d: Can't convert IP address!", new_sock);
1516 Simple_Message(new_sock, "ERROR :Internal Server Error");
1522 /* Validate socket using TCP Wrappers */
1523 request_init(&req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock,
1524 RQ_CLIENT_SIN, &new_addr, NULL);
1526 if (!hosts_access(&req)) {
1528 "Refused connection from %s (by TCP Wrappers)!", ip_str);
1529 Simple_Message(new_sock, "ERROR :Connection refused");
1535 if (!Init_Socket(new_sock))
1538 /* Check global connection limit */
1539 if ((Conf_MaxConnections > 0) &&
1540 (NumConnections >= (size_t) Conf_MaxConnections)) {
1541 Log(LOG_ALERT, "Can't accept connection: limit (%d) reached!",
1542 Conf_MaxConnections);
1543 Simple_Message(new_sock, "ERROR :Connection limit reached");
1548 /* Check IP-based connection limit */
1549 cnt = Count_Connections(&new_addr);
1550 if ((Conf_MaxConnectionsIP > 0) && (cnt >= Conf_MaxConnectionsIP)) {
1551 /* Access denied, too many connections from this IP address! */
1553 "Refused connection from %s: too may connections (%ld) from this IP address!",
1555 Simple_Message(new_sock,
1556 "ERROR :Connection refused, too many connections from your IP address");
1561 if (new_sock >= Pool_Size) {
1562 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION),
1563 (size_t) new_sock)) {
1565 "Can't allocate memory! [New_Connection]");
1566 Simple_Message(new_sock, "ERROR: Internal error");
1570 LogDebug("Bumped connection pool to %ld items (internal: %ld items, %ld bytes)",
1571 new_sock, array_length(&My_ConnArray,
1572 sizeof(CONNECTION)), array_bytes(&My_ConnArray));
1574 /* Adjust pointer to new block */
1575 My_Connections = array_start(&My_ConnArray);
1576 while (Pool_Size <= new_sock)
1577 Init_Conn_Struct(Pool_Size++);
1580 /* register callback */
1581 if (!io_event_create(new_sock, IO_WANTREAD, cb_clientserver)) {
1583 "Can't accept connection: io_event_create failed!");
1584 Simple_Message(new_sock, "ERROR :Internal error");
1589 c = Client_NewLocal(new_sock, NULL, CLIENT_UNKNOWN, false);
1592 "Can't accept connection: can't create client structure!");
1593 Simple_Message(new_sock, "ERROR :Internal error");
1598 Init_Conn_Struct(new_sock);
1599 My_Connections[new_sock].sock = new_sock;
1600 My_Connections[new_sock].addr = new_addr;
1601 My_Connections[new_sock].client = c;
1603 /* Set initial hostname to IP address. This becomes overwritten when
1604 * the DNS lookup is enabled and succeeds, but is used otherwise. */
1605 if (ng_ipaddr_af(&new_addr) != AF_INET)
1606 snprintf(My_Connections[new_sock].host,
1607 sizeof(My_Connections[new_sock].host), "[%s]", ip_str);
1609 strlcpy(My_Connections[new_sock].host, ip_str,
1610 sizeof(My_Connections[new_sock].host));
1612 Client_SetHostname(c, My_Connections[new_sock].host);
1614 Log(LOG_INFO, "Accepted connection %d from \"%s:%d\" on socket %d.",
1615 new_sock, My_Connections[new_sock].host,
1616 ng_ipaddr_getport(&new_addr), Sock);
1617 Account_Connection();
1620 /* Delay connection initalization until SSL handshake is finished */
1623 Conn_StartLogin(new_sock);
1626 } /* New_Connection */
1630 * Finish connection initialization, start resolver subprocess.
1632 * @param Idx Connection index.
1635 Conn_StartLogin(CONN_ID Idx)
1637 int ident_sock = -1;
1641 /* Nothing to do if DNS (and resolver subprocess) is disabled */
1646 /* Should we make an IDENT request? */
1648 ident_sock = My_Connections[Idx].sock;
1651 if (Conf_NoticeAuth) {
1652 /* Send "NOTICE AUTH" messages to the client */
1655 (void)Conn_WriteStr(Idx,
1656 "NOTICE AUTH :*** Looking up your hostname and checking ident");
1659 (void)Conn_WriteStr(Idx,
1660 "NOTICE AUTH :*** Looking up your hostname");
1661 /* Send buffered data to the client, but break on errors
1662 * because Handle_Write() would have closed the connection
1663 * again in this case! */
1664 if (!Handle_Write(Idx))
1668 Resolve_Addr(&My_Connections[Idx].proc_stat, &My_Connections[Idx].addr,
1669 ident_sock, cb_Read_Resolver_Result);
1674 * Update global connection counters.
1677 Account_Connection(void)
1681 if (NumConnections > NumConnectionsMax)
1682 NumConnectionsMax = NumConnections;
1683 LogDebug("Total number of connections now %lu (max %lu).",
1684 NumConnections, NumConnectionsMax);
1685 } /* Account_Connection */
1689 * Translate socket handle into connection index.
1691 * @param Sock Socket handle.
1692 * @returns Connecion index or NONE, if no connection could be found.
1695 Socket2Index( int Sock )
1697 assert( Sock >= 0 );
1699 if( Sock >= Pool_Size || My_Connections[Sock].sock != Sock ) {
1700 /* the Connection was already closed again, likely due to
1702 LogDebug("Socket2Index: can't get connection for socket %d!", Sock);
1706 } /* Socket2Index */
1710 * Read data from the network to the read buffer. If an error occurs,
1711 * the socket of this connection will be shut down.
1713 * @param Idx Connection index.
1716 Read_Request( CONN_ID Idx )
1719 static const unsigned int maxbps = COMMAND_LEN / 2;
1720 char readbuf[READBUFFER_LEN];
1723 assert( Idx > NONE );
1724 assert( My_Connections[Idx].sock > NONE );
1727 if ((array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN) ||
1728 (array_bytes(&My_Connections[Idx].zip.rbuf) >= READBUFFER_LEN))
1730 if (array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN)
1733 /* Read buffer is full */
1735 "Receive buffer space exhausted (connection %d): %d bytes",
1736 Idx, array_bytes(&My_Connections[Idx].rbuf));
1737 Conn_Close(Idx, "Receive buffer space exhausted", NULL, false);
1742 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_SSL))
1743 len = ConnSSL_Read( &My_Connections[Idx], readbuf, sizeof(readbuf));
1746 len = read(My_Connections[Idx].sock, readbuf, sizeof(readbuf));
1748 LogDebug("Client \"%s:%u\" is closing connection %d ...",
1749 My_Connections[Idx].host,
1750 ng_ipaddr_tostr(&My_Connections[Idx].addr), Idx);
1751 Conn_Close(Idx, NULL, "Client closed connection", false);
1756 if( errno == EAGAIN ) return;
1757 Log(LOG_ERR, "Read error on connection %d (socket %d): %s!",
1758 Idx, My_Connections[Idx].sock, strerror(errno));
1759 Conn_Close(Idx, "Read error", "Client closed connection",
1764 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1765 if (!array_catb(&My_Connections[Idx].zip.rbuf, readbuf,
1768 "Could not append received data to zip input buffer (connection %d): %d bytes!",
1770 Conn_Close(Idx, "Receive buffer space exhausted", NULL,
1777 if (!array_catb( &My_Connections[Idx].rbuf, readbuf, len)) {
1779 "Could not append received data to input buffer (connection %d): %d bytes!",
1781 Conn_Close(Idx, "Receive buffer space exhausted", NULL, false );
1785 /* Update connection statistics */
1786 My_Connections[Idx].bytes_in += len;
1787 My_Connections[Idx].bps += Handle_Buffer(Idx);
1789 /* Make sure that there is still a valid client registered */
1790 c = Conn_GetClient(Idx);
1794 /* Update timestamp of last data received if this connection is
1795 * registered as a user, server or service connection. Don't update
1796 * otherwise, so users have at least Conf_PongTimeout seconds time to
1797 * register with the IRC server -- see Check_Connections().
1798 * Update "lastping", too, if time shifted backwards ... */
1799 if (Client_Type(c) == CLIENT_USER
1800 || Client_Type(c) == CLIENT_SERVER
1801 || Client_Type(c) == CLIENT_SERVICE) {
1803 if (My_Connections[Idx].lastdata != t)
1804 My_Connections[Idx].bps = 0;
1806 My_Connections[Idx].lastdata = t;
1807 if (My_Connections[Idx].lastping > t)
1808 My_Connections[Idx].lastping = t;
1811 /* Look at the data in the (read-) buffer of this connection */
1812 if (Client_Type(c) != CLIENT_SERVER
1813 && Client_Type(c) != CLIENT_UNKNOWNSERVER
1814 && Client_Type(c) != CLIENT_SERVICE
1815 && My_Connections[Idx].bps >= maxbps) {
1816 LogDebug("Throttling connection %d: BPS exceeded! (%u >= %u)",
1817 Idx, My_Connections[Idx].bps, maxbps);
1818 Conn_SetPenalty(Idx, 1);
1820 } /* Read_Request */
1824 * Handle all data in the connection read-buffer.
1826 * Data is processed until no complete command is left in the read buffer,
1827 * or MAX_COMMANDS[_SERVER|_SERVICE] commands were processed.
1828 * When a fatal error occurs, the connection is shut down.
1830 * @param Idx Index of the connection.
1831 * @returns Number of bytes processed.
1834 Handle_Buffer(CONN_ID Idx)
1837 char *ptr1, *ptr2, *first_eol;
1845 unsigned int i, maxcmd = MAX_COMMANDS, len_processed = 0;
1848 c = Conn_GetClient(Idx);
1849 starttime = time(NULL);
1853 /* Servers get special command limits that depend on the user count */
1854 switch (Client_Type(c)) {
1856 maxcmd = (int)(Client_UserCount() / 5)
1857 + MAX_COMMANDS_SERVER_MIN;
1858 /* Allow servers to handle even more commands while peering
1859 * to speed up server login and network synchronization. */
1860 if (Conn_LastPing(Idx) == 0)
1863 case CLIENT_SERVICE:
1864 maxcmd = MAX_COMMANDS_SERVICE; break;
1867 for (i=0; i < maxcmd; i++) {
1869 if (My_Connections[Idx].delaytime > starttime)
1872 /* Unpack compressed data, if compression is in use */
1873 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1874 /* When unzipping fails, Unzip_Buffer() shuts
1875 * down the connection itself */
1876 if (!Unzip_Buffer(Idx))
1881 if (0 == array_bytes(&My_Connections[Idx].rbuf))
1884 /* Make sure that the buffer is NULL terminated */
1885 if (!array_cat0_temporary(&My_Connections[Idx].rbuf)) {
1886 Conn_Close(Idx, NULL,
1887 "Can't allocate memory [Handle_Buffer]",
1892 /* RFC 2812, section "2.3 Messages", 5th paragraph:
1893 * "IRC messages are always lines of characters terminated
1894 * with a CR-LF (Carriage Return - Line Feed) pair [...]". */
1896 ptr = strstr(array_start(&My_Connections[Idx].rbuf), "\r\n");
1899 /* Check for non-RFC-compliant request (only CR or LF)?
1900 * Unfortunately, there are quite a few clients out there
1901 * that do this -- e. g. mIRC, BitchX, and Trillian :-( */
1902 ptr1 = strchr(array_start(&My_Connections[Idx].rbuf), '\r');
1903 ptr2 = strchr(array_start(&My_Connections[Idx].rbuf), '\n');
1905 /* Check if there is a single CR or LF _before_ the
1906 * correct CR+LF line terminator: */
1907 first_eol = ptr1 < ptr2 ? ptr1 : ptr2;
1908 if (first_eol < ptr) {
1909 /* Single CR or LF before CR+LF found */
1913 } else if (ptr1 || ptr2) {
1914 /* No CR+LF terminated command found, but single
1915 * CR or LF found ... */
1917 ptr = ptr1 < ptr2 ? ptr1 : ptr2;
1919 ptr = ptr1 ? ptr1 : ptr2;
1927 /* Complete (=line terminated) request found, handle it! */
1930 len = ptr - (char *)array_start(&My_Connections[Idx].rbuf) + delta;
1932 if (len > (COMMAND_LEN - 1)) {
1933 /* Request must not exceed 512 chars (incl. CR+LF!),
1934 * see RFC 2812. Disconnect Client if this happens. */
1936 "Request too long (connection %d): %d bytes (max. %d expected)!",
1937 Idx, array_bytes(&My_Connections[Idx].rbuf),
1939 Conn_Close(Idx, NULL, "Request too long", true);
1943 len_processed += (unsigned int)len;
1945 /* Request is empty (only '\r\n', '\r' or '\n');
1946 * delta is 2 ('\r\n') or 1 ('\r' or '\n'), see above */
1947 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1951 /* remember if stream is already compressed */
1952 old_z = My_Connections[Idx].options & CONN_ZIP;
1955 My_Connections[Idx].msg_in++;
1957 (Idx, (char *)array_start(&My_Connections[Idx].rbuf)))
1958 return 0; /* error -> connection has been closed */
1960 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1962 LogDebug("Connection %d: %d bytes left in read buffer.",
1963 Idx, array_bytes(&My_Connections[Idx].rbuf));
1966 if ((!old_z) && (My_Connections[Idx].options & CONN_ZIP) &&
1967 (array_bytes(&My_Connections[Idx].rbuf) > 0)) {
1968 /* The last command activated socket compression.
1969 * Data that was read after that needs to be copied
1970 * to the unzip buffer for decompression: */
1972 (&My_Connections[Idx].zip.rbuf,
1973 &My_Connections[Idx].rbuf)) {
1974 Conn_Close(Idx, NULL,
1975 "Can't allocate memory [Handle_Buffer]",
1980 array_trunc(&My_Connections[Idx].rbuf);
1982 ("Moved already received data (%u bytes) to uncompression buffer.",
1983 array_bytes(&My_Connections[Idx].zip.rbuf));
1987 return len_processed;
1988 } /* Handle_Buffer */
1992 * Check whether established connections are still alive or not.
1993 * If not, play PING-PONG first; and if that doesn't help either,
1994 * disconnect the respective peer.
1997 Check_Connections(void)
2003 for (i = 0; i < Pool_Size; i++) {
2004 if (My_Connections[i].sock < 0)
2007 c = Conn_GetClient(i);
2008 if (c && ((Client_Type(c) == CLIENT_USER)
2009 || (Client_Type(c) == CLIENT_SERVER)
2010 || (Client_Type(c) == CLIENT_SERVICE))) {
2011 /* connected User, Server or Service */
2012 if (My_Connections[i].lastping >
2013 My_Connections[i].lastdata) {
2014 /* We already sent a ping */
2015 if (My_Connections[i].lastping <
2016 time(NULL) - Conf_PongTimeout) {
2018 snprintf(msg, sizeof(msg),
2019 "Ping timeout: %d seconds",
2021 LogDebug("Connection %d: %s.", i, msg);
2022 Conn_Close(i, NULL, msg, true);
2024 } else if (My_Connections[i].lastdata <
2025 time(NULL) - Conf_PingTimeout) {
2026 /* We need to send a PING ... */
2027 LogDebug("Connection %d: sending PING ...", i);
2029 Conn_WriteStr(i, "PING :%s",
2030 Client_ID(Client_ThisServer()));
2033 /* The connection is not fully established yet, so
2034 * we don't do the PING-PONG game here but instead
2035 * disconnect the client after "a short time" if it's
2036 * still not registered. */
2038 if (My_Connections[i].lastdata <
2039 time(NULL) - Conf_PongTimeout) {
2041 ("Unregistered connection %d timed out ...",
2043 Conn_Close(i, NULL, "Timeout", false);
2047 } /* Check_Connections */
2051 * Check if further server links should be established.
2059 time_now = time(NULL);
2061 /* Check all configured servers */
2062 for (i = 0; i < MAX_SERVERS; i++) {
2063 if (Conf_Server[i].conn_id != NONE)
2064 continue; /* Already establishing or connected */
2065 if (!Conf_Server[i].host[0] || !Conf_Server[i].port > 0)
2066 continue; /* No host and/or port configured */
2067 if (Conf_Server[i].flags & CONF_SFLAG_DISABLED)
2068 continue; /* Disabled configuration entry */
2069 if (Conf_Server[i].lasttry > (time_now - Conf_ConnectRetry))
2070 continue; /* We have to wait a little bit ... */
2072 /* Is there already a connection in this group? */
2073 if (Conf_Server[i].group > NONE) {
2074 for (n = 0; n < MAX_SERVERS; n++) {
2077 if ((Conf_Server[n].conn_id != NONE) &&
2078 (Conf_Server[n].group == Conf_Server[i].group))
2081 if (n < MAX_SERVERS)
2085 /* Okay, try to connect now */
2087 "Preparing to establish a new server link for \"%s\" ...",
2088 Conf_Server[i].name);
2089 Conf_Server[i].lasttry = time_now;
2090 Conf_Server[i].conn_id = SERVER_WAIT;
2091 assert(Proc_GetPipeFd(&Conf_Server[i].res_stat) < 0);
2092 Resolve_Name(&Conf_Server[i].res_stat, Conf_Server[i].host,
2093 cb_Connect_to_Server);
2095 } /* Check_Servers */
2099 * Establish a new outgoing server connection.
2101 * @param Server Configuration index of the server.
2102 * @param dest Destination IP address to connect to.
2105 New_Server( int Server , ng_ipaddr_t *dest)
2107 /* Establish new server link */
2108 char ip_str[NG_INET_ADDRSTRLEN];
2109 int af_dest, res, new_sock;
2112 assert( Server > NONE );
2114 /* Make sure that the remote server hasn't re-linked to this server
2115 * asynchronously on its own */
2116 if (Conf_Server[Server].conn_id > NONE) {
2118 "Connection to \"%s\" meanwhile re-established, aborting preparation.");
2122 if (!ng_ipaddr_tostr_r(dest, ip_str)) {
2123 Log(LOG_WARNING, "New_Server: Could not convert IP to string");
2124 Conf_Server[Server].conn_id = NONE;
2128 af_dest = ng_ipaddr_af(dest);
2129 new_sock = socket(af_dest, SOCK_STREAM, 0);
2132 "Establishing connection for \"%s\" to \"%s:%d\" (%s), socket %d ...",
2133 Conf_Server[Server].name, Conf_Server[Server].host,
2134 Conf_Server[Server].port, ip_str, new_sock);
2137 Log(LOG_CRIT, "Can't create socket (af %d): %s!",
2138 af_dest, strerror(errno));
2139 Conf_Server[Server].conn_id = NONE;
2143 if (!Init_Socket(new_sock)) {
2144 Conf_Server[Server].conn_id = NONE;
2148 /* is a bind address configured? */
2149 res = ng_ipaddr_af(&Conf_Server[Server].bind_addr);
2150 /* if yes, bind now. If it fails, warn and let connect() pick a source address */
2151 if (res && bind(new_sock, (struct sockaddr *) &Conf_Server[Server].bind_addr,
2152 ng_ipaddr_salen(&Conf_Server[Server].bind_addr)))
2154 ng_ipaddr_tostr_r(&Conf_Server[Server].bind_addr, ip_str);
2155 Log(LOG_WARNING, "Can't bind socket to %s: %s!", ip_str, strerror(errno));
2157 ng_ipaddr_setport(dest, Conf_Server[Server].port);
2158 res = connect(new_sock, (struct sockaddr *) dest, ng_ipaddr_salen(dest));
2159 if(( res != 0 ) && ( errno != EINPROGRESS )) {
2160 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
2162 Conf_Server[Server].conn_id = NONE;
2166 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)new_sock)) {
2168 "Cannot allocate memory for server connection (socket %d)",
2171 Conf_Server[Server].conn_id = NONE;
2175 if (!io_event_create( new_sock, IO_WANTWRITE, cb_connserver)) {
2176 Log(LOG_ALERT, "io_event_create(): could not add fd %d", strerror(errno));
2178 Conf_Server[Server].conn_id = NONE;
2182 My_Connections = array_start(&My_ConnArray);
2184 assert(My_Connections[new_sock].sock <= 0);
2186 Init_Conn_Struct(new_sock);
2188 ng_ipaddr_tostr_r(dest, ip_str);
2189 c = Client_NewLocal(new_sock, ip_str, CLIENT_UNKNOWNSERVER, false);
2191 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
2193 Conf_Server[Server].conn_id = NONE;
2197 /* Conn_Close() decrements this counter again */
2198 Account_Connection();
2199 Client_SetIntroducer( c, c );
2200 Client_SetToken( c, TOKEN_OUTBOUND );
2202 /* Register connection */
2203 if (!Conf_SetServer(Server, new_sock))
2205 My_Connections[new_sock].sock = new_sock;
2206 My_Connections[new_sock].addr = *dest;
2207 My_Connections[new_sock].client = c;
2208 strlcpy( My_Connections[new_sock].host, Conf_Server[Server].host,
2209 sizeof(My_Connections[new_sock].host ));
2212 if (Conf_Server[Server].SSLConnect && !ConnSSL_PrepareConnect( &My_Connections[new_sock],
2213 &Conf_Server[Server] ))
2215 Log(LOG_ALERT, "Could not initialize SSL for outgoing connection");
2216 Conn_Close( new_sock, "Could not initialize SSL for outgoing connection", NULL, false );
2217 Init_Conn_Struct( new_sock );
2218 Conf_Server[Server].conn_id = NONE;
2222 LogDebug("Registered new connection %d on socket %d (%ld in total).",
2223 new_sock, My_Connections[new_sock].sock, NumConnections);
2224 Conn_OPTION_ADD( &My_Connections[new_sock], CONN_ISCONNECTING );
2229 * Initialize connection structure.
2231 * @param Idx Connection index.
2234 Init_Conn_Struct(CONN_ID Idx)
2236 time_t now = time(NULL);
2238 memset(&My_Connections[Idx], 0, sizeof(CONNECTION));
2239 My_Connections[Idx].sock = -1;
2240 My_Connections[Idx].signon = now;
2241 My_Connections[Idx].lastdata = now;
2242 My_Connections[Idx].lastprivmsg = now;
2243 Proc_InitStruct(&My_Connections[Idx].proc_stat);
2246 My_Connections[Idx].iconv_from = (iconv_t)(-1);
2247 My_Connections[Idx].iconv_to = (iconv_t)(-1);
2249 } /* Init_Conn_Struct */
2253 * Initialize options of a new socket.
2255 * For example, we try to set socket options SO_REUSEADDR and IPTOS_LOWDELAY.
2256 * The socket is automatically closed if a fatal error is encountered.
2258 * @param Sock Socket handle.
2259 * @returns false if socket was closed due to fatal error.
2262 Init_Socket( int Sock )
2266 if (!io_setnonblock(Sock)) {
2267 Log( LOG_CRIT, "Can't enable non-blocking mode for socket: %s!", strerror( errno ));
2272 /* Don't block this port after socket shutdown */
2274 if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &value, (socklen_t)sizeof( value )) != 0 )
2276 Log( LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!", strerror( errno ));
2277 /* ignore this error */
2280 /* Set type of service (TOS) */
2281 #if defined(IPPROTO_IP) && defined(IPTOS_LOWDELAY)
2282 value = IPTOS_LOWDELAY;
2283 if (setsockopt(Sock, IPPROTO_IP, IP_TOS, &value,
2284 (socklen_t) sizeof(value))) {
2285 LogDebug("Can't set socket option IP_TOS: %s!",
2287 /* ignore this error */
2289 LogDebug("IP_TOS on socket %d has been set to IPTOS_LOWDELAY.",
2298 * Read results of a resolver sub-process and try to initiate a new server
2301 * @param fd File descriptor of the pipe to the sub-process.
2302 * @param events (ignored IO specification)
2305 cb_Connect_to_Server(int fd, UNUSED short events)
2307 /* Read result of resolver sub-process from pipe and start connection */
2310 ng_ipaddr_t dest_addrs[4]; /* we can handle at most 3; but we read up to
2311 four so we can log the 'more than we can handle'
2312 condition. First result is tried immediately, rest
2313 is saved for later if needed. */
2315 LogDebug("Resolver: Got forward lookup callback on fd %d, events %d", fd, events);
2317 for (i=0; i < MAX_SERVERS; i++) {
2318 if (Proc_GetPipeFd(&Conf_Server[i].res_stat) == fd )
2322 if( i >= MAX_SERVERS) {
2323 /* Ops, no matching server found?! */
2325 LogDebug("Resolver: Got Forward Lookup callback for unknown server!?");
2329 /* Read result from pipe */
2330 len = Proc_Read(&Conf_Server[i].res_stat, dest_addrs, sizeof(dest_addrs));
2331 Proc_Close(&Conf_Server[i].res_stat);
2333 /* Error resolving hostname: reset server structure */
2334 Conf_Server[i].conn_id = NONE;
2338 assert((len % sizeof(ng_ipaddr_t)) == 0);
2340 LogDebug("Got result from resolver: %u structs (%u bytes).", len/sizeof(ng_ipaddr_t), len);
2342 memset(&Conf_Server[i].dst_addr, 0, sizeof(Conf_Server[i].dst_addr));
2343 if (len > sizeof(ng_ipaddr_t)) {
2344 /* more than one address for this hostname, remember them
2345 * in case first address is unreachable/not available */
2346 len -= sizeof(ng_ipaddr_t);
2347 if (len > sizeof(Conf_Server[i].dst_addr)) {
2348 len = sizeof(Conf_Server[i].dst_addr);
2350 "Notice: Resolver returned more IP Addresses for host than we can handle, additional addresses dropped.");
2352 memcpy(&Conf_Server[i].dst_addr, &dest_addrs[1], len);
2355 New_Server(i, dest_addrs);
2356 } /* cb_Read_Forward_Lookup */
2360 * Read results of a resolver sub-process from the pipe and update the
2361 * appropriate connection/client structure(s): hostname and/or IDENT user name.
2363 * @param r_fd File descriptor of the pipe to the sub-process.
2364 * @param events (ignored IO specification)
2367 cb_Read_Resolver_Result( int r_fd, UNUSED short events )
2374 char readbuf[HOST_LEN + 2 + CLIENT_USER_LEN];
2377 char readbuf[HOST_LEN + 1];
2380 LogDebug("Resolver: Got callback on fd %d, events %d", r_fd, events );
2381 i = Conn_GetFromProc(r_fd);
2383 /* Ops, none found? Probably the connection has already
2384 * been closed!? We'll ignore that ... */
2386 LogDebug("Resolver: Got callback for unknown connection!?");
2390 /* Read result from pipe */
2391 len = Proc_Read(&My_Connections[i].proc_stat, readbuf, sizeof readbuf -1);
2392 Proc_Close(&My_Connections[i].proc_stat);
2396 readbuf[len] = '\0';
2397 identptr = strchr(readbuf, '\n');
2398 assert(identptr != NULL);
2400 Log( LOG_CRIT, "Resolver: Got malformed result!");
2405 LogDebug("Got result from resolver: \"%s\" (%u bytes read).", readbuf, len);
2406 /* Okay, we got a complete result: this is a host name for outgoing
2407 * connections and a host name and IDENT user name (if enabled) for
2408 * incoming connections.*/
2409 assert ( My_Connections[i].sock >= 0 );
2410 /* Incoming connection. Search client ... */
2411 c = Conn_GetClient( i );
2412 assert( c != NULL );
2414 /* Only update client information of unregistered clients.
2415 * Note: user commands (e. g. WEBIRC) are always read _after_ reading
2416 * the resolver results, so we don't have to worry to override settings
2417 * from these commands here. */
2418 if(Client_Type(c) == CLIENT_UNKNOWN) {
2419 strlcpy(My_Connections[i].host, readbuf,
2420 sizeof(My_Connections[i].host));
2421 Client_SetHostname(c, readbuf);
2422 if (Conf_NoticeAuth)
2423 (void)Conn_WriteStr(i,
2424 "NOTICE AUTH :*** Found your hostname: %s",
2425 My_Connections[i].host);
2431 if ((*ptr < '0' || *ptr > '9') &&
2432 (*ptr < 'A' || *ptr > 'Z') &&
2433 (*ptr < 'a' || *ptr > 'z'))
2438 /* Erroneous IDENT reply */
2440 "Got invalid IDENT reply for connection %d! Ignored.",
2444 "IDENT lookup for connection %d: \"%s\".",
2446 Client_SetUser(c, identptr, true);
2448 if (Conf_NoticeAuth) {
2449 (void)Conn_WriteStr(i,
2450 "NOTICE AUTH :*** Got %sident response%s%s",
2451 *ptr ? "invalid " : "",
2453 *ptr ? "" : identptr);
2455 } else if(Conf_Ident) {
2456 Log(LOG_INFO, "IDENT lookup for connection %d: no result.", i);
2457 if (Conf_NoticeAuth)
2458 (void)Conn_WriteStr(i,
2459 "NOTICE AUTH :*** No ident response");
2463 if (Conf_NoticeAuth) {
2464 /* Send buffered data to the client, but break on
2465 * errors because Handle_Write() would have closed
2466 * the connection again in this case! */
2467 if (!Handle_Write(i))
2471 Class_HandleServerBans(c);
2475 LogDebug("Resolver: discarding result for already registered connection %d.", i);
2477 } /* cb_Read_Resolver_Result */
2481 * Write a "simple" (error) message to a socket.
2483 * The message is sent without using the connection write buffers, without
2484 * compression/encryption, and even without any error reporting. It is
2485 * designed for error messages of e.g. New_Connection().
2487 * @param Sock Socket handle.
2488 * @param Msg Message string to send.
2491 Simple_Message(int Sock, const char *Msg)
2493 char buf[COMMAND_LEN];
2496 assert(Sock > NONE);
2497 assert(Msg != NULL);
2499 strlcpy(buf, Msg, sizeof buf - 2);
2500 len = strlcat(buf, "\r\n", sizeof buf);
2501 if (write(Sock, buf, len) < 0) {
2502 /* Because this function most probably got called to log
2503 * an error message, any write error is ignored here to
2504 * avoid an endless loop. But casting the result of write()
2505 * to "void" doesn't satisfy the GNU C code attribute
2506 * "warn_unused_result" which is used by some versions of
2507 * glibc (e.g. 2.11.1), therefore this silly error
2508 * "handling" code here :-( */
2511 } /* Simple_Error */
2515 * Get CLIENT structure that belongs to a local connection identified by its
2516 * index number. Each connection belongs to a client by definition, so it is
2517 * not required that the caller checks for NULL return values.
2519 * @param Idx Connection index number.
2520 * @returns Pointer to CLIENT structure.
2523 Conn_GetClient( CONN_ID Idx )
2528 c = array_get(&My_ConnArray, sizeof (CONNECTION), (size_t)Idx);
2530 return c ? c->client : NULL;
2534 * Get PROC_STAT sub-process structure of a connection.
2536 * @param Idx Connection index number.
2537 * @returns PROC_STAT structure.
2540 Conn_GetProcStat(CONN_ID Idx)
2545 c = array_get(&My_ConnArray, sizeof (CONNECTION), (size_t)Idx);
2547 return &c->proc_stat;
2548 } /* Conn_GetProcStat */
2552 * Get CONN_ID from file descriptor associated to a subprocess structure.
2554 * @param fd File descriptor.
2555 * @returns CONN_ID or NONE (-1).
2558 Conn_GetFromProc(int fd)
2563 for (i = 0; i < Pool_Size; i++) {
2564 if ((My_Connections[i].sock != NONE)
2565 && (Proc_GetPipeFd(&My_Connections[i].proc_stat) == fd))
2569 } /* Conn_GetFromProc */
2575 Conn_GetAuthPing(CONN_ID Idx)
2577 assert (Idx != NONE);
2578 return My_Connections[Idx].auth_ping;
2579 } /* Conn_GetAuthPing */
2582 Conn_SetAuthPing(CONN_ID Idx, long ID)
2584 assert (Idx != NONE);
2585 My_Connections[Idx].auth_ping = ID;
2586 } /* Conn_SetAuthPing */
2594 * Get information about used SSL cipher.
2596 * @param Idx Connection index number.
2597 * @param buf Buffer for returned information text.
2598 * @param len Size of return buffer "buf".
2599 * @returns true on success, false otherwise.
2602 Conn_GetCipherInfo(CONN_ID Idx, char *buf, size_t len)
2606 assert(Idx < (int) array_length(&My_ConnArray, sizeof(CONNECTION)));
2607 return ConnSSL_GetCipherInfo(&My_Connections[Idx], buf, len);
2612 * Check if a connection is SSL-enabled or not.
2614 * @param Idx Connection index number.
2615 * @return true if connection is SSL-enabled, false otherwise.
2618 Conn_UsesSSL(CONN_ID Idx)
2622 assert(Idx < (int) array_length(&My_ConnArray, sizeof(CONNECTION)));
2623 return Conn_OPTION_ISSET(&My_Connections[Idx], CONN_SSL);
2628 Conn_GetCertFp(CONN_ID Idx)
2632 assert(Idx < (int) array_length(&My_ConnArray, sizeof(CONNECTION)));
2633 return ConnSSL_GetCertFp(&My_Connections[Idx]);
2638 Conn_SetCertFp(CONN_ID Idx, const char *fingerprint)
2642 assert(Idx < (int) array_length(&My_ConnArray, sizeof(CONNECTION)));
2643 return ConnSSL_SetCertFp(&My_Connections[Idx], fingerprint);
2647 Conn_UsesSSL(UNUSED CONN_ID Idx)
2654 Conn_GetCertFp(UNUSED CONN_ID Idx)
2661 Conn_SetCertFp(UNUSED CONN_ID Idx, UNUSED const char *fingerprint)
2671 * Dump internal state of the "connection module".
2674 Conn_DebugDump(void)
2678 Log(LOG_DEBUG, "Connection status:");
2679 for (i = 0; i < Pool_Size; i++) {
2680 if (My_Connections[i].sock == NONE)
2683 " - %d: host=%s, lastdata=%ld, lastping=%ld, delaytime=%ld, flag=%d, options=%d, bps=%d, client=%s",
2684 My_Connections[i].sock, My_Connections[i].host,
2685 My_Connections[i].lastdata, My_Connections[i].lastping,
2686 My_Connections[i].delaytime, My_Connections[i].flag,
2687 My_Connections[i].options, My_Connections[i].bps,
2688 My_Connections[i].client ? Client_ID(My_Connections[i].client) : "-");
2690 } /* Conn_DumpClients */