]> arthur.barton.de Git - ngircd-alex.git/blob - src/ngircd/conn.c
Introduce DEBUG_BUFFER, rework some debug messages
[ngircd-alex.git] / src / ngircd / conn.c
1 /*
2  * ngIRCd -- The Next Generation IRC Daemon
3  * Copyright (c)2001-2010 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
12 #undef DEBUG_BUFFER
13
14 #define CONN_MODULE
15
16 #include "portab.h"
17 #include "conf-ssl.h"
18 #include "io.h"
19
20 /**
21  * @file
22  * Connection management
23  */
24
25 #include "imp.h"
26 #include <assert.h>
27 #ifdef PROTOTYPES
28 # include <stdarg.h>
29 #else
30 # include <varargs.h>
31 #endif
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <unistd.h>
35 #include <errno.h>
36 #include <string.h>
37 #include <sys/socket.h>
38 #include <sys/time.h>
39 #include <sys/types.h>
40 #include <time.h>
41 #include <netinet/in.h>
42
43 #ifdef HAVE_NETINET_IP_H
44 # ifdef HAVE_NETINET_IN_SYSTM_H
45 #  include <netinet/in_systm.h>
46 # endif
47 # include <netinet/ip.h>
48 #endif
49
50 #ifdef HAVE_STDINT_H
51 # include <stdint.h>                    /* e.g. for Mac OS X */
52 #endif
53
54 #ifdef TCPWRAP
55 # include <tcpd.h>                      /* for TCP Wrappers */
56 #endif
57
58 #include "array.h"
59 #include "defines.h"
60
61 #include "exp.h"
62 #include "conn.h"
63
64 #include "imp.h"
65 #include "ngircd.h"
66 #include "array.h"
67 #include "client.h"
68 #include "conf.h"
69 #include "conn-ssl.h"
70 #include "conn-zip.h"
71 #include "conn-func.h"
72 #include "log.h"
73 #include "ng_ipaddr.h"
74 #include "parse.h"
75 #include "resolve.h"
76 #include "tool.h"
77
78 #include "exp.h"
79
80
81 #define SERVER_WAIT (NONE - 1)
82
83 #define MAX_COMMANDS 3
84 #define MAX_COMMANDS_SERVER 10
85 #define MAX_COMMANDS_SERVICE MAX_COMMANDS_SERVER
86
87
88 static bool Handle_Write PARAMS(( CONN_ID Idx ));
89 static bool Conn_Write PARAMS(( CONN_ID Idx, char *Data, size_t Len ));
90 static int New_Connection PARAMS(( int Sock ));
91 static CONN_ID Socket2Index PARAMS(( int Sock ));
92 static void Read_Request PARAMS(( CONN_ID Idx ));
93 static unsigned int Handle_Buffer PARAMS(( CONN_ID Idx ));
94 static void Check_Connections PARAMS(( void ));
95 static void Check_Servers PARAMS(( void ));
96 static void Init_Conn_Struct PARAMS(( CONN_ID Idx ));
97 static bool Init_Socket PARAMS(( int Sock ));
98 static void New_Server PARAMS(( int Server, ng_ipaddr_t *dest ));
99 static void Simple_Message PARAMS(( int Sock, const char *Msg ));
100 static int NewListener PARAMS(( const char *listen_addr, UINT16 Port ));
101 static void Account_Connection PARAMS((void));
102
103
104 static array My_Listeners;
105 static array My_ConnArray;
106 static size_t NumConnections, NumConnectionsMax, NumConnectionsAccepted;
107
108 #ifdef TCPWRAP
109 int allow_severity = LOG_INFO;
110 int deny_severity = LOG_ERR;
111 #endif
112
113 static void server_login PARAMS((CONN_ID idx));
114
115 #ifdef SSL_SUPPORT
116 extern struct SSLOptions Conf_SSLOptions;
117 static void cb_connserver_login_ssl PARAMS((int sock, short what));
118 static void cb_clientserver_ssl PARAMS((int sock, short what));
119 #endif
120 static void cb_Read_Resolver_Result PARAMS((int sock, UNUSED short what));
121 static void cb_Connect_to_Server PARAMS((int sock, UNUSED short what));
122 static void cb_clientserver PARAMS((int sock, short what));
123
124
125 /**
126  * IO callback for listening sockets: handle new connections. This callback
127  * gets called when a new non-SSL connection should be accepted.
128  *
129  * @param sock          Socket descriptor.
130  * @param irrelevant    (ignored IO specification)
131  */
132 static void
133 cb_listen(int sock, short irrelevant)
134 {
135         (void) irrelevant;
136         (void) New_Connection(sock);
137 }
138
139
140 #ifdef SSL_SUPPORT
141 /**
142  * IO callback for listening SSL sockets: handle new connections. This callback
143  * gets called when a new SSL-enabled connection should be accepted.
144  *
145  * @param sock          Socket descriptor.
146  * @param irrelevant    (ignored IO specification)
147  */
148 static void
149 cb_listen_ssl(int sock, short irrelevant)
150 {
151         int fd;
152
153         (void) irrelevant;
154         fd = New_Connection(sock);
155         if (fd < 0)
156                 return;
157         io_event_setcb(My_Connections[fd].sock, cb_clientserver_ssl);
158 }
159 #endif
160
161
162 /**
163  * IO callback for new outgoing non-SSL server connections.
164  *
165  * @param sock  Socket descriptor.
166  * @param what  IO specification (IO_WANTREAD/IO_WANTWRITE/...).
167  */
168 static void
169 cb_connserver(int sock, UNUSED short what)
170 {
171         int res, err, server;
172         socklen_t sock_len;
173         CONN_ID idx = Socket2Index( sock );
174
175         if (idx <= NONE) {
176                 LogDebug("cb_connserver wants to write on unknown socket?!");
177                 io_close(sock);
178                 return;
179         }
180
181         assert(what & IO_WANTWRITE);
182
183         /* Make sure that the server is still configured; it could have been
184          * removed in the meantime! */
185         server = Conf_GetServer(idx);
186         if (server < 0) {
187                 Log(LOG_ERR, "Connection on socket %d to \"%s\" aborted!",
188                     sock, My_Connections[idx].host);
189                 Conn_Close(idx, "Connection aborted!", NULL, false);
190                 return;
191         }
192
193         /* connect() finished, get result. */
194         sock_len = (socklen_t)sizeof(err);
195         res = getsockopt(My_Connections[idx].sock, SOL_SOCKET, SO_ERROR,
196                          &err, &sock_len );
197         assert(sock_len == sizeof(err));
198
199         /* Error while connecting? */
200         if ((res != 0) || (err != 0)) {
201                 if (res != 0)
202                         Log(LOG_CRIT, "getsockopt (connection %d): %s!",
203                             idx, strerror(errno));
204                 else
205                         Log(LOG_CRIT,
206                             "Can't connect socket to \"%s:%d\" (connection %d): %s!",
207                             My_Connections[idx].host, Conf_Server[server].port,
208                             idx, strerror(err));
209
210                 Conn_Close(idx, "Can't connect!", NULL, false);
211
212                 if (ng_ipaddr_af(&Conf_Server[server].dst_addr[0])) {
213                         /* more addresses to try... */
214                         New_Server(server, &Conf_Server[server].dst_addr[0]);
215                         /* connection to dst_addr[0] is now in progress, so
216                          * remove this address... */
217                         Conf_Server[server].dst_addr[0] =
218                                 Conf_Server[server].dst_addr[1];
219                         memset(&Conf_Server[server].dst_addr[1], 0,
220                                sizeof(Conf_Server[server].dst_addr[1]));
221                 }
222                 return;
223         }
224
225         /* connect() succeeded, remove all additional addresses */
226         memset(&Conf_Server[server].dst_addr, 0,
227                sizeof(Conf_Server[server].dst_addr));
228
229         Conn_OPTION_DEL( &My_Connections[idx], CONN_ISCONNECTING );
230 #ifdef SSL_SUPPORT
231         if ( Conn_OPTION_ISSET( &My_Connections[idx], CONN_SSL_CONNECT )) {
232                 io_event_setcb( sock, cb_connserver_login_ssl );
233                 io_event_add( sock, IO_WANTWRITE|IO_WANTREAD );
234                 return;
235         }
236 #endif
237         server_login(idx);
238 }
239
240
241 /**
242  * Login to a remote server.
243  *
244  * @param idx   Connection index.
245  */
246 static void
247 server_login(CONN_ID idx)
248 {
249         Log(LOG_INFO,
250             "Connection %d (socket %d) with \"%s:%d\" established. Now logging in ...",
251             idx, My_Connections[idx].sock, My_Connections[idx].host,
252             Conf_Server[Conf_GetServer(idx)].port);
253
254         io_event_setcb( My_Connections[idx].sock, cb_clientserver);
255         io_event_add( My_Connections[idx].sock, IO_WANTREAD|IO_WANTWRITE);
256
257         /* Send PASS and SERVER command to peer */
258         Conn_WriteStr( idx, "PASS %s %s", Conf_Server[Conf_GetServer( idx )].pwd_out, NGIRCd_ProtoID );
259         Conn_WriteStr( idx, "SERVER %s :%s", Conf_ServerName, Conf_ServerInfo );
260 }
261
262
263 #ifdef SSL_SUPPORT
264 /**
265  * IO callback for new outgoing SSL-enabled server connections.
266  *
267  * @param sock          Socket descriptor.
268  * @param unused        (ignored IO specification)
269  */
270 static void
271 cb_connserver_login_ssl(int sock, short unused)
272 {
273         CONN_ID idx = Socket2Index(sock);
274
275         assert(idx >= 0);
276         if (idx < 0) {
277                 io_close(sock);
278                 return;
279         }
280         (void) unused;
281         switch (ConnSSL_Connect( &My_Connections[idx])) {
282         case 1: break;
283         case 0: LogDebug("ConnSSL_Connect: not ready");
284                 return;
285         case -1:
286                 Log(LOG_ERR, "SSL connection on socket %d failed!", sock);
287                 Conn_Close(idx, "Can't connect!", NULL, false);
288                 return;
289         }
290
291         Log( LOG_INFO, "SSL connection %d with \"%s:%d\" established.", idx,
292                         My_Connections[idx].host, Conf_Server[Conf_GetServer( idx )].port );
293
294         server_login(idx);
295 }
296 #endif
297
298
299 /**
300  * IO callback for established non-SSL client and server connections.
301  *
302  * @param sock  Socket descriptor.
303  * @param what  IO specification (IO_WANTREAD/IO_WANTWRITE/...).
304  */
305 static void
306 cb_clientserver(int sock, short what)
307 {
308         CONN_ID idx = Socket2Index(sock);
309
310         assert(idx >= 0);
311
312         if (idx < 0) {
313                 io_close(sock);
314                 return;
315         }
316 #ifdef SSL_SUPPORT
317         if (what & IO_WANTREAD
318             || (Conn_OPTION_ISSET(&My_Connections[idx], CONN_SSL_WANT_WRITE))) {
319                 /* if TLS layer needs to write additional data, call
320                  * Read_Request() instead so that SSL/TLS can continue */
321                 Read_Request(idx);
322         }
323 #else
324         if (what & IO_WANTREAD)
325                 Read_Request(idx);
326 #endif
327         if (what & IO_WANTWRITE)
328                 Handle_Write(idx);
329 }
330
331
332 #ifdef SSL_SUPPORT
333 /**
334  * IO callback for established SSL-enabled client and server connections.
335  *
336  * @param sock  Socket descriptor.
337  * @param what  IO specification (IO_WANTREAD/IO_WANTWRITE/...).
338  */
339 static void
340 cb_clientserver_ssl(int sock, short what)
341 {
342         CONN_ID idx = Socket2Index(sock);
343
344         assert(idx >= 0);
345
346         if (idx < 0) {
347                 io_close(sock);
348                 return;
349         }
350
351         switch (ConnSSL_Accept(&My_Connections[idx])) {
352         case 1:
353                 break;  /* OK */
354         case 0:
355                 return; /* EAGAIN: callback will be invoked again by IO layer */
356         default:
357                 Conn_Close(idx, "SSL accept error, closing socket", "SSL accept error", false);
358                 return;
359         }
360         if (what & IO_WANTREAD)
361                 Read_Request(idx);
362
363         if (what & IO_WANTWRITE)
364                 Handle_Write(idx);
365
366         io_event_setcb(sock, cb_clientserver);  /* SSL handshake completed */
367 }
368 #endif
369
370
371 /**
372  * Initialite connecion module.
373  */
374 GLOBAL void
375 Conn_Init( void )
376 {
377         CONN_ID i;
378
379         /* Speicher fuer Verbindungs-Pool anfordern */
380         Pool_Size = CONNECTION_POOL;
381         if ((Conf_MaxConnections > 0) &&
382                 (Pool_Size > Conf_MaxConnections))
383                         Pool_Size = Conf_MaxConnections;
384
385         if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)Pool_Size)) {
386                 Log(LOG_EMERG, "Can't allocate memory! [Conn_Init]");
387                 exit(1);
388         }
389
390         /* FIXME: My_Connetions/Pool_Size is needed by other parts of the
391          * code; remove them! */
392         My_Connections = (CONNECTION*) array_start(&My_ConnArray);
393
394         LogDebug("Allocated connection pool for %d items (%ld bytes).",
395                 array_length(&My_ConnArray, sizeof(CONNECTION)),
396                 array_bytes(&My_ConnArray));
397
398         assert(array_length(&My_ConnArray, sizeof(CONNECTION)) >= (size_t)Pool_Size);
399         
400         array_free( &My_Listeners );
401
402         for (i = 0; i < Pool_Size; i++)
403                 Init_Conn_Struct(i);
404 } /* Conn_Init */
405
406
407 /**
408  * Clean up connection module.
409  */
410 GLOBAL void
411 Conn_Exit( void )
412 {
413         CONN_ID idx;
414
415         Conn_ExitListeners();
416
417         LogDebug("Shutting down all connections ..." );
418         for( idx = 0; idx < Pool_Size; idx++ ) {
419                 if( My_Connections[idx].sock > NONE ) {
420                         Conn_Close( idx, NULL, NGIRCd_SignalRestart ?
421                                 "Server going down (restarting)":"Server going down", true );
422                 }
423         }
424
425         array_free(&My_ConnArray);
426         My_Connections = NULL;
427         Pool_Size = 0;
428         io_library_shutdown();
429 } /* Conn_Exit */
430
431
432 /**
433  * Close all sockets (file descriptors) of open connections.
434  * This is useful in forked child processes, for example, to make sure that
435  * they don't hold connections open that the main process wants to close.
436  */
437 GLOBAL void
438 Conn_CloseAllSockets(void)
439 {
440         CONN_ID idx;
441
442         for(idx = 0; idx < Pool_Size; idx++) {
443                 if(My_Connections[idx].sock > NONE)
444                         close(My_Connections[idx].sock);
445         }
446 }
447
448
449 /**
450  * Initialize listening ports.
451  *
452  * @param a             Array containing the ports the daemon should listen on.
453  * @param listen_addr   Address the socket should listen on (can be "0.0.0.0").
454  * @param func          IO callback function to register.
455  * @returns             Number of listening sockets created.
456  */
457 static unsigned int
458 ports_initlisteners(array *a, const char *listen_addr, void (*func)(int,short))
459 {
460         unsigned int created = 0;
461         size_t len;
462         int fd;
463         UINT16 *port;
464
465         len = array_length(a, sizeof (UINT16));
466         port = array_start(a);
467         while (len--) {
468                 fd = NewListener(listen_addr, *port);
469                 if (fd < 0) {
470                         port++;
471                         continue;
472                 }
473                 if (!io_event_create( fd, IO_WANTREAD, func )) {
474                         Log( LOG_ERR, "io_event_create(): Could not add listening fd %d (port %u): %s!",
475                                                 fd, (unsigned int) *port, strerror(errno));
476                         close(fd);
477                         port++;
478                         continue;
479                 }
480                 created++;
481                 port++;
482         }
483         return created;
484 }
485
486
487 /**
488  * Initialize all listening sockets.
489  *
490  * @returns     Number of created listening sockets
491  */
492 GLOBAL unsigned int
493 Conn_InitListeners( void )
494 {
495         /* Initialize ports on which the server should accept connections */
496         unsigned int created = 0;
497         char *copy, *listen_addr;
498
499         assert(Conf_ListenAddress);
500
501         /* can't use Conf_ListenAddress directly, see below */
502         copy = strdup(Conf_ListenAddress);
503         if (!copy) {
504                 Log(LOG_CRIT, "Cannot copy %s: %s", Conf_ListenAddress, strerror(errno));
505                 return 0;
506         }
507         listen_addr = strtok(copy, ",");
508
509         while (listen_addr) {
510                 ngt_TrimStr(listen_addr);
511                 if (*listen_addr) {
512                         created += ports_initlisteners(&Conf_ListenPorts, listen_addr, cb_listen);
513 #ifdef SSL_SUPPORT
514                         created += ports_initlisteners(&Conf_SSLOptions.ListenPorts, listen_addr, cb_listen_ssl);
515 #endif
516                 }
517
518                 listen_addr = strtok(NULL, ",");
519         }
520
521         /* Can't free() Conf_ListenAddress here: on REHASH, if the config file
522          * cannot be re-loaded, we'd end up with a NULL Conf_ListenAddress.
523          * Instead, free() takes place in conf.c, before the config file
524          * is being parsed. */
525         free(copy);
526
527         return created;
528 } /* Conn_InitListeners */
529
530
531 /**
532  * Shut down all listening sockets.
533  */
534 GLOBAL void
535 Conn_ExitListeners( void )
536 {
537         /* Close down all listening sockets */
538         int *fd;
539         size_t arraylen;
540
541         arraylen = array_length(&My_Listeners, sizeof (int));
542         Log(LOG_INFO,
543             "Shutting down all listening sockets (%d total) ...", arraylen);
544         fd = array_start(&My_Listeners);
545         while(arraylen--) {
546                 assert(fd != NULL);
547                 assert(*fd >= 0);
548                 io_close(*fd);
549                 LogDebug("Listening socket %d closed.", *fd );
550                 fd++;
551         }
552         array_free(&My_Listeners);
553 } /* Conn_ExitListeners */
554
555
556 /**
557  * Bind a socket to a specific (source) address.
558  *
559  * @param addr                  Address structure.
560  * @param listen_addrstr        Source address as string.
561  * @param Port                  Port number.
562  * @returns                     true on success, false otherwise.
563  */
564 static bool
565 InitSinaddrListenAddr(ng_ipaddr_t *addr, const char *listen_addrstr, UINT16 Port)
566 {
567         bool ret;
568
569         ret = ng_ipaddr_init(addr, listen_addrstr, Port);
570         if (!ret) {
571                 assert(listen_addrstr);
572                 Log(LOG_CRIT, "Can't bind to [%s]:%u: can't convert ip address \"%s\"",
573                                                 listen_addrstr, Port, listen_addrstr);
574         }
575         return ret;
576 }
577
578
579 /**
580  * Set a socket to "IPv6 only". If the given socket doesn't belong to the
581  * AF_INET6 family, or the operating system doesn't support this functionality,
582  * this function retruns silently.
583  *
584  * @param af    Address family of the socket.
585  * @param sock  Socket handle.
586  */
587 static void
588 set_v6_only(int af, int sock)
589 {
590 #if defined(IPV6_V6ONLY) && defined(WANT_IPV6)
591         int on = 1;
592
593         if (af != AF_INET6)
594                 return;
595
596         if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, (socklen_t)sizeof(on)))
597                 Log(LOG_ERR, "Could not set IPV6_V6ONLY: %s", strerror(errno));
598 #else
599         (void)af;
600         (void)sock;
601 #endif
602 }
603
604
605 /**
606  * Initialize new listening port.
607  *
608  * @param listen_addr   Local address to bind the socet to (can be 0.0.0.0).
609  * @param Port          Port number on which the new socket should be listening.
610  * @returns             file descriptor of the socket or -1 on failure.
611  */
612 static int
613 NewListener(const char *listen_addr, UINT16 Port)
614 {
615         /* Create new listening socket on specified port */
616         ng_ipaddr_t addr;
617         int sock, af;
618
619         if (!InitSinaddrListenAddr(&addr, listen_addr, Port))
620                 return -1;
621
622         af = ng_ipaddr_af(&addr);
623         sock = socket(af, SOCK_STREAM, 0);
624         if( sock < 0 ) {
625                 Log(LOG_CRIT, "Can't create socket (af %d) : %s!", af, strerror(errno));
626                 return -1;
627         }
628
629         set_v6_only(af, sock);
630
631         if (!Init_Socket(sock))
632                 return -1;
633
634         if (bind(sock, (struct sockaddr *)&addr, ng_ipaddr_salen(&addr)) != 0) {
635                 Log(LOG_CRIT, "Can't bind socket to address %s:%d - %s",
636                         ng_ipaddr_tostr(&addr), Port, strerror(errno));
637                 close(sock);
638                 return -1;
639         }
640
641         if( listen( sock, 10 ) != 0 ) {
642                 Log( LOG_CRIT, "Can't listen on socket: %s!", strerror( errno ));
643                 close( sock );
644                 return -1;
645         }
646
647         /* keep fd in list so we can close it when ngircd restarts/shuts down */
648         if (!array_catb( &My_Listeners,(char*) &sock, sizeof(int) )) {
649                 Log( LOG_CRIT, "Can't add socket to My_Listeners array: %s!", strerror( errno ));
650                 close( sock );
651                 return -1;
652         }
653
654         Log(LOG_INFO, "Now listening on [%s]:%d (socket %d).",
655             ng_ipaddr_tostr(&addr), Port, sock);
656         return sock;
657 } /* NewListener */
658
659
660 #ifdef SSL_SUPPORT
661
662 /**
663  * Check if SSL library needs to read SSL-protocol related data.
664  *
665  * SSL/TLS connections require extra treatment:
666  * When either CONN_SSL_WANT_WRITE or CONN_SSL_WANT_READ is set, we
667  * need to take care of that first, before checking read/write buffers.
668  * For instance, while we might have data in our write buffer, the
669  * TLS/SSL protocol might need to read internal data first for TLS/SSL
670  * writes to succeed.
671  *
672  * If this function returns true, such a condition is met and we have
673  * to reverse the condition (check for read even if we've data to write,
674  * do not check for read but writeability even if write-buffer is empty).
675  *
676  * @param c     Connection to check.
677  * @returns     true if SSL-library has to read protocol data.
678  */
679 static bool
680 SSL_WantRead(const CONNECTION *c)
681 {
682         if (Conn_OPTION_ISSET(c, CONN_SSL_WANT_READ)) {
683                 io_event_add(c->sock, IO_WANTREAD);
684                 return true;
685         }
686         return false;
687 }
688
689 /**
690  * Check if SSL library needs to write SSL-protocol related data.
691  *
692  * Please see description of SSL_WantRead() for full description!
693  *
694  * @param c     Connection to check.
695  * @returns     true if SSL-library has to write protocol data.
696  */
697 static bool
698 SSL_WantWrite(const CONNECTION *c)
699 {
700         if (Conn_OPTION_ISSET(c, CONN_SSL_WANT_WRITE)) {
701                 io_event_add(c->sock, IO_WANTWRITE);
702                 return true;
703         }
704         return false;
705 }
706
707 #else
708
709 static inline bool
710 SSL_WantRead(UNUSED const CONNECTION *c)
711 { return false; }
712
713 static inline bool
714 SSL_WantWrite(UNUSED const CONNECTION *c)
715 { return false; }
716
717 #endif
718
719
720 /**
721  * "Main Loop": Loop until shutdown or restart is signalled.
722  *
723  * This function loops until a shutdown or restart of ngIRCd is signalled and
724  * calls io_dispatch() to check for readable and writable sockets every second.
725  * It checks for status changes on pending connections (e. g. when a hostname
726  * has been resolved), checks for "penalties" and timeouts, and handles the
727  * input buffers.
728  */
729 GLOBAL void
730 Conn_Handler(void)
731 {
732         int i;
733         unsigned int wdatalen, bytes_processed;
734         struct timeval tv;
735         time_t t;
736
737         while (!NGIRCd_SignalQuit && !NGIRCd_SignalRestart) {
738                 t = time(NULL);
739
740                 /* Check configured servers and established links */
741                 Check_Servers();
742                 Check_Connections();
743
744                 /* Look for non-empty read buffers ... */
745                 for (i = 0; i < Pool_Size; i++) {
746                         if ((My_Connections[i].sock > NONE)
747                             && (array_bytes(&My_Connections[i].rbuf) > 0)
748                             && (My_Connections[i].delaytime <= t)) {
749                                 /* ... and try to handle the received data */
750                                 bytes_processed = Handle_Buffer(i);
751                                 /* if we processed data, and there might be
752                                  * more commands in the input buffer, do not
753                                  * try to read any more data now */
754                                 if (bytes_processed &&
755                                     array_bytes(&My_Connections[i].rbuf) > 2) {
756                                         LogDebug
757                                             ("Throttling connection %d: command limit reached!",
758                                              i);
759                                         Conn_SetPenalty(i, 1);
760                                 }
761                         }
762                 }
763
764                 /* Look for non-empty write buffers ... */
765                 for (i = 0; i < Pool_Size; i++) {
766                         if (My_Connections[i].sock <= NONE)
767                                 continue;
768
769                         wdatalen = (unsigned int)array_bytes(&My_Connections[i].wbuf);
770 #ifdef ZLIB
771                         if (wdatalen > 0 ||
772                             array_bytes(&My_Connections[i].zip.wbuf) > 0)
773 #else
774                         if (wdatalen > 0)
775 #endif
776                         {
777                                 if (SSL_WantRead(&My_Connections[i]))
778                                         continue;
779                                 io_event_add(My_Connections[i].sock,
780                                              IO_WANTWRITE);
781                         }
782                 }
783
784                 /* Check from which sockets we possibly could read ... */
785                 for (i = 0; i < Pool_Size; i++) {
786                         if (My_Connections[i].sock <= NONE)
787                                 continue;
788 #ifdef SSL_SUPPORT
789                         if (SSL_WantWrite(&My_Connections[i]))
790                                 continue; /* TLS/SSL layer needs to write data; deal with this first */
791 #endif
792                         if (Proc_InProgress(&My_Connections[i].proc_stat)) {
793                                 /* Wait for completion of forked subprocess
794                                  * and ignore the socket in the meantime ... */
795                                 io_event_del(My_Connections[i].sock,
796                                              IO_WANTREAD);
797                                 continue;
798                         }
799
800                         if (Conn_OPTION_ISSET(&My_Connections[i], CONN_ISCONNECTING))
801                                 /* Wait for completion of connect() ... */
802                                 continue;
803
804                         if (My_Connections[i].delaytime > t) {
805                                 /* There is a "penalty time" set: ignore socket! */
806                                 io_event_del(My_Connections[i].sock,
807                                              IO_WANTREAD);
808                                 continue;
809                         }
810
811                         io_event_add(My_Connections[i].sock, IO_WANTREAD);
812                 }
813
814                 /* Set the timeout for reading from the network to 1 second,
815                  * which is the granularity with witch we handle "penalty
816                  * times" for example.
817                  * Note: tv_sec/usec are undefined(!) after io_dispatch()
818                  * returns, so we have to set it beforce each call to it! */
819                 tv.tv_usec = 0;
820                 tv.tv_sec = 1;
821
822                 /* Wait for activity ... */
823                 i = io_dispatch(&tv);
824                 if (i == -1 && errno != EINTR) {
825                         Log(LOG_EMERG, "Conn_Handler(): io_dispatch(): %s!",
826                             strerror(errno));
827                         Log(LOG_ALERT, "%s exiting due to fatal errors!",
828                             PACKAGE_NAME);
829                         exit(1);
830                 }
831         }
832
833         if (NGIRCd_SignalQuit)
834                 Log(LOG_NOTICE | LOG_snotice, "Server going down NOW!");
835         else if (NGIRCd_SignalRestart)
836                 Log(LOG_NOTICE | LOG_snotice, "Server restarting NOW!");
837 } /* Conn_Handler */
838
839
840 /**
841  * Write a text string into the socket of a connection.
842  *
843  * This function automatically appends CR+LF to the string and validates that
844  * the result is a valid IRC message (oversized messages are shortened, for
845  * example). Then it calls the Conn_Write() function to do the actual sending.
846  *
847  * @param Idx           Index fo the connection.
848  * @param Format        Format string, see printf().
849  * @returns             true on success, false otherwise.
850  */
851 #ifdef PROTOTYPES
852 GLOBAL bool
853 Conn_WriteStr(CONN_ID Idx, const char *Format, ...)
854 #else
855 GLOBAL bool 
856 Conn_WriteStr(Idx, Format, va_alist)
857 CONN_ID Idx;
858 const char *Format;
859 va_dcl
860 #endif
861 {
862         char buffer[COMMAND_LEN];
863         size_t len;
864         bool ok;
865         va_list ap;
866
867         assert( Idx > NONE );
868         assert( Format != NULL );
869
870 #ifdef PROTOTYPES
871         va_start( ap, Format );
872 #else
873         va_start( ap );
874 #endif
875         if (vsnprintf( buffer, COMMAND_LEN - 2, Format, ap ) >= COMMAND_LEN - 2 ) {
876                 /*
877                  * The string that should be written to the socket is longer
878                  * than the allowed size of COMMAND_LEN bytes (including both
879                  * the CR and LF characters). This can be caused by the
880                  * IRC_WriteXXX() functions when the prefix of this server had
881                  * to be added to an already "quite long" command line which
882                  * has been received from a regular IRC client, for example.
883                  * 
884                  * We are not allowed to send such "oversized" messages to
885                  * other servers and clients, see RFC 2812 2.3 and 2813 3.3
886                  * ("these messages SHALL NOT exceed 512 characters in length,
887                  * counting all characters including the trailing CR-LF").
888                  *
889                  * So we have a big problem here: we should send more bytes
890                  * to the network than we are allowed to and we don't know
891                  * the originator (any more). The "old" behaviour of blaming
892                  * the receiver ("next hop") is a bad idea (it could be just
893                  * an other server only routing the message!), so the only
894                  * option left is to shorten the string and to hope that the
895                  * result is still somewhat useful ...
896                  *                                                   -alex-
897                  */
898
899                 strcpy (buffer + sizeof(buffer) - strlen(CUT_TXTSUFFIX) - 2 - 1,
900                         CUT_TXTSUFFIX);
901         }
902
903 #ifdef SNIFFER
904         if (NGIRCd_Sniffer)
905                 Log(LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer);
906 #endif
907
908         len = strlcat( buffer, "\r\n", sizeof( buffer ));
909         ok = Conn_Write(Idx, buffer, len);
910         My_Connections[Idx].msg_out++;
911
912         va_end( ap );
913         return ok;
914 } /* Conn_WriteStr */
915
916
917 /**
918  * Append Data to the outbound write buffer of a connection.
919  *
920  * @param Idx   Index of the connection.
921  * @param Data  pointer to the data.
922  * @param Len   length of Data.
923  * @returns     true on success, false otherwise.
924  */
925 static bool
926 Conn_Write( CONN_ID Idx, char *Data, size_t Len )
927 {
928         CLIENT *c;
929         size_t writebuf_limit = WRITEBUFFER_MAX_LEN;
930         assert( Idx > NONE );
931         assert( Data != NULL );
932         assert( Len > 0 );
933
934         c = Conn_GetClient(Idx);
935         assert( c != NULL);
936
937         /* Servers do get special write buffer limits, so they can generate
938          * all the messages that are required while peering. */
939         if (Client_Type(c) == CLIENT_SERVER)
940                 writebuf_limit = WRITEBUFFER_SLINK_LEN;
941
942         /* Is the socket still open? A previous call to Conn_Write()
943          * may have closed the connection due to a fatal error.
944          * In this case it is sufficient to return an error, as well. */
945         if( My_Connections[Idx].sock <= NONE ) {
946                 LogDebug("Skipped write on closed socket (connection %d).", Idx);
947                 return false;
948         }
949
950 #ifdef ZLIB
951         if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
952                 /* Compressed link:
953                  * Zip_Buffer() does all the dirty work for us: it flushes
954                  * the (pre-)compression buffers if required and handles
955                  * all error conditions. */
956                 if (!Zip_Buffer(Idx, Data, Len))
957                         return false;
958         }
959         else
960 #endif
961         {
962                 /* Uncompressed link:
963                  * Check if outbound buffer has enough space for the data. */
964                 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
965                     WRITEBUFFER_FLUSH_LEN) {
966                         /* Buffer is full, flush it. Handle_Write deals with
967                          * low-level errors, if any. */
968                         if (!Handle_Write(Idx))
969                                 return false;
970                 }
971
972                 /* When the write buffer is still too big after flushing it,
973                  * the connection will be killed. */
974                 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
975                     writebuf_limit) {
976                         Log(LOG_NOTICE,
977                             "Write buffer space exhausted (connection %d, limit is %lu bytes, %lu bytes new, %lu bytes pending)",
978                             Idx, writebuf_limit, Len,
979                             (unsigned long)array_bytes(&My_Connections[Idx].wbuf));
980                         Conn_Close(Idx, "Write buffer space exhausted", NULL, false);
981                         return false;
982                 }
983
984                 /* Copy data to write buffer */
985                 if (!array_catb(&My_Connections[Idx].wbuf, Data, Len))
986                         return false;
987
988                 My_Connections[Idx].bytes_out += Len;
989         }
990
991         /* Adjust global write counter */
992         WCounter += Len;
993
994         return true;
995 } /* Conn_Write */
996
997
998 /**
999  * Shut down a connection.
1000  *
1001  * @param Idx           Connection index.
1002  * @param LogMsg        Message to write to the log or NULL. If no LogMsg
1003  *                      is given, the FwdMsg is logged.
1004  * @param FwdMsg        Message to forward to remote servers.
1005  * @param InformClient  If true, inform the client on the connection which is
1006  *                      to be shut down of the reason (FwdMsg) and send
1007  *                      connection statistics before disconnecting it.
1008  */
1009 GLOBAL void
1010 Conn_Close( CONN_ID Idx, const char *LogMsg, const char *FwdMsg, bool InformClient )
1011 {
1012         /* Close connection. Open pipes of asyncronous resolver
1013          * sub-processes are closed down. */
1014
1015         CLIENT *c;
1016         double in_k, out_k;
1017         UINT16 port;
1018 #ifdef ZLIB
1019         double in_z_k, out_z_k;
1020         int in_p, out_p;
1021 #endif
1022
1023         assert( Idx > NONE );
1024
1025         /* Is this link already shutting down? */
1026         if( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ISCLOSING )) {
1027                 /* Conn_Close() has been called recursively for this link;
1028                  * probabe reason: Handle_Write() failed  -- see below. */
1029                 LogDebug("Recursive request to close connection: %d", Idx );
1030                 return;
1031         }
1032
1033         assert( My_Connections[Idx].sock > NONE );
1034
1035         /* Mark link as "closing" */
1036         Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCLOSING );
1037
1038         port = ng_ipaddr_getport(&My_Connections[Idx].addr);
1039         Log(LOG_INFO, "Shutting down connection %d (%s) with %s:%d ...", Idx,
1040             LogMsg ? LogMsg : FwdMsg, My_Connections[Idx].host, port);
1041
1042         /* Search client, if any */
1043         c = Conn_GetClient( Idx );
1044
1045         /* Should the client be informed? */
1046         if (InformClient) {
1047 #ifndef STRICT_RFC
1048                 /* Send statistics to client if registered as user: */
1049                 if ((c != NULL) && (Client_Type(c) == CLIENT_USER)) {
1050                         Conn_WriteStr( Idx,
1051                          ":%s NOTICE %s :%sConnection statistics: client %.1f kb, server %.1f kb.",
1052                          Client_ID(Client_ThisServer()), Client_ID(c),
1053                          NOTICE_TXTPREFIX,
1054                          (double)My_Connections[Idx].bytes_in / 1024,
1055                          (double)My_Connections[Idx].bytes_out / 1024);
1056                 }
1057 #endif
1058                 /* Send ERROR to client (see RFC 2812, section 3.1.7) */
1059                 if (FwdMsg)
1060                         Conn_WriteStr(Idx, "ERROR :%s", FwdMsg);
1061                 else
1062                         Conn_WriteStr(Idx, "ERROR :Closing connection");
1063         }
1064
1065         /* Try to write out the write buffer. Note: Handle_Write() eventually
1066          * removes the CLIENT structure associated with this connection if an
1067          * error occurs! So we have to re-check if there is still an valid
1068          * CLIENT structure after calling Handle_Write() ...*/
1069         (void)Handle_Write( Idx );
1070
1071         /* Search client, if any (re-check!) */
1072         c = Conn_GetClient( Idx );
1073 #ifdef SSL_SUPPORT
1074         if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_SSL )) {
1075                 Log(LOG_INFO, "SSL connection %d shutting down ...", Idx);
1076                 ConnSSL_Free(&My_Connections[Idx]);
1077         }
1078 #endif
1079         /* Shut down socket */
1080         if (! io_close(My_Connections[Idx].sock)) {
1081                 /* Oops, we can't close the socket!? This is ... ugly! */
1082                 Log(LOG_CRIT,
1083                     "Error closing connection %d (socket %d) with %s:%d - %s! (ignored)",
1084                     Idx, My_Connections[Idx].sock, My_Connections[Idx].host,
1085                     port, strerror(errno));
1086         }
1087
1088         /* Mark socket as invalid: */
1089         My_Connections[Idx].sock = NONE;
1090
1091         /* If there is still a client, unregister it now */
1092         if (c)
1093                 Client_Destroy(c, LogMsg, FwdMsg, true);
1094
1095         /* Calculate statistics and log information */
1096         in_k = (double)My_Connections[Idx].bytes_in / 1024;
1097         out_k = (double)My_Connections[Idx].bytes_out / 1024;
1098 #ifdef ZLIB
1099         if (Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP)) {
1100                 in_z_k = (double)My_Connections[Idx].zip.bytes_in / 1024;
1101                 out_z_k = (double)My_Connections[Idx].zip.bytes_out / 1024;
1102                 /* Make sure that no division by zero can occur during
1103                  * the calculation of in_p and out_p: in_z_k and out_z_k
1104                  * are non-zero, that's guaranteed by the protocol until
1105                  * compression can be enabled. */
1106                 if (! in_z_k)
1107                         in_z_k = in_k;
1108                 if (! out_z_k)
1109                         out_z_k = out_k;
1110                 in_p = (int)(( in_k * 100 ) / in_z_k );
1111                 out_p = (int)(( out_k * 100 ) / out_z_k );
1112                 Log(LOG_INFO,
1113                     "Connection %d with %s:%d closed (in: %.1fk/%.1fk/%d%%, out: %.1fk/%.1fk/%d%%).",
1114                     Idx, My_Connections[Idx].host, port,
1115                     in_k, in_z_k, in_p, out_k, out_z_k, out_p);
1116         }
1117         else
1118 #endif
1119         {
1120                 Log(LOG_INFO,
1121                     "Connection %d with %s:%d closed (in: %.1fk, out: %.1fk).",
1122                     Idx, My_Connections[Idx].host, port,
1123                     in_k, out_k);
1124         }
1125
1126         /* Servers: Modify time of next connect attempt? */
1127         Conf_UnsetServer( Idx );
1128
1129 #ifdef ZLIB
1130         /* Clean up zlib, if link was compressed */
1131         if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
1132                 inflateEnd( &My_Connections[Idx].zip.in );
1133                 deflateEnd( &My_Connections[Idx].zip.out );
1134                 array_free(&My_Connections[Idx].zip.rbuf);
1135                 array_free(&My_Connections[Idx].zip.wbuf);
1136         }
1137 #endif
1138
1139         array_free(&My_Connections[Idx].rbuf);
1140         array_free(&My_Connections[Idx].wbuf);
1141
1142         /* Clean up connection structure (=free it) */
1143         Init_Conn_Struct( Idx );
1144
1145         assert(NumConnections > 0);
1146         if (NumConnections)
1147                 NumConnections--;
1148         LogDebug("Shutdown of connection %d completed, %ld connection%s left.",
1149                  Idx, NumConnections, NumConnections != 1 ? "s" : "");
1150 } /* Conn_Close */
1151
1152
1153 /**
1154  * Get current number of connections.
1155  *
1156  * @returns     Number of current connections.
1157  */
1158 GLOBAL long
1159 Conn_Count(void)
1160 {
1161         return NumConnections;
1162 } /* Conn_Count */
1163
1164
1165 /**
1166  * Get number of maximum simultaneous connections.
1167  *
1168  * @returns     Number of maximum simultaneous connections.
1169  */
1170 GLOBAL long
1171 Conn_CountMax(void)
1172 {
1173         return NumConnectionsMax;
1174 } /* Conn_CountMax */
1175
1176
1177 /**
1178  * Get number of connections accepted since the daemon startet.
1179  *
1180  * @returns     Number of connections accepted.
1181  */
1182 GLOBAL long
1183 Conn_CountAccepted(void)
1184 {
1185         return NumConnectionsAccepted;
1186 } /* Conn_CountAccepted */
1187
1188
1189 /**
1190  * Synchronize established connections and configured server structures
1191  * after a configuration update and store the correct connection IDs, if any.
1192  */
1193 GLOBAL void
1194 Conn_SyncServerStruct(void)
1195 {
1196         CLIENT *client;
1197         CONN_ID i;
1198         int c;
1199
1200         for (i = 0; i < Pool_Size; i++) {
1201                 if (My_Connections[i].sock == NONE)
1202                         continue;
1203
1204                 /* Server link? */
1205                 client = Conn_GetClient(i);
1206                 if (!client || Client_Type(client) != CLIENT_SERVER)
1207                         continue;
1208
1209                 for (c = 0; c < MAX_SERVERS; c++) {
1210                         /* Configured server? */
1211                         if (!Conf_Server[c].host[0])
1212                                 continue;
1213
1214                         if (strcasecmp(Conf_Server[c].name, Client_ID(client)) == 0)
1215                                 Conf_Server[c].conn_id = i;
1216                 }
1217         }
1218 } /* SyncServerStruct */
1219
1220
1221 /**
1222  * Send out data of write buffer; connect new sockets.
1223  *
1224  * @param Idx   Connection index.
1225  * @returns     true on success, false otherwise.
1226  */
1227 static bool
1228 Handle_Write( CONN_ID Idx )
1229 {
1230         ssize_t len;
1231         size_t wdatalen;
1232
1233         assert( Idx > NONE );
1234         if ( My_Connections[Idx].sock < 0 ) {
1235                 LogDebug("Handle_Write() on closed socket, connection %d", Idx);
1236                 return false;
1237         }
1238         assert( My_Connections[Idx].sock > NONE );
1239
1240         wdatalen = array_bytes(&My_Connections[Idx].wbuf );
1241
1242 #ifdef ZLIB
1243         if (wdatalen == 0) {
1244                 /* Write buffer is empty, so we try to flush the compression
1245                  * buffer and get some data to work with from there :-) */
1246                 if (!Zip_Flush(Idx))
1247                         return false;
1248
1249                 /* Now the write buffer most probably has changed: */
1250                 wdatalen = array_bytes(&My_Connections[Idx].wbuf);
1251         }
1252 #endif
1253
1254         if (wdatalen == 0) {
1255                 /* Still no data, fine. */
1256                 io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
1257                 return true;
1258         }
1259
1260 #ifdef DEBUG_BUFFER
1261         LogDebug
1262             ("Handle_Write() called for connection %d, %ld bytes pending ...",
1263              Idx, wdatalen);
1264 #endif
1265
1266 #ifdef SSL_SUPPORT
1267         if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_SSL )) {
1268                 len = ConnSSL_Write(&My_Connections[Idx], array_start(&My_Connections[Idx].wbuf), wdatalen);
1269         } else
1270 #endif
1271         {
1272                 len = write(My_Connections[Idx].sock,
1273                             array_start(&My_Connections[Idx].wbuf), wdatalen );
1274         }
1275         if( len < 0 ) {
1276                 if (errno == EAGAIN || errno == EINTR)
1277                         return true;
1278
1279                 Log(LOG_ERR, "Write error on connection %d (socket %d): %s!",
1280                     Idx, My_Connections[Idx].sock, strerror(errno));
1281                 Conn_Close(Idx, "Write error!", NULL, false);
1282                 return false;
1283         }
1284
1285         /* move any data not yet written to beginning */
1286         array_moveleft(&My_Connections[Idx].wbuf, 1, (size_t)len);
1287
1288         return true;
1289 } /* Handle_Write */
1290
1291
1292 /**
1293  * Count established connections to a specific IP address.
1294  *
1295  * @returns     Number of established connections.
1296  */
1297 static int
1298 Count_Connections(ng_ipaddr_t *a)
1299 {
1300         int i, cnt;
1301
1302         cnt = 0;
1303         for (i = 0; i < Pool_Size; i++) {
1304                 if (My_Connections[i].sock <= NONE)
1305                         continue;
1306                 if (ng_ipaddr_ipequal(&My_Connections[i].addr, a))
1307                         cnt++;
1308         }
1309         return cnt;
1310 } /* Count_Connections */
1311
1312
1313 /**
1314  * Initialize new client connection on a listening socket.
1315  *
1316  * @param Sock  Listening socket descriptor.
1317  * @returns     Accepted socket descriptor or -1 on error.
1318  */
1319 static int
1320 New_Connection(int Sock)
1321 {
1322 #ifdef TCPWRAP
1323         struct request_info req;
1324 #endif
1325         ng_ipaddr_t new_addr;
1326         char ip_str[NG_INET_ADDRSTRLEN];
1327         int new_sock, new_sock_len, identsock;
1328         CLIENT *c;
1329         long cnt;
1330
1331         assert(Sock > NONE);
1332
1333         LogDebug("Accepting new connection on socket %d ...", Sock);
1334
1335         new_sock_len = (int)sizeof(new_addr);
1336         new_sock = accept(Sock, (struct sockaddr *)&new_addr,
1337                           (socklen_t *)&new_sock_len);
1338         if (new_sock < 0) {
1339                 Log(LOG_CRIT, "Can't accept connection: %s!", strerror(errno));
1340                 return -1;
1341         }
1342         NumConnectionsAccepted++;
1343
1344         if (!ng_ipaddr_tostr_r(&new_addr, ip_str)) {
1345                 Log(LOG_CRIT, "fd %d: Can't convert IP address!", new_sock);
1346                 Simple_Message(new_sock, "ERROR :Internal Server Error");
1347                 close(new_sock);
1348                 return -1;
1349         }
1350
1351 #ifdef TCPWRAP
1352         /* Validate socket using TCP Wrappers */
1353         request_init(&req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock,
1354                      RQ_CLIENT_SIN, &new_addr, NULL);
1355         fromhost(&req);
1356         if (!hosts_access(&req)) {
1357                 Log(deny_severity,
1358                     "Refused connection from %s (by TCP Wrappers)!", ip_str);
1359                 Simple_Message(new_sock, "ERROR :Connection refused");
1360                 close(new_sock);
1361                 return -1;
1362         }
1363 #endif
1364
1365         if (!Init_Socket(new_sock))
1366                 return -1;
1367
1368         /* Check global connection limit */
1369         if ((Conf_MaxConnections > 0) &&
1370             (NumConnections >= (size_t) Conf_MaxConnections)) {
1371                 Log(LOG_ALERT, "Can't accept connection: limit (%d) reached!",
1372                     Conf_MaxConnections);
1373                 Simple_Message(new_sock, "ERROR :Connection limit reached");
1374                 close(new_sock);
1375                 return -1;
1376         }
1377
1378         /* Check IP-based connection limit */
1379         cnt = Count_Connections(&new_addr);
1380         if ((Conf_MaxConnectionsIP > 0) && (cnt >= Conf_MaxConnectionsIP)) {
1381                 /* Access denied, too many connections from this IP address! */
1382                 Log(LOG_ERR,
1383                     "Refused connection from %s: too may connections (%ld) from this IP address!",
1384                     ip_str, cnt);
1385                 Simple_Message(new_sock,
1386                                "ERROR :Connection refused, too many connections from your IP address");
1387                 close(new_sock);
1388                 return -1;
1389         }
1390
1391         if (new_sock >= Pool_Size) {
1392                 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION),
1393                                  (size_t) new_sock)) {
1394                         Log(LOG_EMERG,
1395                             "Can't allocate memory! [New_Connection]");
1396                         Simple_Message(new_sock, "ERROR: Internal error");
1397                         close(new_sock);
1398                         return -1;
1399                 }
1400                 LogDebug("Bumped connection pool to %ld items (internal: %ld items, %ld bytes)",
1401                          new_sock, array_length(&My_ConnArray,
1402                          sizeof(CONNECTION)), array_bytes(&My_ConnArray));
1403
1404                 /* Adjust pointer to new block */
1405                 My_Connections = array_start(&My_ConnArray);
1406                 while (Pool_Size <= new_sock)
1407                         Init_Conn_Struct(Pool_Size++);
1408         }
1409
1410         /* register callback */
1411         if (!io_event_create(new_sock, IO_WANTREAD, cb_clientserver)) {
1412                 Log(LOG_ALERT,
1413                     "Can't accept connection: io_event_create failed!");
1414                 Simple_Message(new_sock, "ERROR :Internal error");
1415                 close(new_sock);
1416                 return -1;
1417         }
1418
1419         c = Client_NewLocal(new_sock, ip_str, CLIENT_UNKNOWN, false);
1420         if (!c) {
1421                 Log(LOG_ALERT,
1422                     "Can't accept connection: can't create client structure!");
1423                 Simple_Message(new_sock, "ERROR :Internal error");
1424                 io_close(new_sock);
1425                 return -1;
1426         }
1427
1428         Init_Conn_Struct(new_sock);
1429         My_Connections[new_sock].sock = new_sock;
1430         My_Connections[new_sock].addr = new_addr;
1431         My_Connections[new_sock].client = c;
1432
1433         /* Set initial hostname to IP address. This becomes overwritten when
1434          * the DNS lookup is enabled and succeeds, but is used otherwise. */
1435         if (ng_ipaddr_af(&new_addr) != AF_INET)
1436                 snprintf(My_Connections[new_sock].host,
1437                          sizeof(My_Connections[new_sock].host), "[%s]", ip_str);
1438         else
1439                 strlcpy(My_Connections[new_sock].host, ip_str,
1440                         sizeof(My_Connections[new_sock].host));
1441
1442         Client_SetHostname(c, My_Connections[new_sock].host);
1443
1444         Log(LOG_INFO, "Accepted connection %d from %s:%d on socket %d.",
1445             new_sock, My_Connections[new_sock].host,
1446             ng_ipaddr_getport(&new_addr), Sock);
1447
1448         identsock = new_sock;
1449 #ifdef IDENTAUTH
1450         if (!Conf_Ident)
1451                 identsock = -1;
1452 #endif
1453         if (Conf_DNS) {
1454                 if (Conf_NoticeAuth) {
1455 #ifdef IDENTAUTH
1456                         if (Conf_Ident)
1457                                 (void)Conn_WriteStr(new_sock,
1458                                         "NOTICE AUTH :*** Looking up your hostname and checking ident");
1459                         else
1460 #endif
1461                                 (void)Conn_WriteStr(new_sock,
1462                                         "NOTICE AUTH :*** Looking up your hostname");
1463                 }
1464                 Resolve_Addr(&My_Connections[new_sock].proc_stat, &new_addr,
1465                              identsock, cb_Read_Resolver_Result);
1466         }
1467
1468         Account_Connection();
1469         return new_sock;
1470 } /* New_Connection */
1471
1472
1473 /**
1474  * Update global connection counters.
1475  */
1476 static void
1477 Account_Connection(void)
1478 {
1479         NumConnections++;
1480         if (NumConnections > NumConnectionsMax)
1481                 NumConnectionsMax = NumConnections;
1482         LogDebug("Total number of connections now %lu (max %lu).",
1483                  NumConnections, NumConnectionsMax);
1484 } /* Account_Connection */
1485
1486
1487 /**
1488  * Translate socket handle into connection index.
1489  *
1490  * @param Sock  Socket handle.
1491  * @returns     Connecion index or NONE, if no connection could be found.
1492  */
1493 static CONN_ID
1494 Socket2Index( int Sock )
1495 {
1496         assert( Sock >= 0 );
1497
1498         if( Sock >= Pool_Size || My_Connections[Sock].sock != Sock ) {
1499                 /* the Connection was already closed again, likely due to
1500                  * an error. */
1501                 LogDebug("Socket2Index: can't get connection for socket %d!", Sock);
1502                 return NONE;
1503         }
1504         return Sock;
1505 } /* Socket2Index */
1506
1507
1508 /**
1509  * Read data from the network to the read buffer. If an error occures,
1510  * the socket of this connection will be shut down.
1511  *
1512  * @param Idx   Connection index.
1513  */
1514 static void
1515 Read_Request( CONN_ID Idx )
1516 {
1517         ssize_t len;
1518         static const unsigned int maxbps = COMMAND_LEN / 2;
1519         char readbuf[READBUFFER_LEN];
1520         time_t t;
1521         CLIENT *c;
1522         assert( Idx > NONE );
1523         assert( My_Connections[Idx].sock > NONE );
1524
1525 #ifdef ZLIB
1526         if ((array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN) ||
1527                 (array_bytes(&My_Connections[Idx].zip.rbuf) >= READBUFFER_LEN))
1528 #else
1529         if (array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN)
1530 #endif
1531         {
1532                 /* Read buffer is full */
1533                 Log(LOG_ERR,
1534                     "Receive buffer space exhausted (connection %d): %d bytes",
1535                     Idx, array_bytes(&My_Connections[Idx].rbuf));
1536                 Conn_Close(Idx, "Receive buffer space exhausted", NULL, false);
1537                 return;
1538         }
1539
1540 #ifdef SSL_SUPPORT
1541         if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_SSL))
1542                 len = ConnSSL_Read( &My_Connections[Idx], readbuf, sizeof(readbuf));
1543         else
1544 #endif
1545         len = read(My_Connections[Idx].sock, readbuf, sizeof(readbuf));
1546         if (len == 0) {
1547                 Log(LOG_INFO, "%s:%u (%s) is closing the connection ...",
1548                                 My_Connections[Idx].host,
1549                                 (unsigned int) ng_ipaddr_getport(&My_Connections[Idx].addr),
1550                                 ng_ipaddr_tostr(&My_Connections[Idx].addr));
1551                 Conn_Close(Idx,
1552                            "Socket closed!", "Client closed connection",
1553                            false);
1554                 return;
1555         }
1556
1557         if (len < 0) {
1558                 if( errno == EAGAIN ) return;
1559                 Log(LOG_ERR, "Read error on connection %d (socket %d): %s!",
1560                     Idx, My_Connections[Idx].sock, strerror(errno));
1561                 Conn_Close(Idx, "Read error!", "Client closed connection",
1562                            false);
1563                 return;
1564         }
1565 #ifdef ZLIB
1566         if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1567                 if (!array_catb(&My_Connections[Idx].zip.rbuf, readbuf,
1568                                 (size_t) len)) {
1569                         Log(LOG_ERR,
1570                             "Could not append recieved data to zip input buffer (connn %d): %d bytes!",
1571                             Idx, len);
1572                         Conn_Close(Idx, "Receive buffer space exhausted", NULL,
1573                                    false);
1574                         return;
1575                 }
1576         } else
1577 #endif
1578         {
1579                 if (!array_catb( &My_Connections[Idx].rbuf, readbuf, len)) {
1580                         Log( LOG_ERR, "Could not append recieved data to input buffer (connn %d): %d bytes!", Idx, len );
1581                         Conn_Close(Idx, "Receive buffer space exhausted", NULL, false );
1582                 }
1583         }
1584
1585         /* Update connection statistics */
1586         My_Connections[Idx].bytes_in += len;
1587         My_Connections[Idx].bps += Handle_Buffer(Idx);
1588
1589         /* Make sure that there is still a valid client registered */
1590         c = Conn_GetClient(Idx);
1591         if (!c)
1592                 return;
1593
1594         /* Update timestamp of last data received if this connection is
1595          * registered as a user, server or service connection. Don't update
1596          * otherwise, so users have at least Conf_PongTimeout seconds time to
1597          * register with the IRC server -- see Check_Connections().
1598          * Update "lastping", too, if time shifted backwards ... */
1599         if (Client_Type(c) == CLIENT_USER
1600             || Client_Type(c) == CLIENT_SERVER
1601             || Client_Type(c) == CLIENT_SERVICE) {
1602                 t = time(NULL);
1603                 if (My_Connections[Idx].lastdata != t)
1604                         My_Connections[Idx].bps = 0;
1605
1606                 My_Connections[Idx].lastdata = t;
1607                 if (My_Connections[Idx].lastping > t)
1608                         My_Connections[Idx].lastping = t;
1609         }
1610
1611         /* Look at the data in the (read-) buffer of this connection */
1612         if (Client_Type(c) != CLIENT_SERVER
1613             && Client_Type(c) != CLIENT_UNKNOWNSERVER
1614             && Client_Type(c) != CLIENT_SERVICE
1615             && My_Connections[Idx].bps >= maxbps) {
1616                 LogDebug("Throttling connection %d: BPS exceeded! (%u >= %u)",
1617                          Idx, My_Connections[Idx].bps, maxbps);
1618                 Conn_SetPenalty(Idx, 1);
1619         }
1620 } /* Read_Request */
1621
1622
1623 /**
1624  * Handle all data in the connection read-buffer.
1625  *
1626  * Data is processed until no complete command is left in the read buffer,
1627  * or MAX_COMMANDS[_SERVER|_SERVICE] commands were processed.
1628  * When a fatal error occurs, the connection is shut down.
1629  *
1630  * @param Idx   Index of the connection.
1631  * @returns     Number of bytes processed.
1632  */
1633 static unsigned int
1634 Handle_Buffer(CONN_ID Idx)
1635 {
1636 #ifndef STRICT_RFC
1637         char *ptr1, *ptr2, *first_eol;
1638 #endif
1639         char *ptr;
1640         size_t len, delta;
1641         time_t starttime;
1642 #ifdef ZLIB
1643         bool old_z;
1644 #endif
1645         unsigned int i, maxcmd = MAX_COMMANDS, len_processed = 0;
1646         CLIENT *c;
1647
1648         c = Conn_GetClient(Idx);
1649         starttime = time(NULL);
1650
1651         assert(c != NULL);
1652
1653         /* Servers do get special command limits, so they can process
1654          * all the messages that are required while peering. */
1655         switch (Client_Type(c)) {
1656             case CLIENT_SERVER:
1657                 /* Allow servers to send more commands in the first 10 secods
1658                  * to speed up server login and network synchronisation. */
1659                 if (starttime - Client_StartTime(c) < 10)
1660                         maxcmd = MAX_COMMANDS_SERVER * 5;
1661                 else
1662                         maxcmd = MAX_COMMANDS_SERVER;
1663                 break;
1664             case CLIENT_SERVICE:
1665                 maxcmd = MAX_COMMANDS_SERVICE; break;
1666         }
1667
1668         for (i=0; i < maxcmd; i++) {
1669                 /* Check penalty */
1670                 if (My_Connections[Idx].delaytime > starttime)
1671                         return 0;
1672 #ifdef ZLIB
1673                 /* Unpack compressed data, if compression is in use */
1674                 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1675                         /* When unzipping fails, Unzip_Buffer() shuts
1676                          * down the connection itself */
1677                         if (!Unzip_Buffer(Idx))
1678                                 return 0;
1679                 }
1680 #endif
1681
1682                 if (0 == array_bytes(&My_Connections[Idx].rbuf))
1683                         break;
1684
1685                 /* Make sure that the buffer is NULL terminated */
1686                 if (!array_cat0_temporary(&My_Connections[Idx].rbuf)) {
1687                         Conn_Close(Idx, NULL,
1688                                    "Can't allocate memory [Handle_Buffer]",
1689                                    true);
1690                         return 0;
1691                 }
1692
1693                 /* RFC 2812, section "2.3 Messages", 5th paragraph:
1694                  * "IRC messages are always lines of characters terminated
1695                  * with a CR-LF (Carriage Return - Line Feed) pair [...]". */
1696                 delta = 2;
1697                 ptr = strstr(array_start(&My_Connections[Idx].rbuf), "\r\n");
1698
1699 #ifndef STRICT_RFC
1700                 /* Check for non-RFC-compliant request (only CR or LF)?
1701                  * Unfortunately, there are quite a few clients out there
1702                  * that do this -- e. g. mIRC, BitchX, and Trillian :-( */
1703                 ptr1 = strchr(array_start(&My_Connections[Idx].rbuf), '\r');
1704                 ptr2 = strchr(array_start(&My_Connections[Idx].rbuf), '\n');
1705                 if (ptr) {
1706                         /* Check if there is a single CR or LF _before_ the
1707                          * corerct CR+LF line terminator:  */
1708                         first_eol = ptr1 < ptr2 ? ptr1 : ptr2;
1709                         if (first_eol < ptr) {
1710                                 /* Single CR or LF before CR+LF found */
1711                                 ptr = first_eol;
1712                                 delta = 1;
1713                         }
1714                 } else if (ptr1 || ptr2) {
1715                         /* No CR+LF terminated command found, but single
1716                          * CR or LF found ... */
1717                         if (ptr1 && ptr2)
1718                                 ptr = ptr1 < ptr2 ? ptr1 : ptr2;
1719                         else
1720                                 ptr = ptr1 ? ptr1 : ptr2;
1721                         delta = 1;
1722                 }
1723 #endif
1724
1725                 if (!ptr)
1726                         break;
1727
1728                 /* Complete (=line terminated) request found, handle it! */
1729                 *ptr = '\0';
1730
1731                 len = ptr - (char *)array_start(&My_Connections[Idx].rbuf) + delta;
1732
1733                 if (len > (COMMAND_LEN - 1)) {
1734                         /* Request must not exceed 512 chars (incl. CR+LF!),
1735                          * see RFC 2812. Disconnect Client if this happens. */
1736                         Log(LOG_ERR,
1737                             "Request too long (connection %d): %d bytes (max. %d expected)!",
1738                             Idx, array_bytes(&My_Connections[Idx].rbuf),
1739                             COMMAND_LEN - 1);
1740                         Conn_Close(Idx, NULL, "Request too long", true);
1741                         return 0;
1742                 }
1743
1744                 len_processed += (unsigned int)len;
1745                 if (len <= delta) {
1746                         /* Request is empty (only '\r\n', '\r' or '\n');
1747                          * delta is 2 ('\r\n') or 1 ('\r' or '\n'), see above */
1748                         array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1749                         continue;
1750                 }
1751 #ifdef ZLIB
1752                 /* remember if stream is already compressed */
1753                 old_z = My_Connections[Idx].options & CONN_ZIP;
1754 #endif
1755
1756                 My_Connections[Idx].msg_in++;
1757                 if (!Parse_Request
1758                     (Idx, (char *)array_start(&My_Connections[Idx].rbuf)))
1759                         return 0; /* error -> connection has been closed */
1760
1761                 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1762 #ifdef DEBUG_BUFFER
1763                 LogDebug("Connection %d: %d bytes left in read buffer.",
1764                          Idx, array_bytes(&My_Connections[Idx].rbuf));
1765 #endif
1766 #ifdef ZLIB
1767                 if ((!old_z) && (My_Connections[Idx].options & CONN_ZIP) &&
1768                     (array_bytes(&My_Connections[Idx].rbuf) > 0)) {
1769                         /* The last command activated socket compression.
1770                          * Data that was read after that needs to be copied
1771                          * to the unzip buffer for decompression: */
1772                         if (!array_copy
1773                             (&My_Connections[Idx].zip.rbuf,
1774                              &My_Connections[Idx].rbuf)) {
1775                                 Conn_Close(Idx, NULL,
1776                                            "Can't allocate memory [Handle_Buffer]",
1777                                            true);
1778                                 return 0;
1779                         }
1780
1781                         array_trunc(&My_Connections[Idx].rbuf);
1782                         LogDebug
1783                             ("Moved already received data (%u bytes) to uncompression buffer.",
1784                              array_bytes(&My_Connections[Idx].zip.rbuf));
1785                 }
1786 #endif
1787         }
1788         return len_processed;
1789 } /* Handle_Buffer */
1790
1791
1792 /**
1793  * Check whether established connections are still alive or not.
1794  * If not, play PING-PONG first; and if that doesn't help either,
1795  * disconnect the respective peer.
1796  */
1797 static void
1798 Check_Connections(void)
1799 {
1800         CLIENT *c;
1801         CONN_ID i;
1802         char msg[64];
1803
1804         for (i = 0; i < Pool_Size; i++) {
1805                 if (My_Connections[i].sock < 0)
1806                         continue;
1807
1808                 c = Conn_GetClient(i);
1809                 if (c && ((Client_Type(c) == CLIENT_USER)
1810                           || (Client_Type(c) == CLIENT_SERVER)
1811                           || (Client_Type(c) == CLIENT_SERVICE))) {
1812                         /* connected User, Server or Service */
1813                         if (My_Connections[i].lastping >
1814                             My_Connections[i].lastdata) {
1815                                 /* We already sent a ping */
1816                                 if (My_Connections[i].lastping <
1817                                     time(NULL) - Conf_PongTimeout) {
1818                                         /* Timeout */
1819                                         LogDebug
1820                                             ("Connection %d: Ping timeout: %d seconds.",
1821                                              i, Conf_PongTimeout);
1822                                         snprintf(msg, sizeof(msg), "Ping timeout: %d seconds", Conf_PongTimeout);
1823                                         Conn_Close(i, NULL, msg, true);
1824                                 }
1825                         } else if (My_Connections[i].lastdata <
1826                                    time(NULL) - Conf_PingTimeout) {
1827                                 /* We need to send a PING ... */
1828                                 LogDebug("Connection %d: sending PING ...", i);
1829                                 My_Connections[i].lastping = time(NULL);
1830                                 Conn_WriteStr(i, "PING :%s",
1831                                               Client_ID(Client_ThisServer()));
1832                         }
1833                 } else {
1834                         /* The connection is not fully established yet, so
1835                          * we don't do the PING-PONG game here but instead
1836                          * disconnect the client after "a short time" if it's
1837                          * still not registered. */
1838
1839                         if (My_Connections[i].lastdata <
1840                             time(NULL) - Conf_PongTimeout) {
1841                                 LogDebug
1842                                     ("Unregistered connection %d timed out ...",
1843                                      i);
1844                                 Conn_Close(i, NULL, "Timeout", false);
1845                         }
1846                 }
1847         }
1848 } /* Check_Connections */
1849
1850
1851 /**
1852  * Check if further server links should be established.
1853  */
1854 static void
1855 Check_Servers(void)
1856 {
1857         int i, n;
1858         time_t time_now;
1859
1860         time_now = time(NULL);
1861
1862         /* Check all configured servers */
1863         for (i = 0; i < MAX_SERVERS; i++) {
1864                 if (Conf_Server[i].conn_id != NONE)
1865                         continue;       /* Already establishing or connected */
1866                 if (!Conf_Server[i].host[0] || !Conf_Server[i].port > 0)
1867                         continue;       /* No host and/or port configured */
1868                 if (Conf_Server[i].flags & CONF_SFLAG_DISABLED)
1869                         continue;       /* Disabled configuration entry */
1870                 if (Conf_Server[i].lasttry > (time_now - Conf_ConnectRetry))
1871                         continue;       /* We have to wait a little bit ... */
1872
1873                 /* Is there already a connection in this group? */
1874                 if (Conf_Server[i].group > NONE) {
1875                         for (n = 0; n < MAX_SERVERS; n++) {
1876                                 if (n == i)
1877                                         continue;
1878                                 if ((Conf_Server[n].conn_id != NONE) &&
1879                                     (Conf_Server[n].group == Conf_Server[i].group))
1880                                         break;
1881                         }
1882                         if (n < MAX_SERVERS)
1883                                 continue;
1884                 }
1885
1886                 /* Okay, try to connect now */
1887                 Log(LOG_NOTICE,
1888                     "Preparing to establish a new server link for \"%s\" ...",
1889                     Conf_Server[i].name);
1890                 Conf_Server[i].lasttry = time_now;
1891                 Conf_Server[i].conn_id = SERVER_WAIT;
1892                 assert(Proc_GetPipeFd(&Conf_Server[i].res_stat) < 0);
1893                 Resolve_Name(&Conf_Server[i].res_stat, Conf_Server[i].host,
1894                              cb_Connect_to_Server);
1895         }
1896 } /* Check_Servers */
1897
1898
1899 /**
1900  * Establish a new outgoing server connection.
1901  *
1902  * @param Server        Configuration index of the server.
1903  * @param dest          Destination IP address to connect to.
1904  */
1905 static void
1906 New_Server( int Server , ng_ipaddr_t *dest)
1907 {
1908         /* Establish new server link */
1909         char ip_str[NG_INET_ADDRSTRLEN];
1910         int af_dest, res, new_sock;
1911         CLIENT *c;
1912
1913         assert( Server > NONE );
1914
1915         if (!ng_ipaddr_tostr_r(dest, ip_str)) {
1916                 Log(LOG_WARNING, "New_Server: Could not convert IP to string");
1917                 return;
1918         }
1919
1920         af_dest = ng_ipaddr_af(dest);
1921         new_sock = socket(af_dest, SOCK_STREAM, 0);
1922
1923         Log(LOG_INFO,
1924             "Establishing connection for \"%s\" to \"%s:%d\" (%s), socket %d ...",
1925             Conf_Server[Server].name, Conf_Server[Server].host,
1926             Conf_Server[Server].port, ip_str, new_sock);
1927
1928         if (new_sock < 0) {
1929                 Log(LOG_CRIT, "Can't create socket (af %d): %s!",
1930                     af_dest, strerror(errno));
1931                 return;
1932         }
1933
1934         if (!Init_Socket(new_sock))
1935                 return;
1936
1937         /* is a bind address configured? */
1938         res = ng_ipaddr_af(&Conf_Server[Server].bind_addr);
1939         /* if yes, bind now. If it fails, warn and let connect() pick a source address */
1940         if (res && bind(new_sock, (struct sockaddr *) &Conf_Server[Server].bind_addr,
1941                                 ng_ipaddr_salen(&Conf_Server[Server].bind_addr)))
1942         {
1943                 ng_ipaddr_tostr_r(&Conf_Server[Server].bind_addr, ip_str);
1944                 Log(LOG_WARNING, "Can't bind socket to %s: %s!", ip_str, strerror(errno));
1945         }
1946         ng_ipaddr_setport(dest, Conf_Server[Server].port);
1947         res = connect(new_sock, (struct sockaddr *) dest, ng_ipaddr_salen(dest));
1948         if(( res != 0 ) && ( errno != EINPROGRESS )) {
1949                 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1950                 close( new_sock );
1951                 return;
1952         }
1953
1954         if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)new_sock)) {
1955                 Log(LOG_ALERT,
1956                     "Cannot allocate memory for server connection (socket %d)",
1957                     new_sock);
1958                 close( new_sock );
1959                 return;
1960         }
1961
1962         if (!io_event_create( new_sock, IO_WANTWRITE, cb_connserver)) {
1963                 Log(LOG_ALERT, "io_event_create(): could not add fd %d", strerror(errno));
1964                 close(new_sock);
1965                 return;
1966         }
1967
1968         My_Connections = array_start(&My_ConnArray);
1969
1970         assert(My_Connections[new_sock].sock <= 0);
1971
1972         Init_Conn_Struct(new_sock);
1973
1974         ng_ipaddr_tostr_r(dest, ip_str);
1975         c = Client_NewLocal(new_sock, ip_str, CLIENT_UNKNOWNSERVER, false);
1976         if (!c) {
1977                 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1978                 io_close(new_sock);
1979                 return;
1980         }
1981
1982         /* Conn_Close() decrements this counter again */
1983         Account_Connection();
1984         Client_SetIntroducer( c, c );
1985         Client_SetToken( c, TOKEN_OUTBOUND );
1986
1987         /* Register connection */
1988         Conf_Server[Server].conn_id = new_sock;
1989         My_Connections[new_sock].sock = new_sock;
1990         My_Connections[new_sock].addr = *dest;
1991         My_Connections[new_sock].client = c;
1992         strlcpy( My_Connections[new_sock].host, Conf_Server[Server].host,
1993                                 sizeof(My_Connections[new_sock].host ));
1994
1995 #ifdef SSL_SUPPORT
1996         if (Conf_Server[Server].SSLConnect && !ConnSSL_PrepareConnect( &My_Connections[new_sock],
1997                                                                 &Conf_Server[Server] ))
1998         {
1999                 Log(LOG_ALERT, "Could not initialize SSL for outgoing connection");
2000                 Conn_Close( new_sock, "Could not initialize SSL for outgoing connection", NULL, false );
2001                 Init_Conn_Struct( new_sock );
2002                 Conf_Server[Server].conn_id = NONE;
2003                 return;
2004         }
2005 #endif
2006         LogDebug("Registered new connection %d on socket %d (%ld in total).",
2007                  new_sock, My_Connections[new_sock].sock, NumConnections);
2008         Conn_OPTION_ADD( &My_Connections[new_sock], CONN_ISCONNECTING );
2009 } /* New_Server */
2010
2011
2012 /**
2013  * Initialize connection structure.
2014  *
2015  * @param Idx   Connection index.
2016  */
2017 static void
2018 Init_Conn_Struct(CONN_ID Idx)
2019 {
2020         time_t now = time(NULL);
2021
2022         memset(&My_Connections[Idx], 0, sizeof(CONNECTION));
2023         My_Connections[Idx].sock = -1;
2024         My_Connections[Idx].signon = now;
2025         My_Connections[Idx].lastdata = now;
2026         My_Connections[Idx].lastprivmsg = now;
2027         Proc_InitStruct(&My_Connections[Idx].proc_stat);
2028 } /* Init_Conn_Struct */
2029
2030
2031 /**
2032  * Initialize options of a new socket.
2033  *
2034  * For example, we try to set socket options SO_REUSEADDR and IPTOS_LOWDELAY.
2035  * The socket is automatically closed if a fatal error is encountered.
2036  *
2037  * @param Sock  Socket handle.
2038  * @returns false if socket was closed due to fatal error.
2039  */
2040 static bool
2041 Init_Socket( int Sock )
2042 {
2043         int value;
2044
2045         if (!io_setnonblock(Sock)) {
2046                 Log( LOG_CRIT, "Can't enable non-blocking mode for socket: %s!", strerror( errno ));
2047                 close( Sock );
2048                 return false;
2049         }
2050
2051         /* Don't block this port after socket shutdown */
2052         value = 1;
2053         if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &value, (socklen_t)sizeof( value )) != 0 )
2054         {
2055                 Log( LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!", strerror( errno ));
2056                 /* ignore this error */
2057         }
2058
2059         /* Set type of service (TOS) */
2060 #if defined(IPPROTO_IP) && defined(IPTOS_LOWDELAY)
2061         value = IPTOS_LOWDELAY;
2062         if (setsockopt(Sock, IPPROTO_IP, IP_TOS, &value,
2063                        (socklen_t) sizeof(value))) {
2064                 LogDebug("Can't set socket option IP_TOS: %s!",
2065                          strerror(errno));
2066                 /* ignore this error */
2067         } else
2068                 LogDebug("IP_TOS on socket %d has been set to IPTOS_LOWDELAY.",
2069                          Sock);
2070 #endif
2071
2072         return true;
2073 } /* Init_Socket */
2074
2075
2076 /**
2077  * Read results of a resolver sub-process and try to initiate a new server
2078  * connection.
2079  *
2080  * @param fd            File descriptor of the pipe to the sub-process.
2081  * @param events        (ignored IO specification)
2082  */
2083 static void
2084 cb_Connect_to_Server(int fd, UNUSED short events)
2085 {
2086         /* Read result of resolver sub-process from pipe and start connection */
2087         int i;
2088         size_t len;
2089         ng_ipaddr_t dest_addrs[4];      /* we can handle at most 3; but we read up to
2090                                            four so we can log the 'more than we can handle'
2091                                            condition. First result is tried immediately, rest
2092                                            is saved for later if needed. */
2093
2094         LogDebug("Resolver: Got forward lookup callback on fd %d, events %d", fd, events);
2095
2096         for (i=0; i < MAX_SERVERS; i++) {
2097                   if (Proc_GetPipeFd(&Conf_Server[i].res_stat) == fd )
2098                           break;
2099         }
2100
2101         if( i >= MAX_SERVERS) {
2102                 /* Ops, no matching server found?! */
2103                 io_close( fd );
2104                 LogDebug("Resolver: Got Forward Lookup callback for unknown server!?");
2105                 return;
2106         }
2107
2108         /* Read result from pipe */
2109         len = Proc_Read(&Conf_Server[i].res_stat, dest_addrs, sizeof(dest_addrs));
2110         if (len == 0) {
2111                 /* Error resolving hostname: reset server structure */
2112                 Conf_Server[i].conn_id = NONE;
2113                 return;
2114         }
2115
2116         assert((len % sizeof(ng_ipaddr_t)) == 0);
2117
2118         LogDebug("Got result from resolver: %u structs (%u bytes).", len/sizeof(ng_ipaddr_t), len);
2119
2120         memset(&Conf_Server[i].dst_addr, 0, sizeof(Conf_Server[i].dst_addr));
2121         if (len > sizeof(ng_ipaddr_t)) {
2122                 /* more than one address for this hostname, remember them
2123                  * in case first address is unreachable/not available */
2124                 len -= sizeof(ng_ipaddr_t);
2125                 if (len > sizeof(Conf_Server[i].dst_addr)) {
2126                         len = sizeof(Conf_Server[i].dst_addr);
2127                         Log(LOG_NOTICE,
2128                                 "Notice: Resolver returned more IP Addresses for host than we can handle, additional addresses dropped.");
2129                 }
2130                 memcpy(&Conf_Server[i].dst_addr, &dest_addrs[1], len);
2131         }
2132         /* connect() */
2133         New_Server(i, dest_addrs);
2134 } /* cb_Read_Forward_Lookup */
2135
2136
2137 /**
2138  * Read results of a resolver sub-process from the pipe and update the
2139  * apropriate connection/client structure(s): hostname and/or IDENT user name.
2140  *
2141  * @param r_fd          File descriptor of the pipe to the sub-process.
2142  * @param events        (ignored IO specification)
2143  */
2144 static void
2145 cb_Read_Resolver_Result( int r_fd, UNUSED short events )
2146 {
2147         CLIENT *c;
2148         CONN_ID i;
2149         size_t len;
2150         char *identptr;
2151 #ifdef IDENTAUTH
2152         char readbuf[HOST_LEN + 2 + CLIENT_USER_LEN];
2153 #else
2154         char readbuf[HOST_LEN + 1];
2155 #endif
2156
2157         LogDebug("Resolver: Got callback on fd %d, events %d", r_fd, events );
2158         i = Conn_GetFromProc(r_fd);
2159         if (i == NONE) {
2160                 /* Ops, none found? Probably the connection has already
2161                  * been closed!? We'll ignore that ... */
2162                 io_close( r_fd );
2163                 LogDebug("Resolver: Got callback for unknown connection!?");
2164                 return;
2165         }
2166
2167         /* Read result from pipe */
2168         len = Proc_Read(&My_Connections[i].proc_stat, readbuf, sizeof readbuf -1);
2169         if (len == 0)
2170                 return;
2171
2172         readbuf[len] = '\0';
2173         identptr = strchr(readbuf, '\n');
2174         assert(identptr != NULL);
2175         if (!identptr) {
2176                 Log( LOG_CRIT, "Resolver: Got malformed result!");
2177                 return;
2178         }
2179
2180         *identptr = '\0';
2181         LogDebug("Got result from resolver: \"%s\" (%u bytes read).", readbuf, len);
2182         /* Okay, we got a complete result: this is a host name for outgoing
2183          * connections and a host name and IDENT user name (if enabled) for
2184          * incoming connections.*/
2185         assert ( My_Connections[i].sock >= 0 );
2186         /* Incoming connection. Search client ... */
2187         c = Conn_GetClient( i );
2188         assert( c != NULL );
2189
2190         /* Only update client information of unregistered clients.
2191          * Note: user commands (e. g. WEBIRC) are always read _after_ reading
2192          * the resolver results, so we don't have to worry to override settings
2193          * from these commands here. */
2194         if(Client_Type(c) == CLIENT_UNKNOWN) {
2195                 strlcpy(My_Connections[i].host, readbuf,
2196                         sizeof(My_Connections[i].host));
2197                 Client_SetHostname(c, readbuf);
2198                 if (Conf_NoticeAuth)
2199                         (void)Conn_WriteStr(i,
2200                                         "NOTICE AUTH :*** Found your hostname");
2201 #ifdef IDENTAUTH
2202                 ++identptr;
2203                 if (*identptr) {
2204                         Log(LOG_INFO, "IDENT lookup for connection %d: \"%s\".", i, identptr);
2205                         Client_SetUser(c, identptr, true);
2206                         if (Conf_NoticeAuth)
2207                                 (void)Conn_WriteStr(i,
2208                                         "NOTICE AUTH :*** Got ident response");
2209                 } else {
2210                         Log(LOG_INFO, "IDENT lookup for connection %d: no result.", i);
2211                         if (Conf_NoticeAuth && Conf_Ident)
2212                                 (void)Conn_WriteStr(i,
2213                                         "NOTICE AUTH :*** No ident response");
2214                 }
2215 #endif
2216         }
2217 #ifdef DEBUG
2218                 else Log( LOG_DEBUG, "Resolver: discarding result for already registered connection %d.", i );
2219 #endif
2220 } /* cb_Read_Resolver_Result */
2221
2222
2223 /**
2224  * Write a "simple" (error) message to a socket.
2225  *
2226  * The message is sent without using the connection write buffers, without
2227  * compression/encryption, and even without any error reporting. It is
2228  * designed for error messages of e.g. New_Connection().
2229  *
2230  * @param Sock  Socket handle.
2231  * @param Msg   Message string to send.
2232  */
2233 static void
2234 Simple_Message(int Sock, const char *Msg)
2235 {
2236         char buf[COMMAND_LEN];
2237         size_t len;
2238
2239         assert(Sock > NONE);
2240         assert(Msg != NULL);
2241
2242         strlcpy(buf, Msg, sizeof buf - 2);
2243         len = strlcat(buf, "\r\n", sizeof buf);
2244         if (write(Sock, buf, len) < 0) {
2245                 /* Because this function most probably got called to log
2246                  * an error message, any write error is ignored here to
2247                  * avoid an endless loop. But casting the result of write()
2248                  * to "void" doesn't satisfy the GNU C code attribute
2249                  * "warn_unused_result" which is used by some versions of
2250                  * glibc (e.g. 2.11.1), therefore this silly error
2251                  * "handling" code here :-( */
2252                 return;
2253         }
2254 } /* Simple_Error */
2255
2256
2257 /**
2258  * Get CLIENT structure that belongs to a local connection identified by its
2259  * index number. Each connection belongs to a client by definition, so it is
2260  * not required that the caller checks for NULL return values.
2261  *
2262  * @param Idx   Connection index number.
2263  * @returns     Pointer to CLIENT structure.
2264  */
2265 GLOBAL CLIENT *
2266 Conn_GetClient( CONN_ID Idx ) 
2267 {
2268         CONNECTION *c;
2269
2270         assert(Idx >= 0);
2271         c = array_get(&My_ConnArray, sizeof (CONNECTION), (size_t)Idx);
2272         assert(c != NULL);
2273         return c ? c->client : NULL;
2274 }
2275
2276 /**
2277  * Get PROC_STAT sub-process structure of a connection.
2278  *
2279  * @param Idx   Connection index number.
2280  * @returns     PROC_STAT structure.
2281  */
2282 GLOBAL PROC_STAT *
2283 Conn_GetProcStat(CONN_ID Idx)
2284 {
2285         CONNECTION *c;
2286
2287         assert(Idx >= 0);
2288         c = array_get(&My_ConnArray, sizeof (CONNECTION), (size_t)Idx);
2289         assert(c != NULL);
2290         return &c->proc_stat;
2291 } /* Conn_GetProcStat */
2292
2293
2294 /**
2295  * Get CONN_ID from file descriptor associated to a subprocess structure.
2296  *
2297  * @param fd    File descriptor.
2298  * @returns     CONN_ID or NONE (-1).
2299  */
2300 GLOBAL CONN_ID
2301 Conn_GetFromProc(int fd)
2302 {
2303         int i;
2304
2305         assert(fd > 0);
2306         for (i = 0; i < Pool_Size; i++) {
2307                 if ((My_Connections[i].sock != NONE)
2308                     && (Proc_GetPipeFd(&My_Connections[i].proc_stat) == fd))
2309                         return i;
2310         }
2311         return NONE;
2312 } /* Conn_GetFromProc */
2313
2314
2315 #ifndef STRICT_RFC
2316
2317 GLOBAL long
2318 Conn_GetAuthPing(CONN_ID Idx)
2319 {
2320         assert (Idx != NONE);
2321         return My_Connections[Idx].auth_ping;
2322 } /* Conn_GetAuthPing */
2323
2324 GLOBAL void
2325 Conn_SetAuthPing(CONN_ID Idx, long ID)
2326 {
2327         assert (Idx != NONE);
2328         My_Connections[Idx].auth_ping = ID;
2329 } /* Conn_SetAuthPing */
2330
2331 #endif
2332
2333
2334 #ifdef SSL_SUPPORT
2335
2336 /**
2337  * Get information about used SSL chiper.
2338  *
2339  * @param Idx   Connection index number.
2340  * @param buf   Buffer for returned information text.
2341  * @param len   Size of return buffer "buf".
2342  * @returns     true on success, false otherwise.
2343  */
2344 GLOBAL bool
2345 Conn_GetCipherInfo(CONN_ID Idx, char *buf, size_t len)
2346 {
2347         if (Idx < 0)
2348                 return false;
2349         assert(Idx < (int) array_length(&My_ConnArray, sizeof(CONNECTION)));
2350         return ConnSSL_GetCipherInfo(&My_Connections[Idx], buf, len);
2351 }
2352
2353
2354 /**
2355  * Check if a connection is SSL-enabled or not.
2356  *
2357  * @param Idx   Connection index number.
2358  * @return      true if connection is SSL-enabled, false otherwise.
2359  */
2360 GLOBAL bool
2361 Conn_UsesSSL(CONN_ID Idx)
2362 {
2363         if (Idx < 0)
2364                 return false;
2365         assert(Idx < (int) array_length(&My_ConnArray, sizeof(CONNECTION)));
2366         return Conn_OPTION_ISSET(&My_Connections[Idx], CONN_SSL);
2367 }
2368
2369 #endif
2370
2371
2372 #ifdef DEBUG
2373
2374 /**
2375  * Dump internal state of the "connection module".
2376  */
2377 GLOBAL void
2378 Conn_DebugDump(void)
2379 {
2380         int i;
2381
2382         Log(LOG_DEBUG, "Connection status:");
2383         for (i = 0; i < Pool_Size; i++) {
2384                 if (My_Connections[i].sock == NONE)
2385                         continue;
2386                 Log(LOG_DEBUG,
2387                     " - %d: host=%s, lastdata=%ld, lastping=%ld, delaytime=%ld, flag=%d, options=%d, bps=%d, client=%s",
2388                     My_Connections[i].sock, My_Connections[i].host,
2389                     My_Connections[i].lastdata, My_Connections[i].lastping,
2390                     My_Connections[i].delaytime, My_Connections[i].flag,
2391                     My_Connections[i].options, My_Connections[i].bps,
2392                     My_Connections[i].client ? Client_ID(My_Connections[i].client) : "-");
2393         }
2394 } /* Conn_DumpClients */
2395
2396 #endif
2397
2398
2399 /* -eof- */