]> arthur.barton.de Git - ngircd-alex.git/blob - src/ngircd/conn.c
- new functions Conn_ResetWCounter() and Conn_WCounter().
[ngircd-alex.git] / src / ngircd / conn.c
1 /*
2  * ngIRCd -- The Next Generation IRC Daemon
3  * Copyright (c)2001,2002 by Alexander Barton (alex@barton.de)
4  *
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.
10  *
11  * Connection management
12  */
13
14
15 #include "portab.h"
16
17 static char UNUSED id[] = "$Id: conn.c,v 1.106 2002/12/18 13:50:22 alex Exp $";
18
19 #include "imp.h"
20 #include <assert.h>
21 #include <stdarg.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <unistd.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <string.h>
28 #include <sys/socket.h>
29 #include <sys/time.h>
30 #include <sys/types.h>
31 #include <time.h>
32 #include <netinet/in.h>
33
34 #ifdef HAVE_ARPA_INET_H
35 #include <arpa/inet.h>
36 #else
37 #define PF_INET AF_INET
38 #endif
39
40 #ifdef HAVE_STDINT_H
41 #include <stdint.h>                     /* u.a. fuer Mac OS X */
42 #endif
43
44 #ifdef USE_ZLIB
45 #include <zlib.h>
46 #endif
47
48 #include "exp.h"
49 #include "conn.h"
50
51 #include "imp.h"
52 #include "ngircd.h"
53 #include "client.h"
54 #include "resolve.h"
55 #include "conf.h"
56 #include "log.h"
57 #include "parse.h"
58 #include "tool.h"
59
60 #include "exp.h"
61
62
63 #define SERVER_WAIT (NONE - 1)
64
65
66 #ifdef USE_ZLIB
67 typedef struct _ZipData
68 {
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!) */
76 } ZIPDATA;
77 #endif
78
79
80 typedef struct _Connection
81 {
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 */
100 #ifdef USE_ZLIB
101         ZIPDATA zip;                    /* Kompressionsinformationen */
102 #endif
103 } CONNECTION;
104
105
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 ));
119
120 #ifdef USE_ZLIB
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 ));
124 #endif
125
126
127 LOCAL fd_set My_Listeners;
128 LOCAL fd_set My_Sockets;
129 LOCAL fd_set My_Connects;
130
131 LOCAL CONNECTION *My_Connections;
132 LOCAL LONG Pool_Size, WCounter;
133
134
135 GLOBAL VOID
136 Conn_Init( VOID )
137 {
138         /* Modul initialisieren: statische Strukturen "ausnullen". */
139
140         CONN_ID i;
141
142         /* Speicher fuer Verbindungs-Pool anfordern */
143         Pool_Size = CONNECTION_POOL;
144         if( Conf_MaxConnections > 0 )
145         {
146                 /* konfiguriertes Limit beachten */
147                 if( Pool_Size > Conf_MaxConnections ) Pool_Size = Conf_MaxConnections;
148         }
149         My_Connections = malloc( sizeof( CONNECTION ) * Pool_Size );
150         if( ! My_Connections )
151         {
152                 /* Speicher konnte nicht alloziert werden! */
153                 Log( LOG_EMERG, "Can't allocate memory! [Conn_Init]" );
154                 exit( 1 );
155         }
156         Log( LOG_DEBUG, "Allocted connection pool for %ld items (%ld bytes).", Pool_Size, sizeof( CONNECTION ) * Pool_Size );
157
158         /* zu Beginn haben wir keine Verbindungen */
159         FD_ZERO( &My_Listeners );
160         FD_ZERO( &My_Sockets );
161         FD_ZERO( &My_Connects );
162
163         /* Groesster File-Descriptor fuer select() */
164         Conn_MaxFD = 0;
165
166         /* Connection-Struktur initialisieren */
167         for( i = 0; i < Pool_Size; i++ ) Init_Conn_Struct( i );
168
169         /* Global write counter */
170         WCounter = 0;
171 } /* Conn_Init */
172
173
174 GLOBAL VOID
175 Conn_Exit( VOID )
176 {
177         /* Modul abmelden: alle noch offenen Connections
178          * schliessen und freigeben. */
179
180         CONN_ID idx;
181         INT i;
182
183         /* Sockets schliessen */
184         Log( LOG_DEBUG, "Shutting down all connections ..." );
185         for( i = 0; i < Conn_MaxFD + 1; i++ )
186         {
187                 if( FD_ISSET( i, &My_Sockets ))
188                 {
189                         for( idx = 0; idx < Pool_Size; idx++ )
190                         {
191                                 if( My_Connections[idx].sock == i ) break;
192                         }
193                         if( FD_ISSET( i, &My_Listeners ))
194                         {
195                                 close( i );
196                                 Log( LOG_DEBUG, "Listening socket %d closed.", i );
197                         }
198                         else if( FD_ISSET( i, &My_Connects ))
199                         {
200                                 close( i );
201                                 Log( LOG_DEBUG, "Connection %d closed during creation (socket %d).", idx, i );
202                         }
203                         else if( idx < Pool_Size )
204                         {
205                                 if( NGIRCd_Restart ) Conn_Close( idx, NULL, "Server going down (restarting)", TRUE );
206                                 else Conn_Close( idx, NULL, "Server going down", TRUE );
207                         }
208                         else
209                         {
210                                 Log( LOG_WARNING, "Closing unknown connection %d ...", i );
211                                 close( i );
212                         }
213                 }
214         }
215         
216         free( My_Connections );
217         My_Connections = NULL;
218         Pool_Size = 0;
219 } /* Conn_Exit */
220
221
222 GLOBAL INT
223 Conn_InitListeners( VOID )
224 {
225         /* Ports, auf denen der Server Verbindungen entgegennehmen
226         * soll, initialisieren */
227
228         INT created, i;
229
230         created = 0;
231         for( i = 0; i < Conf_ListenPorts_Count; i++ )
232         {
233                 if( Conn_NewListener( Conf_ListenPorts[i] )) created++;
234                 else Log( LOG_ERR, "Can't listen on port %u!", Conf_ListenPorts[i] );
235         }
236         return created;
237 } /* Conn_InitListeners */
238
239
240 GLOBAL VOID
241 Conn_ExitListeners( VOID )
242 {
243         /* Alle "Listen-Sockets" schliessen */
244
245         INT i;
246
247         Log( LOG_INFO, "Shutting down all listening sockets ..." );
248         for( i = 0; i < Conn_MaxFD + 1; i++ )
249         {
250                 if( FD_ISSET( i, &My_Sockets ) && FD_ISSET( i, &My_Listeners ))
251                 {
252                         close( i );
253                         Log( LOG_DEBUG, "Listening socket %d closed.", i );
254                 }
255         }
256 } /* Conn_ExitListeners */
257
258
259 GLOBAL BOOLEAN
260 Conn_NewListener( CONST UINT Port )
261 {
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.*/
265
266         struct sockaddr_in addr;
267         INT sock;
268
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 );
274
275         /* Socket erzeugen */
276         sock = socket( PF_INET, SOCK_STREAM, 0);
277         if( sock < 0 )
278         {
279                 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
280                 return FALSE;
281         }
282
283         if( ! Init_Socket( sock )) return FALSE;
284
285         /* an Port binden */
286         if( bind( sock, (struct sockaddr *)&addr, (socklen_t)sizeof( addr )) != 0 )
287         {
288                 Log( LOG_CRIT, "Can't bind socket: %s!", strerror( errno ));
289                 close( sock );
290                 return FALSE;
291         }
292
293         /* in "listen mode" gehen :-) */
294         if( listen( sock, 10 ) != 0 )
295         {
296                 Log( LOG_CRIT, "Can't listen on soecket: %s!", strerror( errno ));
297                 close( sock );
298                 return FALSE;
299         }
300
301         /* Neuen Listener in Strukturen einfuegen */
302         FD_SET( sock, &My_Listeners );
303         FD_SET( sock, &My_Sockets );
304
305         if( sock > Conn_MaxFD ) Conn_MaxFD = sock;
306
307         Log( LOG_INFO, "Now listening on port %d (socket %d).", Port, sock );
308
309         return TRUE;
310 } /* Conn_NewListener */
311
312
313 GLOBAL VOID
314 Conn_Handler( VOID )
315 {
316         /* "Hauptschleife": Aktive Verbindungen ueberwachen. Folgende Aktionen
317          * werden dabei durchgefuehrt, bis der Server terminieren oder neu
318          * starten soll:
319          *
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.
326          */
327
328         fd_set read_sockets, write_sockets;
329         struct timeval tv;
330         time_t start, t;
331         LONG i, idx;
332         BOOLEAN timeout;
333
334         start = time( NULL );
335         while(( ! NGIRCd_Quit ) && ( ! NGIRCd_Restart ))
336         {
337                 timeout = TRUE;
338         
339                 Check_Servers( );
340
341                 Check_Connections( );
342
343                 /* noch volle Lese-Buffer suchen */
344                 for( i = 0; i < Pool_Size; i++ )
345                 {
346                         if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].rdatalen > 0 ))
347                         {
348                                 /* Kann aus dem Buffer noch ein Befehl extrahiert werden? */
349                                 if( Handle_Buffer( i )) timeout = FALSE;
350                         }
351                 }
352
353                 /* noch volle Schreib-Puffer suchen */
354                 FD_ZERO( &write_sockets );
355                 for( i = 0; i < Pool_Size; i++ )
356                 {
357 #ifdef USE_ZLIB
358                         if(( My_Connections[i].sock > NONE ) && (( My_Connections[i].wdatalen > 0 ) || ( My_Connections[i].zip.wdatalen > 0 )))
359 #else
360                         if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].wdatalen > 0 ))
361 #endif
362                         {
363                                 /* Socket der Verbindung in Set aufnehmen */
364                                 FD_SET( My_Connections[i].sock, &write_sockets );
365                         }
366                 }
367                 /* Sockets mit im Aufbau befindlichen ausgehenden Verbindungen suchen */
368                 for( i = 0; i < Pool_Size; i++ )
369                 {
370                         if(( My_Connections[i].sock > NONE ) && ( FD_ISSET( My_Connections[i].sock, &My_Connects ))) FD_SET( My_Connections[i].sock, &write_sockets );
371                 }
372
373                 /* von welchen Sockets koennte gelesen werden? */
374                 t = time( NULL );
375                 read_sockets = My_Sockets;
376                 for( i = 0; i < Pool_Size; i++ )
377                 {
378                         if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].host[0] == '\0' ))
379                         {
380                                 /* Hier muss noch auf den Resolver Sub-Prozess gewartet werden */
381                                 FD_CLR( My_Connections[i].sock, &read_sockets );
382                         }
383                         if(( My_Connections[i].sock > NONE ) && ( FD_ISSET( My_Connections[i].sock, &My_Connects )))
384                         {
385                                 /* Hier laeuft noch ein asyncrones connect() */
386                                 FD_CLR( My_Connections[i].sock, &read_sockets );
387                         }
388                         if( My_Connections[i].delaytime > t )
389                         {
390                                 /* Fuer die Verbindung ist eine "Penalty-Zeit" gesetzt */
391                                 FD_CLR( My_Connections[i].sock, &read_sockets );
392                                 FD_CLR( My_Connections[i].sock, &write_sockets );
393                         }
394                 }
395                 for( i = 0; i < Conn_MaxFD + 1; i++ )
396                 {
397                         /* Pipes von Resolver Sub-Prozessen aufnehmen */
398                         if( FD_ISSET( i, &Resolver_FDs ))
399                         {
400                                 FD_SET( i, &read_sockets );
401                         }
402                 }
403
404                 /* Timeout initialisieren */
405                 tv.tv_usec = 0;
406                 if( timeout ) tv.tv_sec = TIME_RES;
407                 else tv.tv_sec = 0;
408                 
409                 /* Auf Aktivitaet warten */
410                 i = select( Conn_MaxFD + 1, &read_sockets, &write_sockets, NULL, &tv );
411                 if( i == 0 )
412                 {
413                         /* keine Veraenderung an den Sockets */
414                         continue;
415                 }
416                 if( i == -1 )
417                 {
418                         /* Fehler (z.B. Interrupt) */
419                         if( errno != EINTR )
420                         {
421                                 Log( LOG_EMERG, "Conn_Handler(): select(): %s!", strerror( errno ));
422                                 Log( LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE );
423                                 exit( 1 );
424                         }
425                         continue;
426                 }
427
428                 /* Koennen Daten geschrieben werden? */
429                 for( i = 0; i < Conn_MaxFD + 1; i++ )
430                 {
431                         if( ! FD_ISSET( i, &write_sockets )) continue;
432
433                         /* Es kann geschrieben werden ... */
434                         idx = Socket2Index( i );
435                         if( idx == NONE ) continue;
436                         
437                         if( ! Handle_Write( idx ))
438                         {
439                                 /* Fehler beim Schreiben! Diesen Socket nun
440                                  * auch aus dem Read-Set entfernen: */
441                                 FD_CLR( i, &read_sockets );
442                         }
443                 }
444
445                 /* Daten zum Lesen vorhanden? */
446                 for( i = 0; i < Conn_MaxFD + 1; i++ )
447                 {
448                         if( FD_ISSET( i, &read_sockets )) Handle_Read( i );
449                 }
450         }
451 } /* Conn_Handler */
452
453
454 #ifdef PROTOTYPES
455 GLOBAL BOOLEAN
456 Conn_WriteStr( CONN_ID Idx, CHAR *Format, ... )
457 #else
458 GLOBAL BOOLEAN
459 Conn_WriteStr( Idx, Format, va_alist )
460 CONN_ID Idx;
461 CHAR *Format;
462 va_dcl
463 #endif
464 {
465         /* String in Socket schreiben. CR+LF wird von dieser Funktion
466          * automatisch angehaengt. Im Fehlerfall wird dir Verbindung
467          * getrennt und FALSE geliefert. */
468
469         CHAR buffer[COMMAND_LEN];
470         BOOLEAN ok;
471         va_list ap;
472
473         assert( Idx > NONE );
474         assert( Format != NULL );
475
476 #ifdef PROTOTYPES
477         va_start( ap, Format );
478 #else
479         va_start( ap );
480 #endif
481         if( vsnprintf( buffer, COMMAND_LEN - 2, Format, ap ) == COMMAND_LEN - 2 )
482         {
483                 Log( LOG_CRIT, "Text too long to send (connection %d)!", Idx );
484                 Conn_Close( Idx, "Text too long to send!", NULL, FALSE );
485                 return FALSE;
486         }
487
488 #ifdef SNIFFER
489         if( NGIRCd_Sniffer ) Log( LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer );
490 #endif
491
492         strcat( buffer, "\r\n" );
493         ok = Conn_Write( Idx, buffer, strlen( buffer ));
494         My_Connections[Idx].msg_out++;
495
496         va_end( ap );
497         return ok;
498 } /* Conn_WriteStr */
499
500
501 GLOBAL BOOLEAN
502 Conn_Write( CONN_ID Idx, CHAR *Data, INT Len )
503 {
504         /* Daten in Socket schreiben. Bei "fatalen" Fehlern wird
505          * der Client disconnectiert und FALSE geliefert. */
506
507         assert( Idx > NONE );
508         assert( Data != NULL );
509         assert( Len > 0 );
510
511         /* Ist der entsprechende Socket ueberhaupt noch offen? In einem
512          * "Handler-Durchlauf" kann es passieren, dass dem nicht mehr so
513          * ist, wenn einer von mehreren Conn_Write()'s fehlgeschlagen ist.
514          * In diesem Fall wird hier einfach ein Fehler geliefert. */
515         if( My_Connections[Idx].sock <= NONE )
516         {
517                 Log( LOG_DEBUG, "Skipped write on closed socket (connection %d).", Idx );
518                 return FALSE;
519         }
520
521         /* Pruefen, ob im Schreibpuffer genuegend Platz ist. Ziel ist es,
522          * moeglichts viel im Puffer zu haben und _nicht_ gleich alles auf den
523          * Socket zu schreiben (u.a. wg. Komprimierung). */
524         if( WRITEBUFFER_LEN - My_Connections[Idx].wdatalen - Len <= 0 )
525         {
526                 /* Der Puffer ist dummerweise voll. Jetzt versuchen, den Puffer
527                  * zu schreiben, wenn das nicht klappt, haben wir ein Problem ... */
528                 if( ! Try_Write( Idx )) return FALSE;
529
530                 /* nun neu pruefen: */
531                 if( WRITEBUFFER_LEN - My_Connections[Idx].wdatalen - Len <= 0 )
532                 {
533                         Log( LOG_NOTICE, "Write buffer overflow (connection %d)!", Idx );
534                         Conn_Close( Idx, "Write buffer overflow!", NULL, FALSE );
535                         return FALSE;
536                 }
537         }
538
539 #ifdef USE_ZLIB
540         if( My_Connections[Idx].options & CONN_ZIP )
541         {
542                 /* Daten komprimieren und in Puffer kopieren */
543                 if( ! Zip_Buffer( Idx, Data, Len )) return FALSE;
544         }
545         else
546 #endif
547         {
548                 /* Daten in Puffer kopieren */
549                 memcpy( My_Connections[Idx].wbuf + My_Connections[Idx].wdatalen, Data, Len );
550                 My_Connections[Idx].wdatalen += Len;
551                 My_Connections[Idx].bytes_out += Len;
552         }
553
554         /* Adjust global write counter */
555         WCounter += Len;
556
557         return TRUE;
558 } /* Conn_Write */
559
560
561 GLOBAL VOID
562 Conn_Close( CONN_ID Idx, CHAR *LogMsg, CHAR *FwdMsg, BOOLEAN InformClient )
563 {
564         /* Verbindung schliessen. Evtl. noch von Resolver
565          * Sub-Prozessen offene Pipes werden geschlossen. */
566
567         CLIENT *c;
568         DOUBLE in_k, out_k;
569 #ifdef USE_ZLIB
570         DOUBLE in_z_k, out_z_k;
571         INT in_p, out_p;
572 #endif
573
574         assert( Idx > NONE );
575         assert( My_Connections[Idx].sock > NONE );
576
577         c = Client_GetFromConn( Idx );
578
579         if( InformClient )
580         {
581 #ifndef STRICT_RFC
582                 /* Statistik an Client melden, wenn User */
583                 if(( c != NULL ) && ( Client_Type( c ) == CLIENT_USER ))
584                 {
585                         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 );
586                 }
587 #endif
588
589                 /* ERROR an Client schicken (von RFC so vorgesehen!) */
590                 if( FwdMsg ) Conn_WriteStr( Idx, "ERROR :%s", FwdMsg );
591                 else Conn_WriteStr( Idx, "ERROR :Closing connection." );
592                 if( My_Connections[Idx].sock == NONE ) return;
593         }
594
595         /* zunaechst versuchen, noch im Schreibpuffer vorhandene
596          * Daten auf den Socket zu schreiben ... */
597         Try_Write( Idx );
598
599         if( close( My_Connections[Idx].sock ) != 0 )
600         {
601                 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 ));
602         }
603         else
604         {
605                 in_k = (DOUBLE)My_Connections[Idx].bytes_in / 1024;
606                 out_k = (DOUBLE)My_Connections[Idx].bytes_out / 1024;
607 #ifdef USE_ZLIB
608                 if( My_Connections[Idx].options & CONN_ZIP )
609                 {
610                         in_z_k = (DOUBLE)My_Connections[Idx].zip.bytes_in / 1024;
611                         out_z_k = (DOUBLE)My_Connections[Idx].zip.bytes_out / 1024;
612                         in_p = (INT)(( in_k * 100 ) / in_z_k );
613                         out_p = (INT)(( out_k * 100 ) / out_z_k );
614                         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 );
615                 }
616                 else
617 #endif
618                 {
619                         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 );
620                 }
621         }
622         
623         /* Socket als "ungueltig" markieren */
624         FD_CLR( My_Connections[Idx].sock, &My_Sockets );
625         FD_CLR( My_Connections[Idx].sock, &My_Connects );
626         My_Connections[Idx].sock = NONE;
627
628         if( c ) Client_Destroy( c, LogMsg, FwdMsg, TRUE );
629
630         if( My_Connections[Idx].res_stat )
631         {
632                 /* Resolver-Strukturen freigeben, wenn noch nicht geschehen */
633                 FD_CLR( My_Connections[Idx].res_stat->pipe[0], &Resolver_FDs );
634                 close( My_Connections[Idx].res_stat->pipe[0] );
635                 close( My_Connections[Idx].res_stat->pipe[1] );
636                 free( My_Connections[Idx].res_stat );
637         }
638
639         /* Startzeit des naechsten Connect-Versuchs modifizieren? */
640         if(( My_Connections[Idx].our_server > NONE ) && ( Conf_Server[My_Connections[Idx].our_server].lasttry <  time( NULL ) - Conf_ConnectRetry ))
641         {
642                 /* Okay, die Verbindung stand schon "genuegend lange":
643                  * lasttry-Zeitpunkt so setzen, dass der naechste
644                  * Verbindungsversuch in RECONNECT_DELAY Sekunden
645                  * gestartet wird. */
646                 Conf_Server[My_Connections[Idx].our_server].lasttry = time( NULL ) - Conf_ConnectRetry + RECONNECT_DELAY;
647         }
648
649 #ifdef USE_ZLIB
650         /* Ggf. zlib abmelden */
651         if( Conn_Options( Idx ) & CONN_ZIP )
652         {
653                 inflateEnd( &My_Connections[Idx].zip.in );
654                 deflateEnd( &My_Connections[Idx].zip.out );
655         }
656 #endif
657
658         /* Connection-Struktur loeschen (=freigeben) */
659         Init_Conn_Struct( Idx );
660 } /* Conn_Close */
661
662
663 GLOBAL VOID
664 Conn_UpdateIdle( CONN_ID Idx )
665 {
666         /* Idle-Timer zuruecksetzen */
667
668         assert( Idx > NONE );
669         My_Connections[Idx].lastprivmsg = time( NULL );
670 }
671
672
673 GLOBAL time_t
674 Conn_GetIdle( CONN_ID Idx )
675 {
676         /* Idle-Time einer Verbindung liefern (in Sekunden) */
677
678         assert( Idx > NONE );
679         return time( NULL ) - My_Connections[Idx].lastprivmsg;
680 } /* Conn_GetIdle */
681
682
683 GLOBAL time_t
684 Conn_LastPing( CONN_ID Idx )
685 {
686         /* Zeitpunkt des letzten PING liefern */
687
688         assert( Idx > NONE );
689         return My_Connections[Idx].lastping;
690 } /* Conn_LastPing */
691
692
693 GLOBAL VOID
694 Conn_SetPenalty( CONN_ID Idx, time_t Seconds )
695 {
696         /* Penalty-Delay fuer eine Verbindung (in Sekunden) setzen;
697          * waehrend dieser Zeit wird der entsprechende Socket vom Server
698          * bei Lese-Operationen komplett ignoriert. Der Delay kann mit
699          * dieser Funktion nur erhoeht, nicht aber verringert werden. */
700         
701         time_t t;
702         
703         assert( Idx > NONE );
704         assert( Seconds >= 0 );
705         
706         t = time( NULL ) + Seconds;
707         if( t > My_Connections[Idx].delaytime ) My_Connections[Idx].delaytime = t;
708 } /* Conn_SetPenalty */
709
710
711 GLOBAL VOID
712 Conn_ResetPenalty( CONN_ID Idx )
713 {
714         assert( Idx > NONE );
715         My_Connections[Idx].delaytime = 0;
716 } /* Conn_ResetPenalty */
717
718
719 GLOBAL VOID
720 Conn_ClearFlags( VOID )
721 {
722         /* Alle Connection auf "nicht-markiert" setzen */
723
724         LONG i;
725
726         for( i = 0; i < Pool_Size; i++ ) My_Connections[i].flag = 0;
727 } /* Conn_ClearFlags */
728
729
730 GLOBAL INT
731 Conn_Flag( CONN_ID Idx )
732 {
733         /* Ist eine Connection markiert (TRUE) oder nicht? */
734
735         assert( Idx > NONE );
736         return My_Connections[Idx].flag;
737 } /* Conn_Flag */
738
739
740 GLOBAL VOID
741 Conn_SetFlag( CONN_ID Idx, INT Flag )
742 {
743         /* Connection markieren */
744
745         assert( Idx > NONE );
746         My_Connections[Idx].flag = Flag;
747 } /* Conn_SetFlag */
748
749
750 GLOBAL CONN_ID
751 Conn_First( VOID )
752 {
753         /* Connection-Struktur der ersten Verbindung liefern;
754          * Ist keine Verbindung vorhanden, wird NONE geliefert. */
755
756         LONG i;
757         
758         for( i = 0; i < Pool_Size; i++ )
759         {
760                 if( My_Connections[i].sock != NONE ) return i;
761         }
762         return NONE;
763 } /* Conn_First */
764
765
766 GLOBAL CONN_ID
767 Conn_Next( CONN_ID Idx )
768 {
769         /* Naechste Verbindungs-Struktur liefern; existiert keine
770          * weitere, so wird NONE geliefert. */
771
772         LONG i = NONE;
773
774         assert( Idx > NONE );
775         
776         for( i = Idx + 1; i < Pool_Size; i++ )
777         {
778                 if( My_Connections[i].sock != NONE ) return i;
779         }
780         return NONE;
781 } /* Conn_Next */
782
783
784 GLOBAL VOID
785 Conn_SetServer( CONN_ID Idx, INT ConfServer )
786 {
787         /* Connection als Server markieren: Index des konfigurierten
788          * Servers speichern. Verbindung muss bereits bestehen! */
789         
790         assert( Idx > NONE );
791         assert( My_Connections[Idx].sock > NONE );
792         
793         My_Connections[Idx].our_server = ConfServer;
794 } /* Conn_SetServer */
795
796
797 GLOBAL VOID
798 Conn_SetOption( CONN_ID Idx, INT Option )
799 {
800         /* Option fuer Verbindung setzen.
801          * Initial sind alle Optionen _nicht_ gesetzt. */
802
803         assert( Idx > NONE );
804         assert( Option != 0 );
805
806         My_Connections[Idx].options |= Option;
807 } /* Conn_SetOption */
808
809
810 GLOBAL VOID
811 Conn_UnsetOption( CONN_ID Idx, INT Option )
812 {
813         /* Option fuer Verbindung loeschen */
814
815         assert( Idx > NONE );
816         assert( Option != 0 );
817
818         My_Connections[Idx].options &= ~Option;
819 } /* Conn_UnsetOption */
820
821
822 GLOBAL INT
823 Conn_Options( CONN_ID Idx )
824 {
825         assert( Idx > NONE );
826         return My_Connections[Idx].options;
827 } /* Conn_Options */
828
829
830 #ifdef USE_ZLIB
831
832 GLOBAL BOOLEAN
833 Conn_InitZip( CONN_ID Idx )
834 {
835         /* Kompression fuer Link initialisieren */
836
837         assert( Idx > NONE );
838
839         My_Connections[Idx].zip.in.avail_in = 0;
840         My_Connections[Idx].zip.in.total_in = 0;
841         My_Connections[Idx].zip.in.total_out = 0;
842         My_Connections[Idx].zip.in.zalloc = NULL;
843         My_Connections[Idx].zip.in.zfree = NULL;
844         My_Connections[Idx].zip.in.data_type = Z_ASCII;
845
846         if( inflateInit( &My_Connections[Idx].zip.in ) != Z_OK )
847         {
848                 /* Fehler! */
849                 Log( LOG_ALERT, "Can't initialize compression on connection %d (zlib inflate)!", Idx );
850                 return FALSE;
851         }
852         
853         My_Connections[Idx].zip.out.total_in = 0;
854         My_Connections[Idx].zip.out.total_in = 0;
855         My_Connections[Idx].zip.out.zalloc = NULL;
856         My_Connections[Idx].zip.out.zfree = NULL;
857         My_Connections[Idx].zip.out.data_type = Z_ASCII;
858
859         if( deflateInit( &My_Connections[Idx].zip.out, Z_DEFAULT_COMPRESSION ) != Z_OK )
860         {
861                 /* Fehler! */
862                 Log( LOG_ALERT, "Can't initialize compression on connection %d (zlib deflate)!", Idx );
863                 return FALSE;
864         }
865
866         My_Connections[Idx].zip.bytes_in = My_Connections[Idx].bytes_in;
867         My_Connections[Idx].zip.bytes_out = My_Connections[Idx].bytes_out;
868
869         Log( LOG_INFO, "Enabled link compression (zlib) on connection %d.", Idx );
870         Conn_SetOption( Idx, CONN_ZIP );
871
872         return TRUE;
873 } /* Conn_InitZip */
874
875
876 GLOBAL LONG
877 Conn_SendBytesZip( CONN_ID Idx )
878 {
879         /* Anzahl gesendeter Bytes (komprimiert!) liefern */
880
881         assert( Idx > NONE );
882         return My_Connections[Idx].zip.bytes_out;
883 } /* Conn_SendBytesZip */
884
885
886 GLOBAL LONG
887 Conn_RecvBytesZip( CONN_ID Idx )
888 {
889         /* Anzahl gesendeter Bytes (komprimiert!) liefern */
890
891         assert( Idx > NONE );
892         return My_Connections[Idx].zip.bytes_in;
893 } /* Conn_RecvBytesZip */
894
895 #endif
896
897
898 GLOBAL time_t
899 Conn_StartTime( CONN_ID Idx )
900 {
901         /* Zeitpunkt des Link-Starts liefern (in Sekunden) */
902
903         assert( Idx > NONE );
904         return My_Connections[Idx].starttime;
905 } /* Conn_Uptime */
906
907
908 GLOBAL INT
909 Conn_SendQ( CONN_ID Idx )
910 {
911         /* Laenge der Daten im Schreibbuffer liefern */
912
913         assert( Idx > NONE );
914 #ifdef USE_ZLIB
915         if( My_Connections[Idx].options & CONN_ZIP ) return My_Connections[Idx].zip.wdatalen;
916         else
917 #endif
918         return My_Connections[Idx].wdatalen;
919 } /* Conn_SendQ */
920
921
922 GLOBAL LONG
923 Conn_SendMsg( CONN_ID Idx )
924 {
925         /* Anzahl gesendeter Nachrichten liefern */
926
927         assert( Idx > NONE );
928         return My_Connections[Idx].msg_out;
929 } /* Conn_SendMsg */
930
931
932 GLOBAL LONG
933 Conn_SendBytes( CONN_ID Idx )
934 {
935         /* Anzahl gesendeter Bytes (unkomprimiert) liefern */
936
937         assert( Idx > NONE );
938         return My_Connections[Idx].bytes_out;
939 } /* Conn_SendBytes */
940
941
942 GLOBAL INT
943 Conn_RecvQ( CONN_ID Idx )
944 {
945         /* Laenge der Daten im Lesebuffer liefern */
946
947         assert( Idx > NONE );
948 #ifdef USE_ZLIB
949         if( My_Connections[Idx].options & CONN_ZIP ) return My_Connections[Idx].zip.rdatalen;
950         else
951 #endif
952         return My_Connections[Idx].rdatalen;
953 } /* Conn_RecvQ */
954
955
956 GLOBAL LONG
957 Conn_RecvMsg( CONN_ID Idx )
958 {
959         /* Anzahl empfangener Nachrichten liefern */
960
961         assert( Idx > NONE );
962         return My_Connections[Idx].msg_in;
963 } /* Conn_RecvMsg */
964
965
966 GLOBAL LONG
967 Conn_RecvBytes( CONN_ID Idx )
968 {
969         /* Anzahl empfangener Bytes (unkomprimiert) liefern */
970
971         assert( Idx > NONE );
972         return My_Connections[Idx].bytes_in;
973 } /* Conn_RecvBytes */
974
975
976 GLOBAL VOID
977 Conn_ResetWCounter( VOID )
978 {
979         WCounter = 0;
980 } /* Conn_ResetWCounter */
981
982
983 GLOBAL LONG
984 Conn_WCounter( VOID )
985 {
986         return WCounter;
987 } /* Conn_WCounter */
988
989
990 LOCAL BOOLEAN
991 Try_Write( CONN_ID Idx )
992 {
993         /* Versuchen, Daten aus dem Schreib-Puffer in den Socket zu
994          * schreiben. TRUE wird geliefert, wenn entweder keine Daten
995          * zum Versenden vorhanden sind oder erfolgreich bearbeitet
996          * werden konnten. Im Fehlerfall wird FALSE geliefert und
997          * die Verbindung geschlossen. */
998
999         fd_set write_socket;
1000         struct timeval tv;
1001
1002         assert( Idx > NONE );
1003         assert( My_Connections[Idx].sock > NONE );
1004
1005         /* sind ueberhaupt Daten vorhanden? */
1006 #ifdef USE_ZLIB
1007         if(( ! My_Connections[Idx].wdatalen > 0 ) && ( ! My_Connections[Idx].zip.wdatalen )) return TRUE;
1008 #else
1009         if( ! My_Connections[Idx].wdatalen > 0 ) return TRUE;
1010 #endif
1011
1012         /* Timeout initialisieren: 0 Sekunden, also nicht blockieren */
1013         tv.tv_sec = 0; tv.tv_usec = 0;
1014
1015         FD_ZERO( &write_socket );
1016         FD_SET( My_Connections[Idx].sock, &write_socket );
1017         if( select( My_Connections[Idx].sock + 1, NULL, &write_socket, NULL, &tv ) == -1 )
1018         {
1019                 /* Fehler! */
1020                 if( errno != EINTR )
1021                 {
1022                         Log( LOG_ALERT, "Try_Write(): select() failed: %s (con=%d, sock=%d)!", strerror( errno ), Idx, My_Connections[Idx].sock );
1023                         Conn_Close( Idx, "Server error!", NULL, FALSE );
1024                         return FALSE;
1025                 }
1026         }
1027
1028         if( FD_ISSET( My_Connections[Idx].sock, &write_socket )) return Handle_Write( Idx );
1029         else return TRUE;
1030 } /* Try_Write */
1031
1032
1033 LOCAL VOID
1034 Handle_Read( INT Sock )
1035 {
1036         /* Aktivitaet auf einem Socket verarbeiten:
1037          *  - neue Clients annehmen,
1038          *  - Daten von Clients verarbeiten,
1039          *  - Resolver-Rueckmeldungen annehmen. */
1040
1041         CONN_ID idx;
1042
1043         assert( Sock > NONE );
1044
1045         if( FD_ISSET( Sock, &My_Listeners ))
1046         {
1047                 /* es ist einer unserer Listener-Sockets: es soll
1048                  * also eine neue Verbindung aufgebaut werden. */
1049
1050                 New_Connection( Sock );
1051         }
1052         else if( FD_ISSET( Sock, &Resolver_FDs ))
1053         {
1054                 /* Rueckmeldung von einem Resolver Sub-Prozess */
1055
1056                 Read_Resolver_Result( Sock );
1057         }
1058         else
1059         {
1060                 /* Ein Client Socket: entweder ein User oder Server */
1061
1062                 idx = Socket2Index( Sock );
1063                 if( idx > NONE ) Read_Request( idx );
1064         }
1065 } /* Handle_Read */
1066
1067
1068 LOCAL BOOLEAN
1069 Handle_Write( CONN_ID Idx )
1070 {
1071         /* Daten aus Schreibpuffer versenden bzw. Connection aufbauen */
1072
1073         INT len, res, err;
1074
1075         assert( Idx > NONE );
1076         assert( My_Connections[Idx].sock > NONE );
1077
1078         if( FD_ISSET( My_Connections[Idx].sock, &My_Connects ))
1079         {
1080                 /* es soll nichts geschrieben werden, sondern ein
1081                  * connect() hat ein Ergebnis geliefert */
1082
1083                 FD_CLR( My_Connections[Idx].sock, &My_Connects );
1084
1085                 /* Ergebnis des connect() ermitteln */
1086                 len = sizeof( err );
1087                 res = getsockopt( My_Connections[Idx].sock, SOL_SOCKET, SO_ERROR, &err, &len );
1088                 assert( len == sizeof( err ));
1089
1090                 /* Fehler aufgetreten? */
1091                 if(( res != 0 ) || ( err != 0 ))
1092                 {
1093                         /* Fehler! */
1094                         if( res != 0 ) Log( LOG_CRIT, "getsockopt (connection %d): %s!", Idx, strerror( errno ));
1095                         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 ));
1096
1097                         /* Socket etc. pp. aufraeumen */
1098                         FD_CLR( My_Connections[Idx].sock, &My_Sockets );
1099                         close( My_Connections[Idx].sock );
1100                         Init_Conn_Struct( Idx );
1101
1102                         /* Bei Server-Verbindungen lasttry-Zeitpunkt auf "jetzt" setzen */
1103                         Conf_Server[My_Connections[Idx].our_server].lasttry = time( NULL );
1104
1105                         return FALSE;
1106                 }
1107                 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 );
1108
1109                 /* PASS und SERVER verschicken */
1110                 Conn_WriteStr( Idx, "PASS %s %s", Conf_Server[My_Connections[Idx].our_server].pwd_out, NGIRCd_ProtoID );
1111                 return Conn_WriteStr( Idx, "SERVER %s :%s", Conf_ServerName, Conf_ServerInfo );
1112         }
1113
1114 #ifdef USE_ZLIB
1115         /* Schreibpuffer leer, aber noch Daten im Kompressionsbuffer?
1116          * Dann muss dieser nun geflushed werden! */
1117         if( My_Connections[Idx].wdatalen == 0 ) Zip_Flush( Idx );
1118 #endif
1119
1120         assert( My_Connections[Idx].wdatalen > 0 );
1121
1122         /* Daten schreiben */
1123         len = send( My_Connections[Idx].sock, My_Connections[Idx].wbuf, My_Connections[Idx].wdatalen, 0 );
1124         if( len < 0 )
1125         {
1126                 /* Operation haette Socket "nur" blockiert ... */
1127                 if( errno == EAGAIN ) return TRUE;
1128
1129                 /* Oops, ein Fehler! */
1130                 Log( LOG_ERR, "Write error on connection %d (socket %d): %s!", Idx, My_Connections[Idx].sock, strerror( errno ));
1131                 Conn_Close( Idx, "Write error!", NULL, FALSE );
1132                 return FALSE;
1133         }
1134
1135         /* Puffer anpassen */
1136         My_Connections[Idx].wdatalen -= len;
1137         memmove( My_Connections[Idx].wbuf, My_Connections[Idx].wbuf + len, My_Connections[Idx].wdatalen );
1138
1139         return TRUE;
1140 } /* Handle_Write */
1141
1142
1143 LOCAL VOID
1144 New_Connection( INT Sock )
1145 {
1146         /* Neue Client-Verbindung von Listen-Socket annehmen und
1147          * CLIENT-Struktur anlegen. */
1148
1149         struct sockaddr_in new_addr;
1150         INT new_sock, new_sock_len;
1151         RES_STAT *s;
1152         CONN_ID idx;
1153         CLIENT *c;
1154         POINTER *ptr;
1155         LONG new_size;
1156
1157         assert( Sock > NONE );
1158
1159         /* Connection auf Listen-Socket annehmen */
1160         new_sock_len = sizeof( new_addr );
1161         new_sock = accept( Sock, (struct sockaddr *)&new_addr, (socklen_t *)&new_sock_len );
1162         if( new_sock < 0 )
1163         {
1164                 Log( LOG_CRIT, "Can't accept connection: %s!", strerror( errno ));
1165                 return;
1166         }
1167
1168         /* Socket initialisieren */
1169         Init_Socket( new_sock );
1170
1171         /* Freie Connection-Struktur suchen */
1172         for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
1173         if( idx >= Pool_Size )
1174         {
1175                 new_size = Pool_Size + CONNECTION_POOL;
1176                 
1177                 /* Im bisherigen Pool wurde keine freie Connection-Struktur mehr gefunden.
1178                  * Wenn erlaubt und moeglich muss nun der Pool vergroessert werden: */
1179                 
1180                 if( Conf_MaxConnections > 0 )
1181                 {
1182                         /* Es ist ein Limit konfiguriert */
1183                         if( Pool_Size >= Conf_MaxConnections )
1184                         {
1185                                 /* Mehr Verbindungen duerfen wir leider nicht mehr annehmen ... */
1186                                 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached!", Pool_Size );
1187                                 close( new_sock );
1188                                 return;
1189                         }
1190                         if( new_size > Conf_MaxConnections ) new_size = Conf_MaxConnections;
1191                 }
1192                 
1193                 /* zunaechst realloc() versuchen; wenn das scheitert, malloc() versuchen
1194                  * und Daten ggf. "haendisch" umkopieren. (Haesslich! Eine wirklich
1195                  * dynamische Verwaltung waere wohl _deutlich_ besser ...) */
1196                 ptr = realloc( My_Connections, sizeof( CONNECTION ) * new_size );
1197                 if( ! ptr )
1198                 {
1199                         /* realloc() ist fehlgeschlagen. Nun malloc() probieren: */
1200                         ptr = malloc( sizeof( CONNECTION ) * new_size );
1201                         if( ! ptr )
1202                         {
1203                                 /* Offenbar steht kein weiterer Sepeicher zur Verfuegung :-( */
1204                                 Log( LOG_EMERG, "Can't allocate memory! [New_Connection]" );
1205                                 close( new_sock );
1206                                 return;
1207                         }
1208                         
1209                         /* Struktur umkopieren ... */
1210                         memcpy( ptr, My_Connections, sizeof( CONNECTION ) * Pool_Size );
1211                         
1212                         Log( LOG_DEBUG, "Allocated new connection pool for %ld items (%ld bytes). [malloc()/memcpy()]", new_size, sizeof( CONNECTION ) * new_size );
1213                 }
1214                 else Log( LOG_DEBUG, "Allocated new connection pool for %ld items (%ld bytes). [realloc()]", new_size, sizeof( CONNECTION ) * new_size );
1215                 
1216                 /* Adjust pointer to new block */
1217                 My_Connections = ptr;
1218                 
1219                 /* Initialize new items */
1220                 for( idx = Pool_Size; idx < new_size; idx++ ) Init_Conn_Struct( idx );
1221                 idx = Pool_Size;
1222                 
1223                 /* Adjust new pool size */
1224                 Pool_Size = new_size;
1225         }
1226
1227         /* Client-Struktur initialisieren */
1228         c = Client_NewLocal( idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWN, FALSE );
1229         if( ! c )
1230         {
1231                 Log( LOG_ALERT, "Can't accept connection: can't create client structure!" );
1232                 close( new_sock );
1233                 return;
1234         }
1235
1236         /* Verbindung registrieren */
1237         Init_Conn_Struct( idx );
1238         My_Connections[idx].sock = new_sock;
1239         My_Connections[idx].addr = new_addr;
1240
1241         /* Neuen Socket registrieren */
1242         FD_SET( new_sock, &My_Sockets );
1243         if( new_sock > Conn_MaxFD ) Conn_MaxFD = new_sock;
1244
1245         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 );
1246
1247         /* Hostnamen ermitteln */
1248         strcpy( My_Connections[idx].host, inet_ntoa( new_addr.sin_addr ));
1249         Client_SetHostname( c, My_Connections[idx].host );
1250         s = Resolve_Addr( &new_addr );
1251         if( s )
1252         {
1253                 /* Sub-Prozess wurde asyncron gestartet */
1254                 My_Connections[idx].res_stat = s;
1255         }
1256         
1257         /* Penalty-Zeit setzen */
1258         Conn_SetPenalty( idx, 4 );
1259 } /* New_Connection */
1260
1261
1262 LOCAL CONN_ID
1263 Socket2Index( INT Sock )
1264 {
1265         /* zum Socket passende Connection suchen */
1266
1267         CONN_ID idx;
1268
1269         assert( Sock > NONE );
1270
1271         for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == Sock ) break;
1272
1273         if( idx >= Pool_Size )
1274         {
1275                 /* die Connection wurde vermutlich (wegen eines
1276                  * Fehlers) bereits wieder abgebaut ... */
1277                 Log( LOG_DEBUG, "Socket2Index: can't get connection for socket %d!", Sock );
1278                 return NONE;
1279         }
1280         else return idx;
1281 } /* Socket2Index */
1282
1283
1284 LOCAL VOID
1285 Read_Request( CONN_ID Idx )
1286 {
1287         /* Daten von Socket einlesen und entsprechend behandeln.
1288          * Tritt ein Fehler auf, so wird der Socket geschlossen. */
1289
1290         INT len, bsize;
1291 #ifdef USE_ZLIB
1292         CLIENT *c;
1293 #endif
1294
1295         assert( Idx > NONE );
1296         assert( My_Connections[Idx].sock > NONE );
1297
1298         /* wenn noch nicht registriert: maximal mit ZREADBUFFER_LEN arbeiten,
1299          * ansonsten koennen Daten ggf. nicht umkopiert werden. */
1300         bsize = READBUFFER_LEN;
1301 #ifdef USE_ZLIB
1302         c = Client_GetFromConn( Idx );
1303         if(( Client_Type( c ) != CLIENT_USER ) && ( Client_Type( c ) != CLIENT_SERVER ) && ( Client_Type( c ) != CLIENT_SERVICE ) && ( bsize > ZREADBUFFER_LEN )) bsize = ZREADBUFFER_LEN;
1304 #endif
1305
1306 #ifdef USE_ZLIB
1307         if(( bsize - My_Connections[Idx].rdatalen - 1 < 1 ) || ( ZREADBUFFER_LEN - My_Connections[Idx].zip.rdatalen < 1 ))
1308 #else
1309         if( bsize - My_Connections[Idx].rdatalen - 1 < 1 )
1310 #endif
1311         {
1312                 /* Der Lesepuffer ist voll */
1313                 Log( LOG_ERR, "Read buffer overflow (connection %d): %d bytes!", Idx, My_Connections[Idx].rdatalen );
1314                 Conn_Close( Idx, "Read buffer overflow!", NULL, FALSE );
1315                 return;
1316         }
1317
1318 #ifdef USE_ZLIB
1319         if( My_Connections[Idx].options & CONN_ZIP )
1320         {
1321                 len = recv( My_Connections[Idx].sock, My_Connections[Idx].zip.rbuf + My_Connections[Idx].zip.rdatalen, ( ZREADBUFFER_LEN - My_Connections[Idx].zip.rdatalen ), 0 );
1322                 if( len > 0 ) My_Connections[Idx].zip.rdatalen += len;
1323         }
1324         else
1325 #endif
1326         {
1327                 len = recv( My_Connections[Idx].sock, My_Connections[Idx].rbuf + My_Connections[Idx].rdatalen, bsize - My_Connections[Idx].rdatalen - 1, 0 );
1328                 if( len > 0 ) My_Connections[Idx].rdatalen += len;
1329         }
1330
1331         if( len == 0 )
1332         {
1333                 /* Socket wurde geschlossen */
1334                 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 ));
1335                 Conn_Close( Idx, "Socket closed!", "Client closed connection", FALSE );
1336                 return;
1337         }
1338
1339         if( len < 0 )
1340         {
1341                 /* Operation haette Socket "nur" blockiert ... */
1342                 if( errno == EAGAIN ) return;
1343
1344                 /* Fehler beim Lesen */
1345                 Log( LOG_ERR, "Read error on connection %d (socket %d): %s!", Idx, My_Connections[Idx].sock, strerror( errno ));
1346                 Conn_Close( Idx, "Read error!", "Client closed connection", FALSE );
1347                 return;
1348         }
1349
1350         /* Connection-Statistik aktualisieren */
1351         My_Connections[Idx].bytes_in += len;
1352
1353         /* Timestamp aktualisieren */
1354         My_Connections[Idx].lastdata = time( NULL );
1355
1356         Handle_Buffer( Idx );
1357 } /* Read_Request */
1358
1359
1360 LOCAL BOOLEAN
1361 Handle_Buffer( CONN_ID Idx )
1362 {
1363         /* Daten im Lese-Puffer einer Verbindung verarbeiten.
1364          * Wurde ein Request verarbeitet, so wird TRUE geliefert,
1365          * ansonsten FALSE (auch bei Fehlern). */
1366
1367 #ifndef STRICT_RFC
1368         CHAR *ptr1, *ptr2;
1369 #endif
1370         CHAR *ptr;
1371         INT len, delta;
1372         BOOLEAN action, result;
1373 #ifdef USE_ZLIB
1374         BOOLEAN old_z;
1375 #endif
1376
1377         result = FALSE;
1378         do
1379         {
1380 #ifdef USE_ZLIB
1381                 /* ggf. noch unkomprimiete Daten weiter entpacken */
1382                 if( My_Connections[Idx].options & CONN_ZIP )
1383                 {
1384                         if( ! Unzip_Buffer( Idx )) return FALSE;
1385                 }
1386 #endif
1387         
1388                 if( My_Connections[Idx].rdatalen < 1 ) break;
1389
1390                 /* Eine komplette Anfrage muss mit CR+LF enden, vgl.
1391                  * RFC 2812. Haben wir eine? */
1392                 My_Connections[Idx].rbuf[My_Connections[Idx].rdatalen] = '\0';
1393                 ptr = strstr( My_Connections[Idx].rbuf, "\r\n" );
1394         
1395                 if( ptr ) delta = 2;
1396 #ifndef STRICT_RFC
1397                 else
1398                 {
1399                         /* Nicht RFC-konforme Anfrage mit nur CR oder LF? Leider
1400                          * machen soetwas viele Clients, u.a. "mIRC" :-( */
1401                         ptr1 = strchr( My_Connections[Idx].rbuf, '\r' );
1402                         ptr2 = strchr( My_Connections[Idx].rbuf, '\n' );
1403                         delta = 1;
1404                         if( ptr1 && ptr2 ) ptr = ptr1 > ptr2 ? ptr2 : ptr1;
1405                         else if( ptr1 ) ptr = ptr1;
1406                         else if( ptr2 ) ptr = ptr2;
1407                 }
1408 #endif
1409         
1410                 action = FALSE;
1411                 if( ptr )
1412                 {
1413                         /* Ende der Anfrage wurde gefunden */
1414                         *ptr = '\0';
1415                         len = ( ptr - My_Connections[Idx].rbuf ) + delta;
1416                         if( len > ( COMMAND_LEN - 1 ))
1417                         {
1418                                 /* Eine Anfrage darf(!) nicht laenger als 512 Zeichen
1419                                  * (incl. CR+LF!) werden; vgl. RFC 2812. Wenn soetwas
1420                                  * empfangen wird, wird der Client disconnectiert. */
1421                                 Log( LOG_ERR, "Request too long (connection %d): %d bytes (max. %d expected)!", Idx, My_Connections[Idx].rdatalen, COMMAND_LEN - 1 );
1422                                 Conn_Close( Idx, NULL, "Request too long", TRUE );
1423                                 return FALSE;
1424                         }
1425
1426 #ifdef USE_ZLIB
1427                         /* merken, ob Stream bereits komprimiert wird */
1428                         old_z = My_Connections[Idx].options & CONN_ZIP;
1429 #endif
1430
1431                         if( len > delta )
1432                         {
1433                                 /* Es wurde ein Request gelesen */
1434                                 My_Connections[Idx].msg_in++;
1435                                 if( ! Parse_Request( Idx, My_Connections[Idx].rbuf )) return FALSE;
1436                                 else action = TRUE;
1437                         }
1438
1439                         /* Puffer anpassen */
1440                         My_Connections[Idx].rdatalen -= len;
1441                         memmove( My_Connections[Idx].rbuf, My_Connections[Idx].rbuf + len, My_Connections[Idx].rdatalen );
1442
1443 #ifdef USE_ZLIB
1444                         if(( ! old_z ) && ( My_Connections[Idx].options & CONN_ZIP ) && ( My_Connections[Idx].rdatalen > 0 ))
1445                         {
1446                                 /* Mit dem letzten Befehl wurde Socket-Kompression aktiviert.
1447                                  * Evtl. schon vom Socket gelesene Daten in den Unzip-Puffer
1448                                  * umkopieren, damit diese nun zunaechst entkomprimiert werden */
1449                                 {
1450                                         if( My_Connections[Idx].rdatalen > ZREADBUFFER_LEN )
1451                                         {
1452                                                 /* Hupsa! Soviel Platz haben wir aber gar nicht! */
1453                                                 Log( LOG_ALERT, "Can't move read buffer: No space left in unzip buffer (need %d bytes)!", My_Connections[Idx].rdatalen );
1454                                                 return FALSE;
1455                                         }
1456                                         memcpy( My_Connections[Idx].zip.rbuf, My_Connections[Idx].rbuf, My_Connections[Idx].rdatalen );
1457                                         My_Connections[Idx].zip.rdatalen = My_Connections[Idx].rdatalen;
1458                                         My_Connections[Idx].rdatalen = 0;
1459                                         Log( LOG_DEBUG, "Moved already received data (%d bytes) to uncompression buffer.", My_Connections[Idx].zip.rdatalen );
1460                                 }
1461                         }
1462 #endif
1463                 }
1464                 
1465                 if( action ) result = TRUE;
1466         } while( action );
1467         
1468         return result;
1469 } /* Handle_Buffer */
1470
1471
1472 LOCAL VOID
1473 Check_Connections( VOID )
1474 {
1475         /* Pruefen, ob Verbindungen noch "alive" sind. Ist dies
1476          * nicht der Fall, zunaechst PING-PONG spielen und, wenn
1477          * auch das nicht "hilft", Client disconnectieren. */
1478
1479         CLIENT *c;
1480         LONG i;
1481
1482         for( i = 0; i < Pool_Size; i++ )
1483         {
1484                 if( My_Connections[i].sock == NONE ) continue;
1485
1486                 c = Client_GetFromConn( i );
1487                 if( c && (( Client_Type( c ) == CLIENT_USER ) || ( Client_Type( c ) == CLIENT_SERVER ) || ( Client_Type( c ) == CLIENT_SERVICE )))
1488                 {
1489                         /* verbundener User, Server oder Service */
1490                         if( My_Connections[i].lastping > My_Connections[i].lastdata )
1491                         {
1492                                 /* es wurde bereits ein PING gesendet */
1493                                 if( My_Connections[i].lastping < time( NULL ) - Conf_PongTimeout )
1494                                 {
1495                                         /* Timeout */
1496                                         Log( LOG_DEBUG, "Connection %d: Ping timeout: %d seconds.", i, Conf_PongTimeout );
1497                                         Conn_Close( i, NULL, "Ping timeout", TRUE );
1498                                 }
1499                         }
1500                         else if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout )
1501                         {
1502                                 /* es muss ein PING gesendet werden */
1503                                 Log( LOG_DEBUG, "Connection %d: sending PING ...", i );
1504                                 My_Connections[i].lastping = time( NULL );
1505                                 Conn_WriteStr( i, "PING :%s", Client_ID( Client_ThisServer( )));
1506                         }
1507                 }
1508                 else
1509                 {
1510                         /* noch nicht vollstaendig aufgebaute Verbindung */
1511                         if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout )
1512                         {
1513                                 /* Timeout */
1514                                 Log( LOG_DEBUG, "Connection %d timed out ...", i );
1515                                 Conn_Close( i, NULL, "Timeout", FALSE );
1516                         }
1517                 }
1518         }
1519 } /* Check_Connections */
1520
1521
1522 LOCAL VOID
1523 Check_Servers( VOID )
1524 {
1525         /* Pruefen, ob Server-Verbindungen aufgebaut werden
1526          * muessen bzw. koennen */
1527
1528         RES_STAT *s;
1529         LONG idx, n;
1530         INT i;
1531
1532         /* Wenn "Passive-Mode" aktiv: nicht verbinden */
1533         if( NGIRCd_Passive ) return;
1534
1535         for( i = 0; i < Conf_Server_Count; i++ )
1536         {
1537                 /* Ist ein Hostname und Port definiert? */
1538                 if(( ! Conf_Server[i].host[0] ) || ( ! Conf_Server[i].port > 0 )) continue;
1539
1540                 /* Haben wir schon eine Verbindung? */
1541                 for( n = 0; n < Pool_Size; n++ )
1542                 {
1543                         if( My_Connections[n].sock == NONE ) continue;
1544                         
1545                         /* Verbindung zu diesem Server? */
1546                         if( My_Connections[n].our_server == i )
1547                         {
1548                                 /* Komplett aufgebaute Verbindung? */
1549                                 if( My_Connections[n].sock > NONE ) break;
1550
1551                                 /* IP schon aufgeloest? */
1552                                 if( My_Connections[n].res_stat == NULL ) New_Server( i, n );
1553                         }
1554
1555                         /* Verbindung in dieser Server-Gruppe? */
1556                         if(( My_Connections[n].our_server != NONE ) && ( Conf_Server[i].group != NONE ))
1557                         {
1558                                 if( Conf_Server[My_Connections[n].our_server].group == Conf_Server[i].group ) break;
1559                         }
1560                 }
1561                 if( n < Pool_Size ) continue;
1562
1563                 /* Wann war der letzte Connect-Versuch? */
1564                 if( Conf_Server[i].lasttry > time( NULL ) - Conf_ConnectRetry ) continue;
1565
1566                 /* Okay, Verbindungsaufbau versuchen */
1567                 Conf_Server[i].lasttry = time( NULL );
1568
1569                 /* Freie Connection-Struktur suschen */
1570                 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
1571                 if( idx >= Pool_Size )
1572                 {
1573                         Log( LOG_ALERT, "Can't establist server connection: connection limit reached (%d)!", Pool_Size );
1574                         return;
1575                 }
1576                 Log( LOG_DEBUG, "Preparing connection %d for \"%s\" ...", idx, Conf_Server[i].host );
1577
1578                 /* Verbindungs-Struktur initialisieren */
1579                 Init_Conn_Struct( idx );
1580                 My_Connections[idx].sock = SERVER_WAIT;
1581                 My_Connections[idx].our_server = i;
1582
1583                 /* Hostnamen in IP aufloesen (Default bzw. im Fehlerfall: versuchen, den
1584                  * konfigurierten Text direkt als IP-Adresse zu verwenden ... */
1585                 strcpy( Conf_Server[My_Connections[idx].our_server].ip, Conf_Server[i].host );
1586                 strcpy( My_Connections[idx].host, Conf_Server[i].host );
1587                 s = Resolve_Name( Conf_Server[i].host );
1588                 if( s )
1589                 {
1590                         /* Sub-Prozess wurde asyncron gestartet */
1591                         My_Connections[idx].res_stat = s;
1592                 }
1593         }
1594 } /* Check_Servers */
1595
1596
1597 LOCAL VOID
1598 New_Server( INT Server, CONN_ID Idx )
1599 {
1600         /* Neue Server-Verbindung aufbauen */
1601
1602         struct sockaddr_in new_addr;
1603         struct in_addr inaddr;
1604         INT res, new_sock;
1605         CLIENT *c;
1606
1607         assert( Server > NONE );
1608         assert( Idx > NONE );
1609
1610         /* Wurde eine gueltige IP-Adresse gefunden? */
1611         if( ! Conf_Server[Server].ip[0] )
1612         {
1613                 /* Nein. Verbindung wieder freigeben: */
1614                 Init_Conn_Struct( Idx );
1615                 Log( LOG_ERR, "Can't connect to \"%s\" (connection %d): ip address unknown!", Conf_Server[Server].host, Idx );
1616                 return;
1617         }
1618
1619         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 );
1620
1621 #ifdef HAVE_INET_ATON
1622         if( inet_aton( Conf_Server[Server].ip, &inaddr ) == 0 )
1623 #else
1624         memset( &inaddr, 0, sizeof( inaddr ));
1625         inaddr.s_addr = inet_addr( Conf_Server[Server].ip );
1626         if( inaddr.s_addr == (unsigned)-1 )
1627 #endif
1628         {
1629                 /* Konnte Adresse nicht konvertieren */
1630                 Init_Conn_Struct( Idx );
1631                 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 );
1632                 return;
1633         }
1634
1635         memset( &new_addr, 0, sizeof( new_addr ));
1636         new_addr.sin_family = AF_INET;
1637         new_addr.sin_addr = inaddr;
1638         new_addr.sin_port = htons( Conf_Server[Server].port );
1639
1640         new_sock = socket( PF_INET, SOCK_STREAM, 0 );
1641         if ( new_sock < 0 )
1642         {
1643                 Init_Conn_Struct( Idx );
1644                 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
1645                 return;
1646         }
1647
1648         if( ! Init_Socket( new_sock )) return;
1649
1650         res = connect( new_sock, (struct sockaddr *)&new_addr, sizeof( new_addr ));
1651         if(( res != 0 ) && ( errno != EINPROGRESS ))
1652         {
1653                 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1654                 close( new_sock );
1655                 Init_Conn_Struct( Idx );
1656                 return;
1657         }
1658
1659         /* Client-Struktur initialisieren */
1660         c = Client_NewLocal( Idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWNSERVER, FALSE );
1661         if( ! c )
1662         {
1663                 close( new_sock );
1664                 Init_Conn_Struct( Idx );
1665                 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1666                 return;
1667         }
1668         Client_SetIntroducer( c, c );
1669         Client_SetToken( c, TOKEN_OUTBOUND );
1670
1671         /* Verbindung registrieren */
1672         My_Connections[Idx].sock = new_sock;
1673         My_Connections[Idx].addr = new_addr;
1674         strcpy( My_Connections[Idx].host, Conf_Server[Server].host );
1675
1676         /* Neuen Socket registrieren */
1677         FD_SET( new_sock, &My_Sockets );
1678         FD_SET( new_sock, &My_Connects );
1679         if( new_sock > Conn_MaxFD ) Conn_MaxFD = new_sock;
1680         
1681         Log( LOG_DEBUG, "Registered new connection %d on socket %d.", Idx, My_Connections[Idx].sock );
1682 } /* New_Server */
1683
1684
1685 LOCAL VOID
1686 Init_Conn_Struct( LONG Idx )
1687 {
1688         /* Connection-Struktur initialisieren */
1689
1690         My_Connections[Idx].sock = NONE;
1691         My_Connections[Idx].res_stat = NULL;
1692         My_Connections[Idx].host[0] = '\0';
1693         My_Connections[Idx].rbuf[0] = '\0';
1694         My_Connections[Idx].rdatalen = 0;
1695         My_Connections[Idx].wbuf[0] = '\0';
1696         My_Connections[Idx].wdatalen = 0;
1697         My_Connections[Idx].our_server = NONE;
1698         My_Connections[Idx].starttime = time( NULL );
1699         My_Connections[Idx].lastdata = time( NULL );
1700         My_Connections[Idx].lastping = 0;
1701         My_Connections[Idx].lastprivmsg = time( NULL );
1702         My_Connections[Idx].delaytime = 0;
1703         My_Connections[Idx].bytes_in = 0;
1704         My_Connections[Idx].bytes_out = 0;
1705         My_Connections[Idx].msg_in = 0;
1706         My_Connections[Idx].msg_out = 0;
1707         My_Connections[Idx].flag = 0;
1708         My_Connections[Idx].options = 0;
1709
1710 #ifdef USE_ZLIB
1711         My_Connections[Idx].zip.rbuf[0] = '\0';
1712         My_Connections[Idx].zip.rdatalen = 0;
1713         My_Connections[Idx].zip.wbuf[0] = '\0';
1714         My_Connections[Idx].zip.wdatalen = 0;
1715         My_Connections[Idx].zip.bytes_in = 0;
1716         My_Connections[Idx].zip.bytes_out = 0;
1717 #endif
1718 } /* Init_Conn_Struct */
1719
1720
1721 LOCAL BOOLEAN
1722 Init_Socket( INT Sock )
1723 {
1724         /* Socket-Optionen setzen */
1725
1726         INT on = 1;
1727
1728 #ifdef O_NONBLOCK       /* A/UX kennt das nicht? */
1729         if( fcntl( Sock, F_SETFL, O_NONBLOCK ) != 0 )
1730         {
1731                 Log( LOG_CRIT, "Can't enable non-blocking mode: %s!", strerror( errno ));
1732                 close( Sock );
1733                 return FALSE;
1734         }
1735 #endif
1736         if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &on, (socklen_t)sizeof( on )) != 0)
1737         {
1738                 Log( LOG_ERR, "Can't set socket options: %s!", strerror( errno ));
1739                 /* dieser Fehler kann ignoriert werden. */
1740         }
1741
1742         return TRUE;
1743 } /* Init_Socket */
1744
1745
1746 LOCAL VOID
1747 Read_Resolver_Result( INT r_fd )
1748 {
1749         /* Ergebnis von Resolver Sub-Prozess aus Pipe lesen
1750          * und entsprechende Connection aktualisieren */
1751
1752         CHAR result[HOST_LEN];
1753         CLIENT *c;
1754         INT len, i;
1755
1756         FD_CLR( r_fd, &Resolver_FDs );
1757
1758         /* Anfrage vom Parent lesen */
1759         len = read( r_fd, result, HOST_LEN - 1 );
1760         if( len < 0 )
1761         {
1762                 /* Fehler beim Lesen aus der Pipe */
1763                 close( r_fd );
1764                 Log( LOG_CRIT, "Resolver: Can't read result: %s!", strerror( errno ));
1765                 return;
1766         }
1767         result[len] = '\0';
1768
1769         /* zugehoerige Connection suchen */
1770         for( i = 0; i < Pool_Size; i++ )
1771         {
1772                 if(( My_Connections[i].sock != NONE ) && ( My_Connections[i].res_stat ) && ( My_Connections[i].res_stat->pipe[0] == r_fd )) break;
1773         }
1774         if( i >= Pool_Size )
1775         {
1776                 /* Opsa! Keine passende Connection gefunden!? Vermutlich
1777                  * wurde sie schon wieder geschlossen. */
1778                 close( r_fd );
1779                 Log( LOG_DEBUG, "Resolver: Got result for unknown connection!?" );
1780                 return;
1781         }
1782
1783         Log( LOG_DEBUG, "Resolver: %s is \"%s\".", My_Connections[i].host, result );
1784         
1785         /* Aufraeumen */
1786         close( My_Connections[i].res_stat->pipe[0] );
1787         close( My_Connections[i].res_stat->pipe[1] );
1788         free( My_Connections[i].res_stat );
1789         My_Connections[i].res_stat = NULL;
1790
1791         if( My_Connections[i].sock > NONE )
1792         {
1793                 /* Eingehende Verbindung: Hostnamen setzen */
1794                 c = Client_GetFromConn( i );
1795                 assert( c != NULL );
1796                 strcpy( My_Connections[i].host, result );
1797                 Client_SetHostname( c, result );
1798         }
1799         else
1800         {
1801                 /* Ausgehende Verbindung (=Server): IP setzen */
1802                 assert( My_Connections[i].our_server > NONE );
1803                 strcpy( Conf_Server[My_Connections[i].our_server].ip, result );
1804         }
1805
1806         /* Penalty-Zeit zurueck setzen */
1807         Conn_ResetPenalty( i );
1808 } /* Read_Resolver_Result */
1809
1810
1811 #ifdef USE_ZLIB
1812
1813 LOCAL BOOLEAN
1814 Zip_Buffer( CONN_ID Idx, CHAR *Data, INT Len )
1815 {
1816         /* Daten zum Komprimieren im "Kompressions-Puffer" sammeln.
1817          * Es wird TRUE bei Erfolg, sonst FALSE geliefert. */
1818
1819         assert( Idx > NONE );
1820         assert( Data != NULL );
1821         assert( Len > 0 );
1822
1823         /* Ist noch Platz im Kompressions-Puffer? */
1824         if( ZWRITEBUFFER_LEN - My_Connections[Idx].zip.wdatalen < Len + 50 )
1825         {
1826                 /* Nein! Puffer zunaechst leeren ...*/
1827                 if( ! Zip_Flush( Idx )) return FALSE;
1828         }
1829
1830         /* Daten kopieren */
1831         memmove( My_Connections[Idx].zip.wbuf + My_Connections[Idx].zip.wdatalen, Data, Len );
1832         My_Connections[Idx].zip.wdatalen += Len;
1833
1834         return TRUE;
1835 } /* Zip_Buffer */
1836
1837
1838 LOCAL BOOLEAN
1839 Zip_Flush( CONN_ID Idx )
1840 {
1841         /* Daten komprimieren und in Schreibpuffer kopieren.
1842          * Es wird TRUE bei Erfolg, sonst FALSE geliefert. */
1843
1844         INT result, out_len;
1845         z_stream *out;
1846
1847         out = &My_Connections[Idx].zip.out;
1848
1849         out->next_in = My_Connections[Idx].zip.wbuf;
1850         out->avail_in = My_Connections[Idx].zip.wdatalen;
1851         out->next_out = My_Connections[Idx].wbuf + My_Connections[Idx].wdatalen;
1852         out->avail_out = WRITEBUFFER_LEN - My_Connections[Idx].wdatalen;
1853
1854         result = deflate( out, Z_SYNC_FLUSH );
1855         if(( result != Z_OK ) || ( out->avail_in > 0 ))
1856         {
1857                 Log( LOG_ALERT, "Compression error: code %d!?", result );
1858                 Conn_Close( Idx, "Compression error!", NULL, FALSE );
1859                 return FALSE;
1860         }
1861
1862         out_len = WRITEBUFFER_LEN - My_Connections[Idx].wdatalen - out->avail_out;
1863         My_Connections[Idx].wdatalen += out_len;
1864         My_Connections[Idx].bytes_out += out_len;
1865         My_Connections[Idx].zip.bytes_out += My_Connections[Idx].zip.wdatalen;
1866         My_Connections[Idx].zip.wdatalen = 0;
1867         
1868         return TRUE;
1869 } /* Zip_Flush */
1870
1871
1872 LOCAL BOOLEAN
1873 Unzip_Buffer( CONN_ID Idx )
1874 {
1875         /* Daten entpacken und in Lesepuffer kopieren. Bei Fehlern
1876          * wird FALSE geliefert, ansonsten TRUE. Der Fall, dass keine
1877          * Daten mehr zu entpacken sind, ist _kein_ Fehler! */
1878
1879         INT result, in_len, out_len;
1880         z_stream *in;
1881
1882         assert( Idx > NONE );
1883
1884         if( My_Connections[Idx].zip.rdatalen <= 0 ) return TRUE;
1885
1886         in = &My_Connections[Idx].zip.in;
1887
1888         in->next_in = My_Connections[Idx].zip.rbuf;
1889         in->avail_in = My_Connections[Idx].zip.rdatalen;
1890         in->next_out = My_Connections[Idx].rbuf + My_Connections[Idx].rdatalen;
1891         in->avail_out = READBUFFER_LEN - My_Connections[Idx].rdatalen - 1;
1892
1893         result = inflate( in, Z_SYNC_FLUSH );
1894         if( result != Z_OK )
1895         {
1896                 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 );
1897                 Conn_Close( Idx, "Decompression error!", NULL, FALSE );
1898                 return FALSE;
1899         }
1900
1901         in_len = My_Connections[Idx].zip.rdatalen - in->avail_in;
1902         out_len = READBUFFER_LEN - My_Connections[Idx].rdatalen - 1 - in->avail_out;
1903         My_Connections[Idx].rdatalen += out_len;
1904
1905         if( in->avail_in > 0 )
1906         {
1907                 /* es konnten nicht alle Daten entpackt werden, vermutlich war
1908                  * im Ziel-Puffer kein Platz mehr. Umkopieren ... */
1909                 My_Connections[Idx].zip.rdatalen -= in_len;
1910                 memmove( My_Connections[Idx].zip.rbuf, My_Connections[Idx].zip.rbuf + in_len, My_Connections[Idx].zip.rdatalen );
1911         }
1912         else My_Connections[Idx].zip.rdatalen = 0;
1913         My_Connections[Idx].zip.bytes_in += out_len;
1914
1915         return TRUE;
1916 } /* Unzip_Buffer */
1917
1918
1919 #endif
1920
1921
1922 /* -eof- */