2 * ngIRCd -- The Next Generation IRC Daemon
3 * Copyright (c)2001-2012 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.
22 * Connection management
37 #include <sys/socket.h>
39 #include <sys/types.h>
41 #include <netinet/in.h>
43 #ifdef HAVE_NETINET_IP_H
44 # ifdef HAVE_NETINET_IN_SYSTM_H
45 # include <netinet/in_systm.h>
47 # include <netinet/ip.h>
51 # include <stdint.h> /* e.g. for Mac OS X */
55 # include <tcpd.h> /* for TCP Wrappers */
72 #include "conn-func.h"
74 #include "ng_ipaddr.h"
82 #define SERVER_WAIT (NONE - 1)
84 #define MAX_COMMANDS 3
85 #define MAX_COMMANDS_SERVER_MIN 10
86 #define MAX_COMMANDS_SERVICE 10
89 static bool Handle_Write PARAMS(( CONN_ID Idx ));
90 static bool Conn_Write PARAMS(( CONN_ID Idx, char *Data, size_t Len ));
91 static int New_Connection PARAMS(( int Sock ));
92 static CONN_ID Socket2Index PARAMS(( int Sock ));
93 static void Read_Request PARAMS(( CONN_ID Idx ));
94 static unsigned int Handle_Buffer PARAMS(( CONN_ID Idx ));
95 static void Check_Connections PARAMS(( void ));
96 static void Check_Servers PARAMS(( void ));
97 static void Init_Conn_Struct PARAMS(( CONN_ID Idx ));
98 static bool Init_Socket PARAMS(( int Sock ));
99 static void New_Server PARAMS(( int Server, ng_ipaddr_t *dest ));
100 static void Simple_Message PARAMS(( int Sock, const char *Msg ));
101 static int NewListener PARAMS(( const char *listen_addr, UINT16 Port ));
102 static void Account_Connection PARAMS((void));
105 static array My_Listeners;
106 static array My_ConnArray;
107 static size_t NumConnections, NumConnectionsMax, NumConnectionsAccepted;
110 int allow_severity = LOG_INFO;
111 int deny_severity = LOG_ERR;
114 static void server_login PARAMS((CONN_ID idx));
117 extern struct SSLOptions Conf_SSLOptions;
118 static void cb_connserver_login_ssl PARAMS((int sock, short what));
119 static void cb_clientserver_ssl PARAMS((int sock, short what));
121 static void cb_Read_Resolver_Result PARAMS((int sock, UNUSED short what));
122 static void cb_Connect_to_Server PARAMS((int sock, UNUSED short what));
123 static void cb_clientserver PARAMS((int sock, short what));
127 * IO callback for listening sockets: handle new connections. This callback
128 * gets called when a new non-SSL connection should be accepted.
130 * @param sock Socket descriptor.
131 * @param irrelevant (ignored IO specification)
134 cb_listen(int sock, short irrelevant)
137 (void) New_Connection(sock);
143 * IO callback for listening SSL sockets: handle new connections. This callback
144 * gets called when a new SSL-enabled connection should be accepted.
146 * @param sock Socket descriptor.
147 * @param irrelevant (ignored IO specification)
150 cb_listen_ssl(int sock, short irrelevant)
155 fd = New_Connection(sock);
158 io_event_setcb(My_Connections[fd].sock, cb_clientserver_ssl);
164 * IO callback for new outgoing non-SSL server connections.
166 * @param sock Socket descriptor.
167 * @param what IO specification (IO_WANTREAD/IO_WANTWRITE/...).
170 cb_connserver(int sock, UNUSED short what)
172 int res, err, server;
174 CONN_ID idx = Socket2Index( sock );
177 LogDebug("cb_connserver wants to write on unknown socket?!");
182 assert(what & IO_WANTWRITE);
184 /* Make sure that the server is still configured; it could have been
185 * removed in the meantime! */
186 server = Conf_GetServer(idx);
188 Log(LOG_ERR, "Connection on socket %d to \"%s\" aborted!",
189 sock, My_Connections[idx].host);
190 Conn_Close(idx, "Connection aborted!", NULL, false);
194 /* connect() finished, get result. */
195 sock_len = (socklen_t)sizeof(err);
196 res = getsockopt(My_Connections[idx].sock, SOL_SOCKET, SO_ERROR,
198 assert(sock_len == sizeof(err));
200 /* Error while connecting? */
201 if ((res != 0) || (err != 0)) {
203 Log(LOG_CRIT, "getsockopt (connection %d): %s!",
204 idx, strerror(errno));
207 "Can't connect socket to \"%s:%d\" (connection %d): %s!",
208 My_Connections[idx].host, Conf_Server[server].port,
211 Conn_Close(idx, "Can't connect!", NULL, false);
213 if (ng_ipaddr_af(&Conf_Server[server].dst_addr[0])) {
214 /* more addresses to try... */
215 New_Server(server, &Conf_Server[server].dst_addr[0]);
216 /* connection to dst_addr[0] is now in progress, so
217 * remove this address... */
218 Conf_Server[server].dst_addr[0] =
219 Conf_Server[server].dst_addr[1];
220 memset(&Conf_Server[server].dst_addr[1], 0,
221 sizeof(Conf_Server[server].dst_addr[1]));
226 /* connect() succeeded, remove all additional addresses */
227 memset(&Conf_Server[server].dst_addr, 0,
228 sizeof(Conf_Server[server].dst_addr));
230 Conn_OPTION_DEL( &My_Connections[idx], CONN_ISCONNECTING );
232 if ( Conn_OPTION_ISSET( &My_Connections[idx], CONN_SSL_CONNECT )) {
233 io_event_setcb( sock, cb_connserver_login_ssl );
234 io_event_add( sock, IO_WANTWRITE|IO_WANTREAD );
243 * Login to a remote server.
245 * @param idx Connection index.
248 server_login(CONN_ID idx)
251 "Connection %d (socket %d) with \"%s:%d\" established. Now logging in ...",
252 idx, My_Connections[idx].sock, My_Connections[idx].host,
253 Conf_Server[Conf_GetServer(idx)].port);
255 io_event_setcb( My_Connections[idx].sock, cb_clientserver);
256 io_event_add( My_Connections[idx].sock, IO_WANTREAD|IO_WANTWRITE);
258 /* Send PASS and SERVER command to peer */
259 Conn_WriteStr( idx, "PASS %s %s", Conf_Server[Conf_GetServer( idx )].pwd_out, NGIRCd_ProtoID );
260 Conn_WriteStr( idx, "SERVER %s :%s", Conf_ServerName, Conf_ServerInfo );
266 * IO callback for new outgoing SSL-enabled server connections.
268 * @param sock Socket descriptor.
269 * @param unused (ignored IO specification)
272 cb_connserver_login_ssl(int sock, short unused)
274 CONN_ID idx = Socket2Index(sock);
282 switch (ConnSSL_Connect( &My_Connections[idx])) {
284 case 0: LogDebug("ConnSSL_Connect: not ready");
287 Log(LOG_ERR, "SSL connection on socket %d failed!", sock);
288 Conn_Close(idx, "Can't connect!", NULL, false);
292 Log( LOG_INFO, "SSL connection %d with \"%s:%d\" established.", idx,
293 My_Connections[idx].host, Conf_Server[Conf_GetServer( idx )].port );
301 * IO callback for established non-SSL client and server connections.
303 * @param sock Socket descriptor.
304 * @param what IO specification (IO_WANTREAD/IO_WANTWRITE/...).
307 cb_clientserver(int sock, short what)
309 CONN_ID idx = Socket2Index(sock);
318 if (what & IO_WANTREAD
319 || (Conn_OPTION_ISSET(&My_Connections[idx], CONN_SSL_WANT_WRITE))) {
320 /* if TLS layer needs to write additional data, call
321 * Read_Request() instead so that SSL/TLS can continue */
325 if (what & IO_WANTREAD)
328 if (what & IO_WANTWRITE)
335 * IO callback for established SSL-enabled client and server connections.
337 * @param sock Socket descriptor.
338 * @param what IO specification (IO_WANTREAD/IO_WANTWRITE/...).
341 cb_clientserver_ssl(int sock, short what)
343 CONN_ID idx = Socket2Index(sock);
352 switch (ConnSSL_Accept(&My_Connections[idx])) {
356 return; /* EAGAIN: callback will be invoked again by IO layer */
358 Conn_Close(idx, "SSL accept error, closing socket", "SSL accept error", false);
361 if (what & IO_WANTREAD)
364 if (what & IO_WANTWRITE)
367 io_event_setcb(sock, cb_clientserver); /* SSL handshake completed */
373 * Initialize connecion module.
380 /* Speicher fuer Verbindungs-Pool anfordern */
381 Pool_Size = CONNECTION_POOL;
382 if ((Conf_MaxConnections > 0) &&
383 (Pool_Size > Conf_MaxConnections))
384 Pool_Size = Conf_MaxConnections;
386 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)Pool_Size)) {
387 Log(LOG_EMERG, "Can't allocate memory! [Conn_Init]");
391 /* FIXME: My_Connetions/Pool_Size is needed by other parts of the
392 * code; remove them! */
393 My_Connections = (CONNECTION*) array_start(&My_ConnArray);
395 LogDebug("Allocated connection pool for %d items (%ld bytes).",
396 array_length(&My_ConnArray, sizeof(CONNECTION)),
397 array_bytes(&My_ConnArray));
399 assert(array_length(&My_ConnArray, sizeof(CONNECTION)) >= (size_t)Pool_Size);
401 array_free( &My_Listeners );
403 for (i = 0; i < Pool_Size; i++)
409 * Clean up connection module.
416 Conn_ExitListeners();
418 LogDebug("Shutting down all connections ..." );
419 for( idx = 0; idx < Pool_Size; idx++ ) {
420 if( My_Connections[idx].sock > NONE ) {
421 Conn_Close( idx, NULL, NGIRCd_SignalRestart ?
422 "Server going down (restarting)":"Server going down", true );
426 array_free(&My_ConnArray);
427 My_Connections = NULL;
429 io_library_shutdown();
434 * Close all sockets (file descriptors) of open connections.
435 * This is useful in forked child processes, for example, to make sure that
436 * they don't hold connections open that the main process wants to close.
439 Conn_CloseAllSockets(int ExceptOf)
443 for(idx = 0; idx < Pool_Size; idx++) {
444 if(My_Connections[idx].sock > NONE &&
445 My_Connections[idx].sock != ExceptOf)
446 close(My_Connections[idx].sock);
452 * Initialize listening ports.
454 * @param a Array containing the ports the daemon should listen on.
455 * @param listen_addr Address the socket should listen on (can be "0.0.0.0").
456 * @param func IO callback function to register.
457 * @returns Number of listening sockets created.
460 ports_initlisteners(array *a, const char *listen_addr, void (*func)(int,short))
462 unsigned int created = 0;
467 len = array_length(a, sizeof (UINT16));
468 port = array_start(a);
470 fd = NewListener(listen_addr, *port);
475 if (!io_event_create( fd, IO_WANTREAD, func )) {
476 Log( LOG_ERR, "io_event_create(): Could not add listening fd %d (port %u): %s!",
477 fd, (unsigned int) *port, strerror(errno));
490 * Initialize all listening sockets.
492 * @returns Number of created listening sockets
495 Conn_InitListeners( void )
497 /* Initialize ports on which the server should accept connections */
498 unsigned int created = 0;
499 char *copy, *listen_addr;
501 assert(Conf_ListenAddress);
503 /* can't use Conf_ListenAddress directly, see below */
504 copy = strdup(Conf_ListenAddress);
506 Log(LOG_CRIT, "Cannot copy %s: %s", Conf_ListenAddress, strerror(errno));
509 listen_addr = strtok(copy, ",");
511 while (listen_addr) {
512 ngt_TrimStr(listen_addr);
514 created += ports_initlisteners(&Conf_ListenPorts, listen_addr, cb_listen);
516 created += ports_initlisteners(&Conf_SSLOptions.ListenPorts, listen_addr, cb_listen_ssl);
520 listen_addr = strtok(NULL, ",");
523 /* Can't free() Conf_ListenAddress here: on REHASH, if the config file
524 * cannot be re-loaded, we'd end up with a NULL Conf_ListenAddress.
525 * Instead, free() takes place in conf.c, before the config file
526 * is being parsed. */
530 } /* Conn_InitListeners */
534 * Shut down all listening sockets.
537 Conn_ExitListeners( void )
539 /* Close down all listening sockets */
543 arraylen = array_length(&My_Listeners, sizeof (int));
545 "Shutting down all listening sockets (%d total) ...", arraylen);
546 fd = array_start(&My_Listeners);
551 LogDebug("Listening socket %d closed.", *fd );
554 array_free(&My_Listeners);
555 } /* Conn_ExitListeners */
559 * Bind a socket to a specific (source) address.
561 * @param addr Address structure.
562 * @param listen_addrstr Source address as string.
563 * @param Port Port number.
564 * @returns true on success, false otherwise.
567 InitSinaddrListenAddr(ng_ipaddr_t *addr, const char *listen_addrstr, UINT16 Port)
571 ret = ng_ipaddr_init(addr, listen_addrstr, Port);
573 assert(listen_addrstr);
574 Log(LOG_CRIT, "Can't bind to [%s]:%u: can't convert ip address \"%s\"",
575 listen_addrstr, Port, listen_addrstr);
582 * Set a socket to "IPv6 only". If the given socket doesn't belong to the
583 * AF_INET6 family, or the operating system doesn't support this functionality,
584 * this function retruns silently.
586 * @param af Address family of the socket.
587 * @param sock Socket handle.
590 set_v6_only(int af, int sock)
592 #if defined(IPV6_V6ONLY) && defined(WANT_IPV6)
598 if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, (socklen_t)sizeof(on)))
599 Log(LOG_ERR, "Could not set IPV6_V6ONLY: %s", strerror(errno));
608 * Initialize new listening port.
610 * @param listen_addr Local address to bind the socet to (can be 0.0.0.0).
611 * @param Port Port number on which the new socket should be listening.
612 * @returns file descriptor of the socket or -1 on failure.
615 NewListener(const char *listen_addr, UINT16 Port)
617 /* Create new listening socket on specified port */
621 if (!InitSinaddrListenAddr(&addr, listen_addr, Port))
624 af = ng_ipaddr_af(&addr);
625 sock = socket(af, SOCK_STREAM, 0);
627 Log(LOG_CRIT, "Can't create socket (af %d) : %s!", af, strerror(errno));
631 set_v6_only(af, sock);
633 if (!Init_Socket(sock))
636 if (bind(sock, (struct sockaddr *)&addr, ng_ipaddr_salen(&addr)) != 0) {
637 Log(LOG_CRIT, "Can't bind socket to address %s:%d - %s",
638 ng_ipaddr_tostr(&addr), Port, strerror(errno));
643 if( listen( sock, 10 ) != 0 ) {
644 Log( LOG_CRIT, "Can't listen on socket: %s!", strerror( errno ));
649 /* keep fd in list so we can close it when ngircd restarts/shuts down */
650 if (!array_catb( &My_Listeners,(char*) &sock, sizeof(int) )) {
651 Log( LOG_CRIT, "Can't add socket to My_Listeners array: %s!", strerror( errno ));
656 Log(LOG_INFO, "Now listening on [%s]:%d (socket %d).",
657 ng_ipaddr_tostr(&addr), Port, sock);
665 * Check if SSL library needs to read SSL-protocol related data.
667 * SSL/TLS connections require extra treatment:
668 * When either CONN_SSL_WANT_WRITE or CONN_SSL_WANT_READ is set, we
669 * need to take care of that first, before checking read/write buffers.
670 * For instance, while we might have data in our write buffer, the
671 * TLS/SSL protocol might need to read internal data first for TLS/SSL
674 * If this function returns true, such a condition is met and we have
675 * to reverse the condition (check for read even if we've data to write,
676 * do not check for read but writeability even if write-buffer is empty).
678 * @param c Connection to check.
679 * @returns true if SSL-library has to read protocol data.
682 SSL_WantRead(const CONNECTION *c)
684 if (Conn_OPTION_ISSET(c, CONN_SSL_WANT_READ)) {
685 io_event_add(c->sock, IO_WANTREAD);
692 * Check if SSL library needs to write SSL-protocol related data.
694 * Please see description of SSL_WantRead() for full description!
696 * @param c Connection to check.
697 * @returns true if SSL-library has to write protocol data.
700 SSL_WantWrite(const CONNECTION *c)
702 if (Conn_OPTION_ISSET(c, CONN_SSL_WANT_WRITE)) {
703 io_event_add(c->sock, IO_WANTWRITE);
712 SSL_WantRead(UNUSED const CONNECTION *c)
716 SSL_WantWrite(UNUSED const CONNECTION *c)
723 * "Main Loop": Loop until shutdown or restart is signalled.
725 * This function loops until a shutdown or restart of ngIRCd is signalled and
726 * calls io_dispatch() to check for readable and writable sockets every second.
727 * It checks for status changes on pending connections (e. g. when a hostname
728 * has been resolved), checks for "penalties" and timeouts, and handles the
735 unsigned int wdatalen, bytes_processed;
739 while (!NGIRCd_SignalQuit && !NGIRCd_SignalRestart) {
742 /* Check configured servers and established links */
746 /* Expire outdated class/list items */
749 /* Look for non-empty read buffers ... */
750 for (i = 0; i < Pool_Size; i++) {
751 if ((My_Connections[i].sock > NONE)
752 && (array_bytes(&My_Connections[i].rbuf) > 0)
753 && (My_Connections[i].delaytime <= t)) {
754 /* ... and try to handle the received data */
755 bytes_processed = Handle_Buffer(i);
756 /* if we processed data, and there might be
757 * more commands in the input buffer, do not
758 * try to read any more data now */
759 if (bytes_processed &&
760 array_bytes(&My_Connections[i].rbuf) > 2) {
762 ("Throttling connection %d: command limit reached!",
764 Conn_SetPenalty(i, 1);
769 /* Look for non-empty write buffers ... */
770 for (i = 0; i < Pool_Size; i++) {
771 if (My_Connections[i].sock <= NONE)
774 wdatalen = (unsigned int)array_bytes(&My_Connections[i].wbuf);
777 array_bytes(&My_Connections[i].zip.wbuf) > 0)
782 if (SSL_WantRead(&My_Connections[i]))
784 io_event_add(My_Connections[i].sock,
789 /* Check from which sockets we possibly could read ... */
790 for (i = 0; i < Pool_Size; i++) {
791 if (My_Connections[i].sock <= NONE)
794 if (SSL_WantWrite(&My_Connections[i]))
795 continue; /* TLS/SSL layer needs to write data; deal with this first */
797 if (Proc_InProgress(&My_Connections[i].proc_stat)) {
798 /* Wait for completion of forked subprocess
799 * and ignore the socket in the meantime ... */
800 io_event_del(My_Connections[i].sock,
805 if (Conn_OPTION_ISSET(&My_Connections[i], CONN_ISCONNECTING))
806 /* Wait for completion of connect() ... */
809 if (My_Connections[i].delaytime > t) {
810 /* There is a "penalty time" set: ignore socket! */
811 io_event_del(My_Connections[i].sock,
816 io_event_add(My_Connections[i].sock, IO_WANTREAD);
819 /* Set the timeout for reading from the network to 1 second,
820 * which is the granularity with witch we handle "penalty
821 * times" for example.
822 * Note: tv_sec/usec are undefined(!) after io_dispatch()
823 * returns, so we have to set it beforce each call to it! */
827 /* Wait for activity ... */
828 i = io_dispatch(&tv);
829 if (i == -1 && errno != EINTR) {
830 Log(LOG_EMERG, "Conn_Handler(): io_dispatch(): %s!",
832 Log(LOG_ALERT, "%s exiting due to fatal errors!",
838 if (NGIRCd_SignalQuit)
839 Log(LOG_NOTICE | LOG_snotice, "Server going down NOW!");
840 else if (NGIRCd_SignalRestart)
841 Log(LOG_NOTICE | LOG_snotice, "Server restarting NOW!");
846 * Write a text string into the socket of a connection.
848 * This function automatically appends CR+LF to the string and validates that
849 * the result is a valid IRC message (oversized messages are shortened, for
850 * example). Then it calls the Conn_Write() function to do the actual sending.
852 * @param Idx Index fo the connection.
853 * @param Format Format string, see printf().
854 * @returns true on success, false otherwise.
858 Conn_WriteStr(CONN_ID Idx, const char *Format, ...)
861 Conn_WriteStr(Idx, Format, va_alist)
867 char buffer[COMMAND_LEN];
872 assert( Idx > NONE );
873 assert( Format != NULL );
876 va_start( ap, Format );
880 if (vsnprintf( buffer, COMMAND_LEN - 2, Format, ap ) >= COMMAND_LEN - 2 ) {
882 * The string that should be written to the socket is longer
883 * than the allowed size of COMMAND_LEN bytes (including both
884 * the CR and LF characters). This can be caused by the
885 * IRC_WriteXXX() functions when the prefix of this server had
886 * to be added to an already "quite long" command line which
887 * has been received from a regular IRC client, for example.
889 * We are not allowed to send such "oversized" messages to
890 * other servers and clients, see RFC 2812 2.3 and 2813 3.3
891 * ("these messages SHALL NOT exceed 512 characters in length,
892 * counting all characters including the trailing CR-LF").
894 * So we have a big problem here: we should send more bytes
895 * to the network than we are allowed to and we don't know
896 * the originator (any more). The "old" behaviour of blaming
897 * the receiver ("next hop") is a bad idea (it could be just
898 * an other server only routing the message!), so the only
899 * option left is to shorten the string and to hope that the
900 * result is still somewhat useful ...
904 strcpy (buffer + sizeof(buffer) - strlen(CUT_TXTSUFFIX) - 2 - 1,
910 Log(LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer);
913 len = strlcat( buffer, "\r\n", sizeof( buffer ));
914 ok = Conn_Write(Idx, buffer, len);
915 My_Connections[Idx].msg_out++;
919 } /* Conn_WriteStr */
922 Conn_Password( CONN_ID Idx )
924 assert( Idx > NONE );
925 if (My_Connections[Idx].pwd == NULL)
928 return My_Connections[Idx].pwd;
929 } /* Conn_Password */
932 Conn_SetPassword( CONN_ID Idx, const char *Pwd )
934 assert( Idx > NONE );
936 if (My_Connections[Idx].pwd)
937 free(My_Connections[Idx].pwd);
939 My_Connections[Idx].pwd = strdup(Pwd);
940 if (My_Connections[Idx].pwd == NULL) {
941 Log(LOG_EMERG, "Can't allocate memory! [Conn_SetPassword]");
944 } /* Conn_SetPassword */
947 * Append Data to the outbound write buffer of a connection.
949 * @param Idx Index of the connection.
950 * @param Data pointer to the data.
951 * @param Len length of Data.
952 * @returns true on success, false otherwise.
955 Conn_Write( CONN_ID Idx, char *Data, size_t Len )
958 size_t writebuf_limit = WRITEBUFFER_MAX_LEN;
959 assert( Idx > NONE );
960 assert( Data != NULL );
963 /* Is the socket still open? A previous call to Conn_Write()
964 * may have closed the connection due to a fatal error.
965 * In this case it is sufficient to return an error, as well. */
966 if (My_Connections[Idx].sock <= NONE) {
967 LogDebug("Skipped write on closed socket (connection %d).", Idx);
971 /* Make sure that there still exists a CLIENT structure associated
972 * with this connection and check if this is a server or not: */
973 c = Conn_GetClient(Idx);
975 /* Servers do get special write buffer limits, so they can
976 * generate all the messages that are required while peering. */
977 if (Client_Type(c) == CLIENT_SERVER)
978 writebuf_limit = WRITEBUFFER_SLINK_LEN;
980 LogDebug("Write on socket without client (connection %d)!?", Idx);
983 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
985 * Zip_Buffer() does all the dirty work for us: it flushes
986 * the (pre-)compression buffers if required and handles
987 * all error conditions. */
988 if (!Zip_Buffer(Idx, Data, Len))
994 /* Uncompressed link:
995 * Check if outbound buffer has enough space for the data. */
996 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
997 WRITEBUFFER_FLUSH_LEN) {
998 /* Buffer is full, flush it. Handle_Write deals with
999 * low-level errors, if any. */
1000 if (!Handle_Write(Idx))
1004 /* When the write buffer is still too big after flushing it,
1005 * the connection will be killed. */
1006 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
1009 "Write buffer space exhausted (connection %d, limit is %lu bytes, %lu bytes new, %lu bytes pending)",
1010 Idx, writebuf_limit, Len,
1011 (unsigned long)array_bytes(&My_Connections[Idx].wbuf));
1012 Conn_Close(Idx, "Write buffer space exhausted", NULL, false);
1016 /* Copy data to write buffer */
1017 if (!array_catb(&My_Connections[Idx].wbuf, Data, Len))
1020 My_Connections[Idx].bytes_out += Len;
1023 /* Adjust global write counter */
1031 * Shut down a connection.
1033 * @param Idx Connection index.
1034 * @param LogMsg Message to write to the log or NULL. If no LogMsg
1035 * is given, the FwdMsg is logged.
1036 * @param FwdMsg Message to forward to remote servers.
1037 * @param InformClient If true, inform the client on the connection which is
1038 * to be shut down of the reason (FwdMsg) and send
1039 * connection statistics before disconnecting it.
1042 Conn_Close( CONN_ID Idx, const char *LogMsg, const char *FwdMsg, bool InformClient )
1044 /* Close connection. Open pipes of asynchronous resolver
1045 * sub-processes are closed down. */
1051 double in_z_k, out_z_k;
1055 assert( Idx > NONE );
1057 /* Is this link already shutting down? */
1058 if( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ISCLOSING )) {
1059 /* Conn_Close() has been called recursively for this link;
1060 * probabe reason: Handle_Write() failed -- see below. */
1061 LogDebug("Recursive request to close connection: %d", Idx );
1065 assert( My_Connections[Idx].sock > NONE );
1067 /* Mark link as "closing" */
1068 Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCLOSING );
1070 port = ng_ipaddr_getport(&My_Connections[Idx].addr);
1071 Log(LOG_INFO, "Shutting down connection %d (%s) with %s:%d ...", Idx,
1072 LogMsg ? LogMsg : FwdMsg, My_Connections[Idx].host, port);
1074 /* Search client, if any */
1075 c = Conn_GetClient( Idx );
1077 /* Should the client be informed? */
1080 /* Send statistics to client if registered as user: */
1081 if ((c != NULL) && (Client_Type(c) == CLIENT_USER)) {
1083 ":%s NOTICE %s :%sConnection statistics: client %.1f kb, server %.1f kb.",
1084 Client_ID(Client_ThisServer()), Client_ID(c),
1086 (double)My_Connections[Idx].bytes_in / 1024,
1087 (double)My_Connections[Idx].bytes_out / 1024);
1090 /* Send ERROR to client (see RFC 2812, section 3.1.7) */
1092 Conn_WriteStr(Idx, "ERROR :%s", FwdMsg);
1094 Conn_WriteStr(Idx, "ERROR :Closing connection");
1097 /* Try to write out the write buffer. Note: Handle_Write() eventually
1098 * removes the CLIENT structure associated with this connection if an
1099 * error occurs! So we have to re-check if there is still an valid
1100 * CLIENT structure after calling Handle_Write() ...*/
1101 (void)Handle_Write( Idx );
1103 /* Search client, if any (re-check!) */
1104 c = Conn_GetClient( Idx );
1106 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_SSL )) {
1107 Log(LOG_INFO, "SSL connection %d shutting down ...", Idx);
1108 ConnSSL_Free(&My_Connections[Idx]);
1111 /* Shut down socket */
1112 if (! io_close(My_Connections[Idx].sock)) {
1113 /* Oops, we can't close the socket!? This is ... ugly! */
1115 "Error closing connection %d (socket %d) with %s:%d - %s! (ignored)",
1116 Idx, My_Connections[Idx].sock, My_Connections[Idx].host,
1117 port, strerror(errno));
1120 /* Mark socket as invalid: */
1121 My_Connections[Idx].sock = NONE;
1123 /* If there is still a client, unregister it now */
1125 Client_Destroy(c, LogMsg, FwdMsg, true);
1127 /* Calculate statistics and log information */
1128 in_k = (double)My_Connections[Idx].bytes_in / 1024;
1129 out_k = (double)My_Connections[Idx].bytes_out / 1024;
1131 if (Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP)) {
1132 in_z_k = (double)My_Connections[Idx].zip.bytes_in / 1024;
1133 out_z_k = (double)My_Connections[Idx].zip.bytes_out / 1024;
1134 /* Make sure that no division by zero can occur during
1135 * the calculation of in_p and out_p: in_z_k and out_z_k
1136 * are non-zero, that's guaranteed by the protocol until
1137 * compression can be enabled. */
1142 in_p = (int)(( in_k * 100 ) / in_z_k );
1143 out_p = (int)(( out_k * 100 ) / out_z_k );
1145 "Connection %d with %s:%d closed (in: %.1fk/%.1fk/%d%%, out: %.1fk/%.1fk/%d%%).",
1146 Idx, My_Connections[Idx].host, port,
1147 in_k, in_z_k, in_p, out_k, out_z_k, out_p);
1153 "Connection %d with %s:%d closed (in: %.1fk, out: %.1fk).",
1154 Idx, My_Connections[Idx].host, port,
1158 /* Servers: Modify time of next connect attempt? */
1159 Conf_UnsetServer( Idx );
1162 /* Clean up zlib, if link was compressed */
1163 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
1164 inflateEnd( &My_Connections[Idx].zip.in );
1165 deflateEnd( &My_Connections[Idx].zip.out );
1166 array_free(&My_Connections[Idx].zip.rbuf);
1167 array_free(&My_Connections[Idx].zip.wbuf);
1171 array_free(&My_Connections[Idx].rbuf);
1172 array_free(&My_Connections[Idx].wbuf);
1173 if (My_Connections[Idx].pwd != NULL)
1174 free(My_Connections[Idx].pwd);
1176 /* Clean up connection structure (=free it) */
1177 Init_Conn_Struct( Idx );
1179 assert(NumConnections > 0);
1182 LogDebug("Shutdown of connection %d completed, %ld connection%s left.",
1183 Idx, NumConnections, NumConnections != 1 ? "s" : "");
1188 * Get current number of connections.
1190 * @returns Number of current connections.
1195 return NumConnections;
1200 * Get number of maximum simultaneous connections.
1202 * @returns Number of maximum simultaneous connections.
1207 return NumConnectionsMax;
1208 } /* Conn_CountMax */
1212 * Get number of connections accepted since the daemon startet.
1214 * @returns Number of connections accepted.
1217 Conn_CountAccepted(void)
1219 return NumConnectionsAccepted;
1220 } /* Conn_CountAccepted */
1224 * Synchronize established connections and configured server structures
1225 * after a configuration update and store the correct connection IDs, if any.
1228 Conn_SyncServerStruct(void)
1234 for (i = 0; i < Pool_Size; i++) {
1235 if (My_Connections[i].sock == NONE)
1239 client = Conn_GetClient(i);
1240 if (!client || Client_Type(client) != CLIENT_SERVER)
1243 for (c = 0; c < MAX_SERVERS; c++) {
1244 /* Configured server? */
1245 if (!Conf_Server[c].host[0])
1248 if (strcasecmp(Conf_Server[c].name, Client_ID(client)) == 0)
1249 Conf_Server[c].conn_id = i;
1252 } /* 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);
1270 * Send out data of write buffer; connect new sockets.
1272 * @param Idx Connection index.
1273 * @returns true on success, false otherwise.
1276 Handle_Write( CONN_ID Idx )
1281 assert( Idx > NONE );
1282 if ( My_Connections[Idx].sock < 0 ) {
1283 LogDebug("Handle_Write() on closed socket, connection %d", Idx);
1286 assert( My_Connections[Idx].sock > NONE );
1288 wdatalen = array_bytes(&My_Connections[Idx].wbuf );
1291 if (wdatalen == 0) {
1292 /* Write buffer is empty, so we try to flush the compression
1293 * buffer and get some data to work with from there :-) */
1294 if (!Zip_Flush(Idx))
1297 /* Now the write buffer most probably has changed: */
1298 wdatalen = array_bytes(&My_Connections[Idx].wbuf);
1302 if (wdatalen == 0) {
1303 /* Still no data, fine. */
1304 io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
1310 ("Handle_Write() called for connection %d, %ld bytes pending ...",
1315 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_SSL )) {
1316 len = ConnSSL_Write(&My_Connections[Idx], array_start(&My_Connections[Idx].wbuf), wdatalen);
1320 len = write(My_Connections[Idx].sock,
1321 array_start(&My_Connections[Idx].wbuf), wdatalen );
1324 if (errno == EAGAIN || errno == EINTR)
1327 Log(LOG_ERR, "Write error on connection %d (socket %d): %s!",
1328 Idx, My_Connections[Idx].sock, strerror(errno));
1329 Conn_Close(Idx, "Write error!", NULL, false);
1333 /* move any data not yet written to beginning */
1334 array_moveleft(&My_Connections[Idx].wbuf, 1, (size_t)len);
1337 } /* Handle_Write */
1341 * Count established connections to a specific IP address.
1343 * @returns Number of established connections.
1346 Count_Connections(ng_ipaddr_t *a)
1351 for (i = 0; i < Pool_Size; i++) {
1352 if (My_Connections[i].sock <= NONE)
1354 if (ng_ipaddr_ipequal(&My_Connections[i].addr, a))
1358 } /* Count_Connections */
1362 * Initialize new client connection on a listening socket.
1364 * @param Sock Listening socket descriptor.
1365 * @returns Accepted socket descriptor or -1 on error.
1368 New_Connection(int Sock)
1371 struct request_info req;
1373 ng_ipaddr_t new_addr;
1374 char ip_str[NG_INET_ADDRSTRLEN];
1375 int new_sock, new_sock_len, identsock;
1379 assert(Sock > NONE);
1381 LogDebug("Accepting new connection on socket %d ...", Sock);
1383 new_sock_len = (int)sizeof(new_addr);
1384 new_sock = accept(Sock, (struct sockaddr *)&new_addr,
1385 (socklen_t *)&new_sock_len);
1387 Log(LOG_CRIT, "Can't accept connection: %s!", strerror(errno));
1390 NumConnectionsAccepted++;
1392 if (!ng_ipaddr_tostr_r(&new_addr, ip_str)) {
1393 Log(LOG_CRIT, "fd %d: Can't convert IP address!", new_sock);
1394 Simple_Message(new_sock, "ERROR :Internal Server Error");
1400 /* Validate socket using TCP Wrappers */
1401 request_init(&req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock,
1402 RQ_CLIENT_SIN, &new_addr, NULL);
1404 if (!hosts_access(&req)) {
1406 "Refused connection from %s (by TCP Wrappers)!", ip_str);
1407 Simple_Message(new_sock, "ERROR :Connection refused");
1413 if (!Init_Socket(new_sock))
1416 /* Check global connection limit */
1417 if ((Conf_MaxConnections > 0) &&
1418 (NumConnections >= (size_t) Conf_MaxConnections)) {
1419 Log(LOG_ALERT, "Can't accept connection: limit (%d) reached!",
1420 Conf_MaxConnections);
1421 Simple_Message(new_sock, "ERROR :Connection limit reached");
1426 /* Check IP-based connection limit */
1427 cnt = Count_Connections(&new_addr);
1428 if ((Conf_MaxConnectionsIP > 0) && (cnt >= Conf_MaxConnectionsIP)) {
1429 /* Access denied, too many connections from this IP address! */
1431 "Refused connection from %s: too may connections (%ld) from this IP address!",
1433 Simple_Message(new_sock,
1434 "ERROR :Connection refused, too many connections from your IP address");
1439 if (new_sock >= Pool_Size) {
1440 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION),
1441 (size_t) new_sock)) {
1443 "Can't allocate memory! [New_Connection]");
1444 Simple_Message(new_sock, "ERROR: Internal error");
1448 LogDebug("Bumped connection pool to %ld items (internal: %ld items, %ld bytes)",
1449 new_sock, array_length(&My_ConnArray,
1450 sizeof(CONNECTION)), array_bytes(&My_ConnArray));
1452 /* Adjust pointer to new block */
1453 My_Connections = array_start(&My_ConnArray);
1454 while (Pool_Size <= new_sock)
1455 Init_Conn_Struct(Pool_Size++);
1458 /* register callback */
1459 if (!io_event_create(new_sock, IO_WANTREAD, cb_clientserver)) {
1461 "Can't accept connection: io_event_create failed!");
1462 Simple_Message(new_sock, "ERROR :Internal error");
1467 c = Client_NewLocal(new_sock, NULL, CLIENT_UNKNOWN, false);
1470 "Can't accept connection: can't create client structure!");
1471 Simple_Message(new_sock, "ERROR :Internal error");
1476 Init_Conn_Struct(new_sock);
1477 My_Connections[new_sock].sock = new_sock;
1478 My_Connections[new_sock].addr = new_addr;
1479 My_Connections[new_sock].client = c;
1481 /* Set initial hostname to IP address. This becomes overwritten when
1482 * the DNS lookup is enabled and succeeds, but is used otherwise. */
1483 if (ng_ipaddr_af(&new_addr) != AF_INET)
1484 snprintf(My_Connections[new_sock].host,
1485 sizeof(My_Connections[new_sock].host), "[%s]", ip_str);
1487 strlcpy(My_Connections[new_sock].host, ip_str,
1488 sizeof(My_Connections[new_sock].host));
1490 Client_SetHostname(c, My_Connections[new_sock].host);
1492 Log(LOG_INFO, "Accepted connection %d from %s:%d on socket %d.",
1493 new_sock, My_Connections[new_sock].host,
1494 ng_ipaddr_getport(&new_addr), Sock);
1496 identsock = new_sock;
1502 if (Conf_NoticeAuth) {
1505 (void)Conn_WriteStr(new_sock,
1506 "NOTICE AUTH :*** Looking up your hostname and checking ident");
1509 (void)Conn_WriteStr(new_sock,
1510 "NOTICE AUTH :*** Looking up your hostname");
1511 (void)Handle_Write(new_sock);
1513 Resolve_Addr(&My_Connections[new_sock].proc_stat, &new_addr,
1514 identsock, cb_Read_Resolver_Result);
1517 Account_Connection();
1519 } /* New_Connection */
1523 * Update global connection counters.
1526 Account_Connection(void)
1529 if (NumConnections > NumConnectionsMax)
1530 NumConnectionsMax = NumConnections;
1531 LogDebug("Total number of connections now %lu (max %lu).",
1532 NumConnections, NumConnectionsMax);
1533 } /* Account_Connection */
1537 * Translate socket handle into connection index.
1539 * @param Sock Socket handle.
1540 * @returns Connecion index or NONE, if no connection could be found.
1543 Socket2Index( int Sock )
1545 assert( Sock >= 0 );
1547 if( Sock >= Pool_Size || My_Connections[Sock].sock != Sock ) {
1548 /* the Connection was already closed again, likely due to
1550 LogDebug("Socket2Index: can't get connection for socket %d!", Sock);
1554 } /* Socket2Index */
1558 * Read data from the network to the read buffer. If an error occures,
1559 * the socket of this connection will be shut down.
1561 * @param Idx Connection index.
1564 Read_Request( CONN_ID Idx )
1567 static const unsigned int maxbps = COMMAND_LEN / 2;
1568 char readbuf[READBUFFER_LEN];
1571 assert( Idx > NONE );
1572 assert( My_Connections[Idx].sock > NONE );
1575 if ((array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN) ||
1576 (array_bytes(&My_Connections[Idx].zip.rbuf) >= READBUFFER_LEN))
1578 if (array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN)
1581 /* Read buffer is full */
1583 "Receive buffer space exhausted (connection %d): %d bytes",
1584 Idx, array_bytes(&My_Connections[Idx].rbuf));
1585 Conn_Close(Idx, "Receive buffer space exhausted", NULL, false);
1590 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_SSL))
1591 len = ConnSSL_Read( &My_Connections[Idx], readbuf, sizeof(readbuf));
1594 len = read(My_Connections[Idx].sock, readbuf, sizeof(readbuf));
1596 Log(LOG_INFO, "%s:%u (%s) is closing the connection ...",
1597 My_Connections[Idx].host,
1598 (unsigned int) ng_ipaddr_getport(&My_Connections[Idx].addr),
1599 ng_ipaddr_tostr(&My_Connections[Idx].addr));
1601 "Socket closed!", "Client closed connection",
1607 if( errno == EAGAIN ) return;
1608 Log(LOG_ERR, "Read error on connection %d (socket %d): %s!",
1609 Idx, My_Connections[Idx].sock, strerror(errno));
1610 Conn_Close(Idx, "Read error!", "Client closed connection",
1615 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1616 if (!array_catb(&My_Connections[Idx].zip.rbuf, readbuf,
1619 "Could not append received data to zip input buffer (connection %d): %d bytes!",
1621 Conn_Close(Idx, "Receive buffer space exhausted", NULL,
1628 if (!array_catb( &My_Connections[Idx].rbuf, readbuf, len)) {
1630 "Could not append received data to input buffer (connection %d): %d bytes!",
1632 Conn_Close(Idx, "Receive buffer space exhausted", NULL, false );
1636 /* Update connection statistics */
1637 My_Connections[Idx].bytes_in += len;
1638 My_Connections[Idx].bps += Handle_Buffer(Idx);
1640 /* Make sure that there is still a valid client registered */
1641 c = Conn_GetClient(Idx);
1645 /* Update timestamp of last data received if this connection is
1646 * registered as a user, server or service connection. Don't update
1647 * otherwise, so users have at least Conf_PongTimeout seconds time to
1648 * register with the IRC server -- see Check_Connections().
1649 * Update "lastping", too, if time shifted backwards ... */
1650 if (Client_Type(c) == CLIENT_USER
1651 || Client_Type(c) == CLIENT_SERVER
1652 || Client_Type(c) == CLIENT_SERVICE) {
1654 if (My_Connections[Idx].lastdata != t)
1655 My_Connections[Idx].bps = 0;
1657 My_Connections[Idx].lastdata = t;
1658 if (My_Connections[Idx].lastping > t)
1659 My_Connections[Idx].lastping = t;
1662 /* Look at the data in the (read-) buffer of this connection */
1663 if (Client_Type(c) != CLIENT_SERVER
1664 && Client_Type(c) != CLIENT_UNKNOWNSERVER
1665 && Client_Type(c) != CLIENT_SERVICE
1666 && My_Connections[Idx].bps >= maxbps) {
1667 LogDebug("Throttling connection %d: BPS exceeded! (%u >= %u)",
1668 Idx, My_Connections[Idx].bps, maxbps);
1669 Conn_SetPenalty(Idx, 1);
1671 } /* Read_Request */
1675 * Handle all data in the connection read-buffer.
1677 * Data is processed until no complete command is left in the read buffer,
1678 * or MAX_COMMANDS[_SERVER|_SERVICE] commands were processed.
1679 * When a fatal error occurs, the connection is shut down.
1681 * @param Idx Index of the connection.
1682 * @returns Number of bytes processed.
1685 Handle_Buffer(CONN_ID Idx)
1688 char *ptr1, *ptr2, *first_eol;
1696 unsigned int i, maxcmd = MAX_COMMANDS, len_processed = 0;
1699 c = Conn_GetClient(Idx);
1700 starttime = time(NULL);
1704 /* Servers get special command limits that depend on the user count */
1705 switch (Client_Type(c)) {
1707 maxcmd = (int)(Client_UserCount() / 5)
1708 + MAX_COMMANDS_SERVER_MIN;
1709 /* Allow servers to handle even more commands while peering
1710 * to speed up server login and network synchronisation. */
1711 if (Conn_LastPing(Idx) == 0)
1714 case CLIENT_SERVICE:
1715 maxcmd = MAX_COMMANDS_SERVICE; break;
1718 for (i=0; i < maxcmd; i++) {
1720 if (My_Connections[Idx].delaytime > starttime)
1723 /* Unpack compressed data, if compression is in use */
1724 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1725 /* When unzipping fails, Unzip_Buffer() shuts
1726 * down the connection itself */
1727 if (!Unzip_Buffer(Idx))
1732 if (0 == array_bytes(&My_Connections[Idx].rbuf))
1735 /* Make sure that the buffer is NULL terminated */
1736 if (!array_cat0_temporary(&My_Connections[Idx].rbuf)) {
1737 Conn_Close(Idx, NULL,
1738 "Can't allocate memory [Handle_Buffer]",
1743 /* RFC 2812, section "2.3 Messages", 5th paragraph:
1744 * "IRC messages are always lines of characters terminated
1745 * with a CR-LF (Carriage Return - Line Feed) pair [...]". */
1747 ptr = strstr(array_start(&My_Connections[Idx].rbuf), "\r\n");
1750 /* Check for non-RFC-compliant request (only CR or LF)?
1751 * Unfortunately, there are quite a few clients out there
1752 * that do this -- e. g. mIRC, BitchX, and Trillian :-( */
1753 ptr1 = strchr(array_start(&My_Connections[Idx].rbuf), '\r');
1754 ptr2 = strchr(array_start(&My_Connections[Idx].rbuf), '\n');
1756 /* Check if there is a single CR or LF _before_ the
1757 * corerct CR+LF line terminator: */
1758 first_eol = ptr1 < ptr2 ? ptr1 : ptr2;
1759 if (first_eol < ptr) {
1760 /* Single CR or LF before CR+LF found */
1764 } else if (ptr1 || ptr2) {
1765 /* No CR+LF terminated command found, but single
1766 * CR or LF found ... */
1768 ptr = ptr1 < ptr2 ? ptr1 : ptr2;
1770 ptr = ptr1 ? ptr1 : ptr2;
1778 /* Complete (=line terminated) request found, handle it! */
1781 len = ptr - (char *)array_start(&My_Connections[Idx].rbuf) + delta;
1783 if (len > (COMMAND_LEN - 1)) {
1784 /* Request must not exceed 512 chars (incl. CR+LF!),
1785 * see RFC 2812. Disconnect Client if this happens. */
1787 "Request too long (connection %d): %d bytes (max. %d expected)!",
1788 Idx, array_bytes(&My_Connections[Idx].rbuf),
1790 Conn_Close(Idx, NULL, "Request too long", true);
1794 len_processed += (unsigned int)len;
1796 /* Request is empty (only '\r\n', '\r' or '\n');
1797 * delta is 2 ('\r\n') or 1 ('\r' or '\n'), see above */
1798 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1802 /* remember if stream is already compressed */
1803 old_z = My_Connections[Idx].options & CONN_ZIP;
1806 My_Connections[Idx].msg_in++;
1808 (Idx, (char *)array_start(&My_Connections[Idx].rbuf)))
1809 return 0; /* error -> connection has been closed */
1811 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1813 LogDebug("Connection %d: %d bytes left in read buffer.",
1814 Idx, array_bytes(&My_Connections[Idx].rbuf));
1817 if ((!old_z) && (My_Connections[Idx].options & CONN_ZIP) &&
1818 (array_bytes(&My_Connections[Idx].rbuf) > 0)) {
1819 /* The last command activated socket compression.
1820 * Data that was read after that needs to be copied
1821 * to the unzip buffer for decompression: */
1823 (&My_Connections[Idx].zip.rbuf,
1824 &My_Connections[Idx].rbuf)) {
1825 Conn_Close(Idx, NULL,
1826 "Can't allocate memory [Handle_Buffer]",
1831 array_trunc(&My_Connections[Idx].rbuf);
1833 ("Moved already received data (%u bytes) to uncompression buffer.",
1834 array_bytes(&My_Connections[Idx].zip.rbuf));
1838 return len_processed;
1839 } /* Handle_Buffer */
1843 * Check whether established connections are still alive or not.
1844 * If not, play PING-PONG first; and if that doesn't help either,
1845 * disconnect the respective peer.
1848 Check_Connections(void)
1854 for (i = 0; i < Pool_Size; i++) {
1855 if (My_Connections[i].sock < 0)
1858 c = Conn_GetClient(i);
1859 if (c && ((Client_Type(c) == CLIENT_USER)
1860 || (Client_Type(c) == CLIENT_SERVER)
1861 || (Client_Type(c) == CLIENT_SERVICE))) {
1862 /* connected User, Server or Service */
1863 if (My_Connections[i].lastping >
1864 My_Connections[i].lastdata) {
1865 /* We already sent a ping */
1866 if (My_Connections[i].lastping <
1867 time(NULL) - Conf_PongTimeout) {
1869 snprintf(msg, sizeof(msg),
1870 "Ping timeout: %d seconds",
1872 LogDebug("Connection %d: %s.", i, msg);
1873 Conn_Close(i, NULL, msg, true);
1875 } else if (My_Connections[i].lastdata <
1876 time(NULL) - Conf_PingTimeout) {
1877 /* We need to send a PING ... */
1878 LogDebug("Connection %d: sending PING ...", i);
1880 Conn_WriteStr(i, "PING :%s",
1881 Client_ID(Client_ThisServer()));
1884 /* The connection is not fully established yet, so
1885 * we don't do the PING-PONG game here but instead
1886 * disconnect the client after "a short time" if it's
1887 * still not registered. */
1889 if (My_Connections[i].lastdata <
1890 time(NULL) - Conf_PongTimeout) {
1892 ("Unregistered connection %d timed out ...",
1894 Conn_Close(i, NULL, "Timeout", false);
1898 } /* Check_Connections */
1902 * Check if further server links should be established.
1910 time_now = time(NULL);
1912 /* Check all configured servers */
1913 for (i = 0; i < MAX_SERVERS; i++) {
1914 if (Conf_Server[i].conn_id != NONE)
1915 continue; /* Already establishing or connected */
1916 if (!Conf_Server[i].host[0] || !Conf_Server[i].port > 0)
1917 continue; /* No host and/or port configured */
1918 if (Conf_Server[i].flags & CONF_SFLAG_DISABLED)
1919 continue; /* Disabled configuration entry */
1920 if (Conf_Server[i].lasttry > (time_now - Conf_ConnectRetry))
1921 continue; /* We have to wait a little bit ... */
1923 /* Is there already a connection in this group? */
1924 if (Conf_Server[i].group > NONE) {
1925 for (n = 0; n < MAX_SERVERS; n++) {
1928 if ((Conf_Server[n].conn_id != NONE) &&
1929 (Conf_Server[n].group == Conf_Server[i].group))
1932 if (n < MAX_SERVERS)
1936 /* Okay, try to connect now */
1938 "Preparing to establish a new server link for \"%s\" ...",
1939 Conf_Server[i].name);
1940 Conf_Server[i].lasttry = time_now;
1941 Conf_Server[i].conn_id = SERVER_WAIT;
1942 assert(Proc_GetPipeFd(&Conf_Server[i].res_stat) < 0);
1943 Resolve_Name(&Conf_Server[i].res_stat, Conf_Server[i].host,
1944 cb_Connect_to_Server);
1946 } /* Check_Servers */
1950 * Establish a new outgoing server connection.
1952 * @param Server Configuration index of the server.
1953 * @param dest Destination IP address to connect to.
1956 New_Server( int Server , ng_ipaddr_t *dest)
1958 /* Establish new server link */
1959 char ip_str[NG_INET_ADDRSTRLEN];
1960 int af_dest, res, new_sock;
1963 assert( Server > NONE );
1965 /* Make sure that the remote server hasn't re-linked to this server
1966 * asynchronously on its own */
1967 if (Conf_Server[Server].conn_id > NONE) {
1969 "Connection to \"%s\" meanwhile re-established, aborting preparation.");
1973 if (!ng_ipaddr_tostr_r(dest, ip_str)) {
1974 Log(LOG_WARNING, "New_Server: Could not convert IP to string");
1978 af_dest = ng_ipaddr_af(dest);
1979 new_sock = socket(af_dest, SOCK_STREAM, 0);
1982 "Establishing connection for \"%s\" to \"%s:%d\" (%s), socket %d ...",
1983 Conf_Server[Server].name, Conf_Server[Server].host,
1984 Conf_Server[Server].port, ip_str, new_sock);
1987 Log(LOG_CRIT, "Can't create socket (af %d): %s!",
1988 af_dest, strerror(errno));
1992 if (!Init_Socket(new_sock))
1995 /* is a bind address configured? */
1996 res = ng_ipaddr_af(&Conf_Server[Server].bind_addr);
1997 /* if yes, bind now. If it fails, warn and let connect() pick a source address */
1998 if (res && bind(new_sock, (struct sockaddr *) &Conf_Server[Server].bind_addr,
1999 ng_ipaddr_salen(&Conf_Server[Server].bind_addr)))
2001 ng_ipaddr_tostr_r(&Conf_Server[Server].bind_addr, ip_str);
2002 Log(LOG_WARNING, "Can't bind socket to %s: %s!", ip_str, strerror(errno));
2004 ng_ipaddr_setport(dest, Conf_Server[Server].port);
2005 res = connect(new_sock, (struct sockaddr *) dest, ng_ipaddr_salen(dest));
2006 if(( res != 0 ) && ( errno != EINPROGRESS )) {
2007 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
2012 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)new_sock)) {
2014 "Cannot allocate memory for server connection (socket %d)",
2020 if (!io_event_create( new_sock, IO_WANTWRITE, cb_connserver)) {
2021 Log(LOG_ALERT, "io_event_create(): could not add fd %d", strerror(errno));
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!" );
2040 /* Conn_Close() decrements this counter again */
2041 Account_Connection();
2042 Client_SetIntroducer( c, c );
2043 Client_SetToken( c, TOKEN_OUTBOUND );
2045 /* Register connection */
2046 Conf_SetServer(Server, new_sock);
2047 My_Connections[new_sock].sock = new_sock;
2048 My_Connections[new_sock].addr = *dest;
2049 My_Connections[new_sock].client = c;
2050 strlcpy( My_Connections[new_sock].host, Conf_Server[Server].host,
2051 sizeof(My_Connections[new_sock].host ));
2054 if (Conf_Server[Server].SSLConnect && !ConnSSL_PrepareConnect( &My_Connections[new_sock],
2055 &Conf_Server[Server] ))
2057 Log(LOG_ALERT, "Could not initialize SSL for outgoing connection");
2058 Conn_Close( new_sock, "Could not initialize SSL for outgoing connection", NULL, false );
2059 Init_Conn_Struct( new_sock );
2060 Conf_Server[Server].conn_id = NONE;
2064 LogDebug("Registered new connection %d on socket %d (%ld in total).",
2065 new_sock, My_Connections[new_sock].sock, NumConnections);
2066 Conn_OPTION_ADD( &My_Connections[new_sock], CONN_ISCONNECTING );
2071 * Initialize connection structure.
2073 * @param Idx Connection index.
2076 Init_Conn_Struct(CONN_ID Idx)
2078 time_t now = time(NULL);
2080 memset(&My_Connections[Idx], 0, sizeof(CONNECTION));
2081 My_Connections[Idx].sock = -1;
2082 My_Connections[Idx].signon = now;
2083 My_Connections[Idx].lastdata = now;
2084 My_Connections[Idx].lastprivmsg = now;
2085 Proc_InitStruct(&My_Connections[Idx].proc_stat);
2086 } /* Init_Conn_Struct */
2090 * Initialize options of a new socket.
2092 * For example, we try to set socket options SO_REUSEADDR and IPTOS_LOWDELAY.
2093 * The socket is automatically closed if a fatal error is encountered.
2095 * @param Sock Socket handle.
2096 * @returns false if socket was closed due to fatal error.
2099 Init_Socket( int Sock )
2103 if (!io_setnonblock(Sock)) {
2104 Log( LOG_CRIT, "Can't enable non-blocking mode for socket: %s!", strerror( errno ));
2109 /* Don't block this port after socket shutdown */
2111 if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &value, (socklen_t)sizeof( value )) != 0 )
2113 Log( LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!", strerror( errno ));
2114 /* ignore this error */
2117 /* Set type of service (TOS) */
2118 #if defined(IPPROTO_IP) && defined(IPTOS_LOWDELAY)
2119 value = IPTOS_LOWDELAY;
2120 if (setsockopt(Sock, IPPROTO_IP, IP_TOS, &value,
2121 (socklen_t) sizeof(value))) {
2122 LogDebug("Can't set socket option IP_TOS: %s!",
2124 /* ignore this error */
2126 LogDebug("IP_TOS on socket %d has been set to IPTOS_LOWDELAY.",
2135 * Read results of a resolver sub-process and try to initiate a new server
2138 * @param fd File descriptor of the pipe to the sub-process.
2139 * @param events (ignored IO specification)
2142 cb_Connect_to_Server(int fd, UNUSED short events)
2144 /* Read result of resolver sub-process from pipe and start connection */
2147 ng_ipaddr_t dest_addrs[4]; /* we can handle at most 3; but we read up to
2148 four so we can log the 'more than we can handle'
2149 condition. First result is tried immediately, rest
2150 is saved for later if needed. */
2152 LogDebug("Resolver: Got forward lookup callback on fd %d, events %d", fd, events);
2154 for (i=0; i < MAX_SERVERS; i++) {
2155 if (Proc_GetPipeFd(&Conf_Server[i].res_stat) == fd )
2159 if( i >= MAX_SERVERS) {
2160 /* Ops, no matching server found?! */
2162 LogDebug("Resolver: Got Forward Lookup callback for unknown server!?");
2166 /* Read result from pipe */
2167 len = Proc_Read(&Conf_Server[i].res_stat, dest_addrs, sizeof(dest_addrs));
2168 Proc_Close(&Conf_Server[i].res_stat);
2170 /* Error resolving hostname: reset server structure */
2171 Conf_Server[i].conn_id = NONE;
2175 assert((len % sizeof(ng_ipaddr_t)) == 0);
2177 LogDebug("Got result from resolver: %u structs (%u bytes).", len/sizeof(ng_ipaddr_t), len);
2179 memset(&Conf_Server[i].dst_addr, 0, sizeof(Conf_Server[i].dst_addr));
2180 if (len > sizeof(ng_ipaddr_t)) {
2181 /* more than one address for this hostname, remember them
2182 * in case first address is unreachable/not available */
2183 len -= sizeof(ng_ipaddr_t);
2184 if (len > sizeof(Conf_Server[i].dst_addr)) {
2185 len = sizeof(Conf_Server[i].dst_addr);
2187 "Notice: Resolver returned more IP Addresses for host than we can handle, additional addresses dropped.");
2189 memcpy(&Conf_Server[i].dst_addr, &dest_addrs[1], len);
2192 New_Server(i, dest_addrs);
2193 } /* cb_Read_Forward_Lookup */
2197 * Read results of a resolver sub-process from the pipe and update the
2198 * apropriate connection/client structure(s): hostname and/or IDENT user name.
2200 * @param r_fd File descriptor of the pipe to the sub-process.
2201 * @param events (ignored IO specification)
2204 cb_Read_Resolver_Result( int r_fd, UNUSED short events )
2211 char readbuf[HOST_LEN + 2 + CLIENT_USER_LEN];
2214 char readbuf[HOST_LEN + 1];
2217 LogDebug("Resolver: Got callback on fd %d, events %d", r_fd, events );
2218 i = Conn_GetFromProc(r_fd);
2220 /* Ops, none found? Probably the connection has already
2221 * been closed!? We'll ignore that ... */
2223 LogDebug("Resolver: Got callback for unknown connection!?");
2227 /* Read result from pipe */
2228 len = Proc_Read(&My_Connections[i].proc_stat, readbuf, sizeof readbuf -1);
2229 Proc_Close(&My_Connections[i].proc_stat);
2233 readbuf[len] = '\0';
2234 identptr = strchr(readbuf, '\n');
2235 assert(identptr != NULL);
2237 Log( LOG_CRIT, "Resolver: Got malformed result!");
2242 LogDebug("Got result from resolver: \"%s\" (%u bytes read).", readbuf, len);
2243 /* Okay, we got a complete result: this is a host name for outgoing
2244 * connections and a host name and IDENT user name (if enabled) for
2245 * incoming connections.*/
2246 assert ( My_Connections[i].sock >= 0 );
2247 /* Incoming connection. Search client ... */
2248 c = Conn_GetClient( i );
2249 assert( c != NULL );
2251 /* Only update client information of unregistered clients.
2252 * Note: user commands (e. g. WEBIRC) are always read _after_ reading
2253 * the resolver results, so we don't have to worry to override settings
2254 * from these commands here. */
2255 if(Client_Type(c) == CLIENT_UNKNOWN) {
2256 strlcpy(My_Connections[i].host, readbuf,
2257 sizeof(My_Connections[i].host));
2258 Client_SetHostname(c, readbuf);
2259 if (Conf_NoticeAuth)
2260 (void)Conn_WriteStr(i,
2261 "NOTICE AUTH :*** Found your hostname: %s",
2262 My_Connections[i].host);
2268 if ((*ptr < '0' || *ptr > '9') &&
2269 (*ptr < 'A' || *ptr > 'Z') &&
2270 (*ptr < 'a' || *ptr > 'z'))
2275 /* Erroneous IDENT reply */
2277 "Got invalid IDENT reply for connection %d! Ignored.",
2281 "IDENT lookup for connection %d: \"%s\".",
2283 Client_SetUser(c, identptr, true);
2285 if (Conf_NoticeAuth) {
2286 (void)Conn_WriteStr(i,
2287 "NOTICE AUTH :*** Got %sident response%s%s",
2288 *ptr ? "invalid " : "",
2290 *ptr ? "" : identptr);
2293 Log(LOG_INFO, "IDENT lookup for connection %d: no result.", i);
2294 if (Conf_NoticeAuth && Conf_Ident)
2295 (void)Conn_WriteStr(i,
2296 "NOTICE AUTH :*** No ident response");
2300 if (Conf_NoticeAuth)
2301 (void)Handle_Write(i);
2303 Class_HandleServerBans(c);
2306 else Log( LOG_DEBUG, "Resolver: discarding result for already registered connection %d.", i );
2308 } /* cb_Read_Resolver_Result */
2312 * Write a "simple" (error) message to a socket.
2314 * The message is sent without using the connection write buffers, without
2315 * compression/encryption, and even without any error reporting. It is
2316 * designed for error messages of e.g. New_Connection().
2318 * @param Sock Socket handle.
2319 * @param Msg Message string to send.
2322 Simple_Message(int Sock, const char *Msg)
2324 char buf[COMMAND_LEN];
2327 assert(Sock > NONE);
2328 assert(Msg != NULL);
2330 strlcpy(buf, Msg, sizeof buf - 2);
2331 len = strlcat(buf, "\r\n", sizeof buf);
2332 if (write(Sock, buf, len) < 0) {
2333 /* Because this function most probably got called to log
2334 * an error message, any write error is ignored here to
2335 * avoid an endless loop. But casting the result of write()
2336 * to "void" doesn't satisfy the GNU C code attribute
2337 * "warn_unused_result" which is used by some versions of
2338 * glibc (e.g. 2.11.1), therefore this silly error
2339 * "handling" code here :-( */
2342 } /* Simple_Error */
2346 * Get CLIENT structure that belongs to a local connection identified by its
2347 * index number. Each connection belongs to a client by definition, so it is
2348 * not required that the caller checks for NULL return values.
2350 * @param Idx Connection index number.
2351 * @returns Pointer to CLIENT structure.
2354 Conn_GetClient( CONN_ID Idx )
2359 c = array_get(&My_ConnArray, sizeof (CONNECTION), (size_t)Idx);
2361 return c ? c->client : NULL;
2365 * Get PROC_STAT sub-process structure of a connection.
2367 * @param Idx Connection index number.
2368 * @returns PROC_STAT structure.
2371 Conn_GetProcStat(CONN_ID Idx)
2376 c = array_get(&My_ConnArray, sizeof (CONNECTION), (size_t)Idx);
2378 return &c->proc_stat;
2379 } /* Conn_GetProcStat */
2383 * Get CONN_ID from file descriptor associated to a subprocess structure.
2385 * @param fd File descriptor.
2386 * @returns CONN_ID or NONE (-1).
2389 Conn_GetFromProc(int fd)
2394 for (i = 0; i < Pool_Size; i++) {
2395 if ((My_Connections[i].sock != NONE)
2396 && (Proc_GetPipeFd(&My_Connections[i].proc_stat) == fd))
2400 } /* Conn_GetFromProc */
2406 Conn_GetAuthPing(CONN_ID Idx)
2408 assert (Idx != NONE);
2409 return My_Connections[Idx].auth_ping;
2410 } /* Conn_GetAuthPing */
2413 Conn_SetAuthPing(CONN_ID Idx, long ID)
2415 assert (Idx != NONE);
2416 My_Connections[Idx].auth_ping = ID;
2417 } /* Conn_SetAuthPing */
2425 * Get information about used SSL chiper.
2427 * @param Idx Connection index number.
2428 * @param buf Buffer for returned information text.
2429 * @param len Size of return buffer "buf".
2430 * @returns true on success, false otherwise.
2433 Conn_GetCipherInfo(CONN_ID Idx, char *buf, size_t len)
2437 assert(Idx < (int) array_length(&My_ConnArray, sizeof(CONNECTION)));
2438 return ConnSSL_GetCipherInfo(&My_Connections[Idx], buf, len);
2443 * Check if a connection is SSL-enabled or not.
2445 * @param Idx Connection index number.
2446 * @return true if connection is SSL-enabled, false otherwise.
2449 Conn_UsesSSL(CONN_ID Idx)
2453 assert(Idx < (int) array_length(&My_ConnArray, sizeof(CONNECTION)));
2454 return Conn_OPTION_ISSET(&My_Connections[Idx], CONN_SSL);
2463 * Dump internal state of the "connection module".
2466 Conn_DebugDump(void)
2470 Log(LOG_DEBUG, "Connection status:");
2471 for (i = 0; i < Pool_Size; i++) {
2472 if (My_Connections[i].sock == NONE)
2475 " - %d: host=%s, lastdata=%ld, lastping=%ld, delaytime=%ld, flag=%d, options=%d, bps=%d, client=%s",
2476 My_Connections[i].sock, My_Connections[i].host,
2477 My_Connections[i].lastdata, My_Connections[i].lastping,
2478 My_Connections[i].delaytime, My_Connections[i].flag,
2479 My_Connections[i].options, My_Connections[i].bps,
2480 My_Connections[i].client ? Client_ID(My_Connections[i].client) : "-");
2482 } /* Conn_DumpClients */