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.140 2004/10/20 13:47:32 alex Exp $";
34 #include <sys/socket.h>
36 #include <sys/types.h>
38 #include <netinet/in.h>
40 #ifdef HAVE_NETINET_IP_H
41 # include <netinet/ip.h>
44 #ifdef HAVE_ARPA_INET_H
45 # include <arpa/inet.h>
47 # define PF_INET AF_INET
51 # include <stdint.h> /* e.g. for Mac OS X */
55 # include <tcpd.h> /* for TCP Wrappers */
69 #include "conn-func.h"
75 # include "rendezvous.h"
81 #define SERVER_WAIT (NONE - 1)
84 LOCAL VOID Handle_Read PARAMS(( INT sock ));
85 LOCAL BOOLEAN 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 BOOLEAN Try_Write PARAMS(( CONN_ID Idx ));
90 LOCAL BOOLEAN Handle_Buffer PARAMS(( CONN_ID Idx ));
91 LOCAL VOID Check_Connections PARAMS(( VOID ));
92 LOCAL VOID Check_Servers PARAMS(( VOID ));
93 LOCAL VOID Init_Conn_Struct PARAMS(( CONN_ID Idx ));
94 LOCAL BOOLEAN Init_Socket PARAMS(( INT Sock ));
95 LOCAL VOID New_Server PARAMS(( INT Server, CONN_ID Idx ));
96 LOCAL VOID Read_Resolver_Result PARAMS(( INT r_fd ));
97 LOCAL VOID Simple_Message PARAMS(( INT Sock, CHAR *Msg ));
98 LOCAL INT Count_Connections PARAMS(( struct sockaddr_in addr ));
100 LOCAL fd_set My_Listeners;
101 LOCAL fd_set My_Sockets;
102 LOCAL fd_set My_Connects;
105 INT allow_severity = LOG_INFO;
106 INT deny_severity = LOG_ERR;
113 /* Modul initialisieren: statische Strukturen "ausnullen". */
117 /* Speicher fuer Verbindungs-Pool anfordern */
118 Pool_Size = CONNECTION_POOL;
119 if( Conf_MaxConnections > 0 )
121 /* konfiguriertes Limit beachten */
122 if( Pool_Size > Conf_MaxConnections ) Pool_Size = Conf_MaxConnections;
124 My_Connections = (CONNECTION *)malloc( sizeof( CONNECTION ) * Pool_Size );
125 if( ! My_Connections )
127 /* Speicher konnte nicht alloziert werden! */
128 Log( LOG_EMERG, "Can't allocate memory! [Conn_Init]" );
132 Log( LOG_DEBUG, "Allocated connection pool for %d items (%ld bytes).", Pool_Size, sizeof( CONNECTION ) * Pool_Size );
135 /* zu Beginn haben wir keine Verbindungen */
136 FD_ZERO( &My_Listeners );
137 FD_ZERO( &My_Sockets );
138 FD_ZERO( &My_Connects );
140 /* Groesster File-Descriptor fuer select() */
143 /* Connection-Struktur initialisieren */
144 for( i = 0; i < Pool_Size; i++ ) Init_Conn_Struct( i );
146 /* Global write counter */
154 /* Modul abmelden: alle noch offenen Connections
155 * schliessen und freigeben. */
161 Log( LOG_DEBUG, "Shutting down all connections ..." );
165 Rendezvous_UnregisterListeners( );
168 /* Sockets schliessen */
169 for( i = 0; i < Conn_MaxFD + 1; i++ )
171 if( FD_ISSET( i, &My_Sockets ))
173 for( idx = 0; idx < Pool_Size; idx++ )
175 if( My_Connections[idx].sock == i ) break;
177 if( FD_ISSET( i, &My_Listeners ))
181 Log( LOG_DEBUG, "Listening socket %d closed.", i );
184 else if( FD_ISSET( i, &My_Connects ))
188 Log( LOG_DEBUG, "Connection %d closed during creation (socket %d).", idx, i );
191 else if( idx < Pool_Size )
193 if( NGIRCd_SignalRestart ) Conn_Close( idx, NULL, "Server going down (restarting)", TRUE );
194 else Conn_Close( idx, NULL, "Server going down", TRUE );
198 Log( LOG_WARNING, "Closing unknown connection %d ...", i );
204 free( My_Connections );
205 My_Connections = NULL;
211 Conn_InitListeners( VOID )
213 /* Initialize ports on which the server should accept connections */
218 for( i = 0; i < Conf_ListenPorts_Count; i++ )
220 if( Conn_NewListener( Conf_ListenPorts[i] )) created++;
221 else Log( LOG_ERR, "Can't listen on port %u!", Conf_ListenPorts[i] );
224 } /* Conn_InitListeners */
228 Conn_ExitListeners( VOID )
230 /* Close down all listening sockets */
235 Rendezvous_UnregisterListeners( );
238 Log( LOG_INFO, "Shutting down all listening sockets ..." );
239 for( i = 0; i < Conn_MaxFD + 1; i++ )
241 if( FD_ISSET( i, &My_Sockets ) && FD_ISSET( i, &My_Listeners ))
245 Log( LOG_DEBUG, "Listening socket %d closed.", i );
249 } /* Conn_ExitListeners */
253 Conn_NewListener( CONST UINT Port )
255 /* Create new listening socket on specified port */
257 struct sockaddr_in addr;
258 struct in_addr inaddr;
261 CHAR name[CLIENT_ID_LEN], *info;
264 /* Server-"Listen"-Socket initialisieren */
265 memset( &addr, 0, sizeof( addr ));
266 memset( &inaddr, 0, sizeof( inaddr ));
267 addr.sin_family = AF_INET;
268 addr.sin_port = htons( Port );
269 if( Conf_ListenAddress[0] )
271 #ifdef HAVE_INET_ATON
272 if( inet_aton( Conf_ListenAddress, &inaddr ) == 0 )
274 inaddr.s_addr = inet_addr( Conf_ListenAddress );
275 if( inaddr.s_addr == (unsigned)-1 )
278 Log( LOG_CRIT, "Can't listen on %s:%u: can't convert ip address %s!", Conf_ListenAddress, Port, Conf_ListenAddress );
282 else inaddr.s_addr = htonl( INADDR_ANY );
283 addr.sin_addr = inaddr;
285 /* Socket erzeugen */
286 sock = socket( PF_INET, SOCK_STREAM, 0);
289 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
293 if( ! Init_Socket( sock )) return FALSE;
296 if( bind( sock, (struct sockaddr *)&addr, (socklen_t)sizeof( addr )) != 0 )
298 Log( LOG_CRIT, "Can't bind socket: %s!", strerror( errno ));
303 /* in "listen mode" gehen :-) */
304 if( listen( sock, 10 ) != 0 )
306 Log( LOG_CRIT, "Can't listen on soecket: %s!", strerror( errno ));
311 /* Neuen Listener in Strukturen einfuegen */
312 FD_SET( sock, &My_Listeners );
313 FD_SET( sock, &My_Sockets );
315 if( sock > Conn_MaxFD ) Conn_MaxFD = sock;
317 if( Conf_ListenAddress[0]) Log( LOG_INFO, "Now listening on %s:%d (socket %d).", Conf_ListenAddress, Port, sock );
318 else Log( LOG_INFO, "Now listening on 0.0.0.0:%d (socket %d).", Port, sock );
321 /* Get best server description text */
322 if( ! Conf_ServerInfo[0] ) info = Conf_ServerName;
325 /* Use server info string */
327 if( Conf_ServerInfo[0] == '[' )
329 /* Cut off leading hostname part in "[]" */
330 info = strchr( Conf_ServerInfo, ']' );
334 while( *info == ' ' ) info++;
337 if( ! info ) info = Conf_ServerInfo;
340 /* Add port number to description if non-standard */
341 if( Port != 6667 ) snprintf( name, sizeof( name ), "%s (port %u)", info, Port );
342 else strlcpy( name, info, sizeof( name ));
344 /* Register service */
345 Rendezvous_Register( name, RENDEZVOUS_TYPE, Port );
349 } /* Conn_NewListener */
355 /* "Hauptschleife": Aktive Verbindungen ueberwachen. Folgende Aktionen
356 * werden dabei durchgefuehrt, bis der Server terminieren oder neu
359 * - neue Verbindungen annehmen,
360 * - Server-Verbindungen aufbauen,
361 * - geschlossene Verbindungen loeschen,
362 * - volle Schreibpuffer versuchen zu schreiben,
363 * - volle Lesepuffer versuchen zu verarbeiten,
364 * - Antworten von Resolver Sub-Prozessen annehmen.
367 fd_set read_sockets, write_sockets;
373 start = time( NULL );
374 while(( ! NGIRCd_SignalQuit ) && ( ! NGIRCd_SignalRestart ))
379 Rendezvous_Handler( );
382 /* Should the configuration be reloaded? */
383 if( NGIRCd_SignalRehash ) NGIRCd_Rehash( );
385 /* Check configured servers and established links */
387 Check_Connections( );
391 /* noch volle Lese-Buffer suchen */
392 for( i = 0; i < Pool_Size; i++ )
394 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].rdatalen > 0 ) &&
395 ( My_Connections[i].delaytime < t ))
397 /* Kann aus dem Buffer noch ein Befehl extrahiert werden? */
398 if( Handle_Buffer( i )) timeout = FALSE;
402 /* noch volle Schreib-Puffer suchen */
403 FD_ZERO( &write_sockets );
404 for( i = 0; i < Pool_Size; i++ )
407 if(( My_Connections[i].sock > NONE ) && (( My_Connections[i].wdatalen > 0 ) || ( My_Connections[i].zip.wdatalen > 0 )))
409 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].wdatalen > 0 ))
412 /* Socket der Verbindung in Set aufnehmen */
413 FD_SET( My_Connections[i].sock, &write_sockets );
417 /* Sockets mit im Aufbau befindlichen ausgehenden Verbindungen suchen */
418 for( i = 0; i < Pool_Size; i++ )
420 if(( My_Connections[i].sock > NONE ) && ( FD_ISSET( My_Connections[i].sock, &My_Connects ))) FD_SET( My_Connections[i].sock, &write_sockets );
423 /* von welchen Sockets koennte gelesen werden? */
424 read_sockets = My_Sockets;
425 for( i = 0; i < Pool_Size; i++ )
427 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].host[0] == '\0' ))
429 /* Hier muss noch auf den Resolver Sub-Prozess gewartet werden */
430 FD_CLR( My_Connections[i].sock, &read_sockets );
432 if(( My_Connections[i].sock > NONE ) && ( FD_ISSET( My_Connections[i].sock, &My_Connects )))
434 /* Hier laeuft noch ein asyncrones connect() */
435 FD_CLR( My_Connections[i].sock, &read_sockets );
437 if( My_Connections[i].delaytime > t )
439 /* Fuer die Verbindung ist eine "Penalty-Zeit" gesetzt */
440 FD_CLR( My_Connections[i].sock, &read_sockets );
443 for( i = 0; i < Conn_MaxFD + 1; i++ )
445 /* Pipes von Resolver Sub-Prozessen aufnehmen */
446 if( FD_ISSET( i, &Resolver_FDs ))
448 FD_SET( i, &read_sockets );
452 /* Timeout initialisieren */
454 if( timeout ) tv.tv_sec = 1;
457 /* Auf Aktivitaet warten */
458 i = select( Conn_MaxFD + 1, &read_sockets, &write_sockets, NULL, &tv );
461 /* keine Veraenderung an den Sockets */
466 /* Fehler (z.B. Interrupt) */
469 Log( LOG_EMERG, "Conn_Handler(): select(): %s!", strerror( errno ));
470 Log( LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE_NAME );
476 /* Koennen Daten geschrieben werden? */
477 for( i = 0; i < Conn_MaxFD + 1; i++ )
479 if( ! FD_ISSET( i, &write_sockets )) continue;
481 /* Es kann geschrieben werden ... */
482 idx = Socket2Index( i );
483 if( idx == NONE ) continue;
485 if( ! Handle_Write( idx ))
487 /* Fehler beim Schreiben! Diesen Socket nun
488 * auch aus dem Read-Set entfernen: */
489 FD_CLR( i, &read_sockets );
493 /* Daten zum Lesen vorhanden? */
494 for( i = 0; i < Conn_MaxFD + 1; i++ )
496 if( FD_ISSET( i, &read_sockets )) Handle_Read( i );
500 if( NGIRCd_SignalQuit ) Log( LOG_NOTICE|LOG_snotice, "Server going down NOW!" );
501 else if( NGIRCd_SignalRestart ) Log( LOG_NOTICE|LOG_snotice, "Server restarting NOW!" );
507 Conn_WriteStr( CONN_ID Idx, CHAR *Format, ... )
510 Conn_WriteStr( Idx, Format, va_alist )
516 /* String in Socket schreiben. CR+LF wird von dieser Funktion
517 * automatisch angehaengt. Im Fehlerfall wird dir Verbindung
518 * getrennt und FALSE geliefert. */
520 CHAR buffer[COMMAND_LEN];
524 assert( Idx > NONE );
525 assert( Format != NULL );
528 va_start( ap, Format );
532 if( vsnprintf( buffer, COMMAND_LEN - 2, Format, ap ) == COMMAND_LEN - 2 )
534 Log( LOG_CRIT, "Text too long to send (connection %d)!", Idx );
535 Conn_Close( Idx, "Text too long to send!", NULL, FALSE );
540 if( NGIRCd_Sniffer ) Log( LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer );
543 strlcat( buffer, "\r\n", sizeof( buffer ));
544 ok = Conn_Write( Idx, buffer, strlen( buffer ));
545 My_Connections[Idx].msg_out++;
549 } /* Conn_WriteStr */
553 Conn_Write( CONN_ID Idx, CHAR *Data, INT Len )
555 /* Daten in Socket schreiben. Bei "fatalen" Fehlern wird
556 * der Client disconnectiert und FALSE geliefert. */
558 assert( Idx > NONE );
559 assert( Data != NULL );
562 /* Ist der entsprechende Socket ueberhaupt noch offen? In einem
563 * "Handler-Durchlauf" kann es passieren, dass dem nicht mehr so
564 * ist, wenn einer von mehreren Conn_Write()'s fehlgeschlagen ist.
565 * In diesem Fall wird hier einfach ein Fehler geliefert. */
566 if( My_Connections[Idx].sock <= NONE )
569 Log( LOG_DEBUG, "Skipped write on closed socket (connection %d).", Idx );
574 /* Pruefen, ob im Schreibpuffer genuegend Platz ist. Ziel ist es,
575 * moeglichts viel im Puffer zu haben und _nicht_ gleich alles auf den
576 * Socket zu schreiben (u.a. wg. Komprimierung). */
577 if( WRITEBUFFER_LEN - My_Connections[Idx].wdatalen - Len <= 0 )
579 /* Der Puffer ist dummerweise voll. Jetzt versuchen, den Puffer
580 * zu schreiben, wenn das nicht klappt, haben wir ein Problem ... */
581 if( ! Try_Write( Idx )) return FALSE;
583 /* nun neu pruefen: */
584 if( WRITEBUFFER_LEN - My_Connections[Idx].wdatalen - Len <= 0 )
586 Log( LOG_NOTICE, "Write buffer overflow (connection %d)!", Idx );
587 Conn_Close( Idx, "Write buffer overflow!", NULL, FALSE );
593 if( My_Connections[Idx].options & CONN_ZIP )
595 /* Daten komprimieren und in Puffer kopieren */
596 if( ! Zip_Buffer( Idx, Data, Len )) return FALSE;
601 /* Daten in Puffer kopieren */
602 memcpy( My_Connections[Idx].wbuf + My_Connections[Idx].wdatalen, Data, Len );
603 My_Connections[Idx].wdatalen += Len;
604 My_Connections[Idx].bytes_out += Len;
607 /* Adjust global write counter */
615 Conn_Close( CONN_ID Idx, CHAR *LogMsg, CHAR *FwdMsg, BOOLEAN InformClient )
617 /* Close connection. Open pipes of asyncronous resolver
618 * sub-processes are closed down. */
624 DOUBLE in_z_k, out_z_k;
628 assert( Idx > NONE );
630 /* Is this link already shutting down? */
631 if( My_Connections[Idx].options & CONN_ISCLOSING )
633 /* Conn_Close() has been called recursively for this link;
634 * probabe reason: Try_Write() failed -- see below. */
638 assert( My_Connections[Idx].sock > NONE );
640 /* Mark link as "closing" */
641 My_Connections[Idx].options |= CONN_ISCLOSING;
643 if( LogMsg ) txt = LogMsg;
645 if( ! txt ) txt = "Reason unknown";
647 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 ));
649 /* Search client, if any */
650 c = Client_GetFromConn( Idx );
652 /* Should the client be informed? */
656 /* Send statistics to client if registered as user: */
657 if(( c != NULL ) && ( Client_Type( c ) == CLIENT_USER ))
659 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 );
663 /* Send ERROR to client (see RFC!) */
664 if( FwdMsg ) Conn_WriteStr( Idx, "ERROR :%s", FwdMsg );
665 else Conn_WriteStr( Idx, "ERROR :Closing connection." );
668 /* Try to write out the write buffer */
669 (VOID)Try_Write( Idx );
671 /* Shut down socket */
672 if( close( My_Connections[Idx].sock ) != 0 )
674 /* Oops, we can't close the socket!? This is fatal! */
675 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 ));
676 Log( LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE_NAME );
680 /* Mark socket as invalid: */
681 FD_CLR( My_Connections[Idx].sock, &My_Sockets );
682 FD_CLR( My_Connections[Idx].sock, &My_Connects );
683 My_Connections[Idx].sock = NONE;
685 /* If there is still a client, unregister it now */
686 if( c ) Client_Destroy( c, LogMsg, FwdMsg, TRUE );
688 /* Calculate statistics and log information */
689 in_k = (DOUBLE)My_Connections[Idx].bytes_in / 1024;
690 out_k = (DOUBLE)My_Connections[Idx].bytes_out / 1024;
692 if( My_Connections[Idx].options & CONN_ZIP )
694 in_z_k = (DOUBLE)My_Connections[Idx].zip.bytes_in / 1024;
695 out_z_k = (DOUBLE)My_Connections[Idx].zip.bytes_out / 1024;
696 in_p = (INT)(( in_k * 100 ) / in_z_k );
697 out_p = (INT)(( out_k * 100 ) / out_z_k );
698 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 );
703 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 );
706 /* Is there a resolver sub-process running? */
707 if( My_Connections[Idx].res_stat )
709 /* Free resolver structures */
710 FD_CLR( My_Connections[Idx].res_stat->pipe[0], &Resolver_FDs );
711 close( My_Connections[Idx].res_stat->pipe[0] );
712 close( My_Connections[Idx].res_stat->pipe[1] );
713 free( My_Connections[Idx].res_stat );
716 /* Servers: Modify time of next connect attempt? */
717 Conf_UnsetServer( Idx );
720 /* Clean up zlib, if link was compressed */
721 if( Conn_Options( Idx ) & CONN_ZIP )
723 inflateEnd( &My_Connections[Idx].zip.in );
724 deflateEnd( &My_Connections[Idx].zip.out );
728 /* Clean up connection structure (=free it) */
729 Init_Conn_Struct( Idx );
734 Conn_SyncServerStruct( VOID )
736 /* Synchronize server structures (connection IDs):
737 * connections <-> configuration */
743 for( i = 0; i < Pool_Size; i++ )
745 /* Established connection? */
746 if( My_Connections[i].sock <= NONE ) continue;
748 /* Server connection? */
749 client = Client_GetFromConn( i );
750 if(( ! client ) || ( Client_Type( client ) != CLIENT_SERVER )) continue;
752 for( c = 0; c < MAX_SERVERS; c++ )
754 /* Configured server? */
755 if( ! Conf_Server[c].host[0] ) continue;
758 if( strcmp( Conf_Server[c].name, Client_ID( client )) == 0 ) Conf_Server[c].conn_id = i;
761 } /* SyncServerStruct */
765 Try_Write( CONN_ID Idx )
767 /* Versuchen, Daten aus dem Schreib-Puffer in den Socket zu
768 * schreiben. TRUE wird geliefert, wenn entweder keine Daten
769 * zum Versenden vorhanden sind oder erfolgreich bearbeitet
770 * werden konnten. Im Fehlerfall wird FALSE geliefert und
771 * die Verbindung geschlossen. */
776 assert( Idx > NONE );
777 assert( My_Connections[Idx].sock > NONE );
779 /* sind ueberhaupt Daten vorhanden? */
781 if(( ! My_Connections[Idx].wdatalen > 0 ) && ( ! My_Connections[Idx].zip.wdatalen )) return TRUE;
783 if( ! My_Connections[Idx].wdatalen > 0 ) return TRUE;
786 /* Timeout initialisieren: 0 Sekunden, also nicht blockieren */
787 tv.tv_sec = 0; tv.tv_usec = 0;
789 FD_ZERO( &write_socket );
790 FD_SET( My_Connections[Idx].sock, &write_socket );
791 if( select( My_Connections[Idx].sock + 1, NULL, &write_socket, NULL, &tv ) == -1 )
796 Log( LOG_ALERT, "Try_Write(): select() failed: %s (con=%d, sock=%d)!", strerror( errno ), Idx, My_Connections[Idx].sock );
797 Conn_Close( Idx, "Server error!", NULL, FALSE );
802 if( FD_ISSET( My_Connections[Idx].sock, &write_socket )) return Handle_Write( Idx );
808 Handle_Read( INT Sock )
810 /* Aktivitaet auf einem Socket verarbeiten:
811 * - neue Clients annehmen,
812 * - Daten von Clients verarbeiten,
813 * - Resolver-Rueckmeldungen annehmen. */
817 assert( Sock > NONE );
819 if( FD_ISSET( Sock, &My_Listeners ))
821 /* es ist einer unserer Listener-Sockets: es soll
822 * also eine neue Verbindung aufgebaut werden. */
824 New_Connection( Sock );
826 else if( FD_ISSET( Sock, &Resolver_FDs ))
828 /* Rueckmeldung von einem Resolver Sub-Prozess */
830 Read_Resolver_Result( Sock );
834 /* Ein Client Socket: entweder ein User oder Server */
836 idx = Socket2Index( Sock );
837 if( idx > NONE ) Read_Request( idx );
843 Handle_Write( CONN_ID Idx )
845 /* Daten aus Schreibpuffer versenden bzw. Connection aufbauen */
851 assert( Idx > NONE );
852 assert( My_Connections[Idx].sock > NONE );
854 if( FD_ISSET( My_Connections[Idx].sock, &My_Connects ))
856 /* es soll nichts geschrieben werden, sondern ein
857 * connect() hat ein Ergebnis geliefert */
859 FD_CLR( My_Connections[Idx].sock, &My_Connects );
861 /* Ergebnis des connect() ermitteln */
862 sock_len = sizeof( err );
863 res = getsockopt( My_Connections[Idx].sock, SOL_SOCKET, SO_ERROR, &err, &sock_len );
864 assert( sock_len == sizeof( err ));
866 /* Fehler aufgetreten? */
867 if(( res != 0 ) || ( err != 0 ))
870 if( res != 0 ) Log( LOG_CRIT, "getsockopt (connection %d): %s!", Idx, strerror( errno ));
871 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 ));
873 /* Clean up socket, connection and client structures */
874 FD_CLR( My_Connections[Idx].sock, &My_Sockets );
875 c = Client_GetFromConn( Idx );
876 if( c ) Client_DestroyNow( c );
877 close( My_Connections[Idx].sock );
878 Init_Conn_Struct( Idx );
880 /* Bei Server-Verbindungen lasttry-Zeitpunkt auf "jetzt" setzen */
881 Conf_Server[Conf_GetServer( Idx )].lasttry = time( NULL );
882 Conf_UnsetServer( Idx );
886 Log( LOG_INFO, "Connection %d with \"%s:%d\" established. Now logging in ...", Idx, My_Connections[Idx].host, Conf_Server[Conf_GetServer( Idx )].port );
888 /* Send PASS and SERVER command to peer */
889 Conn_WriteStr( Idx, "PASS %s %s", Conf_Server[Conf_GetServer( Idx )].pwd_out, NGIRCd_ProtoID );
890 return Conn_WriteStr( Idx, "SERVER %s :%s", Conf_ServerName, Conf_ServerInfo );
894 /* Schreibpuffer leer, aber noch Daten im Kompressionsbuffer?
895 * Dann muss dieser nun geflushed werden! */
896 if( My_Connections[Idx].wdatalen == 0 ) Zip_Flush( Idx );
899 assert( My_Connections[Idx].wdatalen > 0 );
901 /* Daten schreiben */
902 len = send( My_Connections[Idx].sock, My_Connections[Idx].wbuf, My_Connections[Idx].wdatalen, 0 );
905 /* Operation haette Socket "nur" blockiert ... */
906 if( errno == EAGAIN ) return TRUE;
908 /* Oops, ein Fehler! */
909 Log( LOG_ERR, "Write error on connection %d (socket %d): %s!", Idx, My_Connections[Idx].sock, strerror( errno ));
910 Conn_Close( Idx, "Write error!", NULL, FALSE );
914 /* Puffer anpassen */
915 My_Connections[Idx].wdatalen -= len;
916 memmove( My_Connections[Idx].wbuf, My_Connections[Idx].wbuf + len, My_Connections[Idx].wdatalen );
923 New_Connection( INT Sock )
925 /* Neue Client-Verbindung von Listen-Socket annehmen und
926 * CLIENT-Struktur anlegen. */
929 struct request_info req;
931 struct sockaddr_in new_addr;
932 INT new_sock, new_sock_len;
939 assert( Sock > NONE );
941 /* Connection auf Listen-Socket annehmen */
942 new_sock_len = sizeof( new_addr );
943 new_sock = accept( Sock, (struct sockaddr *)&new_addr, (socklen_t *)&new_sock_len );
946 Log( LOG_CRIT, "Can't accept connection: %s!", strerror( errno ));
951 /* Validate socket using TCP Wrappers */
952 request_init( &req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock, RQ_CLIENT_SIN, &new_addr, NULL );
954 if( ! hosts_access( &req ))
957 Log( deny_severity, "Refused connection from %s (by TCP Wrappers)!", inet_ntoa( new_addr.sin_addr ));
958 Simple_Message( new_sock, "ERROR :Connection refused" );
964 /* Socket initialisieren */
965 Init_Socket( new_sock );
967 /* Check IP-based connection limit */
968 cnt = Count_Connections( new_addr );
969 if(( Conf_MaxConnectionsIP > 0 ) && ( cnt >= Conf_MaxConnectionsIP ))
971 /* Access denied, too many connections from this IP address! */
972 Log( LOG_ERR, "Refused connection from %s: too may connections (%ld) from this IP address!", inet_ntoa( new_addr.sin_addr ), cnt);
973 Simple_Message( new_sock, "ERROR :Connection refused, too many connections from your IP address!" );
978 /* Freie Connection-Struktur suchen */
979 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
980 if( idx >= Pool_Size )
982 new_size = Pool_Size + CONNECTION_POOL;
984 /* Im bisherigen Pool wurde keine freie Connection-Struktur mehr gefunden.
985 * Wenn erlaubt und moeglich muss nun der Pool vergroessert werden: */
987 if( Conf_MaxConnections > 0 )
989 /* Es ist ein Limit konfiguriert */
990 if( Pool_Size >= Conf_MaxConnections )
992 /* Mehr Verbindungen duerfen wir leider nicht mehr annehmen ... */
993 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached!", Pool_Size );
994 Simple_Message( new_sock, "ERROR :Connection limit reached" );
998 if( new_size > Conf_MaxConnections ) new_size = Conf_MaxConnections;
1000 if( new_size < Pool_Size )
1002 Log( LOG_ALERT, "Can't accespt connection: limit (%d) reached -- overflow!", Pool_Size );
1003 Simple_Message( new_sock, "ERROR :Connection limit reached" );
1008 /* zunaechst realloc() versuchen; wenn das scheitert, malloc() versuchen
1009 * und Daten ggf. "haendisch" umkopieren. (Haesslich! Eine wirklich
1010 * dynamische Verwaltung waere wohl _deutlich_ besser ...) */
1011 ptr = (POINTER *)realloc( My_Connections, sizeof( CONNECTION ) * new_size );
1014 /* realloc() ist fehlgeschlagen. Nun malloc() probieren: */
1015 ptr = (POINTER *)malloc( sizeof( CONNECTION ) * new_size );
1018 /* Offenbar steht kein weiterer Sepeicher zur Verfuegung :-( */
1019 Log( LOG_EMERG, "Can't allocate memory! [New_Connection]" );
1020 Simple_Message( new_sock, "ERROR: Internal error" );
1025 /* Struktur umkopieren ... */
1026 memcpy( ptr, My_Connections, sizeof( CONNECTION ) * Pool_Size );
1029 Log( LOG_DEBUG, "Allocated new connection pool for %ld items (%ld bytes). [malloc()/memcpy()]", new_size, sizeof( CONNECTION ) * new_size );
1033 else Log( LOG_DEBUG, "Allocated new connection pool for %ld items (%ld bytes). [realloc()]", new_size, sizeof( CONNECTION ) * new_size );
1036 /* Adjust pointer to new block */
1037 My_Connections = (CONNECTION *)ptr;
1039 /* Initialize new items */
1040 for( idx = Pool_Size; idx < new_size; idx++ ) Init_Conn_Struct( idx );
1043 /* Adjust new pool size */
1044 Pool_Size = new_size;
1047 /* Client-Struktur initialisieren */
1048 c = Client_NewLocal( idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWN, FALSE );
1051 Log( LOG_ALERT, "Can't accept connection: can't create client structure!" );
1052 Simple_Message( new_sock, "ERROR :Internal error" );
1057 /* Verbindung registrieren */
1058 Init_Conn_Struct( idx );
1059 My_Connections[idx].sock = new_sock;
1060 My_Connections[idx].addr = new_addr;
1062 /* Neuen Socket registrieren */
1063 FD_SET( new_sock, &My_Sockets );
1064 if( new_sock > Conn_MaxFD ) Conn_MaxFD = new_sock;
1066 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 );
1068 /* Hostnamen ermitteln */
1069 strlcpy( My_Connections[idx].host, inet_ntoa( new_addr.sin_addr ), sizeof( My_Connections[idx].host ));
1070 Client_SetHostname( c, My_Connections[idx].host );
1072 s = Resolve_Addr( &new_addr, My_Connections[idx].sock );
1074 s = Resolve_Addr( &new_addr );
1078 /* Sub-Prozess wurde asyncron gestartet */
1079 My_Connections[idx].res_stat = s;
1082 /* Penalty-Zeit setzen */
1083 Conn_SetPenalty( idx, 4 );
1084 } /* New_Connection */
1088 Socket2Index( INT Sock )
1090 /* zum Socket passende Connection suchen */
1094 assert( Sock > NONE );
1096 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == Sock ) break;
1098 if( idx >= Pool_Size )
1100 /* die Connection wurde vermutlich (wegen eines
1101 * Fehlers) bereits wieder abgebaut ... */
1103 Log( LOG_DEBUG, "Socket2Index: can't get connection for socket %d!", Sock );
1108 } /* Socket2Index */
1112 Read_Request( CONN_ID Idx )
1114 /* Daten von Socket einlesen und entsprechend behandeln.
1115 * Tritt ein Fehler auf, so wird der Socket geschlossen. */
1122 assert( Idx > NONE );
1123 assert( My_Connections[Idx].sock > NONE );
1125 /* wenn noch nicht registriert: maximal mit ZREADBUFFER_LEN arbeiten,
1126 * ansonsten koennen Daten ggf. nicht umkopiert werden. */
1127 bsize = READBUFFER_LEN;
1129 c = Client_GetFromConn( Idx );
1130 if(( Client_Type( c ) != CLIENT_USER ) && ( Client_Type( c ) != CLIENT_SERVER ) && ( Client_Type( c ) != CLIENT_SERVICE ) && ( bsize > ZREADBUFFER_LEN )) bsize = ZREADBUFFER_LEN;
1134 if(( bsize - My_Connections[Idx].rdatalen - 1 < 1 ) || ( ZREADBUFFER_LEN - My_Connections[Idx].zip.rdatalen < 1 ))
1136 if( bsize - My_Connections[Idx].rdatalen - 1 < 1 )
1139 /* Der Lesepuffer ist voll */
1140 Log( LOG_ERR, "Receive buffer overflow (connection %d): %d bytes!", Idx, My_Connections[Idx].rdatalen );
1141 Conn_Close( Idx, "Receive buffer overflow!", NULL, FALSE );
1146 if( My_Connections[Idx].options & CONN_ZIP )
1148 len = recv( My_Connections[Idx].sock, My_Connections[Idx].zip.rbuf + My_Connections[Idx].zip.rdatalen, ( ZREADBUFFER_LEN - My_Connections[Idx].zip.rdatalen ), 0 );
1149 if( len > 0 ) My_Connections[Idx].zip.rdatalen += len;
1154 len = recv( My_Connections[Idx].sock, My_Connections[Idx].rbuf + My_Connections[Idx].rdatalen, bsize - My_Connections[Idx].rdatalen - 1, 0 );
1155 if( len > 0 ) My_Connections[Idx].rdatalen += len;
1160 /* Socket wurde geschlossen */
1161 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 ));
1162 Conn_Close( Idx, "Socket closed!", "Client closed connection", FALSE );
1168 /* Operation haette Socket "nur" blockiert ... */
1169 if( errno == EAGAIN ) return;
1171 /* Fehler beim Lesen */
1172 Log( LOG_ERR, "Read error on connection %d (socket %d): %s!", Idx, My_Connections[Idx].sock, strerror( errno ));
1173 Conn_Close( Idx, "Read error!", "Client closed connection", FALSE );
1177 /* Connection-Statistik aktualisieren */
1178 My_Connections[Idx].bytes_in += len;
1180 /* Timestamp aktualisieren */
1181 My_Connections[Idx].lastdata = time( NULL );
1183 Handle_Buffer( Idx );
1184 } /* Read_Request */
1188 Handle_Buffer( CONN_ID Idx )
1190 /* Daten im Lese-Puffer einer Verbindung verarbeiten.
1191 * Wurde ein Request verarbeitet, so wird TRUE geliefert,
1192 * ansonsten FALSE (auch bei Fehlern). */
1199 BOOLEAN action, result;
1208 if( My_Connections[Idx].delaytime > time( NULL )) return result;
1211 /* ggf. noch unkomprimiete Daten weiter entpacken */
1212 if( My_Connections[Idx].options & CONN_ZIP )
1214 if( ! Unzip_Buffer( Idx )) return FALSE;
1218 if( My_Connections[Idx].rdatalen < 1 ) break;
1220 /* Eine komplette Anfrage muss mit CR+LF enden, vgl.
1221 * RFC 2812. Haben wir eine? */
1222 My_Connections[Idx].rbuf[My_Connections[Idx].rdatalen] = '\0';
1223 ptr = strstr( My_Connections[Idx].rbuf, "\r\n" );
1225 if( ptr ) delta = 2;
1229 /* Nicht RFC-konforme Anfrage mit nur CR oder LF? Leider
1230 * machen soetwas viele Clients, u.a. "mIRC" :-( */
1231 ptr1 = strchr( My_Connections[Idx].rbuf, '\r' );
1232 ptr2 = strchr( My_Connections[Idx].rbuf, '\n' );
1234 if( ptr1 && ptr2 ) ptr = ptr1 > ptr2 ? ptr2 : ptr1;
1235 else if( ptr1 ) ptr = ptr1;
1236 else if( ptr2 ) ptr = ptr2;
1243 /* Ende der Anfrage wurde gefunden */
1245 len = ( ptr - My_Connections[Idx].rbuf ) + delta;
1246 if( len > ( COMMAND_LEN - 1 ))
1248 /* Eine Anfrage darf(!) nicht laenger als 512 Zeichen
1249 * (incl. CR+LF!) werden; vgl. RFC 2812. Wenn soetwas
1250 * empfangen wird, wird der Client disconnectiert. */
1251 Log( LOG_ERR, "Request too long (connection %d): %d bytes (max. %d expected)!", Idx, My_Connections[Idx].rdatalen, COMMAND_LEN - 1 );
1252 Conn_Close( Idx, NULL, "Request too long", TRUE );
1257 /* merken, ob Stream bereits komprimiert wird */
1258 old_z = My_Connections[Idx].options & CONN_ZIP;
1263 /* Es wurde ein Request gelesen */
1264 My_Connections[Idx].msg_in++;
1265 if( ! Parse_Request( Idx, My_Connections[Idx].rbuf )) return FALSE;
1269 /* Puffer anpassen */
1270 My_Connections[Idx].rdatalen -= len;
1271 memmove( My_Connections[Idx].rbuf, My_Connections[Idx].rbuf + len, My_Connections[Idx].rdatalen );
1274 if(( ! old_z ) && ( My_Connections[Idx].options & CONN_ZIP ) && ( My_Connections[Idx].rdatalen > 0 ))
1276 /* Mit dem letzten Befehl wurde Socket-Kompression aktiviert.
1277 * Evtl. schon vom Socket gelesene Daten in den Unzip-Puffer
1278 * umkopieren, damit diese nun zunaechst entkomprimiert werden */
1280 if( My_Connections[Idx].rdatalen > ZREADBUFFER_LEN )
1282 /* Hupsa! Soviel Platz haben wir aber gar nicht! */
1283 Log( LOG_ALERT, "Can't move receive buffer: No space left in unzip buffer (need %d bytes)!", My_Connections[Idx].rdatalen );
1286 memcpy( My_Connections[Idx].zip.rbuf, My_Connections[Idx].rbuf, My_Connections[Idx].rdatalen );
1287 My_Connections[Idx].zip.rdatalen = My_Connections[Idx].rdatalen;
1288 My_Connections[Idx].rdatalen = 0;
1290 Log( LOG_DEBUG, "Moved already received data (%d bytes) to uncompression buffer.", My_Connections[Idx].zip.rdatalen );
1297 if( action ) result = TRUE;
1301 } /* Handle_Buffer */
1305 Check_Connections( VOID )
1307 /* Pruefen, ob Verbindungen noch "alive" sind. Ist dies
1308 * nicht der Fall, zunaechst PING-PONG spielen und, wenn
1309 * auch das nicht "hilft", Client disconnectieren. */
1314 for( i = 0; i < Pool_Size; i++ )
1316 if( My_Connections[i].sock == NONE ) continue;
1318 c = Client_GetFromConn( i );
1319 if( c && (( Client_Type( c ) == CLIENT_USER ) || ( Client_Type( c ) == CLIENT_SERVER ) || ( Client_Type( c ) == CLIENT_SERVICE )))
1321 /* verbundener User, Server oder Service */
1322 if( My_Connections[i].lastping > My_Connections[i].lastdata )
1324 /* es wurde bereits ein PING gesendet */
1325 if( My_Connections[i].lastping < time( NULL ) - Conf_PongTimeout )
1329 Log( LOG_DEBUG, "Connection %d: Ping timeout: %d seconds.", i, Conf_PongTimeout );
1331 Conn_Close( i, NULL, "Ping timeout", TRUE );
1334 else if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout )
1336 /* es muss ein PING gesendet werden */
1338 Log( LOG_DEBUG, "Connection %d: sending PING ...", i );
1340 My_Connections[i].lastping = time( NULL );
1341 Conn_WriteStr( i, "PING :%s", Client_ID( Client_ThisServer( )));
1346 /* noch nicht vollstaendig aufgebaute Verbindung */
1347 if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout )
1351 Log( LOG_DEBUG, "Connection %d timed out ...", i );
1353 Conn_Close( i, NULL, "Timeout", FALSE );
1357 } /* Check_Connections */
1361 Check_Servers( VOID )
1363 /* Check if we can establish further server links */
1369 /* Serach all connections, are there results from the resolver? */
1370 for( idx = 0; idx < Pool_Size; idx++ )
1372 if( My_Connections[idx].sock != SERVER_WAIT ) continue;
1375 if( My_Connections[idx].res_stat == NULL ) New_Server( Conf_GetServer( idx ), idx );
1378 /* Check all configured servers */
1379 for( i = 0; i < MAX_SERVERS; i++ )
1381 /* Valid outgoing server which isn't already connected or disabled? */
1382 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;
1384 /* Is there already a connection in this group? */
1385 if( Conf_Server[i].group > NONE )
1387 for( n = 0; n < MAX_SERVERS; n++ )
1389 if( n == i ) continue;
1390 if(( Conf_Server[n].conn_id > NONE ) && ( Conf_Server[n].group == Conf_Server[i].group )) break;
1392 if( n < MAX_SERVERS ) continue;
1395 /* Check last connect attempt? */
1396 if( Conf_Server[i].lasttry > time( NULL ) - Conf_ConnectRetry ) continue;
1398 /* Okay, try to connect now */
1399 Conf_Server[i].lasttry = time( NULL );
1401 /* Search free connection structure */
1402 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
1403 if( idx >= Pool_Size )
1405 Log( LOG_ALERT, "Can't establist server connection: connection limit reached (%d)!", Pool_Size );
1409 Log( LOG_DEBUG, "Preparing connection %d for \"%s\" ...", idx, Conf_Server[i].host );
1412 /* Verbindungs-Struktur initialisieren */
1413 Init_Conn_Struct( idx );
1414 My_Connections[idx].sock = SERVER_WAIT;
1415 Conf_Server[i].conn_id = idx;
1417 /* Resolve Hostname. If this fails, try to use it as an IP address */
1418 strlcpy( Conf_Server[i].ip, Conf_Server[i].host, sizeof( Conf_Server[i].ip ));
1419 strlcpy( My_Connections[idx].host, Conf_Server[i].host, sizeof( My_Connections[idx].host ));
1420 s = Resolve_Name( Conf_Server[i].host );
1423 /* Sub-Prozess wurde asyncron gestartet */
1424 My_Connections[idx].res_stat = s;
1427 } /* Check_Servers */
1431 New_Server( INT Server, CONN_ID Idx )
1433 /* Establish new server link */
1435 struct sockaddr_in new_addr;
1436 struct in_addr inaddr;
1440 assert( Server > NONE );
1441 assert( Idx > NONE );
1443 /* Did we get a valid IP address? */
1444 if( ! Conf_Server[Server].ip[0] )
1446 /* No. Free connection structure and abort: */
1447 Init_Conn_Struct( Idx );
1448 Conf_Server[Server].conn_id = NONE;
1449 Log( LOG_ERR, "Can't connect to \"%s\" (connection %d): ip address unknown!", Conf_Server[Server].host, Idx );
1453 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 );
1455 #ifdef HAVE_INET_ATON
1456 if( inet_aton( Conf_Server[Server].ip, &inaddr ) == 0 )
1458 memset( &inaddr, 0, sizeof( inaddr ));
1459 inaddr.s_addr = inet_addr( Conf_Server[Server].ip );
1460 if( inaddr.s_addr == (unsigned)-1 )
1463 /* Can't convert IP address */
1464 Init_Conn_Struct( Idx );
1465 Conf_Server[Server].conn_id = NONE;
1466 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 );
1470 memset( &new_addr, 0, sizeof( new_addr ));
1471 new_addr.sin_family = AF_INET;
1472 new_addr.sin_addr = inaddr;
1473 new_addr.sin_port = htons( Conf_Server[Server].port );
1475 new_sock = socket( PF_INET, SOCK_STREAM, 0 );
1478 /* Can't create socket */
1479 Init_Conn_Struct( Idx );
1480 Conf_Server[Server].conn_id = NONE;
1481 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
1485 if( ! Init_Socket( new_sock )) return;
1487 res = connect( new_sock, (struct sockaddr *)&new_addr, sizeof( new_addr ));
1488 if(( res != 0 ) && ( errno != EINPROGRESS ))
1490 /* Can't connect socket */
1491 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1493 Init_Conn_Struct( Idx );
1494 Conf_Server[Server].conn_id = NONE;
1498 /* Client-Struktur initialisieren */
1499 c = Client_NewLocal( Idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWNSERVER, FALSE );
1502 /* Can't create new client structure */
1504 Init_Conn_Struct( Idx );
1505 Conf_Server[Server].conn_id = NONE;
1506 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1509 Client_SetIntroducer( c, c );
1510 Client_SetToken( c, TOKEN_OUTBOUND );
1512 /* Register connection */
1513 My_Connections[Idx].sock = new_sock;
1514 My_Connections[Idx].addr = new_addr;
1515 strlcpy( My_Connections[Idx].host, Conf_Server[Server].host, sizeof( My_Connections[Idx].host ));
1517 /* Register new socket */
1518 FD_SET( new_sock, &My_Sockets );
1519 FD_SET( new_sock, &My_Connects );
1520 if( new_sock > Conn_MaxFD ) Conn_MaxFD = new_sock;
1523 Log( LOG_DEBUG, "Registered new connection %d on socket %d.", Idx, My_Connections[Idx].sock );
1529 Init_Conn_Struct( CONN_ID Idx )
1531 /* Connection-Struktur initialisieren */
1533 My_Connections[Idx].sock = NONE;
1534 My_Connections[Idx].res_stat = NULL;
1535 My_Connections[Idx].host[0] = '\0';
1536 My_Connections[Idx].rbuf[0] = '\0';
1537 My_Connections[Idx].rdatalen = 0;
1538 My_Connections[Idx].wbuf[0] = '\0';
1539 My_Connections[Idx].wdatalen = 0;
1540 My_Connections[Idx].starttime = time( NULL );
1541 My_Connections[Idx].lastdata = time( NULL );
1542 My_Connections[Idx].lastping = 0;
1543 My_Connections[Idx].lastprivmsg = time( NULL );
1544 My_Connections[Idx].delaytime = 0;
1545 My_Connections[Idx].bytes_in = 0;
1546 My_Connections[Idx].bytes_out = 0;
1547 My_Connections[Idx].msg_in = 0;
1548 My_Connections[Idx].msg_out = 0;
1549 My_Connections[Idx].flag = 0;
1550 My_Connections[Idx].options = 0;
1553 My_Connections[Idx].zip.rbuf[0] = '\0';
1554 My_Connections[Idx].zip.rdatalen = 0;
1555 My_Connections[Idx].zip.wbuf[0] = '\0';
1556 My_Connections[Idx].zip.wdatalen = 0;
1557 My_Connections[Idx].zip.bytes_in = 0;
1558 My_Connections[Idx].zip.bytes_out = 0;
1560 } /* Init_Conn_Struct */
1564 Init_Socket( INT Sock )
1566 /* Initialize socket (set options) */
1570 #ifdef O_NONBLOCK /* unknown on A/UX */
1571 if( fcntl( Sock, F_SETFL, O_NONBLOCK ) != 0 )
1573 Log( LOG_CRIT, "Can't enable non-blocking mode for socket: %s!", strerror( errno ));
1579 /* Don't block this port after socket shutdown */
1581 if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &value, (socklen_t)sizeof( value )) != 0 )
1583 Log( LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!", strerror( errno ));
1584 /* ignore this error */
1587 /* Set type of service (TOS) */
1588 #if defined(IP_TOS) && defined(IPTOS_LOWDELAY)
1589 value = IPTOS_LOWDELAY;
1591 Log( LOG_DEBUG, "Setting option IP_TOS on socket %d to IPTOS_LOWDELAY (%d).", Sock, value );
1593 if( setsockopt( Sock, SOL_IP, IP_TOS, &value, (socklen_t)sizeof( value )) != 0 )
1595 Log( LOG_ERR, "Can't set socket option IP_TOS: %s!", strerror( errno ));
1596 /* ignore this error */
1605 Read_Resolver_Result( INT r_fd )
1607 /* Read result of resolver sub-process from pipe and update the
1608 * apropriate connection/client structure(s): hostname and/or
1609 * IDENT user name.*/
1616 /* Search associated connection ... */
1617 for( i = 0; i < Pool_Size; i++ )
1619 if(( My_Connections[i].sock != NONE )
1620 && ( My_Connections[i].res_stat != NULL )
1621 && ( My_Connections[i].res_stat->pipe[0] == r_fd ))
1624 if( i >= Pool_Size )
1626 /* Ops, none found? Probably the connection has already
1627 * been closed!? We'll ignore that ... */
1628 FD_CLR( r_fd, &Resolver_FDs );
1631 Log( LOG_DEBUG, "Resolver: Got result for unknown connection!?" );
1636 /* Get resolver structure */
1637 s = My_Connections[i].res_stat;
1638 assert( s != NULL );
1640 /* Read result from pipe */
1641 len = read( r_fd, s->buffer + s->bufpos, sizeof( s->buffer ) - s->bufpos - 1 );
1646 Log( LOG_CRIT, "Resolver: Can't read result: %s!", strerror( errno ));
1650 s->buffer[s->bufpos] = '\0';
1652 /* If the result string is incomplete, return to main loop and
1653 * wait until we can read in more bytes. */
1657 ptr = strchr( s->buffer, '\n' );
1662 Log( LOG_DEBUG, "Got result from resolver: \"%s\" (%d bytes), stage %d.", s->buffer, len, s->stage );
1665 /* Okay, we got a complete result: this is a host name for outgoing
1666 * connections and a host name or IDENT user name (if enabled) for
1667 * incoming conneciions.*/
1668 if( My_Connections[i].sock > NONE )
1670 /* Incoming connection */
1672 /* Search client ... */
1673 c = Client_GetFromConn( i );
1674 assert( c != NULL );
1676 /* Only update client information of unregistered clients */
1677 if( Client_Type( c ) == CLIENT_UNKNOWN )
1682 strlcpy( My_Connections[i].host, s->buffer, sizeof( My_Connections[i].host ));
1683 Client_SetHostname( c, s->buffer );
1686 /* clean up buffer for IDENT result */
1687 len = strlen( s->buffer ) + 1;
1688 memmove( s->buffer, s->buffer + len, sizeof( s->buffer ) - len );
1691 /* Don't close pipe and clean up, but
1692 * instead wait for IDENT result */
1696 else if( s->stage == 1 )
1698 /* IDENT user name */
1701 Log( LOG_INFO, "IDENT lookup for connection %ld: \"%s\".", i, s->buffer );
1702 Client_SetUser( c, s->buffer, TRUE );
1704 else Log( LOG_INFO, "IDENT lookup for connection %ld: no result.", i );
1707 else Log( LOG_ERR, "Resolver: got result for unknown stage %d!?", s->stage );
1710 else Log( LOG_DEBUG, "Resolver: discarding result for already registered connection %d.", i );
1715 /* Outgoing connection (server link): set the IP address
1716 * so that we can connect to it in the main loop. */
1718 /* Search server ... */
1719 n = Conf_GetServer( i );
1722 strlcpy( Conf_Server[n].ip, s->buffer, sizeof( Conf_Server[n].ip ));
1726 FD_CLR( r_fd, &Resolver_FDs );
1727 close( My_Connections[i].res_stat->pipe[0] );
1728 close( My_Connections[i].res_stat->pipe[1] );
1729 free( My_Connections[i].res_stat );
1730 My_Connections[i].res_stat = NULL;
1732 /* Reset penalty time */
1733 Conn_ResetPenalty( i );
1734 } /* Read_Resolver_Result */
1738 Simple_Message( INT Sock, CHAR *Msg )
1740 /* Write "simple" message to socket, without using compression
1741 * or even the connection write buffers. Used e.g. for error
1742 * messages by New_Connection(). */
1744 assert( Sock > NONE );
1745 assert( Msg != NULL );
1747 (VOID)send( Sock, Msg, strlen( Msg ), 0 );
1748 (VOID)send( Sock, "\r\n", 2, 0 );
1749 } /* Simple_Error */
1753 Count_Connections( struct sockaddr_in addr_in )
1758 for( i = 0; i < Pool_Size; i++ )
1760 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].addr.sin_addr.s_addr == addr_in.sin_addr.s_addr )) cnt++;
1763 } /* Count_Connections */