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