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