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.188 2006/02/08 15:20:21 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 );
129 Log(LOG_DEBUG, "cb_connserver wants to write on unknown socket?!");
135 assert( what & IO_WANTWRITE);
137 /* connect() finished, get result. */
138 sock_len = sizeof( err );
139 res = getsockopt( My_Connections[idx].sock, SOL_SOCKET, SO_ERROR, &err, &sock_len );
140 assert( sock_len == sizeof( err ));
142 /* Error while connecting? */
143 if ((res != 0) || (err != 0)) {
145 Log(LOG_CRIT, "getsockopt (connection %d): %s!",
146 idx, strerror(errno));
149 "Can't connect socket to \"%s:%d\" (connection %d): %s!",
150 My_Connections[idx].host,
151 Conf_Server[Conf_GetServer(idx)].port,
154 /* Clean up the CLIENT structure (to avoid silly log
155 * messages) and call Conn_Close() to do the rest. */
156 c = Client_GetFromConn(idx);
158 Client_DestroyNow(c);
160 Conn_Close(idx, "Can't connect!", NULL, false);
165 Conn_OPTION_DEL( &My_Connections[idx], CONN_ISCONNECTING );
171 server_login(CONN_ID idx)
173 Log( LOG_INFO, "Connection %d with \"%s:%d\" established. Now logging in ...", idx,
174 My_Connections[idx].host, Conf_Server[Conf_GetServer( idx )].port );
176 io_event_setcb( My_Connections[idx].sock, cb_clientserver);
177 io_event_add( My_Connections[idx].sock, IO_WANTREAD|IO_WANTWRITE);
179 /* Send PASS and SERVER command to peer */
180 Conn_WriteStr( idx, "PASS %s %s", Conf_Server[Conf_GetServer( idx )].pwd_out, NGIRCd_ProtoID );
181 Conn_WriteStr( idx, "SERVER %s :%s", Conf_ServerName, Conf_ServerInfo );
186 cb_clientserver(int sock, short what)
188 CONN_ID idx = Socket2Index( sock );
191 Log(LOG_WARNING, "WTF: cb_clientserver wants to write on unknown socket?!");
197 if (what & IO_WANTREAD)
200 if (what & IO_WANTWRITE)
208 /* Modul initialisieren: statische Strukturen "ausnullen". */
212 /* Speicher fuer Verbindungs-Pool anfordern */
213 Pool_Size = CONNECTION_POOL;
214 if( Conf_MaxConnections > 0 )
216 /* konfiguriertes Limit beachten */
217 if( Pool_Size > Conf_MaxConnections ) Pool_Size = Conf_MaxConnections;
219 My_Connections = (CONNECTION *) calloc( Pool_Size, sizeof( CONNECTION ) );
220 if( ! My_Connections )
222 /* Speicher konnte nicht alloziert werden! */
223 Log( LOG_EMERG, "Can't allocate memory! [Conn_Init]" );
227 Log( LOG_DEBUG, "Allocated connection pool for %d items (%ld bytes).", Pool_Size, sizeof( CONNECTION ) * Pool_Size );
230 array_free( &My_Listeners );
232 /* Connection-Struktur initialisieren */
233 for( i = 0; i < Pool_Size; i++ ) Init_Conn_Struct( i );
235 /* Global write counter */
243 /* Modul abmelden: alle noch offenen Connections
244 * schliessen und freigeben. */
249 Log( LOG_DEBUG, "Shutting down all connections ..." );
252 Conn_ExitListeners();
254 /* Sockets schliessen */
255 for( idx = 0; idx < Pool_Size; idx++ ) {
256 if( My_Connections[idx].sock > NONE ) {
257 Conn_Close( idx, NULL, NGIRCd_SignalRestart ?
258 "Server going down (restarting)":"Server going down", true );
263 free( My_Connections );
264 My_Connections = NULL;
266 io_library_shutdown();
271 ports_initlisteners(array *a, void (*func)(int,short))
273 unsigned int created = 0, len;
277 len = array_length(a, sizeof (UINT16));
278 port = array_start(a);
280 fd = NewListener( *port );
285 if (!io_event_create( fd, IO_WANTREAD, func )) {
286 Log( LOG_ERR, "io_event_create(): Could not add listening fd %d (port %u): %s!",
287 fd, (unsigned int) *port, strerror(errno));
301 Conn_InitListeners( void )
303 /* Initialize ports on which the server should accept connections */
305 unsigned int created;
307 if (!io_library_init(CONNECTION_POOL)) {
308 Log(LOG_EMERG, "Cannot initialize IO routines: %s", strerror(errno));
312 created = ports_initlisteners(&Conf_ListenPorts, cb_listen);
315 } /* Conn_InitListeners */
319 Conn_ExitListeners( void )
321 /* Close down all listening sockets */
325 Rendezvous_UnregisterListeners( );
328 arraylen = array_length(&My_Listeners, sizeof (int));
329 Log( LOG_INFO, "Shutting down all listening sockets (%d total)...", arraylen );
330 fd = array_start(&My_Listeners);
336 Log( LOG_DEBUG, "Listening socket %d closed.", *fd );
340 array_free(&My_Listeners);
341 } /* Conn_ExitListeners */
344 /* return new listening port file descriptor or -1 on failure */
346 NewListener( const UINT16 Port )
348 /* Create new listening socket on specified port */
350 struct sockaddr_in addr;
351 struct in_addr inaddr;
354 char name[CLIENT_ID_LEN], *info;
357 /* Server-"Listen"-Socket initialisieren */
358 memset( &addr, 0, sizeof( addr ));
359 memset( &inaddr, 0, sizeof( inaddr ));
360 addr.sin_family = AF_INET;
361 addr.sin_port = htons( Port );
362 if( Conf_ListenAddress[0] )
364 #ifdef HAVE_INET_ATON
365 if( inet_aton( Conf_ListenAddress, &inaddr ) == 0 )
367 inaddr.s_addr = inet_addr( Conf_ListenAddress );
368 if( inaddr.s_addr == (unsigned)-1 )
371 Log( LOG_CRIT, "Can't listen on %s:%u: can't convert ip address %s!",
372 Conf_ListenAddress, Port, Conf_ListenAddress );
376 else inaddr.s_addr = htonl( INADDR_ANY );
377 addr.sin_addr = inaddr;
379 sock = socket( PF_INET, SOCK_STREAM, 0);
381 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
385 if( ! Init_Socket( sock )) return -1;
387 if( bind( sock, (struct sockaddr *)&addr, (socklen_t)sizeof( addr )) != 0 ) {
388 Log( LOG_CRIT, "Can't bind socket: %s!", strerror( errno ));
393 if( listen( sock, 10 ) != 0 ) {
394 Log( LOG_CRIT, "Can't listen on socket: %s!", strerror( errno ));
399 /* keep fd in list so we can close it when ngircd restarts/shuts down */
400 if (!array_catb( &My_Listeners,(char*) &sock, sizeof(int) )) {
401 Log( LOG_CRIT, "Can't add socket to My_Listeners array: %s!", strerror( errno ));
406 if( Conf_ListenAddress[0]) Log( LOG_INFO, "Now listening on %s:%d (socket %d).", Conf_ListenAddress, Port, sock );
407 else Log( LOG_INFO, "Now listening on 0.0.0.0:%d (socket %d).", Port, sock );
410 /* Get best server description text */
411 if( ! Conf_ServerInfo[0] ) info = Conf_ServerName;
414 /* Use server info string */
416 if( Conf_ServerInfo[0] == '[' )
418 /* Cut off leading hostname part in "[]" */
419 info = strchr( Conf_ServerInfo, ']' );
423 while( *info == ' ' ) info++;
426 if( ! info ) info = Conf_ServerInfo;
429 /* Add port number to description if non-standard */
430 if( Port != 6667 ) snprintf( name, sizeof( name ), "%s (port %u)", info, Port );
431 else strlcpy( name, info, sizeof( name ));
433 /* Register service */
434 Rendezvous_Register( name, MDNS_TYPE, Port );
443 /* "Main Loop.": Loop until a signal (for shutdown or restart) arrives.
444 * Call io_dispatch() to check for read/writeable sockets every second
445 * Wait for status change on pending connections (e.g: when the hostname has been resolved)
446 * check for penalty/timeouts
447 * handle input buffers
450 unsigned int wdatalen;
455 while(( ! NGIRCd_SignalQuit ) && ( ! NGIRCd_SignalRestart )) {
459 Rendezvous_Handler( );
462 /* Should the configuration be reloaded? */
463 if (NGIRCd_SignalRehash) {
467 /* Check configured servers and established links */
469 Check_Connections( );
473 /* noch volle Lese-Buffer suchen */
474 for( i = 0; i < Pool_Size; i++ ) {
475 if(( My_Connections[i].sock > NONE ) && ( array_bytes(&My_Connections[i].rbuf) > 0 ) &&
476 ( My_Connections[i].delaytime < t ))
478 /* Kann aus dem Buffer noch ein Befehl extrahiert werden? */
479 if (Handle_Buffer( i )) timeout = false;
483 /* noch volle Schreib-Puffer suchen */
484 for( i = 0; i < Pool_Size; i++ ) {
485 if ( My_Connections[i].sock <= NONE )
488 wdatalen = array_bytes(&My_Connections[i].wbuf);
491 if (( wdatalen > 0 ) || ( array_bytes(&My_Connections[i].zip.wbuf)> 0 ))
496 /* Socket der Verbindung in Set aufnehmen */
497 io_event_add( My_Connections[i].sock, IO_WANTWRITE );
501 /* von welchen Sockets koennte gelesen werden? */
502 for (i = 0; i < Pool_Size; i++ ) {
503 if ( My_Connections[i].sock <= NONE )
506 if (Resolve_INPROGRESS(&My_Connections[i].res_stat)) {
507 /* wait for completion of Resolver Sub-Process */
508 io_event_del( My_Connections[i].sock, IO_WANTREAD );
512 if ( Conn_OPTION_ISSET( &My_Connections[i], CONN_ISCONNECTING ))
513 continue; /* wait for completion of connect() */
515 if( My_Connections[i].delaytime > t ) {
516 /* Fuer die Verbindung ist eine "Penalty-Zeit" gesetzt */
517 io_event_del( My_Connections[i].sock, IO_WANTREAD );
520 io_event_add( My_Connections[i].sock, IO_WANTREAD );
523 /* (re-)set timeout - tv_sec/usec are undefined after io_dispatch() returns */
525 tv.tv_sec = timeout ? 1 : 0;
527 /* wait for activity */
528 i = io_dispatch( &tv );
529 if (i == -1 && errno != EINTR ) {
530 Log(LOG_EMERG, "Conn_Handler(): io_dispatch(): %s!", strerror(errno));
531 Log(LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE_NAME);
536 if( NGIRCd_SignalQuit ) Log( LOG_NOTICE|LOG_snotice, "Server going down NOW!" );
537 else if( NGIRCd_SignalRestart ) Log( LOG_NOTICE|LOG_snotice, "Server restarting NOW!" );
542 * Write a text string into the socket of a connection.
543 * This function automatically appends CR+LF to the string and validates that
544 * the result is a valid IRC message (oversized messages are shortened, for
545 * example). Then it calls the Conn_Write() function to do the actual sending.
546 * @param Idx Index fo the connection.
547 * @param Format Format string, see printf().
548 * @return true on success, false otherwise.
552 Conn_WriteStr( CONN_ID Idx, char *Format, ... )
555 Conn_WriteStr( Idx, Format, va_alist )
561 char buffer[COMMAND_LEN];
565 assert( Idx > NONE );
566 assert( Format != NULL );
569 va_start( ap, Format );
573 if (vsnprintf( buffer, COMMAND_LEN - 2, Format, ap ) >= COMMAND_LEN - 2 ) {
575 * The string that should be written to the socket is longer
576 * than the allowed size of COMMAND_LEN bytes (including both
577 * the CR and LF characters). This can be caused by the
578 * IRC_WriteXXX() functions when the prefix of this server had
579 * to be added to an already "quite long" command line which
580 * has been received from a regular IRC client, for example.
582 * We are not allowed to send such "oversized" messages to
583 * other servers and clients, see RFC 2812 2.3 and 2813 3.3
584 * ("these messages SHALL NOT exceed 512 characters in length,
585 * counting all characters including the trailing CR-LF").
587 * So we have a big problem here: we should send more bytes
588 * to the network than we are allowed to and we don't know
589 * the originator (any more). The "old" behaviour of blaming
590 * the receiver ("next hop") is a bad idea (it could be just
591 * an other server only routing the message!), so the only
592 * option left is to shorten the string and to hope that the
593 * result is still somewhat useful ...
597 strcpy (buffer + sizeof(buffer) - strlen(CUT_TXTSUFFIX) - 2 - 1,
603 Log(LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer);
606 strlcat( buffer, "\r\n", sizeof( buffer ));
607 ok = Conn_Write( Idx, buffer, strlen( buffer ));
608 My_Connections[Idx].msg_out++;
612 } /* Conn_WriteStr */
616 Conn_Write( CONN_ID Idx, char *Data, unsigned int Len )
618 /* Daten in Socket schreiben. Bei "fatalen" Fehlern wird
619 * der Client disconnectiert und false geliefert. */
621 assert( Idx > NONE );
622 assert( Data != NULL );
625 /* Ist der entsprechende Socket ueberhaupt noch offen? In einem
626 * "Handler-Durchlauf" kann es passieren, dass dem nicht mehr so
627 * ist, wenn einer von mehreren Conn_Write()'s fehlgeschlagen ist.
628 * In diesem Fall wird hier einfach ein Fehler geliefert. */
629 if( My_Connections[Idx].sock <= NONE )
632 Log( LOG_DEBUG, "Skipped write on closed socket (connection %d).", Idx );
637 /* Pruefen, ob im Schreibpuffer genuegend Platz ist. Ziel ist es,
638 * moeglichts viel im Puffer zu haben und _nicht_ gleich alles auf den
639 * Socket zu schreiben (u.a. wg. Komprimierung). */
640 if( array_bytes(&My_Connections[Idx].wbuf) >= WRITEBUFFER_LEN) {
641 /* Der Puffer ist dummerweise voll. Jetzt versuchen, den Puffer
642 * zu schreiben, wenn das nicht klappt, haben wir ein Problem ... */
643 if( ! Handle_Write( Idx )) return false;
645 /* check again: if our writebuf is twice als large as the initial limit: Kill connection */
646 if( array_bytes(&My_Connections[Idx].wbuf) >= (WRITEBUFFER_LEN*2)) {
647 Log( LOG_NOTICE, "Write buffer overflow (connection %d)!", Idx );
648 Conn_Close( Idx, "Write buffer overflow!", NULL, false );
654 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
655 /* Daten komprimieren und in Puffer kopieren */
656 if( ! Zip_Buffer( Idx, Data, Len )) return false;
661 /* Daten in Puffer kopieren */
662 if (!array_catb( &My_Connections[Idx].wbuf, Data, Len ))
665 My_Connections[Idx].bytes_out += Len;
668 /* Adjust global write counter */
676 Conn_Close( CONN_ID Idx, char *LogMsg, char *FwdMsg, bool InformClient )
678 /* Close connection. Open pipes of asyncronous resolver
679 * sub-processes are closed down. */
685 double in_z_k, out_z_k;
689 assert( Idx > NONE );
691 /* Is this link already shutting down? */
692 if( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ISCLOSING )) {
693 /* Conn_Close() has been called recursively for this link;
694 * probabe reason: Handle_Write() failed -- see below. */
696 Log( LOG_DEBUG, "Recursive request to close connection: %d", Idx );
701 assert( My_Connections[Idx].sock > NONE );
703 /* Mark link as "closing" */
704 Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCLOSING );
706 if( LogMsg ) txt = LogMsg;
708 if( ! txt ) txt = "Reason unknown";
710 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 ));
712 /* Search client, if any */
713 c = Client_GetFromConn( Idx );
715 /* Should the client be informed? */
718 /* Send statistics to client if registered as user: */
719 if ((c != NULL) && (Client_Type(c) == CLIENT_USER)) {
721 ":%s NOTICE %s :%sConnection statistics: client %.1f kb, server %.1f kb.",
722 Client_ID(Client_ThisServer()), Client_ID(c),
724 (double)My_Connections[Idx].bytes_in / 1024,
725 (double)My_Connections[Idx].bytes_out / 1024);
729 /* Send ERROR to client (see RFC!) */
731 Conn_WriteStr(Idx, "ERROR :%s", FwdMsg);
733 Conn_WriteStr(Idx, "ERROR :Closing connection.");
736 /* Try to write out the write buffer. Note: Handle_Write() eventually
737 * removes the CLIENT structure associated with this connection if an
738 * error occurs! So we have to re-check if there is still an valid
739 * CLIENT structure after calling Handle_Write() ...*/
740 (void)Handle_Write( Idx );
742 /* Search client, if any (re-check!) */
743 c = Client_GetFromConn( Idx );
745 /* Shut down socket */
746 if( ! io_close( My_Connections[Idx].sock ))
748 /* Oops, we can't close the socket!? This is ... ugly! */
749 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 ));
752 /* Mark socket as invalid: */
753 My_Connections[Idx].sock = NONE;
755 /* If there is still a client, unregister it now */
756 if( c ) Client_Destroy( c, LogMsg, FwdMsg, true );
758 /* Calculate statistics and log information */
759 in_k = (double)My_Connections[Idx].bytes_in / 1024;
760 out_k = (double)My_Connections[Idx].bytes_out / 1024;
762 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
763 in_z_k = (double)My_Connections[Idx].zip.bytes_in / 1024;
764 out_z_k = (double)My_Connections[Idx].zip.bytes_out / 1024;
765 in_p = (int)(( in_k * 100 ) / in_z_k );
766 out_p = (int)(( out_k * 100 ) / out_z_k );
767 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 );
772 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 );
775 /* cancel running resolver */
776 if (Resolve_INPROGRESS(&My_Connections[Idx].res_stat)) {
777 Resolve_Shutdown(&My_Connections[Idx].res_stat);
780 /* Servers: Modify time of next connect attempt? */
781 Conf_UnsetServer( Idx );
784 /* Clean up zlib, if link was compressed */
785 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
786 inflateEnd( &My_Connections[Idx].zip.in );
787 deflateEnd( &My_Connections[Idx].zip.out );
788 array_free(&My_Connections[Idx].zip.rbuf);
789 array_free(&My_Connections[Idx].zip.wbuf);
793 array_free(&My_Connections[Idx].rbuf);
794 array_free(&My_Connections[Idx].wbuf);
795 /* Clean up connection structure (=free it) */
796 Init_Conn_Struct( Idx );
799 Log( LOG_DEBUG, "Shutdown of connection %d completed.", Idx );
805 Conn_SyncServerStruct( void )
807 /* Synchronize server structures (connection IDs):
808 * connections <-> configuration */
814 for( i = 0; i < Pool_Size; i++ ) {
815 /* Established connection? */
816 if (My_Connections[i].sock < 0)
819 /* Server connection? */
820 client = Client_GetFromConn( i );
821 if(( ! client ) || ( Client_Type( client ) != CLIENT_SERVER )) continue;
823 for( c = 0; c < MAX_SERVERS; c++ )
825 /* Configured server? */
826 if( ! Conf_Server[c].host[0] ) continue;
829 if( strcmp( Conf_Server[c].name, Client_ID( client )) == 0 )
830 Conf_Server[c].conn_id = i;
833 } /* SyncServerStruct */
837 Handle_Write( CONN_ID Idx )
839 /* Daten aus Schreibpuffer versenden bzw. Connection aufbauen */
842 unsigned int wdatalen;
844 assert( Idx > NONE );
845 if ( My_Connections[Idx].sock < 0 ) {
848 "Handle_Write() on closed socket, connection %d", Idx);
852 assert( My_Connections[Idx].sock > NONE );
855 Log(LOG_DEBUG, "Handle_Write() called for connection %d ...", Idx);
858 wdatalen = array_bytes(&My_Connections[Idx].wbuf );
860 if (wdatalen == 0 && !array_bytes(&My_Connections[Idx].zip.wbuf)) {
861 io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
865 /* write buffer empty, but not compression buffer?
866 * -> flush compression buffer! */
871 io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
876 /* Zip_Flush() may have changed the write buffer ... */
877 wdatalen = array_bytes(&My_Connections[Idx].wbuf);
879 len = write(My_Connections[Idx].sock,
880 array_start(&My_Connections[Idx].wbuf), wdatalen );
883 if (errno == EAGAIN || errno == EINTR)
886 Log(LOG_ERR, "Write error on connection %d (socket %d): %s!",
887 Idx, My_Connections[Idx].sock, strerror(errno));
888 Conn_Close(Idx, "Write error!", NULL, false);
892 /* move any data not yet written to beginning */
893 array_moveleft(&My_Connections[Idx].wbuf, 1, len);
900 New_Connection( int Sock )
902 /* Neue Client-Verbindung von Listen-Socket annehmen und
903 * CLIENT-Struktur anlegen. */
906 struct request_info req;
908 struct sockaddr_in new_addr;
909 int i, new_sock, new_sock_len;
914 assert( Sock > NONE );
915 /* Connection auf Listen-Socket annehmen */
916 new_sock_len = sizeof( new_addr );
917 new_sock = accept( Sock, (struct sockaddr *)&new_addr, (socklen_t *)&new_sock_len );
920 Log( LOG_CRIT, "Can't accept connection: %s!", strerror( errno ));
925 /* Validate socket using TCP Wrappers */
926 request_init( &req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock, RQ_CLIENT_SIN, &new_addr, NULL );
928 if( ! hosts_access( &req ))
931 Log( deny_severity, "Refused connection from %s (by TCP Wrappers)!", inet_ntoa( new_addr.sin_addr ));
932 Simple_Message( new_sock, "ERROR :Connection refused" );
938 /* Socket initialisieren */
939 Init_Socket( new_sock );
941 /* Check IP-based connection limit */
942 cnt = Count_Connections( new_addr );
943 if(( Conf_MaxConnectionsIP > 0 ) && ( cnt >= Conf_MaxConnectionsIP ))
945 /* Access denied, too many connections from this IP address! */
946 Log( LOG_ERR, "Refused connection from %s: too may connections (%ld) from this IP address!", inet_ntoa( new_addr.sin_addr ), cnt);
947 Simple_Message( new_sock, "ERROR :Connection refused, too many connections from your IP address!" );
953 if (new_sock < Pool_Size)
954 assert(My_Connections[new_sock].sock == NONE );
956 if( new_sock >= Pool_Size ) {
957 new_size = Pool_Size + CONNECTION_POOL;
959 /* Im bisherigen Pool wurde keine freie Connection-Struktur mehr gefunden.
960 * Wenn erlaubt und moeglich muss nun der Pool vergroessert werden: */
961 if( Conf_MaxConnections > 0 )
963 /* Es ist ein Limit konfiguriert */
964 if( Pool_Size >= Conf_MaxConnections )
966 /* Mehr Verbindungen duerfen wir leider nicht mehr annehmen ... */
967 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached!", Pool_Size );
968 Simple_Message( new_sock, "ERROR :Connection limit reached" );
972 if( new_size > Conf_MaxConnections ) new_size = Conf_MaxConnections;
974 if( new_size < Pool_Size )
976 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached -- overflow!", Pool_Size );
977 Simple_Message( new_sock, "ERROR :Connection limit reached" );
982 ptr = (POINTER *)realloc( My_Connections, sizeof( CONNECTION ) * new_size );
984 Log( LOG_EMERG, "Can't allocate memory! [New_Connection]" );
985 Simple_Message( new_sock, "ERROR: Internal error" );
991 Log( LOG_DEBUG, "Allocated new connection pool for %ld items (%ld bytes). [realloc()]", new_size, sizeof( CONNECTION ) * new_size );
994 /* Adjust pointer to new block */
995 My_Connections = (CONNECTION *)ptr;
997 /* Initialize new items */
998 for( i = Pool_Size; i < new_size; i++ )
999 Init_Conn_Struct( i );
1001 /* Adjust new pool size */
1002 Pool_Size = new_size;
1005 /* Client-Struktur initialisieren */
1006 c = Client_NewLocal( new_sock, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWN, false );
1008 Log( LOG_ALERT, "Can't accept connection: can't create client structure!" );
1009 Simple_Message( new_sock, "ERROR :Internal error" );
1014 /* Verbindung registrieren */
1015 Init_Conn_Struct( new_sock );
1016 My_Connections[new_sock].sock = new_sock;
1017 My_Connections[new_sock].addr = new_addr;
1019 /* Neuen Socket registrieren */
1020 if (!io_event_create( new_sock, IO_WANTREAD, cb_clientserver)) {
1021 Simple_Message( new_sock, "ERROR :Internal error" );
1022 Conn_Close( new_sock, "io_event_create() failed", NULL, false );
1026 Log( LOG_INFO, "Accepted connection %d from %s:%d on socket %d.", new_sock,
1027 inet_ntoa( new_addr.sin_addr ), ntohs( new_addr.sin_port), Sock );
1029 /* Hostnamen ermitteln */
1030 strlcpy( My_Connections[new_sock].host, inet_ntoa( new_addr.sin_addr ),
1031 sizeof( My_Connections[new_sock].host ));
1033 Client_SetHostname( c, My_Connections[new_sock].host );
1035 Resolve_Addr(&My_Connections[new_sock].res_stat, &new_addr,
1036 My_Connections[new_sock].sock, cb_Read_Resolver_Result);
1038 /* Penalty-Zeit setzen */
1039 Conn_SetPenalty( new_sock, 4 );
1041 } /* New_Connection */
1045 Socket2Index( int Sock )
1047 /* zum Socket passende Connection suchen */
1049 assert( Sock >= 0 );
1051 if( Sock >= Pool_Size || My_Connections[Sock].sock != Sock ) {
1052 /* die Connection wurde vermutlich (wegen eines
1053 * Fehlers) bereits wieder abgebaut ... */
1055 Log( LOG_DEBUG, "Socket2Index: can't get connection for socket %d!", Sock );
1060 } /* Socket2Index */
1064 Read_Request( CONN_ID Idx )
1066 /* Daten von Socket einlesen und entsprechend behandeln.
1067 * Tritt ein Fehler auf, so wird der Socket geschlossen. */
1073 assert( Idx > NONE );
1074 assert( My_Connections[Idx].sock > NONE );
1077 if (( array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN ) ||
1078 ( array_bytes(&My_Connections[Idx].zip.rbuf) >= ZREADBUFFER_LEN ))
1080 if ( array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN )
1083 /* Der Lesepuffer ist voll */
1084 Log( LOG_ERR, "Receive buffer overflow (connection %d): %d bytes!", Idx,
1085 array_bytes(&My_Connections[Idx].rbuf));
1086 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1090 len = read( My_Connections[Idx].sock, readbuf, sizeof readbuf -1 );
1092 Log( LOG_INFO, "%s:%d (%s) is closing the connection ...",
1093 My_Connections[Idx].host, ntohs( My_Connections[Idx].addr.sin_port),
1094 inet_ntoa( My_Connections[Idx].addr.sin_addr ));
1095 Conn_Close( Idx, "Socket closed!", "Client closed connection", false );
1100 if( errno == EAGAIN ) return;
1101 Log( LOG_ERR, "Read error on connection %d (socket %d): %s!", Idx,
1102 My_Connections[Idx].sock, strerror( errno ));
1103 Conn_Close( Idx, "Read error!", "Client closed connection", false );
1107 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
1108 if (!array_catb( &My_Connections[Idx].zip.rbuf, readbuf, len)) {
1109 Log( LOG_ERR, "Could not append recieved data to zip input buffer (connn %d): %d bytes!", Idx, len );
1110 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1117 if (!array_cats( &My_Connections[Idx].rbuf, readbuf )) {
1118 Log( LOG_ERR, "Could not append recieved data to input buffer (connn %d): %d bytes!", Idx, len );
1119 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1123 /* Update connection statistics */
1124 My_Connections[Idx].bytes_in += len;
1126 /* Update timestamp of last data received if this connection is
1127 * registered as a user, server or service connection. Don't update
1128 * otherwise, so users have at least Conf_PongTimeout seconds time to
1129 * register with the IRC server -- see Check_Connections(). */
1130 c = Client_GetFromConn(Idx);
1131 if (c && (Client_Type(c) == CLIENT_USER
1132 || Client_Type(c) == CLIENT_SERVER
1133 || Client_Type(c) == CLIENT_SERVICE))
1134 My_Connections[Idx].lastdata = time(NULL);
1136 /* Look at the data in the (read-) buffer of this connection */
1138 } /* Read_Request */
1142 Handle_Buffer( CONN_ID Idx )
1144 /* Handle Data in Connections Read-Buffer.
1145 * Return true if a reuqest was handled, false otherwise (also returned on errors). */
1159 if( My_Connections[Idx].delaytime > time( NULL )) return result;
1161 /* unpack compressed data */
1162 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP ))
1163 if( ! Unzip_Buffer( Idx )) return false;
1166 if (0 == array_bytes(&My_Connections[Idx].rbuf))
1169 if (!array_cat0_temporary(&My_Connections[Idx].rbuf)) /* make sure buf is NULL terminated */
1172 /* A Complete Request end with CR+LF, see RFC 2812. */
1173 ptr = strstr( array_start(&My_Connections[Idx].rbuf), "\r\n" );
1175 if( ptr ) delta = 2; /* complete request */
1178 /* Check for non-RFC-compliant request (only CR or LF)? Unfortunately,
1179 * there are quite a few clients that do this (incl. "mIRC" :-( */
1180 ptr1 = strchr( array_start(&My_Connections[Idx].rbuf), '\r' );
1181 ptr2 = strchr( array_start(&My_Connections[Idx].rbuf), '\n' );
1183 if( ptr1 && ptr2 ) ptr = ptr1 > ptr2 ? ptr2 : ptr1;
1184 else if( ptr1 ) ptr = ptr1;
1185 else if( ptr2 ) ptr = ptr2;
1192 /* End of request found */
1195 len = ( ptr - (char*) array_start(&My_Connections[Idx].rbuf)) + delta;
1197 if( len < 0 || len > ( COMMAND_LEN - 1 )) {
1198 /* Request must not exceed 512 chars (incl. CR+LF!), see
1199 * RFC 2812. Disconnect Client if this happens. */
1200 Log( LOG_ERR, "Request too long (connection %d): %d bytes (max. %d expected)!",
1201 Idx, array_bytes(&My_Connections[Idx].rbuf), COMMAND_LEN - 1 );
1202 Conn_Close( Idx, NULL, "Request too long", true );
1206 if (len <= 2) { /* request was empty (only '\r\n') */
1207 array_moveleft(&My_Connections[Idx].rbuf, 1, delta); /* delta is either 1 or 2 */
1211 /* remember if stream is already compressed */
1212 old_z = My_Connections[Idx].options & CONN_ZIP;
1215 My_Connections[Idx].msg_in++;
1216 if (!Parse_Request(Idx, (char*)array_start(&My_Connections[Idx].rbuf) ))
1221 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1224 "Connection %d: %d bytes left in read buffer.",
1225 Idx, array_bytes(&My_Connections[Idx].rbuf));
1228 if(( ! old_z ) && ( My_Connections[Idx].options & CONN_ZIP ) &&
1229 ( array_bytes(&My_Connections[Idx].rbuf) > 0 ))
1231 /* The last Command activated Socket-Compression.
1232 * Data that was read after that needs to be copied to Unzip-buf
1233 * for decompression */
1234 if( array_bytes(&My_Connections[Idx].rbuf)> ZREADBUFFER_LEN ) {
1235 Log( LOG_ALERT, "Connection %d: No space left in unzip buf (need %u bytes)!",
1236 Idx, array_bytes(&My_Connections[Idx].rbuf ));
1239 if (!array_copy( &My_Connections[Idx].zip.rbuf, &My_Connections[Idx].rbuf ))
1242 array_trunc(&My_Connections[Idx].rbuf);
1244 Log( LOG_DEBUG, "Moved already received data (%u bytes) to uncompression buffer.",
1245 array_bytes(&My_Connections[Idx].zip.rbuf));
1252 } /* Handle_Buffer */
1256 Check_Connections( void )
1258 /* check if connections are alive. if not, play PING-PONG first.
1259 * if this doesn't help either, disconnect client. */
1263 for( i = 0; i < Pool_Size; i++ ) {
1264 if (My_Connections[i].sock < 0)
1267 c = Client_GetFromConn( i );
1268 if( c && (( Client_Type( c ) == CLIENT_USER ) || ( Client_Type( c ) == CLIENT_SERVER ) || ( Client_Type( c ) == CLIENT_SERVICE )))
1270 /* connected User, Server or Service */
1271 if( My_Connections[i].lastping > My_Connections[i].lastdata ) {
1272 /* we already sent a ping */
1273 if( My_Connections[i].lastping < time( NULL ) - Conf_PongTimeout ) {
1276 Log( LOG_DEBUG, "Connection %d: Ping timeout: %d seconds.", i, Conf_PongTimeout );
1278 Conn_Close( i, NULL, "Ping timeout", true );
1281 else if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout ) {
1282 /* we need to sent a PING */
1284 Log( LOG_DEBUG, "Connection %d: sending PING ...", i );
1286 My_Connections[i].lastping = time( NULL );
1287 Conn_WriteStr( i, "PING :%s", Client_ID( Client_ThisServer( )));
1292 /* The connection is not fully established yet, so
1293 * we don't do the PING-PONG game here but instead
1294 * disconnect the client after "a short time" if it's
1295 * still not registered. */
1297 if (My_Connections[i].lastdata <
1298 time(NULL) - Conf_PongTimeout) {
1301 "Unregistered connection %d timed out ...",
1304 Conn_Close(i, NULL, "Timeout", false);
1308 } /* Check_Connections */
1312 Check_Servers( void )
1314 /* Check if we can establish further server links */
1319 /* Check all configured servers */
1320 for( i = 0; i < MAX_SERVERS; i++ ) {
1321 /* Valid outgoing server which isn't already connected or disabled? */
1322 if(( ! Conf_Server[i].host[0] ) || ( ! Conf_Server[i].port > 0 ) ||
1323 ( Conf_Server[i].conn_id > NONE ) || ( Conf_Server[i].flags & CONF_SFLAG_DISABLED ))
1326 /* Is there already a connection in this group? */
1327 if( Conf_Server[i].group > NONE ) {
1328 for (n = 0; n < MAX_SERVERS; n++) {
1329 if (n == i) continue;
1330 if ((Conf_Server[n].conn_id > NONE) &&
1331 (Conf_Server[n].group == Conf_Server[i].group))
1334 if (n < MAX_SERVERS) continue;
1337 /* Check last connect attempt? */
1338 time_now = time(NULL);
1339 if( Conf_Server[i].lasttry > (time_now - Conf_ConnectRetry))
1342 /* Okay, try to connect now */
1343 Conf_Server[i].lasttry = time_now;
1344 assert(Resolve_Getfd(&Conf_Server[i].res_stat) < 0);
1345 Resolve_Name(&Conf_Server[i].res_stat, Conf_Server[i].host, cb_Connect_to_Server);
1347 } /* Check_Servers */
1351 New_Server( int Server )
1353 /* Establish new server link */
1355 struct sockaddr_in new_addr;
1356 struct in_addr inaddr;
1360 assert( Server > NONE );
1362 Log( LOG_INFO, "Establishing connection to \"%s\", %s, port %d ... ", Conf_Server[Server].host,
1363 Conf_Server[Server].ip, Conf_Server[Server].port );
1365 #ifdef HAVE_INET_ATON
1366 if( inet_aton( Conf_Server[Server].ip, &inaddr ) == 0 )
1368 memset( &inaddr, 0, sizeof( inaddr ));
1369 inaddr.s_addr = inet_addr( Conf_Server[Server].ip );
1370 if( inaddr.s_addr == (unsigned)-1 )
1373 Log( LOG_ERR, "Can't connect to \"%s\": can't convert ip address %s!",
1374 Conf_Server[Server].host, Conf_Server[Server].ip );
1378 memset( &new_addr, 0, sizeof( new_addr ));
1379 new_addr.sin_family = AF_INET;
1380 new_addr.sin_addr = inaddr;
1381 new_addr.sin_port = htons( Conf_Server[Server].port );
1383 new_sock = socket( PF_INET, SOCK_STREAM, 0 );
1384 if ( new_sock < 0 ) {
1385 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
1389 if( ! Init_Socket( new_sock )) return;
1391 res = connect( new_sock, (struct sockaddr *)&new_addr, sizeof( new_addr ));
1392 if(( res != 0 ) && ( errno != EINPROGRESS )) {
1393 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1397 if (new_sock >= Pool_Size) {
1398 Log( LOG_ALERT, "Can't establist server connection: connection limit reached (%d)!",
1404 assert(My_Connections[new_sock].sock < 0 );
1406 Init_Conn_Struct(new_sock);
1408 c = Client_NewLocal( new_sock, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWNSERVER, false );
1410 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1415 Client_SetIntroducer( c, c );
1416 Client_SetToken( c, TOKEN_OUTBOUND );
1418 /* Register connection */
1419 Conf_Server[Server].conn_id = new_sock;
1420 My_Connections[new_sock].sock = new_sock;
1421 My_Connections[new_sock].addr = new_addr;
1422 strlcpy( My_Connections[new_sock].host, Conf_Server[Server].host,
1423 sizeof(My_Connections[new_sock].host ));
1425 /* Register new socket */
1426 if (!io_event_create( new_sock, IO_WANTWRITE, cb_connserver)) {
1427 Log( LOG_ALERT, "io_event_create(): could not add fd %d", strerror(errno));
1428 Conn_Close( new_sock, "io_event_create() failed", NULL, false );
1429 Init_Conn_Struct( new_sock );
1430 Conf_Server[Server].conn_id = NONE;
1434 Log( LOG_DEBUG, "Registered new connection %d on socket %d.",
1435 new_sock, My_Connections[new_sock].sock );
1437 Conn_OPTION_ADD( &My_Connections[new_sock], CONN_ISCONNECTING );
1442 Init_Conn_Struct( CONN_ID Idx )
1444 time_t now = time( NULL );
1445 /* Connection-Struktur initialisieren */
1447 memset( &My_Connections[Idx], 0, sizeof ( CONNECTION ));
1448 My_Connections[Idx].sock = -1;
1449 My_Connections[Idx].lastdata = now;
1450 My_Connections[Idx].lastprivmsg = now;
1451 Resolve_Init(&My_Connections[Idx].res_stat);
1452 } /* Init_Conn_Struct */
1456 Init_Socket( int Sock )
1458 /* Initialize socket (set options) */
1462 if (!io_setnonblock(Sock)) {
1463 Log( LOG_CRIT, "Can't enable non-blocking mode for socket: %s!", strerror( errno ));
1468 /* Don't block this port after socket shutdown */
1470 if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &value, (socklen_t)sizeof( value )) != 0 )
1472 Log( LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!", strerror( errno ));
1473 /* ignore this error */
1476 /* Set type of service (TOS) */
1477 #if defined(IP_TOS) && defined(IPTOS_LOWDELAY)
1478 value = IPTOS_LOWDELAY;
1480 Log( LOG_DEBUG, "Setting option IP_TOS on socket %d to IPTOS_LOWDELAY (%d).", Sock, value );
1482 if( setsockopt( Sock, SOL_IP, IP_TOS, &value, (socklen_t)sizeof( value )) != 0 )
1484 Log( LOG_ERR, "Can't set socket option IP_TOS: %s!", strerror( errno ));
1485 /* ignore this error */
1495 cb_Connect_to_Server(int fd, UNUSED short events)
1497 /* Read result of resolver sub-process from pipe and start connection */
1500 char readbuf[HOST_LEN + 1];
1503 Log( LOG_DEBUG, "Resolver: Got forward lookup callback on fd %d, events %d", fd, events);
1505 for (i=0; i < MAX_SERVERS; i++) {
1506 if (Resolve_Getfd(&Conf_Server[i].res_stat) == fd )
1510 if( i >= MAX_SERVERS) {
1511 /* Ops, no matching server found?! */
1514 Log( LOG_DEBUG, "Resolver: Got Forward Lookup callback for unknown server!?" );
1519 /* Read result from pipe */
1520 len = Resolve_Read(&Conf_Server[i].res_stat, readbuf, sizeof readbuf -1);
1524 readbuf[len] = '\0';
1526 Log( LOG_DEBUG, "Got result from resolver: \"%s\" (%u bytes read).", readbuf, len);
1528 strlcpy( Conf_Server[i].ip, readbuf, sizeof( Conf_Server[i].ip ));
1532 } /* cb_Read_Forward_Lookup */
1536 cb_Read_Resolver_Result( int r_fd, UNUSED short events )
1538 /* Read result of resolver sub-process from pipe and update the
1539 * apropriate connection/client structure(s): hostname and/or
1540 * IDENT user name.*/
1547 char readbuf[HOST_LEN + 2 + CLIENT_USER_LEN];
1549 char readbuf[HOST_LEN + 1];
1553 Log( LOG_DEBUG, "Resolver: Got callback on fd %d, events %d", r_fd, events );
1556 /* Search associated connection ... */
1557 for( i = 0; i < Pool_Size; i++ ) {
1558 if(( My_Connections[i].sock != NONE )
1559 && ( Resolve_Getfd(&My_Connections[i].res_stat) == r_fd ))
1562 if( i >= Pool_Size ) {
1563 /* Ops, none found? Probably the connection has already
1564 * been closed!? We'll ignore that ... */
1567 Log( LOG_DEBUG, "Resolver: Got callback for unknown connection!?" );
1572 /* Read result from pipe */
1573 len = Resolve_Read(&My_Connections[i].res_stat, readbuf, sizeof readbuf -1);
1577 readbuf[len] = '\0';
1578 identptr = strchr(readbuf, '\n');
1579 assert(identptr != NULL);
1581 Log( LOG_CRIT, "Resolver: Got malformed result!");
1587 Log( LOG_DEBUG, "Got result from resolver: \"%s\" (%u bytes read).", readbuf, len);
1589 /* Okay, we got a complete result: this is a host name for outgoing
1590 * connections and a host name and IDENT user name (if enabled) for
1591 * incoming connections.*/
1592 assert ( My_Connections[i].sock >= 0 );
1593 /* Incoming connection. Search client ... */
1594 c = Client_GetFromConn( i );
1595 assert( c != NULL );
1597 /* Only update client information of unregistered clients */
1598 if( Client_Type( c ) == CLIENT_UNKNOWN ) {
1599 strlcpy(My_Connections[i].host, readbuf, sizeof( My_Connections[i].host));
1600 Client_SetHostname( c, readbuf);
1604 Log( LOG_INFO, "IDENT lookup for connection %ld: \"%s\".", i, identptr);
1605 Client_SetUser( c, identptr, true );
1607 Log( LOG_INFO, "IDENT lookup for connection %ld: no result.", i );
1612 else Log( LOG_DEBUG, "Resolver: discarding result for already registered connection %d.", i );
1614 /* Reset penalty time */
1615 Conn_ResetPenalty( i );
1616 } /* cb_Read_Resolver_Result */
1620 Simple_Message( int Sock, char *Msg )
1622 char buf[COMMAND_LEN];
1623 /* Write "simple" message to socket, without using compression
1624 * or even the connection write buffers. Used e.g. for error
1625 * messages by New_Connection(). */
1626 assert( Sock > NONE );
1627 assert( Msg != NULL );
1629 strlcpy( buf, Msg, sizeof buf - 2);
1630 strlcat( buf, "\r\n", sizeof buf);
1631 (void)write( Sock, buf, strlen( buf ) );
1632 } /* Simple_Error */
1636 Count_Connections( struct sockaddr_in addr_in )
1641 for( i = 0; i < Pool_Size; i++ ) {
1642 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].addr.sin_addr.s_addr == addr_in.sin_addr.s_addr )) cnt++;
1645 } /* Count_Connections */