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