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