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