2 * ngIRCd -- The Next Generation IRC Daemon
3 * Copyright (c)2001-2005 Alexander Barton <alex@barton.de>
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 * Please read the file COPYING, README and AUTHORS for more information.
11 * Connection management
20 static char UNUSED id[] = "$Id: conn.c,v 1.157 2005/07/07 18:49:04 fw Exp $";
34 #include <sys/socket.h>
36 #include <sys/types.h>
38 #include <netinet/in.h>
40 #ifdef HAVE_NETINET_IP_H
41 # include <netinet/ip.h>
44 #ifdef HAVE_ARPA_INET_H
45 # include <arpa/inet.h>
47 # define PF_INET AF_INET
51 # include <stdint.h> /* e.g. for Mac OS X */
55 # include <tcpd.h> /* for TCP Wrappers */
70 #include "conn-func.h"
76 # include "rendezvous.h"
82 #define SERVER_WAIT (NONE - 1)
85 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 Simple_Message PARAMS(( int Sock, char *Msg ));
96 LOCAL int Count_Connections PARAMS(( struct sockaddr_in addr ));
98 static array My_Listeners;
101 int allow_severity = LOG_INFO;
102 int deny_severity = LOG_ERR;
106 static void cb_clientserver PARAMS((int sock, short what));
109 cb_listen(int sock, short irrelevant)
112 New_Connection( sock );
117 cb_connserver(int sock, short what)
122 CONN_ID idx = Socket2Index( sock );
125 Log(LOG_DEBUG, "cb_connserver wants to write on unknown socket?!");
131 assert( what & IO_WANTWRITE);
133 /* connect() finished, get result. */
134 sock_len = sizeof( err );
135 res = getsockopt( My_Connections[idx].sock, SOL_SOCKET, SO_ERROR, &err, &sock_len );
136 assert( sock_len == sizeof( err ));
138 /* Fehler aufgetreten? */
139 if(( res != 0 ) || ( err != 0 )) {
141 Log( LOG_CRIT, "getsockopt (connection %d): %s!", idx, strerror( errno ));
143 Log( LOG_CRIT, "Can't connect socket to \"%s:%d\" (connection %d): %s!",
144 My_Connections[idx].host, Conf_Server[Conf_GetServer( idx )].port,
145 idx, strerror( err ));
147 /* Clean up socket, connection and client structures */
148 c = Client_GetFromConn( idx );
149 if( c ) Client_DestroyNow( c );
150 io_close( My_Connections[idx].sock );
151 Init_Conn_Struct( idx );
153 /* Bei Server-Verbindungen lasttry-Zeitpunkt auf "jetzt" setzen */
154 Conf_Server[Conf_GetServer( idx )].lasttry = time( NULL );
155 Conf_UnsetServer( idx );
159 Conn_OPTION_DEL( &My_Connections[idx], CONN_ISCONNECTING );
161 Log( LOG_INFO, "Connection %d with \"%s:%d\" established. Now logging in ...", idx,
162 My_Connections[idx].host, Conf_Server[Conf_GetServer( idx )].port );
164 io_event_setcb( My_Connections[idx].sock, cb_clientserver);
165 io_event_add( My_Connections[idx].sock, IO_WANTREAD|IO_WANTWRITE);
167 /* Send PASS and SERVER command to peer */
168 Conn_WriteStr( idx, "PASS %s %s", Conf_Server[Conf_GetServer( idx )].pwd_out, NGIRCd_ProtoID );
169 Conn_WriteStr( idx, "SERVER %s :%s", Conf_ServerName, Conf_ServerInfo );
174 cb_clientserver(int sock, short what)
176 CONN_ID idx = Socket2Index( sock );
179 Log(LOG_WARNING, "WTF: cb_clientserver wants to write on unknown socket?!");
185 if (what & IO_WANTREAD)
188 if (what & IO_WANTWRITE)
194 FreeRes_stat( CONNECTION *c )
197 assert( c->res_stat != NULL );
199 if (!c->res_stat) return;
201 io_close( c->res_stat->pipe[0] );
211 /* Modul initialisieren: statische Strukturen "ausnullen". */
215 /* Speicher fuer Verbindungs-Pool anfordern */
216 Pool_Size = CONNECTION_POOL;
217 if( Conf_MaxConnections > 0 )
219 /* konfiguriertes Limit beachten */
220 if( Pool_Size > Conf_MaxConnections ) Pool_Size = Conf_MaxConnections;
222 My_Connections = (CONNECTION *) calloc( Pool_Size, sizeof( CONNECTION ) );
223 if( ! My_Connections )
225 /* Speicher konnte nicht alloziert werden! */
226 Log( LOG_EMERG, "Can't allocate memory! [Conn_Init]" );
230 Log( LOG_DEBUG, "Allocated connection pool for %d items (%ld bytes).", Pool_Size, sizeof( CONNECTION ) * Pool_Size );
233 array_free( &My_Listeners );
235 /* Groesster File-Descriptor fuer select() */
238 /* Connection-Struktur initialisieren */
239 for( i = 0; i < Pool_Size; i++ ) Init_Conn_Struct( i );
241 /* Global write counter */
249 /* Modul abmelden: alle noch offenen Connections
250 * schliessen und freigeben. */
255 Log( LOG_DEBUG, "Shutting down all connections ..." );
258 Conn_ExitListeners();
260 /* Sockets schliessen */
261 for( idx = 0; idx < Pool_Size; idx++ ) {
262 if( My_Connections[idx].sock > NONE ) {
263 Conn_Close( idx, NULL, NGIRCd_SignalRestart ?
264 "Server going down (restarting)":"Server going down", true );
269 free( My_Connections );
270 My_Connections = NULL;
272 io_library_shutdown();
277 Conn_InitListeners( void )
279 /* Initialize ports on which the server should accept connections */
283 if (!io_library_init(CONNECTION_POOL)) {
284 Log(LOG_EMERG, "Cannot initialize IO routines: %s", strerror(errno));
289 for( i = 0; i < Conf_ListenPorts_Count; i++ )
291 if( Conn_NewListener( Conf_ListenPorts[i] )) created++;
292 else Log( LOG_ERR, "Can't listen on port %u!", (unsigned int) Conf_ListenPorts[i] );
295 } /* Conn_InitListeners */
299 Conn_ExitListeners( void )
301 /* Close down all listening sockets */
303 unsigned int arraylen;
305 Rendezvous_UnregisterListeners( );
308 arraylen = array_length(&My_Listeners, sizeof (int));
309 Log( LOG_INFO, "Shutting down all listening sockets (%d)...", arraylen );
311 fd = (int*) array_get(&My_Listeners, sizeof (int), arraylen);
314 Log( LOG_DEBUG, "Listening socket %d closed.", *fd );
317 Log( LOG_DEBUG, "array_get pos %d returned NULL", arraylen );
321 array_free(&My_Listeners);
322 } /* Conn_ExitListeners */
326 Conn_NewListener( const UINT16 Port )
328 /* Create new listening socket on specified port */
330 struct sockaddr_in addr;
331 struct in_addr inaddr;
334 char name[CLIENT_ID_LEN], *info;
337 /* Server-"Listen"-Socket initialisieren */
338 memset( &addr, 0, sizeof( addr ));
339 memset( &inaddr, 0, sizeof( inaddr ));
340 addr.sin_family = AF_INET;
341 addr.sin_port = htons( Port );
342 if( Conf_ListenAddress[0] )
344 #ifdef HAVE_INET_ATON
345 if( inet_aton( Conf_ListenAddress, &inaddr ) == 0 )
347 inaddr.s_addr = inet_addr( Conf_ListenAddress );
348 if( inaddr.s_addr == (unsigned)-1 )
351 Log( LOG_CRIT, "Can't listen on %s:%u: can't convert ip address %s!", Conf_ListenAddress, Port, Conf_ListenAddress );
355 else inaddr.s_addr = htonl( INADDR_ANY );
356 addr.sin_addr = inaddr;
358 /* Socket erzeugen */
359 sock = socket( PF_INET, SOCK_STREAM, 0);
362 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
366 if( ! Init_Socket( sock )) return false;
369 if( bind( sock, (struct sockaddr *)&addr, (socklen_t)sizeof( addr )) != 0 )
371 Log( LOG_CRIT, "Can't bind socket: %s!", strerror( errno ));
376 /* in "listen mode" gehen :-) */
377 if( listen( sock, 10 ) != 0 )
379 Log( LOG_CRIT, "Can't listen on soecket: %s!", strerror( errno ));
384 /* Neuen Listener in Strukturen einfuegen */
385 if (!array_catb( &My_Listeners,(char*) &sock, sizeof(int) )) {
386 Log( LOG_CRIT, "Can't add socket to My_Listeners array: %s!", strerror( errno ));
390 io_event_create( sock, IO_WANTREAD, cb_listen );
392 if( Conf_ListenAddress[0]) Log( LOG_INFO, "Now listening on %s:%d (socket %d).", Conf_ListenAddress, Port, sock );
393 else Log( LOG_INFO, "Now listening on 0.0.0.0:%d (socket %d).", Port, sock );
396 /* Get best server description text */
397 if( ! Conf_ServerInfo[0] ) info = Conf_ServerName;
400 /* Use server info string */
402 if( Conf_ServerInfo[0] == '[' )
404 /* Cut off leading hostname part in "[]" */
405 info = strchr( Conf_ServerInfo, ']' );
409 while( *info == ' ' ) info++;
412 if( ! info ) info = Conf_ServerInfo;
415 /* Add port number to description if non-standard */
416 if( Port != 6667 ) snprintf( name, sizeof( name ), "%s (port %u)", info, Port );
417 else strlcpy( name, info, sizeof( name ));
419 /* Register service */
420 Rendezvous_Register( name, RENDEZVOUS_TYPE, Port );
423 } /* Conn_NewListener */
429 /* "Hauptschleife": Aktive Verbindungen ueberwachen. Folgende Aktionen
430 * werden dabei durchgefuehrt, bis der Server terminieren oder neu
433 * - neue Verbindungen annehmen,
434 * - Server-Verbindungen aufbauen,
435 * - geschlossene Verbindungen loeschen,
436 * - volle Schreibpuffer versuchen zu schreiben,
437 * - volle Lesepuffer versuchen zu verarbeiten,
438 * - Antworten von Resolver Sub-Prozessen annehmen.
441 unsigned int wdatalen;
446 start = time( NULL );
447 while(( ! NGIRCd_SignalQuit ) && ( ! NGIRCd_SignalRestart ))
452 Rendezvous_Handler( );
455 /* Should the configuration be reloaded? */
456 if( NGIRCd_SignalRehash ) NGIRCd_Rehash( );
458 /* Check configured servers and established links */
460 Check_Connections( );
464 /* noch volle Lese-Buffer suchen */
465 for( i = 0; i < Pool_Size; i++ )
467 if(( My_Connections[i].sock > NONE ) && ( array_bytes(&My_Connections[i].rbuf) > 0 ) &&
468 ( My_Connections[i].delaytime < t ))
470 /* Kann aus dem Buffer noch ein Befehl extrahiert werden? */
471 if (Handle_Buffer( i )) timeout = false;
475 /* noch volle Schreib-Puffer suchen */
476 for( i = 0; i < Pool_Size; i++ ) {
477 if ( My_Connections[i].sock <= NONE )
480 wdatalen = array_bytes(&My_Connections[i].wbuf);
483 if (( wdatalen > 0 ) || ( array_bytes(&My_Connections[i].zip.wbuf)> 0 ))
488 /* Socket der Verbindung in Set aufnehmen */
489 io_event_add( My_Connections[i].sock, IO_WANTWRITE );
494 /* von welchen Sockets koennte gelesen werden? */
495 for (i = 0; i < Pool_Size; i++ ) {
496 if ( My_Connections[i].sock <= NONE )
499 if ( My_Connections[i].res_stat ) {
500 /* wait for completion of Resolver Sub-Process */
501 io_event_del( My_Connections[i].sock, IO_WANTREAD );
505 if ( Conn_OPTION_ISSET( &My_Connections[i], CONN_ISCONNECTING ))
506 continue; /* wait for completion of connect() */
508 if( My_Connections[i].delaytime > t ) {
509 /* Fuer die Verbindung ist eine "Penalty-Zeit" gesetzt */
510 io_event_del( My_Connections[i].sock, IO_WANTREAD );
513 io_event_add( My_Connections[i].sock, IO_WANTREAD );
516 /* Timeout initialisieren */
518 if( timeout ) tv.tv_sec = 1;
521 /* Auf Aktivitaet warten */
522 i = io_dispatch( &tv );
523 if (i == -1 && errno != EINTR ) {
524 Log(LOG_EMERG, "Conn_Handler(): io_dispatch(): %s!", strerror(errno));
525 Log(LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE_NAME);
530 if( NGIRCd_SignalQuit ) Log( LOG_NOTICE|LOG_snotice, "Server going down NOW!" );
531 else if( NGIRCd_SignalRestart ) Log( LOG_NOTICE|LOG_snotice, "Server restarting NOW!" );
536 * Write a text string into the socket of a connection.
537 * This function automatically appends CR+LF to the string and validates that
538 * the result is a valid IRC message (oversized messages are shortened, for
539 * example). Then it calls the Conn_Write() function to do the actual sending.
540 * @param Idx Index fo the connection.
541 * @param Format Format string, see printf().
542 * @return true on success, false otherwise.
546 Conn_WriteStr( CONN_ID Idx, char *Format, ... )
549 Conn_WriteStr( Idx, Format, va_alist )
555 char buffer[COMMAND_LEN];
559 assert( Idx > NONE );
560 assert( Format != NULL );
563 va_start( ap, Format );
567 if (vsnprintf( buffer, COMMAND_LEN - 2, Format, ap ) >= COMMAND_LEN - 2 ) {
569 * The string that should be written to the socket is longer
570 * than the allowed size of COMMAND_LEN bytes (including both
571 * the CR and LF characters). This can be caused by the
572 * IRC_WriteXXX() functions when the prefix of this server had
573 * to be added to an already "quite long" command line which
574 * has been received from a regular IRC client, for example.
576 * We are not allowed to send such "oversized" messages to
577 * other servers and clients, see RFC 2812 2.3 and 2813 3.3
578 * ("these messages SHALL NOT exceed 512 characters in length,
579 * counting all characters including the trailing CR-LF").
581 * So we have a big problem here: we should send more bytes
582 * to the network than we are allowed to and we don't know
583 * the originator (any more). The "old" behaviour of blaming
584 * the receiver ("next hop") is a bad idea (it could be just
585 * an other server only routing the message!), so the only
586 * option left is to shorten the string and to hope that the
587 * result is still somewhat useful ...
591 strcpy (buffer + sizeof(buffer) - strlen(CUT_TXTSUFFIX) - 2 - 1,
597 Log(LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer);
600 strlcat( buffer, "\r\n", sizeof( buffer ));
601 ok = Conn_Write( Idx, buffer, strlen( buffer ));
602 My_Connections[Idx].msg_out++;
606 } /* Conn_WriteStr */
610 Conn_Write( CONN_ID Idx, char *Data, unsigned int Len )
612 /* Daten in Socket schreiben. Bei "fatalen" Fehlern wird
613 * der Client disconnectiert und false geliefert. */
615 assert( Idx > NONE );
616 assert( Data != NULL );
619 /* Ist der entsprechende Socket ueberhaupt noch offen? In einem
620 * "Handler-Durchlauf" kann es passieren, dass dem nicht mehr so
621 * ist, wenn einer von mehreren Conn_Write()'s fehlgeschlagen ist.
622 * In diesem Fall wird hier einfach ein Fehler geliefert. */
623 if( My_Connections[Idx].sock <= NONE )
626 Log( LOG_DEBUG, "Skipped write on closed socket (connection %d).", Idx );
631 /* Pruefen, ob im Schreibpuffer genuegend Platz ist. Ziel ist es,
632 * moeglichts viel im Puffer zu haben und _nicht_ gleich alles auf den
633 * Socket zu schreiben (u.a. wg. Komprimierung). */
634 if( array_bytes(&My_Connections[Idx].wbuf) >= WRITEBUFFER_LEN) {
635 /* Der Puffer ist dummerweise voll. Jetzt versuchen, den Puffer
636 * zu schreiben, wenn das nicht klappt, haben wir ein Problem ... */
637 if( ! Handle_Write( Idx )) return false;
639 /* check again: if our writebuf is twice als large as the initial limit: Kill connection */
640 if( array_bytes(&My_Connections[Idx].wbuf) >= (WRITEBUFFER_LEN*2)) {
641 Log( LOG_NOTICE, "Write buffer overflow (connection %d)!", Idx );
642 Conn_Close( Idx, "Write buffer overflow!", NULL, false );
648 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
649 /* Daten komprimieren und in Puffer kopieren */
650 if( ! Zip_Buffer( Idx, Data, Len )) return false;
655 /* Daten in Puffer kopieren */
656 if (!array_catb( &My_Connections[Idx].wbuf, Data, Len ))
659 My_Connections[Idx].bytes_out += Len;
662 /* Adjust global write counter */
670 Conn_Close( CONN_ID Idx, char *LogMsg, char *FwdMsg, bool InformClient )
672 /* Close connection. Open pipes of asyncronous resolver
673 * sub-processes are closed down. */
679 double in_z_k, out_z_k;
683 assert( Idx > NONE );
685 /* Is this link already shutting down? */
686 if( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ISCLOSING )) {
687 /* Conn_Close() has been called recursively for this link;
688 * probabe reason: Handle_Write() failed -- see below. */
690 Log( LOG_DEBUG, "Recursive request to close connection: %d", Idx );
695 assert( My_Connections[Idx].sock > NONE );
697 /* Mark link as "closing" */
698 Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCLOSING );
700 if( LogMsg ) txt = LogMsg;
702 if( ! txt ) txt = "Reason unknown";
704 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 ));
706 /* Search client, if any */
707 c = Client_GetFromConn( Idx );
709 /* Should the client be informed? */
713 /* Send statistics to client if registered as user: */
714 if(( c != NULL ) && ( Client_Type( c ) == CLIENT_USER ))
716 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 );
720 /* Send ERROR to client (see RFC!) */
721 if( FwdMsg ) Conn_WriteStr( Idx, "ERROR :%s", FwdMsg );
722 else Conn_WriteStr( Idx, "ERROR :Closing connection." );
725 /* Try to write out the write buffer */
726 (void)Handle_Write( Idx );
728 /* Shut down socket */
729 if( ! io_close( My_Connections[Idx].sock ))
731 /* Oops, we can't close the socket!? This is ... ugly! */
732 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 ));
735 /* Mark socket as invalid: */
736 My_Connections[Idx].sock = NONE;
738 /* If there is still a client, unregister it now */
739 if( c ) Client_Destroy( c, LogMsg, FwdMsg, true );
741 /* Calculate statistics and log information */
742 in_k = (double)My_Connections[Idx].bytes_in / 1024;
743 out_k = (double)My_Connections[Idx].bytes_out / 1024;
745 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
746 in_z_k = (double)My_Connections[Idx].zip.bytes_in / 1024;
747 out_z_k = (double)My_Connections[Idx].zip.bytes_out / 1024;
748 in_p = (int)(( in_k * 100 ) / in_z_k );
749 out_p = (int)(( out_k * 100 ) / out_z_k );
750 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 );
755 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 );
758 /* Is there a resolver sub-process running? */
759 if( My_Connections[Idx].res_stat )
760 FreeRes_stat( &My_Connections[Idx] );
762 /* Servers: Modify time of next connect attempt? */
763 Conf_UnsetServer( Idx );
766 /* Clean up zlib, if link was compressed */
767 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
768 inflateEnd( &My_Connections[Idx].zip.in );
769 deflateEnd( &My_Connections[Idx].zip.out );
770 array_free(&My_Connections[Idx].zip.rbuf);
771 array_free(&My_Connections[Idx].zip.wbuf);
775 array_free(&My_Connections[Idx].rbuf);
776 array_free(&My_Connections[Idx].wbuf);
777 /* Clean up connection structure (=free it) */
778 Init_Conn_Struct( Idx );
781 Log( LOG_DEBUG, "Shutdown of connection %d completed.", Idx );
787 Conn_SyncServerStruct( void )
789 /* Synchronize server structures (connection IDs):
790 * connections <-> configuration */
796 for( i = 0; i < Pool_Size; i++ )
798 /* Established connection? */
799 if( My_Connections[i].sock <= NONE ) continue;
801 /* Server connection? */
802 client = Client_GetFromConn( i );
803 if(( ! client ) || ( Client_Type( client ) != CLIENT_SERVER )) continue;
805 for( c = 0; c < MAX_SERVERS; c++ )
807 /* Configured server? */
808 if( ! Conf_Server[c].host[0] ) continue;
811 if( strcmp( Conf_Server[c].name, Client_ID( client )) == 0 ) Conf_Server[c].conn_id = i;
814 } /* SyncServerStruct */
818 Handle_Write( CONN_ID Idx )
820 /* Daten aus Schreibpuffer versenden bzw. Connection aufbauen */
823 unsigned int wdatalen;
825 Log(LOG_DEBUG, "Handle_Write");
826 assert( Idx > NONE );
827 if ( My_Connections[Idx].sock < 0 ) {
828 Log(LOG_WARNING, "Handle_Write() on closed socket, idx %d", Idx);
831 assert( My_Connections[Idx].sock > NONE );
834 wdatalen = array_bytes(&My_Connections[Idx].wbuf );
836 if(( wdatalen == 0 ) && ( ! array_bytes(&My_Connections[Idx].zip.wbuf))) {
837 io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
841 /* write buffer empty, but not compression buf? -> flush compression buf. */
842 if( wdatalen == 0 ) Zip_Flush( Idx );
844 if( wdatalen == 0 ) {
845 io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
850 wdatalen = array_bytes(&My_Connections[Idx].wbuf ); /* Zip_Flush may change wbuf */
851 len = write( My_Connections[Idx].sock, array_start(&My_Connections[Idx].wbuf), wdatalen );
853 if( errno == EAGAIN || errno == EINTR)
856 Log( LOG_ERR, "Write error on connection %d (socket %d): %s!", Idx,
857 My_Connections[Idx].sock, strerror( errno ));
858 Conn_Close( Idx, "Write error!", NULL, false );
862 /* move any data not yet written to beginning */
863 array_moveleft(&My_Connections[Idx].wbuf, 1, len);
870 New_Connection( int Sock )
872 /* Neue Client-Verbindung von Listen-Socket annehmen und
873 * CLIENT-Struktur anlegen. */
876 struct request_info req;
878 struct sockaddr_in new_addr;
879 int new_sock, new_sock_len;
886 assert( Sock > NONE );
887 /* Connection auf Listen-Socket annehmen */
888 new_sock_len = sizeof( new_addr );
889 new_sock = accept( Sock, (struct sockaddr *)&new_addr, (socklen_t *)&new_sock_len );
892 Log( LOG_CRIT, "Can't accept connection: %s!", strerror( errno ));
897 /* Validate socket using TCP Wrappers */
898 request_init( &req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock, RQ_CLIENT_SIN, &new_addr, NULL );
900 if( ! hosts_access( &req ))
903 Log( deny_severity, "Refused connection from %s (by TCP Wrappers)!", inet_ntoa( new_addr.sin_addr ));
904 Simple_Message( new_sock, "ERROR :Connection refused" );
910 /* Socket initialisieren */
911 Init_Socket( new_sock );
913 /* Check IP-based connection limit */
914 cnt = Count_Connections( new_addr );
915 if(( Conf_MaxConnectionsIP > 0 ) && ( cnt >= Conf_MaxConnectionsIP ))
917 /* Access denied, too many connections from this IP address! */
918 Log( LOG_ERR, "Refused connection from %s: too may connections (%ld) from this IP address!", inet_ntoa( new_addr.sin_addr ), cnt);
919 Simple_Message( new_sock, "ERROR :Connection refused, too many connections from your IP address!" );
924 /* Freie Connection-Struktur suchen */
925 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
926 if( idx >= Pool_Size )
928 new_size = Pool_Size + CONNECTION_POOL;
930 /* Im bisherigen Pool wurde keine freie Connection-Struktur mehr gefunden.
931 * Wenn erlaubt und moeglich muss nun der Pool vergroessert werden: */
933 if( Conf_MaxConnections > 0 )
935 /* Es ist ein Limit konfiguriert */
936 if( Pool_Size >= Conf_MaxConnections )
938 /* Mehr Verbindungen duerfen wir leider nicht mehr annehmen ... */
939 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached!", Pool_Size );
940 Simple_Message( new_sock, "ERROR :Connection limit reached" );
944 if( new_size > Conf_MaxConnections ) new_size = Conf_MaxConnections;
946 if( new_size < Pool_Size )
948 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached -- overflow!", Pool_Size );
949 Simple_Message( new_sock, "ERROR :Connection limit reached" );
954 ptr = (POINTER *)realloc( My_Connections, sizeof( CONNECTION ) * new_size );
957 Log( LOG_EMERG, "Can't allocate memory! [New_Connection]" );
958 Simple_Message( new_sock, "ERROR: Internal error" );
964 Log( LOG_DEBUG, "Allocated new connection pool for %ld items (%ld bytes). [realloc()]", new_size, sizeof( CONNECTION ) * new_size );
967 /* Adjust pointer to new block */
968 My_Connections = (CONNECTION *)ptr;
970 /* Initialize new items */
971 for( idx = Pool_Size; idx < new_size; idx++ ) Init_Conn_Struct( idx );
974 /* Adjust new pool size */
975 Pool_Size = new_size;
978 /* Client-Struktur initialisieren */
979 c = Client_NewLocal( idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWN, false );
982 Log( LOG_ALERT, "Can't accept connection: can't create client structure!" );
983 Simple_Message( new_sock, "ERROR :Internal error" );
988 /* Verbindung registrieren */
989 Init_Conn_Struct( idx );
990 My_Connections[idx].sock = new_sock;
991 My_Connections[idx].addr = new_addr;
993 /* Neuen Socket registrieren */
994 io_event_create( new_sock, IO_WANTREAD, cb_clientserver);
996 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 );
998 /* Hostnamen ermitteln */
999 strlcpy( My_Connections[idx].host, inet_ntoa( new_addr.sin_addr ), sizeof( My_Connections[idx].host ));
1000 Client_SetHostname( c, My_Connections[idx].host );
1002 s = Resolve_Addr( &new_addr, My_Connections[idx].sock );
1004 s = Resolve_Addr( &new_addr );
1006 /* resolver process has been started */
1007 if( s ) My_Connections[idx].res_stat = s;
1009 /* Penalty-Zeit setzen */
1010 Conn_SetPenalty( idx, 4 );
1011 } /* New_Connection */
1015 Socket2Index( int Sock )
1017 /* zum Socket passende Connection suchen */
1021 assert( Sock > NONE );
1023 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == Sock ) break;
1025 if( idx >= Pool_Size )
1027 /* die Connection wurde vermutlich (wegen eines
1028 * Fehlers) bereits wieder abgebaut ... */
1030 Log( LOG_DEBUG, "Socket2Index: can't get connection for socket %d!", Sock );
1035 } /* Socket2Index */
1039 Read_Request( CONN_ID Idx )
1041 /* Daten von Socket einlesen und entsprechend behandeln.
1042 * Tritt ein Fehler auf, so wird der Socket geschlossen. */
1051 assert( Idx > NONE );
1052 assert( My_Connections[Idx].sock > NONE );
1054 /* wenn noch nicht registriert: maximal mit ZREADBUFFER_LEN arbeiten,
1055 * ansonsten koennen Daten ggf. nicht umkopiert werden. */
1056 bsize = READBUFFER_LEN;
1058 c = Client_GetFromConn( Idx );
1060 if(( Client_Type( c ) != CLIENT_USER ) && ( Client_Type( c ) != CLIENT_SERVER ) &&
1061 ( Client_Type( c ) != CLIENT_SERVICE ) && ( bsize > ZREADBUFFER_LEN ))
1062 bsize = ZREADBUFFER_LEN;
1066 if (( array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN ) ||
1067 ( array_bytes(&My_Connections[Idx].zip.rbuf) >= ZREADBUFFER_LEN ))
1069 if ( array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN )
1072 /* Der Lesepuffer ist voll */
1073 Log( LOG_ERR, "Receive buffer overflow (connection %d): %d bytes!", Idx,
1074 array_bytes(&My_Connections[Idx].rbuf));
1075 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1079 len = read( My_Connections[Idx].sock, readbuf, sizeof readbuf );
1081 Log( LOG_INFO, "%s:%d (%s) is closing the connection ...",
1082 My_Connections[Idx].host, ntohs( My_Connections[Idx].addr.sin_port),
1083 inet_ntoa( My_Connections[Idx].addr.sin_addr ));
1084 Conn_Close( Idx, "Socket closed!", "Client closed connection", false );
1088 if( errno == EAGAIN ) return;
1089 Log( LOG_ERR, "Read error on connection %d (socket %d): %s!", Idx,
1090 My_Connections[Idx].sock, strerror( errno ));
1091 Conn_Close( Idx, "Read error!", "Client closed connection", false );
1095 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
1096 if (!array_catb( &My_Connections[Idx].zip.rbuf, readbuf, len)) {
1097 Log( LOG_ERR, "Could not append recieved data to zip input buffer (connn %d): %d bytes!", Idx, len );
1098 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1105 if (!array_cats( &My_Connections[Idx].rbuf, readbuf )) {
1106 Log( LOG_ERR, "Could not append recieved data to input buffer (connn %d): %d bytes!", Idx, len );
1107 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1111 /* Connection-Statistik aktualisieren */
1112 My_Connections[Idx].bytes_in += len;
1114 /* Timestamp aktualisieren */
1115 My_Connections[Idx].lastdata = time( NULL );
1117 Handle_Buffer( Idx );
1118 } /* Read_Request */
1122 Handle_Buffer( CONN_ID Idx )
1124 /* Handle Data in Connections Read-Buffer.
1125 * Return true if a reuqest was handled, false otherwise (also returned on errors). */
1131 unsigned int arraylen;
1132 bool action, result;
1141 if( My_Connections[Idx].delaytime > time( NULL )) return result;
1143 /* unpack compressed data */
1144 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP ))
1145 if( ! Unzip_Buffer( Idx )) return false;
1148 arraylen = array_bytes(&My_Connections[Idx].rbuf);
1152 if (!array_cat0(&My_Connections[Idx].rbuf)) /* make sure buf is NULL terminated */
1155 array_truncate(&My_Connections[Idx].rbuf, 1, arraylen); /* do not count trailing NULL */
1158 /* A Complete Request end with CR+LF, see RFC 2812. */
1159 ptr = strstr( array_start(&My_Connections[Idx].rbuf), "\r\n" );
1161 if( ptr ) delta = 2; /* complete request */
1164 /* Check for non-RFC-compliant request (only CR or LF)? Unfortunately,
1165 * there are quite a few clients that do this (incl. "mIRC" :-( */
1166 ptr1 = strchr( array_start(&My_Connections[Idx].rbuf), '\r' );
1167 ptr2 = strchr( array_start(&My_Connections[Idx].rbuf), '\n' );
1169 if( ptr1 && ptr2 ) ptr = ptr1 > ptr2 ? ptr2 : ptr1;
1170 else if( ptr1 ) ptr = ptr1;
1171 else if( ptr2 ) ptr = ptr2;
1179 /* End of request found */
1182 len = ( ptr - (char*) array_start(&My_Connections[Idx].rbuf)) + delta;
1184 if( len < 0 || len > ( COMMAND_LEN - 1 )) {
1185 /* Request must not exceed 512 chars (incl. CR+LF!), see
1186 * RFC 2812. Disconnect Client if this happens. */
1187 Log( LOG_ERR, "Request too long (connection %d): %d bytes (max. %d expected)!",
1188 Idx, array_bytes(&My_Connections[Idx].rbuf), COMMAND_LEN - 1 );
1189 Conn_Close( Idx, NULL, "Request too long", true );
1194 /* remember if stream is already compressed */
1195 old_z = My_Connections[Idx].options & CONN_ZIP;
1200 /* A Request was read */
1201 My_Connections[Idx].msg_in++;
1202 if( ! Parse_Request( Idx, (char*)array_start(&My_Connections[Idx].rbuf) )) return false;
1205 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1207 Log(LOG_DEBUG, "%d byte left in rbuf", array_bytes(&My_Connections[Idx].rbuf));
1212 if(( ! old_z ) && ( My_Connections[Idx].options & CONN_ZIP ) && ( array_bytes(&My_Connections[Idx].rbuf) > 0 ))
1214 /* The last Command activated Socket-Compression.
1215 * Data that was read after that needs to be copied to Unzip-buf
1216 * for decompression */
1217 if( array_bytes(&My_Connections[Idx].rbuf)> ZREADBUFFER_LEN ) {
1219 Log( LOG_ALERT, "Can't move receive buffer: No space left in unzip buffer (need %d bytes)!", array_bytes(&My_Connections[Idx].rbuf ));
1222 if (!array_copy( &My_Connections[Idx].zip.rbuf, &My_Connections[Idx].rbuf ))
1225 array_trunc(&My_Connections[Idx].rbuf);
1227 Log( LOG_DEBUG, "Moved already received data (%d bytes) to uncompression buffer.", array_bytes(&My_Connections[Idx].zip.rbuf));
1231 if( action ) result = true;
1235 } /* Handle_Buffer */
1239 Check_Connections( void )
1241 /* Pruefen, ob Verbindungen noch "alive" sind. Ist dies
1242 * nicht der Fall, zunaechst PING-PONG spielen und, wenn
1243 * auch das nicht "hilft", Client disconnectieren. */
1248 for( i = 0; i < Pool_Size; i++ )
1250 if( My_Connections[i].sock == NONE ) continue;
1252 c = Client_GetFromConn( i );
1253 if( c && (( Client_Type( c ) == CLIENT_USER ) || ( Client_Type( c ) == CLIENT_SERVER ) || ( Client_Type( c ) == CLIENT_SERVICE )))
1255 /* verbundener User, Server oder Service */
1256 if( My_Connections[i].lastping > My_Connections[i].lastdata )
1258 /* es wurde bereits ein PING gesendet */
1259 if( My_Connections[i].lastping < time( NULL ) - Conf_PongTimeout )
1263 Log( LOG_DEBUG, "Connection %d: Ping timeout: %d seconds.", i, Conf_PongTimeout );
1265 Conn_Close( i, NULL, "Ping timeout", true );
1268 else if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout )
1270 /* es muss ein PING gesendet werden */
1272 Log( LOG_DEBUG, "Connection %d: sending PING ...", i );
1274 My_Connections[i].lastping = time( NULL );
1275 Conn_WriteStr( i, "PING :%s", Client_ID( Client_ThisServer( )));
1280 /* noch nicht vollstaendig aufgebaute Verbindung */
1281 if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout )
1285 Log( LOG_DEBUG, "Connection %d timed out ...", i );
1287 Conn_Close( i, NULL, "Timeout", false );
1291 } /* Check_Connections */
1295 Check_Servers( void )
1297 /* Check if we can establish further server links */
1303 /* Serach all connections, are there results from the resolver? */
1304 for( idx = 0; idx < Pool_Size; idx++ )
1306 if( My_Connections[idx].sock != SERVER_WAIT ) continue;
1309 if( My_Connections[idx].res_stat == NULL ) New_Server( Conf_GetServer( idx ), idx );
1312 /* Check all configured servers */
1313 for( i = 0; i < MAX_SERVERS; i++ )
1315 /* Valid outgoing server which isn't already connected or disabled? */
1316 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;
1318 /* Is there already a connection in this group? */
1319 if( Conf_Server[i].group > NONE )
1321 for( n = 0; n < MAX_SERVERS; n++ )
1323 if( n == i ) continue;
1324 if(( Conf_Server[n].conn_id > NONE ) && ( Conf_Server[n].group == Conf_Server[i].group )) break;
1326 if( n < MAX_SERVERS ) continue;
1329 /* Check last connect attempt? */
1330 if( Conf_Server[i].lasttry > time( NULL ) - Conf_ConnectRetry ) continue;
1332 /* Okay, try to connect now */
1333 Conf_Server[i].lasttry = time( NULL );
1335 /* Search free connection structure */
1336 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
1337 if( idx >= Pool_Size )
1339 Log( LOG_ALERT, "Can't establist server connection: connection limit reached (%d)!", Pool_Size );
1343 Log( LOG_DEBUG, "Preparing connection %d for \"%s\" ...", idx, Conf_Server[i].host );
1346 /* Verbindungs-Struktur initialisieren */
1347 Init_Conn_Struct( idx );
1348 My_Connections[idx].sock = SERVER_WAIT;
1349 Conf_Server[i].conn_id = idx;
1351 /* Resolve Hostname. If this fails, try to use it as an IP address */
1352 strlcpy( Conf_Server[i].ip, Conf_Server[i].host, sizeof( Conf_Server[i].ip ));
1353 strlcpy( My_Connections[idx].host, Conf_Server[i].host, sizeof( My_Connections[idx].host ));
1354 s = Resolve_Name( Conf_Server[i].host );
1356 /* resolver process running? */
1357 if( s ) My_Connections[idx].res_stat = s;
1359 } /* Check_Servers */
1363 New_Server( int Server, CONN_ID Idx )
1365 /* Establish new server link */
1367 struct sockaddr_in new_addr;
1368 struct in_addr inaddr;
1372 assert( Server > NONE );
1373 assert( Idx > NONE );
1375 /* Did we get a valid IP address? */
1376 if( ! Conf_Server[Server].ip[0] )
1378 /* No. Free connection structure and abort: */
1379 Init_Conn_Struct( Idx );
1380 Conf_Server[Server].conn_id = NONE;
1381 Log( LOG_ERR, "Can't connect to \"%s\" (connection %d): ip address unknown!", Conf_Server[Server].host, Idx );
1385 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 );
1387 #ifdef HAVE_INET_ATON
1388 if( inet_aton( Conf_Server[Server].ip, &inaddr ) == 0 )
1390 memset( &inaddr, 0, sizeof( inaddr ));
1391 inaddr.s_addr = inet_addr( Conf_Server[Server].ip );
1392 if( inaddr.s_addr == (unsigned)-1 )
1395 /* Can't convert IP address */
1396 Init_Conn_Struct( Idx );
1397 Conf_Server[Server].conn_id = NONE;
1398 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 );
1402 memset( &new_addr, 0, sizeof( new_addr ));
1403 new_addr.sin_family = AF_INET;
1404 new_addr.sin_addr = inaddr;
1405 new_addr.sin_port = htons( Conf_Server[Server].port );
1407 new_sock = socket( PF_INET, SOCK_STREAM, 0 );
1410 /* Can't create socket */
1411 Init_Conn_Struct( Idx );
1412 Conf_Server[Server].conn_id = NONE;
1413 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
1417 if( ! Init_Socket( new_sock )) return;
1419 res = connect( new_sock, (struct sockaddr *)&new_addr, sizeof( new_addr ));
1420 if(( res != 0 ) && ( errno != EINPROGRESS ))
1422 /* Can't connect socket */
1423 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1425 Init_Conn_Struct( Idx );
1426 Conf_Server[Server].conn_id = NONE;
1430 /* Client-Struktur initialisieren */
1431 c = Client_NewLocal( Idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWNSERVER, false );
1434 /* Can't create new client structure */
1436 Init_Conn_Struct( Idx );
1437 Conf_Server[Server].conn_id = NONE;
1438 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1441 Client_SetIntroducer( c, c );
1442 Client_SetToken( c, TOKEN_OUTBOUND );
1444 /* Register connection */
1445 My_Connections[Idx].sock = new_sock;
1446 My_Connections[Idx].addr = new_addr;
1447 strlcpy( My_Connections[Idx].host, Conf_Server[Server].host, sizeof( My_Connections[Idx].host ));
1449 /* Register new socket */
1450 io_event_create( new_sock, IO_WANTWRITE, cb_connserver);
1451 Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCONNECTING );
1454 Log( LOG_DEBUG, "Registered new connection %d on socket %d.", Idx, My_Connections[Idx].sock );
1460 Init_Conn_Struct( CONN_ID Idx )
1462 time_t now = time( NULL );
1463 /* Connection-Struktur initialisieren */
1465 memset( &My_Connections[Idx], 0, sizeof ( CONNECTION ));
1466 My_Connections[Idx].sock = NONE;
1467 My_Connections[Idx].lastdata = now;
1468 My_Connections[Idx].lastprivmsg = now;
1469 } /* Init_Conn_Struct */
1473 Init_Socket( int Sock )
1475 /* Initialize socket (set options) */
1479 if (!io_setnonblock(Sock)) {
1480 Log( LOG_CRIT, "Can't enable non-blocking mode for socket: %s!", strerror( errno ));
1485 /* Don't block this port after socket shutdown */
1487 if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &value, (socklen_t)sizeof( value )) != 0 )
1489 Log( LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!", strerror( errno ));
1490 /* ignore this error */
1493 /* Set type of service (TOS) */
1494 #if defined(IP_TOS) && defined(IPTOS_LOWDELAY)
1495 value = IPTOS_LOWDELAY;
1497 Log( LOG_DEBUG, "Setting option IP_TOS on socket %d to IPTOS_LOWDELAY (%d).", Sock, value );
1499 if( setsockopt( Sock, SOL_IP, IP_TOS, &value, (socklen_t)sizeof( value )) != 0 )
1501 Log( LOG_ERR, "Can't set socket option IP_TOS: %s!", strerror( errno ));
1502 /* ignore this error */
1511 void Read_Resolver_Result( int r_fd )
1513 /* Read result of resolver sub-process from pipe and update the
1514 * apropriate connection/client structure(s): hostname and/or
1515 * IDENT user name.*/
1522 Log( LOG_DEBUG, "Resolver: started, fd %d\n", r_fd );
1523 /* Search associated connection ... */
1524 for( i = 0; i < Pool_Size; i++ )
1526 if(( My_Connections[i].sock != NONE )
1527 && ( My_Connections[i].res_stat != NULL )
1528 && ( My_Connections[i].res_stat->pipe[0] == r_fd ))
1531 if( i >= Pool_Size )
1533 /* Ops, none found? Probably the connection has already
1534 * been closed!? We'll ignore that ... */
1537 Log( LOG_DEBUG, "Resolver: Got result for unknown connection!?" );
1542 /* Get resolver structure */
1543 s = My_Connections[i].res_stat;
1544 assert( s != NULL );
1546 /* Read result from pipe */
1547 len = read( r_fd, s->buffer + s->bufpos, sizeof( s->buffer ) - s->bufpos - 1 );
1551 Log( LOG_CRIT, "Resolver: Can't read result: %s!", strerror( errno ));
1552 FreeRes_stat( &My_Connections[i] );
1556 s->buffer[s->bufpos] = '\0';
1558 /* If the result string is incomplete, return to main loop and
1559 * wait until we can read in more bytes. */
1563 ptr = strchr( s->buffer, '\n' );
1568 Log( LOG_DEBUG, "Got result from resolver: \"%s\" (%d bytes), stage %d.", s->buffer, len, s->stage );
1571 /* Okay, we got a complete result: this is a host name for outgoing
1572 * connections and a host name or IDENT user name (if enabled) for
1573 * incoming connections.*/
1574 if( My_Connections[i].sock > NONE )
1576 /* Incoming connection. Search client ... */
1577 c = Client_GetFromConn( i );
1578 assert( c != NULL );
1580 /* Only update client information of unregistered clients */
1581 if( Client_Type( c ) == CLIENT_UNKNOWN )
1584 case 0: /* host name */
1585 strlcpy( My_Connections[i].host, s->buffer, sizeof( My_Connections[i].host ));
1586 Client_SetHostname( c, s->buffer );
1588 /* clean up buffer for IDENT result */
1589 len = strlen( s->buffer ) + 1;
1590 assert((size_t) len <= sizeof( s->buffer ));
1591 memmove( s->buffer, s->buffer + len, sizeof( s->buffer ) - len );
1592 assert(len <= s->bufpos );
1595 /* Don't close pipe and clean up, but
1596 * instead wait for IDENT result */
1600 case 1: /* IDENT user name */
1603 Log( LOG_INFO, "IDENT lookup for connection %ld: \"%s\".", i, s->buffer );
1604 Client_SetUser( c, s->buffer, true );
1606 else Log( LOG_INFO, "IDENT lookup for connection %ld: no result.", i );
1610 Log( LOG_ERR, "Resolver: got result for unknown stage %d!?", s->stage );
1614 else Log( LOG_DEBUG, "Resolver: discarding result for already registered connection %d.", i );
1619 /* Outgoing connection (server link): set the IP address
1620 * so that we can connect to it in the main loop. */
1622 /* Search server ... */
1623 n = Conf_GetServer( i );
1626 strlcpy( Conf_Server[n].ip, s->buffer, sizeof( Conf_Server[n].ip ));
1630 FreeRes_stat( &My_Connections[i] );
1632 /* Reset penalty time */
1633 Conn_ResetPenalty( i );
1634 } /* Read_Resolver_Result */
1638 Simple_Message( int Sock, char *Msg )
1640 char buf[COMMAND_LEN];
1641 /* Write "simple" message to socket, without using compression
1642 * or even the connection write buffers. Used e.g. for error
1643 * messages by New_Connection(). */
1644 assert( Sock > NONE );
1645 assert( Msg != NULL );
1647 strlcpy( buf, Msg, sizeof buf - 2);
1648 strlcat( buf, "\r\n", sizeof buf);
1649 (void)write( Sock, buf, strlen( buf ) );
1650 } /* Simple_Error */
1654 Count_Connections( struct sockaddr_in addr_in )
1659 for( i = 0; i < Pool_Size; i++ )
1661 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].addr.sin_addr.s_addr == addr_in.sin_addr.s_addr )) cnt++;
1664 } /* Count_Connections */