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 );
185 LogDebug("cb_connserver wants to write on unknown socket?!");
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);
274 * IO callback for established non-SSL client and server connections.
276 * @param sock Socket descriptor.
277 * @param what IO specification (IO_WANTREAD/IO_WANTWRITE/...).
280 cb_clientserver(int sock, short what)
282 CONN_ID idx = Socket2Index(sock);
291 if (what & IO_WANTREAD
292 || (Conn_OPTION_ISSET(&My_Connections[idx], CONN_SSL_WANT_WRITE))) {
293 /* if TLS layer needs to write additional data, call
294 * Read_Request() instead so that SSL/TLS can continue */
298 if (what & IO_WANTREAD)
301 if (what & IO_WANTWRITE)
306 * Initialize connection module.
313 Pool_Size = CONNECTION_POOL;
314 if ((Conf_MaxConnections > 0) &&
315 (Pool_Size > Conf_MaxConnections))
316 Pool_Size = Conf_MaxConnections;
318 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)Pool_Size)) {
319 Log(LOG_EMERG, "Can't allocate memory! [Conn_Init]");
323 /* FIXME: My_Connetions/Pool_Size is needed by other parts of the
324 * code; remove them! */
325 My_Connections = (CONNECTION*) array_start(&My_ConnArray);
327 LogDebug("Allocated connection pool for %d items (%ld bytes).",
328 array_length(&My_ConnArray, sizeof(CONNECTION)),
329 array_bytes(&My_ConnArray));
331 assert(array_length(&My_ConnArray, sizeof(CONNECTION)) >= (size_t)Pool_Size);
333 array_free( &My_Listeners );
335 for (i = 0; i < Pool_Size; i++)
341 * create protocol and server identification.
342 * The syntax used by ngIRCd in PASS commands and the extended flags
343 * are described in doc/Protocol.txt
345 * @param i connection index, may be < 0 to get compile-time constants
346 * @return pointer to static buffer with the connection flags matching i.
349 Conn_BuildProtoID(CONN_ID i)
351 static char proto[256];
353 snprintf(proto, sizeof(proto), "%s%s %s|%s:%s", PROTOVER, PROTOIRCPLUS, PACKAGE_NAME, PACKAGE_VERSION, IRCPLUSFLAGS);
355 /* don't bother with link compression if ssl already does it */
357 if (i < 0 || !Conn_OPTION_ISSET(&My_Connections[i], CONN_SSL_COMPRESSION))
361 strlcat(proto, "Z", sizeof(proto));
363 if (Conf_OperCanMode)
364 strlcat(proto, "o", sizeof(proto));
366 snprintf(proto, sizeof(proto), "%s%s %s|%s", PROTOVER, PROTOIRC, PACKAGE_NAME, PACKAGE_VERSION);
368 strlcat(proto, " P", sizeof(proto));
371 if (i < 0 || !Conn_OPTION_ISSET(&My_Connections[i], CONN_SSL_COMPRESSION))
375 strlcat(proto, "Z", sizeof(proto));
382 * Clean up connection module.
389 Conn_ExitListeners();
391 LogDebug("Shutting down all connections ..." );
392 for( idx = 0; idx < Pool_Size; idx++ ) {
393 if( My_Connections[idx].sock > NONE ) {
394 Conn_Close( idx, NULL, NGIRCd_SignalRestart ?
395 "Server going down (restarting)":"Server going down", true );
399 array_free(&My_ConnArray);
400 My_Connections = NULL;
402 io_library_shutdown();
406 * Close all sockets (file descriptors) of open connections.
407 * This is useful in forked child processes, for example, to make sure that
408 * they don't hold connections open that the main process wants to close.
411 Conn_CloseAllSockets(int ExceptOf)
415 for(idx = 0; idx < Pool_Size; idx++) {
416 if(My_Connections[idx].sock > NONE &&
417 My_Connections[idx].sock != ExceptOf)
418 close(My_Connections[idx].sock);
423 * Initialize listening ports.
425 * @param a Array containing the ports the daemon should listen on.
426 * @param listen_addr Address the socket should listen on (can be "0.0.0.0").
427 * @param func IO callback function to register.
428 * @returns Number of listening sockets created.
431 Init_Listeners(array *a, const char *listen_addr, void (*func)(int,short))
433 unsigned int created = 0;
438 len = array_length(a, sizeof (UINT16));
439 port = array_start(a);
441 fd = NewListener(listen_addr, *port);
446 if (!io_event_create( fd, IO_WANTREAD, func )) {
448 "io_event_create(): Can't add fd %d (port %u): %s!",
449 fd, (unsigned int) *port, strerror(errno));
461 * Initialize all listening sockets.
463 * @returns Number of created listening sockets
466 Conn_InitListeners( void )
468 /* Initialize ports on which the server should accept connections */
469 unsigned int created = 0;
470 char *af_str, *copy, *listen_addr;
471 int count, fd, i, addr_len;
474 assert(Conf_ListenAddress);
476 count = my_sd_listen_fds();
479 "Not re-initializing listening sockets of systemd(8) ...");
483 /* systemd(8) passed sockets to us, so don't try to initialize
484 * listening sockets on our own but use the passed ones */
485 LogDebug("Initializing %d systemd sockets ...", count);
486 for (i = 0; i < count; i++) {
487 fd = SD_LISTEN_FDS_START + i;
488 addr_len = (int)sizeof(addr);
489 getsockname(fd, (struct sockaddr *)&addr,
490 (socklen_t*)&addr_len);
492 if (addr.sin4.sin_family != AF_INET
493 && addr.sin4.sin_family != AF_INET6)
495 if (addr.sin4.sin_family != AF_INET)
498 /* Socket is of unsupported type! For example,
499 * systemd passed in an IPv6 socket but ngIRCd
500 * isn't compiled with IPv6 support. */
501 switch (addr.sin4.sin_family)
503 case AF_UNSPEC: af_str = "AF_UNSPEC"; break;
504 case AF_UNIX: af_str = "AF_UNIX"; break;
505 case AF_INET: af_str = "AF_INET"; break;
507 case AF_INET6: af_str = "AF_INET6"; break;
510 case AF_NETLINK: af_str = "AF_NETLINK"; break;
512 default: af_str = "unknown"; break;
515 "Socket %d is of unsupported type \"%s\" (%d), have to ignore it!",
516 fd, af_str, addr.sin4.sin_family);
522 if (!io_event_create(fd, IO_WANTREAD, cb_listen)) {
524 "io_event_create(): Can't add fd %d: %s!",
525 fd, strerror(errno));
529 "Initialized socket %d from systemd(8): %s:%d.", fd,
530 ng_ipaddr_tostr(&addr), ng_ipaddr_getport(&addr));
536 /* not using systemd socket activation, initialize listening sockets: */
538 /* can't use Conf_ListenAddress directly, see below */
539 copy = strdup(Conf_ListenAddress);
541 Log(LOG_CRIT, "Cannot copy %s: %s", Conf_ListenAddress,
545 listen_addr = strtok(copy, ",");
547 while (listen_addr) {
548 ngt_TrimStr(listen_addr);
550 created += Init_Listeners(&Conf_ListenPorts,
551 listen_addr, cb_listen);
553 created += Init_Listeners(&Conf_SSLOptions.ListenPorts,
554 listen_addr, cb_listen_ssl);
558 listen_addr = strtok(NULL, ",");
561 /* Can't free() Conf_ListenAddress here: on REHASH, if the config file
562 * cannot be re-loaded, we'd end up with a NULL Conf_ListenAddress.
563 * Instead, free() takes place in conf.c, before the config file
564 * is being parsed. */
568 } /* Conn_InitListeners */
571 * Shut down all listening sockets.
574 Conn_ExitListeners( void )
576 /* Close down all listening sockets */
580 /* Get number of listening sockets to shut down. There can be none
581 * if ngIRCd has been "socket activated" by systemd. */
582 arraylen = array_length(&My_Listeners, sizeof (int));
587 "Shutting down all listening sockets (%d total) ...", arraylen);
588 fd = array_start(&My_Listeners);
593 LogDebug("Listening socket %d closed.", *fd );
596 array_free(&My_Listeners);
597 } /* Conn_ExitListeners */
600 * Bind a socket to a specific (source) address.
602 * @param addr Address structure.
603 * @param listen_addrstr Source address as string.
604 * @param Port Port number.
605 * @returns true on success, false otherwise.
608 InitSinaddrListenAddr(ng_ipaddr_t *addr, const char *listen_addrstr, UINT16 Port)
612 ret = ng_ipaddr_init(addr, listen_addrstr, Port);
614 assert(listen_addrstr);
616 "Can't bind to [%s]:%u: can't convert ip address \"%s\"!",
617 listen_addrstr, Port, listen_addrstr);
623 * Set a socket to "IPv6 only". If the given socket doesn't belong to the
624 * AF_INET6 family, or the operating system doesn't support this functionality,
625 * this function retruns silently.
627 * @param af Address family of the socket.
628 * @param sock Socket handle.
631 set_v6_only(int af, int sock)
633 #if defined(IPV6_V6ONLY) && defined(WANT_IPV6)
639 if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, (socklen_t)sizeof(on)))
640 Log(LOG_ERR, "Could not set IPV6_V6ONLY: %s", strerror(errno));
648 * Initialize new listening port.
650 * @param listen_addr Local address to bind the socet to (can be 0.0.0.0).
651 * @param Port Port number on which the new socket should be listening.
652 * @returns file descriptor of the socket or -1 on failure.
655 NewListener(const char *listen_addr, UINT16 Port)
657 /* Create new listening socket on specified port */
661 if (!InitSinaddrListenAddr(&addr, listen_addr, Port))
664 af = ng_ipaddr_af(&addr);
665 sock = socket(af, SOCK_STREAM, 0);
667 Log(LOG_CRIT, "Can't create socket (af %d) : %s!", af,
672 set_v6_only(af, sock);
674 if (!Init_Socket(sock))
677 if (bind(sock, (struct sockaddr *)&addr, ng_ipaddr_salen(&addr)) != 0) {
678 Log(LOG_CRIT, "Can't bind socket to address %s:%d - %s!",
679 ng_ipaddr_tostr(&addr), Port, strerror(errno));
684 if (listen(sock, 10) != 0) {
685 Log(LOG_CRIT, "Can't listen on socket: %s!", strerror(errno));
690 /* keep fd in list so we can close it when ngircd restarts/shuts down */
691 if (!array_catb(&My_Listeners, (char *)&sock, sizeof(int))) {
692 Log(LOG_CRIT, "Can't add socket to My_Listeners array: %s!",
698 Log(LOG_INFO, "Now listening on [%s]:%d (socket %d).",
699 ng_ipaddr_tostr(&addr), Port, sock);
704 * "Main Loop": Loop until shutdown or restart is signalled.
706 * This function loops until a shutdown or restart of ngIRCd is signalled and
707 * calls io_dispatch() to check for readable and writable sockets every second.
708 * It checks for status changes on pending connections (e. g. when a hostname
709 * has been resolved), checks for "penalties" and timeouts, and handles the
720 while (!NGIRCd_SignalQuit && !NGIRCd_SignalRestart) {
723 /* Check configured servers and established links */
727 /* Expire outdated class/list items */
730 /* Look for non-empty read buffers ... */
731 for (i = 0; i < Pool_Size; i++) {
732 if ((My_Connections[i].sock > NONE)
733 && (array_bytes(&My_Connections[i].rbuf) > 0)) {
734 /* ... and try to handle the received data */
739 /* Look for non-empty write buffers ... */
740 for (i = 0; i < Pool_Size; i++) {
741 if (My_Connections[i].sock <= NONE)
744 wdatalen = array_bytes(&My_Connections[i].wbuf);
747 array_bytes(&My_Connections[i].zip.wbuf) > 0)
753 if (SSL_WantRead(&My_Connections[i]))
756 io_event_add(My_Connections[i].sock,
761 /* Check from which sockets we possibly could read ... */
762 for (i = 0; i < Pool_Size; i++) {
763 if (My_Connections[i].sock <= NONE)
766 if (SSL_WantWrite(&My_Connections[i]))
767 /* TLS/SSL layer needs to write data; deal
768 * with this first! */
771 if (Proc_InProgress(&My_Connections[i].proc_stat)) {
772 /* Wait for completion of forked subprocess
773 * and ignore the socket in the meantime ... */
774 io_event_del(My_Connections[i].sock,
779 if (Conn_OPTION_ISSET(&My_Connections[i], CONN_ISCONNECTING))
780 /* Wait for completion of connect() ... */
783 if (My_Connections[i].delaytime > t) {
784 /* There is a "penalty time" set: ignore socket! */
785 io_event_del(My_Connections[i].sock,
790 io_event_add(My_Connections[i].sock, IO_WANTREAD);
793 /* Set the timeout for reading from the network to 1 second,
794 * which is the granularity with witch we handle "penalty
795 * times" for example.
796 * Note: tv_sec/usec are undefined(!) after io_dispatch()
797 * returns, so we have to set it before each call to it! */
801 /* Wait for activity ... */
802 i = io_dispatch(&tv);
803 if (i == -1 && errno != EINTR) {
804 Log(LOG_EMERG, "Conn_Handler(): io_dispatch(): %s!",
806 Log(LOG_ALERT, "%s exiting due to fatal errors!",
811 /* Should ngIRCd timeout when idle? */
812 if (Conf_IdleTimeout > 0 && NumConnectionsAccepted > 0
813 && idle_t > 0 && time(NULL) - idle_t >= Conf_IdleTimeout) {
814 LogDebug("Server idle timeout reached: %d second%s. Initiating shutdown ...",
816 Conf_IdleTimeout == 1 ? "" : "s");
817 NGIRCd_SignalQuit = true;
821 if (NGIRCd_SignalQuit)
822 Log(LOG_NOTICE | LOG_snotice, "Server going down NOW!");
823 else if (NGIRCd_SignalRestart)
824 Log(LOG_NOTICE | LOG_snotice, "Server restarting NOW!");
828 * Write a text string into the socket of a connection.
830 * This function automatically appends CR+LF to the string and validates that
831 * the result is a valid IRC message (oversized messages are shortened, for
832 * example). Then it calls the Conn_Write() function to do the actual sending.
834 * @param Idx Index fo the connection.
835 * @param Format Format string, see printf().
836 * @returns true on success, false otherwise.
840 Conn_WriteStr(CONN_ID Idx, const char *Format, ...)
843 Conn_WriteStr(Idx, Format, va_alist)
849 char buffer[COMMAND_LEN];
858 assert( Idx > NONE );
859 assert( Format != NULL );
862 va_start( ap, Format );
866 r = vsnprintf(buffer, COMMAND_LEN - 2, Format, ap);
867 if (r >= COMMAND_LEN - 2 || r == -1) {
869 * The string that should be written to the socket is longer
870 * than the allowed size of COMMAND_LEN bytes (including both
871 * the CR and LF characters). This can be caused by the
872 * IRC_WriteXXX() functions when the prefix of this server had
873 * to be added to an already "quite long" command line which
874 * has been received from a regular IRC client, for example.
876 * We are not allowed to send such "oversized" messages to
877 * other servers and clients, see RFC 2812 2.3 and 2813 3.3
878 * ("these messages SHALL NOT exceed 512 characters in length,
879 * counting all characters including the trailing CR-LF").
881 * So we have a big problem here: we should send more bytes
882 * to the network than we are allowed to and we don't know
883 * the originator (any more). The "old" behavior of blaming
884 * the receiver ("next hop") is a bad idea (it could be just
885 * an other server only routing the message!), so the only
886 * option left is to shorten the string and to hope that the
887 * result is still somewhat useful ...
890 * C99 states that vsnprintf() "returns the number of characters
891 * that would have been printed if the n were unlimited"; but
892 * according to the Linux manual page "glibc until 2.0.6 would
893 * return -1 when the output was truncated" -- so we have to
894 * handle both cases ...
898 strcpy (buffer + sizeof(buffer) - strlen(CUT_TXTSUFFIX) - 2 - 1,
903 ptr = strchr(buffer + 1, ':');
906 message = Conn_EncodingTo(Idx, ptr);
908 strlcpy(ptr, message, sizeof(buffer) - (ptr - buffer));
914 Log(LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer);
917 len = strlcat( buffer, "\r\n", sizeof( buffer ));
918 ok = Conn_Write(Idx, buffer, len);
919 My_Connections[Idx].msg_out++;
923 } /* Conn_WriteStr */
926 Conn_Password( CONN_ID Idx )
928 assert( Idx > NONE );
929 if (My_Connections[Idx].pwd == NULL)
932 return My_Connections[Idx].pwd;
933 } /* Conn_Password */
936 Conn_SetPassword( CONN_ID Idx, const char *Pwd )
938 assert( Idx > NONE );
940 if (My_Connections[Idx].pwd)
941 free(My_Connections[Idx].pwd);
943 My_Connections[Idx].pwd = strdup(Pwd);
944 if (My_Connections[Idx].pwd == NULL) {
945 Log(LOG_EMERG, "Can't allocate memory! [Conn_SetPassword]");
948 } /* Conn_SetPassword */
951 * Append Data to the outbound write buffer of a connection.
953 * @param Idx Index of the connection.
954 * @param Data pointer to the data.
955 * @param Len length of Data.
956 * @returns true on success, false otherwise.
959 Conn_Write( CONN_ID Idx, char *Data, size_t Len )
962 size_t writebuf_limit = WRITEBUFFER_MAX_LEN;
963 assert( Idx > NONE );
964 assert( Data != NULL );
967 /* Is the socket still open? A previous call to Conn_Write()
968 * may have closed the connection due to a fatal error.
969 * In this case it is sufficient to return an error, as well. */
970 if (My_Connections[Idx].sock <= NONE) {
971 LogDebug("Skipped write on closed socket (connection %d).", Idx);
975 /* Make sure that there still exists a CLIENT structure associated
976 * with this connection and check if this is a server or not: */
977 c = Conn_GetClient(Idx);
979 /* Servers do get special write buffer limits, so they can
980 * generate all the messages that are required while peering. */
981 if (Client_Type(c) == CLIENT_SERVER)
982 writebuf_limit = WRITEBUFFER_SLINK_LEN;
984 LogDebug("Write on socket without client (connection %d)!?", Idx);
987 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
989 * Zip_Buffer() does all the dirty work for us: it flushes
990 * the (pre-)compression buffers if required and handles
991 * all error conditions. */
992 if (!Zip_Buffer(Idx, Data, Len))
998 /* Uncompressed link:
999 * Check if outbound buffer has enough space for the data. */
1000 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
1001 WRITEBUFFER_FLUSH_LEN) {
1002 /* Buffer is full, flush it. Handle_Write deals with
1003 * low-level errors, if any. */
1004 if (!Handle_Write(Idx))
1008 /* When the write buffer is still too big after flushing it,
1009 * the connection will be killed. */
1010 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
1013 "Write buffer space exhausted (connection %d, limit is %lu bytes, %lu bytes new, %lu bytes pending)",
1014 Idx, writebuf_limit, Len,
1015 (unsigned long)array_bytes(&My_Connections[Idx].wbuf));
1016 Conn_Close(Idx, "Write buffer space exhausted", NULL, false);
1020 /* Copy data to write buffer */
1021 if (!array_catb(&My_Connections[Idx].wbuf, Data, Len))
1024 My_Connections[Idx].bytes_out += Len;
1027 /* Adjust global write counter */
1034 * Shut down a connection.
1036 * @param Idx Connection index.
1037 * @param LogMsg Message to write to the log or NULL. If no LogMsg
1038 * is given, the FwdMsg is logged.
1039 * @param FwdMsg Message to forward to remote servers.
1040 * @param InformClient If true, inform the client on the connection which is
1041 * to be shut down of the reason (FwdMsg) and send
1042 * connection statistics before disconnecting it.
1045 Conn_Close(CONN_ID Idx, const char *LogMsg, const char *FwdMsg, bool InformClient)
1047 /* Close connection. Open pipes of asynchronous resolver
1048 * sub-processes are closed down. */
1054 double in_z_k, out_z_k;
1058 assert( Idx > NONE );
1060 /* Is this link already shutting down? */
1061 if( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ISCLOSING )) {
1062 /* Conn_Close() has been called recursively for this link;
1063 * probable reason: Handle_Write() failed -- see below. */
1064 LogDebug("Recursive request to close connection %d!", Idx );
1068 assert( My_Connections[Idx].sock > NONE );
1070 /* Mark link as "closing" */
1071 Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCLOSING );
1073 port = ng_ipaddr_getport(&My_Connections[Idx].addr);
1074 Log(LOG_INFO, "Shutting down connection %d (%s) with \"%s:%d\" ...", Idx,
1075 LogMsg ? LogMsg : FwdMsg, My_Connections[Idx].host, port);
1077 /* Search client, if any */
1078 c = Conn_GetClient( Idx );
1080 /* Should the client be informed? */
1083 /* Send statistics to client if registered as user: */
1084 if ((c != NULL) && (Client_Type(c) == CLIENT_USER)) {
1086 ":%s NOTICE %s :%sConnection statistics: client %.1f kb, server %.1f kb.",
1087 Client_ID(Client_ThisServer()), Client_ID(c),
1089 (double)My_Connections[Idx].bytes_in / 1024,
1090 (double)My_Connections[Idx].bytes_out / 1024);
1093 /* Send ERROR to client (see RFC 2812, section 3.1.7) */
1095 Conn_WriteStr(Idx, "ERROR :%s", FwdMsg);
1097 Conn_WriteStr(Idx, "ERROR :Closing connection");
1100 /* Try to write out the write buffer. Note: Handle_Write() eventually
1101 * removes the CLIENT structure associated with this connection if an
1102 * error occurs! So we have to re-check if there is still an valid
1103 * CLIENT structure after calling Handle_Write() ...*/
1104 (void)Handle_Write( Idx );
1106 /* Search client, if any (re-check!) */
1107 c = Conn_GetClient( Idx );
1109 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_SSL )) {
1110 LogDebug("SSL connection %d shutting down ...", Idx);
1111 ConnSSL_Free(&My_Connections[Idx]);
1114 /* Shut down socket */
1115 if (! io_close(My_Connections[Idx].sock)) {
1116 /* Oops, we can't close the socket!? This is ... ugly! */
1118 "Error closing connection %d (socket %d) with %s:%d - %s! (ignored)",
1119 Idx, My_Connections[Idx].sock, My_Connections[Idx].host,
1120 port, strerror(errno));
1123 /* Mark socket as invalid: */
1124 My_Connections[Idx].sock = NONE;
1126 /* If there is still a client, unregister it now */
1128 Client_Destroy(c, LogMsg, FwdMsg, true);
1130 /* Calculate statistics and log information */
1131 in_k = (double)My_Connections[Idx].bytes_in / 1024;
1132 out_k = (double)My_Connections[Idx].bytes_out / 1024;
1134 if (Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP)) {
1135 in_z_k = (double)My_Connections[Idx].zip.bytes_in / 1024;
1136 out_z_k = (double)My_Connections[Idx].zip.bytes_out / 1024;
1137 /* Make sure that no division by zero can occur during
1138 * the calculation of in_p and out_p: in_z_k and out_z_k
1139 * are non-zero, that's guaranteed by the protocol until
1140 * compression can be enabled. */
1145 in_p = (int)(( in_k * 100 ) / in_z_k );
1146 out_p = (int)(( out_k * 100 ) / out_z_k );
1148 "Connection %d with \"%s:%d\" closed (in: %.1fk/%.1fk/%d%%, out: %.1fk/%.1fk/%d%%).",
1149 Idx, My_Connections[Idx].host, port,
1150 in_k, in_z_k, in_p, out_k, out_z_k, out_p);
1156 "Connection %d with \"%s:%d\" closed (in: %.1fk, out: %.1fk).",
1157 Idx, My_Connections[Idx].host, port,
1161 /* Servers: Modify time of next connect attempt? */
1162 Conf_UnsetServer( Idx );
1165 /* Clean up zlib, if link was compressed */
1166 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
1167 inflateEnd( &My_Connections[Idx].zip.in );
1168 deflateEnd( &My_Connections[Idx].zip.out );
1169 array_free(&My_Connections[Idx].zip.rbuf);
1170 array_free(&My_Connections[Idx].zip.wbuf);
1174 array_free(&My_Connections[Idx].rbuf);
1175 array_free(&My_Connections[Idx].wbuf);
1176 if (My_Connections[Idx].pwd != NULL)
1177 free(My_Connections[Idx].pwd);
1179 /* Clean up connection structure (=free it) */
1180 Init_Conn_Struct( Idx );
1182 assert(NumConnections > 0);
1185 LogDebug("Shutdown of connection %d completed, %ld connection%s left.",
1186 Idx, NumConnections, NumConnections != 1 ? "s" : "");
1188 idle_t = NumConnections > 0 ? 0 : time(NULL);
1192 * Get current number of connections.
1194 * @returns Number of current connections.
1199 return NumConnections;
1203 * Get number of maximum simultaneous connections.
1205 * @returns Number of maximum simultaneous connections.
1210 return NumConnectionsMax;
1211 } /* Conn_CountMax */
1214 * Get number of connections accepted since the daemon startet.
1216 * @returns Number of connections accepted.
1219 Conn_CountAccepted(void)
1221 return NumConnectionsAccepted;
1222 } /* Conn_CountAccepted */
1225 * Synchronize established connections and configured server structures
1226 * after a configuration update and store the correct connection IDs, if any.
1229 Conn_SyncServerStruct(void)
1235 for (i = 0; i < Pool_Size; i++) {
1236 if (My_Connections[i].sock == NONE)
1240 client = Conn_GetClient(i);
1241 if (!client || Client_Type(client) != CLIENT_SERVER)
1244 for (c = 0; c < MAX_SERVERS; c++) {
1245 /* Configured server? */
1246 if (!Conf_Server[c].host[0])
1249 if (strcasecmp(Conf_Server[c].name, Client_ID(client)) == 0)
1250 Conf_Server[c].conn_id = i;
1253 } /* SyncServerStruct */
1256 * Get IP address string of a connection.
1258 * @param Idx Connection index.
1259 * @return Pointer to a global buffer containing the IP address as string.
1262 Conn_GetIPAInfo(CONN_ID Idx)
1265 return ng_ipaddr_tostr(&My_Connections[Idx].addr);
1269 * Send out data of write buffer; connect new sockets.
1271 * @param Idx Connection index.
1272 * @returns true on success, false otherwise.
1275 Handle_Write( CONN_ID Idx )
1280 assert( Idx > NONE );
1281 if ( My_Connections[Idx].sock < 0 ) {
1282 LogDebug("Handle_Write() on closed socket, connection %d", Idx);
1285 assert( My_Connections[Idx].sock > NONE );
1287 wdatalen = array_bytes(&My_Connections[Idx].wbuf );
1290 if (wdatalen == 0) {
1291 /* Write buffer is empty, so we try to flush the compression
1292 * buffer and get some data to work with from there :-) */
1293 if (!Zip_Flush(Idx))
1296 /* Now the write buffer most probably has changed: */
1297 wdatalen = array_bytes(&My_Connections[Idx].wbuf);
1301 if (wdatalen == 0) {
1302 /* Still no data, fine. */
1303 io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
1309 ("Handle_Write() called for connection %d, %ld bytes pending ...",
1314 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_SSL )) {
1315 len = ConnSSL_Write(&My_Connections[Idx],
1316 array_start(&My_Connections[Idx].wbuf),
1321 len = write(My_Connections[Idx].sock,
1322 array_start(&My_Connections[Idx].wbuf), wdatalen );
1325 if (errno == EAGAIN || errno == EINTR)
1328 if (!Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ISCLOSING))
1330 "Write error on connection %d (socket %d): %s!",
1331 Idx, My_Connections[Idx].sock, strerror(errno));
1333 LogDebug("Recursive write error on connection %d (socket %d): %s!",
1334 Idx, My_Connections[Idx].sock, strerror(errno));
1335 Conn_Close(Idx, "Write error", NULL, false);
1339 /* move any data not yet written to beginning */
1340 array_moveleft(&My_Connections[Idx].wbuf, 1, (size_t)len);
1343 } /* Handle_Write */
1346 * Count established connections to a specific IP address.
1348 * @returns Number of established connections.
1351 Count_Connections(ng_ipaddr_t *a)
1356 for (i = 0; i < Pool_Size; i++) {
1357 if (My_Connections[i].sock <= NONE)
1359 if (ng_ipaddr_ipequal(&My_Connections[i].addr, a))
1363 } /* Count_Connections */
1366 * Initialize new client connection on a listening socket.
1368 * @param Sock Listening socket descriptor.
1369 * @param IsSSL true if this socket expects SSL-encrypted data.
1370 * @returns Accepted socket descriptor or -1 on error.
1373 New_Connection(int Sock, UNUSED bool IsSSL)
1376 struct request_info req;
1378 ng_ipaddr_t new_addr;
1379 char ip_str[NG_INET_ADDRSTRLEN];
1380 int new_sock, new_sock_len;
1384 assert(Sock > NONE);
1386 LogDebug("Accepting new connection on socket %d ...", Sock);
1388 new_sock_len = (int)sizeof(new_addr);
1389 new_sock = accept(Sock, (struct sockaddr *)&new_addr,
1390 (socklen_t *)&new_sock_len);
1392 Log(LOG_CRIT, "Can't accept connection: %s!", strerror(errno));
1395 NumConnectionsAccepted++;
1397 if (!ng_ipaddr_tostr_r(&new_addr, ip_str)) {
1398 Log(LOG_CRIT, "fd %d: Can't convert IP address!", new_sock);
1399 Simple_Message(new_sock, "ERROR :Internal Server Error");
1405 /* Validate socket using TCP Wrappers */
1406 request_init(&req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock,
1407 RQ_CLIENT_SIN, &new_addr, NULL);
1409 if (!hosts_access(&req)) {
1411 "Refused connection from %s (by TCP Wrappers)!", ip_str);
1412 Simple_Message(new_sock, "ERROR :Connection refused");
1418 if (!Init_Socket(new_sock))
1421 /* Check global connection limit */
1422 if ((Conf_MaxConnections > 0) &&
1423 (NumConnections >= (size_t) Conf_MaxConnections)) {
1424 Log(LOG_ALERT, "Can't accept connection: limit (%d) reached!",
1425 Conf_MaxConnections);
1426 Simple_Message(new_sock, "ERROR :Connection limit reached");
1431 /* Check IP-based connection limit */
1432 cnt = Count_Connections(&new_addr);
1433 if ((Conf_MaxConnectionsIP > 0) && (cnt >= Conf_MaxConnectionsIP)) {
1434 /* Access denied, too many connections from this IP address! */
1436 "Refused connection from %s: too may connections (%ld) from this IP address!",
1438 Simple_Message(new_sock,
1439 "ERROR :Connection refused, too many connections from your IP address");
1444 if (new_sock >= Pool_Size) {
1445 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION),
1446 (size_t) new_sock)) {
1448 "Can't allocate memory! [New_Connection]");
1449 Simple_Message(new_sock, "ERROR: Internal error");
1453 LogDebug("Bumped connection pool to %ld items (internal: %ld items, %ld bytes)",
1454 new_sock, array_length(&My_ConnArray,
1455 sizeof(CONNECTION)), array_bytes(&My_ConnArray));
1457 /* Adjust pointer to new block */
1458 My_Connections = array_start(&My_ConnArray);
1459 while (Pool_Size <= new_sock)
1460 Init_Conn_Struct(Pool_Size++);
1463 /* register callback */
1464 if (!io_event_create(new_sock, IO_WANTREAD, cb_clientserver)) {
1466 "Can't accept connection: io_event_create failed!");
1467 Simple_Message(new_sock, "ERROR :Internal error");
1472 c = Client_NewLocal(new_sock, NULL, CLIENT_UNKNOWN, false);
1475 "Can't accept connection: can't create client structure!");
1476 Simple_Message(new_sock, "ERROR :Internal error");
1481 Init_Conn_Struct(new_sock);
1482 My_Connections[new_sock].sock = new_sock;
1483 My_Connections[new_sock].addr = new_addr;
1484 My_Connections[new_sock].client = c;
1486 /* Set initial hostname to IP address. This becomes overwritten when
1487 * the DNS lookup is enabled and succeeds, but is used otherwise. */
1488 if (ng_ipaddr_af(&new_addr) != AF_INET)
1489 snprintf(My_Connections[new_sock].host,
1490 sizeof(My_Connections[new_sock].host), "[%s]", ip_str);
1492 strlcpy(My_Connections[new_sock].host, ip_str,
1493 sizeof(My_Connections[new_sock].host));
1495 Client_SetHostname(c, My_Connections[new_sock].host);
1497 Log(LOG_INFO, "Accepted connection %d from \"%s:%d\" on socket %d.",
1498 new_sock, My_Connections[new_sock].host,
1499 ng_ipaddr_getport(&new_addr), Sock);
1500 Account_Connection();
1503 /* Delay connection initalization until SSL handshake is finished */
1506 Conn_StartLogin(new_sock);
1509 } /* New_Connection */
1512 * Finish connection initialization, start resolver subprocess.
1514 * @param Idx Connection index.
1517 Conn_StartLogin(CONN_ID Idx)
1519 int ident_sock = -1;
1523 /* Nothing to do if DNS (and resolver subprocess) is disabled */
1528 /* Should we make an IDENT request? */
1530 ident_sock = My_Connections[Idx].sock;
1533 if (Conf_NoticeAuth) {
1534 /* Send "NOTICE AUTH" messages to the client */
1537 (void)Conn_WriteStr(Idx,
1538 "NOTICE AUTH :*** Looking up your hostname and checking ident");
1541 (void)Conn_WriteStr(Idx,
1542 "NOTICE AUTH :*** Looking up your hostname");
1543 /* Send buffered data to the client, but break on errors
1544 * because Handle_Write() would have closed the connection
1545 * again in this case! */
1546 if (!Handle_Write(Idx))
1550 Resolve_Addr(&My_Connections[Idx].proc_stat, &My_Connections[Idx].addr,
1551 ident_sock, cb_Read_Resolver_Result);
1555 * Update global connection counters.
1558 Account_Connection(void)
1562 if (NumConnections > NumConnectionsMax)
1563 NumConnectionsMax = NumConnections;
1564 LogDebug("Total number of connections now %lu (max %lu).",
1565 NumConnections, NumConnectionsMax);
1566 } /* Account_Connection */
1569 * Translate socket handle into connection index.
1571 * @param Sock Socket handle.
1572 * @returns Connecion index or NONE, if no connection could be found.
1575 Socket2Index( int Sock )
1577 assert( Sock >= 0 );
1579 if( Sock >= Pool_Size || My_Connections[Sock].sock != Sock ) {
1580 /* the Connection was already closed again, likely due to
1582 LogDebug("Socket2Index: can't get connection for socket %d!", Sock);
1586 } /* Socket2Index */
1589 * Read data from the network to the read buffer. If an error occurs,
1590 * the socket of this connection will be shut down.
1592 * @param Idx Connection index.
1595 Read_Request( CONN_ID Idx )
1598 static const unsigned int maxbps = COMMAND_LEN / 2;
1599 char readbuf[READBUFFER_LEN];
1602 assert( Idx > NONE );
1603 assert( My_Connections[Idx].sock > NONE );
1606 if ((array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN) ||
1607 (array_bytes(&My_Connections[Idx].zip.rbuf) >= READBUFFER_LEN))
1609 if (array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN)
1612 /* Read buffer is full */
1614 "Receive buffer space exhausted (connection %d): %d/%d bytes",
1615 Idx, array_bytes(&My_Connections[Idx].rbuf), READBUFFER_LEN);
1616 Conn_Close(Idx, "Receive buffer space exhausted", NULL, false);
1621 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_SSL))
1622 len = ConnSSL_Read( &My_Connections[Idx], readbuf, sizeof(readbuf));
1625 len = read(My_Connections[Idx].sock, readbuf, sizeof(readbuf));
1627 LogDebug("Client \"%s:%u\" is closing connection %d ...",
1628 My_Connections[Idx].host,
1629 ng_ipaddr_tostr(&My_Connections[Idx].addr), Idx);
1630 Conn_Close(Idx, NULL, "Client closed connection", false);
1635 if( errno == EAGAIN ) return;
1636 Log(LOG_ERR, "Read error on connection %d (socket %d): %s!",
1637 Idx, My_Connections[Idx].sock, strerror(errno));
1638 Conn_Close(Idx, "Read error", "Client closed connection",
1643 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1644 if (!array_catb(&My_Connections[Idx].zip.rbuf, readbuf,
1647 "Could not append received data to zip input buffer (connection %d): %d bytes!",
1649 Conn_Close(Idx, "Receive buffer space exhausted", NULL,
1656 if (!array_catb( &My_Connections[Idx].rbuf, readbuf, len)) {
1658 "Could not append received data to input buffer (connection %d): %d bytes!",
1660 Conn_Close(Idx, "Receive buffer space exhausted", NULL,
1665 /* Update connection statistics */
1666 My_Connections[Idx].bytes_in += len;
1668 /* Handle read buffer */
1669 My_Connections[Idx].bps += Handle_Buffer(Idx);
1671 /* Make sure that there is still a valid client registered */
1672 c = Conn_GetClient(Idx);
1676 /* Update timestamp of last data received if this connection is
1677 * registered as a user, server or service connection. Don't update
1678 * otherwise, so users have at least Conf_PongTimeout seconds time to
1679 * register with the IRC server -- see Check_Connections().
1680 * Update "lastping", too, if time shifted backwards ... */
1681 if (Client_Type(c) == CLIENT_USER
1682 || Client_Type(c) == CLIENT_SERVER
1683 || Client_Type(c) == CLIENT_SERVICE) {
1685 if (My_Connections[Idx].lastdata != t)
1686 My_Connections[Idx].bps = 0;
1688 My_Connections[Idx].lastdata = t;
1689 if (My_Connections[Idx].lastping > t)
1690 My_Connections[Idx].lastping = t;
1693 /* Look at the data in the (read-) buffer of this connection */
1694 if (My_Connections[Idx].bps >= maxbps)
1695 Throttle_Connection(Idx, c, THROTTLE_BPS, maxbps);
1696 } /* Read_Request */
1699 * Handle all data in the connection read-buffer.
1701 * Data is processed until no complete command is left in the read buffer,
1702 * or MAX_COMMANDS[_SERVER|_SERVICE] commands were processed.
1703 * When a fatal error occurs, the connection is shut down.
1705 * @param Idx Index of the connection.
1706 * @returns Number of bytes processed.
1709 Handle_Buffer(CONN_ID Idx)
1712 char *ptr1, *ptr2, *first_eol;
1720 unsigned int i, maxcmd = MAX_COMMANDS, len_processed = 0;
1723 c = Conn_GetClient(Idx);
1724 starttime = time(NULL);
1728 /* Servers get special command limits that depend on the user count */
1729 switch (Client_Type(c)) {
1731 maxcmd = (int)(Client_UserCount() / 5)
1732 + MAX_COMMANDS_SERVER_MIN;
1733 /* Allow servers to handle even more commands while peering
1734 * to speed up server login and network synchronization. */
1735 if (Conn_LastPing(Idx) == 0)
1738 case CLIENT_SERVICE:
1739 maxcmd = MAX_COMMANDS_SERVICE;
1742 if (Client_HasMode(c, 'F'))
1743 maxcmd = MAX_COMMANDS_SERVICE;
1747 for (i=0; i < maxcmd; i++) {
1749 if (My_Connections[Idx].delaytime > starttime)
1752 /* Unpack compressed data, if compression is in use */
1753 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1754 /* When unzipping fails, Unzip_Buffer() shuts
1755 * down the connection itself */
1756 if (!Unzip_Buffer(Idx))
1761 if (0 == array_bytes(&My_Connections[Idx].rbuf))
1764 /* Make sure that the buffer is NULL terminated */
1765 if (!array_cat0_temporary(&My_Connections[Idx].rbuf)) {
1766 Conn_Close(Idx, NULL,
1767 "Can't allocate memory [Handle_Buffer]",
1772 /* RFC 2812, section "2.3 Messages", 5th paragraph:
1773 * "IRC messages are always lines of characters terminated
1774 * with a CR-LF (Carriage Return - Line Feed) pair [...]". */
1776 ptr = strstr(array_start(&My_Connections[Idx].rbuf), "\r\n");
1779 /* Check for non-RFC-compliant request (only CR or LF)?
1780 * Unfortunately, there are quite a few clients out there
1781 * that do this -- e. g. mIRC, BitchX, and Trillian :-( */
1782 ptr1 = strchr(array_start(&My_Connections[Idx].rbuf), '\r');
1783 ptr2 = strchr(array_start(&My_Connections[Idx].rbuf), '\n');
1785 /* Check if there is a single CR or LF _before_ the
1786 * correct CR+LF line terminator: */
1787 first_eol = ptr1 < ptr2 ? ptr1 : ptr2;
1788 if (first_eol < ptr) {
1789 /* Single CR or LF before CR+LF found */
1793 } else if (ptr1 || ptr2) {
1794 /* No CR+LF terminated command found, but single
1795 * CR or LF found ... */
1797 ptr = ptr1 < ptr2 ? ptr1 : ptr2;
1799 ptr = ptr1 ? ptr1 : ptr2;
1807 /* Complete (=line terminated) request found, handle it! */
1810 len = ptr - (char *)array_start(&My_Connections[Idx].rbuf) + delta;
1812 if (len > (COMMAND_LEN - 1)) {
1813 /* Request must not exceed 512 chars (incl. CR+LF!),
1814 * see RFC 2812. Disconnect Client if this happens. */
1816 "Request too long (connection %d): %d bytes (max. %d expected)!",
1817 Idx, array_bytes(&My_Connections[Idx].rbuf),
1819 Conn_Close(Idx, NULL, "Request too long", true);
1823 len_processed += (unsigned int)len;
1825 /* Request is empty (only '\r\n', '\r' or '\n');
1826 * delta is 2 ('\r\n') or 1 ('\r' or '\n'), see above */
1827 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1831 /* remember if stream is already compressed */
1832 old_z = My_Connections[Idx].options & CONN_ZIP;
1835 My_Connections[Idx].msg_in++;
1837 (Idx, (char *)array_start(&My_Connections[Idx].rbuf)))
1838 return 0; /* error -> connection has been closed */
1840 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1842 if ((!old_z) && (My_Connections[Idx].options & CONN_ZIP) &&
1843 (array_bytes(&My_Connections[Idx].rbuf) > 0)) {
1844 /* The last command activated socket compression.
1845 * Data that was read after that needs to be copied
1846 * to the unzip buffer for decompression: */
1848 (&My_Connections[Idx].zip.rbuf,
1849 &My_Connections[Idx].rbuf)) {
1850 Conn_Close(Idx, NULL,
1851 "Can't allocate memory [Handle_Buffer]",
1856 array_trunc(&My_Connections[Idx].rbuf);
1858 ("Moved already received data (%u bytes) to uncompression buffer.",
1859 array_bytes(&My_Connections[Idx].zip.rbuf));
1864 LogDebug("Connection %d: Processed %ld commands (max=%ld), %ld bytes. %ld bytes left in read buffer.",
1865 Idx, i, maxcmd, len_processed,
1866 array_bytes(&My_Connections[Idx].rbuf));
1869 /* If data has been processed but there is still data in the read
1870 * buffer, the command limit triggered. Enforce the penalty time: */
1871 if (len_processed && array_bytes(&My_Connections[Idx].rbuf) > 2)
1872 Throttle_Connection(Idx, c, THROTTLE_CMDS, maxcmd);
1874 return len_processed;
1875 } /* Handle_Buffer */
1878 * Check whether established connections are still alive or not.
1879 * If not, play PING-PONG first; and if that doesn't help either,
1880 * disconnect the respective peer.
1883 Check_Connections(void)
1889 for (i = 0; i < Pool_Size; i++) {
1890 if (My_Connections[i].sock < 0)
1893 c = Conn_GetClient(i);
1894 if (c && ((Client_Type(c) == CLIENT_USER)
1895 || (Client_Type(c) == CLIENT_SERVER)
1896 || (Client_Type(c) == CLIENT_SERVICE))) {
1897 /* connected User, Server or Service */
1898 if (My_Connections[i].lastping >
1899 My_Connections[i].lastdata) {
1900 /* We already sent a ping */
1901 if (My_Connections[i].lastping <
1902 time(NULL) - Conf_PongTimeout) {
1904 snprintf(msg, sizeof(msg),
1905 "Ping timeout: %d seconds",
1907 LogDebug("Connection %d: %s.", i, msg);
1908 Conn_Close(i, NULL, msg, true);
1910 } else if (My_Connections[i].lastdata <
1911 time(NULL) - Conf_PingTimeout) {
1912 /* We need to send a PING ... */
1913 LogDebug("Connection %d: sending PING ...", i);
1915 Conn_WriteStr(i, "PING :%s",
1916 Client_ID(Client_ThisServer()));
1919 /* The connection is not fully established yet, so
1920 * we don't do the PING-PONG game here but instead
1921 * disconnect the client after "a short time" if it's
1922 * still not registered. */
1924 if (My_Connections[i].lastdata <
1925 time(NULL) - Conf_PongTimeout) {
1927 ("Unregistered connection %d timed out ...",
1929 Conn_Close(i, NULL, "Timeout", false);
1933 } /* Check_Connections */
1936 * Check if further server links should be established.
1944 time_now = time(NULL);
1946 /* Check all configured servers */
1947 for (i = 0; i < MAX_SERVERS; i++) {
1948 if (Conf_Server[i].conn_id != NONE)
1949 continue; /* Already establishing or connected */
1950 if (!Conf_Server[i].host[0] || Conf_Server[i].port <= 0)
1951 continue; /* No host and/or port configured */
1952 if (Conf_Server[i].flags & CONF_SFLAG_DISABLED)
1953 continue; /* Disabled configuration entry */
1954 if (Conf_Server[i].lasttry > (time_now - Conf_ConnectRetry))
1955 continue; /* We have to wait a little bit ... */
1957 /* Is there already a connection in this group? */
1958 if (Conf_Server[i].group > NONE) {
1959 for (n = 0; n < MAX_SERVERS; n++) {
1962 if ((Conf_Server[n].conn_id != NONE) &&
1963 (Conf_Server[n].group == Conf_Server[i].group))
1966 if (n < MAX_SERVERS)
1970 /* Okay, try to connect now */
1972 "Preparing to establish a new server link for \"%s\" ...",
1973 Conf_Server[i].name);
1974 Conf_Server[i].lasttry = time_now;
1975 Conf_Server[i].conn_id = SERVER_WAIT;
1976 assert(Proc_GetPipeFd(&Conf_Server[i].res_stat) < 0);
1977 Resolve_Name(&Conf_Server[i].res_stat, Conf_Server[i].host,
1978 cb_Connect_to_Server);
1980 } /* Check_Servers */
1983 * Establish a new outgoing server connection.
1985 * @param Server Configuration index of the server.
1986 * @param dest Destination IP address to connect to.
1989 New_Server( int Server , ng_ipaddr_t *dest)
1991 /* Establish new server link */
1992 char ip_str[NG_INET_ADDRSTRLEN];
1993 int af_dest, res, new_sock;
1996 assert( Server > NONE );
1998 /* Make sure that the remote server hasn't re-linked to this server
1999 * asynchronously on its own */
2000 if (Conf_Server[Server].conn_id > NONE) {
2002 "Connection to \"%s\" meanwhile re-established, aborting preparation.");
2006 if (!ng_ipaddr_tostr_r(dest, ip_str)) {
2007 Log(LOG_WARNING, "New_Server: Could not convert IP to string");
2008 Conf_Server[Server].conn_id = NONE;
2012 af_dest = ng_ipaddr_af(dest);
2013 new_sock = socket(af_dest, SOCK_STREAM, 0);
2016 "Establishing connection for \"%s\" to \"%s:%d\" (%s), socket %d ...",
2017 Conf_Server[Server].name, Conf_Server[Server].host,
2018 Conf_Server[Server].port, ip_str, new_sock);
2021 Log(LOG_CRIT, "Can't create socket (af %d): %s!",
2022 af_dest, strerror(errno));
2023 Conf_Server[Server].conn_id = NONE;
2027 if (!Init_Socket(new_sock)) {
2028 Conf_Server[Server].conn_id = NONE;
2032 /* is a bind address configured? */
2033 res = ng_ipaddr_af(&Conf_Server[Server].bind_addr);
2035 /* if yes, bind now. If it fails, warn and let connect() pick a
2037 if (res && bind(new_sock, (struct sockaddr *) &Conf_Server[Server].bind_addr,
2038 ng_ipaddr_salen(&Conf_Server[Server].bind_addr)))
2040 ng_ipaddr_tostr_r(&Conf_Server[Server].bind_addr, ip_str);
2041 Log(LOG_WARNING, "Can't bind socket to %s: %s!", ip_str,
2044 ng_ipaddr_setport(dest, Conf_Server[Server].port);
2045 res = connect(new_sock, (struct sockaddr *) dest, ng_ipaddr_salen(dest));
2046 if(( res != 0 ) && ( errno != EINPROGRESS )) {
2047 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
2049 Conf_Server[Server].conn_id = NONE;
2053 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)new_sock)) {
2055 "Cannot allocate memory for server connection (socket %d)",
2058 Conf_Server[Server].conn_id = NONE;
2062 if (!io_event_create( new_sock, IO_WANTWRITE, cb_connserver)) {
2063 Log(LOG_ALERT, "io_event_create(): could not add fd %d",
2066 Conf_Server[Server].conn_id = NONE;
2070 My_Connections = array_start(&My_ConnArray);
2072 assert(My_Connections[new_sock].sock <= 0);
2074 Init_Conn_Struct(new_sock);
2076 ng_ipaddr_tostr_r(dest, ip_str);
2077 c = Client_NewLocal(new_sock, ip_str, CLIENT_UNKNOWNSERVER, false);
2079 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
2081 Conf_Server[Server].conn_id = NONE;
2085 /* Conn_Close() decrements this counter again */
2086 Account_Connection();
2087 Client_SetIntroducer( c, c );
2088 Client_SetToken( c, TOKEN_OUTBOUND );
2090 /* Register connection */
2091 if (!Conf_SetServer(Server, new_sock))
2093 My_Connections[new_sock].sock = new_sock;
2094 My_Connections[new_sock].addr = *dest;
2095 My_Connections[new_sock].client = c;
2096 strlcpy( My_Connections[new_sock].host, Conf_Server[Server].host,
2097 sizeof(My_Connections[new_sock].host ));
2100 if (Conf_Server[Server].SSLConnect &&
2101 !ConnSSL_PrepareConnect(&My_Connections[new_sock], &Conf_Server[Server]))
2103 Log(LOG_ALERT, "Could not initialize SSL for outgoing connection");
2104 Conn_Close(new_sock, "Could not initialize SSL for outgoing connection",
2106 Init_Conn_Struct(new_sock);
2107 Conf_Server[Server].conn_id = NONE;
2111 LogDebug("Registered new connection %d on socket %d (%ld in total).",
2112 new_sock, My_Connections[new_sock].sock, NumConnections);
2113 Conn_OPTION_ADD( &My_Connections[new_sock], CONN_ISCONNECTING );
2117 * Initialize connection structure.
2119 * @param Idx Connection index.
2122 Init_Conn_Struct(CONN_ID Idx)
2124 time_t now = time(NULL);
2126 memset(&My_Connections[Idx], 0, sizeof(CONNECTION));
2127 My_Connections[Idx].sock = -1;
2128 My_Connections[Idx].signon = now;
2129 My_Connections[Idx].lastdata = now;
2130 My_Connections[Idx].lastprivmsg = now;
2131 Proc_InitStruct(&My_Connections[Idx].proc_stat);
2134 My_Connections[Idx].iconv_from = (iconv_t)(-1);
2135 My_Connections[Idx].iconv_to = (iconv_t)(-1);
2137 } /* Init_Conn_Struct */
2140 * Initialize options of a new socket.
2142 * For example, we try to set socket options SO_REUSEADDR and IPTOS_LOWDELAY.
2143 * The socket is automatically closed if a fatal error is encountered.
2145 * @param Sock Socket handle.
2146 * @returns false if socket was closed due to fatal error.
2149 Init_Socket( int Sock )
2153 if (!io_setnonblock(Sock)) {
2154 Log(LOG_CRIT, "Can't enable non-blocking mode for socket: %s!",
2160 /* Don't block this port after socket shutdown */
2162 if (setsockopt(Sock, SOL_SOCKET, SO_REUSEADDR, &value,
2163 (socklen_t)sizeof(value)) != 0) {
2164 Log(LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!",
2166 /* ignore this error */
2169 /* Set type of service (TOS) */
2170 #if defined(IPPROTO_IP) && defined(IPTOS_LOWDELAY)
2171 value = IPTOS_LOWDELAY;
2172 if (setsockopt(Sock, IPPROTO_IP, IP_TOS, &value,
2173 (socklen_t) sizeof(value))) {
2174 LogDebug("Can't set socket option IP_TOS: %s!",
2176 /* ignore this error */
2178 LogDebug("IP_TOS on socket %d has been set to IPTOS_LOWDELAY.",
2186 * Read results of a resolver sub-process and try to initiate a new server
2189 * @param fd File descriptor of the pipe to the sub-process.
2190 * @param events (ignored IO specification)
2193 cb_Connect_to_Server(int fd, UNUSED short events)
2198 /* we can handle at most 3 addresses; but we read up to 4 so we can
2199 * log the 'more than we can handle' condition. First result is tried
2200 * immediately, rest is saved for later if needed. */
2201 ng_ipaddr_t dest_addrs[4];
2203 LogDebug("Resolver: Got forward lookup callback on fd %d, events %d",
2206 for (i=0; i < MAX_SERVERS; i++) {
2207 if (Proc_GetPipeFd(&Conf_Server[i].res_stat) == fd )
2211 if( i >= MAX_SERVERS) {
2212 /* Ops, no matching server found?! */
2214 LogDebug("Resolver: Got Forward Lookup callback for unknown server!?");
2218 /* Read result from pipe */
2219 len = Proc_Read(&Conf_Server[i].res_stat, dest_addrs, sizeof(dest_addrs));
2220 Proc_Close(&Conf_Server[i].res_stat);
2222 /* Error resolving hostname: reset server structure */
2223 Conf_Server[i].conn_id = NONE;
2227 assert((len % sizeof(ng_ipaddr_t)) == 0);
2229 LogDebug("Got result from resolver: %u structs (%u bytes).",
2230 len/sizeof(ng_ipaddr_t), len);
2232 memset(&Conf_Server[i].dst_addr, 0, sizeof(Conf_Server[i].dst_addr));
2233 if (len > sizeof(ng_ipaddr_t)) {
2234 /* more than one address for this hostname, remember them
2235 * in case first address is unreachable/not available */
2236 len -= sizeof(ng_ipaddr_t);
2237 if (len > sizeof(Conf_Server[i].dst_addr)) {
2238 len = sizeof(Conf_Server[i].dst_addr);
2240 "Notice: Resolver returned more IP Addresses for host than we can handle, additional addresses dropped.");
2242 memcpy(&Conf_Server[i].dst_addr, &dest_addrs[1], len);
2245 New_Server(i, dest_addrs);
2246 } /* cb_Read_Forward_Lookup */
2249 * Read results of a resolver sub-process from the pipe and update the
2250 * appropriate connection/client structure(s): hostname and/or IDENT user name.
2252 * @param r_fd File descriptor of the pipe to the sub-process.
2253 * @param events (ignored IO specification)
2256 cb_Read_Resolver_Result( int r_fd, UNUSED short events )
2263 char readbuf[HOST_LEN + 2 + CLIENT_USER_LEN];
2266 char readbuf[HOST_LEN + 1];
2269 LogDebug("Resolver: Got callback on fd %d, events %d", r_fd, events );
2270 i = Conn_GetFromProc(r_fd);
2272 /* Ops, none found? Probably the connection has already
2273 * been closed!? We'll ignore that ... */
2275 LogDebug("Resolver: Got callback for unknown connection!?");
2279 /* Read result from pipe */
2280 len = Proc_Read(&My_Connections[i].proc_stat, readbuf, sizeof readbuf -1);
2281 Proc_Close(&My_Connections[i].proc_stat);
2285 readbuf[len] = '\0';
2286 identptr = strchr(readbuf, '\n');
2287 assert(identptr != NULL);
2289 Log( LOG_CRIT, "Resolver: Got malformed result!");
2294 LogDebug("Got result from resolver: \"%s\" (%u bytes read).", readbuf, len);
2295 /* Okay, we got a complete result: this is a host name for outgoing
2296 * connections and a host name and IDENT user name (if enabled) for
2297 * incoming connections.*/
2298 assert ( My_Connections[i].sock >= 0 );
2299 /* Incoming connection. Search client ... */
2300 c = Conn_GetClient( i );
2301 assert( c != NULL );
2303 /* Only update client information of unregistered clients.
2304 * Note: user commands (e. g. WEBIRC) are always read _after_ reading
2305 * the resolver results, so we don't have to worry to override settings
2306 * from these commands here. */
2307 if(Client_Type(c) == CLIENT_UNKNOWN) {
2308 strlcpy(My_Connections[i].host, readbuf,
2309 sizeof(My_Connections[i].host));
2310 Client_SetHostname(c, readbuf);
2311 if (Conf_NoticeAuth)
2312 (void)Conn_WriteStr(i,
2313 "NOTICE AUTH :*** Found your hostname: %s",
2314 My_Connections[i].host);
2320 if ((*ptr < '0' || *ptr > '9') &&
2321 (*ptr < 'A' || *ptr > 'Z') &&
2322 (*ptr < 'a' || *ptr > 'z'))
2327 /* Erroneous IDENT reply */
2329 "Got invalid IDENT reply for connection %d! Ignored.",
2333 "IDENT lookup for connection %d: \"%s\".",
2335 Client_SetUser(c, identptr, true);
2337 if (Conf_NoticeAuth) {
2338 (void)Conn_WriteStr(i,
2339 "NOTICE AUTH :*** Got %sident response%s%s",
2340 *ptr ? "invalid " : "",
2342 *ptr ? "" : identptr);
2344 } else if(Conf_Ident) {
2345 Log(LOG_INFO, "IDENT lookup for connection %d: no result.", i);
2346 if (Conf_NoticeAuth)
2347 (void)Conn_WriteStr(i,
2348 "NOTICE AUTH :*** No ident response");
2352 if (Conf_NoticeAuth) {
2353 /* Send buffered data to the client, but break on
2354 * errors because Handle_Write() would have closed
2355 * the connection again in this case! */
2356 if (!Handle_Write(i))
2360 Class_HandleServerBans(c);
2364 LogDebug("Resolver: discarding result for already registered connection %d.", i);
2366 } /* cb_Read_Resolver_Result */
2369 * Write a "simple" (error) message to a socket.
2371 * The message is sent without using the connection write buffers, without
2372 * compression/encryption, and even without any error reporting. It is
2373 * designed for error messages of e.g. New_Connection().
2375 * @param Sock Socket handle.
2376 * @param Msg Message string to send.
2379 Simple_Message(int Sock, const char *Msg)
2381 char buf[COMMAND_LEN];
2384 assert(Sock > NONE);
2385 assert(Msg != NULL);
2387 strlcpy(buf, Msg, sizeof buf - 2);
2388 len = strlcat(buf, "\r\n", sizeof buf);
2389 if (write(Sock, buf, len) < 0) {
2390 /* Because this function most probably got called to log
2391 * an error message, any write error is ignored here to
2392 * avoid an endless loop. But casting the result of write()
2393 * to "void" doesn't satisfy the GNU C code attribute
2394 * "warn_unused_result" which is used by some versions of
2395 * glibc (e.g. 2.11.1), therefore this silly error
2396 * "handling" code here :-( */
2399 } /* Simple_Error */
2402 * Get CLIENT structure that belongs to a local connection identified by its
2403 * index number. Each connection belongs to a client by definition, so it is
2404 * not required that the caller checks for NULL return values.
2406 * @param Idx Connection index number.
2407 * @returns Pointer to CLIENT structure.
2410 Conn_GetClient( CONN_ID Idx )
2415 c = array_get(&My_ConnArray, sizeof (CONNECTION), (size_t)Idx);
2417 return c ? c->client : NULL;
2421 * Get PROC_STAT sub-process structure of a connection.
2423 * @param Idx Connection index number.
2424 * @returns PROC_STAT structure.
2427 Conn_GetProcStat(CONN_ID Idx)
2432 c = array_get(&My_ConnArray, sizeof (CONNECTION), (size_t)Idx);
2434 return &c->proc_stat;
2435 } /* Conn_GetProcStat */
2438 * Get CONN_ID from file descriptor associated to a subprocess structure.
2440 * @param fd File descriptor.
2441 * @returns CONN_ID or NONE (-1).
2444 Conn_GetFromProc(int fd)
2449 for (i = 0; i < Pool_Size; i++) {
2450 if ((My_Connections[i].sock != NONE)
2451 && (Proc_GetPipeFd(&My_Connections[i].proc_stat) == fd))
2455 } /* Conn_GetFromProc */
2458 * Throttle a connection because of excessive usage.
2460 * @param Reason The reason, see THROTTLE_xxx constants.
2461 * @param Idx The connection index.
2462 * @param Client The client of this connection.
2463 * @param Seconds The time to delay this connection.
2466 Throttle_Connection(const CONN_ID Idx, CLIENT *Client, const int Reason,
2470 assert(Client != NULL);
2472 /* Never throttle servers or services, only interrupt processing */
2473 if (Client_Type(Client) == CLIENT_SERVER
2474 || Client_Type(Client) == CLIENT_UNKNOWNSERVER
2475 || Client_Type(Client) == CLIENT_SERVICE)
2478 /* Don't throttle clients with user mode 'F' set */
2479 if (Client_HasMode(Client, 'F'))
2482 LogDebug("Throttling connection %d: code %d, value %d!", Idx,
2484 Conn_SetPenalty(Idx, 1);
2490 Conn_GetAuthPing(CONN_ID Idx)
2492 assert (Idx != NONE);
2493 return My_Connections[Idx].auth_ping;
2494 } /* Conn_GetAuthPing */
2497 Conn_SetAuthPing(CONN_ID Idx, long ID)
2499 assert (Idx != NONE);
2500 My_Connections[Idx].auth_ping = ID;
2501 } /* Conn_SetAuthPing */
2503 #endif /* STRICT_RFC */
2508 * IO callback for new SSL-enabled client and server connections.
2510 * @param sock Socket descriptor.
2511 * @param what IO specification (IO_WANTREAD/IO_WANTWRITE/...).
2514 cb_clientserver_ssl(int sock, UNUSED short what)
2516 CONN_ID idx = Socket2Index(sock);
2525 switch (ConnSSL_Accept(&My_Connections[idx])) {
2529 return; /* EAGAIN: callback will be invoked again by IO layer */
2532 "SSL accept error, closing socket", "SSL accept error",
2537 io_event_setcb(sock, cb_clientserver); /* SSL handshake completed */
2541 * IO callback for listening SSL sockets: handle new connections. This callback
2542 * gets called when a new SSL-enabled connection should be accepted.
2544 * @param sock Socket descriptor.
2545 * @param irrelevant (ignored IO specification)
2548 cb_listen_ssl(int sock, short irrelevant)
2553 fd = New_Connection(sock, true);
2556 io_event_setcb(My_Connections[fd].sock, cb_clientserver_ssl);
2560 * IO callback for new outgoing SSL-enabled server connections.
2562 * @param sock Socket descriptor.
2563 * @param unused (ignored IO specification)
2566 cb_connserver_login_ssl(int sock, short unused)
2568 CONN_ID idx = Socket2Index(sock);
2577 switch (ConnSSL_Connect( &My_Connections[idx])) {
2579 case 0: LogDebug("ConnSSL_Connect: not ready");
2582 Log(LOG_ERR, "SSL connection on socket %d failed!", sock);
2583 Conn_Close(idx, "Can't connect", NULL, false);
2587 serveridx = Conf_GetServer(idx);
2588 assert(serveridx >= 0);
2592 Log( LOG_INFO, "SSL connection %d with \"%s:%d\" established.", idx,
2593 My_Connections[idx].host, Conf_Server[Conf_GetServer( idx )].port );
2595 if (Conf_Server[serveridx].SSLVerify &&
2596 !Conn_OPTION_ISSET(&My_Connections[idx], CONN_SSL_PEERCERT_OK))
2598 Log(LOG_ERR, "SSLVerify enabled for %d, but peer certificate check failed", idx);
2604 Log(LOG_ERR, "SSL connection on socket %d failed!", sock);
2605 Conn_Close(idx, "Can't connect!", NULL, false);
2610 * Check if SSL library needs to read SSL-protocol related data.
2612 * SSL/TLS connections require extra treatment:
2613 * When either CONN_SSL_WANT_WRITE or CONN_SSL_WANT_READ is set, we
2614 * need to take care of that first, before checking read/write buffers.
2615 * For instance, while we might have data in our write buffer, the
2616 * TLS/SSL protocol might need to read internal data first for TLS/SSL
2617 * writes to succeed.
2619 * If this function returns true, such a condition is met and we have
2620 * to reverse the condition (check for read even if we've data to write,
2621 * do not check for read but writeability even if write-buffer is empty).
2623 * @param c Connection to check.
2624 * @returns true if SSL-library has to read protocol data.
2627 SSL_WantRead(const CONNECTION *c)
2629 if (Conn_OPTION_ISSET(c, CONN_SSL_WANT_READ)) {
2630 io_event_add(c->sock, IO_WANTREAD);
2637 * Check if SSL library needs to write SSL-protocol related data.
2639 * Please see description of SSL_WantRead() for full description!
2641 * @param c Connection to check.
2642 * @returns true if SSL-library has to write protocol data.
2645 SSL_WantWrite(const CONNECTION *c)
2647 if (Conn_OPTION_ISSET(c, CONN_SSL_WANT_WRITE)) {
2648 io_event_add(c->sock, IO_WANTWRITE);
2655 * Get information about used SSL cipher.
2657 * @param Idx Connection index number.
2658 * @param buf Buffer for returned information text.
2659 * @param len Size of return buffer "buf".
2660 * @returns true on success, false otherwise.
2663 Conn_GetCipherInfo(CONN_ID Idx, char *buf, size_t len)
2667 assert(Idx < (int) array_length(&My_ConnArray, sizeof(CONNECTION)));
2668 return ConnSSL_GetCipherInfo(&My_Connections[Idx], buf, len);
2672 * Check if a connection is SSL-enabled or not.
2674 * @param Idx Connection index number.
2675 * @return true if connection is SSL-enabled, false otherwise.
2678 Conn_UsesSSL(CONN_ID Idx)
2682 assert(Idx < (int) array_length(&My_ConnArray, sizeof(CONNECTION)));
2683 return Conn_OPTION_ISSET(&My_Connections[Idx], CONN_SSL);
2687 Conn_GetCertFp(CONN_ID Idx)
2691 assert(Idx < (int) array_length(&My_ConnArray, sizeof(CONNECTION)));
2692 return ConnSSL_GetCertFp(&My_Connections[Idx]);
2696 Conn_SetCertFp(CONN_ID Idx, const char *fingerprint)
2700 assert(Idx < (int) array_length(&My_ConnArray, sizeof(CONNECTION)));
2701 return ConnSSL_SetCertFp(&My_Connections[Idx], fingerprint);
2704 #else /* SSL_SUPPORT */
2707 Conn_UsesSSL(UNUSED CONN_ID Idx)
2713 Conn_GetCertFp(UNUSED CONN_ID Idx)
2719 Conn_SetCertFp(UNUSED CONN_ID Idx, UNUSED const char *fingerprint)
2724 #endif /* SSL_SUPPORT */
2729 * Dump internal state of the "connection module".
2732 Conn_DebugDump(void)
2736 Log(LOG_DEBUG, "Connection status:");
2737 for (i = 0; i < Pool_Size; i++) {
2738 if (My_Connections[i].sock == NONE)
2741 " - %d: host=%s, lastdata=%ld, lastping=%ld, delaytime=%ld, flag=%d, options=%d, bps=%d, client=%s",
2742 My_Connections[i].sock, My_Connections[i].host,
2743 My_Connections[i].lastdata, My_Connections[i].lastping,
2744 My_Connections[i].delaytime, My_Connections[i].flag,
2745 My_Connections[i].options, My_Connections[i].bps,
2746 My_Connections[i].client ? Client_ID(My_Connections[i].client) : "-");
2748 } /* Conn_DumpClients */