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