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.166 2005/07/28 16:13:09 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 ));
97 LOCAL int NewListener PARAMS(( const UINT16 Port ));
99 static array My_Listeners;
102 int allow_severity = LOG_INFO;
103 int deny_severity = LOG_ERR;
107 static void cb_clientserver PARAMS((int sock, short what));
110 cb_listen(int sock, short irrelevant)
113 New_Connection( sock );
118 cb_connserver(int sock, UNUSED short what)
123 CONN_ID idx = Socket2Index( sock );
126 Log(LOG_DEBUG, "cb_connserver wants to write on unknown socket?!");
132 assert( what & IO_WANTWRITE);
134 /* connect() finished, get result. */
135 sock_len = sizeof( err );
136 res = getsockopt( My_Connections[idx].sock, SOL_SOCKET, SO_ERROR, &err, &sock_len );
137 assert( sock_len == sizeof( err ));
139 /* Fehler aufgetreten? */
140 if(( res != 0 ) || ( err != 0 )) {
142 Log( LOG_CRIT, "getsockopt (connection %d): %s!", idx, strerror( errno ));
144 Log( LOG_CRIT, "Can't connect socket to \"%s:%d\" (connection %d): %s!",
145 My_Connections[idx].host, Conf_Server[Conf_GetServer( idx )].port,
146 idx, strerror( err ));
148 /* Clean up socket, connection and client structures */
149 c = Client_GetFromConn( idx );
150 if( c ) Client_DestroyNow( c );
151 io_close( My_Connections[idx].sock );
152 Init_Conn_Struct( idx );
154 /* Bei Server-Verbindungen lasttry-Zeitpunkt auf "jetzt" setzen */
155 Conf_Server[Conf_GetServer( idx )].lasttry = time( NULL );
156 Conf_UnsetServer( idx );
160 Conn_OPTION_DEL( &My_Connections[idx], CONN_ISCONNECTING );
162 Log( LOG_INFO, "Connection %d with \"%s:%d\" established. Now logging in ...", idx,
163 My_Connections[idx].host, Conf_Server[Conf_GetServer( idx )].port );
165 io_event_setcb( My_Connections[idx].sock, cb_clientserver);
166 io_event_add( My_Connections[idx].sock, IO_WANTREAD|IO_WANTWRITE);
168 /* Send PASS and SERVER command to peer */
169 Conn_WriteStr( idx, "PASS %s %s", Conf_Server[Conf_GetServer( idx )].pwd_out, NGIRCd_ProtoID );
170 Conn_WriteStr( idx, "SERVER %s :%s", Conf_ServerName, Conf_ServerInfo );
175 cb_clientserver(int sock, short what)
177 CONN_ID idx = Socket2Index( sock );
180 Log(LOG_WARNING, "WTF: cb_clientserver wants to write on unknown socket?!");
186 if (what & IO_WANTREAD)
189 if (what & IO_WANTWRITE)
195 FreeRes_stat( CONNECTION *c )
198 assert( c->res_stat != NULL );
200 if (!c->res_stat) return;
202 io_close( c->res_stat->pipe[0] );
204 array_free(&c->res_stat->buffer);
213 /* Modul initialisieren: statische Strukturen "ausnullen". */
217 /* Speicher fuer Verbindungs-Pool anfordern */
218 Pool_Size = CONNECTION_POOL;
219 if( Conf_MaxConnections > 0 )
221 /* konfiguriertes Limit beachten */
222 if( Pool_Size > Conf_MaxConnections ) Pool_Size = Conf_MaxConnections;
224 My_Connections = (CONNECTION *) calloc( Pool_Size, sizeof( CONNECTION ) );
225 if( ! My_Connections )
227 /* Speicher konnte nicht alloziert werden! */
228 Log( LOG_EMERG, "Can't allocate memory! [Conn_Init]" );
232 Log( LOG_DEBUG, "Allocated connection pool for %d items (%ld bytes).", Pool_Size, sizeof( CONNECTION ) * Pool_Size );
235 array_free( &My_Listeners );
237 /* Groesster File-Descriptor fuer select() */
240 /* Connection-Struktur initialisieren */
241 for( i = 0; i < Pool_Size; i++ ) Init_Conn_Struct( i );
243 /* Global write counter */
251 /* Modul abmelden: alle noch offenen Connections
252 * schliessen und freigeben. */
257 Log( LOG_DEBUG, "Shutting down all connections ..." );
260 Conn_ExitListeners();
262 /* Sockets schliessen */
263 for( idx = 0; idx < Pool_Size; idx++ ) {
264 if( My_Connections[idx].sock > NONE ) {
265 Conn_Close( idx, NULL, NGIRCd_SignalRestart ?
266 "Server going down (restarting)":"Server going down", true );
271 free( My_Connections );
272 My_Connections = NULL;
274 io_library_shutdown();
279 Conn_InitListeners( void )
281 /* Initialize ports on which the server should accept connections */
286 if (!io_library_init(CONNECTION_POOL)) {
287 Log(LOG_EMERG, "Cannot initialize IO routines: %s", strerror(errno));
292 for( i = 0; i < Conf_ListenPorts_Count; i++ ) {
293 fd = NewListener( Conf_ListenPorts[i] );
295 Log( LOG_ERR, "Can't listen on port %u!", (unsigned int) Conf_ListenPorts[i] );
298 if (!io_event_create( fd, IO_WANTREAD, cb_listen )) {
299 Log( LOG_ERR, "io_event_create(): Could not add listening fd %d (port %u): %s!",
300 fd, (unsigned int) Conf_ListenPorts[i], strerror(errno));
307 } /* Conn_InitListeners */
311 Conn_ExitListeners( void )
313 /* Close down all listening sockets */
315 unsigned int arraylen;
317 Rendezvous_UnregisterListeners( );
320 arraylen = array_length(&My_Listeners, sizeof (int));
321 Log( LOG_INFO, "Shutting down all listening sockets (%d)...", arraylen );
323 fd = (int*) array_get(&My_Listeners, sizeof (int), arraylen);
327 Log( LOG_DEBUG, "Listening socket %d closed.", *fd );
329 Log( LOG_DEBUG, "array_get pos %d returned NULL", arraylen );
333 array_free(&My_Listeners);
334 } /* Conn_ExitListeners */
337 /* return new listening port file descriptor or -1 on failure */
339 NewListener( const UINT16 Port )
341 /* Create new listening socket on specified port */
343 struct sockaddr_in addr;
344 struct in_addr inaddr;
347 char name[CLIENT_ID_LEN], *info;
350 /* Server-"Listen"-Socket initialisieren */
351 memset( &addr, 0, sizeof( addr ));
352 memset( &inaddr, 0, sizeof( inaddr ));
353 addr.sin_family = AF_INET;
354 addr.sin_port = htons( Port );
355 if( Conf_ListenAddress[0] )
357 #ifdef HAVE_INET_ATON
358 if( inet_aton( Conf_ListenAddress, &inaddr ) == 0 )
360 inaddr.s_addr = inet_addr( Conf_ListenAddress );
361 if( inaddr.s_addr == (unsigned)-1 )
364 Log( LOG_CRIT, "Can't listen on %s:%u: can't convert ip address %s!", Conf_ListenAddress, Port, Conf_ListenAddress );
368 else inaddr.s_addr = htonl( INADDR_ANY );
369 addr.sin_addr = inaddr;
371 /* Socket erzeugen */
372 sock = socket( PF_INET, SOCK_STREAM, 0);
375 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
379 if( ! Init_Socket( sock )) return -1;
382 if( bind( sock, (struct sockaddr *)&addr, (socklen_t)sizeof( addr )) != 0 )
384 Log( LOG_CRIT, "Can't bind socket: %s!", strerror( errno ));
389 /* in "listen mode" gehen :-) */
390 if( listen( sock, 10 ) != 0 )
392 Log( LOG_CRIT, "Can't listen on soecket: %s!", strerror( errno ));
397 /* Neuen Listener in Strukturen einfuegen */
398 if (!array_catb( &My_Listeners,(char*) &sock, sizeof(int) )) {
399 Log( LOG_CRIT, "Can't add socket to My_Listeners array: %s!", strerror( errno ));
404 if( Conf_ListenAddress[0]) Log( LOG_INFO, "Now listening on %s:%d (socket %d).", Conf_ListenAddress, Port, sock );
405 else Log( LOG_INFO, "Now listening on 0.0.0.0:%d (socket %d).", Port, sock );
408 /* Get best server description text */
409 if( ! Conf_ServerInfo[0] ) info = Conf_ServerName;
412 /* Use server info string */
414 if( Conf_ServerInfo[0] == '[' )
416 /* Cut off leading hostname part in "[]" */
417 info = strchr( Conf_ServerInfo, ']' );
421 while( *info == ' ' ) info++;
424 if( ! info ) info = Conf_ServerInfo;
427 /* Add port number to description if non-standard */
428 if( Port != 6667 ) snprintf( name, sizeof( name ), "%s (port %u)", info, Port );
429 else strlcpy( name, info, sizeof( name ));
431 /* Register service */
432 Rendezvous_Register( name, MDNS_TYPE, Port );
441 /* "Main Loop.": Loop until a signal (for shutdown or restart) arrives.
442 * Call io_dispatch() to check for read/writeable sockets every second
443 * Wait for status change on pending connections (e.g: when the hostname has been resolved)
444 * check for penalty/timeouts
445 * handle input buffers
448 unsigned int wdatalen;
453 start = time( NULL );
454 while(( ! NGIRCd_SignalQuit ) && ( ! NGIRCd_SignalRestart ))
459 Rendezvous_Handler( );
462 /* Should the configuration be reloaded? */
463 if( NGIRCd_SignalRehash ) NGIRCd_Rehash( );
465 /* Check configured servers and established links */
467 Check_Connections( );
471 /* noch volle Lese-Buffer suchen */
472 for( i = 0; i < Pool_Size; i++ )
474 if(( My_Connections[i].sock > NONE ) && ( array_bytes(&My_Connections[i].rbuf) > 0 ) &&
475 ( My_Connections[i].delaytime < t ))
477 /* Kann aus dem Buffer noch ein Befehl extrahiert werden? */
478 if (Handle_Buffer( i )) timeout = false;
482 /* noch volle Schreib-Puffer suchen */
483 for( i = 0; i < Pool_Size; i++ ) {
484 if ( My_Connections[i].sock <= NONE )
487 wdatalen = array_bytes(&My_Connections[i].wbuf);
490 if (( wdatalen > 0 ) || ( array_bytes(&My_Connections[i].zip.wbuf)> 0 ))
495 /* Socket der Verbindung in Set aufnehmen */
496 io_event_add( My_Connections[i].sock, IO_WANTWRITE );
500 /* von welchen Sockets koennte gelesen werden? */
501 for (i = 0; i < Pool_Size; i++ ) {
502 if ( My_Connections[i].sock <= NONE )
505 if ( My_Connections[i].res_stat ) {
506 /* wait for completion of Resolver Sub-Process */
507 io_event_del( My_Connections[i].sock, IO_WANTREAD );
511 if ( Conn_OPTION_ISSET( &My_Connections[i], CONN_ISCONNECTING ))
512 continue; /* wait for completion of connect() */
514 if( My_Connections[i].delaytime > t ) {
515 /* Fuer die Verbindung ist eine "Penalty-Zeit" gesetzt */
516 io_event_del( My_Connections[i].sock, IO_WANTREAD );
519 io_event_add( My_Connections[i].sock, IO_WANTREAD );
522 /* Timeout initialisieren */
524 if( timeout ) tv.tv_sec = 1;
527 /* Auf Aktivitaet warten */
528 i = io_dispatch( &tv );
529 if (i == -1 && errno != EINTR ) {
530 Log(LOG_EMERG, "Conn_Handler(): io_dispatch(): %s!", strerror(errno));
531 Log(LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE_NAME);
536 if( NGIRCd_SignalQuit ) Log( LOG_NOTICE|LOG_snotice, "Server going down NOW!" );
537 else if( NGIRCd_SignalRestart ) Log( LOG_NOTICE|LOG_snotice, "Server restarting NOW!" );
542 * Write a text string into the socket of a connection.
543 * This function automatically appends CR+LF to the string and validates that
544 * the result is a valid IRC message (oversized messages are shortened, for
545 * example). Then it calls the Conn_Write() function to do the actual sending.
546 * @param Idx Index fo the connection.
547 * @param Format Format string, see printf().
548 * @return true on success, false otherwise.
552 Conn_WriteStr( CONN_ID Idx, char *Format, ... )
555 Conn_WriteStr( Idx, Format, va_alist )
561 char buffer[COMMAND_LEN];
565 assert( Idx > NONE );
566 assert( Format != NULL );
569 va_start( ap, Format );
573 if (vsnprintf( buffer, COMMAND_LEN - 2, Format, ap ) >= COMMAND_LEN - 2 ) {
575 * The string that should be written to the socket is longer
576 * than the allowed size of COMMAND_LEN bytes (including both
577 * the CR and LF characters). This can be caused by the
578 * IRC_WriteXXX() functions when the prefix of this server had
579 * to be added to an already "quite long" command line which
580 * has been received from a regular IRC client, for example.
582 * We are not allowed to send such "oversized" messages to
583 * other servers and clients, see RFC 2812 2.3 and 2813 3.3
584 * ("these messages SHALL NOT exceed 512 characters in length,
585 * counting all characters including the trailing CR-LF").
587 * So we have a big problem here: we should send more bytes
588 * to the network than we are allowed to and we don't know
589 * the originator (any more). The "old" behaviour of blaming
590 * the receiver ("next hop") is a bad idea (it could be just
591 * an other server only routing the message!), so the only
592 * option left is to shorten the string and to hope that the
593 * result is still somewhat useful ...
597 strcpy (buffer + sizeof(buffer) - strlen(CUT_TXTSUFFIX) - 2 - 1,
603 Log(LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer);
606 strlcat( buffer, "\r\n", sizeof( buffer ));
607 ok = Conn_Write( Idx, buffer, strlen( buffer ));
608 My_Connections[Idx].msg_out++;
612 } /* Conn_WriteStr */
616 Conn_Write( CONN_ID Idx, char *Data, unsigned int Len )
618 /* Daten in Socket schreiben. Bei "fatalen" Fehlern wird
619 * der Client disconnectiert und false geliefert. */
621 assert( Idx > NONE );
622 assert( Data != NULL );
625 /* Ist der entsprechende Socket ueberhaupt noch offen? In einem
626 * "Handler-Durchlauf" kann es passieren, dass dem nicht mehr so
627 * ist, wenn einer von mehreren Conn_Write()'s fehlgeschlagen ist.
628 * In diesem Fall wird hier einfach ein Fehler geliefert. */
629 if( My_Connections[Idx].sock <= NONE )
632 Log( LOG_DEBUG, "Skipped write on closed socket (connection %d).", Idx );
637 /* Pruefen, ob im Schreibpuffer genuegend Platz ist. Ziel ist es,
638 * moeglichts viel im Puffer zu haben und _nicht_ gleich alles auf den
639 * Socket zu schreiben (u.a. wg. Komprimierung). */
640 if( array_bytes(&My_Connections[Idx].wbuf) >= WRITEBUFFER_LEN) {
641 /* Der Puffer ist dummerweise voll. Jetzt versuchen, den Puffer
642 * zu schreiben, wenn das nicht klappt, haben wir ein Problem ... */
643 if( ! Handle_Write( Idx )) return false;
645 /* check again: if our writebuf is twice als large as the initial limit: Kill connection */
646 if( array_bytes(&My_Connections[Idx].wbuf) >= (WRITEBUFFER_LEN*2)) {
647 Log( LOG_NOTICE, "Write buffer overflow (connection %d)!", Idx );
648 Conn_Close( Idx, "Write buffer overflow!", NULL, false );
654 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
655 /* Daten komprimieren und in Puffer kopieren */
656 if( ! Zip_Buffer( Idx, Data, Len )) return false;
661 /* Daten in Puffer kopieren */
662 if (!array_catb( &My_Connections[Idx].wbuf, Data, Len ))
665 My_Connections[Idx].bytes_out += Len;
668 /* Adjust global write counter */
676 Conn_Close( CONN_ID Idx, char *LogMsg, char *FwdMsg, bool InformClient )
678 /* Close connection. Open pipes of asyncronous resolver
679 * sub-processes are closed down. */
685 double in_z_k, out_z_k;
689 assert( Idx > NONE );
691 /* Is this link already shutting down? */
692 if( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ISCLOSING )) {
693 /* Conn_Close() has been called recursively for this link;
694 * probabe reason: Handle_Write() failed -- see below. */
696 Log( LOG_DEBUG, "Recursive request to close connection: %d", Idx );
701 assert( My_Connections[Idx].sock > NONE );
703 /* Mark link as "closing" */
704 Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCLOSING );
706 if( LogMsg ) txt = LogMsg;
708 if( ! txt ) txt = "Reason unknown";
710 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 ));
712 /* Search client, if any */
713 c = Client_GetFromConn( Idx );
715 /* Should the client be informed? */
719 /* Send statistics to client if registered as user: */
720 if(( c != NULL ) && ( Client_Type( c ) == CLIENT_USER ))
722 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 );
726 /* Send ERROR to client (see RFC!) */
727 if( FwdMsg ) Conn_WriteStr( Idx, "ERROR :%s", FwdMsg );
728 else Conn_WriteStr( Idx, "ERROR :Closing connection." );
731 /* Try to write out the write buffer */
732 (void)Handle_Write( Idx );
734 /* Shut down socket */
735 if( ! io_close( My_Connections[Idx].sock ))
737 /* Oops, we can't close the socket!? This is ... ugly! */
738 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 ));
741 /* Mark socket as invalid: */
742 My_Connections[Idx].sock = NONE;
744 /* If there is still a client, unregister it now */
745 if( c ) Client_Destroy( c, LogMsg, FwdMsg, true );
747 /* Calculate statistics and log information */
748 in_k = (double)My_Connections[Idx].bytes_in / 1024;
749 out_k = (double)My_Connections[Idx].bytes_out / 1024;
751 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
752 in_z_k = (double)My_Connections[Idx].zip.bytes_in / 1024;
753 out_z_k = (double)My_Connections[Idx].zip.bytes_out / 1024;
754 in_p = (int)(( in_k * 100 ) / in_z_k );
755 out_p = (int)(( out_k * 100 ) / out_z_k );
756 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 );
761 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 );
764 /* Is there a resolver sub-process running? */
765 if( My_Connections[Idx].res_stat )
766 FreeRes_stat( &My_Connections[Idx] );
768 /* Servers: Modify time of next connect attempt? */
769 Conf_UnsetServer( Idx );
772 /* Clean up zlib, if link was compressed */
773 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
774 inflateEnd( &My_Connections[Idx].zip.in );
775 deflateEnd( &My_Connections[Idx].zip.out );
776 array_free(&My_Connections[Idx].zip.rbuf);
777 array_free(&My_Connections[Idx].zip.wbuf);
781 array_free(&My_Connections[Idx].rbuf);
782 array_free(&My_Connections[Idx].wbuf);
783 /* Clean up connection structure (=free it) */
784 Init_Conn_Struct( Idx );
787 Log( LOG_DEBUG, "Shutdown of connection %d completed.", Idx );
793 Conn_SyncServerStruct( void )
795 /* Synchronize server structures (connection IDs):
796 * connections <-> configuration */
802 for( i = 0; i < Pool_Size; i++ )
804 /* Established connection? */
805 if( My_Connections[i].sock <= NONE ) continue;
807 /* Server connection? */
808 client = Client_GetFromConn( i );
809 if(( ! client ) || ( Client_Type( client ) != CLIENT_SERVER )) continue;
811 for( c = 0; c < MAX_SERVERS; c++ )
813 /* Configured server? */
814 if( ! Conf_Server[c].host[0] ) continue;
817 if( strcmp( Conf_Server[c].name, Client_ID( client )) == 0 ) Conf_Server[c].conn_id = i;
820 } /* SyncServerStruct */
824 Handle_Write( CONN_ID Idx )
826 /* Daten aus Schreibpuffer versenden bzw. Connection aufbauen */
829 unsigned int wdatalen;
831 Log(LOG_DEBUG, "Handle_Write");
832 assert( Idx > NONE );
833 if ( My_Connections[Idx].sock < 0 ) {
834 Log(LOG_WARNING, "Handle_Write() on closed socket, idx %d", Idx);
837 assert( My_Connections[Idx].sock > NONE );
840 wdatalen = array_bytes(&My_Connections[Idx].wbuf );
842 if(( wdatalen == 0 ) && ( ! array_bytes(&My_Connections[Idx].zip.wbuf))) {
843 io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
847 /* write buffer empty, but not compression buf? -> flush compression buf. */
848 if( wdatalen == 0 ) Zip_Flush( Idx );
850 if( wdatalen == 0 ) {
851 io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
856 wdatalen = array_bytes(&My_Connections[Idx].wbuf ); /* Zip_Flush may change wbuf */
857 len = write( My_Connections[Idx].sock, array_start(&My_Connections[Idx].wbuf), wdatalen );
859 if( errno == EAGAIN || errno == EINTR)
862 Log( LOG_ERR, "Write error on connection %d (socket %d): %s!", Idx,
863 My_Connections[Idx].sock, strerror( errno ));
864 Conn_Close( Idx, "Write error!", NULL, false );
868 /* move any data not yet written to beginning */
869 array_moveleft(&My_Connections[Idx].wbuf, 1, len);
876 New_Connection( int Sock )
878 /* Neue Client-Verbindung von Listen-Socket annehmen und
879 * CLIENT-Struktur anlegen. */
882 struct request_info req;
884 struct sockaddr_in new_addr;
885 int new_sock, new_sock_len;
892 assert( Sock > NONE );
893 /* Connection auf Listen-Socket annehmen */
894 new_sock_len = sizeof( new_addr );
895 new_sock = accept( Sock, (struct sockaddr *)&new_addr, (socklen_t *)&new_sock_len );
898 Log( LOG_CRIT, "Can't accept connection: %s!", strerror( errno ));
903 /* Validate socket using TCP Wrappers */
904 request_init( &req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock, RQ_CLIENT_SIN, &new_addr, NULL );
906 if( ! hosts_access( &req ))
909 Log( deny_severity, "Refused connection from %s (by TCP Wrappers)!", inet_ntoa( new_addr.sin_addr ));
910 Simple_Message( new_sock, "ERROR :Connection refused" );
916 /* Socket initialisieren */
917 Init_Socket( new_sock );
919 /* Check IP-based connection limit */
920 cnt = Count_Connections( new_addr );
921 if(( Conf_MaxConnectionsIP > 0 ) && ( cnt >= Conf_MaxConnectionsIP ))
923 /* Access denied, too many connections from this IP address! */
924 Log( LOG_ERR, "Refused connection from %s: too may connections (%ld) from this IP address!", inet_ntoa( new_addr.sin_addr ), cnt);
925 Simple_Message( new_sock, "ERROR :Connection refused, too many connections from your IP address!" );
930 /* Freie Connection-Struktur suchen */
931 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
932 if( idx >= Pool_Size )
934 new_size = Pool_Size + CONNECTION_POOL;
936 /* Im bisherigen Pool wurde keine freie Connection-Struktur mehr gefunden.
937 * Wenn erlaubt und moeglich muss nun der Pool vergroessert werden: */
939 if( Conf_MaxConnections > 0 )
941 /* Es ist ein Limit konfiguriert */
942 if( Pool_Size >= Conf_MaxConnections )
944 /* Mehr Verbindungen duerfen wir leider nicht mehr annehmen ... */
945 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached!", Pool_Size );
946 Simple_Message( new_sock, "ERROR :Connection limit reached" );
950 if( new_size > Conf_MaxConnections ) new_size = Conf_MaxConnections;
952 if( new_size < Pool_Size )
954 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached -- overflow!", Pool_Size );
955 Simple_Message( new_sock, "ERROR :Connection limit reached" );
960 ptr = (POINTER *)realloc( My_Connections, sizeof( CONNECTION ) * new_size );
962 Log( LOG_EMERG, "Can't allocate memory! [New_Connection]" );
963 Simple_Message( new_sock, "ERROR: Internal error" );
969 Log( LOG_DEBUG, "Allocated new connection pool for %ld items (%ld bytes). [realloc()]", new_size, sizeof( CONNECTION ) * new_size );
972 /* Adjust pointer to new block */
973 My_Connections = (CONNECTION *)ptr;
975 /* Initialize new items */
976 for( idx = Pool_Size; idx < new_size; idx++ ) Init_Conn_Struct( idx );
979 /* Adjust new pool size */
980 Pool_Size = new_size;
983 /* Client-Struktur initialisieren */
984 c = Client_NewLocal( idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWN, false );
986 Log( LOG_ALERT, "Can't accept connection: can't create client structure!" );
987 Simple_Message( new_sock, "ERROR :Internal error" );
992 /* Verbindung registrieren */
993 Init_Conn_Struct( idx );
994 My_Connections[idx].sock = new_sock;
995 My_Connections[idx].addr = new_addr;
997 /* Neuen Socket registrieren */
998 if (!io_event_create( new_sock, IO_WANTREAD, cb_clientserver)) {
999 Simple_Message( new_sock, "ERROR :Internal error" );
1000 Conn_Close( idx, "io_event_create() failed", NULL, false );
1004 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 );
1006 /* Hostnamen ermitteln */
1007 strlcpy( My_Connections[idx].host, inet_ntoa( new_addr.sin_addr ), sizeof( My_Connections[idx].host ));
1008 Client_SetHostname( c, My_Connections[idx].host );
1010 s = Resolve_Addr( &new_addr, My_Connections[idx].sock );
1012 s = Resolve_Addr( &new_addr );
1014 /* resolver process has been started */
1015 if( s ) My_Connections[idx].res_stat = s;
1017 /* Penalty-Zeit setzen */
1018 Conn_SetPenalty( idx, 4 );
1019 } /* New_Connection */
1023 Socket2Index( int Sock )
1025 /* zum Socket passende Connection suchen */
1029 assert( Sock > NONE );
1031 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == Sock ) break;
1033 if( idx >= Pool_Size )
1035 /* die Connection wurde vermutlich (wegen eines
1036 * Fehlers) bereits wieder abgebaut ... */
1038 Log( LOG_DEBUG, "Socket2Index: can't get connection for socket %d!", Sock );
1043 } /* Socket2Index */
1047 Read_Request( CONN_ID Idx )
1049 /* Daten von Socket einlesen und entsprechend behandeln.
1050 * Tritt ein Fehler auf, so wird der Socket geschlossen. */
1055 assert( Idx > NONE );
1056 assert( My_Connections[Idx].sock > NONE );
1059 if (( array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN ) ||
1060 ( array_bytes(&My_Connections[Idx].zip.rbuf) >= ZREADBUFFER_LEN ))
1062 if ( array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN )
1065 /* Der Lesepuffer ist voll */
1066 Log( LOG_ERR, "Receive buffer overflow (connection %d): %d bytes!", Idx,
1067 array_bytes(&My_Connections[Idx].rbuf));
1068 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1072 len = read( My_Connections[Idx].sock, readbuf, sizeof readbuf -1 );
1074 Log( LOG_INFO, "%s:%d (%s) is closing the connection ...",
1075 My_Connections[Idx].host, ntohs( My_Connections[Idx].addr.sin_port),
1076 inet_ntoa( My_Connections[Idx].addr.sin_addr ));
1077 Conn_Close( Idx, "Socket closed!", "Client closed connection", false );
1082 if( errno == EAGAIN ) return;
1083 Log( LOG_ERR, "Read error on connection %d (socket %d): %s!", Idx,
1084 My_Connections[Idx].sock, strerror( errno ));
1085 Conn_Close( Idx, "Read error!", "Client closed connection", false );
1089 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
1090 if (!array_catb( &My_Connections[Idx].zip.rbuf, readbuf, len)) {
1091 Log( LOG_ERR, "Could not append recieved data to zip input buffer (connn %d): %d bytes!", Idx, len );
1092 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1099 if (!array_cats( &My_Connections[Idx].rbuf, readbuf )) {
1100 Log( LOG_ERR, "Could not append recieved data to input buffer (connn %d): %d bytes!", Idx, len );
1101 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1105 /* Connection-Statistik aktualisieren */
1106 My_Connections[Idx].bytes_in += len;
1108 /* Timestamp aktualisieren */
1109 My_Connections[Idx].lastdata = time( NULL );
1111 Handle_Buffer( Idx );
1112 } /* Read_Request */
1116 Handle_Buffer( CONN_ID Idx )
1118 /* Handle Data in Connections Read-Buffer.
1119 * Return true if a reuqest was handled, false otherwise (also returned on errors). */
1125 bool action, result;
1133 if( My_Connections[Idx].delaytime > time( NULL )) return result;
1135 /* unpack compressed data */
1136 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP ))
1137 if( ! Unzip_Buffer( Idx )) return false;
1140 if (0 == array_bytes(&My_Connections[Idx].rbuf))
1143 if (!array_cat0_temporary(&My_Connections[Idx].rbuf)) /* make sure buf is NULL terminated */
1146 /* A Complete Request end with CR+LF, see RFC 2812. */
1147 ptr = strstr( array_start(&My_Connections[Idx].rbuf), "\r\n" );
1149 if( ptr ) delta = 2; /* complete request */
1152 /* Check for non-RFC-compliant request (only CR or LF)? Unfortunately,
1153 * there are quite a few clients that do this (incl. "mIRC" :-( */
1154 ptr1 = strchr( array_start(&My_Connections[Idx].rbuf), '\r' );
1155 ptr2 = strchr( array_start(&My_Connections[Idx].rbuf), '\n' );
1157 if( ptr1 && ptr2 ) ptr = ptr1 > ptr2 ? ptr2 : ptr1;
1158 else if( ptr1 ) ptr = ptr1;
1159 else if( ptr2 ) ptr = ptr2;
1167 /* End of request found */
1170 len = ( ptr - (char*) array_start(&My_Connections[Idx].rbuf)) + delta;
1172 if( len < 0 || len > ( COMMAND_LEN - 1 )) {
1173 /* Request must not exceed 512 chars (incl. CR+LF!), see
1174 * RFC 2812. Disconnect Client if this happens. */
1175 Log( LOG_ERR, "Request too long (connection %d): %d bytes (max. %d expected)!",
1176 Idx, array_bytes(&My_Connections[Idx].rbuf), COMMAND_LEN - 1 );
1177 Conn_Close( Idx, NULL, "Request too long", true );
1182 /* remember if stream is already compressed */
1183 old_z = My_Connections[Idx].options & CONN_ZIP;
1188 /* A Request was read */
1189 My_Connections[Idx].msg_in++;
1190 if( ! Parse_Request( Idx, (char*)array_start(&My_Connections[Idx].rbuf) )) return false;
1193 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1195 Log(LOG_DEBUG, "%d byte left in rbuf", array_bytes(&My_Connections[Idx].rbuf));
1200 if(( ! old_z ) && ( My_Connections[Idx].options & CONN_ZIP ) && ( array_bytes(&My_Connections[Idx].rbuf) > 0 ))
1202 /* The last Command activated Socket-Compression.
1203 * Data that was read after that needs to be copied to Unzip-buf
1204 * for decompression */
1205 if( array_bytes(&My_Connections[Idx].rbuf)> ZREADBUFFER_LEN ) {
1207 Log( LOG_ALERT, "Can't move receive buffer: No space left in unzip buffer (need %d bytes)!", array_bytes(&My_Connections[Idx].rbuf ));
1210 if (!array_copy( &My_Connections[Idx].zip.rbuf, &My_Connections[Idx].rbuf ))
1213 array_trunc(&My_Connections[Idx].rbuf);
1215 Log( LOG_DEBUG, "Moved already received data (%d bytes) to uncompression buffer.", array_bytes(&My_Connections[Idx].zip.rbuf));
1219 if( action ) result = true;
1223 } /* Handle_Buffer */
1227 Check_Connections( void )
1229 /* check if connections are alive. if not, play PING-PONG first.
1230 * if this doesn't help either, disconnect client. */
1234 for( i = 0; i < Pool_Size; i++ ) {
1235 if( My_Connections[i].sock == NONE ) continue;
1237 c = Client_GetFromConn( i );
1238 if( c && (( Client_Type( c ) == CLIENT_USER ) || ( Client_Type( c ) == CLIENT_SERVER ) || ( Client_Type( c ) == CLIENT_SERVICE )))
1240 /* connected User, Server or Service */
1241 if( My_Connections[i].lastping > My_Connections[i].lastdata ) {
1242 /* we already sent a ping */
1243 if( My_Connections[i].lastping < time( NULL ) - Conf_PongTimeout ) {
1246 Log( LOG_DEBUG, "Connection %d: Ping timeout: %d seconds.", i, Conf_PongTimeout );
1248 Conn_Close( i, NULL, "Ping timeout", true );
1251 else if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout ) {
1252 /* we need to sent a PING */
1254 Log( LOG_DEBUG, "Connection %d: sending PING ...", i );
1256 My_Connections[i].lastping = time( NULL );
1257 Conn_WriteStr( i, "PING :%s", Client_ID( Client_ThisServer( )));
1262 /* connection is not fully established yet */
1263 if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout )
1267 Log( LOG_DEBUG, "Connection %d timed out ...", i );
1269 Conn_Close( i, NULL, "Timeout", false );
1273 } /* Check_Connections */
1277 Check_Servers( void )
1279 /* Check if we can establish further server links */
1285 /* Serach all connections, are there results from the resolver? */
1286 for( idx = 0; idx < Pool_Size; idx++ )
1288 if( My_Connections[idx].sock != SERVER_WAIT ) continue;
1291 if( My_Connections[idx].res_stat == NULL ) New_Server( Conf_GetServer( idx ), idx );
1294 /* Check all configured servers */
1295 for( i = 0; i < MAX_SERVERS; i++ )
1297 /* Valid outgoing server which isn't already connected or disabled? */
1298 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;
1300 /* Is there already a connection in this group? */
1301 if( Conf_Server[i].group > NONE )
1303 for( n = 0; n < MAX_SERVERS; n++ )
1305 if( n == i ) continue;
1306 if(( Conf_Server[n].conn_id > NONE ) && ( Conf_Server[n].group == Conf_Server[i].group )) break;
1308 if( n < MAX_SERVERS ) continue;
1311 /* Check last connect attempt? */
1312 if( Conf_Server[i].lasttry > time( NULL ) - Conf_ConnectRetry ) continue;
1314 /* Okay, try to connect now */
1315 Conf_Server[i].lasttry = time( NULL );
1317 /* Search free connection structure */
1318 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
1319 if( idx >= Pool_Size )
1321 Log( LOG_ALERT, "Can't establist server connection: connection limit reached (%d)!", Pool_Size );
1325 Log( LOG_DEBUG, "Preparing connection %d for \"%s\" ...", idx, Conf_Server[i].host );
1328 /* Verbindungs-Struktur initialisieren */
1329 Init_Conn_Struct( idx );
1330 My_Connections[idx].sock = SERVER_WAIT;
1331 Conf_Server[i].conn_id = idx;
1333 /* Resolve Hostname. If this fails, try to use it as an IP address */
1334 strlcpy( Conf_Server[i].ip, Conf_Server[i].host, sizeof( Conf_Server[i].ip ));
1335 strlcpy( My_Connections[idx].host, Conf_Server[i].host, sizeof( My_Connections[idx].host ));
1336 s = Resolve_Name( Conf_Server[i].host );
1338 /* resolver process running? */
1339 if( s ) My_Connections[idx].res_stat = s;
1341 } /* Check_Servers */
1345 New_Server( int Server, CONN_ID Idx )
1347 /* Establish new server link */
1349 struct sockaddr_in new_addr;
1350 struct in_addr inaddr;
1354 assert( Server > NONE );
1355 assert( Idx > NONE );
1357 /* Did we get a valid IP address? */
1358 if( ! Conf_Server[Server].ip[0] ) {
1359 /* No. Free connection structure and abort: */
1360 Log( LOG_ERR, "Can't connect to \"%s\" (connection %d): ip address unknown!", Conf_Server[Server].host, Idx );
1364 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 );
1366 #ifdef HAVE_INET_ATON
1367 if( inet_aton( Conf_Server[Server].ip, &inaddr ) == 0 )
1369 memset( &inaddr, 0, sizeof( inaddr ));
1370 inaddr.s_addr = inet_addr( Conf_Server[Server].ip );
1371 if( inaddr.s_addr == (unsigned)-1 )
1374 /* Can't convert IP address */
1375 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 );
1379 memset( &new_addr, 0, sizeof( new_addr ));
1380 new_addr.sin_family = AF_INET;
1381 new_addr.sin_addr = inaddr;
1382 new_addr.sin_port = htons( Conf_Server[Server].port );
1384 new_sock = socket( PF_INET, SOCK_STREAM, 0 );
1385 if ( new_sock < 0 ) {
1386 /* Can't create socket */
1387 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
1391 if( ! Init_Socket( new_sock )) return;
1393 res = connect( new_sock, (struct sockaddr *)&new_addr, sizeof( new_addr ));
1394 if(( res != 0 ) && ( errno != EINPROGRESS )) {
1395 /* Can't connect socket */
1396 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1401 /* Client-Struktur initialisieren */
1402 c = Client_NewLocal( Idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWNSERVER, false );
1404 /* Can't create new client structure */
1405 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1410 Client_SetIntroducer( c, c );
1411 Client_SetToken( c, TOKEN_OUTBOUND );
1413 /* Register connection */
1414 My_Connections[Idx].sock = new_sock;
1415 My_Connections[Idx].addr = new_addr;
1416 strlcpy( My_Connections[Idx].host, Conf_Server[Server].host, sizeof( My_Connections[Idx].host ));
1418 /* Register new socket */
1419 if (!io_event_create( new_sock, IO_WANTWRITE, cb_connserver)) {
1420 Log( LOG_ALERT, "io_event_create(): could not add fd %d", strerror(errno));
1421 Conn_Close( Idx, "io_event_create() failed", NULL, false );
1426 Log( LOG_DEBUG, "Registered new connection %d on socket %d.", Idx, My_Connections[Idx].sock );
1428 Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCONNECTING );
1431 Init_Conn_Struct( Idx );
1432 Conf_Server[Server].conn_id = NONE;
1437 Init_Conn_Struct( CONN_ID Idx )
1439 time_t now = time( NULL );
1440 /* Connection-Struktur initialisieren */
1442 memset( &My_Connections[Idx], 0, sizeof ( CONNECTION ));
1443 My_Connections[Idx].sock = NONE;
1444 My_Connections[Idx].lastdata = now;
1445 My_Connections[Idx].lastprivmsg = now;
1446 } /* Init_Conn_Struct */
1450 Init_Socket( int Sock )
1452 /* Initialize socket (set options) */
1456 if (!io_setnonblock(Sock)) {
1457 Log( LOG_CRIT, "Can't enable non-blocking mode for socket: %s!", strerror( errno ));
1462 /* Don't block this port after socket shutdown */
1464 if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &value, (socklen_t)sizeof( value )) != 0 )
1466 Log( LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!", strerror( errno ));
1467 /* ignore this error */
1470 /* Set type of service (TOS) */
1471 #if defined(IP_TOS) && defined(IPTOS_LOWDELAY)
1472 value = IPTOS_LOWDELAY;
1474 Log( LOG_DEBUG, "Setting option IP_TOS on socket %d to IPTOS_LOWDELAY (%d).", Sock, value );
1476 if( setsockopt( Sock, SOL_IP, IP_TOS, &value, (socklen_t)sizeof( value )) != 0 )
1478 Log( LOG_ERR, "Can't set socket option IP_TOS: %s!", strerror( errno ));
1479 /* ignore this error */
1488 void Read_Resolver_Result( int r_fd )
1490 /* Read result of resolver sub-process from pipe and update the
1491 * apropriate connection/client structure(s): hostname and/or
1492 * IDENT user name.*/
1495 int bytes_read, i, n;
1500 char readbuf[HOST_LEN];
1502 Log( LOG_DEBUG, "Resolver: started, fd %d\n", r_fd );
1503 /* Search associated connection ... */
1504 for( i = 0; i < Pool_Size; i++ )
1506 if(( My_Connections[i].sock != NONE )
1507 && ( My_Connections[i].res_stat != NULL )
1508 && ( My_Connections[i].res_stat->pipe[0] == r_fd ))
1511 if( i >= Pool_Size )
1513 /* Ops, none found? Probably the connection has already
1514 * been closed!? We'll ignore that ... */
1517 Log( LOG_DEBUG, "Resolver: Got result for unknown connection!?" );
1522 /* Get resolver structure */
1523 s = My_Connections[i].res_stat;
1524 assert( s != NULL );
1526 /* Read result from pipe */
1527 bytes_read = read( r_fd, readbuf, sizeof readbuf -1 );
1528 if( bytes_read < 0 )
1531 Log( LOG_CRIT, "Resolver: Can't read result: %s!", strerror( errno ));
1532 FreeRes_stat( &My_Connections[i] );
1535 len = (unsigned int) bytes_read;
1536 readbuf[len] = '\0';
1537 if (!array_catb(&s->buffer, readbuf, len)) {
1538 Log( LOG_CRIT, "Resolver: Can't append result %s to buffer: %s", readbuf, strerror( errno ));
1539 FreeRes_stat(&My_Connections[i]);
1543 if (!array_cat0_temporary(&s->buffer)) {
1544 Log( LOG_CRIT, "Resolver: Can't append result %s to buffer: %s", readbuf, strerror( errno ));
1545 FreeRes_stat(&My_Connections[i]);
1549 /* If the result string is incomplete, return to main loop and
1550 * wait until we can read in more bytes. */
1554 bufptr = (char*) array_start(&s->buffer);
1555 assert(bufptr != NULL);
1556 ptr = strchr( bufptr, '\n' );
1561 Log( LOG_DEBUG, "Got result from resolver: \"%s\" (%u bytes read), stage %d.", bufptr, len, s->stage);
1564 /* Okay, we got a complete result: this is a host name for outgoing
1565 * connections and a host name or IDENT user name (if enabled) for
1566 * incoming connections.*/
1567 if( My_Connections[i].sock > NONE )
1569 /* Incoming connection. Search client ... */
1570 c = Client_GetFromConn( i );
1571 assert( c != NULL );
1573 /* Only update client information of unregistered clients */
1574 if( Client_Type( c ) == CLIENT_UNKNOWN )
1577 case 0: /* host name */
1578 strlcpy( My_Connections[i].host, bufptr, sizeof( My_Connections[i].host));
1580 Client_SetHostname( c, bufptr);
1582 /* clean up buffer for IDENT result */
1583 len = strlen(bufptr) + 1;
1584 assert(len <= array_bytes(&s->buffer));
1585 array_moveleft(&s->buffer, 1, len);
1587 /* Don't close pipe and clean up, but
1588 * instead wait for IDENT result */
1592 case 1: /* IDENT user name */
1593 if (array_bytes(&s->buffer)) {
1594 bufptr = (char*) array_start(&s->buffer);
1595 Log( LOG_INFO, "IDENT lookup for connection %ld: \"%s\".", i, bufptr);
1596 Client_SetUser( c, bufptr, true );
1598 else Log( LOG_INFO, "IDENT lookup for connection %ld: no result.", i );
1602 Log( LOG_ERR, "Resolver: got result for unknown stage %d!?", s->stage );
1606 else Log( LOG_DEBUG, "Resolver: discarding result for already registered connection %d.", i );
1611 /* Outgoing connection (server link): set the IP address
1612 * so that we can connect to it in the main loop. */
1614 /* Search server ... */
1615 n = Conf_GetServer( i );
1618 bufptr = (char*) array_start(&s->buffer);
1619 strlcpy( Conf_Server[n].ip, bufptr, sizeof( Conf_Server[n].ip ));
1623 FreeRes_stat( &My_Connections[i] );
1625 /* Reset penalty time */
1626 Conn_ResetPenalty( i );
1627 } /* Read_Resolver_Result */
1631 Simple_Message( int Sock, char *Msg )
1633 char buf[COMMAND_LEN];
1634 /* Write "simple" message to socket, without using compression
1635 * or even the connection write buffers. Used e.g. for error
1636 * messages by New_Connection(). */
1637 assert( Sock > NONE );
1638 assert( Msg != NULL );
1640 strlcpy( buf, Msg, sizeof buf - 2);
1641 strlcat( buf, "\r\n", sizeof buf);
1642 (void)write( Sock, buf, strlen( buf ) );
1643 } /* Simple_Error */
1647 Count_Connections( struct sockaddr_in addr_in )
1652 for( i = 0; i < Pool_Size; i++ )
1654 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].addr.sin_addr.s_addr == addr_in.sin_addr.s_addr )) cnt++;
1657 } /* Count_Connections */