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