]> arthur.barton.de Git - ngircd-alex.git/blob - src/ngircd/conn.c
Change formatting of some log messages
[ngircd-alex.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         /* Modul initialisieren: statische Strukturen "ausnullen". */
308
309         CONN_ID i;
310
311         /* Speicher fuer Verbindungs-Pool anfordern */
312         Pool_Size = CONNECTION_POOL;
313         if ((Conf_MaxConnections > 0) &&
314                 (Pool_Size > Conf_MaxConnections))
315                         Pool_Size = Conf_MaxConnections;
316
317         if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)Pool_Size)) {
318                 Log( LOG_EMERG, "Can't allocate memory! [Conn_Init]" );
319                 exit( 1 );
320         }
321
322         /* FIXME: My_Connetions/Pool_Size is needed by other parts of the
323          * code; remove them! */
324         My_Connections = (CONNECTION*) array_start(&My_ConnArray);
325
326         LogDebug("Allocated connection pool for %d items (%ld bytes).",
327                 array_length(&My_ConnArray, sizeof( CONNECTION )), array_bytes(&My_ConnArray));
328
329         assert( array_length(&My_ConnArray, sizeof( CONNECTION )) >= (size_t) Pool_Size);
330         
331         array_free( &My_Listeners );
332
333         /* Connection-Struktur initialisieren */
334         for( i = 0; i < Pool_Size; i++ ) Init_Conn_Struct( i );
335
336         /* Global write counter */
337         WCounter = 0;
338 } /* Conn_Init */
339
340
341 GLOBAL void
342 Conn_Exit( void )
343 {
344         /* Modul abmelden: alle noch offenen Connections
345          * schliessen und freigeben. */
346
347         CONN_ID idx;
348
349         Conn_ExitListeners();
350
351         LogDebug("Shutting down all connections ..." );
352         for( idx = 0; idx < Pool_Size; idx++ ) {
353                 if( My_Connections[idx].sock > NONE ) {
354                         Conn_Close( idx, NULL, NGIRCd_SignalRestart ?
355                                 "Server going down (restarting)":"Server going down", true );
356                 }
357         }
358
359         array_free(&My_ConnArray);
360         My_Connections = NULL;
361         Pool_Size = 0;
362         io_library_shutdown();
363 } /* Conn_Exit */
364
365
366 static unsigned int
367 ports_initlisteners(array *a, const char *listen_addr, void (*func)(int,short))
368 {
369         unsigned int created = 0;
370         size_t len;
371         int fd;
372         UINT16 *port;
373
374         len = array_length(a, sizeof (UINT16));
375         port = array_start(a);
376         while (len--) {
377                 fd = NewListener(listen_addr, *port);
378                 if (fd < 0) {
379                         port++;
380                         continue;
381                 }
382                 if (!io_event_create( fd, IO_WANTREAD, func )) {
383                         Log( LOG_ERR, "io_event_create(): Could not add listening fd %d (port %u): %s!",
384                                                 fd, (unsigned int) *port, strerror(errno));
385                         close(fd);
386                         port++;
387                         continue;
388                 }
389                 created++;
390                 port++;
391         }
392         return created;
393 }
394
395
396 GLOBAL unsigned int
397 Conn_InitListeners( void )
398 {
399         /* Initialize ports on which the server should accept connections */
400         unsigned int created = 0;
401         char *copy, *listen_addr;
402
403         if (!io_library_init(CONNECTION_POOL)) {
404                 Log(LOG_EMERG, "Cannot initialize IO routines: %s", strerror(errno));
405                 return -1;
406         }
407
408         assert(Conf_ListenAddress);
409
410         /* can't use Conf_ListenAddress directly, see below */
411         copy = strdup(Conf_ListenAddress);
412         if (!copy) {
413                 Log(LOG_CRIT, "Cannot copy %s: %s", Conf_ListenAddress, strerror(errno));
414                 return 0;
415         }
416         listen_addr = strtok(copy, ",");
417
418         while (listen_addr) {
419                 ngt_TrimStr(listen_addr);
420                 if (*listen_addr) {
421                         created += ports_initlisteners(&Conf_ListenPorts, listen_addr, cb_listen);
422 #ifdef SSL_SUPPORT
423                         created += ports_initlisteners(&Conf_SSLOptions.ListenPorts, listen_addr, cb_listen_ssl);
424 #endif
425                 }
426
427                 listen_addr = strtok(NULL, ",");
428         }
429
430         /*
431          * can't free() Conf_ListenAddress here. On /REHASH, if the config file
432          * cannot be re-loaded, we'd end up with a NULL Conf_ListenAddress.
433          * Instead, free() takes place in conf.c, before the config file
434          * is being parsed.
435          */
436         free(copy);
437         return created;
438 } /* Conn_InitListeners */
439
440
441 GLOBAL void
442 Conn_ExitListeners( void )
443 {
444         /* Close down all listening sockets */
445         int *fd;
446         size_t arraylen;
447 #ifdef ZEROCONF
448         Rendezvous_UnregisterListeners( );
449 #endif
450
451         arraylen = array_length(&My_Listeners, sizeof (int));
452         Log(LOG_INFO,
453             "Shutting down all listening sockets (%d total) ...", arraylen);
454         fd = array_start(&My_Listeners);
455         while(arraylen--) {
456                 assert(fd != NULL);
457                 assert(*fd >= 0);
458                 io_close(*fd);
459                 LogDebug("Listening socket %d closed.", *fd );
460                 fd++;
461         }
462         array_free(&My_Listeners);
463 } /* Conn_ExitListeners */
464
465
466 static bool
467 InitSinaddrListenAddr(ng_ipaddr_t *addr, const char *listen_addrstr, UINT16 Port)
468 {
469         bool ret;
470
471         ret = ng_ipaddr_init(addr, listen_addrstr, Port);
472         if (!ret) {
473                 assert(listen_addrstr);
474                 Log(LOG_CRIT, "Can't bind to [%s]:%u: can't convert ip address \"%s\"",
475                                                 listen_addrstr, Port, listen_addrstr);
476         }
477         return ret;
478 }
479
480
481 static void
482 set_v6_only(int af, int sock)
483 {
484 #if defined(IPV6_V6ONLY) && defined(WANT_IPV6)
485         int on = 1;
486
487         if (af != AF_INET6)
488                 return;
489
490         if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)))
491                 Log(LOG_ERR, "Could not set IPV6_V6ONLY: %s", strerror(errno));
492 #else
493         (void)af;
494         (void)sock;
495 #endif
496 }
497
498
499 /* return new listening port file descriptor or -1 on failure */
500 static int
501 NewListener(const char *listen_addr, UINT16 Port)
502 {
503         /* Create new listening socket on specified port */
504         ng_ipaddr_t addr;
505         int sock, af;
506 #ifdef ZEROCONF
507         char name[CLIENT_ID_LEN], *info;
508 #endif
509         if (!InitSinaddrListenAddr(&addr, listen_addr, Port))
510                 return -1;
511
512         af = ng_ipaddr_af(&addr);
513         sock = socket(af, SOCK_STREAM, 0);
514         if( sock < 0 ) {
515                 Log(LOG_CRIT, "Can't create socket (af %d) : %s!", af, strerror(errno));
516                 return -1;
517         }
518
519         set_v6_only(af, sock);
520
521         if (!Init_Socket(sock))
522                 return -1;
523
524         if (bind(sock, (struct sockaddr *)&addr, ng_ipaddr_salen(&addr)) != 0) {
525                 Log(LOG_CRIT, "Can't bind socket to address %s:%d - %s",
526                         ng_ipaddr_tostr(&addr), Port, strerror(errno));
527                 close(sock);
528                 return -1;
529         }
530
531         if( listen( sock, 10 ) != 0 ) {
532                 Log( LOG_CRIT, "Can't listen on socket: %s!", strerror( errno ));
533                 close( sock );
534                 return -1;
535         }
536
537         /* keep fd in list so we can close it when ngircd restarts/shuts down */
538         if (!array_catb( &My_Listeners,(char*) &sock, sizeof(int) )) {
539                 Log( LOG_CRIT, "Can't add socket to My_Listeners array: %s!", strerror( errno ));
540                 close( sock );
541                 return -1;
542         }
543
544         Log(LOG_INFO, "Now listening on [%s]:%d (socket %d).", ng_ipaddr_tostr(&addr), Port, sock);
545
546 #ifdef ZEROCONF
547         /* Get best server description text */
548         if( ! Conf_ServerInfo[0] ) info = Conf_ServerName;
549         else
550         {
551                 /* Use server info string */
552                 info = NULL;
553                 if( Conf_ServerInfo[0] == '[' )
554                 {
555                         /* Cut off leading hostname part in "[]" */
556                         info = strchr( Conf_ServerInfo, ']' );
557                         if( info )
558                         {
559                                 info++;
560                                 while( *info == ' ' ) info++;
561                         }
562                 }
563                 if( ! info ) info = Conf_ServerInfo;
564         }
565
566         /* Add port number to description if non-standard */
567         if (Port != 6667)
568                 snprintf(name, sizeof name, "%s (port %u)", info,
569                          (unsigned int)Port);
570         else
571                 strlcpy(name, info, sizeof name);
572
573         /* Register service */
574         Rendezvous_Register( name, MDNS_TYPE, Port );
575 #endif
576         return sock;
577 } /* NewListener */
578
579 #ifdef SSL_SUPPORT
580 /*
581  * SSL/TLS connections require extra treatment:
582  * When either CONN_SSL_WANT_WRITE or CONN_SSL_WANT_READ is set, we
583  * need to take care of that first, before checking read/write buffers.
584  * For instance, while we might have data in our write buffer, the
585  * TLS/SSL protocol might need to read internal data first for TLS/SSL
586  * writes to succeed.
587  *
588  * If this function returns true, such a condition is met and we have
589  * to reverse the condition (check for read even if we've data to write,
590  * do not check for read but writeability even if write-buffer is empty).
591  */
592 static bool
593 SSL_WantRead(const CONNECTION *c)
594 {
595         if (Conn_OPTION_ISSET(c, CONN_SSL_WANT_READ)) {
596                 io_event_add(c->sock, IO_WANTREAD);
597                 return true;
598         }
599         return false;
600 }
601 static bool
602 SSL_WantWrite(const CONNECTION *c)
603 {
604         if (Conn_OPTION_ISSET(c, CONN_SSL_WANT_WRITE)) {
605                 io_event_add(c->sock, IO_WANTWRITE);
606                 return true;
607         }
608         return false;
609 }
610 #else
611 static inline bool
612 SSL_WantRead(UNUSED const CONNECTION *c) { return false; }
613 static inline bool
614 SSL_WantWrite(UNUSED const CONNECTION *c) { return false; }
615 #endif
616
617
618 /**
619  * "Main Loop": Loop until shutdown or restart is signalled.
620  * This function loops until a shutdown or restart of ngIRCd is signalled and
621  * calls io_dispatch() to check for readable and writable sockets every second.
622  * It checks for status changes on pending connections (e. g. when a hostname
623  * has been resolved), checks for "penalties" and timeouts, and handles the
624  * input buffers.
625  */
626 GLOBAL void
627 Conn_Handler(void)
628 {
629         int i;
630         unsigned int wdatalen;
631         struct timeval tv;
632         time_t t;
633
634         while (!NGIRCd_SignalQuit && !NGIRCd_SignalRestart) {
635                 t = time(NULL);
636
637 #ifdef ZEROCONF
638                 Rendezvous_Handler();
639 #endif
640
641                 /* Should the configuration be reloaded? */
642                 if (NGIRCd_SignalRehash)
643                         NGIRCd_Rehash();
644
645                 /* Check configured servers and established links */
646                 Check_Servers();
647                 Check_Connections();
648
649                 /* Look for non-empty read buffers ... */
650                 for (i = 0; i < Pool_Size; i++) {
651                         if ((My_Connections[i].sock > NONE)
652                             && (array_bytes(&My_Connections[i].rbuf) > 0)
653                             && (My_Connections[i].delaytime < t)) {
654                                 /* ... and try to handle the received data */
655                                 Handle_Buffer(i);
656                         }
657                 }
658
659                 /* Look for non-empty write buffers ... */
660                 for (i = 0; i < Pool_Size; i++) {
661                         if (My_Connections[i].sock <= NONE)
662                                 continue;
663
664                         wdatalen = (unsigned int)array_bytes(&My_Connections[i].wbuf);
665 #ifdef ZLIB
666                         if (wdatalen > 0 ||
667                             array_bytes(&My_Connections[i].zip.wbuf) > 0)
668 #else
669                         if (wdatalen > 0)
670 #endif
671                         {
672                                 if (SSL_WantRead(&My_Connections[i]))
673                                         continue;
674                                 io_event_add(My_Connections[i].sock,
675                                              IO_WANTWRITE);
676                         }
677                 }
678
679                 /* Check from which sockets we possibly could read ... */
680                 for (i = 0; i < Pool_Size; i++) {
681                         if (My_Connections[i].sock <= NONE)
682                                 continue;
683 #ifdef SSL_SUPPORT
684                         if (SSL_WantWrite(&My_Connections[i]))
685                                 continue; /* TLS/SSL layer needs to write data; deal with this first */
686 #endif
687                         if (Resolve_INPROGRESS(&My_Connections[i].res_stat)) {
688                                 /* Wait for completion of resolver sub-process ... */
689                                 io_event_del(My_Connections[i].sock,
690                                              IO_WANTREAD);
691                                 continue;
692                         }
693
694                         if (Conn_OPTION_ISSET(&My_Connections[i], CONN_ISCONNECTING))
695                                 /* Wait for completion of connect() ... */
696                                 continue;
697
698                         if (My_Connections[i].delaytime > t) {
699                                 /* There is a "penalty time" set: ignore socket! */
700                                 io_event_del(My_Connections[i].sock,
701                                              IO_WANTREAD);
702                                 continue;
703                         }
704                         io_event_add(My_Connections[i].sock, IO_WANTREAD);
705                 }
706
707                 /* Set the timeout for reading from the network to 1 second,
708                  * which is the granularity with witch we handle "penalty
709                  * times" for example.
710                  * Note: tv_sec/usec are undefined(!) after io_dispatch()
711                  * returns, so we have to set it beforce each call to it! */
712                 tv.tv_usec = 0;
713                 tv.tv_sec = 1;
714
715                 /* Wait for activity ... */
716                 i = io_dispatch(&tv);
717                 if (i == -1 && errno != EINTR) {
718                         Log(LOG_EMERG, "Conn_Handler(): io_dispatch(): %s!",
719                             strerror(errno));
720                         Log(LOG_ALERT, "%s exiting due to fatal errors!",
721                             PACKAGE_NAME);
722                         exit(1);
723                 }
724         }
725
726         if (NGIRCd_SignalQuit)
727                 Log(LOG_NOTICE | LOG_snotice, "Server going down NOW!");
728         else if (NGIRCd_SignalRestart)
729                 Log(LOG_NOTICE | LOG_snotice, "Server restarting NOW!");
730 } /* Conn_Handler */
731
732
733 /**
734  * Write a text string into the socket of a connection.
735  * This function automatically appends CR+LF to the string and validates that
736  * the result is a valid IRC message (oversized messages are shortened, for
737  * example). Then it calls the Conn_Write() function to do the actual sending.
738  * @param Idx Index fo the connection.
739  * @param Format Format string, see printf().
740  * @return true on success, false otherwise.
741  */
742 #ifdef PROTOTYPES
743 GLOBAL bool
744 Conn_WriteStr( CONN_ID Idx, char *Format, ... )
745 #else
746 GLOBAL bool 
747 Conn_WriteStr( Idx, Format, va_alist )
748 CONN_ID Idx;
749 char *Format;
750 va_dcl
751 #endif
752 {
753         char buffer[COMMAND_LEN];
754         size_t len;
755         bool ok;
756         va_list ap;
757
758         assert( Idx > NONE );
759         assert( Format != NULL );
760
761 #ifdef PROTOTYPES
762         va_start( ap, Format );
763 #else
764         va_start( ap );
765 #endif
766         if (vsnprintf( buffer, COMMAND_LEN - 2, Format, ap ) >= COMMAND_LEN - 2 ) {
767                 /*
768                  * The string that should be written to the socket is longer
769                  * than the allowed size of COMMAND_LEN bytes (including both
770                  * the CR and LF characters). This can be caused by the
771                  * IRC_WriteXXX() functions when the prefix of this server had
772                  * to be added to an already "quite long" command line which
773                  * has been received from a regular IRC client, for example.
774                  * 
775                  * We are not allowed to send such "oversized" messages to
776                  * other servers and clients, see RFC 2812 2.3 and 2813 3.3
777                  * ("these messages SHALL NOT exceed 512 characters in length,
778                  * counting all characters including the trailing CR-LF").
779                  *
780                  * So we have a big problem here: we should send more bytes
781                  * to the network than we are allowed to and we don't know
782                  * the originator (any more). The "old" behaviour of blaming
783                  * the receiver ("next hop") is a bad idea (it could be just
784                  * an other server only routing the message!), so the only
785                  * option left is to shorten the string and to hope that the
786                  * result is still somewhat useful ...
787                  *                                                   -alex-
788                  */
789
790                 strcpy (buffer + sizeof(buffer) - strlen(CUT_TXTSUFFIX) - 2 - 1,
791                         CUT_TXTSUFFIX);
792         }
793
794 #ifdef SNIFFER
795         if (NGIRCd_Sniffer)
796                 Log(LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer);
797 #endif
798
799         len = strlcat( buffer, "\r\n", sizeof( buffer ));
800         ok = Conn_Write(Idx, buffer, len);
801         My_Connections[Idx].msg_out++;
802
803         va_end( ap );
804         return ok;
805 } /* Conn_WriteStr */
806
807
808 /**
809  * Append Data to the outbound write buffer of a connection.
810  * @param Idx Index of the connection.
811  * @param Data pointer to the data.
812  * @param Len length of Data.
813  * @return true on success, false otherwise.
814  */
815 static bool
816 Conn_Write( CONN_ID Idx, char *Data, size_t Len )
817 {
818         CLIENT *c;
819         size_t writebuf_limit = WRITEBUFFER_LEN;
820         assert( Idx > NONE );
821         assert( Data != NULL );
822         assert( Len > 0 );
823
824         c = Conn_GetClient(Idx);
825         assert( c != NULL);
826
827         /* Servers do get special write buffer limits, so they can generate
828          * all the messages that are required while peering. */
829         if (Client_Type(c) == CLIENT_SERVER)
830                 writebuf_limit = WRITEBUFFER_SLINK_LEN;
831
832         /* Is the socket still open? A previous call to Conn_Write()
833          * may have closed the connection due to a fatal error.
834          * In this case it is sufficient to return an error, as well. */
835         if( My_Connections[Idx].sock <= NONE ) {
836                 LogDebug("Skipped write on closed socket (connection %d).", Idx);
837                 return false;
838         }
839
840 #ifdef ZLIB
841         if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
842                 /* Compressed link:
843                  * Zip_Buffer() does all the dirty work for us: it flushes
844                  * the (pre-)compression buffers if required and handles
845                  * all error conditions. */
846                 if (!Zip_Buffer(Idx, Data, Len))
847                         return false;
848         }
849         else
850 #endif
851         {
852                 /* Uncompressed link:
853                  * Check if outbound buffer has enough space for the data. */
854                 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
855                     writebuf_limit) {
856                         /* Buffer is full, flush it. Handle_Write deals with
857                          * low-level errors, if any. */
858                         if (!Handle_Write(Idx))
859                                 return false;
860                 }
861
862                 /* When the write buffer is still too big after flushing it,
863                  * the connection will be killed. */
864                 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
865                     writebuf_limit) {
866                         Log(LOG_NOTICE,
867                             "Write buffer overflow (connection %d, size %lu byte)!",
868                             Idx,
869                             (unsigned long)array_bytes(&My_Connections[Idx].wbuf));
870                         Conn_Close(Idx, "Write buffer overflow!", NULL, false);
871                         return false;
872                 }
873
874                 /* Copy data to write buffer */
875                 if (!array_catb(&My_Connections[Idx].wbuf, Data, Len))
876                         return false;
877
878                 My_Connections[Idx].bytes_out += Len;
879         }
880
881         /* Adjust global write counter */
882         WCounter += Len;
883
884         return true;
885 } /* Conn_Write */
886
887
888 GLOBAL void
889 Conn_Close( CONN_ID Idx, char *LogMsg, char *FwdMsg, bool InformClient )
890 {
891         /* Close connection. Open pipes of asyncronous resolver
892          * sub-processes are closed down. */
893
894         CLIENT *c;
895         char *txt;
896         double in_k, out_k;
897         UINT16 port;
898 #ifdef ZLIB
899         double in_z_k, out_z_k;
900         int in_p, out_p;
901 #endif
902
903         assert( Idx > NONE );
904
905         /* Is this link already shutting down? */
906         if( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ISCLOSING )) {
907                 /* Conn_Close() has been called recursively for this link;
908                  * probabe reason: Handle_Write() failed  -- see below. */
909                 LogDebug("Recursive request to close connection: %d", Idx );
910                 return;
911         }
912
913         assert( My_Connections[Idx].sock > NONE );
914
915         /* Mark link as "closing" */
916         Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCLOSING );
917
918         if (LogMsg)
919                 txt = LogMsg;
920         else
921                 txt = FwdMsg;
922         if (! txt)
923                 txt = "Reason unknown";
924
925         port = ng_ipaddr_getport(&My_Connections[Idx].addr);
926         Log(LOG_INFO, "Shutting down connection %d (%s) with %s:%d ...", Idx,
927             LogMsg ? LogMsg : FwdMsg, My_Connections[Idx].host, port);
928
929         /* Search client, if any */
930         c = Conn_GetClient( Idx );
931
932         /* Should the client be informed? */
933         if (InformClient) {
934 #ifndef STRICT_RFC
935                 /* Send statistics to client if registered as user: */
936                 if ((c != NULL) && (Client_Type(c) == CLIENT_USER)) {
937                         Conn_WriteStr( Idx,
938                          ":%s NOTICE %s :%sConnection statistics: client %.1f kb, server %.1f kb.",
939                          Client_ID(Client_ThisServer()), Client_ID(c),
940                          NOTICE_TXTPREFIX,
941                          (double)My_Connections[Idx].bytes_in / 1024,
942                          (double)My_Connections[Idx].bytes_out / 1024);
943                 }
944 #endif
945                 /* Send ERROR to client (see RFC!) */
946                 if (FwdMsg)
947                         Conn_WriteStr(Idx, "ERROR :%s", FwdMsg);
948                 else
949                         Conn_WriteStr(Idx, "ERROR :Closing connection.");
950         }
951
952         /* Try to write out the write buffer. Note: Handle_Write() eventually
953          * removes the CLIENT structure associated with this connection if an
954          * error occurs! So we have to re-check if there is still an valid
955          * CLIENT structure after calling Handle_Write() ...*/
956         (void)Handle_Write( Idx );
957
958         /* Search client, if any (re-check!) */
959         c = Conn_GetClient( Idx );
960 #ifdef SSL_SUPPORT
961         if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_SSL )) {
962                 Log(LOG_INFO, "SSL connection %d shutting down ...", Idx);
963                 ConnSSL_Free(&My_Connections[Idx]);
964         }
965 #endif
966         /* Shut down socket */
967         if (! io_close(My_Connections[Idx].sock)) {
968                 /* Oops, we can't close the socket!? This is ... ugly! */
969                 Log(LOG_CRIT,
970                     "Error closing connection %d (socket %d) with %s:%d - %s! (ignored)",
971                     Idx, My_Connections[Idx].sock, My_Connections[Idx].host,
972                     port, strerror(errno));
973         }
974
975         /* Mark socket as invalid: */
976         My_Connections[Idx].sock = NONE;
977
978         /* If there is still a client, unregister it now */
979         if (c)
980                 Client_Destroy(c, LogMsg, FwdMsg, true);
981
982         /* Calculate statistics and log information */
983         in_k = (double)My_Connections[Idx].bytes_in / 1024;
984         out_k = (double)My_Connections[Idx].bytes_out / 1024;
985 #ifdef ZLIB
986         if (Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP)) {
987                 in_z_k = (double)My_Connections[Idx].zip.bytes_in / 1024;
988                 out_z_k = (double)My_Connections[Idx].zip.bytes_out / 1024;
989                 /* Make sure that no division by zero can occur during
990                  * the calculation of in_p and out_p: in_z_k and out_z_k
991                  * are non-zero, that's guaranteed by the protocol until
992                  * compression can be enabled. */
993                 if (! in_z_k)
994                         in_z_k = in_k;
995                 if (! out_z_k)
996                         out_z_k = out_k;
997                 in_p = (int)(( in_k * 100 ) / in_z_k );
998                 out_p = (int)(( out_k * 100 ) / out_z_k );
999                 Log(LOG_INFO,
1000                     "Connection %d with %s:%d closed (in: %.1fk/%.1fk/%d%%, out: %.1fk/%.1fk/%d%%).",
1001                     Idx, My_Connections[Idx].host, port,
1002                     in_k, in_z_k, in_p, out_k, out_z_k, out_p);
1003         }
1004         else
1005 #endif
1006         {
1007                 Log(LOG_INFO,
1008                     "Connection %d with %s:%d closed (in: %.1fk, out: %.1fk).",
1009                     Idx, My_Connections[Idx].host, port,
1010                     in_k, out_k);
1011         }
1012
1013         /* cancel running resolver */
1014         if (Resolve_INPROGRESS(&My_Connections[Idx].res_stat))
1015                 Resolve_Shutdown(&My_Connections[Idx].res_stat);
1016
1017         /* Servers: Modify time of next connect attempt? */
1018         Conf_UnsetServer( Idx );
1019
1020 #ifdef ZLIB
1021         /* Clean up zlib, if link was compressed */
1022         if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
1023                 inflateEnd( &My_Connections[Idx].zip.in );
1024                 deflateEnd( &My_Connections[Idx].zip.out );
1025                 array_free(&My_Connections[Idx].zip.rbuf);
1026                 array_free(&My_Connections[Idx].zip.wbuf);
1027         }
1028 #endif
1029
1030         array_free(&My_Connections[Idx].rbuf);
1031         array_free(&My_Connections[Idx].wbuf);
1032
1033         /* Clean up connection structure (=free it) */
1034         Init_Conn_Struct( Idx );
1035
1036         assert(NumConnections > 0);
1037         if (NumConnections)
1038                 NumConnections--;
1039         LogDebug("Shutdown of connection %d completed, %ld connection%s left.",
1040                  Idx, NumConnections, NumConnections != 1 ? "s" : "");
1041 } /* Conn_Close */
1042
1043
1044 GLOBAL void
1045 Conn_SyncServerStruct( void )
1046 {
1047         /* Synchronize server structures (connection IDs):
1048          * connections <-> configuration */
1049
1050         CLIENT *client;
1051         CONN_ID i;
1052         int c;
1053
1054         for( i = 0; i < Pool_Size; i++ ) {
1055                 /* Established connection? */
1056                 if (My_Connections[i].sock < 0)
1057                         continue;
1058
1059                 /* Server connection? */
1060                 client = Conn_GetClient( i );
1061                 if(( ! client ) || ( Client_Type( client ) != CLIENT_SERVER )) continue;
1062
1063                 for( c = 0; c < MAX_SERVERS; c++ )
1064                 {
1065                         /* Configured server? */
1066                         if( ! Conf_Server[c].host[0] ) continue;
1067
1068                         /* Duplicate? */
1069                         if( strcmp( Conf_Server[c].name, Client_ID( client )) == 0 )
1070                                 Conf_Server[c].conn_id = i;
1071                 }
1072         }
1073 } /* SyncServerStruct */
1074
1075
1076 /**
1077  * Send out data of write buffer; connect new sockets.
1078  */
1079 static bool
1080 Handle_Write( CONN_ID Idx )
1081 {
1082         ssize_t len;
1083         size_t wdatalen;
1084
1085         assert( Idx > NONE );
1086         if ( My_Connections[Idx].sock < 0 ) {
1087                 LogDebug("Handle_Write() on closed socket, connection %d", Idx);
1088                 return false;
1089         }
1090         assert( My_Connections[Idx].sock > NONE );
1091
1092         wdatalen = array_bytes(&My_Connections[Idx].wbuf );
1093
1094 #ifdef ZLIB
1095         if (wdatalen == 0) {
1096                 /* Write buffer is empty, so we try to flush the compression
1097                  * buffer and get some data to work with from there :-) */
1098                 if (!Zip_Flush(Idx))
1099                         return false;
1100
1101                 /* Now the write buffer most probably has changed: */
1102                 wdatalen = array_bytes(&My_Connections[Idx].wbuf);
1103         }
1104 #endif
1105
1106         if (wdatalen == 0) {
1107                 /* Still no data, fine. */
1108                 io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
1109                 return true;
1110         }
1111
1112         LogDebug
1113             ("Handle_Write() called for connection %d, %ld bytes pending ...",
1114              Idx, wdatalen);
1115
1116 #ifdef SSL_SUPPORT
1117         if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_SSL )) {
1118                 len = ConnSSL_Write(&My_Connections[Idx], array_start(&My_Connections[Idx].wbuf), wdatalen);
1119         } else
1120 #endif
1121         {
1122                 len = write(My_Connections[Idx].sock,
1123                             array_start(&My_Connections[Idx].wbuf), wdatalen );
1124         }
1125         if( len < 0 ) {
1126                 if (errno == EAGAIN || errno == EINTR)
1127                         return true;
1128
1129                 Log(LOG_ERR, "Write error on connection %d (socket %d): %s!",
1130                     Idx, My_Connections[Idx].sock, strerror(errno));
1131                 Conn_Close(Idx, "Write error!", NULL, false);
1132                 return false;
1133         }
1134
1135         /* move any data not yet written to beginning */
1136         array_moveleft(&My_Connections[Idx].wbuf, 1, (size_t)len);
1137
1138         return true;
1139 } /* Handle_Write */
1140
1141
1142 static int
1143 Count_Connections(ng_ipaddr_t *a)
1144 {
1145         int i, cnt;
1146
1147         cnt = 0;
1148         for (i = 0; i < Pool_Size; i++) {
1149                 if (My_Connections[i].sock <= NONE)
1150                         continue;
1151                 if (ng_ipaddr_ipequal(&My_Connections[i].addr, a))
1152                         cnt++;
1153         }
1154         return cnt;
1155 } /* Count_Connections */
1156
1157
1158 static int
1159 New_Connection( int Sock )
1160 {
1161         /* Neue Client-Verbindung von Listen-Socket annehmen und
1162          * CLIENT-Struktur anlegen. */
1163
1164 #ifdef TCPWRAP
1165         struct request_info req;
1166 #endif
1167         ng_ipaddr_t new_addr;
1168         char ip_str[NG_INET_ADDRSTRLEN];
1169         int new_sock, new_sock_len, identsock;
1170         CLIENT *c;
1171         long cnt;
1172
1173         assert( Sock > NONE );
1174         /* Connection auf Listen-Socket annehmen */
1175         new_sock_len = (int)sizeof(new_addr);
1176
1177         new_sock = accept(Sock, (struct sockaddr *)&new_addr,
1178                           (socklen_t *)&new_sock_len);
1179         if (new_sock < 0) {
1180                 Log(LOG_CRIT, "Can't accept connection: %s!", strerror(errno));
1181                 return -1;
1182         }
1183
1184         if (!ng_ipaddr_tostr_r(&new_addr, ip_str)) {
1185                 Log(LOG_CRIT, "fd %d: Can't convert IP address!", new_sock);
1186                 Simple_Message(new_sock, "ERROR :Internal Server Error");
1187                 close(new_sock);
1188                 return -1;
1189         }
1190
1191 #ifdef TCPWRAP
1192         /* Validate socket using TCP Wrappers */
1193         request_init( &req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock, RQ_CLIENT_SIN, &new_addr, NULL );
1194         fromhost(&req);
1195         if (!hosts_access(&req)) {
1196                 Log (deny_severity, "Refused connection from %s (by TCP Wrappers)!", ip_str);
1197                 Simple_Message( new_sock, "ERROR :Connection refused" );
1198                 close( new_sock );
1199                 return -1;
1200         }
1201 #endif
1202
1203         /* Socket initialisieren */
1204         if (!Init_Socket( new_sock ))
1205                 return -1;
1206
1207         /* Check IP-based connection limit */
1208         cnt = Count_Connections(&new_addr);
1209         if ((Conf_MaxConnectionsIP > 0) && (cnt >= Conf_MaxConnectionsIP)) {
1210                 /* Access denied, too many connections from this IP address! */
1211                 Log( LOG_ERR, "Refused connection from %s: too may connections (%ld) from this IP address!", ip_str, cnt);
1212                 Simple_Message( new_sock, "ERROR :Connection refused, too many connections from your IP address!" );
1213                 close( new_sock );
1214                 return -1;
1215         }
1216
1217         if ((Conf_MaxConnections > 0) &&
1218                 (NumConnections >= (size_t) Conf_MaxConnections))
1219         {
1220                 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached!", Conf_MaxConnections);
1221                 Simple_Message( new_sock, "ERROR :Connection limit reached" );
1222                 close( new_sock );
1223                 return -1;
1224         }
1225
1226         if( new_sock >= Pool_Size ) {
1227                 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION),
1228                                  (size_t)new_sock)) {
1229                         Log( LOG_EMERG, "Can't allocate memory! [New_Connection]" );
1230                         Simple_Message( new_sock, "ERROR: Internal error" );
1231                         close( new_sock );
1232                         return -1;
1233                 }
1234                 LogDebug("Bumped connection pool to %ld items (internal: %ld items, %ld bytes)",
1235                         new_sock, array_length(&My_ConnArray, sizeof(CONNECTION)), array_bytes(&My_ConnArray));
1236
1237                 /* Adjust pointer to new block */
1238                 My_Connections = array_start(&My_ConnArray);
1239                 while (Pool_Size <= new_sock)
1240                         Init_Conn_Struct(Pool_Size++);
1241         }
1242
1243         /* register callback */
1244         if (!io_event_create( new_sock, IO_WANTREAD, cb_clientserver)) {
1245                 Log(LOG_ALERT, "Can't accept connection: io_event_create failed!");
1246                 Simple_Message(new_sock, "ERROR :Internal error");
1247                 close(new_sock);
1248                 return -1;
1249         }
1250
1251         c = Client_NewLocal(new_sock, ip_str, CLIENT_UNKNOWN, false );
1252         if( ! c ) {
1253                 Log(LOG_ALERT, "Can't accept connection: can't create client structure!");
1254                 Simple_Message(new_sock, "ERROR :Internal error");
1255                 io_close(new_sock);
1256                 return -1;
1257         }
1258
1259         Init_Conn_Struct( new_sock );
1260         My_Connections[new_sock].sock = new_sock;
1261         My_Connections[new_sock].addr = new_addr;
1262         My_Connections[new_sock].client = c;
1263
1264         Log( LOG_INFO, "Accepted connection %d from %s:%d on socket %d.", new_sock,
1265                         ip_str, ng_ipaddr_getport(&new_addr), Sock);
1266
1267         /* Hostnamen ermitteln */
1268         strlcpy(My_Connections[new_sock].host, ip_str, sizeof(My_Connections[new_sock].host));
1269
1270         Client_SetHostname(c, My_Connections[new_sock].host);
1271
1272         identsock = new_sock;
1273 #ifdef IDENTAUTH
1274         if (Conf_NoIdent)
1275                 identsock = -1;
1276 #endif
1277         if (!Conf_NoDNS)
1278                 Resolve_Addr(&My_Connections[new_sock].res_stat, &new_addr,
1279                              identsock, cb_Read_Resolver_Result);
1280         Conn_SetPenalty(new_sock, 4);
1281         return new_sock;
1282 } /* New_Connection */
1283
1284
1285 static CONN_ID
1286 Socket2Index( int Sock )
1287 {
1288         /* zum Socket passende Connection suchen */
1289
1290         assert( Sock >= 0 );
1291
1292         if( Sock >= Pool_Size || My_Connections[Sock].sock != Sock ) {
1293                 /* die Connection wurde vermutlich (wegen eines
1294                  * Fehlers) bereits wieder abgebaut ... */
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
1544         for (i = 0; i < Pool_Size; i++) {
1545                 if (My_Connections[i].sock < 0)
1546                         continue;
1547
1548                 c = Conn_GetClient(i);
1549                 if (c && ((Client_Type(c) == CLIENT_USER)
1550                           || (Client_Type(c) == CLIENT_SERVER)
1551                           || (Client_Type(c) == CLIENT_SERVICE))) {
1552                         /* connected User, Server or Service */
1553                         if (My_Connections[i].lastping >
1554                             My_Connections[i].lastdata) {
1555                                 /* We already sent a ping */
1556                                 if (My_Connections[i].lastping <
1557                                     time(NULL) - Conf_PongTimeout) {
1558                                         /* Timeout */
1559                                         LogDebug
1560                                             ("Connection %d: Ping timeout: %d seconds.",
1561                                              i, Conf_PongTimeout);
1562                                         Conn_Close(i, NULL, "Ping timeout",
1563                                                    true);
1564                                 }
1565                         } else if (My_Connections[i].lastdata <
1566                                    time(NULL) - Conf_PingTimeout) {
1567                                 /* We need to send a PING ... */
1568                                 LogDebug("Connection %d: sending PING ...", i);
1569                                 My_Connections[i].lastping = time(NULL);
1570                                 Conn_WriteStr(i, "PING :%s",
1571                                               Client_ID(Client_ThisServer()));
1572                         }
1573                 } else {
1574                         /* The connection is not fully established yet, so
1575                          * we don't do the PING-PONG game here but instead
1576                          * disconnect the client after "a short time" if it's
1577                          * still not registered. */
1578
1579                         if (My_Connections[i].lastdata <
1580                             time(NULL) - Conf_PongTimeout) {
1581                                 LogDebug
1582                                     ("Unregistered connection %d timed out ...",
1583                                      i);
1584                                 Conn_Close(i, NULL, "Timeout", false);
1585                         }
1586                 }
1587         }
1588 } /* Check_Connections */
1589
1590
1591 static void
1592 Check_Servers( void )
1593 {
1594         /* Check if we can establish further server links */
1595
1596         int i, n;
1597         time_t time_now;
1598
1599         /* Check all configured servers */
1600         for( i = 0; i < MAX_SERVERS; i++ ) {
1601                 /* Valid outgoing server which isn't already connected or disabled? */
1602                 if(( ! Conf_Server[i].host[0] ) || ( ! Conf_Server[i].port > 0 ) ||
1603                         ( Conf_Server[i].conn_id > NONE ) || ( Conf_Server[i].flags & CONF_SFLAG_DISABLED ))
1604                                 continue;
1605
1606                 /* Is there already a connection in this group? */
1607                 if( Conf_Server[i].group > NONE ) {
1608                         for (n = 0; n < MAX_SERVERS; n++) {
1609                                 if (n == i) continue;
1610                                 if ((Conf_Server[n].conn_id != NONE) &&
1611                                         (Conf_Server[n].group == Conf_Server[i].group))
1612                                                 break;
1613                         }
1614                         if (n < MAX_SERVERS) continue;
1615                 }
1616
1617                 /* Check last connect attempt? */
1618                 time_now = time(NULL);
1619                 if( Conf_Server[i].lasttry > (time_now - Conf_ConnectRetry))
1620                         continue;
1621
1622                 /* Okay, try to connect now */
1623                 Conf_Server[i].lasttry = time_now;
1624                 Conf_Server[i].conn_id = SERVER_WAIT;
1625                 assert(Resolve_Getfd(&Conf_Server[i].res_stat) < 0);
1626                 Resolve_Name(&Conf_Server[i].res_stat, Conf_Server[i].host, cb_Connect_to_Server);
1627         }
1628 } /* Check_Servers */
1629
1630
1631 static void
1632 New_Server( int Server , ng_ipaddr_t *dest)
1633 {
1634         /* Establish new server link */
1635         char ip_str[NG_INET_ADDRSTRLEN];
1636         int af_dest, res, new_sock;
1637         CLIENT *c;
1638
1639         assert( Server > NONE );
1640
1641         if (!ng_ipaddr_tostr_r(dest, ip_str)) {
1642                 Log(LOG_WARNING, "New_Server: Could not convert IP to string");
1643                 return;
1644         }
1645
1646         Log( LOG_INFO, "Establishing connection to \"%s\", %s, port %d ... ",
1647                         Conf_Server[Server].host, ip_str, Conf_Server[Server].port );
1648
1649         af_dest = ng_ipaddr_af(dest);
1650         new_sock = socket(af_dest, SOCK_STREAM, 0);
1651         if (new_sock < 0) {
1652                 Log( LOG_CRIT, "Can't create socket (af %d) : %s!", af_dest, strerror( errno ));
1653                 return;
1654         }
1655
1656         if (!Init_Socket(new_sock))
1657                 return;
1658
1659         /* is a bind address configured? */
1660         res = ng_ipaddr_af(&Conf_Server[Server].bind_addr);
1661         /* if yes, bind now. If it fails, warn and let connect() pick a source address */
1662         if (res && bind(new_sock, (struct sockaddr *) &Conf_Server[Server].bind_addr,
1663                                 ng_ipaddr_salen(&Conf_Server[Server].bind_addr)))
1664         {
1665                 ng_ipaddr_tostr_r(&Conf_Server[Server].bind_addr, ip_str);
1666                 Log(LOG_WARNING, "Can't bind socket to %s: %s!", ip_str, strerror(errno));
1667         }
1668         ng_ipaddr_setport(dest, Conf_Server[Server].port);
1669         res = connect(new_sock, (struct sockaddr *) dest, ng_ipaddr_salen(dest));
1670         if(( res != 0 ) && ( errno != EINPROGRESS )) {
1671                 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1672                 close( new_sock );
1673                 return;
1674         }
1675
1676         if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)new_sock)) {
1677                 Log(LOG_ALERT,
1678                     "Cannot allocate memory for server connection (socket %d)",
1679                     new_sock);
1680                 close( new_sock );
1681                 return;
1682         }
1683
1684         My_Connections = array_start(&My_ConnArray);
1685
1686         assert(My_Connections[new_sock].sock <= 0);
1687
1688         Init_Conn_Struct(new_sock);
1689
1690         ng_ipaddr_tostr_r(dest, ip_str);
1691         c = Client_NewLocal(new_sock, ip_str, CLIENT_UNKNOWNSERVER, false);
1692         if (!c) {
1693                 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1694                 close( new_sock );
1695                 return;
1696         }
1697
1698         Client_SetIntroducer( c, c );
1699         Client_SetToken( c, TOKEN_OUTBOUND );
1700
1701         /* Register connection */
1702         Conf_Server[Server].conn_id = new_sock;
1703         My_Connections[new_sock].sock = new_sock;
1704         My_Connections[new_sock].addr = *dest;
1705         My_Connections[new_sock].client = c;
1706         strlcpy( My_Connections[new_sock].host, Conf_Server[Server].host,
1707                                 sizeof(My_Connections[new_sock].host ));
1708
1709         /* Register new socket */
1710         if (!io_event_create( new_sock, IO_WANTWRITE, cb_connserver)) {
1711                 Log( LOG_ALERT, "io_event_create(): could not add fd %d", strerror(errno));
1712                 Conn_Close( new_sock, "io_event_create() failed", NULL, false );
1713                 Init_Conn_Struct( new_sock );
1714                 Conf_Server[Server].conn_id = NONE;
1715         }
1716 #ifdef SSL_SUPPORT
1717         if (Conf_Server[Server].SSLConnect && !ConnSSL_PrepareConnect( &My_Connections[new_sock],
1718                                                                 &Conf_Server[Server] ))
1719         {
1720                 Log(LOG_ALERT, "Could not initialize SSL for outgoing connection");
1721                 Conn_Close( new_sock, "Could not initialize SSL for outgoing connection", NULL, false );
1722                 Init_Conn_Struct( new_sock );
1723                 Conf_Server[Server].conn_id = NONE;
1724         }
1725 #endif
1726         NumConnections++;
1727         LogDebug("Registered new connection %d on socket %d (%ld in total).",
1728                  new_sock, My_Connections[new_sock].sock, NumConnections);
1729         Conn_OPTION_ADD( &My_Connections[new_sock], CONN_ISCONNECTING );
1730 } /* New_Server */
1731
1732
1733 /**
1734  * Initialize connection structure.
1735  */
1736 static void
1737 Init_Conn_Struct(CONN_ID Idx)
1738 {
1739         time_t now = time(NULL);
1740
1741         memset(&My_Connections[Idx], 0, sizeof(CONNECTION));
1742         My_Connections[Idx].sock = -1;
1743         My_Connections[Idx].signon = now;
1744         My_Connections[Idx].lastdata = now;
1745         My_Connections[Idx].lastprivmsg = now;
1746         Resolve_Init(&My_Connections[Idx].res_stat);
1747 } /* Init_Conn_Struct */
1748
1749
1750 static bool
1751 Init_Socket( int Sock )
1752 {
1753         /* Initialize socket (set options) */
1754
1755         int value;
1756
1757         if (!io_setnonblock(Sock)) {
1758                 Log( LOG_CRIT, "Can't enable non-blocking mode for socket: %s!", strerror( errno ));
1759                 close( Sock );
1760                 return false;
1761         }
1762
1763         /* Don't block this port after socket shutdown */
1764         value = 1;
1765         if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &value, (socklen_t)sizeof( value )) != 0 )
1766         {
1767                 Log( LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!", strerror( errno ));
1768                 /* ignore this error */
1769         }
1770
1771         /* Set type of service (TOS) */
1772 #if defined(IP_TOS) && defined(IPTOS_LOWDELAY)
1773         value = IPTOS_LOWDELAY;
1774         LogDebug("Setting option IP_TOS on socket %d to IPTOS_LOWDELAY (%d).", Sock, value );
1775         if( setsockopt( Sock, SOL_IP, IP_TOS, &value, (socklen_t)sizeof( value )) != 0 )
1776         {
1777                 Log( LOG_ERR, "Can't set socket option IP_TOS: %s!", strerror( errno ));
1778                 /* ignore this error */
1779         }
1780 #endif
1781
1782         return true;
1783 } /* Init_Socket */
1784
1785
1786
1787 static void
1788 cb_Connect_to_Server(int fd, UNUSED short events)
1789 {
1790         /* Read result of resolver sub-process from pipe and start connection */
1791         int i;
1792         size_t len;
1793         ng_ipaddr_t dest_addrs[4];      /* we can handle at most 3; but we read up to
1794                                            four so we can log the 'more than we can handle'
1795                                            condition */
1796
1797         LogDebug("Resolver: Got forward lookup callback on fd %d, events %d", fd, events);
1798
1799         for (i=0; i < MAX_SERVERS; i++) {
1800                   if (Resolve_Getfd(&Conf_Server[i].res_stat) == fd )
1801                           break;
1802         }
1803
1804         if( i >= MAX_SERVERS) {
1805                 /* Ops, no matching server found?! */
1806                 io_close( fd );
1807                 LogDebug("Resolver: Got Forward Lookup callback for unknown server!?");
1808                 return;
1809         }
1810
1811         /* Read result from pipe */
1812         len = Resolve_Read(&Conf_Server[i].res_stat, dest_addrs, sizeof(dest_addrs));
1813         if (len == 0)
1814                 return;
1815
1816         assert((len % sizeof(ng_ipaddr_t)) == 0);
1817
1818         LogDebug("Got result from resolver: %u structs (%u bytes).", len/sizeof(ng_ipaddr_t), len);
1819
1820         memset(&Conf_Server[i].dst_addr, 0, sizeof(&Conf_Server[i].dst_addr));
1821         if (len > sizeof(ng_ipaddr_t)) {
1822                 /* more than one address for this hostname, remember them
1823                  * in case first address is unreachable/not available */
1824                 len -= sizeof(ng_ipaddr_t);
1825                 if (len > sizeof(&Conf_Server[i].dst_addr)) {
1826                         len = sizeof(&Conf_Server[i].dst_addr);
1827                         Log(LOG_NOTICE,
1828                                 "Notice: Resolver returned more IP Addresses for host than we can handle, additional addresses dropped.");
1829                 }
1830                 memcpy(&Conf_Server[i].dst_addr, &dest_addrs[1], len);
1831         }
1832         /* connect() */
1833         New_Server(i, dest_addrs);
1834 } /* cb_Read_Forward_Lookup */
1835
1836
1837 static void
1838 cb_Read_Resolver_Result( int r_fd, UNUSED short events )
1839 {
1840         /* Read result of resolver sub-process from pipe and update the
1841          * apropriate connection/client structure(s): hostname and/or
1842          * IDENT user name.*/
1843
1844         CLIENT *c;
1845         int i;
1846         size_t len;
1847         char *identptr;
1848 #ifdef IDENTAUTH
1849         char readbuf[HOST_LEN + 2 + CLIENT_USER_LEN];
1850 #else
1851         char readbuf[HOST_LEN + 1];
1852 #endif
1853
1854         LogDebug("Resolver: Got callback on fd %d, events %d", r_fd, events );
1855
1856         /* Search associated connection ... */
1857         for( i = 0; i < Pool_Size; i++ ) {
1858                 if(( My_Connections[i].sock != NONE )
1859                   && ( Resolve_Getfd(&My_Connections[i].res_stat) == r_fd ))
1860                         break;
1861         }
1862         if( i >= Pool_Size ) {
1863                 /* Ops, none found? Probably the connection has already
1864                  * been closed!? We'll ignore that ... */
1865                 io_close( r_fd );
1866                 LogDebug("Resolver: Got callback for unknown connection!?");
1867                 return;
1868         }
1869
1870         /* Read result from pipe */
1871         len = Resolve_Read(&My_Connections[i].res_stat, readbuf, sizeof readbuf -1);
1872         if (len == 0)
1873                 return;
1874
1875         readbuf[len] = '\0';
1876         identptr = strchr(readbuf, '\n');
1877         assert(identptr != NULL);
1878         if (!identptr) {
1879                 Log( LOG_CRIT, "Resolver: Got malformed result!");
1880                 return;
1881         }
1882
1883         *identptr = '\0';
1884         LogDebug("Got result from resolver: \"%s\" (%u bytes read).", readbuf, len);
1885         /* Okay, we got a complete result: this is a host name for outgoing
1886          * connections and a host name and IDENT user name (if enabled) for
1887          * incoming connections.*/
1888         assert ( My_Connections[i].sock >= 0 );
1889         /* Incoming connection. Search client ... */
1890         c = Conn_GetClient( i );
1891         assert( c != NULL );
1892
1893         /* Only update client information of unregistered clients */
1894         if( Client_Type( c ) == CLIENT_UNKNOWN ) {
1895                 strlcpy(My_Connections[i].host, readbuf, sizeof( My_Connections[i].host));
1896                 Client_SetHostname( c, readbuf);
1897 #ifdef IDENTAUTH
1898                 ++identptr;
1899                 if (*identptr) {
1900                         Log(LOG_INFO, "IDENT lookup for connection %d: \"%s\".", i, identptr);
1901                         Client_SetUser(c, identptr, true);
1902                 } else {
1903                         Log(LOG_INFO, "IDENT lookup for connection %d: no result.", i);
1904                 }
1905 #endif
1906         }
1907 #ifdef DEBUG
1908                 else Log( LOG_DEBUG, "Resolver: discarding result for already registered connection %d.", i );
1909 #endif
1910         /* Reset penalty time */
1911         Conn_ResetPenalty( i );
1912 } /* cb_Read_Resolver_Result */
1913
1914
1915 static void
1916 Simple_Message( int Sock, const char *Msg )
1917 {
1918         char buf[COMMAND_LEN];
1919         size_t len;
1920         /* Write "simple" message to socket, without using compression
1921          * or even the connection write buffers. Used e.g. for error
1922          * messages by New_Connection(). */
1923         assert( Sock > NONE );
1924         assert( Msg != NULL );
1925
1926         strlcpy( buf, Msg, sizeof buf - 2);
1927         len = strlcat( buf, "\r\n", sizeof buf);
1928         (void)write(Sock, buf, len);
1929 } /* Simple_Error */
1930
1931
1932 GLOBAL CLIENT *
1933 Conn_GetClient( CONN_ID Idx ) 
1934 {
1935         /* return Client-Structure that belongs to the local Connection Idx.
1936          * If none is found, return NULL.
1937          */
1938         CONNECTION *c;
1939         assert( Idx >= 0 );
1940
1941         c = array_get(&My_ConnArray, sizeof (CONNECTION), (size_t)Idx);
1942
1943         assert(c != NULL);
1944
1945         return c ? c->client : NULL;
1946 }
1947
1948 #ifdef SSL_SUPPORT
1949 /* we cannot access My_Connections in irc-info.c */
1950 GLOBAL bool
1951 Conn_GetCipherInfo(CONN_ID Idx, char *buf, size_t len)
1952 {
1953         return ConnSSL_GetCipherInfo(&My_Connections[Idx], buf, len);
1954 }
1955
1956
1957 GLOBAL bool
1958 Conn_UsesSSL(CONN_ID Idx)
1959 {
1960         return Conn_OPTION_ISSET(&My_Connections[Idx], CONN_SSL);
1961 }
1962 #endif
1963 /* -eof- */