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