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