2 * ngIRCd -- The Next Generation IRC Daemon
3 * Copyright (c)2001-2004 by 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.131 2004/02/03 20:28:30 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 = 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. */
619 DOUBLE in_z_k, out_z_k;
623 assert( Idx > NONE );
624 assert( My_Connections[Idx].sock > 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 /* Mark link as "closing" */
635 My_Connections[Idx].options |= CONN_ISCLOSING;
637 /* Search client, if any */
638 c = Client_GetFromConn( Idx );
640 /* Should the client be informed? */
644 /* Send statistics to client if registered as user: */
645 if(( c != NULL ) && ( Client_Type( c ) == CLIENT_USER ))
647 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 );
651 /* Send ERROR to client (see RFC!) */
652 if( FwdMsg ) Conn_WriteStr( Idx, "ERROR :%s", FwdMsg );
653 else Conn_WriteStr( Idx, "ERROR :Closing connection." );
654 if( My_Connections[Idx].sock == NONE ) return;
657 /* Try to write out the write buffer */
658 (VOID)Try_Write( Idx );
660 /* Shut down socket */
661 if( close( My_Connections[Idx].sock ) != 0 )
663 /* Oops, we can't close the socket!? This is fatal! */
664 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 ));
665 Log( LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE_NAME );
669 /* Mark socket as invalid: */
670 FD_CLR( My_Connections[Idx].sock, &My_Sockets );
671 FD_CLR( My_Connections[Idx].sock, &My_Connects );
672 My_Connections[Idx].sock = NONE;
674 /* If there is still a client, unregister it now */
675 if( c ) Client_Destroy( c, LogMsg, FwdMsg, TRUE );
677 /* Calculate statistics and log information */
678 in_k = (DOUBLE)My_Connections[Idx].bytes_in / 1024;
679 out_k = (DOUBLE)My_Connections[Idx].bytes_out / 1024;
681 if( My_Connections[Idx].options & CONN_ZIP )
683 in_z_k = (DOUBLE)My_Connections[Idx].zip.bytes_in / 1024;
684 out_z_k = (DOUBLE)My_Connections[Idx].zip.bytes_out / 1024;
685 in_p = (INT)(( in_k * 100 ) / in_z_k );
686 out_p = (INT)(( out_k * 100 ) / out_z_k );
687 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 );
692 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 );
695 /* Is there a resolver sub-process running? */
696 if( My_Connections[Idx].res_stat )
698 /* Free resolver structures */
699 FD_CLR( My_Connections[Idx].res_stat->pipe[0], &Resolver_FDs );
700 close( My_Connections[Idx].res_stat->pipe[0] );
701 close( My_Connections[Idx].res_stat->pipe[1] );
702 free( My_Connections[Idx].res_stat );
705 /* Servers: Modify time of next connect attempt? */
706 Conf_UnsetServer( Idx );
709 /* Clean up zlib, if link was compressed */
710 if( Conn_Options( Idx ) & CONN_ZIP )
712 inflateEnd( &My_Connections[Idx].zip.in );
713 deflateEnd( &My_Connections[Idx].zip.out );
717 /* Clean up connection structure (=free it) */
718 Init_Conn_Struct( Idx );
723 Conn_SyncServerStruct( VOID )
725 /* Synchronize server structures (connection IDs):
726 * connections <-> configuration */
732 for( i = 0; i < Pool_Size; i++ )
734 /* Established connection? */
735 if( My_Connections[i].sock <= NONE ) continue;
737 /* Server connection? */
738 client = Client_GetFromConn( i );
739 if(( ! client ) || ( Client_Type( client ) != CLIENT_SERVER )) continue;
741 for( c = 0; c < MAX_SERVERS; c++ )
743 /* Configured server? */
744 if( ! Conf_Server[c].host[0] ) continue;
747 if( strcmp( Conf_Server[c].name, Client_ID( client )) == 0 ) Conf_Server[c].conn_id = i;
750 } /* SyncServerStruct */
754 Try_Write( CONN_ID Idx )
756 /* Versuchen, Daten aus dem Schreib-Puffer in den Socket zu
757 * schreiben. TRUE wird geliefert, wenn entweder keine Daten
758 * zum Versenden vorhanden sind oder erfolgreich bearbeitet
759 * werden konnten. Im Fehlerfall wird FALSE geliefert und
760 * die Verbindung geschlossen. */
765 assert( Idx > NONE );
766 assert( My_Connections[Idx].sock > NONE );
768 /* sind ueberhaupt Daten vorhanden? */
770 if(( ! My_Connections[Idx].wdatalen > 0 ) && ( ! My_Connections[Idx].zip.wdatalen )) return TRUE;
772 if( ! My_Connections[Idx].wdatalen > 0 ) return TRUE;
775 /* Timeout initialisieren: 0 Sekunden, also nicht blockieren */
776 tv.tv_sec = 0; tv.tv_usec = 0;
778 FD_ZERO( &write_socket );
779 FD_SET( My_Connections[Idx].sock, &write_socket );
780 if( select( My_Connections[Idx].sock + 1, NULL, &write_socket, NULL, &tv ) == -1 )
785 Log( LOG_ALERT, "Try_Write(): select() failed: %s (con=%d, sock=%d)!", strerror( errno ), Idx, My_Connections[Idx].sock );
786 Conn_Close( Idx, "Server error!", NULL, FALSE );
791 if( FD_ISSET( My_Connections[Idx].sock, &write_socket )) return Handle_Write( Idx );
797 Handle_Read( INT Sock )
799 /* Aktivitaet auf einem Socket verarbeiten:
800 * - neue Clients annehmen,
801 * - Daten von Clients verarbeiten,
802 * - Resolver-Rueckmeldungen annehmen. */
806 assert( Sock > NONE );
808 if( FD_ISSET( Sock, &My_Listeners ))
810 /* es ist einer unserer Listener-Sockets: es soll
811 * also eine neue Verbindung aufgebaut werden. */
813 New_Connection( Sock );
815 else if( FD_ISSET( Sock, &Resolver_FDs ))
817 /* Rueckmeldung von einem Resolver Sub-Prozess */
819 Read_Resolver_Result( Sock );
823 /* Ein Client Socket: entweder ein User oder Server */
825 idx = Socket2Index( Sock );
826 if( idx > NONE ) Read_Request( idx );
832 Handle_Write( CONN_ID Idx )
834 /* Daten aus Schreibpuffer versenden bzw. Connection aufbauen */
840 assert( Idx > NONE );
841 assert( My_Connections[Idx].sock > NONE );
843 if( FD_ISSET( My_Connections[Idx].sock, &My_Connects ))
845 /* es soll nichts geschrieben werden, sondern ein
846 * connect() hat ein Ergebnis geliefert */
848 FD_CLR( My_Connections[Idx].sock, &My_Connects );
850 /* Ergebnis des connect() ermitteln */
851 sock_len = sizeof( err );
852 res = getsockopt( My_Connections[Idx].sock, SOL_SOCKET, SO_ERROR, &err, &sock_len );
853 assert( sock_len == sizeof( err ));
855 /* Fehler aufgetreten? */
856 if(( res != 0 ) || ( err != 0 ))
859 if( res != 0 ) Log( LOG_CRIT, "getsockopt (connection %d): %s!", Idx, strerror( errno ));
860 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 ));
862 /* Clean up socket, connection and client structures */
863 FD_CLR( My_Connections[Idx].sock, &My_Sockets );
864 c = Client_GetFromConn( Idx );
865 if( c ) Client_DestroyNow( c );
866 close( My_Connections[Idx].sock );
867 Init_Conn_Struct( Idx );
869 /* Bei Server-Verbindungen lasttry-Zeitpunkt auf "jetzt" setzen */
870 Conf_Server[Conf_GetServer( Idx )].lasttry = time( NULL );
871 Conf_UnsetServer( Idx );
876 Log( LOG_DEBUG, "Connection %d with \"%s:%d\" established, now sendig PASS and SERVER ...", Idx, My_Connections[Idx].host, Conf_Server[Conf_GetServer( Idx )].port );
879 /* PASS und SERVER verschicken */
880 Conn_WriteStr( Idx, "PASS %s %s", Conf_Server[Conf_GetServer( Idx )].pwd_out, NGIRCd_ProtoID );
881 return Conn_WriteStr( Idx, "SERVER %s :%s", Conf_ServerName, Conf_ServerInfo );
885 /* Schreibpuffer leer, aber noch Daten im Kompressionsbuffer?
886 * Dann muss dieser nun geflushed werden! */
887 if( My_Connections[Idx].wdatalen == 0 ) Zip_Flush( Idx );
890 assert( My_Connections[Idx].wdatalen > 0 );
892 /* Daten schreiben */
893 len = send( My_Connections[Idx].sock, My_Connections[Idx].wbuf, My_Connections[Idx].wdatalen, 0 );
896 /* Operation haette Socket "nur" blockiert ... */
897 if( errno == EAGAIN ) return TRUE;
899 /* Oops, ein Fehler! */
900 Log( LOG_ERR, "Write error on connection %d (socket %d): %s!", Idx, My_Connections[Idx].sock, strerror( errno ));
901 Conn_Close( Idx, "Write error!", NULL, FALSE );
905 /* Puffer anpassen */
906 My_Connections[Idx].wdatalen -= len;
907 memmove( My_Connections[Idx].wbuf, My_Connections[Idx].wbuf + len, My_Connections[Idx].wdatalen );
914 New_Connection( INT Sock )
916 /* Neue Client-Verbindung von Listen-Socket annehmen und
917 * CLIENT-Struktur anlegen. */
920 struct request_info req;
922 struct sockaddr_in new_addr;
923 INT new_sock, new_sock_len;
930 assert( Sock > NONE );
932 /* Connection auf Listen-Socket annehmen */
933 new_sock_len = sizeof( new_addr );
934 new_sock = accept( Sock, (struct sockaddr *)&new_addr, (socklen_t *)&new_sock_len );
937 Log( LOG_CRIT, "Can't accept connection: %s!", strerror( errno ));
942 /* Validate socket using TCP Wrappers */
943 request_init( &req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock, RQ_CLIENT_SIN, &new_addr, NULL );
945 if( ! hosts_access( &req ))
948 Log( deny_severity, "Refused connection from %s (by TCP Wrappers)!", inet_ntoa( new_addr.sin_addr ));
949 Simple_Message( new_sock, "ERROR :Connection refused" );
955 /* Socket initialisieren */
956 Init_Socket( new_sock );
958 /* Check IP-based connection limit */
959 cnt = Count_Connections( new_addr );
960 if(( Conf_MaxConnectionsIP > 0 ) && ( cnt >= Conf_MaxConnectionsIP ))
962 /* Access denied, too many connections from this IP! */
963 Log( LOG_ERR, "Refused connection from %s: too may connections (%ld) from this IP!", inet_ntoa( new_addr.sin_addr ), cnt);
964 Simple_Message( new_sock, "ERROR :Connection refused, too many connections from your IP!" );
969 /* Freie Connection-Struktur suchen */
970 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
971 if( idx >= Pool_Size )
973 new_size = Pool_Size + CONNECTION_POOL;
975 /* Im bisherigen Pool wurde keine freie Connection-Struktur mehr gefunden.
976 * Wenn erlaubt und moeglich muss nun der Pool vergroessert werden: */
978 if( Conf_MaxConnections > 0 )
980 /* Es ist ein Limit konfiguriert */
981 if( Pool_Size >= Conf_MaxConnections )
983 /* Mehr Verbindungen duerfen wir leider nicht mehr annehmen ... */
984 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached!", Pool_Size );
985 Simple_Message( new_sock, "ERROR :Connection limit reached" );
989 if( new_size > Conf_MaxConnections ) new_size = Conf_MaxConnections;
991 if( new_size < Pool_Size )
993 Log( LOG_ALERT, "Can't accespt connection: limit (%d) reached -- overflow!", Pool_Size );
994 Simple_Message( new_sock, "ERROR :Connection limit reached" );
999 /* zunaechst realloc() versuchen; wenn das scheitert, malloc() versuchen
1000 * und Daten ggf. "haendisch" umkopieren. (Haesslich! Eine wirklich
1001 * dynamische Verwaltung waere wohl _deutlich_ besser ...) */
1002 ptr = realloc( My_Connections, sizeof( CONNECTION ) * new_size );
1005 /* realloc() ist fehlgeschlagen. Nun malloc() probieren: */
1006 ptr = malloc( sizeof( CONNECTION ) * new_size );
1009 /* Offenbar steht kein weiterer Sepeicher zur Verfuegung :-( */
1010 Log( LOG_EMERG, "Can't allocate memory! [New_Connection]" );
1011 Simple_Message( new_sock, "ERROR: Internal error" );
1016 /* Struktur umkopieren ... */
1017 memcpy( ptr, My_Connections, sizeof( CONNECTION ) * Pool_Size );
1020 Log( LOG_DEBUG, "Allocated new connection pool for %ld items (%ld bytes). [malloc()/memcpy()]", new_size, sizeof( CONNECTION ) * new_size );
1024 else Log( LOG_DEBUG, "Allocated new connection pool for %ld items (%ld bytes). [realloc()]", new_size, sizeof( CONNECTION ) * new_size );
1027 /* Adjust pointer to new block */
1028 My_Connections = ptr;
1030 /* Initialize new items */
1031 for( idx = Pool_Size; idx < new_size; idx++ ) Init_Conn_Struct( idx );
1034 /* Adjust new pool size */
1035 Pool_Size = new_size;
1038 /* Client-Struktur initialisieren */
1039 c = Client_NewLocal( idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWN, FALSE );
1042 Log( LOG_ALERT, "Can't accept connection: can't create client structure!" );
1043 Simple_Message( new_sock, "ERROR :Internal error" );
1048 /* Verbindung registrieren */
1049 Init_Conn_Struct( idx );
1050 My_Connections[idx].sock = new_sock;
1051 My_Connections[idx].addr = new_addr;
1053 /* Neuen Socket registrieren */
1054 FD_SET( new_sock, &My_Sockets );
1055 if( new_sock > Conn_MaxFD ) Conn_MaxFD = new_sock;
1057 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 );
1059 /* Hostnamen ermitteln */
1060 strlcpy( My_Connections[idx].host, inet_ntoa( new_addr.sin_addr ), sizeof( My_Connections[idx].host ));
1061 Client_SetHostname( c, My_Connections[idx].host );
1063 s = Resolve_Addr( &new_addr, My_Connections[idx].sock );
1065 s = Resolve_Addr( &new_addr );
1069 /* Sub-Prozess wurde asyncron gestartet */
1070 My_Connections[idx].res_stat = s;
1073 /* Penalty-Zeit setzen */
1074 Conn_SetPenalty( idx, 4 );
1075 } /* New_Connection */
1079 Socket2Index( INT Sock )
1081 /* zum Socket passende Connection suchen */
1085 assert( Sock > NONE );
1087 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == Sock ) break;
1089 if( idx >= Pool_Size )
1091 /* die Connection wurde vermutlich (wegen eines
1092 * Fehlers) bereits wieder abgebaut ... */
1094 Log( LOG_DEBUG, "Socket2Index: can't get connection for socket %d!", Sock );
1099 } /* Socket2Index */
1103 Read_Request( CONN_ID Idx )
1105 /* Daten von Socket einlesen und entsprechend behandeln.
1106 * Tritt ein Fehler auf, so wird der Socket geschlossen. */
1113 assert( Idx > NONE );
1114 assert( My_Connections[Idx].sock > NONE );
1116 /* wenn noch nicht registriert: maximal mit ZREADBUFFER_LEN arbeiten,
1117 * ansonsten koennen Daten ggf. nicht umkopiert werden. */
1118 bsize = READBUFFER_LEN;
1120 c = Client_GetFromConn( Idx );
1121 if(( Client_Type( c ) != CLIENT_USER ) && ( Client_Type( c ) != CLIENT_SERVER ) && ( Client_Type( c ) != CLIENT_SERVICE ) && ( bsize > ZREADBUFFER_LEN )) bsize = ZREADBUFFER_LEN;
1125 if(( bsize - My_Connections[Idx].rdatalen - 1 < 1 ) || ( ZREADBUFFER_LEN - My_Connections[Idx].zip.rdatalen < 1 ))
1127 if( bsize - My_Connections[Idx].rdatalen - 1 < 1 )
1130 /* Der Lesepuffer ist voll */
1131 Log( LOG_ERR, "Read buffer overflow (connection %d): %d bytes!", Idx, My_Connections[Idx].rdatalen );
1132 Conn_Close( Idx, "Read buffer overflow!", NULL, FALSE );
1137 if( My_Connections[Idx].options & CONN_ZIP )
1139 len = recv( My_Connections[Idx].sock, My_Connections[Idx].zip.rbuf + My_Connections[Idx].zip.rdatalen, ( ZREADBUFFER_LEN - My_Connections[Idx].zip.rdatalen ), 0 );
1140 if( len > 0 ) My_Connections[Idx].zip.rdatalen += len;
1145 len = recv( My_Connections[Idx].sock, My_Connections[Idx].rbuf + My_Connections[Idx].rdatalen, bsize - My_Connections[Idx].rdatalen - 1, 0 );
1146 if( len > 0 ) My_Connections[Idx].rdatalen += len;
1151 /* Socket wurde geschlossen */
1152 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 ));
1153 Conn_Close( Idx, "Socket closed!", "Client closed connection", FALSE );
1159 /* Operation haette Socket "nur" blockiert ... */
1160 if( errno == EAGAIN ) return;
1162 /* Fehler beim Lesen */
1163 Log( LOG_ERR, "Read error on connection %d (socket %d): %s!", Idx, My_Connections[Idx].sock, strerror( errno ));
1164 Conn_Close( Idx, "Read error!", "Client closed connection", FALSE );
1168 /* Connection-Statistik aktualisieren */
1169 My_Connections[Idx].bytes_in += len;
1171 /* Timestamp aktualisieren */
1172 My_Connections[Idx].lastdata = time( NULL );
1174 Handle_Buffer( Idx );
1175 } /* Read_Request */
1179 Handle_Buffer( CONN_ID Idx )
1181 /* Daten im Lese-Puffer einer Verbindung verarbeiten.
1182 * Wurde ein Request verarbeitet, so wird TRUE geliefert,
1183 * ansonsten FALSE (auch bei Fehlern). */
1190 BOOLEAN action, result;
1199 if( My_Connections[Idx].delaytime > time( NULL )) return result;
1202 /* ggf. noch unkomprimiete Daten weiter entpacken */
1203 if( My_Connections[Idx].options & CONN_ZIP )
1205 if( ! Unzip_Buffer( Idx )) return FALSE;
1209 if( My_Connections[Idx].rdatalen < 1 ) break;
1211 /* Eine komplette Anfrage muss mit CR+LF enden, vgl.
1212 * RFC 2812. Haben wir eine? */
1213 My_Connections[Idx].rbuf[My_Connections[Idx].rdatalen] = '\0';
1214 ptr = strstr( My_Connections[Idx].rbuf, "\r\n" );
1216 if( ptr ) delta = 2;
1220 /* Nicht RFC-konforme Anfrage mit nur CR oder LF? Leider
1221 * machen soetwas viele Clients, u.a. "mIRC" :-( */
1222 ptr1 = strchr( My_Connections[Idx].rbuf, '\r' );
1223 ptr2 = strchr( My_Connections[Idx].rbuf, '\n' );
1225 if( ptr1 && ptr2 ) ptr = ptr1 > ptr2 ? ptr2 : ptr1;
1226 else if( ptr1 ) ptr = ptr1;
1227 else if( ptr2 ) ptr = ptr2;
1234 /* Ende der Anfrage wurde gefunden */
1236 len = ( ptr - My_Connections[Idx].rbuf ) + delta;
1237 if( len > ( COMMAND_LEN - 1 ))
1239 /* Eine Anfrage darf(!) nicht laenger als 512 Zeichen
1240 * (incl. CR+LF!) werden; vgl. RFC 2812. Wenn soetwas
1241 * empfangen wird, wird der Client disconnectiert. */
1242 Log( LOG_ERR, "Request too long (connection %d): %d bytes (max. %d expected)!", Idx, My_Connections[Idx].rdatalen, COMMAND_LEN - 1 );
1243 Conn_Close( Idx, NULL, "Request too long", TRUE );
1248 /* merken, ob Stream bereits komprimiert wird */
1249 old_z = My_Connections[Idx].options & CONN_ZIP;
1254 /* Es wurde ein Request gelesen */
1255 My_Connections[Idx].msg_in++;
1256 if( ! Parse_Request( Idx, My_Connections[Idx].rbuf )) return FALSE;
1260 /* Puffer anpassen */
1261 My_Connections[Idx].rdatalen -= len;
1262 memmove( My_Connections[Idx].rbuf, My_Connections[Idx].rbuf + len, My_Connections[Idx].rdatalen );
1265 if(( ! old_z ) && ( My_Connections[Idx].options & CONN_ZIP ) && ( My_Connections[Idx].rdatalen > 0 ))
1267 /* Mit dem letzten Befehl wurde Socket-Kompression aktiviert.
1268 * Evtl. schon vom Socket gelesene Daten in den Unzip-Puffer
1269 * umkopieren, damit diese nun zunaechst entkomprimiert werden */
1271 if( My_Connections[Idx].rdatalen > ZREADBUFFER_LEN )
1273 /* Hupsa! Soviel Platz haben wir aber gar nicht! */
1274 Log( LOG_ALERT, "Can't move read buffer: No space left in unzip buffer (need %d bytes)!", My_Connections[Idx].rdatalen );
1277 memcpy( My_Connections[Idx].zip.rbuf, My_Connections[Idx].rbuf, My_Connections[Idx].rdatalen );
1278 My_Connections[Idx].zip.rdatalen = My_Connections[Idx].rdatalen;
1279 My_Connections[Idx].rdatalen = 0;
1281 Log( LOG_DEBUG, "Moved already received data (%d bytes) to uncompression buffer.", My_Connections[Idx].zip.rdatalen );
1288 if( action ) result = TRUE;
1292 } /* Handle_Buffer */
1296 Check_Connections( VOID )
1298 /* Pruefen, ob Verbindungen noch "alive" sind. Ist dies
1299 * nicht der Fall, zunaechst PING-PONG spielen und, wenn
1300 * auch das nicht "hilft", Client disconnectieren. */
1305 for( i = 0; i < Pool_Size; i++ )
1307 if( My_Connections[i].sock == NONE ) continue;
1309 c = Client_GetFromConn( i );
1310 if( c && (( Client_Type( c ) == CLIENT_USER ) || ( Client_Type( c ) == CLIENT_SERVER ) || ( Client_Type( c ) == CLIENT_SERVICE )))
1312 /* verbundener User, Server oder Service */
1313 if( My_Connections[i].lastping > My_Connections[i].lastdata )
1315 /* es wurde bereits ein PING gesendet */
1316 if( My_Connections[i].lastping < time( NULL ) - Conf_PongTimeout )
1320 Log( LOG_DEBUG, "Connection %d: Ping timeout: %d seconds.", i, Conf_PongTimeout );
1322 Conn_Close( i, NULL, "Ping timeout", TRUE );
1325 else if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout )
1327 /* es muss ein PING gesendet werden */
1329 Log( LOG_DEBUG, "Connection %d: sending PING ...", i );
1331 My_Connections[i].lastping = time( NULL );
1332 Conn_WriteStr( i, "PING :%s", Client_ID( Client_ThisServer( )));
1337 /* noch nicht vollstaendig aufgebaute Verbindung */
1338 if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout )
1342 Log( LOG_DEBUG, "Connection %d timed out ...", i );
1344 Conn_Close( i, NULL, "Timeout", FALSE );
1348 } /* Check_Connections */
1352 Check_Servers( VOID )
1354 /* Check if we can establish further server links */
1360 /* Serach all connections, are there results from the resolver? */
1361 for( idx = 0; idx < Pool_Size; idx++ )
1363 if( My_Connections[idx].sock != SERVER_WAIT ) continue;
1366 if( My_Connections[idx].res_stat == NULL ) New_Server( Conf_GetServer( idx ), idx );
1369 /* Check all configured servers */
1370 for( i = 0; i < MAX_SERVERS; i++ )
1372 /* Valid outgoing server which isn't already connected or disabled? */
1373 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;
1375 /* Is there already a connection in this group? */
1376 if( Conf_Server[i].group > NONE )
1378 for( n = 0; n < MAX_SERVERS; n++ )
1380 if( n == i ) continue;
1381 if(( Conf_Server[n].conn_id > NONE ) && ( Conf_Server[n].group == Conf_Server[i].group )) break;
1383 if( n < MAX_SERVERS ) continue;
1386 /* Check last connect attempt? */
1387 if( Conf_Server[i].lasttry > time( NULL ) - Conf_ConnectRetry ) continue;
1389 /* Okay, try to connect now */
1390 Conf_Server[i].lasttry = time( NULL );
1392 /* Search free connection structure */
1393 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
1394 if( idx >= Pool_Size )
1396 Log( LOG_ALERT, "Can't establist server connection: connection limit reached (%d)!", Pool_Size );
1400 Log( LOG_DEBUG, "Preparing connection %d for \"%s\" ...", idx, Conf_Server[i].host );
1403 /* Verbindungs-Struktur initialisieren */
1404 Init_Conn_Struct( idx );
1405 My_Connections[idx].sock = SERVER_WAIT;
1406 Conf_Server[i].conn_id = idx;
1408 /* Resolve Hostname. If this fails, try to use it as an IP address */
1409 strlcpy( Conf_Server[i].ip, Conf_Server[i].host, sizeof( Conf_Server[i].ip ));
1410 strlcpy( My_Connections[idx].host, Conf_Server[i].host, sizeof( My_Connections[idx].host ));
1411 s = Resolve_Name( Conf_Server[i].host );
1414 /* Sub-Prozess wurde asyncron gestartet */
1415 My_Connections[idx].res_stat = s;
1418 } /* Check_Servers */
1422 New_Server( INT Server, CONN_ID Idx )
1424 /* Establish new server link */
1426 struct sockaddr_in new_addr;
1427 struct in_addr inaddr;
1431 assert( Server > NONE );
1432 assert( Idx > NONE );
1434 /* Did we get a valid IP address? */
1435 if( ! Conf_Server[Server].ip[0] )
1437 /* No. Free connection structure and abort: */
1438 Init_Conn_Struct( Idx );
1439 Conf_Server[Server].conn_id = NONE;
1440 Log( LOG_ERR, "Can't connect to \"%s\" (connection %d): ip address unknown!", Conf_Server[Server].host, Idx );
1444 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 );
1446 #ifdef HAVE_INET_ATON
1447 if( inet_aton( Conf_Server[Server].ip, &inaddr ) == 0 )
1449 memset( &inaddr, 0, sizeof( inaddr ));
1450 inaddr.s_addr = inet_addr( Conf_Server[Server].ip );
1451 if( inaddr.s_addr == (unsigned)-1 )
1454 /* Can't convert IP address */
1455 Init_Conn_Struct( Idx );
1456 Conf_Server[Server].conn_id = NONE;
1457 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 );
1461 memset( &new_addr, 0, sizeof( new_addr ));
1462 new_addr.sin_family = AF_INET;
1463 new_addr.sin_addr = inaddr;
1464 new_addr.sin_port = htons( Conf_Server[Server].port );
1466 new_sock = socket( PF_INET, SOCK_STREAM, 0 );
1469 /* Can't create socket */
1470 Init_Conn_Struct( Idx );
1471 Conf_Server[Server].conn_id = NONE;
1472 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
1476 if( ! Init_Socket( new_sock )) return;
1478 res = connect( new_sock, (struct sockaddr *)&new_addr, sizeof( new_addr ));
1479 if(( res != 0 ) && ( errno != EINPROGRESS ))
1481 /* Can't connect socket */
1482 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1484 Init_Conn_Struct( Idx );
1485 Conf_Server[Server].conn_id = NONE;
1489 /* Client-Struktur initialisieren */
1490 c = Client_NewLocal( Idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWNSERVER, FALSE );
1493 /* Can't create new client structure */
1495 Init_Conn_Struct( Idx );
1496 Conf_Server[Server].conn_id = NONE;
1497 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1500 Client_SetIntroducer( c, c );
1501 Client_SetToken( c, TOKEN_OUTBOUND );
1503 /* Register connection */
1504 My_Connections[Idx].sock = new_sock;
1505 My_Connections[Idx].addr = new_addr;
1506 strlcpy( My_Connections[Idx].host, Conf_Server[Server].host, sizeof( My_Connections[Idx].host ));
1508 /* Register new socket */
1509 FD_SET( new_sock, &My_Sockets );
1510 FD_SET( new_sock, &My_Connects );
1511 if( new_sock > Conn_MaxFD ) Conn_MaxFD = new_sock;
1514 Log( LOG_DEBUG, "Registered new connection %d on socket %d.", Idx, My_Connections[Idx].sock );
1520 Init_Conn_Struct( CONN_ID Idx )
1522 /* Connection-Struktur initialisieren */
1524 My_Connections[Idx].sock = NONE;
1525 My_Connections[Idx].res_stat = NULL;
1526 My_Connections[Idx].host[0] = '\0';
1527 My_Connections[Idx].rbuf[0] = '\0';
1528 My_Connections[Idx].rdatalen = 0;
1529 My_Connections[Idx].wbuf[0] = '\0';
1530 My_Connections[Idx].wdatalen = 0;
1531 My_Connections[Idx].starttime = time( NULL );
1532 My_Connections[Idx].lastdata = time( NULL );
1533 My_Connections[Idx].lastping = 0;
1534 My_Connections[Idx].lastprivmsg = time( NULL );
1535 My_Connections[Idx].delaytime = 0;
1536 My_Connections[Idx].bytes_in = 0;
1537 My_Connections[Idx].bytes_out = 0;
1538 My_Connections[Idx].msg_in = 0;
1539 My_Connections[Idx].msg_out = 0;
1540 My_Connections[Idx].flag = 0;
1541 My_Connections[Idx].options = 0;
1544 My_Connections[Idx].zip.rbuf[0] = '\0';
1545 My_Connections[Idx].zip.rdatalen = 0;
1546 My_Connections[Idx].zip.wbuf[0] = '\0';
1547 My_Connections[Idx].zip.wdatalen = 0;
1548 My_Connections[Idx].zip.bytes_in = 0;
1549 My_Connections[Idx].zip.bytes_out = 0;
1551 } /* Init_Conn_Struct */
1555 Init_Socket( INT Sock )
1557 /* Initialize socket (set options) */
1561 #ifdef O_NONBLOCK /* unknown on A/UX */
1562 if( fcntl( Sock, F_SETFL, O_NONBLOCK ) != 0 )
1564 Log( LOG_CRIT, "Can't enable non-blocking mode for socket: %s!", strerror( errno ));
1570 /* Don't block this port after socket shutdown */
1572 if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &value, (socklen_t)sizeof( value )) != 0 )
1574 Log( LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!", strerror( errno ));
1575 /* ignore this error */
1578 /* Set type of service (TOS) */
1579 #if defined(IP_TOS) && defined(IPTOS_LOWDELAY)
1580 value = IPTOS_LOWDELAY;
1582 Log( LOG_DEBUG, "Setting option IP_TOS on socket %d to IPTOS_LOWDELAY (%d).", Sock, value );
1584 if( setsockopt( Sock, SOL_IP, IP_TOS, &value, (socklen_t)sizeof( value )) != 0 )
1586 Log( LOG_ERR, "Can't set socket option IP_TOS: %s!", strerror( errno ));
1587 /* ignore this error */
1596 Read_Resolver_Result( INT r_fd )
1598 /* Ergebnis von Resolver Sub-Prozess aus Pipe lesen
1599 * und entsprechende Connection aktualisieren */
1601 CHAR result[HOST_LEN];
1605 FD_CLR( r_fd, &Resolver_FDs );
1607 /* Read result from pipe */
1608 len = read( r_fd, result, HOST_LEN - 1 );
1613 Log( LOG_CRIT, "Resolver: Can't read result: %s!", strerror( errno ));
1618 /* Search associated connection ... */
1619 for( i = 0; i < Pool_Size; i++ )
1621 if(( My_Connections[i].sock != NONE ) && ( My_Connections[i].res_stat ) && ( My_Connections[i].res_stat->pipe[0] == r_fd )) break;
1623 if( i >= Pool_Size )
1625 /* Ops, none found? Probably the connection has already
1629 Log( LOG_DEBUG, "Resolver: Got result for unknown connection!?" );
1635 Log( LOG_DEBUG, "Resolver: %s is \"%s\".", My_Connections[i].host, result );
1639 close( My_Connections[i].res_stat->pipe[0] );
1640 close( My_Connections[i].res_stat->pipe[1] );
1641 free( My_Connections[i].res_stat );
1642 My_Connections[i].res_stat = NULL;
1644 if( My_Connections[i].sock > NONE )
1649 /* Incoming connection: set hostname */
1650 c = Client_GetFromConn( i );
1651 assert( c != NULL );
1652 strlcpy( My_Connections[i].host, result, sizeof( My_Connections[i].host ));
1653 Client_SetHostname( c, result );
1656 ident = strchr( result, 0 );
1659 /* Do we have a result of the IDENT lookup? */
1662 Log( LOG_INFO, "IDENT lookup on connection %ld: \"%s\".", i, ident );
1663 Client_SetUser( c, ident, TRUE );
1665 else Log( LOG_INFO, "IDENT lookup on connection %ld: no result.", i );
1670 /* Outgoing connection (server link!): set IP address */
1671 n = Conf_GetServer( i );
1672 if( n > NONE ) strlcpy( Conf_Server[n].ip, result, sizeof( Conf_Server[n].ip ));
1673 else Log( LOG_ERR, "Got resolver result for non-configured server!?" );
1676 /* Reset penalty time */
1677 Conn_ResetPenalty( i );
1678 } /* Read_Resolver_Result */
1682 Simple_Message( INT Sock, CHAR *Msg )
1684 /* Write "simple" message to socket, without using compression
1685 * or even the connection write buffers. Used e.g. for error
1686 * messages by New_Connection(). */
1688 assert( Sock > NONE );
1689 assert( Msg != NULL );
1691 (VOID)send( Sock, Msg, strlen( Msg ), 0 );
1692 (VOID)send( Sock, "\r\n", 2, 0 );
1693 } /* Simple_Error */
1697 Count_Connections( struct sockaddr_in addr_in )
1702 for( i = 0; i < Pool_Size; i++ )
1704 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].addr.sin_addr.s_addr == addr_in.sin_addr.s_addr )) cnt++;
1707 } /* Count_Connections */