2 * ngIRCd -- The Next Generation IRC Daemon
3 * Copyright (c)2001-2007 Alexander Barton (alex@barton.de)
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.
11 * Connection management
20 static char UNUSED id[] = "$Id: conn.c,v 1.221 2008/02/26 22:04:17 fw Exp $";
34 #include <sys/socket.h>
36 #include <sys/types.h>
38 #include <netinet/in.h>
40 #ifdef HAVE_NETINET_IP_H
41 # include <netinet/ip.h>
45 # include <stdint.h> /* e.g. for Mac OS X */
49 # include <tcpd.h> /* for TCP Wrappers */
64 #include "conn-func.h"
70 # include "rendezvous.h"
76 #define SERVER_WAIT (NONE - 1)
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 bool 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(( int af, const UINT16 Port ));
93 static array My_Listeners;
94 static array My_ConnArray;
97 int allow_severity = LOG_INFO;
98 int deny_severity = LOG_ERR;
101 static void server_login PARAMS((CONN_ID idx));
103 static void cb_Read_Resolver_Result PARAMS(( int sock, UNUSED short what));
104 static void cb_Connect_to_Server PARAMS(( int sock, UNUSED short what));
105 static void cb_clientserver PARAMS((int sock, short what));
108 cb_listen(int sock, short irrelevant)
111 New_Connection( sock );
116 cb_connserver(int sock, UNUSED short what)
120 CONN_ID idx = Socket2Index( sock );
122 LogDebug("cb_connserver wants to write on unknown socket?!");
127 assert( what & IO_WANTWRITE);
129 /* connect() finished, get result. */
130 sock_len = sizeof( err );
131 res = getsockopt( My_Connections[idx].sock, SOL_SOCKET, SO_ERROR, &err, &sock_len );
132 assert( sock_len == sizeof( err ));
134 /* Error while connecting? */
135 if ((res != 0) || (err != 0)) {
137 Log(LOG_CRIT, "getsockopt (connection %d): %s!",
138 idx, strerror(errno));
141 "Can't connect socket to \"%s:%d\" (connection %d): %s!",
142 My_Connections[idx].host,
143 Conf_Server[Conf_GetServer(idx)].port,
146 res = Conf_GetServer(idx);
149 Conn_Close(idx, "Can't connect!", NULL, false);
153 if (ng_ipaddr_af(&Conf_Server[res].dst_addr[0])) {
154 /* more addresses to try... */
155 New_Server(res, &Conf_Server[res].dst_addr[0]);
156 /* connection to dst_addr[0] in progress, remove this address... */
157 Conf_Server[res].dst_addr[0] = Conf_Server[res].dst_addr[1];
159 memset(&Conf_Server[res].dst_addr[1], 0, sizeof(&Conf_Server[res].dst_addr[1]));
164 res = Conf_GetServer(idx);
166 if (res >= 0) /* connect succeeded, remove all additional addresses */
167 memset(&Conf_Server[res].dst_addr, 0, sizeof(&Conf_Server[res].dst_addr));
168 Conn_OPTION_DEL( &My_Connections[idx], CONN_ISCONNECTING );
174 server_login(CONN_ID idx)
176 Log( LOG_INFO, "Connection %d with \"%s:%d\" established. Now logging in ...", idx,
177 My_Connections[idx].host, Conf_Server[Conf_GetServer( idx )].port );
179 io_event_setcb( My_Connections[idx].sock, cb_clientserver);
180 io_event_add( My_Connections[idx].sock, IO_WANTREAD|IO_WANTWRITE);
182 /* Send PASS and SERVER command to peer */
183 Conn_WriteStr( idx, "PASS %s %s", Conf_Server[Conf_GetServer( idx )].pwd_out, NGIRCd_ProtoID );
184 Conn_WriteStr( idx, "SERVER %s :%s", Conf_ServerName, Conf_ServerInfo );
189 cb_clientserver(int sock, short what)
191 CONN_ID idx = Socket2Index( sock );
194 Log(LOG_WARNING, "WTF: cb_clientserver wants to write on unknown socket?!");
200 if (what & IO_WANTREAD)
203 if (what & IO_WANTWRITE)
211 /* Modul initialisieren: statische Strukturen "ausnullen". */
215 /* Speicher fuer Verbindungs-Pool anfordern */
216 Pool_Size = CONNECTION_POOL;
217 if( Conf_MaxConnections > 0 )
219 /* konfiguriertes Limit beachten */
220 if( Pool_Size > Conf_MaxConnections ) Pool_Size = Conf_MaxConnections;
223 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)Pool_Size)) {
224 Log( LOG_EMERG, "Can't allocate memory! [Conn_Init]" );
228 /* FIXME: My_Connetions/Pool_Size is needed by other parts of the
229 * code; remove them! */
230 My_Connections = (CONNECTION*) array_start(&My_ConnArray);
232 LogDebug("Allocated connection pool for %d items (%ld bytes).",
233 array_length(&My_ConnArray, sizeof( CONNECTION )), array_bytes(&My_ConnArray));
235 assert( array_length(&My_ConnArray, sizeof( CONNECTION )) >= (size_t) Pool_Size);
237 array_free( &My_Listeners );
239 /* Connection-Struktur initialisieren */
240 for( i = 0; i < Pool_Size; i++ ) Init_Conn_Struct( i );
242 /* Global write counter */
250 /* Modul abmelden: alle noch offenen Connections
251 * schliessen und freigeben. */
255 LogDebug("Shutting down all connections ..." );
257 Conn_ExitListeners();
259 /* Sockets schliessen */
260 for( idx = 0; idx < Pool_Size; idx++ ) {
261 if( My_Connections[idx].sock > NONE ) {
262 Conn_Close( idx, NULL, NGIRCd_SignalRestart ?
263 "Server going down (restarting)":"Server going down", true );
267 array_free(&My_ConnArray);
268 My_Connections = NULL;
270 io_library_shutdown();
275 ports_initlisteners(array *a, int af, void (*func)(int,short))
277 unsigned int created = 0;
282 len = array_length(a, sizeof (UINT16));
283 port = array_start(a);
285 fd = NewListener(af, *port);
290 if (!io_event_create( fd, IO_WANTREAD, func )) {
291 Log( LOG_ERR, "io_event_create(): Could not add listening fd %d (port %u): %s!",
292 fd, (unsigned int) *port, strerror(errno));
306 Conn_InitListeners( void )
308 /* Initialize ports on which the server should accept connections */
310 unsigned int created = 0;
312 if (!io_library_init(CONNECTION_POOL)) {
313 Log(LOG_EMERG, "Cannot initialize IO routines: %s", strerror(errno));
318 if (!Conf_NoListenIpv6)
319 created = ports_initlisteners(&Conf_ListenPorts, AF_INET6, cb_listen);
321 created += ports_initlisteners(&Conf_ListenPorts, AF_INET, cb_listen);
324 } /* Conn_InitListeners */
328 Conn_ExitListeners( void )
330 /* Close down all listening sockets */
334 Rendezvous_UnregisterListeners( );
337 arraylen = array_length(&My_Listeners, sizeof (int));
338 Log( LOG_INFO, "Shutting down all listening sockets (%d total)...", arraylen );
339 fd = array_start(&My_Listeners);
344 LogDebug("Listening socket %d closed.", *fd );
347 array_free(&My_Listeners);
348 } /* Conn_ExitListeners */
352 InitSinaddrListenAddr(int af, ng_ipaddr_t *addr, UINT16 Port)
355 const char *listen_addrstr = NULL;
358 listen_addrstr = "0.0.0.0";
362 if (Conf_ListenAddress[0]) /* overrides V4/V6 atm */
363 listen_addrstr = Conf_ListenAddress;
365 ret = ng_ipaddr_init(addr, listen_addrstr, Port);
369 Log(LOG_CRIT, "Can't bind to %s:%u: can't convert ip address \"%s\"",
370 listen_addrstr, Port, listen_addrstr);
377 set_v6_only(int af, int sock)
379 #if defined(IPV6_V6ONLY) && defined(WANT_IPV6)
385 if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)))
386 Log(LOG_ERR, "Could not set IPV6_V6ONLY: %s", strerror(errno));
394 /* return new listening port file descriptor or -1 on failure */
396 NewListener(int af, const UINT16 Port)
398 /* Create new listening socket on specified port */
402 char name[CLIENT_ID_LEN], *info;
404 if (!InitSinaddrListenAddr(af, &addr, Port))
407 sock = socket(ng_ipaddr_af(&addr), SOCK_STREAM, 0);
409 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
413 af = ng_ipaddr_af(&addr);
415 set_v6_only(af, sock);
417 if( ! Init_Socket( sock )) return -1;
419 if (bind(sock, (struct sockaddr *)&addr, ng_ipaddr_salen(&addr)) != 0) {
420 Log( LOG_CRIT, "Can't bind socket (port %d) : %s!", Port, strerror( errno ));
425 if( listen( sock, 10 ) != 0 ) {
426 Log( LOG_CRIT, "Can't listen on socket: %s!", strerror( errno ));
431 /* keep fd in list so we can close it when ngircd restarts/shuts down */
432 if (!array_catb( &My_Listeners,(char*) &sock, sizeof(int) )) {
433 Log( LOG_CRIT, "Can't add socket to My_Listeners array: %s!", strerror( errno ));
440 Log(LOG_INFO, "Now listening on [%s]:%d (socket %d).", ng_ipaddr_tostr(&addr), Port, sock);
443 Log(LOG_INFO, "Now listening on %s:%d (socket %d).", ng_ipaddr_tostr(&addr), Port, sock);
446 /* Get best server description text */
447 if( ! Conf_ServerInfo[0] ) info = Conf_ServerName;
450 /* Use server info string */
452 if( Conf_ServerInfo[0] == '[' )
454 /* Cut off leading hostname part in "[]" */
455 info = strchr( Conf_ServerInfo, ']' );
459 while( *info == ' ' ) info++;
462 if( ! info ) info = Conf_ServerInfo;
465 /* Add port number to description if non-standard */
467 snprintf(name, sizeof name, "%s (port %u)", info,
470 strlcpy(name, info, sizeof name);
472 /* Register service */
473 Rendezvous_Register( name, MDNS_TYPE, Port );
482 /* "Main Loop.": Loop until a signal (for shutdown or restart) arrives.
483 * Call io_dispatch() to check for read/writeable sockets every second
484 * Wait for status change on pending connections (e.g: when the hostname has been resolved)
485 * check for penalty/timeouts
486 * handle input buffers
489 unsigned int wdatalen;
494 while(( ! NGIRCd_SignalQuit ) && ( ! NGIRCd_SignalRestart )) {
498 Rendezvous_Handler( );
501 /* Should the configuration be reloaded? */
502 if (NGIRCd_SignalRehash) {
506 /* Check configured servers and established links */
508 Check_Connections( );
512 /* noch volle Lese-Buffer suchen */
513 for( i = 0; i < Pool_Size; i++ ) {
514 if(( My_Connections[i].sock > NONE ) && ( array_bytes(&My_Connections[i].rbuf) > 0 ) &&
515 ( My_Connections[i].delaytime < t ))
517 /* Kann aus dem Buffer noch ein Befehl extrahiert werden? */
518 if (Handle_Buffer( i )) timeout = false;
522 /* noch volle Schreib-Puffer suchen */
523 for( i = 0; i < Pool_Size; i++ ) {
524 if ( My_Connections[i].sock <= NONE )
527 wdatalen = (unsigned int)array_bytes(&My_Connections[i].wbuf);
530 if (( wdatalen > 0 ) || ( array_bytes(&My_Connections[i].zip.wbuf)> 0 ))
535 /* Socket der Verbindung in Set aufnehmen */
536 io_event_add( My_Connections[i].sock, IO_WANTWRITE );
540 /* von welchen Sockets koennte gelesen werden? */
541 for (i = 0; i < Pool_Size; i++ ) {
542 if ( My_Connections[i].sock <= NONE )
545 if (Resolve_INPROGRESS(&My_Connections[i].res_stat)) {
546 /* wait for completion of Resolver Sub-Process */
547 io_event_del( My_Connections[i].sock, IO_WANTREAD );
551 if ( Conn_OPTION_ISSET( &My_Connections[i], CONN_ISCONNECTING ))
552 continue; /* wait for completion of connect() */
554 if( My_Connections[i].delaytime > t ) {
555 /* Fuer die Verbindung ist eine "Penalty-Zeit" gesetzt */
556 io_event_del( My_Connections[i].sock, IO_WANTREAD );
559 io_event_add( My_Connections[i].sock, IO_WANTREAD );
562 /* (re-)set timeout - tv_sec/usec are undefined after io_dispatch() returns */
564 tv.tv_sec = timeout ? 1 : 0;
566 /* wait for activity */
567 i = io_dispatch( &tv );
568 if (i == -1 && errno != EINTR ) {
569 Log(LOG_EMERG, "Conn_Handler(): io_dispatch(): %s!", strerror(errno));
570 Log(LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE_NAME);
575 if( NGIRCd_SignalQuit ) Log( LOG_NOTICE|LOG_snotice, "Server going down NOW!" );
576 else if( NGIRCd_SignalRestart ) Log( LOG_NOTICE|LOG_snotice, "Server restarting NOW!" );
581 * Write a text string into the socket of a connection.
582 * This function automatically appends CR+LF to the string and validates that
583 * the result is a valid IRC message (oversized messages are shortened, for
584 * example). Then it calls the Conn_Write() function to do the actual sending.
585 * @param Idx Index fo the connection.
586 * @param Format Format string, see printf().
587 * @return true on success, false otherwise.
591 Conn_WriteStr( CONN_ID Idx, char *Format, ... )
594 Conn_WriteStr( Idx, Format, va_alist )
600 char buffer[COMMAND_LEN];
605 assert( Idx > NONE );
606 assert( Format != NULL );
609 va_start( ap, Format );
613 if (vsnprintf( buffer, COMMAND_LEN - 2, Format, ap ) >= COMMAND_LEN - 2 ) {
615 * The string that should be written to the socket is longer
616 * than the allowed size of COMMAND_LEN bytes (including both
617 * the CR and LF characters). This can be caused by the
618 * IRC_WriteXXX() functions when the prefix of this server had
619 * to be added to an already "quite long" command line which
620 * has been received from a regular IRC client, for example.
622 * We are not allowed to send such "oversized" messages to
623 * other servers and clients, see RFC 2812 2.3 and 2813 3.3
624 * ("these messages SHALL NOT exceed 512 characters in length,
625 * counting all characters including the trailing CR-LF").
627 * So we have a big problem here: we should send more bytes
628 * to the network than we are allowed to and we don't know
629 * the originator (any more). The "old" behaviour of blaming
630 * the receiver ("next hop") is a bad idea (it could be just
631 * an other server only routing the message!), so the only
632 * option left is to shorten the string and to hope that the
633 * result is still somewhat useful ...
637 strcpy (buffer + sizeof(buffer) - strlen(CUT_TXTSUFFIX) - 2 - 1,
643 Log(LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer);
646 len = strlcat( buffer, "\r\n", sizeof( buffer ));
647 ok = Conn_Write(Idx, buffer, len);
648 My_Connections[Idx].msg_out++;
652 } /* Conn_WriteStr */
656 * Append Data to the outbound write buffer of a connection.
657 * @param Idx Index of the connection.
658 * @param Data pointer to the data.
659 * @param Len length of Data.
660 * @return true on success, false otherwise.
663 Conn_Write( CONN_ID Idx, char *Data, size_t Len )
666 size_t writebuf_limit = WRITEBUFFER_LEN;
667 assert( Idx > NONE );
668 assert( Data != NULL );
671 c = Conn_GetClient(Idx);
674 /* Servers do get special write buffer limits, so they can generate
675 * all the messages that are required while peering. */
676 if (Client_Type(c) == CLIENT_SERVER)
677 writebuf_limit = WRITEBUFFER_SLINK_LEN;
679 /* Is the socket still open? A previous call to Conn_Write()
680 * may have closed the connection due to a fatal error.
681 * In this case it is sufficient to return an error, as well. */
682 if( My_Connections[Idx].sock <= NONE ) {
683 LogDebug("Skipped write on closed socket (connection %d).", Idx);
688 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
690 * Zip_Buffer() does all the dirty work for us: it flushes
691 * the (pre-)compression buffers if required and handles
692 * all error conditions. */
693 if (!Zip_Buffer(Idx, Data, Len))
699 /* Uncompressed link:
700 * Check if outbound buffer has enough space for the data. */
701 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
703 /* Buffer is full, flush it. Handle_Write deals with
704 * low-level errors, if any. */
705 if (!Handle_Write(Idx))
709 /* When the write buffer is still too big after flushing it,
710 * the connection will be killed. */
711 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
714 "Write buffer overflow (connection %d, size %lu byte)!",
716 (unsigned long)array_bytes(&My_Connections[Idx].wbuf));
717 Conn_Close(Idx, "Write buffer overflow!", NULL, false);
721 /* Copy data to write buffer */
722 if (!array_catb(&My_Connections[Idx].wbuf, Data, Len))
725 My_Connections[Idx].bytes_out += Len;
728 /* Adjust global write counter */
736 Conn_Close( CONN_ID Idx, char *LogMsg, char *FwdMsg, bool InformClient )
738 /* Close connection. Open pipes of asyncronous resolver
739 * sub-processes are closed down. */
746 double in_z_k, out_z_k;
750 assert( Idx > NONE );
752 /* Is this link already shutting down? */
753 if( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ISCLOSING )) {
754 /* Conn_Close() has been called recursively for this link;
755 * probabe reason: Handle_Write() failed -- see below. */
756 LogDebug("Recursive request to close connection: %d", Idx );
760 assert( My_Connections[Idx].sock > NONE );
762 /* Mark link as "closing" */
763 Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCLOSING );
770 txt = "Reason unknown";
772 port = ng_ipaddr_getport(&My_Connections[Idx].addr);
773 Log(LOG_INFO, "Shutting down connection %d (%s) with %s:%d ...", Idx,
774 LogMsg ? LogMsg : FwdMsg, My_Connections[Idx].host, port);
776 /* Search client, if any */
777 c = Conn_GetClient( Idx );
779 /* Should the client be informed? */
782 /* Send statistics to client if registered as user: */
783 if ((c != NULL) && (Client_Type(c) == CLIENT_USER)) {
785 ":%s NOTICE %s :%sConnection statistics: client %.1f kb, server %.1f kb.",
786 Client_ID(Client_ThisServer()), Client_ID(c),
788 (double)My_Connections[Idx].bytes_in / 1024,
789 (double)My_Connections[Idx].bytes_out / 1024);
792 /* Send ERROR to client (see RFC!) */
794 Conn_WriteStr(Idx, "ERROR :%s", FwdMsg);
796 Conn_WriteStr(Idx, "ERROR :Closing connection.");
799 /* Try to write out the write buffer. Note: Handle_Write() eventually
800 * removes the CLIENT structure associated with this connection if an
801 * error occurs! So we have to re-check if there is still an valid
802 * CLIENT structure after calling Handle_Write() ...*/
803 (void)Handle_Write( Idx );
805 /* Search client, if any (re-check!) */
806 c = Conn_GetClient( Idx );
808 /* Shut down socket */
809 if (! io_close(My_Connections[Idx].sock)) {
810 /* Oops, we can't close the socket!? This is ... ugly! */
812 "Error closing connection %d (socket %d) with %s:%d - %s! (ignored)",
813 Idx, My_Connections[Idx].sock, My_Connections[Idx].host,
814 port, strerror(errno));
817 /* Mark socket as invalid: */
818 My_Connections[Idx].sock = NONE;
820 /* If there is still a client, unregister it now */
822 Client_Destroy(c, LogMsg, FwdMsg, true);
824 /* Calculate statistics and log information */
825 in_k = (double)My_Connections[Idx].bytes_in / 1024;
826 out_k = (double)My_Connections[Idx].bytes_out / 1024;
828 if (Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP)) {
829 in_z_k = (double)My_Connections[Idx].zip.bytes_in / 1024;
830 out_z_k = (double)My_Connections[Idx].zip.bytes_out / 1024;
831 /* Make sure that no division by zero can occur during
832 * the calculation of in_p and out_p: in_z_k and out_z_k
833 * are non-zero, that's guaranteed by the protocol until
834 * compression can be enabled. */
839 in_p = (int)(( in_k * 100 ) / in_z_k );
840 out_p = (int)(( out_k * 100 ) / out_z_k );
842 "Connection %d with %s:%d closed (in: %.1fk/%.1fk/%d%%, out: %.1fk/%.1fk/%d%%).",
843 Idx, My_Connections[Idx].host, port,
844 in_k, in_z_k, in_p, out_k, out_z_k, out_p);
850 "Connection %d with %s:%d closed (in: %.1fk, out: %.1fk).",
851 Idx, My_Connections[Idx].host, port,
855 /* cancel running resolver */
856 if (Resolve_INPROGRESS(&My_Connections[Idx].res_stat))
857 Resolve_Shutdown(&My_Connections[Idx].res_stat);
859 /* Servers: Modify time of next connect attempt? */
860 Conf_UnsetServer( Idx );
863 /* Clean up zlib, if link was compressed */
864 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
865 inflateEnd( &My_Connections[Idx].zip.in );
866 deflateEnd( &My_Connections[Idx].zip.out );
867 array_free(&My_Connections[Idx].zip.rbuf);
868 array_free(&My_Connections[Idx].zip.wbuf);
872 array_free(&My_Connections[Idx].rbuf);
873 array_free(&My_Connections[Idx].wbuf);
875 /* Clean up connection structure (=free it) */
876 Init_Conn_Struct( Idx );
878 LogDebug("Shutdown of connection %d completed.", Idx );
883 Conn_SyncServerStruct( void )
885 /* Synchronize server structures (connection IDs):
886 * connections <-> configuration */
892 for( i = 0; i < Pool_Size; i++ ) {
893 /* Established connection? */
894 if (My_Connections[i].sock < 0)
897 /* Server connection? */
898 client = Conn_GetClient( i );
899 if(( ! client ) || ( Client_Type( client ) != CLIENT_SERVER )) continue;
901 for( c = 0; c < MAX_SERVERS; c++ )
903 /* Configured server? */
904 if( ! Conf_Server[c].host[0] ) continue;
907 if( strcmp( Conf_Server[c].name, Client_ID( client )) == 0 )
908 Conf_Server[c].conn_id = i;
911 } /* SyncServerStruct */
915 * Send out data of write buffer; connect new sockets.
918 Handle_Write( CONN_ID Idx )
923 assert( Idx > NONE );
924 if ( My_Connections[Idx].sock < 0 ) {
925 LogDebug("Handle_Write() on closed socket, connection %d", Idx);
928 assert( My_Connections[Idx].sock > NONE );
930 wdatalen = array_bytes(&My_Connections[Idx].wbuf );
934 /* Write buffer is empty, so we try to flush the compression
935 * buffer and get some data to work with from there :-) */
939 /* Now the write buffer most probably has changed: */
940 wdatalen = array_bytes(&My_Connections[Idx].wbuf);
945 /* Still no data, fine. */
946 io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
951 ("Handle_Write() called for connection %d, %ld bytes pending ...",
954 len = write(My_Connections[Idx].sock,
955 array_start(&My_Connections[Idx].wbuf), wdatalen );
958 if (errno == EAGAIN || errno == EINTR)
961 Log(LOG_ERR, "Write error on connection %d (socket %d): %s!",
962 Idx, My_Connections[Idx].sock, strerror(errno));
963 Conn_Close(Idx, "Write error!", NULL, false);
967 /* move any data not yet written to beginning */
968 array_moveleft(&My_Connections[Idx].wbuf, 1, (size_t)len);
975 Count_Connections(ng_ipaddr_t *a)
980 for (i = 0; i < Pool_Size; i++) {
981 if (My_Connections[i].sock <= NONE)
983 if (ng_ipaddr_ipequal(&My_Connections[i].addr, a))
987 } /* Count_Connections */
991 New_Connection( int Sock )
993 /* Neue Client-Verbindung von Listen-Socket annehmen und
994 * CLIENT-Struktur anlegen. */
997 struct request_info req;
999 ng_ipaddr_t new_addr;
1000 char ip_str[NG_INET_ADDRSTRLEN];
1001 int new_sock, new_sock_len, new_Pool_Size;
1005 assert( Sock > NONE );
1006 /* Connection auf Listen-Socket annehmen */
1007 new_sock_len = (int)sizeof(new_addr);
1009 new_sock = accept(Sock, (struct sockaddr *)&new_addr,
1010 (socklen_t *)&new_sock_len);
1012 Log(LOG_CRIT, "Can't accept connection: %s!", strerror(errno));
1016 if (!ng_ipaddr_tostr_r(&new_addr, ip_str)) {
1017 Log(LOG_CRIT, "fd %d: Can't convert IP address!", new_sock);
1018 Simple_Message(new_sock, "ERROR :Internal Server Error");
1023 /* Validate socket using TCP Wrappers */
1024 request_init( &req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock, RQ_CLIENT_SIN, &new_addr, NULL );
1026 if (!hosts_access(&req)) {
1027 Log (deny_severity, "Refused connection from %s (by TCP Wrappers)!", ip_str);
1028 Simple_Message( new_sock, "ERROR :Connection refused" );
1034 /* Socket initialisieren */
1035 if (!Init_Socket( new_sock ))
1038 /* Check IP-based connection limit */
1039 cnt = Count_Connections(&new_addr);
1040 if ((Conf_MaxConnectionsIP > 0) && (cnt >= Conf_MaxConnectionsIP)) {
1041 /* Access denied, too many connections from this IP address! */
1042 Log( LOG_ERR, "Refused connection from %s: too may connections (%ld) from this IP address!", ip_str, cnt);
1043 Simple_Message( new_sock, "ERROR :Connection refused, too many connections from your IP address!" );
1048 if( new_sock >= Pool_Size ) {
1049 new_Pool_Size = new_sock + 1;
1050 /* No free Connection Structures, check if we may accept further connections */
1051 if ((( Conf_MaxConnections > 0) && Pool_Size >= Conf_MaxConnections) ||
1052 (new_Pool_Size < Pool_Size))
1054 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached!", Pool_Size );
1055 Simple_Message( new_sock, "ERROR :Connection limit reached" );
1060 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION),
1061 (size_t)new_sock)) {
1062 Log( LOG_EMERG, "Can't allocate memory! [New_Connection]" );
1063 Simple_Message( new_sock, "ERROR: Internal error" );
1067 LogDebug("Bumped connection pool to %ld items (internal: %ld items, %ld bytes)",
1068 new_sock, array_length(&My_ConnArray, sizeof(CONNECTION)), array_bytes(&My_ConnArray));
1070 /* Adjust pointer to new block */
1071 My_Connections = array_start(&My_ConnArray);
1072 while (Pool_Size < new_Pool_Size)
1073 Init_Conn_Struct(Pool_Size++);
1076 /* register callback */
1077 if (!io_event_create( new_sock, IO_WANTREAD, cb_clientserver)) {
1078 Log(LOG_ALERT, "Can't accept connection: io_event_create failed!");
1079 Simple_Message(new_sock, "ERROR :Internal error");
1084 c = Client_NewLocal(new_sock, ip_str, CLIENT_UNKNOWN, false );
1086 Log(LOG_ALERT, "Can't accept connection: can't create client structure!");
1087 Simple_Message(new_sock, "ERROR :Internal error");
1092 Init_Conn_Struct( new_sock );
1093 My_Connections[new_sock].sock = new_sock;
1094 My_Connections[new_sock].addr = new_addr;
1095 My_Connections[new_sock].client = c;
1097 Log( LOG_INFO, "Accepted connection %d from %s:%d on socket %d.", new_sock,
1098 ip_str, ng_ipaddr_getport(&new_addr), Sock);
1100 /* Hostnamen ermitteln */
1101 strlcpy(My_Connections[new_sock].host, ip_str, sizeof(My_Connections[new_sock].host));
1103 Client_SetHostname(c, My_Connections[new_sock].host);
1106 Resolve_Addr(&My_Connections[new_sock].res_stat, &new_addr,
1107 My_Connections[new_sock].sock, cb_Read_Resolver_Result);
1109 Conn_SetPenalty(new_sock, 4);
1111 } /* New_Connection */
1115 Socket2Index( int Sock )
1117 /* zum Socket passende Connection suchen */
1119 assert( Sock >= 0 );
1121 if( Sock >= Pool_Size || My_Connections[Sock].sock != Sock ) {
1122 /* die Connection wurde vermutlich (wegen eines
1123 * Fehlers) bereits wieder abgebaut ... */
1124 LogDebug("Socket2Index: can't get connection for socket %d!", Sock);
1128 } /* Socket2Index */
1132 * Read data from the network to the read buffer. If an error occures,
1133 * the socket of this connection will be shut down.
1136 Read_Request( CONN_ID Idx )
1139 char readbuf[READBUFFER_LEN];
1141 assert( Idx > NONE );
1142 assert( My_Connections[Idx].sock > NONE );
1145 if ((array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN) ||
1146 (array_bytes(&My_Connections[Idx].zip.rbuf) >= READBUFFER_LEN))
1148 if (array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN)
1151 /* Read buffer is full */
1153 "Receive buffer overflow (connection %d): %d bytes!",
1154 Idx, array_bytes(&My_Connections[Idx].rbuf));
1155 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1159 len = read(My_Connections[Idx].sock, readbuf, sizeof(readbuf));
1161 Log(LOG_INFO, "%s:%u (%s) is closing the connection ...",
1162 My_Connections[Idx].host,
1163 (unsigned int) ng_ipaddr_getport(&My_Connections[Idx].addr),
1164 ng_ipaddr_tostr(&My_Connections[Idx].addr));
1166 "Socket closed!", "Client closed connection",
1172 if( errno == EAGAIN ) return;
1173 Log(LOG_ERR, "Read error on connection %d (socket %d): %s!",
1174 Idx, My_Connections[Idx].sock, strerror(errno));
1175 Conn_Close(Idx, "Read error!", "Client closed connection",
1180 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1181 if (!array_catb(&My_Connections[Idx].zip.rbuf, readbuf,
1184 "Could not append recieved data to zip input buffer (connn %d): %d bytes!",
1186 Conn_Close(Idx, "Receive buffer overflow!", NULL,
1193 if (!array_catb( &My_Connections[Idx].rbuf, readbuf, len)) {
1194 Log( LOG_ERR, "Could not append recieved data to input buffer (connn %d): %d bytes!", Idx, len );
1195 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1199 /* Update connection statistics */
1200 My_Connections[Idx].bytes_in += len;
1202 /* Update timestamp of last data received if this connection is
1203 * registered as a user, server or service connection. Don't update
1204 * otherwise, so users have at least Conf_PongTimeout seconds time to
1205 * register with the IRC server -- see Check_Connections().
1206 * Set "lastping", too, so we can handle time shifts backwards ... */
1207 c = Conn_GetClient(Idx);
1208 if (c && (Client_Type(c) == CLIENT_USER
1209 || Client_Type(c) == CLIENT_SERVER
1210 || Client_Type(c) == CLIENT_SERVICE)) {
1211 My_Connections[Idx].lastdata = time(NULL);
1212 My_Connections[Idx].lastping = My_Connections[Idx].lastdata;
1215 /* Look at the data in the (read-) buffer of this connection */
1217 } /* Read_Request */
1221 Handle_Buffer( CONN_ID Idx )
1223 /* Handle Data in Connections Read-Buffer.
1224 * Return true if a reuqest was handled, false otherwise (also returned on errors). */
1236 starttime = time(NULL);
1240 if( My_Connections[Idx].delaytime > starttime) return result;
1242 /* unpack compressed data */
1243 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP ))
1244 if( ! Unzip_Buffer( Idx )) return false;
1247 if (0 == array_bytes(&My_Connections[Idx].rbuf))
1250 if (!array_cat0_temporary(&My_Connections[Idx].rbuf)) /* make sure buf is NULL terminated */
1253 /* A Complete Request end with CR+LF, see RFC 2812. */
1254 ptr = strstr( array_start(&My_Connections[Idx].rbuf), "\r\n" );
1256 if( ptr ) delta = 2; /* complete request */
1259 /* Check for non-RFC-compliant request (only CR or LF)? Unfortunately,
1260 * there are quite a few clients that do this (incl. "mIRC" :-( */
1261 ptr1 = strchr( array_start(&My_Connections[Idx].rbuf), '\r' );
1262 ptr2 = strchr( array_start(&My_Connections[Idx].rbuf), '\n' );
1264 if( ptr1 && ptr2 ) ptr = ptr1 > ptr2 ? ptr2 : ptr1;
1265 else if( ptr1 ) ptr = ptr1;
1266 else if( ptr2 ) ptr = ptr2;
1273 /* End of request found */
1276 len = ( ptr - (char*) array_start(&My_Connections[Idx].rbuf)) + delta;
1278 if( len > ( COMMAND_LEN - 1 )) {
1279 /* Request must not exceed 512 chars (incl. CR+LF!), see
1280 * RFC 2812. Disconnect Client if this happens. */
1281 Log( LOG_ERR, "Request too long (connection %d): %d bytes (max. %d expected)!",
1282 Idx, array_bytes(&My_Connections[Idx].rbuf), COMMAND_LEN - 1 );
1283 Conn_Close( Idx, NULL, "Request too long", true );
1287 if (len <= 2) { /* request was empty (only '\r\n') */
1288 array_moveleft(&My_Connections[Idx].rbuf, 1, delta); /* delta is either 1 or 2 */
1292 /* remember if stream is already compressed */
1293 old_z = My_Connections[Idx].options & CONN_ZIP;
1296 My_Connections[Idx].msg_in++;
1297 if (!Parse_Request(Idx, (char*)array_start(&My_Connections[Idx].rbuf) ))
1302 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1303 LogDebug("Connection %d: %d bytes left in read buffer.",
1304 Idx, array_bytes(&My_Connections[Idx].rbuf));
1306 if(( ! old_z ) && ( My_Connections[Idx].options & CONN_ZIP ) &&
1307 ( array_bytes(&My_Connections[Idx].rbuf) > 0 ))
1309 /* The last Command activated Socket-Compression.
1310 * Data that was read after that needs to be copied to Unzip-buf
1311 * for decompression */
1312 if (!array_copy( &My_Connections[Idx].zip.rbuf, &My_Connections[Idx].rbuf ))
1315 array_trunc(&My_Connections[Idx].rbuf);
1316 LogDebug("Moved already received data (%u bytes) to uncompression buffer.",
1317 array_bytes(&My_Connections[Idx].zip.rbuf));
1322 } /* Handle_Buffer */
1326 Check_Connections(void)
1328 /* check if connections are alive. if not, play PING-PONG first.
1329 * if this doesn't help either, disconnect client. */
1333 for (i = 0; i < Pool_Size; i++) {
1334 if (My_Connections[i].sock < 0)
1337 c = Conn_GetClient(i);
1338 if (c && ((Client_Type(c) == CLIENT_USER)
1339 || (Client_Type(c) == CLIENT_SERVER)
1340 || (Client_Type(c) == CLIENT_SERVICE))) {
1341 /* connected User, Server or Service */
1342 if (My_Connections[i].lastping >
1343 My_Connections[i].lastdata) {
1344 /* We already sent a ping */
1345 if (My_Connections[i].lastping <
1346 time(NULL) - Conf_PongTimeout) {
1349 ("Connection %d: Ping timeout: %d seconds.",
1350 i, Conf_PongTimeout);
1351 Conn_Close(i, NULL, "Ping timeout",
1354 } else if (My_Connections[i].lastdata <
1355 time(NULL) - Conf_PingTimeout) {
1356 /* We need to send a PING ... */
1357 LogDebug("Connection %d: sending PING ...", i);
1358 My_Connections[i].lastping = time(NULL);
1359 Conn_WriteStr(i, "PING :%s",
1360 Client_ID(Client_ThisServer()));
1363 /* The connection is not fully established yet, so
1364 * we don't do the PING-PONG game here but instead
1365 * disconnect the client after "a short time" if it's
1366 * still not registered. */
1368 if (My_Connections[i].lastdata <
1369 time(NULL) - Conf_PongTimeout) {
1371 ("Unregistered connection %d timed out ...",
1373 Conn_Close(i, NULL, "Timeout", false);
1377 } /* Check_Connections */
1381 Check_Servers( void )
1383 /* Check if we can establish further server links */
1388 /* Check all configured servers */
1389 for( i = 0; i < MAX_SERVERS; i++ ) {
1390 /* Valid outgoing server which isn't already connected or disabled? */
1391 if(( ! Conf_Server[i].host[0] ) || ( ! Conf_Server[i].port > 0 ) ||
1392 ( Conf_Server[i].conn_id > NONE ) || ( Conf_Server[i].flags & CONF_SFLAG_DISABLED ))
1395 /* Is there already a connection in this group? */
1396 if( Conf_Server[i].group > NONE ) {
1397 for (n = 0; n < MAX_SERVERS; n++) {
1398 if (n == i) continue;
1399 if ((Conf_Server[n].conn_id != NONE) &&
1400 (Conf_Server[n].group == Conf_Server[i].group))
1403 if (n < MAX_SERVERS) continue;
1406 /* Check last connect attempt? */
1407 time_now = time(NULL);
1408 if( Conf_Server[i].lasttry > (time_now - Conf_ConnectRetry))
1411 /* Okay, try to connect now */
1412 Conf_Server[i].lasttry = time_now;
1413 Conf_Server[i].conn_id = SERVER_WAIT;
1414 assert(Resolve_Getfd(&Conf_Server[i].res_stat) < 0);
1415 Resolve_Name(&Conf_Server[i].res_stat, Conf_Server[i].host, cb_Connect_to_Server);
1417 } /* Check_Servers */
1421 New_Server( int Server , ng_ipaddr_t *dest)
1423 /* Establish new server link */
1424 char ip_str[NG_INET_ADDRSTRLEN];
1425 int af_dest, res, new_sock;
1428 assert( Server > NONE );
1430 if (!ng_ipaddr_tostr_r(dest, ip_str)) {
1431 Log(LOG_WARNING, "New_Server: Could not convert IP to string");
1435 Log( LOG_INFO, "Establishing connection to \"%s\", %s, port %d ... ",
1436 Conf_Server[Server].host, ip_str, Conf_Server[Server].port );
1438 af_dest = ng_ipaddr_af(dest);
1439 new_sock = socket(af_dest, SOCK_STREAM, 0);
1441 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
1445 if (!Init_Socket(new_sock))
1448 /* is a bind address configured? */
1449 res = ng_ipaddr_af(&Conf_Server[Server].bind_addr);
1450 /* if yes, bind now. If it fails, warn and let connect() pick a source address */
1451 if (res && bind(new_sock, (struct sockaddr *) &Conf_Server[Server].bind_addr,
1452 ng_ipaddr_salen(&Conf_Server[Server].bind_addr)))
1454 ng_ipaddr_tostr_r(&Conf_Server[Server].bind_addr, ip_str);
1455 Log(LOG_WARNING, "Can't bind socket to %s: %s!", ip_str, strerror(errno));
1457 ng_ipaddr_setport(dest, Conf_Server[Server].port);
1458 res = connect(new_sock, (struct sockaddr *) dest, ng_ipaddr_salen(dest));
1459 if(( res != 0 ) && ( errno != EINPROGRESS )) {
1460 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1465 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)new_sock)) {
1467 "Cannot allocate memory for server connection (socket %d)",
1473 My_Connections = array_start(&My_ConnArray);
1475 assert(My_Connections[new_sock].sock <= 0);
1477 Init_Conn_Struct(new_sock);
1479 ng_ipaddr_tostr_r(dest, ip_str);
1480 c = Client_NewLocal(new_sock, ip_str, CLIENT_UNKNOWNSERVER, false);
1482 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1487 Client_SetIntroducer( c, c );
1488 Client_SetToken( c, TOKEN_OUTBOUND );
1490 /* Register connection */
1491 Conf_Server[Server].conn_id = new_sock;
1492 My_Connections[new_sock].sock = new_sock;
1493 My_Connections[new_sock].addr = *dest;
1494 My_Connections[new_sock].client = c;
1495 strlcpy( My_Connections[new_sock].host, Conf_Server[Server].host,
1496 sizeof(My_Connections[new_sock].host ));
1498 /* Register new socket */
1499 if (!io_event_create( new_sock, IO_WANTWRITE, cb_connserver)) {
1500 Log( LOG_ALERT, "io_event_create(): could not add fd %d", strerror(errno));
1501 Conn_Close( new_sock, "io_event_create() failed", NULL, false );
1502 Init_Conn_Struct( new_sock );
1503 Conf_Server[Server].conn_id = NONE;
1506 LogDebug("Registered new connection %d on socket %d.",
1507 new_sock, My_Connections[new_sock].sock );
1508 Conn_OPTION_ADD( &My_Connections[new_sock], CONN_ISCONNECTING );
1513 * Initialize connection structure.
1516 Init_Conn_Struct(CONN_ID Idx)
1518 time_t now = time(NULL);
1520 memset(&My_Connections[Idx], 0, sizeof(CONNECTION));
1521 My_Connections[Idx].sock = -1;
1522 My_Connections[Idx].signon = now;
1523 My_Connections[Idx].lastdata = now;
1524 My_Connections[Idx].lastprivmsg = now;
1525 Resolve_Init(&My_Connections[Idx].res_stat);
1526 } /* Init_Conn_Struct */
1530 Init_Socket( int Sock )
1532 /* Initialize socket (set options) */
1536 if (!io_setnonblock(Sock)) {
1537 Log( LOG_CRIT, "Can't enable non-blocking mode for socket: %s!", strerror( errno ));
1542 /* Don't block this port after socket shutdown */
1544 if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &value, (socklen_t)sizeof( value )) != 0 )
1546 Log( LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!", strerror( errno ));
1547 /* ignore this error */
1550 /* Set type of service (TOS) */
1551 #if defined(IP_TOS) && defined(IPTOS_LOWDELAY)
1552 value = IPTOS_LOWDELAY;
1553 LogDebug("Setting option IP_TOS on socket %d to IPTOS_LOWDELAY (%d).", Sock, value );
1554 if( setsockopt( Sock, SOL_IP, IP_TOS, &value, (socklen_t)sizeof( value )) != 0 )
1556 Log( LOG_ERR, "Can't set socket option IP_TOS: %s!", strerror( errno ));
1557 /* ignore this error */
1567 cb_Connect_to_Server(int fd, UNUSED short events)
1569 /* Read result of resolver sub-process from pipe and start connection */
1572 ng_ipaddr_t dest_addrs[4]; /* we can handle at most 3; but we read up to
1573 four so we can log the 'more than we can handle'
1576 LogDebug("Resolver: Got forward lookup callback on fd %d, events %d", fd, events);
1578 for (i=0; i < MAX_SERVERS; i++) {
1579 if (Resolve_Getfd(&Conf_Server[i].res_stat) == fd )
1583 if( i >= MAX_SERVERS) {
1584 /* Ops, no matching server found?! */
1586 LogDebug("Resolver: Got Forward Lookup callback for unknown server!?");
1590 /* Read result from pipe */
1591 len = Resolve_Read(&Conf_Server[i].res_stat, dest_addrs, sizeof(dest_addrs));
1595 assert((len % sizeof(ng_ipaddr_t)) == 0);
1597 LogDebug("Got result from resolver: %u structs (%u bytes).", len/sizeof(ng_ipaddr_t), len);
1599 memset(&Conf_Server[i].dst_addr, 0, sizeof(&Conf_Server[i].dst_addr));
1600 if (len > sizeof(ng_ipaddr_t)) {
1601 /* more than one address for this hostname, remember them
1602 * in case first address is unreachable/not available */
1603 len -= sizeof(ng_ipaddr_t);
1604 if (len > sizeof(&Conf_Server[i].dst_addr)) {
1605 len = sizeof(&Conf_Server[i].dst_addr);
1606 Log(LOG_NOTICE, "Notice: Resolver returned more IP Addresses for host than we can handle,"
1607 " additional addresses dropped");
1609 memcpy(&Conf_Server[i].dst_addr, &dest_addrs[1], len);
1612 New_Server(i, dest_addrs);
1613 } /* cb_Read_Forward_Lookup */
1617 cb_Read_Resolver_Result( int r_fd, UNUSED short events )
1619 /* Read result of resolver sub-process from pipe and update the
1620 * apropriate connection/client structure(s): hostname and/or
1621 * IDENT user name.*/
1628 char readbuf[HOST_LEN + 2 + CLIENT_USER_LEN];
1630 char readbuf[HOST_LEN + 1];
1633 LogDebug("Resolver: Got callback on fd %d, events %d", r_fd, events );
1635 /* Search associated connection ... */
1636 for( i = 0; i < Pool_Size; i++ ) {
1637 if(( My_Connections[i].sock != NONE )
1638 && ( Resolve_Getfd(&My_Connections[i].res_stat) == r_fd ))
1641 if( i >= Pool_Size ) {
1642 /* Ops, none found? Probably the connection has already
1643 * been closed!? We'll ignore that ... */
1645 LogDebug("Resolver: Got callback for unknown connection!?");
1649 /* Read result from pipe */
1650 len = Resolve_Read(&My_Connections[i].res_stat, readbuf, sizeof readbuf -1);
1654 readbuf[len] = '\0';
1655 identptr = strchr(readbuf, '\n');
1656 assert(identptr != NULL);
1658 Log( LOG_CRIT, "Resolver: Got malformed result!");
1663 LogDebug("Got result from resolver: \"%s\" (%u bytes read).", readbuf, len);
1664 /* Okay, we got a complete result: this is a host name for outgoing
1665 * connections and a host name and IDENT user name (if enabled) for
1666 * incoming connections.*/
1667 assert ( My_Connections[i].sock >= 0 );
1668 /* Incoming connection. Search client ... */
1669 c = Conn_GetClient( i );
1670 assert( c != NULL );
1672 /* Only update client information of unregistered clients */
1673 if( Client_Type( c ) == CLIENT_UNKNOWN ) {
1674 strlcpy(My_Connections[i].host, readbuf, sizeof( My_Connections[i].host));
1675 Client_SetHostname( c, readbuf);
1679 Log(LOG_INFO, "IDENT lookup for connection %d: \"%s\".", i, identptr);
1680 Client_SetUser(c, identptr, true);
1682 Log(LOG_INFO, "IDENT lookup for connection %d: no result.", i);
1687 else Log( LOG_DEBUG, "Resolver: discarding result for already registered connection %d.", i );
1689 /* Reset penalty time */
1690 Conn_ResetPenalty( i );
1691 } /* cb_Read_Resolver_Result */
1695 Simple_Message( int Sock, const char *Msg )
1697 char buf[COMMAND_LEN];
1699 /* Write "simple" message to socket, without using compression
1700 * or even the connection write buffers. Used e.g. for error
1701 * messages by New_Connection(). */
1702 assert( Sock > NONE );
1703 assert( Msg != NULL );
1705 strlcpy( buf, Msg, sizeof buf - 2);
1706 len = strlcat( buf, "\r\n", sizeof buf);
1707 (void)write(Sock, buf, len);
1708 } /* Simple_Error */
1712 Conn_GetClient( CONN_ID Idx )
1714 /* return Client-Structure that belongs to the local Connection Idx.
1715 * If none is found, return NULL.
1720 c = array_get(&My_ConnArray, sizeof (CONNECTION), (size_t)Idx);
1724 return c ? c->client : NULL;