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.
18 * Connection management
21 /* Additionan debug messages related to buffer handling: 0=off / 1=on */
22 #define DEBUG_BUFFER 0
36 #include <sys/socket.h>
38 #include <sys/types.h>
40 #include <netinet/in.h>
42 #ifdef HAVE_NETINET_IP_H
43 # ifdef HAVE_NETINET_IN_SYSTM_H
44 # include <netinet/in_systm.h>
46 # include <netinet/ip.h>
50 # include <tcpd.h> /* for TCP Wrappers */
58 # include "conn-encoding.h"
62 #include "conn-func.h"
65 #include "ng_ipaddr.h"
69 #define SERVER_WAIT (NONE - 1) /** "Wait for outgoing connection" flag */
71 #define MAX_COMMANDS 3 /** Max. commands per loop for users */
72 #define MAX_COMMANDS_SERVER_MIN 10 /** Min. commands per loop for servers */
73 #define MAX_COMMANDS_SERVICE 10 /** Max. commands per loop for services */
75 #define SD_LISTEN_FDS_START 3 /** systemd(8) socket activation offset */
77 #define THROTTLE_CMDS 1 /** Throttling: max commands reached */
78 #define THROTTLE_BPS 2 /** Throttling: max bps reached */
80 static bool Handle_Write PARAMS(( CONN_ID Idx ));
81 static bool Conn_Write PARAMS(( CONN_ID Idx, char *Data, size_t Len ));
82 static int New_Connection PARAMS(( int Sock, bool IsSSL ));
83 static CONN_ID Socket2Index PARAMS(( int Sock ));
84 static void Read_Request PARAMS(( CONN_ID Idx ));
85 static unsigned int Handle_Buffer PARAMS(( CONN_ID Idx ));
86 static void Check_Connections PARAMS(( void ));
87 static void Check_Servers PARAMS(( void ));
88 static void Init_Conn_Struct PARAMS(( CONN_ID Idx ));
89 static bool Init_Socket PARAMS(( int Sock ));
90 static void New_Server PARAMS(( int Server, ng_ipaddr_t *dest ));
91 static void Simple_Message PARAMS(( int Sock, const char *Msg ));
92 static int NewListener PARAMS(( const char *listen_addr, UINT16 Port ));
93 static void Account_Connection PARAMS((void));
94 static void Throttle_Connection PARAMS((const CONN_ID Idx, CLIENT *Client,
95 const int Reason, unsigned int Value));
97 static array My_Listeners;
98 static array My_ConnArray;
99 static size_t NumConnections, NumConnectionsMax, NumConnectionsAccepted;
102 int allow_severity = LOG_INFO;
103 int deny_severity = LOG_ERR;
106 static void server_login PARAMS((CONN_ID idx));
109 extern struct SSLOptions Conf_SSLOptions;
110 static bool SSL_WantRead PARAMS((const CONNECTION *c));
111 static bool SSL_WantWrite PARAMS((const CONNECTION *c));
112 static void cb_listen_ssl PARAMS((int sock, short irrelevant));
113 static void cb_connserver_login_ssl PARAMS((int sock, short what));
114 static void cb_clientserver_ssl PARAMS((int sock, short what));
116 static void cb_Read_Resolver_Result PARAMS((int sock, UNUSED short what));
117 static void cb_Connect_to_Server PARAMS((int sock, UNUSED short what));
118 static void cb_clientserver PARAMS((int sock, short what));
123 * Get number of sockets available from systemd(8).
125 * ngIRCd needs to implement its own sd_listen_fds(3) function and can't
126 * use the one provided by systemd itself, because the sockets will be
127 * used in a forked child process with a new PID, and this would trigger
128 * an error in the standard implementation.
130 * @return Number of sockets available, -1 if sockets have already been
131 * initialized, or 0 when no sockets have been passed.
134 my_sd_listen_fds(void)
139 /* Check if LISTEN_PID exists; but we ignore the result, because
140 * normally ngircd forks a child before checking this, and therefore
141 * the PID set in the environment is always wrong ... */
142 e = getenv("LISTEN_PID");
146 e = getenv("LISTEN_FDS");
151 unsetenv("LISTEN_FDS");
158 * IO callback for listening sockets: handle new connections. This callback
159 * gets called when a new non-SSL connection should be accepted.
161 * @param sock Socket descriptor.
162 * @param irrelevant (ignored IO specification)
165 cb_listen(int sock, short irrelevant)
168 (void) New_Connection(sock, false);
172 * IO callback for new outgoing non-SSL server connections.
174 * @param sock Socket descriptor.
175 * @param what IO specification (IO_WANTREAD/IO_WANTWRITE/...).
178 cb_connserver(int sock, UNUSED short what)
180 int res, err, server;
182 CONN_ID idx = Socket2Index( sock );
189 assert(what & IO_WANTWRITE);
191 /* Make sure that the server is still configured; it could have been
192 * removed in the meantime! */
193 server = Conf_GetServer(idx);
195 Log(LOG_ERR, "Connection on socket %d to \"%s\" aborted!",
196 sock, My_Connections[idx].host);
197 Conn_Close(idx, "Connection aborted", NULL, false);
201 /* connect() finished, get result. */
202 sock_len = (socklen_t)sizeof(err);
203 res = getsockopt(My_Connections[idx].sock, SOL_SOCKET, SO_ERROR,
205 assert(sock_len == sizeof(err));
207 /* Error while connecting? */
208 if ((res != 0) || (err != 0)) {
210 Log(LOG_CRIT, "getsockopt (connection %d): %s!",
211 idx, strerror(errno));
214 "Can't connect socket to \"%s:%d\" (connection %d): %s!",
215 My_Connections[idx].host, Conf_Server[server].port,
218 Conn_Close(idx, "Can't connect", NULL, false);
220 if (ng_ipaddr_af(&Conf_Server[server].dst_addr[0])) {
221 /* more addresses to try... */
222 New_Server(server, &Conf_Server[server].dst_addr[0]);
223 /* connection to dst_addr[0] is now in progress, so
224 * remove this address... */
225 Conf_Server[server].dst_addr[0] =
226 Conf_Server[server].dst_addr[1];
227 memset(&Conf_Server[server].dst_addr[1], 0,
228 sizeof(Conf_Server[server].dst_addr[1]));
233 /* connect() succeeded, remove all additional addresses */
234 memset(&Conf_Server[server].dst_addr, 0,
235 sizeof(Conf_Server[server].dst_addr));
237 Conn_OPTION_DEL( &My_Connections[idx], CONN_ISCONNECTING );
239 if ( Conn_OPTION_ISSET( &My_Connections[idx], CONN_SSL_CONNECT )) {
240 io_event_setcb( sock, cb_connserver_login_ssl );
241 io_event_add( sock, IO_WANTWRITE|IO_WANTREAD );
249 * Login to a remote server.
251 * @param idx Connection index.
254 server_login(CONN_ID idx)
257 "Connection %d (socket %d) with \"%s:%d\" established. Now logging in ...",
258 idx, My_Connections[idx].sock, My_Connections[idx].host,
259 Conf_Server[Conf_GetServer(idx)].port);
261 io_event_setcb( My_Connections[idx].sock, cb_clientserver);
262 io_event_add( My_Connections[idx].sock, IO_WANTREAD|IO_WANTWRITE);
264 /* Send PASS and SERVER command to peer */
265 Conn_WriteStr(idx, "PASS %s %s",
266 Conf_Server[Conf_GetServer( idx )].pwd_out, NGIRCd_ProtoID);
267 Conn_WriteStr(idx, "SERVER %s :%s",
268 Conf_ServerName, Conf_ServerInfo);
272 * IO callback for established non-SSL client and server connections.
274 * @param sock Socket descriptor.
275 * @param what IO specification (IO_WANTREAD/IO_WANTWRITE/...).
278 cb_clientserver(int sock, short what)
280 CONN_ID idx = Socket2Index(sock);
288 if (what & IO_WANTREAD
289 || (Conn_OPTION_ISSET(&My_Connections[idx], CONN_SSL_WANT_WRITE))) {
290 /* if TLS layer needs to write additional data, call
291 * Read_Request() instead so that SSL/TLS can continue */
295 if (what & IO_WANTREAD)
298 if (what & IO_WANTWRITE)
303 * Initialize connection module.
310 /* Initialize the "connection pool".
311 * FIXME: My_Connetions/Pool_Size is needed by other parts of the
312 * code; remove them! */
314 size = Conf_MaxConnections > 0 ? Conf_MaxConnections : CONNECTION_POOL;
315 if (Socket2Index(size) <= NONE) {
316 Log(LOG_EMERG, "Failed to initialize connection pool!");
320 /* Initialize "listener" array. */
321 array_free( &My_Listeners );
325 * Clean up connection module.
332 Conn_ExitListeners();
334 LogDebug("Shutting down all connections ..." );
335 for( idx = 0; idx < Pool_Size; idx++ ) {
336 if( My_Connections[idx].sock > NONE ) {
337 Conn_Close( idx, NULL, NGIRCd_SignalRestart ?
338 "Server going down (restarting)":"Server going down", true );
342 array_free(&My_ConnArray);
343 My_Connections = NULL;
345 io_library_shutdown();
349 * Close all sockets (file descriptors) of open connections.
350 * This is useful in forked child processes, for example, to make sure that
351 * they don't hold connections open that the main process wants to close.
354 Conn_CloseAllSockets(int ExceptOf)
358 for(idx = 0; idx < Pool_Size; idx++) {
359 if(My_Connections[idx].sock > NONE &&
360 My_Connections[idx].sock != ExceptOf)
361 close(My_Connections[idx].sock);
366 * Initialize listening ports.
368 * @param a Array containing the ports the daemon should listen on.
369 * @param listen_addr Address the socket should listen on (can be "0.0.0.0").
370 * @param func IO callback function to register.
371 * @returns Number of listening sockets created.
374 Init_Listeners(array *a, const char *listen_addr, void (*func)(int,short))
376 unsigned int created = 0;
381 len = array_length(a, sizeof (UINT16));
382 port = array_start(a);
384 fd = NewListener(listen_addr, *port);
389 if (!io_event_create( fd, IO_WANTREAD, func )) {
391 "io_event_create(): Can't add fd %d (port %u): %s!",
392 fd, (unsigned int) *port, strerror(errno));
404 * Initialize all listening sockets.
406 * @returns Number of created listening sockets
409 Conn_InitListeners( void )
411 /* Initialize ports on which the server should accept connections */
412 unsigned int created = 0;
413 char *af_str, *copy, *listen_addr;
414 int count, fd, i, addr_len;
417 assert(Conf_ListenAddress);
419 count = my_sd_listen_fds();
422 "Not re-initializing listening sockets of systemd(8) ...");
426 /* systemd(8) passed sockets to us, so don't try to initialize
427 * listening sockets on our own but use the passed ones */
428 LogDebug("Initializing %d systemd sockets ...", count);
429 for (i = 0; i < count; i++) {
430 fd = SD_LISTEN_FDS_START + i;
431 addr_len = (int)sizeof(addr);
432 getsockname(fd, (struct sockaddr *)&addr,
433 (socklen_t*)&addr_len);
435 if (addr.sin4.sin_family != AF_INET
436 && addr.sin4.sin_family != AF_INET6)
438 if (addr.sin4.sin_family != AF_INET)
441 /* Socket is of unsupported type! For example,
442 * systemd passed in an IPv6 socket but ngIRCd
443 * isn't compiled with IPv6 support. */
444 switch (addr.sin4.sin_family)
446 case AF_UNSPEC: af_str = "AF_UNSPEC"; break;
447 case AF_UNIX: af_str = "AF_UNIX"; break;
448 case AF_INET: af_str = "AF_INET"; break;
450 case AF_INET6: af_str = "AF_INET6"; break;
453 case AF_NETLINK: af_str = "AF_NETLINK"; break;
455 default: af_str = "unknown"; break;
458 "Socket %d is of unsupported type \"%s\" (%d), have to ignore it!",
459 fd, af_str, addr.sin4.sin_family);
465 if (!io_event_create(fd, IO_WANTREAD, cb_listen)) {
467 "io_event_create(): Can't add fd %d: %s!",
468 fd, strerror(errno));
472 "Initialized socket %d from systemd(8): %s:%d.", fd,
473 ng_ipaddr_tostr(&addr), ng_ipaddr_getport(&addr));
479 /* not using systemd socket activation, initialize listening sockets: */
481 /* can't use Conf_ListenAddress directly, see below */
482 copy = strdup(Conf_ListenAddress);
484 Log(LOG_CRIT, "Cannot copy %s: %s", Conf_ListenAddress,
488 listen_addr = strtok(copy, ",");
490 while (listen_addr) {
491 ngt_TrimStr(listen_addr);
493 created += Init_Listeners(&Conf_ListenPorts,
494 listen_addr, cb_listen);
496 created += Init_Listeners(&Conf_SSLOptions.ListenPorts,
497 listen_addr, cb_listen_ssl);
501 listen_addr = strtok(NULL, ",");
504 /* Can't free() Conf_ListenAddress here: on REHASH, if the config file
505 * cannot be re-loaded, we'd end up with a NULL Conf_ListenAddress.
506 * Instead, free() takes place in conf.c, before the config file
507 * is being parsed. */
511 } /* Conn_InitListeners */
514 * Shut down all listening sockets.
517 Conn_ExitListeners( void )
519 /* Close down all listening sockets */
523 /* Get number of listening sockets to shut down. There can be none
524 * if ngIRCd has been "socket activated" by systemd. */
525 arraylen = array_length(&My_Listeners, sizeof (int));
530 "Shutting down all listening sockets (%d total) ...", arraylen);
531 fd = array_start(&My_Listeners);
536 LogDebug("Listening socket %d closed.", *fd );
539 array_free(&My_Listeners);
540 } /* Conn_ExitListeners */
543 * Bind a socket to a specific (source) address.
545 * @param addr Address structure.
546 * @param listen_addrstr Source address as string.
547 * @param Port Port number.
548 * @returns true on success, false otherwise.
551 InitSinaddrListenAddr(ng_ipaddr_t *addr, const char *listen_addrstr, UINT16 Port)
555 ret = ng_ipaddr_init(addr, listen_addrstr, Port);
557 assert(listen_addrstr);
559 "Can't bind to [%s]:%u: can't convert ip address \"%s\"!",
560 listen_addrstr, Port, listen_addrstr);
566 * Set a socket to "IPv6 only". If the given socket doesn't belong to the
567 * AF_INET6 family, or the operating system doesn't support this functionality,
568 * this function retruns silently.
570 * @param af Address family of the socket.
571 * @param sock Socket handle.
574 set_v6_only(int af, int sock)
576 #if defined(IPV6_V6ONLY) && defined(WANT_IPV6)
582 if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, (socklen_t)sizeof(on)))
583 Log(LOG_ERR, "Could not set IPV6_V6ONLY: %s", strerror(errno));
591 * Initialize new listening port.
593 * @param listen_addr Local address to bind the socet to (can be 0.0.0.0).
594 * @param Port Port number on which the new socket should be listening.
595 * @returns file descriptor of the socket or -1 on failure.
598 NewListener(const char *listen_addr, UINT16 Port)
600 /* Create new listening socket on specified port */
604 if (!InitSinaddrListenAddr(&addr, listen_addr, Port))
607 af = ng_ipaddr_af(&addr);
608 sock = socket(af, SOCK_STREAM, 0);
610 Log(LOG_CRIT, "Can't create socket (af %d) : %s!", af,
615 set_v6_only(af, sock);
617 if (!Init_Socket(sock))
620 if (bind(sock, (struct sockaddr *)&addr, ng_ipaddr_salen(&addr)) != 0) {
621 Log(LOG_CRIT, "Can't bind socket to address %s:%d - %s!",
622 ng_ipaddr_tostr(&addr), Port, strerror(errno));
627 if (listen(sock, 10) != 0) {
628 Log(LOG_CRIT, "Can't listen on socket: %s!", strerror(errno));
633 /* keep fd in list so we can close it when ngircd restarts/shuts down */
634 if (!array_catb(&My_Listeners, (char *)&sock, sizeof(int))) {
635 Log(LOG_CRIT, "Can't add socket to My_Listeners array: %s!",
641 Log(LOG_INFO, "Now listening on [%s]:%d (socket %d).",
642 ng_ipaddr_tostr(&addr), Port, sock);
647 * "Main Loop": Loop until shutdown or restart is signalled.
649 * This function loops until a shutdown or restart of ngIRCd is signalled and
650 * calls io_dispatch() to check for readable and writable sockets every second.
651 * It checks for status changes on pending connections (e. g. when a hostname
652 * has been resolved), checks for "penalties" and timeouts, and handles the
663 while (!NGIRCd_SignalQuit && !NGIRCd_SignalRestart) {
666 /* Check configured servers and established links */
670 /* Expire outdated class/list items */
673 /* Look for non-empty read buffers ... */
674 for (i = 0; i < Pool_Size; i++) {
675 if ((My_Connections[i].sock > NONE)
676 && (array_bytes(&My_Connections[i].rbuf) > 0)) {
677 /* ... and try to handle the received data */
682 /* Look for non-empty write buffers ... */
683 for (i = 0; i < Pool_Size; i++) {
684 if (My_Connections[i].sock <= NONE)
687 wdatalen = array_bytes(&My_Connections[i].wbuf);
690 array_bytes(&My_Connections[i].zip.wbuf) > 0)
696 if (SSL_WantRead(&My_Connections[i]))
699 io_event_add(My_Connections[i].sock,
704 /* Check from which sockets we possibly could read ... */
705 for (i = 0; i < Pool_Size; i++) {
706 if (My_Connections[i].sock <= NONE)
709 if (SSL_WantWrite(&My_Connections[i]))
710 /* TLS/SSL layer needs to write data; deal
711 * with this first! */
714 if (Proc_InProgress(&My_Connections[i].proc_stat)) {
715 /* Wait for completion of forked subprocess
716 * and ignore the socket in the meantime ... */
717 io_event_del(My_Connections[i].sock,
722 if (Conn_OPTION_ISSET(&My_Connections[i], CONN_ISCONNECTING))
723 /* Wait for completion of connect() ... */
726 if (My_Connections[i].delaytime > t) {
727 /* There is a "penalty time" set: ignore socket! */
728 io_event_del(My_Connections[i].sock,
733 io_event_add(My_Connections[i].sock, IO_WANTREAD);
736 /* Set the timeout for reading from the network to 1 second,
737 * which is the granularity with witch we handle "penalty
738 * times" for example.
739 * Note: tv_sec/usec are undefined(!) after io_dispatch()
740 * returns, so we have to set it before each call to it! */
744 /* Wait for activity ... */
745 i = io_dispatch(&tv);
746 if (i == -1 && errno != EINTR) {
747 Log(LOG_EMERG, "Conn_Handler(): io_dispatch(): %s!",
749 Log(LOG_ALERT, "%s exiting due to fatal errors!",
754 /* Should ngIRCd timeout when idle? */
755 if (Conf_IdleTimeout > 0 && NumConnectionsAccepted > 0
756 && idle_t > 0 && time(NULL) - idle_t >= Conf_IdleTimeout) {
757 LogDebug("Server idle timeout reached: %d second%s. Initiating shutdown ...",
759 Conf_IdleTimeout == 1 ? "" : "s");
760 NGIRCd_SignalQuit = true;
764 if (NGIRCd_SignalQuit)
765 Log(LOG_NOTICE | LOG_snotice, "Server going down NOW!");
766 else if (NGIRCd_SignalRestart)
767 Log(LOG_NOTICE | LOG_snotice, "Server restarting NOW!");
771 * Write a text string into the socket of a connection.
773 * This function automatically appends CR+LF to the string and validates that
774 * the result is a valid IRC message (oversized messages are shortened, for
775 * example). Then it calls the Conn_Write() function to do the actual sending.
777 * @param Idx Index fo the connection.
778 * @param Format Format string, see printf().
779 * @returns true on success, false otherwise.
783 Conn_WriteStr(CONN_ID Idx, const char *Format, ...)
786 Conn_WriteStr(Idx, Format, va_alist)
792 char buffer[COMMAND_LEN];
801 assert( Idx > NONE );
802 assert( Format != NULL );
805 va_start( ap, Format );
809 r = vsnprintf(buffer, COMMAND_LEN - 2, Format, ap);
810 if (r >= COMMAND_LEN - 2 || r == -1) {
812 * The string that should be written to the socket is longer
813 * than the allowed size of COMMAND_LEN bytes (including both
814 * the CR and LF characters). This can be caused by the
815 * IRC_WriteXXX() functions when the prefix of this server had
816 * to be added to an already "quite long" command line which
817 * has been received from a regular IRC client, for example.
819 * We are not allowed to send such "oversized" messages to
820 * other servers and clients, see RFC 2812 2.3 and 2813 3.3
821 * ("these messages SHALL NOT exceed 512 characters in length,
822 * counting all characters including the trailing CR-LF").
824 * So we have a big problem here: we should send more bytes
825 * to the network than we are allowed to and we don't know
826 * the originator (any more). The "old" behavior of blaming
827 * the receiver ("next hop") is a bad idea (it could be just
828 * an other server only routing the message!), so the only
829 * option left is to shorten the string and to hope that the
830 * result is still somewhat useful ...
833 * C99 states that vsnprintf() "returns the number of characters
834 * that would have been printed if the n were unlimited"; but
835 * according to the Linux manual page "glibc until 2.0.6 would
836 * return -1 when the output was truncated" -- so we have to
837 * handle both cases ...
841 strcpy (buffer + sizeof(buffer) - strlen(CUT_TXTSUFFIX) - 2 - 1,
846 ptr = strchr(buffer + 1, ':');
849 message = Conn_EncodingTo(Idx, ptr);
851 strlcpy(ptr, message, sizeof(buffer) - (ptr - buffer));
857 Log(LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer);
860 len = strlcat( buffer, "\r\n", sizeof( buffer ));
861 ok = Conn_Write(Idx, buffer, len);
862 My_Connections[Idx].msg_out++;
866 } /* Conn_WriteStr */
869 Conn_Password( CONN_ID Idx )
871 assert( Idx > NONE );
872 if (My_Connections[Idx].pwd == NULL)
875 return My_Connections[Idx].pwd;
876 } /* Conn_Password */
879 Conn_SetPassword( CONN_ID Idx, const char *Pwd )
881 assert( Idx > NONE );
883 if (My_Connections[Idx].pwd)
884 free(My_Connections[Idx].pwd);
886 My_Connections[Idx].pwd = strdup(Pwd);
887 if (My_Connections[Idx].pwd == NULL) {
888 Log(LOG_EMERG, "Can't allocate memory! [Conn_SetPassword]");
891 } /* Conn_SetPassword */
894 * Append Data to the outbound write buffer of a connection.
896 * @param Idx Index of the connection.
897 * @param Data pointer to the data.
898 * @param Len length of Data.
899 * @returns true on success, false otherwise.
902 Conn_Write( CONN_ID Idx, char *Data, size_t Len )
905 size_t writebuf_limit = WRITEBUFFER_MAX_LEN;
906 assert( Idx > NONE );
907 assert( Data != NULL );
910 /* Is the socket still open? A previous call to Conn_Write()
911 * may have closed the connection due to a fatal error.
912 * In this case it is sufficient to return an error, as well. */
913 if (My_Connections[Idx].sock <= NONE) {
914 LogDebug("Skipped write on closed socket (connection %d).", Idx);
918 /* Make sure that there still exists a CLIENT structure associated
919 * with this connection and check if this is a server or not: */
920 c = Conn_GetClient(Idx);
922 /* Servers do get special write buffer limits, so they can
923 * generate all the messages that are required while peering. */
924 if (Client_Type(c) == CLIENT_SERVER)
925 writebuf_limit = WRITEBUFFER_SLINK_LEN;
927 LogDebug("Write on socket without client (connection %d)!?", Idx);
930 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
932 * Zip_Buffer() does all the dirty work for us: it flushes
933 * the (pre-)compression buffers if required and handles
934 * all error conditions. */
935 if (!Zip_Buffer(Idx, Data, Len))
941 /* Uncompressed link:
942 * Check if outbound buffer has enough space for the data. */
943 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
944 WRITEBUFFER_FLUSH_LEN) {
945 /* Buffer is full, flush it. Handle_Write deals with
946 * low-level errors, if any. */
947 if (!Handle_Write(Idx))
951 /* When the write buffer is still too big after flushing it,
952 * the connection will be killed. */
953 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
956 "Write buffer space exhausted (connection %d, limit is %lu bytes, %lu bytes new, %lu bytes pending)",
957 Idx, writebuf_limit, Len,
958 (unsigned long)array_bytes(&My_Connections[Idx].wbuf));
959 Conn_Close(Idx, "Write buffer space exhausted", NULL, false);
963 /* Copy data to write buffer */
964 if (!array_catb(&My_Connections[Idx].wbuf, Data, Len))
967 My_Connections[Idx].bytes_out += Len;
970 /* Adjust global write counter */
977 * Shut down a connection.
979 * @param Idx Connection index.
980 * @param LogMsg Message to write to the log or NULL. If no LogMsg
981 * is given, the FwdMsg is logged.
982 * @param FwdMsg Message to forward to remote servers.
983 * @param InformClient If true, inform the client on the connection which is
984 * to be shut down of the reason (FwdMsg) and send
985 * connection statistics before disconnecting it.
988 Conn_Close(CONN_ID Idx, const char *LogMsg, const char *FwdMsg, bool InformClient)
990 /* Close connection. Open pipes of asynchronous resolver
991 * sub-processes are closed down. */
997 double in_z_k, out_z_k;
1001 assert( Idx > NONE );
1003 /* Is this link already shutting down? */
1004 if( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ISCLOSING )) {
1005 /* Conn_Close() has been called recursively for this link;
1006 * probable reason: Handle_Write() failed -- see below. */
1007 LogDebug("Recursive request to close connection %d!", Idx );
1011 assert( My_Connections[Idx].sock > NONE );
1013 /* Mark link as "closing" */
1014 Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCLOSING );
1016 port = ng_ipaddr_getport(&My_Connections[Idx].addr);
1017 Log(LOG_INFO, "Shutting down connection %d (%s) with \"%s:%d\" ...", Idx,
1018 LogMsg ? LogMsg : FwdMsg, My_Connections[Idx].host, port);
1020 /* Search client, if any */
1021 c = Conn_GetClient( Idx );
1023 /* Should the client be informed? */
1026 /* Send statistics to client if registered as user: */
1027 if ((c != NULL) && (Client_Type(c) == CLIENT_USER)) {
1029 ":%s NOTICE %s :%sConnection statistics: client %.1f kb, server %.1f kb.",
1030 Client_ID(Client_ThisServer()), Client_ID(c),
1032 (double)My_Connections[Idx].bytes_in / 1024,
1033 (double)My_Connections[Idx].bytes_out / 1024);
1036 /* Send ERROR to client (see RFC 2812, section 3.1.7) */
1038 Conn_WriteStr(Idx, "ERROR :%s", FwdMsg);
1040 Conn_WriteStr(Idx, "ERROR :Closing connection");
1043 /* Try to write out the write buffer. Note: Handle_Write() eventually
1044 * removes the CLIENT structure associated with this connection if an
1045 * error occurs! So we have to re-check if there is still an valid
1046 * CLIENT structure after calling Handle_Write() ...*/
1047 (void)Handle_Write( Idx );
1049 /* Search client, if any (re-check!) */
1050 c = Conn_GetClient( Idx );
1052 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_SSL )) {
1053 LogDebug("SSL connection %d shutting down ...", Idx);
1054 ConnSSL_Free(&My_Connections[Idx]);
1057 /* Shut down socket */
1058 if (! io_close(My_Connections[Idx].sock)) {
1059 /* Oops, we can't close the socket!? This is ... ugly! */
1061 "Error closing connection %d (socket %d) with %s:%d - %s! (ignored)",
1062 Idx, My_Connections[Idx].sock, My_Connections[Idx].host,
1063 port, strerror(errno));
1066 /* Mark socket as invalid: */
1067 My_Connections[Idx].sock = NONE;
1069 /* If there is still a client, unregister it now */
1071 Client_Destroy(c, LogMsg, FwdMsg, true);
1073 /* Calculate statistics and log information */
1074 in_k = (double)My_Connections[Idx].bytes_in / 1024;
1075 out_k = (double)My_Connections[Idx].bytes_out / 1024;
1077 if (Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP)) {
1078 in_z_k = (double)My_Connections[Idx].zip.bytes_in / 1024;
1079 out_z_k = (double)My_Connections[Idx].zip.bytes_out / 1024;
1080 /* Make sure that no division by zero can occur during
1081 * the calculation of in_p and out_p: in_z_k and out_z_k
1082 * are non-zero, that's guaranteed by the protocol until
1083 * compression can be enabled. */
1088 in_p = (int)(( in_k * 100 ) / in_z_k );
1089 out_p = (int)(( out_k * 100 ) / out_z_k );
1091 "Connection %d with \"%s:%d\" closed (in: %.1fk/%.1fk/%d%%, out: %.1fk/%.1fk/%d%%).",
1092 Idx, My_Connections[Idx].host, port,
1093 in_k, in_z_k, in_p, out_k, out_z_k, out_p);
1099 "Connection %d with \"%s:%d\" closed (in: %.1fk, out: %.1fk).",
1100 Idx, My_Connections[Idx].host, port,
1104 /* Servers: Modify time of next connect attempt? */
1105 Conf_UnsetServer( Idx );
1108 /* Clean up zlib, if link was compressed */
1109 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
1110 inflateEnd( &My_Connections[Idx].zip.in );
1111 deflateEnd( &My_Connections[Idx].zip.out );
1112 array_free(&My_Connections[Idx].zip.rbuf);
1113 array_free(&My_Connections[Idx].zip.wbuf);
1117 array_free(&My_Connections[Idx].rbuf);
1118 array_free(&My_Connections[Idx].wbuf);
1119 if (My_Connections[Idx].pwd != NULL)
1120 free(My_Connections[Idx].pwd);
1122 /* Clean up connection structure (=free it) */
1123 Init_Conn_Struct( Idx );
1125 assert(NumConnections > 0);
1128 LogDebug("Shutdown of connection %d completed, %ld connection%s left.",
1129 Idx, NumConnections, NumConnections != 1 ? "s" : "");
1131 idle_t = NumConnections > 0 ? 0 : time(NULL);
1135 * Get current number of connections.
1137 * @returns Number of current connections.
1142 return NumConnections;
1146 * Get number of maximum simultaneous connections.
1148 * @returns Number of maximum simultaneous connections.
1153 return NumConnectionsMax;
1154 } /* Conn_CountMax */
1157 * Get number of connections accepted since the daemon startet.
1159 * @returns Number of connections accepted.
1162 Conn_CountAccepted(void)
1164 return NumConnectionsAccepted;
1165 } /* Conn_CountAccepted */
1168 * Synchronize established connections and configured server structures
1169 * after a configuration update and store the correct connection IDs, if any.
1172 Conn_SyncServerStruct(void)
1178 for (i = 0; i < Pool_Size; i++) {
1179 if (My_Connections[i].sock == NONE)
1183 client = Conn_GetClient(i);
1184 if (!client || Client_Type(client) != CLIENT_SERVER)
1187 for (c = 0; c < MAX_SERVERS; c++) {
1188 /* Configured server? */
1189 if (!Conf_Server[c].host[0])
1192 if (strcasecmp(Conf_Server[c].name, Client_ID(client)) == 0)
1193 Conf_Server[c].conn_id = i;
1196 } /* SyncServerStruct */
1199 * Get IP address string of a connection.
1201 * @param Idx Connection index.
1202 * @return Pointer to a global buffer containing the IP address as string.
1205 Conn_GetIPAInfo(CONN_ID Idx)
1208 return ng_ipaddr_tostr(&My_Connections[Idx].addr);
1212 * Send out data of write buffer; connect new sockets.
1214 * @param Idx Connection index.
1215 * @returns true on success, false otherwise.
1218 Handle_Write( CONN_ID Idx )
1223 assert( Idx > NONE );
1224 if ( My_Connections[Idx].sock < 0 ) {
1225 LogDebug("Handle_Write() on closed socket, connection %d", Idx);
1228 assert( My_Connections[Idx].sock > NONE );
1230 wdatalen = array_bytes(&My_Connections[Idx].wbuf );
1233 if (wdatalen == 0) {
1234 /* Write buffer is empty, so we try to flush the compression
1235 * buffer and get some data to work with from there :-) */
1236 if (!Zip_Flush(Idx))
1239 /* Now the write buffer most probably has changed: */
1240 wdatalen = array_bytes(&My_Connections[Idx].wbuf);
1244 if (wdatalen == 0) {
1245 /* Still no data, fine. */
1246 io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
1252 ("Handle_Write() called for connection %d, %ld bytes pending ...",
1257 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_SSL )) {
1258 len = ConnSSL_Write(&My_Connections[Idx],
1259 array_start(&My_Connections[Idx].wbuf),
1264 len = write(My_Connections[Idx].sock,
1265 array_start(&My_Connections[Idx].wbuf), wdatalen );
1268 if (errno == EAGAIN || errno == EINTR)
1271 if (!Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ISCLOSING))
1273 "Write error on connection %d (socket %d): %s!",
1274 Idx, My_Connections[Idx].sock, strerror(errno));
1276 LogDebug("Recursive write error on connection %d (socket %d): %s!",
1277 Idx, My_Connections[Idx].sock, strerror(errno));
1278 Conn_Close(Idx, "Write error", NULL, false);
1282 /* move any data not yet written to beginning */
1283 array_moveleft(&My_Connections[Idx].wbuf, 1, (size_t)len);
1286 } /* Handle_Write */
1289 * Count established connections to a specific IP address.
1291 * @returns Number of established connections.
1294 Count_Connections(ng_ipaddr_t *a)
1299 for (i = 0; i < Pool_Size; i++) {
1300 if (My_Connections[i].sock <= NONE)
1302 if (ng_ipaddr_ipequal(&My_Connections[i].addr, a))
1306 } /* Count_Connections */
1309 * Initialize new client connection on a listening socket.
1311 * @param Sock Listening socket descriptor.
1312 * @param IsSSL true if this socket expects SSL-encrypted data.
1313 * @returns Accepted socket descriptor or -1 on error.
1316 New_Connection(int Sock, UNUSED bool IsSSL)
1319 struct request_info req;
1321 ng_ipaddr_t new_addr;
1322 char ip_str[NG_INET_ADDRSTRLEN];
1323 int new_sock, new_sock_len;
1327 assert(Sock > NONE);
1329 LogDebug("Accepting new connection on socket %d ...", Sock);
1331 new_sock_len = (int)sizeof(new_addr);
1332 new_sock = accept(Sock, (struct sockaddr *)&new_addr,
1333 (socklen_t *)&new_sock_len);
1335 Log(LOG_CRIT, "Can't accept connection: %s!", strerror(errno));
1338 NumConnectionsAccepted++;
1340 if (!ng_ipaddr_tostr_r(&new_addr, ip_str)) {
1341 Log(LOG_CRIT, "fd %d: Can't convert IP address!", new_sock);
1342 Simple_Message(new_sock, "ERROR :Internal Server Error");
1348 /* Validate socket using TCP Wrappers */
1349 request_init(&req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock,
1350 RQ_CLIENT_SIN, &new_addr, NULL);
1352 if (!hosts_access(&req)) {
1354 "Refused connection from %s (by TCP Wrappers)!", ip_str);
1355 Simple_Message(new_sock, "ERROR :Connection refused");
1361 if (!Init_Socket(new_sock))
1364 /* Check global connection limit */
1365 if ((Conf_MaxConnections > 0) &&
1366 (NumConnections >= (size_t) Conf_MaxConnections)) {
1367 Log(LOG_ALERT, "Can't accept new connection on socket %d: Limit (%d) reached!",
1368 Sock, Conf_MaxConnections);
1369 Simple_Message(new_sock, "ERROR :Connection limit reached");
1374 /* Check IP-based connection limit */
1375 cnt = Count_Connections(&new_addr);
1376 if ((Conf_MaxConnectionsIP > 0) && (cnt >= Conf_MaxConnectionsIP)) {
1377 /* Access denied, too many connections from this IP address! */
1379 "Refused connection from %s: too may connections (%ld) from this IP address!",
1381 Simple_Message(new_sock,
1382 "ERROR :Connection refused, too many connections from your IP address");
1387 if (Socket2Index(new_sock) <= NONE) {
1388 Simple_Message(new_sock, "ERROR: Internal error");
1393 /* register callback */
1394 if (!io_event_create(new_sock, IO_WANTREAD, cb_clientserver)) {
1396 "Can't accept connection: io_event_create failed!");
1397 Simple_Message(new_sock, "ERROR :Internal error");
1402 c = Client_NewLocal(new_sock, NULL, CLIENT_UNKNOWN, false);
1405 "Can't accept connection: can't create client structure!");
1406 Simple_Message(new_sock, "ERROR :Internal error");
1411 Init_Conn_Struct(new_sock);
1412 My_Connections[new_sock].sock = new_sock;
1413 My_Connections[new_sock].addr = new_addr;
1414 My_Connections[new_sock].client = c;
1416 /* Set initial hostname to IP address. This becomes overwritten when
1417 * the DNS lookup is enabled and succeeds, but is used otherwise. */
1418 if (ng_ipaddr_af(&new_addr) != AF_INET)
1419 snprintf(My_Connections[new_sock].host,
1420 sizeof(My_Connections[new_sock].host), "[%s]", ip_str);
1422 strlcpy(My_Connections[new_sock].host, ip_str,
1423 sizeof(My_Connections[new_sock].host));
1425 Client_SetHostname(c, My_Connections[new_sock].host);
1427 Log(LOG_INFO, "Accepted connection %d from \"%s:%d\" on socket %d.",
1428 new_sock, My_Connections[new_sock].host,
1429 ng_ipaddr_getport(&new_addr), Sock);
1430 Account_Connection();
1433 /* Delay connection initalization until SSL handshake is finished */
1436 Conn_StartLogin(new_sock);
1439 } /* New_Connection */
1442 * Finish connection initialization, start resolver subprocess.
1444 * @param Idx Connection index.
1447 Conn_StartLogin(CONN_ID Idx)
1449 int ident_sock = -1;
1453 /* Nothing to do if DNS (and resolver subprocess) is disabled */
1458 /* Should we make an IDENT request? */
1460 ident_sock = My_Connections[Idx].sock;
1463 if (Conf_NoticeBeforeRegistration) {
1464 /* Send "NOTICE *" messages to the client */
1467 (void)Conn_WriteStr(Idx,
1468 "NOTICE * :*** Looking up your hostname and checking ident");
1471 (void)Conn_WriteStr(Idx,
1472 "NOTICE * :*** Looking up your hostname");
1473 /* Send buffered data to the client, but break on errors
1474 * because Handle_Write() would have closed the connection
1475 * again in this case! */
1476 if (!Handle_Write(Idx))
1480 Resolve_Addr(&My_Connections[Idx].proc_stat, &My_Connections[Idx].addr,
1481 ident_sock, cb_Read_Resolver_Result);
1485 * Update global connection counters.
1488 Account_Connection(void)
1492 if (NumConnections > NumConnectionsMax)
1493 NumConnectionsMax = NumConnections;
1494 LogDebug("Total number of connections now %lu (max %lu).",
1495 NumConnections, NumConnectionsMax);
1496 } /* Account_Connection */
1499 * Translate socket handle into connection index (for historical reasons, it is
1500 * a 1:1 mapping today) and enlarge the "connection pool" accordingly.
1502 * @param Sock Socket handle.
1503 * @returns Connecion index or NONE when the pool is too small.
1506 Socket2Index( int Sock )
1509 assert(Pool_Size >= 0);
1511 if (Sock < Pool_Size)
1514 /* Try to allocate more memory ... */
1515 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)Sock)) {
1517 "Can't allocate memory to enlarge connection pool!");
1520 LogDebug("Enlarged connection pool for %ld sockets (%ld items, %ld bytes)",
1521 Sock, array_length(&My_ConnArray, sizeof(CONNECTION)),
1522 array_bytes(&My_ConnArray));
1524 /* Adjust pointer to new block, update size and initialize new items. */
1525 My_Connections = array_start(&My_ConnArray);
1526 while (Pool_Size <= Sock)
1527 Init_Conn_Struct(Pool_Size++);
1533 * Read data from the network to the read buffer. If an error occurs,
1534 * the socket of this connection will be shut down.
1536 * @param Idx Connection index.
1539 Read_Request( CONN_ID Idx )
1542 static const unsigned int maxbps = COMMAND_LEN / 2;
1543 char readbuf[READBUFFER_LEN];
1546 assert( Idx > NONE );
1547 assert( My_Connections[Idx].sock > NONE );
1550 if ((array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN) ||
1551 (array_bytes(&My_Connections[Idx].zip.rbuf) >= READBUFFER_LEN))
1553 if (array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN)
1556 /* Read buffer is full */
1558 "Receive buffer space exhausted (connection %d): %d/%d bytes",
1559 Idx, array_bytes(&My_Connections[Idx].rbuf), READBUFFER_LEN);
1560 Conn_Close(Idx, "Receive buffer space exhausted", NULL, false);
1565 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_SSL))
1566 len = ConnSSL_Read( &My_Connections[Idx], readbuf, sizeof(readbuf));
1569 len = read(My_Connections[Idx].sock, readbuf, sizeof(readbuf));
1571 LogDebug("Client \"%s:%u\" is closing connection %d ...",
1572 My_Connections[Idx].host,
1573 ng_ipaddr_getport(&My_Connections[Idx].addr), Idx);
1574 Conn_Close(Idx, NULL, "Client closed connection", false);
1579 if( errno == EAGAIN ) return;
1580 Log(LOG_ERR, "Read error on connection %d (socket %d): %s!",
1581 Idx, My_Connections[Idx].sock, strerror(errno));
1582 Conn_Close(Idx, "Read error", "Client closed connection",
1587 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1588 if (!array_catb(&My_Connections[Idx].zip.rbuf, readbuf,
1591 "Could not append received data to zip input buffer (connection %d): %d bytes!",
1593 Conn_Close(Idx, "Receive buffer space exhausted", NULL,
1600 if (!array_catb( &My_Connections[Idx].rbuf, readbuf, len)) {
1602 "Could not append received data to input buffer (connection %d): %d bytes!",
1604 Conn_Close(Idx, "Receive buffer space exhausted", NULL,
1609 /* Update connection statistics */
1610 My_Connections[Idx].bytes_in += len;
1612 /* Handle read buffer */
1613 My_Connections[Idx].bps += Handle_Buffer(Idx);
1615 /* Make sure that there is still a valid client registered */
1616 c = Conn_GetClient(Idx);
1620 /* Update timestamp of last data received if this connection is
1621 * registered as a user, server or service connection. Don't update
1622 * otherwise, so users have at least Conf_PongTimeout seconds time to
1623 * register with the IRC server -- see Check_Connections().
1624 * Update "lastping", too, if time shifted backwards ... */
1625 if (Client_Type(c) == CLIENT_USER
1626 || Client_Type(c) == CLIENT_SERVER
1627 || Client_Type(c) == CLIENT_SERVICE) {
1629 if (My_Connections[Idx].lastdata != t)
1630 My_Connections[Idx].bps = 0;
1632 My_Connections[Idx].lastdata = t;
1633 if (My_Connections[Idx].lastping > t)
1634 My_Connections[Idx].lastping = t;
1637 /* Look at the data in the (read-) buffer of this connection */
1638 if (My_Connections[Idx].bps >= maxbps)
1639 Throttle_Connection(Idx, c, THROTTLE_BPS, maxbps);
1640 } /* Read_Request */
1643 * Handle all data in the connection read-buffer.
1645 * Data is processed until no complete command is left in the read buffer,
1646 * or MAX_COMMANDS[_SERVER|_SERVICE] commands were processed.
1647 * When a fatal error occurs, the connection is shut down.
1649 * @param Idx Index of the connection.
1650 * @returns Number of bytes processed.
1653 Handle_Buffer(CONN_ID Idx)
1656 char *ptr1, *ptr2, *first_eol;
1664 unsigned int i, maxcmd = MAX_COMMANDS, len_processed = 0;
1667 c = Conn_GetClient(Idx);
1668 starttime = time(NULL);
1672 /* Servers get special command limits that depend on the user count */
1673 switch (Client_Type(c)) {
1675 maxcmd = (int)(Client_UserCount() / 5)
1676 + MAX_COMMANDS_SERVER_MIN;
1677 /* Allow servers to handle even more commands while peering
1678 * to speed up server login and network synchronization. */
1679 if (Conn_LastPing(Idx) == 0)
1682 case CLIENT_SERVICE:
1683 maxcmd = MAX_COMMANDS_SERVICE;
1686 if (Client_HasMode(c, 'F'))
1687 maxcmd = MAX_COMMANDS_SERVICE;
1691 for (i=0; i < maxcmd; i++) {
1693 if (My_Connections[Idx].delaytime > starttime)
1696 /* Unpack compressed data, if compression is in use */
1697 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1698 /* When unzipping fails, Unzip_Buffer() shuts
1699 * down the connection itself */
1700 if (!Unzip_Buffer(Idx))
1705 if (0 == array_bytes(&My_Connections[Idx].rbuf))
1708 /* Make sure that the buffer is NULL terminated */
1709 if (!array_cat0_temporary(&My_Connections[Idx].rbuf)) {
1710 Conn_Close(Idx, NULL,
1711 "Can't allocate memory [Handle_Buffer]",
1716 /* RFC 2812, section "2.3 Messages", 5th paragraph:
1717 * "IRC messages are always lines of characters terminated
1718 * with a CR-LF (Carriage Return - Line Feed) pair [...]". */
1720 ptr = strstr(array_start(&My_Connections[Idx].rbuf), "\r\n");
1723 /* Check for non-RFC-compliant request (only CR or LF)?
1724 * Unfortunately, there are quite a few clients out there
1725 * that do this -- e. g. mIRC, BitchX, and Trillian :-( */
1726 ptr1 = strchr(array_start(&My_Connections[Idx].rbuf), '\r');
1727 ptr2 = strchr(array_start(&My_Connections[Idx].rbuf), '\n');
1729 /* Check if there is a single CR or LF _before_ the
1730 * correct CR+LF line terminator: */
1731 first_eol = ptr1 < ptr2 ? ptr1 : ptr2;
1732 if (first_eol < ptr) {
1733 /* Single CR or LF before CR+LF found */
1737 } else if (ptr1 || ptr2) {
1738 /* No CR+LF terminated command found, but single
1739 * CR or LF found ... */
1741 ptr = ptr1 < ptr2 ? ptr1 : ptr2;
1743 ptr = ptr1 ? ptr1 : ptr2;
1751 /* Complete (=line terminated) request found, handle it! */
1754 len = ptr - (char *)array_start(&My_Connections[Idx].rbuf) + delta;
1756 if (len > (COMMAND_LEN - 1)) {
1757 /* Request must not exceed 512 chars (incl. CR+LF!),
1758 * see RFC 2812. Disconnect Client if this happens. */
1760 "Request too long (connection %d): %d bytes (max. %d expected)!",
1761 Idx, array_bytes(&My_Connections[Idx].rbuf),
1763 Conn_Close(Idx, NULL, "Request too long", true);
1767 len_processed += (unsigned int)len;
1769 /* Request is empty (only '\r\n', '\r' or '\n');
1770 * delta is 2 ('\r\n') or 1 ('\r' or '\n'), see above */
1771 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1775 /* remember if stream is already compressed */
1776 old_z = My_Connections[Idx].options & CONN_ZIP;
1779 My_Connections[Idx].msg_in++;
1781 (Idx, (char *)array_start(&My_Connections[Idx].rbuf)))
1782 return 0; /* error -> connection has been closed */
1784 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1786 if ((!old_z) && (My_Connections[Idx].options & CONN_ZIP) &&
1787 (array_bytes(&My_Connections[Idx].rbuf) > 0)) {
1788 /* The last command activated socket compression.
1789 * Data that was read after that needs to be copied
1790 * to the unzip buffer for decompression: */
1792 (&My_Connections[Idx].zip.rbuf,
1793 &My_Connections[Idx].rbuf)) {
1794 Conn_Close(Idx, NULL,
1795 "Can't allocate memory [Handle_Buffer]",
1800 array_trunc(&My_Connections[Idx].rbuf);
1802 ("Moved already received data (%u bytes) to uncompression buffer.",
1803 array_bytes(&My_Connections[Idx].zip.rbuf));
1808 LogDebug("Connection %d: Processed %ld commands (max=%ld), %ld bytes. %ld bytes left in read buffer.",
1809 Idx, i, maxcmd, len_processed,
1810 array_bytes(&My_Connections[Idx].rbuf));
1813 /* If data has been processed but there is still data in the read
1814 * buffer, the command limit triggered. Enforce the penalty time: */
1815 if (len_processed && array_bytes(&My_Connections[Idx].rbuf) > 2)
1816 Throttle_Connection(Idx, c, THROTTLE_CMDS, maxcmd);
1818 return len_processed;
1819 } /* Handle_Buffer */
1822 * Check whether established connections are still alive or not.
1823 * If not, play PING-PONG first; and if that doesn't help either,
1824 * disconnect the respective peer.
1827 Check_Connections(void)
1833 for (i = 0; i < Pool_Size; i++) {
1834 if (My_Connections[i].sock < 0)
1837 c = Conn_GetClient(i);
1838 if (c && ((Client_Type(c) == CLIENT_USER)
1839 || (Client_Type(c) == CLIENT_SERVER)
1840 || (Client_Type(c) == CLIENT_SERVICE))) {
1841 /* connected User, Server or Service */
1842 if (My_Connections[i].lastping >
1843 My_Connections[i].lastdata) {
1844 /* We already sent a ping */
1845 if (My_Connections[i].lastping <
1846 time(NULL) - Conf_PongTimeout) {
1848 snprintf(msg, sizeof(msg),
1849 "Ping timeout: %d seconds",
1851 LogDebug("Connection %d: %s.", i, msg);
1852 Conn_Close(i, NULL, msg, true);
1854 } else if (My_Connections[i].lastdata <
1855 time(NULL) - Conf_PingTimeout) {
1856 /* We need to send a PING ... */
1857 LogDebug("Connection %d: sending PING ...", i);
1859 Conn_WriteStr(i, "PING :%s",
1860 Client_ID(Client_ThisServer()));
1863 /* The connection is not fully established yet, so
1864 * we don't do the PING-PONG game here but instead
1865 * disconnect the client after "a short time" if it's
1866 * still not registered. */
1868 if (My_Connections[i].lastdata <
1869 time(NULL) - Conf_PongTimeout) {
1871 ("Unregistered connection %d timed out ...",
1873 Conn_Close(i, NULL, "Timeout", false);
1877 } /* Check_Connections */
1880 * Check if further server links should be established.
1888 time_now = time(NULL);
1890 /* Check all configured servers */
1891 for (i = 0; i < MAX_SERVERS; i++) {
1892 if (Conf_Server[i].conn_id != NONE)
1893 continue; /* Already establishing or connected */
1894 if (!Conf_Server[i].host[0] || Conf_Server[i].port <= 0)
1895 continue; /* No host and/or port configured */
1896 if (Conf_Server[i].flags & CONF_SFLAG_DISABLED)
1897 continue; /* Disabled configuration entry */
1898 if (Conf_Server[i].lasttry > (time_now - Conf_ConnectRetry))
1899 continue; /* We have to wait a little bit ... */
1901 /* Is there already a connection in this group? */
1902 if (Conf_Server[i].group > NONE) {
1903 for (n = 0; n < MAX_SERVERS; n++) {
1906 if ((Conf_Server[n].conn_id != NONE) &&
1907 (Conf_Server[n].group == Conf_Server[i].group))
1910 if (n < MAX_SERVERS)
1914 /* Okay, try to connect now */
1916 "Preparing to establish a new server link for \"%s\" ...",
1917 Conf_Server[i].name);
1918 Conf_Server[i].lasttry = time_now;
1919 Conf_Server[i].conn_id = SERVER_WAIT;
1920 assert(Proc_GetPipeFd(&Conf_Server[i].res_stat) < 0);
1921 Resolve_Name(&Conf_Server[i].res_stat, Conf_Server[i].host,
1922 cb_Connect_to_Server);
1924 } /* Check_Servers */
1927 * Establish a new outgoing server connection.
1929 * @param Server Configuration index of the server.
1930 * @param dest Destination IP address to connect to.
1933 New_Server( int Server , ng_ipaddr_t *dest)
1935 /* Establish new server link */
1936 char ip_str[NG_INET_ADDRSTRLEN];
1937 int af_dest, res, new_sock;
1940 assert( Server > NONE );
1942 /* Make sure that the remote server hasn't re-linked to this server
1943 * asynchronously on its own */
1944 if (Conf_Server[Server].conn_id > NONE) {
1946 "Connection to \"%s\" meanwhile re-established, aborting preparation.");
1950 if (!ng_ipaddr_tostr_r(dest, ip_str)) {
1951 Log(LOG_WARNING, "New_Server: Could not convert IP to string");
1952 Conf_Server[Server].conn_id = NONE;
1956 af_dest = ng_ipaddr_af(dest);
1957 new_sock = socket(af_dest, SOCK_STREAM, 0);
1960 "Establishing connection for \"%s\" to \"%s:%d\" (%s), socket %d ...",
1961 Conf_Server[Server].name, Conf_Server[Server].host,
1962 Conf_Server[Server].port, ip_str, new_sock);
1965 Log(LOG_CRIT, "Can't create socket (af %d): %s!",
1966 af_dest, strerror(errno));
1967 Conf_Server[Server].conn_id = NONE;
1971 if (!Init_Socket(new_sock)) {
1972 Conf_Server[Server].conn_id = NONE;
1976 /* is a bind address configured? */
1977 res = ng_ipaddr_af(&Conf_Server[Server].bind_addr);
1979 /* if yes, bind now. If it fails, warn and let connect() pick a
1981 if (res && bind(new_sock, (struct sockaddr *) &Conf_Server[Server].bind_addr,
1982 ng_ipaddr_salen(&Conf_Server[Server].bind_addr)))
1984 ng_ipaddr_tostr_r(&Conf_Server[Server].bind_addr, ip_str);
1985 Log(LOG_WARNING, "Can't bind socket to %s: %s!", ip_str,
1988 ng_ipaddr_setport(dest, Conf_Server[Server].port);
1989 res = connect(new_sock, (struct sockaddr *) dest, ng_ipaddr_salen(dest));
1990 if(( res != 0 ) && ( errno != EINPROGRESS )) {
1991 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1993 Conf_Server[Server].conn_id = NONE;
1997 if (Socket2Index(new_sock) <= NONE) {
1999 Conf_Server[Server].conn_id = NONE;
2003 if (!io_event_create( new_sock, IO_WANTWRITE, cb_connserver)) {
2004 Log(LOG_ALERT, "io_event_create(): could not add fd %d",
2007 Conf_Server[Server].conn_id = NONE;
2011 assert(My_Connections[new_sock].sock <= 0);
2013 Init_Conn_Struct(new_sock);
2015 ng_ipaddr_tostr_r(dest, ip_str);
2016 c = Client_NewLocal(new_sock, ip_str, CLIENT_UNKNOWNSERVER, false);
2018 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
2020 Conf_Server[Server].conn_id = NONE;
2024 /* Conn_Close() decrements this counter again */
2025 Account_Connection();
2026 Client_SetIntroducer( c, c );
2027 Client_SetToken( c, TOKEN_OUTBOUND );
2029 /* Register connection */
2030 if (!Conf_SetServer(Server, new_sock))
2032 My_Connections[new_sock].sock = new_sock;
2033 My_Connections[new_sock].addr = *dest;
2034 My_Connections[new_sock].client = c;
2035 strlcpy( My_Connections[new_sock].host, Conf_Server[Server].host,
2036 sizeof(My_Connections[new_sock].host ));
2039 if (Conf_Server[Server].SSLConnect &&
2040 !ConnSSL_PrepareConnect(&My_Connections[new_sock], &Conf_Server[Server]))
2042 Log(LOG_ALERT, "Could not initialize SSL for outgoing connection");
2043 Conn_Close(new_sock, "Could not initialize SSL for outgoing connection",
2045 Init_Conn_Struct(new_sock);
2046 Conf_Server[Server].conn_id = NONE;
2050 LogDebug("Registered new connection %d on socket %d (%ld in total).",
2051 new_sock, My_Connections[new_sock].sock, NumConnections);
2052 Conn_OPTION_ADD( &My_Connections[new_sock], CONN_ISCONNECTING );
2056 * Initialize connection structure.
2058 * @param Idx Connection index.
2061 Init_Conn_Struct(CONN_ID Idx)
2063 time_t now = time(NULL);
2065 memset(&My_Connections[Idx], 0, sizeof(CONNECTION));
2066 My_Connections[Idx].sock = -1;
2067 My_Connections[Idx].signon = now;
2068 My_Connections[Idx].lastdata = now;
2069 My_Connections[Idx].lastprivmsg = now;
2070 Proc_InitStruct(&My_Connections[Idx].proc_stat);
2073 My_Connections[Idx].iconv_from = (iconv_t)(-1);
2074 My_Connections[Idx].iconv_to = (iconv_t)(-1);
2076 } /* Init_Conn_Struct */
2079 * Initialize options of a new socket.
2081 * For example, we try to set socket options SO_REUSEADDR and IPTOS_LOWDELAY.
2082 * The socket is automatically closed if a fatal error is encountered.
2084 * @param Sock Socket handle.
2085 * @returns false if socket was closed due to fatal error.
2088 Init_Socket( int Sock )
2092 if (!io_setnonblock(Sock)) {
2093 Log(LOG_CRIT, "Can't enable non-blocking mode for socket: %s!",
2099 /* Don't block this port after socket shutdown */
2101 if (setsockopt(Sock, SOL_SOCKET, SO_REUSEADDR, &value,
2102 (socklen_t)sizeof(value)) != 0) {
2103 Log(LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!",
2105 /* ignore this error */
2108 /* Set type of service (TOS) */
2109 #if defined(IPPROTO_IP) && defined(IPTOS_LOWDELAY)
2110 value = IPTOS_LOWDELAY;
2111 if (setsockopt(Sock, IPPROTO_IP, IP_TOS, &value,
2112 (socklen_t) sizeof(value))) {
2113 LogDebug("Can't set socket option IP_TOS: %s!",
2115 /* ignore this error */
2117 LogDebug("IP_TOS on socket %d has been set to IPTOS_LOWDELAY.",
2125 * Read results of a resolver sub-process and try to initiate a new server
2128 * @param fd File descriptor of the pipe to the sub-process.
2129 * @param events (ignored IO specification)
2132 cb_Connect_to_Server(int fd, UNUSED short events)
2137 /* we can handle at most 3 addresses; but we read up to 4 so we can
2138 * log the 'more than we can handle' condition. First result is tried
2139 * immediately, rest is saved for later if needed. */
2140 ng_ipaddr_t dest_addrs[4];
2142 LogDebug("Resolver: Got forward lookup callback on fd %d, events %d",
2145 for (i=0; i < MAX_SERVERS; i++) {
2146 if (Proc_GetPipeFd(&Conf_Server[i].res_stat) == fd )
2150 if( i >= MAX_SERVERS) {
2151 /* Ops, no matching server found?! */
2153 LogDebug("Resolver: Got Forward Lookup callback for unknown server!?");
2157 /* Read result from pipe */
2158 len = Proc_Read(&Conf_Server[i].res_stat, dest_addrs, sizeof(dest_addrs));
2159 Proc_Close(&Conf_Server[i].res_stat);
2161 /* Error resolving hostname: reset server structure */
2162 Conf_Server[i].conn_id = NONE;
2166 assert((len % sizeof(ng_ipaddr_t)) == 0);
2168 LogDebug("Got result from resolver: %u structs (%u bytes).",
2169 len/sizeof(ng_ipaddr_t), len);
2171 memset(&Conf_Server[i].dst_addr, 0, sizeof(Conf_Server[i].dst_addr));
2172 if (len > sizeof(ng_ipaddr_t)) {
2173 /* more than one address for this hostname, remember them
2174 * in case first address is unreachable/not available */
2175 len -= sizeof(ng_ipaddr_t);
2176 if (len > sizeof(Conf_Server[i].dst_addr)) {
2177 len = sizeof(Conf_Server[i].dst_addr);
2179 "Notice: Resolver returned more IP Addresses for host than we can handle, additional addresses dropped.");
2181 memcpy(&Conf_Server[i].dst_addr, &dest_addrs[1], len);
2184 New_Server(i, dest_addrs);
2185 } /* cb_Read_Forward_Lookup */
2188 * Read results of a resolver sub-process from the pipe and update the
2189 * appropriate connection/client structure(s): hostname and/or IDENT user name.
2191 * @param r_fd File descriptor of the pipe to the sub-process.
2192 * @param events (ignored IO specification)
2195 cb_Read_Resolver_Result( int r_fd, UNUSED short events )
2202 char readbuf[HOST_LEN + 2 + CLIENT_USER_LEN];
2205 char readbuf[HOST_LEN + 1];
2208 LogDebug("Resolver: Got callback on fd %d, events %d", r_fd, events );
2209 i = Conn_GetFromProc(r_fd);
2211 /* Ops, none found? Probably the connection has already
2212 * been closed!? We'll ignore that ... */
2214 LogDebug("Resolver: Got callback for unknown connection!?");
2218 /* Read result from pipe */
2219 len = Proc_Read(&My_Connections[i].proc_stat, readbuf, sizeof readbuf -1);
2220 Proc_Close(&My_Connections[i].proc_stat);
2224 readbuf[len] = '\0';
2225 identptr = strchr(readbuf, '\n');
2226 assert(identptr != NULL);
2228 Log( LOG_CRIT, "Resolver: Got malformed result!");
2233 LogDebug("Got result from resolver: \"%s\" (%u bytes read).", readbuf, len);
2234 /* Okay, we got a complete result: this is a host name for outgoing
2235 * connections and a host name and IDENT user name (if enabled) for
2236 * incoming connections.*/
2237 assert ( My_Connections[i].sock >= 0 );
2238 /* Incoming connection. Search client ... */
2239 c = Conn_GetClient( i );
2240 assert( c != NULL );
2242 /* Only update client information of unregistered clients.
2243 * Note: user commands (e. g. WEBIRC) are always read _after_ reading
2244 * the resolver results, so we don't have to worry to override settings
2245 * from these commands here. */
2246 if(Client_Type(c) == CLIENT_UNKNOWN) {
2247 strlcpy(My_Connections[i].host, readbuf,
2248 sizeof(My_Connections[i].host));
2249 Client_SetHostname(c, readbuf);
2250 if (Conf_NoticeBeforeRegistration)
2251 (void)Conn_WriteStr(i,
2252 "NOTICE * :*** Found your hostname: %s",
2253 My_Connections[i].host);
2259 if ((*ptr < '0' || *ptr > '9') &&
2260 (*ptr < 'A' || *ptr > 'Z') &&
2261 (*ptr < 'a' || *ptr > 'z'))
2266 /* Erroneous IDENT reply */
2268 "Got invalid IDENT reply for connection %d! Ignored.",
2272 "IDENT lookup for connection %d: \"%s\".",
2274 Client_SetUser(c, identptr, true);
2276 if (Conf_NoticeBeforeRegistration) {
2277 (void)Conn_WriteStr(i,
2278 "NOTICE * :*** Got %sident response%s%s",
2279 *ptr ? "invalid " : "",
2281 *ptr ? "" : identptr);
2283 } else if(Conf_Ident) {
2284 Log(LOG_INFO, "IDENT lookup for connection %d: no result.", i);
2285 if (Conf_NoticeBeforeRegistration)
2286 (void)Conn_WriteStr(i,
2287 "NOTICE * :*** No ident response");
2291 if (Conf_NoticeBeforeRegistration) {
2292 /* Send buffered data to the client, but break on
2293 * errors because Handle_Write() would have closed
2294 * the connection again in this case! */
2295 if (!Handle_Write(i))
2299 Class_HandleServerBans(c);
2303 LogDebug("Resolver: discarding result for already registered connection %d.", i);
2305 } /* cb_Read_Resolver_Result */
2308 * Write a "simple" (error) message to a socket.
2310 * The message is sent without using the connection write buffers, without
2311 * compression/encryption, and even without any error reporting. It is
2312 * designed for error messages of e.g. New_Connection().
2314 * @param Sock Socket handle.
2315 * @param Msg Message string to send.
2318 Simple_Message(int Sock, const char *Msg)
2320 char buf[COMMAND_LEN];
2323 assert(Sock > NONE);
2324 assert(Msg != NULL);
2326 strlcpy(buf, Msg, sizeof buf - 2);
2327 len = strlcat(buf, "\r\n", sizeof buf);
2328 if (write(Sock, buf, len) < 0) {
2329 /* Because this function most probably got called to log
2330 * an error message, any write error is ignored here to
2331 * avoid an endless loop. But casting the result of write()
2332 * to "void" doesn't satisfy the GNU C code attribute
2333 * "warn_unused_result" which is used by some versions of
2334 * glibc (e.g. 2.11.1), therefore this silly error
2335 * "handling" code here :-( */
2338 } /* Simple_Error */
2341 * Get CLIENT structure that belongs to a local connection identified by its
2342 * index number. Each connection belongs to a client by definition, so it is
2343 * not required that the caller checks for NULL return values.
2345 * @param Idx Connection index number.
2346 * @returns Pointer to CLIENT structure.
2349 Conn_GetClient( CONN_ID Idx )
2354 c = array_get(&My_ConnArray, sizeof (CONNECTION), (size_t)Idx);
2356 return c ? c->client : NULL;
2360 * Get PROC_STAT sub-process structure of a connection.
2362 * @param Idx Connection index number.
2363 * @returns PROC_STAT structure.
2366 Conn_GetProcStat(CONN_ID Idx)
2371 c = array_get(&My_ConnArray, sizeof (CONNECTION), (size_t)Idx);
2373 return &c->proc_stat;
2374 } /* Conn_GetProcStat */
2377 * Get CONN_ID from file descriptor associated to a subprocess structure.
2379 * @param fd File descriptor.
2380 * @returns CONN_ID or NONE (-1).
2383 Conn_GetFromProc(int fd)
2388 for (i = 0; i < Pool_Size; i++) {
2389 if ((My_Connections[i].sock != NONE)
2390 && (Proc_GetPipeFd(&My_Connections[i].proc_stat) == fd))
2394 } /* Conn_GetFromProc */
2397 * Throttle a connection because of excessive usage.
2399 * @param Reason The reason, see THROTTLE_xxx constants.
2400 * @param Idx The connection index.
2401 * @param Client The client of this connection.
2402 * @param Seconds The time to delay this connection.
2405 Throttle_Connection(const CONN_ID Idx, CLIENT *Client, const int Reason,
2409 assert(Client != NULL);
2411 /* Never throttle servers or services, only interrupt processing */
2412 if (Client_Type(Client) == CLIENT_SERVER
2413 || Client_Type(Client) == CLIENT_UNKNOWNSERVER
2414 || Client_Type(Client) == CLIENT_SERVICE)
2417 /* Don't throttle clients with user mode 'F' set */
2418 if (Client_HasMode(Client, 'F'))
2421 LogDebug("Throttling connection %d: code %d, value %d!", Idx,
2423 Conn_SetPenalty(Idx, 1);
2429 Conn_GetAuthPing(CONN_ID Idx)
2431 assert (Idx != NONE);
2432 return My_Connections[Idx].auth_ping;
2433 } /* Conn_GetAuthPing */
2436 Conn_SetAuthPing(CONN_ID Idx, long ID)
2438 assert (Idx != NONE);
2439 My_Connections[Idx].auth_ping = ID;
2440 } /* Conn_SetAuthPing */
2442 #endif /* STRICT_RFC */
2447 * IO callback for new SSL-enabled client and server connections.
2449 * @param sock Socket descriptor.
2450 * @param what IO specification (IO_WANTREAD/IO_WANTWRITE/...).
2453 cb_clientserver_ssl(int sock, UNUSED short what)
2455 CONN_ID idx = Socket2Index(sock);
2462 switch (ConnSSL_Accept(&My_Connections[idx])) {
2466 return; /* EAGAIN: callback will be invoked again by IO layer */
2469 "SSL accept error, closing socket", "SSL accept error",
2474 io_event_setcb(sock, cb_clientserver); /* SSL handshake completed */
2478 * IO callback for listening SSL sockets: handle new connections. This callback
2479 * gets called when a new SSL-enabled connection should be accepted.
2481 * @param sock Socket descriptor.
2482 * @param irrelevant (ignored IO specification)
2485 cb_listen_ssl(int sock, short irrelevant)
2490 fd = New_Connection(sock, true);
2493 io_event_setcb(My_Connections[fd].sock, cb_clientserver_ssl);
2497 * IO callback for new outgoing SSL-enabled server connections.
2499 * @param sock Socket descriptor.
2500 * @param unused (ignored IO specification)
2503 cb_connserver_login_ssl(int sock, short unused)
2505 CONN_ID idx = Socket2Index(sock);
2514 switch (ConnSSL_Connect( &My_Connections[idx])) {
2516 case 0: LogDebug("ConnSSL_Connect: not ready");
2519 Log(LOG_ERR, "SSL connection on socket %d failed!", sock);
2520 Conn_Close(idx, "Can't connect", NULL, false);
2524 Log( LOG_INFO, "SSL connection %d with \"%s:%d\" established.", idx,
2525 My_Connections[idx].host, Conf_Server[Conf_GetServer( idx )].port );
2532 * Check if SSL library needs to read SSL-protocol related data.
2534 * SSL/TLS connections require extra treatment:
2535 * When either CONN_SSL_WANT_WRITE or CONN_SSL_WANT_READ is set, we
2536 * need to take care of that first, before checking read/write buffers.
2537 * For instance, while we might have data in our write buffer, the
2538 * TLS/SSL protocol might need to read internal data first for TLS/SSL
2539 * writes to succeed.
2541 * If this function returns true, such a condition is met and we have
2542 * to reverse the condition (check for read even if we've data to write,
2543 * do not check for read but writeability even if write-buffer is empty).
2545 * @param c Connection to check.
2546 * @returns true if SSL-library has to read protocol data.
2549 SSL_WantRead(const CONNECTION *c)
2551 if (Conn_OPTION_ISSET(c, CONN_SSL_WANT_READ)) {
2552 io_event_add(c->sock, IO_WANTREAD);
2559 * Check if SSL library needs to write SSL-protocol related data.
2561 * Please see description of SSL_WantRead() for full description!
2563 * @param c Connection to check.
2564 * @returns true if SSL-library has to write protocol data.
2567 SSL_WantWrite(const CONNECTION *c)
2569 if (Conn_OPTION_ISSET(c, CONN_SSL_WANT_WRITE)) {
2570 io_event_add(c->sock, IO_WANTWRITE);
2577 * Get information about used SSL cipher.
2579 * @param Idx Connection index number.
2580 * @param buf Buffer for returned information text.
2581 * @param len Size of return buffer "buf".
2582 * @returns true on success, false otherwise.
2585 Conn_GetCipherInfo(CONN_ID Idx, char *buf, size_t len)
2589 assert(Idx < (int) array_length(&My_ConnArray, sizeof(CONNECTION)));
2590 return ConnSSL_GetCipherInfo(&My_Connections[Idx], buf, len);
2594 * Check if a connection is SSL-enabled or not.
2596 * @param Idx Connection index number.
2597 * @return true if connection is SSL-enabled, false otherwise.
2600 Conn_UsesSSL(CONN_ID Idx)
2604 assert(Idx < (int) array_length(&My_ConnArray, sizeof(CONNECTION)));
2605 return Conn_OPTION_ISSET(&My_Connections[Idx], CONN_SSL);
2609 Conn_GetCertFp(CONN_ID Idx)
2613 assert(Idx < (int) array_length(&My_ConnArray, sizeof(CONNECTION)));
2614 return ConnSSL_GetCertFp(&My_Connections[Idx]);
2618 Conn_SetCertFp(CONN_ID Idx, const char *fingerprint)
2622 assert(Idx < (int) array_length(&My_ConnArray, sizeof(CONNECTION)));
2623 return ConnSSL_SetCertFp(&My_Connections[Idx], fingerprint);
2626 #else /* SSL_SUPPORT */
2629 Conn_UsesSSL(UNUSED CONN_ID Idx)
2635 Conn_GetCertFp(UNUSED CONN_ID Idx)
2641 Conn_SetCertFp(UNUSED CONN_ID Idx, UNUSED const char *fingerprint)
2646 #endif /* SSL_SUPPORT */
2651 * Dump internal state of the "connection module".
2654 Conn_DebugDump(void)
2658 Log(LOG_DEBUG, "Connection status:");
2659 for (i = 0; i < Pool_Size; i++) {
2660 if (My_Connections[i].sock == NONE)
2663 " - %d: host=%s, lastdata=%ld, lastping=%ld, delaytime=%ld, flag=%d, options=%d, bps=%d, client=%s",
2664 My_Connections[i].sock, My_Connections[i].host,
2665 My_Connections[i].lastdata, My_Connections[i].lastping,
2666 My_Connections[i].delaytime, My_Connections[i].flag,
2667 My_Connections[i].options, My_Connections[i].bps,
2668 My_Connections[i].client ? Client_ID(My_Connections[i].client) : "-");
2670 } /* Conn_DumpClients */