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.193 2006/04/29 16:19:46 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, 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), Pool_Size)) {
220 Log( LOG_EMERG, "Can't allocate memory! [Conn_Init]" );
224 /* XXX: My_Connetions/Pool_Size are needed by other parts of the code; remove them */
225 My_Connections = (CONNECTION*) array_start(&My_ConnArray);
227 LogDebug("Allocated connection pool for %d items (%ld bytes).",
228 array_length(&My_ConnArray, sizeof( CONNECTION )), array_bytes(&My_ConnArray));
230 assert( array_length(&My_ConnArray, sizeof( CONNECTION )) >= (size_t) Pool_Size);
232 array_free( &My_Listeners );
234 /* Connection-Struktur initialisieren */
235 for( i = 0; i < Pool_Size; i++ ) Init_Conn_Struct( i );
237 /* Global write counter */
245 /* Modul abmelden: alle noch offenen Connections
246 * schliessen und freigeben. */
250 LogDebug("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 );
262 array_free(&My_ConnArray);
263 My_Connections = NULL;
265 io_library_shutdown();
270 ports_initlisteners(array *a, void (*func)(int,short))
272 unsigned int created = 0, len;
276 len = array_length(a, sizeof (UINT16));
277 port = array_start(a);
279 fd = NewListener( *port );
284 if (!io_event_create( fd, IO_WANTREAD, func )) {
285 Log( LOG_ERR, "io_event_create(): Could not add listening fd %d (port %u): %s!",
286 fd, (unsigned int) *port, strerror(errno));
300 Conn_InitListeners( void )
302 /* Initialize ports on which the server should accept connections */
304 unsigned int created;
306 if (!io_library_init(CONNECTION_POOL)) {
307 Log(LOG_EMERG, "Cannot initialize IO routines: %s", strerror(errno));
311 created = ports_initlisteners(&Conf_ListenPorts, cb_listen);
314 } /* Conn_InitListeners */
318 Conn_ExitListeners( void )
320 /* Close down all listening sockets */
324 Rendezvous_UnregisterListeners( );
327 arraylen = array_length(&My_Listeners, sizeof (int));
328 Log( LOG_INFO, "Shutting down all listening sockets (%d total)...", arraylen );
329 fd = array_start(&My_Listeners);
334 LogDebug("Listening socket %d closed.", *fd );
337 array_free(&My_Listeners);
338 } /* Conn_ExitListeners */
341 /* return new listening port file descriptor or -1 on failure */
343 NewListener( const UINT16 Port )
345 /* Create new listening socket on specified port */
347 struct sockaddr_in addr;
348 struct in_addr inaddr;
351 char name[CLIENT_ID_LEN], *info;
354 /* Server-"Listen"-Socket initialisieren */
355 memset( &addr, 0, sizeof( addr ));
356 memset( &inaddr, 0, sizeof( inaddr ));
357 addr.sin_family = AF_INET;
358 addr.sin_port = htons( Port );
359 if( Conf_ListenAddress[0] )
361 #ifdef HAVE_INET_ATON
362 if( inet_aton( Conf_ListenAddress, &inaddr ) == 0 )
364 inaddr.s_addr = inet_addr( Conf_ListenAddress );
365 if( inaddr.s_addr == (unsigned)-1 )
368 Log( LOG_CRIT, "Can't listen on %s:%u: can't convert ip address %s!",
369 Conf_ListenAddress, Port, Conf_ListenAddress );
373 else inaddr.s_addr = htonl( INADDR_ANY );
374 addr.sin_addr = inaddr;
376 sock = socket( PF_INET, SOCK_STREAM, 0);
378 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
382 if( ! Init_Socket( sock )) return -1;
384 if( bind( sock, (struct sockaddr *)&addr, (socklen_t)sizeof( addr )) != 0 ) {
385 Log( LOG_CRIT, "Can't bind socket: %s!", strerror( errno ));
390 if( listen( sock, 10 ) != 0 ) {
391 Log( LOG_CRIT, "Can't listen on socket: %s!", strerror( errno ));
396 /* keep fd in list so we can close it when ngircd restarts/shuts down */
397 if (!array_catb( &My_Listeners,(char*) &sock, sizeof(int) )) {
398 Log( LOG_CRIT, "Can't add socket to My_Listeners array: %s!", strerror( errno ));
403 if( Conf_ListenAddress[0]) Log( LOG_INFO, "Now listening on %s:%d (socket %d).", Conf_ListenAddress, Port, sock );
404 else Log( LOG_INFO, "Now listening on 0.0.0.0:%d (socket %d).", Port, sock );
407 /* Get best server description text */
408 if( ! Conf_ServerInfo[0] ) info = Conf_ServerName;
411 /* Use server info string */
413 if( Conf_ServerInfo[0] == '[' )
415 /* Cut off leading hostname part in "[]" */
416 info = strchr( Conf_ServerInfo, ']' );
420 while( *info == ' ' ) info++;
423 if( ! info ) info = Conf_ServerInfo;
426 /* Add port number to description if non-standard */
427 if( Port != 6667 ) snprintf( name, sizeof( name ), "%s (port %u)", info, Port );
428 else strlcpy( name, info, sizeof( name ));
430 /* Register service */
431 Rendezvous_Register( name, MDNS_TYPE, Port );
440 /* "Main Loop.": Loop until a signal (for shutdown or restart) arrives.
441 * Call io_dispatch() to check for read/writeable sockets every second
442 * Wait for status change on pending connections (e.g: when the hostname has been resolved)
443 * check for penalty/timeouts
444 * handle input buffers
447 unsigned int wdatalen;
452 while(( ! NGIRCd_SignalQuit ) && ( ! NGIRCd_SignalRestart )) {
456 Rendezvous_Handler( );
459 /* Should the configuration be reloaded? */
460 if (NGIRCd_SignalRehash) {
464 /* Check configured servers and established links */
466 Check_Connections( );
470 /* noch volle Lese-Buffer suchen */
471 for( i = 0; i < Pool_Size; i++ ) {
472 if(( My_Connections[i].sock > NONE ) && ( array_bytes(&My_Connections[i].rbuf) > 0 ) &&
473 ( My_Connections[i].delaytime < t ))
475 /* Kann aus dem Buffer noch ein Befehl extrahiert werden? */
476 if (Handle_Buffer( i )) timeout = false;
480 /* noch volle Schreib-Puffer suchen */
481 for( i = 0; i < Pool_Size; i++ ) {
482 if ( My_Connections[i].sock <= NONE )
485 wdatalen = array_bytes(&My_Connections[i].wbuf);
488 if (( wdatalen > 0 ) || ( array_bytes(&My_Connections[i].zip.wbuf)> 0 ))
493 /* Socket der Verbindung in Set aufnehmen */
494 io_event_add( My_Connections[i].sock, IO_WANTWRITE );
498 /* von welchen Sockets koennte gelesen werden? */
499 for (i = 0; i < Pool_Size; i++ ) {
500 if ( My_Connections[i].sock <= NONE )
503 if (Resolve_INPROGRESS(&My_Connections[i].res_stat)) {
504 /* wait for completion of Resolver Sub-Process */
505 io_event_del( My_Connections[i].sock, IO_WANTREAD );
509 if ( Conn_OPTION_ISSET( &My_Connections[i], CONN_ISCONNECTING ))
510 continue; /* wait for completion of connect() */
512 if( My_Connections[i].delaytime > t ) {
513 /* Fuer die Verbindung ist eine "Penalty-Zeit" gesetzt */
514 io_event_del( My_Connections[i].sock, IO_WANTREAD );
517 io_event_add( My_Connections[i].sock, IO_WANTREAD );
520 /* (re-)set timeout - tv_sec/usec are undefined after io_dispatch() returns */
522 tv.tv_sec = timeout ? 1 : 0;
524 /* wait for activity */
525 i = io_dispatch( &tv );
526 if (i == -1 && errno != EINTR ) {
527 Log(LOG_EMERG, "Conn_Handler(): io_dispatch(): %s!", strerror(errno));
528 Log(LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE_NAME);
533 if( NGIRCd_SignalQuit ) Log( LOG_NOTICE|LOG_snotice, "Server going down NOW!" );
534 else if( NGIRCd_SignalRestart ) Log( LOG_NOTICE|LOG_snotice, "Server restarting NOW!" );
539 * Write a text string into the socket of a connection.
540 * This function automatically appends CR+LF to the string and validates that
541 * the result is a valid IRC message (oversized messages are shortened, for
542 * example). Then it calls the Conn_Write() function to do the actual sending.
543 * @param Idx Index fo the connection.
544 * @param Format Format string, see printf().
545 * @return true on success, false otherwise.
549 Conn_WriteStr( CONN_ID Idx, char *Format, ... )
552 Conn_WriteStr( Idx, Format, va_alist )
558 char buffer[COMMAND_LEN];
563 assert( Idx > NONE );
564 assert( Format != NULL );
567 va_start( ap, Format );
571 if (vsnprintf( buffer, COMMAND_LEN - 2, Format, ap ) >= COMMAND_LEN - 2 ) {
573 * The string that should be written to the socket is longer
574 * than the allowed size of COMMAND_LEN bytes (including both
575 * the CR and LF characters). This can be caused by the
576 * IRC_WriteXXX() functions when the prefix of this server had
577 * to be added to an already "quite long" command line which
578 * has been received from a regular IRC client, for example.
580 * We are not allowed to send such "oversized" messages to
581 * other servers and clients, see RFC 2812 2.3 and 2813 3.3
582 * ("these messages SHALL NOT exceed 512 characters in length,
583 * counting all characters including the trailing CR-LF").
585 * So we have a big problem here: we should send more bytes
586 * to the network than we are allowed to and we don't know
587 * the originator (any more). The "old" behaviour of blaming
588 * the receiver ("next hop") is a bad idea (it could be just
589 * an other server only routing the message!), so the only
590 * option left is to shorten the string and to hope that the
591 * result is still somewhat useful ...
595 strcpy (buffer + sizeof(buffer) - strlen(CUT_TXTSUFFIX) - 2 - 1,
601 Log(LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer);
604 len = strlcat( buffer, "\r\n", sizeof( buffer ));
605 ok = Conn_Write(Idx, buffer, len);
606 My_Connections[Idx].msg_out++;
610 } /* Conn_WriteStr */
614 Conn_Write( CONN_ID Idx, char *Data, unsigned int Len )
616 /* Daten in Socket schreiben. Bei "fatalen" Fehlern wird
617 * der Client disconnectiert und false geliefert. */
619 assert( Idx > NONE );
620 assert( Data != NULL );
623 /* Ist der entsprechende Socket ueberhaupt noch offen? In einem
624 * "Handler-Durchlauf" kann es passieren, dass dem nicht mehr so
625 * ist, wenn einer von mehreren Conn_Write()'s fehlgeschlagen ist.
626 * In diesem Fall wird hier einfach ein Fehler geliefert. */
627 if( My_Connections[Idx].sock <= NONE ) {
628 LogDebug("Skipped write on closed socket (connection %d).", Idx );
632 /* Pruefen, ob im Schreibpuffer genuegend Platz ist. Ziel ist es,
633 * moeglichts viel im Puffer zu haben und _nicht_ gleich alles auf den
634 * Socket zu schreiben (u.a. wg. Komprimierung). */
635 if( array_bytes(&My_Connections[Idx].wbuf) >= WRITEBUFFER_LEN) {
636 /* Der Puffer ist dummerweise voll. Jetzt versuchen, den Puffer
637 * zu schreiben, wenn das nicht klappt, haben wir ein Problem ... */
638 if( ! Handle_Write( Idx )) return false;
640 /* check again: if our writebuf is twice als large as the initial limit: Kill connection */
641 if( array_bytes(&My_Connections[Idx].wbuf) >= (WRITEBUFFER_LEN*2)) {
642 Log( LOG_NOTICE, "Write buffer overflow (connection %d)!", Idx );
643 Conn_Close( Idx, "Write buffer overflow!", NULL, false );
649 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
650 /* Daten komprimieren und in Puffer kopieren */
651 if( ! Zip_Buffer( Idx, Data, Len )) return false;
656 /* Daten in Puffer kopieren */
657 if (!array_catb( &My_Connections[Idx].wbuf, Data, Len ))
660 My_Connections[Idx].bytes_out += Len;
663 /* Adjust global write counter */
671 Conn_Close( CONN_ID Idx, char *LogMsg, char *FwdMsg, bool InformClient )
673 /* Close connection. Open pipes of asyncronous resolver
674 * sub-processes are closed down. */
680 double in_z_k, out_z_k;
684 assert( Idx > NONE );
686 /* Is this link already shutting down? */
687 if( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ISCLOSING )) {
688 /* Conn_Close() has been called recursively for this link;
689 * probabe reason: Handle_Write() failed -- see below. */
690 LogDebug("Recursive request to close connection: %d", Idx );
694 assert( My_Connections[Idx].sock > NONE );
696 /* Mark link as "closing" */
697 Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCLOSING );
699 if( LogMsg ) txt = LogMsg;
701 if( ! txt ) txt = "Reason unknown";
703 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 ));
705 /* Search client, if any */
706 c = Conn_GetClient( Idx );
708 /* Should the client be informed? */
711 /* Send statistics to client if registered as user: */
712 if ((c != NULL) && (Client_Type(c) == CLIENT_USER)) {
714 ":%s NOTICE %s :%sConnection statistics: client %.1f kb, server %.1f kb.",
715 Client_ID(Client_ThisServer()), Client_ID(c),
717 (double)My_Connections[Idx].bytes_in / 1024,
718 (double)My_Connections[Idx].bytes_out / 1024);
722 /* Send ERROR to client (see RFC!) */
724 Conn_WriteStr(Idx, "ERROR :%s", FwdMsg);
726 Conn_WriteStr(Idx, "ERROR :Closing connection.");
729 /* Try to write out the write buffer. Note: Handle_Write() eventually
730 * removes the CLIENT structure associated with this connection if an
731 * error occurs! So we have to re-check if there is still an valid
732 * CLIENT structure after calling Handle_Write() ...*/
733 (void)Handle_Write( Idx );
735 /* Search client, if any (re-check!) */
736 c = Conn_GetClient( Idx );
738 /* Shut down socket */
739 if( ! io_close( My_Connections[Idx].sock ))
741 /* Oops, we can't close the socket!? This is ... ugly! */
742 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 ));
745 /* Mark socket as invalid: */
746 My_Connections[Idx].sock = NONE;
748 /* If there is still a client, unregister it now */
749 if( c ) Client_Destroy( c, LogMsg, FwdMsg, true );
751 /* Calculate statistics and log information */
752 in_k = (double)My_Connections[Idx].bytes_in / 1024;
753 out_k = (double)My_Connections[Idx].bytes_out / 1024;
755 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
756 in_z_k = (double)My_Connections[Idx].zip.bytes_in / 1024;
757 out_z_k = (double)My_Connections[Idx].zip.bytes_out / 1024;
758 in_p = (int)(( in_k * 100 ) / in_z_k );
759 out_p = (int)(( out_k * 100 ) / out_z_k );
760 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 );
765 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 );
768 /* cancel running resolver */
769 if (Resolve_INPROGRESS(&My_Connections[Idx].res_stat)) {
770 Resolve_Shutdown(&My_Connections[Idx].res_stat);
773 /* Servers: Modify time of next connect attempt? */
774 Conf_UnsetServer( Idx );
777 /* Clean up zlib, if link was compressed */
778 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
779 inflateEnd( &My_Connections[Idx].zip.in );
780 deflateEnd( &My_Connections[Idx].zip.out );
781 array_free(&My_Connections[Idx].zip.rbuf);
782 array_free(&My_Connections[Idx].zip.wbuf);
786 array_free(&My_Connections[Idx].rbuf);
787 array_free(&My_Connections[Idx].wbuf);
788 /* Clean up connection structure (=free it) */
789 Init_Conn_Struct( Idx );
791 LogDebug("Shutdown of connection %d completed.", Idx );
796 Conn_SyncServerStruct( void )
798 /* Synchronize server structures (connection IDs):
799 * connections <-> configuration */
805 for( i = 0; i < Pool_Size; i++ ) {
806 /* Established connection? */
807 if (My_Connections[i].sock < 0)
810 /* Server connection? */
811 client = Conn_GetClient( i );
812 if(( ! client ) || ( Client_Type( client ) != CLIENT_SERVER )) continue;
814 for( c = 0; c < MAX_SERVERS; c++ )
816 /* Configured server? */
817 if( ! Conf_Server[c].host[0] ) continue;
820 if( strcmp( Conf_Server[c].name, Client_ID( client )) == 0 )
821 Conf_Server[c].conn_id = i;
824 } /* SyncServerStruct */
828 Handle_Write( CONN_ID Idx )
830 /* Daten aus Schreibpuffer versenden bzw. Connection aufbauen */
833 unsigned int wdatalen;
835 assert( Idx > NONE );
836 if ( My_Connections[Idx].sock < 0 ) {
837 LogDebug("Handle_Write() on closed socket, connection %d", Idx);
840 assert( My_Connections[Idx].sock > NONE );
842 LogDebug("Handle_Write() called for connection %d ...", Idx);
844 wdatalen = array_bytes(&My_Connections[Idx].wbuf );
846 if (wdatalen == 0 && !array_bytes(&My_Connections[Idx].zip.wbuf)) {
847 io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
851 /* write buffer empty, but not compression buffer?
852 * -> flush compression buffer! */
857 io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
862 /* Zip_Flush() may have changed the write buffer ... */
863 wdatalen = array_bytes(&My_Connections[Idx].wbuf);
865 len = write(My_Connections[Idx].sock,
866 array_start(&My_Connections[Idx].wbuf), wdatalen );
869 if (errno == EAGAIN || errno == EINTR)
872 Log(LOG_ERR, "Write error on connection %d (socket %d): %s!",
873 Idx, My_Connections[Idx].sock, strerror(errno));
874 Conn_Close(Idx, "Write error!", NULL, false);
878 /* move any data not yet written to beginning */
879 array_moveleft(&My_Connections[Idx].wbuf, 1, len);
886 New_Connection( int Sock )
888 /* Neue Client-Verbindung von Listen-Socket annehmen und
889 * CLIENT-Struktur anlegen. */
892 struct request_info req;
894 struct sockaddr_in new_addr;
895 int new_sock, new_sock_len, new_Pool_Size;
899 assert( Sock > NONE );
900 /* Connection auf Listen-Socket annehmen */
901 new_sock_len = sizeof( new_addr );
902 new_sock = accept( Sock, (struct sockaddr *)&new_addr, (socklen_t *)&new_sock_len );
905 Log( LOG_CRIT, "Can't accept connection: %s!", strerror( errno ));
910 /* Validate socket using TCP Wrappers */
911 request_init( &req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock, RQ_CLIENT_SIN, &new_addr, NULL );
913 if( ! hosts_access( &req ))
916 Log( deny_severity, "Refused connection from %s (by TCP Wrappers)!", inet_ntoa( new_addr.sin_addr ));
917 Simple_Message( new_sock, "ERROR :Connection refused" );
923 /* Socket initialisieren */
924 if (!Init_Socket( new_sock ))
927 /* Check IP-based connection limit */
928 cnt = Count_Connections( new_addr );
929 if(( Conf_MaxConnectionsIP > 0 ) && ( cnt >= Conf_MaxConnectionsIP ))
931 /* Access denied, too many connections from this IP address! */
932 Log( LOG_ERR, "Refused connection from %s: too may connections (%ld) from this IP address!", inet_ntoa( new_addr.sin_addr ), cnt);
933 Simple_Message( new_sock, "ERROR :Connection refused, too many connections from your IP address!" );
938 if( new_sock >= Pool_Size ) {
939 new_Pool_Size = new_sock + 1;
940 /* No free Connection Structures, check if we may accept further connections */
941 if ((( Conf_MaxConnections > 0) && Pool_Size >= Conf_MaxConnections) ||
942 (new_Pool_Size < Pool_Size))
944 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached!", Pool_Size );
945 Simple_Message( new_sock, "ERROR :Connection limit reached" );
950 if (!array_alloc(&My_ConnArray, sizeof( CONNECTION ), new_sock)) {
951 Log( LOG_EMERG, "Can't allocate memory! [New_Connection]" );
952 Simple_Message( new_sock, "ERROR: Internal error" );
956 LogDebug("Bumped connection pool to %ld items (internal: %ld items, %ld bytes)",
957 new_sock, array_length(&My_ConnArray, sizeof(CONNECTION)), array_bytes(&My_ConnArray));
959 /* Adjust pointer to new block */
960 My_Connections = array_start(&My_ConnArray);
961 while (Pool_Size < new_Pool_Size)
962 Init_Conn_Struct(Pool_Size++);
965 c = Client_NewLocal( new_sock, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWN, false );
967 Log( LOG_ALERT, "Can't accept connection: can't create client structure!" );
968 Simple_Message( new_sock, "ERROR :Internal error" );
973 Init_Conn_Struct( new_sock );
974 My_Connections[new_sock].sock = new_sock;
975 My_Connections[new_sock].addr = new_addr;
976 My_Connections[new_sock].client = c;
978 /* register callback */
979 if (!io_event_create( new_sock, IO_WANTREAD, cb_clientserver)) {
980 Simple_Message( new_sock, "ERROR :Internal error" );
981 Conn_Close( new_sock, "io_event_create() failed", NULL, false );
985 Log( LOG_INFO, "Accepted connection %d from %s:%d on socket %d.", new_sock,
986 inet_ntoa( new_addr.sin_addr ), ntohs( new_addr.sin_port), Sock );
988 /* Hostnamen ermitteln */
989 strlcpy( My_Connections[new_sock].host, inet_ntoa( new_addr.sin_addr ),
990 sizeof( My_Connections[new_sock].host ));
992 Client_SetHostname( c, My_Connections[new_sock].host );
994 Resolve_Addr(&My_Connections[new_sock].res_stat, &new_addr,
995 My_Connections[new_sock].sock, cb_Read_Resolver_Result);
997 /* Penalty-Zeit setzen */
998 Conn_SetPenalty( new_sock, 4 );
1000 } /* New_Connection */
1004 Socket2Index( int Sock )
1006 /* zum Socket passende Connection suchen */
1008 assert( Sock >= 0 );
1010 if( Sock >= Pool_Size || My_Connections[Sock].sock != Sock ) {
1011 /* die Connection wurde vermutlich (wegen eines
1012 * Fehlers) bereits wieder abgebaut ... */
1013 LogDebug("Socket2Index: can't get connection for socket %d!", Sock);
1017 } /* Socket2Index */
1021 Read_Request( CONN_ID Idx )
1023 /* Daten von Socket einlesen und entsprechend behandeln.
1024 * Tritt ein Fehler auf, so wird der Socket geschlossen. */
1030 assert( Idx > NONE );
1031 assert( My_Connections[Idx].sock > NONE );
1034 if (( array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN ) ||
1035 ( array_bytes(&My_Connections[Idx].zip.rbuf) >= ZREADBUFFER_LEN ))
1037 if ( array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN )
1040 /* Der Lesepuffer ist voll */
1041 Log( LOG_ERR, "Receive buffer overflow (connection %d): %d bytes!", Idx,
1042 array_bytes(&My_Connections[Idx].rbuf));
1043 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1047 len = read( My_Connections[Idx].sock, readbuf, sizeof readbuf -1 );
1049 Log( LOG_INFO, "%s:%d (%s) is closing the connection ...",
1050 My_Connections[Idx].host, ntohs( My_Connections[Idx].addr.sin_port),
1051 inet_ntoa( My_Connections[Idx].addr.sin_addr ));
1052 Conn_Close( Idx, "Socket closed!", "Client closed connection", false );
1057 if( errno == EAGAIN ) return;
1058 Log( LOG_ERR, "Read error on connection %d (socket %d): %s!", Idx,
1059 My_Connections[Idx].sock, strerror( errno ));
1060 Conn_Close( Idx, "Read error!", "Client closed connection", false );
1064 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
1065 if (!array_catb( &My_Connections[Idx].zip.rbuf, readbuf, len)) {
1066 Log( LOG_ERR, "Could not append recieved data to zip input buffer (connn %d): %d bytes!", Idx, len );
1067 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1074 if (!array_cats( &My_Connections[Idx].rbuf, readbuf )) {
1075 Log( LOG_ERR, "Could not append recieved data to input buffer (connn %d): %d bytes!", Idx, len );
1076 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1080 /* Update connection statistics */
1081 My_Connections[Idx].bytes_in += len;
1083 /* Update timestamp of last data received if this connection is
1084 * registered as a user, server or service connection. Don't update
1085 * otherwise, so users have at least Conf_PongTimeout seconds time to
1086 * register with the IRC server -- see Check_Connections(). */
1087 c = Conn_GetClient(Idx);
1088 if (c && (Client_Type(c) == CLIENT_USER
1089 || Client_Type(c) == CLIENT_SERVER
1090 || Client_Type(c) == CLIENT_SERVICE))
1091 My_Connections[Idx].lastdata = time(NULL);
1093 /* Look at the data in the (read-) buffer of this connection */
1095 } /* Read_Request */
1099 Handle_Buffer( CONN_ID Idx )
1101 /* Handle Data in Connections Read-Buffer.
1102 * Return true if a reuqest was handled, false otherwise (also returned on errors). */
1114 starttime = time(NULL);
1118 if( My_Connections[Idx].delaytime > starttime) return result;
1120 /* unpack compressed data */
1121 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP ))
1122 if( ! Unzip_Buffer( Idx )) return false;
1125 if (0 == array_bytes(&My_Connections[Idx].rbuf))
1128 if (!array_cat0_temporary(&My_Connections[Idx].rbuf)) /* make sure buf is NULL terminated */
1131 /* A Complete Request end with CR+LF, see RFC 2812. */
1132 ptr = strstr( array_start(&My_Connections[Idx].rbuf), "\r\n" );
1134 if( ptr ) delta = 2; /* complete request */
1137 /* Check for non-RFC-compliant request (only CR or LF)? Unfortunately,
1138 * there are quite a few clients that do this (incl. "mIRC" :-( */
1139 ptr1 = strchr( array_start(&My_Connections[Idx].rbuf), '\r' );
1140 ptr2 = strchr( array_start(&My_Connections[Idx].rbuf), '\n' );
1142 if( ptr1 && ptr2 ) ptr = ptr1 > ptr2 ? ptr2 : ptr1;
1143 else if( ptr1 ) ptr = ptr1;
1144 else if( ptr2 ) ptr = ptr2;
1151 /* End of request found */
1154 len = ( ptr - (char*) array_start(&My_Connections[Idx].rbuf)) + delta;
1156 if( len < 0 || len > ( COMMAND_LEN - 1 )) {
1157 /* Request must not exceed 512 chars (incl. CR+LF!), see
1158 * RFC 2812. Disconnect Client if this happens. */
1159 Log( LOG_ERR, "Request too long (connection %d): %d bytes (max. %d expected)!",
1160 Idx, array_bytes(&My_Connections[Idx].rbuf), COMMAND_LEN - 1 );
1161 Conn_Close( Idx, NULL, "Request too long", true );
1165 if (len <= 2) { /* request was empty (only '\r\n') */
1166 array_moveleft(&My_Connections[Idx].rbuf, 1, delta); /* delta is either 1 or 2 */
1170 /* remember if stream is already compressed */
1171 old_z = My_Connections[Idx].options & CONN_ZIP;
1174 My_Connections[Idx].msg_in++;
1175 if (!Parse_Request(Idx, (char*)array_start(&My_Connections[Idx].rbuf) ))
1180 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1181 LogDebug("Connection %d: %d bytes left in read buffer.",
1182 Idx, array_bytes(&My_Connections[Idx].rbuf));
1184 if(( ! old_z ) && ( My_Connections[Idx].options & CONN_ZIP ) &&
1185 ( array_bytes(&My_Connections[Idx].rbuf) > 0 ))
1187 /* The last Command activated Socket-Compression.
1188 * Data that was read after that needs to be copied to Unzip-buf
1189 * for decompression */
1190 if( array_bytes(&My_Connections[Idx].rbuf)> ZREADBUFFER_LEN ) {
1191 Log( LOG_ALERT, "Connection %d: No space left in unzip buf (need %u bytes)!",
1192 Idx, array_bytes(&My_Connections[Idx].rbuf ));
1195 if (!array_copy( &My_Connections[Idx].zip.rbuf, &My_Connections[Idx].rbuf ))
1198 array_trunc(&My_Connections[Idx].rbuf);
1199 LogDebug("Moved already received data (%u bytes) to uncompression buffer.",
1200 array_bytes(&My_Connections[Idx].zip.rbuf));
1205 } /* Handle_Buffer */
1209 Check_Connections( void )
1211 /* check if connections are alive. if not, play PING-PONG first.
1212 * if this doesn't help either, disconnect client. */
1216 for( i = 0; i < Pool_Size; i++ ) {
1217 if (My_Connections[i].sock < 0)
1220 c = Conn_GetClient( i );
1221 if( c && (( Client_Type( c ) == CLIENT_USER ) || ( Client_Type( c ) == CLIENT_SERVER ) || ( Client_Type( c ) == CLIENT_SERVICE )))
1223 /* connected User, Server or Service */
1224 if( My_Connections[i].lastping > My_Connections[i].lastdata ) {
1225 /* we already sent a ping */
1226 if( My_Connections[i].lastping < time( NULL ) - Conf_PongTimeout ) {
1228 LogDebug("Connection %d: Ping timeout: %d seconds.",
1229 i, Conf_PongTimeout );
1230 Conn_Close( i, NULL, "Ping timeout", true );
1233 else if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout ) {
1234 /* we need to sent a PING */
1235 LogDebug("Connection %d: sending PING ...", i );
1236 My_Connections[i].lastping = time( NULL );
1237 Conn_WriteStr( i, "PING :%s", Client_ID( Client_ThisServer( )));
1242 /* The connection is not fully established yet, so
1243 * we don't do the PING-PONG game here but instead
1244 * disconnect the client after "a short time" if it's
1245 * still not registered. */
1247 if (My_Connections[i].lastdata <
1248 time(NULL) - Conf_PongTimeout) {
1249 LogDebug("Unregistered connection %d timed out ...", i);
1250 Conn_Close(i, NULL, "Timeout", false);
1254 } /* Check_Connections */
1258 Check_Servers( void )
1260 /* Check if we can establish further server links */
1265 /* Check all configured servers */
1266 for( i = 0; i < MAX_SERVERS; i++ ) {
1267 /* Valid outgoing server which isn't already connected or disabled? */
1268 if(( ! Conf_Server[i].host[0] ) || ( ! Conf_Server[i].port > 0 ) ||
1269 ( Conf_Server[i].conn_id > NONE ) || ( Conf_Server[i].flags & CONF_SFLAG_DISABLED ))
1272 /* Is there already a connection in this group? */
1273 if( Conf_Server[i].group > NONE ) {
1274 for (n = 0; n < MAX_SERVERS; n++) {
1275 if (n == i) continue;
1276 if ((Conf_Server[n].conn_id > NONE) &&
1277 (Conf_Server[n].group == Conf_Server[i].group))
1280 if (n < MAX_SERVERS) continue;
1283 /* Check last connect attempt? */
1284 time_now = time(NULL);
1285 if( Conf_Server[i].lasttry > (time_now - Conf_ConnectRetry))
1288 /* Okay, try to connect now */
1289 Conf_Server[i].lasttry = time_now;
1290 assert(Resolve_Getfd(&Conf_Server[i].res_stat) < 0);
1291 Resolve_Name(&Conf_Server[i].res_stat, Conf_Server[i].host, cb_Connect_to_Server);
1293 } /* Check_Servers */
1297 New_Server( int Server )
1299 /* Establish new server link */
1301 struct sockaddr_in new_addr;
1302 struct in_addr inaddr;
1306 assert( Server > NONE );
1308 Log( LOG_INFO, "Establishing connection to \"%s\", %s, port %d ... ", Conf_Server[Server].host,
1309 Conf_Server[Server].ip, Conf_Server[Server].port );
1311 #ifdef HAVE_INET_ATON
1312 if( inet_aton( Conf_Server[Server].ip, &inaddr ) == 0 )
1314 memset( &inaddr, 0, sizeof( inaddr ));
1315 inaddr.s_addr = inet_addr( Conf_Server[Server].ip );
1316 if( inaddr.s_addr == (unsigned)-1 )
1319 Log( LOG_ERR, "Can't connect to \"%s\": can't convert ip address %s!",
1320 Conf_Server[Server].host, Conf_Server[Server].ip );
1324 memset( &new_addr, 0, sizeof( new_addr ));
1325 new_addr.sin_family = AF_INET;
1326 new_addr.sin_addr = inaddr;
1327 new_addr.sin_port = htons( Conf_Server[Server].port );
1329 new_sock = socket( PF_INET, SOCK_STREAM, 0 );
1330 if ( new_sock < 0 ) {
1331 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
1335 if( ! Init_Socket( new_sock )) return;
1337 res = connect( new_sock, (struct sockaddr *)&new_addr, sizeof( new_addr ));
1338 if(( res != 0 ) && ( errno != EINPROGRESS )) {
1339 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1344 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), new_sock)) {
1345 Log( LOG_ALERT, "Cannot allocate memory for server connection (socket %d)", new_sock);
1350 My_Connections = array_start(&My_ConnArray);
1352 assert(My_Connections[new_sock].sock <= 0);
1354 Init_Conn_Struct(new_sock);
1356 c = Client_NewLocal( new_sock, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWNSERVER, false );
1358 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1363 Client_SetIntroducer( c, c );
1364 Client_SetToken( c, TOKEN_OUTBOUND );
1366 /* Register connection */
1367 Conf_Server[Server].conn_id = new_sock;
1368 My_Connections[new_sock].sock = new_sock;
1369 My_Connections[new_sock].addr = new_addr;
1370 My_Connections[new_sock].client = c;
1371 strlcpy( My_Connections[new_sock].host, Conf_Server[Server].host,
1372 sizeof(My_Connections[new_sock].host ));
1374 /* Register new socket */
1375 if (!io_event_create( new_sock, IO_WANTWRITE, cb_connserver)) {
1376 Log( LOG_ALERT, "io_event_create(): could not add fd %d", strerror(errno));
1377 Conn_Close( new_sock, "io_event_create() failed", NULL, false );
1378 Init_Conn_Struct( new_sock );
1379 Conf_Server[Server].conn_id = NONE;
1382 LogDebug("Registered new connection %d on socket %d.",
1383 new_sock, My_Connections[new_sock].sock );
1384 Conn_OPTION_ADD( &My_Connections[new_sock], CONN_ISCONNECTING );
1389 Init_Conn_Struct( CONN_ID Idx )
1391 time_t now = time( NULL );
1392 /* Connection-Struktur initialisieren */
1394 memset( &My_Connections[Idx], 0, sizeof ( CONNECTION ));
1395 My_Connections[Idx].sock = -1;
1396 My_Connections[Idx].lastdata = now;
1397 My_Connections[Idx].lastprivmsg = now;
1398 Resolve_Init(&My_Connections[Idx].res_stat);
1399 } /* Init_Conn_Struct */
1403 Init_Socket( int Sock )
1405 /* Initialize socket (set options) */
1409 if (!io_setnonblock(Sock)) {
1410 Log( LOG_CRIT, "Can't enable non-blocking mode for socket: %s!", strerror( errno ));
1415 /* Don't block this port after socket shutdown */
1417 if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &value, (socklen_t)sizeof( value )) != 0 )
1419 Log( LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!", strerror( errno ));
1420 /* ignore this error */
1423 /* Set type of service (TOS) */
1424 #if defined(IP_TOS) && defined(IPTOS_LOWDELAY)
1425 value = IPTOS_LOWDELAY;
1426 LogDebug("Setting option IP_TOS on socket %d to IPTOS_LOWDELAY (%d).", Sock, value );
1427 if( setsockopt( Sock, SOL_IP, IP_TOS, &value, (socklen_t)sizeof( value )) != 0 )
1429 Log( LOG_ERR, "Can't set socket option IP_TOS: %s!", strerror( errno ));
1430 /* ignore this error */
1440 cb_Connect_to_Server(int fd, UNUSED short events)
1442 /* Read result of resolver sub-process from pipe and start connection */
1445 char readbuf[HOST_LEN + 1];
1447 LogDebug("Resolver: Got forward lookup callback on fd %d, events %d", fd, events);
1449 for (i=0; i < MAX_SERVERS; i++) {
1450 if (Resolve_Getfd(&Conf_Server[i].res_stat) == fd )
1454 if( i >= MAX_SERVERS) {
1455 /* Ops, no matching server found?! */
1457 LogDebug("Resolver: Got Forward Lookup callback for unknown server!?");
1461 /* Read result from pipe */
1462 len = Resolve_Read(&Conf_Server[i].res_stat, readbuf, sizeof readbuf -1);
1466 readbuf[len] = '\0';
1467 LogDebug("Got result from resolver: \"%s\" (%u bytes read).", readbuf, len);
1468 strlcpy( Conf_Server[i].ip, readbuf, sizeof( Conf_Server[i].ip ));
1472 } /* cb_Read_Forward_Lookup */
1476 cb_Read_Resolver_Result( int r_fd, UNUSED short events )
1478 /* Read result of resolver sub-process from pipe and update the
1479 * apropriate connection/client structure(s): hostname and/or
1480 * IDENT user name.*/
1487 char readbuf[HOST_LEN + 2 + CLIENT_USER_LEN];
1489 char readbuf[HOST_LEN + 1];
1492 LogDebug("Resolver: Got callback on fd %d, events %d", r_fd, events );
1494 /* Search associated connection ... */
1495 for( i = 0; i < Pool_Size; i++ ) {
1496 if(( My_Connections[i].sock != NONE )
1497 && ( Resolve_Getfd(&My_Connections[i].res_stat) == r_fd ))
1500 if( i >= Pool_Size ) {
1501 /* Ops, none found? Probably the connection has already
1502 * been closed!? We'll ignore that ... */
1504 LogDebug("Resolver: Got callback for unknown connection!?");
1508 /* Read result from pipe */
1509 len = Resolve_Read(&My_Connections[i].res_stat, readbuf, sizeof readbuf -1);
1513 readbuf[len] = '\0';
1514 identptr = strchr(readbuf, '\n');
1515 assert(identptr != NULL);
1517 Log( LOG_CRIT, "Resolver: Got malformed result!");
1522 LogDebug("Got result from resolver: \"%s\" (%u bytes read).", readbuf, len);
1523 /* Okay, we got a complete result: this is a host name for outgoing
1524 * connections and a host name and IDENT user name (if enabled) for
1525 * incoming connections.*/
1526 assert ( My_Connections[i].sock >= 0 );
1527 /* Incoming connection. Search client ... */
1528 c = Conn_GetClient( i );
1529 assert( c != NULL );
1531 /* Only update client information of unregistered clients */
1532 if( Client_Type( c ) == CLIENT_UNKNOWN ) {
1533 strlcpy(My_Connections[i].host, readbuf, sizeof( My_Connections[i].host));
1534 Client_SetHostname( c, readbuf);
1538 Log( LOG_INFO, "IDENT lookup for connection %ld: \"%s\".", i, identptr);
1539 Client_SetUser( c, identptr, true );
1541 Log( LOG_INFO, "IDENT lookup for connection %ld: no result.", i );
1546 else Log( LOG_DEBUG, "Resolver: discarding result for already registered connection %d.", i );
1548 /* Reset penalty time */
1549 Conn_ResetPenalty( i );
1550 } /* cb_Read_Resolver_Result */
1554 Simple_Message( int Sock, const char *Msg )
1556 char buf[COMMAND_LEN];
1558 /* Write "simple" message to socket, without using compression
1559 * or even the connection write buffers. Used e.g. for error
1560 * messages by New_Connection(). */
1561 assert( Sock > NONE );
1562 assert( Msg != NULL );
1564 strlcpy( buf, Msg, sizeof buf - 2);
1565 len = strlcat( buf, "\r\n", sizeof buf);
1566 (void)write(Sock, buf, len);
1567 } /* Simple_Error */
1571 Count_Connections( struct sockaddr_in addr_in )
1576 for( i = 0; i < Pool_Size; i++ ) {
1577 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].addr.sin_addr.s_addr == addr_in.sin_addr.s_addr )) cnt++;
1580 } /* Count_Connections */
1584 Conn_GetClient( CONN_ID Idx )
1586 /* return Client-Structure that belongs to the local Connection Idx.
1587 * If none is found, return NULL.
1592 c = array_get(&My_ConnArray, sizeof (CONNECTION), Idx);
1596 return c ? c->client : NULL;