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