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