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.150 2005/05/22 23:55:58 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 */
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 ... ugly! */
675 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 ));
678 /* Mark socket as invalid: */
679 FD_CLR( My_Connections[Idx].sock, &My_Sockets );
680 My_Connections[Idx].sock = NONE;
682 /* If there is still a client, unregister it now */
683 if( c ) Client_Destroy( c, LogMsg, FwdMsg, true );
685 /* Calculate statistics and log information */
686 in_k = (double)My_Connections[Idx].bytes_in / 1024;
687 out_k = (double)My_Connections[Idx].bytes_out / 1024;
689 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
690 in_z_k = (double)My_Connections[Idx].zip.bytes_in / 1024;
691 out_z_k = (double)My_Connections[Idx].zip.bytes_out / 1024;
692 in_p = (int)(( in_k * 100 ) / in_z_k );
693 out_p = (int)(( out_k * 100 ) / out_z_k );
694 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 );
699 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 );
702 /* Is there a resolver sub-process running? */
703 if( My_Connections[Idx].res_stat )
705 /* Free resolver structures */
706 FD_CLR( My_Connections[Idx].res_stat->pipe[0], &Resolver_FDs );
707 close( My_Connections[Idx].res_stat->pipe[0] );
708 close( My_Connections[Idx].res_stat->pipe[1] );
709 free( My_Connections[Idx].res_stat );
712 /* Servers: Modify time of next connect attempt? */
713 Conf_UnsetServer( Idx );
716 /* Clean up zlib, if link was compressed */
717 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
718 inflateEnd( &My_Connections[Idx].zip.in );
719 deflateEnd( &My_Connections[Idx].zip.out );
723 /* Clean up connection structure (=free it) */
724 Init_Conn_Struct( Idx );
727 Log( LOG_DEBUG, "Shutdown of connection %d completed.", Idx );
733 Conn_SyncServerStruct( void )
735 /* Synchronize server structures (connection IDs):
736 * connections <-> configuration */
742 for( i = 0; i < Pool_Size; i++ )
744 /* Established connection? */
745 if( My_Connections[i].sock <= NONE ) continue;
747 /* Server connection? */
748 client = Client_GetFromConn( i );
749 if(( ! client ) || ( Client_Type( client ) != CLIENT_SERVER )) continue;
751 for( c = 0; c < MAX_SERVERS; c++ )
753 /* Configured server? */
754 if( ! Conf_Server[c].host[0] ) continue;
757 if( strcmp( Conf_Server[c].name, Client_ID( client )) == 0 ) Conf_Server[c].conn_id = i;
760 } /* SyncServerStruct */
764 Try_Write( CONN_ID Idx )
766 /* Versuchen, Daten aus dem Schreib-Puffer in den Socket zu
767 * schreiben. true wird geliefert, wenn entweder keine Daten
768 * zum Versenden vorhanden sind oder erfolgreich bearbeitet
769 * werden konnten. Im Fehlerfall wird false geliefert und
770 * die Verbindung geschlossen. */
775 assert( Idx > NONE );
776 assert( My_Connections[Idx].sock > NONE );
778 /* sind ueberhaupt Daten vorhanden? */
780 if(( ! My_Connections[Idx].wdatalen > 0 ) && ( ! My_Connections[Idx].zip.wdatalen )) return true;
782 if( ! My_Connections[Idx].wdatalen > 0 ) return true;
785 /* Timeout initialisieren: 0 Sekunden, also nicht blockieren */
786 tv.tv_sec = 0; tv.tv_usec = 0;
788 FD_ZERO( &write_socket );
789 FD_SET( My_Connections[Idx].sock, &write_socket );
790 if( select( My_Connections[Idx].sock + 1, NULL, &write_socket, NULL, &tv ) == -1 )
795 Log( LOG_ALERT, "Try_Write(): select() failed: %s (con=%d, sock=%d)!", strerror( errno ), Idx, My_Connections[Idx].sock );
796 Conn_Close( Idx, "Server error!", NULL, false );
801 if( FD_ISSET( My_Connections[Idx].sock, &write_socket )) return Handle_Write( Idx );
807 Handle_Read( int Sock )
809 /* Aktivitaet auf einem Socket verarbeiten:
810 * - neue Clients annehmen,
811 * - Daten von Clients verarbeiten,
812 * - Resolver-Rueckmeldungen annehmen. */
816 assert( Sock > NONE );
818 if( FD_ISSET( Sock, &My_Listeners ))
820 /* es ist einer unserer Listener-Sockets: es soll
821 * also eine neue Verbindung aufgebaut werden. */
823 New_Connection( Sock );
825 else if( FD_ISSET( Sock, &Resolver_FDs ))
827 /* Rueckmeldung von einem Resolver Sub-Prozess */
829 Read_Resolver_Result( Sock );
833 /* Ein Client Socket: entweder ein User oder Server */
835 idx = Socket2Index( Sock );
836 if( idx > NONE ) Read_Request( idx );
842 Handle_Write( CONN_ID Idx )
844 /* Daten aus Schreibpuffer versenden bzw. Connection aufbauen */
850 assert( Idx > NONE );
851 assert( My_Connections[Idx].sock > NONE );
853 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ISCONNECTING )) {
854 /* connect() has finished, check result */
856 Conn_OPTION_DEL( &My_Connections[Idx], CONN_ISCONNECTING );
858 /* Ergebnis des connect() ermitteln */
859 sock_len = sizeof( err );
860 res = getsockopt( My_Connections[Idx].sock, SOL_SOCKET, SO_ERROR, &err, &sock_len );
861 assert( sock_len == sizeof( err ));
863 /* Fehler aufgetreten? */
864 if(( res != 0 ) || ( err != 0 ))
867 if( res != 0 ) Log( LOG_CRIT, "getsockopt (connection %d): %s!", Idx, strerror( errno ));
868 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 ));
870 /* Clean up socket, connection and client structures */
871 FD_CLR( My_Connections[Idx].sock, &My_Sockets );
872 c = Client_GetFromConn( Idx );
873 if( c ) Client_DestroyNow( c );
874 close( My_Connections[Idx].sock );
875 Init_Conn_Struct( Idx );
877 /* Bei Server-Verbindungen lasttry-Zeitpunkt auf "jetzt" setzen */
878 Conf_Server[Conf_GetServer( Idx )].lasttry = time( NULL );
879 Conf_UnsetServer( Idx );
883 Log( LOG_INFO, "Connection %d with \"%s:%d\" established. Now logging in ...", Idx, My_Connections[Idx].host, Conf_Server[Conf_GetServer( Idx )].port );
885 /* Send PASS and SERVER command to peer */
886 Conn_WriteStr( Idx, "PASS %s %s", Conf_Server[Conf_GetServer( Idx )].pwd_out, NGIRCd_ProtoID );
887 return Conn_WriteStr( Idx, "SERVER %s :%s", Conf_ServerName, Conf_ServerInfo );
891 /* Schreibpuffer leer, aber noch Daten im Kompressionsbuffer?
892 * Dann muss dieser nun geflushed werden! */
893 if( My_Connections[Idx].wdatalen == 0 ) Zip_Flush( Idx );
896 assert( My_Connections[Idx].wdatalen > 0 );
898 /* Daten schreiben */
899 len = send( My_Connections[Idx].sock, My_Connections[Idx].wbuf, My_Connections[Idx].wdatalen, 0 );
902 /* Operation haette Socket "nur" blockiert ... */
903 if( errno == EAGAIN ) return true;
905 /* Oops, ein Fehler! */
906 Log( LOG_ERR, "Write error on connection %d (socket %d): %s!", Idx, My_Connections[Idx].sock, strerror( errno ));
907 Conn_Close( Idx, "Write error!", NULL, false );
911 /* Puffer anpassen */
912 My_Connections[Idx].wdatalen -= len;
913 memmove( My_Connections[Idx].wbuf, My_Connections[Idx].wbuf + len, My_Connections[Idx].wdatalen );
920 New_Connection( int Sock )
922 /* Neue Client-Verbindung von Listen-Socket annehmen und
923 * CLIENT-Struktur anlegen. */
926 struct request_info req;
928 struct sockaddr_in new_addr;
929 int new_sock, new_sock_len;
936 assert( Sock > NONE );
938 /* Connection auf Listen-Socket annehmen */
939 new_sock_len = sizeof( new_addr );
940 new_sock = accept( Sock, (struct sockaddr *)&new_addr, (socklen_t *)&new_sock_len );
943 Log( LOG_CRIT, "Can't accept connection: %s!", strerror( errno ));
948 /* Validate socket using TCP Wrappers */
949 request_init( &req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock, RQ_CLIENT_SIN, &new_addr, NULL );
951 if( ! hosts_access( &req ))
954 Log( deny_severity, "Refused connection from %s (by TCP Wrappers)!", inet_ntoa( new_addr.sin_addr ));
955 Simple_Message( new_sock, "ERROR :Connection refused" );
961 /* Socket initialisieren */
962 Init_Socket( new_sock );
964 /* Check IP-based connection limit */
965 cnt = Count_Connections( new_addr );
966 if(( Conf_MaxConnectionsIP > 0 ) && ( cnt >= Conf_MaxConnectionsIP ))
968 /* Access denied, too many connections from this IP address! */
969 Log( LOG_ERR, "Refused connection from %s: too may connections (%ld) from this IP address!", inet_ntoa( new_addr.sin_addr ), cnt);
970 Simple_Message( new_sock, "ERROR :Connection refused, too many connections from your IP address!" );
975 /* Freie Connection-Struktur suchen */
976 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
977 if( idx >= Pool_Size )
979 new_size = Pool_Size + CONNECTION_POOL;
981 /* Im bisherigen Pool wurde keine freie Connection-Struktur mehr gefunden.
982 * Wenn erlaubt und moeglich muss nun der Pool vergroessert werden: */
984 if( Conf_MaxConnections > 0 )
986 /* Es ist ein Limit konfiguriert */
987 if( Pool_Size >= Conf_MaxConnections )
989 /* Mehr Verbindungen duerfen wir leider nicht mehr annehmen ... */
990 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached!", Pool_Size );
991 Simple_Message( new_sock, "ERROR :Connection limit reached" );
995 if( new_size > Conf_MaxConnections ) new_size = Conf_MaxConnections;
997 if( new_size < Pool_Size )
999 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached -- overflow!", Pool_Size );
1000 Simple_Message( new_sock, "ERROR :Connection limit reached" );
1005 ptr = (POINTER *)realloc( My_Connections, sizeof( CONNECTION ) * new_size );
1008 Log( LOG_EMERG, "Can't allocate memory! [New_Connection]" );
1009 Simple_Message( new_sock, "ERROR: Internal error" );
1015 Log( LOG_DEBUG, "Allocated new connection pool for %ld items (%ld bytes). [realloc()]", new_size, sizeof( CONNECTION ) * new_size );
1018 /* Adjust pointer to new block */
1019 My_Connections = (CONNECTION *)ptr;
1021 /* Initialize new items */
1022 for( idx = Pool_Size; idx < new_size; idx++ ) Init_Conn_Struct( idx );
1025 /* Adjust new pool size */
1026 Pool_Size = new_size;
1029 /* Client-Struktur initialisieren */
1030 c = Client_NewLocal( idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWN, false );
1033 Log( LOG_ALERT, "Can't accept connection: can't create client structure!" );
1034 Simple_Message( new_sock, "ERROR :Internal error" );
1039 /* Verbindung registrieren */
1040 Init_Conn_Struct( idx );
1041 My_Connections[idx].sock = new_sock;
1042 My_Connections[idx].addr = new_addr;
1044 /* Neuen Socket registrieren */
1045 FD_SET( new_sock, &My_Sockets );
1046 if( new_sock > Conn_MaxFD ) Conn_MaxFD = new_sock;
1048 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 );
1050 /* Hostnamen ermitteln */
1051 strlcpy( My_Connections[idx].host, inet_ntoa( new_addr.sin_addr ), sizeof( My_Connections[idx].host ));
1052 Client_SetHostname( c, My_Connections[idx].host );
1054 s = Resolve_Addr( &new_addr, My_Connections[idx].sock );
1056 s = Resolve_Addr( &new_addr );
1060 /* Sub-Prozess wurde asyncron gestartet */
1061 My_Connections[idx].res_stat = s;
1064 /* Penalty-Zeit setzen */
1065 Conn_SetPenalty( idx, 4 );
1066 } /* New_Connection */
1070 Socket2Index( int Sock )
1072 /* zum Socket passende Connection suchen */
1076 assert( Sock > NONE );
1078 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == Sock ) break;
1080 if( idx >= Pool_Size )
1082 /* die Connection wurde vermutlich (wegen eines
1083 * Fehlers) bereits wieder abgebaut ... */
1085 Log( LOG_DEBUG, "Socket2Index: can't get connection for socket %d!", Sock );
1090 } /* Socket2Index */
1094 Read_Request( CONN_ID Idx )
1096 /* Daten von Socket einlesen und entsprechend behandeln.
1097 * Tritt ein Fehler auf, so wird der Socket geschlossen. */
1104 assert( Idx > NONE );
1105 assert( My_Connections[Idx].sock > NONE );
1107 /* wenn noch nicht registriert: maximal mit ZREADBUFFER_LEN arbeiten,
1108 * ansonsten koennen Daten ggf. nicht umkopiert werden. */
1109 bsize = READBUFFER_LEN;
1111 c = Client_GetFromConn( Idx );
1112 if(( Client_Type( c ) != CLIENT_USER ) && ( Client_Type( c ) != CLIENT_SERVER ) && ( Client_Type( c ) != CLIENT_SERVICE ) && ( bsize > ZREADBUFFER_LEN )) bsize = ZREADBUFFER_LEN;
1116 if(( bsize - My_Connections[Idx].rdatalen - 1 < 1 ) || ( ZREADBUFFER_LEN - My_Connections[Idx].zip.rdatalen < 1 ))
1118 if( bsize - My_Connections[Idx].rdatalen - 1 < 1 )
1121 /* Der Lesepuffer ist voll */
1122 Log( LOG_ERR, "Receive buffer overflow (connection %d): %d bytes!", Idx, My_Connections[Idx].rdatalen );
1123 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1128 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
1129 len = recv( My_Connections[Idx].sock, My_Connections[Idx].zip.rbuf + My_Connections[Idx].zip.rdatalen, ( ZREADBUFFER_LEN - My_Connections[Idx].zip.rdatalen ), 0 );
1130 if( len > 0 ) My_Connections[Idx].zip.rdatalen += len;
1135 len = recv( My_Connections[Idx].sock, My_Connections[Idx].rbuf + My_Connections[Idx].rdatalen, bsize - My_Connections[Idx].rdatalen - 1, 0 );
1136 if( len > 0 ) My_Connections[Idx].rdatalen += len;
1141 /* Socket wurde geschlossen */
1142 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 ));
1143 Conn_Close( Idx, "Socket closed!", "Client closed connection", false );
1149 /* Operation haette Socket "nur" blockiert ... */
1150 if( errno == EAGAIN ) return;
1152 /* Fehler beim Lesen */
1153 Log( LOG_ERR, "Read error on connection %d (socket %d): %s!", Idx, My_Connections[Idx].sock, strerror( errno ));
1154 Conn_Close( Idx, "Read error!", "Client closed connection", false );
1158 /* Connection-Statistik aktualisieren */
1159 My_Connections[Idx].bytes_in += len;
1161 /* Timestamp aktualisieren */
1162 My_Connections[Idx].lastdata = time( NULL );
1164 Handle_Buffer( Idx );
1165 } /* Read_Request */
1169 Handle_Buffer( CONN_ID Idx )
1171 /* Daten im Lese-Puffer einer Verbindung verarbeiten.
1172 * Wurde ein Request verarbeitet, so wird true geliefert,
1173 * ansonsten false (auch bei Fehlern). */
1180 bool action, result;
1189 if( My_Connections[Idx].delaytime > time( NULL )) return result;
1192 /* ggf. noch unkomprimiete Daten weiter entpacken */
1193 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP ))
1194 if( ! Unzip_Buffer( Idx )) return false;
1197 if( My_Connections[Idx].rdatalen < 1 ) break;
1199 /* Eine komplette Anfrage muss mit CR+LF enden, vgl.
1200 * RFC 2812. Haben wir eine? */
1201 My_Connections[Idx].rbuf[My_Connections[Idx].rdatalen] = '\0';
1202 ptr = strstr( My_Connections[Idx].rbuf, "\r\n" );
1204 if( ptr ) delta = 2;
1208 /* Nicht RFC-konforme Anfrage mit nur CR oder LF? Leider
1209 * machen soetwas viele Clients, u.a. "mIRC" :-( */
1210 ptr1 = strchr( My_Connections[Idx].rbuf, '\r' );
1211 ptr2 = strchr( My_Connections[Idx].rbuf, '\n' );
1213 if( ptr1 && ptr2 ) ptr = ptr1 > ptr2 ? ptr2 : ptr1;
1214 else if( ptr1 ) ptr = ptr1;
1215 else if( ptr2 ) ptr = ptr2;
1222 /* Ende der Anfrage wurde gefunden */
1224 len = ( ptr - My_Connections[Idx].rbuf ) + delta;
1225 if( len > ( COMMAND_LEN - 1 ))
1227 /* Eine Anfrage darf(!) nicht laenger als 512 Zeichen
1228 * (incl. CR+LF!) werden; vgl. RFC 2812. Wenn soetwas
1229 * empfangen wird, wird der Client disconnectiert. */
1230 Log( LOG_ERR, "Request too long (connection %d): %d bytes (max. %d expected)!", Idx, My_Connections[Idx].rdatalen, COMMAND_LEN - 1 );
1231 Conn_Close( Idx, NULL, "Request too long", true );
1236 /* merken, ob Stream bereits komprimiert wird */
1237 old_z = My_Connections[Idx].options & CONN_ZIP;
1242 /* Es wurde ein Request gelesen */
1243 My_Connections[Idx].msg_in++;
1244 if( ! Parse_Request( Idx, My_Connections[Idx].rbuf )) return false;
1248 /* Puffer anpassen */
1249 My_Connections[Idx].rdatalen -= len;
1250 memmove( My_Connections[Idx].rbuf, My_Connections[Idx].rbuf + len, My_Connections[Idx].rdatalen );
1253 if(( ! old_z ) && ( My_Connections[Idx].options & CONN_ZIP ) && ( My_Connections[Idx].rdatalen > 0 ))
1255 /* Mit dem letzten Befehl wurde Socket-Kompression aktiviert.
1256 * Evtl. schon vom Socket gelesene Daten in den Unzip-Puffer
1257 * umkopieren, damit diese nun zunaechst entkomprimiert werden */
1258 if( My_Connections[Idx].rdatalen > ZREADBUFFER_LEN )
1260 /* Hupsa! Soviel Platz haben wir aber gar nicht! */
1261 Log( LOG_ALERT, "Can't move receive buffer: No space left in unzip buffer (need %d bytes)!", My_Connections[Idx].rdatalen );
1264 memcpy( My_Connections[Idx].zip.rbuf, My_Connections[Idx].rbuf, My_Connections[Idx].rdatalen );
1265 My_Connections[Idx].zip.rdatalen = My_Connections[Idx].rdatalen;
1266 My_Connections[Idx].rdatalen = 0;
1268 Log( LOG_DEBUG, "Moved already received data (%d bytes) to uncompression buffer.", My_Connections[Idx].zip.rdatalen );
1274 if( action ) result = true;
1278 } /* Handle_Buffer */
1282 Check_Connections( void )
1284 /* Pruefen, ob Verbindungen noch "alive" sind. Ist dies
1285 * nicht der Fall, zunaechst PING-PONG spielen und, wenn
1286 * auch das nicht "hilft", Client disconnectieren. */
1291 for( i = 0; i < Pool_Size; i++ )
1293 if( My_Connections[i].sock == NONE ) continue;
1295 c = Client_GetFromConn( i );
1296 if( c && (( Client_Type( c ) == CLIENT_USER ) || ( Client_Type( c ) == CLIENT_SERVER ) || ( Client_Type( c ) == CLIENT_SERVICE )))
1298 /* verbundener User, Server oder Service */
1299 if( My_Connections[i].lastping > My_Connections[i].lastdata )
1301 /* es wurde bereits ein PING gesendet */
1302 if( My_Connections[i].lastping < time( NULL ) - Conf_PongTimeout )
1306 Log( LOG_DEBUG, "Connection %d: Ping timeout: %d seconds.", i, Conf_PongTimeout );
1308 Conn_Close( i, NULL, "Ping timeout", true );
1311 else if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout )
1313 /* es muss ein PING gesendet werden */
1315 Log( LOG_DEBUG, "Connection %d: sending PING ...", i );
1317 My_Connections[i].lastping = time( NULL );
1318 Conn_WriteStr( i, "PING :%s", Client_ID( Client_ThisServer( )));
1323 /* noch nicht vollstaendig aufgebaute Verbindung */
1324 if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout )
1328 Log( LOG_DEBUG, "Connection %d timed out ...", i );
1330 Conn_Close( i, NULL, "Timeout", false );
1334 } /* Check_Connections */
1338 Check_Servers( void )
1340 /* Check if we can establish further server links */
1346 /* Serach all connections, are there results from the resolver? */
1347 for( idx = 0; idx < Pool_Size; idx++ )
1349 if( My_Connections[idx].sock != SERVER_WAIT ) continue;
1352 if( My_Connections[idx].res_stat == NULL ) New_Server( Conf_GetServer( idx ), idx );
1355 /* Check all configured servers */
1356 for( i = 0; i < MAX_SERVERS; i++ )
1358 /* Valid outgoing server which isn't already connected or disabled? */
1359 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;
1361 /* Is there already a connection in this group? */
1362 if( Conf_Server[i].group > NONE )
1364 for( n = 0; n < MAX_SERVERS; n++ )
1366 if( n == i ) continue;
1367 if(( Conf_Server[n].conn_id > NONE ) && ( Conf_Server[n].group == Conf_Server[i].group )) break;
1369 if( n < MAX_SERVERS ) continue;
1372 /* Check last connect attempt? */
1373 if( Conf_Server[i].lasttry > time( NULL ) - Conf_ConnectRetry ) continue;
1375 /* Okay, try to connect now */
1376 Conf_Server[i].lasttry = time( NULL );
1378 /* Search free connection structure */
1379 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
1380 if( idx >= Pool_Size )
1382 Log( LOG_ALERT, "Can't establist server connection: connection limit reached (%d)!", Pool_Size );
1386 Log( LOG_DEBUG, "Preparing connection %d for \"%s\" ...", idx, Conf_Server[i].host );
1389 /* Verbindungs-Struktur initialisieren */
1390 Init_Conn_Struct( idx );
1391 My_Connections[idx].sock = SERVER_WAIT;
1392 Conf_Server[i].conn_id = idx;
1394 /* Resolve Hostname. If this fails, try to use it as an IP address */
1395 strlcpy( Conf_Server[i].ip, Conf_Server[i].host, sizeof( Conf_Server[i].ip ));
1396 strlcpy( My_Connections[idx].host, Conf_Server[i].host, sizeof( My_Connections[idx].host ));
1397 s = Resolve_Name( Conf_Server[i].host );
1400 /* Sub-Prozess wurde asyncron gestartet */
1401 My_Connections[idx].res_stat = s;
1404 } /* Check_Servers */
1408 New_Server( int Server, CONN_ID Idx )
1410 /* Establish new server link */
1412 struct sockaddr_in new_addr;
1413 struct in_addr inaddr;
1417 assert( Server > NONE );
1418 assert( Idx > NONE );
1420 /* Did we get a valid IP address? */
1421 if( ! Conf_Server[Server].ip[0] )
1423 /* No. Free connection structure and abort: */
1424 Init_Conn_Struct( Idx );
1425 Conf_Server[Server].conn_id = NONE;
1426 Log( LOG_ERR, "Can't connect to \"%s\" (connection %d): ip address unknown!", Conf_Server[Server].host, Idx );
1430 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 );
1432 #ifdef HAVE_INET_ATON
1433 if( inet_aton( Conf_Server[Server].ip, &inaddr ) == 0 )
1435 memset( &inaddr, 0, sizeof( inaddr ));
1436 inaddr.s_addr = inet_addr( Conf_Server[Server].ip );
1437 if( inaddr.s_addr == (unsigned)-1 )
1440 /* Can't convert IP address */
1441 Init_Conn_Struct( Idx );
1442 Conf_Server[Server].conn_id = NONE;
1443 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 );
1447 memset( &new_addr, 0, sizeof( new_addr ));
1448 new_addr.sin_family = AF_INET;
1449 new_addr.sin_addr = inaddr;
1450 new_addr.sin_port = htons( Conf_Server[Server].port );
1452 new_sock = socket( PF_INET, SOCK_STREAM, 0 );
1455 /* Can't create socket */
1456 Init_Conn_Struct( Idx );
1457 Conf_Server[Server].conn_id = NONE;
1458 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
1462 if( ! Init_Socket( new_sock )) return;
1464 res = connect( new_sock, (struct sockaddr *)&new_addr, sizeof( new_addr ));
1465 if(( res != 0 ) && ( errno != EINPROGRESS ))
1467 /* Can't connect socket */
1468 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1470 Init_Conn_Struct( Idx );
1471 Conf_Server[Server].conn_id = NONE;
1475 /* Client-Struktur initialisieren */
1476 c = Client_NewLocal( Idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWNSERVER, false );
1479 /* Can't create new client structure */
1481 Init_Conn_Struct( Idx );
1482 Conf_Server[Server].conn_id = NONE;
1483 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1486 Client_SetIntroducer( c, c );
1487 Client_SetToken( c, TOKEN_OUTBOUND );
1489 /* Register connection */
1490 My_Connections[Idx].sock = new_sock;
1491 My_Connections[Idx].addr = new_addr;
1492 strlcpy( My_Connections[Idx].host, Conf_Server[Server].host, sizeof( My_Connections[Idx].host ));
1494 /* Register new socket */
1495 FD_SET( new_sock, &My_Sockets );
1496 Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCONNECTING );
1498 if( new_sock > Conn_MaxFD ) Conn_MaxFD = new_sock;
1501 Log( LOG_DEBUG, "Registered new connection %d on socket %d.", Idx, My_Connections[Idx].sock );
1507 Init_Conn_Struct( CONN_ID Idx )
1509 time_t now = time( NULL );
1510 /* Connection-Struktur initialisieren */
1512 memset( &My_Connections[Idx], 0, sizeof ( CONNECTION ));
1513 My_Connections[Idx].sock = NONE;
1514 My_Connections[Idx].starttime = now;
1515 My_Connections[Idx].lastdata = now;
1516 My_Connections[Idx].lastprivmsg = now;
1517 } /* Init_Conn_Struct */
1521 Init_Socket( int Sock )
1523 /* Initialize socket (set options) */
1527 #ifdef O_NONBLOCK /* unknown on A/UX */
1528 if( fcntl( Sock, F_SETFL, O_NONBLOCK ) != 0 )
1530 Log( LOG_CRIT, "Can't enable non-blocking mode for socket: %s!", strerror( errno ));
1536 /* Don't block this port after socket shutdown */
1538 if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &value, (socklen_t)sizeof( value )) != 0 )
1540 Log( LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!", strerror( errno ));
1541 /* ignore this error */
1544 /* Set type of service (TOS) */
1545 #if defined(IP_TOS) && defined(IPTOS_LOWDELAY)
1546 value = IPTOS_LOWDELAY;
1548 Log( LOG_DEBUG, "Setting option IP_TOS on socket %d to IPTOS_LOWDELAY (%d).", Sock, value );
1550 if( setsockopt( Sock, SOL_IP, IP_TOS, &value, (socklen_t)sizeof( value )) != 0 )
1552 Log( LOG_ERR, "Can't set socket option IP_TOS: %s!", strerror( errno ));
1553 /* ignore this error */
1562 Read_Resolver_Result( int r_fd )
1564 /* Read result of resolver sub-process from pipe and update the
1565 * apropriate connection/client structure(s): hostname and/or
1566 * IDENT user name.*/
1573 /* Search associated connection ... */
1574 for( i = 0; i < Pool_Size; i++ )
1576 if(( My_Connections[i].sock != NONE )
1577 && ( My_Connections[i].res_stat != NULL )
1578 && ( My_Connections[i].res_stat->pipe[0] == r_fd ))
1581 if( i >= Pool_Size )
1583 /* Ops, none found? Probably the connection has already
1584 * been closed!? We'll ignore that ... */
1585 FD_CLR( r_fd, &Resolver_FDs );
1588 Log( LOG_DEBUG, "Resolver: Got result for unknown connection!?" );
1593 /* Get resolver structure */
1594 s = My_Connections[i].res_stat;
1595 assert( s != NULL );
1597 /* Read result from pipe */
1598 len = read( r_fd, s->buffer + s->bufpos, sizeof( s->buffer ) - s->bufpos - 1 );
1603 Log( LOG_CRIT, "Resolver: Can't read result: %s!", strerror( errno ));
1607 s->buffer[s->bufpos] = '\0';
1609 /* If the result string is incomplete, return to main loop and
1610 * wait until we can read in more bytes. */
1614 ptr = strchr( s->buffer, '\n' );
1619 Log( LOG_DEBUG, "Got result from resolver: \"%s\" (%d bytes), stage %d.", s->buffer, len, s->stage );
1622 /* Okay, we got a complete result: this is a host name for outgoing
1623 * connections and a host name or IDENT user name (if enabled) for
1624 * incoming conneciions.*/
1625 if( My_Connections[i].sock > NONE )
1627 /* Incoming connection */
1629 /* Search client ... */
1630 c = Client_GetFromConn( i );
1631 assert( c != NULL );
1633 /* Only update client information of unregistered clients */
1634 if( Client_Type( c ) == CLIENT_UNKNOWN )
1639 strlcpy( My_Connections[i].host, s->buffer, sizeof( My_Connections[i].host ));
1640 Client_SetHostname( c, s->buffer );
1643 /* clean up buffer for IDENT result */
1644 len = strlen( s->buffer ) + 1;
1645 memmove( s->buffer, s->buffer + len, sizeof( s->buffer ) - len );
1648 /* Don't close pipe and clean up, but
1649 * instead wait for IDENT result */
1653 else if( s->stage == 1 )
1655 /* IDENT user name */
1658 Log( LOG_INFO, "IDENT lookup for connection %ld: \"%s\".", i, s->buffer );
1659 Client_SetUser( c, s->buffer, true );
1661 else Log( LOG_INFO, "IDENT lookup for connection %ld: no result.", i );
1664 else Log( LOG_ERR, "Resolver: got result for unknown stage %d!?", s->stage );
1667 else Log( LOG_DEBUG, "Resolver: discarding result for already registered connection %d.", i );
1672 /* Outgoing connection (server link): set the IP address
1673 * so that we can connect to it in the main loop. */
1675 /* Search server ... */
1676 n = Conf_GetServer( i );
1679 strlcpy( Conf_Server[n].ip, s->buffer, sizeof( Conf_Server[n].ip ));
1683 FD_CLR( r_fd, &Resolver_FDs );
1684 close( My_Connections[i].res_stat->pipe[0] );
1685 close( My_Connections[i].res_stat->pipe[1] );
1686 free( My_Connections[i].res_stat );
1687 My_Connections[i].res_stat = NULL;
1689 /* Reset penalty time */
1690 Conn_ResetPenalty( i );
1691 } /* Read_Resolver_Result */
1695 Simple_Message( int Sock, char *Msg )
1697 /* Write "simple" message to socket, without using compression
1698 * or even the connection write buffers. Used e.g. for error
1699 * messages by New_Connection(). */
1701 assert( Sock > NONE );
1702 assert( Msg != NULL );
1704 (void)send( Sock, Msg, strlen( Msg ), 0 );
1705 (void)send( Sock, "\r\n", 2, 0 );
1706 } /* Simple_Error */
1710 Count_Connections( struct sockaddr_in addr_in )
1715 for( i = 0; i < Pool_Size; i++ )
1717 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].addr.sin_addr.s_addr == addr_in.sin_addr.s_addr )) cnt++;
1720 } /* Count_Connections */