2 * ngIRCd -- The Next Generation IRC Daemon
3 * Copyright (c)2001-2004 Alexander Barton <alex@barton.de>
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 * Please read the file COPYING, README and AUTHORS for more information.
11 * Connection management
19 static char UNUSED id[] = "$Id: conn.c,v 1.137 2004/05/30 16:25:51 alex Exp $";
30 #include <sys/socket.h>
32 #include <sys/types.h>
34 #include <netinet/in.h>
36 #ifdef HAVE_NETINET_IP_H
37 # include <netinet/ip.h>
40 #ifdef HAVE_ARPA_INET_H
41 # include <arpa/inet.h>
43 # define PF_INET AF_INET
47 # include <stdint.h> /* e.g. for Mac OS X */
51 # include <tcpd.h> /* for TCP Wrappers */
65 #include "conn-func.h"
71 # include "rendezvous.h"
77 #define SERVER_WAIT (NONE - 1)
80 LOCAL VOID Handle_Read PARAMS(( INT sock ));
81 LOCAL BOOLEAN Handle_Write PARAMS(( CONN_ID Idx ));
82 LOCAL VOID New_Connection PARAMS(( INT Sock ));
83 LOCAL CONN_ID Socket2Index PARAMS(( INT Sock ));
84 LOCAL VOID Read_Request PARAMS(( CONN_ID Idx ));
85 LOCAL BOOLEAN Try_Write PARAMS(( CONN_ID Idx ));
86 LOCAL BOOLEAN Handle_Buffer PARAMS(( CONN_ID Idx ));
87 LOCAL VOID Check_Connections PARAMS(( VOID ));
88 LOCAL VOID Check_Servers PARAMS(( VOID ));
89 LOCAL VOID Init_Conn_Struct PARAMS(( CONN_ID Idx ));
90 LOCAL BOOLEAN Init_Socket PARAMS(( INT Sock ));
91 LOCAL VOID New_Server PARAMS(( INT Server, CONN_ID Idx ));
92 LOCAL VOID Read_Resolver_Result PARAMS(( INT r_fd ));
93 LOCAL VOID Simple_Message PARAMS(( INT Sock, CHAR *Msg ));
94 LOCAL INT Count_Connections PARAMS(( struct sockaddr_in addr ));
96 LOCAL fd_set My_Listeners;
97 LOCAL fd_set My_Sockets;
98 LOCAL fd_set My_Connects;
101 INT allow_severity = LOG_INFO;
102 INT deny_severity = LOG_ERR;
109 /* Modul initialisieren: statische Strukturen "ausnullen". */
113 /* Speicher fuer Verbindungs-Pool anfordern */
114 Pool_Size = CONNECTION_POOL;
115 if( Conf_MaxConnections > 0 )
117 /* konfiguriertes Limit beachten */
118 if( Pool_Size > Conf_MaxConnections ) Pool_Size = Conf_MaxConnections;
120 My_Connections = (CONNECTION *)malloc( sizeof( CONNECTION ) * Pool_Size );
121 if( ! My_Connections )
123 /* Speicher konnte nicht alloziert werden! */
124 Log( LOG_EMERG, "Can't allocate memory! [Conn_Init]" );
128 Log( LOG_DEBUG, "Allocated connection pool for %d items (%ld bytes).", Pool_Size, sizeof( CONNECTION ) * Pool_Size );
131 /* zu Beginn haben wir keine Verbindungen */
132 FD_ZERO( &My_Listeners );
133 FD_ZERO( &My_Sockets );
134 FD_ZERO( &My_Connects );
136 /* Groesster File-Descriptor fuer select() */
139 /* Connection-Struktur initialisieren */
140 for( i = 0; i < Pool_Size; i++ ) Init_Conn_Struct( i );
142 /* Global write counter */
150 /* Modul abmelden: alle noch offenen Connections
151 * schliessen und freigeben. */
157 Log( LOG_DEBUG, "Shutting down all connections ..." );
161 Rendezvous_UnregisterListeners( );
164 /* Sockets schliessen */
165 for( i = 0; i < Conn_MaxFD + 1; i++ )
167 if( FD_ISSET( i, &My_Sockets ))
169 for( idx = 0; idx < Pool_Size; idx++ )
171 if( My_Connections[idx].sock == i ) break;
173 if( FD_ISSET( i, &My_Listeners ))
177 Log( LOG_DEBUG, "Listening socket %d closed.", i );
180 else if( FD_ISSET( i, &My_Connects ))
184 Log( LOG_DEBUG, "Connection %d closed during creation (socket %d).", idx, i );
187 else if( idx < Pool_Size )
189 if( NGIRCd_SignalRestart ) Conn_Close( idx, NULL, "Server going down (restarting)", TRUE );
190 else Conn_Close( idx, NULL, "Server going down", TRUE );
194 Log( LOG_WARNING, "Closing unknown connection %d ...", i );
200 free( My_Connections );
201 My_Connections = NULL;
207 Conn_InitListeners( VOID )
209 /* Initialize ports on which the server should accept connections */
214 for( i = 0; i < Conf_ListenPorts_Count; i++ )
216 if( Conn_NewListener( Conf_ListenPorts[i] )) created++;
217 else Log( LOG_ERR, "Can't listen on port %u!", Conf_ListenPorts[i] );
220 } /* Conn_InitListeners */
224 Conn_ExitListeners( VOID )
226 /* Close down all listening sockets */
231 Rendezvous_UnregisterListeners( );
234 Log( LOG_INFO, "Shutting down all listening sockets ..." );
235 for( i = 0; i < Conn_MaxFD + 1; i++ )
237 if( FD_ISSET( i, &My_Sockets ) && FD_ISSET( i, &My_Listeners ))
241 Log( LOG_DEBUG, "Listening socket %d closed.", i );
245 } /* Conn_ExitListeners */
249 Conn_NewListener( CONST UINT Port )
251 /* Create new listening socket on specified port */
253 struct sockaddr_in addr;
254 struct in_addr inaddr;
257 CHAR name[CLIENT_ID_LEN], *info;
260 /* Server-"Listen"-Socket initialisieren */
261 memset( &addr, 0, sizeof( addr ));
262 memset( &inaddr, 0, sizeof( inaddr ));
263 addr.sin_family = AF_INET;
264 addr.sin_port = htons( Port );
265 if( Conf_ListenAddress[0] )
267 #ifdef HAVE_INET_ATON
268 if( inet_aton( Conf_ListenAddress, &inaddr ) == 0 )
270 inaddr.s_addr = inet_addr( Conf_ListenAddress );
271 if( inaddr.s_addr == (unsigned)-1 )
274 Log( LOG_CRIT, "Can't listen on %s:%u: can't convert ip address %s!", Conf_ListenAddress, Port, Conf_ListenAddress );
278 else inaddr.s_addr = htonl( INADDR_ANY );
279 addr.sin_addr = inaddr;
281 /* Socket erzeugen */
282 sock = socket( PF_INET, SOCK_STREAM, 0);
285 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
289 if( ! Init_Socket( sock )) return FALSE;
292 if( bind( sock, (struct sockaddr *)&addr, (socklen_t)sizeof( addr )) != 0 )
294 Log( LOG_CRIT, "Can't bind socket: %s!", strerror( errno ));
299 /* in "listen mode" gehen :-) */
300 if( listen( sock, 10 ) != 0 )
302 Log( LOG_CRIT, "Can't listen on soecket: %s!", strerror( errno ));
307 /* Neuen Listener in Strukturen einfuegen */
308 FD_SET( sock, &My_Listeners );
309 FD_SET( sock, &My_Sockets );
311 if( sock > Conn_MaxFD ) Conn_MaxFD = sock;
313 if( Conf_ListenAddress[0]) Log( LOG_INFO, "Now listening on %s:%d (socket %d).", Conf_ListenAddress, Port, sock );
314 else Log( LOG_INFO, "Now listening on 0.0.0.0:%d (socket %d).", Port, sock );
317 /* Get best server description text */
318 if( ! Conf_ServerInfo[0] ) info = Conf_ServerName;
321 /* Use server info string */
323 if( Conf_ServerInfo[0] == '[' )
325 /* Cut off leading hostname part in "[]" */
326 info = strchr( Conf_ServerInfo, ']' );
330 while( *info == ' ' ) info++;
333 if( ! info ) info = Conf_ServerInfo;
336 /* Add port number to description if non-standard */
337 if( Port != 6667 ) snprintf( name, sizeof( name ), "%s (port %u)", info, Port );
338 else strlcpy( name, info, sizeof( name ));
340 /* Register service */
341 Rendezvous_Register( name, RENDEZVOUS_TYPE, Port );
345 } /* Conn_NewListener */
351 /* "Hauptschleife": Aktive Verbindungen ueberwachen. Folgende Aktionen
352 * werden dabei durchgefuehrt, bis der Server terminieren oder neu
355 * - neue Verbindungen annehmen,
356 * - Server-Verbindungen aufbauen,
357 * - geschlossene Verbindungen loeschen,
358 * - volle Schreibpuffer versuchen zu schreiben,
359 * - volle Lesepuffer versuchen zu verarbeiten,
360 * - Antworten von Resolver Sub-Prozessen annehmen.
363 fd_set read_sockets, write_sockets;
369 start = time( NULL );
370 while(( ! NGIRCd_SignalQuit ) && ( ! NGIRCd_SignalRestart ))
375 Rendezvous_Handler( );
378 /* Should the configuration be reloaded? */
379 if( NGIRCd_SignalRehash ) NGIRCd_Rehash( );
381 /* Check configured servers and established links */
383 Check_Connections( );
387 /* noch volle Lese-Buffer suchen */
388 for( i = 0; i < Pool_Size; i++ )
390 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].rdatalen > 0 ) &&
391 ( My_Connections[i].delaytime < t ))
393 /* Kann aus dem Buffer noch ein Befehl extrahiert werden? */
394 if( Handle_Buffer( i )) timeout = FALSE;
398 /* noch volle Schreib-Puffer suchen */
399 FD_ZERO( &write_sockets );
400 for( i = 0; i < Pool_Size; i++ )
403 if(( My_Connections[i].sock > NONE ) && (( My_Connections[i].wdatalen > 0 ) || ( My_Connections[i].zip.wdatalen > 0 )))
405 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].wdatalen > 0 ))
408 /* Socket der Verbindung in Set aufnehmen */
409 FD_SET( My_Connections[i].sock, &write_sockets );
413 /* Sockets mit im Aufbau befindlichen ausgehenden Verbindungen suchen */
414 for( i = 0; i < Pool_Size; i++ )
416 if(( My_Connections[i].sock > NONE ) && ( FD_ISSET( My_Connections[i].sock, &My_Connects ))) FD_SET( My_Connections[i].sock, &write_sockets );
419 /* von welchen Sockets koennte gelesen werden? */
420 read_sockets = My_Sockets;
421 for( i = 0; i < Pool_Size; i++ )
423 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].host[0] == '\0' ))
425 /* Hier muss noch auf den Resolver Sub-Prozess gewartet werden */
426 FD_CLR( My_Connections[i].sock, &read_sockets );
428 if(( My_Connections[i].sock > NONE ) && ( FD_ISSET( My_Connections[i].sock, &My_Connects )))
430 /* Hier laeuft noch ein asyncrones connect() */
431 FD_CLR( My_Connections[i].sock, &read_sockets );
433 if( My_Connections[i].delaytime > t )
435 /* Fuer die Verbindung ist eine "Penalty-Zeit" gesetzt */
436 FD_CLR( My_Connections[i].sock, &read_sockets );
439 for( i = 0; i < Conn_MaxFD + 1; i++ )
441 /* Pipes von Resolver Sub-Prozessen aufnehmen */
442 if( FD_ISSET( i, &Resolver_FDs ))
444 FD_SET( i, &read_sockets );
448 /* Timeout initialisieren */
450 if( timeout ) tv.tv_sec = 1;
453 /* Auf Aktivitaet warten */
454 i = select( Conn_MaxFD + 1, &read_sockets, &write_sockets, NULL, &tv );
457 /* keine Veraenderung an den Sockets */
462 /* Fehler (z.B. Interrupt) */
465 Log( LOG_EMERG, "Conn_Handler(): select(): %s!", strerror( errno ));
466 Log( LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE_NAME );
472 /* Koennen Daten geschrieben werden? */
473 for( i = 0; i < Conn_MaxFD + 1; i++ )
475 if( ! FD_ISSET( i, &write_sockets )) continue;
477 /* Es kann geschrieben werden ... */
478 idx = Socket2Index( i );
479 if( idx == NONE ) continue;
481 if( ! Handle_Write( idx ))
483 /* Fehler beim Schreiben! Diesen Socket nun
484 * auch aus dem Read-Set entfernen: */
485 FD_CLR( i, &read_sockets );
489 /* Daten zum Lesen vorhanden? */
490 for( i = 0; i < Conn_MaxFD + 1; i++ )
492 if( FD_ISSET( i, &read_sockets )) Handle_Read( i );
496 if( NGIRCd_SignalQuit ) Log( LOG_NOTICE|LOG_snotice, "Server going down NOW!" );
497 else if( NGIRCd_SignalRestart ) Log( LOG_NOTICE|LOG_snotice, "Server restarting NOW!" );
503 Conn_WriteStr( CONN_ID Idx, CHAR *Format, ... )
506 Conn_WriteStr( Idx, Format, va_alist )
512 /* String in Socket schreiben. CR+LF wird von dieser Funktion
513 * automatisch angehaengt. Im Fehlerfall wird dir Verbindung
514 * getrennt und FALSE geliefert. */
516 CHAR buffer[COMMAND_LEN];
520 assert( Idx > NONE );
521 assert( Format != NULL );
524 va_start( ap, Format );
528 if( vsnprintf( buffer, COMMAND_LEN - 2, Format, ap ) == COMMAND_LEN - 2 )
530 Log( LOG_CRIT, "Text too long to send (connection %d)!", Idx );
531 Conn_Close( Idx, "Text too long to send!", NULL, FALSE );
536 if( NGIRCd_Sniffer ) Log( LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer );
539 strlcat( buffer, "\r\n", sizeof( buffer ));
540 ok = Conn_Write( Idx, buffer, strlen( buffer ));
541 My_Connections[Idx].msg_out++;
545 } /* Conn_WriteStr */
549 Conn_Write( CONN_ID Idx, CHAR *Data, INT Len )
551 /* Daten in Socket schreiben. Bei "fatalen" Fehlern wird
552 * der Client disconnectiert und FALSE geliefert. */
554 assert( Idx > NONE );
555 assert( Data != NULL );
558 /* Ist der entsprechende Socket ueberhaupt noch offen? In einem
559 * "Handler-Durchlauf" kann es passieren, dass dem nicht mehr so
560 * ist, wenn einer von mehreren Conn_Write()'s fehlgeschlagen ist.
561 * In diesem Fall wird hier einfach ein Fehler geliefert. */
562 if( My_Connections[Idx].sock <= NONE )
565 Log( LOG_DEBUG, "Skipped write on closed socket (connection %d).", Idx );
570 /* Pruefen, ob im Schreibpuffer genuegend Platz ist. Ziel ist es,
571 * moeglichts viel im Puffer zu haben und _nicht_ gleich alles auf den
572 * Socket zu schreiben (u.a. wg. Komprimierung). */
573 if( WRITEBUFFER_LEN - My_Connections[Idx].wdatalen - Len <= 0 )
575 /* Der Puffer ist dummerweise voll. Jetzt versuchen, den Puffer
576 * zu schreiben, wenn das nicht klappt, haben wir ein Problem ... */
577 if( ! Try_Write( Idx )) return FALSE;
579 /* nun neu pruefen: */
580 if( WRITEBUFFER_LEN - My_Connections[Idx].wdatalen - Len <= 0 )
582 Log( LOG_NOTICE, "Write buffer overflow (connection %d)!", Idx );
583 Conn_Close( Idx, "Write buffer overflow!", NULL, FALSE );
589 if( My_Connections[Idx].options & CONN_ZIP )
591 /* Daten komprimieren und in Puffer kopieren */
592 if( ! Zip_Buffer( Idx, Data, Len )) return FALSE;
597 /* Daten in Puffer kopieren */
598 memcpy( My_Connections[Idx].wbuf + My_Connections[Idx].wdatalen, Data, Len );
599 My_Connections[Idx].wdatalen += Len;
600 My_Connections[Idx].bytes_out += Len;
603 /* Adjust global write counter */
611 Conn_Close( CONN_ID Idx, CHAR *LogMsg, CHAR *FwdMsg, BOOLEAN InformClient )
613 /* Close connection. Open pipes of asyncronous resolver
614 * sub-processes are closed down. */
620 DOUBLE in_z_k, out_z_k;
624 assert( Idx > NONE );
626 /* Is this link already shutting down? */
627 if( My_Connections[Idx].options & CONN_ISCLOSING )
629 /* Conn_Close() has been called recursively for this link;
630 * probabe reason: Try_Write() failed -- see below. */
634 assert( My_Connections[Idx].sock > NONE );
636 /* Mark link as "closing" */
637 My_Connections[Idx].options |= CONN_ISCLOSING;
639 if( LogMsg ) txt = LogMsg;
641 if( ! txt ) txt = "Reason unknown";
643 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 ));
645 /* Search client, if any */
646 c = Client_GetFromConn( Idx );
648 /* Should the client be informed? */
652 /* Send statistics to client if registered as user: */
653 if(( c != NULL ) && ( Client_Type( c ) == CLIENT_USER ))
655 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 );
659 /* Send ERROR to client (see RFC!) */
660 if( FwdMsg ) Conn_WriteStr( Idx, "ERROR :%s", FwdMsg );
661 else Conn_WriteStr( Idx, "ERROR :Closing connection." );
664 /* Try to write out the write buffer */
665 (VOID)Try_Write( Idx );
667 /* Shut down socket */
668 if( close( My_Connections[Idx].sock ) != 0 )
670 /* Oops, we can't close the socket!? This is fatal! */
671 Log( LOG_EMERG, "Error closing connection %d (socket %d) with %s:%d - %s!", Idx, My_Connections[Idx].sock, My_Connections[Idx].host, ntohs( My_Connections[Idx].addr.sin_port), strerror( errno ));
672 Log( LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE_NAME );
676 /* Mark socket as invalid: */
677 FD_CLR( My_Connections[Idx].sock, &My_Sockets );
678 FD_CLR( My_Connections[Idx].sock, &My_Connects );
679 My_Connections[Idx].sock = NONE;
681 /* If there is still a client, unregister it now */
682 if( c ) Client_Destroy( c, LogMsg, FwdMsg, TRUE );
684 /* Calculate statistics and log information */
685 in_k = (DOUBLE)My_Connections[Idx].bytes_in / 1024;
686 out_k = (DOUBLE)My_Connections[Idx].bytes_out / 1024;
688 if( My_Connections[Idx].options & CONN_ZIP )
690 in_z_k = (DOUBLE)My_Connections[Idx].zip.bytes_in / 1024;
691 out_z_k = (DOUBLE)My_Connections[Idx].zip.bytes_out / 1024;
692 in_p = (INT)(( in_k * 100 ) / in_z_k );
693 out_p = (INT)(( out_k * 100 ) / out_z_k );
694 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 );
699 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 );
702 /* Is there a resolver sub-process running? */
703 if( My_Connections[Idx].res_stat )
705 /* Free resolver structures */
706 FD_CLR( My_Connections[Idx].res_stat->pipe[0], &Resolver_FDs );
707 close( My_Connections[Idx].res_stat->pipe[0] );
708 close( My_Connections[Idx].res_stat->pipe[1] );
709 free( My_Connections[Idx].res_stat );
712 /* Servers: Modify time of next connect attempt? */
713 Conf_UnsetServer( Idx );
716 /* Clean up zlib, if link was compressed */
717 if( Conn_Options( Idx ) & CONN_ZIP )
719 inflateEnd( &My_Connections[Idx].zip.in );
720 deflateEnd( &My_Connections[Idx].zip.out );
724 /* Clean up connection structure (=free it) */
725 Init_Conn_Struct( Idx );
730 Conn_SyncServerStruct( VOID )
732 /* Synchronize server structures (connection IDs):
733 * connections <-> configuration */
739 for( i = 0; i < Pool_Size; i++ )
741 /* Established connection? */
742 if( My_Connections[i].sock <= NONE ) continue;
744 /* Server connection? */
745 client = Client_GetFromConn( i );
746 if(( ! client ) || ( Client_Type( client ) != CLIENT_SERVER )) continue;
748 for( c = 0; c < MAX_SERVERS; c++ )
750 /* Configured server? */
751 if( ! Conf_Server[c].host[0] ) continue;
754 if( strcmp( Conf_Server[c].name, Client_ID( client )) == 0 ) Conf_Server[c].conn_id = i;
757 } /* SyncServerStruct */
761 Try_Write( CONN_ID Idx )
763 /* Versuchen, Daten aus dem Schreib-Puffer in den Socket zu
764 * schreiben. TRUE wird geliefert, wenn entweder keine Daten
765 * zum Versenden vorhanden sind oder erfolgreich bearbeitet
766 * werden konnten. Im Fehlerfall wird FALSE geliefert und
767 * die Verbindung geschlossen. */
772 assert( Idx > NONE );
773 assert( My_Connections[Idx].sock > NONE );
775 /* sind ueberhaupt Daten vorhanden? */
777 if(( ! My_Connections[Idx].wdatalen > 0 ) && ( ! My_Connections[Idx].zip.wdatalen )) return TRUE;
779 if( ! My_Connections[Idx].wdatalen > 0 ) return TRUE;
782 /* Timeout initialisieren: 0 Sekunden, also nicht blockieren */
783 tv.tv_sec = 0; tv.tv_usec = 0;
785 FD_ZERO( &write_socket );
786 FD_SET( My_Connections[Idx].sock, &write_socket );
787 if( select( My_Connections[Idx].sock + 1, NULL, &write_socket, NULL, &tv ) == -1 )
792 Log( LOG_ALERT, "Try_Write(): select() failed: %s (con=%d, sock=%d)!", strerror( errno ), Idx, My_Connections[Idx].sock );
793 Conn_Close( Idx, "Server error!", NULL, FALSE );
798 if( FD_ISSET( My_Connections[Idx].sock, &write_socket )) return Handle_Write( Idx );
804 Handle_Read( INT Sock )
806 /* Aktivitaet auf einem Socket verarbeiten:
807 * - neue Clients annehmen,
808 * - Daten von Clients verarbeiten,
809 * - Resolver-Rueckmeldungen annehmen. */
813 assert( Sock > NONE );
815 if( FD_ISSET( Sock, &My_Listeners ))
817 /* es ist einer unserer Listener-Sockets: es soll
818 * also eine neue Verbindung aufgebaut werden. */
820 New_Connection( Sock );
822 else if( FD_ISSET( Sock, &Resolver_FDs ))
824 /* Rueckmeldung von einem Resolver Sub-Prozess */
826 Read_Resolver_Result( Sock );
830 /* Ein Client Socket: entweder ein User oder Server */
832 idx = Socket2Index( Sock );
833 if( idx > NONE ) Read_Request( idx );
839 Handle_Write( CONN_ID Idx )
841 /* Daten aus Schreibpuffer versenden bzw. Connection aufbauen */
847 assert( Idx > NONE );
848 assert( My_Connections[Idx].sock > NONE );
850 if( FD_ISSET( My_Connections[Idx].sock, &My_Connects ))
852 /* es soll nichts geschrieben werden, sondern ein
853 * connect() hat ein Ergebnis geliefert */
855 FD_CLR( My_Connections[Idx].sock, &My_Connects );
857 /* Ergebnis des connect() ermitteln */
858 sock_len = sizeof( err );
859 res = getsockopt( My_Connections[Idx].sock, SOL_SOCKET, SO_ERROR, &err, &sock_len );
860 assert( sock_len == sizeof( err ));
862 /* Fehler aufgetreten? */
863 if(( res != 0 ) || ( err != 0 ))
866 if( res != 0 ) Log( LOG_CRIT, "getsockopt (connection %d): %s!", Idx, strerror( errno ));
867 else Log( LOG_CRIT, "Can't connect socket to \"%s:%d\" (connection %d): %s!", My_Connections[Idx].host, Conf_Server[Conf_GetServer( Idx )].port, Idx, strerror( err ));
869 /* Clean up socket, connection and client structures */
870 FD_CLR( My_Connections[Idx].sock, &My_Sockets );
871 c = Client_GetFromConn( Idx );
872 if( c ) Client_DestroyNow( c );
873 close( My_Connections[Idx].sock );
874 Init_Conn_Struct( Idx );
876 /* Bei Server-Verbindungen lasttry-Zeitpunkt auf "jetzt" setzen */
877 Conf_Server[Conf_GetServer( Idx )].lasttry = time( NULL );
878 Conf_UnsetServer( Idx );
882 Log( LOG_INFO, "Connection %d with \"%s:%d\" established. Now logging in ...", Idx, My_Connections[Idx].host, Conf_Server[Conf_GetServer( Idx )].port );
884 /* Send PASS and SERVER command to peer */
885 Conn_WriteStr( Idx, "PASS %s %s", Conf_Server[Conf_GetServer( Idx )].pwd_out, NGIRCd_ProtoID );
886 return Conn_WriteStr( Idx, "SERVER %s :%s", Conf_ServerName, Conf_ServerInfo );
890 /* Schreibpuffer leer, aber noch Daten im Kompressionsbuffer?
891 * Dann muss dieser nun geflushed werden! */
892 if( My_Connections[Idx].wdatalen == 0 ) Zip_Flush( Idx );
895 assert( My_Connections[Idx].wdatalen > 0 );
897 /* Daten schreiben */
898 len = send( My_Connections[Idx].sock, My_Connections[Idx].wbuf, My_Connections[Idx].wdatalen, 0 );
901 /* Operation haette Socket "nur" blockiert ... */
902 if( errno == EAGAIN ) return TRUE;
904 /* Oops, ein Fehler! */
905 Log( LOG_ERR, "Write error on connection %d (socket %d): %s!", Idx, My_Connections[Idx].sock, strerror( errno ));
906 Conn_Close( Idx, "Write error!", NULL, FALSE );
910 /* Puffer anpassen */
911 My_Connections[Idx].wdatalen -= len;
912 memmove( My_Connections[Idx].wbuf, My_Connections[Idx].wbuf + len, My_Connections[Idx].wdatalen );
919 New_Connection( INT Sock )
921 /* Neue Client-Verbindung von Listen-Socket annehmen und
922 * CLIENT-Struktur anlegen. */
925 struct request_info req;
927 struct sockaddr_in new_addr;
928 INT new_sock, new_sock_len;
935 assert( Sock > NONE );
937 /* Connection auf Listen-Socket annehmen */
938 new_sock_len = sizeof( new_addr );
939 new_sock = accept( Sock, (struct sockaddr *)&new_addr, (socklen_t *)&new_sock_len );
942 Log( LOG_CRIT, "Can't accept connection: %s!", strerror( errno ));
947 /* Validate socket using TCP Wrappers */
948 request_init( &req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock, RQ_CLIENT_SIN, &new_addr, NULL );
950 if( ! hosts_access( &req ))
953 Log( deny_severity, "Refused connection from %s (by TCP Wrappers)!", inet_ntoa( new_addr.sin_addr ));
954 Simple_Message( new_sock, "ERROR :Connection refused" );
960 /* Socket initialisieren */
961 Init_Socket( new_sock );
963 /* Check IP-based connection limit */
964 cnt = Count_Connections( new_addr );
965 if(( Conf_MaxConnectionsIP > 0 ) && ( cnt >= Conf_MaxConnectionsIP ))
967 /* Access denied, too many connections from this IP! */
968 Log( LOG_ERR, "Refused connection from %s: too may connections (%ld) from this IP!", inet_ntoa( new_addr.sin_addr ), cnt);
969 Simple_Message( new_sock, "ERROR :Connection refused, too many connections from your IP!" );
974 /* Freie Connection-Struktur suchen */
975 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
976 if( idx >= Pool_Size )
978 new_size = Pool_Size + CONNECTION_POOL;
980 /* Im bisherigen Pool wurde keine freie Connection-Struktur mehr gefunden.
981 * Wenn erlaubt und moeglich muss nun der Pool vergroessert werden: */
983 if( Conf_MaxConnections > 0 )
985 /* Es ist ein Limit konfiguriert */
986 if( Pool_Size >= Conf_MaxConnections )
988 /* Mehr Verbindungen duerfen wir leider nicht mehr annehmen ... */
989 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached!", Pool_Size );
990 Simple_Message( new_sock, "ERROR :Connection limit reached" );
994 if( new_size > Conf_MaxConnections ) new_size = Conf_MaxConnections;
996 if( new_size < Pool_Size )
998 Log( LOG_ALERT, "Can't accespt connection: limit (%d) reached -- overflow!", Pool_Size );
999 Simple_Message( new_sock, "ERROR :Connection limit reached" );
1004 /* zunaechst realloc() versuchen; wenn das scheitert, malloc() versuchen
1005 * und Daten ggf. "haendisch" umkopieren. (Haesslich! Eine wirklich
1006 * dynamische Verwaltung waere wohl _deutlich_ besser ...) */
1007 ptr = (POINTER *)realloc( My_Connections, sizeof( CONNECTION ) * new_size );
1010 /* realloc() ist fehlgeschlagen. Nun malloc() probieren: */
1011 ptr = (POINTER *)malloc( sizeof( CONNECTION ) * new_size );
1014 /* Offenbar steht kein weiterer Sepeicher zur Verfuegung :-( */
1015 Log( LOG_EMERG, "Can't allocate memory! [New_Connection]" );
1016 Simple_Message( new_sock, "ERROR: Internal error" );
1021 /* Struktur umkopieren ... */
1022 memcpy( ptr, My_Connections, sizeof( CONNECTION ) * Pool_Size );
1025 Log( LOG_DEBUG, "Allocated new connection pool for %ld items (%ld bytes). [malloc()/memcpy()]", new_size, sizeof( CONNECTION ) * new_size );
1029 else Log( LOG_DEBUG, "Allocated new connection pool for %ld items (%ld bytes). [realloc()]", new_size, sizeof( CONNECTION ) * new_size );
1032 /* Adjust pointer to new block */
1033 My_Connections = (CONNECTION *)ptr;
1035 /* Initialize new items */
1036 for( idx = Pool_Size; idx < new_size; idx++ ) Init_Conn_Struct( idx );
1039 /* Adjust new pool size */
1040 Pool_Size = new_size;
1043 /* Client-Struktur initialisieren */
1044 c = Client_NewLocal( idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWN, FALSE );
1047 Log( LOG_ALERT, "Can't accept connection: can't create client structure!" );
1048 Simple_Message( new_sock, "ERROR :Internal error" );
1053 /* Verbindung registrieren */
1054 Init_Conn_Struct( idx );
1055 My_Connections[idx].sock = new_sock;
1056 My_Connections[idx].addr = new_addr;
1058 /* Neuen Socket registrieren */
1059 FD_SET( new_sock, &My_Sockets );
1060 if( new_sock > Conn_MaxFD ) Conn_MaxFD = new_sock;
1062 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 );
1064 /* Hostnamen ermitteln */
1065 strlcpy( My_Connections[idx].host, inet_ntoa( new_addr.sin_addr ), sizeof( My_Connections[idx].host ));
1066 Client_SetHostname( c, My_Connections[idx].host );
1068 s = Resolve_Addr( &new_addr, My_Connections[idx].sock );
1070 s = Resolve_Addr( &new_addr );
1074 /* Sub-Prozess wurde asyncron gestartet */
1075 My_Connections[idx].res_stat = s;
1078 /* Penalty-Zeit setzen */
1079 Conn_SetPenalty( idx, 4 );
1080 } /* New_Connection */
1084 Socket2Index( INT Sock )
1086 /* zum Socket passende Connection suchen */
1090 assert( Sock > NONE );
1092 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == Sock ) break;
1094 if( idx >= Pool_Size )
1096 /* die Connection wurde vermutlich (wegen eines
1097 * Fehlers) bereits wieder abgebaut ... */
1099 Log( LOG_DEBUG, "Socket2Index: can't get connection for socket %d!", Sock );
1104 } /* Socket2Index */
1108 Read_Request( CONN_ID Idx )
1110 /* Daten von Socket einlesen und entsprechend behandeln.
1111 * Tritt ein Fehler auf, so wird der Socket geschlossen. */
1118 assert( Idx > NONE );
1119 assert( My_Connections[Idx].sock > NONE );
1121 /* wenn noch nicht registriert: maximal mit ZREADBUFFER_LEN arbeiten,
1122 * ansonsten koennen Daten ggf. nicht umkopiert werden. */
1123 bsize = READBUFFER_LEN;
1125 c = Client_GetFromConn( Idx );
1126 if(( Client_Type( c ) != CLIENT_USER ) && ( Client_Type( c ) != CLIENT_SERVER ) && ( Client_Type( c ) != CLIENT_SERVICE ) && ( bsize > ZREADBUFFER_LEN )) bsize = ZREADBUFFER_LEN;
1130 if(( bsize - My_Connections[Idx].rdatalen - 1 < 1 ) || ( ZREADBUFFER_LEN - My_Connections[Idx].zip.rdatalen < 1 ))
1132 if( bsize - My_Connections[Idx].rdatalen - 1 < 1 )
1135 /* Der Lesepuffer ist voll */
1136 Log( LOG_ERR, "Read buffer overflow (connection %d): %d bytes!", Idx, My_Connections[Idx].rdatalen );
1137 Conn_Close( Idx, "Read buffer overflow!", NULL, FALSE );
1142 if( My_Connections[Idx].options & CONN_ZIP )
1144 len = recv( My_Connections[Idx].sock, My_Connections[Idx].zip.rbuf + My_Connections[Idx].zip.rdatalen, ( ZREADBUFFER_LEN - My_Connections[Idx].zip.rdatalen ), 0 );
1145 if( len > 0 ) My_Connections[Idx].zip.rdatalen += len;
1150 len = recv( My_Connections[Idx].sock, My_Connections[Idx].rbuf + My_Connections[Idx].rdatalen, bsize - My_Connections[Idx].rdatalen - 1, 0 );
1151 if( len > 0 ) My_Connections[Idx].rdatalen += len;
1156 /* Socket wurde geschlossen */
1157 Log( LOG_INFO, "%s:%d (%s) is closing the connection ...", My_Connections[Idx].host, ntohs( My_Connections[Idx].addr.sin_port), inet_ntoa( My_Connections[Idx].addr.sin_addr ));
1158 Conn_Close( Idx, "Socket closed!", "Client closed connection", FALSE );
1164 /* Operation haette Socket "nur" blockiert ... */
1165 if( errno == EAGAIN ) return;
1167 /* Fehler beim Lesen */
1168 Log( LOG_ERR, "Read error on connection %d (socket %d): %s!", Idx, My_Connections[Idx].sock, strerror( errno ));
1169 Conn_Close( Idx, "Read error!", "Client closed connection", FALSE );
1173 /* Connection-Statistik aktualisieren */
1174 My_Connections[Idx].bytes_in += len;
1176 /* Timestamp aktualisieren */
1177 My_Connections[Idx].lastdata = time( NULL );
1179 Handle_Buffer( Idx );
1180 } /* Read_Request */
1184 Handle_Buffer( CONN_ID Idx )
1186 /* Daten im Lese-Puffer einer Verbindung verarbeiten.
1187 * Wurde ein Request verarbeitet, so wird TRUE geliefert,
1188 * ansonsten FALSE (auch bei Fehlern). */
1195 BOOLEAN action, result;
1204 if( My_Connections[Idx].delaytime > time( NULL )) return result;
1207 /* ggf. noch unkomprimiete Daten weiter entpacken */
1208 if( My_Connections[Idx].options & CONN_ZIP )
1210 if( ! Unzip_Buffer( Idx )) return FALSE;
1214 if( My_Connections[Idx].rdatalen < 1 ) break;
1216 /* Eine komplette Anfrage muss mit CR+LF enden, vgl.
1217 * RFC 2812. Haben wir eine? */
1218 My_Connections[Idx].rbuf[My_Connections[Idx].rdatalen] = '\0';
1219 ptr = strstr( My_Connections[Idx].rbuf, "\r\n" );
1221 if( ptr ) delta = 2;
1225 /* Nicht RFC-konforme Anfrage mit nur CR oder LF? Leider
1226 * machen soetwas viele Clients, u.a. "mIRC" :-( */
1227 ptr1 = strchr( My_Connections[Idx].rbuf, '\r' );
1228 ptr2 = strchr( My_Connections[Idx].rbuf, '\n' );
1230 if( ptr1 && ptr2 ) ptr = ptr1 > ptr2 ? ptr2 : ptr1;
1231 else if( ptr1 ) ptr = ptr1;
1232 else if( ptr2 ) ptr = ptr2;
1239 /* Ende der Anfrage wurde gefunden */
1241 len = ( ptr - My_Connections[Idx].rbuf ) + delta;
1242 if( len > ( COMMAND_LEN - 1 ))
1244 /* Eine Anfrage darf(!) nicht laenger als 512 Zeichen
1245 * (incl. CR+LF!) werden; vgl. RFC 2812. Wenn soetwas
1246 * empfangen wird, wird der Client disconnectiert. */
1247 Log( LOG_ERR, "Request too long (connection %d): %d bytes (max. %d expected)!", Idx, My_Connections[Idx].rdatalen, COMMAND_LEN - 1 );
1248 Conn_Close( Idx, NULL, "Request too long", TRUE );
1253 /* merken, ob Stream bereits komprimiert wird */
1254 old_z = My_Connections[Idx].options & CONN_ZIP;
1259 /* Es wurde ein Request gelesen */
1260 My_Connections[Idx].msg_in++;
1261 if( ! Parse_Request( Idx, My_Connections[Idx].rbuf )) return FALSE;
1265 /* Puffer anpassen */
1266 My_Connections[Idx].rdatalen -= len;
1267 memmove( My_Connections[Idx].rbuf, My_Connections[Idx].rbuf + len, My_Connections[Idx].rdatalen );
1270 if(( ! old_z ) && ( My_Connections[Idx].options & CONN_ZIP ) && ( My_Connections[Idx].rdatalen > 0 ))
1272 /* Mit dem letzten Befehl wurde Socket-Kompression aktiviert.
1273 * Evtl. schon vom Socket gelesene Daten in den Unzip-Puffer
1274 * umkopieren, damit diese nun zunaechst entkomprimiert werden */
1276 if( My_Connections[Idx].rdatalen > ZREADBUFFER_LEN )
1278 /* Hupsa! Soviel Platz haben wir aber gar nicht! */
1279 Log( LOG_ALERT, "Can't move read buffer: No space left in unzip buffer (need %d bytes)!", My_Connections[Idx].rdatalen );
1282 memcpy( My_Connections[Idx].zip.rbuf, My_Connections[Idx].rbuf, My_Connections[Idx].rdatalen );
1283 My_Connections[Idx].zip.rdatalen = My_Connections[Idx].rdatalen;
1284 My_Connections[Idx].rdatalen = 0;
1286 Log( LOG_DEBUG, "Moved already received data (%d bytes) to uncompression buffer.", My_Connections[Idx].zip.rdatalen );
1293 if( action ) result = TRUE;
1297 } /* Handle_Buffer */
1301 Check_Connections( VOID )
1303 /* Pruefen, ob Verbindungen noch "alive" sind. Ist dies
1304 * nicht der Fall, zunaechst PING-PONG spielen und, wenn
1305 * auch das nicht "hilft", Client disconnectieren. */
1310 for( i = 0; i < Pool_Size; i++ )
1312 if( My_Connections[i].sock == NONE ) continue;
1314 c = Client_GetFromConn( i );
1315 if( c && (( Client_Type( c ) == CLIENT_USER ) || ( Client_Type( c ) == CLIENT_SERVER ) || ( Client_Type( c ) == CLIENT_SERVICE )))
1317 /* verbundener User, Server oder Service */
1318 if( My_Connections[i].lastping > My_Connections[i].lastdata )
1320 /* es wurde bereits ein PING gesendet */
1321 if( My_Connections[i].lastping < time( NULL ) - Conf_PongTimeout )
1325 Log( LOG_DEBUG, "Connection %d: Ping timeout: %d seconds.", i, Conf_PongTimeout );
1327 Conn_Close( i, NULL, "Ping timeout", TRUE );
1330 else if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout )
1332 /* es muss ein PING gesendet werden */
1334 Log( LOG_DEBUG, "Connection %d: sending PING ...", i );
1336 My_Connections[i].lastping = time( NULL );
1337 Conn_WriteStr( i, "PING :%s", Client_ID( Client_ThisServer( )));
1342 /* noch nicht vollstaendig aufgebaute Verbindung */
1343 if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout )
1347 Log( LOG_DEBUG, "Connection %d timed out ...", i );
1349 Conn_Close( i, NULL, "Timeout", FALSE );
1353 } /* Check_Connections */
1357 Check_Servers( VOID )
1359 /* Check if we can establish further server links */
1365 /* Serach all connections, are there results from the resolver? */
1366 for( idx = 0; idx < Pool_Size; idx++ )
1368 if( My_Connections[idx].sock != SERVER_WAIT ) continue;
1371 if( My_Connections[idx].res_stat == NULL ) New_Server( Conf_GetServer( idx ), idx );
1374 /* Check all configured servers */
1375 for( i = 0; i < MAX_SERVERS; i++ )
1377 /* Valid outgoing server which isn't already connected or disabled? */
1378 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;
1380 /* Is there already a connection in this group? */
1381 if( Conf_Server[i].group > NONE )
1383 for( n = 0; n < MAX_SERVERS; n++ )
1385 if( n == i ) continue;
1386 if(( Conf_Server[n].conn_id > NONE ) && ( Conf_Server[n].group == Conf_Server[i].group )) break;
1388 if( n < MAX_SERVERS ) continue;
1391 /* Check last connect attempt? */
1392 if( Conf_Server[i].lasttry > time( NULL ) - Conf_ConnectRetry ) continue;
1394 /* Okay, try to connect now */
1395 Conf_Server[i].lasttry = time( NULL );
1397 /* Search free connection structure */
1398 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
1399 if( idx >= Pool_Size )
1401 Log( LOG_ALERT, "Can't establist server connection: connection limit reached (%d)!", Pool_Size );
1405 Log( LOG_DEBUG, "Preparing connection %d for \"%s\" ...", idx, Conf_Server[i].host );
1408 /* Verbindungs-Struktur initialisieren */
1409 Init_Conn_Struct( idx );
1410 My_Connections[idx].sock = SERVER_WAIT;
1411 Conf_Server[i].conn_id = idx;
1413 /* Resolve Hostname. If this fails, try to use it as an IP address */
1414 strlcpy( Conf_Server[i].ip, Conf_Server[i].host, sizeof( Conf_Server[i].ip ));
1415 strlcpy( My_Connections[idx].host, Conf_Server[i].host, sizeof( My_Connections[idx].host ));
1416 s = Resolve_Name( Conf_Server[i].host );
1419 /* Sub-Prozess wurde asyncron gestartet */
1420 My_Connections[idx].res_stat = s;
1423 } /* Check_Servers */
1427 New_Server( INT Server, CONN_ID Idx )
1429 /* Establish new server link */
1431 struct sockaddr_in new_addr;
1432 struct in_addr inaddr;
1436 assert( Server > NONE );
1437 assert( Idx > NONE );
1439 /* Did we get a valid IP address? */
1440 if( ! Conf_Server[Server].ip[0] )
1442 /* No. Free connection structure and abort: */
1443 Init_Conn_Struct( Idx );
1444 Conf_Server[Server].conn_id = NONE;
1445 Log( LOG_ERR, "Can't connect to \"%s\" (connection %d): ip address unknown!", Conf_Server[Server].host, Idx );
1449 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 );
1451 #ifdef HAVE_INET_ATON
1452 if( inet_aton( Conf_Server[Server].ip, &inaddr ) == 0 )
1454 memset( &inaddr, 0, sizeof( inaddr ));
1455 inaddr.s_addr = inet_addr( Conf_Server[Server].ip );
1456 if( inaddr.s_addr == (unsigned)-1 )
1459 /* Can't convert IP address */
1460 Init_Conn_Struct( Idx );
1461 Conf_Server[Server].conn_id = NONE;
1462 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 );
1466 memset( &new_addr, 0, sizeof( new_addr ));
1467 new_addr.sin_family = AF_INET;
1468 new_addr.sin_addr = inaddr;
1469 new_addr.sin_port = htons( Conf_Server[Server].port );
1471 new_sock = socket( PF_INET, SOCK_STREAM, 0 );
1474 /* Can't create socket */
1475 Init_Conn_Struct( Idx );
1476 Conf_Server[Server].conn_id = NONE;
1477 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
1481 if( ! Init_Socket( new_sock )) return;
1483 res = connect( new_sock, (struct sockaddr *)&new_addr, sizeof( new_addr ));
1484 if(( res != 0 ) && ( errno != EINPROGRESS ))
1486 /* Can't connect socket */
1487 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1489 Init_Conn_Struct( Idx );
1490 Conf_Server[Server].conn_id = NONE;
1494 /* Client-Struktur initialisieren */
1495 c = Client_NewLocal( Idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWNSERVER, FALSE );
1498 /* Can't create new client structure */
1500 Init_Conn_Struct( Idx );
1501 Conf_Server[Server].conn_id = NONE;
1502 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1505 Client_SetIntroducer( c, c );
1506 Client_SetToken( c, TOKEN_OUTBOUND );
1508 /* Register connection */
1509 My_Connections[Idx].sock = new_sock;
1510 My_Connections[Idx].addr = new_addr;
1511 strlcpy( My_Connections[Idx].host, Conf_Server[Server].host, sizeof( My_Connections[Idx].host ));
1513 /* Register new socket */
1514 FD_SET( new_sock, &My_Sockets );
1515 FD_SET( new_sock, &My_Connects );
1516 if( new_sock > Conn_MaxFD ) Conn_MaxFD = new_sock;
1519 Log( LOG_DEBUG, "Registered new connection %d on socket %d.", Idx, My_Connections[Idx].sock );
1525 Init_Conn_Struct( CONN_ID Idx )
1527 /* Connection-Struktur initialisieren */
1529 My_Connections[Idx].sock = NONE;
1530 My_Connections[Idx].res_stat = NULL;
1531 My_Connections[Idx].host[0] = '\0';
1532 My_Connections[Idx].rbuf[0] = '\0';
1533 My_Connections[Idx].rdatalen = 0;
1534 My_Connections[Idx].wbuf[0] = '\0';
1535 My_Connections[Idx].wdatalen = 0;
1536 My_Connections[Idx].starttime = time( NULL );
1537 My_Connections[Idx].lastdata = time( NULL );
1538 My_Connections[Idx].lastping = 0;
1539 My_Connections[Idx].lastprivmsg = time( NULL );
1540 My_Connections[Idx].delaytime = 0;
1541 My_Connections[Idx].bytes_in = 0;
1542 My_Connections[Idx].bytes_out = 0;
1543 My_Connections[Idx].msg_in = 0;
1544 My_Connections[Idx].msg_out = 0;
1545 My_Connections[Idx].flag = 0;
1546 My_Connections[Idx].options = 0;
1549 My_Connections[Idx].zip.rbuf[0] = '\0';
1550 My_Connections[Idx].zip.rdatalen = 0;
1551 My_Connections[Idx].zip.wbuf[0] = '\0';
1552 My_Connections[Idx].zip.wdatalen = 0;
1553 My_Connections[Idx].zip.bytes_in = 0;
1554 My_Connections[Idx].zip.bytes_out = 0;
1556 } /* Init_Conn_Struct */
1560 Init_Socket( INT Sock )
1562 /* Initialize socket (set options) */
1566 #ifdef O_NONBLOCK /* unknown on A/UX */
1567 if( fcntl( Sock, F_SETFL, O_NONBLOCK ) != 0 )
1569 Log( LOG_CRIT, "Can't enable non-blocking mode for socket: %s!", strerror( errno ));
1575 /* Don't block this port after socket shutdown */
1577 if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &value, (socklen_t)sizeof( value )) != 0 )
1579 Log( LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!", strerror( errno ));
1580 /* ignore this error */
1583 /* Set type of service (TOS) */
1584 #if defined(IP_TOS) && defined(IPTOS_LOWDELAY)
1585 value = IPTOS_LOWDELAY;
1587 Log( LOG_DEBUG, "Setting option IP_TOS on socket %d to IPTOS_LOWDELAY (%d).", Sock, value );
1589 if( setsockopt( Sock, SOL_IP, IP_TOS, &value, (socklen_t)sizeof( value )) != 0 )
1591 Log( LOG_ERR, "Can't set socket option IP_TOS: %s!", strerror( errno ));
1592 /* ignore this error */
1601 Read_Resolver_Result( INT r_fd )
1603 /* Read result of resolver sub-process from pipe and update the
1604 * apropriate connection/client structure(s): hostname and/or
1605 * IDENT user name.*/
1612 /* Search associated connection ... */
1613 for( i = 0; i < Pool_Size; i++ )
1615 if(( My_Connections[i].sock != NONE )
1616 && ( My_Connections[i].res_stat != NULL )
1617 && ( My_Connections[i].res_stat->pipe[0] == r_fd ))
1620 if( i >= Pool_Size )
1622 /* Ops, none found? Probably the connection has already
1623 * been closed!? We'll ignore that ... */
1624 FD_CLR( r_fd, &Resolver_FDs );
1627 Log( LOG_DEBUG, "Resolver: Got result for unknown connection!?" );
1632 /* Get resolver structure */
1633 s = My_Connections[i].res_stat;
1634 assert( s != NULL );
1636 /* Read result from pipe */
1637 len = read( r_fd, s->buffer + s->bufpos, sizeof( s->buffer ) - s->bufpos - 1 );
1642 Log( LOG_CRIT, "Resolver: Can't read result: %s!", strerror( errno ));
1646 s->buffer[s->bufpos] = '\0';
1648 /* If the result string is incomplete, return to main loop and
1649 * wait until we can read in more bytes. */
1653 ptr = strchr( s->buffer, '\n' );
1658 Log( LOG_DEBUG, "Got result from resolver: \"%s\" (%d bytes), stage %d.", s->buffer, len, s->stage );
1661 /* Okay, we got a complete result: this is a host name for outgoing
1662 * connections and a host name or IDENT user name (if enabled) for
1663 * incoming conneciions.*/
1664 if( My_Connections[i].sock > NONE )
1666 /* Incoming connection */
1668 /* Search client ... */
1669 c = Client_GetFromConn( i );
1670 assert( c != NULL );
1672 /* Only update client information of unregistered clients */
1673 if( Client_Type( c ) == CLIENT_UNKNOWN )
1678 strlcpy( My_Connections[i].host, s->buffer, sizeof( My_Connections[i].host ));
1679 Client_SetHostname( c, s->buffer );
1682 /* clean up buffer for IDENT result */
1683 len = strlen( s->buffer ) + 1;
1684 memmove( s->buffer, s->buffer + len, sizeof( s->buffer ) - len );
1687 /* Don't close pipe and clean up, but
1688 * instead wait for IDENT result */
1692 else if( s->stage == 1 )
1694 /* IDENT user name */
1697 Log( LOG_INFO, "IDENT lookup for connection %ld: \"%s\".", i, s->buffer );
1698 Client_SetUser( c, s->buffer, TRUE );
1700 else Log( LOG_INFO, "IDENT lookup for connection %ld: no result.", i );
1703 else Log( LOG_ERR, "Resolver: got result for unknown stage %d!?", s->stage );
1706 else Log( LOG_DEBUG, "Resolver: discarding result for already registered connection %d.", i );
1711 /* Outgoing connection (server link): set the IP address
1712 * so that we can connect to it in the main loop. */
1714 /* Search server ... */
1715 n = Conf_GetServer( i );
1718 strlcpy( Conf_Server[n].ip, s->buffer, sizeof( Conf_Server[n].ip ));
1722 FD_CLR( r_fd, &Resolver_FDs );
1723 close( My_Connections[i].res_stat->pipe[0] );
1724 close( My_Connections[i].res_stat->pipe[1] );
1725 free( My_Connections[i].res_stat );
1726 My_Connections[i].res_stat = NULL;
1728 /* Reset penalty time */
1729 Conn_ResetPenalty( i );
1730 } /* Read_Resolver_Result */
1734 Simple_Message( INT Sock, CHAR *Msg )
1736 /* Write "simple" message to socket, without using compression
1737 * or even the connection write buffers. Used e.g. for error
1738 * messages by New_Connection(). */
1740 assert( Sock > NONE );
1741 assert( Msg != NULL );
1743 (VOID)send( Sock, Msg, strlen( Msg ), 0 );
1744 (VOID)send( Sock, "\r\n", 2, 0 );
1745 } /* Simple_Error */
1749 Count_Connections( struct sockaddr_in addr_in )
1754 for( i = 0; i < Pool_Size; i++ )
1756 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].addr.sin_addr.s_addr == addr_in.sin_addr.s_addr )) cnt++;
1759 } /* Count_Connections */