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(( const char *listen_addr, 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, const char *listen_addr, void (*func)(int,short))
277 unsigned int created = 0;
282 len = array_length(a, sizeof (UINT16));
283 port = array_start(a);
285 fd = NewListener(listen_addr, *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));
305 Conn_InitListeners( void )
307 /* Initialize ports on which the server should accept connections */
308 unsigned int created = 0;
309 char *copy, *listen_addr;
311 if (!io_library_init(CONNECTION_POOL)) {
312 Log(LOG_EMERG, "Cannot initialize IO routines: %s", strerror(errno));
316 assert(Conf_ListenAddress);
318 /* can't use Conf_ListenAddress directly, see below */
319 copy = strdup(Conf_ListenAddress);
321 Log(LOG_CRIT, "Cannot copy %s: %s", Conf_ListenAddress, strerror(errno));
324 listen_addr = strtok(copy, ",");
326 while (listen_addr) {
327 ngt_TrimStr(listen_addr);
329 created += ports_initlisteners(&Conf_ListenPorts, listen_addr, cb_listen);
331 listen_addr = strtok(NULL, ",");
335 * can't free() Conf_ListenAddress here. On /REHASH, if the config file
336 * cannot be re-loaded, we'd end up with a NULL Conf_ListenAddress.
337 * Instead, free() takes place in conf.c, before the config file
342 } /* Conn_InitListeners */
346 Conn_ExitListeners( void )
348 /* Close down all listening sockets */
352 Rendezvous_UnregisterListeners( );
355 arraylen = array_length(&My_Listeners, sizeof (int));
356 Log( LOG_INFO, "Shutting down all listening sockets (%d total)...", arraylen );
357 fd = array_start(&My_Listeners);
362 LogDebug("Listening socket %d closed.", *fd );
365 array_free(&My_Listeners);
366 } /* Conn_ExitListeners */
370 InitSinaddrListenAddr(ng_ipaddr_t *addr, const char *listen_addrstr, UINT16 Port)
374 ret = ng_ipaddr_init(addr, listen_addrstr, Port);
376 assert(listen_addrstr);
377 Log(LOG_CRIT, "Can't bind to [%s]:%u: can't convert ip address \"%s\"",
378 listen_addrstr, Port, listen_addrstr);
385 set_v6_only(int af, int sock)
387 #if defined(IPV6_V6ONLY) && defined(WANT_IPV6)
393 if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)))
394 Log(LOG_ERR, "Could not set IPV6_V6ONLY: %s", strerror(errno));
402 /* return new listening port file descriptor or -1 on failure */
404 NewListener(const char *listen_addr, UINT16 Port)
406 /* Create new listening socket on specified port */
410 char name[CLIENT_ID_LEN], *info;
412 if (!InitSinaddrListenAddr(&addr, listen_addr, Port))
415 af = ng_ipaddr_af(&addr);
416 sock = socket(af, SOCK_STREAM, 0);
418 Log(LOG_CRIT, "Can't create socket (af %d) : %s!", af, strerror(errno));
422 set_v6_only(af, sock);
424 if (!Init_Socket(sock))
427 if (bind(sock, (struct sockaddr *)&addr, ng_ipaddr_salen(&addr)) != 0) {
428 Log(LOG_CRIT, "Can't bind socket to address %s:%d - %s",
429 ng_ipaddr_tostr(&addr), Port, strerror(errno));
434 if( listen( sock, 10 ) != 0 ) {
435 Log( LOG_CRIT, "Can't listen on socket: %s!", strerror( errno ));
440 /* keep fd in list so we can close it when ngircd restarts/shuts down */
441 if (!array_catb( &My_Listeners,(char*) &sock, sizeof(int) )) {
442 Log( LOG_CRIT, "Can't add socket to My_Listeners array: %s!", strerror( errno ));
447 Log(LOG_INFO, "Now listening on [%s]:%d (socket %d).", ng_ipaddr_tostr(&addr), Port, sock);
450 /* Get best server description text */
451 if( ! Conf_ServerInfo[0] ) info = Conf_ServerName;
454 /* Use server info string */
456 if( Conf_ServerInfo[0] == '[' )
458 /* Cut off leading hostname part in "[]" */
459 info = strchr( Conf_ServerInfo, ']' );
463 while( *info == ' ' ) info++;
466 if( ! info ) info = Conf_ServerInfo;
469 /* Add port number to description if non-standard */
471 snprintf(name, sizeof name, "%s (port %u)", info,
474 strlcpy(name, info, sizeof name);
476 /* Register service */
477 Rendezvous_Register( name, MDNS_TYPE, Port );
486 /* "Main Loop.": Loop until a signal (for shutdown or restart) arrives.
487 * Call io_dispatch() to check for read/writeable sockets every second
488 * Wait for status change on pending connections (e.g: when the hostname has been resolved)
489 * check for penalty/timeouts
490 * handle input buffers
493 unsigned int wdatalen;
498 while(( ! NGIRCd_SignalQuit ) && ( ! NGIRCd_SignalRestart )) {
502 Rendezvous_Handler( );
505 /* Should the configuration be reloaded? */
506 if (NGIRCd_SignalRehash) {
510 /* Check configured servers and established links */
512 Check_Connections( );
516 /* noch volle Lese-Buffer suchen */
517 for( i = 0; i < Pool_Size; i++ ) {
518 if(( My_Connections[i].sock > NONE ) && ( array_bytes(&My_Connections[i].rbuf) > 0 ) &&
519 ( My_Connections[i].delaytime < t ))
521 /* Kann aus dem Buffer noch ein Befehl extrahiert werden? */
522 if (Handle_Buffer( i )) timeout = false;
526 /* noch volle Schreib-Puffer suchen */
527 for( i = 0; i < Pool_Size; i++ ) {
528 if ( My_Connections[i].sock <= NONE )
531 wdatalen = (unsigned int)array_bytes(&My_Connections[i].wbuf);
534 if (( wdatalen > 0 ) || ( array_bytes(&My_Connections[i].zip.wbuf)> 0 ))
539 /* Socket der Verbindung in Set aufnehmen */
540 io_event_add( My_Connections[i].sock, IO_WANTWRITE );
544 /* von welchen Sockets koennte gelesen werden? */
545 for (i = 0; i < Pool_Size; i++ ) {
546 if ( My_Connections[i].sock <= NONE )
549 if (Resolve_INPROGRESS(&My_Connections[i].res_stat)) {
550 /* wait for completion of Resolver Sub-Process */
551 io_event_del( My_Connections[i].sock, IO_WANTREAD );
555 if ( Conn_OPTION_ISSET( &My_Connections[i], CONN_ISCONNECTING ))
556 continue; /* wait for completion of connect() */
558 if( My_Connections[i].delaytime > t ) {
559 /* Fuer die Verbindung ist eine "Penalty-Zeit" gesetzt */
560 io_event_del( My_Connections[i].sock, IO_WANTREAD );
563 io_event_add( My_Connections[i].sock, IO_WANTREAD );
566 /* (re-)set timeout - tv_sec/usec are undefined after io_dispatch() returns */
568 tv.tv_sec = timeout ? 1 : 0;
570 /* wait for activity */
571 i = io_dispatch( &tv );
572 if (i == -1 && errno != EINTR ) {
573 Log(LOG_EMERG, "Conn_Handler(): io_dispatch(): %s!", strerror(errno));
574 Log(LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE_NAME);
579 if( NGIRCd_SignalQuit ) Log( LOG_NOTICE|LOG_snotice, "Server going down NOW!" );
580 else if( NGIRCd_SignalRestart ) Log( LOG_NOTICE|LOG_snotice, "Server restarting NOW!" );
585 * Write a text string into the socket of a connection.
586 * This function automatically appends CR+LF to the string and validates that
587 * the result is a valid IRC message (oversized messages are shortened, for
588 * example). Then it calls the Conn_Write() function to do the actual sending.
589 * @param Idx Index fo the connection.
590 * @param Format Format string, see printf().
591 * @return true on success, false otherwise.
595 Conn_WriteStr( CONN_ID Idx, char *Format, ... )
598 Conn_WriteStr( Idx, Format, va_alist )
604 char buffer[COMMAND_LEN];
609 assert( Idx > NONE );
610 assert( Format != NULL );
613 va_start( ap, Format );
617 if (vsnprintf( buffer, COMMAND_LEN - 2, Format, ap ) >= COMMAND_LEN - 2 ) {
619 * The string that should be written to the socket is longer
620 * than the allowed size of COMMAND_LEN bytes (including both
621 * the CR and LF characters). This can be caused by the
622 * IRC_WriteXXX() functions when the prefix of this server had
623 * to be added to an already "quite long" command line which
624 * has been received from a regular IRC client, for example.
626 * We are not allowed to send such "oversized" messages to
627 * other servers and clients, see RFC 2812 2.3 and 2813 3.3
628 * ("these messages SHALL NOT exceed 512 characters in length,
629 * counting all characters including the trailing CR-LF").
631 * So we have a big problem here: we should send more bytes
632 * to the network than we are allowed to and we don't know
633 * the originator (any more). The "old" behaviour of blaming
634 * the receiver ("next hop") is a bad idea (it could be just
635 * an other server only routing the message!), so the only
636 * option left is to shorten the string and to hope that the
637 * result is still somewhat useful ...
641 strcpy (buffer + sizeof(buffer) - strlen(CUT_TXTSUFFIX) - 2 - 1,
647 Log(LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer);
650 len = strlcat( buffer, "\r\n", sizeof( buffer ));
651 ok = Conn_Write(Idx, buffer, len);
652 My_Connections[Idx].msg_out++;
656 } /* Conn_WriteStr */
660 * Append Data to the outbound write buffer of a connection.
661 * @param Idx Index of the connection.
662 * @param Data pointer to the data.
663 * @param Len length of Data.
664 * @return true on success, false otherwise.
667 Conn_Write( CONN_ID Idx, char *Data, size_t Len )
670 size_t writebuf_limit = WRITEBUFFER_LEN;
671 assert( Idx > NONE );
672 assert( Data != NULL );
675 c = Conn_GetClient(Idx);
678 /* Servers do get special write buffer limits, so they can generate
679 * all the messages that are required while peering. */
680 if (Client_Type(c) == CLIENT_SERVER)
681 writebuf_limit = WRITEBUFFER_SLINK_LEN;
683 /* Is the socket still open? A previous call to Conn_Write()
684 * may have closed the connection due to a fatal error.
685 * In this case it is sufficient to return an error, as well. */
686 if( My_Connections[Idx].sock <= NONE ) {
687 LogDebug("Skipped write on closed socket (connection %d).", Idx);
692 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
694 * Zip_Buffer() does all the dirty work for us: it flushes
695 * the (pre-)compression buffers if required and handles
696 * all error conditions. */
697 if (!Zip_Buffer(Idx, Data, Len))
703 /* Uncompressed link:
704 * Check if outbound buffer has enough space for the data. */
705 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
707 /* Buffer is full, flush it. Handle_Write deals with
708 * low-level errors, if any. */
709 if (!Handle_Write(Idx))
713 /* When the write buffer is still too big after flushing it,
714 * the connection will be killed. */
715 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
718 "Write buffer overflow (connection %d, size %lu byte)!",
720 (unsigned long)array_bytes(&My_Connections[Idx].wbuf));
721 Conn_Close(Idx, "Write buffer overflow!", NULL, false);
725 /* Copy data to write buffer */
726 if (!array_catb(&My_Connections[Idx].wbuf, Data, Len))
729 My_Connections[Idx].bytes_out += Len;
732 /* Adjust global write counter */
740 Conn_Close( CONN_ID Idx, char *LogMsg, char *FwdMsg, bool InformClient )
742 /* Close connection. Open pipes of asyncronous resolver
743 * sub-processes are closed down. */
750 double in_z_k, out_z_k;
754 assert( Idx > NONE );
756 /* Is this link already shutting down? */
757 if( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ISCLOSING )) {
758 /* Conn_Close() has been called recursively for this link;
759 * probabe reason: Handle_Write() failed -- see below. */
760 LogDebug("Recursive request to close connection: %d", Idx );
764 assert( My_Connections[Idx].sock > NONE );
766 /* Mark link as "closing" */
767 Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCLOSING );
774 txt = "Reason unknown";
776 port = ng_ipaddr_getport(&My_Connections[Idx].addr);
777 Log(LOG_INFO, "Shutting down connection %d (%s) with %s:%d ...", Idx,
778 LogMsg ? LogMsg : FwdMsg, My_Connections[Idx].host, port);
780 /* Search client, if any */
781 c = Conn_GetClient( Idx );
783 /* Should the client be informed? */
786 /* Send statistics to client if registered as user: */
787 if ((c != NULL) && (Client_Type(c) == CLIENT_USER)) {
789 ":%s NOTICE %s :%sConnection statistics: client %.1f kb, server %.1f kb.",
790 Client_ID(Client_ThisServer()), Client_ID(c),
792 (double)My_Connections[Idx].bytes_in / 1024,
793 (double)My_Connections[Idx].bytes_out / 1024);
796 /* Send ERROR to client (see RFC!) */
798 Conn_WriteStr(Idx, "ERROR :%s", FwdMsg);
800 Conn_WriteStr(Idx, "ERROR :Closing connection.");
803 /* Try to write out the write buffer. Note: Handle_Write() eventually
804 * removes the CLIENT structure associated with this connection if an
805 * error occurs! So we have to re-check if there is still an valid
806 * CLIENT structure after calling Handle_Write() ...*/
807 (void)Handle_Write( Idx );
809 /* Search client, if any (re-check!) */
810 c = Conn_GetClient( Idx );
812 /* Shut down socket */
813 if (! io_close(My_Connections[Idx].sock)) {
814 /* Oops, we can't close the socket!? This is ... ugly! */
816 "Error closing connection %d (socket %d) with %s:%d - %s! (ignored)",
817 Idx, My_Connections[Idx].sock, My_Connections[Idx].host,
818 port, strerror(errno));
821 /* Mark socket as invalid: */
822 My_Connections[Idx].sock = NONE;
824 /* If there is still a client, unregister it now */
826 Client_Destroy(c, LogMsg, FwdMsg, true);
828 /* Calculate statistics and log information */
829 in_k = (double)My_Connections[Idx].bytes_in / 1024;
830 out_k = (double)My_Connections[Idx].bytes_out / 1024;
832 if (Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP)) {
833 in_z_k = (double)My_Connections[Idx].zip.bytes_in / 1024;
834 out_z_k = (double)My_Connections[Idx].zip.bytes_out / 1024;
835 /* Make sure that no division by zero can occur during
836 * the calculation of in_p and out_p: in_z_k and out_z_k
837 * are non-zero, that's guaranteed by the protocol until
838 * compression can be enabled. */
843 in_p = (int)(( in_k * 100 ) / in_z_k );
844 out_p = (int)(( out_k * 100 ) / out_z_k );
846 "Connection %d with %s:%d closed (in: %.1fk/%.1fk/%d%%, out: %.1fk/%.1fk/%d%%).",
847 Idx, My_Connections[Idx].host, port,
848 in_k, in_z_k, in_p, out_k, out_z_k, out_p);
854 "Connection %d with %s:%d closed (in: %.1fk, out: %.1fk).",
855 Idx, My_Connections[Idx].host, port,
859 /* cancel running resolver */
860 if (Resolve_INPROGRESS(&My_Connections[Idx].res_stat))
861 Resolve_Shutdown(&My_Connections[Idx].res_stat);
863 /* Servers: Modify time of next connect attempt? */
864 Conf_UnsetServer( Idx );
867 /* Clean up zlib, if link was compressed */
868 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
869 inflateEnd( &My_Connections[Idx].zip.in );
870 deflateEnd( &My_Connections[Idx].zip.out );
871 array_free(&My_Connections[Idx].zip.rbuf);
872 array_free(&My_Connections[Idx].zip.wbuf);
876 array_free(&My_Connections[Idx].rbuf);
877 array_free(&My_Connections[Idx].wbuf);
879 /* Clean up connection structure (=free it) */
880 Init_Conn_Struct( Idx );
882 LogDebug("Shutdown of connection %d completed.", Idx );
887 Conn_SyncServerStruct( void )
889 /* Synchronize server structures (connection IDs):
890 * connections <-> configuration */
896 for( i = 0; i < Pool_Size; i++ ) {
897 /* Established connection? */
898 if (My_Connections[i].sock < 0)
901 /* Server connection? */
902 client = Conn_GetClient( i );
903 if(( ! client ) || ( Client_Type( client ) != CLIENT_SERVER )) continue;
905 for( c = 0; c < MAX_SERVERS; c++ )
907 /* Configured server? */
908 if( ! Conf_Server[c].host[0] ) continue;
911 if( strcmp( Conf_Server[c].name, Client_ID( client )) == 0 )
912 Conf_Server[c].conn_id = i;
915 } /* SyncServerStruct */
919 * Send out data of write buffer; connect new sockets.
922 Handle_Write( CONN_ID Idx )
927 assert( Idx > NONE );
928 if ( My_Connections[Idx].sock < 0 ) {
929 LogDebug("Handle_Write() on closed socket, connection %d", Idx);
932 assert( My_Connections[Idx].sock > NONE );
934 wdatalen = array_bytes(&My_Connections[Idx].wbuf );
938 /* Write buffer is empty, so we try to flush the compression
939 * buffer and get some data to work with from there :-) */
943 /* Now the write buffer most probably has changed: */
944 wdatalen = array_bytes(&My_Connections[Idx].wbuf);
949 /* Still no data, fine. */
950 io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
955 ("Handle_Write() called for connection %d, %ld bytes pending ...",
958 len = write(My_Connections[Idx].sock,
959 array_start(&My_Connections[Idx].wbuf), wdatalen );
962 if (errno == EAGAIN || errno == EINTR)
965 Log(LOG_ERR, "Write error on connection %d (socket %d): %s!",
966 Idx, My_Connections[Idx].sock, strerror(errno));
967 Conn_Close(Idx, "Write error!", NULL, false);
971 /* move any data not yet written to beginning */
972 array_moveleft(&My_Connections[Idx].wbuf, 1, (size_t)len);
979 Count_Connections(ng_ipaddr_t *a)
984 for (i = 0; i < Pool_Size; i++) {
985 if (My_Connections[i].sock <= NONE)
987 if (ng_ipaddr_ipequal(&My_Connections[i].addr, a))
991 } /* Count_Connections */
995 New_Connection( int Sock )
997 /* Neue Client-Verbindung von Listen-Socket annehmen und
998 * CLIENT-Struktur anlegen. */
1001 struct request_info req;
1003 ng_ipaddr_t new_addr;
1004 char ip_str[NG_INET_ADDRSTRLEN];
1005 int new_sock, new_sock_len, new_Pool_Size;
1009 assert( Sock > NONE );
1010 /* Connection auf Listen-Socket annehmen */
1011 new_sock_len = (int)sizeof(new_addr);
1013 new_sock = accept(Sock, (struct sockaddr *)&new_addr,
1014 (socklen_t *)&new_sock_len);
1016 Log(LOG_CRIT, "Can't accept connection: %s!", strerror(errno));
1020 if (!ng_ipaddr_tostr_r(&new_addr, ip_str)) {
1021 Log(LOG_CRIT, "fd %d: Can't convert IP address!", new_sock);
1022 Simple_Message(new_sock, "ERROR :Internal Server Error");
1027 /* Validate socket using TCP Wrappers */
1028 request_init( &req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock, RQ_CLIENT_SIN, &new_addr, NULL );
1030 if (!hosts_access(&req)) {
1031 Log (deny_severity, "Refused connection from %s (by TCP Wrappers)!", ip_str);
1032 Simple_Message( new_sock, "ERROR :Connection refused" );
1038 /* Socket initialisieren */
1039 if (!Init_Socket( new_sock ))
1042 /* Check IP-based connection limit */
1043 cnt = Count_Connections(&new_addr);
1044 if ((Conf_MaxConnectionsIP > 0) && (cnt >= Conf_MaxConnectionsIP)) {
1045 /* Access denied, too many connections from this IP address! */
1046 Log( LOG_ERR, "Refused connection from %s: too may connections (%ld) from this IP address!", ip_str, cnt);
1047 Simple_Message( new_sock, "ERROR :Connection refused, too many connections from your IP address!" );
1052 if( new_sock >= Pool_Size ) {
1053 new_Pool_Size = new_sock + 1;
1054 /* No free Connection Structures, check if we may accept further connections */
1055 if ((( Conf_MaxConnections > 0) && Pool_Size >= Conf_MaxConnections) ||
1056 (new_Pool_Size < Pool_Size))
1058 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached!", Pool_Size );
1059 Simple_Message( new_sock, "ERROR :Connection limit reached" );
1064 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION),
1065 (size_t)new_sock)) {
1066 Log( LOG_EMERG, "Can't allocate memory! [New_Connection]" );
1067 Simple_Message( new_sock, "ERROR: Internal error" );
1071 LogDebug("Bumped connection pool to %ld items (internal: %ld items, %ld bytes)",
1072 new_sock, array_length(&My_ConnArray, sizeof(CONNECTION)), array_bytes(&My_ConnArray));
1074 /* Adjust pointer to new block */
1075 My_Connections = array_start(&My_ConnArray);
1076 while (Pool_Size < new_Pool_Size)
1077 Init_Conn_Struct(Pool_Size++);
1080 /* register callback */
1081 if (!io_event_create( new_sock, IO_WANTREAD, cb_clientserver)) {
1082 Log(LOG_ALERT, "Can't accept connection: io_event_create failed!");
1083 Simple_Message(new_sock, "ERROR :Internal error");
1088 c = Client_NewLocal(new_sock, ip_str, CLIENT_UNKNOWN, false );
1090 Log(LOG_ALERT, "Can't accept connection: can't create client structure!");
1091 Simple_Message(new_sock, "ERROR :Internal error");
1096 Init_Conn_Struct( new_sock );
1097 My_Connections[new_sock].sock = new_sock;
1098 My_Connections[new_sock].addr = new_addr;
1099 My_Connections[new_sock].client = c;
1101 Log( LOG_INFO, "Accepted connection %d from %s:%d on socket %d.", new_sock,
1102 ip_str, ng_ipaddr_getport(&new_addr), Sock);
1104 /* Hostnamen ermitteln */
1105 strlcpy(My_Connections[new_sock].host, ip_str, sizeof(My_Connections[new_sock].host));
1107 Client_SetHostname(c, My_Connections[new_sock].host);
1110 Resolve_Addr(&My_Connections[new_sock].res_stat, &new_addr,
1111 My_Connections[new_sock].sock, cb_Read_Resolver_Result);
1113 Conn_SetPenalty(new_sock, 4);
1115 } /* New_Connection */
1119 Socket2Index( int Sock )
1121 /* zum Socket passende Connection suchen */
1123 assert( Sock >= 0 );
1125 if( Sock >= Pool_Size || My_Connections[Sock].sock != Sock ) {
1126 /* die Connection wurde vermutlich (wegen eines
1127 * Fehlers) bereits wieder abgebaut ... */
1128 LogDebug("Socket2Index: can't get connection for socket %d!", Sock);
1132 } /* Socket2Index */
1136 * Read data from the network to the read buffer. If an error occures,
1137 * the socket of this connection will be shut down.
1140 Read_Request( CONN_ID Idx )
1143 char readbuf[READBUFFER_LEN];
1145 assert( Idx > NONE );
1146 assert( My_Connections[Idx].sock > NONE );
1149 if ((array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN) ||
1150 (array_bytes(&My_Connections[Idx].zip.rbuf) >= READBUFFER_LEN))
1152 if (array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN)
1155 /* Read buffer is full */
1157 "Receive buffer overflow (connection %d): %d bytes!",
1158 Idx, array_bytes(&My_Connections[Idx].rbuf));
1159 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1163 len = read(My_Connections[Idx].sock, readbuf, sizeof(readbuf));
1165 Log(LOG_INFO, "%s:%u (%s) is closing the connection ...",
1166 My_Connections[Idx].host,
1167 (unsigned int) ng_ipaddr_getport(&My_Connections[Idx].addr),
1168 ng_ipaddr_tostr(&My_Connections[Idx].addr));
1170 "Socket closed!", "Client closed connection",
1176 if( errno == EAGAIN ) return;
1177 Log(LOG_ERR, "Read error on connection %d (socket %d): %s!",
1178 Idx, My_Connections[Idx].sock, strerror(errno));
1179 Conn_Close(Idx, "Read error!", "Client closed connection",
1184 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1185 if (!array_catb(&My_Connections[Idx].zip.rbuf, readbuf,
1188 "Could not append recieved data to zip input buffer (connn %d): %d bytes!",
1190 Conn_Close(Idx, "Receive buffer overflow!", NULL,
1197 if (!array_catb( &My_Connections[Idx].rbuf, readbuf, len)) {
1198 Log( LOG_ERR, "Could not append recieved data to input buffer (connn %d): %d bytes!", Idx, len );
1199 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1203 /* Update connection statistics */
1204 My_Connections[Idx].bytes_in += len;
1206 /* Update timestamp of last data received if this connection is
1207 * registered as a user, server or service connection. Don't update
1208 * otherwise, so users have at least Conf_PongTimeout seconds time to
1209 * register with the IRC server -- see Check_Connections().
1210 * Set "lastping", too, so we can handle time shifts backwards ... */
1211 c = Conn_GetClient(Idx);
1212 if (c && (Client_Type(c) == CLIENT_USER
1213 || Client_Type(c) == CLIENT_SERVER
1214 || Client_Type(c) == CLIENT_SERVICE)) {
1215 My_Connections[Idx].lastdata = time(NULL);
1216 My_Connections[Idx].lastping = My_Connections[Idx].lastdata;
1219 /* Look at the data in the (read-) buffer of this connection */
1221 } /* Read_Request */
1225 * Handle data in connection read-buffer.
1226 * @return true if a reuqest was handled, false otherwise (and on errors).
1229 Handle_Buffer(CONN_ID Idx)
1242 starttime = time(NULL);
1246 if (My_Connections[Idx].delaytime > starttime)
1249 /* Unpack compressed data, if compression is in use */
1250 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1251 if (!Unzip_Buffer(Idx))
1256 if (0 == array_bytes(&My_Connections[Idx].rbuf))
1259 /* Make sure that the buffer is NULL terminated */
1260 if (!array_cat0_temporary(&My_Connections[Idx].rbuf))
1263 /* RFC 2812, section "2.3 Messages", 5th paragraph:
1264 * "IRC messages are always lines of characters terminated
1265 * with a CR-LF (Carriage Return - Line Feed) pair [...]". */
1267 ptr = strstr(array_start(&My_Connections[Idx].rbuf), "\r\n");
1271 /* Check for non-RFC-compliant request (only CR or
1272 * LF)? Unfortunately, there are quite a few clients
1273 * out there that do this -- incl. "mIRC" :-( */
1275 ptr1 = strchr(array_start(&My_Connections[Idx].rbuf), '\r');
1276 ptr2 = strchr(array_start(&My_Connections[Idx].rbuf), '\n');
1278 ptr = ptr1 > ptr2 ? ptr2 : ptr1;
1289 /* Complete (=line terminated) request found, handle it! */
1292 len = ptr - (char *)array_start(&My_Connections[Idx].rbuf) + delta;
1294 if (len > (COMMAND_LEN - 1)) {
1295 /* Request must not exceed 512 chars (incl. CR+LF!),
1296 * see RFC 2812. Disconnect Client if this happens. */
1298 "Request too long (connection %d): %d bytes (max. %d expected)!",
1299 Idx, array_bytes(&My_Connections[Idx].rbuf),
1301 Conn_Close(Idx, NULL, "Request too long", true);
1306 /* Request is empty (only '\r\n', '\r' or '\n');
1307 * delta is 2 ('\r\n') or 1 ('\r' or '\n'), see above */
1308 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1313 /* remember if stream is already compressed */
1314 old_z = My_Connections[Idx].options & CONN_ZIP;
1317 My_Connections[Idx].msg_in++;
1319 (Idx, (char *)array_start(&My_Connections[Idx].rbuf)))
1324 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1325 LogDebug("Connection %d: %d bytes left in read buffer.",
1326 Idx, array_bytes(&My_Connections[Idx].rbuf));
1328 if ((!old_z) && (My_Connections[Idx].options & CONN_ZIP) &&
1329 (array_bytes(&My_Connections[Idx].rbuf) > 0)) {
1330 /* The last command activated socket compression.
1331 * Data that was read after that needs to be copied
1332 * to the unzip buffer for decompression: */
1334 (&My_Connections[Idx].zip.rbuf,
1335 &My_Connections[Idx].rbuf))
1338 array_trunc(&My_Connections[Idx].rbuf);
1340 ("Moved already received data (%u bytes) to uncompression buffer.",
1341 array_bytes(&My_Connections[Idx].zip.rbuf));
1346 } /* Handle_Buffer */
1350 Check_Connections(void)
1352 /* check if connections are alive. if not, play PING-PONG first.
1353 * if this doesn't help either, disconnect client. */
1357 for (i = 0; i < Pool_Size; i++) {
1358 if (My_Connections[i].sock < 0)
1361 c = Conn_GetClient(i);
1362 if (c && ((Client_Type(c) == CLIENT_USER)
1363 || (Client_Type(c) == CLIENT_SERVER)
1364 || (Client_Type(c) == CLIENT_SERVICE))) {
1365 /* connected User, Server or Service */
1366 if (My_Connections[i].lastping >
1367 My_Connections[i].lastdata) {
1368 /* We already sent a ping */
1369 if (My_Connections[i].lastping <
1370 time(NULL) - Conf_PongTimeout) {
1373 ("Connection %d: Ping timeout: %d seconds.",
1374 i, Conf_PongTimeout);
1375 Conn_Close(i, NULL, "Ping timeout",
1378 } else if (My_Connections[i].lastdata <
1379 time(NULL) - Conf_PingTimeout) {
1380 /* We need to send a PING ... */
1381 LogDebug("Connection %d: sending PING ...", i);
1382 My_Connections[i].lastping = time(NULL);
1383 Conn_WriteStr(i, "PING :%s",
1384 Client_ID(Client_ThisServer()));
1387 /* The connection is not fully established yet, so
1388 * we don't do the PING-PONG game here but instead
1389 * disconnect the client after "a short time" if it's
1390 * still not registered. */
1392 if (My_Connections[i].lastdata <
1393 time(NULL) - Conf_PongTimeout) {
1395 ("Unregistered connection %d timed out ...",
1397 Conn_Close(i, NULL, "Timeout", false);
1401 } /* Check_Connections */
1405 Check_Servers( void )
1407 /* Check if we can establish further server links */
1412 /* Check all configured servers */
1413 for( i = 0; i < MAX_SERVERS; i++ ) {
1414 /* Valid outgoing server which isn't already connected or disabled? */
1415 if(( ! Conf_Server[i].host[0] ) || ( ! Conf_Server[i].port > 0 ) ||
1416 ( Conf_Server[i].conn_id > NONE ) || ( Conf_Server[i].flags & CONF_SFLAG_DISABLED ))
1419 /* Is there already a connection in this group? */
1420 if( Conf_Server[i].group > NONE ) {
1421 for (n = 0; n < MAX_SERVERS; n++) {
1422 if (n == i) continue;
1423 if ((Conf_Server[n].conn_id != NONE) &&
1424 (Conf_Server[n].group == Conf_Server[i].group))
1427 if (n < MAX_SERVERS) continue;
1430 /* Check last connect attempt? */
1431 time_now = time(NULL);
1432 if( Conf_Server[i].lasttry > (time_now - Conf_ConnectRetry))
1435 /* Okay, try to connect now */
1436 Conf_Server[i].lasttry = time_now;
1437 Conf_Server[i].conn_id = SERVER_WAIT;
1438 assert(Resolve_Getfd(&Conf_Server[i].res_stat) < 0);
1439 Resolve_Name(&Conf_Server[i].res_stat, Conf_Server[i].host, cb_Connect_to_Server);
1441 } /* Check_Servers */
1445 New_Server( int Server , ng_ipaddr_t *dest)
1447 /* Establish new server link */
1448 char ip_str[NG_INET_ADDRSTRLEN];
1449 int af_dest, res, new_sock;
1452 assert( Server > NONE );
1454 if (!ng_ipaddr_tostr_r(dest, ip_str)) {
1455 Log(LOG_WARNING, "New_Server: Could not convert IP to string");
1459 Log( LOG_INFO, "Establishing connection to \"%s\", %s, port %d ... ",
1460 Conf_Server[Server].host, ip_str, Conf_Server[Server].port );
1462 af_dest = ng_ipaddr_af(dest);
1463 new_sock = socket(af_dest, SOCK_STREAM, 0);
1465 Log( LOG_CRIT, "Can't create socket (af %d) : %s!", af_dest, strerror( errno ));
1469 if (!Init_Socket(new_sock))
1472 /* is a bind address configured? */
1473 res = ng_ipaddr_af(&Conf_Server[Server].bind_addr);
1474 /* if yes, bind now. If it fails, warn and let connect() pick a source address */
1475 if (res && bind(new_sock, (struct sockaddr *) &Conf_Server[Server].bind_addr,
1476 ng_ipaddr_salen(&Conf_Server[Server].bind_addr)))
1478 ng_ipaddr_tostr_r(&Conf_Server[Server].bind_addr, ip_str);
1479 Log(LOG_WARNING, "Can't bind socket to %s: %s!", ip_str, strerror(errno));
1481 ng_ipaddr_setport(dest, Conf_Server[Server].port);
1482 res = connect(new_sock, (struct sockaddr *) dest, ng_ipaddr_salen(dest));
1483 if(( res != 0 ) && ( errno != EINPROGRESS )) {
1484 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1489 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)new_sock)) {
1491 "Cannot allocate memory for server connection (socket %d)",
1497 My_Connections = array_start(&My_ConnArray);
1499 assert(My_Connections[new_sock].sock <= 0);
1501 Init_Conn_Struct(new_sock);
1503 ng_ipaddr_tostr_r(dest, ip_str);
1504 c = Client_NewLocal(new_sock, ip_str, CLIENT_UNKNOWNSERVER, false);
1506 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1511 Client_SetIntroducer( c, c );
1512 Client_SetToken( c, TOKEN_OUTBOUND );
1514 /* Register connection */
1515 Conf_Server[Server].conn_id = new_sock;
1516 My_Connections[new_sock].sock = new_sock;
1517 My_Connections[new_sock].addr = *dest;
1518 My_Connections[new_sock].client = c;
1519 strlcpy( My_Connections[new_sock].host, Conf_Server[Server].host,
1520 sizeof(My_Connections[new_sock].host ));
1522 /* Register new socket */
1523 if (!io_event_create( new_sock, IO_WANTWRITE, cb_connserver)) {
1524 Log( LOG_ALERT, "io_event_create(): could not add fd %d", strerror(errno));
1525 Conn_Close( new_sock, "io_event_create() failed", NULL, false );
1526 Init_Conn_Struct( new_sock );
1527 Conf_Server[Server].conn_id = NONE;
1530 LogDebug("Registered new connection %d on socket %d.",
1531 new_sock, My_Connections[new_sock].sock );
1532 Conn_OPTION_ADD( &My_Connections[new_sock], CONN_ISCONNECTING );
1537 * Initialize connection structure.
1540 Init_Conn_Struct(CONN_ID Idx)
1542 time_t now = time(NULL);
1544 memset(&My_Connections[Idx], 0, sizeof(CONNECTION));
1545 My_Connections[Idx].sock = -1;
1546 My_Connections[Idx].signon = now;
1547 My_Connections[Idx].lastdata = now;
1548 My_Connections[Idx].lastprivmsg = now;
1549 Resolve_Init(&My_Connections[Idx].res_stat);
1550 } /* Init_Conn_Struct */
1554 Init_Socket( int Sock )
1556 /* Initialize socket (set options) */
1560 if (!io_setnonblock(Sock)) {
1561 Log( LOG_CRIT, "Can't enable non-blocking mode for socket: %s!", strerror( errno ));
1566 /* Don't block this port after socket shutdown */
1568 if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &value, (socklen_t)sizeof( value )) != 0 )
1570 Log( LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!", strerror( errno ));
1571 /* ignore this error */
1574 /* Set type of service (TOS) */
1575 #if defined(IP_TOS) && defined(IPTOS_LOWDELAY)
1576 value = IPTOS_LOWDELAY;
1577 LogDebug("Setting option IP_TOS on socket %d to IPTOS_LOWDELAY (%d).", Sock, value );
1578 if( setsockopt( Sock, SOL_IP, IP_TOS, &value, (socklen_t)sizeof( value )) != 0 )
1580 Log( LOG_ERR, "Can't set socket option IP_TOS: %s!", strerror( errno ));
1581 /* ignore this error */
1591 cb_Connect_to_Server(int fd, UNUSED short events)
1593 /* Read result of resolver sub-process from pipe and start connection */
1596 ng_ipaddr_t dest_addrs[4]; /* we can handle at most 3; but we read up to
1597 four so we can log the 'more than we can handle'
1600 LogDebug("Resolver: Got forward lookup callback on fd %d, events %d", fd, events);
1602 for (i=0; i < MAX_SERVERS; i++) {
1603 if (Resolve_Getfd(&Conf_Server[i].res_stat) == fd )
1607 if( i >= MAX_SERVERS) {
1608 /* Ops, no matching server found?! */
1610 LogDebug("Resolver: Got Forward Lookup callback for unknown server!?");
1614 /* Read result from pipe */
1615 len = Resolve_Read(&Conf_Server[i].res_stat, dest_addrs, sizeof(dest_addrs));
1619 assert((len % sizeof(ng_ipaddr_t)) == 0);
1621 LogDebug("Got result from resolver: %u structs (%u bytes).", len/sizeof(ng_ipaddr_t), len);
1623 memset(&Conf_Server[i].dst_addr, 0, sizeof(&Conf_Server[i].dst_addr));
1624 if (len > sizeof(ng_ipaddr_t)) {
1625 /* more than one address for this hostname, remember them
1626 * in case first address is unreachable/not available */
1627 len -= sizeof(ng_ipaddr_t);
1628 if (len > sizeof(&Conf_Server[i].dst_addr)) {
1629 len = sizeof(&Conf_Server[i].dst_addr);
1630 Log(LOG_NOTICE, "Notice: Resolver returned more IP Addresses for host than we can handle,"
1631 " additional addresses dropped");
1633 memcpy(&Conf_Server[i].dst_addr, &dest_addrs[1], len);
1636 New_Server(i, dest_addrs);
1637 } /* cb_Read_Forward_Lookup */
1641 cb_Read_Resolver_Result( int r_fd, UNUSED short events )
1643 /* Read result of resolver sub-process from pipe and update the
1644 * apropriate connection/client structure(s): hostname and/or
1645 * IDENT user name.*/
1652 char readbuf[HOST_LEN + 2 + CLIENT_USER_LEN];
1654 char readbuf[HOST_LEN + 1];
1657 LogDebug("Resolver: Got callback on fd %d, events %d", r_fd, events );
1659 /* Search associated connection ... */
1660 for( i = 0; i < Pool_Size; i++ ) {
1661 if(( My_Connections[i].sock != NONE )
1662 && ( Resolve_Getfd(&My_Connections[i].res_stat) == r_fd ))
1665 if( i >= Pool_Size ) {
1666 /* Ops, none found? Probably the connection has already
1667 * been closed!? We'll ignore that ... */
1669 LogDebug("Resolver: Got callback for unknown connection!?");
1673 /* Read result from pipe */
1674 len = Resolve_Read(&My_Connections[i].res_stat, readbuf, sizeof readbuf -1);
1678 readbuf[len] = '\0';
1679 identptr = strchr(readbuf, '\n');
1680 assert(identptr != NULL);
1682 Log( LOG_CRIT, "Resolver: Got malformed result!");
1687 LogDebug("Got result from resolver: \"%s\" (%u bytes read).", readbuf, len);
1688 /* Okay, we got a complete result: this is a host name for outgoing
1689 * connections and a host name and IDENT user name (if enabled) for
1690 * incoming connections.*/
1691 assert ( My_Connections[i].sock >= 0 );
1692 /* Incoming connection. Search client ... */
1693 c = Conn_GetClient( i );
1694 assert( c != NULL );
1696 /* Only update client information of unregistered clients */
1697 if( Client_Type( c ) == CLIENT_UNKNOWN ) {
1698 strlcpy(My_Connections[i].host, readbuf, sizeof( My_Connections[i].host));
1699 Client_SetHostname( c, readbuf);
1703 Log(LOG_INFO, "IDENT lookup for connection %d: \"%s\".", i, identptr);
1704 Client_SetUser(c, identptr, true);
1706 Log(LOG_INFO, "IDENT lookup for connection %d: no result.", i);
1711 else Log( LOG_DEBUG, "Resolver: discarding result for already registered connection %d.", i );
1713 /* Reset penalty time */
1714 Conn_ResetPenalty( i );
1715 } /* cb_Read_Resolver_Result */
1719 Simple_Message( int Sock, const char *Msg )
1721 char buf[COMMAND_LEN];
1723 /* Write "simple" message to socket, without using compression
1724 * or even the connection write buffers. Used e.g. for error
1725 * messages by New_Connection(). */
1726 assert( Sock > NONE );
1727 assert( Msg != NULL );
1729 strlcpy( buf, Msg, sizeof buf - 2);
1730 len = strlcat( buf, "\r\n", sizeof buf);
1731 (void)write(Sock, buf, len);
1732 } /* Simple_Error */
1736 Conn_GetClient( CONN_ID Idx )
1738 /* return Client-Structure that belongs to the local Connection Idx.
1739 * If none is found, return NULL.
1744 c = array_get(&My_ConnArray, sizeof (CONNECTION), (size_t)Idx);
1748 return c ? c->client : NULL;