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