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