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.98 2002/11/28 16:56:20 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 );
573 /* Statistik an Client melden, wenn User */
574 if(( c != NULL ) && ( Client_Type( c ) == CLIENT_USER ))
576 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 );
579 /* ERROR an Client schicken (von RFC so vorgesehen!) */
580 if( FwdMsg ) Conn_WriteStr( Idx, "ERROR :%s", FwdMsg );
581 else Conn_WriteStr( Idx, "ERROR :Closing connection." );
582 if( My_Connections[Idx].sock == NONE ) return;
585 /* zunaechst versuchen, noch im Schreibpuffer vorhandene
586 * Daten auf den Socket zu schreiben ... */
589 if( close( My_Connections[Idx].sock ) != 0 )
591 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 ));
595 in_k = (DOUBLE)My_Connections[Idx].bytes_in / 1024;
596 out_k = (DOUBLE)My_Connections[Idx].bytes_out / 1024;
598 if( My_Connections[Idx].options & CONN_ZIP )
600 in_z_k = (DOUBLE)My_Connections[Idx].zip.bytes_in / 1024;
601 out_z_k = (DOUBLE)My_Connections[Idx].zip.bytes_out / 1024;
602 in_p = (INT)(( in_k * 100 ) / in_z_k );
603 out_p = (INT)(( out_k * 100 ) / out_z_k );
604 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 );
609 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 );
613 /* Socket als "ungueltig" markieren */
614 FD_CLR( My_Connections[Idx].sock, &My_Sockets );
615 FD_CLR( My_Connections[Idx].sock, &My_Connects );
616 My_Connections[Idx].sock = NONE;
618 if( c ) Client_Destroy( c, LogMsg, FwdMsg, TRUE );
620 if( My_Connections[Idx].res_stat )
622 /* Resolver-Strukturen freigeben, wenn noch nicht geschehen */
623 FD_CLR( My_Connections[Idx].res_stat->pipe[0], &Resolver_FDs );
624 close( My_Connections[Idx].res_stat->pipe[0] );
625 close( My_Connections[Idx].res_stat->pipe[1] );
626 free( My_Connections[Idx].res_stat );
629 /* Startzeit des naechsten Connect-Versuchs modifizieren? */
630 if(( My_Connections[Idx].our_server > NONE ) && ( Conf_Server[My_Connections[Idx].our_server].lasttry < time( NULL ) - Conf_ConnectRetry ))
632 /* Okay, die Verbindung stand schon "genuegend lange":
633 * lasttry-Zeitpunkt so setzen, dass der naechste
634 * Verbindungsversuch in RECONNECT_DELAY Sekunden
636 Conf_Server[My_Connections[Idx].our_server].lasttry = time( NULL ) - Conf_ConnectRetry + RECONNECT_DELAY;
640 /* Ggf. zlib abmelden */
641 if( Conn_Options( Idx ) & CONN_ZIP )
643 inflateEnd( &My_Connections[Idx].zip.in );
644 deflateEnd( &My_Connections[Idx].zip.out );
648 /* Connection-Struktur loeschen (=freigeben) */
649 Init_Conn_Struct( Idx );
654 Conn_UpdateIdle( CONN_ID Idx )
656 /* Idle-Timer zuruecksetzen */
658 assert( Idx > NONE );
659 My_Connections[Idx].lastprivmsg = time( NULL );
664 Conn_GetIdle( CONN_ID Idx )
666 /* Idle-Time einer Verbindung liefern (in Sekunden) */
668 assert( Idx > NONE );
669 return time( NULL ) - My_Connections[Idx].lastprivmsg;
674 Conn_LastPing( CONN_ID Idx )
676 /* Zeitpunkt des letzten PING liefern */
678 assert( Idx > NONE );
679 return My_Connections[Idx].lastping;
680 } /* Conn_LastPing */
684 Conn_SetPenalty( CONN_ID Idx, time_t Seconds )
686 /* Penalty-Delay fuer eine Verbindung (in Sekunden) setzen;
687 * waehrend dieser Zeit wird der entsprechende Socket vom Server
688 * bei Lese-Operationen komplett ignoriert. Der Delay kann mit
689 * dieser Funktion nur erhoeht, nicht aber verringert werden. */
693 assert( Idx > NONE );
694 assert( Seconds >= 0 );
696 t = time( NULL ) + Seconds;
697 if( t > My_Connections[Idx].delaytime ) My_Connections[Idx].delaytime = t;
698 } /* Conn_SetPenalty */
702 Conn_ResetPenalty( CONN_ID Idx )
704 assert( Idx > NONE );
705 My_Connections[Idx].delaytime = 0;
706 } /* Conn_ResetPenalty */
710 Conn_ClearFlags( VOID )
712 /* Alle Connection auf "nicht-markiert" setzen */
716 for( i = 0; i < Pool_Size; i++ ) My_Connections[i].flag = 0;
717 } /* Conn_ClearFlags */
721 Conn_Flag( CONN_ID Idx )
723 /* Ist eine Connection markiert (TRUE) oder nicht? */
725 assert( Idx > NONE );
726 return My_Connections[Idx].flag;
731 Conn_SetFlag( CONN_ID Idx, INT Flag )
733 /* Connection markieren */
735 assert( Idx > NONE );
736 My_Connections[Idx].flag = Flag;
743 /* Connection-Struktur der ersten Verbindung liefern;
744 * Ist keine Verbindung vorhanden, wird NONE geliefert. */
748 for( i = 0; i < Pool_Size; i++ )
750 if( My_Connections[i].sock != NONE ) return i;
757 Conn_Next( CONN_ID Idx )
759 /* Naechste Verbindungs-Struktur liefern; existiert keine
760 * weitere, so wird NONE geliefert. */
764 assert( Idx > NONE );
766 for( i = Idx + 1; i < Pool_Size; i++ )
768 if( My_Connections[i].sock != NONE ) return i;
775 Conn_SetServer( CONN_ID Idx, INT ConfServer )
777 /* Connection als Server markieren: Index des konfigurierten
778 * Servers speichern. Verbindung muss bereits bestehen! */
780 assert( Idx > NONE );
781 assert( My_Connections[Idx].sock > NONE );
783 My_Connections[Idx].our_server = ConfServer;
784 } /* Conn_SetServer */
788 Conn_SetOption( CONN_ID Idx, INT Option )
790 /* Option fuer Verbindung setzen.
791 * Initial sind alle Optionen _nicht_ gesetzt. */
793 assert( Idx > NONE );
794 assert( Option != 0 );
796 My_Connections[Idx].options |= Option;
797 } /* Conn_SetOption */
801 Conn_UnsetOption( CONN_ID Idx, INT Option )
803 /* Option fuer Verbindung loeschen */
805 assert( Idx > NONE );
806 assert( Option != 0 );
808 My_Connections[Idx].options &= ~Option;
809 } /* Conn_UnsetOption */
813 Conn_Options( CONN_ID Idx )
815 assert( Idx > NONE );
816 return My_Connections[Idx].options;
823 Conn_InitZip( CONN_ID Idx )
825 /* Kompression fuer Link initialisieren */
827 assert( Idx > NONE );
829 My_Connections[Idx].zip.in.avail_in = 0;
830 My_Connections[Idx].zip.in.total_in = 0;
831 My_Connections[Idx].zip.in.total_out = 0;
832 My_Connections[Idx].zip.in.zalloc = NULL;
833 My_Connections[Idx].zip.in.zfree = NULL;
834 My_Connections[Idx].zip.in.data_type = Z_ASCII;
836 if( inflateInit( &My_Connections[Idx].zip.in ) != Z_OK )
839 Log( LOG_ALERT, "Can't initialize compression on connection %d (zlib inflate)!", Idx );
843 My_Connections[Idx].zip.out.total_in = 0;
844 My_Connections[Idx].zip.out.total_in = 0;
845 My_Connections[Idx].zip.out.zalloc = NULL;
846 My_Connections[Idx].zip.out.zfree = NULL;
847 My_Connections[Idx].zip.out.data_type = Z_ASCII;
849 if( deflateInit( &My_Connections[Idx].zip.out, Z_DEFAULT_COMPRESSION ) != Z_OK )
852 Log( LOG_ALERT, "Can't initialize compression on connection %d (zlib deflate)!", Idx );
856 My_Connections[Idx].zip.bytes_in = My_Connections[Idx].bytes_in;
857 My_Connections[Idx].zip.bytes_out = My_Connections[Idx].bytes_out;
859 Log( LOG_INFO, "Enabled link compression (zlib) on connection %d.", Idx );
860 Conn_SetOption( Idx, CONN_ZIP );
869 Try_Write( CONN_ID Idx )
871 /* Versuchen, Daten aus dem Schreib-Puffer in den Socket zu
872 * schreiben. TRUE wird geliefert, wenn entweder keine Daten
873 * zum Versenden vorhanden sind oder erfolgreich bearbeitet
874 * werden konnten. Im Fehlerfall wird FALSE geliefert und
875 * die Verbindung geschlossen. */
880 assert( Idx > NONE );
881 assert( My_Connections[Idx].sock > NONE );
883 /* sind ueberhaupt Daten vorhanden? */
885 if(( ! My_Connections[Idx].wdatalen > 0 ) && ( ! My_Connections[Idx].zip.wdatalen )) return TRUE;
887 if( ! My_Connections[Idx].wdatalen > 0 ) return TRUE;
890 /* Timeout initialisieren: 0 Sekunden, also nicht blockieren */
891 tv.tv_sec = 0; tv.tv_usec = 0;
893 FD_ZERO( &write_socket );
894 FD_SET( My_Connections[Idx].sock, &write_socket );
895 if( select( My_Connections[Idx].sock + 1, NULL, &write_socket, NULL, &tv ) == -1 )
900 Log( LOG_ALERT, "Try_Write(): select() failed: %s (con=%d, sock=%d)!", strerror( errno ), Idx, My_Connections[Idx].sock );
901 Conn_Close( Idx, "Server error!", NULL, FALSE );
906 if( FD_ISSET( My_Connections[Idx].sock, &write_socket )) return Handle_Write( Idx );
912 Handle_Read( INT Sock )
914 /* Aktivitaet auf einem Socket verarbeiten:
915 * - neue Clients annehmen,
916 * - Daten von Clients verarbeiten,
917 * - Resolver-Rueckmeldungen annehmen. */
921 assert( Sock > NONE );
923 if( FD_ISSET( Sock, &My_Listeners ))
925 /* es ist einer unserer Listener-Sockets: es soll
926 * also eine neue Verbindung aufgebaut werden. */
928 New_Connection( Sock );
930 else if( FD_ISSET( Sock, &Resolver_FDs ))
932 /* Rueckmeldung von einem Resolver Sub-Prozess */
934 Read_Resolver_Result( Sock );
938 /* Ein Client Socket: entweder ein User oder Server */
940 idx = Socket2Index( Sock );
941 if( idx > NONE ) Read_Request( idx );
947 Handle_Write( CONN_ID Idx )
949 /* Daten aus Schreibpuffer versenden bzw. Connection aufbauen */
953 assert( Idx > NONE );
954 assert( My_Connections[Idx].sock > NONE );
956 if( FD_ISSET( My_Connections[Idx].sock, &My_Connects ))
958 /* es soll nichts geschrieben werden, sondern ein
959 * connect() hat ein Ergebnis geliefert */
961 FD_CLR( My_Connections[Idx].sock, &My_Connects );
963 /* Ergebnis des connect() ermitteln */
965 res = getsockopt( My_Connections[Idx].sock, SOL_SOCKET, SO_ERROR, &err, &len );
966 assert( len == sizeof( err ));
968 /* Fehler aufgetreten? */
969 if(( res != 0 ) || ( err != 0 ))
972 if( res != 0 ) Log( LOG_CRIT, "getsockopt (connection %d): %s!", Idx, strerror( errno ));
973 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 ));
975 /* Socket etc. pp. aufraeumen */
976 FD_CLR( My_Connections[Idx].sock, &My_Sockets );
977 close( My_Connections[Idx].sock );
978 Init_Conn_Struct( Idx );
980 /* Bei Server-Verbindungen lasttry-Zeitpunkt auf "jetzt" setzen */
981 Conf_Server[My_Connections[Idx].our_server].lasttry = time( NULL );
985 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 );
987 /* PASS und SERVER verschicken */
988 Conn_WriteStr( Idx, "PASS %s %s", Conf_Server[My_Connections[Idx].our_server].pwd_out, NGIRCd_ProtoID );
989 return Conn_WriteStr( Idx, "SERVER %s :%s", Conf_ServerName, Conf_ServerInfo );
993 /* Schreibpuffer leer, aber noch Daten im Kompressionsbuffer?
994 * Dann muss dieser nun geflushed werden! */
995 if( My_Connections[Idx].wdatalen == 0 ) Zip_Flush( Idx );
998 assert( My_Connections[Idx].wdatalen > 0 );
1000 /* Daten schreiben */
1001 len = send( My_Connections[Idx].sock, My_Connections[Idx].wbuf, My_Connections[Idx].wdatalen, 0 );
1004 /* Operation haette Socket "nur" blockiert ... */
1005 if( errno == EAGAIN ) return TRUE;
1007 /* Oops, ein Fehler! */
1008 Log( LOG_ERR, "Write error on connection %d (socket %d): %s!", Idx, My_Connections[Idx].sock, strerror( errno ));
1009 Conn_Close( Idx, "Write error!", NULL, FALSE );
1013 /* Puffer anpassen */
1014 My_Connections[Idx].wdatalen -= len;
1015 memmove( My_Connections[Idx].wbuf, My_Connections[Idx].wbuf + len, My_Connections[Idx].wdatalen );
1018 } /* Handle_Write */
1022 New_Connection( INT Sock )
1024 /* Neue Client-Verbindung von Listen-Socket annehmen und
1025 * CLIENT-Struktur anlegen. */
1027 struct sockaddr_in new_addr;
1028 INT new_sock, new_sock_len;
1035 assert( Sock > NONE );
1037 /* Connection auf Listen-Socket annehmen */
1038 new_sock_len = sizeof( new_addr );
1039 new_sock = accept( Sock, (struct sockaddr *)&new_addr, (socklen_t *)&new_sock_len );
1042 Log( LOG_CRIT, "Can't accept connection: %s!", strerror( errno ));
1046 /* Socket initialisieren */
1047 Init_Socket( new_sock );
1049 /* Freie Connection-Struktur suchen */
1050 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
1051 if( idx >= Pool_Size )
1053 new_size = Pool_Size + CONNECTION_POOL;
1055 /* Im bisherigen Pool wurde keine freie Connection-Struktur mehr gefunden.
1056 * Wenn erlaubt und moeglich muss nun der Pool vergroessert werden: */
1058 if( Conf_MaxConnections > 0 )
1060 /* Es ist ein Limit konfiguriert */
1061 if( Pool_Size >= Conf_MaxConnections )
1063 /* Mehr Verbindungen duerfen wir leider nicht mehr annehmen ... */
1064 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached!", Pool_Size );
1068 if( new_size > Conf_MaxConnections ) new_size = Conf_MaxConnections;
1071 /* zunaechst realloc() versuchen; wenn das scheitert, malloc() versuchen
1072 * und Daten ggf. "haendisch" umkopieren. (Haesslich! Eine wirklich
1073 * dynamische Verwaltung waere wohl _deutlich_ besser ...) */
1074 ptr = realloc( My_Connections, sizeof( CONNECTION ) * new_size );
1077 /* realloc() ist fehlgeschlagen. Nun malloc() probieren: */
1078 ptr = malloc( sizeof( CONNECTION ) * new_size );
1081 /* Offenbar steht kein weiterer Sepeicher zur Verfuegung :-( */
1082 Log( LOG_EMERG, "Can't allocate memory! [New_Connection]" );
1087 /* Struktur umkopieren ... */
1088 memcpy( ptr, My_Connections, sizeof( CONNECTION ) * Pool_Size );
1090 Log( LOG_DEBUG, "Allocated new connection pool for %ld items. [malloc()/memcpy()]", new_size );
1092 else Log( LOG_DEBUG, "Allocated new connection pool for %ld items. [realloc()]", new_size );
1094 My_Connections = ptr;
1095 Pool_Size = new_size;
1098 /* Client-Struktur initialisieren */
1099 c = Client_NewLocal( idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWN, FALSE );
1102 Log( LOG_ALERT, "Can't accept connection: can't create client structure!" );
1107 /* Verbindung registrieren */
1108 Init_Conn_Struct( idx );
1109 My_Connections[idx].sock = new_sock;
1110 My_Connections[idx].addr = new_addr;
1112 /* Neuen Socket registrieren */
1113 FD_SET( new_sock, &My_Sockets );
1114 if( new_sock > Conn_MaxFD ) Conn_MaxFD = new_sock;
1116 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 );
1118 /* Hostnamen ermitteln */
1119 strcpy( My_Connections[idx].host, inet_ntoa( new_addr.sin_addr ));
1120 Client_SetHostname( c, My_Connections[idx].host );
1121 s = Resolve_Addr( &new_addr );
1124 /* Sub-Prozess wurde asyncron gestartet */
1125 Conn_WriteStr( idx, "NOTICE AUTH :%sLooking up your hostname ...", NOTICE_TXTPREFIX );
1126 My_Connections[idx].res_stat = s;
1129 /* Penalty-Zeit setzen */
1130 Conn_SetPenalty( idx, 4 );
1131 } /* New_Connection */
1135 Socket2Index( INT Sock )
1137 /* zum Socket passende Connection suchen */
1141 assert( Sock > NONE );
1143 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == Sock ) break;
1145 if( idx >= Pool_Size )
1147 /* die Connection wurde vermutlich (wegen eines
1148 * Fehlers) bereits wieder abgebaut ... */
1149 Log( LOG_DEBUG, "Socket2Index: can't get connection for socket %d!", Sock );
1153 } /* Socket2Index */
1157 Read_Request( CONN_ID Idx )
1159 /* Daten von Socket einlesen und entsprechend behandeln.
1160 * Tritt ein Fehler auf, so wird der Socket geschlossen. */
1165 assert( Idx > NONE );
1166 assert( My_Connections[Idx].sock > NONE );
1168 /* wenn noch nicht registriert: maximal mit ZREADBUFFER_LEN arbeiten,
1169 * ansonsten koennen Daten ggf. nicht umkopiert werden. */
1170 bsize = READBUFFER_LEN;
1172 c = Client_GetFromConn( Idx );
1173 if(( Client_Type( c ) != CLIENT_USER ) && ( Client_Type( c ) != CLIENT_SERVER ) && ( Client_Type( c ) != CLIENT_SERVICE ) && ( bsize > ZREADBUFFER_LEN )) bsize = ZREADBUFFER_LEN;
1177 if(( bsize - My_Connections[Idx].rdatalen - 1 < 1 ) || ( ZREADBUFFER_LEN - My_Connections[Idx].zip.rdatalen < 1 ))
1179 if( bsize - My_Connections[Idx].rdatalen - 1 < 1 )
1182 /* Der Lesepuffer ist voll */
1183 Log( LOG_ERR, "Read buffer overflow (connection %d): %d bytes!", Idx, My_Connections[Idx].rdatalen );
1184 Conn_Close( Idx, "Read buffer overflow!", NULL, FALSE );
1189 if( My_Connections[Idx].options & CONN_ZIP )
1191 len = recv( My_Connections[Idx].sock, My_Connections[Idx].zip.rbuf + My_Connections[Idx].zip.rdatalen, ( ZREADBUFFER_LEN - My_Connections[Idx].zip.rdatalen ), 0 );
1192 if( len > 0 ) My_Connections[Idx].zip.rdatalen += len;
1197 len = recv( My_Connections[Idx].sock, My_Connections[Idx].rbuf + My_Connections[Idx].rdatalen, bsize - My_Connections[Idx].rdatalen - 1, 0 );
1198 if( len > 0 ) My_Connections[Idx].rdatalen += len;
1203 /* Socket wurde geschlossen */
1204 Log( LOG_INFO, "%s:%d is closing the connection ...", inet_ntoa( My_Connections[Idx].addr.sin_addr ), ntohs( My_Connections[Idx].addr.sin_port));
1205 Conn_Close( Idx, "Socket closed!", "Client closed connection", FALSE );
1211 /* Operation haette Socket "nur" blockiert ... */
1212 if( errno == EAGAIN ) return;
1214 /* Fehler beim Lesen */
1215 Log( LOG_ERR, "Read error on connection %d (socket %d): %s!", Idx, My_Connections[Idx].sock, strerror( errno ));
1216 Conn_Close( Idx, "Read error!", "Client closed connection", FALSE );
1220 /* Connection-Statistik aktualisieren */
1221 My_Connections[Idx].bytes_in += len;
1223 /* Timestamp aktualisieren */
1224 My_Connections[Idx].lastdata = time( NULL );
1226 Handle_Buffer( Idx );
1227 } /* Read_Request */
1231 Handle_Buffer( CONN_ID Idx )
1233 /* Daten im Lese-Puffer einer Verbindung verarbeiten.
1234 * Wurde ein Request verarbeitet, so wird TRUE geliefert,
1235 * ansonsten FALSE (auch bei Fehlern). */
1242 BOOLEAN action, result;
1251 /* ggf. noch unkomprimiete Daten weiter entpacken */
1252 if( My_Connections[Idx].options & CONN_ZIP )
1254 if( ! Unzip_Buffer( Idx )) return FALSE;
1258 if( My_Connections[Idx].rdatalen < 1 ) break;
1260 /* Eine komplette Anfrage muss mit CR+LF enden, vgl.
1261 * RFC 2812. Haben wir eine? */
1262 My_Connections[Idx].rbuf[My_Connections[Idx].rdatalen] = '\0';
1263 ptr = strstr( My_Connections[Idx].rbuf, "\r\n" );
1265 if( ptr ) delta = 2;
1269 /* Nicht RFC-konforme Anfrage mit nur CR oder LF? Leider
1270 * machen soetwas viele Clients, u.a. "mIRC" :-( */
1271 ptr1 = strchr( My_Connections[Idx].rbuf, '\r' );
1272 ptr2 = strchr( My_Connections[Idx].rbuf, '\n' );
1274 if( ptr1 && ptr2 ) ptr = ptr1 > ptr2 ? ptr2 : ptr1;
1275 else if( ptr1 ) ptr = ptr1;
1276 else if( ptr2 ) ptr = ptr2;
1283 /* Ende der Anfrage wurde gefunden */
1285 len = ( ptr - My_Connections[Idx].rbuf ) + delta;
1286 if( len > ( COMMAND_LEN - 1 ))
1288 /* Eine Anfrage darf(!) nicht laenger als 512 Zeichen
1289 * (incl. CR+LF!) werden; vgl. RFC 2812. Wenn soetwas
1290 * empfangen wird, wird der Client disconnectiert. */
1291 Log( LOG_ERR, "Request too long (connection %d): %d bytes (max. %d expected)!", Idx, My_Connections[Idx].rdatalen, COMMAND_LEN - 1 );
1292 Conn_Close( Idx, NULL, "Request too long", TRUE );
1297 /* merken, ob Stream bereits komprimiert wird */
1298 old_z = My_Connections[Idx].options & CONN_ZIP;
1303 /* Es wurde ein Request gelesen */
1304 if( ! Parse_Request( Idx, My_Connections[Idx].rbuf )) return FALSE;
1308 /* Puffer anpassen */
1309 My_Connections[Idx].rdatalen -= len;
1310 memmove( My_Connections[Idx].rbuf, My_Connections[Idx].rbuf + len, My_Connections[Idx].rdatalen );
1313 if(( ! old_z ) && ( My_Connections[Idx].options & CONN_ZIP ) && ( My_Connections[Idx].rdatalen > 0 ))
1315 /* Mit dem letzten Befehl wurde Socket-Kompression aktiviert.
1316 * Evtl. schon vom Socket gelesene Daten in den Unzip-Puffer
1317 * umkopieren, damit diese nun zunaechst entkomprimiert werden */
1319 if( My_Connections[Idx].rdatalen > ZREADBUFFER_LEN )
1321 /* Hupsa! Soviel Platz haben wir aber gar nicht! */
1322 Log( LOG_ALERT, "Can't move read buffer: No space left in unzip buffer (need %d bytes)!", My_Connections[Idx].rdatalen );
1325 memcpy( My_Connections[Idx].zip.rbuf, My_Connections[Idx].rbuf, My_Connections[Idx].rdatalen );
1326 My_Connections[Idx].zip.rdatalen = My_Connections[Idx].rdatalen;
1327 My_Connections[Idx].rdatalen = 0;
1328 Log( LOG_DEBUG, "Moved already received data (%d bytes) to uncompression buffer.", My_Connections[Idx].zip.rdatalen );
1334 if( action ) result = TRUE;
1338 } /* Handle_Buffer */
1342 Check_Connections( VOID )
1344 /* Pruefen, ob Verbindungen noch "alive" sind. Ist dies
1345 * nicht der Fall, zunaechst PING-PONG spielen und, wenn
1346 * auch das nicht "hilft", Client disconnectieren. */
1351 for( i = 0; i < Pool_Size; i++ )
1353 if( My_Connections[i].sock == NONE ) continue;
1355 c = Client_GetFromConn( i );
1356 if( c && (( Client_Type( c ) == CLIENT_USER ) || ( Client_Type( c ) == CLIENT_SERVER ) || ( Client_Type( c ) == CLIENT_SERVICE )))
1358 /* verbundener User, Server oder Service */
1359 if( My_Connections[i].lastping > My_Connections[i].lastdata )
1361 /* es wurde bereits ein PING gesendet */
1362 if( My_Connections[i].lastping < time( NULL ) - Conf_PongTimeout )
1365 Log( LOG_DEBUG, "Connection %d: Ping timeout: %d seconds.", i, Conf_PongTimeout );
1366 Conn_Close( i, NULL, "Ping timeout", TRUE );
1369 else if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout )
1371 /* es muss ein PING gesendet werden */
1372 Log( LOG_DEBUG, "Connection %d: sending PING ...", i );
1373 My_Connections[i].lastping = time( NULL );
1374 Conn_WriteStr( i, "PING :%s", Client_ID( Client_ThisServer( )));
1379 /* noch nicht vollstaendig aufgebaute Verbindung */
1380 if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout )
1383 Log( LOG_DEBUG, "Connection %d timed out ...", i );
1384 Conn_Close( i, NULL, "Timeout", FALSE );
1388 } /* Check_Connections */
1392 Check_Servers( VOID )
1394 /* Pruefen, ob Server-Verbindungen aufgebaut werden
1395 * muessen bzw. koennen */
1401 /* Wenn "Passive-Mode" aktiv: nicht verbinden */
1402 if( NGIRCd_Passive ) return;
1404 for( i = 0; i < Conf_Server_Count; i++ )
1406 /* Ist ein Hostname und Port definiert? */
1407 if(( ! Conf_Server[i].host[0] ) || ( ! Conf_Server[i].port > 0 )) continue;
1409 /* Haben wir schon eine Verbindung? */
1410 for( n = 0; n < Pool_Size; n++ )
1412 if( My_Connections[n].sock == NONE ) continue;
1414 /* Verbindung zu diesem Server? */
1415 if( My_Connections[n].our_server == i )
1417 /* Komplett aufgebaute Verbindung? */
1418 if( My_Connections[n].sock > NONE ) break;
1420 /* IP schon aufgeloest? */
1421 if( My_Connections[n].res_stat == NULL ) New_Server( i, n );
1424 /* Verbindung in dieser Server-Gruppe? */
1425 if(( My_Connections[n].our_server != NONE ) && ( Conf_Server[i].group != NONE ))
1427 if( Conf_Server[My_Connections[n].our_server].group == Conf_Server[i].group ) break;
1430 if( n < Pool_Size ) continue;
1432 /* Wann war der letzte Connect-Versuch? */
1433 if( Conf_Server[i].lasttry > time( NULL ) - Conf_ConnectRetry ) continue;
1435 /* Okay, Verbindungsaufbau versuchen */
1436 Conf_Server[i].lasttry = time( NULL );
1438 /* Freie Connection-Struktur suschen */
1439 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
1440 if( idx >= Pool_Size )
1442 Log( LOG_ALERT, "Can't establist server connection: connection limit reached (%d)!", Pool_Size );
1445 Log( LOG_DEBUG, "Preparing connection %d for \"%s\" ...", idx, Conf_Server[i].host );
1447 /* Verbindungs-Struktur initialisieren */
1448 Init_Conn_Struct( idx );
1449 My_Connections[idx].sock = SERVER_WAIT;
1450 My_Connections[idx].our_server = i;
1452 /* Hostnamen in IP aufloesen (Default bzw. im Fehlerfall: versuchen, den
1453 * konfigurierten Text direkt als IP-Adresse zu verwenden ... */
1454 strcpy( Conf_Server[My_Connections[idx].our_server].ip, Conf_Server[i].host );
1455 strcpy( My_Connections[idx].host, Conf_Server[i].host );
1456 s = Resolve_Name( Conf_Server[i].host );
1459 /* Sub-Prozess wurde asyncron gestartet */
1460 My_Connections[idx].res_stat = s;
1463 } /* Check_Servers */
1467 New_Server( INT Server, CONN_ID Idx )
1469 /* Neue Server-Verbindung aufbauen */
1471 struct sockaddr_in new_addr;
1472 struct in_addr inaddr;
1476 assert( Server > NONE );
1477 assert( Idx > NONE );
1479 /* Wurde eine gueltige IP-Adresse gefunden? */
1480 if( ! Conf_Server[Server].ip[0] )
1482 /* Nein. Verbindung wieder freigeben: */
1483 Init_Conn_Struct( Idx );
1484 Log( LOG_ERR, "Can't connect to \"%s\" (connection %d): ip address unknown!", Conf_Server[Server].host, Idx );
1488 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 );
1490 #ifdef HAVE_INET_ATON
1491 if( inet_aton( Conf_Server[Server].ip, &inaddr ) == 0 )
1493 memset( &inaddr, 0, sizeof( inaddr ));
1494 inaddr.s_addr = inet_addr( Conf_Server[Server].ip );
1495 if( inaddr.s_addr == (unsigned)-1 )
1498 /* Konnte Adresse nicht konvertieren */
1499 Init_Conn_Struct( Idx );
1500 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 );
1504 memset( &new_addr, 0, sizeof( new_addr ));
1505 new_addr.sin_family = AF_INET;
1506 new_addr.sin_addr = inaddr;
1507 new_addr.sin_port = htons( Conf_Server[Server].port );
1509 new_sock = socket( PF_INET, SOCK_STREAM, 0 );
1512 Init_Conn_Struct( Idx );
1513 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
1517 if( ! Init_Socket( new_sock )) return;
1519 res = connect( new_sock, (struct sockaddr *)&new_addr, sizeof( new_addr ));
1520 if(( res != 0 ) && ( errno != EINPROGRESS ))
1522 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1524 Init_Conn_Struct( Idx );
1528 /* Client-Struktur initialisieren */
1529 c = Client_NewLocal( Idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWNSERVER, FALSE );
1533 Init_Conn_Struct( Idx );
1534 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1537 Client_SetIntroducer( c, c );
1538 Client_SetToken( c, TOKEN_OUTBOUND );
1540 /* Verbindung registrieren */
1541 My_Connections[Idx].sock = new_sock;
1542 My_Connections[Idx].addr = new_addr;
1543 strcpy( My_Connections[Idx].host, Conf_Server[Server].host );
1545 /* Neuen Socket registrieren */
1546 FD_SET( new_sock, &My_Sockets );
1547 FD_SET( new_sock, &My_Connects );
1548 if( new_sock > Conn_MaxFD ) Conn_MaxFD = new_sock;
1550 Log( LOG_DEBUG, "Registered new connection %d on socket %d.", Idx, My_Connections[Idx].sock );
1555 Init_Conn_Struct( LONG Idx )
1557 /* Connection-Struktur initialisieren */
1559 My_Connections[Idx].sock = NONE;
1560 My_Connections[Idx].res_stat = NULL;
1561 My_Connections[Idx].host[0] = '\0';
1562 My_Connections[Idx].rbuf[0] = '\0';
1563 My_Connections[Idx].rdatalen = 0;
1564 My_Connections[Idx].wbuf[0] = '\0';
1565 My_Connections[Idx].wdatalen = 0;
1566 My_Connections[Idx].our_server = NONE;
1567 My_Connections[Idx].lastdata = time( NULL );
1568 My_Connections[Idx].lastping = 0;
1569 My_Connections[Idx].lastprivmsg = time( NULL );
1570 My_Connections[Idx].delaytime = 0;
1571 My_Connections[Idx].bytes_in = 0;
1572 My_Connections[Idx].bytes_out = 0;
1573 My_Connections[Idx].flag = 0;
1574 My_Connections[Idx].options = 0;
1577 My_Connections[Idx].zip.rbuf[0] = '\0';
1578 My_Connections[Idx].zip.rdatalen = 0;
1579 My_Connections[Idx].zip.wbuf[0] = '\0';
1580 My_Connections[Idx].zip.wdatalen = 0;
1581 My_Connections[Idx].zip.bytes_in = 0;
1582 My_Connections[Idx].zip.bytes_out = 0;
1584 } /* Init_Conn_Struct */
1588 Init_Socket( INT Sock )
1590 /* Socket-Optionen setzen */
1594 #ifdef O_NONBLOCK /* A/UX kennt das nicht? */
1595 if( fcntl( Sock, F_SETFL, O_NONBLOCK ) != 0 )
1597 Log( LOG_CRIT, "Can't enable non-blocking mode: %s!", strerror( errno ));
1602 if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &on, (socklen_t)sizeof( on )) != 0)
1604 Log( LOG_ERR, "Can't set socket options: %s!", strerror( errno ));
1605 /* dieser Fehler kann ignoriert werden. */
1613 Read_Resolver_Result( INT r_fd )
1615 /* Ergebnis von Resolver Sub-Prozess aus Pipe lesen
1616 * und entsprechende Connection aktualisieren */
1618 CHAR result[HOST_LEN];
1622 FD_CLR( r_fd, &Resolver_FDs );
1624 /* Anfrage vom Parent lesen */
1625 len = read( r_fd, result, HOST_LEN - 1 );
1628 /* Fehler beim Lesen aus der Pipe */
1630 Log( LOG_CRIT, "Resolver: Can't read result: %s!", strerror( errno ));
1635 /* zugehoerige Connection suchen */
1636 for( i = 0; i < Pool_Size; i++ )
1638 if(( My_Connections[i].sock != NONE ) && ( My_Connections[i].res_stat ) && ( My_Connections[i].res_stat->pipe[0] == r_fd )) break;
1640 if( i >= Pool_Size )
1642 /* Opsa! Keine passende Connection gefunden!? Vermutlich
1643 * wurde sie schon wieder geschlossen. */
1645 Log( LOG_DEBUG, "Resolver: Got result for unknown connection!?" );
1649 Log( LOG_DEBUG, "Resolver: %s is \"%s\".", My_Connections[i].host, result );
1652 close( My_Connections[i].res_stat->pipe[0] );
1653 close( My_Connections[i].res_stat->pipe[1] );
1654 free( My_Connections[i].res_stat );
1655 My_Connections[i].res_stat = NULL;
1657 if( My_Connections[i].sock > NONE )
1659 /* Eingehende Verbindung: Hostnamen setzen */
1660 c = Client_GetFromConn( i );
1661 assert( c != NULL );
1662 strcpy( My_Connections[i].host, result );
1663 Client_SetHostname( c, result );
1665 Conn_WriteStr( i, "NOTICE AUTH :%sGot your hostname.", NOTICE_TXTPREFIX );
1669 /* Ausgehende Verbindung (=Server): IP setzen */
1670 assert( My_Connections[i].our_server > NONE );
1671 strcpy( Conf_Server[My_Connections[i].our_server].ip, result );
1674 /* Penalty-Zeit zurueck setzen */
1675 Conn_ResetPenalty( i );
1676 } /* Read_Resolver_Result */
1682 Zip_Buffer( CONN_ID Idx, CHAR *Data, INT Len )
1684 /* Daten zum Komprimieren im "Kompressions-Puffer" sammeln.
1685 * Es wird TRUE bei Erfolg, sonst FALSE geliefert. */
1687 assert( Idx > NONE );
1688 assert( Data != NULL );
1691 /* Ist noch Platz im Kompressions-Puffer? */
1692 if( ZWRITEBUFFER_LEN - My_Connections[Idx].zip.wdatalen < Len + 50 )
1694 /* Nein! Puffer zunaechst leeren ...*/
1695 if( ! Zip_Flush( Idx )) return FALSE;
1698 /* Daten kopieren */
1699 memmove( My_Connections[Idx].zip.wbuf + My_Connections[Idx].zip.wdatalen, Data, Len );
1700 My_Connections[Idx].zip.wdatalen += Len;
1707 Zip_Flush( CONN_ID Idx )
1709 /* Daten komprimieren und in Schreibpuffer kopieren.
1710 * Es wird TRUE bei Erfolg, sonst FALSE geliefert. */
1712 INT result, out_len;
1715 out = &My_Connections[Idx].zip.out;
1717 out->next_in = My_Connections[Idx].zip.wbuf;
1718 out->avail_in = My_Connections[Idx].zip.wdatalen;
1719 out->next_out = My_Connections[Idx].wbuf + My_Connections[Idx].wdatalen;
1720 out->avail_out = WRITEBUFFER_LEN - My_Connections[Idx].wdatalen;
1722 result = deflate( out, Z_SYNC_FLUSH );
1723 if(( result != Z_OK ) || ( out->avail_in > 0 ))
1725 Log( LOG_ALERT, "Compression error: code %d!?", result );
1726 Conn_Close( Idx, "Compression error!", NULL, FALSE );
1730 out_len = WRITEBUFFER_LEN - My_Connections[Idx].wdatalen - out->avail_out;
1731 My_Connections[Idx].wdatalen += out_len;
1732 My_Connections[Idx].bytes_out += out_len;
1733 My_Connections[Idx].zip.bytes_out += My_Connections[Idx].zip.wdatalen;
1734 My_Connections[Idx].zip.wdatalen = 0;
1741 Unzip_Buffer( CONN_ID Idx )
1743 /* Daten entpacken und in Lesepuffer kopieren. Bei Fehlern
1744 * wird FALSE geliefert, ansonsten TRUE. Der Fall, dass keine
1745 * Daten mehr zu entpacken sind, ist _kein_ Fehler! */
1747 INT result, in_len, out_len;
1750 assert( Idx > NONE );
1752 if( My_Connections[Idx].zip.rdatalen <= 0 ) return TRUE;
1754 in = &My_Connections[Idx].zip.in;
1756 in->next_in = My_Connections[Idx].zip.rbuf;
1757 in->avail_in = My_Connections[Idx].zip.rdatalen;
1758 in->next_out = My_Connections[Idx].rbuf + My_Connections[Idx].rdatalen;
1759 in->avail_out = READBUFFER_LEN - My_Connections[Idx].rdatalen - 1;
1761 result = inflate( in, Z_SYNC_FLUSH );
1762 if( result != Z_OK )
1764 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 );
1765 Conn_Close( Idx, "Decompression error!", NULL, FALSE );
1769 in_len = My_Connections[Idx].zip.rdatalen - in->avail_in;
1770 out_len = READBUFFER_LEN - My_Connections[Idx].rdatalen - 1 - in->avail_out;
1771 My_Connections[Idx].rdatalen += out_len;
1773 if( in->avail_in > 0 )
1775 /* es konnten nicht alle Daten entpackt werden, vermutlich war
1776 * im Ziel-Puffer kein Platz mehr. Umkopieren ... */
1777 My_Connections[Idx].zip.rdatalen -= in_len;
1778 memmove( My_Connections[Idx].zip.rbuf, My_Connections[Idx].zip.rbuf + in_len, My_Connections[Idx].zip.rdatalen );
1780 else My_Connections[Idx].zip.rdatalen = 0;
1781 My_Connections[Idx].zip.bytes_in += out_len;
1784 } /* Unzip_Buffer */