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.176 2005/08/30 22:08:00 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 static bool Handle_Write PARAMS(( CONN_ID Idx ));
86 static int New_Connection PARAMS(( int Sock ));
87 static CONN_ID Socket2Index PARAMS(( int Sock ));
88 static void Read_Request PARAMS(( CONN_ID Idx ));
89 static bool Handle_Buffer PARAMS(( CONN_ID Idx ));
90 static void Check_Connections PARAMS(( void ));
91 static void Check_Servers PARAMS(( void ));
92 static void Init_Conn_Struct PARAMS(( CONN_ID Idx ));
93 static bool Init_Socket PARAMS(( int Sock ));
94 static void New_Server PARAMS(( int Server, CONN_ID Idx ));
95 static void Simple_Message PARAMS(( int Sock, char *Msg ));
96 static int Count_Connections PARAMS(( struct sockaddr_in addr ));
97 static int NewListener PARAMS(( const UINT16 Port ));
99 static array My_Listeners;
102 int allow_severity = LOG_INFO;
103 int deny_severity = LOG_ERR;
106 static void server_login PARAMS((CONN_ID idx));
108 static void cb_clientserver PARAMS((int sock, short what));
111 cb_listen(int sock, short irrelevant)
114 New_Connection( sock );
119 cb_connserver(int sock, UNUSED short what)
124 CONN_ID idx = Socket2Index( sock );
127 Log(LOG_DEBUG, "cb_connserver wants to write on unknown socket?!");
133 assert( what & IO_WANTWRITE);
135 /* connect() finished, get result. */
136 sock_len = sizeof( err );
137 res = getsockopt( My_Connections[idx].sock, SOL_SOCKET, SO_ERROR, &err, &sock_len );
138 assert( sock_len == sizeof( err ));
140 /* Fehler aufgetreten? */
141 if(( res != 0 ) || ( err != 0 )) {
143 Log( LOG_CRIT, "getsockopt (connection %d): %s!", idx, strerror( errno ));
145 Log( LOG_CRIT, "Can't connect socket to \"%s:%d\" (connection %d): %s!",
146 My_Connections[idx].host, Conf_Server[Conf_GetServer( idx )].port,
147 idx, strerror( err ));
149 /* Clean up socket, connection and client structures */
150 c = Client_GetFromConn( idx );
151 if( c ) Client_DestroyNow( c );
152 io_close( My_Connections[idx].sock );
153 Init_Conn_Struct( idx );
155 /* Bei Server-Verbindungen lasttry-Zeitpunkt auf "jetzt" setzen */
156 Conf_Server[Conf_GetServer( idx )].lasttry = time( NULL );
157 Conf_UnsetServer( idx );
161 Conn_OPTION_DEL( &My_Connections[idx], CONN_ISCONNECTING );
167 server_login(CONN_ID idx)
169 Log( LOG_INFO, "Connection %d with \"%s:%d\" established. Now logging in ...", idx,
170 My_Connections[idx].host, Conf_Server[Conf_GetServer( idx )].port );
172 io_event_setcb( My_Connections[idx].sock, cb_clientserver);
173 io_event_add( My_Connections[idx].sock, IO_WANTREAD|IO_WANTWRITE);
175 /* Send PASS and SERVER command to peer */
176 Conn_WriteStr( idx, "PASS %s %s", Conf_Server[Conf_GetServer( idx )].pwd_out, NGIRCd_ProtoID );
177 Conn_WriteStr( idx, "SERVER %s :%s", Conf_ServerName, Conf_ServerInfo );
182 cb_clientserver(int sock, short what)
184 CONN_ID idx = Socket2Index( sock );
187 Log(LOG_WARNING, "WTF: cb_clientserver wants to write on unknown socket?!");
193 if (what & IO_WANTREAD)
196 if (what & IO_WANTWRITE)
202 FreeRes_stat( CONNECTION *c )
205 assert( c->res_stat != NULL );
207 if (!c->res_stat) return;
209 io_close( c->res_stat->pipe[0] );
211 array_free(&c->res_stat->buffer);
220 /* Modul initialisieren: statische Strukturen "ausnullen". */
224 /* Speicher fuer Verbindungs-Pool anfordern */
225 Pool_Size = CONNECTION_POOL;
226 if( Conf_MaxConnections > 0 )
228 /* konfiguriertes Limit beachten */
229 if( Pool_Size > Conf_MaxConnections ) Pool_Size = Conf_MaxConnections;
231 My_Connections = (CONNECTION *) calloc( Pool_Size, sizeof( CONNECTION ) );
232 if( ! My_Connections )
234 /* Speicher konnte nicht alloziert werden! */
235 Log( LOG_EMERG, "Can't allocate memory! [Conn_Init]" );
239 Log( LOG_DEBUG, "Allocated connection pool for %d items (%ld bytes).", Pool_Size, sizeof( CONNECTION ) * Pool_Size );
242 array_free( &My_Listeners );
244 /* Groesster File-Descriptor fuer select() */
247 /* Connection-Struktur initialisieren */
248 for( i = 0; i < Pool_Size; i++ ) Init_Conn_Struct( i );
250 /* Global write counter */
258 /* Modul abmelden: alle noch offenen Connections
259 * schliessen und freigeben. */
264 Log( LOG_DEBUG, "Shutting down all connections ..." );
267 Conn_ExitListeners();
269 /* Sockets schliessen */
270 for( idx = 0; idx < Pool_Size; idx++ ) {
271 if( My_Connections[idx].sock > NONE ) {
272 Conn_Close( idx, NULL, NGIRCd_SignalRestart ?
273 "Server going down (restarting)":"Server going down", true );
278 free( My_Connections );
279 My_Connections = NULL;
281 io_library_shutdown();
286 ports_initlisteners(array *a, void (*func)(int,short))
288 unsigned int created = 0, len;
292 len = array_length(a, sizeof (UINT16));
293 port = array_start(a);
295 fd = NewListener( *port );
300 if (!io_event_create( fd, IO_WANTREAD, func )) {
301 Log( LOG_ERR, "io_event_create(): Could not add listening fd %d (port %u): %s!",
302 fd, (unsigned int) *port, strerror(errno));
316 Conn_InitListeners( void )
318 /* Initialize ports on which the server should accept connections */
320 unsigned int created;
322 if (!io_library_init(CONNECTION_POOL)) {
323 Log(LOG_EMERG, "Cannot initialize IO routines: %s", strerror(errno));
327 created = ports_initlisteners(&Conf_ListenPorts, cb_listen);
330 } /* Conn_InitListeners */
334 Conn_ExitListeners( void )
336 /* Close down all listening sockets */
338 unsigned int arraylen;
340 Rendezvous_UnregisterListeners( );
343 arraylen = array_length(&My_Listeners, sizeof (int));
344 Log( LOG_INFO, "Shutting down all listening sockets (%d)...", arraylen );
346 fd = (int*) array_get(&My_Listeners, sizeof (int), arraylen);
350 Log( LOG_DEBUG, "Listening socket %d closed.", *fd );
352 Log( LOG_DEBUG, "array_get pos %d returned NULL", arraylen );
356 array_free(&My_Listeners);
357 } /* Conn_ExitListeners */
360 /* return new listening port file descriptor or -1 on failure */
362 NewListener( const UINT16 Port )
364 /* Create new listening socket on specified port */
366 struct sockaddr_in addr;
367 struct in_addr inaddr;
370 char name[CLIENT_ID_LEN], *info;
373 /* Server-"Listen"-Socket initialisieren */
374 memset( &addr, 0, sizeof( addr ));
375 memset( &inaddr, 0, sizeof( inaddr ));
376 addr.sin_family = AF_INET;
377 addr.sin_port = htons( Port );
378 if( Conf_ListenAddress[0] )
380 #ifdef HAVE_INET_ATON
381 if( inet_aton( Conf_ListenAddress, &inaddr ) == 0 )
383 inaddr.s_addr = inet_addr( Conf_ListenAddress );
384 if( inaddr.s_addr == (unsigned)-1 )
387 Log( LOG_CRIT, "Can't listen on %s:%u: can't convert ip address %s!", Conf_ListenAddress, Port, Conf_ListenAddress );
391 else inaddr.s_addr = htonl( INADDR_ANY );
392 addr.sin_addr = inaddr;
394 /* Socket erzeugen */
395 sock = socket( PF_INET, SOCK_STREAM, 0);
398 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
402 if( ! Init_Socket( sock )) return -1;
405 if( bind( sock, (struct sockaddr *)&addr, (socklen_t)sizeof( addr )) != 0 )
407 Log( LOG_CRIT, "Can't bind socket: %s!", strerror( errno ));
412 /* in "listen mode" gehen :-) */
413 if( listen( sock, 10 ) != 0 )
415 Log( LOG_CRIT, "Can't listen on soecket: %s!", strerror( errno ));
420 /* Neuen Listener in Strukturen einfuegen */
421 if (!array_catb( &My_Listeners,(char*) &sock, sizeof(int) )) {
422 Log( LOG_CRIT, "Can't add socket to My_Listeners array: %s!", strerror( errno ));
427 if( Conf_ListenAddress[0]) Log( LOG_INFO, "Now listening on %s:%d (socket %d).", Conf_ListenAddress, Port, sock );
428 else Log( LOG_INFO, "Now listening on 0.0.0.0:%d (socket %d).", Port, sock );
431 /* Get best server description text */
432 if( ! Conf_ServerInfo[0] ) info = Conf_ServerName;
435 /* Use server info string */
437 if( Conf_ServerInfo[0] == '[' )
439 /* Cut off leading hostname part in "[]" */
440 info = strchr( Conf_ServerInfo, ']' );
444 while( *info == ' ' ) info++;
447 if( ! info ) info = Conf_ServerInfo;
450 /* Add port number to description if non-standard */
451 if( Port != 6667 ) snprintf( name, sizeof( name ), "%s (port %u)", info, Port );
452 else strlcpy( name, info, sizeof( name ));
454 /* Register service */
455 Rendezvous_Register( name, MDNS_TYPE, Port );
464 /* "Main Loop.": Loop until a signal (for shutdown or restart) arrives.
465 * Call io_dispatch() to check for read/writeable sockets every second
466 * Wait for status change on pending connections (e.g: when the hostname has been resolved)
467 * check for penalty/timeouts
468 * handle input buffers
471 unsigned int wdatalen;
476 start = time( NULL );
477 while(( ! NGIRCd_SignalQuit ) && ( ! NGIRCd_SignalRestart ))
482 Rendezvous_Handler( );
485 /* Should the configuration be reloaded? */
486 if( NGIRCd_SignalRehash ) NGIRCd_Rehash( );
488 /* Check configured servers and established links */
490 Check_Connections( );
494 /* noch volle Lese-Buffer suchen */
495 for( i = 0; i < Pool_Size; i++ )
497 if(( My_Connections[i].sock > NONE ) && ( array_bytes(&My_Connections[i].rbuf) > 0 ) &&
498 ( My_Connections[i].delaytime < t ))
500 /* Kann aus dem Buffer noch ein Befehl extrahiert werden? */
501 if (Handle_Buffer( i )) timeout = false;
505 /* noch volle Schreib-Puffer suchen */
506 for( i = 0; i < Pool_Size; i++ ) {
507 if ( My_Connections[i].sock <= NONE )
510 wdatalen = array_bytes(&My_Connections[i].wbuf);
513 if (( wdatalen > 0 ) || ( array_bytes(&My_Connections[i].zip.wbuf)> 0 ))
518 /* Socket der Verbindung in Set aufnehmen */
519 io_event_add( My_Connections[i].sock, IO_WANTWRITE );
523 /* von welchen Sockets koennte gelesen werden? */
524 for (i = 0; i < Pool_Size; i++ ) {
525 if ( My_Connections[i].sock <= NONE )
528 if ( My_Connections[i].res_stat ) {
529 /* wait for completion of Resolver Sub-Process */
530 io_event_del( My_Connections[i].sock, IO_WANTREAD );
534 if ( Conn_OPTION_ISSET( &My_Connections[i], CONN_ISCONNECTING ))
535 continue; /* wait for completion of connect() */
537 if( My_Connections[i].delaytime > t ) {
538 /* Fuer die Verbindung ist eine "Penalty-Zeit" gesetzt */
539 io_event_del( My_Connections[i].sock, IO_WANTREAD );
542 io_event_add( My_Connections[i].sock, IO_WANTREAD );
545 /* Timeout initialisieren */
547 if( timeout ) tv.tv_sec = 1;
550 /* Auf Aktivitaet warten */
551 i = io_dispatch( &tv );
552 if (i == -1 && errno != EINTR ) {
553 Log(LOG_EMERG, "Conn_Handler(): io_dispatch(): %s!", strerror(errno));
554 Log(LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE_NAME);
559 if( NGIRCd_SignalQuit ) Log( LOG_NOTICE|LOG_snotice, "Server going down NOW!" );
560 else if( NGIRCd_SignalRestart ) Log( LOG_NOTICE|LOG_snotice, "Server restarting NOW!" );
565 * Write a text string into the socket of a connection.
566 * This function automatically appends CR+LF to the string and validates that
567 * the result is a valid IRC message (oversized messages are shortened, for
568 * example). Then it calls the Conn_Write() function to do the actual sending.
569 * @param Idx Index fo the connection.
570 * @param Format Format string, see printf().
571 * @return true on success, false otherwise.
575 Conn_WriteStr( CONN_ID Idx, char *Format, ... )
578 Conn_WriteStr( Idx, Format, va_alist )
584 char buffer[COMMAND_LEN];
588 assert( Idx > NONE );
589 assert( Format != NULL );
592 va_start( ap, Format );
596 if (vsnprintf( buffer, COMMAND_LEN - 2, Format, ap ) >= COMMAND_LEN - 2 ) {
598 * The string that should be written to the socket is longer
599 * than the allowed size of COMMAND_LEN bytes (including both
600 * the CR and LF characters). This can be caused by the
601 * IRC_WriteXXX() functions when the prefix of this server had
602 * to be added to an already "quite long" command line which
603 * has been received from a regular IRC client, for example.
605 * We are not allowed to send such "oversized" messages to
606 * other servers and clients, see RFC 2812 2.3 and 2813 3.3
607 * ("these messages SHALL NOT exceed 512 characters in length,
608 * counting all characters including the trailing CR-LF").
610 * So we have a big problem here: we should send more bytes
611 * to the network than we are allowed to and we don't know
612 * the originator (any more). The "old" behaviour of blaming
613 * the receiver ("next hop") is a bad idea (it could be just
614 * an other server only routing the message!), so the only
615 * option left is to shorten the string and to hope that the
616 * result is still somewhat useful ...
620 strcpy (buffer + sizeof(buffer) - strlen(CUT_TXTSUFFIX) - 2 - 1,
626 Log(LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer);
629 strlcat( buffer, "\r\n", sizeof( buffer ));
630 ok = Conn_Write( Idx, buffer, strlen( buffer ));
631 My_Connections[Idx].msg_out++;
635 } /* Conn_WriteStr */
639 Conn_Write( CONN_ID Idx, char *Data, unsigned int Len )
641 /* Daten in Socket schreiben. Bei "fatalen" Fehlern wird
642 * der Client disconnectiert und false geliefert. */
644 assert( Idx > NONE );
645 assert( Data != NULL );
648 /* Ist der entsprechende Socket ueberhaupt noch offen? In einem
649 * "Handler-Durchlauf" kann es passieren, dass dem nicht mehr so
650 * ist, wenn einer von mehreren Conn_Write()'s fehlgeschlagen ist.
651 * In diesem Fall wird hier einfach ein Fehler geliefert. */
652 if( My_Connections[Idx].sock <= NONE )
655 Log( LOG_DEBUG, "Skipped write on closed socket (connection %d).", Idx );
660 /* Pruefen, ob im Schreibpuffer genuegend Platz ist. Ziel ist es,
661 * moeglichts viel im Puffer zu haben und _nicht_ gleich alles auf den
662 * Socket zu schreiben (u.a. wg. Komprimierung). */
663 if( array_bytes(&My_Connections[Idx].wbuf) >= WRITEBUFFER_LEN) {
664 /* Der Puffer ist dummerweise voll. Jetzt versuchen, den Puffer
665 * zu schreiben, wenn das nicht klappt, haben wir ein Problem ... */
666 if( ! Handle_Write( Idx )) return false;
668 /* check again: if our writebuf is twice als large as the initial limit: Kill connection */
669 if( array_bytes(&My_Connections[Idx].wbuf) >= (WRITEBUFFER_LEN*2)) {
670 Log( LOG_NOTICE, "Write buffer overflow (connection %d)!", Idx );
671 Conn_Close( Idx, "Write buffer overflow!", NULL, false );
677 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
678 /* Daten komprimieren und in Puffer kopieren */
679 if( ! Zip_Buffer( Idx, Data, Len )) return false;
684 /* Daten in Puffer kopieren */
685 if (!array_catb( &My_Connections[Idx].wbuf, Data, Len ))
688 My_Connections[Idx].bytes_out += Len;
691 /* Adjust global write counter */
699 Conn_Close( CONN_ID Idx, char *LogMsg, char *FwdMsg, bool InformClient )
701 /* Close connection. Open pipes of asyncronous resolver
702 * sub-processes are closed down. */
708 double in_z_k, out_z_k;
712 assert( Idx > NONE );
714 /* Is this link already shutting down? */
715 if( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ISCLOSING )) {
716 /* Conn_Close() has been called recursively for this link;
717 * probabe reason: Handle_Write() failed -- see below. */
719 Log( LOG_DEBUG, "Recursive request to close connection: %d", Idx );
724 assert( My_Connections[Idx].sock > NONE );
726 /* Mark link as "closing" */
727 Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCLOSING );
729 if( LogMsg ) txt = LogMsg;
731 if( ! txt ) txt = "Reason unknown";
733 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 ));
735 /* Search client, if any */
736 c = Client_GetFromConn( Idx );
738 /* Should the client be informed? */
741 /* Send statistics to client if registered as user: */
742 if ((c != NULL) && (Client_Type(c) == CLIENT_USER)) {
744 ":%s NOTICE %s :%sConnection statistics: client %.1f kb, server %.1f kb.",
745 Client_ID(Client_ThisServer()), Client_ID(c),
747 (double)My_Connections[Idx].bytes_in / 1024,
748 (double)My_Connections[Idx].bytes_out / 1024);
752 /* Send ERROR to client (see RFC!) */
754 Conn_WriteStr(Idx, "ERROR :%s", FwdMsg);
756 Conn_WriteStr(Idx, "ERROR :Closing connection.");
759 /* Try to write out the write buffer */
760 (void)Handle_Write( Idx );
762 /* Shut down socket */
763 if( ! io_close( My_Connections[Idx].sock ))
765 /* Oops, we can't close the socket!? This is ... ugly! */
766 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 ));
769 /* Mark socket as invalid: */
770 My_Connections[Idx].sock = NONE;
772 /* If there is still a client, unregister it now */
773 if( c ) Client_Destroy( c, LogMsg, FwdMsg, true );
775 /* Calculate statistics and log information */
776 in_k = (double)My_Connections[Idx].bytes_in / 1024;
777 out_k = (double)My_Connections[Idx].bytes_out / 1024;
779 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
780 in_z_k = (double)My_Connections[Idx].zip.bytes_in / 1024;
781 out_z_k = (double)My_Connections[Idx].zip.bytes_out / 1024;
782 in_p = (int)(( in_k * 100 ) / in_z_k );
783 out_p = (int)(( out_k * 100 ) / out_z_k );
784 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 );
789 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 );
792 /* Is there a resolver sub-process running? */
793 if( My_Connections[Idx].res_stat )
794 FreeRes_stat( &My_Connections[Idx] );
796 /* Servers: Modify time of next connect attempt? */
797 Conf_UnsetServer( Idx );
800 /* Clean up zlib, if link was compressed */
801 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
802 inflateEnd( &My_Connections[Idx].zip.in );
803 deflateEnd( &My_Connections[Idx].zip.out );
804 array_free(&My_Connections[Idx].zip.rbuf);
805 array_free(&My_Connections[Idx].zip.wbuf);
809 array_free(&My_Connections[Idx].rbuf);
810 array_free(&My_Connections[Idx].wbuf);
811 /* Clean up connection structure (=free it) */
812 Init_Conn_Struct( Idx );
815 Log( LOG_DEBUG, "Shutdown of connection %d completed.", Idx );
821 Conn_SyncServerStruct( void )
823 /* Synchronize server structures (connection IDs):
824 * connections <-> configuration */
830 for( i = 0; i < Pool_Size; i++ )
832 /* Established connection? */
833 if( My_Connections[i].sock <= NONE ) continue;
835 /* Server connection? */
836 client = Client_GetFromConn( i );
837 if(( ! client ) || ( Client_Type( client ) != CLIENT_SERVER )) continue;
839 for( c = 0; c < MAX_SERVERS; c++ )
841 /* Configured server? */
842 if( ! Conf_Server[c].host[0] ) continue;
845 if( strcmp( Conf_Server[c].name, Client_ID( client )) == 0 ) Conf_Server[c].conn_id = i;
848 } /* SyncServerStruct */
852 Handle_Write( CONN_ID Idx )
854 /* Daten aus Schreibpuffer versenden bzw. Connection aufbauen */
857 unsigned int wdatalen;
859 Log(LOG_DEBUG, "Handle_Write");
860 assert( Idx > NONE );
861 if ( My_Connections[Idx].sock < 0 ) {
862 Log(LOG_WARNING, "Handle_Write() on closed socket, idx %d", Idx);
865 assert( My_Connections[Idx].sock > NONE );
867 wdatalen = array_bytes(&My_Connections[Idx].wbuf );
869 if(( wdatalen == 0 ) && ( ! array_bytes(&My_Connections[Idx].zip.wbuf))) {
870 io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
874 /* write buffer empty, but not compression buf? -> flush compression buf. */
875 if( wdatalen == 0 ) Zip_Flush( Idx );
877 if( wdatalen == 0 ) {
878 io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
883 wdatalen = array_bytes(&My_Connections[Idx].wbuf ); /* Zip_Flush may change wbuf */
884 len = write( My_Connections[Idx].sock, array_start(&My_Connections[Idx].wbuf), wdatalen );
886 if( errno == EAGAIN || errno == EINTR)
889 Log( LOG_ERR, "Write error on connection %d (socket %d): %s!", Idx,
890 My_Connections[Idx].sock, strerror( errno ));
891 Conn_Close( Idx, "Write error!", NULL, false );
895 /* move any data not yet written to beginning */
896 array_moveleft(&My_Connections[Idx].wbuf, 1, len);
903 New_Connection( int Sock )
905 /* Neue Client-Verbindung von Listen-Socket annehmen und
906 * CLIENT-Struktur anlegen. */
909 struct request_info req;
911 struct sockaddr_in new_addr;
912 int new_sock, new_sock_len;
919 assert( Sock > NONE );
920 /* Connection auf Listen-Socket annehmen */
921 new_sock_len = sizeof( new_addr );
922 new_sock = accept( Sock, (struct sockaddr *)&new_addr, (socklen_t *)&new_sock_len );
925 Log( LOG_CRIT, "Can't accept connection: %s!", strerror( errno ));
930 /* Validate socket using TCP Wrappers */
931 request_init( &req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock, RQ_CLIENT_SIN, &new_addr, NULL );
933 if( ! hosts_access( &req ))
936 Log( deny_severity, "Refused connection from %s (by TCP Wrappers)!", inet_ntoa( new_addr.sin_addr ));
937 Simple_Message( new_sock, "ERROR :Connection refused" );
943 /* Socket initialisieren */
944 Init_Socket( new_sock );
946 /* Check IP-based connection limit */
947 cnt = Count_Connections( new_addr );
948 if(( Conf_MaxConnectionsIP > 0 ) && ( cnt >= Conf_MaxConnectionsIP ))
950 /* Access denied, too many connections from this IP address! */
951 Log( LOG_ERR, "Refused connection from %s: too may connections (%ld) from this IP address!", inet_ntoa( new_addr.sin_addr ), cnt);
952 Simple_Message( new_sock, "ERROR :Connection refused, too many connections from your IP address!" );
957 /* Freie Connection-Struktur suchen */
958 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
959 if( idx >= Pool_Size )
961 new_size = Pool_Size + CONNECTION_POOL;
963 /* Im bisherigen Pool wurde keine freie Connection-Struktur mehr gefunden.
964 * Wenn erlaubt und moeglich muss nun der Pool vergroessert werden: */
966 if( Conf_MaxConnections > 0 )
968 /* Es ist ein Limit konfiguriert */
969 if( Pool_Size >= Conf_MaxConnections )
971 /* Mehr Verbindungen duerfen wir leider nicht mehr annehmen ... */
972 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached!", Pool_Size );
973 Simple_Message( new_sock, "ERROR :Connection limit reached" );
977 if( new_size > Conf_MaxConnections ) new_size = Conf_MaxConnections;
979 if( new_size < Pool_Size )
981 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached -- overflow!", Pool_Size );
982 Simple_Message( new_sock, "ERROR :Connection limit reached" );
987 ptr = (POINTER *)realloc( My_Connections, sizeof( CONNECTION ) * new_size );
989 Log( LOG_EMERG, "Can't allocate memory! [New_Connection]" );
990 Simple_Message( new_sock, "ERROR: Internal error" );
996 Log( LOG_DEBUG, "Allocated new connection pool for %ld items (%ld bytes). [realloc()]", new_size, sizeof( CONNECTION ) * new_size );
999 /* Adjust pointer to new block */
1000 My_Connections = (CONNECTION *)ptr;
1002 /* Initialize new items */
1003 for( idx = Pool_Size; idx < new_size; idx++ ) Init_Conn_Struct( idx );
1006 /* Adjust new pool size */
1007 Pool_Size = new_size;
1010 /* Client-Struktur initialisieren */
1011 c = Client_NewLocal( idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWN, false );
1013 Log( LOG_ALERT, "Can't accept connection: can't create client structure!" );
1014 Simple_Message( new_sock, "ERROR :Internal error" );
1019 /* Verbindung registrieren */
1020 Init_Conn_Struct( idx );
1021 My_Connections[idx].sock = new_sock;
1022 My_Connections[idx].addr = new_addr;
1024 /* Neuen Socket registrieren */
1025 if (!io_event_create( new_sock, IO_WANTREAD, cb_clientserver)) {
1026 Simple_Message( new_sock, "ERROR :Internal error" );
1027 Conn_Close( idx, "io_event_create() failed", NULL, false );
1031 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 );
1033 /* Hostnamen ermitteln */
1034 strlcpy( My_Connections[idx].host, inet_ntoa( new_addr.sin_addr ), sizeof( My_Connections[idx].host ));
1035 Client_SetHostname( c, My_Connections[idx].host );
1037 s = Resolve_Addr( &new_addr, My_Connections[idx].sock );
1039 s = Resolve_Addr( &new_addr );
1041 /* resolver process has been started */
1042 if( s ) My_Connections[idx].res_stat = s;
1044 /* Penalty-Zeit setzen */
1045 Conn_SetPenalty( idx, 4 );
1047 } /* New_Connection */
1051 Socket2Index( int Sock )
1053 /* zum Socket passende Connection suchen */
1057 assert( Sock > NONE );
1059 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == Sock ) break;
1061 if( idx >= Pool_Size )
1063 /* die Connection wurde vermutlich (wegen eines
1064 * Fehlers) bereits wieder abgebaut ... */
1066 Log( LOG_DEBUG, "Socket2Index: can't get connection for socket %d!", Sock );
1071 } /* Socket2Index */
1075 Read_Request( CONN_ID Idx )
1077 /* Daten von Socket einlesen und entsprechend behandeln.
1078 * Tritt ein Fehler auf, so wird der Socket geschlossen. */
1084 assert( Idx > NONE );
1085 assert( My_Connections[Idx].sock > NONE );
1088 if (( array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN ) ||
1089 ( array_bytes(&My_Connections[Idx].zip.rbuf) >= ZREADBUFFER_LEN ))
1091 if ( array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN )
1094 /* Der Lesepuffer ist voll */
1095 Log( LOG_ERR, "Receive buffer overflow (connection %d): %d bytes!", Idx,
1096 array_bytes(&My_Connections[Idx].rbuf));
1097 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1101 len = read( My_Connections[Idx].sock, readbuf, sizeof readbuf -1 );
1103 Log( LOG_INFO, "%s:%d (%s) is closing the connection ...",
1104 My_Connections[Idx].host, ntohs( My_Connections[Idx].addr.sin_port),
1105 inet_ntoa( My_Connections[Idx].addr.sin_addr ));
1106 Conn_Close( Idx, "Socket closed!", "Client closed connection", false );
1111 if( errno == EAGAIN ) return;
1112 Log( LOG_ERR, "Read error on connection %d (socket %d): %s!", Idx,
1113 My_Connections[Idx].sock, strerror( errno ));
1114 Conn_Close( Idx, "Read error!", "Client closed connection", false );
1118 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
1119 if (!array_catb( &My_Connections[Idx].zip.rbuf, readbuf, len)) {
1120 Log( LOG_ERR, "Could not append recieved data to zip input buffer (connn %d): %d bytes!", Idx, len );
1121 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1128 if (!array_cats( &My_Connections[Idx].rbuf, readbuf )) {
1129 Log( LOG_ERR, "Could not append recieved data to input buffer (connn %d): %d bytes!", Idx, len );
1130 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1134 /* Update connection statistics */
1135 My_Connections[Idx].bytes_in += len;
1137 /* Update timestamp of last data received if this connection is
1138 * registered as a user, server or service connection. Don't update
1139 * otherwise, so users have at least Conf_PongTimeout seconds time to
1140 * register with the IRC server -- see Check_Connections(). */
1141 c = Client_GetFromConn(Idx);
1142 if (c && (Client_Type(c) == CLIENT_USER
1143 || Client_Type(c) == CLIENT_SERVER
1144 || Client_Type(c) == CLIENT_SERVICE))
1145 My_Connections[Idx].lastdata = time(NULL);
1147 /* Look at the data in the (read-) buffer of this connection */
1149 } /* Read_Request */
1153 Handle_Buffer( CONN_ID Idx )
1155 /* Handle Data in Connections Read-Buffer.
1156 * Return true if a reuqest was handled, false otherwise (also returned on errors). */
1170 if( My_Connections[Idx].delaytime > time( NULL )) return result;
1172 /* unpack compressed data */
1173 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP ))
1174 if( ! Unzip_Buffer( Idx )) return false;
1177 if (0 == array_bytes(&My_Connections[Idx].rbuf))
1180 if (!array_cat0_temporary(&My_Connections[Idx].rbuf)) /* make sure buf is NULL terminated */
1183 /* A Complete Request end with CR+LF, see RFC 2812. */
1184 ptr = strstr( array_start(&My_Connections[Idx].rbuf), "\r\n" );
1186 if( ptr ) delta = 2; /* complete request */
1189 /* Check for non-RFC-compliant request (only CR or LF)? Unfortunately,
1190 * there are quite a few clients that do this (incl. "mIRC" :-( */
1191 ptr1 = strchr( array_start(&My_Connections[Idx].rbuf), '\r' );
1192 ptr2 = strchr( array_start(&My_Connections[Idx].rbuf), '\n' );
1194 if( ptr1 && ptr2 ) ptr = ptr1 > ptr2 ? ptr2 : ptr1;
1195 else if( ptr1 ) ptr = ptr1;
1196 else if( ptr2 ) ptr = ptr2;
1203 /* End of request found */
1206 len = ( ptr - (char*) array_start(&My_Connections[Idx].rbuf)) + delta;
1208 if( len < 0 || len > ( COMMAND_LEN - 1 )) {
1209 /* Request must not exceed 512 chars (incl. CR+LF!), see
1210 * RFC 2812. Disconnect Client if this happens. */
1211 Log( LOG_ERR, "Request too long (connection %d): %d bytes (max. %d expected)!",
1212 Idx, array_bytes(&My_Connections[Idx].rbuf), COMMAND_LEN - 1 );
1213 Conn_Close( Idx, NULL, "Request too long", true );
1217 if (len <= 2) { /* request was empty (only '\r\n') */
1218 array_moveleft(&My_Connections[Idx].rbuf, 1, delta); /* delta is either 1 or 2 */
1222 /* remember if stream is already compressed */
1223 old_z = My_Connections[Idx].options & CONN_ZIP;
1226 My_Connections[Idx].msg_in++;
1227 if (!Parse_Request(Idx, (char*)array_start(&My_Connections[Idx].rbuf) ))
1232 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1234 Log(LOG_DEBUG, "%u byte left in rbuf", array_bytes(&My_Connections[Idx].rbuf));
1238 if(( ! old_z ) && ( My_Connections[Idx].options & CONN_ZIP ) &&
1239 ( array_bytes(&My_Connections[Idx].rbuf) > 0 ))
1241 /* The last Command activated Socket-Compression.
1242 * Data that was read after that needs to be copied to Unzip-buf
1243 * for decompression */
1244 if( array_bytes(&My_Connections[Idx].rbuf)> ZREADBUFFER_LEN ) {
1245 Log( LOG_ALERT, "Connection %d: No space left in unzip buf (need %u bytes)!",
1246 Idx, array_bytes(&My_Connections[Idx].rbuf ));
1249 if (!array_copy( &My_Connections[Idx].zip.rbuf, &My_Connections[Idx].rbuf ))
1252 array_trunc(&My_Connections[Idx].rbuf);
1254 Log( LOG_DEBUG, "Moved already received data (%u bytes) to uncompression buffer.",
1255 array_bytes(&My_Connections[Idx].zip.rbuf));
1262 } /* Handle_Buffer */
1266 Check_Connections( void )
1268 /* check if connections are alive. if not, play PING-PONG first.
1269 * if this doesn't help either, disconnect client. */
1273 for( i = 0; i < Pool_Size; i++ ) {
1274 if( My_Connections[i].sock == NONE ) continue;
1276 c = Client_GetFromConn( i );
1277 if( c && (( Client_Type( c ) == CLIENT_USER ) || ( Client_Type( c ) == CLIENT_SERVER ) || ( Client_Type( c ) == CLIENT_SERVICE )))
1279 /* connected User, Server or Service */
1280 if( My_Connections[i].lastping > My_Connections[i].lastdata ) {
1281 /* we already sent a ping */
1282 if( My_Connections[i].lastping < time( NULL ) - Conf_PongTimeout ) {
1285 Log( LOG_DEBUG, "Connection %d: Ping timeout: %d seconds.", i, Conf_PongTimeout );
1287 Conn_Close( i, NULL, "Ping timeout", true );
1290 else if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout ) {
1291 /* we need to sent a PING */
1293 Log( LOG_DEBUG, "Connection %d: sending PING ...", i );
1295 My_Connections[i].lastping = time( NULL );
1296 Conn_WriteStr( i, "PING :%s", Client_ID( Client_ThisServer( )));
1301 /* The connection is not fully established yet, so
1302 * we don't do the PING-PONG game here but instead
1303 * disconnect the client after "a short time" if it's
1304 * still not registered. */
1306 if (My_Connections[i].lastdata <
1307 time(NULL) - Conf_PongTimeout) {
1310 "Unregistered connection %d timed out ...",
1313 Conn_Close(i, NULL, "Timeout", false);
1317 } /* Check_Connections */
1321 Check_Servers( void )
1323 /* Check if we can establish further server links */
1329 /* Search all connections, are there results from the resolver? */
1330 for( idx = 0; idx < Pool_Size; idx++ ) {
1331 if( My_Connections[idx].sock != SERVER_WAIT ) continue;
1334 if( My_Connections[idx].res_stat == NULL ) New_Server( Conf_GetServer( idx ), idx );
1337 /* Check all configured servers */
1338 for( i = 0; i < MAX_SERVERS; i++ ) {
1339 /* Valid outgoing server which isn't already connected or disabled? */
1340 if(( ! Conf_Server[i].host[0] ) || ( ! Conf_Server[i].port > 0 ) ||
1341 ( Conf_Server[i].conn_id > NONE ) || ( Conf_Server[i].flags & CONF_SFLAG_DISABLED ))
1344 /* Is there already a connection in this group? */
1345 if( Conf_Server[i].group > NONE ) {
1346 for( n = 0; n < MAX_SERVERS; n++ ) {
1347 if( n == i ) continue;
1348 if(( Conf_Server[n].conn_id > NONE ) &&
1349 ( Conf_Server[n].group == Conf_Server[i].group ))
1352 if (n < MAX_SERVERS) continue;
1355 /* Check last connect attempt? */
1356 if( Conf_Server[i].lasttry > time( NULL ) - Conf_ConnectRetry ) continue;
1358 /* Okay, try to connect now */
1359 Conf_Server[i].lasttry = time( NULL );
1361 /* Search free connection structure */
1362 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
1363 if( idx >= Pool_Size )
1365 Log( LOG_ALERT, "Can't establist server connection: connection limit reached (%d)!", Pool_Size );
1369 Log( LOG_DEBUG, "Preparing connection %d for \"%s\" ...", idx, Conf_Server[i].host );
1372 /* Verbindungs-Struktur initialisieren */
1373 Init_Conn_Struct( idx );
1374 My_Connections[idx].sock = SERVER_WAIT;
1375 Conf_Server[i].conn_id = idx;
1377 /* Resolve Hostname. If this fails, try to use it as an IP address */
1378 strlcpy( Conf_Server[i].ip, Conf_Server[i].host, sizeof( Conf_Server[i].ip ));
1379 strlcpy( My_Connections[idx].host, Conf_Server[i].host, sizeof( My_Connections[idx].host ));
1380 s = Resolve_Name( Conf_Server[i].host );
1382 /* resolver process running? */
1383 if( s ) My_Connections[idx].res_stat = s;
1385 } /* Check_Servers */
1389 New_Server( int Server, CONN_ID Idx )
1391 /* Establish new server link */
1393 struct sockaddr_in new_addr;
1394 struct in_addr inaddr;
1398 assert( Server > NONE );
1399 assert( Idx > NONE );
1401 /* Did we get a valid IP address? */
1402 if( ! Conf_Server[Server].ip[0] ) {
1403 /* No. Free connection structure and abort: */
1404 Log( LOG_ERR, "Can't connect to \"%s\": ip address unknown!", Conf_Server[Server].host );
1405 Init_Conn_Struct( Idx );
1406 Conf_Server[Server].conn_id = NONE;
1410 Log( LOG_INFO, "Establishing connection to \"%s\", %s, port %d ... ", Conf_Server[Server].host,
1411 Conf_Server[Server].ip, Conf_Server[Server].port );
1413 #ifdef HAVE_INET_ATON
1414 if( inet_aton( Conf_Server[Server].ip, &inaddr ) == 0 )
1416 memset( &inaddr, 0, sizeof( inaddr ));
1417 inaddr.s_addr = inet_addr( Conf_Server[Server].ip );
1418 if( inaddr.s_addr == (unsigned)-1 )
1421 /* Can't convert IP address */
1422 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 );
1426 memset( &new_addr, 0, sizeof( new_addr ));
1427 new_addr.sin_family = AF_INET;
1428 new_addr.sin_addr = inaddr;
1429 new_addr.sin_port = htons( Conf_Server[Server].port );
1431 new_sock = socket( PF_INET, SOCK_STREAM, 0 );
1432 if ( new_sock < 0 ) {
1433 /* Can't create socket */
1434 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
1438 if( ! Init_Socket( new_sock )) return;
1440 res = connect( new_sock, (struct sockaddr *)&new_addr, sizeof( new_addr ));
1441 if(( res != 0 ) && ( errno != EINPROGRESS )) {
1442 /* Can't connect socket */
1443 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1448 /* Client-Struktur initialisieren */
1449 c = Client_NewLocal( Idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWNSERVER, false );
1451 /* Can't create new client structure */
1452 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1457 Client_SetIntroducer( c, c );
1458 Client_SetToken( c, TOKEN_OUTBOUND );
1460 /* Register connection */
1461 My_Connections[Idx].sock = new_sock;
1462 My_Connections[Idx].addr = new_addr;
1463 strlcpy( My_Connections[Idx].host, Conf_Server[Server].host, sizeof( My_Connections[Idx].host ));
1465 /* Register new socket */
1466 if (!io_event_create( new_sock, IO_WANTWRITE, cb_connserver)) {
1467 Log( LOG_ALERT, "io_event_create(): could not add fd %d", strerror(errno));
1468 Conn_Close( Idx, "io_event_create() failed", NULL, false );
1473 Log( LOG_DEBUG, "Registered new connection %d on socket %d.", Idx, My_Connections[Idx].sock );
1475 Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCONNECTING );
1478 Init_Conn_Struct( Idx );
1479 Conf_Server[Server].conn_id = NONE;
1484 Init_Conn_Struct( CONN_ID Idx )
1486 time_t now = time( NULL );
1487 /* Connection-Struktur initialisieren */
1489 memset( &My_Connections[Idx], 0, sizeof ( CONNECTION ));
1490 My_Connections[Idx].sock = NONE;
1491 My_Connections[Idx].lastdata = now;
1492 My_Connections[Idx].lastprivmsg = now;
1493 } /* Init_Conn_Struct */
1497 Init_Socket( int Sock )
1499 /* Initialize socket (set options) */
1503 if (!io_setnonblock(Sock)) {
1504 Log( LOG_CRIT, "Can't enable non-blocking mode for socket: %s!", strerror( errno ));
1509 /* Don't block this port after socket shutdown */
1511 if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &value, (socklen_t)sizeof( value )) != 0 )
1513 Log( LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!", strerror( errno ));
1514 /* ignore this error */
1517 /* Set type of service (TOS) */
1518 #if defined(IP_TOS) && defined(IPTOS_LOWDELAY)
1519 value = IPTOS_LOWDELAY;
1521 Log( LOG_DEBUG, "Setting option IP_TOS on socket %d to IPTOS_LOWDELAY (%d).", Sock, value );
1523 if( setsockopt( Sock, SOL_IP, IP_TOS, &value, (socklen_t)sizeof( value )) != 0 )
1525 Log( LOG_ERR, "Can't set socket option IP_TOS: %s!", strerror( errno ));
1526 /* ignore this error */
1535 void Read_Resolver_Result( int r_fd )
1537 /* Read result of resolver sub-process from pipe and update the
1538 * apropriate connection/client structure(s): hostname and/or
1539 * IDENT user name.*/
1542 int bytes_read, i, n;
1547 char readbuf[HOST_LEN];
1549 Log( LOG_DEBUG, "Resolver: started, fd %d", r_fd );
1550 /* Search associated connection ... */
1551 for( i = 0; i < Pool_Size; i++ ) {
1552 if(( My_Connections[i].sock != NONE )
1553 && ( My_Connections[i].res_stat != NULL )
1554 && ( My_Connections[i].res_stat->pipe[0] == r_fd ))
1557 if( i >= Pool_Size )
1559 /* Ops, none found? Probably the connection has already
1560 * been closed!? We'll ignore that ... */
1563 Log( LOG_DEBUG, "Resolver: Got result for unknown connection!?" );
1568 /* Get resolver structure */
1569 s = My_Connections[i].res_stat;
1570 assert( s != NULL );
1572 /* Read result from pipe */
1573 bytes_read = read( r_fd, readbuf, sizeof readbuf -1 );
1574 if( bytes_read < 0 ) {
1576 Log( LOG_CRIT, "Resolver: Can't read result: %s!", strerror( errno ));
1577 FreeRes_stat( &My_Connections[i] );
1580 len = (unsigned int) bytes_read;
1581 readbuf[len] = '\0';
1582 if (!array_catb(&s->buffer, readbuf, len)) {
1583 Log( LOG_CRIT, "Resolver: Can't append result %s to buffer: %s", readbuf, strerror( errno ));
1584 FreeRes_stat(&My_Connections[i]);
1588 if (!array_cat0_temporary(&s->buffer)) {
1589 Log( LOG_CRIT, "Resolver: Can't append result %s to buffer: %s", readbuf, strerror( errno ));
1590 FreeRes_stat(&My_Connections[i]);
1594 /* If the result string is incomplete, return to main loop and
1595 * wait until we can read in more bytes. */
1599 bufptr = (char*) array_start(&s->buffer);
1600 assert(bufptr != NULL);
1601 ptr = strchr( bufptr, '\n' );
1606 Log( LOG_DEBUG, "Got result from resolver: \"%s\" (%u bytes read), stage %d.", bufptr, len, s->stage);
1609 /* Okay, we got a complete result: this is a host name for outgoing
1610 * connections and a host name or IDENT user name (if enabled) for
1611 * incoming connections.*/
1612 if( My_Connections[i].sock > NONE )
1614 /* Incoming connection. Search client ... */
1615 c = Client_GetFromConn( i );
1616 assert( c != NULL );
1618 /* Only update client information of unregistered clients */
1619 if( Client_Type( c ) == CLIENT_UNKNOWN )
1622 case 0: /* host name */
1623 strlcpy( My_Connections[i].host, bufptr, sizeof( My_Connections[i].host));
1625 Client_SetHostname( c, bufptr);
1627 /* clean up buffer for IDENT result */
1628 len = strlen(bufptr) + 1;
1629 assert(len <= array_bytes(&s->buffer));
1630 array_moveleft(&s->buffer, 1, len);
1632 /* Don't close pipe and clean up, but
1633 * instead wait for IDENT result */
1637 case 1: /* IDENT user name */
1638 if (array_bytes(&s->buffer)) {
1639 bufptr = (char*) array_start(&s->buffer);
1640 Log( LOG_INFO, "IDENT lookup for connection %ld: \"%s\".", i, bufptr);
1641 Client_SetUser( c, bufptr, true );
1643 else Log( LOG_INFO, "IDENT lookup for connection %ld: no result.", i );
1647 Log( LOG_ERR, "Resolver: got result for unknown stage %d!?", s->stage );
1651 else Log( LOG_DEBUG, "Resolver: discarding result for already registered connection %d.", i );
1656 /* Outgoing connection (server link): set the IP address
1657 * so that we can connect to it in the main loop. */
1659 /* Search server ... */
1660 n = Conf_GetServer( i );
1663 bufptr = (char*) array_start(&s->buffer);
1664 strlcpy( Conf_Server[n].ip, bufptr, sizeof( Conf_Server[n].ip ));
1668 FreeRes_stat( &My_Connections[i] );
1670 /* Reset penalty time */
1671 Conn_ResetPenalty( i );
1672 } /* Read_Resolver_Result */
1676 Simple_Message( int Sock, char *Msg )
1678 char buf[COMMAND_LEN];
1679 /* Write "simple" message to socket, without using compression
1680 * or even the connection write buffers. Used e.g. for error
1681 * messages by New_Connection(). */
1682 assert( Sock > NONE );
1683 assert( Msg != NULL );
1685 strlcpy( buf, Msg, sizeof buf - 2);
1686 strlcat( buf, "\r\n", sizeof buf);
1687 (void)write( Sock, buf, strlen( buf ) );
1688 } /* Simple_Error */
1692 Count_Connections( struct sockaddr_in addr_in )
1697 for( i = 0; i < Pool_Size; i++ )
1699 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].addr.sin_addr.s_addr == addr_in.sin_addr.s_addr )) cnt++;
1702 } /* Count_Connections */