2 * ngIRCd -- The Next Generation IRC Daemon
3 * Copyright (c)2001-2005 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.
11 * Connection management
20 static char UNUSED id[] = "$Id: conn.c,v 1.189 2006/02/08 17:33:28 fw Exp $";
34 #include <sys/socket.h>
36 #include <sys/types.h>
38 #include <netinet/in.h>
40 #ifdef HAVE_NETINET_IP_H
41 # include <netinet/ip.h>
44 #ifdef HAVE_ARPA_INET_H
45 # include <arpa/inet.h>
47 # define PF_INET AF_INET
51 # include <stdint.h> /* e.g. for Mac OS X */
55 # include <tcpd.h> /* for TCP Wrappers */
70 #include "conn-func.h"
76 # include "rendezvous.h"
82 #define SERVER_WAIT (NONE - 1)
85 static bool Handle_Write PARAMS(( CONN_ID Idx ));
86 static int New_Connection PARAMS(( int Sock ));
87 static CONN_ID Socket2Index PARAMS(( int Sock ));
88 static void Read_Request PARAMS(( CONN_ID Idx ));
89 static bool Handle_Buffer PARAMS(( CONN_ID Idx ));
90 static void Check_Connections PARAMS(( void ));
91 static void Check_Servers PARAMS(( void ));
92 static void Init_Conn_Struct PARAMS(( CONN_ID Idx ));
93 static bool Init_Socket PARAMS(( int Sock ));
94 static void New_Server PARAMS(( int Server ));
95 static void Simple_Message PARAMS(( int Sock, char *Msg ));
96 static int Count_Connections PARAMS(( struct sockaddr_in addr ));
97 static int NewListener PARAMS(( const UINT16 Port ));
99 static array My_Listeners;
102 int allow_severity = LOG_INFO;
103 int deny_severity = LOG_ERR;
106 static void server_login PARAMS((CONN_ID idx));
108 static void cb_Read_Resolver_Result PARAMS(( int sock, UNUSED short what));
109 static void cb_Connect_to_Server PARAMS(( int sock, UNUSED short what));
110 static void cb_clientserver PARAMS((int sock, short what));
113 cb_listen(int sock, short irrelevant)
116 New_Connection( sock );
121 cb_connserver(int sock, UNUSED short what)
126 CONN_ID idx = Socket2Index( sock );
128 LogDebug("cb_connserver wants to write on unknown socket?!");
133 assert( what & IO_WANTWRITE);
135 /* connect() finished, get result. */
136 sock_len = sizeof( err );
137 res = getsockopt( My_Connections[idx].sock, SOL_SOCKET, SO_ERROR, &err, &sock_len );
138 assert( sock_len == sizeof( err ));
140 /* Error while connecting? */
141 if ((res != 0) || (err != 0)) {
143 Log(LOG_CRIT, "getsockopt (connection %d): %s!",
144 idx, strerror(errno));
147 "Can't connect socket to \"%s:%d\" (connection %d): %s!",
148 My_Connections[idx].host,
149 Conf_Server[Conf_GetServer(idx)].port,
152 /* Clean up the CLIENT structure (to avoid silly log
153 * messages) and call Conn_Close() to do the rest. */
154 c = Client_GetFromConn(idx);
156 Client_DestroyNow(c);
158 Conn_Close(idx, "Can't connect!", NULL, false);
163 Conn_OPTION_DEL( &My_Connections[idx], CONN_ISCONNECTING );
169 server_login(CONN_ID idx)
171 Log( LOG_INFO, "Connection %d with \"%s:%d\" established. Now logging in ...", idx,
172 My_Connections[idx].host, Conf_Server[Conf_GetServer( idx )].port );
174 io_event_setcb( My_Connections[idx].sock, cb_clientserver);
175 io_event_add( My_Connections[idx].sock, IO_WANTREAD|IO_WANTWRITE);
177 /* Send PASS and SERVER command to peer */
178 Conn_WriteStr( idx, "PASS %s %s", Conf_Server[Conf_GetServer( idx )].pwd_out, NGIRCd_ProtoID );
179 Conn_WriteStr( idx, "SERVER %s :%s", Conf_ServerName, Conf_ServerInfo );
184 cb_clientserver(int sock, short what)
186 CONN_ID idx = Socket2Index( sock );
189 Log(LOG_WARNING, "WTF: cb_clientserver wants to write on unknown socket?!");
195 if (what & IO_WANTREAD)
198 if (what & IO_WANTWRITE)
206 /* Modul initialisieren: statische Strukturen "ausnullen". */
210 /* Speicher fuer Verbindungs-Pool anfordern */
211 Pool_Size = CONNECTION_POOL;
212 if( Conf_MaxConnections > 0 )
214 /* konfiguriertes Limit beachten */
215 if( Pool_Size > Conf_MaxConnections ) Pool_Size = Conf_MaxConnections;
217 My_Connections = (CONNECTION *) calloc( Pool_Size, sizeof( CONNECTION ) );
218 if( ! My_Connections )
220 /* Speicher konnte nicht alloziert werden! */
221 Log( LOG_EMERG, "Can't allocate memory! [Conn_Init]" );
224 LogDebug("Allocated connection pool for %d items (%ld bytes).", Pool_Size,
225 sizeof( CONNECTION ) * Pool_Size );
227 array_free( &My_Listeners );
229 /* Connection-Struktur initialisieren */
230 for( i = 0; i < Pool_Size; i++ ) Init_Conn_Struct( i );
232 /* Global write counter */
240 /* Modul abmelden: alle noch offenen Connections
241 * schliessen und freigeben. */
245 LogDebug("Shutting down all connections ..." );
247 Conn_ExitListeners();
249 /* Sockets schliessen */
250 for( idx = 0; idx < Pool_Size; idx++ ) {
251 if( My_Connections[idx].sock > NONE ) {
252 Conn_Close( idx, NULL, NGIRCd_SignalRestart ?
253 "Server going down (restarting)":"Server going down", true );
258 free( My_Connections );
259 My_Connections = NULL;
261 io_library_shutdown();
266 ports_initlisteners(array *a, void (*func)(int,short))
268 unsigned int created = 0, len;
272 len = array_length(a, sizeof (UINT16));
273 port = array_start(a);
275 fd = NewListener( *port );
280 if (!io_event_create( fd, IO_WANTREAD, func )) {
281 Log( LOG_ERR, "io_event_create(): Could not add listening fd %d (port %u): %s!",
282 fd, (unsigned int) *port, strerror(errno));
296 Conn_InitListeners( void )
298 /* Initialize ports on which the server should accept connections */
300 unsigned int created;
302 if (!io_library_init(CONNECTION_POOL)) {
303 Log(LOG_EMERG, "Cannot initialize IO routines: %s", strerror(errno));
307 created = ports_initlisteners(&Conf_ListenPorts, cb_listen);
310 } /* Conn_InitListeners */
314 Conn_ExitListeners( void )
316 /* Close down all listening sockets */
320 Rendezvous_UnregisterListeners( );
323 arraylen = array_length(&My_Listeners, sizeof (int));
324 Log( LOG_INFO, "Shutting down all listening sockets (%d total)...", arraylen );
325 fd = array_start(&My_Listeners);
330 LogDebug("Listening socket %d closed.", *fd );
333 array_free(&My_Listeners);
334 } /* Conn_ExitListeners */
337 /* return new listening port file descriptor or -1 on failure */
339 NewListener( const UINT16 Port )
341 /* Create new listening socket on specified port */
343 struct sockaddr_in addr;
344 struct in_addr inaddr;
347 char name[CLIENT_ID_LEN], *info;
350 /* Server-"Listen"-Socket initialisieren */
351 memset( &addr, 0, sizeof( addr ));
352 memset( &inaddr, 0, sizeof( inaddr ));
353 addr.sin_family = AF_INET;
354 addr.sin_port = htons( Port );
355 if( Conf_ListenAddress[0] )
357 #ifdef HAVE_INET_ATON
358 if( inet_aton( Conf_ListenAddress, &inaddr ) == 0 )
360 inaddr.s_addr = inet_addr( Conf_ListenAddress );
361 if( inaddr.s_addr == (unsigned)-1 )
364 Log( LOG_CRIT, "Can't listen on %s:%u: can't convert ip address %s!",
365 Conf_ListenAddress, Port, Conf_ListenAddress );
369 else inaddr.s_addr = htonl( INADDR_ANY );
370 addr.sin_addr = inaddr;
372 sock = socket( PF_INET, SOCK_STREAM, 0);
374 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
378 if( ! Init_Socket( sock )) return -1;
380 if( bind( sock, (struct sockaddr *)&addr, (socklen_t)sizeof( addr )) != 0 ) {
381 Log( LOG_CRIT, "Can't bind socket: %s!", strerror( errno ));
386 if( listen( sock, 10 ) != 0 ) {
387 Log( LOG_CRIT, "Can't listen on socket: %s!", strerror( errno ));
392 /* keep fd in list so we can close it when ngircd restarts/shuts down */
393 if (!array_catb( &My_Listeners,(char*) &sock, sizeof(int) )) {
394 Log( LOG_CRIT, "Can't add socket to My_Listeners array: %s!", strerror( errno ));
399 if( Conf_ListenAddress[0]) Log( LOG_INFO, "Now listening on %s:%d (socket %d).", Conf_ListenAddress, Port, sock );
400 else Log( LOG_INFO, "Now listening on 0.0.0.0:%d (socket %d).", Port, sock );
403 /* Get best server description text */
404 if( ! Conf_ServerInfo[0] ) info = Conf_ServerName;
407 /* Use server info string */
409 if( Conf_ServerInfo[0] == '[' )
411 /* Cut off leading hostname part in "[]" */
412 info = strchr( Conf_ServerInfo, ']' );
416 while( *info == ' ' ) info++;
419 if( ! info ) info = Conf_ServerInfo;
422 /* Add port number to description if non-standard */
423 if( Port != 6667 ) snprintf( name, sizeof( name ), "%s (port %u)", info, Port );
424 else strlcpy( name, info, sizeof( name ));
426 /* Register service */
427 Rendezvous_Register( name, MDNS_TYPE, Port );
436 /* "Main Loop.": Loop until a signal (for shutdown or restart) arrives.
437 * Call io_dispatch() to check for read/writeable sockets every second
438 * Wait for status change on pending connections (e.g: when the hostname has been resolved)
439 * check for penalty/timeouts
440 * handle input buffers
443 unsigned int wdatalen;
448 while(( ! NGIRCd_SignalQuit ) && ( ! NGIRCd_SignalRestart )) {
452 Rendezvous_Handler( );
455 /* Should the configuration be reloaded? */
456 if (NGIRCd_SignalRehash) {
460 /* Check configured servers and established links */
462 Check_Connections( );
466 /* noch volle Lese-Buffer suchen */
467 for( i = 0; i < Pool_Size; i++ ) {
468 if(( My_Connections[i].sock > NONE ) && ( array_bytes(&My_Connections[i].rbuf) > 0 ) &&
469 ( My_Connections[i].delaytime < t ))
471 /* Kann aus dem Buffer noch ein Befehl extrahiert werden? */
472 if (Handle_Buffer( i )) timeout = false;
476 /* noch volle Schreib-Puffer suchen */
477 for( i = 0; i < Pool_Size; i++ ) {
478 if ( My_Connections[i].sock <= NONE )
481 wdatalen = array_bytes(&My_Connections[i].wbuf);
484 if (( wdatalen > 0 ) || ( array_bytes(&My_Connections[i].zip.wbuf)> 0 ))
489 /* Socket der Verbindung in Set aufnehmen */
490 io_event_add( My_Connections[i].sock, IO_WANTWRITE );
494 /* von welchen Sockets koennte gelesen werden? */
495 for (i = 0; i < Pool_Size; i++ ) {
496 if ( My_Connections[i].sock <= NONE )
499 if (Resolve_INPROGRESS(&My_Connections[i].res_stat)) {
500 /* wait for completion of Resolver Sub-Process */
501 io_event_del( My_Connections[i].sock, IO_WANTREAD );
505 if ( Conn_OPTION_ISSET( &My_Connections[i], CONN_ISCONNECTING ))
506 continue; /* wait for completion of connect() */
508 if( My_Connections[i].delaytime > t ) {
509 /* Fuer die Verbindung ist eine "Penalty-Zeit" gesetzt */
510 io_event_del( My_Connections[i].sock, IO_WANTREAD );
513 io_event_add( My_Connections[i].sock, IO_WANTREAD );
516 /* (re-)set timeout - tv_sec/usec are undefined after io_dispatch() returns */
518 tv.tv_sec = timeout ? 1 : 0;
520 /* wait for activity */
521 i = io_dispatch( &tv );
522 if (i == -1 && errno != EINTR ) {
523 Log(LOG_EMERG, "Conn_Handler(): io_dispatch(): %s!", strerror(errno));
524 Log(LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE_NAME);
529 if( NGIRCd_SignalQuit ) Log( LOG_NOTICE|LOG_snotice, "Server going down NOW!" );
530 else if( NGIRCd_SignalRestart ) Log( LOG_NOTICE|LOG_snotice, "Server restarting NOW!" );
535 * Write a text string into the socket of a connection.
536 * This function automatically appends CR+LF to the string and validates that
537 * the result is a valid IRC message (oversized messages are shortened, for
538 * example). Then it calls the Conn_Write() function to do the actual sending.
539 * @param Idx Index fo the connection.
540 * @param Format Format string, see printf().
541 * @return true on success, false otherwise.
545 Conn_WriteStr( CONN_ID Idx, char *Format, ... )
548 Conn_WriteStr( Idx, Format, va_alist )
554 char buffer[COMMAND_LEN];
558 assert( Idx > NONE );
559 assert( Format != NULL );
562 va_start( ap, Format );
566 if (vsnprintf( buffer, COMMAND_LEN - 2, Format, ap ) >= COMMAND_LEN - 2 ) {
568 * The string that should be written to the socket is longer
569 * than the allowed size of COMMAND_LEN bytes (including both
570 * the CR and LF characters). This can be caused by the
571 * IRC_WriteXXX() functions when the prefix of this server had
572 * to be added to an already "quite long" command line which
573 * has been received from a regular IRC client, for example.
575 * We are not allowed to send such "oversized" messages to
576 * other servers and clients, see RFC 2812 2.3 and 2813 3.3
577 * ("these messages SHALL NOT exceed 512 characters in length,
578 * counting all characters including the trailing CR-LF").
580 * So we have a big problem here: we should send more bytes
581 * to the network than we are allowed to and we don't know
582 * the originator (any more). The "old" behaviour of blaming
583 * the receiver ("next hop") is a bad idea (it could be just
584 * an other server only routing the message!), so the only
585 * option left is to shorten the string and to hope that the
586 * result is still somewhat useful ...
590 strcpy (buffer + sizeof(buffer) - strlen(CUT_TXTSUFFIX) - 2 - 1,
596 Log(LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer);
599 strlcat( buffer, "\r\n", sizeof( buffer ));
600 ok = Conn_Write( Idx, buffer, strlen( buffer ));
601 My_Connections[Idx].msg_out++;
605 } /* Conn_WriteStr */
609 Conn_Write( CONN_ID Idx, char *Data, unsigned int Len )
611 /* Daten in Socket schreiben. Bei "fatalen" Fehlern wird
612 * der Client disconnectiert und false geliefert. */
614 assert( Idx > NONE );
615 assert( Data != NULL );
618 /* Ist der entsprechende Socket ueberhaupt noch offen? In einem
619 * "Handler-Durchlauf" kann es passieren, dass dem nicht mehr so
620 * ist, wenn einer von mehreren Conn_Write()'s fehlgeschlagen ist.
621 * In diesem Fall wird hier einfach ein Fehler geliefert. */
622 if( My_Connections[Idx].sock <= NONE ) {
623 LogDebug("Skipped write on closed socket (connection %d).", Idx );
627 /* Pruefen, ob im Schreibpuffer genuegend Platz ist. Ziel ist es,
628 * moeglichts viel im Puffer zu haben und _nicht_ gleich alles auf den
629 * Socket zu schreiben (u.a. wg. Komprimierung). */
630 if( array_bytes(&My_Connections[Idx].wbuf) >= WRITEBUFFER_LEN) {
631 /* Der Puffer ist dummerweise voll. Jetzt versuchen, den Puffer
632 * zu schreiben, wenn das nicht klappt, haben wir ein Problem ... */
633 if( ! Handle_Write( Idx )) return false;
635 /* check again: if our writebuf is twice als large as the initial limit: Kill connection */
636 if( array_bytes(&My_Connections[Idx].wbuf) >= (WRITEBUFFER_LEN*2)) {
637 Log( LOG_NOTICE, "Write buffer overflow (connection %d)!", Idx );
638 Conn_Close( Idx, "Write buffer overflow!", NULL, false );
644 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
645 /* Daten komprimieren und in Puffer kopieren */
646 if( ! Zip_Buffer( Idx, Data, Len )) return false;
651 /* Daten in Puffer kopieren */
652 if (!array_catb( &My_Connections[Idx].wbuf, Data, Len ))
655 My_Connections[Idx].bytes_out += Len;
658 /* Adjust global write counter */
666 Conn_Close( CONN_ID Idx, char *LogMsg, char *FwdMsg, bool InformClient )
668 /* Close connection. Open pipes of asyncronous resolver
669 * sub-processes are closed down. */
675 double in_z_k, out_z_k;
679 assert( Idx > NONE );
681 /* Is this link already shutting down? */
682 if( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ISCLOSING )) {
683 /* Conn_Close() has been called recursively for this link;
684 * probabe reason: Handle_Write() failed -- see below. */
685 LogDebug("Recursive request to close connection: %d", Idx );
689 assert( My_Connections[Idx].sock > NONE );
691 /* Mark link as "closing" */
692 Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCLOSING );
694 if( LogMsg ) txt = LogMsg;
696 if( ! txt ) txt = "Reason unknown";
698 Log( LOG_INFO, "Shutting down connection %d (%s) with %s:%d ...", Idx, LogMsg ? LogMsg : FwdMsg, My_Connections[Idx].host, ntohs( My_Connections[Idx].addr.sin_port ));
700 /* Search client, if any */
701 c = Client_GetFromConn( Idx );
703 /* Should the client be informed? */
706 /* Send statistics to client if registered as user: */
707 if ((c != NULL) && (Client_Type(c) == CLIENT_USER)) {
709 ":%s NOTICE %s :%sConnection statistics: client %.1f kb, server %.1f kb.",
710 Client_ID(Client_ThisServer()), Client_ID(c),
712 (double)My_Connections[Idx].bytes_in / 1024,
713 (double)My_Connections[Idx].bytes_out / 1024);
717 /* Send ERROR to client (see RFC!) */
719 Conn_WriteStr(Idx, "ERROR :%s", FwdMsg);
721 Conn_WriteStr(Idx, "ERROR :Closing connection.");
724 /* Try to write out the write buffer. Note: Handle_Write() eventually
725 * removes the CLIENT structure associated with this connection if an
726 * error occurs! So we have to re-check if there is still an valid
727 * CLIENT structure after calling Handle_Write() ...*/
728 (void)Handle_Write( Idx );
730 /* Search client, if any (re-check!) */
731 c = Client_GetFromConn( Idx );
733 /* Shut down socket */
734 if( ! io_close( My_Connections[Idx].sock ))
736 /* Oops, we can't close the socket!? This is ... ugly! */
737 Log( LOG_CRIT, "Error closing connection %d (socket %d) with %s:%d - %s! (ignored)", Idx, My_Connections[Idx].sock, My_Connections[Idx].host, ntohs( My_Connections[Idx].addr.sin_port), strerror( errno ));
740 /* Mark socket as invalid: */
741 My_Connections[Idx].sock = NONE;
743 /* If there is still a client, unregister it now */
744 if( c ) Client_Destroy( c, LogMsg, FwdMsg, true );
746 /* Calculate statistics and log information */
747 in_k = (double)My_Connections[Idx].bytes_in / 1024;
748 out_k = (double)My_Connections[Idx].bytes_out / 1024;
750 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
751 in_z_k = (double)My_Connections[Idx].zip.bytes_in / 1024;
752 out_z_k = (double)My_Connections[Idx].zip.bytes_out / 1024;
753 in_p = (int)(( in_k * 100 ) / in_z_k );
754 out_p = (int)(( out_k * 100 ) / out_z_k );
755 Log( LOG_INFO, "Connection %d with %s:%d closed (in: %.1fk/%.1fk/%d%%, out: %.1fk/%.1fk/%d%%).", Idx, My_Connections[Idx].host, ntohs( My_Connections[Idx].addr.sin_port ), in_k, in_z_k, in_p, out_k, out_z_k, out_p );
760 Log( LOG_INFO, "Connection %d with %s:%d closed (in: %.1fk, out: %.1fk).", Idx, My_Connections[Idx].host, ntohs( My_Connections[Idx].addr.sin_port ), in_k, out_k );
763 /* cancel running resolver */
764 if (Resolve_INPROGRESS(&My_Connections[Idx].res_stat)) {
765 Resolve_Shutdown(&My_Connections[Idx].res_stat);
768 /* Servers: Modify time of next connect attempt? */
769 Conf_UnsetServer( Idx );
772 /* Clean up zlib, if link was compressed */
773 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
774 inflateEnd( &My_Connections[Idx].zip.in );
775 deflateEnd( &My_Connections[Idx].zip.out );
776 array_free(&My_Connections[Idx].zip.rbuf);
777 array_free(&My_Connections[Idx].zip.wbuf);
781 array_free(&My_Connections[Idx].rbuf);
782 array_free(&My_Connections[Idx].wbuf);
783 /* Clean up connection structure (=free it) */
784 Init_Conn_Struct( Idx );
787 LogDebug("Shutdown of connection %d completed.", Idx );
793 Conn_SyncServerStruct( void )
795 /* Synchronize server structures (connection IDs):
796 * connections <-> configuration */
802 for( i = 0; i < Pool_Size; i++ ) {
803 /* Established connection? */
804 if (My_Connections[i].sock < 0)
807 /* Server connection? */
808 client = Client_GetFromConn( i );
809 if(( ! client ) || ( Client_Type( client ) != CLIENT_SERVER )) continue;
811 for( c = 0; c < MAX_SERVERS; c++ )
813 /* Configured server? */
814 if( ! Conf_Server[c].host[0] ) continue;
817 if( strcmp( Conf_Server[c].name, Client_ID( client )) == 0 )
818 Conf_Server[c].conn_id = i;
821 } /* SyncServerStruct */
825 Handle_Write( CONN_ID Idx )
827 /* Daten aus Schreibpuffer versenden bzw. Connection aufbauen */
830 unsigned int wdatalen;
832 assert( Idx > NONE );
833 if ( My_Connections[Idx].sock < 0 ) {
834 LogDebug("Handle_Write() on closed socket, connection %d", Idx);
837 assert( My_Connections[Idx].sock > NONE );
839 LogDebug("Handle_Write() called for connection %d ...", Idx);
841 wdatalen = array_bytes(&My_Connections[Idx].wbuf );
843 if (wdatalen == 0 && !array_bytes(&My_Connections[Idx].zip.wbuf)) {
844 io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
848 /* write buffer empty, but not compression buffer?
849 * -> flush compression buffer! */
854 io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
859 /* Zip_Flush() may have changed the write buffer ... */
860 wdatalen = array_bytes(&My_Connections[Idx].wbuf);
862 len = write(My_Connections[Idx].sock,
863 array_start(&My_Connections[Idx].wbuf), wdatalen );
866 if (errno == EAGAIN || errno == EINTR)
869 Log(LOG_ERR, "Write error on connection %d (socket %d): %s!",
870 Idx, My_Connections[Idx].sock, strerror(errno));
871 Conn_Close(Idx, "Write error!", NULL, false);
875 /* move any data not yet written to beginning */
876 array_moveleft(&My_Connections[Idx].wbuf, 1, len);
883 New_Connection( int Sock )
885 /* Neue Client-Verbindung von Listen-Socket annehmen und
886 * CLIENT-Struktur anlegen. */
889 struct request_info req;
891 struct sockaddr_in new_addr;
892 int i, new_sock, new_sock_len;
897 assert( Sock > NONE );
898 /* Connection auf Listen-Socket annehmen */
899 new_sock_len = sizeof( new_addr );
900 new_sock = accept( Sock, (struct sockaddr *)&new_addr, (socklen_t *)&new_sock_len );
903 Log( LOG_CRIT, "Can't accept connection: %s!", strerror( errno ));
908 /* Validate socket using TCP Wrappers */
909 request_init( &req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock, RQ_CLIENT_SIN, &new_addr, NULL );
911 if( ! hosts_access( &req ))
914 Log( deny_severity, "Refused connection from %s (by TCP Wrappers)!", inet_ntoa( new_addr.sin_addr ));
915 Simple_Message( new_sock, "ERROR :Connection refused" );
921 /* Socket initialisieren */
922 Init_Socket( new_sock );
924 /* Check IP-based connection limit */
925 cnt = Count_Connections( new_addr );
926 if(( Conf_MaxConnectionsIP > 0 ) && ( cnt >= Conf_MaxConnectionsIP ))
928 /* Access denied, too many connections from this IP address! */
929 Log( LOG_ERR, "Refused connection from %s: too may connections (%ld) from this IP address!", inet_ntoa( new_addr.sin_addr ), cnt);
930 Simple_Message( new_sock, "ERROR :Connection refused, too many connections from your IP address!" );
936 if (new_sock < Pool_Size)
937 assert(My_Connections[new_sock].sock == NONE );
939 if( new_sock >= Pool_Size ) {
940 new_size = Pool_Size + CONNECTION_POOL;
942 /* Im bisherigen Pool wurde keine freie Connection-Struktur mehr gefunden.
943 * Wenn erlaubt und moeglich muss nun der Pool vergroessert werden: */
944 if( Conf_MaxConnections > 0 )
946 /* Es ist ein Limit konfiguriert */
947 if( Pool_Size >= Conf_MaxConnections )
949 /* Mehr Verbindungen duerfen wir leider nicht mehr annehmen ... */
950 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached!", Pool_Size );
951 Simple_Message( new_sock, "ERROR :Connection limit reached" );
955 if( new_size > Conf_MaxConnections ) new_size = Conf_MaxConnections;
957 if( new_size < Pool_Size )
959 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached -- overflow!", Pool_Size );
960 Simple_Message( new_sock, "ERROR :Connection limit reached" );
965 ptr = (POINTER *)realloc( My_Connections, sizeof( CONNECTION ) * new_size );
967 Log( LOG_EMERG, "Can't allocate memory! [New_Connection]" );
968 Simple_Message( new_sock, "ERROR: Internal error" );
973 LogDebug("Allocated new connection pool for %ld items (%ld bytes). [realloc()]",
974 new_size, sizeof( CONNECTION ) * new_size );
976 /* Adjust pointer to new block */
977 My_Connections = (CONNECTION *)ptr;
979 /* Initialize new items */
980 for( i = Pool_Size; i < new_size; i++ )
981 Init_Conn_Struct( i );
983 /* Adjust new pool size */
984 Pool_Size = new_size;
987 /* Client-Struktur initialisieren */
988 c = Client_NewLocal( new_sock, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWN, false );
990 Log( LOG_ALERT, "Can't accept connection: can't create client structure!" );
991 Simple_Message( new_sock, "ERROR :Internal error" );
996 /* Verbindung registrieren */
997 Init_Conn_Struct( new_sock );
998 My_Connections[new_sock].sock = new_sock;
999 My_Connections[new_sock].addr = new_addr;
1001 /* Neuen Socket registrieren */
1002 if (!io_event_create( new_sock, IO_WANTREAD, cb_clientserver)) {
1003 Simple_Message( new_sock, "ERROR :Internal error" );
1004 Conn_Close( new_sock, "io_event_create() failed", NULL, false );
1008 LogDebug( "Accepted connection %d from %s:%d on socket %d.", new_sock,
1009 inet_ntoa( new_addr.sin_addr ), ntohs( new_addr.sin_port), Sock );
1011 /* Hostnamen ermitteln */
1012 strlcpy( My_Connections[new_sock].host, inet_ntoa( new_addr.sin_addr ),
1013 sizeof( My_Connections[new_sock].host ));
1015 Client_SetHostname( c, My_Connections[new_sock].host );
1017 Resolve_Addr(&My_Connections[new_sock].res_stat, &new_addr,
1018 My_Connections[new_sock].sock, cb_Read_Resolver_Result);
1020 /* Penalty-Zeit setzen */
1021 Conn_SetPenalty( new_sock, 4 );
1023 } /* New_Connection */
1027 Socket2Index( int Sock )
1029 /* zum Socket passende Connection suchen */
1031 assert( Sock >= 0 );
1033 if( Sock >= Pool_Size || My_Connections[Sock].sock != Sock ) {
1034 /* die Connection wurde vermutlich (wegen eines
1035 * Fehlers) bereits wieder abgebaut ... */
1037 LogDebug( "Socket2Index: can't get connection for socket %d!", Sock );
1041 } /* Socket2Index */
1045 Read_Request( CONN_ID Idx )
1047 /* Daten von Socket einlesen und entsprechend behandeln.
1048 * Tritt ein Fehler auf, so wird der Socket geschlossen. */
1054 assert( Idx > NONE );
1055 assert( My_Connections[Idx].sock > NONE );
1058 if (( array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN ) ||
1059 ( array_bytes(&My_Connections[Idx].zip.rbuf) >= ZREADBUFFER_LEN ))
1061 if ( array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN )
1064 /* Der Lesepuffer ist voll */
1065 Log( LOG_ERR, "Receive buffer overflow (connection %d): %d bytes!", Idx,
1066 array_bytes(&My_Connections[Idx].rbuf));
1067 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1071 len = read( My_Connections[Idx].sock, readbuf, sizeof readbuf -1 );
1073 Log( LOG_INFO, "%s:%d (%s) is closing the connection ...",
1074 My_Connections[Idx].host, ntohs( My_Connections[Idx].addr.sin_port),
1075 inet_ntoa( My_Connections[Idx].addr.sin_addr ));
1076 Conn_Close( Idx, "Socket closed!", "Client closed connection", false );
1081 if( errno == EAGAIN ) return;
1082 Log( LOG_ERR, "Read error on connection %d (socket %d): %s!", Idx,
1083 My_Connections[Idx].sock, strerror( errno ));
1084 Conn_Close( Idx, "Read error!", "Client closed connection", false );
1088 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
1089 if (!array_catb( &My_Connections[Idx].zip.rbuf, readbuf, len)) {
1090 Log( LOG_ERR, "Could not append recieved data to zip input buffer (connn %d): %d bytes!", Idx, len );
1091 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1098 if (!array_cats( &My_Connections[Idx].rbuf, readbuf )) {
1099 Log( LOG_ERR, "Could not append recieved data to input buffer (connn %d): %d bytes!", Idx, len );
1100 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1104 /* Update connection statistics */
1105 My_Connections[Idx].bytes_in += len;
1107 /* Update timestamp of last data received if this connection is
1108 * registered as a user, server or service connection. Don't update
1109 * otherwise, so users have at least Conf_PongTimeout seconds time to
1110 * register with the IRC server -- see Check_Connections(). */
1111 c = Client_GetFromConn(Idx);
1112 if (c && (Client_Type(c) == CLIENT_USER
1113 || Client_Type(c) == CLIENT_SERVER
1114 || Client_Type(c) == CLIENT_SERVICE))
1115 My_Connections[Idx].lastdata = time(NULL);
1117 /* Look at the data in the (read-) buffer of this connection */
1119 } /* Read_Request */
1123 Handle_Buffer( CONN_ID Idx )
1125 /* Handle Data in Connections Read-Buffer.
1126 * Return true if a reuqest was handled, false otherwise (also returned on errors). */
1140 if( My_Connections[Idx].delaytime > time( NULL )) return result;
1142 /* unpack compressed data */
1143 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP ))
1144 if( ! Unzip_Buffer( Idx )) return false;
1147 if (0 == array_bytes(&My_Connections[Idx].rbuf))
1150 if (!array_cat0_temporary(&My_Connections[Idx].rbuf)) /* make sure buf is NULL terminated */
1153 /* A Complete Request end with CR+LF, see RFC 2812. */
1154 ptr = strstr( array_start(&My_Connections[Idx].rbuf), "\r\n" );
1156 if( ptr ) delta = 2; /* complete request */
1159 /* Check for non-RFC-compliant request (only CR or LF)? Unfortunately,
1160 * there are quite a few clients that do this (incl. "mIRC" :-( */
1161 ptr1 = strchr( array_start(&My_Connections[Idx].rbuf), '\r' );
1162 ptr2 = strchr( array_start(&My_Connections[Idx].rbuf), '\n' );
1164 if( ptr1 && ptr2 ) ptr = ptr1 > ptr2 ? ptr2 : ptr1;
1165 else if( ptr1 ) ptr = ptr1;
1166 else if( ptr2 ) ptr = ptr2;
1173 /* End of request found */
1176 len = ( ptr - (char*) array_start(&My_Connections[Idx].rbuf)) + delta;
1178 if( len < 0 || len > ( COMMAND_LEN - 1 )) {
1179 /* Request must not exceed 512 chars (incl. CR+LF!), see
1180 * RFC 2812. Disconnect Client if this happens. */
1181 Log( LOG_ERR, "Request too long (connection %d): %d bytes (max. %d expected)!",
1182 Idx, array_bytes(&My_Connections[Idx].rbuf), COMMAND_LEN - 1 );
1183 Conn_Close( Idx, NULL, "Request too long", true );
1187 if (len <= 2) { /* request was empty (only '\r\n') */
1188 array_moveleft(&My_Connections[Idx].rbuf, 1, delta); /* delta is either 1 or 2 */
1192 /* remember if stream is already compressed */
1193 old_z = My_Connections[Idx].options & CONN_ZIP;
1196 My_Connections[Idx].msg_in++;
1197 if (!Parse_Request(Idx, (char*)array_start(&My_Connections[Idx].rbuf) ))
1202 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1204 LogDebug("Connection %d: %d bytes left in read buffer.", Idx,
1205 array_bytes(&My_Connections[Idx].rbuf));
1207 if(( ! old_z ) && ( My_Connections[Idx].options & CONN_ZIP ) &&
1208 ( array_bytes(&My_Connections[Idx].rbuf) > 0 ))
1210 /* The last Command activated Socket-Compression.
1211 * Data that was read after that needs to be copied to Unzip-buf
1212 * for decompression */
1213 if( array_bytes(&My_Connections[Idx].rbuf)> ZREADBUFFER_LEN ) {
1214 Log( LOG_ALERT, "Connection %d: No space left in unzip buf (need %u bytes)!",
1215 Idx, array_bytes(&My_Connections[Idx].rbuf ));
1218 if (!array_copy( &My_Connections[Idx].zip.rbuf, &My_Connections[Idx].rbuf ))
1221 array_trunc(&My_Connections[Idx].rbuf);
1223 LogDebug("Moved already received data (%u bytes) to uncompression buffer.",
1224 array_bytes(&My_Connections[Idx].zip.rbuf));
1230 } /* Handle_Buffer */
1234 Check_Connections( void )
1236 /* check if connections are alive. if not, play PING-PONG first.
1237 * if this doesn't help either, disconnect client. */
1241 for( i = 0; i < Pool_Size; i++ ) {
1242 if (My_Connections[i].sock < 0)
1245 c = Client_GetFromConn( i );
1246 if( c && (( Client_Type( c ) == CLIENT_USER ) || ( Client_Type( c ) == CLIENT_SERVER ) || ( Client_Type( c ) == CLIENT_SERVICE )))
1248 /* connected User, Server or Service */
1249 if( My_Connections[i].lastping > My_Connections[i].lastdata ) {
1250 /* we already sent a ping */
1251 if( My_Connections[i].lastping < time( NULL ) - Conf_PongTimeout ) {
1254 LogDebug("Connection %d: Ping timeout: %d seconds.", i,
1256 Conn_Close( i, NULL, "Ping timeout", true );
1259 else if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout ) {
1260 /* we need to sent a PING */
1261 LogDebug("Connection %d: sending PING ...", i );
1262 My_Connections[i].lastping = time( NULL );
1263 Conn_WriteStr( i, "PING :%s", Client_ID( Client_ThisServer( )));
1268 /* The connection is not fully established yet, so
1269 * we don't do the PING-PONG game here but instead
1270 * disconnect the client after "a short time" if it's
1271 * still not registered. */
1273 if (My_Connections[i].lastdata <
1274 time(NULL) - Conf_PongTimeout) {
1275 LogDebug("Unregistered connection %d timed out ...", i);
1276 Conn_Close(i, NULL, "Timeout", false);
1280 } /* Check_Connections */
1284 Check_Servers( void )
1286 /* Check if we can establish further server links */
1291 /* Check all configured servers */
1292 for( i = 0; i < MAX_SERVERS; i++ ) {
1293 /* Valid outgoing server which isn't already connected or disabled? */
1294 if(( ! Conf_Server[i].host[0] ) || ( ! Conf_Server[i].port > 0 ) ||
1295 ( Conf_Server[i].conn_id > NONE ) || ( Conf_Server[i].flags & CONF_SFLAG_DISABLED ))
1298 /* Is there already a connection in this group? */
1299 if( Conf_Server[i].group > NONE ) {
1300 for (n = 0; n < MAX_SERVERS; n++) {
1301 if (n == i) continue;
1302 if ((Conf_Server[n].conn_id > NONE) &&
1303 (Conf_Server[n].group == Conf_Server[i].group))
1306 if (n < MAX_SERVERS) continue;
1309 /* Check last connect attempt? */
1310 time_now = time(NULL);
1311 if( Conf_Server[i].lasttry > (time_now - Conf_ConnectRetry))
1314 /* Okay, try to connect now */
1315 Conf_Server[i].lasttry = time_now;
1316 assert(Resolve_Getfd(&Conf_Server[i].res_stat) < 0);
1317 Resolve_Name(&Conf_Server[i].res_stat, Conf_Server[i].host, cb_Connect_to_Server);
1319 } /* Check_Servers */
1323 New_Server( int Server )
1325 /* Establish new server link */
1327 struct sockaddr_in new_addr;
1328 struct in_addr inaddr;
1332 assert( Server > NONE );
1334 Log( LOG_INFO, "Establishing connection to \"%s\", %s, port %d ... ", Conf_Server[Server].host,
1335 Conf_Server[Server].ip, Conf_Server[Server].port );
1337 #ifdef HAVE_INET_ATON
1338 if( inet_aton( Conf_Server[Server].ip, &inaddr ) == 0 )
1340 memset( &inaddr, 0, sizeof( inaddr ));
1341 inaddr.s_addr = inet_addr( Conf_Server[Server].ip );
1342 if( inaddr.s_addr == (unsigned)-1 )
1345 Log( LOG_ERR, "Can't connect to \"%s\": can't convert ip address %s!",
1346 Conf_Server[Server].host, Conf_Server[Server].ip );
1350 memset( &new_addr, 0, sizeof( new_addr ));
1351 new_addr.sin_family = AF_INET;
1352 new_addr.sin_addr = inaddr;
1353 new_addr.sin_port = htons( Conf_Server[Server].port );
1355 new_sock = socket( PF_INET, SOCK_STREAM, 0 );
1356 if ( new_sock < 0 ) {
1357 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
1361 if( ! Init_Socket( new_sock )) return;
1363 res = connect( new_sock, (struct sockaddr *)&new_addr, sizeof( new_addr ));
1364 if(( res != 0 ) && ( errno != EINPROGRESS )) {
1365 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1369 if (new_sock >= Pool_Size) {
1370 Log( LOG_ALERT, "Can't establist server connection: connection limit reached (%d)!",
1376 assert(My_Connections[new_sock].sock < 0 );
1378 Init_Conn_Struct(new_sock);
1380 c = Client_NewLocal( new_sock, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWNSERVER, false );
1382 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1387 Client_SetIntroducer( c, c );
1388 Client_SetToken( c, TOKEN_OUTBOUND );
1390 /* Register connection */
1391 Conf_Server[Server].conn_id = new_sock;
1392 My_Connections[new_sock].sock = new_sock;
1393 My_Connections[new_sock].addr = new_addr;
1394 strlcpy( My_Connections[new_sock].host, Conf_Server[Server].host,
1395 sizeof(My_Connections[new_sock].host ));
1397 /* Register new socket */
1398 if (!io_event_create( new_sock, IO_WANTWRITE, cb_connserver)) {
1399 Log( LOG_ALERT, "io_event_create(): could not add fd %d", strerror(errno));
1400 Conn_Close( new_sock, "io_event_create() failed", NULL, false );
1401 Init_Conn_Struct( new_sock );
1402 Conf_Server[Server].conn_id = NONE;
1405 LogDebug("Registered new connection %d on socket %d.", new_sock, My_Connections[new_sock].sock );
1406 Conn_OPTION_ADD( &My_Connections[new_sock], CONN_ISCONNECTING );
1411 Init_Conn_Struct( CONN_ID Idx )
1413 time_t now = time( NULL );
1414 /* Connection-Struktur initialisieren */
1416 memset( &My_Connections[Idx], 0, sizeof ( CONNECTION ));
1417 My_Connections[Idx].sock = -1;
1418 My_Connections[Idx].lastdata = now;
1419 My_Connections[Idx].lastprivmsg = now;
1420 Resolve_Init(&My_Connections[Idx].res_stat);
1421 } /* Init_Conn_Struct */
1425 Init_Socket( int Sock )
1427 /* Initialize socket (set options) */
1431 if (!io_setnonblock(Sock)) {
1432 Log( LOG_CRIT, "Can't enable non-blocking mode for socket: %s!", strerror( errno ));
1437 /* Don't block this port after socket shutdown */
1439 if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &value, (socklen_t)sizeof( value )) != 0 )
1441 Log( LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!", strerror( errno ));
1442 /* ignore this error */
1445 /* Set type of service (TOS) */
1446 #if defined(IP_TOS) && defined(IPTOS_LOWDELAY)
1447 value = IPTOS_LOWDELAY;
1449 LogDebug("Setting option IP_TOS on socket %d to IPTOS_LOWDELAY (%d).", Sock, value );
1450 if( setsockopt( Sock, SOL_IP, IP_TOS, &value, (socklen_t)sizeof( value )) != 0 )
1452 Log( LOG_ERR, "Can't set socket option IP_TOS: %s!", strerror( errno ));
1453 /* ignore this error */
1463 cb_Connect_to_Server(int fd, UNUSED short events)
1465 /* Read result of resolver sub-process from pipe and start connection */
1468 char readbuf[HOST_LEN + 1];
1470 LogDebug("Resolver: Got forward lookup callback on fd %d, events %d", fd, events);
1472 for (i=0; i < MAX_SERVERS; i++) {
1473 if (Resolve_Getfd(&Conf_Server[i].res_stat) == fd )
1477 if( i >= MAX_SERVERS) {
1478 /* Ops, no matching server found?! */
1480 LogDebug("Resolver: Got Forward Lookup callback for unknown server!?" );
1484 /* Read result from pipe */
1485 len = Resolve_Read(&Conf_Server[i].res_stat, readbuf, sizeof readbuf -1);
1489 readbuf[len] = '\0';
1490 LogDebug("Got result from resolver: \"%s\" (%u bytes read).", readbuf, len);
1491 strlcpy( Conf_Server[i].ip, readbuf, sizeof( Conf_Server[i].ip ));
1495 } /* cb_Read_Forward_Lookup */
1499 cb_Read_Resolver_Result( int r_fd, UNUSED short events )
1501 /* Read result of resolver sub-process from pipe and update the
1502 * apropriate connection/client structure(s): hostname and/or
1503 * IDENT user name.*/
1510 char readbuf[HOST_LEN + 2 + CLIENT_USER_LEN];
1512 char readbuf[HOST_LEN + 1];
1515 LogDebug("Resolver: Got callback on fd %d, events %d", r_fd, events );
1517 /* Search associated connection ... */
1518 for( i = 0; i < Pool_Size; i++ ) {
1519 if(( My_Connections[i].sock != NONE )
1520 && ( Resolve_Getfd(&My_Connections[i].res_stat) == r_fd ))
1523 if( i >= Pool_Size ) {
1524 /* Ops, none found? Probably the connection has already
1525 * been closed!? We'll ignore that ... */
1527 LogDebug("Resolver: Got callback for unknown connection!?");
1531 /* Read result from pipe */
1532 len = Resolve_Read(&My_Connections[i].res_stat, readbuf, sizeof readbuf -1);
1536 readbuf[len] = '\0';
1537 identptr = strchr(readbuf, '\n');
1538 assert(identptr != NULL);
1540 Log( LOG_CRIT, "Resolver: Got malformed result!");
1546 LogDebug( "Got result from resolver: \"%s\" (%u bytes read).", readbuf, len);
1548 /* Okay, we got a complete result: this is a host name for outgoing
1549 * connections and a host name and IDENT user name (if enabled) for
1550 * incoming connections.*/
1551 assert ( My_Connections[i].sock >= 0 );
1552 /* Incoming connection. Search client ... */
1553 c = Client_GetFromConn( i );
1554 assert( c != NULL );
1556 /* Only update client information of unregistered clients */
1557 if( Client_Type( c ) == CLIENT_UNKNOWN ) {
1558 strlcpy(My_Connections[i].host, readbuf, sizeof( My_Connections[i].host));
1559 Client_SetHostname( c, readbuf);
1563 Log( LOG_INFO, "IDENT lookup for connection %ld: \"%s\".", i, identptr);
1564 Client_SetUser( c, identptr, true );
1566 Log( LOG_INFO, "IDENT lookup for connection %ld: no result.", i );
1571 else Log( LOG_DEBUG, "Resolver: discarding result for already registered connection %d.", i );
1573 /* Reset penalty time */
1574 Conn_ResetPenalty( i );
1575 } /* cb_Read_Resolver_Result */
1579 Simple_Message( int Sock, char *Msg )
1581 char buf[COMMAND_LEN];
1582 /* Write "simple" message to socket, without using compression
1583 * or even the connection write buffers. Used e.g. for error
1584 * messages by New_Connection(). */
1585 assert( Sock > NONE );
1586 assert( Msg != NULL );
1588 strlcpy( buf, Msg, sizeof buf - 2);
1589 strlcat( buf, "\r\n", sizeof buf);
1590 (void)write( Sock, buf, strlen( buf ) );
1591 } /* Simple_Error */
1595 Count_Connections( struct sockaddr_in addr_in )
1600 for( i = 0; i < Pool_Size; i++ ) {
1601 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].addr.sin_addr.s_addr == addr_in.sin_addr.s_addr )) cnt++;
1604 } /* Count_Connections */