2 * ngIRCd -- The Next Generation IRC Daemon
3 * Copyright (c)2001-2004 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
19 static char UNUSED id[] = "$Id: conn.c,v 1.149 2005/04/23 14:28:44 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 */
69 #include "conn-func.h"
75 # include "rendezvous.h"
81 #define SERVER_WAIT (NONE - 1)
84 LOCAL void Handle_Read PARAMS(( int sock ));
85 LOCAL bool Handle_Write PARAMS(( CONN_ID Idx ));
86 LOCAL void New_Connection PARAMS(( int Sock ));
87 LOCAL CONN_ID Socket2Index PARAMS(( int Sock ));
88 LOCAL void Read_Request PARAMS(( CONN_ID Idx ));
89 LOCAL bool Try_Write PARAMS(( CONN_ID Idx ));
90 LOCAL bool Handle_Buffer PARAMS(( CONN_ID Idx ));
91 LOCAL void Check_Connections PARAMS(( void ));
92 LOCAL void Check_Servers PARAMS(( void ));
93 LOCAL void Init_Conn_Struct PARAMS(( CONN_ID Idx ));
94 LOCAL bool Init_Socket PARAMS(( int Sock ));
95 LOCAL void New_Server PARAMS(( int Server, CONN_ID Idx ));
96 LOCAL void Read_Resolver_Result PARAMS(( int r_fd ));
97 LOCAL void Simple_Message PARAMS(( int Sock, char *Msg ));
98 LOCAL int Count_Connections PARAMS(( struct sockaddr_in addr ));
100 LOCAL fd_set My_Listeners;
101 LOCAL fd_set My_Sockets;
104 int allow_severity = LOG_INFO;
105 int deny_severity = LOG_ERR;
112 /* Modul initialisieren: statische Strukturen "ausnullen". */
116 /* Speicher fuer Verbindungs-Pool anfordern */
117 Pool_Size = CONNECTION_POOL;
118 if( Conf_MaxConnections > 0 )
120 /* konfiguriertes Limit beachten */
121 if( Pool_Size > Conf_MaxConnections ) Pool_Size = Conf_MaxConnections;
123 My_Connections = (CONNECTION *) calloc( Pool_Size, sizeof( CONNECTION ) );
124 if( ! My_Connections )
126 /* Speicher konnte nicht alloziert werden! */
127 Log( LOG_EMERG, "Can't allocate memory! [Conn_Init]" );
131 Log( LOG_DEBUG, "Allocated connection pool for %d items (%ld bytes).", Pool_Size, sizeof( CONNECTION ) * Pool_Size );
134 /* zu Beginn haben wir keine Verbindungen */
135 FD_ZERO( &My_Listeners );
136 FD_ZERO( &My_Sockets );
138 /* Groesster File-Descriptor fuer select() */
141 /* Connection-Struktur initialisieren */
142 for( i = 0; i < Pool_Size; i++ ) Init_Conn_Struct( i );
144 /* Global write counter */
152 /* Modul abmelden: alle noch offenen Connections
153 * schliessen und freigeben. */
159 Log( LOG_DEBUG, "Shutting down all connections ..." );
163 Rendezvous_UnregisterListeners( );
166 /* Sockets schliessen */
167 for( i = 0; i < Conn_MaxFD + 1; i++ )
169 if( FD_ISSET( i, &My_Sockets ))
171 for( idx = 0; idx < Pool_Size; idx++ )
173 if( My_Connections[idx].sock == i ) break;
175 if( FD_ISSET( i, &My_Listeners ))
179 Log( LOG_DEBUG, "Listening socket %d closed.", i );
182 else if( idx < Pool_Size )
184 if( NGIRCd_SignalRestart ) Conn_Close( idx, NULL, "Server going down (restarting)", true );
185 else Conn_Close( idx, NULL, "Server going down", true );
189 Log( LOG_WARNING, "Closing unknown connection %d ...", i );
195 free( My_Connections );
196 My_Connections = NULL;
202 Conn_InitListeners( void )
204 /* Initialize ports on which the server should accept connections */
209 for( i = 0; i < Conf_ListenPorts_Count; i++ )
211 if( Conn_NewListener( Conf_ListenPorts[i] )) created++;
212 else Log( LOG_ERR, "Can't listen on port %u!", (unsigned int) Conf_ListenPorts[i] );
215 } /* Conn_InitListeners */
219 Conn_ExitListeners( void )
221 /* Close down all listening sockets */
226 Rendezvous_UnregisterListeners( );
229 Log( LOG_INFO, "Shutting down all listening sockets ..." );
230 for( i = 0; i < Conn_MaxFD + 1; i++ )
232 if( FD_ISSET( i, &My_Sockets ) && FD_ISSET( i, &My_Listeners ))
236 Log( LOG_DEBUG, "Listening socket %d closed.", i );
240 } /* Conn_ExitListeners */
244 Conn_NewListener( const UINT16 Port )
246 /* Create new listening socket on specified port */
248 struct sockaddr_in addr;
249 struct in_addr inaddr;
252 char name[CLIENT_ID_LEN], *info;
255 /* Server-"Listen"-Socket initialisieren */
256 memset( &addr, 0, sizeof( addr ));
257 memset( &inaddr, 0, sizeof( inaddr ));
258 addr.sin_family = AF_INET;
259 addr.sin_port = htons( Port );
260 if( Conf_ListenAddress[0] )
262 #ifdef HAVE_INET_ATON
263 if( inet_aton( Conf_ListenAddress, &inaddr ) == 0 )
265 inaddr.s_addr = inet_addr( Conf_ListenAddress );
266 if( inaddr.s_addr == (unsigned)-1 )
269 Log( LOG_CRIT, "Can't listen on %s:%u: can't convert ip address %s!", Conf_ListenAddress, Port, Conf_ListenAddress );
273 else inaddr.s_addr = htonl( INADDR_ANY );
274 addr.sin_addr = inaddr;
276 /* Socket erzeugen */
277 sock = socket( PF_INET, SOCK_STREAM, 0);
280 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
284 if( ! Init_Socket( sock )) return false;
287 if( bind( sock, (struct sockaddr *)&addr, (socklen_t)sizeof( addr )) != 0 )
289 Log( LOG_CRIT, "Can't bind socket: %s!", strerror( errno ));
294 /* in "listen mode" gehen :-) */
295 if( listen( sock, 10 ) != 0 )
297 Log( LOG_CRIT, "Can't listen on soecket: %s!", strerror( errno ));
302 /* Neuen Listener in Strukturen einfuegen */
303 FD_SET( sock, &My_Listeners );
304 FD_SET( sock, &My_Sockets );
306 if( sock > Conn_MaxFD ) Conn_MaxFD = sock;
308 if( Conf_ListenAddress[0]) Log( LOG_INFO, "Now listening on %s:%d (socket %d).", Conf_ListenAddress, Port, sock );
309 else Log( LOG_INFO, "Now listening on 0.0.0.0:%d (socket %d).", Port, sock );
312 /* Get best server description text */
313 if( ! Conf_ServerInfo[0] ) info = Conf_ServerName;
316 /* Use server info string */
318 if( Conf_ServerInfo[0] == '[' )
320 /* Cut off leading hostname part in "[]" */
321 info = strchr( Conf_ServerInfo, ']' );
325 while( *info == ' ' ) info++;
328 if( ! info ) info = Conf_ServerInfo;
331 /* Add port number to description if non-standard */
332 if( Port != 6667 ) snprintf( name, sizeof( name ), "%s (port %u)", info, Port );
333 else strlcpy( name, info, sizeof( name ));
335 /* Register service */
336 Rendezvous_Register( name, RENDEZVOUS_TYPE, Port );
340 } /* Conn_NewListener */
346 /* "Hauptschleife": Aktive Verbindungen ueberwachen. Folgende Aktionen
347 * werden dabei durchgefuehrt, bis der Server terminieren oder neu
350 * - neue Verbindungen annehmen,
351 * - Server-Verbindungen aufbauen,
352 * - geschlossene Verbindungen loeschen,
353 * - volle Schreibpuffer versuchen zu schreiben,
354 * - volle Lesepuffer versuchen zu verarbeiten,
355 * - Antworten von Resolver Sub-Prozessen annehmen.
358 fd_set read_sockets, write_sockets;
364 start = time( NULL );
365 while(( ! NGIRCd_SignalQuit ) && ( ! NGIRCd_SignalRestart ))
370 Rendezvous_Handler( );
373 /* Should the configuration be reloaded? */
374 if( NGIRCd_SignalRehash ) NGIRCd_Rehash( );
376 /* Check configured servers and established links */
378 Check_Connections( );
382 /* noch volle Lese-Buffer suchen */
383 for( i = 0; i < Pool_Size; i++ )
385 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].rdatalen > 0 ) &&
386 ( My_Connections[i].delaytime < t ))
388 /* Kann aus dem Buffer noch ein Befehl extrahiert werden? */
389 if( Handle_Buffer( i )) timeout = false;
393 /* noch volle Schreib-Puffer suchen */
394 FD_ZERO( &write_sockets );
395 for( i = 0; i < Pool_Size; i++ )
398 if(( My_Connections[i].sock > NONE ) && (( My_Connections[i].wdatalen > 0 ) || ( My_Connections[i].zip.wdatalen > 0 )))
400 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].wdatalen > 0 ))
403 /* Socket der Verbindung in Set aufnehmen */
404 FD_SET( My_Connections[i].sock, &write_sockets );
408 /* Sockets mit im Aufbau befindlichen ausgehenden Verbindungen suchen */
409 for( i = 0; i < Pool_Size; i++ )
411 if ( My_Connections[i].sock > NONE ) {
412 if ( Conn_OPTION_ISSET( &My_Connections[i], CONN_ISCONNECTING )) {
413 FD_SET( My_Connections[i].sock, &write_sockets );
419 /* von welchen Sockets koennte gelesen werden? */
420 read_sockets = My_Sockets;
421 for( i = 0; i < Pool_Size; i++ )
423 if ( My_Connections[i].sock > NONE ) {
424 if ( My_Connections[i].host[0] == '\0' ) {
425 /* wait for completion of Resolver Sub-Process */
426 FD_CLR( My_Connections[i].sock, &read_sockets );
430 if ( Conn_OPTION_ISSET( &My_Connections[i], CONN_ISCONNECTING )) {
431 /* wait for completion of connect() */
432 FD_CLR( My_Connections[i].sock, &read_sockets );
436 if( My_Connections[i].delaytime > t )
438 /* Fuer die Verbindung ist eine "Penalty-Zeit" gesetzt */
439 FD_CLR( My_Connections[i].sock, &read_sockets );
442 for( i = 0; i < Conn_MaxFD + 1; i++ )
444 /* Pipes von Resolver Sub-Prozessen aufnehmen */
445 if( FD_ISSET( i, &Resolver_FDs ))
447 FD_SET( i, &read_sockets );
451 /* Timeout initialisieren */
453 if( timeout ) tv.tv_sec = 1;
456 /* Auf Aktivitaet warten */
457 i = select( Conn_MaxFD + 1, &read_sockets, &write_sockets, NULL, &tv );
460 /* keine Veraenderung an den Sockets */
465 /* Fehler (z.B. Interrupt) */
468 Log( LOG_EMERG, "Conn_Handler(): select(): %s!", strerror( errno ));
469 Log( LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE_NAME );
475 /* Koennen Daten geschrieben werden? */
476 for( i = 0; i < Conn_MaxFD + 1; i++ )
478 if( ! FD_ISSET( i, &write_sockets )) continue;
480 /* Es kann geschrieben werden ... */
481 idx = Socket2Index( i );
482 if( idx == NONE ) continue;
484 if( ! Handle_Write( idx ))
486 /* Fehler beim Schreiben! Diesen Socket nun
487 * auch aus dem Read-Set entfernen: */
488 FD_CLR( i, &read_sockets );
492 /* Daten zum Lesen vorhanden? */
493 for( i = 0; i < Conn_MaxFD + 1; i++ )
495 if( FD_ISSET( i, &read_sockets )) Handle_Read( i );
499 if( NGIRCd_SignalQuit ) Log( LOG_NOTICE|LOG_snotice, "Server going down NOW!" );
500 else if( NGIRCd_SignalRestart ) Log( LOG_NOTICE|LOG_snotice, "Server restarting NOW!" );
506 Conn_WriteStr( CONN_ID Idx, char *Format, ... )
509 Conn_WriteStr( Idx, Format, va_alist )
515 /* String in Socket schreiben. CR+LF wird von dieser Funktion
516 * automatisch angehaengt. Im Fehlerfall wird dir Verbindung
517 * getrennt und false geliefert. */
519 char buffer[COMMAND_LEN];
523 assert( Idx > NONE );
524 assert( Format != NULL );
527 va_start( ap, Format );
531 if( vsnprintf( buffer, COMMAND_LEN - 2, Format, ap ) >= COMMAND_LEN - 2 )
533 Log( LOG_CRIT, "Text too long to send (connection %d)!", Idx );
534 Conn_Close( Idx, "Text too long to send!", NULL, false );
539 if( NGIRCd_Sniffer ) Log( LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer );
542 strlcat( buffer, "\r\n", sizeof( buffer ));
543 ok = Conn_Write( Idx, buffer, strlen( buffer ));
544 My_Connections[Idx].msg_out++;
548 } /* Conn_WriteStr */
552 Conn_Write( CONN_ID Idx, char *Data, int Len )
554 /* Daten in Socket schreiben. Bei "fatalen" Fehlern wird
555 * der Client disconnectiert und false geliefert. */
557 assert( Idx > NONE );
558 assert( Data != NULL );
561 /* Ist der entsprechende Socket ueberhaupt noch offen? In einem
562 * "Handler-Durchlauf" kann es passieren, dass dem nicht mehr so
563 * ist, wenn einer von mehreren Conn_Write()'s fehlgeschlagen ist.
564 * In diesem Fall wird hier einfach ein Fehler geliefert. */
565 if( My_Connections[Idx].sock <= NONE )
568 Log( LOG_DEBUG, "Skipped write on closed socket (connection %d).", Idx );
573 /* Pruefen, ob im Schreibpuffer genuegend Platz ist. Ziel ist es,
574 * moeglichts viel im Puffer zu haben und _nicht_ gleich alles auf den
575 * Socket zu schreiben (u.a. wg. Komprimierung). */
576 if( WRITEBUFFER_LEN - My_Connections[Idx].wdatalen - Len <= 0 )
578 /* Der Puffer ist dummerweise voll. Jetzt versuchen, den Puffer
579 * zu schreiben, wenn das nicht klappt, haben wir ein Problem ... */
580 if( ! Try_Write( Idx )) return false;
582 /* nun neu pruefen: */
583 if( WRITEBUFFER_LEN - My_Connections[Idx].wdatalen - Len <= 0 )
585 Log( LOG_NOTICE, "Write buffer overflow (connection %d)!", Idx );
586 Conn_Close( Idx, "Write buffer overflow!", NULL, false );
592 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
593 /* Daten komprimieren und in Puffer kopieren */
594 if( ! Zip_Buffer( Idx, Data, Len )) return false;
599 /* Daten in Puffer kopieren */
600 memcpy( My_Connections[Idx].wbuf + My_Connections[Idx].wdatalen, Data, Len );
601 My_Connections[Idx].wdatalen += Len;
602 My_Connections[Idx].bytes_out += Len;
605 /* Adjust global write counter */
613 Conn_Close( CONN_ID Idx, char *LogMsg, char *FwdMsg, bool InformClient )
615 /* Close connection. Open pipes of asyncronous resolver
616 * sub-processes are closed down. */
622 double in_z_k, out_z_k;
626 assert( Idx > NONE );
628 /* Is this link already shutting down? */
629 if( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ISCLOSING )) {
630 /* Conn_Close() has been called recursively for this link;
631 * probabe reason: Try_Write() failed -- see below. */
633 Log( LOG_DEBUG, "Recursive request to close connection: %d", Idx );
638 assert( My_Connections[Idx].sock > NONE );
640 /* Mark link as "closing" */
641 Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCLOSING );
643 if( LogMsg ) txt = LogMsg;
645 if( ! txt ) txt = "Reason unknown";
647 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 ));
649 /* Search client, if any */
650 c = Client_GetFromConn( Idx );
652 /* Should the client be informed? */
656 /* Send statistics to client if registered as user: */
657 if(( c != NULL ) && ( Client_Type( c ) == CLIENT_USER ))
659 Conn_WriteStr( Idx, "NOTICE %s :%sConnection statistics: client %.1f kb, server %.1f kb.", Client_ThisServer( ), NOTICE_TXTPREFIX, (double)My_Connections[Idx].bytes_in / 1024, (double)My_Connections[Idx].bytes_out / 1024 );
663 /* Send ERROR to client (see RFC!) */
664 if( FwdMsg ) Conn_WriteStr( Idx, "ERROR :%s", FwdMsg );
665 else Conn_WriteStr( Idx, "ERROR :Closing connection." );
668 /* Try to write out the write buffer */
669 (void)Try_Write( Idx );
671 /* Shut down socket */
672 if( close( My_Connections[Idx].sock ) != 0 )
674 /* Oops, we can't close the socket!? This is fatal! */
675 Log( LOG_EMERG, "Error closing connection %d (socket %d) with %s:%d - %s!", Idx, My_Connections[Idx].sock, My_Connections[Idx].host, ntohs( My_Connections[Idx].addr.sin_port), strerror( errno ));
676 Log( LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE_NAME );
680 /* Mark socket as invalid: */
681 FD_CLR( My_Connections[Idx].sock, &My_Sockets );
682 My_Connections[Idx].sock = NONE;
684 /* If there is still a client, unregister it now */
685 if( c ) Client_Destroy( c, LogMsg, FwdMsg, true );
687 /* Calculate statistics and log information */
688 in_k = (double)My_Connections[Idx].bytes_in / 1024;
689 out_k = (double)My_Connections[Idx].bytes_out / 1024;
691 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
692 in_z_k = (double)My_Connections[Idx].zip.bytes_in / 1024;
693 out_z_k = (double)My_Connections[Idx].zip.bytes_out / 1024;
694 in_p = (int)(( in_k * 100 ) / in_z_k );
695 out_p = (int)(( out_k * 100 ) / out_z_k );
696 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 );
701 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 );
704 /* Is there a resolver sub-process running? */
705 if( My_Connections[Idx].res_stat )
707 /* Free resolver structures */
708 FD_CLR( My_Connections[Idx].res_stat->pipe[0], &Resolver_FDs );
709 close( My_Connections[Idx].res_stat->pipe[0] );
710 close( My_Connections[Idx].res_stat->pipe[1] );
711 free( My_Connections[Idx].res_stat );
714 /* Servers: Modify time of next connect attempt? */
715 Conf_UnsetServer( Idx );
718 /* Clean up zlib, if link was compressed */
719 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
720 inflateEnd( &My_Connections[Idx].zip.in );
721 deflateEnd( &My_Connections[Idx].zip.out );
725 /* Clean up connection structure (=free it) */
726 Init_Conn_Struct( Idx );
729 Log( LOG_DEBUG, "Shutdown of connection %d completed.", Idx );
735 Conn_SyncServerStruct( void )
737 /* Synchronize server structures (connection IDs):
738 * connections <-> configuration */
744 for( i = 0; i < Pool_Size; i++ )
746 /* Established connection? */
747 if( My_Connections[i].sock <= NONE ) continue;
749 /* Server connection? */
750 client = Client_GetFromConn( i );
751 if(( ! client ) || ( Client_Type( client ) != CLIENT_SERVER )) continue;
753 for( c = 0; c < MAX_SERVERS; c++ )
755 /* Configured server? */
756 if( ! Conf_Server[c].host[0] ) continue;
759 if( strcmp( Conf_Server[c].name, Client_ID( client )) == 0 ) Conf_Server[c].conn_id = i;
762 } /* SyncServerStruct */
766 Try_Write( CONN_ID Idx )
768 /* Versuchen, Daten aus dem Schreib-Puffer in den Socket zu
769 * schreiben. true wird geliefert, wenn entweder keine Daten
770 * zum Versenden vorhanden sind oder erfolgreich bearbeitet
771 * werden konnten. Im Fehlerfall wird false geliefert und
772 * die Verbindung geschlossen. */
777 assert( Idx > NONE );
778 assert( My_Connections[Idx].sock > NONE );
780 /* sind ueberhaupt Daten vorhanden? */
782 if(( ! My_Connections[Idx].wdatalen > 0 ) && ( ! My_Connections[Idx].zip.wdatalen )) return true;
784 if( ! My_Connections[Idx].wdatalen > 0 ) return true;
787 /* Timeout initialisieren: 0 Sekunden, also nicht blockieren */
788 tv.tv_sec = 0; tv.tv_usec = 0;
790 FD_ZERO( &write_socket );
791 FD_SET( My_Connections[Idx].sock, &write_socket );
792 if( select( My_Connections[Idx].sock + 1, NULL, &write_socket, NULL, &tv ) == -1 )
797 Log( LOG_ALERT, "Try_Write(): select() failed: %s (con=%d, sock=%d)!", strerror( errno ), Idx, My_Connections[Idx].sock );
798 Conn_Close( Idx, "Server error!", NULL, false );
803 if( FD_ISSET( My_Connections[Idx].sock, &write_socket )) return Handle_Write( Idx );
809 Handle_Read( int Sock )
811 /* Aktivitaet auf einem Socket verarbeiten:
812 * - neue Clients annehmen,
813 * - Daten von Clients verarbeiten,
814 * - Resolver-Rueckmeldungen annehmen. */
818 assert( Sock > NONE );
820 if( FD_ISSET( Sock, &My_Listeners ))
822 /* es ist einer unserer Listener-Sockets: es soll
823 * also eine neue Verbindung aufgebaut werden. */
825 New_Connection( Sock );
827 else if( FD_ISSET( Sock, &Resolver_FDs ))
829 /* Rueckmeldung von einem Resolver Sub-Prozess */
831 Read_Resolver_Result( Sock );
835 /* Ein Client Socket: entweder ein User oder Server */
837 idx = Socket2Index( Sock );
838 if( idx > NONE ) Read_Request( idx );
844 Handle_Write( CONN_ID Idx )
846 /* Daten aus Schreibpuffer versenden bzw. Connection aufbauen */
852 assert( Idx > NONE );
853 assert( My_Connections[Idx].sock > NONE );
855 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ISCONNECTING )) {
856 /* connect() has finished, check result */
858 Conn_OPTION_DEL( &My_Connections[Idx], CONN_ISCONNECTING );
860 /* Ergebnis des connect() ermitteln */
861 sock_len = sizeof( err );
862 res = getsockopt( My_Connections[Idx].sock, SOL_SOCKET, SO_ERROR, &err, &sock_len );
863 assert( sock_len == sizeof( err ));
865 /* Fehler aufgetreten? */
866 if(( res != 0 ) || ( err != 0 ))
869 if( res != 0 ) Log( LOG_CRIT, "getsockopt (connection %d): %s!", Idx, strerror( errno ));
870 else Log( LOG_CRIT, "Can't connect socket to \"%s:%d\" (connection %d): %s!", My_Connections[Idx].host, Conf_Server[Conf_GetServer( Idx )].port, Idx, strerror( err ));
872 /* Clean up socket, connection and client structures */
873 FD_CLR( My_Connections[Idx].sock, &My_Sockets );
874 c = Client_GetFromConn( Idx );
875 if( c ) Client_DestroyNow( c );
876 close( My_Connections[Idx].sock );
877 Init_Conn_Struct( Idx );
879 /* Bei Server-Verbindungen lasttry-Zeitpunkt auf "jetzt" setzen */
880 Conf_Server[Conf_GetServer( Idx )].lasttry = time( NULL );
881 Conf_UnsetServer( Idx );
885 Log( LOG_INFO, "Connection %d with \"%s:%d\" established. Now logging in ...", Idx, My_Connections[Idx].host, Conf_Server[Conf_GetServer( Idx )].port );
887 /* Send PASS and SERVER command to peer */
888 Conn_WriteStr( Idx, "PASS %s %s", Conf_Server[Conf_GetServer( Idx )].pwd_out, NGIRCd_ProtoID );
889 return Conn_WriteStr( Idx, "SERVER %s :%s", Conf_ServerName, Conf_ServerInfo );
893 /* Schreibpuffer leer, aber noch Daten im Kompressionsbuffer?
894 * Dann muss dieser nun geflushed werden! */
895 if( My_Connections[Idx].wdatalen == 0 ) Zip_Flush( Idx );
898 assert( My_Connections[Idx].wdatalen > 0 );
900 /* Daten schreiben */
901 len = send( My_Connections[Idx].sock, My_Connections[Idx].wbuf, My_Connections[Idx].wdatalen, 0 );
904 /* Operation haette Socket "nur" blockiert ... */
905 if( errno == EAGAIN ) return true;
907 /* Oops, ein Fehler! */
908 Log( LOG_ERR, "Write error on connection %d (socket %d): %s!", Idx, My_Connections[Idx].sock, strerror( errno ));
909 Conn_Close( Idx, "Write error!", NULL, false );
913 /* Puffer anpassen */
914 My_Connections[Idx].wdatalen -= len;
915 memmove( My_Connections[Idx].wbuf, My_Connections[Idx].wbuf + len, My_Connections[Idx].wdatalen );
922 New_Connection( int Sock )
924 /* Neue Client-Verbindung von Listen-Socket annehmen und
925 * CLIENT-Struktur anlegen. */
928 struct request_info req;
930 struct sockaddr_in new_addr;
931 int new_sock, new_sock_len;
938 assert( Sock > NONE );
940 /* Connection auf Listen-Socket annehmen */
941 new_sock_len = sizeof( new_addr );
942 new_sock = accept( Sock, (struct sockaddr *)&new_addr, (socklen_t *)&new_sock_len );
945 Log( LOG_CRIT, "Can't accept connection: %s!", strerror( errno ));
950 /* Validate socket using TCP Wrappers */
951 request_init( &req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock, RQ_CLIENT_SIN, &new_addr, NULL );
953 if( ! hosts_access( &req ))
956 Log( deny_severity, "Refused connection from %s (by TCP Wrappers)!", inet_ntoa( new_addr.sin_addr ));
957 Simple_Message( new_sock, "ERROR :Connection refused" );
963 /* Socket initialisieren */
964 Init_Socket( new_sock );
966 /* Check IP-based connection limit */
967 cnt = Count_Connections( new_addr );
968 if(( Conf_MaxConnectionsIP > 0 ) && ( cnt >= Conf_MaxConnectionsIP ))
970 /* Access denied, too many connections from this IP address! */
971 Log( LOG_ERR, "Refused connection from %s: too may connections (%ld) from this IP address!", inet_ntoa( new_addr.sin_addr ), cnt);
972 Simple_Message( new_sock, "ERROR :Connection refused, too many connections from your IP address!" );
977 /* Freie Connection-Struktur suchen */
978 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
979 if( idx >= Pool_Size )
981 new_size = Pool_Size + CONNECTION_POOL;
983 /* Im bisherigen Pool wurde keine freie Connection-Struktur mehr gefunden.
984 * Wenn erlaubt und moeglich muss nun der Pool vergroessert werden: */
986 if( Conf_MaxConnections > 0 )
988 /* Es ist ein Limit konfiguriert */
989 if( Pool_Size >= Conf_MaxConnections )
991 /* Mehr Verbindungen duerfen wir leider nicht mehr annehmen ... */
992 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached!", Pool_Size );
993 Simple_Message( new_sock, "ERROR :Connection limit reached" );
997 if( new_size > Conf_MaxConnections ) new_size = Conf_MaxConnections;
999 if( new_size < Pool_Size )
1001 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached -- overflow!", Pool_Size );
1002 Simple_Message( new_sock, "ERROR :Connection limit reached" );
1007 ptr = (POINTER *)realloc( My_Connections, sizeof( CONNECTION ) * new_size );
1010 Log( LOG_EMERG, "Can't allocate memory! [New_Connection]" );
1011 Simple_Message( new_sock, "ERROR: Internal error" );
1017 Log( LOG_DEBUG, "Allocated new connection pool for %ld items (%ld bytes). [realloc()]", new_size, sizeof( CONNECTION ) * new_size );
1020 /* Adjust pointer to new block */
1021 My_Connections = (CONNECTION *)ptr;
1023 /* Initialize new items */
1024 for( idx = Pool_Size; idx < new_size; idx++ ) Init_Conn_Struct( idx );
1027 /* Adjust new pool size */
1028 Pool_Size = new_size;
1031 /* Client-Struktur initialisieren */
1032 c = Client_NewLocal( idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWN, false );
1035 Log( LOG_ALERT, "Can't accept connection: can't create client structure!" );
1036 Simple_Message( new_sock, "ERROR :Internal error" );
1041 /* Verbindung registrieren */
1042 Init_Conn_Struct( idx );
1043 My_Connections[idx].sock = new_sock;
1044 My_Connections[idx].addr = new_addr;
1046 /* Neuen Socket registrieren */
1047 FD_SET( new_sock, &My_Sockets );
1048 if( new_sock > Conn_MaxFD ) Conn_MaxFD = new_sock;
1050 Log( LOG_INFO, "Accepted connection %d from %s:%d on socket %d.", idx, inet_ntoa( new_addr.sin_addr ), ntohs( new_addr.sin_port), Sock );
1052 /* Hostnamen ermitteln */
1053 strlcpy( My_Connections[idx].host, inet_ntoa( new_addr.sin_addr ), sizeof( My_Connections[idx].host ));
1054 Client_SetHostname( c, My_Connections[idx].host );
1056 s = Resolve_Addr( &new_addr, My_Connections[idx].sock );
1058 s = Resolve_Addr( &new_addr );
1062 /* Sub-Prozess wurde asyncron gestartet */
1063 My_Connections[idx].res_stat = s;
1066 /* Penalty-Zeit setzen */
1067 Conn_SetPenalty( idx, 4 );
1068 } /* New_Connection */
1072 Socket2Index( int Sock )
1074 /* zum Socket passende Connection suchen */
1078 assert( Sock > NONE );
1080 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == Sock ) break;
1082 if( idx >= Pool_Size )
1084 /* die Connection wurde vermutlich (wegen eines
1085 * Fehlers) bereits wieder abgebaut ... */
1087 Log( LOG_DEBUG, "Socket2Index: can't get connection for socket %d!", Sock );
1092 } /* Socket2Index */
1096 Read_Request( CONN_ID Idx )
1098 /* Daten von Socket einlesen und entsprechend behandeln.
1099 * Tritt ein Fehler auf, so wird der Socket geschlossen. */
1106 assert( Idx > NONE );
1107 assert( My_Connections[Idx].sock > NONE );
1109 /* wenn noch nicht registriert: maximal mit ZREADBUFFER_LEN arbeiten,
1110 * ansonsten koennen Daten ggf. nicht umkopiert werden. */
1111 bsize = READBUFFER_LEN;
1113 c = Client_GetFromConn( Idx );
1114 if(( Client_Type( c ) != CLIENT_USER ) && ( Client_Type( c ) != CLIENT_SERVER ) && ( Client_Type( c ) != CLIENT_SERVICE ) && ( bsize > ZREADBUFFER_LEN )) bsize = ZREADBUFFER_LEN;
1118 if(( bsize - My_Connections[Idx].rdatalen - 1 < 1 ) || ( ZREADBUFFER_LEN - My_Connections[Idx].zip.rdatalen < 1 ))
1120 if( bsize - My_Connections[Idx].rdatalen - 1 < 1 )
1123 /* Der Lesepuffer ist voll */
1124 Log( LOG_ERR, "Receive buffer overflow (connection %d): %d bytes!", Idx, My_Connections[Idx].rdatalen );
1125 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1130 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
1131 len = recv( My_Connections[Idx].sock, My_Connections[Idx].zip.rbuf + My_Connections[Idx].zip.rdatalen, ( ZREADBUFFER_LEN - My_Connections[Idx].zip.rdatalen ), 0 );
1132 if( len > 0 ) My_Connections[Idx].zip.rdatalen += len;
1137 len = recv( My_Connections[Idx].sock, My_Connections[Idx].rbuf + My_Connections[Idx].rdatalen, bsize - My_Connections[Idx].rdatalen - 1, 0 );
1138 if( len > 0 ) My_Connections[Idx].rdatalen += len;
1143 /* Socket wurde geschlossen */
1144 Log( LOG_INFO, "%s:%d (%s) is closing the connection ...", My_Connections[Idx].host, ntohs( My_Connections[Idx].addr.sin_port), inet_ntoa( My_Connections[Idx].addr.sin_addr ));
1145 Conn_Close( Idx, "Socket closed!", "Client closed connection", false );
1151 /* Operation haette Socket "nur" blockiert ... */
1152 if( errno == EAGAIN ) return;
1154 /* Fehler beim Lesen */
1155 Log( LOG_ERR, "Read error on connection %d (socket %d): %s!", Idx, My_Connections[Idx].sock, strerror( errno ));
1156 Conn_Close( Idx, "Read error!", "Client closed connection", false );
1160 /* Connection-Statistik aktualisieren */
1161 My_Connections[Idx].bytes_in += len;
1163 /* Timestamp aktualisieren */
1164 My_Connections[Idx].lastdata = time( NULL );
1166 Handle_Buffer( Idx );
1167 } /* Read_Request */
1171 Handle_Buffer( CONN_ID Idx )
1173 /* Daten im Lese-Puffer einer Verbindung verarbeiten.
1174 * Wurde ein Request verarbeitet, so wird true geliefert,
1175 * ansonsten false (auch bei Fehlern). */
1182 bool action, result;
1191 if( My_Connections[Idx].delaytime > time( NULL )) return result;
1194 /* ggf. noch unkomprimiete Daten weiter entpacken */
1195 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP ))
1196 if( ! Unzip_Buffer( Idx )) return false;
1199 if( My_Connections[Idx].rdatalen < 1 ) break;
1201 /* Eine komplette Anfrage muss mit CR+LF enden, vgl.
1202 * RFC 2812. Haben wir eine? */
1203 My_Connections[Idx].rbuf[My_Connections[Idx].rdatalen] = '\0';
1204 ptr = strstr( My_Connections[Idx].rbuf, "\r\n" );
1206 if( ptr ) delta = 2;
1210 /* Nicht RFC-konforme Anfrage mit nur CR oder LF? Leider
1211 * machen soetwas viele Clients, u.a. "mIRC" :-( */
1212 ptr1 = strchr( My_Connections[Idx].rbuf, '\r' );
1213 ptr2 = strchr( My_Connections[Idx].rbuf, '\n' );
1215 if( ptr1 && ptr2 ) ptr = ptr1 > ptr2 ? ptr2 : ptr1;
1216 else if( ptr1 ) ptr = ptr1;
1217 else if( ptr2 ) ptr = ptr2;
1224 /* Ende der Anfrage wurde gefunden */
1226 len = ( ptr - My_Connections[Idx].rbuf ) + delta;
1227 if( len > ( COMMAND_LEN - 1 ))
1229 /* Eine Anfrage darf(!) nicht laenger als 512 Zeichen
1230 * (incl. CR+LF!) werden; vgl. RFC 2812. Wenn soetwas
1231 * empfangen wird, wird der Client disconnectiert. */
1232 Log( LOG_ERR, "Request too long (connection %d): %d bytes (max. %d expected)!", Idx, My_Connections[Idx].rdatalen, COMMAND_LEN - 1 );
1233 Conn_Close( Idx, NULL, "Request too long", true );
1238 /* merken, ob Stream bereits komprimiert wird */
1239 old_z = My_Connections[Idx].options & CONN_ZIP;
1244 /* Es wurde ein Request gelesen */
1245 My_Connections[Idx].msg_in++;
1246 if( ! Parse_Request( Idx, My_Connections[Idx].rbuf )) return false;
1250 /* Puffer anpassen */
1251 My_Connections[Idx].rdatalen -= len;
1252 memmove( My_Connections[Idx].rbuf, My_Connections[Idx].rbuf + len, My_Connections[Idx].rdatalen );
1255 if(( ! old_z ) && ( My_Connections[Idx].options & CONN_ZIP ) && ( My_Connections[Idx].rdatalen > 0 ))
1257 /* Mit dem letzten Befehl wurde Socket-Kompression aktiviert.
1258 * Evtl. schon vom Socket gelesene Daten in den Unzip-Puffer
1259 * umkopieren, damit diese nun zunaechst entkomprimiert werden */
1260 if( My_Connections[Idx].rdatalen > ZREADBUFFER_LEN )
1262 /* Hupsa! Soviel Platz haben wir aber gar nicht! */
1263 Log( LOG_ALERT, "Can't move receive buffer: No space left in unzip buffer (need %d bytes)!", My_Connections[Idx].rdatalen );
1266 memcpy( My_Connections[Idx].zip.rbuf, My_Connections[Idx].rbuf, My_Connections[Idx].rdatalen );
1267 My_Connections[Idx].zip.rdatalen = My_Connections[Idx].rdatalen;
1268 My_Connections[Idx].rdatalen = 0;
1270 Log( LOG_DEBUG, "Moved already received data (%d bytes) to uncompression buffer.", My_Connections[Idx].zip.rdatalen );
1276 if( action ) result = true;
1280 } /* Handle_Buffer */
1284 Check_Connections( void )
1286 /* Pruefen, ob Verbindungen noch "alive" sind. Ist dies
1287 * nicht der Fall, zunaechst PING-PONG spielen und, wenn
1288 * auch das nicht "hilft", Client disconnectieren. */
1293 for( i = 0; i < Pool_Size; i++ )
1295 if( My_Connections[i].sock == NONE ) continue;
1297 c = Client_GetFromConn( i );
1298 if( c && (( Client_Type( c ) == CLIENT_USER ) || ( Client_Type( c ) == CLIENT_SERVER ) || ( Client_Type( c ) == CLIENT_SERVICE )))
1300 /* verbundener User, Server oder Service */
1301 if( My_Connections[i].lastping > My_Connections[i].lastdata )
1303 /* es wurde bereits ein PING gesendet */
1304 if( My_Connections[i].lastping < time( NULL ) - Conf_PongTimeout )
1308 Log( LOG_DEBUG, "Connection %d: Ping timeout: %d seconds.", i, Conf_PongTimeout );
1310 Conn_Close( i, NULL, "Ping timeout", true );
1313 else if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout )
1315 /* es muss ein PING gesendet werden */
1317 Log( LOG_DEBUG, "Connection %d: sending PING ...", i );
1319 My_Connections[i].lastping = time( NULL );
1320 Conn_WriteStr( i, "PING :%s", Client_ID( Client_ThisServer( )));
1325 /* noch nicht vollstaendig aufgebaute Verbindung */
1326 if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout )
1330 Log( LOG_DEBUG, "Connection %d timed out ...", i );
1332 Conn_Close( i, NULL, "Timeout", false );
1336 } /* Check_Connections */
1340 Check_Servers( void )
1342 /* Check if we can establish further server links */
1348 /* Serach all connections, are there results from the resolver? */
1349 for( idx = 0; idx < Pool_Size; idx++ )
1351 if( My_Connections[idx].sock != SERVER_WAIT ) continue;
1354 if( My_Connections[idx].res_stat == NULL ) New_Server( Conf_GetServer( idx ), idx );
1357 /* Check all configured servers */
1358 for( i = 0; i < MAX_SERVERS; i++ )
1360 /* Valid outgoing server which isn't already connected or disabled? */
1361 if(( ! Conf_Server[i].host[0] ) || ( ! Conf_Server[i].port > 0 ) || ( Conf_Server[i].conn_id > NONE ) || ( Conf_Server[i].flags & CONF_SFLAG_DISABLED )) continue;
1363 /* Is there already a connection in this group? */
1364 if( Conf_Server[i].group > NONE )
1366 for( n = 0; n < MAX_SERVERS; n++ )
1368 if( n == i ) continue;
1369 if(( Conf_Server[n].conn_id > NONE ) && ( Conf_Server[n].group == Conf_Server[i].group )) break;
1371 if( n < MAX_SERVERS ) continue;
1374 /* Check last connect attempt? */
1375 if( Conf_Server[i].lasttry > time( NULL ) - Conf_ConnectRetry ) continue;
1377 /* Okay, try to connect now */
1378 Conf_Server[i].lasttry = time( NULL );
1380 /* Search free connection structure */
1381 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
1382 if( idx >= Pool_Size )
1384 Log( LOG_ALERT, "Can't establist server connection: connection limit reached (%d)!", Pool_Size );
1388 Log( LOG_DEBUG, "Preparing connection %d for \"%s\" ...", idx, Conf_Server[i].host );
1391 /* Verbindungs-Struktur initialisieren */
1392 Init_Conn_Struct( idx );
1393 My_Connections[idx].sock = SERVER_WAIT;
1394 Conf_Server[i].conn_id = idx;
1396 /* Resolve Hostname. If this fails, try to use it as an IP address */
1397 strlcpy( Conf_Server[i].ip, Conf_Server[i].host, sizeof( Conf_Server[i].ip ));
1398 strlcpy( My_Connections[idx].host, Conf_Server[i].host, sizeof( My_Connections[idx].host ));
1399 s = Resolve_Name( Conf_Server[i].host );
1402 /* Sub-Prozess wurde asyncron gestartet */
1403 My_Connections[idx].res_stat = s;
1406 } /* Check_Servers */
1410 New_Server( int Server, CONN_ID Idx )
1412 /* Establish new server link */
1414 struct sockaddr_in new_addr;
1415 struct in_addr inaddr;
1419 assert( Server > NONE );
1420 assert( Idx > NONE );
1422 /* Did we get a valid IP address? */
1423 if( ! Conf_Server[Server].ip[0] )
1425 /* No. Free connection structure and abort: */
1426 Init_Conn_Struct( Idx );
1427 Conf_Server[Server].conn_id = NONE;
1428 Log( LOG_ERR, "Can't connect to \"%s\" (connection %d): ip address unknown!", Conf_Server[Server].host, Idx );
1432 Log( LOG_INFO, "Establishing connection to \"%s\", %s, port %d (connection %d) ... ", Conf_Server[Server].host, Conf_Server[Server].ip, Conf_Server[Server].port, Idx );
1434 #ifdef HAVE_INET_ATON
1435 if( inet_aton( Conf_Server[Server].ip, &inaddr ) == 0 )
1437 memset( &inaddr, 0, sizeof( inaddr ));
1438 inaddr.s_addr = inet_addr( Conf_Server[Server].ip );
1439 if( inaddr.s_addr == (unsigned)-1 )
1442 /* Can't convert IP address */
1443 Init_Conn_Struct( Idx );
1444 Conf_Server[Server].conn_id = NONE;
1445 Log( LOG_ERR, "Can't connect to \"%s\" (connection %d): can't convert ip address %s!", Conf_Server[Server].host, Idx, Conf_Server[Server].ip );
1449 memset( &new_addr, 0, sizeof( new_addr ));
1450 new_addr.sin_family = AF_INET;
1451 new_addr.sin_addr = inaddr;
1452 new_addr.sin_port = htons( Conf_Server[Server].port );
1454 new_sock = socket( PF_INET, SOCK_STREAM, 0 );
1457 /* Can't create socket */
1458 Init_Conn_Struct( Idx );
1459 Conf_Server[Server].conn_id = NONE;
1460 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
1464 if( ! Init_Socket( new_sock )) return;
1466 res = connect( new_sock, (struct sockaddr *)&new_addr, sizeof( new_addr ));
1467 if(( res != 0 ) && ( errno != EINPROGRESS ))
1469 /* Can't connect socket */
1470 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1472 Init_Conn_Struct( Idx );
1473 Conf_Server[Server].conn_id = NONE;
1477 /* Client-Struktur initialisieren */
1478 c = Client_NewLocal( Idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWNSERVER, false );
1481 /* Can't create new client structure */
1483 Init_Conn_Struct( Idx );
1484 Conf_Server[Server].conn_id = NONE;
1485 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1488 Client_SetIntroducer( c, c );
1489 Client_SetToken( c, TOKEN_OUTBOUND );
1491 /* Register connection */
1492 My_Connections[Idx].sock = new_sock;
1493 My_Connections[Idx].addr = new_addr;
1494 strlcpy( My_Connections[Idx].host, Conf_Server[Server].host, sizeof( My_Connections[Idx].host ));
1496 /* Register new socket */
1497 FD_SET( new_sock, &My_Sockets );
1498 Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCONNECTING );
1500 if( new_sock > Conn_MaxFD ) Conn_MaxFD = new_sock;
1503 Log( LOG_DEBUG, "Registered new connection %d on socket %d.", Idx, My_Connections[Idx].sock );
1509 Init_Conn_Struct( CONN_ID Idx )
1511 time_t now = time( NULL );
1512 /* Connection-Struktur initialisieren */
1514 memset( &My_Connections[Idx], 0, sizeof ( CONNECTION ));
1515 My_Connections[Idx].sock = NONE;
1516 My_Connections[Idx].starttime = now;
1517 My_Connections[Idx].lastdata = now;
1518 My_Connections[Idx].lastprivmsg = now;
1519 } /* Init_Conn_Struct */
1523 Init_Socket( int Sock )
1525 /* Initialize socket (set options) */
1529 #ifdef O_NONBLOCK /* unknown on A/UX */
1530 if( fcntl( Sock, F_SETFL, O_NONBLOCK ) != 0 )
1532 Log( LOG_CRIT, "Can't enable non-blocking mode for socket: %s!", strerror( errno ));
1538 /* Don't block this port after socket shutdown */
1540 if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &value, (socklen_t)sizeof( value )) != 0 )
1542 Log( LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!", strerror( errno ));
1543 /* ignore this error */
1546 /* Set type of service (TOS) */
1547 #if defined(IP_TOS) && defined(IPTOS_LOWDELAY)
1548 value = IPTOS_LOWDELAY;
1550 Log( LOG_DEBUG, "Setting option IP_TOS on socket %d to IPTOS_LOWDELAY (%d).", Sock, value );
1552 if( setsockopt( Sock, SOL_IP, IP_TOS, &value, (socklen_t)sizeof( value )) != 0 )
1554 Log( LOG_ERR, "Can't set socket option IP_TOS: %s!", strerror( errno ));
1555 /* ignore this error */
1564 Read_Resolver_Result( int r_fd )
1566 /* Read result of resolver sub-process from pipe and update the
1567 * apropriate connection/client structure(s): hostname and/or
1568 * IDENT user name.*/
1575 /* Search associated connection ... */
1576 for( i = 0; i < Pool_Size; i++ )
1578 if(( My_Connections[i].sock != NONE )
1579 && ( My_Connections[i].res_stat != NULL )
1580 && ( My_Connections[i].res_stat->pipe[0] == r_fd ))
1583 if( i >= Pool_Size )
1585 /* Ops, none found? Probably the connection has already
1586 * been closed!? We'll ignore that ... */
1587 FD_CLR( r_fd, &Resolver_FDs );
1590 Log( LOG_DEBUG, "Resolver: Got result for unknown connection!?" );
1595 /* Get resolver structure */
1596 s = My_Connections[i].res_stat;
1597 assert( s != NULL );
1599 /* Read result from pipe */
1600 len = read( r_fd, s->buffer + s->bufpos, sizeof( s->buffer ) - s->bufpos - 1 );
1605 Log( LOG_CRIT, "Resolver: Can't read result: %s!", strerror( errno ));
1609 s->buffer[s->bufpos] = '\0';
1611 /* If the result string is incomplete, return to main loop and
1612 * wait until we can read in more bytes. */
1616 ptr = strchr( s->buffer, '\n' );
1621 Log( LOG_DEBUG, "Got result from resolver: \"%s\" (%d bytes), stage %d.", s->buffer, len, s->stage );
1624 /* Okay, we got a complete result: this is a host name for outgoing
1625 * connections and a host name or IDENT user name (if enabled) for
1626 * incoming conneciions.*/
1627 if( My_Connections[i].sock > NONE )
1629 /* Incoming connection */
1631 /* Search client ... */
1632 c = Client_GetFromConn( i );
1633 assert( c != NULL );
1635 /* Only update client information of unregistered clients */
1636 if( Client_Type( c ) == CLIENT_UNKNOWN )
1641 strlcpy( My_Connections[i].host, s->buffer, sizeof( My_Connections[i].host ));
1642 Client_SetHostname( c, s->buffer );
1645 /* clean up buffer for IDENT result */
1646 len = strlen( s->buffer ) + 1;
1647 memmove( s->buffer, s->buffer + len, sizeof( s->buffer ) - len );
1650 /* Don't close pipe and clean up, but
1651 * instead wait for IDENT result */
1655 else if( s->stage == 1 )
1657 /* IDENT user name */
1660 Log( LOG_INFO, "IDENT lookup for connection %ld: \"%s\".", i, s->buffer );
1661 Client_SetUser( c, s->buffer, true );
1663 else Log( LOG_INFO, "IDENT lookup for connection %ld: no result.", i );
1666 else Log( LOG_ERR, "Resolver: got result for unknown stage %d!?", s->stage );
1669 else Log( LOG_DEBUG, "Resolver: discarding result for already registered connection %d.", i );
1674 /* Outgoing connection (server link): set the IP address
1675 * so that we can connect to it in the main loop. */
1677 /* Search server ... */
1678 n = Conf_GetServer( i );
1681 strlcpy( Conf_Server[n].ip, s->buffer, sizeof( Conf_Server[n].ip ));
1685 FD_CLR( r_fd, &Resolver_FDs );
1686 close( My_Connections[i].res_stat->pipe[0] );
1687 close( My_Connections[i].res_stat->pipe[1] );
1688 free( My_Connections[i].res_stat );
1689 My_Connections[i].res_stat = NULL;
1691 /* Reset penalty time */
1692 Conn_ResetPenalty( i );
1693 } /* Read_Resolver_Result */
1697 Simple_Message( int Sock, char *Msg )
1699 /* Write "simple" message to socket, without using compression
1700 * or even the connection write buffers. Used e.g. for error
1701 * messages by New_Connection(). */
1703 assert( Sock > NONE );
1704 assert( Msg != NULL );
1706 (void)send( Sock, Msg, strlen( Msg ), 0 );
1707 (void)send( Sock, "\r\n", 2, 0 );
1708 } /* Simple_Error */
1712 Count_Connections( struct sockaddr_in addr_in )
1717 for( i = 0; i < Pool_Size; i++ )
1719 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].addr.sin_addr.s_addr == addr_in.sin_addr.s_addr )) cnt++;
1722 } /* Count_Connections */