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