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