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