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 static bool Handle_Write PARAMS(( CONN_ID Idx ));
78 static bool Conn_Write PARAMS(( CONN_ID Idx, char *Data, size_t Len ));
79 static int New_Connection PARAMS(( int Sock, bool IsSSL ));
80 static CONN_ID Socket2Index PARAMS(( int Sock ));
81 static void Read_Request PARAMS(( CONN_ID Idx ));
82 static unsigned int Handle_Buffer PARAMS(( CONN_ID Idx ));
83 static void Check_Connections PARAMS(( void ));
84 static void Check_Servers PARAMS(( void ));
85 static void Init_Conn_Struct PARAMS(( CONN_ID Idx ));
86 static bool Init_Socket PARAMS(( int Sock ));
87 static void New_Server PARAMS(( int Server, ng_ipaddr_t *dest ));
88 static void Simple_Message PARAMS(( int Sock, const char *Msg ));
89 static int NewListener PARAMS(( const char *listen_addr, UINT16 Port ));
90 static void Account_Connection PARAMS((void));
92 static array My_Listeners;
93 static array My_ConnArray;
94 static size_t NumConnections, NumConnectionsMax, NumConnectionsAccepted;
97 int allow_severity = LOG_INFO;
98 int deny_severity = LOG_ERR;
101 static void server_login PARAMS((CONN_ID idx));
104 extern struct SSLOptions Conf_SSLOptions;
105 static bool SSL_WantRead PARAMS((const CONNECTION *c));
106 static bool SSL_WantWrite PARAMS((const CONNECTION *c));
107 static void cb_listen_ssl PARAMS((int sock, short irrelevant));
108 static void cb_connserver_login_ssl PARAMS((int sock, short what));
109 static void cb_clientserver_ssl PARAMS((int sock, short what));
111 static void cb_Read_Resolver_Result PARAMS((int sock, UNUSED short what));
112 static void cb_Connect_to_Server PARAMS((int sock, UNUSED short what));
113 static void cb_clientserver PARAMS((int sock, short what));
118 * Get number of sockets available from systemd(8).
120 * ngIRCd needs to implement its own sd_listen_fds(3) function and can't
121 * use the one provided by systemd itself, because the sockets will be
122 * used in a forked child process with a new PID, and this would trigger
123 * an error in the standard implementation.
125 * @return Number of sockets available, -1 if sockets have already been
126 * initialized, or 0 when no sockets have been passed.
129 my_sd_listen_fds(void)
134 /* Check if LISTEN_PID exists; but we ignore the result, because
135 * normally ngircd forks a child before checking this, and therefore
136 * the PID set in the environment is always wrong ... */
137 e = getenv("LISTEN_PID");
141 e = getenv("LISTEN_FDS");
146 unsetenv("LISTEN_FDS");
153 * IO callback for listening sockets: handle new connections. This callback
154 * gets called when a new non-SSL connection should be accepted.
156 * @param sock Socket descriptor.
157 * @param irrelevant (ignored IO specification)
160 cb_listen(int sock, short irrelevant)
163 (void) New_Connection(sock, false);
167 * IO callback for new outgoing non-SSL server connections.
169 * @param sock Socket descriptor.
170 * @param what IO specification (IO_WANTREAD/IO_WANTWRITE/...).
173 cb_connserver(int sock, UNUSED short what)
175 int res, err, server;
177 CONN_ID idx = Socket2Index( sock );
180 LogDebug("cb_connserver wants to write on unknown socket?!");
185 assert(what & IO_WANTWRITE);
187 /* Make sure that the server is still configured; it could have been
188 * removed in the meantime! */
189 server = Conf_GetServer(idx);
191 Log(LOG_ERR, "Connection on socket %d to \"%s\" aborted!",
192 sock, My_Connections[idx].host);
193 Conn_Close(idx, "Connection aborted", NULL, false);
197 /* connect() finished, get result. */
198 sock_len = (socklen_t)sizeof(err);
199 res = getsockopt(My_Connections[idx].sock, SOL_SOCKET, SO_ERROR,
201 assert(sock_len == sizeof(err));
203 /* Error while connecting? */
204 if ((res != 0) || (err != 0)) {
206 Log(LOG_CRIT, "getsockopt (connection %d): %s!",
207 idx, strerror(errno));
210 "Can't connect socket to \"%s:%d\" (connection %d): %s!",
211 My_Connections[idx].host, Conf_Server[server].port,
214 Conn_Close(idx, "Can't connect", NULL, false);
216 if (ng_ipaddr_af(&Conf_Server[server].dst_addr[0])) {
217 /* more addresses to try... */
218 New_Server(server, &Conf_Server[server].dst_addr[0]);
219 /* connection to dst_addr[0] is now in progress, so
220 * remove this address... */
221 Conf_Server[server].dst_addr[0] =
222 Conf_Server[server].dst_addr[1];
223 memset(&Conf_Server[server].dst_addr[1], 0,
224 sizeof(Conf_Server[server].dst_addr[1]));
229 /* connect() succeeded, remove all additional addresses */
230 memset(&Conf_Server[server].dst_addr, 0,
231 sizeof(Conf_Server[server].dst_addr));
233 Conn_OPTION_DEL( &My_Connections[idx], CONN_ISCONNECTING );
235 if ( Conn_OPTION_ISSET( &My_Connections[idx], CONN_SSL_CONNECT )) {
236 io_event_setcb( sock, cb_connserver_login_ssl );
237 io_event_add( sock, IO_WANTWRITE|IO_WANTREAD );
245 * Login to a remote server.
247 * @param idx Connection index.
250 server_login(CONN_ID idx)
253 "Connection %d (socket %d) with \"%s:%d\" established. Now logging in ...",
254 idx, My_Connections[idx].sock, My_Connections[idx].host,
255 Conf_Server[Conf_GetServer(idx)].port);
257 io_event_setcb( My_Connections[idx].sock, cb_clientserver);
258 io_event_add( My_Connections[idx].sock, IO_WANTREAD|IO_WANTWRITE);
260 /* Send PASS and SERVER command to peer */
261 Conn_WriteStr(idx, "PASS %s %s",
262 Conf_Server[Conf_GetServer( idx )].pwd_out, NGIRCd_ProtoID);
263 Conn_WriteStr(idx, "SERVER %s :%s",
264 Conf_ServerName, Conf_ServerInfo);
268 * IO callback for established non-SSL client and server connections.
270 * @param sock Socket descriptor.
271 * @param what IO specification (IO_WANTREAD/IO_WANTWRITE/...).
274 cb_clientserver(int sock, short what)
276 CONN_ID idx = Socket2Index(sock);
285 if (what & IO_WANTREAD
286 || (Conn_OPTION_ISSET(&My_Connections[idx], CONN_SSL_WANT_WRITE))) {
287 /* if TLS layer needs to write additional data, call
288 * Read_Request() instead so that SSL/TLS can continue */
292 if (what & IO_WANTREAD)
295 if (what & IO_WANTWRITE)
300 * Initialize connection module.
307 Pool_Size = CONNECTION_POOL;
308 if ((Conf_MaxConnections > 0) &&
309 (Pool_Size > Conf_MaxConnections))
310 Pool_Size = Conf_MaxConnections;
312 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)Pool_Size)) {
313 Log(LOG_EMERG, "Can't allocate memory! [Conn_Init]");
317 /* FIXME: My_Connetions/Pool_Size is needed by other parts of the
318 * code; remove them! */
319 My_Connections = (CONNECTION*) array_start(&My_ConnArray);
321 LogDebug("Allocated connection pool for %d items (%ld bytes).",
322 array_length(&My_ConnArray, sizeof(CONNECTION)),
323 array_bytes(&My_ConnArray));
325 assert(array_length(&My_ConnArray, sizeof(CONNECTION)) >= (size_t)Pool_Size);
327 array_free( &My_Listeners );
329 for (i = 0; i < Pool_Size; i++)
334 * Clean up connection module.
341 Conn_ExitListeners();
343 LogDebug("Shutting down all connections ..." );
344 for( idx = 0; idx < Pool_Size; idx++ ) {
345 if( My_Connections[idx].sock > NONE ) {
346 Conn_Close( idx, NULL, NGIRCd_SignalRestart ?
347 "Server going down (restarting)":"Server going down", true );
351 array_free(&My_ConnArray);
352 My_Connections = NULL;
354 io_library_shutdown();
358 * Close all sockets (file descriptors) of open connections.
359 * This is useful in forked child processes, for example, to make sure that
360 * they don't hold connections open that the main process wants to close.
363 Conn_CloseAllSockets(int ExceptOf)
367 for(idx = 0; idx < Pool_Size; idx++) {
368 if(My_Connections[idx].sock > NONE &&
369 My_Connections[idx].sock != ExceptOf)
370 close(My_Connections[idx].sock);
375 * Initialize listening ports.
377 * @param a Array containing the ports the daemon should listen on.
378 * @param listen_addr Address the socket should listen on (can be "0.0.0.0").
379 * @param func IO callback function to register.
380 * @returns Number of listening sockets created.
383 Init_Listeners(array *a, const char *listen_addr, void (*func)(int,short))
385 unsigned int created = 0;
390 len = array_length(a, sizeof (UINT16));
391 port = array_start(a);
393 fd = NewListener(listen_addr, *port);
398 if (!io_event_create( fd, IO_WANTREAD, func )) {
400 "io_event_create(): Can't add fd %d (port %u): %s!",
401 fd, (unsigned int) *port, strerror(errno));
413 * Initialize all listening sockets.
415 * @returns Number of created listening sockets
418 Conn_InitListeners( void )
420 /* Initialize ports on which the server should accept connections */
421 unsigned int created = 0;
422 char *af_str, *copy, *listen_addr;
423 int count, fd, i, addr_len;
426 assert(Conf_ListenAddress);
428 count = my_sd_listen_fds();
431 "Not re-initializing listening sockets of systemd(8) ...");
435 /* systemd(8) passed sockets to us, so don't try to initialize
436 * listening sockets on our own but use the passed ones */
437 LogDebug("Initializing %d systemd sockets ...", count);
438 for (i = 0; i < count; i++) {
439 fd = SD_LISTEN_FDS_START + i;
440 addr_len = (int)sizeof(addr);
441 getsockname(fd, (struct sockaddr *)&addr,
442 (socklen_t*)&addr_len);
444 if (addr.sin4.sin_family != AF_INET
445 && addr.sin4.sin_family != AF_INET6)
447 if (addr.sin4.sin_family != AF_INET)
450 /* Socket is of unsupported type! For example,
451 * systemd passed in an IPv6 socket but ngIRCd
452 * isn't compiled with IPv6 support. */
453 switch (addr.sin4.sin_family)
455 case AF_UNSPEC: af_str = "AF_UNSPEC"; break;
456 case AF_UNIX: af_str = "AF_UNIX"; break;
457 case AF_INET: af_str = "AF_INET"; break;
459 case AF_INET6: af_str = "AF_INET6"; break;
462 case AF_NETLINK: af_str = "AF_NETLINK"; break;
464 default: af_str = "unknown"; break;
467 "Socket %d is of unsupported type \"%s\" (%d), have to ignore it!",
468 fd, af_str, addr.sin4.sin_family);
474 if (!io_event_create(fd, IO_WANTREAD, cb_listen)) {
476 "io_event_create(): Can't add fd %d: %s!",
477 fd, strerror(errno));
481 "Initialized socket %d from systemd(8): %s:%d.", fd,
482 ng_ipaddr_tostr(&addr), ng_ipaddr_getport(&addr));
488 /* not using systemd socket activation, initialize listening sockets: */
490 /* can't use Conf_ListenAddress directly, see below */
491 copy = strdup(Conf_ListenAddress);
493 Log(LOG_CRIT, "Cannot copy %s: %s", Conf_ListenAddress,
497 listen_addr = strtok(copy, ",");
499 while (listen_addr) {
500 ngt_TrimStr(listen_addr);
502 created += Init_Listeners(&Conf_ListenPorts,
503 listen_addr, cb_listen);
505 created += Init_Listeners(&Conf_SSLOptions.ListenPorts,
506 listen_addr, cb_listen_ssl);
510 listen_addr = strtok(NULL, ",");
513 /* Can't free() Conf_ListenAddress here: on REHASH, if the config file
514 * cannot be re-loaded, we'd end up with a NULL Conf_ListenAddress.
515 * Instead, free() takes place in conf.c, before the config file
516 * is being parsed. */
520 } /* Conn_InitListeners */
523 * Shut down all listening sockets.
526 Conn_ExitListeners( void )
528 /* Close down all listening sockets */
532 /* Get number of listening sockets to shut down. There can be none
533 * if ngIRCd has been "socket activated" by systemd. */
534 arraylen = array_length(&My_Listeners, sizeof (int));
539 "Shutting down all listening sockets (%d total) ...", arraylen);
540 fd = array_start(&My_Listeners);
545 LogDebug("Listening socket %d closed.", *fd );
548 array_free(&My_Listeners);
549 } /* Conn_ExitListeners */
552 * Bind a socket to a specific (source) address.
554 * @param addr Address structure.
555 * @param listen_addrstr Source address as string.
556 * @param Port Port number.
557 * @returns true on success, false otherwise.
560 InitSinaddrListenAddr(ng_ipaddr_t *addr, const char *listen_addrstr, UINT16 Port)
564 ret = ng_ipaddr_init(addr, listen_addrstr, Port);
566 assert(listen_addrstr);
568 "Can't bind to [%s]:%u: can't convert ip address \"%s\"!",
569 listen_addrstr, Port, listen_addrstr);
575 * Set a socket to "IPv6 only". If the given socket doesn't belong to the
576 * AF_INET6 family, or the operating system doesn't support this functionality,
577 * this function retruns silently.
579 * @param af Address family of the socket.
580 * @param sock Socket handle.
583 set_v6_only(int af, int sock)
585 #if defined(IPV6_V6ONLY) && defined(WANT_IPV6)
591 if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, (socklen_t)sizeof(on)))
592 Log(LOG_ERR, "Could not set IPV6_V6ONLY: %s", strerror(errno));
600 * Initialize new listening port.
602 * @param listen_addr Local address to bind the socet to (can be 0.0.0.0).
603 * @param Port Port number on which the new socket should be listening.
604 * @returns file descriptor of the socket or -1 on failure.
607 NewListener(const char *listen_addr, UINT16 Port)
609 /* Create new listening socket on specified port */
613 if (!InitSinaddrListenAddr(&addr, listen_addr, Port))
616 af = ng_ipaddr_af(&addr);
617 sock = socket(af, SOCK_STREAM, 0);
619 Log(LOG_CRIT, "Can't create socket (af %d) : %s!", af,
624 set_v6_only(af, sock);
626 if (!Init_Socket(sock))
629 if (bind(sock, (struct sockaddr *)&addr, ng_ipaddr_salen(&addr)) != 0) {
630 Log(LOG_CRIT, "Can't bind socket to address %s:%d - %s!",
631 ng_ipaddr_tostr(&addr), Port, strerror(errno));
636 if (listen(sock, 10) != 0) {
637 Log(LOG_CRIT, "Can't listen on socket: %s!", strerror(errno));
642 /* keep fd in list so we can close it when ngircd restarts/shuts down */
643 if (!array_catb(&My_Listeners, (char *)&sock, sizeof(int))) {
644 Log(LOG_CRIT, "Can't add socket to My_Listeners array: %s!",
650 Log(LOG_INFO, "Now listening on [%s]:%d (socket %d).",
651 ng_ipaddr_tostr(&addr), Port, sock);
656 * "Main Loop": Loop until shutdown or restart is signalled.
658 * This function loops until a shutdown or restart of ngIRCd is signalled and
659 * calls io_dispatch() to check for readable and writable sockets every second.
660 * It checks for status changes on pending connections (e. g. when a hostname
661 * has been resolved), checks for "penalties" and timeouts, and handles the
668 size_t wdatalen, bytes_processed;
672 while (!NGIRCd_SignalQuit && !NGIRCd_SignalRestart) {
675 /* Check configured servers and established links */
679 /* Expire outdated class/list items */
682 /* Look for non-empty read buffers ... */
683 for (i = 0; i < Pool_Size; i++) {
684 if ((My_Connections[i].sock > NONE)
685 && (array_bytes(&My_Connections[i].rbuf) > 0)) {
686 /* ... and try to handle the received data */
687 bytes_processed = Handle_Buffer(i);
688 /* if we processed data, and there might be
689 * more commands in the input buffer, do not
690 * try to read any more data now */
691 if (bytes_processed &&
692 array_bytes(&My_Connections[i].rbuf) > 2) {
694 ("Throttling connection %d: command limit reached!",
696 Conn_SetPenalty(i, 1);
701 /* Look for non-empty write buffers ... */
702 for (i = 0; i < Pool_Size; i++) {
703 if (My_Connections[i].sock <= NONE)
706 wdatalen = array_bytes(&My_Connections[i].wbuf);
709 array_bytes(&My_Connections[i].zip.wbuf) > 0)
715 if (SSL_WantRead(&My_Connections[i]))
718 io_event_add(My_Connections[i].sock,
723 /* Check from which sockets we possibly could read ... */
724 for (i = 0; i < Pool_Size; i++) {
725 if (My_Connections[i].sock <= NONE)
728 if (SSL_WantWrite(&My_Connections[i]))
729 /* TLS/SSL layer needs to write data; deal
730 * with this first! */
733 if (Proc_InProgress(&My_Connections[i].proc_stat)) {
734 /* Wait for completion of forked subprocess
735 * and ignore the socket in the meantime ... */
736 io_event_del(My_Connections[i].sock,
741 if (Conn_OPTION_ISSET(&My_Connections[i], CONN_ISCONNECTING))
742 /* Wait for completion of connect() ... */
745 if (My_Connections[i].delaytime > t) {
746 /* There is a "penalty time" set: ignore socket! */
747 io_event_del(My_Connections[i].sock,
752 io_event_add(My_Connections[i].sock, IO_WANTREAD);
755 /* Set the timeout for reading from the network to 1 second,
756 * which is the granularity with witch we handle "penalty
757 * times" for example.
758 * Note: tv_sec/usec are undefined(!) after io_dispatch()
759 * returns, so we have to set it before each call to it! */
763 /* Wait for activity ... */
764 i = io_dispatch(&tv);
765 if (i == -1 && errno != EINTR) {
766 Log(LOG_EMERG, "Conn_Handler(): io_dispatch(): %s!",
768 Log(LOG_ALERT, "%s exiting due to fatal errors!",
773 /* Should ngIRCd timeout when idle? */
774 if (Conf_IdleTimeout > 0 && NumConnectionsAccepted > 0
775 && idle_t > 0 && time(NULL) - idle_t >= Conf_IdleTimeout) {
776 LogDebug("Server idle timeout reached: %d second%s. Initiating shutdown ...",
778 Conf_IdleTimeout == 1 ? "" : "s");
779 NGIRCd_SignalQuit = true;
783 if (NGIRCd_SignalQuit)
784 Log(LOG_NOTICE | LOG_snotice, "Server going down NOW!");
785 else if (NGIRCd_SignalRestart)
786 Log(LOG_NOTICE | LOG_snotice, "Server restarting NOW!");
790 * Write a text string into the socket of a connection.
792 * This function automatically appends CR+LF to the string and validates that
793 * the result is a valid IRC message (oversized messages are shortened, for
794 * example). Then it calls the Conn_Write() function to do the actual sending.
796 * @param Idx Index fo the connection.
797 * @param Format Format string, see printf().
798 * @returns true on success, false otherwise.
802 Conn_WriteStr(CONN_ID Idx, const char *Format, ...)
805 Conn_WriteStr(Idx, Format, va_alist)
811 char buffer[COMMAND_LEN];
820 assert( Idx > NONE );
821 assert( Format != NULL );
824 va_start( ap, Format );
828 r = vsnprintf(buffer, COMMAND_LEN - 2, Format, ap);
829 if (r >= COMMAND_LEN - 2 || r == -1) {
831 * The string that should be written to the socket is longer
832 * than the allowed size of COMMAND_LEN bytes (including both
833 * the CR and LF characters). This can be caused by the
834 * IRC_WriteXXX() functions when the prefix of this server had
835 * to be added to an already "quite long" command line which
836 * has been received from a regular IRC client, for example.
838 * We are not allowed to send such "oversized" messages to
839 * other servers and clients, see RFC 2812 2.3 and 2813 3.3
840 * ("these messages SHALL NOT exceed 512 characters in length,
841 * counting all characters including the trailing CR-LF").
843 * So we have a big problem here: we should send more bytes
844 * to the network than we are allowed to and we don't know
845 * the originator (any more). The "old" behavior of blaming
846 * the receiver ("next hop") is a bad idea (it could be just
847 * an other server only routing the message!), so the only
848 * option left is to shorten the string and to hope that the
849 * result is still somewhat useful ...
852 * C99 states that vsnprintf() "returns the number of characters
853 * that would have been printed if the n were unlimited"; but
854 * according to the Linux manual page "glibc until 2.0.6 would
855 * return -1 when the output was truncated" -- so we have to
856 * handle both cases ...
860 strcpy (buffer + sizeof(buffer) - strlen(CUT_TXTSUFFIX) - 2 - 1,
865 ptr = strchr(buffer + 1, ':');
868 message = Conn_EncodingTo(Idx, ptr);
870 strlcpy(ptr, message, sizeof(buffer) - (ptr - buffer));
876 Log(LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer);
879 len = strlcat( buffer, "\r\n", sizeof( buffer ));
880 ok = Conn_Write(Idx, buffer, len);
881 My_Connections[Idx].msg_out++;
885 } /* Conn_WriteStr */
888 Conn_Password( CONN_ID Idx )
890 assert( Idx > NONE );
891 if (My_Connections[Idx].pwd == NULL)
894 return My_Connections[Idx].pwd;
895 } /* Conn_Password */
898 Conn_SetPassword( CONN_ID Idx, const char *Pwd )
900 assert( Idx > NONE );
902 if (My_Connections[Idx].pwd)
903 free(My_Connections[Idx].pwd);
905 My_Connections[Idx].pwd = strdup(Pwd);
906 if (My_Connections[Idx].pwd == NULL) {
907 Log(LOG_EMERG, "Can't allocate memory! [Conn_SetPassword]");
910 } /* Conn_SetPassword */
913 * Append Data to the outbound write buffer of a connection.
915 * @param Idx Index of the connection.
916 * @param Data pointer to the data.
917 * @param Len length of Data.
918 * @returns true on success, false otherwise.
921 Conn_Write( CONN_ID Idx, char *Data, size_t Len )
924 size_t writebuf_limit = WRITEBUFFER_MAX_LEN;
925 assert( Idx > NONE );
926 assert( Data != NULL );
929 /* Is the socket still open? A previous call to Conn_Write()
930 * may have closed the connection due to a fatal error.
931 * In this case it is sufficient to return an error, as well. */
932 if (My_Connections[Idx].sock <= NONE) {
933 LogDebug("Skipped write on closed socket (connection %d).", Idx);
937 /* Make sure that there still exists a CLIENT structure associated
938 * with this connection and check if this is a server or not: */
939 c = Conn_GetClient(Idx);
941 /* Servers do get special write buffer limits, so they can
942 * generate all the messages that are required while peering. */
943 if (Client_Type(c) == CLIENT_SERVER)
944 writebuf_limit = WRITEBUFFER_SLINK_LEN;
946 LogDebug("Write on socket without client (connection %d)!?", Idx);
949 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
951 * Zip_Buffer() does all the dirty work for us: it flushes
952 * the (pre-)compression buffers if required and handles
953 * all error conditions. */
954 if (!Zip_Buffer(Idx, Data, Len))
960 /* Uncompressed link:
961 * Check if outbound buffer has enough space for the data. */
962 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
963 WRITEBUFFER_FLUSH_LEN) {
964 /* Buffer is full, flush it. Handle_Write deals with
965 * low-level errors, if any. */
966 if (!Handle_Write(Idx))
970 /* When the write buffer is still too big after flushing it,
971 * the connection will be killed. */
972 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
975 "Write buffer space exhausted (connection %d, limit is %lu bytes, %lu bytes new, %lu bytes pending)",
976 Idx, writebuf_limit, Len,
977 (unsigned long)array_bytes(&My_Connections[Idx].wbuf));
978 Conn_Close(Idx, "Write buffer space exhausted", NULL, false);
982 /* Copy data to write buffer */
983 if (!array_catb(&My_Connections[Idx].wbuf, Data, Len))
986 My_Connections[Idx].bytes_out += Len;
989 /* Adjust global write counter */
996 * Shut down a connection.
998 * @param Idx Connection index.
999 * @param LogMsg Message to write to the log or NULL. If no LogMsg
1000 * is given, the FwdMsg is logged.
1001 * @param FwdMsg Message to forward to remote servers.
1002 * @param InformClient If true, inform the client on the connection which is
1003 * to be shut down of the reason (FwdMsg) and send
1004 * connection statistics before disconnecting it.
1007 Conn_Close(CONN_ID Idx, const char *LogMsg, const char *FwdMsg, bool InformClient)
1009 /* Close connection. Open pipes of asynchronous resolver
1010 * sub-processes are closed down. */
1016 double in_z_k, out_z_k;
1020 assert( Idx > NONE );
1022 /* Is this link already shutting down? */
1023 if( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ISCLOSING )) {
1024 /* Conn_Close() has been called recursively for this link;
1025 * probable reason: Handle_Write() failed -- see below. */
1026 LogDebug("Recursive request to close connection %d!", Idx );
1030 assert( My_Connections[Idx].sock > NONE );
1032 /* Mark link as "closing" */
1033 Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCLOSING );
1035 port = ng_ipaddr_getport(&My_Connections[Idx].addr);
1036 Log(LOG_INFO, "Shutting down connection %d (%s) with \"%s:%d\" ...", Idx,
1037 LogMsg ? LogMsg : FwdMsg, My_Connections[Idx].host, port);
1039 /* Search client, if any */
1040 c = Conn_GetClient( Idx );
1042 /* Should the client be informed? */
1045 /* Send statistics to client if registered as user: */
1046 if ((c != NULL) && (Client_Type(c) == CLIENT_USER)) {
1048 ":%s NOTICE %s :%sConnection statistics: client %.1f kb, server %.1f kb.",
1049 Client_ID(Client_ThisServer()), Client_ID(c),
1051 (double)My_Connections[Idx].bytes_in / 1024,
1052 (double)My_Connections[Idx].bytes_out / 1024);
1055 /* Send ERROR to client (see RFC 2812, section 3.1.7) */
1057 Conn_WriteStr(Idx, "ERROR :%s", FwdMsg);
1059 Conn_WriteStr(Idx, "ERROR :Closing connection");
1062 /* Try to write out the write buffer. Note: Handle_Write() eventually
1063 * removes the CLIENT structure associated with this connection if an
1064 * error occurs! So we have to re-check if there is still an valid
1065 * CLIENT structure after calling Handle_Write() ...*/
1066 (void)Handle_Write( Idx );
1068 /* Search client, if any (re-check!) */
1069 c = Conn_GetClient( Idx );
1071 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_SSL )) {
1072 LogDebug("SSL connection %d shutting down ...", Idx);
1073 ConnSSL_Free(&My_Connections[Idx]);
1076 /* Shut down socket */
1077 if (! io_close(My_Connections[Idx].sock)) {
1078 /* Oops, we can't close the socket!? This is ... ugly! */
1080 "Error closing connection %d (socket %d) with %s:%d - %s! (ignored)",
1081 Idx, My_Connections[Idx].sock, My_Connections[Idx].host,
1082 port, strerror(errno));
1085 /* Mark socket as invalid: */
1086 My_Connections[Idx].sock = NONE;
1088 /* If there is still a client, unregister it now */
1090 Client_Destroy(c, LogMsg, FwdMsg, true);
1092 /* Calculate statistics and log information */
1093 in_k = (double)My_Connections[Idx].bytes_in / 1024;
1094 out_k = (double)My_Connections[Idx].bytes_out / 1024;
1096 if (Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP)) {
1097 in_z_k = (double)My_Connections[Idx].zip.bytes_in / 1024;
1098 out_z_k = (double)My_Connections[Idx].zip.bytes_out / 1024;
1099 /* Make sure that no division by zero can occur during
1100 * the calculation of in_p and out_p: in_z_k and out_z_k
1101 * are non-zero, that's guaranteed by the protocol until
1102 * compression can be enabled. */
1107 in_p = (int)(( in_k * 100 ) / in_z_k );
1108 out_p = (int)(( out_k * 100 ) / out_z_k );
1110 "Connection %d with \"%s:%d\" closed (in: %.1fk/%.1fk/%d%%, out: %.1fk/%.1fk/%d%%).",
1111 Idx, My_Connections[Idx].host, port,
1112 in_k, in_z_k, in_p, out_k, out_z_k, out_p);
1118 "Connection %d with \"%s:%d\" closed (in: %.1fk, out: %.1fk).",
1119 Idx, My_Connections[Idx].host, port,
1123 /* Servers: Modify time of next connect attempt? */
1124 Conf_UnsetServer( Idx );
1127 /* Clean up zlib, if link was compressed */
1128 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
1129 inflateEnd( &My_Connections[Idx].zip.in );
1130 deflateEnd( &My_Connections[Idx].zip.out );
1131 array_free(&My_Connections[Idx].zip.rbuf);
1132 array_free(&My_Connections[Idx].zip.wbuf);
1136 array_free(&My_Connections[Idx].rbuf);
1137 array_free(&My_Connections[Idx].wbuf);
1138 if (My_Connections[Idx].pwd != NULL)
1139 free(My_Connections[Idx].pwd);
1141 /* Clean up connection structure (=free it) */
1142 Init_Conn_Struct( Idx );
1144 assert(NumConnections > 0);
1147 LogDebug("Shutdown of connection %d completed, %ld connection%s left.",
1148 Idx, NumConnections, NumConnections != 1 ? "s" : "");
1150 idle_t = NumConnections > 0 ? 0 : time(NULL);
1154 * Get current number of connections.
1156 * @returns Number of current connections.
1161 return NumConnections;
1165 * Get number of maximum simultaneous connections.
1167 * @returns Number of maximum simultaneous connections.
1172 return NumConnectionsMax;
1173 } /* Conn_CountMax */
1176 * Get number of connections accepted since the daemon startet.
1178 * @returns Number of connections accepted.
1181 Conn_CountAccepted(void)
1183 return NumConnectionsAccepted;
1184 } /* Conn_CountAccepted */
1187 * Synchronize established connections and configured server structures
1188 * after a configuration update and store the correct connection IDs, if any.
1191 Conn_SyncServerStruct(void)
1197 for (i = 0; i < Pool_Size; i++) {
1198 if (My_Connections[i].sock == NONE)
1202 client = Conn_GetClient(i);
1203 if (!client || Client_Type(client) != CLIENT_SERVER)
1206 for (c = 0; c < MAX_SERVERS; c++) {
1207 /* Configured server? */
1208 if (!Conf_Server[c].host[0])
1211 if (strcasecmp(Conf_Server[c].name, Client_ID(client)) == 0)
1212 Conf_Server[c].conn_id = i;
1215 } /* SyncServerStruct */
1218 * Get IP address string of a connection.
1220 * @param Idx Connection index.
1221 * @return Pointer to a global buffer containing the IP address as string.
1224 Conn_GetIPAInfo(CONN_ID Idx)
1227 return ng_ipaddr_tostr(&My_Connections[Idx].addr);
1231 * Send out data of write buffer; connect new sockets.
1233 * @param Idx Connection index.
1234 * @returns true on success, false otherwise.
1237 Handle_Write( CONN_ID Idx )
1242 assert( Idx > NONE );
1243 if ( My_Connections[Idx].sock < 0 ) {
1244 LogDebug("Handle_Write() on closed socket, connection %d", Idx);
1247 assert( My_Connections[Idx].sock > NONE );
1249 wdatalen = array_bytes(&My_Connections[Idx].wbuf );
1252 if (wdatalen == 0) {
1253 /* Write buffer is empty, so we try to flush the compression
1254 * buffer and get some data to work with from there :-) */
1255 if (!Zip_Flush(Idx))
1258 /* Now the write buffer most probably has changed: */
1259 wdatalen = array_bytes(&My_Connections[Idx].wbuf);
1263 if (wdatalen == 0) {
1264 /* Still no data, fine. */
1265 io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
1271 ("Handle_Write() called for connection %d, %ld bytes pending ...",
1276 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_SSL )) {
1277 len = ConnSSL_Write(&My_Connections[Idx],
1278 array_start(&My_Connections[Idx].wbuf),
1283 len = write(My_Connections[Idx].sock,
1284 array_start(&My_Connections[Idx].wbuf), wdatalen );
1287 if (errno == EAGAIN || errno == EINTR)
1290 if (!Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ISCLOSING))
1292 "Write error on connection %d (socket %d): %s!",
1293 Idx, My_Connections[Idx].sock, strerror(errno));
1295 LogDebug("Recursive write error on connection %d (socket %d): %s!",
1296 Idx, My_Connections[Idx].sock, strerror(errno));
1297 Conn_Close(Idx, "Write error", NULL, false);
1301 /* move any data not yet written to beginning */
1302 array_moveleft(&My_Connections[Idx].wbuf, 1, (size_t)len);
1305 } /* Handle_Write */
1308 * Count established connections to a specific IP address.
1310 * @returns Number of established connections.
1313 Count_Connections(ng_ipaddr_t *a)
1318 for (i = 0; i < Pool_Size; i++) {
1319 if (My_Connections[i].sock <= NONE)
1321 if (ng_ipaddr_ipequal(&My_Connections[i].addr, a))
1325 } /* Count_Connections */
1328 * Initialize new client connection on a listening socket.
1330 * @param Sock Listening socket descriptor.
1331 * @param IsSSL true if this socket expects SSL-encrypted data.
1332 * @returns Accepted socket descriptor or -1 on error.
1335 New_Connection(int Sock, UNUSED bool IsSSL)
1338 struct request_info req;
1340 ng_ipaddr_t new_addr;
1341 char ip_str[NG_INET_ADDRSTRLEN];
1342 int new_sock, new_sock_len;
1346 assert(Sock > NONE);
1348 LogDebug("Accepting new connection on socket %d ...", Sock);
1350 new_sock_len = (int)sizeof(new_addr);
1351 new_sock = accept(Sock, (struct sockaddr *)&new_addr,
1352 (socklen_t *)&new_sock_len);
1354 Log(LOG_CRIT, "Can't accept connection: %s!", strerror(errno));
1357 NumConnectionsAccepted++;
1359 if (!ng_ipaddr_tostr_r(&new_addr, ip_str)) {
1360 Log(LOG_CRIT, "fd %d: Can't convert IP address!", new_sock);
1361 Simple_Message(new_sock, "ERROR :Internal Server Error");
1367 /* Validate socket using TCP Wrappers */
1368 request_init(&req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock,
1369 RQ_CLIENT_SIN, &new_addr, NULL);
1371 if (!hosts_access(&req)) {
1373 "Refused connection from %s (by TCP Wrappers)!", ip_str);
1374 Simple_Message(new_sock, "ERROR :Connection refused");
1380 if (!Init_Socket(new_sock))
1383 /* Check global connection limit */
1384 if ((Conf_MaxConnections > 0) &&
1385 (NumConnections >= (size_t) Conf_MaxConnections)) {
1386 Log(LOG_ALERT, "Can't accept connection: limit (%d) reached!",
1387 Conf_MaxConnections);
1388 Simple_Message(new_sock, "ERROR :Connection limit reached");
1393 /* Check IP-based connection limit */
1394 cnt = Count_Connections(&new_addr);
1395 if ((Conf_MaxConnectionsIP > 0) && (cnt >= Conf_MaxConnectionsIP)) {
1396 /* Access denied, too many connections from this IP address! */
1398 "Refused connection from %s: too may connections (%ld) from this IP address!",
1400 Simple_Message(new_sock,
1401 "ERROR :Connection refused, too many connections from your IP address");
1406 if (new_sock >= Pool_Size) {
1407 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION),
1408 (size_t) new_sock)) {
1410 "Can't allocate memory! [New_Connection]");
1411 Simple_Message(new_sock, "ERROR: Internal error");
1415 LogDebug("Bumped connection pool to %ld items (internal: %ld items, %ld bytes)",
1416 new_sock, array_length(&My_ConnArray,
1417 sizeof(CONNECTION)), array_bytes(&My_ConnArray));
1419 /* Adjust pointer to new block */
1420 My_Connections = array_start(&My_ConnArray);
1421 while (Pool_Size <= new_sock)
1422 Init_Conn_Struct(Pool_Size++);
1425 /* register callback */
1426 if (!io_event_create(new_sock, IO_WANTREAD, cb_clientserver)) {
1428 "Can't accept connection: io_event_create failed!");
1429 Simple_Message(new_sock, "ERROR :Internal error");
1434 c = Client_NewLocal(new_sock, NULL, CLIENT_UNKNOWN, false);
1437 "Can't accept connection: can't create client structure!");
1438 Simple_Message(new_sock, "ERROR :Internal error");
1443 Init_Conn_Struct(new_sock);
1444 My_Connections[new_sock].sock = new_sock;
1445 My_Connections[new_sock].addr = new_addr;
1446 My_Connections[new_sock].client = c;
1448 /* Set initial hostname to IP address. This becomes overwritten when
1449 * the DNS lookup is enabled and succeeds, but is used otherwise. */
1450 if (ng_ipaddr_af(&new_addr) != AF_INET)
1451 snprintf(My_Connections[new_sock].host,
1452 sizeof(My_Connections[new_sock].host), "[%s]", ip_str);
1454 strlcpy(My_Connections[new_sock].host, ip_str,
1455 sizeof(My_Connections[new_sock].host));
1457 Client_SetHostname(c, My_Connections[new_sock].host);
1459 Log(LOG_INFO, "Accepted connection %d from \"%s:%d\" on socket %d.",
1460 new_sock, My_Connections[new_sock].host,
1461 ng_ipaddr_getport(&new_addr), Sock);
1462 Account_Connection();
1465 /* Delay connection initalization until SSL handshake is finished */
1468 Conn_StartLogin(new_sock);
1471 } /* New_Connection */
1474 * Finish connection initialization, start resolver subprocess.
1476 * @param Idx Connection index.
1479 Conn_StartLogin(CONN_ID Idx)
1481 int ident_sock = -1;
1485 /* Nothing to do if DNS (and resolver subprocess) is disabled */
1490 /* Should we make an IDENT request? */
1492 ident_sock = My_Connections[Idx].sock;
1495 if (Conf_NoticeAuth) {
1496 /* Send "NOTICE AUTH" messages to the client */
1499 (void)Conn_WriteStr(Idx,
1500 "NOTICE AUTH :*** Looking up your hostname and checking ident");
1503 (void)Conn_WriteStr(Idx,
1504 "NOTICE AUTH :*** Looking up your hostname");
1505 /* Send buffered data to the client, but break on errors
1506 * because Handle_Write() would have closed the connection
1507 * again in this case! */
1508 if (!Handle_Write(Idx))
1512 Resolve_Addr(&My_Connections[Idx].proc_stat, &My_Connections[Idx].addr,
1513 ident_sock, cb_Read_Resolver_Result);
1517 * Update global connection counters.
1520 Account_Connection(void)
1524 if (NumConnections > NumConnectionsMax)
1525 NumConnectionsMax = NumConnections;
1526 LogDebug("Total number of connections now %lu (max %lu).",
1527 NumConnections, NumConnectionsMax);
1528 } /* Account_Connection */
1531 * Translate socket handle into connection index.
1533 * @param Sock Socket handle.
1534 * @returns Connecion index or NONE, if no connection could be found.
1537 Socket2Index( int Sock )
1539 assert( Sock >= 0 );
1541 if( Sock >= Pool_Size || My_Connections[Sock].sock != Sock ) {
1542 /* the Connection was already closed again, likely due to
1544 LogDebug("Socket2Index: can't get connection for socket %d!", Sock);
1548 } /* Socket2Index */
1551 * Read data from the network to the read buffer. If an error occurs,
1552 * the socket of this connection will be shut down.
1554 * @param Idx Connection index.
1557 Read_Request( CONN_ID Idx )
1560 static const unsigned int maxbps = COMMAND_LEN / 2;
1561 char readbuf[READBUFFER_LEN];
1564 assert( Idx > NONE );
1565 assert( My_Connections[Idx].sock > NONE );
1568 if ((array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN) ||
1569 (array_bytes(&My_Connections[Idx].zip.rbuf) >= READBUFFER_LEN))
1571 if (array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN)
1574 /* Read buffer is full */
1576 "Receive buffer space exhausted (connection %d): %d bytes",
1577 Idx, array_bytes(&My_Connections[Idx].rbuf));
1578 Conn_Close(Idx, "Receive buffer space exhausted", NULL, false);
1583 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_SSL))
1584 len = ConnSSL_Read( &My_Connections[Idx], readbuf, sizeof(readbuf));
1587 len = read(My_Connections[Idx].sock, readbuf, sizeof(readbuf));
1589 LogDebug("Client \"%s:%u\" is closing connection %d ...",
1590 My_Connections[Idx].host,
1591 ng_ipaddr_tostr(&My_Connections[Idx].addr), Idx);
1592 Conn_Close(Idx, NULL, "Client closed connection", false);
1597 if( errno == EAGAIN ) return;
1598 Log(LOG_ERR, "Read error on connection %d (socket %d): %s!",
1599 Idx, My_Connections[Idx].sock, strerror(errno));
1600 Conn_Close(Idx, "Read error", "Client closed connection",
1605 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1606 if (!array_catb(&My_Connections[Idx].zip.rbuf, readbuf,
1609 "Could not append received data to zip input buffer (connection %d): %d bytes!",
1611 Conn_Close(Idx, "Receive buffer space exhausted", NULL,
1618 if (!array_catb( &My_Connections[Idx].rbuf, readbuf, len)) {
1620 "Could not append received data to input buffer (connection %d): %d bytes!",
1622 Conn_Close(Idx, "Receive buffer space exhausted", NULL,
1627 /* Update connection statistics */
1628 My_Connections[Idx].bytes_in += len;
1629 My_Connections[Idx].bps += Handle_Buffer(Idx);
1631 /* Make sure that there is still a valid client registered */
1632 c = Conn_GetClient(Idx);
1636 /* Update timestamp of last data received if this connection is
1637 * registered as a user, server or service connection. Don't update
1638 * otherwise, so users have at least Conf_PongTimeout seconds time to
1639 * register with the IRC server -- see Check_Connections().
1640 * Update "lastping", too, if time shifted backwards ... */
1641 if (Client_Type(c) == CLIENT_USER
1642 || Client_Type(c) == CLIENT_SERVER
1643 || Client_Type(c) == CLIENT_SERVICE) {
1645 if (My_Connections[Idx].lastdata != t)
1646 My_Connections[Idx].bps = 0;
1648 My_Connections[Idx].lastdata = t;
1649 if (My_Connections[Idx].lastping > t)
1650 My_Connections[Idx].lastping = t;
1653 /* Look at the data in the (read-) buffer of this connection */
1654 if (Client_Type(c) != CLIENT_SERVER
1655 && Client_Type(c) != CLIENT_UNKNOWNSERVER
1656 && Client_Type(c) != CLIENT_SERVICE
1657 && My_Connections[Idx].bps >= maxbps) {
1658 LogDebug("Throttling connection %d: BPS exceeded! (%u >= %u)",
1659 Idx, My_Connections[Idx].bps, maxbps);
1660 Conn_SetPenalty(Idx, 1);
1662 } /* Read_Request */
1665 * Handle all data in the connection read-buffer.
1667 * Data is processed until no complete command is left in the read buffer,
1668 * or MAX_COMMANDS[_SERVER|_SERVICE] commands were processed.
1669 * When a fatal error occurs, the connection is shut down.
1671 * @param Idx Index of the connection.
1672 * @returns Number of bytes processed.
1675 Handle_Buffer(CONN_ID Idx)
1678 char *ptr1, *ptr2, *first_eol;
1686 unsigned int i, maxcmd = MAX_COMMANDS, len_processed = 0;
1689 c = Conn_GetClient(Idx);
1690 starttime = time(NULL);
1694 /* Servers get special command limits that depend on the user count */
1695 switch (Client_Type(c)) {
1697 maxcmd = (int)(Client_UserCount() / 5)
1698 + MAX_COMMANDS_SERVER_MIN;
1699 /* Allow servers to handle even more commands while peering
1700 * to speed up server login and network synchronization. */
1701 if (Conn_LastPing(Idx) == 0)
1704 case CLIENT_SERVICE:
1705 maxcmd = MAX_COMMANDS_SERVICE; break;
1708 for (i=0; i < maxcmd; i++) {
1710 if (My_Connections[Idx].delaytime > starttime)
1713 /* Unpack compressed data, if compression is in use */
1714 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1715 /* When unzipping fails, Unzip_Buffer() shuts
1716 * down the connection itself */
1717 if (!Unzip_Buffer(Idx))
1722 if (0 == array_bytes(&My_Connections[Idx].rbuf))
1725 /* Make sure that the buffer is NULL terminated */
1726 if (!array_cat0_temporary(&My_Connections[Idx].rbuf)) {
1727 Conn_Close(Idx, NULL,
1728 "Can't allocate memory [Handle_Buffer]",
1733 /* RFC 2812, section "2.3 Messages", 5th paragraph:
1734 * "IRC messages are always lines of characters terminated
1735 * with a CR-LF (Carriage Return - Line Feed) pair [...]". */
1737 ptr = strstr(array_start(&My_Connections[Idx].rbuf), "\r\n");
1740 /* Check for non-RFC-compliant request (only CR or LF)?
1741 * Unfortunately, there are quite a few clients out there
1742 * that do this -- e. g. mIRC, BitchX, and Trillian :-( */
1743 ptr1 = strchr(array_start(&My_Connections[Idx].rbuf), '\r');
1744 ptr2 = strchr(array_start(&My_Connections[Idx].rbuf), '\n');
1746 /* Check if there is a single CR or LF _before_ the
1747 * correct CR+LF line terminator: */
1748 first_eol = ptr1 < ptr2 ? ptr1 : ptr2;
1749 if (first_eol < ptr) {
1750 /* Single CR or LF before CR+LF found */
1754 } else if (ptr1 || ptr2) {
1755 /* No CR+LF terminated command found, but single
1756 * CR or LF found ... */
1758 ptr = ptr1 < ptr2 ? ptr1 : ptr2;
1760 ptr = ptr1 ? ptr1 : ptr2;
1768 /* Complete (=line terminated) request found, handle it! */
1771 len = ptr - (char *)array_start(&My_Connections[Idx].rbuf) + delta;
1773 if (len > (COMMAND_LEN - 1)) {
1774 /* Request must not exceed 512 chars (incl. CR+LF!),
1775 * see RFC 2812. Disconnect Client if this happens. */
1777 "Request too long (connection %d): %d bytes (max. %d expected)!",
1778 Idx, array_bytes(&My_Connections[Idx].rbuf),
1780 Conn_Close(Idx, NULL, "Request too long", true);
1784 len_processed += (unsigned int)len;
1786 /* Request is empty (only '\r\n', '\r' or '\n');
1787 * delta is 2 ('\r\n') or 1 ('\r' or '\n'), see above */
1788 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1792 /* remember if stream is already compressed */
1793 old_z = My_Connections[Idx].options & CONN_ZIP;
1796 My_Connections[Idx].msg_in++;
1798 (Idx, (char *)array_start(&My_Connections[Idx].rbuf)))
1799 return 0; /* error -> connection has been closed */
1801 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1803 if ((!old_z) && (My_Connections[Idx].options & CONN_ZIP) &&
1804 (array_bytes(&My_Connections[Idx].rbuf) > 0)) {
1805 /* The last command activated socket compression.
1806 * Data that was read after that needs to be copied
1807 * to the unzip buffer for decompression: */
1809 (&My_Connections[Idx].zip.rbuf,
1810 &My_Connections[Idx].rbuf)) {
1811 Conn_Close(Idx, NULL,
1812 "Can't allocate memory [Handle_Buffer]",
1817 array_trunc(&My_Connections[Idx].rbuf);
1819 ("Moved already received data (%u bytes) to uncompression buffer.",
1820 array_bytes(&My_Connections[Idx].zip.rbuf));
1825 LogDebug("Connection %d: Processed %ld commands (max=%ld), %ld bytes. %ld bytes left in read buffer.",
1826 Idx, i, maxcmd, len_processed,
1827 array_bytes(&My_Connections[Idx].rbuf));
1830 return len_processed;
1831 } /* Handle_Buffer */
1834 * Check whether established connections are still alive or not.
1835 * If not, play PING-PONG first; and if that doesn't help either,
1836 * disconnect the respective peer.
1839 Check_Connections(void)
1845 for (i = 0; i < Pool_Size; i++) {
1846 if (My_Connections[i].sock < 0)
1849 c = Conn_GetClient(i);
1850 if (c && ((Client_Type(c) == CLIENT_USER)
1851 || (Client_Type(c) == CLIENT_SERVER)
1852 || (Client_Type(c) == CLIENT_SERVICE))) {
1853 /* connected User, Server or Service */
1854 if (My_Connections[i].lastping >
1855 My_Connections[i].lastdata) {
1856 /* We already sent a ping */
1857 if (My_Connections[i].lastping <
1858 time(NULL) - Conf_PongTimeout) {
1860 snprintf(msg, sizeof(msg),
1861 "Ping timeout: %d seconds",
1863 LogDebug("Connection %d: %s.", i, msg);
1864 Conn_Close(i, NULL, msg, true);
1866 } else if (My_Connections[i].lastdata <
1867 time(NULL) - Conf_PingTimeout) {
1868 /* We need to send a PING ... */
1869 LogDebug("Connection %d: sending PING ...", i);
1871 Conn_WriteStr(i, "PING :%s",
1872 Client_ID(Client_ThisServer()));
1875 /* The connection is not fully established yet, so
1876 * we don't do the PING-PONG game here but instead
1877 * disconnect the client after "a short time" if it's
1878 * still not registered. */
1880 if (My_Connections[i].lastdata <
1881 time(NULL) - Conf_PongTimeout) {
1883 ("Unregistered connection %d timed out ...",
1885 Conn_Close(i, NULL, "Timeout", false);
1889 } /* Check_Connections */
1892 * Check if further server links should be established.
1900 time_now = time(NULL);
1902 /* Check all configured servers */
1903 for (i = 0; i < MAX_SERVERS; i++) {
1904 if (Conf_Server[i].conn_id != NONE)
1905 continue; /* Already establishing or connected */
1906 if (!Conf_Server[i].host[0] || !Conf_Server[i].port > 0)
1907 continue; /* No host and/or port configured */
1908 if (Conf_Server[i].flags & CONF_SFLAG_DISABLED)
1909 continue; /* Disabled configuration entry */
1910 if (Conf_Server[i].lasttry > (time_now - Conf_ConnectRetry))
1911 continue; /* We have to wait a little bit ... */
1913 /* Is there already a connection in this group? */
1914 if (Conf_Server[i].group > NONE) {
1915 for (n = 0; n < MAX_SERVERS; n++) {
1918 if ((Conf_Server[n].conn_id != NONE) &&
1919 (Conf_Server[n].group == Conf_Server[i].group))
1922 if (n < MAX_SERVERS)
1926 /* Okay, try to connect now */
1928 "Preparing to establish a new server link for \"%s\" ...",
1929 Conf_Server[i].name);
1930 Conf_Server[i].lasttry = time_now;
1931 Conf_Server[i].conn_id = SERVER_WAIT;
1932 assert(Proc_GetPipeFd(&Conf_Server[i].res_stat) < 0);
1933 Resolve_Name(&Conf_Server[i].res_stat, Conf_Server[i].host,
1934 cb_Connect_to_Server);
1936 } /* Check_Servers */
1939 * Establish a new outgoing server connection.
1941 * @param Server Configuration index of the server.
1942 * @param dest Destination IP address to connect to.
1945 New_Server( int Server , ng_ipaddr_t *dest)
1947 /* Establish new server link */
1948 char ip_str[NG_INET_ADDRSTRLEN];
1949 int af_dest, res, new_sock;
1952 assert( Server > NONE );
1954 /* Make sure that the remote server hasn't re-linked to this server
1955 * asynchronously on its own */
1956 if (Conf_Server[Server].conn_id > NONE) {
1958 "Connection to \"%s\" meanwhile re-established, aborting preparation.");
1962 if (!ng_ipaddr_tostr_r(dest, ip_str)) {
1963 Log(LOG_WARNING, "New_Server: Could not convert IP to string");
1964 Conf_Server[Server].conn_id = NONE;
1968 af_dest = ng_ipaddr_af(dest);
1969 new_sock = socket(af_dest, SOCK_STREAM, 0);
1972 "Establishing connection for \"%s\" to \"%s:%d\" (%s), socket %d ...",
1973 Conf_Server[Server].name, Conf_Server[Server].host,
1974 Conf_Server[Server].port, ip_str, new_sock);
1977 Log(LOG_CRIT, "Can't create socket (af %d): %s!",
1978 af_dest, strerror(errno));
1979 Conf_Server[Server].conn_id = NONE;
1983 if (!Init_Socket(new_sock)) {
1984 Conf_Server[Server].conn_id = NONE;
1988 /* is a bind address configured? */
1989 res = ng_ipaddr_af(&Conf_Server[Server].bind_addr);
1991 /* if yes, bind now. If it fails, warn and let connect() pick a
1993 if (res && bind(new_sock, (struct sockaddr *) &Conf_Server[Server].bind_addr,
1994 ng_ipaddr_salen(&Conf_Server[Server].bind_addr)))
1996 ng_ipaddr_tostr_r(&Conf_Server[Server].bind_addr, ip_str);
1997 Log(LOG_WARNING, "Can't bind socket to %s: %s!", ip_str,
2000 ng_ipaddr_setport(dest, Conf_Server[Server].port);
2001 res = connect(new_sock, (struct sockaddr *) dest, ng_ipaddr_salen(dest));
2002 if(( res != 0 ) && ( errno != EINPROGRESS )) {
2003 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
2005 Conf_Server[Server].conn_id = NONE;
2009 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)new_sock)) {
2011 "Cannot allocate memory for server connection (socket %d)",
2014 Conf_Server[Server].conn_id = NONE;
2018 if (!io_event_create( new_sock, IO_WANTWRITE, cb_connserver)) {
2019 Log(LOG_ALERT, "io_event_create(): could not add fd %d",
2022 Conf_Server[Server].conn_id = NONE;
2026 My_Connections = array_start(&My_ConnArray);
2028 assert(My_Connections[new_sock].sock <= 0);
2030 Init_Conn_Struct(new_sock);
2032 ng_ipaddr_tostr_r(dest, ip_str);
2033 c = Client_NewLocal(new_sock, ip_str, CLIENT_UNKNOWNSERVER, false);
2035 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
2037 Conf_Server[Server].conn_id = NONE;
2041 /* Conn_Close() decrements this counter again */
2042 Account_Connection();
2043 Client_SetIntroducer( c, c );
2044 Client_SetToken( c, TOKEN_OUTBOUND );
2046 /* Register connection */
2047 if (!Conf_SetServer(Server, new_sock))
2049 My_Connections[new_sock].sock = new_sock;
2050 My_Connections[new_sock].addr = *dest;
2051 My_Connections[new_sock].client = c;
2052 strlcpy( My_Connections[new_sock].host, Conf_Server[Server].host,
2053 sizeof(My_Connections[new_sock].host ));
2056 if (Conf_Server[Server].SSLConnect &&
2057 !ConnSSL_PrepareConnect(&My_Connections[new_sock], &Conf_Server[Server]))
2059 Log(LOG_ALERT, "Could not initialize SSL for outgoing connection");
2060 Conn_Close(new_sock, "Could not initialize SSL for outgoing connection",
2062 Init_Conn_Struct(new_sock);
2063 Conf_Server[Server].conn_id = NONE;
2067 LogDebug("Registered new connection %d on socket %d (%ld in total).",
2068 new_sock, My_Connections[new_sock].sock, NumConnections);
2069 Conn_OPTION_ADD( &My_Connections[new_sock], CONN_ISCONNECTING );
2073 * Initialize connection structure.
2075 * @param Idx Connection index.
2078 Init_Conn_Struct(CONN_ID Idx)
2080 time_t now = time(NULL);
2082 memset(&My_Connections[Idx], 0, sizeof(CONNECTION));
2083 My_Connections[Idx].sock = -1;
2084 My_Connections[Idx].signon = now;
2085 My_Connections[Idx].lastdata = now;
2086 My_Connections[Idx].lastprivmsg = now;
2087 Proc_InitStruct(&My_Connections[Idx].proc_stat);
2090 My_Connections[Idx].iconv_from = (iconv_t)(-1);
2091 My_Connections[Idx].iconv_to = (iconv_t)(-1);
2093 } /* Init_Conn_Struct */
2096 * Initialize options of a new socket.
2098 * For example, we try to set socket options SO_REUSEADDR and IPTOS_LOWDELAY.
2099 * The socket is automatically closed if a fatal error is encountered.
2101 * @param Sock Socket handle.
2102 * @returns false if socket was closed due to fatal error.
2105 Init_Socket( int Sock )
2109 if (!io_setnonblock(Sock)) {
2110 Log(LOG_CRIT, "Can't enable non-blocking mode for socket: %s!",
2116 /* Don't block this port after socket shutdown */
2118 if (setsockopt(Sock, SOL_SOCKET, SO_REUSEADDR, &value,
2119 (socklen_t)sizeof(value)) != 0) {
2120 Log(LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!",
2122 /* ignore this error */
2125 /* Set type of service (TOS) */
2126 #if defined(IPPROTO_IP) && defined(IPTOS_LOWDELAY)
2127 value = IPTOS_LOWDELAY;
2128 if (setsockopt(Sock, IPPROTO_IP, IP_TOS, &value,
2129 (socklen_t) sizeof(value))) {
2130 LogDebug("Can't set socket option IP_TOS: %s!",
2132 /* ignore this error */
2134 LogDebug("IP_TOS on socket %d has been set to IPTOS_LOWDELAY.",
2142 * Read results of a resolver sub-process and try to initiate a new server
2145 * @param fd File descriptor of the pipe to the sub-process.
2146 * @param events (ignored IO specification)
2149 cb_Connect_to_Server(int fd, UNUSED short events)
2154 /* we can handle at most 3 addresses; but we read up to 4 so we can
2155 * log the 'more than we can handle' condition. First result is tried
2156 * immediately, rest is saved for later if needed. */
2157 ng_ipaddr_t dest_addrs[4];
2159 LogDebug("Resolver: Got forward lookup callback on fd %d, events %d",
2162 for (i=0; i < MAX_SERVERS; i++) {
2163 if (Proc_GetPipeFd(&Conf_Server[i].res_stat) == fd )
2167 if( i >= MAX_SERVERS) {
2168 /* Ops, no matching server found?! */
2170 LogDebug("Resolver: Got Forward Lookup callback for unknown server!?");
2174 /* Read result from pipe */
2175 len = Proc_Read(&Conf_Server[i].res_stat, dest_addrs, sizeof(dest_addrs));
2176 Proc_Close(&Conf_Server[i].res_stat);
2178 /* Error resolving hostname: reset server structure */
2179 Conf_Server[i].conn_id = NONE;
2183 assert((len % sizeof(ng_ipaddr_t)) == 0);
2185 LogDebug("Got result from resolver: %u structs (%u bytes).",
2186 len/sizeof(ng_ipaddr_t), len);
2188 memset(&Conf_Server[i].dst_addr, 0, sizeof(Conf_Server[i].dst_addr));
2189 if (len > sizeof(ng_ipaddr_t)) {
2190 /* more than one address for this hostname, remember them
2191 * in case first address is unreachable/not available */
2192 len -= sizeof(ng_ipaddr_t);
2193 if (len > sizeof(Conf_Server[i].dst_addr)) {
2194 len = sizeof(Conf_Server[i].dst_addr);
2196 "Notice: Resolver returned more IP Addresses for host than we can handle, additional addresses dropped.");
2198 memcpy(&Conf_Server[i].dst_addr, &dest_addrs[1], len);
2201 New_Server(i, dest_addrs);
2202 } /* cb_Read_Forward_Lookup */
2205 * Read results of a resolver sub-process from the pipe and update the
2206 * appropriate connection/client structure(s): hostname and/or IDENT user name.
2208 * @param r_fd File descriptor of the pipe to the sub-process.
2209 * @param events (ignored IO specification)
2212 cb_Read_Resolver_Result( int r_fd, UNUSED short events )
2219 char readbuf[HOST_LEN + 2 + CLIENT_USER_LEN];
2222 char readbuf[HOST_LEN + 1];
2225 LogDebug("Resolver: Got callback on fd %d, events %d", r_fd, events );
2226 i = Conn_GetFromProc(r_fd);
2228 /* Ops, none found? Probably the connection has already
2229 * been closed!? We'll ignore that ... */
2231 LogDebug("Resolver: Got callback for unknown connection!?");
2235 /* Read result from pipe */
2236 len = Proc_Read(&My_Connections[i].proc_stat, readbuf, sizeof readbuf -1);
2237 Proc_Close(&My_Connections[i].proc_stat);
2241 readbuf[len] = '\0';
2242 identptr = strchr(readbuf, '\n');
2243 assert(identptr != NULL);
2245 Log( LOG_CRIT, "Resolver: Got malformed result!");
2250 LogDebug("Got result from resolver: \"%s\" (%u bytes read).", readbuf, len);
2251 /* Okay, we got a complete result: this is a host name for outgoing
2252 * connections and a host name and IDENT user name (if enabled) for
2253 * incoming connections.*/
2254 assert ( My_Connections[i].sock >= 0 );
2255 /* Incoming connection. Search client ... */
2256 c = Conn_GetClient( i );
2257 assert( c != NULL );
2259 /* Only update client information of unregistered clients.
2260 * Note: user commands (e. g. WEBIRC) are always read _after_ reading
2261 * the resolver results, so we don't have to worry to override settings
2262 * from these commands here. */
2263 if(Client_Type(c) == CLIENT_UNKNOWN) {
2264 strlcpy(My_Connections[i].host, readbuf,
2265 sizeof(My_Connections[i].host));
2266 Client_SetHostname(c, readbuf);
2267 if (Conf_NoticeAuth)
2268 (void)Conn_WriteStr(i,
2269 "NOTICE AUTH :*** Found your hostname: %s",
2270 My_Connections[i].host);
2276 if ((*ptr < '0' || *ptr > '9') &&
2277 (*ptr < 'A' || *ptr > 'Z') &&
2278 (*ptr < 'a' || *ptr > 'z'))
2283 /* Erroneous IDENT reply */
2285 "Got invalid IDENT reply for connection %d! Ignored.",
2289 "IDENT lookup for connection %d: \"%s\".",
2291 Client_SetUser(c, identptr, true);
2293 if (Conf_NoticeAuth) {
2294 (void)Conn_WriteStr(i,
2295 "NOTICE AUTH :*** Got %sident response%s%s",
2296 *ptr ? "invalid " : "",
2298 *ptr ? "" : identptr);
2300 } else if(Conf_Ident) {
2301 Log(LOG_INFO, "IDENT lookup for connection %d: no result.", i);
2302 if (Conf_NoticeAuth)
2303 (void)Conn_WriteStr(i,
2304 "NOTICE AUTH :*** No ident response");
2308 if (Conf_NoticeAuth) {
2309 /* Send buffered data to the client, but break on
2310 * errors because Handle_Write() would have closed
2311 * the connection again in this case! */
2312 if (!Handle_Write(i))
2316 Class_HandleServerBans(c);
2320 LogDebug("Resolver: discarding result for already registered connection %d.", i);
2322 } /* cb_Read_Resolver_Result */
2325 * Write a "simple" (error) message to a socket.
2327 * The message is sent without using the connection write buffers, without
2328 * compression/encryption, and even without any error reporting. It is
2329 * designed for error messages of e.g. New_Connection().
2331 * @param Sock Socket handle.
2332 * @param Msg Message string to send.
2335 Simple_Message(int Sock, const char *Msg)
2337 char buf[COMMAND_LEN];
2340 assert(Sock > NONE);
2341 assert(Msg != NULL);
2343 strlcpy(buf, Msg, sizeof buf - 2);
2344 len = strlcat(buf, "\r\n", sizeof buf);
2345 if (write(Sock, buf, len) < 0) {
2346 /* Because this function most probably got called to log
2347 * an error message, any write error is ignored here to
2348 * avoid an endless loop. But casting the result of write()
2349 * to "void" doesn't satisfy the GNU C code attribute
2350 * "warn_unused_result" which is used by some versions of
2351 * glibc (e.g. 2.11.1), therefore this silly error
2352 * "handling" code here :-( */
2355 } /* Simple_Error */
2358 * Get CLIENT structure that belongs to a local connection identified by its
2359 * index number. Each connection belongs to a client by definition, so it is
2360 * not required that the caller checks for NULL return values.
2362 * @param Idx Connection index number.
2363 * @returns Pointer to CLIENT structure.
2366 Conn_GetClient( CONN_ID Idx )
2371 c = array_get(&My_ConnArray, sizeof (CONNECTION), (size_t)Idx);
2373 return c ? c->client : NULL;
2377 * Get PROC_STAT sub-process structure of a connection.
2379 * @param Idx Connection index number.
2380 * @returns PROC_STAT structure.
2383 Conn_GetProcStat(CONN_ID Idx)
2388 c = array_get(&My_ConnArray, sizeof (CONNECTION), (size_t)Idx);
2390 return &c->proc_stat;
2391 } /* Conn_GetProcStat */
2394 * Get CONN_ID from file descriptor associated to a subprocess structure.
2396 * @param fd File descriptor.
2397 * @returns CONN_ID or NONE (-1).
2400 Conn_GetFromProc(int fd)
2405 for (i = 0; i < Pool_Size; i++) {
2406 if ((My_Connections[i].sock != NONE)
2407 && (Proc_GetPipeFd(&My_Connections[i].proc_stat) == fd))
2411 } /* Conn_GetFromProc */
2417 Conn_GetAuthPing(CONN_ID Idx)
2419 assert (Idx != NONE);
2420 return My_Connections[Idx].auth_ping;
2421 } /* Conn_GetAuthPing */
2424 Conn_SetAuthPing(CONN_ID Idx, long ID)
2426 assert (Idx != NONE);
2427 My_Connections[Idx].auth_ping = ID;
2428 } /* Conn_SetAuthPing */
2430 #endif /* STRICT_RFC */
2435 * IO callback for new SSL-enabled client and server connections.
2437 * @param sock Socket descriptor.
2438 * @param what IO specification (IO_WANTREAD/IO_WANTWRITE/...).
2441 cb_clientserver_ssl(int sock, UNUSED short what)
2443 CONN_ID idx = Socket2Index(sock);
2452 switch (ConnSSL_Accept(&My_Connections[idx])) {
2456 return; /* EAGAIN: callback will be invoked again by IO layer */
2459 "SSL accept error, closing socket", "SSL accept error",
2464 io_event_setcb(sock, cb_clientserver); /* SSL handshake completed */
2468 * IO callback for listening SSL sockets: handle new connections. This callback
2469 * gets called when a new SSL-enabled connection should be accepted.
2471 * @param sock Socket descriptor.
2472 * @param irrelevant (ignored IO specification)
2475 cb_listen_ssl(int sock, short irrelevant)
2480 fd = New_Connection(sock, true);
2483 io_event_setcb(My_Connections[fd].sock, cb_clientserver_ssl);
2487 * IO callback for new outgoing SSL-enabled server connections.
2489 * @param sock Socket descriptor.
2490 * @param unused (ignored IO specification)
2493 cb_connserver_login_ssl(int sock, short unused)
2495 CONN_ID idx = Socket2Index(sock);
2503 switch (ConnSSL_Connect( &My_Connections[idx])) {
2505 case 0: LogDebug("ConnSSL_Connect: not ready");
2508 Log(LOG_ERR, "SSL connection on socket %d failed!", sock);
2509 Conn_Close(idx, "Can't connect", NULL, false);
2513 Log( LOG_INFO, "SSL connection %d with \"%s:%d\" established.", idx,
2514 My_Connections[idx].host, Conf_Server[Conf_GetServer( idx )].port );
2521 * Check if SSL library needs to read SSL-protocol related data.
2523 * SSL/TLS connections require extra treatment:
2524 * When either CONN_SSL_WANT_WRITE or CONN_SSL_WANT_READ is set, we
2525 * need to take care of that first, before checking read/write buffers.
2526 * For instance, while we might have data in our write buffer, the
2527 * TLS/SSL protocol might need to read internal data first for TLS/SSL
2528 * writes to succeed.
2530 * If this function returns true, such a condition is met and we have
2531 * to reverse the condition (check for read even if we've data to write,
2532 * do not check for read but writeability even if write-buffer is empty).
2534 * @param c Connection to check.
2535 * @returns true if SSL-library has to read protocol data.
2538 SSL_WantRead(const CONNECTION *c)
2540 if (Conn_OPTION_ISSET(c, CONN_SSL_WANT_READ)) {
2541 io_event_add(c->sock, IO_WANTREAD);
2548 * Check if SSL library needs to write SSL-protocol related data.
2550 * Please see description of SSL_WantRead() for full description!
2552 * @param c Connection to check.
2553 * @returns true if SSL-library has to write protocol data.
2556 SSL_WantWrite(const CONNECTION *c)
2558 if (Conn_OPTION_ISSET(c, CONN_SSL_WANT_WRITE)) {
2559 io_event_add(c->sock, IO_WANTWRITE);
2566 * Get information about used SSL cipher.
2568 * @param Idx Connection index number.
2569 * @param buf Buffer for returned information text.
2570 * @param len Size of return buffer "buf".
2571 * @returns true on success, false otherwise.
2574 Conn_GetCipherInfo(CONN_ID Idx, char *buf, size_t len)
2578 assert(Idx < (int) array_length(&My_ConnArray, sizeof(CONNECTION)));
2579 return ConnSSL_GetCipherInfo(&My_Connections[Idx], buf, len);
2583 * Check if a connection is SSL-enabled or not.
2585 * @param Idx Connection index number.
2586 * @return true if connection is SSL-enabled, false otherwise.
2589 Conn_UsesSSL(CONN_ID Idx)
2593 assert(Idx < (int) array_length(&My_ConnArray, sizeof(CONNECTION)));
2594 return Conn_OPTION_ISSET(&My_Connections[Idx], CONN_SSL);
2598 Conn_GetCertFp(CONN_ID Idx)
2602 assert(Idx < (int) array_length(&My_ConnArray, sizeof(CONNECTION)));
2603 return ConnSSL_GetCertFp(&My_Connections[Idx]);
2607 Conn_SetCertFp(CONN_ID Idx, const char *fingerprint)
2611 assert(Idx < (int) array_length(&My_ConnArray, sizeof(CONNECTION)));
2612 return ConnSSL_SetCertFp(&My_Connections[Idx], fingerprint);
2615 #else /* SSL_SUPPORT */
2618 Conn_UsesSSL(UNUSED CONN_ID Idx)
2624 Conn_GetCertFp(UNUSED CONN_ID Idx)
2630 Conn_SetCertFp(UNUSED CONN_ID Idx, UNUSED const char *fingerprint)
2635 #endif /* SSL_SUPPORT */
2640 * Dump internal state of the "connection module".
2643 Conn_DebugDump(void)
2647 Log(LOG_DEBUG, "Connection status:");
2648 for (i = 0; i < Pool_Size; i++) {
2649 if (My_Connections[i].sock == NONE)
2652 " - %d: host=%s, lastdata=%ld, lastping=%ld, delaytime=%ld, flag=%d, options=%d, bps=%d, client=%s",
2653 My_Connections[i].sock, My_Connections[i].host,
2654 My_Connections[i].lastdata, My_Connections[i].lastping,
2655 My_Connections[i].delaytime, My_Connections[i].flag,
2656 My_Connections[i].options, My_Connections[i].bps,
2657 My_Connections[i].client ? Client_ID(My_Connections[i].client) : "-");
2659 } /* Conn_DumpClients */