2 * ngIRCd -- The Next Generation IRC Daemon
3 * Copyright (c)2001,2002 by Alexander Barton (alex@barton.de)
5 * Dieses Programm ist freie Software. Sie koennen es unter den Bedingungen
6 * der GNU General Public License (GPL), wie von der Free Software Foundation
7 * herausgegeben, weitergeben und/oder modifizieren, entweder unter Version 2
8 * der Lizenz oder (wenn Sie es wuenschen) jeder spaeteren Version.
9 * Naehere Informationen entnehmen Sie bitter der Datei COPYING. Eine Liste
10 * der an ngIRCd beteiligten Autoren finden Sie in der Datei AUTHORS.
12 * $Id: conn.c,v 1.99 2002/11/29 13:13:42 alex Exp $
14 * connect.h: Verwaltung aller Netz-Verbindungen ("connections")
29 #include <sys/socket.h>
31 #include <sys/types.h>
33 #include <netinet/in.h>
35 #ifdef HAVE_ARPA_INET_H
36 #include <arpa/inet.h>
38 #define PF_INET AF_INET
42 #include <stdint.h> /* u.a. fuer Mac OS X */
64 #define SERVER_WAIT (NONE - 1)
68 typedef struct _ZipData
70 z_stream in; /* "Handle" fuer Input-Stream */
71 z_stream out; /* "Handle" fuer Output-Stream */
72 CHAR rbuf[READBUFFER_LEN]; /* Lesepuffer */
73 INT rdatalen; /* Laenge der Daten im Lesepuffer (komprimiert) */
74 CHAR wbuf[WRITEBUFFER_LEN]; /* Schreibpuffer */
75 INT wdatalen; /* Laenge der Daten im Schreibpuffer (unkomprimiert) */
76 LONG bytes_in, bytes_out; /* Counter fuer Statistik (unkomprimiert!) */
81 typedef struct _Connection
83 INT sock; /* Socket Handle */
84 struct sockaddr_in addr; /* Adresse des Client */
85 RES_STAT *res_stat; /* "Resolver-Status", s.o. */
86 CHAR host[HOST_LEN]; /* Hostname */
87 CHAR rbuf[READBUFFER_LEN]; /* Lesepuffer */
88 INT rdatalen; /* Laenge der Daten im Lesepuffer */
89 CHAR wbuf[WRITEBUFFER_LEN]; /* Schreibpuffer */
90 INT wdatalen; /* Laenge der Daten im Schreibpuffer */
91 INT our_server; /* wenn von uns zu connectender Server: ID */
92 time_t lastdata; /* Letzte Aktivitaet */
93 time_t lastping; /* Letzter PING */
94 time_t lastprivmsg; /* Letzte PRIVMSG */
95 time_t delaytime; /* Nicht beachten bis ("penalty") */
96 LONG bytes_in, bytes_out; /* Counter fuer Statistik */
97 INT flag; /* "Markierungs-Flag" (vgl. "irc-write"-Modul) */
98 INT options; /* Link-Optionen */
100 ZIPDATA zip; /* Kompressionsinformationen */
105 LOCAL VOID Handle_Read PARAMS(( INT sock ));
106 LOCAL BOOLEAN Handle_Write PARAMS(( CONN_ID Idx ));
107 LOCAL VOID New_Connection PARAMS(( INT Sock ));
108 LOCAL CONN_ID Socket2Index PARAMS(( INT Sock ));
109 LOCAL VOID Read_Request PARAMS(( CONN_ID Idx ));
110 LOCAL BOOLEAN Try_Write PARAMS(( CONN_ID Idx ));
111 LOCAL BOOLEAN Handle_Buffer PARAMS(( CONN_ID Idx ));
112 LOCAL VOID Check_Connections PARAMS(( VOID ));
113 LOCAL VOID Check_Servers PARAMS(( VOID ));
114 LOCAL VOID Init_Conn_Struct PARAMS(( LONG Idx ));
115 LOCAL BOOLEAN Init_Socket PARAMS(( INT Sock ));
116 LOCAL VOID New_Server PARAMS(( INT Server, CONN_ID Idx ));
117 LOCAL VOID Read_Resolver_Result PARAMS(( INT r_fd ));
120 LOCAL BOOLEAN Zip_Buffer PARAMS(( CONN_ID Idx, CHAR *Data, INT Len ));
121 LOCAL BOOLEAN Zip_Flush PARAMS(( CONN_ID Idx ));
122 LOCAL BOOLEAN Unzip_Buffer PARAMS(( CONN_ID Idx ));
126 LOCAL fd_set My_Listeners;
127 LOCAL fd_set My_Sockets;
128 LOCAL fd_set My_Connects;
130 LOCAL CONNECTION *My_Connections;
131 LOCAL LONG Pool_Size;
137 /* Modul initialisieren: statische Strukturen "ausnullen". */
141 /* Speicher fuer Verbindungs-Pool anfordern */
142 Pool_Size = CONNECTION_POOL;
143 if( Conf_MaxConnections > 0 )
145 /* konfiguriertes Limit beachten */
146 if( Pool_Size > Conf_MaxConnections ) Pool_Size = Conf_MaxConnections;
148 My_Connections = malloc( sizeof( CONNECTION ) * Pool_Size );
149 if( ! My_Connections )
151 /* Speicher konnte nicht alloziert werden! */
152 Log( LOG_EMERG, "Can't allocate memory! [Conn_Init]" );
155 Log( LOG_DEBUG, "Allocted connection pool for %ld items.", Pool_Size );
157 /* zu Beginn haben wir keine Verbindungen */
158 FD_ZERO( &My_Listeners );
159 FD_ZERO( &My_Sockets );
160 FD_ZERO( &My_Connects );
162 /* Groesster File-Descriptor fuer select() */
165 /* Connection-Struktur initialisieren */
166 for( i = 0; i < Pool_Size; i++ ) Init_Conn_Struct( i );
173 /* Modul abmelden: alle noch offenen Connections
174 * schliessen und freigeben. */
179 /* Sockets schliessen */
180 Log( LOG_DEBUG, "Shutting down all connections ..." );
181 for( i = 0; i < Conn_MaxFD + 1; i++ )
183 if( FD_ISSET( i, &My_Sockets ))
185 for( idx = 0; idx < Pool_Size; idx++ )
187 if( My_Connections[idx].sock == i ) break;
189 if( FD_ISSET( i, &My_Listeners ))
192 Log( LOG_DEBUG, "Listening socket %d closed.", i );
194 else if( FD_ISSET( i, &My_Connects ))
197 Log( LOG_DEBUG, "Connection %d closed during creation (socket %d).", idx, i );
199 else if( idx < Pool_Size )
201 if( NGIRCd_Restart ) Conn_Close( idx, NULL, "Server going down (restarting)", TRUE );
202 else Conn_Close( idx, NULL, "Server going down", TRUE );
206 Log( LOG_WARNING, "Closing unknown connection %d ...", i );
212 free( My_Connections );
213 My_Connections = NULL;
219 Conn_InitListeners( VOID )
221 /* Ports, auf denen der Server Verbindungen entgegennehmen
222 * soll, initialisieren */
227 for( i = 0; i < Conf_ListenPorts_Count; i++ )
229 if( Conn_NewListener( Conf_ListenPorts[i] )) created++;
230 else Log( LOG_ERR, "Can't listen on port %u!", Conf_ListenPorts[i] );
233 } /* Conn_InitListeners */
237 Conn_ExitListeners( VOID )
239 /* Alle "Listen-Sockets" schliessen */
243 Log( LOG_INFO, "Shutting down all listening sockets ..." );
244 for( i = 0; i < Conn_MaxFD + 1; i++ )
246 if( FD_ISSET( i, &My_Sockets ) && FD_ISSET( i, &My_Listeners ))
249 Log( LOG_DEBUG, "Listening socket %d closed.", i );
252 } /* Conn_ExitListeners */
256 Conn_NewListener( CONST UINT Port )
258 /* Neuen Listen-Socket erzeugen: der Server wartet dann auf
259 * dem angegebenen Port auf Verbindungen. Kann der Listen-
260 * Socket nicht erteugt werden, so wird NULL geliefert.*/
262 struct sockaddr_in addr;
265 /* Server-"Listen"-Socket initialisieren */
266 memset( &addr, 0, sizeof( addr ));
267 addr.sin_family = AF_INET;
268 addr.sin_port = htons( Port );
269 addr.sin_addr.s_addr = htonl( INADDR_ANY );
271 /* Socket erzeugen */
272 sock = socket( PF_INET, SOCK_STREAM, 0);
275 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
279 if( ! Init_Socket( sock )) return FALSE;
282 if( bind( sock, (struct sockaddr *)&addr, (socklen_t)sizeof( addr )) != 0 )
284 Log( LOG_CRIT, "Can't bind socket: %s!", strerror( errno ));
289 /* in "listen mode" gehen :-) */
290 if( listen( sock, 10 ) != 0 )
292 Log( LOG_CRIT, "Can't listen on soecket: %s!", strerror( errno ));
297 /* Neuen Listener in Strukturen einfuegen */
298 FD_SET( sock, &My_Listeners );
299 FD_SET( sock, &My_Sockets );
301 if( sock > Conn_MaxFD ) Conn_MaxFD = sock;
303 Log( LOG_INFO, "Now listening on port %d (socket %d).", Port, sock );
306 } /* Conn_NewListener */
312 /* "Hauptschleife": Aktive Verbindungen ueberwachen. Folgende Aktionen
313 * werden dabei durchgefuehrt, bis der Server terminieren oder neu
316 * - neue Verbindungen annehmen,
317 * - Server-Verbindungen aufbauen,
318 * - geschlossene Verbindungen loeschen,
319 * - volle Schreibpuffer versuchen zu schreiben,
320 * - volle Lesepuffer versuchen zu verarbeiten,
321 * - Antworten von Resolver Sub-Prozessen annehmen.
324 fd_set read_sockets, write_sockets;
330 start = time( NULL );
331 while(( ! NGIRCd_Quit ) && ( ! NGIRCd_Restart ))
337 Check_Connections( );
339 /* noch volle Lese-Buffer suchen */
340 for( i = 0; i < Pool_Size; i++ )
342 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].rdatalen > 0 ))
344 /* Kann aus dem Buffer noch ein Befehl extrahiert werden? */
345 if( Handle_Buffer( i )) timeout = FALSE;
349 /* noch volle Schreib-Puffer suchen */
350 FD_ZERO( &write_sockets );
351 for( i = 0; i < Pool_Size; i++ )
354 if(( My_Connections[i].sock > NONE ) && (( My_Connections[i].wdatalen > 0 ) || ( My_Connections[i].zip.wdatalen > 0 )))
356 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].wdatalen > 0 ))
359 /* Socket der Verbindung in Set aufnehmen */
360 FD_SET( My_Connections[i].sock, &write_sockets );
363 /* Sockets mit im Aufbau befindlichen ausgehenden Verbindungen suchen */
364 for( i = 0; i < Pool_Size; i++ )
366 if(( My_Connections[i].sock > NONE ) && ( FD_ISSET( My_Connections[i].sock, &My_Connects ))) FD_SET( My_Connections[i].sock, &write_sockets );
369 /* von welchen Sockets koennte gelesen werden? */
371 read_sockets = My_Sockets;
372 for( i = 0; i < Pool_Size; i++ )
374 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].host[0] == '\0' ))
376 /* Hier muss noch auf den Resolver Sub-Prozess gewartet werden */
377 FD_CLR( My_Connections[i].sock, &read_sockets );
379 if(( My_Connections[i].sock > NONE ) && ( FD_ISSET( My_Connections[i].sock, &My_Connects )))
381 /* Hier laeuft noch ein asyncrones connect() */
382 FD_CLR( My_Connections[i].sock, &read_sockets );
384 if( My_Connections[i].delaytime > t )
386 /* Fuer die Verbindung ist eine "Penalty-Zeit" gesetzt */
387 FD_CLR( My_Connections[i].sock, &read_sockets );
388 FD_CLR( My_Connections[i].sock, &write_sockets );
391 for( i = 0; i < Conn_MaxFD + 1; i++ )
393 /* Pipes von Resolver Sub-Prozessen aufnehmen */
394 if( FD_ISSET( i, &Resolver_FDs ))
396 FD_SET( i, &read_sockets );
400 /* Timeout initialisieren */
402 if( timeout ) tv.tv_sec = TIME_RES;
405 /* Auf Aktivitaet warten */
406 i = select( Conn_MaxFD + 1, &read_sockets, &write_sockets, NULL, &tv );
409 /* keine Veraenderung an den Sockets */
414 /* Fehler (z.B. Interrupt) */
417 Log( LOG_EMERG, "Conn_Handler(): select(): %s!", strerror( errno ));
418 Log( LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE );
424 /* Koennen Daten geschrieben werden? */
425 for( i = 0; i < Conn_MaxFD + 1; i++ )
427 if( ! FD_ISSET( i, &write_sockets )) continue;
429 /* Es kann geschrieben werden ... */
430 idx = Socket2Index( i );
431 if( idx == NONE ) continue;
433 if( ! Handle_Write( idx ))
435 /* Fehler beim Schreiben! Diesen Socket nun
436 * auch aus dem Read-Set entfernen: */
437 FD_CLR( i, &read_sockets );
441 /* Daten zum Lesen vorhanden? */
442 for( i = 0; i < Conn_MaxFD + 1; i++ )
444 if( FD_ISSET( i, &read_sockets )) Handle_Read( i );
452 Conn_WriteStr( CONN_ID Idx, CHAR *Format, ... )
455 Conn_WriteStr( Idx, Format, va_alist )
461 /* String in Socket schreiben. CR+LF wird von dieser Funktion
462 * automatisch angehaengt. Im Fehlerfall wird dir Verbindung
463 * getrennt und FALSE geliefert. */
465 CHAR buffer[COMMAND_LEN];
469 assert( Idx > NONE );
470 assert( Format != NULL );
473 va_start( ap, Format );
477 if( vsnprintf( buffer, COMMAND_LEN - 2, Format, ap ) == COMMAND_LEN - 2 )
479 Log( LOG_CRIT, "Text too long to send (connection %d)!", Idx );
480 Conn_Close( Idx, "Text too long to send!", NULL, FALSE );
485 if( NGIRCd_Sniffer ) Log( LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer );
488 strcat( buffer, "\r\n" );
489 ok = Conn_Write( Idx, buffer, strlen( buffer ));
493 } /* Conn_WriteStr */
497 Conn_Write( CONN_ID Idx, CHAR *Data, INT Len )
499 /* Daten in Socket schreiben. Bei "fatalen" Fehlern wird
500 * der Client disconnectiert und FALSE geliefert. */
502 assert( Idx > NONE );
503 assert( Data != NULL );
506 /* Ist der entsprechende Socket ueberhaupt noch offen? In einem
507 * "Handler-Durchlauf" kann es passieren, dass dem nicht mehr so
508 * ist, wenn einer von mehreren Conn_Write()'s fehlgeschlagen ist.
509 * In diesem Fall wird hier einfach ein Fehler geliefert. */
510 if( My_Connections[Idx].sock <= NONE )
512 Log( LOG_DEBUG, "Skipped write on closed socket (connection %d).", Idx );
516 /* Pruefen, ob im Schreibpuffer genuegend Platz ist. Ziel ist es,
517 * moeglichts viel im Puffer zu haben und _nicht_ gleich alles auf den
518 * Socket zu schreiben (u.a. wg. Komprimierung). */
519 if( WRITEBUFFER_LEN - My_Connections[Idx].wdatalen - Len <= 0 )
521 /* Der Puffer ist dummerweise voll. Jetzt versuchen, den Puffer
522 * zu schreiben, wenn das nicht klappt, haben wir ein Problem ... */
523 if( ! Try_Write( Idx )) return FALSE;
525 /* nun neu pruefen: */
526 if( WRITEBUFFER_LEN - My_Connections[Idx].wdatalen - Len <= 0 )
528 Log( LOG_NOTICE, "Write buffer overflow (connection %d)!", Idx );
529 Conn_Close( Idx, "Write buffer overflow!", NULL, FALSE );
535 if( My_Connections[Idx].options & CONN_ZIP )
537 /* Daten komprimieren und in Puffer kopieren */
538 if( ! Zip_Buffer( Idx, Data, Len )) return FALSE;
543 /* Daten in Puffer kopieren */
544 memcpy( My_Connections[Idx].wbuf + My_Connections[Idx].wdatalen, Data, Len );
545 My_Connections[Idx].wdatalen += Len;
546 My_Connections[Idx].bytes_out += Len;
554 Conn_Close( CONN_ID Idx, CHAR *LogMsg, CHAR *FwdMsg, BOOLEAN InformClient )
556 /* Verbindung schliessen. Evtl. noch von Resolver
557 * Sub-Prozessen offene Pipes werden geschlossen. */
562 DOUBLE in_z_k, out_z_k;
566 assert( Idx > NONE );
567 assert( My_Connections[Idx].sock > NONE );
569 c = Client_GetFromConn( Idx );
574 /* Statistik an Client melden, wenn User */
575 if(( c != NULL ) && ( Client_Type( c ) == CLIENT_USER ))
577 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 );
581 /* ERROR an Client schicken (von RFC so vorgesehen!) */
582 if( FwdMsg ) Conn_WriteStr( Idx, "ERROR :%s", FwdMsg );
583 else Conn_WriteStr( Idx, "ERROR :Closing connection." );
584 if( My_Connections[Idx].sock == NONE ) return;
587 /* zunaechst versuchen, noch im Schreibpuffer vorhandene
588 * Daten auf den Socket zu schreiben ... */
591 if( close( My_Connections[Idx].sock ) != 0 )
593 Log( LOG_ERR, "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 ));
597 in_k = (DOUBLE)My_Connections[Idx].bytes_in / 1024;
598 out_k = (DOUBLE)My_Connections[Idx].bytes_out / 1024;
600 if( My_Connections[Idx].options & CONN_ZIP )
602 in_z_k = (DOUBLE)My_Connections[Idx].zip.bytes_in / 1024;
603 out_z_k = (DOUBLE)My_Connections[Idx].zip.bytes_out / 1024;
604 in_p = (INT)(( in_k * 100 ) / in_z_k );
605 out_p = (INT)(( out_k * 100 ) / out_z_k );
606 Log( LOG_INFO, "Connection %d (socket %d) with %s:%d closed (in: %.1fk/%.1fk/%d%%, out: %.1fk/%.1fk/%d%%).", Idx, My_Connections[Idx].sock, 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 );
611 Log( LOG_INFO, "Connection %d (socket %d) with %s:%d closed (in: %.1fk, out: %.1fk).", Idx, My_Connections[Idx].sock, My_Connections[Idx].host, ntohs( My_Connections[Idx].addr.sin_port ), in_k, out_k );
615 /* Socket als "ungueltig" markieren */
616 FD_CLR( My_Connections[Idx].sock, &My_Sockets );
617 FD_CLR( My_Connections[Idx].sock, &My_Connects );
618 My_Connections[Idx].sock = NONE;
620 if( c ) Client_Destroy( c, LogMsg, FwdMsg, TRUE );
622 if( My_Connections[Idx].res_stat )
624 /* Resolver-Strukturen freigeben, wenn noch nicht geschehen */
625 FD_CLR( My_Connections[Idx].res_stat->pipe[0], &Resolver_FDs );
626 close( My_Connections[Idx].res_stat->pipe[0] );
627 close( My_Connections[Idx].res_stat->pipe[1] );
628 free( My_Connections[Idx].res_stat );
631 /* Startzeit des naechsten Connect-Versuchs modifizieren? */
632 if(( My_Connections[Idx].our_server > NONE ) && ( Conf_Server[My_Connections[Idx].our_server].lasttry < time( NULL ) - Conf_ConnectRetry ))
634 /* Okay, die Verbindung stand schon "genuegend lange":
635 * lasttry-Zeitpunkt so setzen, dass der naechste
636 * Verbindungsversuch in RECONNECT_DELAY Sekunden
638 Conf_Server[My_Connections[Idx].our_server].lasttry = time( NULL ) - Conf_ConnectRetry + RECONNECT_DELAY;
642 /* Ggf. zlib abmelden */
643 if( Conn_Options( Idx ) & CONN_ZIP )
645 inflateEnd( &My_Connections[Idx].zip.in );
646 deflateEnd( &My_Connections[Idx].zip.out );
650 /* Connection-Struktur loeschen (=freigeben) */
651 Init_Conn_Struct( Idx );
656 Conn_UpdateIdle( CONN_ID Idx )
658 /* Idle-Timer zuruecksetzen */
660 assert( Idx > NONE );
661 My_Connections[Idx].lastprivmsg = time( NULL );
666 Conn_GetIdle( CONN_ID Idx )
668 /* Idle-Time einer Verbindung liefern (in Sekunden) */
670 assert( Idx > NONE );
671 return time( NULL ) - My_Connections[Idx].lastprivmsg;
676 Conn_LastPing( CONN_ID Idx )
678 /* Zeitpunkt des letzten PING liefern */
680 assert( Idx > NONE );
681 return My_Connections[Idx].lastping;
682 } /* Conn_LastPing */
686 Conn_SetPenalty( CONN_ID Idx, time_t Seconds )
688 /* Penalty-Delay fuer eine Verbindung (in Sekunden) setzen;
689 * waehrend dieser Zeit wird der entsprechende Socket vom Server
690 * bei Lese-Operationen komplett ignoriert. Der Delay kann mit
691 * dieser Funktion nur erhoeht, nicht aber verringert werden. */
695 assert( Idx > NONE );
696 assert( Seconds >= 0 );
698 t = time( NULL ) + Seconds;
699 if( t > My_Connections[Idx].delaytime ) My_Connections[Idx].delaytime = t;
700 } /* Conn_SetPenalty */
704 Conn_ResetPenalty( CONN_ID Idx )
706 assert( Idx > NONE );
707 My_Connections[Idx].delaytime = 0;
708 } /* Conn_ResetPenalty */
712 Conn_ClearFlags( VOID )
714 /* Alle Connection auf "nicht-markiert" setzen */
718 for( i = 0; i < Pool_Size; i++ ) My_Connections[i].flag = 0;
719 } /* Conn_ClearFlags */
723 Conn_Flag( CONN_ID Idx )
725 /* Ist eine Connection markiert (TRUE) oder nicht? */
727 assert( Idx > NONE );
728 return My_Connections[Idx].flag;
733 Conn_SetFlag( CONN_ID Idx, INT Flag )
735 /* Connection markieren */
737 assert( Idx > NONE );
738 My_Connections[Idx].flag = Flag;
745 /* Connection-Struktur der ersten Verbindung liefern;
746 * Ist keine Verbindung vorhanden, wird NONE geliefert. */
750 for( i = 0; i < Pool_Size; i++ )
752 if( My_Connections[i].sock != NONE ) return i;
759 Conn_Next( CONN_ID Idx )
761 /* Naechste Verbindungs-Struktur liefern; existiert keine
762 * weitere, so wird NONE geliefert. */
766 assert( Idx > NONE );
768 for( i = Idx + 1; i < Pool_Size; i++ )
770 if( My_Connections[i].sock != NONE ) return i;
777 Conn_SetServer( CONN_ID Idx, INT ConfServer )
779 /* Connection als Server markieren: Index des konfigurierten
780 * Servers speichern. Verbindung muss bereits bestehen! */
782 assert( Idx > NONE );
783 assert( My_Connections[Idx].sock > NONE );
785 My_Connections[Idx].our_server = ConfServer;
786 } /* Conn_SetServer */
790 Conn_SetOption( CONN_ID Idx, INT Option )
792 /* Option fuer Verbindung setzen.
793 * Initial sind alle Optionen _nicht_ gesetzt. */
795 assert( Idx > NONE );
796 assert( Option != 0 );
798 My_Connections[Idx].options |= Option;
799 } /* Conn_SetOption */
803 Conn_UnsetOption( CONN_ID Idx, INT Option )
805 /* Option fuer Verbindung loeschen */
807 assert( Idx > NONE );
808 assert( Option != 0 );
810 My_Connections[Idx].options &= ~Option;
811 } /* Conn_UnsetOption */
815 Conn_Options( CONN_ID Idx )
817 assert( Idx > NONE );
818 return My_Connections[Idx].options;
825 Conn_InitZip( CONN_ID Idx )
827 /* Kompression fuer Link initialisieren */
829 assert( Idx > NONE );
831 My_Connections[Idx].zip.in.avail_in = 0;
832 My_Connections[Idx].zip.in.total_in = 0;
833 My_Connections[Idx].zip.in.total_out = 0;
834 My_Connections[Idx].zip.in.zalloc = NULL;
835 My_Connections[Idx].zip.in.zfree = NULL;
836 My_Connections[Idx].zip.in.data_type = Z_ASCII;
838 if( inflateInit( &My_Connections[Idx].zip.in ) != Z_OK )
841 Log( LOG_ALERT, "Can't initialize compression on connection %d (zlib inflate)!", Idx );
845 My_Connections[Idx].zip.out.total_in = 0;
846 My_Connections[Idx].zip.out.total_in = 0;
847 My_Connections[Idx].zip.out.zalloc = NULL;
848 My_Connections[Idx].zip.out.zfree = NULL;
849 My_Connections[Idx].zip.out.data_type = Z_ASCII;
851 if( deflateInit( &My_Connections[Idx].zip.out, Z_DEFAULT_COMPRESSION ) != Z_OK )
854 Log( LOG_ALERT, "Can't initialize compression on connection %d (zlib deflate)!", Idx );
858 My_Connections[Idx].zip.bytes_in = My_Connections[Idx].bytes_in;
859 My_Connections[Idx].zip.bytes_out = My_Connections[Idx].bytes_out;
861 Log( LOG_INFO, "Enabled link compression (zlib) on connection %d.", Idx );
862 Conn_SetOption( Idx, CONN_ZIP );
871 Try_Write( CONN_ID Idx )
873 /* Versuchen, Daten aus dem Schreib-Puffer in den Socket zu
874 * schreiben. TRUE wird geliefert, wenn entweder keine Daten
875 * zum Versenden vorhanden sind oder erfolgreich bearbeitet
876 * werden konnten. Im Fehlerfall wird FALSE geliefert und
877 * die Verbindung geschlossen. */
882 assert( Idx > NONE );
883 assert( My_Connections[Idx].sock > NONE );
885 /* sind ueberhaupt Daten vorhanden? */
887 if(( ! My_Connections[Idx].wdatalen > 0 ) && ( ! My_Connections[Idx].zip.wdatalen )) return TRUE;
889 if( ! My_Connections[Idx].wdatalen > 0 ) return TRUE;
892 /* Timeout initialisieren: 0 Sekunden, also nicht blockieren */
893 tv.tv_sec = 0; tv.tv_usec = 0;
895 FD_ZERO( &write_socket );
896 FD_SET( My_Connections[Idx].sock, &write_socket );
897 if( select( My_Connections[Idx].sock + 1, NULL, &write_socket, NULL, &tv ) == -1 )
902 Log( LOG_ALERT, "Try_Write(): select() failed: %s (con=%d, sock=%d)!", strerror( errno ), Idx, My_Connections[Idx].sock );
903 Conn_Close( Idx, "Server error!", NULL, FALSE );
908 if( FD_ISSET( My_Connections[Idx].sock, &write_socket )) return Handle_Write( Idx );
914 Handle_Read( INT Sock )
916 /* Aktivitaet auf einem Socket verarbeiten:
917 * - neue Clients annehmen,
918 * - Daten von Clients verarbeiten,
919 * - Resolver-Rueckmeldungen annehmen. */
923 assert( Sock > NONE );
925 if( FD_ISSET( Sock, &My_Listeners ))
927 /* es ist einer unserer Listener-Sockets: es soll
928 * also eine neue Verbindung aufgebaut werden. */
930 New_Connection( Sock );
932 else if( FD_ISSET( Sock, &Resolver_FDs ))
934 /* Rueckmeldung von einem Resolver Sub-Prozess */
936 Read_Resolver_Result( Sock );
940 /* Ein Client Socket: entweder ein User oder Server */
942 idx = Socket2Index( Sock );
943 if( idx > NONE ) Read_Request( idx );
949 Handle_Write( CONN_ID Idx )
951 /* Daten aus Schreibpuffer versenden bzw. Connection aufbauen */
955 assert( Idx > NONE );
956 assert( My_Connections[Idx].sock > NONE );
958 if( FD_ISSET( My_Connections[Idx].sock, &My_Connects ))
960 /* es soll nichts geschrieben werden, sondern ein
961 * connect() hat ein Ergebnis geliefert */
963 FD_CLR( My_Connections[Idx].sock, &My_Connects );
965 /* Ergebnis des connect() ermitteln */
967 res = getsockopt( My_Connections[Idx].sock, SOL_SOCKET, SO_ERROR, &err, &len );
968 assert( len == sizeof( err ));
970 /* Fehler aufgetreten? */
971 if(( res != 0 ) || ( err != 0 ))
974 if( res != 0 ) Log( LOG_CRIT, "getsockopt (connection %d): %s!", Idx, strerror( errno ));
975 else Log( LOG_CRIT, "Can't connect socket to \"%s:%d\" (connection %d): %s!", My_Connections[Idx].host, Conf_Server[My_Connections[Idx].our_server].port, Idx, strerror( err ));
977 /* Socket etc. pp. aufraeumen */
978 FD_CLR( My_Connections[Idx].sock, &My_Sockets );
979 close( My_Connections[Idx].sock );
980 Init_Conn_Struct( Idx );
982 /* Bei Server-Verbindungen lasttry-Zeitpunkt auf "jetzt" setzen */
983 Conf_Server[My_Connections[Idx].our_server].lasttry = time( NULL );
987 Log( LOG_DEBUG, "Connection %d with \"%s:%d\" established, now sendig PASS and SERVER ...", Idx, My_Connections[Idx].host, Conf_Server[My_Connections[Idx].our_server].port );
989 /* PASS und SERVER verschicken */
990 Conn_WriteStr( Idx, "PASS %s %s", Conf_Server[My_Connections[Idx].our_server].pwd_out, NGIRCd_ProtoID );
991 return Conn_WriteStr( Idx, "SERVER %s :%s", Conf_ServerName, Conf_ServerInfo );
995 /* Schreibpuffer leer, aber noch Daten im Kompressionsbuffer?
996 * Dann muss dieser nun geflushed werden! */
997 if( My_Connections[Idx].wdatalen == 0 ) Zip_Flush( Idx );
1000 assert( My_Connections[Idx].wdatalen > 0 );
1002 /* Daten schreiben */
1003 len = send( My_Connections[Idx].sock, My_Connections[Idx].wbuf, My_Connections[Idx].wdatalen, 0 );
1006 /* Operation haette Socket "nur" blockiert ... */
1007 if( errno == EAGAIN ) return TRUE;
1009 /* Oops, ein Fehler! */
1010 Log( LOG_ERR, "Write error on connection %d (socket %d): %s!", Idx, My_Connections[Idx].sock, strerror( errno ));
1011 Conn_Close( Idx, "Write error!", NULL, FALSE );
1015 /* Puffer anpassen */
1016 My_Connections[Idx].wdatalen -= len;
1017 memmove( My_Connections[Idx].wbuf, My_Connections[Idx].wbuf + len, My_Connections[Idx].wdatalen );
1020 } /* Handle_Write */
1024 New_Connection( INT Sock )
1026 /* Neue Client-Verbindung von Listen-Socket annehmen und
1027 * CLIENT-Struktur anlegen. */
1029 struct sockaddr_in new_addr;
1030 INT new_sock, new_sock_len;
1037 assert( Sock > NONE );
1039 /* Connection auf Listen-Socket annehmen */
1040 new_sock_len = sizeof( new_addr );
1041 new_sock = accept( Sock, (struct sockaddr *)&new_addr, (socklen_t *)&new_sock_len );
1044 Log( LOG_CRIT, "Can't accept connection: %s!", strerror( errno ));
1048 /* Socket initialisieren */
1049 Init_Socket( new_sock );
1051 /* Freie Connection-Struktur suchen */
1052 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
1053 if( idx >= Pool_Size )
1055 new_size = Pool_Size + CONNECTION_POOL;
1057 /* Im bisherigen Pool wurde keine freie Connection-Struktur mehr gefunden.
1058 * Wenn erlaubt und moeglich muss nun der Pool vergroessert werden: */
1060 if( Conf_MaxConnections > 0 )
1062 /* Es ist ein Limit konfiguriert */
1063 if( Pool_Size >= Conf_MaxConnections )
1065 /* Mehr Verbindungen duerfen wir leider nicht mehr annehmen ... */
1066 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached!", Pool_Size );
1070 if( new_size > Conf_MaxConnections ) new_size = Conf_MaxConnections;
1073 /* zunaechst realloc() versuchen; wenn das scheitert, malloc() versuchen
1074 * und Daten ggf. "haendisch" umkopieren. (Haesslich! Eine wirklich
1075 * dynamische Verwaltung waere wohl _deutlich_ besser ...) */
1076 ptr = realloc( My_Connections, sizeof( CONNECTION ) * new_size );
1079 /* realloc() ist fehlgeschlagen. Nun malloc() probieren: */
1080 ptr = malloc( sizeof( CONNECTION ) * new_size );
1083 /* Offenbar steht kein weiterer Sepeicher zur Verfuegung :-( */
1084 Log( LOG_EMERG, "Can't allocate memory! [New_Connection]" );
1089 /* Struktur umkopieren ... */
1090 memcpy( ptr, My_Connections, sizeof( CONNECTION ) * Pool_Size );
1092 Log( LOG_DEBUG, "Allocated new connection pool for %ld items. [malloc()/memcpy()]", new_size );
1094 else Log( LOG_DEBUG, "Allocated new connection pool for %ld items. [realloc()]", new_size );
1096 My_Connections = ptr;
1097 Pool_Size = new_size;
1100 /* Client-Struktur initialisieren */
1101 c = Client_NewLocal( idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWN, FALSE );
1104 Log( LOG_ALERT, "Can't accept connection: can't create client structure!" );
1109 /* Verbindung registrieren */
1110 Init_Conn_Struct( idx );
1111 My_Connections[idx].sock = new_sock;
1112 My_Connections[idx].addr = new_addr;
1114 /* Neuen Socket registrieren */
1115 FD_SET( new_sock, &My_Sockets );
1116 if( new_sock > Conn_MaxFD ) Conn_MaxFD = new_sock;
1118 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 );
1120 /* Hostnamen ermitteln */
1121 strcpy( My_Connections[idx].host, inet_ntoa( new_addr.sin_addr ));
1122 Client_SetHostname( c, My_Connections[idx].host );
1123 s = Resolve_Addr( &new_addr );
1126 /* Sub-Prozess wurde asyncron gestartet */
1128 Conn_WriteStr( idx, "NOTICE AUTH :%sLooking up your hostname ...", NOTICE_TXTPREFIX );
1130 My_Connections[idx].res_stat = s;
1133 /* Penalty-Zeit setzen */
1134 Conn_SetPenalty( idx, 4 );
1135 } /* New_Connection */
1139 Socket2Index( INT Sock )
1141 /* zum Socket passende Connection suchen */
1145 assert( Sock > NONE );
1147 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == Sock ) break;
1149 if( idx >= Pool_Size )
1151 /* die Connection wurde vermutlich (wegen eines
1152 * Fehlers) bereits wieder abgebaut ... */
1153 Log( LOG_DEBUG, "Socket2Index: can't get connection for socket %d!", Sock );
1157 } /* Socket2Index */
1161 Read_Request( CONN_ID Idx )
1163 /* Daten von Socket einlesen und entsprechend behandeln.
1164 * Tritt ein Fehler auf, so wird der Socket geschlossen. */
1171 assert( Idx > NONE );
1172 assert( My_Connections[Idx].sock > NONE );
1174 /* wenn noch nicht registriert: maximal mit ZREADBUFFER_LEN arbeiten,
1175 * ansonsten koennen Daten ggf. nicht umkopiert werden. */
1176 bsize = READBUFFER_LEN;
1178 c = Client_GetFromConn( Idx );
1179 if(( Client_Type( c ) != CLIENT_USER ) && ( Client_Type( c ) != CLIENT_SERVER ) && ( Client_Type( c ) != CLIENT_SERVICE ) && ( bsize > ZREADBUFFER_LEN )) bsize = ZREADBUFFER_LEN;
1183 if(( bsize - My_Connections[Idx].rdatalen - 1 < 1 ) || ( ZREADBUFFER_LEN - My_Connections[Idx].zip.rdatalen < 1 ))
1185 if( bsize - My_Connections[Idx].rdatalen - 1 < 1 )
1188 /* Der Lesepuffer ist voll */
1189 Log( LOG_ERR, "Read buffer overflow (connection %d): %d bytes!", Idx, My_Connections[Idx].rdatalen );
1190 Conn_Close( Idx, "Read buffer overflow!", NULL, FALSE );
1195 if( My_Connections[Idx].options & CONN_ZIP )
1197 len = recv( My_Connections[Idx].sock, My_Connections[Idx].zip.rbuf + My_Connections[Idx].zip.rdatalen, ( ZREADBUFFER_LEN - My_Connections[Idx].zip.rdatalen ), 0 );
1198 if( len > 0 ) My_Connections[Idx].zip.rdatalen += len;
1203 len = recv( My_Connections[Idx].sock, My_Connections[Idx].rbuf + My_Connections[Idx].rdatalen, bsize - My_Connections[Idx].rdatalen - 1, 0 );
1204 if( len > 0 ) My_Connections[Idx].rdatalen += len;
1209 /* Socket wurde geschlossen */
1210 Log( LOG_INFO, "%s:%d is closing the connection ...", inet_ntoa( My_Connections[Idx].addr.sin_addr ), ntohs( My_Connections[Idx].addr.sin_port));
1211 Conn_Close( Idx, "Socket closed!", "Client closed connection", FALSE );
1217 /* Operation haette Socket "nur" blockiert ... */
1218 if( errno == EAGAIN ) return;
1220 /* Fehler beim Lesen */
1221 Log( LOG_ERR, "Read error on connection %d (socket %d): %s!", Idx, My_Connections[Idx].sock, strerror( errno ));
1222 Conn_Close( Idx, "Read error!", "Client closed connection", FALSE );
1226 /* Connection-Statistik aktualisieren */
1227 My_Connections[Idx].bytes_in += len;
1229 /* Timestamp aktualisieren */
1230 My_Connections[Idx].lastdata = time( NULL );
1232 Handle_Buffer( Idx );
1233 } /* Read_Request */
1237 Handle_Buffer( CONN_ID Idx )
1239 /* Daten im Lese-Puffer einer Verbindung verarbeiten.
1240 * Wurde ein Request verarbeitet, so wird TRUE geliefert,
1241 * ansonsten FALSE (auch bei Fehlern). */
1248 BOOLEAN action, result;
1257 /* ggf. noch unkomprimiete Daten weiter entpacken */
1258 if( My_Connections[Idx].options & CONN_ZIP )
1260 if( ! Unzip_Buffer( Idx )) return FALSE;
1264 if( My_Connections[Idx].rdatalen < 1 ) break;
1266 /* Eine komplette Anfrage muss mit CR+LF enden, vgl.
1267 * RFC 2812. Haben wir eine? */
1268 My_Connections[Idx].rbuf[My_Connections[Idx].rdatalen] = '\0';
1269 ptr = strstr( My_Connections[Idx].rbuf, "\r\n" );
1271 if( ptr ) delta = 2;
1275 /* Nicht RFC-konforme Anfrage mit nur CR oder LF? Leider
1276 * machen soetwas viele Clients, u.a. "mIRC" :-( */
1277 ptr1 = strchr( My_Connections[Idx].rbuf, '\r' );
1278 ptr2 = strchr( My_Connections[Idx].rbuf, '\n' );
1280 if( ptr1 && ptr2 ) ptr = ptr1 > ptr2 ? ptr2 : ptr1;
1281 else if( ptr1 ) ptr = ptr1;
1282 else if( ptr2 ) ptr = ptr2;
1289 /* Ende der Anfrage wurde gefunden */
1291 len = ( ptr - My_Connections[Idx].rbuf ) + delta;
1292 if( len > ( COMMAND_LEN - 1 ))
1294 /* Eine Anfrage darf(!) nicht laenger als 512 Zeichen
1295 * (incl. CR+LF!) werden; vgl. RFC 2812. Wenn soetwas
1296 * empfangen wird, wird der Client disconnectiert. */
1297 Log( LOG_ERR, "Request too long (connection %d): %d bytes (max. %d expected)!", Idx, My_Connections[Idx].rdatalen, COMMAND_LEN - 1 );
1298 Conn_Close( Idx, NULL, "Request too long", TRUE );
1303 /* merken, ob Stream bereits komprimiert wird */
1304 old_z = My_Connections[Idx].options & CONN_ZIP;
1309 /* Es wurde ein Request gelesen */
1310 if( ! Parse_Request( Idx, My_Connections[Idx].rbuf )) return FALSE;
1314 /* Puffer anpassen */
1315 My_Connections[Idx].rdatalen -= len;
1316 memmove( My_Connections[Idx].rbuf, My_Connections[Idx].rbuf + len, My_Connections[Idx].rdatalen );
1319 if(( ! old_z ) && ( My_Connections[Idx].options & CONN_ZIP ) && ( My_Connections[Idx].rdatalen > 0 ))
1321 /* Mit dem letzten Befehl wurde Socket-Kompression aktiviert.
1322 * Evtl. schon vom Socket gelesene Daten in den Unzip-Puffer
1323 * umkopieren, damit diese nun zunaechst entkomprimiert werden */
1325 if( My_Connections[Idx].rdatalen > ZREADBUFFER_LEN )
1327 /* Hupsa! Soviel Platz haben wir aber gar nicht! */
1328 Log( LOG_ALERT, "Can't move read buffer: No space left in unzip buffer (need %d bytes)!", My_Connections[Idx].rdatalen );
1331 memcpy( My_Connections[Idx].zip.rbuf, My_Connections[Idx].rbuf, My_Connections[Idx].rdatalen );
1332 My_Connections[Idx].zip.rdatalen = My_Connections[Idx].rdatalen;
1333 My_Connections[Idx].rdatalen = 0;
1334 Log( LOG_DEBUG, "Moved already received data (%d bytes) to uncompression buffer.", My_Connections[Idx].zip.rdatalen );
1340 if( action ) result = TRUE;
1344 } /* Handle_Buffer */
1348 Check_Connections( VOID )
1350 /* Pruefen, ob Verbindungen noch "alive" sind. Ist dies
1351 * nicht der Fall, zunaechst PING-PONG spielen und, wenn
1352 * auch das nicht "hilft", Client disconnectieren. */
1357 for( i = 0; i < Pool_Size; i++ )
1359 if( My_Connections[i].sock == NONE ) continue;
1361 c = Client_GetFromConn( i );
1362 if( c && (( Client_Type( c ) == CLIENT_USER ) || ( Client_Type( c ) == CLIENT_SERVER ) || ( Client_Type( c ) == CLIENT_SERVICE )))
1364 /* verbundener User, Server oder Service */
1365 if( My_Connections[i].lastping > My_Connections[i].lastdata )
1367 /* es wurde bereits ein PING gesendet */
1368 if( My_Connections[i].lastping < time( NULL ) - Conf_PongTimeout )
1371 Log( LOG_DEBUG, "Connection %d: Ping timeout: %d seconds.", i, Conf_PongTimeout );
1372 Conn_Close( i, NULL, "Ping timeout", TRUE );
1375 else if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout )
1377 /* es muss ein PING gesendet werden */
1378 Log( LOG_DEBUG, "Connection %d: sending PING ...", i );
1379 My_Connections[i].lastping = time( NULL );
1380 Conn_WriteStr( i, "PING :%s", Client_ID( Client_ThisServer( )));
1385 /* noch nicht vollstaendig aufgebaute Verbindung */
1386 if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout )
1389 Log( LOG_DEBUG, "Connection %d timed out ...", i );
1390 Conn_Close( i, NULL, "Timeout", FALSE );
1394 } /* Check_Connections */
1398 Check_Servers( VOID )
1400 /* Pruefen, ob Server-Verbindungen aufgebaut werden
1401 * muessen bzw. koennen */
1407 /* Wenn "Passive-Mode" aktiv: nicht verbinden */
1408 if( NGIRCd_Passive ) return;
1410 for( i = 0; i < Conf_Server_Count; i++ )
1412 /* Ist ein Hostname und Port definiert? */
1413 if(( ! Conf_Server[i].host[0] ) || ( ! Conf_Server[i].port > 0 )) continue;
1415 /* Haben wir schon eine Verbindung? */
1416 for( n = 0; n < Pool_Size; n++ )
1418 if( My_Connections[n].sock == NONE ) continue;
1420 /* Verbindung zu diesem Server? */
1421 if( My_Connections[n].our_server == i )
1423 /* Komplett aufgebaute Verbindung? */
1424 if( My_Connections[n].sock > NONE ) break;
1426 /* IP schon aufgeloest? */
1427 if( My_Connections[n].res_stat == NULL ) New_Server( i, n );
1430 /* Verbindung in dieser Server-Gruppe? */
1431 if(( My_Connections[n].our_server != NONE ) && ( Conf_Server[i].group != NONE ))
1433 if( Conf_Server[My_Connections[n].our_server].group == Conf_Server[i].group ) break;
1436 if( n < Pool_Size ) continue;
1438 /* Wann war der letzte Connect-Versuch? */
1439 if( Conf_Server[i].lasttry > time( NULL ) - Conf_ConnectRetry ) continue;
1441 /* Okay, Verbindungsaufbau versuchen */
1442 Conf_Server[i].lasttry = time( NULL );
1444 /* Freie Connection-Struktur suschen */
1445 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
1446 if( idx >= Pool_Size )
1448 Log( LOG_ALERT, "Can't establist server connection: connection limit reached (%d)!", Pool_Size );
1451 Log( LOG_DEBUG, "Preparing connection %d for \"%s\" ...", idx, Conf_Server[i].host );
1453 /* Verbindungs-Struktur initialisieren */
1454 Init_Conn_Struct( idx );
1455 My_Connections[idx].sock = SERVER_WAIT;
1456 My_Connections[idx].our_server = i;
1458 /* Hostnamen in IP aufloesen (Default bzw. im Fehlerfall: versuchen, den
1459 * konfigurierten Text direkt als IP-Adresse zu verwenden ... */
1460 strcpy( Conf_Server[My_Connections[idx].our_server].ip, Conf_Server[i].host );
1461 strcpy( My_Connections[idx].host, Conf_Server[i].host );
1462 s = Resolve_Name( Conf_Server[i].host );
1465 /* Sub-Prozess wurde asyncron gestartet */
1466 My_Connections[idx].res_stat = s;
1469 } /* Check_Servers */
1473 New_Server( INT Server, CONN_ID Idx )
1475 /* Neue Server-Verbindung aufbauen */
1477 struct sockaddr_in new_addr;
1478 struct in_addr inaddr;
1482 assert( Server > NONE );
1483 assert( Idx > NONE );
1485 /* Wurde eine gueltige IP-Adresse gefunden? */
1486 if( ! Conf_Server[Server].ip[0] )
1488 /* Nein. Verbindung wieder freigeben: */
1489 Init_Conn_Struct( Idx );
1490 Log( LOG_ERR, "Can't connect to \"%s\" (connection %d): ip address unknown!", Conf_Server[Server].host, Idx );
1494 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 );
1496 #ifdef HAVE_INET_ATON
1497 if( inet_aton( Conf_Server[Server].ip, &inaddr ) == 0 )
1499 memset( &inaddr, 0, sizeof( inaddr ));
1500 inaddr.s_addr = inet_addr( Conf_Server[Server].ip );
1501 if( inaddr.s_addr == (unsigned)-1 )
1504 /* Konnte Adresse nicht konvertieren */
1505 Init_Conn_Struct( Idx );
1506 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 );
1510 memset( &new_addr, 0, sizeof( new_addr ));
1511 new_addr.sin_family = AF_INET;
1512 new_addr.sin_addr = inaddr;
1513 new_addr.sin_port = htons( Conf_Server[Server].port );
1515 new_sock = socket( PF_INET, SOCK_STREAM, 0 );
1518 Init_Conn_Struct( Idx );
1519 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
1523 if( ! Init_Socket( new_sock )) return;
1525 res = connect( new_sock, (struct sockaddr *)&new_addr, sizeof( new_addr ));
1526 if(( res != 0 ) && ( errno != EINPROGRESS ))
1528 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1530 Init_Conn_Struct( Idx );
1534 /* Client-Struktur initialisieren */
1535 c = Client_NewLocal( Idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWNSERVER, FALSE );
1539 Init_Conn_Struct( Idx );
1540 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1543 Client_SetIntroducer( c, c );
1544 Client_SetToken( c, TOKEN_OUTBOUND );
1546 /* Verbindung registrieren */
1547 My_Connections[Idx].sock = new_sock;
1548 My_Connections[Idx].addr = new_addr;
1549 strcpy( My_Connections[Idx].host, Conf_Server[Server].host );
1551 /* Neuen Socket registrieren */
1552 FD_SET( new_sock, &My_Sockets );
1553 FD_SET( new_sock, &My_Connects );
1554 if( new_sock > Conn_MaxFD ) Conn_MaxFD = new_sock;
1556 Log( LOG_DEBUG, "Registered new connection %d on socket %d.", Idx, My_Connections[Idx].sock );
1561 Init_Conn_Struct( LONG Idx )
1563 /* Connection-Struktur initialisieren */
1565 My_Connections[Idx].sock = NONE;
1566 My_Connections[Idx].res_stat = NULL;
1567 My_Connections[Idx].host[0] = '\0';
1568 My_Connections[Idx].rbuf[0] = '\0';
1569 My_Connections[Idx].rdatalen = 0;
1570 My_Connections[Idx].wbuf[0] = '\0';
1571 My_Connections[Idx].wdatalen = 0;
1572 My_Connections[Idx].our_server = NONE;
1573 My_Connections[Idx].lastdata = time( NULL );
1574 My_Connections[Idx].lastping = 0;
1575 My_Connections[Idx].lastprivmsg = time( NULL );
1576 My_Connections[Idx].delaytime = 0;
1577 My_Connections[Idx].bytes_in = 0;
1578 My_Connections[Idx].bytes_out = 0;
1579 My_Connections[Idx].flag = 0;
1580 My_Connections[Idx].options = 0;
1583 My_Connections[Idx].zip.rbuf[0] = '\0';
1584 My_Connections[Idx].zip.rdatalen = 0;
1585 My_Connections[Idx].zip.wbuf[0] = '\0';
1586 My_Connections[Idx].zip.wdatalen = 0;
1587 My_Connections[Idx].zip.bytes_in = 0;
1588 My_Connections[Idx].zip.bytes_out = 0;
1590 } /* Init_Conn_Struct */
1594 Init_Socket( INT Sock )
1596 /* Socket-Optionen setzen */
1600 #ifdef O_NONBLOCK /* A/UX kennt das nicht? */
1601 if( fcntl( Sock, F_SETFL, O_NONBLOCK ) != 0 )
1603 Log( LOG_CRIT, "Can't enable non-blocking mode: %s!", strerror( errno ));
1608 if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &on, (socklen_t)sizeof( on )) != 0)
1610 Log( LOG_ERR, "Can't set socket options: %s!", strerror( errno ));
1611 /* dieser Fehler kann ignoriert werden. */
1619 Read_Resolver_Result( INT r_fd )
1621 /* Ergebnis von Resolver Sub-Prozess aus Pipe lesen
1622 * und entsprechende Connection aktualisieren */
1624 CHAR result[HOST_LEN];
1628 FD_CLR( r_fd, &Resolver_FDs );
1630 /* Anfrage vom Parent lesen */
1631 len = read( r_fd, result, HOST_LEN - 1 );
1634 /* Fehler beim Lesen aus der Pipe */
1636 Log( LOG_CRIT, "Resolver: Can't read result: %s!", strerror( errno ));
1641 /* zugehoerige Connection suchen */
1642 for( i = 0; i < Pool_Size; i++ )
1644 if(( My_Connections[i].sock != NONE ) && ( My_Connections[i].res_stat ) && ( My_Connections[i].res_stat->pipe[0] == r_fd )) break;
1646 if( i >= Pool_Size )
1648 /* Opsa! Keine passende Connection gefunden!? Vermutlich
1649 * wurde sie schon wieder geschlossen. */
1651 Log( LOG_DEBUG, "Resolver: Got result for unknown connection!?" );
1655 Log( LOG_DEBUG, "Resolver: %s is \"%s\".", My_Connections[i].host, result );
1658 close( My_Connections[i].res_stat->pipe[0] );
1659 close( My_Connections[i].res_stat->pipe[1] );
1660 free( My_Connections[i].res_stat );
1661 My_Connections[i].res_stat = NULL;
1663 if( My_Connections[i].sock > NONE )
1665 /* Eingehende Verbindung: Hostnamen setzen */
1666 c = Client_GetFromConn( i );
1667 assert( c != NULL );
1668 strcpy( My_Connections[i].host, result );
1669 Client_SetHostname( c, result );
1672 Conn_WriteStr( i, "NOTICE AUTH :%sGot your hostname.", NOTICE_TXTPREFIX );
1677 /* Ausgehende Verbindung (=Server): IP setzen */
1678 assert( My_Connections[i].our_server > NONE );
1679 strcpy( Conf_Server[My_Connections[i].our_server].ip, result );
1682 /* Penalty-Zeit zurueck setzen */
1683 Conn_ResetPenalty( i );
1684 } /* Read_Resolver_Result */
1690 Zip_Buffer( CONN_ID Idx, CHAR *Data, INT Len )
1692 /* Daten zum Komprimieren im "Kompressions-Puffer" sammeln.
1693 * Es wird TRUE bei Erfolg, sonst FALSE geliefert. */
1695 assert( Idx > NONE );
1696 assert( Data != NULL );
1699 /* Ist noch Platz im Kompressions-Puffer? */
1700 if( ZWRITEBUFFER_LEN - My_Connections[Idx].zip.wdatalen < Len + 50 )
1702 /* Nein! Puffer zunaechst leeren ...*/
1703 if( ! Zip_Flush( Idx )) return FALSE;
1706 /* Daten kopieren */
1707 memmove( My_Connections[Idx].zip.wbuf + My_Connections[Idx].zip.wdatalen, Data, Len );
1708 My_Connections[Idx].zip.wdatalen += Len;
1715 Zip_Flush( CONN_ID Idx )
1717 /* Daten komprimieren und in Schreibpuffer kopieren.
1718 * Es wird TRUE bei Erfolg, sonst FALSE geliefert. */
1720 INT result, out_len;
1723 out = &My_Connections[Idx].zip.out;
1725 out->next_in = My_Connections[Idx].zip.wbuf;
1726 out->avail_in = My_Connections[Idx].zip.wdatalen;
1727 out->next_out = My_Connections[Idx].wbuf + My_Connections[Idx].wdatalen;
1728 out->avail_out = WRITEBUFFER_LEN - My_Connections[Idx].wdatalen;
1730 result = deflate( out, Z_SYNC_FLUSH );
1731 if(( result != Z_OK ) || ( out->avail_in > 0 ))
1733 Log( LOG_ALERT, "Compression error: code %d!?", result );
1734 Conn_Close( Idx, "Compression error!", NULL, FALSE );
1738 out_len = WRITEBUFFER_LEN - My_Connections[Idx].wdatalen - out->avail_out;
1739 My_Connections[Idx].wdatalen += out_len;
1740 My_Connections[Idx].bytes_out += out_len;
1741 My_Connections[Idx].zip.bytes_out += My_Connections[Idx].zip.wdatalen;
1742 My_Connections[Idx].zip.wdatalen = 0;
1749 Unzip_Buffer( CONN_ID Idx )
1751 /* Daten entpacken und in Lesepuffer kopieren. Bei Fehlern
1752 * wird FALSE geliefert, ansonsten TRUE. Der Fall, dass keine
1753 * Daten mehr zu entpacken sind, ist _kein_ Fehler! */
1755 INT result, in_len, out_len;
1758 assert( Idx > NONE );
1760 if( My_Connections[Idx].zip.rdatalen <= 0 ) return TRUE;
1762 in = &My_Connections[Idx].zip.in;
1764 in->next_in = My_Connections[Idx].zip.rbuf;
1765 in->avail_in = My_Connections[Idx].zip.rdatalen;
1766 in->next_out = My_Connections[Idx].rbuf + My_Connections[Idx].rdatalen;
1767 in->avail_out = READBUFFER_LEN - My_Connections[Idx].rdatalen - 1;
1769 result = inflate( in, Z_SYNC_FLUSH );
1770 if( result != Z_OK )
1772 Log( LOG_ALERT, "Decompression error: code %d (ni=%d, ai=%d, no=%d, ao=%d)!?", result, in->next_in, in->avail_in, in->next_out, in->avail_out );
1773 Conn_Close( Idx, "Decompression error!", NULL, FALSE );
1777 in_len = My_Connections[Idx].zip.rdatalen - in->avail_in;
1778 out_len = READBUFFER_LEN - My_Connections[Idx].rdatalen - 1 - in->avail_out;
1779 My_Connections[Idx].rdatalen += out_len;
1781 if( in->avail_in > 0 )
1783 /* es konnten nicht alle Daten entpackt werden, vermutlich war
1784 * im Ziel-Puffer kein Platz mehr. Umkopieren ... */
1785 My_Connections[Idx].zip.rdatalen -= in_len;
1786 memmove( My_Connections[Idx].zip.rbuf, My_Connections[Idx].zip.rbuf + in_len, My_Connections[Idx].zip.rdatalen );
1788 else My_Connections[Idx].zip.rdatalen = 0;
1789 My_Connections[Idx].zip.bytes_in += out_len;
1792 } /* Unzip_Buffer */