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