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