2 * ngIRCd -- The Next Generation IRC Daemon
3 * Copyright (c)2001-2010 Alexander Barton <alex@barton.de>
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 */
71 #include "conn-func.h"
73 #include "ng_ipaddr.h"
81 #define SERVER_WAIT (NONE - 1)
83 #define MAX_COMMANDS 3
84 #define MAX_COMMANDS_SERVER 10
85 #define MAX_COMMANDS_SERVICE MAX_COMMANDS_SERVER
88 static bool Handle_Write PARAMS(( CONN_ID Idx ));
89 static bool Conn_Write PARAMS(( CONN_ID Idx, char *Data, size_t Len ));
90 static int New_Connection PARAMS(( int Sock ));
91 static CONN_ID Socket2Index PARAMS(( int Sock ));
92 static void Read_Request PARAMS(( CONN_ID Idx ));
93 static unsigned int Handle_Buffer PARAMS(( CONN_ID Idx ));
94 static void Check_Connections PARAMS(( void ));
95 static void Check_Servers PARAMS(( void ));
96 static void Init_Conn_Struct PARAMS(( CONN_ID Idx ));
97 static bool Init_Socket PARAMS(( int Sock ));
98 static void New_Server PARAMS(( int Server, ng_ipaddr_t *dest ));
99 static void Simple_Message PARAMS(( int Sock, const char *Msg ));
100 static int NewListener PARAMS(( const char *listen_addr, UINT16 Port ));
101 static void Account_Connection PARAMS((void));
104 static array My_Listeners;
105 static array My_ConnArray;
106 static size_t NumConnections, NumConnectionsMax, NumConnectionsAccepted;
109 int allow_severity = LOG_INFO;
110 int deny_severity = LOG_ERR;
113 static void server_login PARAMS((CONN_ID idx));
116 extern struct SSLOptions Conf_SSLOptions;
117 static void cb_connserver_login_ssl PARAMS((int sock, short what));
118 static void cb_clientserver_ssl PARAMS((int sock, short what));
120 static void cb_Read_Resolver_Result PARAMS((int sock, UNUSED short what));
121 static void cb_Connect_to_Server PARAMS((int sock, UNUSED short what));
122 static void cb_clientserver PARAMS((int sock, short what));
126 * IO callback for listening sockets: handle new connections. This callback
127 * gets called when a new non-SSL connection should be accepted.
129 * @param sock Socket descriptor.
130 * @param irrelevant (ignored IO specification)
133 cb_listen(int sock, short irrelevant)
136 (void) New_Connection(sock);
142 * IO callback for listening SSL sockets: handle new connections. This callback
143 * gets called when a new SSL-enabled connection should be accepted.
145 * @param sock Socket descriptor.
146 * @param irrelevant (ignored IO specification)
149 cb_listen_ssl(int sock, short irrelevant)
154 fd = New_Connection(sock);
157 io_event_setcb(My_Connections[fd].sock, cb_clientserver_ssl);
163 * IO callback for new outgoing non-SSL server connections.
165 * @param sock Socket descriptor.
166 * @param what IO specification (IO_WANTREAD/IO_WANTWRITE/...).
169 cb_connserver(int sock, UNUSED short what)
171 int res, err, server;
173 CONN_ID idx = Socket2Index( sock );
176 LogDebug("cb_connserver wants to write on unknown socket?!");
181 assert(what & IO_WANTWRITE);
183 /* Make sure that the server is still configured; it could have been
184 * removed in the meantime! */
185 server = Conf_GetServer(idx);
187 Log(LOG_ERR, "Connection on socket %d to \"%s\" aborted!",
188 sock, My_Connections[idx].host);
189 Conn_Close(idx, "Connection aborted!", NULL, false);
193 /* connect() finished, get result. */
194 sock_len = (socklen_t)sizeof(err);
195 res = getsockopt(My_Connections[idx].sock, SOL_SOCKET, SO_ERROR,
197 assert(sock_len == sizeof(err));
199 /* Error while connecting? */
200 if ((res != 0) || (err != 0)) {
202 Log(LOG_CRIT, "getsockopt (connection %d): %s!",
203 idx, strerror(errno));
206 "Can't connect socket to \"%s:%d\" (connection %d): %s!",
207 My_Connections[idx].host, Conf_Server[server].port,
210 Conn_Close(idx, "Can't connect!", NULL, false);
212 if (ng_ipaddr_af(&Conf_Server[server].dst_addr[0])) {
213 /* more addresses to try... */
214 New_Server(server, &Conf_Server[server].dst_addr[0]);
215 /* connection to dst_addr[0] is now in progress, so
216 * remove this address... */
217 Conf_Server[server].dst_addr[0] =
218 Conf_Server[server].dst_addr[1];
219 memset(&Conf_Server[server].dst_addr[1], 0,
220 sizeof(Conf_Server[server].dst_addr[1]));
225 /* connect() succeeded, remove all additional addresses */
226 memset(&Conf_Server[server].dst_addr, 0,
227 sizeof(Conf_Server[server].dst_addr));
229 Conn_OPTION_DEL( &My_Connections[idx], CONN_ISCONNECTING );
231 if ( Conn_OPTION_ISSET( &My_Connections[idx], CONN_SSL_CONNECT )) {
232 io_event_setcb( sock, cb_connserver_login_ssl );
233 io_event_add( sock, IO_WANTWRITE|IO_WANTREAD );
242 * Login to a remote server.
244 * @param idx Connection index.
247 server_login(CONN_ID idx)
250 "Connection %d (socket %d) with \"%s:%d\" established. Now logging in ...",
251 idx, My_Connections[idx].sock, My_Connections[idx].host,
252 Conf_Server[Conf_GetServer(idx)].port);
254 io_event_setcb( My_Connections[idx].sock, cb_clientserver);
255 io_event_add( My_Connections[idx].sock, IO_WANTREAD|IO_WANTWRITE);
257 /* Send PASS and SERVER command to peer */
258 Conn_WriteStr( idx, "PASS %s %s", Conf_Server[Conf_GetServer( idx )].pwd_out, NGIRCd_ProtoID );
259 Conn_WriteStr( idx, "SERVER %s :%s", Conf_ServerName, Conf_ServerInfo );
265 * IO callback for new outgoing SSL-enabled server connections.
267 * @param sock Socket descriptor.
268 * @param unused (ignored IO specification)
271 cb_connserver_login_ssl(int sock, short unused)
273 CONN_ID idx = Socket2Index(sock);
281 switch (ConnSSL_Connect( &My_Connections[idx])) {
283 case 0: LogDebug("ConnSSL_Connect: not ready");
286 Log(LOG_ERR, "SSL connection on socket %d failed!", sock);
287 Conn_Close(idx, "Can't connect!", NULL, false);
291 Log( LOG_INFO, "SSL connection %d with \"%s:%d\" established.", idx,
292 My_Connections[idx].host, Conf_Server[Conf_GetServer( idx )].port );
300 * IO callback for established non-SSL client and server connections.
302 * @param sock Socket descriptor.
303 * @param what IO specification (IO_WANTREAD/IO_WANTWRITE/...).
306 cb_clientserver(int sock, short what)
308 CONN_ID idx = Socket2Index(sock);
317 if (what & IO_WANTREAD
318 || (Conn_OPTION_ISSET(&My_Connections[idx], CONN_SSL_WANT_WRITE))) {
319 /* if TLS layer needs to write additional data, call
320 * Read_Request() instead so that SSL/TLS can continue */
324 if (what & IO_WANTREAD)
327 if (what & IO_WANTWRITE)
334 * IO callback for established SSL-enabled client and server connections.
336 * @param sock Socket descriptor.
337 * @param what IO specification (IO_WANTREAD/IO_WANTWRITE/...).
340 cb_clientserver_ssl(int sock, short what)
342 CONN_ID idx = Socket2Index(sock);
351 switch (ConnSSL_Accept(&My_Connections[idx])) {
355 return; /* EAGAIN: callback will be invoked again by IO layer */
357 Conn_Close(idx, "SSL accept error, closing socket", "SSL accept error", false);
360 if (what & IO_WANTREAD)
363 if (what & IO_WANTWRITE)
366 io_event_setcb(sock, cb_clientserver); /* SSL handshake completed */
372 * Initialite connecion module.
379 /* Speicher fuer Verbindungs-Pool anfordern */
380 Pool_Size = CONNECTION_POOL;
381 if ((Conf_MaxConnections > 0) &&
382 (Pool_Size > Conf_MaxConnections))
383 Pool_Size = Conf_MaxConnections;
385 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)Pool_Size)) {
386 Log(LOG_EMERG, "Can't allocate memory! [Conn_Init]");
390 /* FIXME: My_Connetions/Pool_Size is needed by other parts of the
391 * code; remove them! */
392 My_Connections = (CONNECTION*) array_start(&My_ConnArray);
394 LogDebug("Allocated connection pool for %d items (%ld bytes).",
395 array_length(&My_ConnArray, sizeof(CONNECTION)),
396 array_bytes(&My_ConnArray));
398 assert(array_length(&My_ConnArray, sizeof(CONNECTION)) >= (size_t)Pool_Size);
400 array_free( &My_Listeners );
402 for (i = 0; i < Pool_Size; i++)
408 * Clean up connection module.
415 Conn_ExitListeners();
417 LogDebug("Shutting down all connections ..." );
418 for( idx = 0; idx < Pool_Size; idx++ ) {
419 if( My_Connections[idx].sock > NONE ) {
420 Conn_Close( idx, NULL, NGIRCd_SignalRestart ?
421 "Server going down (restarting)":"Server going down", true );
425 array_free(&My_ConnArray);
426 My_Connections = NULL;
428 io_library_shutdown();
433 * Close all sockets (file descriptors) of open connections.
434 * This is useful in forked child processes, for example, to make sure that
435 * they don't hold connections open that the main process wants to close.
438 Conn_CloseAllSockets(void)
442 for(idx = 0; idx < Pool_Size; idx++) {
443 if(My_Connections[idx].sock > NONE)
444 close(My_Connections[idx].sock);
450 * Initialize listening ports.
452 * @param a Array containing the ports the daemon should listen on.
453 * @param listen_addr Address the socket should listen on (can be "0.0.0.0").
454 * @param func IO callback function to register.
455 * @returns Number of listening sockets created.
458 ports_initlisteners(array *a, const char *listen_addr, void (*func)(int,short))
460 unsigned int created = 0;
465 len = array_length(a, sizeof (UINT16));
466 port = array_start(a);
468 fd = NewListener(listen_addr, *port);
473 if (!io_event_create( fd, IO_WANTREAD, func )) {
474 Log( LOG_ERR, "io_event_create(): Could not add listening fd %d (port %u): %s!",
475 fd, (unsigned int) *port, strerror(errno));
488 * Initialize all listening sockets.
490 * @returns Number of created listening sockets
493 Conn_InitListeners( void )
495 /* Initialize ports on which the server should accept connections */
496 unsigned int created = 0;
497 char *copy, *listen_addr;
499 assert(Conf_ListenAddress);
501 /* can't use Conf_ListenAddress directly, see below */
502 copy = strdup(Conf_ListenAddress);
504 Log(LOG_CRIT, "Cannot copy %s: %s", Conf_ListenAddress, strerror(errno));
507 listen_addr = strtok(copy, ",");
509 while (listen_addr) {
510 ngt_TrimStr(listen_addr);
512 created += ports_initlisteners(&Conf_ListenPorts, listen_addr, cb_listen);
514 created += ports_initlisteners(&Conf_SSLOptions.ListenPorts, listen_addr, cb_listen_ssl);
518 listen_addr = strtok(NULL, ",");
521 /* Can't free() Conf_ListenAddress here: on REHASH, if the config file
522 * cannot be re-loaded, we'd end up with a NULL Conf_ListenAddress.
523 * Instead, free() takes place in conf.c, before the config file
524 * is being parsed. */
528 } /* Conn_InitListeners */
532 * Shut down all listening sockets.
535 Conn_ExitListeners( void )
537 /* Close down all listening sockets */
541 arraylen = array_length(&My_Listeners, sizeof (int));
543 "Shutting down all listening sockets (%d total) ...", arraylen);
544 fd = array_start(&My_Listeners);
549 LogDebug("Listening socket %d closed.", *fd );
552 array_free(&My_Listeners);
553 } /* Conn_ExitListeners */
557 * Bind a socket to a specific (source) address.
559 * @param addr Address structure.
560 * @param listen_addrstr Source address as string.
561 * @param Port Port number.
562 * @returns true on success, false otherwise.
565 InitSinaddrListenAddr(ng_ipaddr_t *addr, const char *listen_addrstr, UINT16 Port)
569 ret = ng_ipaddr_init(addr, listen_addrstr, Port);
571 assert(listen_addrstr);
572 Log(LOG_CRIT, "Can't bind to [%s]:%u: can't convert ip address \"%s\"",
573 listen_addrstr, Port, listen_addrstr);
580 * Set a socket to "IPv6 only". If the given socket doesn't belong to the
581 * AF_INET6 family, or the operating system doesn't support this functionality,
582 * this function retruns silently.
584 * @param af Address family of the socket.
585 * @param sock Socket handle.
588 set_v6_only(int af, int sock)
590 #if defined(IPV6_V6ONLY) && defined(WANT_IPV6)
596 if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, (socklen_t)sizeof(on)))
597 Log(LOG_ERR, "Could not set IPV6_V6ONLY: %s", strerror(errno));
606 * Initialize new listening port.
608 * @param listen_addr Local address to bind the socet to (can be 0.0.0.0).
609 * @param Port Port number on which the new socket should be listening.
610 * @returns file descriptor of the socket or -1 on failure.
613 NewListener(const char *listen_addr, UINT16 Port)
615 /* Create new listening socket on specified port */
619 if (!InitSinaddrListenAddr(&addr, listen_addr, Port))
622 af = ng_ipaddr_af(&addr);
623 sock = socket(af, SOCK_STREAM, 0);
625 Log(LOG_CRIT, "Can't create socket (af %d) : %s!", af, strerror(errno));
629 set_v6_only(af, sock);
631 if (!Init_Socket(sock))
634 if (bind(sock, (struct sockaddr *)&addr, ng_ipaddr_salen(&addr)) != 0) {
635 Log(LOG_CRIT, "Can't bind socket to address %s:%d - %s",
636 ng_ipaddr_tostr(&addr), Port, strerror(errno));
641 if( listen( sock, 10 ) != 0 ) {
642 Log( LOG_CRIT, "Can't listen on socket: %s!", strerror( errno ));
647 /* keep fd in list so we can close it when ngircd restarts/shuts down */
648 if (!array_catb( &My_Listeners,(char*) &sock, sizeof(int) )) {
649 Log( LOG_CRIT, "Can't add socket to My_Listeners array: %s!", strerror( errno ));
654 Log(LOG_INFO, "Now listening on [%s]:%d (socket %d).",
655 ng_ipaddr_tostr(&addr), Port, sock);
663 * Check if SSL library needs to read SSL-protocol related data.
665 * SSL/TLS connections require extra treatment:
666 * When either CONN_SSL_WANT_WRITE or CONN_SSL_WANT_READ is set, we
667 * need to take care of that first, before checking read/write buffers.
668 * For instance, while we might have data in our write buffer, the
669 * TLS/SSL protocol might need to read internal data first for TLS/SSL
672 * If this function returns true, such a condition is met and we have
673 * to reverse the condition (check for read even if we've data to write,
674 * do not check for read but writeability even if write-buffer is empty).
676 * @param c Connection to check.
677 * @returns true if SSL-library has to read protocol data.
680 SSL_WantRead(const CONNECTION *c)
682 if (Conn_OPTION_ISSET(c, CONN_SSL_WANT_READ)) {
683 io_event_add(c->sock, IO_WANTREAD);
690 * Check if SSL library needs to write SSL-protocol related data.
692 * Please see description of SSL_WantRead() for full description!
694 * @param c Connection to check.
695 * @returns true if SSL-library has to write protocol data.
698 SSL_WantWrite(const CONNECTION *c)
700 if (Conn_OPTION_ISSET(c, CONN_SSL_WANT_WRITE)) {
701 io_event_add(c->sock, IO_WANTWRITE);
710 SSL_WantRead(UNUSED const CONNECTION *c)
714 SSL_WantWrite(UNUSED const CONNECTION *c)
721 * "Main Loop": Loop until shutdown or restart is signalled.
723 * This function loops until a shutdown or restart of ngIRCd is signalled and
724 * calls io_dispatch() to check for readable and writable sockets every second.
725 * It checks for status changes on pending connections (e. g. when a hostname
726 * has been resolved), checks for "penalties" and timeouts, and handles the
733 unsigned int wdatalen, bytes_processed;
737 while (!NGIRCd_SignalQuit && !NGIRCd_SignalRestart) {
740 /* Check configured servers and established links */
744 /* Look for non-empty read buffers ... */
745 for (i = 0; i < Pool_Size; i++) {
746 if ((My_Connections[i].sock > NONE)
747 && (array_bytes(&My_Connections[i].rbuf) > 0)
748 && (My_Connections[i].delaytime <= t)) {
749 /* ... and try to handle the received data */
750 bytes_processed = Handle_Buffer(i);
751 /* if we processed data, and there might be
752 * more commands in the input buffer, do not
753 * try to read any more data now */
754 if (bytes_processed &&
755 array_bytes(&My_Connections[i].rbuf) > 2) {
757 ("Throttling connection %d: command limit reached!",
759 Conn_SetPenalty(i, 1);
764 /* Look for non-empty write buffers ... */
765 for (i = 0; i < Pool_Size; i++) {
766 if (My_Connections[i].sock <= NONE)
769 wdatalen = (unsigned int)array_bytes(&My_Connections[i].wbuf);
772 array_bytes(&My_Connections[i].zip.wbuf) > 0)
777 if (SSL_WantRead(&My_Connections[i]))
779 io_event_add(My_Connections[i].sock,
784 /* Check from which sockets we possibly could read ... */
785 for (i = 0; i < Pool_Size; i++) {
786 if (My_Connections[i].sock <= NONE)
789 if (SSL_WantWrite(&My_Connections[i]))
790 continue; /* TLS/SSL layer needs to write data; deal with this first */
792 if (Proc_InProgress(&My_Connections[i].proc_stat)) {
793 /* Wait for completion of forked subprocess
794 * and ignore the socket in the meantime ... */
795 io_event_del(My_Connections[i].sock,
800 if (Conn_OPTION_ISSET(&My_Connections[i], CONN_ISCONNECTING))
801 /* Wait for completion of connect() ... */
804 if (My_Connections[i].delaytime > t) {
805 /* There is a "penalty time" set: ignore socket! */
806 io_event_del(My_Connections[i].sock,
811 io_event_add(My_Connections[i].sock, IO_WANTREAD);
814 /* Set the timeout for reading from the network to 1 second,
815 * which is the granularity with witch we handle "penalty
816 * times" for example.
817 * Note: tv_sec/usec are undefined(!) after io_dispatch()
818 * returns, so we have to set it beforce each call to it! */
822 /* Wait for activity ... */
823 i = io_dispatch(&tv);
824 if (i == -1 && errno != EINTR) {
825 Log(LOG_EMERG, "Conn_Handler(): io_dispatch(): %s!",
827 Log(LOG_ALERT, "%s exiting due to fatal errors!",
833 if (NGIRCd_SignalQuit)
834 Log(LOG_NOTICE | LOG_snotice, "Server going down NOW!");
835 else if (NGIRCd_SignalRestart)
836 Log(LOG_NOTICE | LOG_snotice, "Server restarting NOW!");
841 * Write a text string into the socket of a connection.
843 * This function automatically appends CR+LF to the string and validates that
844 * the result is a valid IRC message (oversized messages are shortened, for
845 * example). Then it calls the Conn_Write() function to do the actual sending.
847 * @param Idx Index fo the connection.
848 * @param Format Format string, see printf().
849 * @returns true on success, false otherwise.
853 Conn_WriteStr(CONN_ID Idx, const char *Format, ...)
856 Conn_WriteStr(Idx, Format, va_alist)
862 char buffer[COMMAND_LEN];
867 assert( Idx > NONE );
868 assert( Format != NULL );
871 va_start( ap, Format );
875 if (vsnprintf( buffer, COMMAND_LEN - 2, Format, ap ) >= COMMAND_LEN - 2 ) {
877 * The string that should be written to the socket is longer
878 * than the allowed size of COMMAND_LEN bytes (including both
879 * the CR and LF characters). This can be caused by the
880 * IRC_WriteXXX() functions when the prefix of this server had
881 * to be added to an already "quite long" command line which
882 * has been received from a regular IRC client, for example.
884 * We are not allowed to send such "oversized" messages to
885 * other servers and clients, see RFC 2812 2.3 and 2813 3.3
886 * ("these messages SHALL NOT exceed 512 characters in length,
887 * counting all characters including the trailing CR-LF").
889 * So we have a big problem here: we should send more bytes
890 * to the network than we are allowed to and we don't know
891 * the originator (any more). The "old" behaviour of blaming
892 * the receiver ("next hop") is a bad idea (it could be just
893 * an other server only routing the message!), so the only
894 * option left is to shorten the string and to hope that the
895 * result is still somewhat useful ...
899 strcpy (buffer + sizeof(buffer) - strlen(CUT_TXTSUFFIX) - 2 - 1,
905 Log(LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer);
908 len = strlcat( buffer, "\r\n", sizeof( buffer ));
909 ok = Conn_Write(Idx, buffer, len);
910 My_Connections[Idx].msg_out++;
914 } /* Conn_WriteStr */
918 * Append Data to the outbound write buffer of a connection.
920 * @param Idx Index of the connection.
921 * @param Data pointer to the data.
922 * @param Len length of Data.
923 * @returns true on success, false otherwise.
926 Conn_Write( CONN_ID Idx, char *Data, size_t Len )
929 size_t writebuf_limit = WRITEBUFFER_MAX_LEN;
930 assert( Idx > NONE );
931 assert( Data != NULL );
934 c = Conn_GetClient(Idx);
937 /* Servers do get special write buffer limits, so they can generate
938 * all the messages that are required while peering. */
939 if (Client_Type(c) == CLIENT_SERVER)
940 writebuf_limit = WRITEBUFFER_SLINK_LEN;
942 /* Is the socket still open? A previous call to Conn_Write()
943 * may have closed the connection due to a fatal error.
944 * In this case it is sufficient to return an error, as well. */
945 if( My_Connections[Idx].sock <= NONE ) {
946 LogDebug("Skipped write on closed socket (connection %d).", Idx);
951 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
953 * Zip_Buffer() does all the dirty work for us: it flushes
954 * the (pre-)compression buffers if required and handles
955 * all error conditions. */
956 if (!Zip_Buffer(Idx, Data, Len))
962 /* Uncompressed link:
963 * Check if outbound buffer has enough space for the data. */
964 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
965 WRITEBUFFER_FLUSH_LEN) {
966 /* Buffer is full, flush it. Handle_Write deals with
967 * low-level errors, if any. */
968 if (!Handle_Write(Idx))
972 /* When the write buffer is still too big after flushing it,
973 * the connection will be killed. */
974 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
977 "Write buffer space exhausted (connection %d, limit is %lu bytes, %lu bytes new, %lu bytes pending)",
978 Idx, writebuf_limit, Len,
979 (unsigned long)array_bytes(&My_Connections[Idx].wbuf));
980 Conn_Close(Idx, "Write buffer space exhausted", NULL, false);
984 /* Copy data to write buffer */
985 if (!array_catb(&My_Connections[Idx].wbuf, Data, Len))
988 My_Connections[Idx].bytes_out += Len;
991 /* Adjust global write counter */
999 * Shut down a connection.
1001 * @param Idx Connection index.
1002 * @param LogMsg Message to write to the log or NULL. If no LogMsg
1003 * is given, the FwdMsg is logged.
1004 * @param FwdMsg Message to forward to remote servers.
1005 * @param InformClient If true, inform the client on the connection which is
1006 * to be shut down of the reason (FwdMsg) and send
1007 * connection statistics before disconnecting it.
1010 Conn_Close( CONN_ID Idx, const char *LogMsg, const char *FwdMsg, bool InformClient )
1012 /* Close connection. Open pipes of asyncronous resolver
1013 * sub-processes are closed down. */
1019 double in_z_k, out_z_k;
1023 assert( Idx > NONE );
1025 /* Is this link already shutting down? */
1026 if( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ISCLOSING )) {
1027 /* Conn_Close() has been called recursively for this link;
1028 * probabe reason: Handle_Write() failed -- see below. */
1029 LogDebug("Recursive request to close connection: %d", Idx );
1033 assert( My_Connections[Idx].sock > NONE );
1035 /* Mark link as "closing" */
1036 Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCLOSING );
1038 port = ng_ipaddr_getport(&My_Connections[Idx].addr);
1039 Log(LOG_INFO, "Shutting down connection %d (%s) with %s:%d ...", Idx,
1040 LogMsg ? LogMsg : FwdMsg, My_Connections[Idx].host, port);
1042 /* Search client, if any */
1043 c = Conn_GetClient( Idx );
1045 /* Should the client be informed? */
1048 /* Send statistics to client if registered as user: */
1049 if ((c != NULL) && (Client_Type(c) == CLIENT_USER)) {
1051 ":%s NOTICE %s :%sConnection statistics: client %.1f kb, server %.1f kb.",
1052 Client_ID(Client_ThisServer()), Client_ID(c),
1054 (double)My_Connections[Idx].bytes_in / 1024,
1055 (double)My_Connections[Idx].bytes_out / 1024);
1058 /* Send ERROR to client (see RFC 2812, section 3.1.7) */
1060 Conn_WriteStr(Idx, "ERROR :%s", FwdMsg);
1062 Conn_WriteStr(Idx, "ERROR :Closing connection");
1065 /* Try to write out the write buffer. Note: Handle_Write() eventually
1066 * removes the CLIENT structure associated with this connection if an
1067 * error occurs! So we have to re-check if there is still an valid
1068 * CLIENT structure after calling Handle_Write() ...*/
1069 (void)Handle_Write( Idx );
1071 /* Search client, if any (re-check!) */
1072 c = Conn_GetClient( Idx );
1074 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_SSL )) {
1075 Log(LOG_INFO, "SSL connection %d shutting down ...", Idx);
1076 ConnSSL_Free(&My_Connections[Idx]);
1079 /* Shut down socket */
1080 if (! io_close(My_Connections[Idx].sock)) {
1081 /* Oops, we can't close the socket!? This is ... ugly! */
1083 "Error closing connection %d (socket %d) with %s:%d - %s! (ignored)",
1084 Idx, My_Connections[Idx].sock, My_Connections[Idx].host,
1085 port, strerror(errno));
1088 /* Mark socket as invalid: */
1089 My_Connections[Idx].sock = NONE;
1091 /* If there is still a client, unregister it now */
1093 Client_Destroy(c, LogMsg, FwdMsg, true);
1095 /* Calculate statistics and log information */
1096 in_k = (double)My_Connections[Idx].bytes_in / 1024;
1097 out_k = (double)My_Connections[Idx].bytes_out / 1024;
1099 if (Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP)) {
1100 in_z_k = (double)My_Connections[Idx].zip.bytes_in / 1024;
1101 out_z_k = (double)My_Connections[Idx].zip.bytes_out / 1024;
1102 /* Make sure that no division by zero can occur during
1103 * the calculation of in_p and out_p: in_z_k and out_z_k
1104 * are non-zero, that's guaranteed by the protocol until
1105 * compression can be enabled. */
1110 in_p = (int)(( in_k * 100 ) / in_z_k );
1111 out_p = (int)(( out_k * 100 ) / out_z_k );
1113 "Connection %d with %s:%d closed (in: %.1fk/%.1fk/%d%%, out: %.1fk/%.1fk/%d%%).",
1114 Idx, My_Connections[Idx].host, port,
1115 in_k, in_z_k, in_p, out_k, out_z_k, out_p);
1121 "Connection %d with %s:%d closed (in: %.1fk, out: %.1fk).",
1122 Idx, My_Connections[Idx].host, port,
1126 /* Servers: Modify time of next connect attempt? */
1127 Conf_UnsetServer( Idx );
1130 /* Clean up zlib, if link was compressed */
1131 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
1132 inflateEnd( &My_Connections[Idx].zip.in );
1133 deflateEnd( &My_Connections[Idx].zip.out );
1134 array_free(&My_Connections[Idx].zip.rbuf);
1135 array_free(&My_Connections[Idx].zip.wbuf);
1139 array_free(&My_Connections[Idx].rbuf);
1140 array_free(&My_Connections[Idx].wbuf);
1142 /* Clean up connection structure (=free it) */
1143 Init_Conn_Struct( Idx );
1145 assert(NumConnections > 0);
1148 LogDebug("Shutdown of connection %d completed, %ld connection%s left.",
1149 Idx, NumConnections, NumConnections != 1 ? "s" : "");
1154 * Get current number of connections.
1156 * @returns Number of current connections.
1161 return NumConnections;
1166 * Get number of maximum simultaneous connections.
1168 * @returns Number of maximum simultaneous connections.
1173 return NumConnectionsMax;
1174 } /* Conn_CountMax */
1178 * Get number of connections accepted since the daemon startet.
1180 * @returns Number of connections accepted.
1183 Conn_CountAccepted(void)
1185 return NumConnectionsAccepted;
1186 } /* Conn_CountAccepted */
1190 * Synchronize established connections and configured server structures
1191 * after a configuration update and store the correct connection IDs, if any.
1194 Conn_SyncServerStruct(void)
1200 for (i = 0; i < Pool_Size; i++) {
1201 if (My_Connections[i].sock == NONE)
1205 client = Conn_GetClient(i);
1206 if (!client || Client_Type(client) != CLIENT_SERVER)
1209 for (c = 0; c < MAX_SERVERS; c++) {
1210 /* Configured server? */
1211 if (!Conf_Server[c].host[0])
1214 if (strcasecmp(Conf_Server[c].name, Client_ID(client)) == 0)
1215 Conf_Server[c].conn_id = i;
1218 } /* SyncServerStruct */
1222 * Send out data of write buffer; connect new sockets.
1224 * @param Idx Connection index.
1225 * @returns true on success, false otherwise.
1228 Handle_Write( CONN_ID Idx )
1233 assert( Idx > NONE );
1234 if ( My_Connections[Idx].sock < 0 ) {
1235 LogDebug("Handle_Write() on closed socket, connection %d", Idx);
1238 assert( My_Connections[Idx].sock > NONE );
1240 wdatalen = array_bytes(&My_Connections[Idx].wbuf );
1243 if (wdatalen == 0) {
1244 /* Write buffer is empty, so we try to flush the compression
1245 * buffer and get some data to work with from there :-) */
1246 if (!Zip_Flush(Idx))
1249 /* Now the write buffer most probably has changed: */
1250 wdatalen = array_bytes(&My_Connections[Idx].wbuf);
1254 if (wdatalen == 0) {
1255 /* Still no data, fine. */
1256 io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
1262 ("Handle_Write() called for connection %d, %ld bytes pending ...",
1267 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_SSL )) {
1268 len = ConnSSL_Write(&My_Connections[Idx], array_start(&My_Connections[Idx].wbuf), wdatalen);
1272 len = write(My_Connections[Idx].sock,
1273 array_start(&My_Connections[Idx].wbuf), wdatalen );
1276 if (errno == EAGAIN || errno == EINTR)
1279 Log(LOG_ERR, "Write error on connection %d (socket %d): %s!",
1280 Idx, My_Connections[Idx].sock, strerror(errno));
1281 Conn_Close(Idx, "Write error!", NULL, false);
1285 /* move any data not yet written to beginning */
1286 array_moveleft(&My_Connections[Idx].wbuf, 1, (size_t)len);
1289 } /* Handle_Write */
1293 * Count established connections to a specific IP address.
1295 * @returns Number of established connections.
1298 Count_Connections(ng_ipaddr_t *a)
1303 for (i = 0; i < Pool_Size; i++) {
1304 if (My_Connections[i].sock <= NONE)
1306 if (ng_ipaddr_ipequal(&My_Connections[i].addr, a))
1310 } /* Count_Connections */
1314 * Initialize new client connection on a listening socket.
1316 * @param Sock Listening socket descriptor.
1317 * @returns Accepted socket descriptor or -1 on error.
1320 New_Connection(int Sock)
1323 struct request_info req;
1325 ng_ipaddr_t new_addr;
1326 char ip_str[NG_INET_ADDRSTRLEN];
1327 int new_sock, new_sock_len, identsock;
1331 assert(Sock > NONE);
1333 LogDebug("Accepting new connection on socket %d ...", Sock);
1335 new_sock_len = (int)sizeof(new_addr);
1336 new_sock = accept(Sock, (struct sockaddr *)&new_addr,
1337 (socklen_t *)&new_sock_len);
1339 Log(LOG_CRIT, "Can't accept connection: %s!", strerror(errno));
1342 NumConnectionsAccepted++;
1344 if (!ng_ipaddr_tostr_r(&new_addr, ip_str)) {
1345 Log(LOG_CRIT, "fd %d: Can't convert IP address!", new_sock);
1346 Simple_Message(new_sock, "ERROR :Internal Server Error");
1352 /* Validate socket using TCP Wrappers */
1353 request_init(&req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock,
1354 RQ_CLIENT_SIN, &new_addr, NULL);
1356 if (!hosts_access(&req)) {
1358 "Refused connection from %s (by TCP Wrappers)!", ip_str);
1359 Simple_Message(new_sock, "ERROR :Connection refused");
1365 if (!Init_Socket(new_sock))
1368 /* Check global connection limit */
1369 if ((Conf_MaxConnections > 0) &&
1370 (NumConnections >= (size_t) Conf_MaxConnections)) {
1371 Log(LOG_ALERT, "Can't accept connection: limit (%d) reached!",
1372 Conf_MaxConnections);
1373 Simple_Message(new_sock, "ERROR :Connection limit reached");
1378 /* Check IP-based connection limit */
1379 cnt = Count_Connections(&new_addr);
1380 if ((Conf_MaxConnectionsIP > 0) && (cnt >= Conf_MaxConnectionsIP)) {
1381 /* Access denied, too many connections from this IP address! */
1383 "Refused connection from %s: too may connections (%ld) from this IP address!",
1385 Simple_Message(new_sock,
1386 "ERROR :Connection refused, too many connections from your IP address");
1391 if (new_sock >= Pool_Size) {
1392 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION),
1393 (size_t) new_sock)) {
1395 "Can't allocate memory! [New_Connection]");
1396 Simple_Message(new_sock, "ERROR: Internal error");
1400 LogDebug("Bumped connection pool to %ld items (internal: %ld items, %ld bytes)",
1401 new_sock, array_length(&My_ConnArray,
1402 sizeof(CONNECTION)), array_bytes(&My_ConnArray));
1404 /* Adjust pointer to new block */
1405 My_Connections = array_start(&My_ConnArray);
1406 while (Pool_Size <= new_sock)
1407 Init_Conn_Struct(Pool_Size++);
1410 /* register callback */
1411 if (!io_event_create(new_sock, IO_WANTREAD, cb_clientserver)) {
1413 "Can't accept connection: io_event_create failed!");
1414 Simple_Message(new_sock, "ERROR :Internal error");
1419 c = Client_NewLocal(new_sock, ip_str, CLIENT_UNKNOWN, false);
1422 "Can't accept connection: can't create client structure!");
1423 Simple_Message(new_sock, "ERROR :Internal error");
1428 Init_Conn_Struct(new_sock);
1429 My_Connections[new_sock].sock = new_sock;
1430 My_Connections[new_sock].addr = new_addr;
1431 My_Connections[new_sock].client = c;
1433 /* Set initial hostname to IP address. This becomes overwritten when
1434 * the DNS lookup is enabled and succeeds, but is used otherwise. */
1435 if (ng_ipaddr_af(&new_addr) != AF_INET)
1436 snprintf(My_Connections[new_sock].host,
1437 sizeof(My_Connections[new_sock].host), "[%s]", ip_str);
1439 strlcpy(My_Connections[new_sock].host, ip_str,
1440 sizeof(My_Connections[new_sock].host));
1442 Client_SetHostname(c, My_Connections[new_sock].host);
1444 Log(LOG_INFO, "Accepted connection %d from %s:%d on socket %d.",
1445 new_sock, My_Connections[new_sock].host,
1446 ng_ipaddr_getport(&new_addr), Sock);
1448 identsock = new_sock;
1454 if (Conf_NoticeAuth) {
1457 (void)Conn_WriteStr(new_sock,
1458 "NOTICE AUTH :*** Looking up your hostname and checking ident");
1461 (void)Conn_WriteStr(new_sock,
1462 "NOTICE AUTH :*** Looking up your hostname");
1464 Resolve_Addr(&My_Connections[new_sock].proc_stat, &new_addr,
1465 identsock, cb_Read_Resolver_Result);
1468 Account_Connection();
1470 } /* New_Connection */
1474 * Update global connection counters.
1477 Account_Connection(void)
1480 if (NumConnections > NumConnectionsMax)
1481 NumConnectionsMax = NumConnections;
1482 LogDebug("Total number of connections now %lu (max %lu).",
1483 NumConnections, NumConnectionsMax);
1484 } /* Account_Connection */
1488 * Translate socket handle into connection index.
1490 * @param Sock Socket handle.
1491 * @returns Connecion index or NONE, if no connection could be found.
1494 Socket2Index( int Sock )
1496 assert( Sock >= 0 );
1498 if( Sock >= Pool_Size || My_Connections[Sock].sock != Sock ) {
1499 /* the Connection was already closed again, likely due to
1501 LogDebug("Socket2Index: can't get connection for socket %d!", Sock);
1505 } /* Socket2Index */
1509 * Read data from the network to the read buffer. If an error occures,
1510 * the socket of this connection will be shut down.
1512 * @param Idx Connection index.
1515 Read_Request( CONN_ID Idx )
1518 static const unsigned int maxbps = COMMAND_LEN / 2;
1519 char readbuf[READBUFFER_LEN];
1522 assert( Idx > NONE );
1523 assert( My_Connections[Idx].sock > NONE );
1526 if ((array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN) ||
1527 (array_bytes(&My_Connections[Idx].zip.rbuf) >= READBUFFER_LEN))
1529 if (array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN)
1532 /* Read buffer is full */
1534 "Receive buffer space exhausted (connection %d): %d bytes",
1535 Idx, array_bytes(&My_Connections[Idx].rbuf));
1536 Conn_Close(Idx, "Receive buffer space exhausted", NULL, false);
1541 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_SSL))
1542 len = ConnSSL_Read( &My_Connections[Idx], readbuf, sizeof(readbuf));
1545 len = read(My_Connections[Idx].sock, readbuf, sizeof(readbuf));
1547 Log(LOG_INFO, "%s:%u (%s) is closing the connection ...",
1548 My_Connections[Idx].host,
1549 (unsigned int) ng_ipaddr_getport(&My_Connections[Idx].addr),
1550 ng_ipaddr_tostr(&My_Connections[Idx].addr));
1552 "Socket closed!", "Client closed connection",
1558 if( errno == EAGAIN ) return;
1559 Log(LOG_ERR, "Read error on connection %d (socket %d): %s!",
1560 Idx, My_Connections[Idx].sock, strerror(errno));
1561 Conn_Close(Idx, "Read error!", "Client closed connection",
1566 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1567 if (!array_catb(&My_Connections[Idx].zip.rbuf, readbuf,
1570 "Could not append recieved data to zip input buffer (connn %d): %d bytes!",
1572 Conn_Close(Idx, "Receive buffer space exhausted", NULL,
1579 if (!array_catb( &My_Connections[Idx].rbuf, readbuf, len)) {
1580 Log( LOG_ERR, "Could not append recieved data to input buffer (connn %d): %d bytes!", Idx, len );
1581 Conn_Close(Idx, "Receive buffer space exhausted", NULL, false );
1585 /* Update connection statistics */
1586 My_Connections[Idx].bytes_in += len;
1587 My_Connections[Idx].bps += Handle_Buffer(Idx);
1589 /* Make sure that there is still a valid client registered */
1590 c = Conn_GetClient(Idx);
1594 /* Update timestamp of last data received if this connection is
1595 * registered as a user, server or service connection. Don't update
1596 * otherwise, so users have at least Conf_PongTimeout seconds time to
1597 * register with the IRC server -- see Check_Connections().
1598 * Update "lastping", too, if time shifted backwards ... */
1599 if (Client_Type(c) == CLIENT_USER
1600 || Client_Type(c) == CLIENT_SERVER
1601 || Client_Type(c) == CLIENT_SERVICE) {
1603 if (My_Connections[Idx].lastdata != t)
1604 My_Connections[Idx].bps = 0;
1606 My_Connections[Idx].lastdata = t;
1607 if (My_Connections[Idx].lastping > t)
1608 My_Connections[Idx].lastping = t;
1611 /* Look at the data in the (read-) buffer of this connection */
1612 if (Client_Type(c) != CLIENT_SERVER
1613 && Client_Type(c) != CLIENT_UNKNOWNSERVER
1614 && Client_Type(c) != CLIENT_SERVICE
1615 && My_Connections[Idx].bps >= maxbps) {
1616 LogDebug("Throttling connection %d: BPS exceeded! (%u >= %u)",
1617 Idx, My_Connections[Idx].bps, maxbps);
1618 Conn_SetPenalty(Idx, 1);
1620 } /* Read_Request */
1624 * Handle all data in the connection read-buffer.
1626 * Data is processed until no complete command is left in the read buffer,
1627 * or MAX_COMMANDS[_SERVER|_SERVICE] commands were processed.
1628 * When a fatal error occurs, the connection is shut down.
1630 * @param Idx Index of the connection.
1631 * @returns Number of bytes processed.
1634 Handle_Buffer(CONN_ID Idx)
1637 char *ptr1, *ptr2, *first_eol;
1645 unsigned int i, maxcmd = MAX_COMMANDS, len_processed = 0;
1648 c = Conn_GetClient(Idx);
1649 starttime = time(NULL);
1653 /* Servers do get special command limits, so they can process
1654 * all the messages that are required while peering. */
1655 switch (Client_Type(c)) {
1657 /* Allow servers to send more commands in the first 10 secods
1658 * to speed up server login and network synchronisation. */
1659 if (starttime - Client_StartTime(c) < 10)
1660 maxcmd = MAX_COMMANDS_SERVER * 5;
1662 maxcmd = MAX_COMMANDS_SERVER;
1664 case CLIENT_SERVICE:
1665 maxcmd = MAX_COMMANDS_SERVICE; break;
1668 for (i=0; i < maxcmd; i++) {
1670 if (My_Connections[Idx].delaytime > starttime)
1673 /* Unpack compressed data, if compression is in use */
1674 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1675 /* When unzipping fails, Unzip_Buffer() shuts
1676 * down the connection itself */
1677 if (!Unzip_Buffer(Idx))
1682 if (0 == array_bytes(&My_Connections[Idx].rbuf))
1685 /* Make sure that the buffer is NULL terminated */
1686 if (!array_cat0_temporary(&My_Connections[Idx].rbuf)) {
1687 Conn_Close(Idx, NULL,
1688 "Can't allocate memory [Handle_Buffer]",
1693 /* RFC 2812, section "2.3 Messages", 5th paragraph:
1694 * "IRC messages are always lines of characters terminated
1695 * with a CR-LF (Carriage Return - Line Feed) pair [...]". */
1697 ptr = strstr(array_start(&My_Connections[Idx].rbuf), "\r\n");
1700 /* Check for non-RFC-compliant request (only CR or LF)?
1701 * Unfortunately, there are quite a few clients out there
1702 * that do this -- e. g. mIRC, BitchX, and Trillian :-( */
1703 ptr1 = strchr(array_start(&My_Connections[Idx].rbuf), '\r');
1704 ptr2 = strchr(array_start(&My_Connections[Idx].rbuf), '\n');
1706 /* Check if there is a single CR or LF _before_ the
1707 * corerct CR+LF line terminator: */
1708 first_eol = ptr1 < ptr2 ? ptr1 : ptr2;
1709 if (first_eol < ptr) {
1710 /* Single CR or LF before CR+LF found */
1714 } else if (ptr1 || ptr2) {
1715 /* No CR+LF terminated command found, but single
1716 * CR or LF found ... */
1718 ptr = ptr1 < ptr2 ? ptr1 : ptr2;
1720 ptr = ptr1 ? ptr1 : ptr2;
1728 /* Complete (=line terminated) request found, handle it! */
1731 len = ptr - (char *)array_start(&My_Connections[Idx].rbuf) + delta;
1733 if (len > (COMMAND_LEN - 1)) {
1734 /* Request must not exceed 512 chars (incl. CR+LF!),
1735 * see RFC 2812. Disconnect Client if this happens. */
1737 "Request too long (connection %d): %d bytes (max. %d expected)!",
1738 Idx, array_bytes(&My_Connections[Idx].rbuf),
1740 Conn_Close(Idx, NULL, "Request too long", true);
1744 len_processed += (unsigned int)len;
1746 /* Request is empty (only '\r\n', '\r' or '\n');
1747 * delta is 2 ('\r\n') or 1 ('\r' or '\n'), see above */
1748 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1752 /* remember if stream is already compressed */
1753 old_z = My_Connections[Idx].options & CONN_ZIP;
1756 My_Connections[Idx].msg_in++;
1758 (Idx, (char *)array_start(&My_Connections[Idx].rbuf)))
1759 return 0; /* error -> connection has been closed */
1761 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1763 LogDebug("Connection %d: %d bytes left in read buffer.",
1764 Idx, array_bytes(&My_Connections[Idx].rbuf));
1767 if ((!old_z) && (My_Connections[Idx].options & CONN_ZIP) &&
1768 (array_bytes(&My_Connections[Idx].rbuf) > 0)) {
1769 /* The last command activated socket compression.
1770 * Data that was read after that needs to be copied
1771 * to the unzip buffer for decompression: */
1773 (&My_Connections[Idx].zip.rbuf,
1774 &My_Connections[Idx].rbuf)) {
1775 Conn_Close(Idx, NULL,
1776 "Can't allocate memory [Handle_Buffer]",
1781 array_trunc(&My_Connections[Idx].rbuf);
1783 ("Moved already received data (%u bytes) to uncompression buffer.",
1784 array_bytes(&My_Connections[Idx].zip.rbuf));
1788 return len_processed;
1789 } /* Handle_Buffer */
1793 * Check whether established connections are still alive or not.
1794 * If not, play PING-PONG first; and if that doesn't help either,
1795 * disconnect the respective peer.
1798 Check_Connections(void)
1804 for (i = 0; i < Pool_Size; i++) {
1805 if (My_Connections[i].sock < 0)
1808 c = Conn_GetClient(i);
1809 if (c && ((Client_Type(c) == CLIENT_USER)
1810 || (Client_Type(c) == CLIENT_SERVER)
1811 || (Client_Type(c) == CLIENT_SERVICE))) {
1812 /* connected User, Server or Service */
1813 if (My_Connections[i].lastping >
1814 My_Connections[i].lastdata) {
1815 /* We already sent a ping */
1816 if (My_Connections[i].lastping <
1817 time(NULL) - Conf_PongTimeout) {
1820 ("Connection %d: Ping timeout: %d seconds.",
1821 i, Conf_PongTimeout);
1822 snprintf(msg, sizeof(msg), "Ping timeout: %d seconds", Conf_PongTimeout);
1823 Conn_Close(i, NULL, msg, true);
1825 } else if (My_Connections[i].lastdata <
1826 time(NULL) - Conf_PingTimeout) {
1827 /* We need to send a PING ... */
1828 LogDebug("Connection %d: sending PING ...", i);
1829 My_Connections[i].lastping = time(NULL);
1830 Conn_WriteStr(i, "PING :%s",
1831 Client_ID(Client_ThisServer()));
1834 /* The connection is not fully established yet, so
1835 * we don't do the PING-PONG game here but instead
1836 * disconnect the client after "a short time" if it's
1837 * still not registered. */
1839 if (My_Connections[i].lastdata <
1840 time(NULL) - Conf_PongTimeout) {
1842 ("Unregistered connection %d timed out ...",
1844 Conn_Close(i, NULL, "Timeout", false);
1848 } /* Check_Connections */
1852 * Check if further server links should be established.
1860 time_now = time(NULL);
1862 /* Check all configured servers */
1863 for (i = 0; i < MAX_SERVERS; i++) {
1864 if (Conf_Server[i].conn_id != NONE)
1865 continue; /* Already establishing or connected */
1866 if (!Conf_Server[i].host[0] || !Conf_Server[i].port > 0)
1867 continue; /* No host and/or port configured */
1868 if (Conf_Server[i].flags & CONF_SFLAG_DISABLED)
1869 continue; /* Disabled configuration entry */
1870 if (Conf_Server[i].lasttry > (time_now - Conf_ConnectRetry))
1871 continue; /* We have to wait a little bit ... */
1873 /* Is there already a connection in this group? */
1874 if (Conf_Server[i].group > NONE) {
1875 for (n = 0; n < MAX_SERVERS; n++) {
1878 if ((Conf_Server[n].conn_id != NONE) &&
1879 (Conf_Server[n].group == Conf_Server[i].group))
1882 if (n < MAX_SERVERS)
1886 /* Okay, try to connect now */
1888 "Preparing to establish a new server link for \"%s\" ...",
1889 Conf_Server[i].name);
1890 Conf_Server[i].lasttry = time_now;
1891 Conf_Server[i].conn_id = SERVER_WAIT;
1892 assert(Proc_GetPipeFd(&Conf_Server[i].res_stat) < 0);
1893 Resolve_Name(&Conf_Server[i].res_stat, Conf_Server[i].host,
1894 cb_Connect_to_Server);
1896 } /* Check_Servers */
1900 * Establish a new outgoing server connection.
1902 * @param Server Configuration index of the server.
1903 * @param dest Destination IP address to connect to.
1906 New_Server( int Server , ng_ipaddr_t *dest)
1908 /* Establish new server link */
1909 char ip_str[NG_INET_ADDRSTRLEN];
1910 int af_dest, res, new_sock;
1913 assert( Server > NONE );
1915 if (!ng_ipaddr_tostr_r(dest, ip_str)) {
1916 Log(LOG_WARNING, "New_Server: Could not convert IP to string");
1920 af_dest = ng_ipaddr_af(dest);
1921 new_sock = socket(af_dest, SOCK_STREAM, 0);
1924 "Establishing connection for \"%s\" to \"%s:%d\" (%s), socket %d ...",
1925 Conf_Server[Server].name, Conf_Server[Server].host,
1926 Conf_Server[Server].port, ip_str, new_sock);
1929 Log(LOG_CRIT, "Can't create socket (af %d): %s!",
1930 af_dest, strerror(errno));
1934 if (!Init_Socket(new_sock))
1937 /* is a bind address configured? */
1938 res = ng_ipaddr_af(&Conf_Server[Server].bind_addr);
1939 /* if yes, bind now. If it fails, warn and let connect() pick a source address */
1940 if (res && bind(new_sock, (struct sockaddr *) &Conf_Server[Server].bind_addr,
1941 ng_ipaddr_salen(&Conf_Server[Server].bind_addr)))
1943 ng_ipaddr_tostr_r(&Conf_Server[Server].bind_addr, ip_str);
1944 Log(LOG_WARNING, "Can't bind socket to %s: %s!", ip_str, strerror(errno));
1946 ng_ipaddr_setport(dest, Conf_Server[Server].port);
1947 res = connect(new_sock, (struct sockaddr *) dest, ng_ipaddr_salen(dest));
1948 if(( res != 0 ) && ( errno != EINPROGRESS )) {
1949 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1954 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)new_sock)) {
1956 "Cannot allocate memory for server connection (socket %d)",
1962 if (!io_event_create( new_sock, IO_WANTWRITE, cb_connserver)) {
1963 Log(LOG_ALERT, "io_event_create(): could not add fd %d", strerror(errno));
1968 My_Connections = array_start(&My_ConnArray);
1970 assert(My_Connections[new_sock].sock <= 0);
1972 Init_Conn_Struct(new_sock);
1974 ng_ipaddr_tostr_r(dest, ip_str);
1975 c = Client_NewLocal(new_sock, ip_str, CLIENT_UNKNOWNSERVER, false);
1977 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1982 /* Conn_Close() decrements this counter again */
1983 Account_Connection();
1984 Client_SetIntroducer( c, c );
1985 Client_SetToken( c, TOKEN_OUTBOUND );
1987 /* Register connection */
1988 Conf_Server[Server].conn_id = new_sock;
1989 My_Connections[new_sock].sock = new_sock;
1990 My_Connections[new_sock].addr = *dest;
1991 My_Connections[new_sock].client = c;
1992 strlcpy( My_Connections[new_sock].host, Conf_Server[Server].host,
1993 sizeof(My_Connections[new_sock].host ));
1996 if (Conf_Server[Server].SSLConnect && !ConnSSL_PrepareConnect( &My_Connections[new_sock],
1997 &Conf_Server[Server] ))
1999 Log(LOG_ALERT, "Could not initialize SSL for outgoing connection");
2000 Conn_Close( new_sock, "Could not initialize SSL for outgoing connection", NULL, false );
2001 Init_Conn_Struct( new_sock );
2002 Conf_Server[Server].conn_id = NONE;
2006 LogDebug("Registered new connection %d on socket %d (%ld in total).",
2007 new_sock, My_Connections[new_sock].sock, NumConnections);
2008 Conn_OPTION_ADD( &My_Connections[new_sock], CONN_ISCONNECTING );
2013 * Initialize connection structure.
2015 * @param Idx Connection index.
2018 Init_Conn_Struct(CONN_ID Idx)
2020 time_t now = time(NULL);
2022 memset(&My_Connections[Idx], 0, sizeof(CONNECTION));
2023 My_Connections[Idx].sock = -1;
2024 My_Connections[Idx].signon = now;
2025 My_Connections[Idx].lastdata = now;
2026 My_Connections[Idx].lastprivmsg = now;
2027 Proc_InitStruct(&My_Connections[Idx].proc_stat);
2028 } /* Init_Conn_Struct */
2032 * Initialize options of a new socket.
2034 * For example, we try to set socket options SO_REUSEADDR and IPTOS_LOWDELAY.
2035 * The socket is automatically closed if a fatal error is encountered.
2037 * @param Sock Socket handle.
2038 * @returns false if socket was closed due to fatal error.
2041 Init_Socket( int Sock )
2045 if (!io_setnonblock(Sock)) {
2046 Log( LOG_CRIT, "Can't enable non-blocking mode for socket: %s!", strerror( errno ));
2051 /* Don't block this port after socket shutdown */
2053 if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &value, (socklen_t)sizeof( value )) != 0 )
2055 Log( LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!", strerror( errno ));
2056 /* ignore this error */
2059 /* Set type of service (TOS) */
2060 #if defined(IPPROTO_IP) && defined(IPTOS_LOWDELAY)
2061 value = IPTOS_LOWDELAY;
2062 if (setsockopt(Sock, IPPROTO_IP, IP_TOS, &value,
2063 (socklen_t) sizeof(value))) {
2064 LogDebug("Can't set socket option IP_TOS: %s!",
2066 /* ignore this error */
2068 LogDebug("IP_TOS on socket %d has been set to IPTOS_LOWDELAY.",
2077 * Read results of a resolver sub-process and try to initiate a new server
2080 * @param fd File descriptor of the pipe to the sub-process.
2081 * @param events (ignored IO specification)
2084 cb_Connect_to_Server(int fd, UNUSED short events)
2086 /* Read result of resolver sub-process from pipe and start connection */
2089 ng_ipaddr_t dest_addrs[4]; /* we can handle at most 3; but we read up to
2090 four so we can log the 'more than we can handle'
2091 condition. First result is tried immediately, rest
2092 is saved for later if needed. */
2094 LogDebug("Resolver: Got forward lookup callback on fd %d, events %d", fd, events);
2096 for (i=0; i < MAX_SERVERS; i++) {
2097 if (Proc_GetPipeFd(&Conf_Server[i].res_stat) == fd )
2101 if( i >= MAX_SERVERS) {
2102 /* Ops, no matching server found?! */
2104 LogDebug("Resolver: Got Forward Lookup callback for unknown server!?");
2108 /* Read result from pipe */
2109 len = Proc_Read(&Conf_Server[i].res_stat, dest_addrs, sizeof(dest_addrs));
2110 Proc_Close(&Conf_Server[i].res_stat);
2112 /* Error resolving hostname: reset server structure */
2113 Conf_Server[i].conn_id = NONE;
2117 assert((len % sizeof(ng_ipaddr_t)) == 0);
2119 LogDebug("Got result from resolver: %u structs (%u bytes).", len/sizeof(ng_ipaddr_t), len);
2121 memset(&Conf_Server[i].dst_addr, 0, sizeof(Conf_Server[i].dst_addr));
2122 if (len > sizeof(ng_ipaddr_t)) {
2123 /* more than one address for this hostname, remember them
2124 * in case first address is unreachable/not available */
2125 len -= sizeof(ng_ipaddr_t);
2126 if (len > sizeof(Conf_Server[i].dst_addr)) {
2127 len = sizeof(Conf_Server[i].dst_addr);
2129 "Notice: Resolver returned more IP Addresses for host than we can handle, additional addresses dropped.");
2131 memcpy(&Conf_Server[i].dst_addr, &dest_addrs[1], len);
2134 New_Server(i, dest_addrs);
2135 } /* cb_Read_Forward_Lookup */
2139 * Read results of a resolver sub-process from the pipe and update the
2140 * apropriate connection/client structure(s): hostname and/or IDENT user name.
2142 * @param r_fd File descriptor of the pipe to the sub-process.
2143 * @param events (ignored IO specification)
2146 cb_Read_Resolver_Result( int r_fd, UNUSED short events )
2153 char readbuf[HOST_LEN + 2 + CLIENT_USER_LEN];
2155 char readbuf[HOST_LEN + 1];
2158 LogDebug("Resolver: Got callback on fd %d, events %d", r_fd, events );
2159 i = Conn_GetFromProc(r_fd);
2161 /* Ops, none found? Probably the connection has already
2162 * been closed!? We'll ignore that ... */
2164 LogDebug("Resolver: Got callback for unknown connection!?");
2168 /* Read result from pipe */
2169 len = Proc_Read(&My_Connections[i].proc_stat, readbuf, sizeof readbuf -1);
2170 Proc_Close(&My_Connections[i].proc_stat);
2174 readbuf[len] = '\0';
2175 identptr = strchr(readbuf, '\n');
2176 assert(identptr != NULL);
2178 Log( LOG_CRIT, "Resolver: Got malformed result!");
2183 LogDebug("Got result from resolver: \"%s\" (%u bytes read).", readbuf, len);
2184 /* Okay, we got a complete result: this is a host name for outgoing
2185 * connections and a host name and IDENT user name (if enabled) for
2186 * incoming connections.*/
2187 assert ( My_Connections[i].sock >= 0 );
2188 /* Incoming connection. Search client ... */
2189 c = Conn_GetClient( i );
2190 assert( c != NULL );
2192 /* Only update client information of unregistered clients.
2193 * Note: user commands (e. g. WEBIRC) are always read _after_ reading
2194 * the resolver results, so we don't have to worry to override settings
2195 * from these commands here. */
2196 if(Client_Type(c) == CLIENT_UNKNOWN) {
2197 strlcpy(My_Connections[i].host, readbuf,
2198 sizeof(My_Connections[i].host));
2199 Client_SetHostname(c, readbuf);
2200 if (Conf_NoticeAuth)
2201 (void)Conn_WriteStr(i,
2202 "NOTICE AUTH :*** Found your hostname");
2206 Log(LOG_INFO, "IDENT lookup for connection %d: \"%s\".", i, identptr);
2207 Client_SetUser(c, identptr, true);
2208 if (Conf_NoticeAuth)
2209 (void)Conn_WriteStr(i,
2210 "NOTICE AUTH :*** Got ident response");
2212 Log(LOG_INFO, "IDENT lookup for connection %d: no result.", i);
2213 if (Conf_NoticeAuth && Conf_Ident)
2214 (void)Conn_WriteStr(i,
2215 "NOTICE AUTH :*** No ident response");
2220 else Log( LOG_DEBUG, "Resolver: discarding result for already registered connection %d.", i );
2222 } /* cb_Read_Resolver_Result */
2226 * Write a "simple" (error) message to a socket.
2228 * The message is sent without using the connection write buffers, without
2229 * compression/encryption, and even without any error reporting. It is
2230 * designed for error messages of e.g. New_Connection().
2232 * @param Sock Socket handle.
2233 * @param Msg Message string to send.
2236 Simple_Message(int Sock, const char *Msg)
2238 char buf[COMMAND_LEN];
2241 assert(Sock > NONE);
2242 assert(Msg != NULL);
2244 strlcpy(buf, Msg, sizeof buf - 2);
2245 len = strlcat(buf, "\r\n", sizeof buf);
2246 if (write(Sock, buf, len) < 0) {
2247 /* Because this function most probably got called to log
2248 * an error message, any write error is ignored here to
2249 * avoid an endless loop. But casting the result of write()
2250 * to "void" doesn't satisfy the GNU C code attribute
2251 * "warn_unused_result" which is used by some versions of
2252 * glibc (e.g. 2.11.1), therefore this silly error
2253 * "handling" code here :-( */
2256 } /* Simple_Error */
2260 * Get CLIENT structure that belongs to a local connection identified by its
2261 * index number. Each connection belongs to a client by definition, so it is
2262 * not required that the caller checks for NULL return values.
2264 * @param Idx Connection index number.
2265 * @returns Pointer to CLIENT structure.
2268 Conn_GetClient( CONN_ID Idx )
2273 c = array_get(&My_ConnArray, sizeof (CONNECTION), (size_t)Idx);
2275 return c ? c->client : NULL;
2279 * Get PROC_STAT sub-process structure of a connection.
2281 * @param Idx Connection index number.
2282 * @returns PROC_STAT structure.
2285 Conn_GetProcStat(CONN_ID Idx)
2290 c = array_get(&My_ConnArray, sizeof (CONNECTION), (size_t)Idx);
2292 return &c->proc_stat;
2293 } /* Conn_GetProcStat */
2297 * Get CONN_ID from file descriptor associated to a subprocess structure.
2299 * @param fd File descriptor.
2300 * @returns CONN_ID or NONE (-1).
2303 Conn_GetFromProc(int fd)
2308 for (i = 0; i < Pool_Size; i++) {
2309 if ((My_Connections[i].sock != NONE)
2310 && (Proc_GetPipeFd(&My_Connections[i].proc_stat) == fd))
2314 } /* Conn_GetFromProc */
2320 Conn_GetAuthPing(CONN_ID Idx)
2322 assert (Idx != NONE);
2323 return My_Connections[Idx].auth_ping;
2324 } /* Conn_GetAuthPing */
2327 Conn_SetAuthPing(CONN_ID Idx, long ID)
2329 assert (Idx != NONE);
2330 My_Connections[Idx].auth_ping = ID;
2331 } /* Conn_SetAuthPing */
2339 * Get information about used SSL chiper.
2341 * @param Idx Connection index number.
2342 * @param buf Buffer for returned information text.
2343 * @param len Size of return buffer "buf".
2344 * @returns true on success, false otherwise.
2347 Conn_GetCipherInfo(CONN_ID Idx, char *buf, size_t len)
2351 assert(Idx < (int) array_length(&My_ConnArray, sizeof(CONNECTION)));
2352 return ConnSSL_GetCipherInfo(&My_Connections[Idx], buf, len);
2357 * Check if a connection is SSL-enabled or not.
2359 * @param Idx Connection index number.
2360 * @return true if connection is SSL-enabled, false otherwise.
2363 Conn_UsesSSL(CONN_ID Idx)
2367 assert(Idx < (int) array_length(&My_ConnArray, sizeof(CONNECTION)));
2368 return Conn_OPTION_ISSET(&My_Connections[Idx], CONN_SSL);
2377 * Dump internal state of the "connection module".
2380 Conn_DebugDump(void)
2384 Log(LOG_DEBUG, "Connection status:");
2385 for (i = 0; i < Pool_Size; i++) {
2386 if (My_Connections[i].sock == NONE)
2389 " - %d: host=%s, lastdata=%ld, lastping=%ld, delaytime=%ld, flag=%d, options=%d, bps=%d, client=%s",
2390 My_Connections[i].sock, My_Connections[i].host,
2391 My_Connections[i].lastdata, My_Connections[i].lastping,
2392 My_Connections[i].delaytime, My_Connections[i].flag,
2393 My_Connections[i].options, My_Connections[i].bps,
2394 My_Connections[i].client ? Client_ID(My_Connections[i].client) : "-");
2396 } /* Conn_DumpClients */