2 * ngIRCd -- The Next Generation IRC Daemon
3 * Copyright (c)2001,2002 by Alexander Barton (alex@barton.de)
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 * Please read the file COPYING, README and AUTHORS for more information.
11 * Connection management
17 static char UNUSED id[] = "$Id: conn.c,v 1.110 2002/12/27 13:20:13 alex Exp $";
28 #include <sys/socket.h>
30 #include <sys/types.h>
32 #include <netinet/in.h>
34 #ifdef HAVE_ARPA_INET_H
35 #include <arpa/inet.h>
37 #define PF_INET AF_INET
41 #include <stdint.h> /* u.a. fuer Mac OS X */
63 #define SERVER_WAIT (NONE - 1)
67 typedef struct _ZipData
69 z_stream in; /* "Handle" fuer Input-Stream */
70 z_stream out; /* "Handle" fuer Output-Stream */
71 CHAR rbuf[READBUFFER_LEN]; /* Lesepuffer */
72 INT rdatalen; /* Laenge der Daten im Lesepuffer (komprimiert) */
73 CHAR wbuf[WRITEBUFFER_LEN]; /* Schreibpuffer */
74 INT wdatalen; /* Laenge der Daten im Schreibpuffer (unkomprimiert) */
75 LONG bytes_in, bytes_out; /* Counter fuer Statistik (unkomprimiert!) */
80 typedef struct _Connection
82 INT sock; /* Socket Handle */
83 struct sockaddr_in addr; /* Adresse des Client */
84 RES_STAT *res_stat; /* "Resolver-Status", s.o. */
85 CHAR host[HOST_LEN]; /* Hostname */
86 CHAR rbuf[READBUFFER_LEN]; /* Lesepuffer */
87 INT rdatalen; /* Laenge der Daten im Lesepuffer */
88 CHAR wbuf[WRITEBUFFER_LEN]; /* Schreibpuffer */
89 INT wdatalen; /* Laenge der Daten im Schreibpuffer */
90 INT our_server; /* wenn von uns zu connectender Server: ID */
91 time_t starttime; /* Startzeit des Links */
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; /* Empfangene uns gesendete Bytes */
97 LONG msg_in, msg_out; /* Empfangene uns gesendete Nachtichten */
98 INT flag; /* "Markierungs-Flag" (vgl. "irc-write"-Modul) */
99 INT options; /* Link-Optionen */
101 ZIPDATA zip; /* Kompressionsinformationen */
106 LOCAL VOID Handle_Read PARAMS(( INT sock ));
107 LOCAL BOOLEAN Handle_Write PARAMS(( CONN_ID Idx ));
108 LOCAL VOID New_Connection PARAMS(( INT Sock ));
109 LOCAL CONN_ID Socket2Index PARAMS(( INT Sock ));
110 LOCAL VOID Read_Request PARAMS(( CONN_ID Idx ));
111 LOCAL BOOLEAN Try_Write PARAMS(( CONN_ID Idx ));
112 LOCAL BOOLEAN Handle_Buffer PARAMS(( CONN_ID Idx ));
113 LOCAL VOID Check_Connections PARAMS(( VOID ));
114 LOCAL VOID Check_Servers PARAMS(( VOID ));
115 LOCAL VOID Init_Conn_Struct PARAMS(( LONG Idx ));
116 LOCAL BOOLEAN Init_Socket PARAMS(( INT Sock ));
117 LOCAL VOID New_Server PARAMS(( INT Server, CONN_ID Idx ));
118 LOCAL VOID Read_Resolver_Result PARAMS(( INT r_fd ));
121 LOCAL BOOLEAN Zip_Buffer PARAMS(( CONN_ID Idx, CHAR *Data, INT Len ));
122 LOCAL BOOLEAN Zip_Flush PARAMS(( CONN_ID Idx ));
123 LOCAL BOOLEAN Unzip_Buffer PARAMS(( CONN_ID Idx ));
127 LOCAL fd_set My_Listeners;
128 LOCAL fd_set My_Sockets;
129 LOCAL fd_set My_Connects;
131 LOCAL CONNECTION *My_Connections;
132 LOCAL LONG Pool_Size, WCounter;
138 /* Modul initialisieren: statische Strukturen "ausnullen". */
142 /* Speicher fuer Verbindungs-Pool anfordern */
143 Pool_Size = CONNECTION_POOL;
144 if( Conf_MaxConnections > 0 )
146 /* konfiguriertes Limit beachten */
147 if( Pool_Size > Conf_MaxConnections ) Pool_Size = Conf_MaxConnections;
149 My_Connections = malloc( sizeof( CONNECTION ) * Pool_Size );
150 if( ! My_Connections )
152 /* Speicher konnte nicht alloziert werden! */
153 Log( LOG_EMERG, "Can't allocate memory! [Conn_Init]" );
156 Log( LOG_DEBUG, "Allocted connection pool for %ld items (%ld bytes).", Pool_Size, sizeof( CONNECTION ) * Pool_Size );
158 /* zu Beginn haben wir keine Verbindungen */
159 FD_ZERO( &My_Listeners );
160 FD_ZERO( &My_Sockets );
161 FD_ZERO( &My_Connects );
163 /* Groesster File-Descriptor fuer select() */
166 /* Connection-Struktur initialisieren */
167 for( i = 0; i < Pool_Size; i++ ) Init_Conn_Struct( i );
169 /* Global write counter */
177 /* Modul abmelden: alle noch offenen Connections
178 * schliessen und freigeben. */
183 /* Sockets schliessen */
184 Log( LOG_DEBUG, "Shutting down all connections ..." );
185 for( i = 0; i < Conn_MaxFD + 1; i++ )
187 if( FD_ISSET( i, &My_Sockets ))
189 for( idx = 0; idx < Pool_Size; idx++ )
191 if( My_Connections[idx].sock == i ) break;
193 if( FD_ISSET( i, &My_Listeners ))
196 Log( LOG_DEBUG, "Listening socket %d closed.", i );
198 else if( FD_ISSET( i, &My_Connects ))
201 Log( LOG_DEBUG, "Connection %d closed during creation (socket %d).", idx, i );
203 else if( idx < Pool_Size )
205 if( NGIRCd_SignalRestart ) Conn_Close( idx, NULL, "Server going down (restarting)", TRUE );
206 else Conn_Close( idx, NULL, "Server going down", TRUE );
210 Log( LOG_WARNING, "Closing unknown connection %d ...", i );
216 free( My_Connections );
217 My_Connections = NULL;
223 Conn_InitListeners( VOID )
225 /* Ports, auf denen der Server Verbindungen entgegennehmen
226 * soll, initialisieren */
231 for( i = 0; i < Conf_ListenPorts_Count; i++ )
233 if( Conn_NewListener( Conf_ListenPorts[i] )) created++;
234 else Log( LOG_ERR, "Can't listen on port %u!", Conf_ListenPorts[i] );
237 } /* Conn_InitListeners */
241 Conn_ExitListeners( VOID )
243 /* Alle "Listen-Sockets" schliessen */
247 Log( LOG_INFO, "Shutting down all listening sockets ..." );
248 for( i = 0; i < Conn_MaxFD + 1; i++ )
250 if( FD_ISSET( i, &My_Sockets ) && FD_ISSET( i, &My_Listeners ))
253 Log( LOG_DEBUG, "Listening socket %d closed.", i );
256 } /* Conn_ExitListeners */
260 Conn_NewListener( CONST UINT Port )
262 /* Neuen Listen-Socket erzeugen: der Server wartet dann auf
263 * dem angegebenen Port auf Verbindungen. Kann der Listen-
264 * Socket nicht erteugt werden, so wird NULL geliefert.*/
266 struct sockaddr_in addr;
269 /* Server-"Listen"-Socket initialisieren */
270 memset( &addr, 0, sizeof( addr ));
271 addr.sin_family = AF_INET;
272 addr.sin_port = htons( Port );
273 addr.sin_addr.s_addr = htonl( INADDR_ANY );
275 /* Socket erzeugen */
276 sock = socket( PF_INET, SOCK_STREAM, 0);
279 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
283 if( ! Init_Socket( sock )) return FALSE;
286 if( bind( sock, (struct sockaddr *)&addr, (socklen_t)sizeof( addr )) != 0 )
288 Log( LOG_CRIT, "Can't bind socket: %s!", strerror( errno ));
293 /* in "listen mode" gehen :-) */
294 if( listen( sock, 10 ) != 0 )
296 Log( LOG_CRIT, "Can't listen on soecket: %s!", strerror( errno ));
301 /* Neuen Listener in Strukturen einfuegen */
302 FD_SET( sock, &My_Listeners );
303 FD_SET( sock, &My_Sockets );
305 if( sock > Conn_MaxFD ) Conn_MaxFD = sock;
307 Log( LOG_INFO, "Now listening on port %d (socket %d).", Port, sock );
310 } /* Conn_NewListener */
316 /* "Hauptschleife": Aktive Verbindungen ueberwachen. Folgende Aktionen
317 * werden dabei durchgefuehrt, bis der Server terminieren oder neu
320 * - neue Verbindungen annehmen,
321 * - Server-Verbindungen aufbauen,
322 * - geschlossene Verbindungen loeschen,
323 * - volle Schreibpuffer versuchen zu schreiben,
324 * - volle Lesepuffer versuchen zu verarbeiten,
325 * - Antworten von Resolver Sub-Prozessen annehmen.
328 fd_set read_sockets, write_sockets;
334 start = time( NULL );
335 while(( ! NGIRCd_SignalQuit ) && ( ! NGIRCd_SignalRestart ))
339 /* Should the configuration be reloaded? */
340 if( NGIRCd_SignalRehash ) NGIRCd_Rehash( );
342 /* Check configured servers and established links */
344 Check_Connections( );
346 /* noch volle Lese-Buffer suchen */
347 for( i = 0; i < Pool_Size; i++ )
349 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].rdatalen > 0 ))
351 /* Kann aus dem Buffer noch ein Befehl extrahiert werden? */
352 if( Handle_Buffer( i )) timeout = FALSE;
356 /* noch volle Schreib-Puffer suchen */
357 FD_ZERO( &write_sockets );
358 for( i = 0; i < Pool_Size; i++ )
361 if(( My_Connections[i].sock > NONE ) && (( My_Connections[i].wdatalen > 0 ) || ( My_Connections[i].zip.wdatalen > 0 )))
363 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].wdatalen > 0 ))
366 /* Socket der Verbindung in Set aufnehmen */
367 FD_SET( My_Connections[i].sock, &write_sockets );
370 /* Sockets mit im Aufbau befindlichen ausgehenden Verbindungen suchen */
371 for( i = 0; i < Pool_Size; i++ )
373 if(( My_Connections[i].sock > NONE ) && ( FD_ISSET( My_Connections[i].sock, &My_Connects ))) FD_SET( My_Connections[i].sock, &write_sockets );
376 /* von welchen Sockets koennte gelesen werden? */
378 read_sockets = My_Sockets;
379 for( i = 0; i < Pool_Size; i++ )
381 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].host[0] == '\0' ))
383 /* Hier muss noch auf den Resolver Sub-Prozess gewartet werden */
384 FD_CLR( My_Connections[i].sock, &read_sockets );
386 if(( My_Connections[i].sock > NONE ) && ( FD_ISSET( My_Connections[i].sock, &My_Connects )))
388 /* Hier laeuft noch ein asyncrones connect() */
389 FD_CLR( My_Connections[i].sock, &read_sockets );
391 if( My_Connections[i].delaytime > t )
393 /* Fuer die Verbindung ist eine "Penalty-Zeit" gesetzt */
394 FD_CLR( My_Connections[i].sock, &read_sockets );
395 FD_CLR( My_Connections[i].sock, &write_sockets );
398 for( i = 0; i < Conn_MaxFD + 1; i++ )
400 /* Pipes von Resolver Sub-Prozessen aufnehmen */
401 if( FD_ISSET( i, &Resolver_FDs ))
403 FD_SET( i, &read_sockets );
407 /* Timeout initialisieren */
409 if( timeout ) tv.tv_sec = TIME_RES;
412 /* Auf Aktivitaet warten */
413 i = select( Conn_MaxFD + 1, &read_sockets, &write_sockets, NULL, &tv );
416 /* keine Veraenderung an den Sockets */
421 /* Fehler (z.B. Interrupt) */
424 Log( LOG_EMERG, "Conn_Handler(): select(): %s!", strerror( errno ));
425 Log( LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE );
431 /* Koennen Daten geschrieben werden? */
432 for( i = 0; i < Conn_MaxFD + 1; i++ )
434 if( ! FD_ISSET( i, &write_sockets )) continue;
436 /* Es kann geschrieben werden ... */
437 idx = Socket2Index( i );
438 if( idx == NONE ) continue;
440 if( ! Handle_Write( idx ))
442 /* Fehler beim Schreiben! Diesen Socket nun
443 * auch aus dem Read-Set entfernen: */
444 FD_CLR( i, &read_sockets );
448 /* Daten zum Lesen vorhanden? */
449 for( i = 0; i < Conn_MaxFD + 1; i++ )
451 if( FD_ISSET( i, &read_sockets )) Handle_Read( i );
455 if( NGIRCd_SignalQuit ) Log( LOG_NOTICE|LOG_snotice, "Server going down NOW!" );
456 else if( NGIRCd_SignalRestart ) Log( LOG_NOTICE|LOG_snotice, "Server restarting NOW!" );
462 Conn_WriteStr( CONN_ID Idx, CHAR *Format, ... )
465 Conn_WriteStr( Idx, Format, va_alist )
471 /* String in Socket schreiben. CR+LF wird von dieser Funktion
472 * automatisch angehaengt. Im Fehlerfall wird dir Verbindung
473 * getrennt und FALSE geliefert. */
475 CHAR buffer[COMMAND_LEN];
479 assert( Idx > NONE );
480 assert( Format != NULL );
483 va_start( ap, Format );
487 if( vsnprintf( buffer, COMMAND_LEN - 2, Format, ap ) == COMMAND_LEN - 2 )
489 Log( LOG_CRIT, "Text too long to send (connection %d)!", Idx );
490 Conn_Close( Idx, "Text too long to send!", NULL, FALSE );
495 if( NGIRCd_Sniffer ) Log( LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer );
498 strlcat( buffer, "\r\n", sizeof( buffer ));
499 ok = Conn_Write( Idx, buffer, strlen( buffer ));
500 My_Connections[Idx].msg_out++;
504 } /* Conn_WriteStr */
508 Conn_Write( CONN_ID Idx, CHAR *Data, INT Len )
510 /* Daten in Socket schreiben. Bei "fatalen" Fehlern wird
511 * der Client disconnectiert und FALSE geliefert. */
513 assert( Idx > NONE );
514 assert( Data != NULL );
517 /* Ist der entsprechende Socket ueberhaupt noch offen? In einem
518 * "Handler-Durchlauf" kann es passieren, dass dem nicht mehr so
519 * ist, wenn einer von mehreren Conn_Write()'s fehlgeschlagen ist.
520 * In diesem Fall wird hier einfach ein Fehler geliefert. */
521 if( My_Connections[Idx].sock <= NONE )
523 Log( LOG_DEBUG, "Skipped write on closed socket (connection %d).", Idx );
527 /* Pruefen, ob im Schreibpuffer genuegend Platz ist. Ziel ist es,
528 * moeglichts viel im Puffer zu haben und _nicht_ gleich alles auf den
529 * Socket zu schreiben (u.a. wg. Komprimierung). */
530 if( WRITEBUFFER_LEN - My_Connections[Idx].wdatalen - Len <= 0 )
532 /* Der Puffer ist dummerweise voll. Jetzt versuchen, den Puffer
533 * zu schreiben, wenn das nicht klappt, haben wir ein Problem ... */
534 if( ! Try_Write( Idx )) return FALSE;
536 /* nun neu pruefen: */
537 if( WRITEBUFFER_LEN - My_Connections[Idx].wdatalen - Len <= 0 )
539 Log( LOG_NOTICE, "Write buffer overflow (connection %d)!", Idx );
540 Conn_Close( Idx, "Write buffer overflow!", NULL, FALSE );
546 if( My_Connections[Idx].options & CONN_ZIP )
548 /* Daten komprimieren und in Puffer kopieren */
549 if( ! Zip_Buffer( Idx, Data, Len )) return FALSE;
554 /* Daten in Puffer kopieren */
555 memcpy( My_Connections[Idx].wbuf + My_Connections[Idx].wdatalen, Data, Len );
556 My_Connections[Idx].wdatalen += Len;
557 My_Connections[Idx].bytes_out += Len;
560 /* Adjust global write counter */
568 Conn_Close( CONN_ID Idx, CHAR *LogMsg, CHAR *FwdMsg, BOOLEAN InformClient )
570 /* Close connection. Open pipes of asyncronous resolver
571 * sub-processes are closed down. */
576 DOUBLE in_z_k, out_z_k;
580 assert( Idx > NONE );
581 assert( My_Connections[Idx].sock > NONE );
583 /* Search client, if any */
584 c = Client_GetFromConn( Idx );
586 /* Should the client be informed? */
590 /* Send statistics to client if registered as user: */
591 if(( c != NULL ) && ( Client_Type( c ) == CLIENT_USER ))
593 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 );
597 /* Send ERROR to client (see RFC!) */
598 if( FwdMsg ) Conn_WriteStr( Idx, "ERROR :%s", FwdMsg );
599 else Conn_WriteStr( Idx, "ERROR :Closing connection." );
600 if( My_Connections[Idx].sock == NONE ) return;
603 /* Try to write out the write buffer */
606 /* Shut down socket */
607 if( close( My_Connections[Idx].sock ) != 0 )
609 /* Oops, we can't close the socket!? This is fatal! */
610 Log( LOG_EMERG, "Error closing connection %d (socket %d) with %s:%d - %s!", Idx, My_Connections[Idx].sock, My_Connections[Idx].host, ntohs( My_Connections[Idx].addr.sin_port), strerror( errno ));
611 Log( LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE );
615 /* Mark socket as invalid: */
616 FD_CLR( My_Connections[Idx].sock, &My_Sockets );
617 FD_CLR( My_Connections[Idx].sock, &My_Connects );
618 My_Connections[Idx].sock = NONE;
620 /* If there is still a client, unregister it now */
621 if( c ) Client_Destroy( c, LogMsg, FwdMsg, TRUE );
623 /* Calculate statistics and log information */
624 in_k = (DOUBLE)My_Connections[Idx].bytes_in / 1024;
625 out_k = (DOUBLE)My_Connections[Idx].bytes_out / 1024;
627 if( My_Connections[Idx].options & CONN_ZIP )
629 in_z_k = (DOUBLE)My_Connections[Idx].zip.bytes_in / 1024;
630 out_z_k = (DOUBLE)My_Connections[Idx].zip.bytes_out / 1024;
631 in_p = (INT)(( in_k * 100 ) / in_z_k );
632 out_p = (INT)(( out_k * 100 ) / out_z_k );
633 Log( LOG_INFO, "Connection %d with %s:%d closed (in: %.1fk/%.1fk/%d%%, out: %.1fk/%.1fk/%d%%).", Idx, My_Connections[Idx].host, ntohs( My_Connections[Idx].addr.sin_port ), in_k, in_z_k, in_p, out_k, out_z_k, out_p );
638 Log( LOG_INFO, "Connection %d with %s:%d closed (in: %.1fk, out: %.1fk).", Idx, My_Connections[Idx].host, ntohs( My_Connections[Idx].addr.sin_port ), in_k, out_k );
641 /* Is there a resolver sub-process running? */
642 if( My_Connections[Idx].res_stat )
644 /* Free resolver structures */
645 FD_CLR( My_Connections[Idx].res_stat->pipe[0], &Resolver_FDs );
646 close( My_Connections[Idx].res_stat->pipe[0] );
647 close( My_Connections[Idx].res_stat->pipe[1] );
648 free( My_Connections[Idx].res_stat );
651 /* Servers: Modify time of next connect attempt? */
652 if(( My_Connections[Idx].our_server > NONE ) && ( Conf_Server[My_Connections[Idx].our_server].lasttry < time( NULL ) - Conf_ConnectRetry ))
654 /* Okay, die Verbindung stand schon "genuegend lange":
655 * lasttry-Zeitpunkt so setzen, dass der naechste
656 * Verbindungsversuch in RECONNECT_DELAY Sekunden
658 Conf_Server[My_Connections[Idx].our_server].lasttry = time( NULL ) - Conf_ConnectRetry + RECONNECT_DELAY;
662 /* Clean up zlib, if link was compressed */
663 if( Conn_Options( Idx ) & CONN_ZIP )
665 inflateEnd( &My_Connections[Idx].zip.in );
666 deflateEnd( &My_Connections[Idx].zip.out );
670 /* Clean up connection structure (=free it) */
671 Init_Conn_Struct( Idx );
676 Conn_UpdateIdle( CONN_ID Idx )
678 /* Idle-Timer zuruecksetzen */
680 assert( Idx > NONE );
681 My_Connections[Idx].lastprivmsg = time( NULL );
686 Conn_GetIdle( CONN_ID Idx )
688 /* Idle-Time einer Verbindung liefern (in Sekunden) */
690 assert( Idx > NONE );
691 return time( NULL ) - My_Connections[Idx].lastprivmsg;
696 Conn_LastPing( CONN_ID Idx )
698 /* Zeitpunkt des letzten PING liefern */
700 assert( Idx > NONE );
701 return My_Connections[Idx].lastping;
702 } /* Conn_LastPing */
706 Conn_SetPenalty( CONN_ID Idx, time_t Seconds )
708 /* Penalty-Delay fuer eine Verbindung (in Sekunden) setzen;
709 * waehrend dieser Zeit wird der entsprechende Socket vom Server
710 * bei Lese-Operationen komplett ignoriert. Der Delay kann mit
711 * dieser Funktion nur erhoeht, nicht aber verringert werden. */
715 assert( Idx > NONE );
716 assert( Seconds >= 0 );
718 t = time( NULL ) + Seconds;
719 if( t > My_Connections[Idx].delaytime ) My_Connections[Idx].delaytime = t;
720 } /* Conn_SetPenalty */
724 Conn_ResetPenalty( CONN_ID Idx )
726 assert( Idx > NONE );
727 My_Connections[Idx].delaytime = 0;
728 } /* Conn_ResetPenalty */
732 Conn_ClearFlags( VOID )
734 /* Alle Connection auf "nicht-markiert" setzen */
738 for( i = 0; i < Pool_Size; i++ ) My_Connections[i].flag = 0;
739 } /* Conn_ClearFlags */
743 Conn_Flag( CONN_ID Idx )
745 /* Ist eine Connection markiert (TRUE) oder nicht? */
747 assert( Idx > NONE );
748 return My_Connections[Idx].flag;
753 Conn_SetFlag( CONN_ID Idx, INT Flag )
755 /* Connection markieren */
757 assert( Idx > NONE );
758 My_Connections[Idx].flag = Flag;
765 /* Connection-Struktur der ersten Verbindung liefern;
766 * Ist keine Verbindung vorhanden, wird NONE geliefert. */
770 for( i = 0; i < Pool_Size; i++ )
772 if( My_Connections[i].sock != NONE ) return i;
779 Conn_Next( CONN_ID Idx )
781 /* Naechste Verbindungs-Struktur liefern; existiert keine
782 * weitere, so wird NONE geliefert. */
786 assert( Idx > NONE );
788 for( i = Idx + 1; i < Pool_Size; i++ )
790 if( My_Connections[i].sock != NONE ) return i;
797 Conn_SetServer( CONN_ID Idx, INT ConfServer )
799 /* Connection als Server markieren: Index des konfigurierten
800 * Servers speichern. Verbindung muss bereits bestehen! */
802 assert( Idx > NONE );
803 assert( My_Connections[Idx].sock > NONE );
805 My_Connections[Idx].our_server = ConfServer;
806 } /* Conn_SetServer */
810 Conn_SetOption( CONN_ID Idx, INT Option )
812 /* Option fuer Verbindung setzen.
813 * Initial sind alle Optionen _nicht_ gesetzt. */
815 assert( Idx > NONE );
816 assert( Option != 0 );
818 My_Connections[Idx].options |= Option;
819 } /* Conn_SetOption */
823 Conn_UnsetOption( CONN_ID Idx, INT Option )
825 /* Option fuer Verbindung loeschen */
827 assert( Idx > NONE );
828 assert( Option != 0 );
830 My_Connections[Idx].options &= ~Option;
831 } /* Conn_UnsetOption */
835 Conn_Options( CONN_ID Idx )
837 assert( Idx > NONE );
838 return My_Connections[Idx].options;
845 Conn_InitZip( CONN_ID Idx )
847 /* Kompression fuer Link initialisieren */
849 assert( Idx > NONE );
851 My_Connections[Idx].zip.in.avail_in = 0;
852 My_Connections[Idx].zip.in.total_in = 0;
853 My_Connections[Idx].zip.in.total_out = 0;
854 My_Connections[Idx].zip.in.zalloc = NULL;
855 My_Connections[Idx].zip.in.zfree = NULL;
856 My_Connections[Idx].zip.in.data_type = Z_ASCII;
858 if( inflateInit( &My_Connections[Idx].zip.in ) != Z_OK )
861 Log( LOG_ALERT, "Can't initialize compression on connection %d (zlib inflate)!", Idx );
865 My_Connections[Idx].zip.out.total_in = 0;
866 My_Connections[Idx].zip.out.total_in = 0;
867 My_Connections[Idx].zip.out.zalloc = NULL;
868 My_Connections[Idx].zip.out.zfree = NULL;
869 My_Connections[Idx].zip.out.data_type = Z_ASCII;
871 if( deflateInit( &My_Connections[Idx].zip.out, Z_DEFAULT_COMPRESSION ) != Z_OK )
874 Log( LOG_ALERT, "Can't initialize compression on connection %d (zlib deflate)!", Idx );
878 My_Connections[Idx].zip.bytes_in = My_Connections[Idx].bytes_in;
879 My_Connections[Idx].zip.bytes_out = My_Connections[Idx].bytes_out;
881 Log( LOG_INFO, "Enabled link compression (zlib) on connection %d.", Idx );
882 Conn_SetOption( Idx, CONN_ZIP );
889 Conn_SendBytesZip( CONN_ID Idx )
891 /* Anzahl gesendeter Bytes (komprimiert!) liefern */
893 assert( Idx > NONE );
894 return My_Connections[Idx].zip.bytes_out;
895 } /* Conn_SendBytesZip */
899 Conn_RecvBytesZip( CONN_ID Idx )
901 /* Anzahl gesendeter Bytes (komprimiert!) liefern */
903 assert( Idx > NONE );
904 return My_Connections[Idx].zip.bytes_in;
905 } /* Conn_RecvBytesZip */
911 Conn_StartTime( CONN_ID Idx )
913 /* Zeitpunkt des Link-Starts liefern (in Sekunden) */
915 assert( Idx > NONE );
916 return My_Connections[Idx].starttime;
921 Conn_SendQ( CONN_ID Idx )
923 /* Laenge der Daten im Schreibbuffer liefern */
925 assert( Idx > NONE );
927 if( My_Connections[Idx].options & CONN_ZIP ) return My_Connections[Idx].zip.wdatalen;
930 return My_Connections[Idx].wdatalen;
935 Conn_SendMsg( CONN_ID Idx )
937 /* Anzahl gesendeter Nachrichten liefern */
939 assert( Idx > NONE );
940 return My_Connections[Idx].msg_out;
945 Conn_SendBytes( CONN_ID Idx )
947 /* Anzahl gesendeter Bytes (unkomprimiert) liefern */
949 assert( Idx > NONE );
950 return My_Connections[Idx].bytes_out;
951 } /* Conn_SendBytes */
955 Conn_RecvQ( CONN_ID Idx )
957 /* Laenge der Daten im Lesebuffer liefern */
959 assert( Idx > NONE );
961 if( My_Connections[Idx].options & CONN_ZIP ) return My_Connections[Idx].zip.rdatalen;
964 return My_Connections[Idx].rdatalen;
969 Conn_RecvMsg( CONN_ID Idx )
971 /* Anzahl empfangener Nachrichten liefern */
973 assert( Idx > NONE );
974 return My_Connections[Idx].msg_in;
979 Conn_RecvBytes( CONN_ID Idx )
981 /* Anzahl empfangener Bytes (unkomprimiert) liefern */
983 assert( Idx > NONE );
984 return My_Connections[Idx].bytes_in;
985 } /* Conn_RecvBytes */
989 Conn_ResetWCounter( VOID )
992 } /* Conn_ResetWCounter */
996 Conn_WCounter( VOID )
999 } /* Conn_WCounter */
1003 Try_Write( CONN_ID Idx )
1005 /* Versuchen, Daten aus dem Schreib-Puffer in den Socket zu
1006 * schreiben. TRUE wird geliefert, wenn entweder keine Daten
1007 * zum Versenden vorhanden sind oder erfolgreich bearbeitet
1008 * werden konnten. Im Fehlerfall wird FALSE geliefert und
1009 * die Verbindung geschlossen. */
1011 fd_set write_socket;
1014 assert( Idx > NONE );
1015 assert( My_Connections[Idx].sock > NONE );
1017 /* sind ueberhaupt Daten vorhanden? */
1019 if(( ! My_Connections[Idx].wdatalen > 0 ) && ( ! My_Connections[Idx].zip.wdatalen )) return TRUE;
1021 if( ! My_Connections[Idx].wdatalen > 0 ) return TRUE;
1024 /* Timeout initialisieren: 0 Sekunden, also nicht blockieren */
1025 tv.tv_sec = 0; tv.tv_usec = 0;
1027 FD_ZERO( &write_socket );
1028 FD_SET( My_Connections[Idx].sock, &write_socket );
1029 if( select( My_Connections[Idx].sock + 1, NULL, &write_socket, NULL, &tv ) == -1 )
1032 if( errno != EINTR )
1034 Log( LOG_ALERT, "Try_Write(): select() failed: %s (con=%d, sock=%d)!", strerror( errno ), Idx, My_Connections[Idx].sock );
1035 Conn_Close( Idx, "Server error!", NULL, FALSE );
1040 if( FD_ISSET( My_Connections[Idx].sock, &write_socket )) return Handle_Write( Idx );
1046 Handle_Read( INT Sock )
1048 /* Aktivitaet auf einem Socket verarbeiten:
1049 * - neue Clients annehmen,
1050 * - Daten von Clients verarbeiten,
1051 * - Resolver-Rueckmeldungen annehmen. */
1055 assert( Sock > NONE );
1057 if( FD_ISSET( Sock, &My_Listeners ))
1059 /* es ist einer unserer Listener-Sockets: es soll
1060 * also eine neue Verbindung aufgebaut werden. */
1062 New_Connection( Sock );
1064 else if( FD_ISSET( Sock, &Resolver_FDs ))
1066 /* Rueckmeldung von einem Resolver Sub-Prozess */
1068 Read_Resolver_Result( Sock );
1072 /* Ein Client Socket: entweder ein User oder Server */
1074 idx = Socket2Index( Sock );
1075 if( idx > NONE ) Read_Request( idx );
1081 Handle_Write( CONN_ID Idx )
1083 /* Daten aus Schreibpuffer versenden bzw. Connection aufbauen */
1087 assert( Idx > NONE );
1088 assert( My_Connections[Idx].sock > NONE );
1090 if( FD_ISSET( My_Connections[Idx].sock, &My_Connects ))
1092 /* es soll nichts geschrieben werden, sondern ein
1093 * connect() hat ein Ergebnis geliefert */
1095 FD_CLR( My_Connections[Idx].sock, &My_Connects );
1097 /* Ergebnis des connect() ermitteln */
1098 len = sizeof( err );
1099 res = getsockopt( My_Connections[Idx].sock, SOL_SOCKET, SO_ERROR, &err, &len );
1100 assert( len == sizeof( err ));
1102 /* Fehler aufgetreten? */
1103 if(( res != 0 ) || ( err != 0 ))
1106 if( res != 0 ) Log( LOG_CRIT, "getsockopt (connection %d): %s!", Idx, strerror( errno ));
1107 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 ));
1109 /* Socket etc. pp. aufraeumen */
1110 FD_CLR( My_Connections[Idx].sock, &My_Sockets );
1111 close( My_Connections[Idx].sock );
1112 Init_Conn_Struct( Idx );
1114 /* Bei Server-Verbindungen lasttry-Zeitpunkt auf "jetzt" setzen */
1115 Conf_Server[My_Connections[Idx].our_server].lasttry = time( NULL );
1119 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 );
1121 /* PASS und SERVER verschicken */
1122 Conn_WriteStr( Idx, "PASS %s %s", Conf_Server[My_Connections[Idx].our_server].pwd_out, NGIRCd_ProtoID );
1123 return Conn_WriteStr( Idx, "SERVER %s :%s", Conf_ServerName, Conf_ServerInfo );
1127 /* Schreibpuffer leer, aber noch Daten im Kompressionsbuffer?
1128 * Dann muss dieser nun geflushed werden! */
1129 if( My_Connections[Idx].wdatalen == 0 ) Zip_Flush( Idx );
1132 assert( My_Connections[Idx].wdatalen > 0 );
1134 /* Daten schreiben */
1135 len = send( My_Connections[Idx].sock, My_Connections[Idx].wbuf, My_Connections[Idx].wdatalen, 0 );
1138 /* Operation haette Socket "nur" blockiert ... */
1139 if( errno == EAGAIN ) return TRUE;
1141 /* Oops, ein Fehler! */
1142 Log( LOG_ERR, "Write error on connection %d (socket %d): %s!", Idx, My_Connections[Idx].sock, strerror( errno ));
1143 Conn_Close( Idx, "Write error!", NULL, FALSE );
1147 /* Puffer anpassen */
1148 My_Connections[Idx].wdatalen -= len;
1149 memmove( My_Connections[Idx].wbuf, My_Connections[Idx].wbuf + len, My_Connections[Idx].wdatalen );
1152 } /* Handle_Write */
1156 New_Connection( INT Sock )
1158 /* Neue Client-Verbindung von Listen-Socket annehmen und
1159 * CLIENT-Struktur anlegen. */
1161 struct sockaddr_in new_addr;
1162 INT new_sock, new_sock_len;
1169 assert( Sock > NONE );
1171 /* Connection auf Listen-Socket annehmen */
1172 new_sock_len = sizeof( new_addr );
1173 new_sock = accept( Sock, (struct sockaddr *)&new_addr, (socklen_t *)&new_sock_len );
1176 Log( LOG_CRIT, "Can't accept connection: %s!", strerror( errno ));
1180 /* Socket initialisieren */
1181 Init_Socket( new_sock );
1183 /* Freie Connection-Struktur suchen */
1184 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
1185 if( idx >= Pool_Size )
1187 new_size = Pool_Size + CONNECTION_POOL;
1189 /* Im bisherigen Pool wurde keine freie Connection-Struktur mehr gefunden.
1190 * Wenn erlaubt und moeglich muss nun der Pool vergroessert werden: */
1192 if( Conf_MaxConnections > 0 )
1194 /* Es ist ein Limit konfiguriert */
1195 if( Pool_Size >= Conf_MaxConnections )
1197 /* Mehr Verbindungen duerfen wir leider nicht mehr annehmen ... */
1198 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached!", Pool_Size );
1202 if( new_size > Conf_MaxConnections ) new_size = Conf_MaxConnections;
1205 /* zunaechst realloc() versuchen; wenn das scheitert, malloc() versuchen
1206 * und Daten ggf. "haendisch" umkopieren. (Haesslich! Eine wirklich
1207 * dynamische Verwaltung waere wohl _deutlich_ besser ...) */
1208 ptr = realloc( My_Connections, sizeof( CONNECTION ) * new_size );
1211 /* realloc() ist fehlgeschlagen. Nun malloc() probieren: */
1212 ptr = malloc( sizeof( CONNECTION ) * new_size );
1215 /* Offenbar steht kein weiterer Sepeicher zur Verfuegung :-( */
1216 Log( LOG_EMERG, "Can't allocate memory! [New_Connection]" );
1221 /* Struktur umkopieren ... */
1222 memcpy( ptr, My_Connections, sizeof( CONNECTION ) * Pool_Size );
1224 Log( LOG_DEBUG, "Allocated new connection pool for %ld items (%ld bytes). [malloc()/memcpy()]", new_size, sizeof( CONNECTION ) * new_size );
1226 else Log( LOG_DEBUG, "Allocated new connection pool for %ld items (%ld bytes). [realloc()]", new_size, sizeof( CONNECTION ) * new_size );
1228 /* Adjust pointer to new block */
1229 My_Connections = ptr;
1231 /* Initialize new items */
1232 for( idx = Pool_Size; idx < new_size; idx++ ) Init_Conn_Struct( idx );
1235 /* Adjust new pool size */
1236 Pool_Size = new_size;
1239 /* Client-Struktur initialisieren */
1240 c = Client_NewLocal( idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWN, FALSE );
1243 Log( LOG_ALERT, "Can't accept connection: can't create client structure!" );
1248 /* Verbindung registrieren */
1249 Init_Conn_Struct( idx );
1250 My_Connections[idx].sock = new_sock;
1251 My_Connections[idx].addr = new_addr;
1253 /* Neuen Socket registrieren */
1254 FD_SET( new_sock, &My_Sockets );
1255 if( new_sock > Conn_MaxFD ) Conn_MaxFD = new_sock;
1257 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 );
1259 /* Hostnamen ermitteln */
1260 strlcpy( My_Connections[idx].host, inet_ntoa( new_addr.sin_addr ), sizeof( My_Connections[idx].host ));
1261 Client_SetHostname( c, My_Connections[idx].host );
1262 s = Resolve_Addr( &new_addr );
1265 /* Sub-Prozess wurde asyncron gestartet */
1266 My_Connections[idx].res_stat = s;
1269 /* Penalty-Zeit setzen */
1270 Conn_SetPenalty( idx, 4 );
1271 } /* New_Connection */
1275 Socket2Index( INT Sock )
1277 /* zum Socket passende Connection suchen */
1281 assert( Sock > NONE );
1283 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == Sock ) break;
1285 if( idx >= Pool_Size )
1287 /* die Connection wurde vermutlich (wegen eines
1288 * Fehlers) bereits wieder abgebaut ... */
1289 Log( LOG_DEBUG, "Socket2Index: can't get connection for socket %d!", Sock );
1293 } /* Socket2Index */
1297 Read_Request( CONN_ID Idx )
1299 /* Daten von Socket einlesen und entsprechend behandeln.
1300 * Tritt ein Fehler auf, so wird der Socket geschlossen. */
1307 assert( Idx > NONE );
1308 assert( My_Connections[Idx].sock > NONE );
1310 /* wenn noch nicht registriert: maximal mit ZREADBUFFER_LEN arbeiten,
1311 * ansonsten koennen Daten ggf. nicht umkopiert werden. */
1312 bsize = READBUFFER_LEN;
1314 c = Client_GetFromConn( Idx );
1315 if(( Client_Type( c ) != CLIENT_USER ) && ( Client_Type( c ) != CLIENT_SERVER ) && ( Client_Type( c ) != CLIENT_SERVICE ) && ( bsize > ZREADBUFFER_LEN )) bsize = ZREADBUFFER_LEN;
1319 if(( bsize - My_Connections[Idx].rdatalen - 1 < 1 ) || ( ZREADBUFFER_LEN - My_Connections[Idx].zip.rdatalen < 1 ))
1321 if( bsize - My_Connections[Idx].rdatalen - 1 < 1 )
1324 /* Der Lesepuffer ist voll */
1325 Log( LOG_ERR, "Read buffer overflow (connection %d): %d bytes!", Idx, My_Connections[Idx].rdatalen );
1326 Conn_Close( Idx, "Read buffer overflow!", NULL, FALSE );
1331 if( My_Connections[Idx].options & CONN_ZIP )
1333 len = recv( My_Connections[Idx].sock, My_Connections[Idx].zip.rbuf + My_Connections[Idx].zip.rdatalen, ( ZREADBUFFER_LEN - My_Connections[Idx].zip.rdatalen ), 0 );
1334 if( len > 0 ) My_Connections[Idx].zip.rdatalen += len;
1339 len = recv( My_Connections[Idx].sock, My_Connections[Idx].rbuf + My_Connections[Idx].rdatalen, bsize - My_Connections[Idx].rdatalen - 1, 0 );
1340 if( len > 0 ) My_Connections[Idx].rdatalen += len;
1345 /* Socket wurde geschlossen */
1346 Log( LOG_INFO, "%s:%d (%s) is closing the connection ...", My_Connections[Idx].host, ntohs( My_Connections[Idx].addr.sin_port), inet_ntoa( My_Connections[Idx].addr.sin_addr ));
1347 Conn_Close( Idx, "Socket closed!", "Client closed connection", FALSE );
1353 /* Operation haette Socket "nur" blockiert ... */
1354 if( errno == EAGAIN ) return;
1356 /* Fehler beim Lesen */
1357 Log( LOG_ERR, "Read error on connection %d (socket %d): %s!", Idx, My_Connections[Idx].sock, strerror( errno ));
1358 Conn_Close( Idx, "Read error!", "Client closed connection", FALSE );
1362 /* Connection-Statistik aktualisieren */
1363 My_Connections[Idx].bytes_in += len;
1365 /* Timestamp aktualisieren */
1366 My_Connections[Idx].lastdata = time( NULL );
1368 Handle_Buffer( Idx );
1369 } /* Read_Request */
1373 Handle_Buffer( CONN_ID Idx )
1375 /* Daten im Lese-Puffer einer Verbindung verarbeiten.
1376 * Wurde ein Request verarbeitet, so wird TRUE geliefert,
1377 * ansonsten FALSE (auch bei Fehlern). */
1384 BOOLEAN action, result;
1393 /* ggf. noch unkomprimiete Daten weiter entpacken */
1394 if( My_Connections[Idx].options & CONN_ZIP )
1396 if( ! Unzip_Buffer( Idx )) return FALSE;
1400 if( My_Connections[Idx].rdatalen < 1 ) break;
1402 /* Eine komplette Anfrage muss mit CR+LF enden, vgl.
1403 * RFC 2812. Haben wir eine? */
1404 My_Connections[Idx].rbuf[My_Connections[Idx].rdatalen] = '\0';
1405 ptr = strstr( My_Connections[Idx].rbuf, "\r\n" );
1407 if( ptr ) delta = 2;
1411 /* Nicht RFC-konforme Anfrage mit nur CR oder LF? Leider
1412 * machen soetwas viele Clients, u.a. "mIRC" :-( */
1413 ptr1 = strchr( My_Connections[Idx].rbuf, '\r' );
1414 ptr2 = strchr( My_Connections[Idx].rbuf, '\n' );
1416 if( ptr1 && ptr2 ) ptr = ptr1 > ptr2 ? ptr2 : ptr1;
1417 else if( ptr1 ) ptr = ptr1;
1418 else if( ptr2 ) ptr = ptr2;
1425 /* Ende der Anfrage wurde gefunden */
1427 len = ( ptr - My_Connections[Idx].rbuf ) + delta;
1428 if( len > ( COMMAND_LEN - 1 ))
1430 /* Eine Anfrage darf(!) nicht laenger als 512 Zeichen
1431 * (incl. CR+LF!) werden; vgl. RFC 2812. Wenn soetwas
1432 * empfangen wird, wird der Client disconnectiert. */
1433 Log( LOG_ERR, "Request too long (connection %d): %d bytes (max. %d expected)!", Idx, My_Connections[Idx].rdatalen, COMMAND_LEN - 1 );
1434 Conn_Close( Idx, NULL, "Request too long", TRUE );
1439 /* merken, ob Stream bereits komprimiert wird */
1440 old_z = My_Connections[Idx].options & CONN_ZIP;
1445 /* Es wurde ein Request gelesen */
1446 My_Connections[Idx].msg_in++;
1447 if( ! Parse_Request( Idx, My_Connections[Idx].rbuf )) return FALSE;
1451 /* Puffer anpassen */
1452 My_Connections[Idx].rdatalen -= len;
1453 memmove( My_Connections[Idx].rbuf, My_Connections[Idx].rbuf + len, My_Connections[Idx].rdatalen );
1456 if(( ! old_z ) && ( My_Connections[Idx].options & CONN_ZIP ) && ( My_Connections[Idx].rdatalen > 0 ))
1458 /* Mit dem letzten Befehl wurde Socket-Kompression aktiviert.
1459 * Evtl. schon vom Socket gelesene Daten in den Unzip-Puffer
1460 * umkopieren, damit diese nun zunaechst entkomprimiert werden */
1462 if( My_Connections[Idx].rdatalen > ZREADBUFFER_LEN )
1464 /* Hupsa! Soviel Platz haben wir aber gar nicht! */
1465 Log( LOG_ALERT, "Can't move read buffer: No space left in unzip buffer (need %d bytes)!", My_Connections[Idx].rdatalen );
1468 memcpy( My_Connections[Idx].zip.rbuf, My_Connections[Idx].rbuf, My_Connections[Idx].rdatalen );
1469 My_Connections[Idx].zip.rdatalen = My_Connections[Idx].rdatalen;
1470 My_Connections[Idx].rdatalen = 0;
1471 Log( LOG_DEBUG, "Moved already received data (%d bytes) to uncompression buffer.", My_Connections[Idx].zip.rdatalen );
1477 if( action ) result = TRUE;
1481 } /* Handle_Buffer */
1485 Check_Connections( VOID )
1487 /* Pruefen, ob Verbindungen noch "alive" sind. Ist dies
1488 * nicht der Fall, zunaechst PING-PONG spielen und, wenn
1489 * auch das nicht "hilft", Client disconnectieren. */
1494 for( i = 0; i < Pool_Size; i++ )
1496 if( My_Connections[i].sock == NONE ) continue;
1498 c = Client_GetFromConn( i );
1499 if( c && (( Client_Type( c ) == CLIENT_USER ) || ( Client_Type( c ) == CLIENT_SERVER ) || ( Client_Type( c ) == CLIENT_SERVICE )))
1501 /* verbundener User, Server oder Service */
1502 if( My_Connections[i].lastping > My_Connections[i].lastdata )
1504 /* es wurde bereits ein PING gesendet */
1505 if( My_Connections[i].lastping < time( NULL ) - Conf_PongTimeout )
1508 Log( LOG_DEBUG, "Connection %d: Ping timeout: %d seconds.", i, Conf_PongTimeout );
1509 Conn_Close( i, NULL, "Ping timeout", TRUE );
1512 else if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout )
1514 /* es muss ein PING gesendet werden */
1515 Log( LOG_DEBUG, "Connection %d: sending PING ...", i );
1516 My_Connections[i].lastping = time( NULL );
1517 Conn_WriteStr( i, "PING :%s", Client_ID( Client_ThisServer( )));
1522 /* noch nicht vollstaendig aufgebaute Verbindung */
1523 if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout )
1526 Log( LOG_DEBUG, "Connection %d timed out ...", i );
1527 Conn_Close( i, NULL, "Timeout", FALSE );
1531 } /* Check_Connections */
1535 Check_Servers( VOID )
1537 /* Pruefen, ob Server-Verbindungen aufgebaut werden
1538 * muessen bzw. koennen */
1544 /* Wenn "Passive-Mode" aktiv: nicht verbinden */
1545 if( NGIRCd_Passive ) return;
1547 for( i = 0; i < Conf_Server_Count; i++ )
1549 /* Ist ein Hostname und Port definiert? */
1550 if(( ! Conf_Server[i].host[0] ) || ( ! Conf_Server[i].port > 0 )) continue;
1552 /* Haben wir schon eine Verbindung? */
1553 for( n = 0; n < Pool_Size; n++ )
1555 if( My_Connections[n].sock == NONE ) continue;
1557 /* Verbindung zu diesem Server? */
1558 if( My_Connections[n].our_server == i )
1560 /* Komplett aufgebaute Verbindung? */
1561 if( My_Connections[n].sock > NONE ) break;
1563 /* IP schon aufgeloest? */
1564 if( My_Connections[n].res_stat == NULL ) New_Server( i, n );
1567 /* Verbindung in dieser Server-Gruppe? */
1568 if(( My_Connections[n].our_server != NONE ) && ( Conf_Server[i].group != NONE ))
1570 if( Conf_Server[My_Connections[n].our_server].group == Conf_Server[i].group ) break;
1573 if( n < Pool_Size ) continue;
1575 /* Wann war der letzte Connect-Versuch? */
1576 if( Conf_Server[i].lasttry > time( NULL ) - Conf_ConnectRetry ) continue;
1578 /* Okay, Verbindungsaufbau versuchen */
1579 Conf_Server[i].lasttry = time( NULL );
1581 /* Freie Connection-Struktur suschen */
1582 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
1583 if( idx >= Pool_Size )
1585 Log( LOG_ALERT, "Can't establist server connection: connection limit reached (%d)!", Pool_Size );
1588 Log( LOG_DEBUG, "Preparing connection %d for \"%s\" ...", idx, Conf_Server[i].host );
1590 /* Verbindungs-Struktur initialisieren */
1591 Init_Conn_Struct( idx );
1592 My_Connections[idx].sock = SERVER_WAIT;
1593 My_Connections[idx].our_server = i;
1595 /* Hostnamen in IP aufloesen (Default bzw. im Fehlerfall: versuchen, den
1596 * konfigurierten Text direkt als IP-Adresse zu verwenden ... */
1597 strlcpy( Conf_Server[My_Connections[idx].our_server].ip, Conf_Server[i].host, sizeof( Conf_Server[My_Connections[idx].our_server].ip ));
1598 strlcpy( My_Connections[idx].host, Conf_Server[i].host, sizeof( My_Connections[idx].host ));
1599 s = Resolve_Name( Conf_Server[i].host );
1602 /* Sub-Prozess wurde asyncron gestartet */
1603 My_Connections[idx].res_stat = s;
1606 } /* Check_Servers */
1610 New_Server( INT Server, CONN_ID Idx )
1612 /* Neue Server-Verbindung aufbauen */
1614 struct sockaddr_in new_addr;
1615 struct in_addr inaddr;
1619 assert( Server > NONE );
1620 assert( Idx > NONE );
1622 /* Wurde eine gueltige IP-Adresse gefunden? */
1623 if( ! Conf_Server[Server].ip[0] )
1625 /* Nein. Verbindung wieder freigeben: */
1626 Init_Conn_Struct( Idx );
1627 Log( LOG_ERR, "Can't connect to \"%s\" (connection %d): ip address unknown!", Conf_Server[Server].host, Idx );
1631 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 );
1633 #ifdef HAVE_INET_ATON
1634 if( inet_aton( Conf_Server[Server].ip, &inaddr ) == 0 )
1636 memset( &inaddr, 0, sizeof( inaddr ));
1637 inaddr.s_addr = inet_addr( Conf_Server[Server].ip );
1638 if( inaddr.s_addr == (unsigned)-1 )
1641 /* Konnte Adresse nicht konvertieren */
1642 Init_Conn_Struct( Idx );
1643 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 );
1647 memset( &new_addr, 0, sizeof( new_addr ));
1648 new_addr.sin_family = AF_INET;
1649 new_addr.sin_addr = inaddr;
1650 new_addr.sin_port = htons( Conf_Server[Server].port );
1652 new_sock = socket( PF_INET, SOCK_STREAM, 0 );
1655 Init_Conn_Struct( Idx );
1656 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
1660 if( ! Init_Socket( new_sock )) return;
1662 res = connect( new_sock, (struct sockaddr *)&new_addr, sizeof( new_addr ));
1663 if(( res != 0 ) && ( errno != EINPROGRESS ))
1665 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1667 Init_Conn_Struct( Idx );
1671 /* Client-Struktur initialisieren */
1672 c = Client_NewLocal( Idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWNSERVER, FALSE );
1676 Init_Conn_Struct( Idx );
1677 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1680 Client_SetIntroducer( c, c );
1681 Client_SetToken( c, TOKEN_OUTBOUND );
1683 /* Verbindung registrieren */
1684 My_Connections[Idx].sock = new_sock;
1685 My_Connections[Idx].addr = new_addr;
1686 strlcpy( My_Connections[Idx].host, Conf_Server[Server].host, sizeof( My_Connections[Idx].host ));
1688 /* Neuen Socket registrieren */
1689 FD_SET( new_sock, &My_Sockets );
1690 FD_SET( new_sock, &My_Connects );
1691 if( new_sock > Conn_MaxFD ) Conn_MaxFD = new_sock;
1693 Log( LOG_DEBUG, "Registered new connection %d on socket %d.", Idx, My_Connections[Idx].sock );
1698 Init_Conn_Struct( LONG Idx )
1700 /* Connection-Struktur initialisieren */
1702 My_Connections[Idx].sock = NONE;
1703 My_Connections[Idx].res_stat = NULL;
1704 My_Connections[Idx].host[0] = '\0';
1705 My_Connections[Idx].rbuf[0] = '\0';
1706 My_Connections[Idx].rdatalen = 0;
1707 My_Connections[Idx].wbuf[0] = '\0';
1708 My_Connections[Idx].wdatalen = 0;
1709 My_Connections[Idx].our_server = NONE;
1710 My_Connections[Idx].starttime = time( NULL );
1711 My_Connections[Idx].lastdata = time( NULL );
1712 My_Connections[Idx].lastping = 0;
1713 My_Connections[Idx].lastprivmsg = time( NULL );
1714 My_Connections[Idx].delaytime = 0;
1715 My_Connections[Idx].bytes_in = 0;
1716 My_Connections[Idx].bytes_out = 0;
1717 My_Connections[Idx].msg_in = 0;
1718 My_Connections[Idx].msg_out = 0;
1719 My_Connections[Idx].flag = 0;
1720 My_Connections[Idx].options = 0;
1723 My_Connections[Idx].zip.rbuf[0] = '\0';
1724 My_Connections[Idx].zip.rdatalen = 0;
1725 My_Connections[Idx].zip.wbuf[0] = '\0';
1726 My_Connections[Idx].zip.wdatalen = 0;
1727 My_Connections[Idx].zip.bytes_in = 0;
1728 My_Connections[Idx].zip.bytes_out = 0;
1730 } /* Init_Conn_Struct */
1734 Init_Socket( INT Sock )
1736 /* Socket-Optionen setzen */
1740 #ifdef O_NONBLOCK /* A/UX kennt das nicht? */
1741 if( fcntl( Sock, F_SETFL, O_NONBLOCK ) != 0 )
1743 Log( LOG_CRIT, "Can't enable non-blocking mode: %s!", strerror( errno ));
1748 if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &on, (socklen_t)sizeof( on )) != 0)
1750 Log( LOG_ERR, "Can't set socket options: %s!", strerror( errno ));
1751 /* dieser Fehler kann ignoriert werden. */
1759 Read_Resolver_Result( INT r_fd )
1761 /* Ergebnis von Resolver Sub-Prozess aus Pipe lesen
1762 * und entsprechende Connection aktualisieren */
1764 CHAR result[HOST_LEN];
1768 FD_CLR( r_fd, &Resolver_FDs );
1770 /* Anfrage vom Parent lesen */
1771 len = read( r_fd, result, HOST_LEN - 1 );
1774 /* Fehler beim Lesen aus der Pipe */
1776 Log( LOG_CRIT, "Resolver: Can't read result: %s!", strerror( errno ));
1781 /* zugehoerige Connection suchen */
1782 for( i = 0; i < Pool_Size; i++ )
1784 if(( My_Connections[i].sock != NONE ) && ( My_Connections[i].res_stat ) && ( My_Connections[i].res_stat->pipe[0] == r_fd )) break;
1786 if( i >= Pool_Size )
1788 /* Opsa! Keine passende Connection gefunden!? Vermutlich
1789 * wurde sie schon wieder geschlossen. */
1791 Log( LOG_DEBUG, "Resolver: Got result for unknown connection!?" );
1795 Log( LOG_DEBUG, "Resolver: %s is \"%s\".", My_Connections[i].host, result );
1798 close( My_Connections[i].res_stat->pipe[0] );
1799 close( My_Connections[i].res_stat->pipe[1] );
1800 free( My_Connections[i].res_stat );
1801 My_Connections[i].res_stat = NULL;
1803 if( My_Connections[i].sock > NONE )
1805 /* Eingehende Verbindung: Hostnamen setzen */
1806 c = Client_GetFromConn( i );
1807 assert( c != NULL );
1808 strlcpy( My_Connections[i].host, result, sizeof( My_Connections[i].host ));
1809 Client_SetHostname( c, result );
1813 /* Ausgehende Verbindung (=Server): IP setzen */
1814 assert( My_Connections[i].our_server > NONE );
1815 strlcpy( Conf_Server[My_Connections[i].our_server].ip, result, sizeof( Conf_Server[My_Connections[i].our_server].ip ));
1818 /* Penalty-Zeit zurueck setzen */
1819 Conn_ResetPenalty( i );
1820 } /* Read_Resolver_Result */
1826 Zip_Buffer( CONN_ID Idx, CHAR *Data, INT Len )
1828 /* Daten zum Komprimieren im "Kompressions-Puffer" sammeln.
1829 * Es wird TRUE bei Erfolg, sonst FALSE geliefert. */
1831 assert( Idx > NONE );
1832 assert( Data != NULL );
1835 /* Ist noch Platz im Kompressions-Puffer? */
1836 if( ZWRITEBUFFER_LEN - My_Connections[Idx].zip.wdatalen < Len + 50 )
1838 /* Nein! Puffer zunaechst leeren ...*/
1839 if( ! Zip_Flush( Idx )) return FALSE;
1842 /* Daten kopieren */
1843 memmove( My_Connections[Idx].zip.wbuf + My_Connections[Idx].zip.wdatalen, Data, Len );
1844 My_Connections[Idx].zip.wdatalen += Len;
1851 Zip_Flush( CONN_ID Idx )
1853 /* Daten komprimieren und in Schreibpuffer kopieren.
1854 * Es wird TRUE bei Erfolg, sonst FALSE geliefert. */
1856 INT result, out_len;
1859 out = &My_Connections[Idx].zip.out;
1861 out->next_in = My_Connections[Idx].zip.wbuf;
1862 out->avail_in = My_Connections[Idx].zip.wdatalen;
1863 out->next_out = My_Connections[Idx].wbuf + My_Connections[Idx].wdatalen;
1864 out->avail_out = WRITEBUFFER_LEN - My_Connections[Idx].wdatalen;
1866 result = deflate( out, Z_SYNC_FLUSH );
1867 if(( result != Z_OK ) || ( out->avail_in > 0 ))
1869 Log( LOG_ALERT, "Compression error: code %d!?", result );
1870 Conn_Close( Idx, "Compression error!", NULL, FALSE );
1874 out_len = WRITEBUFFER_LEN - My_Connections[Idx].wdatalen - out->avail_out;
1875 My_Connections[Idx].wdatalen += out_len;
1876 My_Connections[Idx].bytes_out += out_len;
1877 My_Connections[Idx].zip.bytes_out += My_Connections[Idx].zip.wdatalen;
1878 My_Connections[Idx].zip.wdatalen = 0;
1885 Unzip_Buffer( CONN_ID Idx )
1887 /* Daten entpacken und in Lesepuffer kopieren. Bei Fehlern
1888 * wird FALSE geliefert, ansonsten TRUE. Der Fall, dass keine
1889 * Daten mehr zu entpacken sind, ist _kein_ Fehler! */
1891 INT result, in_len, out_len;
1894 assert( Idx > NONE );
1896 if( My_Connections[Idx].zip.rdatalen <= 0 ) return TRUE;
1898 in = &My_Connections[Idx].zip.in;
1900 in->next_in = My_Connections[Idx].zip.rbuf;
1901 in->avail_in = My_Connections[Idx].zip.rdatalen;
1902 in->next_out = My_Connections[Idx].rbuf + My_Connections[Idx].rdatalen;
1903 in->avail_out = READBUFFER_LEN - My_Connections[Idx].rdatalen - 1;
1905 result = inflate( in, Z_SYNC_FLUSH );
1906 if( result != Z_OK )
1908 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 );
1909 Conn_Close( Idx, "Decompression error!", NULL, FALSE );
1913 in_len = My_Connections[Idx].zip.rdatalen - in->avail_in;
1914 out_len = READBUFFER_LEN - My_Connections[Idx].rdatalen - 1 - in->avail_out;
1915 My_Connections[Idx].rdatalen += out_len;
1917 if( in->avail_in > 0 )
1919 /* es konnten nicht alle Daten entpackt werden, vermutlich war
1920 * im Ziel-Puffer kein Platz mehr. Umkopieren ... */
1921 My_Connections[Idx].zip.rdatalen -= in_len;
1922 memmove( My_Connections[Idx].zip.rbuf, My_Connections[Idx].zip.rbuf + in_len, My_Connections[Idx].zip.rdatalen );
1924 else My_Connections[Idx].zip.rdatalen = 0;
1925 My_Connections[Idx].zip.bytes_in += out_len;
1928 } /* Unzip_Buffer */