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