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.101 2002/12/02 13:19:37 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 starttime; /* Startzeit des Links */
93 time_t lastdata; /* Letzte Aktivitaet */
94 time_t lastping; /* Letzter PING */
95 time_t lastprivmsg; /* Letzte PRIVMSG */
96 time_t delaytime; /* Nicht beachten bis ("penalty") */
97 LONG bytes_in, bytes_out; /* Empfangene uns gesendete Bytes */
98 LONG msg_in, msg_out; /* Empfangene uns gesendete Nachtichten */
99 INT flag; /* "Markierungs-Flag" (vgl. "irc-write"-Modul) */
100 INT options; /* Link-Optionen */
102 ZIPDATA zip; /* Kompressionsinformationen */
107 LOCAL VOID Handle_Read PARAMS(( INT sock ));
108 LOCAL BOOLEAN Handle_Write PARAMS(( CONN_ID Idx ));
109 LOCAL VOID New_Connection PARAMS(( INT Sock ));
110 LOCAL CONN_ID Socket2Index PARAMS(( INT Sock ));
111 LOCAL VOID Read_Request PARAMS(( CONN_ID Idx ));
112 LOCAL BOOLEAN Try_Write PARAMS(( CONN_ID Idx ));
113 LOCAL BOOLEAN Handle_Buffer PARAMS(( CONN_ID Idx ));
114 LOCAL VOID Check_Connections PARAMS(( VOID ));
115 LOCAL VOID Check_Servers PARAMS(( VOID ));
116 LOCAL VOID Init_Conn_Struct PARAMS(( LONG Idx ));
117 LOCAL BOOLEAN Init_Socket PARAMS(( INT Sock ));
118 LOCAL VOID New_Server PARAMS(( INT Server, CONN_ID Idx ));
119 LOCAL VOID Read_Resolver_Result PARAMS(( INT r_fd ));
122 LOCAL BOOLEAN Zip_Buffer PARAMS(( CONN_ID Idx, CHAR *Data, INT Len ));
123 LOCAL BOOLEAN Zip_Flush PARAMS(( CONN_ID Idx ));
124 LOCAL BOOLEAN Unzip_Buffer PARAMS(( CONN_ID Idx ));
128 LOCAL fd_set My_Listeners;
129 LOCAL fd_set My_Sockets;
130 LOCAL fd_set My_Connects;
132 LOCAL CONNECTION *My_Connections;
133 LOCAL LONG Pool_Size;
139 /* Modul initialisieren: statische Strukturen "ausnullen". */
143 /* Speicher fuer Verbindungs-Pool anfordern */
144 Pool_Size = CONNECTION_POOL;
145 if( Conf_MaxConnections > 0 )
147 /* konfiguriertes Limit beachten */
148 if( Pool_Size > Conf_MaxConnections ) Pool_Size = Conf_MaxConnections;
150 My_Connections = malloc( sizeof( CONNECTION ) * Pool_Size );
151 if( ! My_Connections )
153 /* Speicher konnte nicht alloziert werden! */
154 Log( LOG_EMERG, "Can't allocate memory! [Conn_Init]" );
157 Log( LOG_DEBUG, "Allocted connection pool for %ld items.", Pool_Size );
159 /* zu Beginn haben wir keine Verbindungen */
160 FD_ZERO( &My_Listeners );
161 FD_ZERO( &My_Sockets );
162 FD_ZERO( &My_Connects );
164 /* Groesster File-Descriptor fuer select() */
167 /* Connection-Struktur initialisieren */
168 for( i = 0; i < Pool_Size; i++ ) Init_Conn_Struct( i );
175 /* Modul abmelden: alle noch offenen Connections
176 * schliessen und freigeben. */
181 /* Sockets schliessen */
182 Log( LOG_DEBUG, "Shutting down all connections ..." );
183 for( i = 0; i < Conn_MaxFD + 1; i++ )
185 if( FD_ISSET( i, &My_Sockets ))
187 for( idx = 0; idx < Pool_Size; idx++ )
189 if( My_Connections[idx].sock == i ) break;
191 if( FD_ISSET( i, &My_Listeners ))
194 Log( LOG_DEBUG, "Listening socket %d closed.", i );
196 else if( FD_ISSET( i, &My_Connects ))
199 Log( LOG_DEBUG, "Connection %d closed during creation (socket %d).", idx, i );
201 else if( idx < Pool_Size )
203 if( NGIRCd_Restart ) Conn_Close( idx, NULL, "Server going down (restarting)", TRUE );
204 else Conn_Close( idx, NULL, "Server going down", TRUE );
208 Log( LOG_WARNING, "Closing unknown connection %d ...", i );
214 free( My_Connections );
215 My_Connections = NULL;
221 Conn_InitListeners( VOID )
223 /* Ports, auf denen der Server Verbindungen entgegennehmen
224 * soll, initialisieren */
229 for( i = 0; i < Conf_ListenPorts_Count; i++ )
231 if( Conn_NewListener( Conf_ListenPorts[i] )) created++;
232 else Log( LOG_ERR, "Can't listen on port %u!", Conf_ListenPorts[i] );
235 } /* Conn_InitListeners */
239 Conn_ExitListeners( VOID )
241 /* Alle "Listen-Sockets" schliessen */
245 Log( LOG_INFO, "Shutting down all listening sockets ..." );
246 for( i = 0; i < Conn_MaxFD + 1; i++ )
248 if( FD_ISSET( i, &My_Sockets ) && FD_ISSET( i, &My_Listeners ))
251 Log( LOG_DEBUG, "Listening socket %d closed.", i );
254 } /* Conn_ExitListeners */
258 Conn_NewListener( CONST UINT Port )
260 /* Neuen Listen-Socket erzeugen: der Server wartet dann auf
261 * dem angegebenen Port auf Verbindungen. Kann der Listen-
262 * Socket nicht erteugt werden, so wird NULL geliefert.*/
264 struct sockaddr_in addr;
267 /* Server-"Listen"-Socket initialisieren */
268 memset( &addr, 0, sizeof( addr ));
269 addr.sin_family = AF_INET;
270 addr.sin_port = htons( Port );
271 addr.sin_addr.s_addr = htonl( INADDR_ANY );
273 /* Socket erzeugen */
274 sock = socket( PF_INET, SOCK_STREAM, 0);
277 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
281 if( ! Init_Socket( sock )) return FALSE;
284 if( bind( sock, (struct sockaddr *)&addr, (socklen_t)sizeof( addr )) != 0 )
286 Log( LOG_CRIT, "Can't bind socket: %s!", strerror( errno ));
291 /* in "listen mode" gehen :-) */
292 if( listen( sock, 10 ) != 0 )
294 Log( LOG_CRIT, "Can't listen on soecket: %s!", strerror( errno ));
299 /* Neuen Listener in Strukturen einfuegen */
300 FD_SET( sock, &My_Listeners );
301 FD_SET( sock, &My_Sockets );
303 if( sock > Conn_MaxFD ) Conn_MaxFD = sock;
305 Log( LOG_INFO, "Now listening on port %d (socket %d).", Port, sock );
308 } /* Conn_NewListener */
314 /* "Hauptschleife": Aktive Verbindungen ueberwachen. Folgende Aktionen
315 * werden dabei durchgefuehrt, bis der Server terminieren oder neu
318 * - neue Verbindungen annehmen,
319 * - Server-Verbindungen aufbauen,
320 * - geschlossene Verbindungen loeschen,
321 * - volle Schreibpuffer versuchen zu schreiben,
322 * - volle Lesepuffer versuchen zu verarbeiten,
323 * - Antworten von Resolver Sub-Prozessen annehmen.
326 fd_set read_sockets, write_sockets;
332 start = time( NULL );
333 while(( ! NGIRCd_Quit ) && ( ! NGIRCd_Restart ))
339 Check_Connections( );
341 /* noch volle Lese-Buffer suchen */
342 for( i = 0; i < Pool_Size; i++ )
344 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].rdatalen > 0 ))
346 /* Kann aus dem Buffer noch ein Befehl extrahiert werden? */
347 if( Handle_Buffer( i )) timeout = FALSE;
351 /* noch volle Schreib-Puffer suchen */
352 FD_ZERO( &write_sockets );
353 for( i = 0; i < Pool_Size; i++ )
356 if(( My_Connections[i].sock > NONE ) && (( My_Connections[i].wdatalen > 0 ) || ( My_Connections[i].zip.wdatalen > 0 )))
358 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].wdatalen > 0 ))
361 /* Socket der Verbindung in Set aufnehmen */
362 FD_SET( My_Connections[i].sock, &write_sockets );
365 /* Sockets mit im Aufbau befindlichen ausgehenden Verbindungen suchen */
366 for( i = 0; i < Pool_Size; i++ )
368 if(( My_Connections[i].sock > NONE ) && ( FD_ISSET( My_Connections[i].sock, &My_Connects ))) FD_SET( My_Connections[i].sock, &write_sockets );
371 /* von welchen Sockets koennte gelesen werden? */
373 read_sockets = My_Sockets;
374 for( i = 0; i < Pool_Size; i++ )
376 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].host[0] == '\0' ))
378 /* Hier muss noch auf den Resolver Sub-Prozess gewartet werden */
379 FD_CLR( My_Connections[i].sock, &read_sockets );
381 if(( My_Connections[i].sock > NONE ) && ( FD_ISSET( My_Connections[i].sock, &My_Connects )))
383 /* Hier laeuft noch ein asyncrones connect() */
384 FD_CLR( My_Connections[i].sock, &read_sockets );
386 if( My_Connections[i].delaytime > t )
388 /* Fuer die Verbindung ist eine "Penalty-Zeit" gesetzt */
389 FD_CLR( My_Connections[i].sock, &read_sockets );
390 FD_CLR( My_Connections[i].sock, &write_sockets );
393 for( i = 0; i < Conn_MaxFD + 1; i++ )
395 /* Pipes von Resolver Sub-Prozessen aufnehmen */
396 if( FD_ISSET( i, &Resolver_FDs ))
398 FD_SET( i, &read_sockets );
402 /* Timeout initialisieren */
404 if( timeout ) tv.tv_sec = TIME_RES;
407 /* Auf Aktivitaet warten */
408 i = select( Conn_MaxFD + 1, &read_sockets, &write_sockets, NULL, &tv );
411 /* keine Veraenderung an den Sockets */
416 /* Fehler (z.B. Interrupt) */
419 Log( LOG_EMERG, "Conn_Handler(): select(): %s!", strerror( errno ));
420 Log( LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE );
426 /* Koennen Daten geschrieben werden? */
427 for( i = 0; i < Conn_MaxFD + 1; i++ )
429 if( ! FD_ISSET( i, &write_sockets )) continue;
431 /* Es kann geschrieben werden ... */
432 idx = Socket2Index( i );
433 if( idx == NONE ) continue;
435 if( ! Handle_Write( idx ))
437 /* Fehler beim Schreiben! Diesen Socket nun
438 * auch aus dem Read-Set entfernen: */
439 FD_CLR( i, &read_sockets );
443 /* Daten zum Lesen vorhanden? */
444 for( i = 0; i < Conn_MaxFD + 1; i++ )
446 if( FD_ISSET( i, &read_sockets )) Handle_Read( i );
454 Conn_WriteStr( CONN_ID Idx, CHAR *Format, ... )
457 Conn_WriteStr( Idx, Format, va_alist )
463 /* String in Socket schreiben. CR+LF wird von dieser Funktion
464 * automatisch angehaengt. Im Fehlerfall wird dir Verbindung
465 * getrennt und FALSE geliefert. */
467 CHAR buffer[COMMAND_LEN];
471 assert( Idx > NONE );
472 assert( Format != NULL );
475 va_start( ap, Format );
479 if( vsnprintf( buffer, COMMAND_LEN - 2, Format, ap ) == COMMAND_LEN - 2 )
481 Log( LOG_CRIT, "Text too long to send (connection %d)!", Idx );
482 Conn_Close( Idx, "Text too long to send!", NULL, FALSE );
487 if( NGIRCd_Sniffer ) Log( LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer );
490 strcat( buffer, "\r\n" );
491 ok = Conn_Write( Idx, buffer, strlen( buffer ));
492 My_Connections[Idx].msg_out++;
496 } /* Conn_WriteStr */
500 Conn_Write( CONN_ID Idx, CHAR *Data, INT Len )
502 /* Daten in Socket schreiben. Bei "fatalen" Fehlern wird
503 * der Client disconnectiert und FALSE geliefert. */
505 assert( Idx > NONE );
506 assert( Data != NULL );
509 /* Ist der entsprechende Socket ueberhaupt noch offen? In einem
510 * "Handler-Durchlauf" kann es passieren, dass dem nicht mehr so
511 * ist, wenn einer von mehreren Conn_Write()'s fehlgeschlagen ist.
512 * In diesem Fall wird hier einfach ein Fehler geliefert. */
513 if( My_Connections[Idx].sock <= NONE )
515 Log( LOG_DEBUG, "Skipped write on closed socket (connection %d).", Idx );
519 /* Pruefen, ob im Schreibpuffer genuegend Platz ist. Ziel ist es,
520 * moeglichts viel im Puffer zu haben und _nicht_ gleich alles auf den
521 * Socket zu schreiben (u.a. wg. Komprimierung). */
522 if( WRITEBUFFER_LEN - My_Connections[Idx].wdatalen - Len <= 0 )
524 /* Der Puffer ist dummerweise voll. Jetzt versuchen, den Puffer
525 * zu schreiben, wenn das nicht klappt, haben wir ein Problem ... */
526 if( ! Try_Write( Idx )) return FALSE;
528 /* nun neu pruefen: */
529 if( WRITEBUFFER_LEN - My_Connections[Idx].wdatalen - Len <= 0 )
531 Log( LOG_NOTICE, "Write buffer overflow (connection %d)!", Idx );
532 Conn_Close( Idx, "Write buffer overflow!", NULL, FALSE );
538 if( My_Connections[Idx].options & CONN_ZIP )
540 /* Daten komprimieren und in Puffer kopieren */
541 if( ! Zip_Buffer( Idx, Data, Len )) return FALSE;
546 /* Daten in Puffer kopieren */
547 memcpy( My_Connections[Idx].wbuf + My_Connections[Idx].wdatalen, Data, Len );
548 My_Connections[Idx].wdatalen += Len;
549 My_Connections[Idx].bytes_out += Len;
557 Conn_Close( CONN_ID Idx, CHAR *LogMsg, CHAR *FwdMsg, BOOLEAN InformClient )
559 /* Verbindung schliessen. Evtl. noch von Resolver
560 * Sub-Prozessen offene Pipes werden geschlossen. */
565 DOUBLE in_z_k, out_z_k;
569 assert( Idx > NONE );
570 assert( My_Connections[Idx].sock > NONE );
572 c = Client_GetFromConn( Idx );
577 /* Statistik an Client melden, wenn User */
578 if(( c != NULL ) && ( Client_Type( c ) == CLIENT_USER ))
580 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 );
584 /* ERROR an Client schicken (von RFC so vorgesehen!) */
585 if( FwdMsg ) Conn_WriteStr( Idx, "ERROR :%s", FwdMsg );
586 else Conn_WriteStr( Idx, "ERROR :Closing connection." );
587 if( My_Connections[Idx].sock == NONE ) return;
590 /* zunaechst versuchen, noch im Schreibpuffer vorhandene
591 * Daten auf den Socket zu schreiben ... */
594 if( close( My_Connections[Idx].sock ) != 0 )
596 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 ));
600 in_k = (DOUBLE)My_Connections[Idx].bytes_in / 1024;
601 out_k = (DOUBLE)My_Connections[Idx].bytes_out / 1024;
603 if( My_Connections[Idx].options & CONN_ZIP )
605 in_z_k = (DOUBLE)My_Connections[Idx].zip.bytes_in / 1024;
606 out_z_k = (DOUBLE)My_Connections[Idx].zip.bytes_out / 1024;
607 in_p = (INT)(( in_k * 100 ) / in_z_k );
608 out_p = (INT)(( out_k * 100 ) / out_z_k );
609 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 );
614 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 );
618 /* Socket als "ungueltig" markieren */
619 FD_CLR( My_Connections[Idx].sock, &My_Sockets );
620 FD_CLR( My_Connections[Idx].sock, &My_Connects );
621 My_Connections[Idx].sock = NONE;
623 if( c ) Client_Destroy( c, LogMsg, FwdMsg, TRUE );
625 if( My_Connections[Idx].res_stat )
627 /* Resolver-Strukturen freigeben, wenn noch nicht geschehen */
628 FD_CLR( My_Connections[Idx].res_stat->pipe[0], &Resolver_FDs );
629 close( My_Connections[Idx].res_stat->pipe[0] );
630 close( My_Connections[Idx].res_stat->pipe[1] );
631 free( My_Connections[Idx].res_stat );
634 /* Startzeit des naechsten Connect-Versuchs modifizieren? */
635 if(( My_Connections[Idx].our_server > NONE ) && ( Conf_Server[My_Connections[Idx].our_server].lasttry < time( NULL ) - Conf_ConnectRetry ))
637 /* Okay, die Verbindung stand schon "genuegend lange":
638 * lasttry-Zeitpunkt so setzen, dass der naechste
639 * Verbindungsversuch in RECONNECT_DELAY Sekunden
641 Conf_Server[My_Connections[Idx].our_server].lasttry = time( NULL ) - Conf_ConnectRetry + RECONNECT_DELAY;
645 /* Ggf. zlib abmelden */
646 if( Conn_Options( Idx ) & CONN_ZIP )
648 inflateEnd( &My_Connections[Idx].zip.in );
649 deflateEnd( &My_Connections[Idx].zip.out );
653 /* Connection-Struktur loeschen (=freigeben) */
654 Init_Conn_Struct( Idx );
659 Conn_UpdateIdle( CONN_ID Idx )
661 /* Idle-Timer zuruecksetzen */
663 assert( Idx > NONE );
664 My_Connections[Idx].lastprivmsg = time( NULL );
669 Conn_GetIdle( CONN_ID Idx )
671 /* Idle-Time einer Verbindung liefern (in Sekunden) */
673 assert( Idx > NONE );
674 return time( NULL ) - My_Connections[Idx].lastprivmsg;
679 Conn_LastPing( CONN_ID Idx )
681 /* Zeitpunkt des letzten PING liefern */
683 assert( Idx > NONE );
684 return My_Connections[Idx].lastping;
685 } /* Conn_LastPing */
689 Conn_SetPenalty( CONN_ID Idx, time_t Seconds )
691 /* Penalty-Delay fuer eine Verbindung (in Sekunden) setzen;
692 * waehrend dieser Zeit wird der entsprechende Socket vom Server
693 * bei Lese-Operationen komplett ignoriert. Der Delay kann mit
694 * dieser Funktion nur erhoeht, nicht aber verringert werden. */
698 assert( Idx > NONE );
699 assert( Seconds >= 0 );
701 t = time( NULL ) + Seconds;
702 if( t > My_Connections[Idx].delaytime ) My_Connections[Idx].delaytime = t;
703 } /* Conn_SetPenalty */
707 Conn_ResetPenalty( CONN_ID Idx )
709 assert( Idx > NONE );
710 My_Connections[Idx].delaytime = 0;
711 } /* Conn_ResetPenalty */
715 Conn_ClearFlags( VOID )
717 /* Alle Connection auf "nicht-markiert" setzen */
721 for( i = 0; i < Pool_Size; i++ ) My_Connections[i].flag = 0;
722 } /* Conn_ClearFlags */
726 Conn_Flag( CONN_ID Idx )
728 /* Ist eine Connection markiert (TRUE) oder nicht? */
730 assert( Idx > NONE );
731 return My_Connections[Idx].flag;
736 Conn_SetFlag( CONN_ID Idx, INT Flag )
738 /* Connection markieren */
740 assert( Idx > NONE );
741 My_Connections[Idx].flag = Flag;
748 /* Connection-Struktur der ersten Verbindung liefern;
749 * Ist keine Verbindung vorhanden, wird NONE geliefert. */
753 for( i = 0; i < Pool_Size; i++ )
755 if( My_Connections[i].sock != NONE ) return i;
762 Conn_Next( CONN_ID Idx )
764 /* Naechste Verbindungs-Struktur liefern; existiert keine
765 * weitere, so wird NONE geliefert. */
769 assert( Idx > NONE );
771 for( i = Idx + 1; i < Pool_Size; i++ )
773 if( My_Connections[i].sock != NONE ) return i;
780 Conn_SetServer( CONN_ID Idx, INT ConfServer )
782 /* Connection als Server markieren: Index des konfigurierten
783 * Servers speichern. Verbindung muss bereits bestehen! */
785 assert( Idx > NONE );
786 assert( My_Connections[Idx].sock > NONE );
788 My_Connections[Idx].our_server = ConfServer;
789 } /* Conn_SetServer */
793 Conn_SetOption( CONN_ID Idx, INT Option )
795 /* Option fuer Verbindung setzen.
796 * Initial sind alle Optionen _nicht_ gesetzt. */
798 assert( Idx > NONE );
799 assert( Option != 0 );
801 My_Connections[Idx].options |= Option;
802 } /* Conn_SetOption */
806 Conn_UnsetOption( CONN_ID Idx, INT Option )
808 /* Option fuer Verbindung loeschen */
810 assert( Idx > NONE );
811 assert( Option != 0 );
813 My_Connections[Idx].options &= ~Option;
814 } /* Conn_UnsetOption */
818 Conn_Options( CONN_ID Idx )
820 assert( Idx > NONE );
821 return My_Connections[Idx].options;
828 Conn_InitZip( CONN_ID Idx )
830 /* Kompression fuer Link initialisieren */
832 assert( Idx > NONE );
834 My_Connections[Idx].zip.in.avail_in = 0;
835 My_Connections[Idx].zip.in.total_in = 0;
836 My_Connections[Idx].zip.in.total_out = 0;
837 My_Connections[Idx].zip.in.zalloc = NULL;
838 My_Connections[Idx].zip.in.zfree = NULL;
839 My_Connections[Idx].zip.in.data_type = Z_ASCII;
841 if( inflateInit( &My_Connections[Idx].zip.in ) != Z_OK )
844 Log( LOG_ALERT, "Can't initialize compression on connection %d (zlib inflate)!", Idx );
848 My_Connections[Idx].zip.out.total_in = 0;
849 My_Connections[Idx].zip.out.total_in = 0;
850 My_Connections[Idx].zip.out.zalloc = NULL;
851 My_Connections[Idx].zip.out.zfree = NULL;
852 My_Connections[Idx].zip.out.data_type = Z_ASCII;
854 if( deflateInit( &My_Connections[Idx].zip.out, Z_DEFAULT_COMPRESSION ) != Z_OK )
857 Log( LOG_ALERT, "Can't initialize compression on connection %d (zlib deflate)!", Idx );
861 My_Connections[Idx].zip.bytes_in = My_Connections[Idx].bytes_in;
862 My_Connections[Idx].zip.bytes_out = My_Connections[Idx].bytes_out;
864 Log( LOG_INFO, "Enabled link compression (zlib) on connection %d.", Idx );
865 Conn_SetOption( Idx, CONN_ZIP );
872 Conn_SendBytesZip( CONN_ID Idx )
874 /* Anzahl gesendeter Bytes (komprimiert!) liefern */
876 assert( Idx > NONE );
877 return My_Connections[Idx].zip.bytes_out;
878 } /* Conn_SendBytesZip */
882 Conn_RecvBytesZip( CONN_ID Idx )
884 /* Anzahl gesendeter Bytes (komprimiert!) liefern */
886 assert( Idx > NONE );
887 return My_Connections[Idx].zip.bytes_in;
888 } /* Conn_RecvBytesZip */
894 Conn_StartTime( CONN_ID Idx )
896 /* Zeitpunkt des Link-Starts liefern (in Sekunden) */
898 assert( Idx > NONE );
899 return My_Connections[Idx].starttime;
904 Conn_SendQ( CONN_ID Idx )
906 /* Laenge der Daten im Schreibbuffer liefern */
908 assert( Idx > NONE );
910 return My_Connections[Idx].zip.wdatalen;
912 return My_Connections[Idx].wdatalen;
918 Conn_SendMsg( CONN_ID Idx )
920 /* Anzahl gesendeter Nachrichten liefern */
922 assert( Idx > NONE );
923 return My_Connections[Idx].msg_out;
928 Conn_SendBytes( CONN_ID Idx )
930 /* Anzahl gesendeter Bytes (unkomprimiert) liefern */
932 assert( Idx > NONE );
933 return My_Connections[Idx].bytes_out;
934 } /* Conn_SendBytes */
938 Conn_RecvQ( CONN_ID Idx )
940 /* Laenge der Daten im Lesebuffer liefern */
942 assert( Idx > NONE );
944 return My_Connections[Idx].zip.rdatalen;
946 return My_Connections[Idx].rdatalen;
952 Conn_RecvMsg( CONN_ID Idx )
954 /* Anzahl empfangener Nachrichten liefern */
956 assert( Idx > NONE );
957 return My_Connections[Idx].msg_in;
962 Conn_RecvBytes( CONN_ID Idx )
964 /* Anzahl empfangener Bytes (unkomprimiert) liefern */
966 assert( Idx > NONE );
967 return My_Connections[Idx].bytes_in;
968 } /* Conn_RecvBytes */
972 Try_Write( CONN_ID Idx )
974 /* Versuchen, Daten aus dem Schreib-Puffer in den Socket zu
975 * schreiben. TRUE wird geliefert, wenn entweder keine Daten
976 * zum Versenden vorhanden sind oder erfolgreich bearbeitet
977 * werden konnten. Im Fehlerfall wird FALSE geliefert und
978 * die Verbindung geschlossen. */
983 assert( Idx > NONE );
984 assert( My_Connections[Idx].sock > NONE );
986 /* sind ueberhaupt Daten vorhanden? */
988 if(( ! My_Connections[Idx].wdatalen > 0 ) && ( ! My_Connections[Idx].zip.wdatalen )) return TRUE;
990 if( ! My_Connections[Idx].wdatalen > 0 ) return TRUE;
993 /* Timeout initialisieren: 0 Sekunden, also nicht blockieren */
994 tv.tv_sec = 0; tv.tv_usec = 0;
996 FD_ZERO( &write_socket );
997 FD_SET( My_Connections[Idx].sock, &write_socket );
998 if( select( My_Connections[Idx].sock + 1, NULL, &write_socket, NULL, &tv ) == -1 )
1001 if( errno != EINTR )
1003 Log( LOG_ALERT, "Try_Write(): select() failed: %s (con=%d, sock=%d)!", strerror( errno ), Idx, My_Connections[Idx].sock );
1004 Conn_Close( Idx, "Server error!", NULL, FALSE );
1009 if( FD_ISSET( My_Connections[Idx].sock, &write_socket )) return Handle_Write( Idx );
1015 Handle_Read( INT Sock )
1017 /* Aktivitaet auf einem Socket verarbeiten:
1018 * - neue Clients annehmen,
1019 * - Daten von Clients verarbeiten,
1020 * - Resolver-Rueckmeldungen annehmen. */
1024 assert( Sock > NONE );
1026 if( FD_ISSET( Sock, &My_Listeners ))
1028 /* es ist einer unserer Listener-Sockets: es soll
1029 * also eine neue Verbindung aufgebaut werden. */
1031 New_Connection( Sock );
1033 else if( FD_ISSET( Sock, &Resolver_FDs ))
1035 /* Rueckmeldung von einem Resolver Sub-Prozess */
1037 Read_Resolver_Result( Sock );
1041 /* Ein Client Socket: entweder ein User oder Server */
1043 idx = Socket2Index( Sock );
1044 if( idx > NONE ) Read_Request( idx );
1050 Handle_Write( CONN_ID Idx )
1052 /* Daten aus Schreibpuffer versenden bzw. Connection aufbauen */
1056 assert( Idx > NONE );
1057 assert( My_Connections[Idx].sock > NONE );
1059 if( FD_ISSET( My_Connections[Idx].sock, &My_Connects ))
1061 /* es soll nichts geschrieben werden, sondern ein
1062 * connect() hat ein Ergebnis geliefert */
1064 FD_CLR( My_Connections[Idx].sock, &My_Connects );
1066 /* Ergebnis des connect() ermitteln */
1067 len = sizeof( err );
1068 res = getsockopt( My_Connections[Idx].sock, SOL_SOCKET, SO_ERROR, &err, &len );
1069 assert( len == sizeof( err ));
1071 /* Fehler aufgetreten? */
1072 if(( res != 0 ) || ( err != 0 ))
1075 if( res != 0 ) Log( LOG_CRIT, "getsockopt (connection %d): %s!", Idx, strerror( errno ));
1076 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 ));
1078 /* Socket etc. pp. aufraeumen */
1079 FD_CLR( My_Connections[Idx].sock, &My_Sockets );
1080 close( My_Connections[Idx].sock );
1081 Init_Conn_Struct( Idx );
1083 /* Bei Server-Verbindungen lasttry-Zeitpunkt auf "jetzt" setzen */
1084 Conf_Server[My_Connections[Idx].our_server].lasttry = time( NULL );
1088 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 );
1090 /* PASS und SERVER verschicken */
1091 Conn_WriteStr( Idx, "PASS %s %s", Conf_Server[My_Connections[Idx].our_server].pwd_out, NGIRCd_ProtoID );
1092 return Conn_WriteStr( Idx, "SERVER %s :%s", Conf_ServerName, Conf_ServerInfo );
1096 /* Schreibpuffer leer, aber noch Daten im Kompressionsbuffer?
1097 * Dann muss dieser nun geflushed werden! */
1098 if( My_Connections[Idx].wdatalen == 0 ) Zip_Flush( Idx );
1101 assert( My_Connections[Idx].wdatalen > 0 );
1103 /* Daten schreiben */
1104 len = send( My_Connections[Idx].sock, My_Connections[Idx].wbuf, My_Connections[Idx].wdatalen, 0 );
1107 /* Operation haette Socket "nur" blockiert ... */
1108 if( errno == EAGAIN ) return TRUE;
1110 /* Oops, ein Fehler! */
1111 Log( LOG_ERR, "Write error on connection %d (socket %d): %s!", Idx, My_Connections[Idx].sock, strerror( errno ));
1112 Conn_Close( Idx, "Write error!", NULL, FALSE );
1116 /* Puffer anpassen */
1117 My_Connections[Idx].wdatalen -= len;
1118 memmove( My_Connections[Idx].wbuf, My_Connections[Idx].wbuf + len, My_Connections[Idx].wdatalen );
1121 } /* Handle_Write */
1125 New_Connection( INT Sock )
1127 /* Neue Client-Verbindung von Listen-Socket annehmen und
1128 * CLIENT-Struktur anlegen. */
1130 struct sockaddr_in new_addr;
1131 INT new_sock, new_sock_len;
1138 assert( Sock > NONE );
1140 /* Connection auf Listen-Socket annehmen */
1141 new_sock_len = sizeof( new_addr );
1142 new_sock = accept( Sock, (struct sockaddr *)&new_addr, (socklen_t *)&new_sock_len );
1145 Log( LOG_CRIT, "Can't accept connection: %s!", strerror( errno ));
1149 /* Socket initialisieren */
1150 Init_Socket( new_sock );
1152 /* Freie Connection-Struktur suchen */
1153 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
1154 if( idx >= Pool_Size )
1156 new_size = Pool_Size + CONNECTION_POOL;
1158 /* Im bisherigen Pool wurde keine freie Connection-Struktur mehr gefunden.
1159 * Wenn erlaubt und moeglich muss nun der Pool vergroessert werden: */
1161 if( Conf_MaxConnections > 0 )
1163 /* Es ist ein Limit konfiguriert */
1164 if( Pool_Size >= Conf_MaxConnections )
1166 /* Mehr Verbindungen duerfen wir leider nicht mehr annehmen ... */
1167 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached!", Pool_Size );
1171 if( new_size > Conf_MaxConnections ) new_size = Conf_MaxConnections;
1174 /* zunaechst realloc() versuchen; wenn das scheitert, malloc() versuchen
1175 * und Daten ggf. "haendisch" umkopieren. (Haesslich! Eine wirklich
1176 * dynamische Verwaltung waere wohl _deutlich_ besser ...) */
1177 ptr = realloc( My_Connections, sizeof( CONNECTION ) * new_size );
1180 /* realloc() ist fehlgeschlagen. Nun malloc() probieren: */
1181 ptr = malloc( sizeof( CONNECTION ) * new_size );
1184 /* Offenbar steht kein weiterer Sepeicher zur Verfuegung :-( */
1185 Log( LOG_EMERG, "Can't allocate memory! [New_Connection]" );
1190 /* Struktur umkopieren ... */
1191 memcpy( ptr, My_Connections, sizeof( CONNECTION ) * Pool_Size );
1193 Log( LOG_DEBUG, "Allocated new connection pool for %ld items. [malloc()/memcpy()]", new_size );
1195 else Log( LOG_DEBUG, "Allocated new connection pool for %ld items. [realloc()]", new_size );
1197 My_Connections = ptr;
1198 Pool_Size = new_size;
1201 /* Client-Struktur initialisieren */
1202 c = Client_NewLocal( idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWN, FALSE );
1205 Log( LOG_ALERT, "Can't accept connection: can't create client structure!" );
1210 /* Verbindung registrieren */
1211 Init_Conn_Struct( idx );
1212 My_Connections[idx].sock = new_sock;
1213 My_Connections[idx].addr = new_addr;
1215 /* Neuen Socket registrieren */
1216 FD_SET( new_sock, &My_Sockets );
1217 if( new_sock > Conn_MaxFD ) Conn_MaxFD = new_sock;
1219 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 );
1221 /* Hostnamen ermitteln */
1222 strcpy( My_Connections[idx].host, inet_ntoa( new_addr.sin_addr ));
1223 Client_SetHostname( c, My_Connections[idx].host );
1224 s = Resolve_Addr( &new_addr );
1227 /* Sub-Prozess wurde asyncron gestartet */
1228 My_Connections[idx].res_stat = s;
1231 /* Penalty-Zeit setzen */
1232 Conn_SetPenalty( idx, 4 );
1233 } /* New_Connection */
1237 Socket2Index( INT Sock )
1239 /* zum Socket passende Connection suchen */
1243 assert( Sock > NONE );
1245 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == Sock ) break;
1247 if( idx >= Pool_Size )
1249 /* die Connection wurde vermutlich (wegen eines
1250 * Fehlers) bereits wieder abgebaut ... */
1251 Log( LOG_DEBUG, "Socket2Index: can't get connection for socket %d!", Sock );
1255 } /* Socket2Index */
1259 Read_Request( CONN_ID Idx )
1261 /* Daten von Socket einlesen und entsprechend behandeln.
1262 * Tritt ein Fehler auf, so wird der Socket geschlossen. */
1269 assert( Idx > NONE );
1270 assert( My_Connections[Idx].sock > NONE );
1272 /* wenn noch nicht registriert: maximal mit ZREADBUFFER_LEN arbeiten,
1273 * ansonsten koennen Daten ggf. nicht umkopiert werden. */
1274 bsize = READBUFFER_LEN;
1276 c = Client_GetFromConn( Idx );
1277 if(( Client_Type( c ) != CLIENT_USER ) && ( Client_Type( c ) != CLIENT_SERVER ) && ( Client_Type( c ) != CLIENT_SERVICE ) && ( bsize > ZREADBUFFER_LEN )) bsize = ZREADBUFFER_LEN;
1281 if(( bsize - My_Connections[Idx].rdatalen - 1 < 1 ) || ( ZREADBUFFER_LEN - My_Connections[Idx].zip.rdatalen < 1 ))
1283 if( bsize - My_Connections[Idx].rdatalen - 1 < 1 )
1286 /* Der Lesepuffer ist voll */
1287 Log( LOG_ERR, "Read buffer overflow (connection %d): %d bytes!", Idx, My_Connections[Idx].rdatalen );
1288 Conn_Close( Idx, "Read buffer overflow!", NULL, FALSE );
1293 if( My_Connections[Idx].options & CONN_ZIP )
1295 len = recv( My_Connections[Idx].sock, My_Connections[Idx].zip.rbuf + My_Connections[Idx].zip.rdatalen, ( ZREADBUFFER_LEN - My_Connections[Idx].zip.rdatalen ), 0 );
1296 if( len > 0 ) My_Connections[Idx].zip.rdatalen += len;
1301 len = recv( My_Connections[Idx].sock, My_Connections[Idx].rbuf + My_Connections[Idx].rdatalen, bsize - My_Connections[Idx].rdatalen - 1, 0 );
1302 if( len > 0 ) My_Connections[Idx].rdatalen += len;
1307 /* Socket wurde geschlossen */
1308 Log( LOG_INFO, "%s:%d is closing the connection ...", inet_ntoa( My_Connections[Idx].addr.sin_addr ), ntohs( My_Connections[Idx].addr.sin_port));
1309 Conn_Close( Idx, "Socket closed!", "Client closed connection", FALSE );
1315 /* Operation haette Socket "nur" blockiert ... */
1316 if( errno == EAGAIN ) return;
1318 /* Fehler beim Lesen */
1319 Log( LOG_ERR, "Read error on connection %d (socket %d): %s!", Idx, My_Connections[Idx].sock, strerror( errno ));
1320 Conn_Close( Idx, "Read error!", "Client closed connection", FALSE );
1324 /* Connection-Statistik aktualisieren */
1325 My_Connections[Idx].bytes_in += len;
1327 /* Timestamp aktualisieren */
1328 My_Connections[Idx].lastdata = time( NULL );
1330 Handle_Buffer( Idx );
1331 } /* Read_Request */
1335 Handle_Buffer( CONN_ID Idx )
1337 /* Daten im Lese-Puffer einer Verbindung verarbeiten.
1338 * Wurde ein Request verarbeitet, so wird TRUE geliefert,
1339 * ansonsten FALSE (auch bei Fehlern). */
1346 BOOLEAN action, result;
1355 /* ggf. noch unkomprimiete Daten weiter entpacken */
1356 if( My_Connections[Idx].options & CONN_ZIP )
1358 if( ! Unzip_Buffer( Idx )) return FALSE;
1362 if( My_Connections[Idx].rdatalen < 1 ) break;
1364 /* Eine komplette Anfrage muss mit CR+LF enden, vgl.
1365 * RFC 2812. Haben wir eine? */
1366 My_Connections[Idx].rbuf[My_Connections[Idx].rdatalen] = '\0';
1367 ptr = strstr( My_Connections[Idx].rbuf, "\r\n" );
1369 if( ptr ) delta = 2;
1373 /* Nicht RFC-konforme Anfrage mit nur CR oder LF? Leider
1374 * machen soetwas viele Clients, u.a. "mIRC" :-( */
1375 ptr1 = strchr( My_Connections[Idx].rbuf, '\r' );
1376 ptr2 = strchr( My_Connections[Idx].rbuf, '\n' );
1378 if( ptr1 && ptr2 ) ptr = ptr1 > ptr2 ? ptr2 : ptr1;
1379 else if( ptr1 ) ptr = ptr1;
1380 else if( ptr2 ) ptr = ptr2;
1387 /* Ende der Anfrage wurde gefunden */
1389 len = ( ptr - My_Connections[Idx].rbuf ) + delta;
1390 if( len > ( COMMAND_LEN - 1 ))
1392 /* Eine Anfrage darf(!) nicht laenger als 512 Zeichen
1393 * (incl. CR+LF!) werden; vgl. RFC 2812. Wenn soetwas
1394 * empfangen wird, wird der Client disconnectiert. */
1395 Log( LOG_ERR, "Request too long (connection %d): %d bytes (max. %d expected)!", Idx, My_Connections[Idx].rdatalen, COMMAND_LEN - 1 );
1396 Conn_Close( Idx, NULL, "Request too long", TRUE );
1401 /* merken, ob Stream bereits komprimiert wird */
1402 old_z = My_Connections[Idx].options & CONN_ZIP;
1407 /* Es wurde ein Request gelesen */
1408 My_Connections[Idx].msg_in++;
1409 if( ! Parse_Request( Idx, My_Connections[Idx].rbuf )) return FALSE;
1413 /* Puffer anpassen */
1414 My_Connections[Idx].rdatalen -= len;
1415 memmove( My_Connections[Idx].rbuf, My_Connections[Idx].rbuf + len, My_Connections[Idx].rdatalen );
1418 if(( ! old_z ) && ( My_Connections[Idx].options & CONN_ZIP ) && ( My_Connections[Idx].rdatalen > 0 ))
1420 /* Mit dem letzten Befehl wurde Socket-Kompression aktiviert.
1421 * Evtl. schon vom Socket gelesene Daten in den Unzip-Puffer
1422 * umkopieren, damit diese nun zunaechst entkomprimiert werden */
1424 if( My_Connections[Idx].rdatalen > ZREADBUFFER_LEN )
1426 /* Hupsa! Soviel Platz haben wir aber gar nicht! */
1427 Log( LOG_ALERT, "Can't move read buffer: No space left in unzip buffer (need %d bytes)!", My_Connections[Idx].rdatalen );
1430 memcpy( My_Connections[Idx].zip.rbuf, My_Connections[Idx].rbuf, My_Connections[Idx].rdatalen );
1431 My_Connections[Idx].zip.rdatalen = My_Connections[Idx].rdatalen;
1432 My_Connections[Idx].rdatalen = 0;
1433 Log( LOG_DEBUG, "Moved already received data (%d bytes) to uncompression buffer.", My_Connections[Idx].zip.rdatalen );
1439 if( action ) result = TRUE;
1443 } /* Handle_Buffer */
1447 Check_Connections( VOID )
1449 /* Pruefen, ob Verbindungen noch "alive" sind. Ist dies
1450 * nicht der Fall, zunaechst PING-PONG spielen und, wenn
1451 * auch das nicht "hilft", Client disconnectieren. */
1456 for( i = 0; i < Pool_Size; i++ )
1458 if( My_Connections[i].sock == NONE ) continue;
1460 c = Client_GetFromConn( i );
1461 if( c && (( Client_Type( c ) == CLIENT_USER ) || ( Client_Type( c ) == CLIENT_SERVER ) || ( Client_Type( c ) == CLIENT_SERVICE )))
1463 /* verbundener User, Server oder Service */
1464 if( My_Connections[i].lastping > My_Connections[i].lastdata )
1466 /* es wurde bereits ein PING gesendet */
1467 if( My_Connections[i].lastping < time( NULL ) - Conf_PongTimeout )
1470 Log( LOG_DEBUG, "Connection %d: Ping timeout: %d seconds.", i, Conf_PongTimeout );
1471 Conn_Close( i, NULL, "Ping timeout", TRUE );
1474 else if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout )
1476 /* es muss ein PING gesendet werden */
1477 Log( LOG_DEBUG, "Connection %d: sending PING ...", i );
1478 My_Connections[i].lastping = time( NULL );
1479 Conn_WriteStr( i, "PING :%s", Client_ID( Client_ThisServer( )));
1484 /* noch nicht vollstaendig aufgebaute Verbindung */
1485 if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout )
1488 Log( LOG_DEBUG, "Connection %d timed out ...", i );
1489 Conn_Close( i, NULL, "Timeout", FALSE );
1493 } /* Check_Connections */
1497 Check_Servers( VOID )
1499 /* Pruefen, ob Server-Verbindungen aufgebaut werden
1500 * muessen bzw. koennen */
1506 /* Wenn "Passive-Mode" aktiv: nicht verbinden */
1507 if( NGIRCd_Passive ) return;
1509 for( i = 0; i < Conf_Server_Count; i++ )
1511 /* Ist ein Hostname und Port definiert? */
1512 if(( ! Conf_Server[i].host[0] ) || ( ! Conf_Server[i].port > 0 )) continue;
1514 /* Haben wir schon eine Verbindung? */
1515 for( n = 0; n < Pool_Size; n++ )
1517 if( My_Connections[n].sock == NONE ) continue;
1519 /* Verbindung zu diesem Server? */
1520 if( My_Connections[n].our_server == i )
1522 /* Komplett aufgebaute Verbindung? */
1523 if( My_Connections[n].sock > NONE ) break;
1525 /* IP schon aufgeloest? */
1526 if( My_Connections[n].res_stat == NULL ) New_Server( i, n );
1529 /* Verbindung in dieser Server-Gruppe? */
1530 if(( My_Connections[n].our_server != NONE ) && ( Conf_Server[i].group != NONE ))
1532 if( Conf_Server[My_Connections[n].our_server].group == Conf_Server[i].group ) break;
1535 if( n < Pool_Size ) continue;
1537 /* Wann war der letzte Connect-Versuch? */
1538 if( Conf_Server[i].lasttry > time( NULL ) - Conf_ConnectRetry ) continue;
1540 /* Okay, Verbindungsaufbau versuchen */
1541 Conf_Server[i].lasttry = time( NULL );
1543 /* Freie Connection-Struktur suschen */
1544 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
1545 if( idx >= Pool_Size )
1547 Log( LOG_ALERT, "Can't establist server connection: connection limit reached (%d)!", Pool_Size );
1550 Log( LOG_DEBUG, "Preparing connection %d for \"%s\" ...", idx, Conf_Server[i].host );
1552 /* Verbindungs-Struktur initialisieren */
1553 Init_Conn_Struct( idx );
1554 My_Connections[idx].sock = SERVER_WAIT;
1555 My_Connections[idx].our_server = i;
1557 /* Hostnamen in IP aufloesen (Default bzw. im Fehlerfall: versuchen, den
1558 * konfigurierten Text direkt als IP-Adresse zu verwenden ... */
1559 strcpy( Conf_Server[My_Connections[idx].our_server].ip, Conf_Server[i].host );
1560 strcpy( My_Connections[idx].host, Conf_Server[i].host );
1561 s = Resolve_Name( Conf_Server[i].host );
1564 /* Sub-Prozess wurde asyncron gestartet */
1565 My_Connections[idx].res_stat = s;
1568 } /* Check_Servers */
1572 New_Server( INT Server, CONN_ID Idx )
1574 /* Neue Server-Verbindung aufbauen */
1576 struct sockaddr_in new_addr;
1577 struct in_addr inaddr;
1581 assert( Server > NONE );
1582 assert( Idx > NONE );
1584 /* Wurde eine gueltige IP-Adresse gefunden? */
1585 if( ! Conf_Server[Server].ip[0] )
1587 /* Nein. Verbindung wieder freigeben: */
1588 Init_Conn_Struct( Idx );
1589 Log( LOG_ERR, "Can't connect to \"%s\" (connection %d): ip address unknown!", Conf_Server[Server].host, Idx );
1593 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 );
1595 #ifdef HAVE_INET_ATON
1596 if( inet_aton( Conf_Server[Server].ip, &inaddr ) == 0 )
1598 memset( &inaddr, 0, sizeof( inaddr ));
1599 inaddr.s_addr = inet_addr( Conf_Server[Server].ip );
1600 if( inaddr.s_addr == (unsigned)-1 )
1603 /* Konnte Adresse nicht konvertieren */
1604 Init_Conn_Struct( Idx );
1605 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 );
1609 memset( &new_addr, 0, sizeof( new_addr ));
1610 new_addr.sin_family = AF_INET;
1611 new_addr.sin_addr = inaddr;
1612 new_addr.sin_port = htons( Conf_Server[Server].port );
1614 new_sock = socket( PF_INET, SOCK_STREAM, 0 );
1617 Init_Conn_Struct( Idx );
1618 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
1622 if( ! Init_Socket( new_sock )) return;
1624 res = connect( new_sock, (struct sockaddr *)&new_addr, sizeof( new_addr ));
1625 if(( res != 0 ) && ( errno != EINPROGRESS ))
1627 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1629 Init_Conn_Struct( Idx );
1633 /* Client-Struktur initialisieren */
1634 c = Client_NewLocal( Idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWNSERVER, FALSE );
1638 Init_Conn_Struct( Idx );
1639 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1642 Client_SetIntroducer( c, c );
1643 Client_SetToken( c, TOKEN_OUTBOUND );
1645 /* Verbindung registrieren */
1646 My_Connections[Idx].sock = new_sock;
1647 My_Connections[Idx].addr = new_addr;
1648 strcpy( My_Connections[Idx].host, Conf_Server[Server].host );
1650 /* Neuen Socket registrieren */
1651 FD_SET( new_sock, &My_Sockets );
1652 FD_SET( new_sock, &My_Connects );
1653 if( new_sock > Conn_MaxFD ) Conn_MaxFD = new_sock;
1655 Log( LOG_DEBUG, "Registered new connection %d on socket %d.", Idx, My_Connections[Idx].sock );
1660 Init_Conn_Struct( LONG Idx )
1662 /* Connection-Struktur initialisieren */
1664 My_Connections[Idx].sock = NONE;
1665 My_Connections[Idx].res_stat = NULL;
1666 My_Connections[Idx].host[0] = '\0';
1667 My_Connections[Idx].rbuf[0] = '\0';
1668 My_Connections[Idx].rdatalen = 0;
1669 My_Connections[Idx].wbuf[0] = '\0';
1670 My_Connections[Idx].wdatalen = 0;
1671 My_Connections[Idx].our_server = NONE;
1672 My_Connections[Idx].starttime = time( NULL );
1673 My_Connections[Idx].lastdata = time( NULL );
1674 My_Connections[Idx].lastping = 0;
1675 My_Connections[Idx].lastprivmsg = time( NULL );
1676 My_Connections[Idx].delaytime = 0;
1677 My_Connections[Idx].bytes_in = 0;
1678 My_Connections[Idx].bytes_out = 0;
1679 My_Connections[Idx].msg_in = 0;
1680 My_Connections[Idx].msg_out = 0;
1681 My_Connections[Idx].flag = 0;
1682 My_Connections[Idx].options = 0;
1685 My_Connections[Idx].zip.rbuf[0] = '\0';
1686 My_Connections[Idx].zip.rdatalen = 0;
1687 My_Connections[Idx].zip.wbuf[0] = '\0';
1688 My_Connections[Idx].zip.wdatalen = 0;
1689 My_Connections[Idx].zip.bytes_in = 0;
1690 My_Connections[Idx].zip.bytes_out = 0;
1692 } /* Init_Conn_Struct */
1696 Init_Socket( INT Sock )
1698 /* Socket-Optionen setzen */
1702 #ifdef O_NONBLOCK /* A/UX kennt das nicht? */
1703 if( fcntl( Sock, F_SETFL, O_NONBLOCK ) != 0 )
1705 Log( LOG_CRIT, "Can't enable non-blocking mode: %s!", strerror( errno ));
1710 if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &on, (socklen_t)sizeof( on )) != 0)
1712 Log( LOG_ERR, "Can't set socket options: %s!", strerror( errno ));
1713 /* dieser Fehler kann ignoriert werden. */
1721 Read_Resolver_Result( INT r_fd )
1723 /* Ergebnis von Resolver Sub-Prozess aus Pipe lesen
1724 * und entsprechende Connection aktualisieren */
1726 CHAR result[HOST_LEN];
1730 FD_CLR( r_fd, &Resolver_FDs );
1732 /* Anfrage vom Parent lesen */
1733 len = read( r_fd, result, HOST_LEN - 1 );
1736 /* Fehler beim Lesen aus der Pipe */
1738 Log( LOG_CRIT, "Resolver: Can't read result: %s!", strerror( errno ));
1743 /* zugehoerige Connection suchen */
1744 for( i = 0; i < Pool_Size; i++ )
1746 if(( My_Connections[i].sock != NONE ) && ( My_Connections[i].res_stat ) && ( My_Connections[i].res_stat->pipe[0] == r_fd )) break;
1748 if( i >= Pool_Size )
1750 /* Opsa! Keine passende Connection gefunden!? Vermutlich
1751 * wurde sie schon wieder geschlossen. */
1753 Log( LOG_DEBUG, "Resolver: Got result for unknown connection!?" );
1757 Log( LOG_DEBUG, "Resolver: %s is \"%s\".", My_Connections[i].host, result );
1760 close( My_Connections[i].res_stat->pipe[0] );
1761 close( My_Connections[i].res_stat->pipe[1] );
1762 free( My_Connections[i].res_stat );
1763 My_Connections[i].res_stat = NULL;
1765 if( My_Connections[i].sock > NONE )
1767 /* Eingehende Verbindung: Hostnamen setzen */
1768 c = Client_GetFromConn( i );
1769 assert( c != NULL );
1770 strcpy( My_Connections[i].host, result );
1771 Client_SetHostname( c, result );
1775 /* Ausgehende Verbindung (=Server): IP setzen */
1776 assert( My_Connections[i].our_server > NONE );
1777 strcpy( Conf_Server[My_Connections[i].our_server].ip, result );
1780 /* Penalty-Zeit zurueck setzen */
1781 Conn_ResetPenalty( i );
1782 } /* Read_Resolver_Result */
1788 Zip_Buffer( CONN_ID Idx, CHAR *Data, INT Len )
1790 /* Daten zum Komprimieren im "Kompressions-Puffer" sammeln.
1791 * Es wird TRUE bei Erfolg, sonst FALSE geliefert. */
1793 assert( Idx > NONE );
1794 assert( Data != NULL );
1797 /* Ist noch Platz im Kompressions-Puffer? */
1798 if( ZWRITEBUFFER_LEN - My_Connections[Idx].zip.wdatalen < Len + 50 )
1800 /* Nein! Puffer zunaechst leeren ...*/
1801 if( ! Zip_Flush( Idx )) return FALSE;
1804 /* Daten kopieren */
1805 memmove( My_Connections[Idx].zip.wbuf + My_Connections[Idx].zip.wdatalen, Data, Len );
1806 My_Connections[Idx].zip.wdatalen += Len;
1813 Zip_Flush( CONN_ID Idx )
1815 /* Daten komprimieren und in Schreibpuffer kopieren.
1816 * Es wird TRUE bei Erfolg, sonst FALSE geliefert. */
1818 INT result, out_len;
1821 out = &My_Connections[Idx].zip.out;
1823 out->next_in = My_Connections[Idx].zip.wbuf;
1824 out->avail_in = My_Connections[Idx].zip.wdatalen;
1825 out->next_out = My_Connections[Idx].wbuf + My_Connections[Idx].wdatalen;
1826 out->avail_out = WRITEBUFFER_LEN - My_Connections[Idx].wdatalen;
1828 result = deflate( out, Z_SYNC_FLUSH );
1829 if(( result != Z_OK ) || ( out->avail_in > 0 ))
1831 Log( LOG_ALERT, "Compression error: code %d!?", result );
1832 Conn_Close( Idx, "Compression error!", NULL, FALSE );
1836 out_len = WRITEBUFFER_LEN - My_Connections[Idx].wdatalen - out->avail_out;
1837 My_Connections[Idx].wdatalen += out_len;
1838 My_Connections[Idx].bytes_out += out_len;
1839 My_Connections[Idx].zip.bytes_out += My_Connections[Idx].zip.wdatalen;
1840 My_Connections[Idx].zip.wdatalen = 0;
1847 Unzip_Buffer( CONN_ID Idx )
1849 /* Daten entpacken und in Lesepuffer kopieren. Bei Fehlern
1850 * wird FALSE geliefert, ansonsten TRUE. Der Fall, dass keine
1851 * Daten mehr zu entpacken sind, ist _kein_ Fehler! */
1853 INT result, in_len, out_len;
1856 assert( Idx > NONE );
1858 if( My_Connections[Idx].zip.rdatalen <= 0 ) return TRUE;
1860 in = &My_Connections[Idx].zip.in;
1862 in->next_in = My_Connections[Idx].zip.rbuf;
1863 in->avail_in = My_Connections[Idx].zip.rdatalen;
1864 in->next_out = My_Connections[Idx].rbuf + My_Connections[Idx].rdatalen;
1865 in->avail_out = READBUFFER_LEN - My_Connections[Idx].rdatalen - 1;
1867 result = inflate( in, Z_SYNC_FLUSH );
1868 if( result != Z_OK )
1870 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 );
1871 Conn_Close( Idx, "Decompression error!", NULL, FALSE );
1875 in_len = My_Connections[Idx].zip.rdatalen - in->avail_in;
1876 out_len = READBUFFER_LEN - My_Connections[Idx].rdatalen - 1 - in->avail_out;
1877 My_Connections[Idx].rdatalen += out_len;
1879 if( in->avail_in > 0 )
1881 /* es konnten nicht alle Daten entpackt werden, vermutlich war
1882 * im Ziel-Puffer kein Platz mehr. Umkopieren ... */
1883 My_Connections[Idx].zip.rdatalen -= in_len;
1884 memmove( My_Connections[Idx].zip.rbuf, My_Connections[Idx].zip.rbuf + in_len, My_Connections[Idx].zip.rdatalen );
1886 else My_Connections[Idx].zip.rdatalen = 0;
1887 My_Connections[Idx].zip.bytes_in += out_len;
1890 } /* Unzip_Buffer */