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.197 2006/07/23 15:22:56 alex 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, const 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;
100 static array My_ConnArray;
103 int allow_severity = LOG_INFO;
104 int deny_severity = LOG_ERR;
107 static void server_login PARAMS((CONN_ID idx));
109 static void cb_Read_Resolver_Result PARAMS(( int sock, UNUSED short what));
110 static void cb_Connect_to_Server PARAMS(( int sock, UNUSED short what));
111 static void cb_clientserver PARAMS((int sock, short what));
114 cb_listen(int sock, short irrelevant)
117 New_Connection( sock );
122 cb_connserver(int sock, UNUSED short what)
127 CONN_ID idx = Socket2Index( sock );
129 LogDebug("cb_connserver wants to write on unknown socket?!");
134 assert( what & IO_WANTWRITE);
136 /* connect() finished, get result. */
137 sock_len = sizeof( err );
138 res = getsockopt( My_Connections[idx].sock, SOL_SOCKET, SO_ERROR, &err, &sock_len );
139 assert( sock_len == sizeof( err ));
141 /* Error while connecting? */
142 if ((res != 0) || (err != 0)) {
144 Log(LOG_CRIT, "getsockopt (connection %d): %s!",
145 idx, strerror(errno));
148 "Can't connect socket to \"%s:%d\" (connection %d): %s!",
149 My_Connections[idx].host,
150 Conf_Server[Conf_GetServer(idx)].port,
153 /* Clean up the CLIENT structure (to avoid silly log
154 * messages) and call Conn_Close() to do the rest. */
155 c = Conn_GetClient(idx);
157 Client_DestroyNow(c);
159 Conn_Close(idx, "Can't connect!", NULL, false);
164 Conn_OPTION_DEL( &My_Connections[idx], CONN_ISCONNECTING );
170 server_login(CONN_ID idx)
172 Log( LOG_INFO, "Connection %d with \"%s:%d\" established. Now logging in ...", idx,
173 My_Connections[idx].host, Conf_Server[Conf_GetServer( idx )].port );
175 io_event_setcb( My_Connections[idx].sock, cb_clientserver);
176 io_event_add( My_Connections[idx].sock, IO_WANTREAD|IO_WANTWRITE);
178 /* Send PASS and SERVER command to peer */
179 Conn_WriteStr( idx, "PASS %s %s", Conf_Server[Conf_GetServer( idx )].pwd_out, NGIRCd_ProtoID );
180 Conn_WriteStr( idx, "SERVER %s :%s", Conf_ServerName, Conf_ServerInfo );
185 cb_clientserver(int sock, short what)
187 CONN_ID idx = Socket2Index( sock );
190 Log(LOG_WARNING, "WTF: cb_clientserver wants to write on unknown socket?!");
196 if (what & IO_WANTREAD)
199 if (what & IO_WANTWRITE)
207 /* Modul initialisieren: statische Strukturen "ausnullen". */
211 /* Speicher fuer Verbindungs-Pool anfordern */
212 Pool_Size = CONNECTION_POOL;
213 if( Conf_MaxConnections > 0 )
215 /* konfiguriertes Limit beachten */
216 if( Pool_Size > Conf_MaxConnections ) Pool_Size = Conf_MaxConnections;
219 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)Pool_Size)) {
220 Log( LOG_EMERG, "Can't allocate memory! [Conn_Init]" );
224 /* FIXME: My_Connetions/Pool_Size is needed by other parts of the
225 * code; remove them! */
226 My_Connections = (CONNECTION*) array_start(&My_ConnArray);
228 LogDebug("Allocated connection pool for %d items (%ld bytes).",
229 array_length(&My_ConnArray, sizeof( CONNECTION )), array_bytes(&My_ConnArray));
231 assert( array_length(&My_ConnArray, sizeof( CONNECTION )) >= (size_t) Pool_Size);
233 array_free( &My_Listeners );
235 /* Connection-Struktur initialisieren */
236 for( i = 0; i < Pool_Size; i++ ) Init_Conn_Struct( i );
238 /* Global write counter */
246 /* Modul abmelden: alle noch offenen Connections
247 * schliessen und freigeben. */
251 LogDebug("Shutting down all connections ..." );
253 Conn_ExitListeners();
255 /* Sockets schliessen */
256 for( idx = 0; idx < Pool_Size; idx++ ) {
257 if( My_Connections[idx].sock > NONE ) {
258 Conn_Close( idx, NULL, NGIRCd_SignalRestart ?
259 "Server going down (restarting)":"Server going down", true );
263 array_free(&My_ConnArray);
264 My_Connections = NULL;
266 io_library_shutdown();
271 ports_initlisteners(array *a, void (*func)(int,short))
278 len = array_length(a, sizeof (UINT16));
279 port = array_start(a);
281 fd = NewListener( *port );
286 if (!io_event_create( fd, IO_WANTREAD, func )) {
287 Log( LOG_ERR, "io_event_create(): Could not add listening fd %d (port %u): %s!",
288 fd, (unsigned int) *port, strerror(errno));
302 Conn_InitListeners( void )
304 /* Initialize ports on which the server should accept connections */
308 if (!io_library_init(CONNECTION_POOL)) {
309 Log(LOG_EMERG, "Cannot initialize IO routines: %s", strerror(errno));
313 created = ports_initlisteners(&Conf_ListenPorts, cb_listen);
316 } /* Conn_InitListeners */
320 Conn_ExitListeners( void )
322 /* Close down all listening sockets */
326 Rendezvous_UnregisterListeners( );
329 arraylen = array_length(&My_Listeners, sizeof (int));
330 Log( LOG_INFO, "Shutting down all listening sockets (%d total)...", arraylen );
331 fd = array_start(&My_Listeners);
336 LogDebug("Listening socket %d closed.", *fd );
339 array_free(&My_Listeners);
340 } /* Conn_ExitListeners */
343 /* return new listening port file descriptor or -1 on failure */
345 NewListener( const UINT16 Port )
347 /* Create new listening socket on specified port */
349 struct sockaddr_in addr;
350 struct in_addr inaddr;
353 char name[CLIENT_ID_LEN], *info;
356 /* Server-"Listen"-Socket initialisieren */
357 memset( &addr, 0, sizeof( addr ));
358 memset( &inaddr, 0, sizeof( inaddr ));
359 addr.sin_family = (sa_family_t)AF_INET;
360 addr.sin_port = htons( Port );
361 if( Conf_ListenAddress[0] )
363 #ifdef HAVE_INET_ATON
364 if( inet_aton( Conf_ListenAddress, &inaddr ) == 0 )
366 inaddr.s_addr = inet_addr( Conf_ListenAddress );
367 if( inaddr.s_addr == (unsigned)-1 )
370 Log( LOG_CRIT, "Can't listen on %s:%u: can't convert ip address %s!",
371 Conf_ListenAddress, Port, Conf_ListenAddress );
375 else inaddr.s_addr = htonl( INADDR_ANY );
376 addr.sin_addr = inaddr;
378 sock = socket( PF_INET, SOCK_STREAM, 0);
380 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
384 if( ! Init_Socket( sock )) return -1;
386 if (bind(sock, (struct sockaddr *)&addr, (socklen_t)sizeof(addr)) != 0) {
387 Log( LOG_CRIT, "Can't bind socket: %s!", strerror( errno ));
392 if( listen( sock, 10 ) != 0 ) {
393 Log( LOG_CRIT, "Can't listen on socket: %s!", strerror( errno ));
398 /* keep fd in list so we can close it when ngircd restarts/shuts down */
399 if (!array_catb( &My_Listeners,(char*) &sock, sizeof(int) )) {
400 Log( LOG_CRIT, "Can't add socket to My_Listeners array: %s!", strerror( errno ));
405 if( Conf_ListenAddress[0]) Log( LOG_INFO, "Now listening on %s:%d (socket %d).", Conf_ListenAddress, Port, sock );
406 else Log( LOG_INFO, "Now listening on 0.0.0.0:%d (socket %d).", Port, sock );
409 /* Get best server description text */
410 if( ! Conf_ServerInfo[0] ) info = Conf_ServerName;
413 /* Use server info string */
415 if( Conf_ServerInfo[0] == '[' )
417 /* Cut off leading hostname part in "[]" */
418 info = strchr( Conf_ServerInfo, ']' );
422 while( *info == ' ' ) info++;
425 if( ! info ) info = Conf_ServerInfo;
428 /* Add port number to description if non-standard */
430 snprintf(name, sizeof name, "%s (port %u)", info,
433 strlcpy(name, info, sizeof name);
435 /* Register service */
436 Rendezvous_Register( name, MDNS_TYPE, Port );
445 /* "Main Loop.": Loop until a signal (for shutdown or restart) arrives.
446 * Call io_dispatch() to check for read/writeable sockets every second
447 * Wait for status change on pending connections (e.g: when the hostname has been resolved)
448 * check for penalty/timeouts
449 * handle input buffers
452 unsigned int wdatalen;
457 while(( ! NGIRCd_SignalQuit ) && ( ! NGIRCd_SignalRestart )) {
461 Rendezvous_Handler( );
464 /* Should the configuration be reloaded? */
465 if (NGIRCd_SignalRehash) {
469 /* Check configured servers and established links */
471 Check_Connections( );
475 /* noch volle Lese-Buffer suchen */
476 for( i = 0; i < Pool_Size; i++ ) {
477 if(( My_Connections[i].sock > NONE ) && ( array_bytes(&My_Connections[i].rbuf) > 0 ) &&
478 ( My_Connections[i].delaytime < t ))
480 /* Kann aus dem Buffer noch ein Befehl extrahiert werden? */
481 if (Handle_Buffer( i )) timeout = false;
485 /* noch volle Schreib-Puffer suchen */
486 for( i = 0; i < Pool_Size; i++ ) {
487 if ( My_Connections[i].sock <= NONE )
490 wdatalen = (unsigned int)array_bytes(&My_Connections[i].wbuf);
493 if (( wdatalen > 0 ) || ( array_bytes(&My_Connections[i].zip.wbuf)> 0 ))
498 /* Socket der Verbindung in Set aufnehmen */
499 io_event_add( My_Connections[i].sock, IO_WANTWRITE );
503 /* von welchen Sockets koennte gelesen werden? */
504 for (i = 0; i < Pool_Size; i++ ) {
505 if ( My_Connections[i].sock <= NONE )
508 if (Resolve_INPROGRESS(&My_Connections[i].res_stat)) {
509 /* wait for completion of Resolver Sub-Process */
510 io_event_del( My_Connections[i].sock, IO_WANTREAD );
514 if ( Conn_OPTION_ISSET( &My_Connections[i], CONN_ISCONNECTING ))
515 continue; /* wait for completion of connect() */
517 if( My_Connections[i].delaytime > t ) {
518 /* Fuer die Verbindung ist eine "Penalty-Zeit" gesetzt */
519 io_event_del( My_Connections[i].sock, IO_WANTREAD );
522 io_event_add( My_Connections[i].sock, IO_WANTREAD );
525 /* (re-)set timeout - tv_sec/usec are undefined after io_dispatch() returns */
527 tv.tv_sec = timeout ? 1 : 0;
529 /* wait for activity */
530 i = io_dispatch( &tv );
531 if (i == -1 && errno != EINTR ) {
532 Log(LOG_EMERG, "Conn_Handler(): io_dispatch(): %s!", strerror(errno));
533 Log(LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE_NAME);
538 if( NGIRCd_SignalQuit ) Log( LOG_NOTICE|LOG_snotice, "Server going down NOW!" );
539 else if( NGIRCd_SignalRestart ) Log( LOG_NOTICE|LOG_snotice, "Server restarting NOW!" );
544 * Write a text string into the socket of a connection.
545 * This function automatically appends CR+LF to the string and validates that
546 * the result is a valid IRC message (oversized messages are shortened, for
547 * example). Then it calls the Conn_Write() function to do the actual sending.
548 * @param Idx Index fo the connection.
549 * @param Format Format string, see printf().
550 * @return true on success, false otherwise.
554 Conn_WriteStr( CONN_ID Idx, char *Format, ... )
557 Conn_WriteStr( Idx, Format, va_alist )
563 char buffer[COMMAND_LEN];
568 assert( Idx > NONE );
569 assert( Format != NULL );
572 va_start( ap, Format );
576 if (vsnprintf( buffer, COMMAND_LEN - 2, Format, ap ) >= COMMAND_LEN - 2 ) {
578 * The string that should be written to the socket is longer
579 * than the allowed size of COMMAND_LEN bytes (including both
580 * the CR and LF characters). This can be caused by the
581 * IRC_WriteXXX() functions when the prefix of this server had
582 * to be added to an already "quite long" command line which
583 * has been received from a regular IRC client, for example.
585 * We are not allowed to send such "oversized" messages to
586 * other servers and clients, see RFC 2812 2.3 and 2813 3.3
587 * ("these messages SHALL NOT exceed 512 characters in length,
588 * counting all characters including the trailing CR-LF").
590 * So we have a big problem here: we should send more bytes
591 * to the network than we are allowed to and we don't know
592 * the originator (any more). The "old" behaviour of blaming
593 * the receiver ("next hop") is a bad idea (it could be just
594 * an other server only routing the message!), so the only
595 * option left is to shorten the string and to hope that the
596 * result is still somewhat useful ...
600 strcpy (buffer + sizeof(buffer) - strlen(CUT_TXTSUFFIX) - 2 - 1,
606 Log(LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer);
609 len = strlcat( buffer, "\r\n", sizeof( buffer ));
610 ok = Conn_Write(Idx, buffer, len);
611 My_Connections[Idx].msg_out++;
615 } /* Conn_WriteStr */
619 Conn_Write( CONN_ID Idx, char *Data, size_t Len )
621 /* Daten in Socket schreiben. Bei "fatalen" Fehlern wird
622 * der Client disconnectiert und false geliefert. */
624 assert( Idx > NONE );
625 assert( Data != NULL );
628 /* Ist der entsprechende Socket ueberhaupt noch offen? In einem
629 * "Handler-Durchlauf" kann es passieren, dass dem nicht mehr so
630 * ist, wenn einer von mehreren Conn_Write()'s fehlgeschlagen ist.
631 * In diesem Fall wird hier einfach ein Fehler geliefert. */
632 if( My_Connections[Idx].sock <= NONE ) {
633 LogDebug("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. */
695 LogDebug("Recursive request to close connection: %d", Idx );
699 assert( My_Connections[Idx].sock > NONE );
701 /* Mark link as "closing" */
702 Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCLOSING );
704 if( LogMsg ) txt = LogMsg;
706 if( ! txt ) txt = "Reason unknown";
708 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 ));
710 /* Search client, if any */
711 c = Conn_GetClient( Idx );
713 /* Should the client be informed? */
716 /* Send statistics to client if registered as user: */
717 if ((c != NULL) && (Client_Type(c) == CLIENT_USER)) {
719 ":%s NOTICE %s :%sConnection statistics: client %.1f kb, server %.1f kb.",
720 Client_ID(Client_ThisServer()), Client_ID(c),
722 (double)My_Connections[Idx].bytes_in / 1024,
723 (double)My_Connections[Idx].bytes_out / 1024);
727 /* Send ERROR to client (see RFC!) */
729 Conn_WriteStr(Idx, "ERROR :%s", FwdMsg);
731 Conn_WriteStr(Idx, "ERROR :Closing connection.");
734 /* Try to write out the write buffer. Note: Handle_Write() eventually
735 * removes the CLIENT structure associated with this connection if an
736 * error occurs! So we have to re-check if there is still an valid
737 * CLIENT structure after calling Handle_Write() ...*/
738 (void)Handle_Write( Idx );
740 /* Search client, if any (re-check!) */
741 c = Conn_GetClient( Idx );
743 /* Shut down socket */
744 if( ! io_close( My_Connections[Idx].sock ))
746 /* Oops, we can't close the socket!? This is ... ugly! */
747 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 ));
750 /* Mark socket as invalid: */
751 My_Connections[Idx].sock = NONE;
753 /* If there is still a client, unregister it now */
754 if( c ) Client_Destroy( c, LogMsg, FwdMsg, true );
756 /* Calculate statistics and log information */
757 in_k = (double)My_Connections[Idx].bytes_in / 1024;
758 out_k = (double)My_Connections[Idx].bytes_out / 1024;
760 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
761 in_z_k = (double)My_Connections[Idx].zip.bytes_in / 1024;
762 out_z_k = (double)My_Connections[Idx].zip.bytes_out / 1024;
763 in_p = (int)(( in_k * 100 ) / in_z_k );
764 out_p = (int)(( out_k * 100 ) / out_z_k );
765 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 );
770 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 );
773 /* cancel running resolver */
774 if (Resolve_INPROGRESS(&My_Connections[Idx].res_stat)) {
775 Resolve_Shutdown(&My_Connections[Idx].res_stat);
778 /* Servers: Modify time of next connect attempt? */
779 Conf_UnsetServer( Idx );
782 /* Clean up zlib, if link was compressed */
783 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
784 inflateEnd( &My_Connections[Idx].zip.in );
785 deflateEnd( &My_Connections[Idx].zip.out );
786 array_free(&My_Connections[Idx].zip.rbuf);
787 array_free(&My_Connections[Idx].zip.wbuf);
791 array_free(&My_Connections[Idx].rbuf);
792 array_free(&My_Connections[Idx].wbuf);
793 /* Clean up connection structure (=free it) */
794 Init_Conn_Struct( Idx );
796 LogDebug("Shutdown of connection %d completed.", Idx );
801 Conn_SyncServerStruct( void )
803 /* Synchronize server structures (connection IDs):
804 * connections <-> configuration */
810 for( i = 0; i < Pool_Size; i++ ) {
811 /* Established connection? */
812 if (My_Connections[i].sock < 0)
815 /* Server connection? */
816 client = Conn_GetClient( i );
817 if(( ! client ) || ( Client_Type( client ) != CLIENT_SERVER )) continue;
819 for( c = 0; c < MAX_SERVERS; c++ )
821 /* Configured server? */
822 if( ! Conf_Server[c].host[0] ) continue;
825 if( strcmp( Conf_Server[c].name, Client_ID( client )) == 0 )
826 Conf_Server[c].conn_id = i;
829 } /* SyncServerStruct */
833 * Send out data of write buffer; connect new sockets.
836 Handle_Write( CONN_ID Idx )
841 assert( Idx > NONE );
842 if ( My_Connections[Idx].sock < 0 ) {
843 LogDebug("Handle_Write() on closed socket, connection %d", Idx);
846 assert( My_Connections[Idx].sock > NONE );
848 wdatalen = array_bytes(&My_Connections[Idx].wbuf );
851 if (wdatalen == 0 && !array_bytes(&My_Connections[Idx].zip.wbuf)) {
852 io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
856 /* write buffer empty, but not compression buffer?
857 * -> flush compression buffer! */
862 io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
867 /* Zip_Flush() may have changed the write buffer ... */
868 wdatalen = array_bytes(&My_Connections[Idx].wbuf);
870 ("Handle_Write() called for connection %d, %ld bytes pending ...",
873 len = write(My_Connections[Idx].sock,
874 array_start(&My_Connections[Idx].wbuf), wdatalen );
877 if (errno == EAGAIN || errno == EINTR)
880 Log(LOG_ERR, "Write error on connection %d (socket %d): %s!",
881 Idx, My_Connections[Idx].sock, strerror(errno));
882 Conn_Close(Idx, "Write error!", NULL, false);
886 /* move any data not yet written to beginning */
887 array_moveleft(&My_Connections[Idx].wbuf, 1, (size_t)len);
894 New_Connection( int Sock )
896 /* Neue Client-Verbindung von Listen-Socket annehmen und
897 * CLIENT-Struktur anlegen. */
900 struct request_info req;
902 struct sockaddr_in new_addr;
903 int new_sock, new_sock_len, new_Pool_Size;
907 assert( Sock > NONE );
908 /* Connection auf Listen-Socket annehmen */
909 new_sock_len = (int)sizeof new_addr;
910 new_sock = accept(Sock, (struct sockaddr *)&new_addr,
911 (socklen_t *)&new_sock_len);
913 Log(LOG_CRIT, "Can't accept connection: %s!", strerror(errno));
918 /* Validate socket using TCP Wrappers */
919 request_init( &req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock, RQ_CLIENT_SIN, &new_addr, NULL );
921 if( ! hosts_access( &req ))
924 Log( deny_severity, "Refused connection from %s (by TCP Wrappers)!", inet_ntoa( new_addr.sin_addr ));
925 Simple_Message( new_sock, "ERROR :Connection refused" );
931 /* Socket initialisieren */
932 if (!Init_Socket( new_sock ))
935 /* Check IP-based connection limit */
936 cnt = Count_Connections( new_addr );
937 if(( Conf_MaxConnectionsIP > 0 ) && ( cnt >= Conf_MaxConnectionsIP ))
939 /* Access denied, too many connections from this IP address! */
940 Log( LOG_ERR, "Refused connection from %s: too may connections (%ld) from this IP address!", inet_ntoa( new_addr.sin_addr ), cnt);
941 Simple_Message( new_sock, "ERROR :Connection refused, too many connections from your IP address!" );
946 if( new_sock >= Pool_Size ) {
947 new_Pool_Size = new_sock + 1;
948 /* No free Connection Structures, check if we may accept further connections */
949 if ((( Conf_MaxConnections > 0) && Pool_Size >= Conf_MaxConnections) ||
950 (new_Pool_Size < Pool_Size))
952 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached!", Pool_Size );
953 Simple_Message( new_sock, "ERROR :Connection limit reached" );
958 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION),
960 Log( LOG_EMERG, "Can't allocate memory! [New_Connection]" );
961 Simple_Message( new_sock, "ERROR: Internal error" );
965 LogDebug("Bumped connection pool to %ld items (internal: %ld items, %ld bytes)",
966 new_sock, array_length(&My_ConnArray, sizeof(CONNECTION)), array_bytes(&My_ConnArray));
968 /* Adjust pointer to new block */
969 My_Connections = array_start(&My_ConnArray);
970 while (Pool_Size < new_Pool_Size)
971 Init_Conn_Struct(Pool_Size++);
974 c = Client_NewLocal( new_sock, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWN, false );
976 Log( LOG_ALERT, "Can't accept connection: can't create client structure!" );
977 Simple_Message( new_sock, "ERROR :Internal error" );
982 Init_Conn_Struct( new_sock );
983 My_Connections[new_sock].sock = new_sock;
984 My_Connections[new_sock].addr = new_addr;
985 My_Connections[new_sock].client = c;
987 /* register callback */
988 if (!io_event_create( new_sock, IO_WANTREAD, cb_clientserver)) {
989 Simple_Message( new_sock, "ERROR :Internal error" );
990 Conn_Close( new_sock, "io_event_create() failed", NULL, false );
994 Log( LOG_INFO, "Accepted connection %d from %s:%d on socket %d.", new_sock,
995 inet_ntoa( new_addr.sin_addr ), ntohs( new_addr.sin_port), Sock );
997 /* Hostnamen ermitteln */
998 strlcpy( My_Connections[new_sock].host, inet_ntoa( new_addr.sin_addr ),
999 sizeof( My_Connections[new_sock].host ));
1001 Client_SetHostname( c, My_Connections[new_sock].host );
1003 Resolve_Addr(&My_Connections[new_sock].res_stat, &new_addr,
1004 My_Connections[new_sock].sock, cb_Read_Resolver_Result);
1006 /* Penalty-Zeit setzen */
1007 Conn_SetPenalty( new_sock, 4 );
1009 } /* New_Connection */
1013 Socket2Index( int Sock )
1015 /* zum Socket passende Connection suchen */
1017 assert( Sock >= 0 );
1019 if( Sock >= Pool_Size || My_Connections[Sock].sock != Sock ) {
1020 /* die Connection wurde vermutlich (wegen eines
1021 * Fehlers) bereits wieder abgebaut ... */
1022 LogDebug("Socket2Index: can't get connection for socket %d!", Sock);
1026 } /* Socket2Index */
1030 Read_Request( CONN_ID Idx )
1032 /* Daten von Socket einlesen und entsprechend behandeln.
1033 * Tritt ein Fehler auf, so wird der Socket geschlossen. */
1039 assert( Idx > NONE );
1040 assert( My_Connections[Idx].sock > NONE );
1043 if (( array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN ) ||
1044 ( array_bytes(&My_Connections[Idx].zip.rbuf) >= ZREADBUFFER_LEN ))
1046 if ( array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN )
1049 /* Der Lesepuffer ist voll */
1050 Log( LOG_ERR, "Receive buffer overflow (connection %d): %d bytes!", Idx,
1051 array_bytes(&My_Connections[Idx].rbuf));
1052 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1056 len = read( My_Connections[Idx].sock, readbuf, sizeof readbuf -1 );
1058 Log( LOG_INFO, "%s:%d (%s) is closing the connection ...",
1059 My_Connections[Idx].host, ntohs( My_Connections[Idx].addr.sin_port),
1060 inet_ntoa( My_Connections[Idx].addr.sin_addr ));
1061 Conn_Close( Idx, "Socket closed!", "Client closed connection", false );
1066 if( errno == EAGAIN ) return;
1067 Log( LOG_ERR, "Read error on connection %d (socket %d): %s!", Idx,
1068 My_Connections[Idx].sock, strerror( errno ));
1069 Conn_Close( Idx, "Read error!", "Client closed connection", false );
1073 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1074 if (!array_catb(&My_Connections[Idx].zip.rbuf, readbuf,
1077 "Could not append recieved data to zip input buffer (connn %d): %d bytes!",
1079 Conn_Close(Idx, "Receive buffer overflow!", NULL,
1087 if (!array_cats( &My_Connections[Idx].rbuf, readbuf )) {
1088 Log( LOG_ERR, "Could not append recieved data to input buffer (connn %d): %d bytes!", Idx, len );
1089 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1093 /* Update connection statistics */
1094 My_Connections[Idx].bytes_in += len;
1096 /* Update timestamp of last data received if this connection is
1097 * registered as a user, server or service connection. Don't update
1098 * otherwise, so users have at least Conf_PongTimeout seconds time to
1099 * register with the IRC server -- see Check_Connections().
1100 * Set "lastping", too, so we can handle time shifts backwards ... */
1101 c = Conn_GetClient(Idx);
1102 if (c && (Client_Type(c) == CLIENT_USER
1103 || Client_Type(c) == CLIENT_SERVER
1104 || Client_Type(c) == CLIENT_SERVICE)) {
1105 My_Connections[Idx].lastdata = time(NULL);
1106 My_Connections[Idx].lastping = My_Connections[Idx].lastdata;
1109 /* Look at the data in the (read-) buffer of this connection */
1111 } /* Read_Request */
1115 Handle_Buffer( CONN_ID Idx )
1117 /* Handle Data in Connections Read-Buffer.
1118 * Return true if a reuqest was handled, false otherwise (also returned on errors). */
1130 starttime = time(NULL);
1134 if( My_Connections[Idx].delaytime > starttime) return result;
1136 /* unpack compressed data */
1137 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP ))
1138 if( ! Unzip_Buffer( Idx )) return false;
1141 if (0 == array_bytes(&My_Connections[Idx].rbuf))
1144 if (!array_cat0_temporary(&My_Connections[Idx].rbuf)) /* make sure buf is NULL terminated */
1147 /* A Complete Request end with CR+LF, see RFC 2812. */
1148 ptr = strstr( array_start(&My_Connections[Idx].rbuf), "\r\n" );
1150 if( ptr ) delta = 2; /* complete request */
1153 /* Check for non-RFC-compliant request (only CR or LF)? Unfortunately,
1154 * there are quite a few clients that do this (incl. "mIRC" :-( */
1155 ptr1 = strchr( array_start(&My_Connections[Idx].rbuf), '\r' );
1156 ptr2 = strchr( array_start(&My_Connections[Idx].rbuf), '\n' );
1158 if( ptr1 && ptr2 ) ptr = ptr1 > ptr2 ? ptr2 : ptr1;
1159 else if( ptr1 ) ptr = ptr1;
1160 else if( ptr2 ) ptr = ptr2;
1167 /* End of request found */
1170 len = ( ptr - (char*) array_start(&My_Connections[Idx].rbuf)) + delta;
1172 if( len > ( COMMAND_LEN - 1 )) {
1173 /* Request must not exceed 512 chars (incl. CR+LF!), see
1174 * RFC 2812. Disconnect Client if this happens. */
1175 Log( LOG_ERR, "Request too long (connection %d): %d bytes (max. %d expected)!",
1176 Idx, array_bytes(&My_Connections[Idx].rbuf), COMMAND_LEN - 1 );
1177 Conn_Close( Idx, NULL, "Request too long", true );
1181 if (len <= 2) { /* request was empty (only '\r\n') */
1182 array_moveleft(&My_Connections[Idx].rbuf, 1, delta); /* delta is either 1 or 2 */
1186 /* remember if stream is already compressed */
1187 old_z = My_Connections[Idx].options & CONN_ZIP;
1190 My_Connections[Idx].msg_in++;
1191 if (!Parse_Request(Idx, (char*)array_start(&My_Connections[Idx].rbuf) ))
1196 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1197 LogDebug("Connection %d: %d bytes left in read buffer.",
1198 Idx, array_bytes(&My_Connections[Idx].rbuf));
1200 if(( ! old_z ) && ( My_Connections[Idx].options & CONN_ZIP ) &&
1201 ( array_bytes(&My_Connections[Idx].rbuf) > 0 ))
1203 /* The last Command activated Socket-Compression.
1204 * Data that was read after that needs to be copied to Unzip-buf
1205 * for decompression */
1206 if( array_bytes(&My_Connections[Idx].rbuf)> ZREADBUFFER_LEN ) {
1207 Log( LOG_ALERT, "Connection %d: No space left in unzip buf (need %u bytes)!",
1208 Idx, array_bytes(&My_Connections[Idx].rbuf ));
1211 if (!array_copy( &My_Connections[Idx].zip.rbuf, &My_Connections[Idx].rbuf ))
1214 array_trunc(&My_Connections[Idx].rbuf);
1215 LogDebug("Moved already received data (%u bytes) to uncompression buffer.",
1216 array_bytes(&My_Connections[Idx].zip.rbuf));
1221 } /* Handle_Buffer */
1225 Check_Connections(void)
1227 /* check if connections are alive. if not, play PING-PONG first.
1228 * if this doesn't help either, disconnect client. */
1232 for (i = 0; i < Pool_Size; i++) {
1233 if (My_Connections[i].sock < 0)
1236 c = Conn_GetClient(i);
1237 if (c && ((Client_Type(c) == CLIENT_USER)
1238 || (Client_Type(c) == CLIENT_SERVER)
1239 || (Client_Type(c) == CLIENT_SERVICE))) {
1240 /* connected User, Server or Service */
1241 if (My_Connections[i].lastping >
1242 My_Connections[i].lastdata) {
1243 /* We already sent a ping */
1244 if (My_Connections[i].lastping <
1245 time(NULL) - Conf_PongTimeout) {
1248 ("Connection %d: Ping timeout: %d seconds.",
1249 i, Conf_PongTimeout);
1250 Conn_Close(i, NULL, "Ping timeout",
1253 } else if (My_Connections[i].lastdata <
1254 time(NULL) - Conf_PingTimeout) {
1255 /* We need to send a PING ... */
1256 LogDebug("Connection %d: sending PING ...", i);
1257 My_Connections[i].lastping = time(NULL);
1258 Conn_WriteStr(i, "PING :%s",
1259 Client_ID(Client_ThisServer()));
1262 /* The connection is not fully established yet, so
1263 * we don't do the PING-PONG game here but instead
1264 * disconnect the client after "a short time" if it's
1265 * still not registered. */
1267 if (My_Connections[i].lastdata <
1268 time(NULL) - Conf_PongTimeout) {
1270 ("Unregistered connection %d timed out ...",
1272 Conn_Close(i, NULL, "Timeout", false);
1276 } /* Check_Connections */
1280 Check_Servers( void )
1282 /* Check if we can establish further server links */
1287 /* Check all configured servers */
1288 for( i = 0; i < MAX_SERVERS; i++ ) {
1289 /* Valid outgoing server which isn't already connected or disabled? */
1290 if(( ! Conf_Server[i].host[0] ) || ( ! Conf_Server[i].port > 0 ) ||
1291 ( Conf_Server[i].conn_id > NONE ) || ( Conf_Server[i].flags & CONF_SFLAG_DISABLED ))
1294 /* Is there already a connection in this group? */
1295 if( Conf_Server[i].group > NONE ) {
1296 for (n = 0; n < MAX_SERVERS; n++) {
1297 if (n == i) continue;
1298 if ((Conf_Server[n].conn_id > NONE) &&
1299 (Conf_Server[n].group == Conf_Server[i].group))
1302 if (n < MAX_SERVERS) continue;
1305 /* Check last connect attempt? */
1306 time_now = time(NULL);
1307 if( Conf_Server[i].lasttry > (time_now - Conf_ConnectRetry))
1310 /* Okay, try to connect now */
1311 Conf_Server[i].lasttry = time_now;
1312 assert(Resolve_Getfd(&Conf_Server[i].res_stat) < 0);
1313 Resolve_Name(&Conf_Server[i].res_stat, Conf_Server[i].host, cb_Connect_to_Server);
1315 } /* Check_Servers */
1319 New_Server( int Server )
1321 /* Establish new server link */
1323 struct sockaddr_in new_addr;
1324 struct in_addr inaddr;
1328 assert( Server > NONE );
1330 Log( LOG_INFO, "Establishing connection to \"%s\", %s, port %d ... ", Conf_Server[Server].host,
1331 Conf_Server[Server].ip, Conf_Server[Server].port );
1333 #ifdef HAVE_INET_ATON
1334 if( inet_aton( Conf_Server[Server].ip, &inaddr ) == 0 )
1336 memset( &inaddr, 0, sizeof( inaddr ));
1337 inaddr.s_addr = inet_addr( Conf_Server[Server].ip );
1338 if( inaddr.s_addr == (unsigned)-1 )
1341 Log( LOG_ERR, "Can't connect to \"%s\": can't convert ip address %s!",
1342 Conf_Server[Server].host, Conf_Server[Server].ip );
1346 memset( &new_addr, 0, sizeof( new_addr ));
1347 new_addr.sin_family = (sa_family_t)AF_INET;
1348 new_addr.sin_addr = inaddr;
1349 new_addr.sin_port = htons( Conf_Server[Server].port );
1351 new_sock = socket( PF_INET, SOCK_STREAM, 0 );
1352 if ( new_sock < 0 ) {
1353 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
1357 if( ! Init_Socket( new_sock )) return;
1359 res = connect(new_sock, (struct sockaddr *)&new_addr,
1360 (socklen_t)sizeof(new_addr));
1361 if(( res != 0 ) && ( errno != EINPROGRESS )) {
1362 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1367 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)new_sock)) {
1369 "Cannot allocate memory for server connection (socket %d)",
1375 My_Connections = array_start(&My_ConnArray);
1377 assert(My_Connections[new_sock].sock <= 0);
1379 Init_Conn_Struct(new_sock);
1381 c = Client_NewLocal( new_sock, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWNSERVER, false );
1383 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1388 Client_SetIntroducer( c, c );
1389 Client_SetToken( c, TOKEN_OUTBOUND );
1391 /* Register connection */
1392 Conf_Server[Server].conn_id = new_sock;
1393 My_Connections[new_sock].sock = new_sock;
1394 My_Connections[new_sock].addr = new_addr;
1395 My_Connections[new_sock].client = c;
1396 strlcpy( My_Connections[new_sock].host, Conf_Server[Server].host,
1397 sizeof(My_Connections[new_sock].host ));
1399 /* Register new socket */
1400 if (!io_event_create( new_sock, IO_WANTWRITE, cb_connserver)) {
1401 Log( LOG_ALERT, "io_event_create(): could not add fd %d", strerror(errno));
1402 Conn_Close( new_sock, "io_event_create() failed", NULL, false );
1403 Init_Conn_Struct( new_sock );
1404 Conf_Server[Server].conn_id = NONE;
1407 LogDebug("Registered new connection %d on socket %d.",
1408 new_sock, My_Connections[new_sock].sock );
1409 Conn_OPTION_ADD( &My_Connections[new_sock], CONN_ISCONNECTING );
1414 Init_Conn_Struct( CONN_ID Idx )
1416 time_t now = time( NULL );
1417 /* Connection-Struktur initialisieren */
1419 memset( &My_Connections[Idx], 0, sizeof ( CONNECTION ));
1420 My_Connections[Idx].sock = -1;
1421 My_Connections[Idx].lastdata = now;
1422 My_Connections[Idx].lastprivmsg = now;
1423 Resolve_Init(&My_Connections[Idx].res_stat);
1424 } /* Init_Conn_Struct */
1428 Init_Socket( int Sock )
1430 /* Initialize socket (set options) */
1434 if (!io_setnonblock(Sock)) {
1435 Log( LOG_CRIT, "Can't enable non-blocking mode for socket: %s!", strerror( errno ));
1440 /* Don't block this port after socket shutdown */
1442 if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &value, (socklen_t)sizeof( value )) != 0 )
1444 Log( LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!", strerror( errno ));
1445 /* ignore this error */
1448 /* Set type of service (TOS) */
1449 #if defined(IP_TOS) && defined(IPTOS_LOWDELAY)
1450 value = IPTOS_LOWDELAY;
1451 LogDebug("Setting option IP_TOS on socket %d to IPTOS_LOWDELAY (%d).", Sock, value );
1452 if( setsockopt( Sock, SOL_IP, IP_TOS, &value, (socklen_t)sizeof( value )) != 0 )
1454 Log( LOG_ERR, "Can't set socket option IP_TOS: %s!", strerror( errno ));
1455 /* ignore this error */
1465 cb_Connect_to_Server(int fd, UNUSED short events)
1467 /* Read result of resolver sub-process from pipe and start connection */
1470 char readbuf[HOST_LEN + 1];
1472 LogDebug("Resolver: Got forward lookup callback on fd %d, events %d", fd, events);
1474 for (i=0; i < MAX_SERVERS; i++) {
1475 if (Resolve_Getfd(&Conf_Server[i].res_stat) == fd )
1479 if( i >= MAX_SERVERS) {
1480 /* Ops, no matching server found?! */
1482 LogDebug("Resolver: Got Forward Lookup callback for unknown server!?");
1486 /* Read result from pipe */
1487 len = Resolve_Read(&Conf_Server[i].res_stat, readbuf, sizeof readbuf -1);
1491 readbuf[len] = '\0';
1492 LogDebug("Got result from resolver: \"%s\" (%u bytes read).", readbuf, len);
1493 strlcpy( Conf_Server[i].ip, readbuf, sizeof( Conf_Server[i].ip ));
1497 } /* cb_Read_Forward_Lookup */
1501 cb_Read_Resolver_Result( int r_fd, UNUSED short events )
1503 /* Read result of resolver sub-process from pipe and update the
1504 * apropriate connection/client structure(s): hostname and/or
1505 * IDENT user name.*/
1512 char readbuf[HOST_LEN + 2 + CLIENT_USER_LEN];
1514 char readbuf[HOST_LEN + 1];
1517 LogDebug("Resolver: Got callback on fd %d, events %d", r_fd, events );
1519 /* Search associated connection ... */
1520 for( i = 0; i < Pool_Size; i++ ) {
1521 if(( My_Connections[i].sock != NONE )
1522 && ( Resolve_Getfd(&My_Connections[i].res_stat) == r_fd ))
1525 if( i >= Pool_Size ) {
1526 /* Ops, none found? Probably the connection has already
1527 * been closed!? We'll ignore that ... */
1529 LogDebug("Resolver: Got callback for unknown connection!?");
1533 /* Read result from pipe */
1534 len = Resolve_Read(&My_Connections[i].res_stat, readbuf, sizeof readbuf -1);
1538 readbuf[len] = '\0';
1539 identptr = strchr(readbuf, '\n');
1540 assert(identptr != NULL);
1542 Log( LOG_CRIT, "Resolver: Got malformed result!");
1547 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 = Conn_GetClient( 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, const char *Msg )
1581 char buf[COMMAND_LEN];
1583 /* Write "simple" message to socket, without using compression
1584 * or even the connection write buffers. Used e.g. for error
1585 * messages by New_Connection(). */
1586 assert( Sock > NONE );
1587 assert( Msg != NULL );
1589 strlcpy( buf, Msg, sizeof buf - 2);
1590 len = strlcat( buf, "\r\n", sizeof buf);
1591 (void)write(Sock, buf, len);
1592 } /* Simple_Error */
1596 Count_Connections( struct sockaddr_in addr_in )
1601 for( i = 0; i < Pool_Size; i++ ) {
1602 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].addr.sin_addr.s_addr == addr_in.sin_addr.s_addr )) cnt++;
1605 } /* Count_Connections */
1609 Conn_GetClient( CONN_ID Idx )
1611 /* return Client-Structure that belongs to the local Connection Idx.
1612 * If none is found, return NULL.
1617 c = array_get(&My_ConnArray, sizeof (CONNECTION), (size_t)Idx);
1621 return c ? c->client : NULL;