]> arthur.barton.de Git - ngircd-alex.git/blob - src/ngircd/conn.c
351a245990615b7b761903c77d24f537a1f73325
[ngircd-alex.git] / src / ngircd / conn.c
1 /*
2  * ngIRCd -- The Next Generation IRC Daemon
3  * Copyright (c)2001-2004 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.130 2004/01/25 16:06:35 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 = 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         DOUBLE in_k, out_k;
618 #ifdef ZLIB
619         DOUBLE in_z_k, out_z_k;
620         INT in_p, out_p;
621 #endif
622
623         assert( Idx > NONE );
624         assert( My_Connections[Idx].sock > 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         /* Mark link as "closing" */
635         My_Connections[Idx].options |= CONN_ISCLOSING;
636
637         /* Search client, if any */
638         c = Client_GetFromConn( Idx );
639
640         /* Should the client be informed? */
641         if( InformClient )
642         {
643 #ifndef STRICT_RFC
644                 /* Send statistics to client if registered as user: */
645                 if(( c != NULL ) && ( Client_Type( c ) == CLIENT_USER ))
646                 {
647                         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 );
648                 }
649 #endif
650
651                 /* Send ERROR to client (see RFC!) */
652                 if( FwdMsg ) Conn_WriteStr( Idx, "ERROR :%s", FwdMsg );
653                 else Conn_WriteStr( Idx, "ERROR :Closing connection." );
654                 if( My_Connections[Idx].sock == NONE ) return;
655         }
656
657         /* Try to write out the write buffer */
658         (VOID)Try_Write( Idx );
659
660         /* Shut down socket */
661         if( close( My_Connections[Idx].sock ) != 0 )
662         {
663                 /* Oops, we can't close the socket!? This is fatal! */
664                 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 ));
665                 Log( LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE_NAME );
666                 exit( 1 );
667         }
668
669         /* Mark socket as invalid: */
670         FD_CLR( My_Connections[Idx].sock, &My_Sockets );
671         FD_CLR( My_Connections[Idx].sock, &My_Connects );
672         My_Connections[Idx].sock = NONE;
673
674         /* If there is still a client, unregister it now */
675         if( c ) Client_Destroy( c, LogMsg, FwdMsg, TRUE );
676
677         /* Calculate statistics and log information */
678         in_k = (DOUBLE)My_Connections[Idx].bytes_in / 1024;
679         out_k = (DOUBLE)My_Connections[Idx].bytes_out / 1024;
680 #ifdef ZLIB
681         if( My_Connections[Idx].options & CONN_ZIP )
682         {
683                 in_z_k = (DOUBLE)My_Connections[Idx].zip.bytes_in / 1024;
684                 out_z_k = (DOUBLE)My_Connections[Idx].zip.bytes_out / 1024;
685                 in_p = (INT)(( in_k * 100 ) / in_z_k );
686                 out_p = (INT)(( out_k * 100 ) / out_z_k );
687                 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 );
688         }
689         else
690 #endif
691         {
692                 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 );
693         }
694
695         /* Is there a resolver sub-process running? */
696         if( My_Connections[Idx].res_stat )
697         {
698                 /* Free resolver structures */
699                 FD_CLR( My_Connections[Idx].res_stat->pipe[0], &Resolver_FDs );
700                 close( My_Connections[Idx].res_stat->pipe[0] );
701                 close( My_Connections[Idx].res_stat->pipe[1] );
702                 free( My_Connections[Idx].res_stat );
703         }
704
705         /* Servers: Modify time of next connect attempt? */
706         Conf_UnsetServer( Idx );
707
708 #ifdef ZLIB
709         /* Clean up zlib, if link was compressed */
710         if( Conn_Options( Idx ) & CONN_ZIP )
711         {
712                 inflateEnd( &My_Connections[Idx].zip.in );
713                 deflateEnd( &My_Connections[Idx].zip.out );
714         }
715 #endif
716
717         /* Clean up connection structure (=free it) */
718         Init_Conn_Struct( Idx );
719 } /* Conn_Close */
720
721
722 GLOBAL VOID
723 Conn_SyncServerStruct( VOID )
724 {
725         /* Synchronize server structures (connection IDs):
726          * connections <-> configuration */
727
728         CLIENT *client;
729         CONN_ID i;
730         INT c;
731
732         for( i = 0; i < Pool_Size; i++ )
733         {
734                 /* Established connection? */
735                 if( My_Connections[i].sock <= NONE ) continue;
736
737                 /* Server connection? */
738                 client = Client_GetFromConn( i );
739                 if(( ! client ) || ( Client_Type( client ) != CLIENT_SERVER )) continue;
740
741                 for( c = 0; c < MAX_SERVERS; c++ )
742                 {
743                         /* Configured server? */
744                         if( ! Conf_Server[c].host[0] ) continue;
745
746                         /* Duplicate? */
747                         if( strcmp( Conf_Server[c].name, Client_ID( client )) == 0 ) Conf_Server[c].conn_id = i;
748                 }
749         }
750 } /* SyncServerStruct */
751
752
753 LOCAL BOOLEAN
754 Try_Write( CONN_ID Idx )
755 {
756         /* Versuchen, Daten aus dem Schreib-Puffer in den Socket zu
757          * schreiben. TRUE wird geliefert, wenn entweder keine Daten
758          * zum Versenden vorhanden sind oder erfolgreich bearbeitet
759          * werden konnten. Im Fehlerfall wird FALSE geliefert und
760          * die Verbindung geschlossen. */
761
762         fd_set write_socket;
763         struct timeval tv;
764
765         assert( Idx > NONE );
766         assert( My_Connections[Idx].sock > NONE );
767
768         /* sind ueberhaupt Daten vorhanden? */
769 #ifdef ZLIB
770         if(( ! My_Connections[Idx].wdatalen > 0 ) && ( ! My_Connections[Idx].zip.wdatalen )) return TRUE;
771 #else
772         if( ! My_Connections[Idx].wdatalen > 0 ) return TRUE;
773 #endif
774
775         /* Timeout initialisieren: 0 Sekunden, also nicht blockieren */
776         tv.tv_sec = 0; tv.tv_usec = 0;
777
778         FD_ZERO( &write_socket );
779         FD_SET( My_Connections[Idx].sock, &write_socket );
780         if( select( My_Connections[Idx].sock + 1, NULL, &write_socket, NULL, &tv ) == -1 )
781         {
782                 /* Fehler! */
783                 if( errno != EINTR )
784                 {
785                         Log( LOG_ALERT, "Try_Write(): select() failed: %s (con=%d, sock=%d)!", strerror( errno ), Idx, My_Connections[Idx].sock );
786                         Conn_Close( Idx, "Server error!", NULL, FALSE );
787                         return FALSE;
788                 }
789         }
790
791         if( FD_ISSET( My_Connections[Idx].sock, &write_socket )) return Handle_Write( Idx );
792         else return TRUE;
793 } /* Try_Write */
794
795
796 LOCAL VOID
797 Handle_Read( INT Sock )
798 {
799         /* Aktivitaet auf einem Socket verarbeiten:
800          *  - neue Clients annehmen,
801          *  - Daten von Clients verarbeiten,
802          *  - Resolver-Rueckmeldungen annehmen. */
803
804         CONN_ID idx;
805
806         assert( Sock > NONE );
807
808         if( FD_ISSET( Sock, &My_Listeners ))
809         {
810                 /* es ist einer unserer Listener-Sockets: es soll
811                  * also eine neue Verbindung aufgebaut werden. */
812
813                 New_Connection( Sock );
814         }
815         else if( FD_ISSET( Sock, &Resolver_FDs ))
816         {
817                 /* Rueckmeldung von einem Resolver Sub-Prozess */
818
819                 Read_Resolver_Result( Sock );
820         }
821         else
822         {
823                 /* Ein Client Socket: entweder ein User oder Server */
824
825                 idx = Socket2Index( Sock );
826                 if( idx > NONE ) Read_Request( idx );
827         }
828 } /* Handle_Read */
829
830
831 LOCAL BOOLEAN
832 Handle_Write( CONN_ID Idx )
833 {
834         /* Daten aus Schreibpuffer versenden bzw. Connection aufbauen */
835
836         INT len, res, err;
837         socklen_t sock_len;
838         CLIENT *c;
839
840         assert( Idx > NONE );
841         assert( My_Connections[Idx].sock > NONE );
842
843         if( FD_ISSET( My_Connections[Idx].sock, &My_Connects ))
844         {
845                 /* es soll nichts geschrieben werden, sondern ein
846                  * connect() hat ein Ergebnis geliefert */
847
848                 FD_CLR( My_Connections[Idx].sock, &My_Connects );
849
850                 /* Ergebnis des connect() ermitteln */
851                 sock_len = sizeof( err );
852                 res = getsockopt( My_Connections[Idx].sock, SOL_SOCKET, SO_ERROR, &err, &sock_len );
853                 assert( sock_len == sizeof( err ));
854
855                 /* Fehler aufgetreten? */
856                 if(( res != 0 ) || ( err != 0 ))
857                 {
858                         /* Fehler! */
859                         if( res != 0 ) Log( LOG_CRIT, "getsockopt (connection %d): %s!", Idx, strerror( errno ));
860                         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 ));
861
862                         /* Clean up socket, connection and client structures */
863                         FD_CLR( My_Connections[Idx].sock, &My_Sockets );
864                         c = Client_GetFromConn( Idx );
865                         if( c ) Client_DestroyNow( c );
866                         close( My_Connections[Idx].sock );
867                         Init_Conn_Struct( Idx );
868
869                         /* Bei Server-Verbindungen lasttry-Zeitpunkt auf "jetzt" setzen */
870                         Conf_Server[Conf_GetServer( Idx )].lasttry = time( NULL );
871                         Conf_UnsetServer( Idx );
872
873                         return FALSE;
874                 }
875 #ifdef DEBUG
876                 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 );
877 #endif
878
879                 /* PASS und SERVER verschicken */
880                 Conn_WriteStr( Idx, "PASS %s %s", Conf_Server[Conf_GetServer( Idx )].pwd_out, NGIRCd_ProtoID );
881                 return Conn_WriteStr( Idx, "SERVER %s :%s", Conf_ServerName, Conf_ServerInfo );
882         }
883
884 #ifdef ZLIB
885         /* Schreibpuffer leer, aber noch Daten im Kompressionsbuffer?
886          * Dann muss dieser nun geflushed werden! */
887         if( My_Connections[Idx].wdatalen == 0 ) Zip_Flush( Idx );
888 #endif
889
890         assert( My_Connections[Idx].wdatalen > 0 );
891
892         /* Daten schreiben */
893         len = send( My_Connections[Idx].sock, My_Connections[Idx].wbuf, My_Connections[Idx].wdatalen, 0 );
894         if( len < 0 )
895         {
896                 /* Operation haette Socket "nur" blockiert ... */
897                 if( errno == EAGAIN ) return TRUE;
898
899                 /* Oops, ein Fehler! */
900                 Log( LOG_ERR, "Write error on connection %d (socket %d): %s!", Idx, My_Connections[Idx].sock, strerror( errno ));
901                 Conn_Close( Idx, "Write error!", NULL, FALSE );
902                 return FALSE;
903         }
904
905         /* Puffer anpassen */
906         My_Connections[Idx].wdatalen -= len;
907         memmove( My_Connections[Idx].wbuf, My_Connections[Idx].wbuf + len, My_Connections[Idx].wdatalen );
908
909         return TRUE;
910 } /* Handle_Write */
911
912
913 LOCAL VOID
914 New_Connection( INT Sock )
915 {
916         /* Neue Client-Verbindung von Listen-Socket annehmen und
917          * CLIENT-Struktur anlegen. */
918
919 #ifdef TCPWRAP
920         struct request_info req;
921 #endif
922         struct sockaddr_in new_addr;
923         INT new_sock, new_sock_len;
924         RES_STAT *s;
925         CONN_ID idx;
926         CLIENT *c;
927         POINTER *ptr;
928         LONG new_size, cnt;
929
930         assert( Sock > NONE );
931
932         /* Connection auf Listen-Socket annehmen */
933         new_sock_len = sizeof( new_addr );
934         new_sock = accept( Sock, (struct sockaddr *)&new_addr, (socklen_t *)&new_sock_len );
935         if( new_sock < 0 )
936         {
937                 Log( LOG_CRIT, "Can't accept connection: %s!", strerror( errno ));
938                 return;
939         }
940
941 #ifdef TCPWRAP
942         /* Validate socket using TCP Wrappers */
943         request_init( &req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock, RQ_CLIENT_SIN, &new_addr, NULL );
944         if( ! hosts_access( &req ))
945         {
946                 /* Access denied! */
947                 Log( deny_severity, "Refused connection from %s (by TCP Wrappers)!", inet_ntoa( new_addr.sin_addr ));
948                 Simple_Message( new_sock, "ERROR :Connection refused" );
949                 close( new_sock );
950                 return;
951         }
952 #endif
953
954         /* Socket initialisieren */
955         Init_Socket( new_sock );
956         
957         /* Check IP-based connection limit */
958         cnt = Count_Connections( new_addr );
959         if(( Conf_MaxConnectionsIP > 0 ) && ( cnt >= Conf_MaxConnectionsIP ))
960         {
961                 /* Access denied, too many connections from this IP! */
962                 Log( LOG_ERR, "Refused connection from %s: too may connections (%ld) from this IP!", inet_ntoa( new_addr.sin_addr ), cnt);
963                 Simple_Message( new_sock, "ERROR :Connection refused, too many connections from your IP!" );
964                 close( new_sock );
965                 return;
966         }
967
968         /* Freie Connection-Struktur suchen */
969         for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
970         if( idx >= Pool_Size )
971         {
972                 new_size = Pool_Size + CONNECTION_POOL;
973
974                 /* Im bisherigen Pool wurde keine freie Connection-Struktur mehr gefunden.
975                  * Wenn erlaubt und moeglich muss nun der Pool vergroessert werden: */
976
977                 if( Conf_MaxConnections > 0 )
978                 {
979                         /* Es ist ein Limit konfiguriert */
980                         if( Pool_Size >= Conf_MaxConnections )
981                         {
982                                 /* Mehr Verbindungen duerfen wir leider nicht mehr annehmen ... */
983                                 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached!", Pool_Size );
984                                 Simple_Message( new_sock, "ERROR :Connection limit reached" );
985                                 close( new_sock );
986                                 return;
987                         }
988                         if( new_size > Conf_MaxConnections ) new_size = Conf_MaxConnections;
989                 }
990                 if( new_size < Pool_Size )
991                 {
992                         Log( LOG_ALERT, "Can't accespt connection: limit (%d) reached -- overflow!", Pool_Size );
993                         Simple_Message( new_sock, "ERROR :Connection limit reached" );
994                         close( new_sock );
995                         return;
996                 }
997
998                 /* zunaechst realloc() versuchen; wenn das scheitert, malloc() versuchen
999                  * und Daten ggf. "haendisch" umkopieren. (Haesslich! Eine wirklich
1000                  * dynamische Verwaltung waere wohl _deutlich_ besser ...) */
1001                 ptr = realloc( My_Connections, sizeof( CONNECTION ) * new_size );
1002                 if( ! ptr )
1003                 {
1004                         /* realloc() ist fehlgeschlagen. Nun malloc() probieren: */
1005                         ptr = malloc( sizeof( CONNECTION ) * new_size );
1006                         if( ! ptr )
1007                         {
1008                                 /* Offenbar steht kein weiterer Sepeicher zur Verfuegung :-( */
1009                                 Log( LOG_EMERG, "Can't allocate memory! [New_Connection]" );
1010                                 Simple_Message( new_sock, "ERROR: Internal error" );
1011                                 close( new_sock );
1012                                 return;
1013                         }
1014
1015                         /* Struktur umkopieren ... */
1016                         memcpy( ptr, My_Connections, sizeof( CONNECTION ) * Pool_Size );
1017
1018 #ifdef DEBUG
1019                         Log( LOG_DEBUG, "Allocated new connection pool for %ld items (%ld bytes). [malloc()/memcpy()]", new_size, sizeof( CONNECTION ) * new_size );
1020 #endif
1021                 }
1022 #ifdef DEBUG
1023                 else Log( LOG_DEBUG, "Allocated new connection pool for %ld items (%ld bytes). [realloc()]", new_size, sizeof( CONNECTION ) * new_size );
1024 #endif
1025
1026                 /* Adjust pointer to new block */
1027                 My_Connections = ptr;
1028
1029                 /* Initialize new items */
1030                 for( idx = Pool_Size; idx < new_size; idx++ ) Init_Conn_Struct( idx );
1031                 idx = Pool_Size;
1032
1033                 /* Adjust new pool size */
1034                 Pool_Size = new_size;
1035         }
1036
1037         /* Client-Struktur initialisieren */
1038         c = Client_NewLocal( idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWN, FALSE );
1039         if( ! c )
1040         {
1041                 Log( LOG_ALERT, "Can't accept connection: can't create client structure!" );
1042                 Simple_Message( new_sock, "ERROR :Internal error" );
1043                 close( new_sock );
1044                 return;
1045         }
1046
1047         /* Verbindung registrieren */
1048         Init_Conn_Struct( idx );
1049         My_Connections[idx].sock = new_sock;
1050         My_Connections[idx].addr = new_addr;
1051
1052         /* Neuen Socket registrieren */
1053         FD_SET( new_sock, &My_Sockets );
1054         if( new_sock > Conn_MaxFD ) Conn_MaxFD = new_sock;
1055
1056         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 );
1057
1058         /* Hostnamen ermitteln */
1059         strlcpy( My_Connections[idx].host, inet_ntoa( new_addr.sin_addr ), sizeof( My_Connections[idx].host ));
1060         Client_SetHostname( c, My_Connections[idx].host );
1061 #ifdef IDENTAUTH
1062         s = Resolve_Addr( &new_addr, My_Connections[idx].sock );
1063 #else
1064         s = Resolve_Addr( &new_addr );
1065 #endif
1066         if( s )
1067         {
1068                 /* Sub-Prozess wurde asyncron gestartet */
1069                 My_Connections[idx].res_stat = s;
1070         }
1071
1072         /* Penalty-Zeit setzen */
1073         Conn_SetPenalty( idx, 4 );
1074 } /* New_Connection */
1075
1076
1077 LOCAL CONN_ID
1078 Socket2Index( INT Sock )
1079 {
1080         /* zum Socket passende Connection suchen */
1081
1082         CONN_ID idx;
1083
1084         assert( Sock > NONE );
1085
1086         for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == Sock ) break;
1087
1088         if( idx >= Pool_Size )
1089         {
1090                 /* die Connection wurde vermutlich (wegen eines
1091                  * Fehlers) bereits wieder abgebaut ... */
1092 #ifdef DEBUG
1093                 Log( LOG_DEBUG, "Socket2Index: can't get connection for socket %d!", Sock );
1094 #endif
1095                 return NONE;
1096         }
1097         else return idx;
1098 } /* Socket2Index */
1099
1100
1101 LOCAL VOID
1102 Read_Request( CONN_ID Idx )
1103 {
1104         /* Daten von Socket einlesen und entsprechend behandeln.
1105          * Tritt ein Fehler auf, so wird der Socket geschlossen. */
1106
1107         INT len, bsize;
1108 #ifdef ZLIB
1109         CLIENT *c;
1110 #endif
1111
1112         assert( Idx > NONE );
1113         assert( My_Connections[Idx].sock > NONE );
1114
1115         /* wenn noch nicht registriert: maximal mit ZREADBUFFER_LEN arbeiten,
1116          * ansonsten koennen Daten ggf. nicht umkopiert werden. */
1117         bsize = READBUFFER_LEN;
1118 #ifdef ZLIB
1119         c = Client_GetFromConn( Idx );
1120         if(( Client_Type( c ) != CLIENT_USER ) && ( Client_Type( c ) != CLIENT_SERVER ) && ( Client_Type( c ) != CLIENT_SERVICE ) && ( bsize > ZREADBUFFER_LEN )) bsize = ZREADBUFFER_LEN;
1121 #endif
1122
1123 #ifdef ZLIB
1124         if(( bsize - My_Connections[Idx].rdatalen - 1 < 1 ) || ( ZREADBUFFER_LEN - My_Connections[Idx].zip.rdatalen < 1 ))
1125 #else
1126         if( bsize - My_Connections[Idx].rdatalen - 1 < 1 )
1127 #endif
1128         {
1129                 /* Der Lesepuffer ist voll */
1130                 Log( LOG_ERR, "Read buffer overflow (connection %d): %d bytes!", Idx, My_Connections[Idx].rdatalen );
1131                 Conn_Close( Idx, "Read buffer overflow!", NULL, FALSE );
1132                 return;
1133         }
1134
1135 #ifdef ZLIB
1136         if( My_Connections[Idx].options & CONN_ZIP )
1137         {
1138                 len = recv( My_Connections[Idx].sock, My_Connections[Idx].zip.rbuf + My_Connections[Idx].zip.rdatalen, ( ZREADBUFFER_LEN - My_Connections[Idx].zip.rdatalen ), 0 );
1139                 if( len > 0 ) My_Connections[Idx].zip.rdatalen += len;
1140         }
1141         else
1142 #endif
1143         {
1144                 len = recv( My_Connections[Idx].sock, My_Connections[Idx].rbuf + My_Connections[Idx].rdatalen, bsize - My_Connections[Idx].rdatalen - 1, 0 );
1145                 if( len > 0 ) My_Connections[Idx].rdatalen += len;
1146         }
1147
1148         if( len == 0 )
1149         {
1150                 /* Socket wurde geschlossen */
1151                 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 ));
1152                 Conn_Close( Idx, "Socket closed!", "Client closed connection", FALSE );
1153                 return;
1154         }
1155
1156         if( len < 0 )
1157         {
1158                 /* Operation haette Socket "nur" blockiert ... */
1159                 if( errno == EAGAIN ) return;
1160
1161                 /* Fehler beim Lesen */
1162                 Log( LOG_ERR, "Read error on connection %d (socket %d): %s!", Idx, My_Connections[Idx].sock, strerror( errno ));
1163                 Conn_Close( Idx, "Read error!", "Client closed connection", FALSE );
1164                 return;
1165         }
1166
1167         /* Connection-Statistik aktualisieren */
1168         My_Connections[Idx].bytes_in += len;
1169
1170         /* Timestamp aktualisieren */
1171         My_Connections[Idx].lastdata = time( NULL );
1172
1173         Handle_Buffer( Idx );
1174 } /* Read_Request */
1175
1176
1177 LOCAL BOOLEAN
1178 Handle_Buffer( CONN_ID Idx )
1179 {
1180         /* Daten im Lese-Puffer einer Verbindung verarbeiten.
1181          * Wurde ein Request verarbeitet, so wird TRUE geliefert,
1182          * ansonsten FALSE (auch bei Fehlern). */
1183
1184 #ifndef STRICT_RFC
1185         CHAR *ptr1, *ptr2;
1186 #endif
1187         CHAR *ptr;
1188         INT len, delta;
1189         BOOLEAN action, result;
1190 #ifdef ZLIB
1191         BOOLEAN old_z;
1192 #endif
1193
1194         result = FALSE;
1195         do
1196         {
1197                 /* Check penalty */
1198                 if( My_Connections[Idx].delaytime > time( NULL )) return result;
1199                 
1200 #ifdef ZLIB
1201                 /* ggf. noch unkomprimiete Daten weiter entpacken */
1202                 if( My_Connections[Idx].options & CONN_ZIP )
1203                 {
1204                         if( ! Unzip_Buffer( Idx )) return FALSE;
1205                 }
1206 #endif
1207
1208                 if( My_Connections[Idx].rdatalen < 1 ) break;
1209
1210                 /* Eine komplette Anfrage muss mit CR+LF enden, vgl.
1211                  * RFC 2812. Haben wir eine? */
1212                 My_Connections[Idx].rbuf[My_Connections[Idx].rdatalen] = '\0';
1213                 ptr = strstr( My_Connections[Idx].rbuf, "\r\n" );
1214
1215                 if( ptr ) delta = 2;
1216 #ifndef STRICT_RFC
1217                 else
1218                 {
1219                         /* Nicht RFC-konforme Anfrage mit nur CR oder LF? Leider
1220                          * machen soetwas viele Clients, u.a. "mIRC" :-( */
1221                         ptr1 = strchr( My_Connections[Idx].rbuf, '\r' );
1222                         ptr2 = strchr( My_Connections[Idx].rbuf, '\n' );
1223                         delta = 1;
1224                         if( ptr1 && ptr2 ) ptr = ptr1 > ptr2 ? ptr2 : ptr1;
1225                         else if( ptr1 ) ptr = ptr1;
1226                         else if( ptr2 ) ptr = ptr2;
1227                 }
1228 #endif
1229
1230                 action = FALSE;
1231                 if( ptr )
1232                 {
1233                         /* Ende der Anfrage wurde gefunden */
1234                         *ptr = '\0';
1235                         len = ( ptr - My_Connections[Idx].rbuf ) + delta;
1236                         if( len > ( COMMAND_LEN - 1 ))
1237                         {
1238                                 /* Eine Anfrage darf(!) nicht laenger als 512 Zeichen
1239                                  * (incl. CR+LF!) werden; vgl. RFC 2812. Wenn soetwas
1240                                  * empfangen wird, wird der Client disconnectiert. */
1241                                 Log( LOG_ERR, "Request too long (connection %d): %d bytes (max. %d expected)!", Idx, My_Connections[Idx].rdatalen, COMMAND_LEN - 1 );
1242                                 Conn_Close( Idx, NULL, "Request too long", TRUE );
1243                                 return FALSE;
1244                         }
1245
1246 #ifdef ZLIB
1247                         /* merken, ob Stream bereits komprimiert wird */
1248                         old_z = My_Connections[Idx].options & CONN_ZIP;
1249 #endif
1250
1251                         if( len > delta )
1252                         {
1253                                 /* Es wurde ein Request gelesen */
1254                                 My_Connections[Idx].msg_in++;
1255                                 if( ! Parse_Request( Idx, My_Connections[Idx].rbuf )) return FALSE;
1256                                 else action = TRUE;
1257                         }
1258
1259                         /* Puffer anpassen */
1260                         My_Connections[Idx].rdatalen -= len;
1261                         memmove( My_Connections[Idx].rbuf, My_Connections[Idx].rbuf + len, My_Connections[Idx].rdatalen );
1262
1263 #ifdef ZLIB
1264                         if(( ! old_z ) && ( My_Connections[Idx].options & CONN_ZIP ) && ( My_Connections[Idx].rdatalen > 0 ))
1265                         {
1266                                 /* Mit dem letzten Befehl wurde Socket-Kompression aktiviert.
1267                                  * Evtl. schon vom Socket gelesene Daten in den Unzip-Puffer
1268                                  * umkopieren, damit diese nun zunaechst entkomprimiert werden */
1269                                 {
1270                                         if( My_Connections[Idx].rdatalen > ZREADBUFFER_LEN )
1271                                         {
1272                                                 /* Hupsa! Soviel Platz haben wir aber gar nicht! */
1273                                                 Log( LOG_ALERT, "Can't move read buffer: No space left in unzip buffer (need %d bytes)!", My_Connections[Idx].rdatalen );
1274                                                 return FALSE;
1275                                         }
1276                                         memcpy( My_Connections[Idx].zip.rbuf, My_Connections[Idx].rbuf, My_Connections[Idx].rdatalen );
1277                                         My_Connections[Idx].zip.rdatalen = My_Connections[Idx].rdatalen;
1278                                         My_Connections[Idx].rdatalen = 0;
1279 #ifdef DEBUG
1280                                         Log( LOG_DEBUG, "Moved already received data (%d bytes) to uncompression buffer.", My_Connections[Idx].zip.rdatalen );
1281 #endif
1282                                 }
1283                         }
1284 #endif
1285                 }
1286
1287                 if( action ) result = TRUE;
1288         } while( action );
1289
1290         return result;
1291 } /* Handle_Buffer */
1292
1293
1294 LOCAL VOID
1295 Check_Connections( VOID )
1296 {
1297         /* Pruefen, ob Verbindungen noch "alive" sind. Ist dies
1298          * nicht der Fall, zunaechst PING-PONG spielen und, wenn
1299          * auch das nicht "hilft", Client disconnectieren. */
1300
1301         CLIENT *c;
1302         CONN_ID i;
1303
1304         for( i = 0; i < Pool_Size; i++ )
1305         {
1306                 if( My_Connections[i].sock == NONE ) continue;
1307
1308                 c = Client_GetFromConn( i );
1309                 if( c && (( Client_Type( c ) == CLIENT_USER ) || ( Client_Type( c ) == CLIENT_SERVER ) || ( Client_Type( c ) == CLIENT_SERVICE )))
1310                 {
1311                         /* verbundener User, Server oder Service */
1312                         if( My_Connections[i].lastping > My_Connections[i].lastdata )
1313                         {
1314                                 /* es wurde bereits ein PING gesendet */
1315                                 if( My_Connections[i].lastping < time( NULL ) - Conf_PongTimeout )
1316                                 {
1317                                         /* Timeout */
1318 #ifdef DEBUG
1319                                         Log( LOG_DEBUG, "Connection %d: Ping timeout: %d seconds.", i, Conf_PongTimeout );
1320 #endif
1321                                         Conn_Close( i, NULL, "Ping timeout", TRUE );
1322                                 }
1323                         }
1324                         else if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout )
1325                         {
1326                                 /* es muss ein PING gesendet werden */
1327 #ifdef DEBUG
1328                                 Log( LOG_DEBUG, "Connection %d: sending PING ...", i );
1329 #endif
1330                                 My_Connections[i].lastping = time( NULL );
1331                                 Conn_WriteStr( i, "PING :%s", Client_ID( Client_ThisServer( )));
1332                         }
1333                 }
1334                 else
1335                 {
1336                         /* noch nicht vollstaendig aufgebaute Verbindung */
1337                         if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout )
1338                         {
1339                                 /* Timeout */
1340 #ifdef DEBUG
1341                                 Log( LOG_DEBUG, "Connection %d timed out ...", i );
1342 #endif
1343                                 Conn_Close( i, NULL, "Timeout", FALSE );
1344                         }
1345                 }
1346         }
1347 } /* Check_Connections */
1348
1349
1350 LOCAL VOID
1351 Check_Servers( VOID )
1352 {
1353         /* Check if we can establish further server links */
1354
1355         RES_STAT *s;
1356         CONN_ID idx;
1357         INT i, n;
1358
1359         /* Serach all connections, are there results from the resolver? */
1360         for( idx = 0; idx < Pool_Size; idx++ )
1361         {
1362                 if( My_Connections[idx].sock != SERVER_WAIT ) continue;
1363
1364                 /* IP resolved? */
1365                 if( My_Connections[idx].res_stat == NULL ) New_Server( Conf_GetServer( idx ), idx );
1366         }
1367
1368         /* Check all configured servers */
1369         for( i = 0; i < MAX_SERVERS; i++ )
1370         {
1371                 /* Valid outgoing server which isn't already connected or disabled? */
1372                 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;
1373
1374                 /* Is there already a connection in this group? */
1375                 if( Conf_Server[i].group > NONE )
1376                 {
1377                         for( n = 0; n < MAX_SERVERS; n++ )
1378                         {
1379                                 if( n == i ) continue;
1380                                 if(( Conf_Server[n].conn_id > NONE ) && ( Conf_Server[n].group == Conf_Server[i].group )) break;
1381                         }
1382                         if( n < MAX_SERVERS ) continue;
1383                 }
1384
1385                 /* Check last connect attempt? */
1386                 if( Conf_Server[i].lasttry > time( NULL ) - Conf_ConnectRetry ) continue;
1387
1388                 /* Okay, try to connect now */
1389                 Conf_Server[i].lasttry = time( NULL );
1390
1391                 /* Search free connection structure */
1392                 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
1393                 if( idx >= Pool_Size )
1394                 {
1395                         Log( LOG_ALERT, "Can't establist server connection: connection limit reached (%d)!", Pool_Size );
1396                         return;
1397                 }
1398 #ifdef DEBUG
1399                 Log( LOG_DEBUG, "Preparing connection %d for \"%s\" ...", idx, Conf_Server[i].host );
1400 #endif
1401
1402                 /* Verbindungs-Struktur initialisieren */
1403                 Init_Conn_Struct( idx );
1404                 My_Connections[idx].sock = SERVER_WAIT;
1405                 Conf_Server[i].conn_id = idx;
1406
1407                 /* Resolve Hostname. If this fails, try to use it as an IP address */
1408                 strlcpy( Conf_Server[i].ip, Conf_Server[i].host, sizeof( Conf_Server[i].ip ));
1409                 strlcpy( My_Connections[idx].host, Conf_Server[i].host, sizeof( My_Connections[idx].host ));
1410                 s = Resolve_Name( Conf_Server[i].host );
1411                 if( s )
1412                 {
1413                         /* Sub-Prozess wurde asyncron gestartet */
1414                         My_Connections[idx].res_stat = s;
1415                 }
1416         }
1417 } /* Check_Servers */
1418
1419
1420 LOCAL VOID
1421 New_Server( INT Server, CONN_ID Idx )
1422 {
1423         /* Establish new server link */
1424
1425         struct sockaddr_in new_addr;
1426         struct in_addr inaddr;
1427         INT res, new_sock;
1428         CLIENT *c;
1429
1430         assert( Server > NONE );
1431         assert( Idx > NONE );
1432
1433         /* Did we get a valid IP address? */
1434         if( ! Conf_Server[Server].ip[0] )
1435         {
1436                 /* No. Free connection structure and abort: */
1437                 Init_Conn_Struct( Idx );
1438                 Conf_Server[Server].conn_id = NONE;
1439                 Log( LOG_ERR, "Can't connect to \"%s\" (connection %d): ip address unknown!", Conf_Server[Server].host, Idx );
1440                 return;
1441         }
1442
1443         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 );
1444
1445 #ifdef HAVE_INET_ATON
1446         if( inet_aton( Conf_Server[Server].ip, &inaddr ) == 0 )
1447 #else
1448         memset( &inaddr, 0, sizeof( inaddr ));
1449         inaddr.s_addr = inet_addr( Conf_Server[Server].ip );
1450         if( inaddr.s_addr == (unsigned)-1 )
1451 #endif
1452         {
1453                 /* Can't convert IP address */
1454                 Init_Conn_Struct( Idx );
1455                 Conf_Server[Server].conn_id = NONE;
1456                 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 );
1457                 return;
1458         }
1459
1460         memset( &new_addr, 0, sizeof( new_addr ));
1461         new_addr.sin_family = AF_INET;
1462         new_addr.sin_addr = inaddr;
1463         new_addr.sin_port = htons( Conf_Server[Server].port );
1464
1465         new_sock = socket( PF_INET, SOCK_STREAM, 0 );
1466         if ( new_sock < 0 )
1467         {
1468                 /* Can't create socket */
1469                 Init_Conn_Struct( Idx );
1470                 Conf_Server[Server].conn_id = NONE;
1471                 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
1472                 return;
1473         }
1474
1475         if( ! Init_Socket( new_sock )) return;
1476
1477         res = connect( new_sock, (struct sockaddr *)&new_addr, sizeof( new_addr ));
1478         if(( res != 0 ) && ( errno != EINPROGRESS ))
1479         {
1480                 /* Can't connect socket */
1481                 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1482                 close( new_sock );
1483                 Init_Conn_Struct( Idx );
1484                 Conf_Server[Server].conn_id = NONE;
1485                 return;
1486         }
1487
1488         /* Client-Struktur initialisieren */
1489         c = Client_NewLocal( Idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWNSERVER, FALSE );
1490         if( ! c )
1491         {
1492                 /* Can't create new client structure */
1493                 close( new_sock );
1494                 Init_Conn_Struct( Idx );
1495                 Conf_Server[Server].conn_id = NONE;
1496                 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1497                 return;
1498         }
1499         Client_SetIntroducer( c, c );
1500         Client_SetToken( c, TOKEN_OUTBOUND );
1501
1502         /* Register connection */
1503         My_Connections[Idx].sock = new_sock;
1504         My_Connections[Idx].addr = new_addr;
1505         strlcpy( My_Connections[Idx].host, Conf_Server[Server].host, sizeof( My_Connections[Idx].host ));
1506
1507         /* Register new socket */
1508         FD_SET( new_sock, &My_Sockets );
1509         FD_SET( new_sock, &My_Connects );
1510         if( new_sock > Conn_MaxFD ) Conn_MaxFD = new_sock;
1511
1512 #ifdef DEBUG
1513         Log( LOG_DEBUG, "Registered new connection %d on socket %d.", Idx, My_Connections[Idx].sock );
1514 #endif
1515 } /* New_Server */
1516
1517
1518 LOCAL VOID
1519 Init_Conn_Struct( CONN_ID Idx )
1520 {
1521         /* Connection-Struktur initialisieren */
1522
1523         My_Connections[Idx].sock = NONE;
1524         My_Connections[Idx].res_stat = NULL;
1525         My_Connections[Idx].host[0] = '\0';
1526         My_Connections[Idx].rbuf[0] = '\0';
1527         My_Connections[Idx].rdatalen = 0;
1528         My_Connections[Idx].wbuf[0] = '\0';
1529         My_Connections[Idx].wdatalen = 0;
1530         My_Connections[Idx].starttime = time( NULL );
1531         My_Connections[Idx].lastdata = time( NULL );
1532         My_Connections[Idx].lastping = 0;
1533         My_Connections[Idx].lastprivmsg = time( NULL );
1534         My_Connections[Idx].delaytime = 0;
1535         My_Connections[Idx].bytes_in = 0;
1536         My_Connections[Idx].bytes_out = 0;
1537         My_Connections[Idx].msg_in = 0;
1538         My_Connections[Idx].msg_out = 0;
1539         My_Connections[Idx].flag = 0;
1540         My_Connections[Idx].options = 0;
1541
1542 #ifdef ZLIB
1543         My_Connections[Idx].zip.rbuf[0] = '\0';
1544         My_Connections[Idx].zip.rdatalen = 0;
1545         My_Connections[Idx].zip.wbuf[0] = '\0';
1546         My_Connections[Idx].zip.wdatalen = 0;
1547         My_Connections[Idx].zip.bytes_in = 0;
1548         My_Connections[Idx].zip.bytes_out = 0;
1549 #endif
1550 } /* Init_Conn_Struct */
1551
1552
1553 LOCAL BOOLEAN
1554 Init_Socket( INT Sock )
1555 {
1556         /* Initialize socket (set options) */
1557
1558         INT value;
1559
1560 #ifdef O_NONBLOCK       /* unknown on A/UX */
1561         if( fcntl( Sock, F_SETFL, O_NONBLOCK ) != 0 )
1562         {
1563                 Log( LOG_CRIT, "Can't enable non-blocking mode for socket: %s!", strerror( errno ));
1564                 close( Sock );
1565                 return FALSE;
1566         }
1567 #endif
1568
1569         /* Don't block this port after socket shutdown */
1570         value = 1;
1571         if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &value, (socklen_t)sizeof( value )) != 0 )
1572         {
1573                 Log( LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!", strerror( errno ));
1574                 /* ignore this error */
1575         }
1576
1577         /* Set type of service (TOS) */
1578 #if defined(IP_TOS) && defined(IPTOS_LOWDELAY)
1579         value = IPTOS_LOWDELAY;
1580 #ifdef DEBUG
1581         Log( LOG_DEBUG, "Setting option IP_TOS on socket %d to IPTOS_LOWDELAY (%d).", Sock, value );
1582 #endif
1583         if( setsockopt( Sock, SOL_IP, IP_TOS, &value, (socklen_t)sizeof( value )) != 0 )
1584         {
1585                 Log( LOG_ERR, "Can't set socket option IP_TOS: %s!", strerror( errno ));
1586                 /* ignore this error */
1587         }
1588 #endif
1589
1590         return TRUE;
1591 } /* Init_Socket */
1592
1593
1594 LOCAL VOID
1595 Read_Resolver_Result( INT r_fd )
1596 {
1597         /* Ergebnis von Resolver Sub-Prozess aus Pipe lesen
1598          * und entsprechende Connection aktualisieren */
1599
1600         CHAR result[HOST_LEN];
1601         CLIENT *c;
1602         INT len, i, n;
1603
1604         FD_CLR( r_fd, &Resolver_FDs );
1605
1606         /* Read result from pipe */
1607         len = read( r_fd, result, HOST_LEN - 1 );
1608         if( len < 0 )
1609         {
1610                 /* Error! */
1611                 close( r_fd );
1612                 Log( LOG_CRIT, "Resolver: Can't read result: %s!", strerror( errno ));
1613                 return;
1614         }
1615         result[len] = '\0';
1616
1617         /* Search associated connection ... */
1618         for( i = 0; i < Pool_Size; i++ )
1619         {
1620                 if(( My_Connections[i].sock != NONE ) && ( My_Connections[i].res_stat ) && ( My_Connections[i].res_stat->pipe[0] == r_fd )) break;
1621         }
1622         if( i >= Pool_Size )
1623         {
1624                 /* Ops, none found? Probably the connection has already
1625                  * been closed. */
1626                 close( r_fd );
1627 #ifdef DEBUG
1628                 Log( LOG_DEBUG, "Resolver: Got result for unknown connection!?" );
1629 #endif
1630                 return;
1631         }
1632
1633 #ifdef DEBUG
1634         Log( LOG_DEBUG, "Resolver: %s is \"%s\".", My_Connections[i].host, result );
1635 #endif
1636
1637         /* Clean up ... */
1638         close( My_Connections[i].res_stat->pipe[0] );
1639         close( My_Connections[i].res_stat->pipe[1] );
1640         free( My_Connections[i].res_stat );
1641         My_Connections[i].res_stat = NULL;
1642
1643         if( My_Connections[i].sock > NONE )
1644         {
1645 #ifdef IDENTAUTH
1646                 CHAR *ident;
1647 #endif
1648                 /* Incoming connection: set hostname */
1649                 c = Client_GetFromConn( i );
1650                 assert( c != NULL );
1651                 strlcpy( My_Connections[i].host, result, sizeof( My_Connections[i].host ));
1652                 Client_SetHostname( c, result );
1653
1654 #ifdef IDENTAUTH
1655                 ident = strchr( result, 0 );
1656                 ident++;
1657
1658                 /* Do we have a result of the IDENT lookup? */
1659                 if( *ident )
1660                 {
1661                         Log( LOG_INFO, "IDENT lookup on connection %ld: \"%s\".", i, ident );
1662                         Client_SetUser( c, ident, TRUE );
1663                 }
1664                 else Log( LOG_INFO, "IDENT lookup on connection %ld: no result.", i );
1665 #endif
1666         }
1667         else
1668         {
1669                 /* Outgoing connection (server link!): set IP address */
1670                 n = Conf_GetServer( i );
1671                 if( n > NONE ) strlcpy( Conf_Server[n].ip, result, sizeof( Conf_Server[n].ip ));
1672                 else Log( LOG_ERR, "Got resolver result for non-configured server!?" );
1673         }
1674
1675         /* Reset penalty time */
1676         Conn_ResetPenalty( i );
1677 } /* Read_Resolver_Result */
1678
1679
1680 LOCAL VOID
1681 Simple_Message( INT Sock, CHAR *Msg )
1682 {
1683         /* Write "simple" message to socket, without using compression
1684          * or even the connection write buffers. Used e.g. for error
1685          * messages by New_Connection(). */
1686
1687         assert( Sock > NONE );
1688         assert( Msg != NULL );
1689
1690         (VOID)send( Sock, Msg, strlen( Msg ), 0 );
1691         (VOID)send( Sock, "\r\n", 2, 0 );
1692 } /* Simple_Error */
1693
1694
1695 LOCAL INT
1696 Count_Connections( struct sockaddr_in addr_in )
1697 {
1698         INT i, cnt;
1699         
1700         cnt = 0;
1701         for( i = 0; i < Pool_Size; i++ )
1702         {
1703                 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].addr.sin_addr.s_addr == addr_in.sin_addr.s_addr )) cnt++;
1704         }
1705         return cnt;
1706 } /* Count_Connections */
1707
1708
1709 /* -eof- */