2 * ngIRCd -- The Next Generation IRC Daemon
3 * Copyright (c)2001-2005 Alexander Barton <alex@barton.de>
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 * Please read the file COPYING, README and AUTHORS for more information.
11 * Connection management
19 static char UNUSED id[] = "$Id: conn.c,v 1.156 2005/07/02 14:36:03 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 Handle_Buffer PARAMS(( CONN_ID Idx ));
90 LOCAL void Check_Connections PARAMS(( void ));
91 LOCAL void Check_Servers PARAMS(( void ));
92 LOCAL void Init_Conn_Struct PARAMS(( CONN_ID Idx ));
93 LOCAL bool Init_Socket PARAMS(( int Sock ));
94 LOCAL void New_Server PARAMS(( int Server, CONN_ID Idx ));
95 LOCAL void Read_Resolver_Result PARAMS(( int r_fd ));
96 LOCAL void Simple_Message PARAMS(( int Sock, char *Msg ));
97 LOCAL int Count_Connections PARAMS(( struct sockaddr_in addr ));
99 LOCAL fd_set My_Listeners;
100 LOCAL fd_set My_Sockets;
103 int allow_severity = LOG_INFO;
104 int deny_severity = LOG_ERR;
108 FreeRes_stat( CONNECTION *c )
111 assert( c->res_stat != NULL );
113 if (!c->res_stat) return;
115 FD_CLR( c->res_stat->pipe[0], &Resolver_FDs );
117 close( c->res_stat->pipe[0] );
118 close( c->res_stat->pipe[1] );
128 /* Modul initialisieren: statische Strukturen "ausnullen". */
132 /* Speicher fuer Verbindungs-Pool anfordern */
133 Pool_Size = CONNECTION_POOL;
134 if( Conf_MaxConnections > 0 )
136 /* konfiguriertes Limit beachten */
137 if( Pool_Size > Conf_MaxConnections ) Pool_Size = Conf_MaxConnections;
139 My_Connections = (CONNECTION *) calloc( Pool_Size, sizeof( CONNECTION ) );
140 if( ! My_Connections )
142 /* Speicher konnte nicht alloziert werden! */
143 Log( LOG_EMERG, "Can't allocate memory! [Conn_Init]" );
147 Log( LOG_DEBUG, "Allocated connection pool for %d items (%ld bytes).", Pool_Size, sizeof( CONNECTION ) * Pool_Size );
150 /* zu Beginn haben wir keine Verbindungen */
151 FD_ZERO( &My_Listeners );
152 FD_ZERO( &My_Sockets );
154 /* Groesster File-Descriptor fuer select() */
157 /* Connection-Struktur initialisieren */
158 for( i = 0; i < Pool_Size; i++ ) Init_Conn_Struct( i );
160 /* Global write counter */
168 /* Modul abmelden: alle noch offenen Connections
169 * schliessen und freigeben. */
175 Log( LOG_DEBUG, "Shutting down all connections ..." );
179 Rendezvous_UnregisterListeners( );
182 /* Sockets schliessen */
183 for( i = 0; i < Conn_MaxFD + 1; i++ )
185 if( FD_ISSET( i, &My_Sockets ))
187 for( idx = 0; idx < Pool_Size; idx++ )
189 if( My_Connections[idx].sock == i ) break;
191 if( FD_ISSET( i, &My_Listeners ))
195 Log( LOG_DEBUG, "Listening socket %d closed.", i );
198 else if( idx < Pool_Size )
200 if( NGIRCd_SignalRestart ) Conn_Close( idx, NULL, "Server going down (restarting)", true );
201 else Conn_Close( idx, NULL, "Server going down", true );
205 Log( LOG_WARNING, "Closing unknown connection %d ...", i );
211 free( My_Connections );
212 My_Connections = NULL;
218 Conn_InitListeners( void )
220 /* Initialize ports on which the server should accept connections */
225 for( i = 0; i < Conf_ListenPorts_Count; i++ )
227 if( Conn_NewListener( Conf_ListenPorts[i] )) created++;
228 else Log( LOG_ERR, "Can't listen on port %u!", (unsigned int) Conf_ListenPorts[i] );
231 } /* Conn_InitListeners */
235 Conn_ExitListeners( void )
237 /* Close down all listening sockets */
242 Rendezvous_UnregisterListeners( );
245 Log( LOG_INFO, "Shutting down all listening sockets ..." );
246 for( i = 0; i < Conn_MaxFD + 1; i++ )
248 if( FD_ISSET( i, &My_Sockets ) && FD_ISSET( i, &My_Listeners ))
252 Log( LOG_DEBUG, "Listening socket %d closed.", i );
256 } /* Conn_ExitListeners */
260 Conn_NewListener( const UINT16 Port )
262 /* Create new listening socket on specified port */
264 struct sockaddr_in addr;
265 struct in_addr inaddr;
268 char name[CLIENT_ID_LEN], *info;
271 /* Server-"Listen"-Socket initialisieren */
272 memset( &addr, 0, sizeof( addr ));
273 memset( &inaddr, 0, sizeof( inaddr ));
274 addr.sin_family = AF_INET;
275 addr.sin_port = htons( Port );
276 if( Conf_ListenAddress[0] )
278 #ifdef HAVE_INET_ATON
279 if( inet_aton( Conf_ListenAddress, &inaddr ) == 0 )
281 inaddr.s_addr = inet_addr( Conf_ListenAddress );
282 if( inaddr.s_addr == (unsigned)-1 )
285 Log( LOG_CRIT, "Can't listen on %s:%u: can't convert ip address %s!", Conf_ListenAddress, Port, Conf_ListenAddress );
289 else inaddr.s_addr = htonl( INADDR_ANY );
290 addr.sin_addr = inaddr;
292 /* Socket erzeugen */
293 sock = socket( PF_INET, SOCK_STREAM, 0);
296 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
300 if( ! Init_Socket( sock )) return false;
303 if( bind( sock, (struct sockaddr *)&addr, (socklen_t)sizeof( addr )) != 0 )
305 Log( LOG_CRIT, "Can't bind socket: %s!", strerror( errno ));
310 /* in "listen mode" gehen :-) */
311 if( listen( sock, 10 ) != 0 )
313 Log( LOG_CRIT, "Can't listen on soecket: %s!", strerror( errno ));
318 /* Neuen Listener in Strukturen einfuegen */
319 FD_SET( sock, &My_Listeners );
320 FD_SET( sock, &My_Sockets );
322 if( sock > Conn_MaxFD ) Conn_MaxFD = sock;
324 if( Conf_ListenAddress[0]) Log( LOG_INFO, "Now listening on %s:%d (socket %d).", Conf_ListenAddress, Port, sock );
325 else Log( LOG_INFO, "Now listening on 0.0.0.0:%d (socket %d).", Port, sock );
328 /* Get best server description text */
329 if( ! Conf_ServerInfo[0] ) info = Conf_ServerName;
332 /* Use server info string */
334 if( Conf_ServerInfo[0] == '[' )
336 /* Cut off leading hostname part in "[]" */
337 info = strchr( Conf_ServerInfo, ']' );
341 while( *info == ' ' ) info++;
344 if( ! info ) info = Conf_ServerInfo;
347 /* Add port number to description if non-standard */
348 if( Port != 6667 ) snprintf( name, sizeof( name ), "%s (port %u)", info, Port );
349 else strlcpy( name, info, sizeof( name ));
351 /* Register service */
352 Rendezvous_Register( name, RENDEZVOUS_TYPE, Port );
356 } /* Conn_NewListener */
362 /* "Hauptschleife": Aktive Verbindungen ueberwachen. Folgende Aktionen
363 * werden dabei durchgefuehrt, bis der Server terminieren oder neu
366 * - neue Verbindungen annehmen,
367 * - Server-Verbindungen aufbauen,
368 * - geschlossene Verbindungen loeschen,
369 * - volle Schreibpuffer versuchen zu schreiben,
370 * - volle Lesepuffer versuchen zu verarbeiten,
371 * - Antworten von Resolver Sub-Prozessen annehmen.
374 fd_set read_sockets, write_sockets;
380 start = time( NULL );
381 while(( ! NGIRCd_SignalQuit ) && ( ! NGIRCd_SignalRestart ))
386 Rendezvous_Handler( );
389 /* Should the configuration be reloaded? */
390 if( NGIRCd_SignalRehash ) NGIRCd_Rehash( );
392 /* Check configured servers and established links */
394 Check_Connections( );
398 /* noch volle Lese-Buffer suchen */
399 for( i = 0; i < Pool_Size; i++ )
401 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].rdatalen > 0 ) &&
402 ( My_Connections[i].delaytime < t ))
404 /* Kann aus dem Buffer noch ein Befehl extrahiert werden? */
405 if( Handle_Buffer( i )) timeout = false;
409 /* noch volle Schreib-Puffer suchen */
410 FD_ZERO( &write_sockets );
411 for( i = 0; i < Pool_Size; i++ )
414 if(( My_Connections[i].sock > NONE ) && (( My_Connections[i].wdatalen > 0 ) || ( My_Connections[i].zip.wdatalen > 0 )))
416 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].wdatalen > 0 ))
419 /* Socket der Verbindung in Set aufnehmen */
420 FD_SET( My_Connections[i].sock, &write_sockets );
424 /* Sockets mit im Aufbau befindlichen ausgehenden Verbindungen suchen */
425 for( i = 0; i < Pool_Size; i++ )
427 if ( My_Connections[i].sock > NONE ) {
428 if ( Conn_OPTION_ISSET( &My_Connections[i], CONN_ISCONNECTING )) {
429 FD_SET( My_Connections[i].sock, &write_sockets );
435 /* von welchen Sockets koennte gelesen werden? */
436 read_sockets = My_Sockets;
437 for( i = 0; i < Pool_Size; i++ )
439 if ( My_Connections[i].sock > NONE ) {
440 if ( My_Connections[i].res_stat ) {
441 /* wait for completion of Resolver Sub-Process */
442 FD_CLR( My_Connections[i].sock, &read_sockets );
446 if ( Conn_OPTION_ISSET( &My_Connections[i], CONN_ISCONNECTING )) {
447 /* wait for completion of connect() */
448 FD_CLR( My_Connections[i].sock, &read_sockets );
452 if( My_Connections[i].delaytime > t )
454 /* Fuer die Verbindung ist eine "Penalty-Zeit" gesetzt */
455 FD_CLR( My_Connections[i].sock, &read_sockets );
458 for( i = 0; i < Conn_MaxFD + 1; i++ )
460 /* Pipes von Resolver Sub-Prozessen aufnehmen */
461 if( FD_ISSET( i, &Resolver_FDs ))
463 FD_SET( i, &read_sockets );
467 /* Timeout initialisieren */
469 if( timeout ) tv.tv_sec = 1;
472 /* Auf Aktivitaet warten */
473 i = select( Conn_MaxFD + 1, &read_sockets, &write_sockets, NULL, &tv );
476 /* keine Veraenderung an den Sockets */
481 /* Fehler (z.B. Interrupt) */
484 Log( LOG_EMERG, "Conn_Handler(): select(): %s!", strerror( errno ));
485 Log( LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE_NAME );
491 /* Koennen Daten geschrieben werden? */
492 for( i = 0; i < Conn_MaxFD + 1; i++ )
494 if( ! FD_ISSET( i, &write_sockets )) continue;
496 /* Es kann geschrieben werden ... */
497 idx = Socket2Index( i );
498 if( idx == NONE ) continue;
500 if( ! Handle_Write( idx ))
502 /* Fehler beim Schreiben! Diesen Socket nun
503 * auch aus dem Read-Set entfernen: */
504 FD_CLR( i, &read_sockets );
508 /* Daten zum Lesen vorhanden? */
509 for( i = 0; i < Conn_MaxFD + 1; i++ )
511 if( FD_ISSET( i, &read_sockets )) Handle_Read( i );
515 if( NGIRCd_SignalQuit ) Log( LOG_NOTICE|LOG_snotice, "Server going down NOW!" );
516 else if( NGIRCd_SignalRestart ) Log( LOG_NOTICE|LOG_snotice, "Server restarting NOW!" );
521 * Write a text string into the socket of a connection.
522 * This function automatically appends CR+LF to the string and validates that
523 * the result is a valid IRC message (oversized messages are shortened, for
524 * example). Then it calls the Conn_Write() function to do the actual sending.
525 * @param Idx Index fo the connection.
526 * @param Format Format string, see printf().
527 * @return true on success, false otherwise.
531 Conn_WriteStr( CONN_ID Idx, char *Format, ... )
534 Conn_WriteStr( Idx, Format, va_alist )
540 char buffer[COMMAND_LEN];
544 assert( Idx > NONE );
545 assert( Format != NULL );
548 va_start( ap, Format );
553 if (vsnprintf(buffer, COMMAND_LEN - 2, Format, ap) >= COMMAND_LEN - 2) {
555 * The string that should be written to the socket is longer
556 * than the allowed size of COMMAND_LEN bytes (including both
557 * the CR and LF characters). This can be caused by the
558 * IRC_WriteXXX() functions when the prefix of this server had
559 * to be added to an already "quite long" command line which
560 * has been received from a regular IRC client, for example.
562 * We are not allowed to send such "oversized" messages to
563 * other servers and clients, see RFC 2812 2.3 and 2813 3.3
564 * ("these messages SHALL NOT exceed 512 characters in length,
565 * counting all characters including the trailing CR-LF").
567 * So we have a big problem here: we should send more bytes
568 * to the network than we are allowed to and we don't know
569 * the originator (any more). The "old" behaviour of blaming
570 * the receiver ("next hop") is a bad idea (it could be just
571 * an other server only routing the message!), so the only
572 * option left is to shorten the string and to hope that the
573 * result is still somewhat useful ...
577 strcpy (buffer + sizeof(buffer) - strlen(CUT_TXTSUFFIX) - 2 - 1,
583 Log(LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer);
586 strlcat( buffer, "\r\n", sizeof( buffer ));
587 ok = Conn_Write( Idx, buffer, strlen( buffer ));
588 My_Connections[Idx].msg_out++;
592 } /* Conn_WriteStr */
596 Conn_Write( CONN_ID Idx, char *Data, int Len )
598 /* Daten in Socket schreiben. Bei "fatalen" Fehlern wird
599 * der Client disconnectiert und false geliefert. */
601 assert( Idx > NONE );
602 assert( Data != NULL );
605 /* Ist der entsprechende Socket ueberhaupt noch offen? In einem
606 * "Handler-Durchlauf" kann es passieren, dass dem nicht mehr so
607 * ist, wenn einer von mehreren Conn_Write()'s fehlgeschlagen ist.
608 * In diesem Fall wird hier einfach ein Fehler geliefert. */
609 if( My_Connections[Idx].sock <= NONE )
612 Log( LOG_DEBUG, "Skipped write on closed socket (connection %d).", Idx );
617 /* Pruefen, ob im Schreibpuffer genuegend Platz ist. Ziel ist es,
618 * moeglichts viel im Puffer zu haben und _nicht_ gleich alles auf den
619 * Socket zu schreiben (u.a. wg. Komprimierung). */
620 if( WRITEBUFFER_LEN - My_Connections[Idx].wdatalen - Len <= 0 )
622 /* Der Puffer ist dummerweise voll. Jetzt versuchen, den Puffer
623 * zu schreiben, wenn das nicht klappt, haben wir ein Problem ... */
624 if( ! Handle_Write( Idx )) return false;
626 /* nun neu pruefen: */
627 if( WRITEBUFFER_LEN - My_Connections[Idx].wdatalen - Len <= 0 )
629 Log( LOG_NOTICE, "Write buffer overflow (connection %d)!", Idx );
630 Conn_Close( Idx, "Write buffer overflow!", NULL, false );
636 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
637 /* Daten komprimieren und in Puffer kopieren */
638 if( ! Zip_Buffer( Idx, Data, Len )) return false;
643 /* Daten in Puffer kopieren */
644 memcpy( My_Connections[Idx].wbuf + My_Connections[Idx].wdatalen, Data, Len );
645 My_Connections[Idx].wdatalen += Len;
646 My_Connections[Idx].bytes_out += Len;
649 /* Adjust global write counter */
657 Conn_Close( CONN_ID Idx, char *LogMsg, char *FwdMsg, bool InformClient )
659 /* Close connection. Open pipes of asyncronous resolver
660 * sub-processes are closed down. */
666 double in_z_k, out_z_k;
670 assert( Idx > NONE );
672 /* Is this link already shutting down? */
673 if( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ISCLOSING )) {
674 /* Conn_Close() has been called recursively for this link;
675 * probabe reason: Handle_Write() failed -- see below. */
677 Log( LOG_DEBUG, "Recursive request to close connection: %d", Idx );
682 assert( My_Connections[Idx].sock > NONE );
684 /* Mark link as "closing" */
685 Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCLOSING );
687 if( LogMsg ) txt = LogMsg;
689 if( ! txt ) txt = "Reason unknown";
691 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 ));
693 /* Search client, if any */
694 c = Client_GetFromConn( Idx );
696 /* Should the client be informed? */
700 /* Send statistics to client if registered as user: */
701 if(( c != NULL ) && ( Client_Type( c ) == CLIENT_USER ))
703 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 );
707 /* Send ERROR to client (see RFC!) */
708 if( FwdMsg ) Conn_WriteStr( Idx, "ERROR :%s", FwdMsg );
709 else Conn_WriteStr( Idx, "ERROR :Closing connection." );
712 /* Try to write out the write buffer */
713 (void)Handle_Write( Idx );
715 /* Shut down socket */
716 if( close( My_Connections[Idx].sock ) != 0 )
718 /* Oops, we can't close the socket!? This is ... ugly! */
719 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 ));
722 /* Mark socket as invalid: */
723 FD_CLR( My_Connections[Idx].sock, &My_Sockets );
724 My_Connections[Idx].sock = NONE;
726 /* If there is still a client, unregister it now */
727 if( c ) Client_Destroy( c, LogMsg, FwdMsg, true );
729 /* Calculate statistics and log information */
730 in_k = (double)My_Connections[Idx].bytes_in / 1024;
731 out_k = (double)My_Connections[Idx].bytes_out / 1024;
733 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
734 in_z_k = (double)My_Connections[Idx].zip.bytes_in / 1024;
735 out_z_k = (double)My_Connections[Idx].zip.bytes_out / 1024;
736 in_p = (int)(( in_k * 100 ) / in_z_k );
737 out_p = (int)(( out_k * 100 ) / out_z_k );
738 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 );
743 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 );
746 /* Is there a resolver sub-process running? */
747 if( My_Connections[Idx].res_stat )
748 FreeRes_stat( &My_Connections[Idx] );
750 /* Servers: Modify time of next connect attempt? */
751 Conf_UnsetServer( Idx );
754 /* Clean up zlib, if link was compressed */
755 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
756 inflateEnd( &My_Connections[Idx].zip.in );
757 deflateEnd( &My_Connections[Idx].zip.out );
761 /* Clean up connection structure (=free it) */
762 Init_Conn_Struct( Idx );
765 Log( LOG_DEBUG, "Shutdown of connection %d completed.", Idx );
771 Conn_SyncServerStruct( void )
773 /* Synchronize server structures (connection IDs):
774 * connections <-> configuration */
780 for( i = 0; i < Pool_Size; i++ )
782 /* Established connection? */
783 if( My_Connections[i].sock <= NONE ) continue;
785 /* Server connection? */
786 client = Client_GetFromConn( i );
787 if(( ! client ) || ( Client_Type( client ) != CLIENT_SERVER )) continue;
789 for( c = 0; c < MAX_SERVERS; c++ )
791 /* Configured server? */
792 if( ! Conf_Server[c].host[0] ) continue;
795 if( strcmp( Conf_Server[c].name, Client_ID( client )) == 0 ) Conf_Server[c].conn_id = i;
798 } /* SyncServerStruct */
802 Handle_Read( int Sock )
804 /* Aktivitaet auf einem Socket verarbeiten:
805 * - neue Clients annehmen,
806 * - Daten von Clients verarbeiten,
807 * - Resolver-Rueckmeldungen annehmen. */
811 assert( Sock > NONE );
813 if( FD_ISSET( Sock, &My_Listeners ))
815 /* es ist einer unserer Listener-Sockets: es soll
816 * also eine neue Verbindung aufgebaut werden. */
818 New_Connection( Sock );
820 else if( FD_ISSET( Sock, &Resolver_FDs ))
822 /* Rueckmeldung von einem Resolver Sub-Prozess */
824 Read_Resolver_Result( Sock );
828 /* Ein Client Socket: entweder ein User oder Server */
830 idx = Socket2Index( Sock );
831 if( idx > NONE ) Read_Request( idx );
837 Handle_Write( CONN_ID Idx )
839 /* Daten aus Schreibpuffer versenden bzw. Connection aufbauen */
845 assert( Idx > NONE );
846 assert( My_Connections[Idx].sock > NONE );
848 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ISCONNECTING )) {
849 /* connect() has finished, check result */
851 Conn_OPTION_DEL( &My_Connections[Idx], CONN_ISCONNECTING );
853 /* Ergebnis des connect() ermitteln */
854 sock_len = sizeof( err );
855 res = getsockopt( My_Connections[Idx].sock, SOL_SOCKET, SO_ERROR, &err, &sock_len );
856 assert( sock_len == sizeof( err ));
858 /* Fehler aufgetreten? */
859 if(( res != 0 ) || ( err != 0 ))
862 if( res != 0 ) Log( LOG_CRIT, "getsockopt (connection %d): %s!", Idx, strerror( errno ));
863 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 ));
865 /* Clean up socket, connection and client structures */
866 FD_CLR( My_Connections[Idx].sock, &My_Sockets );
867 c = Client_GetFromConn( Idx );
868 if( c ) Client_DestroyNow( c );
869 close( My_Connections[Idx].sock );
870 Init_Conn_Struct( Idx );
872 /* Bei Server-Verbindungen lasttry-Zeitpunkt auf "jetzt" setzen */
873 Conf_Server[Conf_GetServer( Idx )].lasttry = time( NULL );
874 Conf_UnsetServer( Idx );
878 Log( LOG_INFO, "Connection %d with \"%s:%d\" established. Now logging in ...", Idx, My_Connections[Idx].host, Conf_Server[Conf_GetServer( Idx )].port );
880 /* Send PASS and SERVER command to peer */
881 Conn_WriteStr( Idx, "PASS %s %s", Conf_Server[Conf_GetServer( Idx )].pwd_out, NGIRCd_ProtoID );
882 return Conn_WriteStr( Idx, "SERVER %s :%s", Conf_ServerName, Conf_ServerInfo );
886 if(( My_Connections[Idx].wdatalen <= 0 ) && ( ! My_Connections[Idx].zip.wdatalen ))
889 /* write buffer empty, but not compression buf? -> flush compression buf. */
890 if( My_Connections[Idx].wdatalen == 0 ) Zip_Flush( Idx );
892 if( My_Connections[Idx].wdatalen <= 0 )
896 len = write( My_Connections[Idx].sock, My_Connections[Idx].wbuf, My_Connections[Idx].wdatalen );
898 if( errno == EAGAIN || errno == EINTR)
901 Log( LOG_ERR, "Write error on connection %d (socket %d): %s!", Idx,
902 My_Connections[Idx].sock, strerror( errno ));
903 Conn_Close( Idx, "Write error!", NULL, false );
907 /* Update buffer len and move any data not yet written to beginning of buf */
908 My_Connections[Idx].wdatalen -= len;
909 memmove( My_Connections[Idx].wbuf, My_Connections[Idx].wbuf + len, My_Connections[Idx].wdatalen );
916 New_Connection( int Sock )
918 /* Neue Client-Verbindung von Listen-Socket annehmen und
919 * CLIENT-Struktur anlegen. */
922 struct request_info req;
924 struct sockaddr_in new_addr;
925 int new_sock, new_sock_len;
932 assert( Sock > NONE );
934 /* Connection auf Listen-Socket annehmen */
935 new_sock_len = sizeof( new_addr );
936 new_sock = accept( Sock, (struct sockaddr *)&new_addr, (socklen_t *)&new_sock_len );
939 Log( LOG_CRIT, "Can't accept connection: %s!", strerror( errno ));
944 /* Validate socket using TCP Wrappers */
945 request_init( &req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock, RQ_CLIENT_SIN, &new_addr, NULL );
947 if( ! hosts_access( &req ))
950 Log( deny_severity, "Refused connection from %s (by TCP Wrappers)!", inet_ntoa( new_addr.sin_addr ));
951 Simple_Message( new_sock, "ERROR :Connection refused" );
957 /* Socket initialisieren */
958 Init_Socket( new_sock );
960 /* Check IP-based connection limit */
961 cnt = Count_Connections( new_addr );
962 if(( Conf_MaxConnectionsIP > 0 ) && ( cnt >= Conf_MaxConnectionsIP ))
964 /* Access denied, too many connections from this IP address! */
965 Log( LOG_ERR, "Refused connection from %s: too may connections (%ld) from this IP address!", inet_ntoa( new_addr.sin_addr ), cnt);
966 Simple_Message( new_sock, "ERROR :Connection refused, too many connections from your IP address!" );
971 /* Freie Connection-Struktur suchen */
972 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
973 if( idx >= Pool_Size )
975 new_size = Pool_Size + CONNECTION_POOL;
977 /* Im bisherigen Pool wurde keine freie Connection-Struktur mehr gefunden.
978 * Wenn erlaubt und moeglich muss nun der Pool vergroessert werden: */
980 if( Conf_MaxConnections > 0 )
982 /* Es ist ein Limit konfiguriert */
983 if( Pool_Size >= Conf_MaxConnections )
985 /* Mehr Verbindungen duerfen wir leider nicht mehr annehmen ... */
986 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached!", Pool_Size );
987 Simple_Message( new_sock, "ERROR :Connection limit reached" );
991 if( new_size > Conf_MaxConnections ) new_size = Conf_MaxConnections;
993 if( new_size < Pool_Size )
995 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached -- overflow!", Pool_Size );
996 Simple_Message( new_sock, "ERROR :Connection limit reached" );
1001 ptr = (POINTER *)realloc( My_Connections, sizeof( CONNECTION ) * new_size );
1004 Log( LOG_EMERG, "Can't allocate memory! [New_Connection]" );
1005 Simple_Message( new_sock, "ERROR: Internal error" );
1011 Log( LOG_DEBUG, "Allocated new connection pool for %ld items (%ld bytes). [realloc()]", new_size, sizeof( CONNECTION ) * new_size );
1014 /* Adjust pointer to new block */
1015 My_Connections = (CONNECTION *)ptr;
1017 /* Initialize new items */
1018 for( idx = Pool_Size; idx < new_size; idx++ ) Init_Conn_Struct( idx );
1021 /* Adjust new pool size */
1022 Pool_Size = new_size;
1025 /* Client-Struktur initialisieren */
1026 c = Client_NewLocal( idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWN, false );
1029 Log( LOG_ALERT, "Can't accept connection: can't create client structure!" );
1030 Simple_Message( new_sock, "ERROR :Internal error" );
1035 /* Verbindung registrieren */
1036 Init_Conn_Struct( idx );
1037 My_Connections[idx].sock = new_sock;
1038 My_Connections[idx].addr = new_addr;
1040 /* Neuen Socket registrieren */
1041 FD_SET( new_sock, &My_Sockets );
1042 if( new_sock > Conn_MaxFD ) Conn_MaxFD = new_sock;
1044 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 );
1046 /* Hostnamen ermitteln */
1047 strlcpy( My_Connections[idx].host, inet_ntoa( new_addr.sin_addr ), sizeof( My_Connections[idx].host ));
1048 Client_SetHostname( c, My_Connections[idx].host );
1050 s = Resolve_Addr( &new_addr, My_Connections[idx].sock );
1052 s = Resolve_Addr( &new_addr );
1054 /* resolver process has been started */
1055 if( s ) My_Connections[idx].res_stat = s;
1057 /* Penalty-Zeit setzen */
1058 Conn_SetPenalty( idx, 4 );
1059 } /* New_Connection */
1063 Socket2Index( int Sock )
1065 /* zum Socket passende Connection suchen */
1069 assert( Sock > NONE );
1071 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == Sock ) break;
1073 if( idx >= Pool_Size )
1075 /* die Connection wurde vermutlich (wegen eines
1076 * Fehlers) bereits wieder abgebaut ... */
1078 Log( LOG_DEBUG, "Socket2Index: can't get connection for socket %d!", Sock );
1083 } /* Socket2Index */
1087 Read_Request( CONN_ID Idx )
1089 /* Daten von Socket einlesen und entsprechend behandeln.
1090 * Tritt ein Fehler auf, so wird der Socket geschlossen. */
1097 assert( Idx > NONE );
1098 assert( My_Connections[Idx].sock > NONE );
1100 /* wenn noch nicht registriert: maximal mit ZREADBUFFER_LEN arbeiten,
1101 * ansonsten koennen Daten ggf. nicht umkopiert werden. */
1102 bsize = READBUFFER_LEN;
1104 c = Client_GetFromConn( Idx );
1105 if(( Client_Type( c ) != CLIENT_USER ) && ( Client_Type( c ) != CLIENT_SERVER ) && ( Client_Type( c ) != CLIENT_SERVICE ) && ( bsize > ZREADBUFFER_LEN )) bsize = ZREADBUFFER_LEN;
1109 if(( bsize - My_Connections[Idx].rdatalen - 1 < 1 ) || ( ZREADBUFFER_LEN - My_Connections[Idx].zip.rdatalen < 1 ))
1111 if( bsize - My_Connections[Idx].rdatalen - 1 < 1 )
1114 /* Der Lesepuffer ist voll */
1115 Log( LOG_ERR, "Receive buffer overflow (connection %d): %d bytes!", Idx, My_Connections[Idx].rdatalen );
1116 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1121 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
1122 len = recv( My_Connections[Idx].sock, My_Connections[Idx].zip.rbuf + My_Connections[Idx].zip.rdatalen, ( ZREADBUFFER_LEN - My_Connections[Idx].zip.rdatalen ), 0 );
1123 if( len > 0 ) My_Connections[Idx].zip.rdatalen += len;
1128 len = recv( My_Connections[Idx].sock, My_Connections[Idx].rbuf + My_Connections[Idx].rdatalen, bsize - My_Connections[Idx].rdatalen - 1, 0 );
1129 if( len > 0 ) My_Connections[Idx].rdatalen += len;
1134 /* Socket wurde geschlossen */
1135 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 ));
1136 Conn_Close( Idx, "Socket closed!", "Client closed connection", false );
1142 /* Operation haette Socket "nur" blockiert ... */
1143 if( errno == EAGAIN ) return;
1145 /* Fehler beim Lesen */
1146 Log( LOG_ERR, "Read error on connection %d (socket %d): %s!", Idx, My_Connections[Idx].sock, strerror( errno ));
1147 Conn_Close( Idx, "Read error!", "Client closed connection", false );
1151 /* Connection-Statistik aktualisieren */
1152 My_Connections[Idx].bytes_in += len;
1154 /* Timestamp aktualisieren */
1155 My_Connections[Idx].lastdata = time( NULL );
1157 Handle_Buffer( Idx );
1158 } /* Read_Request */
1162 Handle_Buffer( CONN_ID Idx )
1164 /* Daten im Lese-Puffer einer Verbindung verarbeiten.
1165 * Wurde ein Request verarbeitet, so wird true geliefert,
1166 * ansonsten false (auch bei Fehlern). */
1173 bool action, result;
1182 if( My_Connections[Idx].delaytime > time( NULL )) return result;
1185 /* ggf. noch unkomprimiete Daten weiter entpacken */
1186 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP ))
1187 if( ! Unzip_Buffer( Idx )) return false;
1190 if( My_Connections[Idx].rdatalen < 1 ) break;
1192 /* Eine komplette Anfrage muss mit CR+LF enden, vgl.
1193 * RFC 2812. Haben wir eine? */
1194 My_Connections[Idx].rbuf[My_Connections[Idx].rdatalen] = '\0';
1195 ptr = strstr( My_Connections[Idx].rbuf, "\r\n" );
1197 if( ptr ) delta = 2;
1201 /* Nicht RFC-konforme Anfrage mit nur CR oder LF? Leider
1202 * machen soetwas viele Clients, u.a. "mIRC" :-( */
1203 ptr1 = strchr( My_Connections[Idx].rbuf, '\r' );
1204 ptr2 = strchr( My_Connections[Idx].rbuf, '\n' );
1206 if( ptr1 && ptr2 ) ptr = ptr1 > ptr2 ? ptr2 : ptr1;
1207 else if( ptr1 ) ptr = ptr1;
1208 else if( ptr2 ) ptr = ptr2;
1215 /* Ende der Anfrage wurde gefunden */
1217 len = ( ptr - My_Connections[Idx].rbuf ) + delta;
1218 if( len > ( COMMAND_LEN - 1 ))
1220 /* Eine Anfrage darf(!) nicht laenger als 512 Zeichen
1221 * (incl. CR+LF!) werden; vgl. RFC 2812. Wenn soetwas
1222 * empfangen wird, wird der Client disconnectiert. */
1223 Log( LOG_ERR, "Request too long (connection %d): %d bytes (max. %d expected)!", Idx, My_Connections[Idx].rdatalen, COMMAND_LEN - 1 );
1224 Conn_Close( Idx, NULL, "Request too long", true );
1229 /* merken, ob Stream bereits komprimiert wird */
1230 old_z = My_Connections[Idx].options & CONN_ZIP;
1235 /* Es wurde ein Request gelesen */
1236 My_Connections[Idx].msg_in++;
1237 if( ! Parse_Request( Idx, My_Connections[Idx].rbuf )) return false;
1241 /* Puffer anpassen */
1242 My_Connections[Idx].rdatalen -= len;
1243 memmove( My_Connections[Idx].rbuf, My_Connections[Idx].rbuf + len, My_Connections[Idx].rdatalen );
1246 if(( ! old_z ) && ( My_Connections[Idx].options & CONN_ZIP ) && ( My_Connections[Idx].rdatalen > 0 ))
1248 /* Mit dem letzten Befehl wurde Socket-Kompression aktiviert.
1249 * Evtl. schon vom Socket gelesene Daten in den Unzip-Puffer
1250 * umkopieren, damit diese nun zunaechst entkomprimiert werden */
1251 if( My_Connections[Idx].rdatalen > ZREADBUFFER_LEN )
1253 /* Hupsa! Soviel Platz haben wir aber gar nicht! */
1254 Log( LOG_ALERT, "Can't move receive buffer: No space left in unzip buffer (need %d bytes)!", My_Connections[Idx].rdatalen );
1257 memcpy( My_Connections[Idx].zip.rbuf, My_Connections[Idx].rbuf, My_Connections[Idx].rdatalen );
1258 My_Connections[Idx].zip.rdatalen = My_Connections[Idx].rdatalen;
1259 My_Connections[Idx].rdatalen = 0;
1261 Log( LOG_DEBUG, "Moved already received data (%d bytes) to uncompression buffer.", My_Connections[Idx].zip.rdatalen );
1267 if( action ) result = true;
1271 } /* Handle_Buffer */
1275 Check_Connections( void )
1277 /* Pruefen, ob Verbindungen noch "alive" sind. Ist dies
1278 * nicht der Fall, zunaechst PING-PONG spielen und, wenn
1279 * auch das nicht "hilft", Client disconnectieren. */
1284 for( i = 0; i < Pool_Size; i++ )
1286 if( My_Connections[i].sock == NONE ) continue;
1288 c = Client_GetFromConn( i );
1289 if( c && (( Client_Type( c ) == CLIENT_USER ) || ( Client_Type( c ) == CLIENT_SERVER ) || ( Client_Type( c ) == CLIENT_SERVICE )))
1291 /* verbundener User, Server oder Service */
1292 if( My_Connections[i].lastping > My_Connections[i].lastdata )
1294 /* es wurde bereits ein PING gesendet */
1295 if( My_Connections[i].lastping < time( NULL ) - Conf_PongTimeout )
1299 Log( LOG_DEBUG, "Connection %d: Ping timeout: %d seconds.", i, Conf_PongTimeout );
1301 Conn_Close( i, NULL, "Ping timeout", true );
1304 else if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout )
1306 /* es muss ein PING gesendet werden */
1308 Log( LOG_DEBUG, "Connection %d: sending PING ...", i );
1310 My_Connections[i].lastping = time( NULL );
1311 Conn_WriteStr( i, "PING :%s", Client_ID( Client_ThisServer( )));
1316 /* noch nicht vollstaendig aufgebaute Verbindung */
1317 if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout )
1321 Log( LOG_DEBUG, "Connection %d timed out ...", i );
1323 Conn_Close( i, NULL, "Timeout", false );
1327 } /* Check_Connections */
1331 Check_Servers( void )
1333 /* Check if we can establish further server links */
1339 /* Serach all connections, are there results from the resolver? */
1340 for( idx = 0; idx < Pool_Size; idx++ )
1342 if( My_Connections[idx].sock != SERVER_WAIT ) continue;
1345 if( My_Connections[idx].res_stat == NULL ) New_Server( Conf_GetServer( idx ), idx );
1348 /* Check all configured servers */
1349 for( i = 0; i < MAX_SERVERS; i++ )
1351 /* Valid outgoing server which isn't already connected or disabled? */
1352 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;
1354 /* Is there already a connection in this group? */
1355 if( Conf_Server[i].group > NONE )
1357 for( n = 0; n < MAX_SERVERS; n++ )
1359 if( n == i ) continue;
1360 if(( Conf_Server[n].conn_id > NONE ) && ( Conf_Server[n].group == Conf_Server[i].group )) break;
1362 if( n < MAX_SERVERS ) continue;
1365 /* Check last connect attempt? */
1366 if( Conf_Server[i].lasttry > time( NULL ) - Conf_ConnectRetry ) continue;
1368 /* Okay, try to connect now */
1369 Conf_Server[i].lasttry = time( NULL );
1371 /* Search free connection structure */
1372 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
1373 if( idx >= Pool_Size )
1375 Log( LOG_ALERT, "Can't establist server connection: connection limit reached (%d)!", Pool_Size );
1379 Log( LOG_DEBUG, "Preparing connection %d for \"%s\" ...", idx, Conf_Server[i].host );
1382 /* Verbindungs-Struktur initialisieren */
1383 Init_Conn_Struct( idx );
1384 My_Connections[idx].sock = SERVER_WAIT;
1385 Conf_Server[i].conn_id = idx;
1387 /* Resolve Hostname. If this fails, try to use it as an IP address */
1388 strlcpy( Conf_Server[i].ip, Conf_Server[i].host, sizeof( Conf_Server[i].ip ));
1389 strlcpy( My_Connections[idx].host, Conf_Server[i].host, sizeof( My_Connections[idx].host ));
1390 s = Resolve_Name( Conf_Server[i].host );
1392 /* resolver process running? */
1393 if( s ) My_Connections[idx].res_stat = s;
1395 } /* Check_Servers */
1399 New_Server( int Server, CONN_ID Idx )
1401 /* Establish new server link */
1403 struct sockaddr_in new_addr;
1404 struct in_addr inaddr;
1408 assert( Server > NONE );
1409 assert( Idx > NONE );
1411 /* Did we get a valid IP address? */
1412 if( ! Conf_Server[Server].ip[0] )
1414 /* No. Free connection structure and abort: */
1415 Init_Conn_Struct( Idx );
1416 Conf_Server[Server].conn_id = NONE;
1417 Log( LOG_ERR, "Can't connect to \"%s\" (connection %d): ip address unknown!", Conf_Server[Server].host, Idx );
1421 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 );
1423 #ifdef HAVE_INET_ATON
1424 if( inet_aton( Conf_Server[Server].ip, &inaddr ) == 0 )
1426 memset( &inaddr, 0, sizeof( inaddr ));
1427 inaddr.s_addr = inet_addr( Conf_Server[Server].ip );
1428 if( inaddr.s_addr == (unsigned)-1 )
1431 /* Can't convert IP address */
1432 Init_Conn_Struct( Idx );
1433 Conf_Server[Server].conn_id = NONE;
1434 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 );
1438 memset( &new_addr, 0, sizeof( new_addr ));
1439 new_addr.sin_family = AF_INET;
1440 new_addr.sin_addr = inaddr;
1441 new_addr.sin_port = htons( Conf_Server[Server].port );
1443 new_sock = socket( PF_INET, SOCK_STREAM, 0 );
1446 /* Can't create socket */
1447 Init_Conn_Struct( Idx );
1448 Conf_Server[Server].conn_id = NONE;
1449 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
1453 if( ! Init_Socket( new_sock )) return;
1455 res = connect( new_sock, (struct sockaddr *)&new_addr, sizeof( new_addr ));
1456 if(( res != 0 ) && ( errno != EINPROGRESS ))
1458 /* Can't connect socket */
1459 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1461 Init_Conn_Struct( Idx );
1462 Conf_Server[Server].conn_id = NONE;
1466 /* Client-Struktur initialisieren */
1467 c = Client_NewLocal( Idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWNSERVER, false );
1470 /* Can't create new client structure */
1472 Init_Conn_Struct( Idx );
1473 Conf_Server[Server].conn_id = NONE;
1474 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1477 Client_SetIntroducer( c, c );
1478 Client_SetToken( c, TOKEN_OUTBOUND );
1480 /* Register connection */
1481 My_Connections[Idx].sock = new_sock;
1482 My_Connections[Idx].addr = new_addr;
1483 strlcpy( My_Connections[Idx].host, Conf_Server[Server].host, sizeof( My_Connections[Idx].host ));
1485 /* Register new socket */
1486 FD_SET( new_sock, &My_Sockets );
1487 Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCONNECTING );
1489 if( new_sock > Conn_MaxFD ) Conn_MaxFD = new_sock;
1492 Log( LOG_DEBUG, "Registered new connection %d on socket %d.", Idx, My_Connections[Idx].sock );
1498 Init_Conn_Struct( CONN_ID Idx )
1500 time_t now = time( NULL );
1501 /* Connection-Struktur initialisieren */
1503 memset( &My_Connections[Idx], 0, sizeof ( CONNECTION ));
1504 My_Connections[Idx].sock = NONE;
1505 My_Connections[Idx].lastdata = now;
1506 My_Connections[Idx].lastprivmsg = now;
1507 } /* Init_Conn_Struct */
1511 Init_Socket( int Sock )
1513 /* Initialize socket (set options) */
1517 #ifdef O_NONBLOCK /* unknown on A/UX */
1518 if( fcntl( Sock, F_SETFL, O_NONBLOCK ) != 0 )
1520 Log( LOG_CRIT, "Can't enable non-blocking mode for socket: %s!", strerror( errno ));
1526 /* Don't block this port after socket shutdown */
1528 if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &value, (socklen_t)sizeof( value )) != 0 )
1530 Log( LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!", strerror( errno ));
1531 /* ignore this error */
1534 /* Set type of service (TOS) */
1535 #if defined(IP_TOS) && defined(IPTOS_LOWDELAY)
1536 value = IPTOS_LOWDELAY;
1538 Log( LOG_DEBUG, "Setting option IP_TOS on socket %d to IPTOS_LOWDELAY (%d).", Sock, value );
1540 if( setsockopt( Sock, SOL_IP, IP_TOS, &value, (socklen_t)sizeof( value )) != 0 )
1542 Log( LOG_ERR, "Can't set socket option IP_TOS: %s!", strerror( errno ));
1543 /* ignore this error */
1552 Read_Resolver_Result( int r_fd )
1554 /* Read result of resolver sub-process from pipe and update the
1555 * apropriate connection/client structure(s): hostname and/or
1556 * IDENT user name.*/
1563 /* Search associated connection ... */
1564 for( i = 0; i < Pool_Size; i++ )
1566 if(( My_Connections[i].sock != NONE )
1567 && ( My_Connections[i].res_stat != NULL )
1568 && ( My_Connections[i].res_stat->pipe[0] == r_fd ))
1571 if( i >= Pool_Size )
1573 /* Ops, none found? Probably the connection has already
1574 * been closed!? We'll ignore that ... */
1575 FD_CLR( r_fd, &Resolver_FDs );
1578 Log( LOG_DEBUG, "Resolver: Got result for unknown connection!?" );
1583 /* Get resolver structure */
1584 s = My_Connections[i].res_stat;
1585 assert( s != NULL );
1587 /* Read result from pipe */
1588 len = read( r_fd, s->buffer + s->bufpos, sizeof( s->buffer ) - s->bufpos - 1 );
1592 Log( LOG_CRIT, "Resolver: Can't read result: %s!", strerror( errno ));
1593 FreeRes_stat( &My_Connections[i] );
1597 s->buffer[s->bufpos] = '\0';
1599 /* If the result string is incomplete, return to main loop and
1600 * wait until we can read in more bytes. */
1604 ptr = strchr( s->buffer, '\n' );
1609 Log( LOG_DEBUG, "Got result from resolver: \"%s\" (%d bytes), stage %d.", s->buffer, len, s->stage );
1612 /* Okay, we got a complete result: this is a host name for outgoing
1613 * connections and a host name or IDENT user name (if enabled) for
1614 * incoming connections.*/
1615 if( My_Connections[i].sock > NONE )
1617 /* Incoming connection. Search client ... */
1618 c = Client_GetFromConn( i );
1619 assert( c != NULL );
1621 /* Only update client information of unregistered clients */
1622 if( Client_Type( c ) == CLIENT_UNKNOWN )
1625 case 0: /* host name */
1626 strlcpy( My_Connections[i].host, s->buffer, sizeof( My_Connections[i].host ));
1627 Client_SetHostname( c, s->buffer );
1629 /* clean up buffer for IDENT result */
1630 len = strlen( s->buffer ) + 1;
1631 assert((size_t)len <= sizeof( s->buffer ));
1632 memmove( s->buffer, s->buffer + len, sizeof( s->buffer ) - len );
1633 assert(len <= s->bufpos );
1636 /* Don't close pipe and clean up, but
1637 * instead wait for IDENT result */
1641 case 1: /* IDENT user name */
1644 Log( LOG_INFO, "IDENT lookup for connection %ld: \"%s\".", i, s->buffer );
1645 Client_SetUser( c, s->buffer, true );
1647 else Log( LOG_INFO, "IDENT lookup for connection %ld: no result.", i );
1651 Log( LOG_ERR, "Resolver: got result for unknown stage %d!?", s->stage );
1655 else Log( LOG_DEBUG, "Resolver: discarding result for already registered connection %d.", i );
1660 /* Outgoing connection (server link): set the IP address
1661 * so that we can connect to it in the main loop. */
1663 /* Search server ... */
1664 n = Conf_GetServer( i );
1667 strlcpy( Conf_Server[n].ip, s->buffer, sizeof( Conf_Server[n].ip ));
1671 FreeRes_stat( &My_Connections[i] );
1673 /* Reset penalty time */
1674 Conn_ResetPenalty( i );
1675 } /* Read_Resolver_Result */
1679 Simple_Message( int Sock, char *Msg )
1681 char buf[COMMAND_LEN];
1682 /* Write "simple" message to socket, without using compression
1683 * or even the connection write buffers. Used e.g. for error
1684 * messages by New_Connection(). */
1685 assert( Sock > NONE );
1686 assert( Msg != NULL );
1688 strlcpy( buf, Msg, sizeof buf - 2);
1689 strlcat( buf, "\r\n", sizeof buf);
1690 (void)write( Sock, buf, strlen( buf ) );
1691 } /* Simple_Error */
1695 Count_Connections( struct sockaddr_in addr_in )
1700 for( i = 0; i < Pool_Size; i++ )
1702 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].addr.sin_addr.s_addr == addr_in.sin_addr.s_addr )) cnt++;
1705 } /* Count_Connections */