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