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