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