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