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.151 2005/06/01 21:28:50 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;
109 FreeRes_stat( CONNECTION *c )
112 assert( c->res_stat != NULL );
114 if (!c->res_stat) return;
116 FD_CLR( c->res_stat->pipe[0], &Resolver_FDs );
118 close( c->res_stat->pipe[0] );
119 close( c->res_stat->pipe[1] );
129 /* Modul initialisieren: statische Strukturen "ausnullen". */
133 /* Speicher fuer Verbindungs-Pool anfordern */
134 Pool_Size = CONNECTION_POOL;
135 if( Conf_MaxConnections > 0 )
137 /* konfiguriertes Limit beachten */
138 if( Pool_Size > Conf_MaxConnections ) Pool_Size = Conf_MaxConnections;
140 My_Connections = (CONNECTION *) calloc( Pool_Size, sizeof( CONNECTION ) );
141 if( ! My_Connections )
143 /* Speicher konnte nicht alloziert werden! */
144 Log( LOG_EMERG, "Can't allocate memory! [Conn_Init]" );
148 Log( LOG_DEBUG, "Allocated connection pool for %d items (%ld bytes).", Pool_Size, sizeof( CONNECTION ) * Pool_Size );
151 /* zu Beginn haben wir keine Verbindungen */
152 FD_ZERO( &My_Listeners );
153 FD_ZERO( &My_Sockets );
155 /* Groesster File-Descriptor fuer select() */
158 /* Connection-Struktur initialisieren */
159 for( i = 0; i < Pool_Size; i++ ) Init_Conn_Struct( i );
161 /* Global write counter */
169 /* Modul abmelden: alle noch offenen Connections
170 * schliessen und freigeben. */
176 Log( LOG_DEBUG, "Shutting down all connections ..." );
180 Rendezvous_UnregisterListeners( );
183 /* Sockets schliessen */
184 for( i = 0; i < Conn_MaxFD + 1; i++ )
186 if( FD_ISSET( i, &My_Sockets ))
188 for( idx = 0; idx < Pool_Size; idx++ )
190 if( My_Connections[idx].sock == i ) break;
192 if( FD_ISSET( i, &My_Listeners ))
196 Log( LOG_DEBUG, "Listening socket %d closed.", i );
199 else if( idx < Pool_Size )
201 if( NGIRCd_SignalRestart ) Conn_Close( idx, NULL, "Server going down (restarting)", true );
202 else Conn_Close( idx, NULL, "Server going down", true );
206 Log( LOG_WARNING, "Closing unknown connection %d ...", i );
212 free( My_Connections );
213 My_Connections = NULL;
219 Conn_InitListeners( void )
221 /* Initialize ports on which the server should accept connections */
226 for( i = 0; i < Conf_ListenPorts_Count; i++ )
228 if( Conn_NewListener( Conf_ListenPorts[i] )) created++;
229 else Log( LOG_ERR, "Can't listen on port %u!", (unsigned int) Conf_ListenPorts[i] );
232 } /* Conn_InitListeners */
236 Conn_ExitListeners( void )
238 /* Close down all listening sockets */
243 Rendezvous_UnregisterListeners( );
246 Log( LOG_INFO, "Shutting down all listening sockets ..." );
247 for( i = 0; i < Conn_MaxFD + 1; i++ )
249 if( FD_ISSET( i, &My_Sockets ) && FD_ISSET( i, &My_Listeners ))
253 Log( LOG_DEBUG, "Listening socket %d closed.", i );
257 } /* Conn_ExitListeners */
261 Conn_NewListener( const UINT16 Port )
263 /* Create new listening socket on specified port */
265 struct sockaddr_in addr;
266 struct in_addr inaddr;
269 char name[CLIENT_ID_LEN], *info;
272 /* Server-"Listen"-Socket initialisieren */
273 memset( &addr, 0, sizeof( addr ));
274 memset( &inaddr, 0, sizeof( inaddr ));
275 addr.sin_family = AF_INET;
276 addr.sin_port = htons( Port );
277 if( Conf_ListenAddress[0] )
279 #ifdef HAVE_INET_ATON
280 if( inet_aton( Conf_ListenAddress, &inaddr ) == 0 )
282 inaddr.s_addr = inet_addr( Conf_ListenAddress );
283 if( inaddr.s_addr == (unsigned)-1 )
286 Log( LOG_CRIT, "Can't listen on %s:%u: can't convert ip address %s!", Conf_ListenAddress, Port, Conf_ListenAddress );
290 else inaddr.s_addr = htonl( INADDR_ANY );
291 addr.sin_addr = inaddr;
293 /* Socket erzeugen */
294 sock = socket( PF_INET, SOCK_STREAM, 0);
297 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
301 if( ! Init_Socket( sock )) return false;
304 if( bind( sock, (struct sockaddr *)&addr, (socklen_t)sizeof( addr )) != 0 )
306 Log( LOG_CRIT, "Can't bind socket: %s!", strerror( errno ));
311 /* in "listen mode" gehen :-) */
312 if( listen( sock, 10 ) != 0 )
314 Log( LOG_CRIT, "Can't listen on soecket: %s!", strerror( errno ));
319 /* Neuen Listener in Strukturen einfuegen */
320 FD_SET( sock, &My_Listeners );
321 FD_SET( sock, &My_Sockets );
323 if( sock > Conn_MaxFD ) Conn_MaxFD = sock;
325 if( Conf_ListenAddress[0]) Log( LOG_INFO, "Now listening on %s:%d (socket %d).", Conf_ListenAddress, Port, sock );
326 else Log( LOG_INFO, "Now listening on 0.0.0.0:%d (socket %d).", Port, sock );
329 /* Get best server description text */
330 if( ! Conf_ServerInfo[0] ) info = Conf_ServerName;
333 /* Use server info string */
335 if( Conf_ServerInfo[0] == '[' )
337 /* Cut off leading hostname part in "[]" */
338 info = strchr( Conf_ServerInfo, ']' );
342 while( *info == ' ' ) info++;
345 if( ! info ) info = Conf_ServerInfo;
348 /* Add port number to description if non-standard */
349 if( Port != 6667 ) snprintf( name, sizeof( name ), "%s (port %u)", info, Port );
350 else strlcpy( name, info, sizeof( name ));
352 /* Register service */
353 Rendezvous_Register( name, RENDEZVOUS_TYPE, Port );
357 } /* Conn_NewListener */
363 /* "Hauptschleife": Aktive Verbindungen ueberwachen. Folgende Aktionen
364 * werden dabei durchgefuehrt, bis der Server terminieren oder neu
367 * - neue Verbindungen annehmen,
368 * - Server-Verbindungen aufbauen,
369 * - geschlossene Verbindungen loeschen,
370 * - volle Schreibpuffer versuchen zu schreiben,
371 * - volle Lesepuffer versuchen zu verarbeiten,
372 * - Antworten von Resolver Sub-Prozessen annehmen.
375 fd_set read_sockets, write_sockets;
381 start = time( NULL );
382 while(( ! NGIRCd_SignalQuit ) && ( ! NGIRCd_SignalRestart ))
387 Rendezvous_Handler( );
390 /* Should the configuration be reloaded? */
391 if( NGIRCd_SignalRehash ) NGIRCd_Rehash( );
393 /* Check configured servers and established links */
395 Check_Connections( );
399 /* noch volle Lese-Buffer suchen */
400 for( i = 0; i < Pool_Size; i++ )
402 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].rdatalen > 0 ) &&
403 ( My_Connections[i].delaytime < t ))
405 /* Kann aus dem Buffer noch ein Befehl extrahiert werden? */
406 if( Handle_Buffer( i )) timeout = false;
410 /* noch volle Schreib-Puffer suchen */
411 FD_ZERO( &write_sockets );
412 for( i = 0; i < Pool_Size; i++ )
415 if(( My_Connections[i].sock > NONE ) && (( My_Connections[i].wdatalen > 0 ) || ( My_Connections[i].zip.wdatalen > 0 )))
417 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].wdatalen > 0 ))
420 /* Socket der Verbindung in Set aufnehmen */
421 FD_SET( My_Connections[i].sock, &write_sockets );
425 /* Sockets mit im Aufbau befindlichen ausgehenden Verbindungen suchen */
426 for( i = 0; i < Pool_Size; i++ )
428 if ( My_Connections[i].sock > NONE ) {
429 if ( Conn_OPTION_ISSET( &My_Connections[i], CONN_ISCONNECTING )) {
430 FD_SET( My_Connections[i].sock, &write_sockets );
436 /* von welchen Sockets koennte gelesen werden? */
437 read_sockets = My_Sockets;
438 for( i = 0; i < Pool_Size; i++ )
440 if ( My_Connections[i].sock > NONE ) {
441 if ( My_Connections[i].res_stat ) {
442 /* wait for completion of Resolver Sub-Process */
443 FD_CLR( My_Connections[i].sock, &read_sockets );
447 if ( Conn_OPTION_ISSET( &My_Connections[i], CONN_ISCONNECTING )) {
448 /* wait for completion of connect() */
449 FD_CLR( My_Connections[i].sock, &read_sockets );
453 if( My_Connections[i].delaytime > t )
455 /* Fuer die Verbindung ist eine "Penalty-Zeit" gesetzt */
456 FD_CLR( My_Connections[i].sock, &read_sockets );
459 for( i = 0; i < Conn_MaxFD + 1; i++ )
461 /* Pipes von Resolver Sub-Prozessen aufnehmen */
462 if( FD_ISSET( i, &Resolver_FDs ))
464 FD_SET( i, &read_sockets );
468 /* Timeout initialisieren */
470 if( timeout ) tv.tv_sec = 1;
473 /* Auf Aktivitaet warten */
474 i = select( Conn_MaxFD + 1, &read_sockets, &write_sockets, NULL, &tv );
477 /* keine Veraenderung an den Sockets */
482 /* Fehler (z.B. Interrupt) */
485 Log( LOG_EMERG, "Conn_Handler(): select(): %s!", strerror( errno ));
486 Log( LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE_NAME );
492 /* Koennen Daten geschrieben werden? */
493 for( i = 0; i < Conn_MaxFD + 1; i++ )
495 if( ! FD_ISSET( i, &write_sockets )) continue;
497 /* Es kann geschrieben werden ... */
498 idx = Socket2Index( i );
499 if( idx == NONE ) continue;
501 if( ! Handle_Write( idx ))
503 /* Fehler beim Schreiben! Diesen Socket nun
504 * auch aus dem Read-Set entfernen: */
505 FD_CLR( i, &read_sockets );
509 /* Daten zum Lesen vorhanden? */
510 for( i = 0; i < Conn_MaxFD + 1; i++ )
512 if( FD_ISSET( i, &read_sockets )) Handle_Read( i );
516 if( NGIRCd_SignalQuit ) Log( LOG_NOTICE|LOG_snotice, "Server going down NOW!" );
517 else if( NGIRCd_SignalRestart ) Log( LOG_NOTICE|LOG_snotice, "Server restarting NOW!" );
523 Conn_WriteStr( CONN_ID Idx, char *Format, ... )
526 Conn_WriteStr( Idx, Format, va_alist )
532 /* String in Socket schreiben. CR+LF wird von dieser Funktion
533 * automatisch angehaengt. Im Fehlerfall wird dir Verbindung
534 * getrennt und false geliefert. */
536 char buffer[COMMAND_LEN];
540 assert( Idx > NONE );
541 assert( Format != NULL );
544 va_start( ap, Format );
548 if( vsnprintf( buffer, COMMAND_LEN - 2, Format, ap ) >= COMMAND_LEN - 2 )
550 Log( LOG_CRIT, "Text too long to send (connection %d)!", Idx );
551 Conn_Close( Idx, "Text too long to send!", NULL, false );
556 if( NGIRCd_Sniffer ) Log( LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer );
559 strlcat( buffer, "\r\n", sizeof( buffer ));
560 ok = Conn_Write( Idx, buffer, strlen( buffer ));
561 My_Connections[Idx].msg_out++;
565 } /* Conn_WriteStr */
569 Conn_Write( CONN_ID Idx, char *Data, int Len )
571 /* Daten in Socket schreiben. Bei "fatalen" Fehlern wird
572 * der Client disconnectiert und false geliefert. */
574 assert( Idx > NONE );
575 assert( Data != NULL );
578 /* Ist der entsprechende Socket ueberhaupt noch offen? In einem
579 * "Handler-Durchlauf" kann es passieren, dass dem nicht mehr so
580 * ist, wenn einer von mehreren Conn_Write()'s fehlgeschlagen ist.
581 * In diesem Fall wird hier einfach ein Fehler geliefert. */
582 if( My_Connections[Idx].sock <= NONE )
585 Log( LOG_DEBUG, "Skipped write on closed socket (connection %d).", Idx );
590 /* Pruefen, ob im Schreibpuffer genuegend Platz ist. Ziel ist es,
591 * moeglichts viel im Puffer zu haben und _nicht_ gleich alles auf den
592 * Socket zu schreiben (u.a. wg. Komprimierung). */
593 if( WRITEBUFFER_LEN - My_Connections[Idx].wdatalen - Len <= 0 )
595 /* Der Puffer ist dummerweise voll. Jetzt versuchen, den Puffer
596 * zu schreiben, wenn das nicht klappt, haben wir ein Problem ... */
597 if( ! Try_Write( Idx )) return false;
599 /* nun neu pruefen: */
600 if( WRITEBUFFER_LEN - My_Connections[Idx].wdatalen - Len <= 0 )
602 Log( LOG_NOTICE, "Write buffer overflow (connection %d)!", Idx );
603 Conn_Close( Idx, "Write buffer overflow!", NULL, false );
609 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
610 /* Daten komprimieren und in Puffer kopieren */
611 if( ! Zip_Buffer( Idx, Data, Len )) return false;
616 /* Daten in Puffer kopieren */
617 memcpy( My_Connections[Idx].wbuf + My_Connections[Idx].wdatalen, Data, Len );
618 My_Connections[Idx].wdatalen += Len;
619 My_Connections[Idx].bytes_out += Len;
622 /* Adjust global write counter */
630 Conn_Close( CONN_ID Idx, char *LogMsg, char *FwdMsg, bool InformClient )
632 /* Close connection. Open pipes of asyncronous resolver
633 * sub-processes are closed down. */
639 double in_z_k, out_z_k;
643 assert( Idx > NONE );
645 /* Is this link already shutting down? */
646 if( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ISCLOSING )) {
647 /* Conn_Close() has been called recursively for this link;
648 * probabe reason: Try_Write() failed -- see below. */
650 Log( LOG_DEBUG, "Recursive request to close connection: %d", Idx );
655 assert( My_Connections[Idx].sock > NONE );
657 /* Mark link as "closing" */
658 Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCLOSING );
660 if( LogMsg ) txt = LogMsg;
662 if( ! txt ) txt = "Reason unknown";
664 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 ));
666 /* Search client, if any */
667 c = Client_GetFromConn( Idx );
669 /* Should the client be informed? */
673 /* Send statistics to client if registered as user: */
674 if(( c != NULL ) && ( Client_Type( c ) == CLIENT_USER ))
676 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 );
680 /* Send ERROR to client (see RFC!) */
681 if( FwdMsg ) Conn_WriteStr( Idx, "ERROR :%s", FwdMsg );
682 else Conn_WriteStr( Idx, "ERROR :Closing connection." );
685 /* Try to write out the write buffer */
686 (void)Try_Write( Idx );
688 /* Shut down socket */
689 if( close( My_Connections[Idx].sock ) != 0 )
691 /* Oops, we can't close the socket!? This is ... ugly! */
692 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 ));
695 /* Mark socket as invalid: */
696 FD_CLR( My_Connections[Idx].sock, &My_Sockets );
697 My_Connections[Idx].sock = NONE;
699 /* If there is still a client, unregister it now */
700 if( c ) Client_Destroy( c, LogMsg, FwdMsg, true );
702 /* Calculate statistics and log information */
703 in_k = (double)My_Connections[Idx].bytes_in / 1024;
704 out_k = (double)My_Connections[Idx].bytes_out / 1024;
706 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
707 in_z_k = (double)My_Connections[Idx].zip.bytes_in / 1024;
708 out_z_k = (double)My_Connections[Idx].zip.bytes_out / 1024;
709 in_p = (int)(( in_k * 100 ) / in_z_k );
710 out_p = (int)(( out_k * 100 ) / out_z_k );
711 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 );
716 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 );
719 /* Is there a resolver sub-process running? */
720 if( My_Connections[Idx].res_stat )
721 FreeRes_stat( &My_Connections[Idx] );
723 /* Servers: Modify time of next connect attempt? */
724 Conf_UnsetServer( Idx );
727 /* Clean up zlib, if link was compressed */
728 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
729 inflateEnd( &My_Connections[Idx].zip.in );
730 deflateEnd( &My_Connections[Idx].zip.out );
734 /* Clean up connection structure (=free it) */
735 Init_Conn_Struct( Idx );
738 Log( LOG_DEBUG, "Shutdown of connection %d completed.", Idx );
744 Conn_SyncServerStruct( void )
746 /* Synchronize server structures (connection IDs):
747 * connections <-> configuration */
753 for( i = 0; i < Pool_Size; i++ )
755 /* Established connection? */
756 if( My_Connections[i].sock <= NONE ) continue;
758 /* Server connection? */
759 client = Client_GetFromConn( i );
760 if(( ! client ) || ( Client_Type( client ) != CLIENT_SERVER )) continue;
762 for( c = 0; c < MAX_SERVERS; c++ )
764 /* Configured server? */
765 if( ! Conf_Server[c].host[0] ) continue;
768 if( strcmp( Conf_Server[c].name, Client_ID( client )) == 0 ) Conf_Server[c].conn_id = i;
771 } /* SyncServerStruct */
775 Try_Write( CONN_ID Idx )
777 /* Versuchen, Daten aus dem Schreib-Puffer in den Socket zu
778 * schreiben. true wird geliefert, wenn entweder keine Daten
779 * zum Versenden vorhanden sind oder erfolgreich bearbeitet
780 * werden konnten. Im Fehlerfall wird false geliefert und
781 * die Verbindung geschlossen. */
786 assert( Idx > NONE );
787 assert( My_Connections[Idx].sock > NONE );
789 /* sind ueberhaupt Daten vorhanden? */
791 if(( ! My_Connections[Idx].wdatalen > 0 ) && ( ! My_Connections[Idx].zip.wdatalen )) return true;
793 if( ! My_Connections[Idx].wdatalen > 0 ) return true;
796 /* Timeout initialisieren: 0 Sekunden, also nicht blockieren */
797 tv.tv_sec = 0; tv.tv_usec = 0;
799 FD_ZERO( &write_socket );
800 FD_SET( My_Connections[Idx].sock, &write_socket );
801 if( select( My_Connections[Idx].sock + 1, NULL, &write_socket, NULL, &tv ) == -1 )
806 Log( LOG_ALERT, "Try_Write(): select() failed: %s (con=%d, sock=%d)!", strerror( errno ), Idx, My_Connections[Idx].sock );
807 Conn_Close( Idx, "Server error!", NULL, false );
812 if( FD_ISSET( My_Connections[Idx].sock, &write_socket )) return Handle_Write( Idx );
818 Handle_Read( int Sock )
820 /* Aktivitaet auf einem Socket verarbeiten:
821 * - neue Clients annehmen,
822 * - Daten von Clients verarbeiten,
823 * - Resolver-Rueckmeldungen annehmen. */
827 assert( Sock > NONE );
829 if( FD_ISSET( Sock, &My_Listeners ))
831 /* es ist einer unserer Listener-Sockets: es soll
832 * also eine neue Verbindung aufgebaut werden. */
834 New_Connection( Sock );
836 else if( FD_ISSET( Sock, &Resolver_FDs ))
838 /* Rueckmeldung von einem Resolver Sub-Prozess */
840 Read_Resolver_Result( Sock );
844 /* Ein Client Socket: entweder ein User oder Server */
846 idx = Socket2Index( Sock );
847 if( idx > NONE ) Read_Request( idx );
853 Handle_Write( CONN_ID Idx )
855 /* Daten aus Schreibpuffer versenden bzw. Connection aufbauen */
861 assert( Idx > NONE );
862 assert( My_Connections[Idx].sock > NONE );
864 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ISCONNECTING )) {
865 /* connect() has finished, check result */
867 Conn_OPTION_DEL( &My_Connections[Idx], CONN_ISCONNECTING );
869 /* Ergebnis des connect() ermitteln */
870 sock_len = sizeof( err );
871 res = getsockopt( My_Connections[Idx].sock, SOL_SOCKET, SO_ERROR, &err, &sock_len );
872 assert( sock_len == sizeof( err ));
874 /* Fehler aufgetreten? */
875 if(( res != 0 ) || ( err != 0 ))
878 if( res != 0 ) Log( LOG_CRIT, "getsockopt (connection %d): %s!", Idx, strerror( errno ));
879 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 ));
881 /* Clean up socket, connection and client structures */
882 FD_CLR( My_Connections[Idx].sock, &My_Sockets );
883 c = Client_GetFromConn( Idx );
884 if( c ) Client_DestroyNow( c );
885 close( My_Connections[Idx].sock );
886 Init_Conn_Struct( Idx );
888 /* Bei Server-Verbindungen lasttry-Zeitpunkt auf "jetzt" setzen */
889 Conf_Server[Conf_GetServer( Idx )].lasttry = time( NULL );
890 Conf_UnsetServer( Idx );
894 Log( LOG_INFO, "Connection %d with \"%s:%d\" established. Now logging in ...", Idx, My_Connections[Idx].host, Conf_Server[Conf_GetServer( Idx )].port );
896 /* Send PASS and SERVER command to peer */
897 Conn_WriteStr( Idx, "PASS %s %s", Conf_Server[Conf_GetServer( Idx )].pwd_out, NGIRCd_ProtoID );
898 return Conn_WriteStr( Idx, "SERVER %s :%s", Conf_ServerName, Conf_ServerInfo );
902 /* Schreibpuffer leer, aber noch Daten im Kompressionsbuffer?
903 * Dann muss dieser nun geflushed werden! */
904 if( My_Connections[Idx].wdatalen == 0 ) Zip_Flush( Idx );
907 assert( My_Connections[Idx].wdatalen > 0 );
909 /* Daten schreiben */
910 len = write( My_Connections[Idx].sock, My_Connections[Idx].wbuf, My_Connections[Idx].wdatalen );
913 /* Operation haette Socket "nur" blockiert ... */
914 if( errno == EAGAIN ) return true;
916 /* Oops, ein Fehler! */
917 Log( LOG_ERR, "Write error on connection %d (socket %d): %s!", Idx, My_Connections[Idx].sock, strerror( errno ));
918 Conn_Close( Idx, "Write error!", NULL, false );
922 /* Puffer anpassen */
923 My_Connections[Idx].wdatalen -= len;
924 memmove( My_Connections[Idx].wbuf, My_Connections[Idx].wbuf + len, My_Connections[Idx].wdatalen );
931 New_Connection( int Sock )
933 /* Neue Client-Verbindung von Listen-Socket annehmen und
934 * CLIENT-Struktur anlegen. */
937 struct request_info req;
939 struct sockaddr_in new_addr;
940 int new_sock, new_sock_len;
947 assert( Sock > NONE );
949 /* Connection auf Listen-Socket annehmen */
950 new_sock_len = sizeof( new_addr );
951 new_sock = accept( Sock, (struct sockaddr *)&new_addr, (socklen_t *)&new_sock_len );
954 Log( LOG_CRIT, "Can't accept connection: %s!", strerror( errno ));
959 /* Validate socket using TCP Wrappers */
960 request_init( &req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock, RQ_CLIENT_SIN, &new_addr, NULL );
962 if( ! hosts_access( &req ))
965 Log( deny_severity, "Refused connection from %s (by TCP Wrappers)!", inet_ntoa( new_addr.sin_addr ));
966 Simple_Message( new_sock, "ERROR :Connection refused" );
972 /* Socket initialisieren */
973 Init_Socket( new_sock );
975 /* Check IP-based connection limit */
976 cnt = Count_Connections( new_addr );
977 if(( Conf_MaxConnectionsIP > 0 ) && ( cnt >= Conf_MaxConnectionsIP ))
979 /* Access denied, too many connections from this IP address! */
980 Log( LOG_ERR, "Refused connection from %s: too may connections (%ld) from this IP address!", inet_ntoa( new_addr.sin_addr ), cnt);
981 Simple_Message( new_sock, "ERROR :Connection refused, too many connections from your IP address!" );
986 /* Freie Connection-Struktur suchen */
987 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
988 if( idx >= Pool_Size )
990 new_size = Pool_Size + CONNECTION_POOL;
992 /* Im bisherigen Pool wurde keine freie Connection-Struktur mehr gefunden.
993 * Wenn erlaubt und moeglich muss nun der Pool vergroessert werden: */
995 if( Conf_MaxConnections > 0 )
997 /* Es ist ein Limit konfiguriert */
998 if( Pool_Size >= Conf_MaxConnections )
1000 /* Mehr Verbindungen duerfen wir leider nicht mehr annehmen ... */
1001 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached!", Pool_Size );
1002 Simple_Message( new_sock, "ERROR :Connection limit reached" );
1006 if( new_size > Conf_MaxConnections ) new_size = Conf_MaxConnections;
1008 if( new_size < Pool_Size )
1010 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached -- overflow!", Pool_Size );
1011 Simple_Message( new_sock, "ERROR :Connection limit reached" );
1016 ptr = (POINTER *)realloc( My_Connections, sizeof( CONNECTION ) * new_size );
1019 Log( LOG_EMERG, "Can't allocate memory! [New_Connection]" );
1020 Simple_Message( new_sock, "ERROR: Internal error" );
1026 Log( LOG_DEBUG, "Allocated new connection pool for %ld items (%ld bytes). [realloc()]", new_size, sizeof( CONNECTION ) * new_size );
1029 /* Adjust pointer to new block */
1030 My_Connections = (CONNECTION *)ptr;
1032 /* Initialize new items */
1033 for( idx = Pool_Size; idx < new_size; idx++ ) Init_Conn_Struct( idx );
1036 /* Adjust new pool size */
1037 Pool_Size = new_size;
1040 /* Client-Struktur initialisieren */
1041 c = Client_NewLocal( idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWN, false );
1044 Log( LOG_ALERT, "Can't accept connection: can't create client structure!" );
1045 Simple_Message( new_sock, "ERROR :Internal error" );
1050 /* Verbindung registrieren */
1051 Init_Conn_Struct( idx );
1052 My_Connections[idx].sock = new_sock;
1053 My_Connections[idx].addr = new_addr;
1055 /* Neuen Socket registrieren */
1056 FD_SET( new_sock, &My_Sockets );
1057 if( new_sock > Conn_MaxFD ) Conn_MaxFD = new_sock;
1059 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 );
1061 /* Hostnamen ermitteln */
1062 strlcpy( My_Connections[idx].host, inet_ntoa( new_addr.sin_addr ), sizeof( My_Connections[idx].host ));
1063 Client_SetHostname( c, My_Connections[idx].host );
1065 s = Resolve_Addr( &new_addr, My_Connections[idx].sock );
1067 s = Resolve_Addr( &new_addr );
1069 /* resolver process has been started */
1070 if( s ) My_Connections[idx].res_stat = s;
1072 /* Penalty-Zeit setzen */
1073 Conn_SetPenalty( idx, 4 );
1074 } /* New_Connection */
1078 Socket2Index( int Sock )
1080 /* zum Socket passende Connection suchen */
1084 assert( Sock > NONE );
1086 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == Sock ) break;
1088 if( idx >= Pool_Size )
1090 /* die Connection wurde vermutlich (wegen eines
1091 * Fehlers) bereits wieder abgebaut ... */
1093 Log( LOG_DEBUG, "Socket2Index: can't get connection for socket %d!", Sock );
1098 } /* Socket2Index */
1102 Read_Request( CONN_ID Idx )
1104 /* Daten von Socket einlesen und entsprechend behandeln.
1105 * Tritt ein Fehler auf, so wird der Socket geschlossen. */
1112 assert( Idx > NONE );
1113 assert( My_Connections[Idx].sock > NONE );
1115 /* wenn noch nicht registriert: maximal mit ZREADBUFFER_LEN arbeiten,
1116 * ansonsten koennen Daten ggf. nicht umkopiert werden. */
1117 bsize = READBUFFER_LEN;
1119 c = Client_GetFromConn( Idx );
1120 if(( Client_Type( c ) != CLIENT_USER ) && ( Client_Type( c ) != CLIENT_SERVER ) && ( Client_Type( c ) != CLIENT_SERVICE ) && ( bsize > ZREADBUFFER_LEN )) bsize = ZREADBUFFER_LEN;
1124 if(( bsize - My_Connections[Idx].rdatalen - 1 < 1 ) || ( ZREADBUFFER_LEN - My_Connections[Idx].zip.rdatalen < 1 ))
1126 if( bsize - My_Connections[Idx].rdatalen - 1 < 1 )
1129 /* Der Lesepuffer ist voll */
1130 Log( LOG_ERR, "Receive buffer overflow (connection %d): %d bytes!", Idx, My_Connections[Idx].rdatalen );
1131 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1136 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
1137 len = recv( My_Connections[Idx].sock, My_Connections[Idx].zip.rbuf + My_Connections[Idx].zip.rdatalen, ( ZREADBUFFER_LEN - My_Connections[Idx].zip.rdatalen ), 0 );
1138 if( len > 0 ) My_Connections[Idx].zip.rdatalen += len;
1143 len = recv( My_Connections[Idx].sock, My_Connections[Idx].rbuf + My_Connections[Idx].rdatalen, bsize - My_Connections[Idx].rdatalen - 1, 0 );
1144 if( len > 0 ) My_Connections[Idx].rdatalen += len;
1149 /* Socket wurde geschlossen */
1150 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 ));
1151 Conn_Close( Idx, "Socket closed!", "Client closed connection", false );
1157 /* Operation haette Socket "nur" blockiert ... */
1158 if( errno == EAGAIN ) return;
1160 /* Fehler beim Lesen */
1161 Log( LOG_ERR, "Read error on connection %d (socket %d): %s!", Idx, My_Connections[Idx].sock, strerror( errno ));
1162 Conn_Close( Idx, "Read error!", "Client closed connection", false );
1166 /* Connection-Statistik aktualisieren */
1167 My_Connections[Idx].bytes_in += len;
1169 /* Timestamp aktualisieren */
1170 My_Connections[Idx].lastdata = time( NULL );
1172 Handle_Buffer( Idx );
1173 } /* Read_Request */
1177 Handle_Buffer( CONN_ID Idx )
1179 /* Daten im Lese-Puffer einer Verbindung verarbeiten.
1180 * Wurde ein Request verarbeitet, so wird true geliefert,
1181 * ansonsten false (auch bei Fehlern). */
1188 bool action, result;
1197 if( My_Connections[Idx].delaytime > time( NULL )) return result;
1200 /* ggf. noch unkomprimiete Daten weiter entpacken */
1201 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP ))
1202 if( ! Unzip_Buffer( Idx )) return false;
1205 if( My_Connections[Idx].rdatalen < 1 ) break;
1207 /* Eine komplette Anfrage muss mit CR+LF enden, vgl.
1208 * RFC 2812. Haben wir eine? */
1209 My_Connections[Idx].rbuf[My_Connections[Idx].rdatalen] = '\0';
1210 ptr = strstr( My_Connections[Idx].rbuf, "\r\n" );
1212 if( ptr ) delta = 2;
1216 /* Nicht RFC-konforme Anfrage mit nur CR oder LF? Leider
1217 * machen soetwas viele Clients, u.a. "mIRC" :-( */
1218 ptr1 = strchr( My_Connections[Idx].rbuf, '\r' );
1219 ptr2 = strchr( My_Connections[Idx].rbuf, '\n' );
1221 if( ptr1 && ptr2 ) ptr = ptr1 > ptr2 ? ptr2 : ptr1;
1222 else if( ptr1 ) ptr = ptr1;
1223 else if( ptr2 ) ptr = ptr2;
1230 /* Ende der Anfrage wurde gefunden */
1232 len = ( ptr - My_Connections[Idx].rbuf ) + delta;
1233 if( len > ( COMMAND_LEN - 1 ))
1235 /* Eine Anfrage darf(!) nicht laenger als 512 Zeichen
1236 * (incl. CR+LF!) werden; vgl. RFC 2812. Wenn soetwas
1237 * empfangen wird, wird der Client disconnectiert. */
1238 Log( LOG_ERR, "Request too long (connection %d): %d bytes (max. %d expected)!", Idx, My_Connections[Idx].rdatalen, COMMAND_LEN - 1 );
1239 Conn_Close( Idx, NULL, "Request too long", true );
1244 /* merken, ob Stream bereits komprimiert wird */
1245 old_z = My_Connections[Idx].options & CONN_ZIP;
1250 /* Es wurde ein Request gelesen */
1251 My_Connections[Idx].msg_in++;
1252 if( ! Parse_Request( Idx, My_Connections[Idx].rbuf )) return false;
1256 /* Puffer anpassen */
1257 My_Connections[Idx].rdatalen -= len;
1258 memmove( My_Connections[Idx].rbuf, My_Connections[Idx].rbuf + len, My_Connections[Idx].rdatalen );
1261 if(( ! old_z ) && ( My_Connections[Idx].options & CONN_ZIP ) && ( My_Connections[Idx].rdatalen > 0 ))
1263 /* Mit dem letzten Befehl wurde Socket-Kompression aktiviert.
1264 * Evtl. schon vom Socket gelesene Daten in den Unzip-Puffer
1265 * umkopieren, damit diese nun zunaechst entkomprimiert werden */
1266 if( My_Connections[Idx].rdatalen > ZREADBUFFER_LEN )
1268 /* Hupsa! Soviel Platz haben wir aber gar nicht! */
1269 Log( LOG_ALERT, "Can't move receive buffer: No space left in unzip buffer (need %d bytes)!", My_Connections[Idx].rdatalen );
1272 memcpy( My_Connections[Idx].zip.rbuf, My_Connections[Idx].rbuf, My_Connections[Idx].rdatalen );
1273 My_Connections[Idx].zip.rdatalen = My_Connections[Idx].rdatalen;
1274 My_Connections[Idx].rdatalen = 0;
1276 Log( LOG_DEBUG, "Moved already received data (%d bytes) to uncompression buffer.", My_Connections[Idx].zip.rdatalen );
1282 if( action ) result = true;
1286 } /* Handle_Buffer */
1290 Check_Connections( void )
1292 /* Pruefen, ob Verbindungen noch "alive" sind. Ist dies
1293 * nicht der Fall, zunaechst PING-PONG spielen und, wenn
1294 * auch das nicht "hilft", Client disconnectieren. */
1299 for( i = 0; i < Pool_Size; i++ )
1301 if( My_Connections[i].sock == NONE ) continue;
1303 c = Client_GetFromConn( i );
1304 if( c && (( Client_Type( c ) == CLIENT_USER ) || ( Client_Type( c ) == CLIENT_SERVER ) || ( Client_Type( c ) == CLIENT_SERVICE )))
1306 /* verbundener User, Server oder Service */
1307 if( My_Connections[i].lastping > My_Connections[i].lastdata )
1309 /* es wurde bereits ein PING gesendet */
1310 if( My_Connections[i].lastping < time( NULL ) - Conf_PongTimeout )
1314 Log( LOG_DEBUG, "Connection %d: Ping timeout: %d seconds.", i, Conf_PongTimeout );
1316 Conn_Close( i, NULL, "Ping timeout", true );
1319 else if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout )
1321 /* es muss ein PING gesendet werden */
1323 Log( LOG_DEBUG, "Connection %d: sending PING ...", i );
1325 My_Connections[i].lastping = time( NULL );
1326 Conn_WriteStr( i, "PING :%s", Client_ID( Client_ThisServer( )));
1331 /* noch nicht vollstaendig aufgebaute Verbindung */
1332 if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout )
1336 Log( LOG_DEBUG, "Connection %d timed out ...", i );
1338 Conn_Close( i, NULL, "Timeout", false );
1342 } /* Check_Connections */
1346 Check_Servers( void )
1348 /* Check if we can establish further server links */
1354 /* Serach all connections, are there results from the resolver? */
1355 for( idx = 0; idx < Pool_Size; idx++ )
1357 if( My_Connections[idx].sock != SERVER_WAIT ) continue;
1360 if( My_Connections[idx].res_stat == NULL ) New_Server( Conf_GetServer( idx ), idx );
1363 /* Check all configured servers */
1364 for( i = 0; i < MAX_SERVERS; i++ )
1366 /* Valid outgoing server which isn't already connected or disabled? */
1367 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;
1369 /* Is there already a connection in this group? */
1370 if( Conf_Server[i].group > NONE )
1372 for( n = 0; n < MAX_SERVERS; n++ )
1374 if( n == i ) continue;
1375 if(( Conf_Server[n].conn_id > NONE ) && ( Conf_Server[n].group == Conf_Server[i].group )) break;
1377 if( n < MAX_SERVERS ) continue;
1380 /* Check last connect attempt? */
1381 if( Conf_Server[i].lasttry > time( NULL ) - Conf_ConnectRetry ) continue;
1383 /* Okay, try to connect now */
1384 Conf_Server[i].lasttry = time( NULL );
1386 /* Search free connection structure */
1387 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
1388 if( idx >= Pool_Size )
1390 Log( LOG_ALERT, "Can't establist server connection: connection limit reached (%d)!", Pool_Size );
1394 Log( LOG_DEBUG, "Preparing connection %d for \"%s\" ...", idx, Conf_Server[i].host );
1397 /* Verbindungs-Struktur initialisieren */
1398 Init_Conn_Struct( idx );
1399 My_Connections[idx].sock = SERVER_WAIT;
1400 Conf_Server[i].conn_id = idx;
1402 /* Resolve Hostname. If this fails, try to use it as an IP address */
1403 strlcpy( Conf_Server[i].ip, Conf_Server[i].host, sizeof( Conf_Server[i].ip ));
1404 strlcpy( My_Connections[idx].host, Conf_Server[i].host, sizeof( My_Connections[idx].host ));
1405 s = Resolve_Name( Conf_Server[i].host );
1407 /* resolver process running? */
1408 if( s ) My_Connections[idx].res_stat = s;
1410 } /* Check_Servers */
1414 New_Server( int Server, CONN_ID Idx )
1416 /* Establish new server link */
1418 struct sockaddr_in new_addr;
1419 struct in_addr inaddr;
1423 assert( Server > NONE );
1424 assert( Idx > NONE );
1426 /* Did we get a valid IP address? */
1427 if( ! Conf_Server[Server].ip[0] )
1429 /* No. Free connection structure and abort: */
1430 Init_Conn_Struct( Idx );
1431 Conf_Server[Server].conn_id = NONE;
1432 Log( LOG_ERR, "Can't connect to \"%s\" (connection %d): ip address unknown!", Conf_Server[Server].host, Idx );
1436 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 );
1438 #ifdef HAVE_INET_ATON
1439 if( inet_aton( Conf_Server[Server].ip, &inaddr ) == 0 )
1441 memset( &inaddr, 0, sizeof( inaddr ));
1442 inaddr.s_addr = inet_addr( Conf_Server[Server].ip );
1443 if( inaddr.s_addr == (unsigned)-1 )
1446 /* Can't convert IP address */
1447 Init_Conn_Struct( Idx );
1448 Conf_Server[Server].conn_id = NONE;
1449 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 );
1453 memset( &new_addr, 0, sizeof( new_addr ));
1454 new_addr.sin_family = AF_INET;
1455 new_addr.sin_addr = inaddr;
1456 new_addr.sin_port = htons( Conf_Server[Server].port );
1458 new_sock = socket( PF_INET, SOCK_STREAM, 0 );
1461 /* Can't create socket */
1462 Init_Conn_Struct( Idx );
1463 Conf_Server[Server].conn_id = NONE;
1464 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
1468 if( ! Init_Socket( new_sock )) return;
1470 res = connect( new_sock, (struct sockaddr *)&new_addr, sizeof( new_addr ));
1471 if(( res != 0 ) && ( errno != EINPROGRESS ))
1473 /* Can't connect socket */
1474 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1476 Init_Conn_Struct( Idx );
1477 Conf_Server[Server].conn_id = NONE;
1481 /* Client-Struktur initialisieren */
1482 c = Client_NewLocal( Idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWNSERVER, false );
1485 /* Can't create new client structure */
1487 Init_Conn_Struct( Idx );
1488 Conf_Server[Server].conn_id = NONE;
1489 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1492 Client_SetIntroducer( c, c );
1493 Client_SetToken( c, TOKEN_OUTBOUND );
1495 /* Register connection */
1496 My_Connections[Idx].sock = new_sock;
1497 My_Connections[Idx].addr = new_addr;
1498 strlcpy( My_Connections[Idx].host, Conf_Server[Server].host, sizeof( My_Connections[Idx].host ));
1500 /* Register new socket */
1501 FD_SET( new_sock, &My_Sockets );
1502 Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCONNECTING );
1504 if( new_sock > Conn_MaxFD ) Conn_MaxFD = new_sock;
1507 Log( LOG_DEBUG, "Registered new connection %d on socket %d.", Idx, My_Connections[Idx].sock );
1513 Init_Conn_Struct( CONN_ID Idx )
1515 time_t now = time( NULL );
1516 /* Connection-Struktur initialisieren */
1518 memset( &My_Connections[Idx], 0, sizeof ( CONNECTION ));
1519 My_Connections[Idx].sock = NONE;
1520 My_Connections[Idx].starttime = now;
1521 My_Connections[Idx].lastdata = now;
1522 My_Connections[Idx].lastprivmsg = now;
1523 } /* Init_Conn_Struct */
1527 Init_Socket( int Sock )
1529 /* Initialize socket (set options) */
1533 #ifdef O_NONBLOCK /* unknown on A/UX */
1534 if( fcntl( Sock, F_SETFL, O_NONBLOCK ) != 0 )
1536 Log( LOG_CRIT, "Can't enable non-blocking mode for socket: %s!", strerror( errno ));
1542 /* Don't block this port after socket shutdown */
1544 if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &value, (socklen_t)sizeof( value )) != 0 )
1546 Log( LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!", strerror( errno ));
1547 /* ignore this error */
1550 /* Set type of service (TOS) */
1551 #if defined(IP_TOS) && defined(IPTOS_LOWDELAY)
1552 value = IPTOS_LOWDELAY;
1554 Log( LOG_DEBUG, "Setting option IP_TOS on socket %d to IPTOS_LOWDELAY (%d).", Sock, value );
1556 if( setsockopt( Sock, SOL_IP, IP_TOS, &value, (socklen_t)sizeof( value )) != 0 )
1558 Log( LOG_ERR, "Can't set socket option IP_TOS: %s!", strerror( errno ));
1559 /* ignore this error */
1568 Read_Resolver_Result( int r_fd )
1570 /* Read result of resolver sub-process from pipe and update the
1571 * apropriate connection/client structure(s): hostname and/or
1572 * IDENT user name.*/
1579 /* Search associated connection ... */
1580 for( i = 0; i < Pool_Size; i++ )
1582 if(( My_Connections[i].sock != NONE )
1583 && ( My_Connections[i].res_stat != NULL )
1584 && ( My_Connections[i].res_stat->pipe[0] == r_fd ))
1587 if( i >= Pool_Size )
1589 /* Ops, none found? Probably the connection has already
1590 * been closed!? We'll ignore that ... */
1591 FD_CLR( r_fd, &Resolver_FDs );
1594 Log( LOG_DEBUG, "Resolver: Got result for unknown connection!?" );
1599 /* Get resolver structure */
1600 s = My_Connections[i].res_stat;
1601 assert( s != NULL );
1603 /* Read result from pipe */
1604 len = read( r_fd, s->buffer + s->bufpos, sizeof( s->buffer ) - s->bufpos - 1 );
1608 Log( LOG_CRIT, "Resolver: Can't read result: %s!", strerror( errno ));
1609 FreeRes_stat( &My_Connections[i] );
1613 s->buffer[s->bufpos] = '\0';
1615 /* If the result string is incomplete, return to main loop and
1616 * wait until we can read in more bytes. */
1620 ptr = strchr( s->buffer, '\n' );
1625 Log( LOG_DEBUG, "Got result from resolver: \"%s\" (%d bytes), stage %d.", s->buffer, len, s->stage );
1628 /* Okay, we got a complete result: this is a host name for outgoing
1629 * connections and a host name or IDENT user name (if enabled) for
1630 * incoming connections.*/
1631 if( My_Connections[i].sock > NONE )
1633 /* Incoming connection. Search client ... */
1634 c = Client_GetFromConn( i );
1635 assert( c != NULL );
1637 /* Only update client information of unregistered clients */
1638 if( Client_Type( c ) == CLIENT_UNKNOWN )
1641 case 0: /* host name */
1642 strlcpy( My_Connections[i].host, s->buffer, sizeof( My_Connections[i].host ));
1643 Client_SetHostname( c, s->buffer );
1645 /* clean up buffer for IDENT result */
1646 len = strlen( s->buffer ) + 1;
1647 assert(len <= sizeof( s->buffer ));
1648 memmove( s->buffer, s->buffer + len, sizeof( s->buffer ) - len );
1649 assert(len <= s->bufpos );
1652 /* Don't close pipe and clean up, but
1653 * instead wait for IDENT result */
1657 case 1: /* 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 );
1667 Log( LOG_ERR, "Resolver: got result for unknown stage %d!?", s->stage );
1671 else Log( LOG_DEBUG, "Resolver: discarding result for already registered connection %d.", i );
1676 /* Outgoing connection (server link): set the IP address
1677 * so that we can connect to it in the main loop. */
1679 /* Search server ... */
1680 n = Conf_GetServer( i );
1683 strlcpy( Conf_Server[n].ip, s->buffer, sizeof( Conf_Server[n].ip ));
1687 FreeRes_stat( &My_Connections[i] );
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)write( Sock, Msg, strlen( Msg ) );
1705 (void)write( Sock, "\r\n", 2 );
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 */