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