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