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));
319 created = ports_initlisteners(&Conf_ListenPorts, AF_INET6, cb_listen);
322 created += ports_initlisteners(&Conf_ListenPorts, AF_INET, cb_listen);
325 } /* Conn_InitListeners */
329 Conn_ExitListeners( void )
331 /* Close down all listening sockets */
335 Rendezvous_UnregisterListeners( );
338 arraylen = array_length(&My_Listeners, sizeof (int));
339 Log( LOG_INFO, "Shutting down all listening sockets (%d total)...", arraylen );
340 fd = array_start(&My_Listeners);
345 LogDebug("Listening socket %d closed.", *fd );
348 array_free(&My_Listeners);
349 } /* Conn_ExitListeners */
353 InitSinaddrListenAddr(int af, ng_ipaddr_t *addr, UINT16 Port)
356 const char *listen_addrstr = NULL;
359 listen_addrstr = "0.0.0.0";
363 if (Conf_ListenAddress[0]) /* overrides V4/V6 atm */
364 listen_addrstr = Conf_ListenAddress;
366 ret = ng_ipaddr_init(addr, listen_addrstr, Port);
370 Log(LOG_CRIT, "Can't bind to %s:%u: can't convert ip address \"%s\"",
371 listen_addrstr, Port, listen_addrstr);
378 set_v6_only(int af, int sock)
380 #if defined(IPV6_V6ONLY) && defined(WANT_IPV6)
386 if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)))
387 Log(LOG_ERR, "Could not set IPV6_V6ONLY: %s", strerror(errno));
395 /* return new listening port file descriptor or -1 on failure */
397 NewListener(int af, const UINT16 Port)
399 /* Create new listening socket on specified port */
403 char name[CLIENT_ID_LEN], *info;
405 if (!InitSinaddrListenAddr(af, &addr, Port))
408 sock = socket(ng_ipaddr_af(&addr), SOCK_STREAM, 0);
410 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
414 af = ng_ipaddr_af(&addr);
416 set_v6_only(af, sock);
418 if (!Init_Socket(sock))
421 if (bind(sock, (struct sockaddr *)&addr, ng_ipaddr_salen(&addr)) != 0) {
422 Log(LOG_CRIT, "Can't bind socket to address %s:%d - %s",
423 ng_ipaddr_tostr(&addr), Port, strerror(errno));
428 if( listen( sock, 10 ) != 0 ) {
429 Log( LOG_CRIT, "Can't listen on socket: %s!", strerror( errno ));
434 /* keep fd in list so we can close it when ngircd restarts/shuts down */
435 if (!array_catb( &My_Listeners,(char*) &sock, sizeof(int) )) {
436 Log( LOG_CRIT, "Can't add socket to My_Listeners array: %s!", strerror( errno ));
443 Log(LOG_INFO, "Now listening on [%s]:%d (socket %d).", ng_ipaddr_tostr(&addr), Port, sock);
446 Log(LOG_INFO, "Now listening on %s:%d (socket %d).", ng_ipaddr_tostr(&addr), Port, sock);
449 /* Get best server description text */
450 if( ! Conf_ServerInfo[0] ) info = Conf_ServerName;
453 /* Use server info string */
455 if( Conf_ServerInfo[0] == '[' )
457 /* Cut off leading hostname part in "[]" */
458 info = strchr( Conf_ServerInfo, ']' );
462 while( *info == ' ' ) info++;
465 if( ! info ) info = Conf_ServerInfo;
468 /* Add port number to description if non-standard */
470 snprintf(name, sizeof name, "%s (port %u)", info,
473 strlcpy(name, info, sizeof name);
475 /* Register service */
476 Rendezvous_Register( name, MDNS_TYPE, Port );
485 /* "Main Loop.": Loop until a signal (for shutdown or restart) arrives.
486 * Call io_dispatch() to check for read/writeable sockets every second
487 * Wait for status change on pending connections (e.g: when the hostname has been resolved)
488 * check for penalty/timeouts
489 * handle input buffers
492 unsigned int wdatalen;
497 while(( ! NGIRCd_SignalQuit ) && ( ! NGIRCd_SignalRestart )) {
501 Rendezvous_Handler( );
504 /* Should the configuration be reloaded? */
505 if (NGIRCd_SignalRehash) {
509 /* Check configured servers and established links */
511 Check_Connections( );
515 /* noch volle Lese-Buffer suchen */
516 for( i = 0; i < Pool_Size; i++ ) {
517 if(( My_Connections[i].sock > NONE ) && ( array_bytes(&My_Connections[i].rbuf) > 0 ) &&
518 ( My_Connections[i].delaytime < t ))
520 /* Kann aus dem Buffer noch ein Befehl extrahiert werden? */
521 if (Handle_Buffer( i )) timeout = false;
525 /* noch volle Schreib-Puffer suchen */
526 for( i = 0; i < Pool_Size; i++ ) {
527 if ( My_Connections[i].sock <= NONE )
530 wdatalen = (unsigned int)array_bytes(&My_Connections[i].wbuf);
533 if (( wdatalen > 0 ) || ( array_bytes(&My_Connections[i].zip.wbuf)> 0 ))
538 /* Socket der Verbindung in Set aufnehmen */
539 io_event_add( My_Connections[i].sock, IO_WANTWRITE );
543 /* von welchen Sockets koennte gelesen werden? */
544 for (i = 0; i < Pool_Size; i++ ) {
545 if ( My_Connections[i].sock <= NONE )
548 if (Resolve_INPROGRESS(&My_Connections[i].res_stat)) {
549 /* wait for completion of Resolver Sub-Process */
550 io_event_del( My_Connections[i].sock, IO_WANTREAD );
554 if ( Conn_OPTION_ISSET( &My_Connections[i], CONN_ISCONNECTING ))
555 continue; /* wait for completion of connect() */
557 if( My_Connections[i].delaytime > t ) {
558 /* Fuer die Verbindung ist eine "Penalty-Zeit" gesetzt */
559 io_event_del( My_Connections[i].sock, IO_WANTREAD );
562 io_event_add( My_Connections[i].sock, IO_WANTREAD );
565 /* (re-)set timeout - tv_sec/usec are undefined after io_dispatch() returns */
567 tv.tv_sec = timeout ? 1 : 0;
569 /* wait for activity */
570 i = io_dispatch( &tv );
571 if (i == -1 && errno != EINTR ) {
572 Log(LOG_EMERG, "Conn_Handler(): io_dispatch(): %s!", strerror(errno));
573 Log(LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE_NAME);
578 if( NGIRCd_SignalQuit ) Log( LOG_NOTICE|LOG_snotice, "Server going down NOW!" );
579 else if( NGIRCd_SignalRestart ) Log( LOG_NOTICE|LOG_snotice, "Server restarting NOW!" );
584 * Write a text string into the socket of a connection.
585 * This function automatically appends CR+LF to the string and validates that
586 * the result is a valid IRC message (oversized messages are shortened, for
587 * example). Then it calls the Conn_Write() function to do the actual sending.
588 * @param Idx Index fo the connection.
589 * @param Format Format string, see printf().
590 * @return true on success, false otherwise.
594 Conn_WriteStr( CONN_ID Idx, char *Format, ... )
597 Conn_WriteStr( Idx, Format, va_alist )
603 char buffer[COMMAND_LEN];
608 assert( Idx > NONE );
609 assert( Format != NULL );
612 va_start( ap, Format );
616 if (vsnprintf( buffer, COMMAND_LEN - 2, Format, ap ) >= COMMAND_LEN - 2 ) {
618 * The string that should be written to the socket is longer
619 * than the allowed size of COMMAND_LEN bytes (including both
620 * the CR and LF characters). This can be caused by the
621 * IRC_WriteXXX() functions when the prefix of this server had
622 * to be added to an already "quite long" command line which
623 * has been received from a regular IRC client, for example.
625 * We are not allowed to send such "oversized" messages to
626 * other servers and clients, see RFC 2812 2.3 and 2813 3.3
627 * ("these messages SHALL NOT exceed 512 characters in length,
628 * counting all characters including the trailing CR-LF").
630 * So we have a big problem here: we should send more bytes
631 * to the network than we are allowed to and we don't know
632 * the originator (any more). The "old" behaviour of blaming
633 * the receiver ("next hop") is a bad idea (it could be just
634 * an other server only routing the message!), so the only
635 * option left is to shorten the string and to hope that the
636 * result is still somewhat useful ...
640 strcpy (buffer + sizeof(buffer) - strlen(CUT_TXTSUFFIX) - 2 - 1,
646 Log(LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer);
649 len = strlcat( buffer, "\r\n", sizeof( buffer ));
650 ok = Conn_Write(Idx, buffer, len);
651 My_Connections[Idx].msg_out++;
655 } /* Conn_WriteStr */
659 * Append Data to the outbound write buffer of a connection.
660 * @param Idx Index of the connection.
661 * @param Data pointer to the data.
662 * @param Len length of Data.
663 * @return true on success, false otherwise.
666 Conn_Write( CONN_ID Idx, char *Data, size_t Len )
669 size_t writebuf_limit = WRITEBUFFER_LEN;
670 assert( Idx > NONE );
671 assert( Data != NULL );
674 c = Conn_GetClient(Idx);
677 /* Servers do get special write buffer limits, so they can generate
678 * all the messages that are required while peering. */
679 if (Client_Type(c) == CLIENT_SERVER)
680 writebuf_limit = WRITEBUFFER_SLINK_LEN;
682 /* Is the socket still open? A previous call to Conn_Write()
683 * may have closed the connection due to a fatal error.
684 * In this case it is sufficient to return an error, as well. */
685 if( My_Connections[Idx].sock <= NONE ) {
686 LogDebug("Skipped write on closed socket (connection %d).", Idx);
691 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
693 * Zip_Buffer() does all the dirty work for us: it flushes
694 * the (pre-)compression buffers if required and handles
695 * all error conditions. */
696 if (!Zip_Buffer(Idx, Data, Len))
702 /* Uncompressed link:
703 * Check if outbound buffer has enough space for the data. */
704 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
706 /* Buffer is full, flush it. Handle_Write deals with
707 * low-level errors, if any. */
708 if (!Handle_Write(Idx))
712 /* When the write buffer is still too big after flushing it,
713 * the connection will be killed. */
714 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
717 "Write buffer overflow (connection %d, size %lu byte)!",
719 (unsigned long)array_bytes(&My_Connections[Idx].wbuf));
720 Conn_Close(Idx, "Write buffer overflow!", NULL, false);
724 /* Copy data to write buffer */
725 if (!array_catb(&My_Connections[Idx].wbuf, Data, Len))
728 My_Connections[Idx].bytes_out += Len;
731 /* Adjust global write counter */
739 Conn_Close( CONN_ID Idx, char *LogMsg, char *FwdMsg, bool InformClient )
741 /* Close connection. Open pipes of asyncronous resolver
742 * sub-processes are closed down. */
749 double in_z_k, out_z_k;
753 assert( Idx > NONE );
755 /* Is this link already shutting down? */
756 if( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ISCLOSING )) {
757 /* Conn_Close() has been called recursively for this link;
758 * probabe reason: Handle_Write() failed -- see below. */
759 LogDebug("Recursive request to close connection: %d", Idx );
763 assert( My_Connections[Idx].sock > NONE );
765 /* Mark link as "closing" */
766 Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCLOSING );
773 txt = "Reason unknown";
775 port = ng_ipaddr_getport(&My_Connections[Idx].addr);
776 Log(LOG_INFO, "Shutting down connection %d (%s) with %s:%d ...", Idx,
777 LogMsg ? LogMsg : FwdMsg, My_Connections[Idx].host, port);
779 /* Search client, if any */
780 c = Conn_GetClient( Idx );
782 /* Should the client be informed? */
785 /* Send statistics to client if registered as user: */
786 if ((c != NULL) && (Client_Type(c) == CLIENT_USER)) {
788 ":%s NOTICE %s :%sConnection statistics: client %.1f kb, server %.1f kb.",
789 Client_ID(Client_ThisServer()), Client_ID(c),
791 (double)My_Connections[Idx].bytes_in / 1024,
792 (double)My_Connections[Idx].bytes_out / 1024);
795 /* Send ERROR to client (see RFC!) */
797 Conn_WriteStr(Idx, "ERROR :%s", FwdMsg);
799 Conn_WriteStr(Idx, "ERROR :Closing connection.");
802 /* Try to write out the write buffer. Note: Handle_Write() eventually
803 * removes the CLIENT structure associated with this connection if an
804 * error occurs! So we have to re-check if there is still an valid
805 * CLIENT structure after calling Handle_Write() ...*/
806 (void)Handle_Write( Idx );
808 /* Search client, if any (re-check!) */
809 c = Conn_GetClient( Idx );
811 /* Shut down socket */
812 if (! io_close(My_Connections[Idx].sock)) {
813 /* Oops, we can't close the socket!? This is ... ugly! */
815 "Error closing connection %d (socket %d) with %s:%d - %s! (ignored)",
816 Idx, My_Connections[Idx].sock, My_Connections[Idx].host,
817 port, strerror(errno));
820 /* Mark socket as invalid: */
821 My_Connections[Idx].sock = NONE;
823 /* If there is still a client, unregister it now */
825 Client_Destroy(c, LogMsg, FwdMsg, true);
827 /* Calculate statistics and log information */
828 in_k = (double)My_Connections[Idx].bytes_in / 1024;
829 out_k = (double)My_Connections[Idx].bytes_out / 1024;
831 if (Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP)) {
832 in_z_k = (double)My_Connections[Idx].zip.bytes_in / 1024;
833 out_z_k = (double)My_Connections[Idx].zip.bytes_out / 1024;
834 /* Make sure that no division by zero can occur during
835 * the calculation of in_p and out_p: in_z_k and out_z_k
836 * are non-zero, that's guaranteed by the protocol until
837 * compression can be enabled. */
842 in_p = (int)(( in_k * 100 ) / in_z_k );
843 out_p = (int)(( out_k * 100 ) / out_z_k );
845 "Connection %d with %s:%d closed (in: %.1fk/%.1fk/%d%%, out: %.1fk/%.1fk/%d%%).",
846 Idx, My_Connections[Idx].host, port,
847 in_k, in_z_k, in_p, out_k, out_z_k, out_p);
853 "Connection %d with %s:%d closed (in: %.1fk, out: %.1fk).",
854 Idx, My_Connections[Idx].host, port,
858 /* cancel running resolver */
859 if (Resolve_INPROGRESS(&My_Connections[Idx].res_stat))
860 Resolve_Shutdown(&My_Connections[Idx].res_stat);
862 /* Servers: Modify time of next connect attempt? */
863 Conf_UnsetServer( Idx );
866 /* Clean up zlib, if link was compressed */
867 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
868 inflateEnd( &My_Connections[Idx].zip.in );
869 deflateEnd( &My_Connections[Idx].zip.out );
870 array_free(&My_Connections[Idx].zip.rbuf);
871 array_free(&My_Connections[Idx].zip.wbuf);
875 array_free(&My_Connections[Idx].rbuf);
876 array_free(&My_Connections[Idx].wbuf);
878 /* Clean up connection structure (=free it) */
879 Init_Conn_Struct( Idx );
881 LogDebug("Shutdown of connection %d completed.", Idx );
886 Conn_SyncServerStruct( void )
888 /* Synchronize server structures (connection IDs):
889 * connections <-> configuration */
895 for( i = 0; i < Pool_Size; i++ ) {
896 /* Established connection? */
897 if (My_Connections[i].sock < 0)
900 /* Server connection? */
901 client = Conn_GetClient( i );
902 if(( ! client ) || ( Client_Type( client ) != CLIENT_SERVER )) continue;
904 for( c = 0; c < MAX_SERVERS; c++ )
906 /* Configured server? */
907 if( ! Conf_Server[c].host[0] ) continue;
910 if( strcmp( Conf_Server[c].name, Client_ID( client )) == 0 )
911 Conf_Server[c].conn_id = i;
914 } /* SyncServerStruct */
918 * Send out data of write buffer; connect new sockets.
921 Handle_Write( CONN_ID Idx )
926 assert( Idx > NONE );
927 if ( My_Connections[Idx].sock < 0 ) {
928 LogDebug("Handle_Write() on closed socket, connection %d", Idx);
931 assert( My_Connections[Idx].sock > NONE );
933 wdatalen = array_bytes(&My_Connections[Idx].wbuf );
937 /* Write buffer is empty, so we try to flush the compression
938 * buffer and get some data to work with from there :-) */
942 /* Now the write buffer most probably has changed: */
943 wdatalen = array_bytes(&My_Connections[Idx].wbuf);
948 /* Still no data, fine. */
949 io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
954 ("Handle_Write() called for connection %d, %ld bytes pending ...",
957 len = write(My_Connections[Idx].sock,
958 array_start(&My_Connections[Idx].wbuf), wdatalen );
961 if (errno == EAGAIN || errno == EINTR)
964 Log(LOG_ERR, "Write error on connection %d (socket %d): %s!",
965 Idx, My_Connections[Idx].sock, strerror(errno));
966 Conn_Close(Idx, "Write error!", NULL, false);
970 /* move any data not yet written to beginning */
971 array_moveleft(&My_Connections[Idx].wbuf, 1, (size_t)len);
978 Count_Connections(ng_ipaddr_t *a)
983 for (i = 0; i < Pool_Size; i++) {
984 if (My_Connections[i].sock <= NONE)
986 if (ng_ipaddr_ipequal(&My_Connections[i].addr, a))
990 } /* Count_Connections */
994 New_Connection( int Sock )
996 /* Neue Client-Verbindung von Listen-Socket annehmen und
997 * CLIENT-Struktur anlegen. */
1000 struct request_info req;
1002 ng_ipaddr_t new_addr;
1003 char ip_str[NG_INET_ADDRSTRLEN];
1004 int new_sock, new_sock_len, new_Pool_Size;
1008 assert( Sock > NONE );
1009 /* Connection auf Listen-Socket annehmen */
1010 new_sock_len = (int)sizeof(new_addr);
1012 new_sock = accept(Sock, (struct sockaddr *)&new_addr,
1013 (socklen_t *)&new_sock_len);
1015 Log(LOG_CRIT, "Can't accept connection: %s!", strerror(errno));
1019 if (!ng_ipaddr_tostr_r(&new_addr, ip_str)) {
1020 Log(LOG_CRIT, "fd %d: Can't convert IP address!", new_sock);
1021 Simple_Message(new_sock, "ERROR :Internal Server Error");
1026 /* Validate socket using TCP Wrappers */
1027 request_init( &req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock, RQ_CLIENT_SIN, &new_addr, NULL );
1029 if (!hosts_access(&req)) {
1030 Log (deny_severity, "Refused connection from %s (by TCP Wrappers)!", ip_str);
1031 Simple_Message( new_sock, "ERROR :Connection refused" );
1037 /* Socket initialisieren */
1038 if (!Init_Socket( new_sock ))
1041 /* Check IP-based connection limit */
1042 cnt = Count_Connections(&new_addr);
1043 if ((Conf_MaxConnectionsIP > 0) && (cnt >= Conf_MaxConnectionsIP)) {
1044 /* Access denied, too many connections from this IP address! */
1045 Log( LOG_ERR, "Refused connection from %s: too may connections (%ld) from this IP address!", ip_str, cnt);
1046 Simple_Message( new_sock, "ERROR :Connection refused, too many connections from your IP address!" );
1051 if( new_sock >= Pool_Size ) {
1052 new_Pool_Size = new_sock + 1;
1053 /* No free Connection Structures, check if we may accept further connections */
1054 if ((( Conf_MaxConnections > 0) && Pool_Size >= Conf_MaxConnections) ||
1055 (new_Pool_Size < Pool_Size))
1057 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached!", Pool_Size );
1058 Simple_Message( new_sock, "ERROR :Connection limit reached" );
1063 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION),
1064 (size_t)new_sock)) {
1065 Log( LOG_EMERG, "Can't allocate memory! [New_Connection]" );
1066 Simple_Message( new_sock, "ERROR: Internal error" );
1070 LogDebug("Bumped connection pool to %ld items (internal: %ld items, %ld bytes)",
1071 new_sock, array_length(&My_ConnArray, sizeof(CONNECTION)), array_bytes(&My_ConnArray));
1073 /* Adjust pointer to new block */
1074 My_Connections = array_start(&My_ConnArray);
1075 while (Pool_Size < new_Pool_Size)
1076 Init_Conn_Struct(Pool_Size++);
1079 /* register callback */
1080 if (!io_event_create( new_sock, IO_WANTREAD, cb_clientserver)) {
1081 Log(LOG_ALERT, "Can't accept connection: io_event_create failed!");
1082 Simple_Message(new_sock, "ERROR :Internal error");
1087 c = Client_NewLocal(new_sock, ip_str, CLIENT_UNKNOWN, false );
1089 Log(LOG_ALERT, "Can't accept connection: can't create client structure!");
1090 Simple_Message(new_sock, "ERROR :Internal error");
1095 Init_Conn_Struct( new_sock );
1096 My_Connections[new_sock].sock = new_sock;
1097 My_Connections[new_sock].addr = new_addr;
1098 My_Connections[new_sock].client = c;
1100 Log( LOG_INFO, "Accepted connection %d from %s:%d on socket %d.", new_sock,
1101 ip_str, ng_ipaddr_getport(&new_addr), Sock);
1103 /* Hostnamen ermitteln */
1104 strlcpy(My_Connections[new_sock].host, ip_str, sizeof(My_Connections[new_sock].host));
1106 Client_SetHostname(c, My_Connections[new_sock].host);
1109 Resolve_Addr(&My_Connections[new_sock].res_stat, &new_addr,
1110 My_Connections[new_sock].sock, cb_Read_Resolver_Result);
1112 Conn_SetPenalty(new_sock, 4);
1114 } /* New_Connection */
1118 Socket2Index( int Sock )
1120 /* zum Socket passende Connection suchen */
1122 assert( Sock >= 0 );
1124 if( Sock >= Pool_Size || My_Connections[Sock].sock != Sock ) {
1125 /* die Connection wurde vermutlich (wegen eines
1126 * Fehlers) bereits wieder abgebaut ... */
1127 LogDebug("Socket2Index: can't get connection for socket %d!", Sock);
1131 } /* Socket2Index */
1135 * Read data from the network to the read buffer. If an error occures,
1136 * the socket of this connection will be shut down.
1139 Read_Request( CONN_ID Idx )
1142 char readbuf[READBUFFER_LEN];
1144 assert( Idx > NONE );
1145 assert( My_Connections[Idx].sock > NONE );
1148 if ((array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN) ||
1149 (array_bytes(&My_Connections[Idx].zip.rbuf) >= READBUFFER_LEN))
1151 if (array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN)
1154 /* Read buffer is full */
1156 "Receive buffer overflow (connection %d): %d bytes!",
1157 Idx, array_bytes(&My_Connections[Idx].rbuf));
1158 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1162 len = read(My_Connections[Idx].sock, readbuf, sizeof(readbuf));
1164 Log(LOG_INFO, "%s:%u (%s) is closing the connection ...",
1165 My_Connections[Idx].host,
1166 (unsigned int) ng_ipaddr_getport(&My_Connections[Idx].addr),
1167 ng_ipaddr_tostr(&My_Connections[Idx].addr));
1169 "Socket closed!", "Client closed connection",
1175 if( errno == EAGAIN ) return;
1176 Log(LOG_ERR, "Read error on connection %d (socket %d): %s!",
1177 Idx, My_Connections[Idx].sock, strerror(errno));
1178 Conn_Close(Idx, "Read error!", "Client closed connection",
1183 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1184 if (!array_catb(&My_Connections[Idx].zip.rbuf, readbuf,
1187 "Could not append recieved data to zip input buffer (connn %d): %d bytes!",
1189 Conn_Close(Idx, "Receive buffer overflow!", NULL,
1196 if (!array_catb( &My_Connections[Idx].rbuf, readbuf, len)) {
1197 Log( LOG_ERR, "Could not append recieved data to input buffer (connn %d): %d bytes!", Idx, len );
1198 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1202 /* Update connection statistics */
1203 My_Connections[Idx].bytes_in += len;
1205 /* Update timestamp of last data received if this connection is
1206 * registered as a user, server or service connection. Don't update
1207 * otherwise, so users have at least Conf_PongTimeout seconds time to
1208 * register with the IRC server -- see Check_Connections().
1209 * Set "lastping", too, so we can handle time shifts backwards ... */
1210 c = Conn_GetClient(Idx);
1211 if (c && (Client_Type(c) == CLIENT_USER
1212 || Client_Type(c) == CLIENT_SERVER
1213 || Client_Type(c) == CLIENT_SERVICE)) {
1214 My_Connections[Idx].lastdata = time(NULL);
1215 My_Connections[Idx].lastping = My_Connections[Idx].lastdata;
1218 /* Look at the data in the (read-) buffer of this connection */
1220 } /* Read_Request */
1224 * Handle data in connection read-buffer.
1225 * @return true if a reuqest was handled, false otherwise (and on errors).
1228 Handle_Buffer(CONN_ID Idx)
1241 starttime = time(NULL);
1245 if (My_Connections[Idx].delaytime > starttime)
1248 /* Unpack compressed data, if compression is in use */
1249 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1250 if (!Unzip_Buffer(Idx))
1255 if (0 == array_bytes(&My_Connections[Idx].rbuf))
1258 /* Make sure that the buffer is NULL terminated */
1259 if (!array_cat0_temporary(&My_Connections[Idx].rbuf))
1262 /* RFC 2812, section "2.3 Messages", 5th paragraph:
1263 * "IRC messages are always lines of characters terminated
1264 * with a CR-LF (Carriage Return - Line Feed) pair [...]". */
1266 ptr = strstr(array_start(&My_Connections[Idx].rbuf), "\r\n");
1270 /* Check for non-RFC-compliant request (only CR or
1271 * LF)? Unfortunately, there are quite a few clients
1272 * out there that do this -- incl. "mIRC" :-( */
1274 ptr1 = strchr(array_start(&My_Connections[Idx].rbuf), '\r');
1275 ptr2 = strchr(array_start(&My_Connections[Idx].rbuf), '\n');
1277 ptr = ptr1 > ptr2 ? ptr2 : ptr1;
1288 /* Complete (=line terminated) request found, handle it! */
1291 len = ptr - (char *)array_start(&My_Connections[Idx].rbuf) + delta;
1293 if (len > (COMMAND_LEN - 1)) {
1294 /* Request must not exceed 512 chars (incl. CR+LF!),
1295 * see RFC 2812. Disconnect Client if this happens. */
1297 "Request too long (connection %d): %d bytes (max. %d expected)!",
1298 Idx, array_bytes(&My_Connections[Idx].rbuf),
1300 Conn_Close(Idx, NULL, "Request too long", true);
1305 /* Request is empty (only '\r\n', '\r' or '\n');
1306 * delta is 2 ('\r\n') or 1 ('\r' or '\n'), see above */
1307 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1312 /* remember if stream is already compressed */
1313 old_z = My_Connections[Idx].options & CONN_ZIP;
1316 My_Connections[Idx].msg_in++;
1318 (Idx, (char *)array_start(&My_Connections[Idx].rbuf)))
1323 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1324 LogDebug("Connection %d: %d bytes left in read buffer.",
1325 Idx, array_bytes(&My_Connections[Idx].rbuf));
1327 if ((!old_z) && (My_Connections[Idx].options & CONN_ZIP) &&
1328 (array_bytes(&My_Connections[Idx].rbuf) > 0)) {
1329 /* The last command activated socket compression.
1330 * Data that was read after that needs to be copied
1331 * to the unzip buffer for decompression: */
1333 (&My_Connections[Idx].zip.rbuf,
1334 &My_Connections[Idx].rbuf))
1337 array_trunc(&My_Connections[Idx].rbuf);
1339 ("Moved already received data (%u bytes) to uncompression buffer.",
1340 array_bytes(&My_Connections[Idx].zip.rbuf));
1345 } /* Handle_Buffer */
1349 Check_Connections(void)
1351 /* check if connections are alive. if not, play PING-PONG first.
1352 * if this doesn't help either, disconnect client. */
1356 for (i = 0; i < Pool_Size; i++) {
1357 if (My_Connections[i].sock < 0)
1360 c = Conn_GetClient(i);
1361 if (c && ((Client_Type(c) == CLIENT_USER)
1362 || (Client_Type(c) == CLIENT_SERVER)
1363 || (Client_Type(c) == CLIENT_SERVICE))) {
1364 /* connected User, Server or Service */
1365 if (My_Connections[i].lastping >
1366 My_Connections[i].lastdata) {
1367 /* We already sent a ping */
1368 if (My_Connections[i].lastping <
1369 time(NULL) - Conf_PongTimeout) {
1372 ("Connection %d: Ping timeout: %d seconds.",
1373 i, Conf_PongTimeout);
1374 Conn_Close(i, NULL, "Ping timeout",
1377 } else if (My_Connections[i].lastdata <
1378 time(NULL) - Conf_PingTimeout) {
1379 /* We need to send a PING ... */
1380 LogDebug("Connection %d: sending PING ...", i);
1381 My_Connections[i].lastping = time(NULL);
1382 Conn_WriteStr(i, "PING :%s",
1383 Client_ID(Client_ThisServer()));
1386 /* The connection is not fully established yet, so
1387 * we don't do the PING-PONG game here but instead
1388 * disconnect the client after "a short time" if it's
1389 * still not registered. */
1391 if (My_Connections[i].lastdata <
1392 time(NULL) - Conf_PongTimeout) {
1394 ("Unregistered connection %d timed out ...",
1396 Conn_Close(i, NULL, "Timeout", false);
1400 } /* Check_Connections */
1404 Check_Servers( void )
1406 /* Check if we can establish further server links */
1411 /* Check all configured servers */
1412 for( i = 0; i < MAX_SERVERS; i++ ) {
1413 /* Valid outgoing server which isn't already connected or disabled? */
1414 if(( ! Conf_Server[i].host[0] ) || ( ! Conf_Server[i].port > 0 ) ||
1415 ( Conf_Server[i].conn_id > NONE ) || ( Conf_Server[i].flags & CONF_SFLAG_DISABLED ))
1418 /* Is there already a connection in this group? */
1419 if( Conf_Server[i].group > NONE ) {
1420 for (n = 0; n < MAX_SERVERS; n++) {
1421 if (n == i) continue;
1422 if ((Conf_Server[n].conn_id != NONE) &&
1423 (Conf_Server[n].group == Conf_Server[i].group))
1426 if (n < MAX_SERVERS) continue;
1429 /* Check last connect attempt? */
1430 time_now = time(NULL);
1431 if( Conf_Server[i].lasttry > (time_now - Conf_ConnectRetry))
1434 /* Okay, try to connect now */
1435 Conf_Server[i].lasttry = time_now;
1436 Conf_Server[i].conn_id = SERVER_WAIT;
1437 assert(Resolve_Getfd(&Conf_Server[i].res_stat) < 0);
1438 Resolve_Name(&Conf_Server[i].res_stat, Conf_Server[i].host, cb_Connect_to_Server);
1440 } /* Check_Servers */
1444 New_Server( int Server , ng_ipaddr_t *dest)
1446 /* Establish new server link */
1447 char ip_str[NG_INET_ADDRSTRLEN];
1448 int af_dest, res, new_sock;
1451 assert( Server > NONE );
1453 if (!ng_ipaddr_tostr_r(dest, ip_str)) {
1454 Log(LOG_WARNING, "New_Server: Could not convert IP to string");
1458 Log( LOG_INFO, "Establishing connection to \"%s\", %s, port %d ... ",
1459 Conf_Server[Server].host, ip_str, Conf_Server[Server].port );
1461 af_dest = ng_ipaddr_af(dest);
1462 new_sock = socket(af_dest, SOCK_STREAM, 0);
1464 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
1468 if (!Init_Socket(new_sock))
1471 /* is a bind address configured? */
1472 res = ng_ipaddr_af(&Conf_Server[Server].bind_addr);
1473 /* if yes, bind now. If it fails, warn and let connect() pick a source address */
1474 if (res && bind(new_sock, (struct sockaddr *) &Conf_Server[Server].bind_addr,
1475 ng_ipaddr_salen(&Conf_Server[Server].bind_addr)))
1477 ng_ipaddr_tostr_r(&Conf_Server[Server].bind_addr, ip_str);
1478 Log(LOG_WARNING, "Can't bind socket to %s: %s!", ip_str, strerror(errno));
1480 ng_ipaddr_setport(dest, Conf_Server[Server].port);
1481 res = connect(new_sock, (struct sockaddr *) dest, ng_ipaddr_salen(dest));
1482 if(( res != 0 ) && ( errno != EINPROGRESS )) {
1483 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1488 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)new_sock)) {
1490 "Cannot allocate memory for server connection (socket %d)",
1496 My_Connections = array_start(&My_ConnArray);
1498 assert(My_Connections[new_sock].sock <= 0);
1500 Init_Conn_Struct(new_sock);
1502 ng_ipaddr_tostr_r(dest, ip_str);
1503 c = Client_NewLocal(new_sock, ip_str, CLIENT_UNKNOWNSERVER, false);
1505 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1510 Client_SetIntroducer( c, c );
1511 Client_SetToken( c, TOKEN_OUTBOUND );
1513 /* Register connection */
1514 Conf_Server[Server].conn_id = new_sock;
1515 My_Connections[new_sock].sock = new_sock;
1516 My_Connections[new_sock].addr = *dest;
1517 My_Connections[new_sock].client = c;
1518 strlcpy( My_Connections[new_sock].host, Conf_Server[Server].host,
1519 sizeof(My_Connections[new_sock].host ));
1521 /* Register new socket */
1522 if (!io_event_create( new_sock, IO_WANTWRITE, cb_connserver)) {
1523 Log( LOG_ALERT, "io_event_create(): could not add fd %d", strerror(errno));
1524 Conn_Close( new_sock, "io_event_create() failed", NULL, false );
1525 Init_Conn_Struct( new_sock );
1526 Conf_Server[Server].conn_id = NONE;
1529 LogDebug("Registered new connection %d on socket %d.",
1530 new_sock, My_Connections[new_sock].sock );
1531 Conn_OPTION_ADD( &My_Connections[new_sock], CONN_ISCONNECTING );
1536 * Initialize connection structure.
1539 Init_Conn_Struct(CONN_ID Idx)
1541 time_t now = time(NULL);
1543 memset(&My_Connections[Idx], 0, sizeof(CONNECTION));
1544 My_Connections[Idx].sock = -1;
1545 My_Connections[Idx].signon = now;
1546 My_Connections[Idx].lastdata = now;
1547 My_Connections[Idx].lastprivmsg = now;
1548 Resolve_Init(&My_Connections[Idx].res_stat);
1549 } /* Init_Conn_Struct */
1553 Init_Socket( int Sock )
1555 /* Initialize socket (set options) */
1559 if (!io_setnonblock(Sock)) {
1560 Log( LOG_CRIT, "Can't enable non-blocking mode for socket: %s!", strerror( errno ));
1565 /* Don't block this port after socket shutdown */
1567 if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &value, (socklen_t)sizeof( value )) != 0 )
1569 Log( LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!", strerror( errno ));
1570 /* ignore this error */
1573 /* Set type of service (TOS) */
1574 #if defined(IP_TOS) && defined(IPTOS_LOWDELAY)
1575 value = IPTOS_LOWDELAY;
1576 LogDebug("Setting option IP_TOS on socket %d to IPTOS_LOWDELAY (%d).", Sock, value );
1577 if( setsockopt( Sock, SOL_IP, IP_TOS, &value, (socklen_t)sizeof( value )) != 0 )
1579 Log( LOG_ERR, "Can't set socket option IP_TOS: %s!", strerror( errno ));
1580 /* ignore this error */
1590 cb_Connect_to_Server(int fd, UNUSED short events)
1592 /* Read result of resolver sub-process from pipe and start connection */
1595 ng_ipaddr_t dest_addrs[4]; /* we can handle at most 3; but we read up to
1596 four so we can log the 'more than we can handle'
1599 LogDebug("Resolver: Got forward lookup callback on fd %d, events %d", fd, events);
1601 for (i=0; i < MAX_SERVERS; i++) {
1602 if (Resolve_Getfd(&Conf_Server[i].res_stat) == fd )
1606 if( i >= MAX_SERVERS) {
1607 /* Ops, no matching server found?! */
1609 LogDebug("Resolver: Got Forward Lookup callback for unknown server!?");
1613 /* Read result from pipe */
1614 len = Resolve_Read(&Conf_Server[i].res_stat, dest_addrs, sizeof(dest_addrs));
1618 assert((len % sizeof(ng_ipaddr_t)) == 0);
1620 LogDebug("Got result from resolver: %u structs (%u bytes).", len/sizeof(ng_ipaddr_t), len);
1622 memset(&Conf_Server[i].dst_addr, 0, sizeof(&Conf_Server[i].dst_addr));
1623 if (len > sizeof(ng_ipaddr_t)) {
1624 /* more than one address for this hostname, remember them
1625 * in case first address is unreachable/not available */
1626 len -= sizeof(ng_ipaddr_t);
1627 if (len > sizeof(&Conf_Server[i].dst_addr)) {
1628 len = sizeof(&Conf_Server[i].dst_addr);
1629 Log(LOG_NOTICE, "Notice: Resolver returned more IP Addresses for host than we can handle,"
1630 " additional addresses dropped");
1632 memcpy(&Conf_Server[i].dst_addr, &dest_addrs[1], len);
1635 New_Server(i, dest_addrs);
1636 } /* cb_Read_Forward_Lookup */
1640 cb_Read_Resolver_Result( int r_fd, UNUSED short events )
1642 /* Read result of resolver sub-process from pipe and update the
1643 * apropriate connection/client structure(s): hostname and/or
1644 * IDENT user name.*/
1651 char readbuf[HOST_LEN + 2 + CLIENT_USER_LEN];
1653 char readbuf[HOST_LEN + 1];
1656 LogDebug("Resolver: Got callback on fd %d, events %d", r_fd, events );
1658 /* Search associated connection ... */
1659 for( i = 0; i < Pool_Size; i++ ) {
1660 if(( My_Connections[i].sock != NONE )
1661 && ( Resolve_Getfd(&My_Connections[i].res_stat) == r_fd ))
1664 if( i >= Pool_Size ) {
1665 /* Ops, none found? Probably the connection has already
1666 * been closed!? We'll ignore that ... */
1668 LogDebug("Resolver: Got callback for unknown connection!?");
1672 /* Read result from pipe */
1673 len = Resolve_Read(&My_Connections[i].res_stat, readbuf, sizeof readbuf -1);
1677 readbuf[len] = '\0';
1678 identptr = strchr(readbuf, '\n');
1679 assert(identptr != NULL);
1681 Log( LOG_CRIT, "Resolver: Got malformed result!");
1686 LogDebug("Got result from resolver: \"%s\" (%u bytes read).", readbuf, len);
1687 /* Okay, we got a complete result: this is a host name for outgoing
1688 * connections and a host name and IDENT user name (if enabled) for
1689 * incoming connections.*/
1690 assert ( My_Connections[i].sock >= 0 );
1691 /* Incoming connection. Search client ... */
1692 c = Conn_GetClient( i );
1693 assert( c != NULL );
1695 /* Only update client information of unregistered clients */
1696 if( Client_Type( c ) == CLIENT_UNKNOWN ) {
1697 strlcpy(My_Connections[i].host, readbuf, sizeof( My_Connections[i].host));
1698 Client_SetHostname( c, readbuf);
1702 Log(LOG_INFO, "IDENT lookup for connection %d: \"%s\".", i, identptr);
1703 Client_SetUser(c, identptr, true);
1705 Log(LOG_INFO, "IDENT lookup for connection %d: no result.", i);
1710 else Log( LOG_DEBUG, "Resolver: discarding result for already registered connection %d.", i );
1712 /* Reset penalty time */
1713 Conn_ResetPenalty( i );
1714 } /* cb_Read_Resolver_Result */
1718 Simple_Message( int Sock, const char *Msg )
1720 char buf[COMMAND_LEN];
1722 /* Write "simple" message to socket, without using compression
1723 * or even the connection write buffers. Used e.g. for error
1724 * messages by New_Connection(). */
1725 assert( Sock > NONE );
1726 assert( Msg != NULL );
1728 strlcpy( buf, Msg, sizeof buf - 2);
1729 len = strlcat( buf, "\r\n", sizeof buf);
1730 (void)write(Sock, buf, len);
1731 } /* Simple_Error */
1735 Conn_GetClient( CONN_ID Idx )
1737 /* return Client-Structure that belongs to the local Connection Idx.
1738 * If none is found, return NULL.
1743 c = array_get(&My_ConnArray, sizeof (CONNECTION), (size_t)Idx);
1747 return c ? c->client : NULL;