2 * ngIRCd -- The Next Generation IRC Daemon
3 * Copyright (c)2001-2019 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.
13 #define CONN_MODULE_GLOBAL_INIT
19 * Connection management
22 /* Additionan debug messages related to buffer handling: 0=off / 1=on */
23 #define DEBUG_BUFFER 0
37 #include <sys/socket.h>
39 #include <sys/types.h>
41 #include <netinet/in.h>
43 #ifdef HAVE_NETINET_IP_H
44 # ifdef HAVE_NETINET_IN_SYSTM_H
45 # include <netinet/in_systm.h>
47 # include <netinet/ip.h>
51 # include <tcpd.h> /* for TCP Wrappers */
59 # include "conn-encoding.h"
63 #include "conn-func.h"
66 #include "ng_ipaddr.h"
70 #define SERVER_WAIT (NONE - 1) /** "Wait for outgoing connection" flag */
72 #define MAX_COMMANDS 3 /** Max. commands per loop for users */
73 #define MAX_COMMANDS_SERVER_MIN 10 /** Min. commands per loop for servers */
74 #define MAX_COMMANDS_SERVICE 10 /** Max. commands per loop for services */
76 #define SD_LISTEN_FDS_START 3 /** systemd(8) socket activation offset */
78 #define THROTTLE_CMDS 1 /** Throttling: max commands reached */
79 #define THROTTLE_BPS 2 /** Throttling: max bps reached */
81 static bool Handle_Write PARAMS(( CONN_ID Idx ));
82 static bool Conn_Write PARAMS(( CONN_ID Idx, char *Data, size_t Len ));
83 static int New_Connection PARAMS(( int Sock, bool IsSSL ));
84 static CONN_ID Socket2Index PARAMS(( int Sock ));
85 static void Read_Request PARAMS(( CONN_ID Idx ));
86 static unsigned int Handle_Buffer PARAMS(( CONN_ID Idx ));
87 static void Check_Connections PARAMS(( void ));
88 static void Check_Servers PARAMS(( void ));
89 static void Init_Conn_Struct PARAMS(( CONN_ID Idx ));
90 static bool Init_Socket PARAMS(( int Sock ));
91 static void New_Server PARAMS(( int Server, ng_ipaddr_t *dest ));
92 static void Simple_Message PARAMS(( int Sock, const char *Msg ));
93 static int NewListener PARAMS(( const char *listen_addr, UINT16 Port ));
94 static void Account_Connection PARAMS((void));
95 static void Throttle_Connection PARAMS((const CONN_ID Idx, CLIENT *Client,
96 const int Reason, unsigned int Value));
98 static array My_Listeners;
99 static array My_ConnArray;
100 static size_t NumConnections, NumConnectionsMax, NumConnectionsAccepted;
103 int allow_severity = LOG_INFO;
104 int deny_severity = LOG_ERR;
107 static void server_login PARAMS((CONN_ID idx));
110 extern struct SSLOptions Conf_SSLOptions;
111 static bool SSL_WantRead PARAMS((const CONNECTION *c));
112 static bool SSL_WantWrite PARAMS((const CONNECTION *c));
113 static void cb_listen_ssl PARAMS((int sock, short irrelevant));
114 static void cb_connserver_login_ssl PARAMS((int sock, short what));
115 static void cb_clientserver_ssl PARAMS((int sock, short what));
117 static void cb_Read_Resolver_Result PARAMS((int sock, UNUSED short what));
118 static void cb_Connect_to_Server PARAMS((int sock, UNUSED short what));
119 static void cb_clientserver PARAMS((int sock, short what));
124 * Get number of sockets available from systemd(8).
126 * ngIRCd needs to implement its own sd_listen_fds(3) function and can't
127 * use the one provided by systemd itself, because the sockets will be
128 * used in a forked child process with a new PID, and this would trigger
129 * an error in the standard implementation.
131 * @return Number of sockets available, -1 if sockets have already been
132 * initialized, or 0 when no sockets have been passed.
135 my_sd_listen_fds(void)
140 /* Check if LISTEN_PID exists; but we ignore the result, because
141 * normally ngircd forks a child before checking this, and therefore
142 * the PID set in the environment is always wrong ... */
143 e = getenv("LISTEN_PID");
147 e = getenv("LISTEN_FDS");
152 unsetenv("LISTEN_FDS");
159 * IO callback for listening sockets: handle new connections. This callback
160 * gets called when a new non-SSL connection should be accepted.
162 * @param sock Socket descriptor.
163 * @param irrelevant (ignored IO specification)
166 cb_listen(int sock, short irrelevant)
169 (void) New_Connection(sock, false);
173 * IO callback for new outgoing non-SSL server connections.
175 * @param sock Socket descriptor.
176 * @param what IO specification (IO_WANTREAD/IO_WANTWRITE/...).
179 cb_connserver(int sock, UNUSED short what)
181 int res, err, server;
183 CONN_ID idx = Socket2Index( sock );
190 assert(what & IO_WANTWRITE);
192 /* Make sure that the server is still configured; it could have been
193 * removed in the meantime! */
194 server = Conf_GetServer(idx);
196 Log(LOG_ERR, "Connection on socket %d to \"%s\" aborted!",
197 sock, My_Connections[idx].host);
198 Conn_Close(idx, "Connection aborted", NULL, false);
202 /* connect() finished, get result. */
203 sock_len = (socklen_t)sizeof(err);
204 res = getsockopt(My_Connections[idx].sock, SOL_SOCKET, SO_ERROR,
206 assert(sock_len == sizeof(err));
208 /* Error while connecting? */
209 if ((res != 0) || (err != 0)) {
211 Log(LOG_CRIT, "getsockopt (connection %d): %s!",
212 idx, strerror(errno));
215 "Can't connect socket to \"%s:%d\" (connection %d): %s!",
216 My_Connections[idx].host, Conf_Server[server].port,
219 Conn_Close(idx, "Can't connect", NULL, false);
221 if (ng_ipaddr_af(&Conf_Server[server].dst_addr[0])) {
222 /* more addresses to try... */
223 New_Server(server, &Conf_Server[server].dst_addr[0]);
224 /* connection to dst_addr[0] is now in progress, so
225 * remove this address... */
226 Conf_Server[server].dst_addr[0] =
227 Conf_Server[server].dst_addr[1];
228 memset(&Conf_Server[server].dst_addr[1], 0,
229 sizeof(Conf_Server[server].dst_addr[1]));
234 /* connect() succeeded, remove all additional addresses */
235 memset(&Conf_Server[server].dst_addr, 0,
236 sizeof(Conf_Server[server].dst_addr));
238 Conn_OPTION_DEL( &My_Connections[idx], CONN_ISCONNECTING );
240 if ( Conn_OPTION_ISSET( &My_Connections[idx], CONN_SSL_CONNECT )) {
241 io_event_setcb( sock, cb_connserver_login_ssl );
242 io_event_add( sock, IO_WANTWRITE|IO_WANTREAD );
250 * Login to a remote server.
252 * @param idx Connection index.
255 server_login(CONN_ID idx)
258 "Connection %d (socket %d) with \"%s:%d\" established. Now logging in ...",
259 idx, My_Connections[idx].sock, My_Connections[idx].host,
260 Conf_Server[Conf_GetServer(idx)].port);
262 io_event_setcb( My_Connections[idx].sock, cb_clientserver);
263 io_event_add( My_Connections[idx].sock, IO_WANTREAD|IO_WANTWRITE);
265 /* Send PASS and SERVER command to peer */
266 Conn_WriteStr(idx, "PASS %s %s",
267 Conf_Server[Conf_GetServer( idx )].pwd_out, NGIRCd_ProtoID);
268 Conn_WriteStr(idx, "SERVER %s :%s",
269 Conf_ServerName, Conf_ServerInfo);
273 * IO callback for established non-SSL client and server connections.
275 * @param sock Socket descriptor.
276 * @param what IO specification (IO_WANTREAD/IO_WANTWRITE/...).
279 cb_clientserver(int sock, short what)
281 CONN_ID idx = Socket2Index(sock);
289 if (what & IO_WANTREAD
290 || (Conn_OPTION_ISSET(&My_Connections[idx], CONN_SSL_WANT_WRITE))) {
291 /* if TLS layer needs to write additional data, call
292 * Read_Request() instead so that SSL/TLS can continue */
296 if (what & IO_WANTREAD)
299 if (what & IO_WANTWRITE)
304 * Initialize connection module.
311 /* Initialize the "connection pool".
312 * FIXME: My_Connetions/Pool_Size is needed by other parts of the
313 * code; remove them! */
315 size = Conf_MaxConnections > 0 ? Conf_MaxConnections : CONNECTION_POOL;
316 if (Socket2Index(size) <= NONE) {
317 Log(LOG_EMERG, "Failed to initialize connection pool!");
321 /* Initialize "listener" array. */
322 array_free( &My_Listeners );
326 * Clean up connection module.
333 Conn_ExitListeners();
335 LogDebug("Shutting down all connections ..." );
336 for( idx = 0; idx < Pool_Size; idx++ ) {
337 if( My_Connections[idx].sock > NONE ) {
338 Conn_Close( idx, NULL, NGIRCd_SignalRestart ?
339 "Server going down (restarting)":"Server going down", true );
343 array_free(&My_ConnArray);
344 My_Connections = NULL;
346 io_library_shutdown();
350 * Close all sockets (file descriptors) of open connections.
351 * This is useful in forked child processes, for example, to make sure that
352 * they don't hold connections open that the main process wants to close.
355 Conn_CloseAllSockets(int ExceptOf)
359 for(idx = 0; idx < Pool_Size; idx++) {
360 if(My_Connections[idx].sock > NONE &&
361 My_Connections[idx].sock != ExceptOf)
362 close(My_Connections[idx].sock);
367 * Initialize listening ports.
369 * @param a Array containing the ports the daemon should listen on.
370 * @param listen_addr Address the socket should listen on (can be "0.0.0.0").
371 * @param func IO callback function to register.
372 * @returns Number of listening sockets created.
375 Init_Listeners(array *a, const char *listen_addr, void (*func)(int,short))
377 unsigned int created = 0;
382 len = array_length(a, sizeof (UINT16));
383 port = array_start(a);
385 fd = NewListener(listen_addr, *port);
390 if (!io_event_create( fd, IO_WANTREAD, func )) {
392 "io_event_create(): Can't add fd %d (port %u): %s!",
393 fd, (unsigned int) *port, strerror(errno));
405 * Initialize all listening sockets.
407 * @returns Number of created listening sockets
410 Conn_InitListeners( void )
412 /* Initialize ports on which the server should accept connections */
413 unsigned int created = 0;
414 char *af_str, *copy, *listen_addr;
415 int count, fd, i, addr_len;
418 assert(Conf_ListenAddress);
420 count = my_sd_listen_fds();
423 "Not re-initializing listening sockets of systemd(8) ...");
427 /* systemd(8) passed sockets to us, so don't try to initialize
428 * listening sockets on our own but use the passed ones */
429 LogDebug("Initializing %d systemd sockets ...", count);
430 for (i = 0; i < count; i++) {
431 fd = SD_LISTEN_FDS_START + i;
432 addr_len = (int)sizeof(addr);
433 getsockname(fd, (struct sockaddr *)&addr,
434 (socklen_t*)&addr_len);
436 if (addr.sin4.sin_family != AF_INET
437 && addr.sin4.sin_family != AF_INET6)
439 if (addr.sin4.sin_family != AF_INET)
442 /* Socket is of unsupported type! For example,
443 * systemd passed in an IPv6 socket but ngIRCd
444 * isn't compiled with IPv6 support. */
445 switch (addr.sin4.sin_family)
447 case AF_UNSPEC: af_str = "AF_UNSPEC"; break;
448 case AF_UNIX: af_str = "AF_UNIX"; break;
449 case AF_INET: af_str = "AF_INET"; break;
451 case AF_INET6: af_str = "AF_INET6"; break;
454 case AF_NETLINK: af_str = "AF_NETLINK"; break;
456 default: af_str = "unknown"; break;
459 "Socket %d is of unsupported type \"%s\" (%d), have to ignore it!",
460 fd, af_str, addr.sin4.sin_family);
466 if (!io_event_create(fd, IO_WANTREAD, cb_listen)) {
468 "io_event_create(): Can't add fd %d: %s!",
469 fd, strerror(errno));
473 "Initialized socket %d from systemd(8): %s:%d.", fd,
474 ng_ipaddr_tostr(&addr), ng_ipaddr_getport(&addr));
480 /* not using systemd socket activation, initialize listening sockets: */
482 /* can't use Conf_ListenAddress directly, see below */
483 copy = strdup(Conf_ListenAddress);
485 Log(LOG_CRIT, "Cannot copy %s: %s", Conf_ListenAddress,
489 listen_addr = strtok(copy, ",");
491 while (listen_addr) {
492 ngt_TrimStr(listen_addr);
494 created += Init_Listeners(&Conf_ListenPorts,
495 listen_addr, cb_listen);
497 created += Init_Listeners(&Conf_SSLOptions.ListenPorts,
498 listen_addr, cb_listen_ssl);
502 listen_addr = strtok(NULL, ",");
505 /* Can't free() Conf_ListenAddress here: on REHASH, if the config file
506 * cannot be re-loaded, we'd end up with a NULL Conf_ListenAddress.
507 * Instead, free() takes place in conf.c, before the config file
508 * is being parsed. */
512 } /* Conn_InitListeners */
515 * Shut down all listening sockets.
518 Conn_ExitListeners( void )
520 /* Close down all listening sockets */
524 /* Get number of listening sockets to shut down. There can be none
525 * if ngIRCd has been "socket activated" by systemd. */
526 arraylen = array_length(&My_Listeners, sizeof (int));
531 "Shutting down all listening sockets (%d total) ...", arraylen);
532 fd = array_start(&My_Listeners);
537 LogDebug("Listening socket %d closed.", *fd );
540 array_free(&My_Listeners);
541 } /* Conn_ExitListeners */
544 * Bind a socket to a specific (source) address.
546 * @param addr Address structure.
547 * @param listen_addrstr Source address as string.
548 * @param Port Port number.
549 * @returns true on success, false otherwise.
552 InitSinaddrListenAddr(ng_ipaddr_t *addr, const char *listen_addrstr, UINT16 Port)
556 ret = ng_ipaddr_init(addr, listen_addrstr, Port);
558 assert(listen_addrstr);
560 "Can't listen on [%s]:%u: Failed to parse IP address!",
561 listen_addrstr, Port);
567 * Set a socket to "IPv6 only". If the given socket doesn't belong to the
568 * AF_INET6 family, or the operating system doesn't support this functionality,
569 * this function retruns silently.
571 * @param af Address family of the socket.
572 * @param sock Socket handle.
575 set_v6_only(int af, int sock)
577 #if defined(IPV6_V6ONLY) && defined(WANT_IPV6)
583 if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, (socklen_t)sizeof(on)))
584 Log(LOG_ERR, "Could not set IPV6_V6ONLY: %s", strerror(errno));
592 * Initialize new listening port.
594 * @param listen_addr Local address to bind the socket to (can be 0.0.0.0).
595 * @param Port Port number on which the new socket should be listening.
596 * @returns file descriptor of the socket or -1 on failure.
599 NewListener(const char *listen_addr, UINT16 Port)
601 /* Create new listening socket on specified port */
605 if (!InitSinaddrListenAddr(&addr, listen_addr, Port))
608 af = ng_ipaddr_af(&addr);
609 sock = socket(af, SOCK_STREAM, 0);
611 Log(LOG_CRIT, "Can't create socket (af %d) : %s!", af,
616 set_v6_only(af, sock);
618 if (!Init_Socket(sock))
621 if (bind(sock, (struct sockaddr *)&addr, ng_ipaddr_salen(&addr)) != 0) {
622 Log(LOG_CRIT, "Can't bind socket to address %s:%d - %s!",
623 ng_ipaddr_tostr(&addr), Port, strerror(errno));
628 if (listen(sock, 10) != 0) {
629 Log(LOG_CRIT, "Can't listen on socket: %s!", strerror(errno));
634 /* keep fd in list so we can close it when ngircd restarts/shuts down */
635 if (!array_catb(&My_Listeners, (char *)&sock, sizeof(int))) {
636 Log(LOG_CRIT, "Can't add socket to My_Listeners array: %s!",
642 Log(LOG_INFO, "Now listening on [%s]:%d (socket %d).",
643 ng_ipaddr_tostr(&addr), Port, sock);
648 * "Main Loop": Loop until shutdown or restart is signalled.
650 * This function loops until a shutdown or restart of ngIRCd is signalled and
651 * calls io_dispatch() to check for readable and writable sockets every second.
652 * It checks for status changes on pending connections (e. g. when a hostname
653 * has been resolved), checks for "penalties" and timeouts, and handles the
663 bool command_available;
665 Log(LOG_NOTICE, "Server \"%s\" (on \"%s\") ready.",
666 Client_ID(Client_ThisServer()), Client_Hostname(Client_ThisServer()));
668 while (!NGIRCd_SignalQuit && !NGIRCd_SignalRestart) {
670 command_available = false;
672 /* Check configured servers and established links */
676 /* Expire outdated class/list items */
679 /* Look for non-empty read buffers ... */
680 for (i = 0; i < Pool_Size; i++) {
681 if ((My_Connections[i].sock > NONE)
682 && (array_bytes(&My_Connections[i].rbuf) > 0)) {
683 /* ... and try to handle the received data */
688 /* Look for non-empty write buffers ... */
689 for (i = 0; i < Pool_Size; i++) {
690 if (My_Connections[i].sock <= NONE)
693 wdatalen = array_bytes(&My_Connections[i].wbuf);
696 array_bytes(&My_Connections[i].zip.wbuf) > 0)
702 if (SSL_WantRead(&My_Connections[i]))
705 io_event_add(My_Connections[i].sock,
710 /* Check from which sockets we possibly could read ... */
711 for (i = 0; i < Pool_Size; i++) {
712 if (My_Connections[i].sock <= NONE)
715 if (SSL_WantWrite(&My_Connections[i]))
716 /* TLS/SSL layer needs to write data; deal
717 * with this first! */
720 if (Proc_InProgress(&My_Connections[i].proc_stat)) {
721 /* Wait for completion of forked subprocess
722 * and ignore the socket in the meantime ... */
723 io_event_del(My_Connections[i].sock,
728 if (Conn_OPTION_ISSET(&My_Connections[i], CONN_ISCONNECTING))
729 /* Wait for completion of connect() ... */
732 if (My_Connections[i].delaytime > t) {
733 /* There is a "penalty time" set: ignore socket! */
734 io_event_del(My_Connections[i].sock,
739 if (array_bytes(&My_Connections[i].rbuf) >= COMMAND_LEN) {
740 /* There is still more data in the read buffer
741 * than a single valid command can get long:
742 * so either there is a complete command, or
743 * invalid data. Therefore don't try to read in
744 * even more data from the network but wait for
745 * this command(s) to be handled first! */
746 io_event_del(My_Connections[i].sock,
748 command_available = true;
752 io_event_add(My_Connections[i].sock, IO_WANTREAD);
755 /* Don't wait for data when there is still at least one command
756 * available in a read buffer which can be handled immediately;
757 * set the timeout for reading from the network to 1 second
758 * otherwise, which is the granularity with witch we handle
759 * "penalty times" for example.
760 * Note: tv_sec/usec are undefined(!) after io_dispatch()
761 * returns, so we have to set it before each call to it! */
763 tv.tv_sec = command_available ? 0 : 1;
765 /* Wait for activity ... */
766 i = io_dispatch(&tv);
767 if (i == -1 && errno != EINTR) {
768 Log(LOG_EMERG, "Conn_Handler(): io_dispatch(): %s!",
770 Log(LOG_ALERT, "%s exiting due to fatal errors!",
775 /* Should ngIRCd timeout when idle? */
776 if (Conf_IdleTimeout > 0 && NumConnectionsAccepted > 0
777 && idle_t > 0 && time(NULL) - idle_t >= Conf_IdleTimeout) {
778 LogDebug("Server idle timeout reached: %d second%s. Initiating shutdown ...",
780 Conf_IdleTimeout == 1 ? "" : "s");
781 NGIRCd_SignalQuit = true;
785 if (NGIRCd_SignalQuit)
786 Log(LOG_NOTICE | LOG_snotice, "Server going down NOW!");
787 else if (NGIRCd_SignalRestart)
788 Log(LOG_NOTICE | LOG_snotice, "Server restarting NOW!");
792 * Write a text string into the socket of a connection.
794 * This function automatically appends CR+LF to the string and validates that
795 * the result is a valid IRC message (oversized messages are shortened, for
796 * example). Then it calls the Conn_Write() function to do the actual sending.
798 * @param Idx Index fo the connection.
799 * @param Format Format string, see printf().
800 * @returns true on success, false otherwise.
804 Conn_WriteStr(CONN_ID Idx, const char *Format, ...)
807 Conn_WriteStr(Idx, Format, va_alist)
813 char buffer[COMMAND_LEN];
822 assert( Idx > NONE );
823 assert( Format != NULL );
826 va_start( ap, Format );
830 r = vsnprintf(buffer, COMMAND_LEN - 2, Format, ap);
831 if (r >= COMMAND_LEN - 2 || r == -1) {
833 * The string that should be written to the socket is longer
834 * than the allowed size of COMMAND_LEN bytes (including both
835 * the CR and LF characters). This can be caused by the
836 * IRC_WriteXXX() functions when the prefix of this server had
837 * to be added to an already "quite long" command line which
838 * has been received from a regular IRC client, for example.
840 * We are not allowed to send such "oversized" messages to
841 * other servers and clients, see RFC 2812 2.3 and 2813 3.3
842 * ("these messages SHALL NOT exceed 512 characters in length,
843 * counting all characters including the trailing CR-LF").
845 * So we have a big problem here: we should send more bytes
846 * to the network than we are allowed to and we don't know
847 * the originator (any more). The "old" behavior of blaming
848 * the receiver ("next hop") is a bad idea (it could be just
849 * an other server only routing the message!), so the only
850 * option left is to shorten the string and to hope that the
851 * result is still somewhat useful ...
854 * C99 states that vsnprintf() "returns the number of characters
855 * that would have been printed if the n were unlimited"; but
856 * according to the Linux manual page "glibc until 2.0.6 would
857 * return -1 when the output was truncated" -- so we have to
858 * handle both cases ...
862 strcpy (buffer + sizeof(buffer) - strlen(CUT_TXTSUFFIX) - 2 - 1,
867 ptr = strchr(buffer + 1, ':');
870 message = Conn_EncodingTo(Idx, ptr);
872 strlcpy(ptr, message, sizeof(buffer) - (ptr - buffer));
878 LogDebug("-> connection %d: '%s'.", Idx, buffer);
881 len = strlcat( buffer, "\r\n", sizeof( buffer ));
882 ok = Conn_Write(Idx, buffer, len);
883 My_Connections[Idx].msg_out++;
887 } /* Conn_WriteStr */
890 Conn_Password( CONN_ID Idx )
892 assert( Idx > NONE );
893 if (My_Connections[Idx].pwd == NULL)
896 return My_Connections[Idx].pwd;
897 } /* Conn_Password */
900 Conn_SetPassword( CONN_ID Idx, const char *Pwd )
902 assert( Idx > NONE );
904 if (My_Connections[Idx].pwd)
905 free(My_Connections[Idx].pwd);
907 My_Connections[Idx].pwd = strdup(Pwd);
908 if (My_Connections[Idx].pwd == NULL) {
909 Log(LOG_EMERG, "Can't allocate memory! [Conn_SetPassword]");
912 } /* Conn_SetPassword */
915 * Append Data to the outbound write buffer of a connection.
917 * @param Idx Index of the connection.
918 * @param Data pointer to the data.
919 * @param Len length of Data.
920 * @returns true on success, false otherwise.
923 Conn_Write( CONN_ID Idx, char *Data, size_t Len )
926 size_t writebuf_limit = WRITEBUFFER_MAX_LEN;
927 assert( Idx > NONE );
928 assert( Data != NULL );
931 /* Is the socket still open? A previous call to Conn_Write()
932 * may have closed the connection due to a fatal error.
933 * In this case it is sufficient to return an error, as well. */
934 if (My_Connections[Idx].sock <= NONE) {
935 LogDebug("Skipped write on closed socket (connection %d).", Idx);
939 /* Make sure that there still exists a CLIENT structure associated
940 * with this connection and check if this is a server or not: */
941 c = Conn_GetClient(Idx);
943 /* Servers do get special write buffer limits, so they can
944 * generate all the messages that are required while peering. */
945 if (Client_Type(c) == CLIENT_SERVER)
946 writebuf_limit = WRITEBUFFER_SLINK_LEN;
948 LogDebug("Write on socket without client (connection %d)!?", Idx);
951 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
953 * Zip_Buffer() does all the dirty work for us: it flushes
954 * the (pre-)compression buffers if required and handles
955 * all error conditions. */
956 if (!Zip_Buffer(Idx, Data, Len))
962 /* Uncompressed link:
963 * Check if outbound buffer has enough space for the data. */
964 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
965 WRITEBUFFER_FLUSH_LEN) {
966 /* Buffer is full, flush it. Handle_Write deals with
967 * low-level errors, if any. */
968 if (!Handle_Write(Idx))
972 /* When the write buffer is still too big after flushing it,
973 * the connection will be killed. */
974 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
977 "Write buffer space exhausted (connection %d, limit is %lu bytes, %lu bytes new, %lu bytes pending)",
978 Idx, writebuf_limit, Len,
979 (unsigned long)array_bytes(&My_Connections[Idx].wbuf));
980 Conn_Close(Idx, "Write buffer space exhausted", NULL, false);
984 /* Copy data to write buffer */
985 if (!array_catb(&My_Connections[Idx].wbuf, Data, Len))
988 My_Connections[Idx].bytes_out += Len;
991 /* Adjust global write counter */
998 * Shut down a connection.
1000 * @param Idx Connection index.
1001 * @param LogMsg Message to write to the log or NULL. If no LogMsg
1002 * is given, the FwdMsg is logged.
1003 * @param FwdMsg Message to forward to remote servers.
1004 * @param InformClient If true, inform the client on the connection which is
1005 * to be shut down of the reason (FwdMsg) and send
1006 * connection statistics before disconnecting it.
1009 Conn_Close(CONN_ID Idx, const char *LogMsg, const char *FwdMsg, bool InformClient)
1011 /* Close connection. Open pipes of asynchronous resolver
1012 * sub-processes are closed down. */
1018 double in_z_k, out_z_k;
1022 assert( Idx > NONE );
1024 /* Is this link already shutting down? */
1025 if( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ISCLOSING )) {
1026 /* Conn_Close() has been called recursively for this link;
1027 * probable reason: Handle_Write() failed -- see below. */
1028 LogDebug("Recursive request to close connection %d!", Idx );
1032 assert( My_Connections[Idx].sock > NONE );
1034 /* Mark link as "closing" */
1035 Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCLOSING );
1037 port = ng_ipaddr_getport(&My_Connections[Idx].addr);
1038 Log(LOG_INFO, "Shutting down connection %d (%s) with \"%s:%d\" ...", Idx,
1039 LogMsg ? LogMsg : FwdMsg, My_Connections[Idx].host, port);
1041 /* Search client, if any */
1042 c = Conn_GetClient( Idx );
1044 /* Should the client be informed? */
1047 /* Send statistics to client if registered as user: */
1048 if ((c != NULL) && (Client_Type(c) == CLIENT_USER)) {
1050 ":%s NOTICE %s :%sConnection statistics: client %.1f kb, server %.1f kb.",
1051 Client_ID(Client_ThisServer()), Client_ID(c),
1053 (double)My_Connections[Idx].bytes_in / 1024,
1054 (double)My_Connections[Idx].bytes_out / 1024);
1057 /* Send ERROR to client (see RFC 2812, section 3.1.7) */
1059 Conn_WriteStr(Idx, "ERROR :Closing connection: %s[%s@%s] (%s)",
1060 Client_ID(c), Client_User(c), Client_Hostname(c),
1061 FwdMsg ? FwdMsg : "\"\"");
1063 Conn_WriteStr(Idx, "ERROR :Closing connection");
1066 /* Try to write out the write buffer. Note: Handle_Write() eventually
1067 * removes the CLIENT structure associated with this connection if an
1068 * error occurs! So we have to re-check if there is still an valid
1069 * CLIENT structure after calling Handle_Write() ...*/
1070 (void)Handle_Write( Idx );
1072 /* Search client, if any (re-check!) */
1073 c = Conn_GetClient( Idx );
1075 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_SSL )) {
1076 LogDebug("SSL connection %d shutting down ...", Idx);
1077 ConnSSL_Free(&My_Connections[Idx]);
1080 /* Shut down socket */
1081 if (! io_close(My_Connections[Idx].sock)) {
1082 /* Oops, we can't close the socket!? This is ... ugly! */
1084 "Error closing connection %d (socket %d) with %s:%d - %s! (ignored)",
1085 Idx, My_Connections[Idx].sock, My_Connections[Idx].host,
1086 port, strerror(errno));
1089 /* Mark socket as invalid: */
1090 My_Connections[Idx].sock = NONE;
1092 /* If there is still a client, unregister it now */
1094 Client_Destroy(c, LogMsg, FwdMsg, true);
1096 /* Calculate statistics and log information */
1097 in_k = (double)My_Connections[Idx].bytes_in / 1024;
1098 out_k = (double)My_Connections[Idx].bytes_out / 1024;
1100 if (Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP)) {
1101 in_z_k = (double)My_Connections[Idx].zip.bytes_in / 1024;
1102 out_z_k = (double)My_Connections[Idx].zip.bytes_out / 1024;
1103 /* Make sure that no division by zero can occur during
1104 * the calculation of in_p and out_p: in_z_k and out_z_k
1105 * are non-zero, that's guaranteed by the protocol until
1106 * compression can be enabled. */
1111 in_p = (int)(( in_k * 100 ) / in_z_k );
1112 out_p = (int)(( out_k * 100 ) / out_z_k );
1114 "Connection %d with \"%s:%d\" closed (in: %.1fk/%.1fk/%d%%, out: %.1fk/%.1fk/%d%%).",
1115 Idx, My_Connections[Idx].host, port,
1116 in_k, in_z_k, in_p, out_k, out_z_k, out_p);
1122 "Connection %d with \"%s:%d\" closed (in: %.1fk, out: %.1fk).",
1123 Idx, My_Connections[Idx].host, port,
1127 /* Servers: Modify time of next connect attempt? */
1128 Conf_UnsetServer( Idx );
1131 /* Clean up zlib, if link was compressed */
1132 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
1133 inflateEnd( &My_Connections[Idx].zip.in );
1134 deflateEnd( &My_Connections[Idx].zip.out );
1135 array_free(&My_Connections[Idx].zip.rbuf);
1136 array_free(&My_Connections[Idx].zip.wbuf);
1140 array_free(&My_Connections[Idx].rbuf);
1141 array_free(&My_Connections[Idx].wbuf);
1142 if (My_Connections[Idx].pwd != NULL)
1143 free(My_Connections[Idx].pwd);
1145 /* Clean up connection structure (=free it) */
1146 Init_Conn_Struct( Idx );
1148 assert(NumConnections > 0);
1151 LogDebug("Shutdown of connection %d completed, %ld connection%s left.",
1152 Idx, NumConnections, NumConnections != 1 ? "s" : "");
1154 idle_t = NumConnections > 0 ? 0 : time(NULL);
1158 * Get current number of connections.
1160 * @returns Number of current connections.
1165 return NumConnections;
1169 * Get number of maximum simultaneous connections.
1171 * @returns Number of maximum simultaneous connections.
1176 return NumConnectionsMax;
1177 } /* Conn_CountMax */
1180 * Get number of connections accepted since the daemon startet.
1182 * @returns Number of connections accepted.
1185 Conn_CountAccepted(void)
1187 return NumConnectionsAccepted;
1188 } /* Conn_CountAccepted */
1191 * Synchronize established connections and configured server structures
1192 * after a configuration update and store the correct connection IDs, if any.
1195 Conn_SyncServerStruct(void)
1201 for (i = 0; i < Pool_Size; i++) {
1202 if (My_Connections[i].sock == NONE)
1206 client = Conn_GetClient(i);
1207 if (!client || Client_Type(client) != CLIENT_SERVER)
1210 for (c = 0; c < MAX_SERVERS; c++) {
1211 /* Configured server? */
1212 if (!Conf_Server[c].host[0])
1215 if (strcasecmp(Conf_Server[c].name, Client_ID(client)) == 0)
1216 Conf_Server[c].conn_id = i;
1219 } /* SyncServerStruct */
1222 * Get IP address string of a connection.
1224 * @param Idx Connection index.
1225 * @return Pointer to a global buffer containing the IP address as string.
1228 Conn_GetIPAInfo(CONN_ID Idx)
1231 return ng_ipaddr_tostr(&My_Connections[Idx].addr);
1235 * Send out data of write buffer; connect new sockets.
1237 * @param Idx Connection index.
1238 * @returns true on success, false otherwise.
1241 Handle_Write( CONN_ID Idx )
1246 assert( Idx > NONE );
1247 if ( My_Connections[Idx].sock < 0 ) {
1248 LogDebug("Handle_Write() on closed socket, connection %d", Idx);
1251 assert( My_Connections[Idx].sock > NONE );
1253 wdatalen = array_bytes(&My_Connections[Idx].wbuf );
1256 if (wdatalen == 0) {
1257 /* Write buffer is empty, so we try to flush the compression
1258 * buffer and get some data to work with from there :-) */
1259 if (!Zip_Flush(Idx))
1262 /* Now the write buffer most probably has changed: */
1263 wdatalen = array_bytes(&My_Connections[Idx].wbuf);
1267 if (wdatalen == 0) {
1268 /* Still no data, fine. */
1269 io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
1275 ("Handle_Write() called for connection %d, %ld bytes pending ...",
1280 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_SSL )) {
1281 len = ConnSSL_Write(&My_Connections[Idx],
1282 array_start(&My_Connections[Idx].wbuf),
1287 len = write(My_Connections[Idx].sock,
1288 array_start(&My_Connections[Idx].wbuf), wdatalen );
1291 if (errno == EAGAIN || errno == EINTR)
1294 /* Log write errors but do not close the connection yet.
1295 * Calling Conn_Close() now could result in too many recursive calls.
1297 if (!Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ISCLOSING))
1299 "Write error on connection %d (socket %d): %s!",
1300 Idx, My_Connections[Idx].sock, strerror(errno));
1302 LogDebug("Recursive write error on connection %d (socket %d): %s!",
1303 Idx, My_Connections[Idx].sock, strerror(errno));
1308 /* move any data not yet written to beginning */
1309 array_moveleft(&My_Connections[Idx].wbuf, 1, (size_t)len);
1312 } /* Handle_Write */
1315 * Count established connections to a specific IP address.
1317 * @returns Number of established connections.
1320 Count_Connections(ng_ipaddr_t *a)
1325 for (i = 0; i < Pool_Size; i++) {
1326 if (My_Connections[i].sock <= NONE)
1328 if (ng_ipaddr_ipequal(&My_Connections[i].addr, a))
1332 } /* Count_Connections */
1335 * Initialize new client connection on a listening socket.
1337 * @param Sock Listening socket descriptor.
1338 * @param IsSSL true if this socket expects SSL-encrypted data.
1339 * @returns Accepted socket descriptor or -1 on error.
1342 New_Connection(int Sock, UNUSED bool IsSSL)
1345 struct request_info req;
1347 ng_ipaddr_t new_addr;
1348 char ip_str[NG_INET_ADDRSTRLEN];
1349 int new_sock, new_sock_len;
1353 assert(Sock > NONE);
1355 LogDebug("Accepting new connection on socket %d ...", Sock);
1357 new_sock_len = (int)sizeof(new_addr);
1358 new_sock = accept(Sock, (struct sockaddr *)&new_addr,
1359 (socklen_t *)&new_sock_len);
1361 Log(LOG_CRIT, "Can't accept connection on socket %d: %s!",
1362 Sock, strerror(errno));
1365 NumConnectionsAccepted++;
1367 if (!ng_ipaddr_tostr_r(&new_addr, ip_str)) {
1368 Log(LOG_CRIT, "Can't convert peer IP address of socket %d!", new_sock);
1369 Simple_Message(new_sock, "ERROR :Internal Server Error");
1375 /* Validate socket using TCP Wrappers */
1376 request_init(&req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock,
1377 RQ_CLIENT_SIN, &new_addr, NULL);
1379 if (!hosts_access(&req)) {
1381 "Refused connection from %s on socket %d (by TCP Wrappers)!",
1383 Simple_Message(new_sock, "ERROR :Connection refused");
1389 if (!Init_Socket(new_sock))
1392 /* Check global connection limit */
1393 if ((Conf_MaxConnections > 0) &&
1394 (NumConnections >= (size_t) Conf_MaxConnections)) {
1395 Log(LOG_ALERT, "Can't accept new connection on socket %d: Limit (%d) reached!",
1396 Sock, Conf_MaxConnections);
1397 Simple_Message(new_sock, "ERROR :Connection limit reached");
1402 /* Check IP-based connection limit */
1403 cnt = Count_Connections(&new_addr);
1404 if ((Conf_MaxConnectionsIP > 0) && (cnt >= Conf_MaxConnectionsIP)) {
1405 /* Access denied, too many connections from this IP address! */
1407 "Refused connection from %s on socket %d: too may connections (%ld) from this IP address!",
1409 Simple_Message(new_sock,
1410 "ERROR :Connection refused, too many connections from your IP address");
1415 if (Socket2Index(new_sock) <= NONE) {
1416 Simple_Message(new_sock, "ERROR: Internal error");
1421 /* register callback */
1422 if (!io_event_create(new_sock, IO_WANTREAD, cb_clientserver)) {
1424 "Can't accept connection: io_event_create failed!");
1425 Simple_Message(new_sock, "ERROR :Internal error");
1430 c = Client_NewLocal(new_sock, NULL, CLIENT_UNKNOWN, false);
1433 "Can't accept connection: can't create client structure!");
1434 Simple_Message(new_sock, "ERROR :Internal error");
1439 Init_Conn_Struct(new_sock);
1440 My_Connections[new_sock].sock = new_sock;
1441 My_Connections[new_sock].addr = new_addr;
1442 My_Connections[new_sock].client = c;
1444 /* Set initial hostname to IP address. This becomes overwritten when
1445 * the DNS lookup is enabled and succeeds, but is used otherwise. */
1446 if (ng_ipaddr_af(&new_addr) != AF_INET)
1447 snprintf(My_Connections[new_sock].host,
1448 sizeof(My_Connections[new_sock].host), "[%s]", ip_str);
1450 strlcpy(My_Connections[new_sock].host, ip_str,
1451 sizeof(My_Connections[new_sock].host));
1453 Client_SetHostname(c, My_Connections[new_sock].host);
1455 Log(LOG_INFO, "Accepted connection %d from \"%s:%d\" on socket %d.",
1456 new_sock, My_Connections[new_sock].host,
1457 ng_ipaddr_getport(&new_addr), Sock);
1458 Account_Connection();
1461 /* Delay connection initialization until SSL handshake is finished */
1464 Conn_StartLogin(new_sock);
1467 } /* New_Connection */
1470 * Finish connection initialization, start resolver subprocess.
1472 * @param Idx Connection index.
1475 Conn_StartLogin(CONN_ID Idx)
1477 int ident_sock = -1;
1481 /* Nothing to do if DNS (and resolver subprocess) is disabled */
1486 /* Should we make an IDENT request? */
1488 ident_sock = My_Connections[Idx].sock;
1491 if (Conf_NoticeBeforeRegistration) {
1492 /* Send "NOTICE *" messages to the client */
1495 (void)Conn_WriteStr(Idx,
1496 "NOTICE * :*** Looking up your hostname and checking ident");
1499 (void)Conn_WriteStr(Idx,
1500 "NOTICE * :*** Looking up your hostname");
1501 /* Send buffered data to the client, but break on errors
1502 * because Handle_Write() would have closed the connection
1503 * again in this case! */
1504 if (!Handle_Write(Idx))
1508 Resolve_Addr(&My_Connections[Idx].proc_stat, &My_Connections[Idx].addr,
1509 ident_sock, cb_Read_Resolver_Result);
1513 * Update global connection counters.
1516 Account_Connection(void)
1520 if (NumConnections > NumConnectionsMax)
1521 NumConnectionsMax = NumConnections;
1522 LogDebug("Total number of connections now %lu (max %lu).",
1523 NumConnections, NumConnectionsMax);
1524 } /* Account_Connection */
1527 * Translate socket handle into connection index (for historical reasons, it is
1528 * a 1:1 mapping today) and enlarge the "connection pool" accordingly.
1530 * @param Sock Socket handle.
1531 * @returns Connecion index or NONE when the pool is too small.
1534 Socket2Index( int Sock )
1537 assert(Pool_Size >= 0);
1539 if (Sock < Pool_Size)
1542 /* Try to allocate more memory ... */
1543 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)Sock)) {
1545 "Can't allocate memory to enlarge connection pool!");
1548 LogDebug("Enlarged connection pool for %ld sockets (%ld items, %ld bytes)",
1549 Sock, array_length(&My_ConnArray, sizeof(CONNECTION)),
1550 array_bytes(&My_ConnArray));
1552 /* Adjust pointer to new block, update size and initialize new items. */
1553 My_Connections = array_start(&My_ConnArray);
1554 while (Pool_Size <= Sock)
1555 Init_Conn_Struct(Pool_Size++);
1561 * Read data from the network to the read buffer. If an error occurs,
1562 * the socket of this connection will be shut down.
1564 * @param Idx Connection index.
1567 Read_Request(CONN_ID Idx)
1570 static const unsigned int maxbps = COMMAND_LEN / 2;
1571 char readbuf[READBUFFER_LEN];
1576 assert(My_Connections[Idx].sock > NONE);
1578 /* Check if the read buffer is "full". Basically this shouldn't happen
1579 * here, because as long as there possibly are commands in the read
1580 * buffer (buffer usage > COMMAND_LEN), the socket shouldn't be
1581 * scheduled for reading in Conn_Handler() at all ... */
1583 if ((array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN) ||
1584 (array_bytes(&My_Connections[Idx].zip.rbuf) >= READBUFFER_LEN))
1586 if (array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN)
1590 "Receive buffer space exhausted (connection %d): %d/%d bytes",
1591 Idx, array_bytes(&My_Connections[Idx].rbuf), READBUFFER_LEN);
1592 Conn_Close(Idx, "Receive buffer space exhausted", NULL, false);
1596 /* Now read new data from the network, up to READBUFFER_LEN bytes ... */
1598 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_SSL))
1599 len = ConnSSL_Read(&My_Connections[Idx], readbuf, sizeof(readbuf));
1602 len = read(My_Connections[Idx].sock, readbuf, sizeof(readbuf));
1605 LogDebug("Client \"%s:%u\" is closing connection %d ...",
1606 My_Connections[Idx].host,
1607 ng_ipaddr_getport(&My_Connections[Idx].addr), Idx);
1608 Conn_Close(Idx, NULL, "Client closed connection", false);
1613 if (errno == EAGAIN)
1616 Log(LOG_ERR, "Read error on connection %d (socket %d): %s!",
1617 Idx, My_Connections[Idx].sock, strerror(errno));
1618 Conn_Close(Idx, "Read error", "Client closed connection",
1623 /* Now append the newly received data to the connection buffer.
1624 * NOTE: This can lead to connection read buffers being bigger(!) than
1625 * READBUFFER_LEN bytes, as we add up to READBUFFER_LEN new bytes to a
1626 * buffer possibly being "almost" READBUFFER_LEN bytes already! */
1628 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1629 if (!array_catb(&My_Connections[Idx].zip.rbuf, readbuf,
1632 "Could not append received data to zip input buffer (connection %d): %d bytes!",
1634 Conn_Close(Idx, "Receive buffer space exhausted", NULL,
1641 if (!array_catb( &My_Connections[Idx].rbuf, readbuf, len)) {
1643 "Could not append received data to input buffer (connection %d): %d bytes!",
1645 Conn_Close(Idx, "Receive buffer space exhausted", NULL,
1650 /* Update connection statistics */
1651 My_Connections[Idx].bytes_in += len;
1653 /* Handle read buffer */
1654 My_Connections[Idx].bps += Handle_Buffer(Idx);
1656 /* Make sure that there is still a valid client registered */
1657 c = Conn_GetClient(Idx);
1661 /* Update timestamp of last data received if this connection is
1662 * registered as a user, server or service connection. Don't update
1663 * otherwise, so users have at least Conf_PongTimeout seconds time to
1664 * register with the IRC server -- see Check_Connections().
1665 * Update "lastping", too, if time shifted backwards ... */
1666 if (Client_Type(c) == CLIENT_USER
1667 || Client_Type(c) == CLIENT_SERVER
1668 || Client_Type(c) == CLIENT_SERVICE) {
1670 if (My_Connections[Idx].lastdata != t)
1671 My_Connections[Idx].bps = 0;
1673 My_Connections[Idx].lastdata = t;
1674 if (My_Connections[Idx].lastping > t)
1675 My_Connections[Idx].lastping = t;
1678 /* Look at the data in the (read-) buffer of this connection */
1679 if (My_Connections[Idx].bps >= maxbps)
1680 Throttle_Connection(Idx, c, THROTTLE_BPS, maxbps);
1681 } /* Read_Request */
1684 * Handle all data in the connection read-buffer.
1686 * Data is processed until no complete command is left in the read buffer,
1687 * or MAX_COMMANDS[_SERVER|_SERVICE] commands were processed.
1688 * When a fatal error occurs, the connection is shut down.
1690 * @param Idx Index of the connection.
1691 * @returns Number of bytes processed.
1694 Handle_Buffer(CONN_ID Idx)
1697 char *ptr1, *ptr2, *first_eol;
1705 unsigned int i, maxcmd = MAX_COMMANDS, len_processed = 0;
1708 c = Conn_GetClient(Idx);
1709 starttime = time(NULL);
1713 /* Servers get special command limits that depend on the user count */
1714 switch (Client_Type(c)) {
1716 maxcmd = (int)(Client_UserCount() / 5)
1717 + MAX_COMMANDS_SERVER_MIN;
1718 /* Allow servers to handle even more commands while peering
1719 * to speed up server login and network synchronization. */
1720 if (Conn_LastPing(Idx) == 0)
1723 case CLIENT_SERVICE:
1724 maxcmd = MAX_COMMANDS_SERVICE;
1727 if (Client_HasMode(c, 'F'))
1728 maxcmd = MAX_COMMANDS_SERVICE;
1732 for (i=0; i < maxcmd; i++) {
1734 if (My_Connections[Idx].delaytime > starttime)
1737 /* Unpack compressed data, if compression is in use */
1738 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1739 /* When unzipping fails, Unzip_Buffer() shuts
1740 * down the connection itself */
1741 if (!Unzip_Buffer(Idx))
1746 if (0 == array_bytes(&My_Connections[Idx].rbuf))
1749 /* Make sure that the buffer is NULL terminated */
1750 if (!array_cat0_temporary(&My_Connections[Idx].rbuf)) {
1751 Conn_Close(Idx, NULL,
1752 "Can't allocate memory [Handle_Buffer]",
1757 /* RFC 2812, section "2.3 Messages", 5th paragraph:
1758 * "IRC messages are always lines of characters terminated
1759 * with a CR-LF (Carriage Return - Line Feed) pair [...]". */
1761 ptr = strstr(array_start(&My_Connections[Idx].rbuf), "\r\n");
1764 /* Check for non-RFC-compliant request (only CR or LF)?
1765 * Unfortunately, there are quite a few clients out there
1766 * that do this -- e. g. mIRC, BitchX, and Trillian :-( */
1767 ptr1 = strchr(array_start(&My_Connections[Idx].rbuf), '\r');
1768 ptr2 = strchr(array_start(&My_Connections[Idx].rbuf), '\n');
1770 /* Check if there is a single CR or LF _before_ the
1771 * correct CR+LF line terminator: */
1772 first_eol = ptr1 < ptr2 ? ptr1 : ptr2;
1773 if (first_eol < ptr) {
1774 /* Single CR or LF before CR+LF found */
1778 } else if (ptr1 || ptr2) {
1779 /* No CR+LF terminated command found, but single
1780 * CR or LF found ... */
1782 ptr = ptr1 < ptr2 ? ptr1 : ptr2;
1784 ptr = ptr1 ? ptr1 : ptr2;
1792 /* Complete (=line terminated) request found, handle it! */
1795 len = ptr - (char *)array_start(&My_Connections[Idx].rbuf) + delta;
1797 if (len > (COMMAND_LEN - 1)) {
1798 /* Request must not exceed 512 chars (incl. CR+LF!),
1799 * see RFC 2812. Disconnect Client if this happens. */
1801 "Request too long (connection %d): %d bytes (max. %d expected)!",
1802 Idx, array_bytes(&My_Connections[Idx].rbuf),
1804 Conn_Close(Idx, NULL, "Request too long", true);
1808 len_processed += (unsigned int)len;
1810 /* Request is empty (only '\r\n', '\r' or '\n');
1811 * delta is 2 ('\r\n') or 1 ('\r' or '\n'), see above */
1812 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1816 /* remember if stream is already compressed */
1817 old_z = My_Connections[Idx].options & CONN_ZIP;
1820 My_Connections[Idx].msg_in++;
1822 (Idx, (char *)array_start(&My_Connections[Idx].rbuf)))
1823 return 0; /* error -> connection has been closed */
1825 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1827 if ((!old_z) && (My_Connections[Idx].options & CONN_ZIP) &&
1828 (array_bytes(&My_Connections[Idx].rbuf) > 0)) {
1829 /* The last command activated socket compression.
1830 * Data that was read after that needs to be copied
1831 * to the unzip buffer for decompression: */
1833 (&My_Connections[Idx].zip.rbuf,
1834 &My_Connections[Idx].rbuf)) {
1835 Conn_Close(Idx, NULL,
1836 "Can't allocate memory [Handle_Buffer]",
1841 array_trunc(&My_Connections[Idx].rbuf);
1843 ("Moved already received data (%u bytes) to uncompression buffer.",
1844 array_bytes(&My_Connections[Idx].zip.rbuf));
1849 LogDebug("Connection %d: Processed %ld commands (max=%ld), %ld bytes. %ld bytes left in read buffer.",
1850 Idx, i, maxcmd, len_processed,
1851 array_bytes(&My_Connections[Idx].rbuf));
1854 /* If data has been processed but there is still data in the read
1855 * buffer, the command limit triggered. Enforce the penalty time: */
1856 if (len_processed && array_bytes(&My_Connections[Idx].rbuf) > 2)
1857 Throttle_Connection(Idx, c, THROTTLE_CMDS, maxcmd);
1859 return len_processed;
1860 } /* Handle_Buffer */
1863 * Check whether established connections are still alive or not.
1864 * If not, play PING-PONG first; and if that doesn't help either,
1865 * disconnect the respective peer.
1868 Check_Connections(void)
1875 time_now = time(NULL);
1877 for (i = 0; i < Pool_Size; i++) {
1878 if (My_Connections[i].sock < 0)
1881 c = Conn_GetClient(i);
1882 if (c && ((Client_Type(c) == CLIENT_USER)
1883 || (Client_Type(c) == CLIENT_SERVER)
1884 || (Client_Type(c) == CLIENT_SERVICE))) {
1885 /* connected User, Server or Service */
1886 if (My_Connections[i].lastping >
1887 My_Connections[i].lastdata) {
1888 /* We already sent a ping */
1889 if (My_Connections[i].lastping <
1890 time_now - Conf_PongTimeout) {
1892 snprintf(msg, sizeof(msg),
1893 "Ping timeout: %d seconds",
1895 LogDebug("Connection %d: %s.", i, msg);
1896 Conn_Close(i, NULL, msg, true);
1898 } else if (My_Connections[i].lastdata <
1899 time_now - Conf_PingTimeout) {
1900 /* We need to send a PING ... */
1901 LogDebug("Connection %d: sending PING ...", i);
1902 Conn_UpdatePing(i, time_now);
1903 Conn_WriteStr(i, "PING :%s",
1904 Client_ID(Client_ThisServer()));
1907 /* The connection is not fully established yet, so
1908 * we don't do the PING-PONG game here but instead
1909 * disconnect the client after "a short time" if it's
1910 * still not registered. */
1912 if (My_Connections[i].lastdata <
1913 time_now - Conf_PongTimeout) {
1915 ("Unregistered connection %d timed out ...",
1917 Conn_Close(i, NULL, "Timeout", false);
1921 } /* Check_Connections */
1924 * Check if further server links should be established.
1932 time_now = time(NULL);
1934 /* Check all configured servers */
1935 for (i = 0; i < MAX_SERVERS; i++) {
1936 if (Conf_Server[i].conn_id != NONE)
1937 continue; /* Already establishing or connected */
1938 if (!Conf_Server[i].host[0] || Conf_Server[i].port <= 0)
1939 continue; /* No host and/or port configured */
1940 if (Conf_Server[i].flags & CONF_SFLAG_DISABLED)
1941 continue; /* Disabled configuration entry */
1942 if (Conf_Server[i].lasttry > (time_now - Conf_ConnectRetry))
1943 continue; /* We have to wait a little bit ... */
1945 /* Is there already a connection in this group? */
1946 if (Conf_Server[i].group > NONE) {
1947 for (n = 0; n < MAX_SERVERS; n++) {
1950 if ((Conf_Server[n].conn_id != NONE) &&
1951 (Conf_Server[n].group == Conf_Server[i].group))
1954 if (n < MAX_SERVERS)
1958 /* Okay, try to connect now */
1960 "Preparing to establish a new server link for \"%s\" ...",
1961 Conf_Server[i].name);
1962 Conf_Server[i].lasttry = time_now;
1963 Conf_Server[i].conn_id = SERVER_WAIT;
1964 assert(Proc_GetPipeFd(&Conf_Server[i].res_stat) < 0);
1966 /* Start resolver subprocess ... */
1967 if (!Resolve_Name(&Conf_Server[i].res_stat, Conf_Server[i].host,
1968 cb_Connect_to_Server))
1969 Conf_Server[i].conn_id = NONE;
1971 } /* Check_Servers */
1974 * Establish a new outgoing server connection.
1976 * @param Server Configuration index of the server.
1977 * @param dest Destination IP address to connect to.
1980 New_Server( int Server , ng_ipaddr_t *dest)
1982 /* Establish new server link */
1983 char ip_str[NG_INET_ADDRSTRLEN];
1984 int af_dest, res, new_sock;
1987 assert( Server > NONE );
1989 /* Make sure that the remote server hasn't re-linked to this server
1990 * asynchronously on its own */
1991 if (Conf_Server[Server].conn_id > NONE) {
1993 "Connection to \"%s\" meanwhile re-established, aborting preparation.");
1997 if (!ng_ipaddr_tostr_r(dest, ip_str)) {
1998 Log(LOG_WARNING, "New_Server: Could not convert IP to string");
1999 Conf_Server[Server].conn_id = NONE;
2003 af_dest = ng_ipaddr_af(dest);
2004 new_sock = socket(af_dest, SOCK_STREAM, 0);
2007 "Establishing connection for \"%s\" to \"%s:%d\" (%s), socket %d ...",
2008 Conf_Server[Server].name, Conf_Server[Server].host,
2009 Conf_Server[Server].port, ip_str, new_sock);
2012 Log(LOG_CRIT, "Can't create socket (af %d): %s!",
2013 af_dest, strerror(errno));
2014 Conf_Server[Server].conn_id = NONE;
2018 if (!Init_Socket(new_sock)) {
2019 Conf_Server[Server].conn_id = NONE;
2023 /* is a bind address configured? */
2024 res = ng_ipaddr_af(&Conf_Server[Server].bind_addr);
2026 /* if yes, bind now. If it fails, warn and let connect() pick a
2028 if (res && bind(new_sock, (struct sockaddr *) &Conf_Server[Server].bind_addr,
2029 ng_ipaddr_salen(&Conf_Server[Server].bind_addr)))
2031 ng_ipaddr_tostr_r(&Conf_Server[Server].bind_addr, ip_str);
2032 Log(LOG_WARNING, "Can't bind socket to %s: %s!", ip_str,
2035 ng_ipaddr_setport(dest, Conf_Server[Server].port);
2036 res = connect(new_sock, (struct sockaddr *) dest, ng_ipaddr_salen(dest));
2037 if(( res != 0 ) && ( errno != EINPROGRESS )) {
2038 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
2040 Conf_Server[Server].conn_id = NONE;
2044 if (Socket2Index(new_sock) <= NONE) {
2046 Conf_Server[Server].conn_id = NONE;
2050 if (!io_event_create( new_sock, IO_WANTWRITE, cb_connserver)) {
2051 Log(LOG_ALERT, "io_event_create(): could not add fd %d",
2054 Conf_Server[Server].conn_id = NONE;
2058 assert(My_Connections[new_sock].sock <= 0);
2060 Init_Conn_Struct(new_sock);
2062 ng_ipaddr_tostr_r(dest, ip_str);
2063 c = Client_NewLocal(new_sock, ip_str, CLIENT_UNKNOWNSERVER, false);
2065 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
2067 Conf_Server[Server].conn_id = NONE;
2071 /* Conn_Close() decrements this counter again */
2072 Account_Connection();
2073 Client_SetIntroducer( c, c );
2074 Client_SetToken( c, TOKEN_OUTBOUND );
2076 /* Register connection */
2077 if (!Conf_SetServer(Server, new_sock))
2079 My_Connections[new_sock].sock = new_sock;
2080 My_Connections[new_sock].addr = *dest;
2081 My_Connections[new_sock].client = c;
2082 strlcpy( My_Connections[new_sock].host, Conf_Server[Server].host,
2083 sizeof(My_Connections[new_sock].host ));
2086 if (Conf_Server[Server].SSLConnect &&
2087 !ConnSSL_PrepareConnect(&My_Connections[new_sock], &Conf_Server[Server]))
2089 Log(LOG_ALERT, "Could not initialize SSL for outgoing connection");
2090 Conn_Close(new_sock, "Could not initialize SSL for outgoing connection",
2092 Init_Conn_Struct(new_sock);
2093 Conf_Server[Server].conn_id = NONE;
2097 LogDebug("Registered new connection %d on socket %d (%ld in total).",
2098 new_sock, My_Connections[new_sock].sock, NumConnections);
2099 Conn_OPTION_ADD( &My_Connections[new_sock], CONN_ISCONNECTING );
2103 * Initialize connection structure.
2105 * @param Idx Connection index.
2108 Init_Conn_Struct(CONN_ID Idx)
2110 time_t now = time(NULL);
2112 memset(&My_Connections[Idx], 0, sizeof(CONNECTION));
2113 My_Connections[Idx].sock = -1;
2114 My_Connections[Idx].signon = now;
2115 My_Connections[Idx].lastdata = now;
2116 My_Connections[Idx].lastprivmsg = now;
2117 Proc_InitStruct(&My_Connections[Idx].proc_stat);
2120 My_Connections[Idx].iconv_from = (iconv_t)(-1);
2121 My_Connections[Idx].iconv_to = (iconv_t)(-1);
2123 } /* Init_Conn_Struct */
2126 * Initialize options of a new socket.
2128 * For example, we try to set socket options SO_REUSEADDR and IPTOS_LOWDELAY.
2129 * The socket is automatically closed if a fatal error is encountered.
2131 * @param Sock Socket handle.
2132 * @returns false if socket was closed due to fatal error.
2135 Init_Socket( int Sock )
2139 if (!io_setnonblock(Sock)) {
2140 Log(LOG_CRIT, "Can't enable non-blocking mode for socket: %s!",
2146 /* Don't block this port after socket shutdown */
2148 if (setsockopt(Sock, SOL_SOCKET, SO_REUSEADDR, &value,
2149 (socklen_t)sizeof(value)) != 0) {
2150 Log(LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!",
2152 /* ignore this error */
2155 /* Set type of service (TOS) */
2156 #if defined(IPPROTO_IP) && defined(IPTOS_LOWDELAY)
2157 value = IPTOS_LOWDELAY;
2158 if (setsockopt(Sock, IPPROTO_IP, IP_TOS, &value,
2159 (socklen_t) sizeof(value))) {
2160 LogDebug("Can't set socket option IP_TOS: %s!",
2162 /* ignore this error */
2164 LogDebug("IP_TOS on socket %d has been set to IPTOS_LOWDELAY.",
2172 * Read results of a resolver sub-process and try to initiate a new server
2175 * @param fd File descriptor of the pipe to the sub-process.
2176 * @param events (ignored IO specification)
2179 cb_Connect_to_Server(int fd, UNUSED short events)
2184 /* we can handle at most 3 addresses; but we read up to 4 so we can
2185 * log the 'more than we can handle' condition. First result is tried
2186 * immediately, rest is saved for later if needed. */
2187 ng_ipaddr_t dest_addrs[4];
2189 LogDebug("Resolver: Got forward lookup callback on fd %d, events %d",
2192 for (i=0; i < MAX_SERVERS; i++) {
2193 if (Proc_GetPipeFd(&Conf_Server[i].res_stat) == fd )
2197 if( i >= MAX_SERVERS) {
2198 /* Ops, no matching server found?! */
2200 LogDebug("Resolver: Got Forward Lookup callback for unknown server!?");
2204 /* Read result from pipe */
2205 len = Proc_Read(&Conf_Server[i].res_stat, dest_addrs, sizeof(dest_addrs));
2206 Proc_Close(&Conf_Server[i].res_stat);
2208 /* Error resolving hostname: reset server structure */
2209 Conf_Server[i].conn_id = NONE;
2213 assert((len % sizeof(ng_ipaddr_t)) == 0);
2215 LogDebug("Got result from resolver: %u structs (%u bytes).",
2216 len/sizeof(ng_ipaddr_t), len);
2218 memset(&Conf_Server[i].dst_addr, 0, sizeof(Conf_Server[i].dst_addr));
2219 if (len > sizeof(ng_ipaddr_t)) {
2220 /* more than one address for this hostname, remember them
2221 * in case first address is unreachable/not available */
2222 len -= sizeof(ng_ipaddr_t);
2223 if (len > sizeof(Conf_Server[i].dst_addr)) {
2224 len = sizeof(Conf_Server[i].dst_addr);
2226 "Notice: Resolver returned more IP Addresses for host than we can handle, additional addresses dropped.");
2228 memcpy(&Conf_Server[i].dst_addr, &dest_addrs[1], len);
2231 New_Server(i, dest_addrs);
2232 } /* cb_Read_Forward_Lookup */
2235 * Read results of a resolver sub-process from the pipe and update the
2236 * appropriate connection/client structure(s): hostname and/or IDENT user name.
2238 * @param r_fd File descriptor of the pipe to the sub-process.
2239 * @param events (ignored IO specification)
2242 cb_Read_Resolver_Result( int r_fd, UNUSED short events )
2249 char readbuf[HOST_LEN + 2 + CLIENT_USER_LEN];
2252 char readbuf[HOST_LEN + 1];
2255 LogDebug("Resolver: Got callback on fd %d, events %d", r_fd, events );
2256 i = Conn_GetFromProc(r_fd);
2258 /* Ops, none found? Probably the connection has already
2259 * been closed!? We'll ignore that ... */
2261 LogDebug("Resolver: Got callback for unknown connection!?");
2265 /* Read result from pipe */
2266 len = Proc_Read(&My_Connections[i].proc_stat, readbuf, sizeof readbuf -1);
2267 Proc_Close(&My_Connections[i].proc_stat);
2271 readbuf[len] = '\0';
2272 identptr = strchr(readbuf, '\n');
2273 assert(identptr != NULL);
2275 Log( LOG_CRIT, "Resolver: Got malformed result!");
2280 LogDebug("Got result from resolver: \"%s\" (%u bytes read).", readbuf, len);
2281 /* Okay, we got a complete result: this is a host name for outgoing
2282 * connections and a host name and IDENT user name (if enabled) for
2283 * incoming connections.*/
2284 assert ( My_Connections[i].sock >= 0 );
2285 /* Incoming connection. Search client ... */
2286 c = Conn_GetClient( i );
2287 assert( c != NULL );
2289 /* Only update client information of unregistered clients.
2290 * Note: user commands (e. g. WEBIRC) are always read _after_ reading
2291 * the resolver results, so we don't have to worry to override settings
2292 * from these commands here. */
2293 if(Client_Type(c) == CLIENT_UNKNOWN) {
2294 strlcpy(My_Connections[i].host, readbuf,
2295 sizeof(My_Connections[i].host));
2296 Client_SetHostname(c, readbuf);
2297 if (Conf_NoticeBeforeRegistration)
2298 (void)Conn_WriteStr(i,
2299 "NOTICE * :*** Found your hostname: %s",
2300 My_Connections[i].host);
2306 if ((*ptr < '0' || *ptr > '9') &&
2307 (*ptr < 'A' || *ptr > 'Z') &&
2308 (*ptr < 'a' || *ptr > 'z'))
2313 /* Erroneous IDENT reply */
2315 "Got invalid IDENT reply for connection %d! Ignored.",
2319 "IDENT lookup for connection %d: \"%s\".",
2321 Client_SetUser(c, identptr, true);
2323 if (Conf_NoticeBeforeRegistration) {
2324 (void)Conn_WriteStr(i,
2325 "NOTICE * :*** Got %sident response%s%s",
2326 *ptr ? "invalid " : "",
2328 *ptr ? "" : identptr);
2330 } else if(Conf_Ident) {
2331 Log(LOG_INFO, "IDENT lookup for connection %d: no result.", i);
2332 if (Conf_NoticeBeforeRegistration)
2333 (void)Conn_WriteStr(i,
2334 "NOTICE * :*** No ident response");
2338 if (Conf_NoticeBeforeRegistration) {
2339 /* Send buffered data to the client, but break on
2340 * errors because Handle_Write() would have closed
2341 * the connection again in this case! */
2342 if (!Handle_Write(i))
2346 Class_HandleServerBans(c);
2349 LogDebug("Resolver: discarding result for already registered connection %d.", i);
2350 } /* cb_Read_Resolver_Result */
2353 * Write a "simple" (error) message to a socket.
2355 * The message is sent without using the connection write buffers, without
2356 * compression/encryption, and even without any error reporting. It is
2357 * designed for error messages of e.g. New_Connection().
2359 * @param Sock Socket handle.
2360 * @param Msg Message string to send.
2363 Simple_Message(int Sock, const char *Msg)
2365 char buf[COMMAND_LEN];
2368 assert(Sock > NONE);
2369 assert(Msg != NULL);
2371 strlcpy(buf, Msg, sizeof buf - 2);
2372 len = strlcat(buf, "\r\n", sizeof buf);
2373 if (write(Sock, buf, len) < 0) {
2374 /* Because this function most probably got called to log
2375 * an error message, any write error is ignored here to
2376 * avoid an endless loop. But casting the result of write()
2377 * to "void" doesn't satisfy the GNU C code attribute
2378 * "warn_unused_result" which is used by some versions of
2379 * glibc (e.g. 2.11.1), therefore this silly error
2380 * "handling" code here :-( */
2383 } /* Simple_Error */
2386 * Get CLIENT structure that belongs to a local connection identified by its
2387 * index number. Each connection belongs to a client by definition, so it is
2388 * not required that the caller checks for NULL return values.
2390 * @param Idx Connection index number.
2391 * @returns Pointer to CLIENT structure.
2394 Conn_GetClient( CONN_ID Idx )
2399 c = array_get(&My_ConnArray, sizeof (CONNECTION), (size_t)Idx);
2401 return c ? c->client : NULL;
2405 * Get PROC_STAT sub-process structure of a connection.
2407 * @param Idx Connection index number.
2408 * @returns PROC_STAT structure.
2411 Conn_GetProcStat(CONN_ID Idx)
2416 c = array_get(&My_ConnArray, sizeof (CONNECTION), (size_t)Idx);
2418 return &c->proc_stat;
2419 } /* Conn_GetProcStat */
2422 * Get CONN_ID from file descriptor associated to a subprocess structure.
2424 * @param fd File descriptor.
2425 * @returns CONN_ID or NONE (-1).
2428 Conn_GetFromProc(int fd)
2433 for (i = 0; i < Pool_Size; i++) {
2434 if ((My_Connections[i].sock != NONE)
2435 && (Proc_GetPipeFd(&My_Connections[i].proc_stat) == fd))
2439 } /* Conn_GetFromProc */
2442 * Throttle a connection because of excessive usage.
2444 * @param Reason The reason, see THROTTLE_xxx constants.
2445 * @param Idx The connection index.
2446 * @param Client The client of this connection.
2447 * @param Value The time to delay this connection.
2450 Throttle_Connection(const CONN_ID Idx, CLIENT *Client, const int Reason,
2454 assert(Client != NULL);
2456 /* Never throttle servers or services, only interrupt processing */
2457 if (Client_Type(Client) == CLIENT_SERVER
2458 || Client_Type(Client) == CLIENT_UNKNOWNSERVER
2459 || Client_Type(Client) == CLIENT_SERVICE)
2462 /* Don't throttle clients with user mode 'F' set */
2463 if (Client_HasMode(Client, 'F'))
2466 LogDebug("Throttling connection %d: code %d, value %d!", Idx,
2468 Conn_SetPenalty(Idx, 1);
2474 Conn_GetAuthPing(CONN_ID Idx)
2476 assert (Idx != NONE);
2477 return My_Connections[Idx].auth_ping;
2478 } /* Conn_GetAuthPing */
2481 Conn_SetAuthPing(CONN_ID Idx, long ID)
2483 assert (Idx != NONE);
2484 My_Connections[Idx].auth_ping = ID;
2485 } /* Conn_SetAuthPing */
2487 #endif /* STRICT_RFC */
2492 * IO callback for new SSL-enabled client and server connections.
2494 * @param sock Socket descriptor.
2495 * @param what IO specification (IO_WANTREAD/IO_WANTWRITE/...).
2498 cb_clientserver_ssl(int sock, UNUSED short what)
2500 CONN_ID idx = Socket2Index(sock);
2507 switch (ConnSSL_Accept(&My_Connections[idx])) {
2511 return; /* EAGAIN: callback will be invoked again by IO layer */
2514 "SSL accept error, closing socket", "SSL accept error",
2519 io_event_setcb(sock, cb_clientserver); /* SSL handshake completed */
2523 * IO callback for listening SSL sockets: handle new connections. This callback
2524 * gets called when a new SSL-enabled connection should be accepted.
2526 * @param sock Socket descriptor.
2527 * @param irrelevant (ignored IO specification)
2530 cb_listen_ssl(int sock, short irrelevant)
2535 fd = New_Connection(sock, true);
2538 io_event_setcb(My_Connections[fd].sock, cb_clientserver_ssl);
2542 * IO callback for new outgoing SSL-enabled server connections.
2544 * @param sock Socket descriptor.
2545 * @param unused (ignored IO specification)
2548 cb_connserver_login_ssl(int sock, short unused)
2550 CONN_ID idx = Socket2Index(sock);
2559 switch (ConnSSL_Connect( &My_Connections[idx])) {
2561 case 0: LogDebug("ConnSSL_Connect: not ready");
2564 Log(LOG_ERR, "SSL connection on socket %d failed!", sock);
2565 Conn_Close(idx, "Can't connect", NULL, false);
2569 Log( LOG_INFO, "SSL connection %d with \"%s:%d\" established.", idx,
2570 My_Connections[idx].host, Conf_Server[Conf_GetServer( idx )].port );
2577 * Check if SSL library needs to read SSL-protocol related data.
2579 * SSL/TLS connections require extra treatment:
2580 * When either CONN_SSL_WANT_WRITE or CONN_SSL_WANT_READ is set, we
2581 * need to take care of that first, before checking read/write buffers.
2582 * For instance, while we might have data in our write buffer, the
2583 * TLS/SSL protocol might need to read internal data first for TLS/SSL
2584 * writes to succeed.
2586 * If this function returns true, such a condition is met and we have
2587 * to reverse the condition (check for read even if we've data to write,
2588 * do not check for read but writeability even if write-buffer is empty).
2590 * @param c Connection to check.
2591 * @returns true if SSL-library has to read protocol data.
2594 SSL_WantRead(const CONNECTION *c)
2596 if (Conn_OPTION_ISSET(c, CONN_SSL_WANT_READ)) {
2597 io_event_add(c->sock, IO_WANTREAD);
2604 * Check if SSL library needs to write SSL-protocol related data.
2606 * Please see description of SSL_WantRead() for full description!
2608 * @param c Connection to check.
2609 * @returns true if SSL-library has to write protocol data.
2612 SSL_WantWrite(const CONNECTION *c)
2614 if (Conn_OPTION_ISSET(c, CONN_SSL_WANT_WRITE)) {
2615 io_event_add(c->sock, IO_WANTWRITE);
2622 * Get information about used SSL cipher.
2624 * @param Idx Connection index number.
2625 * @param buf Buffer for returned information text.
2626 * @param len Size of return buffer "buf".
2627 * @returns true on success, false otherwise.
2630 Conn_GetCipherInfo(CONN_ID Idx, char *buf, size_t len)
2634 assert(Idx < (int) array_length(&My_ConnArray, sizeof(CONNECTION)));
2635 return ConnSSL_GetCipherInfo(&My_Connections[Idx], buf, len);
2639 * Check if a connection is SSL-enabled or not.
2641 * @param Idx Connection index number.
2642 * @return true if connection is SSL-enabled, false otherwise.
2645 Conn_UsesSSL(CONN_ID Idx)
2649 assert(Idx < (int) array_length(&My_ConnArray, sizeof(CONNECTION)));
2650 return Conn_OPTION_ISSET(&My_Connections[Idx], CONN_SSL);
2654 Conn_GetCertFp(CONN_ID Idx)
2658 assert(Idx < (int) array_length(&My_ConnArray, sizeof(CONNECTION)));
2659 return ConnSSL_GetCertFp(&My_Connections[Idx]);
2663 Conn_SetCertFp(CONN_ID Idx, const char *fingerprint)
2667 assert(Idx < (int) array_length(&My_ConnArray, sizeof(CONNECTION)));
2668 return ConnSSL_SetCertFp(&My_Connections[Idx], fingerprint);
2671 #else /* SSL_SUPPORT */
2674 Conn_UsesSSL(UNUSED CONN_ID Idx)
2680 Conn_GetCertFp(UNUSED CONN_ID Idx)
2686 Conn_SetCertFp(UNUSED CONN_ID Idx, UNUSED const char *fingerprint)
2691 #endif /* SSL_SUPPORT */
2695 * Dump internal state of the "connection module".
2698 Conn_DebugDump(void)
2702 LogDebug("Connection status:");
2703 for (i = 0; i < Pool_Size; i++) {
2704 if (My_Connections[i].sock == NONE)
2707 " - %d: host=%s, lastdata=%ld, lastping=%ld, delaytime=%ld, flag=%d, options=%d, bps=%d, client=%s",
2708 My_Connections[i].sock, My_Connections[i].host,
2709 My_Connections[i].lastdata, My_Connections[i].lastping,
2710 My_Connections[i].delaytime, My_Connections[i].flag,
2711 My_Connections[i].options, My_Connections[i].bps,
2712 My_Connections[i].client ? Client_ID(My_Connections[i].client) : "-");
2714 } /* Conn_DumpClients */