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