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