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