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
33 #include <sys/socket.h>
35 #include <sys/types.h>
37 #include <netinet/in.h>
39 #ifdef HAVE_NETINET_IP_H
40 # include <netinet/ip.h>
44 # include <stdint.h> /* e.g. for Mac OS X */
48 # 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 void Handle_Buffer PARAMS(( CONN_ID Idx ));
85 static void Check_Connections PARAMS(( void ));
86 static void Check_Servers PARAMS(( void ));
87 static void Init_Conn_Struct PARAMS(( CONN_ID Idx ));
88 static bool Init_Socket PARAMS(( int Sock ));
89 static void New_Server PARAMS(( int Server, ng_ipaddr_t *dest ));
90 static void Simple_Message PARAMS(( int Sock, const char *Msg ));
91 static int NewListener PARAMS(( const char *listen_addr, UINT16 Port ));
93 static array My_Listeners;
94 static array My_ConnArray;
95 static size_t NumConnections;
98 int allow_severity = LOG_INFO;
99 int deny_severity = LOG_ERR;
102 static void server_login PARAMS((CONN_ID idx));
105 extern struct SSLOptions Conf_SSLOptions;
106 static void cb_connserver_login_ssl PARAMS((int sock, short what));
107 static void cb_clientserver_ssl PARAMS((int sock, short what));
109 static void cb_Read_Resolver_Result PARAMS(( int sock, UNUSED short what));
110 static void cb_Connect_to_Server PARAMS(( int sock, UNUSED short what));
111 static void cb_clientserver PARAMS((int sock, short what));
114 cb_listen(int sock, short irrelevant)
117 if (New_Connection( sock ) >= 0)
124 cb_listen_ssl(int sock, short irrelevant)
128 fd = New_Connection(sock);
133 io_event_setcb(My_Connections[fd].sock, cb_clientserver_ssl);
139 cb_connserver(int sock, UNUSED short what)
143 CONN_ID idx = Socket2Index( sock );
145 LogDebug("cb_connserver wants to write on unknown socket?!");
150 assert( what & IO_WANTWRITE);
152 /* connect() finished, get result. */
153 sock_len = sizeof( err );
154 res = getsockopt( My_Connections[idx].sock, SOL_SOCKET, SO_ERROR, &err, &sock_len );
155 assert( sock_len == sizeof( err ));
157 /* Error while connecting? */
158 if ((res != 0) || (err != 0)) {
160 Log(LOG_CRIT, "getsockopt (connection %d): %s!",
161 idx, strerror(errno));
164 "Can't connect socket to \"%s:%d\" (connection %d): %s!",
165 My_Connections[idx].host,
166 Conf_Server[Conf_GetServer(idx)].port,
169 res = Conf_GetServer(idx);
172 Conn_Close(idx, "Can't connect!", NULL, false);
176 if (ng_ipaddr_af(&Conf_Server[res].dst_addr[0])) {
177 /* more addresses to try... */
178 New_Server(res, &Conf_Server[res].dst_addr[0]);
179 /* connection to dst_addr[0] in progress, remove this address... */
180 Conf_Server[res].dst_addr[0] = Conf_Server[res].dst_addr[1];
182 memset(&Conf_Server[res].dst_addr[1], 0, sizeof(&Conf_Server[res].dst_addr[1]));
187 res = Conf_GetServer(idx);
189 if (res >= 0) /* connect succeeded, remove all additional addresses */
190 memset(&Conf_Server[res].dst_addr, 0, sizeof(&Conf_Server[res].dst_addr));
191 Conn_OPTION_DEL( &My_Connections[idx], CONN_ISCONNECTING );
193 if ( Conn_OPTION_ISSET( &My_Connections[idx], CONN_SSL_CONNECT )) {
194 io_event_setcb( sock, cb_connserver_login_ssl );
195 io_event_add( sock, IO_WANTWRITE|IO_WANTREAD );
204 server_login(CONN_ID idx)
206 Log( LOG_INFO, "Connection %d with \"%s:%d\" established. Now logging in ...", idx,
207 My_Connections[idx].host, Conf_Server[Conf_GetServer( idx )].port );
209 io_event_setcb( My_Connections[idx].sock, cb_clientserver);
210 io_event_add( My_Connections[idx].sock, IO_WANTREAD|IO_WANTWRITE);
212 /* Send PASS and SERVER command to peer */
213 Conn_WriteStr( idx, "PASS %s %s", Conf_Server[Conf_GetServer( idx )].pwd_out, NGIRCd_ProtoID );
214 Conn_WriteStr( idx, "SERVER %s :%s", Conf_ServerName, Conf_ServerInfo );
220 cb_connserver_login_ssl(int sock, short unused)
222 CONN_ID idx = Socket2Index(sock);
230 switch (ConnSSL_Connect( &My_Connections[idx])) {
232 case 0: LogDebug("ConnSSL_Connect: not ready");
235 Log(LOG_INFO, "SSL connection on socket %d failed", sock);
236 Conn_Close(idx, "Can't connect!", NULL, false);
240 Log( LOG_INFO, "SSL Connection %d with \"%s:%d\" established.", idx,
241 My_Connections[idx].host, Conf_Server[Conf_GetServer( idx )].port );
249 cb_clientserver(int sock, short what)
251 CONN_ID idx = Socket2Index(sock);
260 if (what & IO_WANTREAD || (Conn_OPTION_ISSET(&My_Connections[idx], CONN_SSL_WANT_WRITE)))
261 Read_Request( idx ); /* if TLS layer needs to write additional data, call Read_Request instead so SSL/TLS can continue */
263 if (what & IO_WANTREAD)
266 if (what & IO_WANTWRITE)
273 cb_clientserver_ssl(int sock, short what)
275 CONN_ID idx = Socket2Index(sock);
284 switch (ConnSSL_Accept(&My_Connections[idx])) {
285 case 1: break; /* OK */
286 case 0: return; /* EAGAIN: this callback will be invoked again by the io layer */
288 Conn_Close( idx, "Socket closed!", "SSL accept error", false );
291 if (what & IO_WANTREAD)
294 if (what & IO_WANTWRITE)
297 io_event_setcb(sock, cb_clientserver); /* SSL handshake completed */
305 /* Modul initialisieren: statische Strukturen "ausnullen". */
309 /* Speicher fuer Verbindungs-Pool anfordern */
310 Pool_Size = CONNECTION_POOL;
311 if ((Conf_MaxConnections > 0) &&
312 (Pool_Size > Conf_MaxConnections))
313 Pool_Size = Conf_MaxConnections;
315 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)Pool_Size)) {
316 Log( LOG_EMERG, "Can't allocate memory! [Conn_Init]" );
320 /* FIXME: My_Connetions/Pool_Size is needed by other parts of the
321 * code; remove them! */
322 My_Connections = (CONNECTION*) array_start(&My_ConnArray);
324 LogDebug("Allocated connection pool for %d items (%ld bytes).",
325 array_length(&My_ConnArray, sizeof( CONNECTION )), array_bytes(&My_ConnArray));
327 assert( array_length(&My_ConnArray, sizeof( CONNECTION )) >= (size_t) Pool_Size);
329 array_free( &My_Listeners );
331 /* Connection-Struktur initialisieren */
332 for( i = 0; i < Pool_Size; i++ ) Init_Conn_Struct( i );
334 /* Global write counter */
342 /* Modul abmelden: alle noch offenen Connections
343 * schliessen und freigeben. */
347 LogDebug("Shutting down all connections ..." );
349 Conn_ExitListeners();
351 /* Sockets schliessen */
352 for( idx = 0; idx < Pool_Size; idx++ ) {
353 if( My_Connections[idx].sock > NONE ) {
354 Conn_Close( idx, NULL, NGIRCd_SignalRestart ?
355 "Server going down (restarting)":"Server going down", true );
359 array_free(&My_ConnArray);
360 My_Connections = NULL;
362 io_library_shutdown();
367 ports_initlisteners(array *a, const char *listen_addr, void (*func)(int,short))
369 unsigned int created = 0;
374 len = array_length(a, sizeof (UINT16));
375 port = array_start(a);
377 fd = NewListener(listen_addr, *port);
382 if (!io_event_create( fd, IO_WANTREAD, func )) {
383 Log( LOG_ERR, "io_event_create(): Could not add listening fd %d (port %u): %s!",
384 fd, (unsigned int) *port, strerror(errno));
397 Conn_InitListeners( void )
399 /* Initialize ports on which the server should accept connections */
400 unsigned int created = 0;
401 char *copy, *listen_addr;
403 if (!io_library_init(CONNECTION_POOL)) {
404 Log(LOG_EMERG, "Cannot initialize IO routines: %s", strerror(errno));
408 assert(Conf_ListenAddress);
410 /* can't use Conf_ListenAddress directly, see below */
411 copy = strdup(Conf_ListenAddress);
413 Log(LOG_CRIT, "Cannot copy %s: %s", Conf_ListenAddress, strerror(errno));
416 listen_addr = strtok(copy, ",");
418 while (listen_addr) {
419 ngt_TrimStr(listen_addr);
421 created += ports_initlisteners(&Conf_ListenPorts, listen_addr, cb_listen);
423 created += ports_initlisteners(&Conf_SSLOptions.ListenPorts, listen_addr, cb_listen_ssl);
427 listen_addr = strtok(NULL, ",");
431 * can't free() Conf_ListenAddress here. On /REHASH, if the config file
432 * cannot be re-loaded, we'd end up with a NULL Conf_ListenAddress.
433 * Instead, free() takes place in conf.c, before the config file
438 } /* Conn_InitListeners */
442 Conn_ExitListeners( void )
444 /* Close down all listening sockets */
448 Rendezvous_UnregisterListeners( );
451 arraylen = array_length(&My_Listeners, sizeof (int));
452 Log( LOG_INFO, "Shutting down all listening sockets (%d total)...", arraylen );
453 fd = array_start(&My_Listeners);
458 LogDebug("Listening socket %d closed.", *fd );
461 array_free(&My_Listeners);
462 } /* Conn_ExitListeners */
466 InitSinaddrListenAddr(ng_ipaddr_t *addr, const char *listen_addrstr, UINT16 Port)
470 ret = ng_ipaddr_init(addr, listen_addrstr, Port);
472 assert(listen_addrstr);
473 Log(LOG_CRIT, "Can't bind to [%s]:%u: can't convert ip address \"%s\"",
474 listen_addrstr, Port, listen_addrstr);
481 set_v6_only(int af, int sock)
483 #if defined(IPV6_V6ONLY) && defined(WANT_IPV6)
489 if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)))
490 Log(LOG_ERR, "Could not set IPV6_V6ONLY: %s", strerror(errno));
498 /* return new listening port file descriptor or -1 on failure */
500 NewListener(const char *listen_addr, UINT16 Port)
502 /* Create new listening socket on specified port */
506 char name[CLIENT_ID_LEN], *info;
508 if (!InitSinaddrListenAddr(&addr, listen_addr, Port))
511 af = ng_ipaddr_af(&addr);
512 sock = socket(af, SOCK_STREAM, 0);
514 Log(LOG_CRIT, "Can't create socket (af %d) : %s!", af, strerror(errno));
518 set_v6_only(af, sock);
520 if (!Init_Socket(sock))
523 if (bind(sock, (struct sockaddr *)&addr, ng_ipaddr_salen(&addr)) != 0) {
524 Log(LOG_CRIT, "Can't bind socket to address %s:%d - %s",
525 ng_ipaddr_tostr(&addr), Port, strerror(errno));
530 if( listen( sock, 10 ) != 0 ) {
531 Log( LOG_CRIT, "Can't listen on socket: %s!", strerror( errno ));
536 /* keep fd in list so we can close it when ngircd restarts/shuts down */
537 if (!array_catb( &My_Listeners,(char*) &sock, sizeof(int) )) {
538 Log( LOG_CRIT, "Can't add socket to My_Listeners array: %s!", strerror( errno ));
543 Log(LOG_INFO, "Now listening on [%s]:%d (socket %d).", ng_ipaddr_tostr(&addr), Port, sock);
546 /* Get best server description text */
547 if( ! Conf_ServerInfo[0] ) info = Conf_ServerName;
550 /* Use server info string */
552 if( Conf_ServerInfo[0] == '[' )
554 /* Cut off leading hostname part in "[]" */
555 info = strchr( Conf_ServerInfo, ']' );
559 while( *info == ' ' ) info++;
562 if( ! info ) info = Conf_ServerInfo;
565 /* Add port number to description if non-standard */
567 snprintf(name, sizeof name, "%s (port %u)", info,
570 strlcpy(name, info, sizeof name);
572 /* Register service */
573 Rendezvous_Register( name, MDNS_TYPE, Port );
580 * SSL/TLS connections require extra treatment:
581 * When either CONN_SSL_WANT_WRITE or CONN_SSL_WANT_READ is set, we
582 * need to take care of that first, before checking read/write buffers.
583 * For instance, while we might have data in our write buffer, the
584 * TLS/SSL protocol might need to read internal data first for TLS/SSL
587 * If this function returns true, such a condition is met and we have
588 * to reverse the condition (check for read even if we've data to write,
589 * do not check for read but writeability even if write-buffer is empty).
592 SSL_WantRead(const CONNECTION *c)
594 if (Conn_OPTION_ISSET(c, CONN_SSL_WANT_READ)) {
595 io_event_add(c->sock, IO_WANTREAD);
601 SSL_WantWrite(const CONNECTION *c)
603 if (Conn_OPTION_ISSET(c, CONN_SSL_WANT_WRITE)) {
604 io_event_add(c->sock, IO_WANTWRITE);
611 SSL_WantRead(UNUSED const CONNECTION *c) { return false; }
613 SSL_WantWrite(UNUSED const CONNECTION *c) { return false; }
618 * "Main Loop": Loop until shutdown or restart is signalled.
619 * This function loops until a shutdown or restart of ngIRCd is signalled and
620 * calls io_dispatch() to check for readable and writable sockets every second.
621 * It checks for status changes on pending connections (e. g. when a hostname
622 * has been resolved), checks for "penalties" and timeouts, and handles the
629 unsigned int wdatalen;
633 while (!NGIRCd_SignalQuit && !NGIRCd_SignalRestart) {
637 Rendezvous_Handler();
640 /* Should the configuration be reloaded? */
641 if (NGIRCd_SignalRehash)
644 /* Check configured servers and established links */
648 /* Look for non-empty read buffers ... */
649 for (i = 0; i < Pool_Size; i++) {
650 if ((My_Connections[i].sock > NONE)
651 && (array_bytes(&My_Connections[i].rbuf) > 0)
652 && (My_Connections[i].delaytime < t)) {
653 /* ... and try to handle the received data */
658 /* Look for non-empty write buffers ... */
659 for (i = 0; i < Pool_Size; i++) {
660 if (My_Connections[i].sock <= NONE)
663 wdatalen = (unsigned int)array_bytes(&My_Connections[i].wbuf);
666 array_bytes(&My_Connections[i].zip.wbuf) > 0)
671 if (SSL_WantRead(&My_Connections[i]))
673 io_event_add(My_Connections[i].sock,
678 /* Check from which sockets we possibly could read ... */
679 for (i = 0; i < Pool_Size; i++) {
680 if (My_Connections[i].sock <= NONE)
683 if (SSL_WantWrite(&My_Connections[i]))
684 continue; /* TLS/SSL layer needs to write data; deal with this first */
686 if (Resolve_INPROGRESS(&My_Connections[i].res_stat)) {
687 /* Wait for completion of resolver sub-process ... */
688 io_event_del(My_Connections[i].sock,
693 if (Conn_OPTION_ISSET(&My_Connections[i], CONN_ISCONNECTING))
694 /* Wait for completion of connect() ... */
697 if (My_Connections[i].delaytime > t) {
698 /* There is a "penalty time" set: ignore socket! */
699 io_event_del(My_Connections[i].sock,
703 io_event_add(My_Connections[i].sock, IO_WANTREAD);
706 /* Set the timeout for reading from the network to 1 second,
707 * which is the granularity with witch we handle "penalty
708 * times" for example.
709 * Note: tv_sec/usec are undefined(!) after io_dispatch()
710 * returns, so we have to set it beforce each call to it! */
714 /* Wait for activity ... */
715 i = io_dispatch(&tv);
716 if (i == -1 && errno != EINTR) {
717 Log(LOG_EMERG, "Conn_Handler(): io_dispatch(): %s!",
719 Log(LOG_ALERT, "%s exiting due to fatal errors!",
725 if (NGIRCd_SignalQuit)
726 Log(LOG_NOTICE | LOG_snotice, "Server going down NOW!");
727 else if (NGIRCd_SignalRestart)
728 Log(LOG_NOTICE | LOG_snotice, "Server restarting NOW!");
733 * Write a text string into the socket of a connection.
734 * This function automatically appends CR+LF to the string and validates that
735 * the result is a valid IRC message (oversized messages are shortened, for
736 * example). Then it calls the Conn_Write() function to do the actual sending.
737 * @param Idx Index fo the connection.
738 * @param Format Format string, see printf().
739 * @return true on success, false otherwise.
743 Conn_WriteStr( CONN_ID Idx, char *Format, ... )
746 Conn_WriteStr( Idx, Format, va_alist )
752 char buffer[COMMAND_LEN];
757 assert( Idx > NONE );
758 assert( Format != NULL );
761 va_start( ap, Format );
765 if (vsnprintf( buffer, COMMAND_LEN - 2, Format, ap ) >= COMMAND_LEN - 2 ) {
767 * The string that should be written to the socket is longer
768 * than the allowed size of COMMAND_LEN bytes (including both
769 * the CR and LF characters). This can be caused by the
770 * IRC_WriteXXX() functions when the prefix of this server had
771 * to be added to an already "quite long" command line which
772 * has been received from a regular IRC client, for example.
774 * We are not allowed to send such "oversized" messages to
775 * other servers and clients, see RFC 2812 2.3 and 2813 3.3
776 * ("these messages SHALL NOT exceed 512 characters in length,
777 * counting all characters including the trailing CR-LF").
779 * So we have a big problem here: we should send more bytes
780 * to the network than we are allowed to and we don't know
781 * the originator (any more). The "old" behaviour of blaming
782 * the receiver ("next hop") is a bad idea (it could be just
783 * an other server only routing the message!), so the only
784 * option left is to shorten the string and to hope that the
785 * result is still somewhat useful ...
789 strcpy (buffer + sizeof(buffer) - strlen(CUT_TXTSUFFIX) - 2 - 1,
795 Log(LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer);
798 len = strlcat( buffer, "\r\n", sizeof( buffer ));
799 ok = Conn_Write(Idx, buffer, len);
800 My_Connections[Idx].msg_out++;
804 } /* Conn_WriteStr */
808 * Append Data to the outbound write buffer of a connection.
809 * @param Idx Index of the connection.
810 * @param Data pointer to the data.
811 * @param Len length of Data.
812 * @return true on success, false otherwise.
815 Conn_Write( CONN_ID Idx, char *Data, size_t Len )
818 size_t writebuf_limit = WRITEBUFFER_LEN;
819 assert( Idx > NONE );
820 assert( Data != NULL );
823 c = Conn_GetClient(Idx);
826 /* Servers do get special write buffer limits, so they can generate
827 * all the messages that are required while peering. */
828 if (Client_Type(c) == CLIENT_SERVER)
829 writebuf_limit = WRITEBUFFER_SLINK_LEN;
831 /* Is the socket still open? A previous call to Conn_Write()
832 * may have closed the connection due to a fatal error.
833 * In this case it is sufficient to return an error, as well. */
834 if( My_Connections[Idx].sock <= NONE ) {
835 LogDebug("Skipped write on closed socket (connection %d).", Idx);
840 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
842 * Zip_Buffer() does all the dirty work for us: it flushes
843 * the (pre-)compression buffers if required and handles
844 * all error conditions. */
845 if (!Zip_Buffer(Idx, Data, Len))
851 /* Uncompressed link:
852 * Check if outbound buffer has enough space for the data. */
853 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
855 /* Buffer is full, flush it. Handle_Write deals with
856 * low-level errors, if any. */
857 if (!Handle_Write(Idx))
861 /* When the write buffer is still too big after flushing it,
862 * the connection will be killed. */
863 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
866 "Write buffer overflow (connection %d, size %lu byte)!",
868 (unsigned long)array_bytes(&My_Connections[Idx].wbuf));
869 Conn_Close(Idx, "Write buffer overflow!", NULL, false);
873 /* Copy data to write buffer */
874 if (!array_catb(&My_Connections[Idx].wbuf, Data, Len))
877 My_Connections[Idx].bytes_out += Len;
880 /* Adjust global write counter */
888 Conn_Close( CONN_ID Idx, char *LogMsg, char *FwdMsg, bool InformClient )
890 /* Close connection. Open pipes of asyncronous resolver
891 * sub-processes are closed down. */
898 double in_z_k, out_z_k;
902 assert( Idx > NONE );
904 /* Is this link already shutting down? */
905 if( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ISCLOSING )) {
906 /* Conn_Close() has been called recursively for this link;
907 * probabe reason: Handle_Write() failed -- see below. */
908 LogDebug("Recursive request to close connection: %d", Idx );
912 assert( My_Connections[Idx].sock > NONE );
914 /* Mark link as "closing" */
915 Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCLOSING );
922 txt = "Reason unknown";
924 port = ng_ipaddr_getport(&My_Connections[Idx].addr);
925 Log(LOG_INFO, "Shutting down connection %d (%s) with %s:%d ...", Idx,
926 LogMsg ? LogMsg : FwdMsg, My_Connections[Idx].host, port);
928 /* Search client, if any */
929 c = Conn_GetClient( Idx );
931 /* Should the client be informed? */
934 /* Send statistics to client if registered as user: */
935 if ((c != NULL) && (Client_Type(c) == CLIENT_USER)) {
937 ":%s NOTICE %s :%sConnection statistics: client %.1f kb, server %.1f kb.",
938 Client_ID(Client_ThisServer()), Client_ID(c),
940 (double)My_Connections[Idx].bytes_in / 1024,
941 (double)My_Connections[Idx].bytes_out / 1024);
944 /* Send ERROR to client (see RFC!) */
946 Conn_WriteStr(Idx, "ERROR :%s", FwdMsg);
948 Conn_WriteStr(Idx, "ERROR :Closing connection.");
951 /* Try to write out the write buffer. Note: Handle_Write() eventually
952 * removes the CLIENT structure associated with this connection if an
953 * error occurs! So we have to re-check if there is still an valid
954 * CLIENT structure after calling Handle_Write() ...*/
955 (void)Handle_Write( Idx );
957 /* Search client, if any (re-check!) */
958 c = Conn_GetClient( Idx );
960 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_SSL )) {
961 Log( LOG_INFO, "SSL Connection %d shutting down", Idx );
962 ConnSSL_Free(&My_Connections[Idx]);
965 /* Shut down socket */
966 if (! io_close(My_Connections[Idx].sock)) {
967 /* Oops, we can't close the socket!? This is ... ugly! */
969 "Error closing connection %d (socket %d) with %s:%d - %s! (ignored)",
970 Idx, My_Connections[Idx].sock, My_Connections[Idx].host,
971 port, strerror(errno));
974 /* Mark socket as invalid: */
975 My_Connections[Idx].sock = NONE;
977 /* If there is still a client, unregister it now */
979 Client_Destroy(c, LogMsg, FwdMsg, true);
981 /* Calculate statistics and log information */
982 in_k = (double)My_Connections[Idx].bytes_in / 1024;
983 out_k = (double)My_Connections[Idx].bytes_out / 1024;
985 if (Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP)) {
986 in_z_k = (double)My_Connections[Idx].zip.bytes_in / 1024;
987 out_z_k = (double)My_Connections[Idx].zip.bytes_out / 1024;
988 /* Make sure that no division by zero can occur during
989 * the calculation of in_p and out_p: in_z_k and out_z_k
990 * are non-zero, that's guaranteed by the protocol until
991 * compression can be enabled. */
996 in_p = (int)(( in_k * 100 ) / in_z_k );
997 out_p = (int)(( out_k * 100 ) / out_z_k );
999 "Connection %d with %s:%d closed (in: %.1fk/%.1fk/%d%%, out: %.1fk/%.1fk/%d%%).",
1000 Idx, My_Connections[Idx].host, port,
1001 in_k, in_z_k, in_p, out_k, out_z_k, out_p);
1007 "Connection %d with %s:%d closed (in: %.1fk, out: %.1fk).",
1008 Idx, My_Connections[Idx].host, port,
1012 /* cancel running resolver */
1013 if (Resolve_INPROGRESS(&My_Connections[Idx].res_stat))
1014 Resolve_Shutdown(&My_Connections[Idx].res_stat);
1016 /* Servers: Modify time of next connect attempt? */
1017 Conf_UnsetServer( Idx );
1020 /* Clean up zlib, if link was compressed */
1021 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
1022 inflateEnd( &My_Connections[Idx].zip.in );
1023 deflateEnd( &My_Connections[Idx].zip.out );
1024 array_free(&My_Connections[Idx].zip.rbuf);
1025 array_free(&My_Connections[Idx].zip.wbuf);
1029 array_free(&My_Connections[Idx].rbuf);
1030 array_free(&My_Connections[Idx].wbuf);
1032 /* Clean up connection structure (=free it) */
1033 Init_Conn_Struct( Idx );
1035 assert(NumConnections > 0);
1038 LogDebug("Shutdown of connection %d completed", Idx );
1043 Conn_SyncServerStruct( void )
1045 /* Synchronize server structures (connection IDs):
1046 * connections <-> configuration */
1052 for( i = 0; i < Pool_Size; i++ ) {
1053 /* Established connection? */
1054 if (My_Connections[i].sock < 0)
1057 /* Server connection? */
1058 client = Conn_GetClient( i );
1059 if(( ! client ) || ( Client_Type( client ) != CLIENT_SERVER )) continue;
1061 for( c = 0; c < MAX_SERVERS; c++ )
1063 /* Configured server? */
1064 if( ! Conf_Server[c].host[0] ) continue;
1067 if( strcmp( Conf_Server[c].name, Client_ID( client )) == 0 )
1068 Conf_Server[c].conn_id = i;
1071 } /* SyncServerStruct */
1075 * Send out data of write buffer; connect new sockets.
1078 Handle_Write( CONN_ID Idx )
1083 assert( Idx > NONE );
1084 if ( My_Connections[Idx].sock < 0 ) {
1085 LogDebug("Handle_Write() on closed socket, connection %d", Idx);
1088 assert( My_Connections[Idx].sock > NONE );
1090 wdatalen = array_bytes(&My_Connections[Idx].wbuf );
1093 if (wdatalen == 0) {
1094 /* Write buffer is empty, so we try to flush the compression
1095 * buffer and get some data to work with from there :-) */
1096 if (!Zip_Flush(Idx))
1099 /* Now the write buffer most probably has changed: */
1100 wdatalen = array_bytes(&My_Connections[Idx].wbuf);
1104 if (wdatalen == 0) {
1105 /* Still no data, fine. */
1106 io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
1111 ("Handle_Write() called for connection %d, %ld bytes pending ...",
1115 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_SSL )) {
1116 len = ConnSSL_Write(&My_Connections[Idx], array_start(&My_Connections[Idx].wbuf), wdatalen);
1120 len = write(My_Connections[Idx].sock,
1121 array_start(&My_Connections[Idx].wbuf), wdatalen );
1124 if (errno == EAGAIN || errno == EINTR)
1127 Log(LOG_ERR, "Write error on connection %d (socket %d): %s!",
1128 Idx, My_Connections[Idx].sock, strerror(errno));
1129 Conn_Close(Idx, "Write error!", NULL, false);
1133 /* move any data not yet written to beginning */
1134 array_moveleft(&My_Connections[Idx].wbuf, 1, (size_t)len);
1137 } /* Handle_Write */
1141 Count_Connections(ng_ipaddr_t *a)
1146 for (i = 0; i < Pool_Size; i++) {
1147 if (My_Connections[i].sock <= NONE)
1149 if (ng_ipaddr_ipequal(&My_Connections[i].addr, a))
1153 } /* Count_Connections */
1157 New_Connection( int Sock )
1159 /* Neue Client-Verbindung von Listen-Socket annehmen und
1160 * CLIENT-Struktur anlegen. */
1163 struct request_info req;
1165 ng_ipaddr_t new_addr;
1166 char ip_str[NG_INET_ADDRSTRLEN];
1167 int new_sock, new_sock_len;
1171 assert( Sock > NONE );
1172 /* Connection auf Listen-Socket annehmen */
1173 new_sock_len = (int)sizeof(new_addr);
1175 new_sock = accept(Sock, (struct sockaddr *)&new_addr,
1176 (socklen_t *)&new_sock_len);
1178 Log(LOG_CRIT, "Can't accept connection: %s!", strerror(errno));
1182 if (!ng_ipaddr_tostr_r(&new_addr, ip_str)) {
1183 Log(LOG_CRIT, "fd %d: Can't convert IP address!", new_sock);
1184 Simple_Message(new_sock, "ERROR :Internal Server Error");
1190 /* Validate socket using TCP Wrappers */
1191 request_init( &req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock, RQ_CLIENT_SIN, &new_addr, NULL );
1193 if (!hosts_access(&req)) {
1194 Log (deny_severity, "Refused connection from %s (by TCP Wrappers)!", ip_str);
1195 Simple_Message( new_sock, "ERROR :Connection refused" );
1201 /* Socket initialisieren */
1202 if (!Init_Socket( new_sock ))
1205 /* Check IP-based connection limit */
1206 cnt = Count_Connections(&new_addr);
1207 if ((Conf_MaxConnectionsIP > 0) && (cnt >= Conf_MaxConnectionsIP)) {
1208 /* Access denied, too many connections from this IP address! */
1209 Log( LOG_ERR, "Refused connection from %s: too may connections (%ld) from this IP address!", ip_str, cnt);
1210 Simple_Message( new_sock, "ERROR :Connection refused, too many connections from your IP address!" );
1215 if ((Conf_MaxConnections > 0) &&
1216 (NumConnections >= (size_t) Conf_MaxConnections))
1218 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached!", Conf_MaxConnections);
1219 Simple_Message( new_sock, "ERROR :Connection limit reached" );
1224 if( new_sock >= Pool_Size ) {
1225 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION),
1226 (size_t)new_sock)) {
1227 Log( LOG_EMERG, "Can't allocate memory! [New_Connection]" );
1228 Simple_Message( new_sock, "ERROR: Internal error" );
1232 LogDebug("Bumped connection pool to %ld items (internal: %ld items, %ld bytes)",
1233 new_sock, array_length(&My_ConnArray, sizeof(CONNECTION)), array_bytes(&My_ConnArray));
1235 /* Adjust pointer to new block */
1236 My_Connections = array_start(&My_ConnArray);
1237 while (Pool_Size <= new_sock)
1238 Init_Conn_Struct(Pool_Size++);
1241 /* register callback */
1242 if (!io_event_create( new_sock, IO_WANTREAD, cb_clientserver)) {
1243 Log(LOG_ALERT, "Can't accept connection: io_event_create failed!");
1244 Simple_Message(new_sock, "ERROR :Internal error");
1249 c = Client_NewLocal(new_sock, ip_str, CLIENT_UNKNOWN, false );
1251 Log(LOG_ALERT, "Can't accept connection: can't create client structure!");
1252 Simple_Message(new_sock, "ERROR :Internal error");
1257 Init_Conn_Struct( new_sock );
1258 My_Connections[new_sock].sock = new_sock;
1259 My_Connections[new_sock].addr = new_addr;
1260 My_Connections[new_sock].client = c;
1262 Log( LOG_INFO, "Accepted connection %d from %s:%d on socket %d.", new_sock,
1263 ip_str, ng_ipaddr_getport(&new_addr), Sock);
1265 /* Hostnamen ermitteln */
1266 strlcpy(My_Connections[new_sock].host, ip_str, sizeof(My_Connections[new_sock].host));
1268 Client_SetHostname(c, My_Connections[new_sock].host);
1271 Resolve_Addr(&My_Connections[new_sock].res_stat, &new_addr,
1272 My_Connections[new_sock].sock, cb_Read_Resolver_Result);
1274 Conn_SetPenalty(new_sock, 4);
1276 } /* New_Connection */
1280 Socket2Index( int Sock )
1282 /* zum Socket passende Connection suchen */
1284 assert( Sock >= 0 );
1286 if( Sock >= Pool_Size || My_Connections[Sock].sock != Sock ) {
1287 /* die Connection wurde vermutlich (wegen eines
1288 * Fehlers) bereits wieder abgebaut ... */
1289 LogDebug("Socket2Index: can't get connection for socket %d!", Sock);
1293 } /* Socket2Index */
1297 * Read data from the network to the read buffer. If an error occures,
1298 * the socket of this connection will be shut down.
1301 Read_Request( CONN_ID Idx )
1304 char readbuf[READBUFFER_LEN];
1306 assert( Idx > NONE );
1307 assert( My_Connections[Idx].sock > NONE );
1310 if ((array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN) ||
1311 (array_bytes(&My_Connections[Idx].zip.rbuf) >= READBUFFER_LEN))
1313 if (array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN)
1316 /* Read buffer is full */
1318 "Receive buffer overflow (connection %d): %d bytes!",
1319 Idx, array_bytes(&My_Connections[Idx].rbuf));
1320 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1325 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_SSL))
1326 len = ConnSSL_Read( &My_Connections[Idx], readbuf, sizeof(readbuf));
1329 len = read(My_Connections[Idx].sock, readbuf, sizeof(readbuf));
1331 Log(LOG_INFO, "%s:%u (%s) is closing the connection ...",
1332 My_Connections[Idx].host,
1333 (unsigned int) ng_ipaddr_getport(&My_Connections[Idx].addr),
1334 ng_ipaddr_tostr(&My_Connections[Idx].addr));
1336 "Socket closed!", "Client closed connection",
1342 if( errno == EAGAIN ) return;
1343 Log(LOG_ERR, "Read error on connection %d (socket %d): %s!",
1344 Idx, My_Connections[Idx].sock, strerror(errno));
1345 Conn_Close(Idx, "Read error!", "Client closed connection",
1350 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1351 if (!array_catb(&My_Connections[Idx].zip.rbuf, readbuf,
1354 "Could not append recieved data to zip input buffer (connn %d): %d bytes!",
1356 Conn_Close(Idx, "Receive buffer overflow!", NULL,
1363 if (!array_catb( &My_Connections[Idx].rbuf, readbuf, len)) {
1364 Log( LOG_ERR, "Could not append recieved data to input buffer (connn %d): %d bytes!", Idx, len );
1365 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1369 /* Update connection statistics */
1370 My_Connections[Idx].bytes_in += len;
1372 /* Update timestamp of last data received if this connection is
1373 * registered as a user, server or service connection. Don't update
1374 * otherwise, so users have at least Conf_PongTimeout seconds time to
1375 * register with the IRC server -- see Check_Connections().
1376 * Set "lastping", too, so we can handle time shifts backwards ... */
1377 c = Conn_GetClient(Idx);
1378 if (c && (Client_Type(c) == CLIENT_USER
1379 || Client_Type(c) == CLIENT_SERVER
1380 || Client_Type(c) == CLIENT_SERVICE)) {
1381 My_Connections[Idx].lastdata = time(NULL);
1382 My_Connections[Idx].lastping = My_Connections[Idx].lastdata;
1385 /* Look at the data in the (read-) buffer of this connection */
1387 } /* Read_Request */
1391 * Handle all data in the connection read-buffer.
1392 * All data is precessed until no complete command is left. When a fatal
1393 * error occurs, the connection is shut down.
1396 Handle_Buffer(CONN_ID Idx)
1399 char *ptr1, *ptr2, *first_eol;
1408 starttime = time(NULL);
1411 if (My_Connections[Idx].delaytime > starttime)
1414 /* Unpack compressed data, if compression is in use */
1415 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1416 /* When unzipping fails, Unzip_Buffer() shuts
1417 * down the connection itself */
1418 if (!Unzip_Buffer(Idx))
1423 if (0 == array_bytes(&My_Connections[Idx].rbuf))
1426 /* Make sure that the buffer is NULL terminated */
1427 if (!array_cat0_temporary(&My_Connections[Idx].rbuf)) {
1428 Conn_Close(Idx, NULL,
1429 "Can't allocate memory [Handle_Buffer]",
1434 /* RFC 2812, section "2.3 Messages", 5th paragraph:
1435 * "IRC messages are always lines of characters terminated
1436 * with a CR-LF (Carriage Return - Line Feed) pair [...]". */
1438 ptr = strstr(array_start(&My_Connections[Idx].rbuf), "\r\n");
1441 /* Check for non-RFC-compliant request (only CR or LF)?
1442 * Unfortunately, there are quite a few clients out there
1443 * that do this -- e. g. mIRC, BitchX, and Trillian :-( */
1444 ptr1 = strchr(array_start(&My_Connections[Idx].rbuf), '\r');
1445 ptr2 = strchr(array_start(&My_Connections[Idx].rbuf), '\n');
1447 /* Check if there is a single CR or LF _before_ the
1448 * corerct CR+LF line terminator: */
1449 first_eol = ptr1 < ptr2 ? ptr1 : ptr2;
1450 if (first_eol < ptr) {
1451 /* Single CR or LF before CR+LF found */
1455 } else if (ptr1 || ptr2) {
1456 /* No CR+LF terminated command found, but single
1457 * CR or LF found ... */
1459 ptr = ptr1 < ptr2 ? ptr1 : ptr2;
1461 ptr = ptr1 ? ptr1 : ptr2;
1469 /* Complete (=line terminated) request found, handle it! */
1472 len = ptr - (char *)array_start(&My_Connections[Idx].rbuf) + delta;
1474 if (len > (COMMAND_LEN - 1)) {
1475 /* Request must not exceed 512 chars (incl. CR+LF!),
1476 * see RFC 2812. Disconnect Client if this happens. */
1478 "Request too long (connection %d): %d bytes (max. %d expected)!",
1479 Idx, array_bytes(&My_Connections[Idx].rbuf),
1481 Conn_Close(Idx, NULL, "Request too long", true);
1486 /* Request is empty (only '\r\n', '\r' or '\n');
1487 * delta is 2 ('\r\n') or 1 ('\r' or '\n'), see above */
1488 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1493 /* remember if stream is already compressed */
1494 old_z = My_Connections[Idx].options & CONN_ZIP;
1497 My_Connections[Idx].msg_in++;
1499 (Idx, (char *)array_start(&My_Connections[Idx].rbuf)))
1502 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1503 LogDebug("Connection %d: %d bytes left in read buffer.",
1504 Idx, array_bytes(&My_Connections[Idx].rbuf));
1506 if ((!old_z) && (My_Connections[Idx].options & CONN_ZIP) &&
1507 (array_bytes(&My_Connections[Idx].rbuf) > 0)) {
1508 /* The last command activated socket compression.
1509 * Data that was read after that needs to be copied
1510 * to the unzip buffer for decompression: */
1512 (&My_Connections[Idx].zip.rbuf,
1513 &My_Connections[Idx].rbuf)) {
1514 Conn_Close(Idx, NULL,
1515 "Can't allocate memory [Handle_Buffer]",
1520 array_trunc(&My_Connections[Idx].rbuf);
1522 ("Moved already received data (%u bytes) to uncompression buffer.",
1523 array_bytes(&My_Connections[Idx].zip.rbuf));
1527 } /* Handle_Buffer */
1531 Check_Connections(void)
1533 /* check if connections are alive. if not, play PING-PONG first.
1534 * if this doesn't help either, disconnect client. */
1538 for (i = 0; i < Pool_Size; i++) {
1539 if (My_Connections[i].sock < 0)
1542 c = Conn_GetClient(i);
1543 if (c && ((Client_Type(c) == CLIENT_USER)
1544 || (Client_Type(c) == CLIENT_SERVER)
1545 || (Client_Type(c) == CLIENT_SERVICE))) {
1546 /* connected User, Server or Service */
1547 if (My_Connections[i].lastping >
1548 My_Connections[i].lastdata) {
1549 /* We already sent a ping */
1550 if (My_Connections[i].lastping <
1551 time(NULL) - Conf_PongTimeout) {
1554 ("Connection %d: Ping timeout: %d seconds.",
1555 i, Conf_PongTimeout);
1556 Conn_Close(i, NULL, "Ping timeout",
1559 } else if (My_Connections[i].lastdata <
1560 time(NULL) - Conf_PingTimeout) {
1561 /* We need to send a PING ... */
1562 LogDebug("Connection %d: sending PING ...", i);
1563 My_Connections[i].lastping = time(NULL);
1564 Conn_WriteStr(i, "PING :%s",
1565 Client_ID(Client_ThisServer()));
1568 /* The connection is not fully established yet, so
1569 * we don't do the PING-PONG game here but instead
1570 * disconnect the client after "a short time" if it's
1571 * still not registered. */
1573 if (My_Connections[i].lastdata <
1574 time(NULL) - Conf_PongTimeout) {
1576 ("Unregistered connection %d timed out ...",
1578 Conn_Close(i, NULL, "Timeout", false);
1582 } /* Check_Connections */
1586 Check_Servers( void )
1588 /* Check if we can establish further server links */
1593 /* Check all configured servers */
1594 for( i = 0; i < MAX_SERVERS; i++ ) {
1595 /* Valid outgoing server which isn't already connected or disabled? */
1596 if(( ! Conf_Server[i].host[0] ) || ( ! Conf_Server[i].port > 0 ) ||
1597 ( Conf_Server[i].conn_id > NONE ) || ( Conf_Server[i].flags & CONF_SFLAG_DISABLED ))
1600 /* Is there already a connection in this group? */
1601 if( Conf_Server[i].group > NONE ) {
1602 for (n = 0; n < MAX_SERVERS; n++) {
1603 if (n == i) continue;
1604 if ((Conf_Server[n].conn_id != NONE) &&
1605 (Conf_Server[n].group == Conf_Server[i].group))
1608 if (n < MAX_SERVERS) continue;
1611 /* Check last connect attempt? */
1612 time_now = time(NULL);
1613 if( Conf_Server[i].lasttry > (time_now - Conf_ConnectRetry))
1616 /* Okay, try to connect now */
1617 Conf_Server[i].lasttry = time_now;
1618 Conf_Server[i].conn_id = SERVER_WAIT;
1619 assert(Resolve_Getfd(&Conf_Server[i].res_stat) < 0);
1620 Resolve_Name(&Conf_Server[i].res_stat, Conf_Server[i].host, cb_Connect_to_Server);
1622 } /* Check_Servers */
1626 New_Server( int Server , ng_ipaddr_t *dest)
1628 /* Establish new server link */
1629 char ip_str[NG_INET_ADDRSTRLEN];
1630 int af_dest, res, new_sock;
1633 assert( Server > NONE );
1635 if (!ng_ipaddr_tostr_r(dest, ip_str)) {
1636 Log(LOG_WARNING, "New_Server: Could not convert IP to string");
1640 Log( LOG_INFO, "Establishing connection to \"%s\", %s, port %d ... ",
1641 Conf_Server[Server].host, ip_str, Conf_Server[Server].port );
1643 af_dest = ng_ipaddr_af(dest);
1644 new_sock = socket(af_dest, SOCK_STREAM, 0);
1646 Log( LOG_CRIT, "Can't create socket (af %d) : %s!", af_dest, strerror( errno ));
1650 if (!Init_Socket(new_sock))
1653 /* is a bind address configured? */
1654 res = ng_ipaddr_af(&Conf_Server[Server].bind_addr);
1655 /* if yes, bind now. If it fails, warn and let connect() pick a source address */
1656 if (res && bind(new_sock, (struct sockaddr *) &Conf_Server[Server].bind_addr,
1657 ng_ipaddr_salen(&Conf_Server[Server].bind_addr)))
1659 ng_ipaddr_tostr_r(&Conf_Server[Server].bind_addr, ip_str);
1660 Log(LOG_WARNING, "Can't bind socket to %s: %s!", ip_str, strerror(errno));
1662 ng_ipaddr_setport(dest, Conf_Server[Server].port);
1663 res = connect(new_sock, (struct sockaddr *) dest, ng_ipaddr_salen(dest));
1664 if(( res != 0 ) && ( errno != EINPROGRESS )) {
1665 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1670 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)new_sock)) {
1672 "Cannot allocate memory for server connection (socket %d)",
1678 My_Connections = array_start(&My_ConnArray);
1680 assert(My_Connections[new_sock].sock <= 0);
1682 Init_Conn_Struct(new_sock);
1684 ng_ipaddr_tostr_r(dest, ip_str);
1685 c = Client_NewLocal(new_sock, ip_str, CLIENT_UNKNOWNSERVER, false);
1687 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1692 Client_SetIntroducer( c, c );
1693 Client_SetToken( c, TOKEN_OUTBOUND );
1695 /* Register connection */
1696 Conf_Server[Server].conn_id = new_sock;
1697 My_Connections[new_sock].sock = new_sock;
1698 My_Connections[new_sock].addr = *dest;
1699 My_Connections[new_sock].client = c;
1700 strlcpy( My_Connections[new_sock].host, Conf_Server[Server].host,
1701 sizeof(My_Connections[new_sock].host ));
1703 /* Register new socket */
1704 if (!io_event_create( new_sock, IO_WANTWRITE, cb_connserver)) {
1705 Log( LOG_ALERT, "io_event_create(): could not add fd %d", strerror(errno));
1706 Conn_Close( new_sock, "io_event_create() failed", NULL, false );
1707 Init_Conn_Struct( new_sock );
1708 Conf_Server[Server].conn_id = NONE;
1711 if (Conf_Server[Server].SSLConnect && !ConnSSL_PrepareConnect( &My_Connections[new_sock],
1712 &Conf_Server[Server] ))
1714 Log(LOG_ALERT, "Could not initialize SSL for outgoing connection");
1715 Conn_Close( new_sock, "Could not initialize SSL for outgoing connection", NULL, false );
1716 Init_Conn_Struct( new_sock );
1717 Conf_Server[Server].conn_id = NONE;
1720 LogDebug("Registered new connection %d on socket %d.",
1721 new_sock, My_Connections[new_sock].sock );
1722 Conn_OPTION_ADD( &My_Connections[new_sock], CONN_ISCONNECTING );
1727 * Initialize connection structure.
1730 Init_Conn_Struct(CONN_ID Idx)
1732 time_t now = time(NULL);
1734 memset(&My_Connections[Idx], 0, sizeof(CONNECTION));
1735 My_Connections[Idx].sock = -1;
1736 My_Connections[Idx].signon = now;
1737 My_Connections[Idx].lastdata = now;
1738 My_Connections[Idx].lastprivmsg = now;
1739 Resolve_Init(&My_Connections[Idx].res_stat);
1740 } /* Init_Conn_Struct */
1744 Init_Socket( int Sock )
1746 /* Initialize socket (set options) */
1750 if (!io_setnonblock(Sock)) {
1751 Log( LOG_CRIT, "Can't enable non-blocking mode for socket: %s!", strerror( errno ));
1756 /* Don't block this port after socket shutdown */
1758 if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &value, (socklen_t)sizeof( value )) != 0 )
1760 Log( LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!", strerror( errno ));
1761 /* ignore this error */
1764 /* Set type of service (TOS) */
1765 #if defined(IP_TOS) && defined(IPTOS_LOWDELAY)
1766 value = IPTOS_LOWDELAY;
1767 LogDebug("Setting option IP_TOS on socket %d to IPTOS_LOWDELAY (%d).", Sock, value );
1768 if( setsockopt( Sock, SOL_IP, IP_TOS, &value, (socklen_t)sizeof( value )) != 0 )
1770 Log( LOG_ERR, "Can't set socket option IP_TOS: %s!", strerror( errno ));
1771 /* ignore this error */
1781 cb_Connect_to_Server(int fd, UNUSED short events)
1783 /* Read result of resolver sub-process from pipe and start connection */
1786 ng_ipaddr_t dest_addrs[4]; /* we can handle at most 3; but we read up to
1787 four so we can log the 'more than we can handle'
1790 LogDebug("Resolver: Got forward lookup callback on fd %d, events %d", fd, events);
1792 for (i=0; i < MAX_SERVERS; i++) {
1793 if (Resolve_Getfd(&Conf_Server[i].res_stat) == fd )
1797 if( i >= MAX_SERVERS) {
1798 /* Ops, no matching server found?! */
1800 LogDebug("Resolver: Got Forward Lookup callback for unknown server!?");
1804 /* Read result from pipe */
1805 len = Resolve_Read(&Conf_Server[i].res_stat, dest_addrs, sizeof(dest_addrs));
1809 assert((len % sizeof(ng_ipaddr_t)) == 0);
1811 LogDebug("Got result from resolver: %u structs (%u bytes).", len/sizeof(ng_ipaddr_t), len);
1813 memset(&Conf_Server[i].dst_addr, 0, sizeof(&Conf_Server[i].dst_addr));
1814 if (len > sizeof(ng_ipaddr_t)) {
1815 /* more than one address for this hostname, remember them
1816 * in case first address is unreachable/not available */
1817 len -= sizeof(ng_ipaddr_t);
1818 if (len > sizeof(&Conf_Server[i].dst_addr)) {
1819 len = sizeof(&Conf_Server[i].dst_addr);
1820 Log(LOG_NOTICE, "Notice: Resolver returned more IP Addresses for host than we can handle,"
1821 " additional addresses dropped");
1823 memcpy(&Conf_Server[i].dst_addr, &dest_addrs[1], len);
1826 New_Server(i, dest_addrs);
1827 } /* cb_Read_Forward_Lookup */
1831 cb_Read_Resolver_Result( int r_fd, UNUSED short events )
1833 /* Read result of resolver sub-process from pipe and update the
1834 * apropriate connection/client structure(s): hostname and/or
1835 * IDENT user name.*/
1842 char readbuf[HOST_LEN + 2 + CLIENT_USER_LEN];
1844 char readbuf[HOST_LEN + 1];
1847 LogDebug("Resolver: Got callback on fd %d, events %d", r_fd, events );
1849 /* Search associated connection ... */
1850 for( i = 0; i < Pool_Size; i++ ) {
1851 if(( My_Connections[i].sock != NONE )
1852 && ( Resolve_Getfd(&My_Connections[i].res_stat) == r_fd ))
1855 if( i >= Pool_Size ) {
1856 /* Ops, none found? Probably the connection has already
1857 * been closed!? We'll ignore that ... */
1859 LogDebug("Resolver: Got callback for unknown connection!?");
1863 /* Read result from pipe */
1864 len = Resolve_Read(&My_Connections[i].res_stat, readbuf, sizeof readbuf -1);
1868 readbuf[len] = '\0';
1869 identptr = strchr(readbuf, '\n');
1870 assert(identptr != NULL);
1872 Log( LOG_CRIT, "Resolver: Got malformed result!");
1877 LogDebug("Got result from resolver: \"%s\" (%u bytes read).", readbuf, len);
1878 /* Okay, we got a complete result: this is a host name for outgoing
1879 * connections and a host name and IDENT user name (if enabled) for
1880 * incoming connections.*/
1881 assert ( My_Connections[i].sock >= 0 );
1882 /* Incoming connection. Search client ... */
1883 c = Conn_GetClient( i );
1884 assert( c != NULL );
1886 /* Only update client information of unregistered clients */
1887 if( Client_Type( c ) == CLIENT_UNKNOWN ) {
1888 strlcpy(My_Connections[i].host, readbuf, sizeof( My_Connections[i].host));
1889 Client_SetHostname( c, readbuf);
1893 Log(LOG_INFO, "IDENT lookup for connection %d: \"%s\".", i, identptr);
1894 Client_SetUser(c, identptr, true);
1896 Log(LOG_INFO, "IDENT lookup for connection %d: no result.", i);
1901 else Log( LOG_DEBUG, "Resolver: discarding result for already registered connection %d.", i );
1903 /* Reset penalty time */
1904 Conn_ResetPenalty( i );
1905 } /* cb_Read_Resolver_Result */
1909 Simple_Message( int Sock, const char *Msg )
1911 char buf[COMMAND_LEN];
1913 /* Write "simple" message to socket, without using compression
1914 * or even the connection write buffers. Used e.g. for error
1915 * messages by New_Connection(). */
1916 assert( Sock > NONE );
1917 assert( Msg != NULL );
1919 strlcpy( buf, Msg, sizeof buf - 2);
1920 len = strlcat( buf, "\r\n", sizeof buf);
1921 (void)write(Sock, buf, len);
1922 } /* Simple_Error */
1926 Conn_GetClient( CONN_ID Idx )
1928 /* return Client-Structure that belongs to the local Connection Idx.
1929 * If none is found, return NULL.
1934 c = array_get(&My_ConnArray, sizeof (CONNECTION), (size_t)Idx);
1938 return c ? c->client : NULL;
1942 /* we cannot access My_Connections in irc-info.c */
1944 Conn_GetCipherInfo(CONN_ID Idx, char *buf, size_t len)
1946 return ConnSSL_GetCipherInfo(&My_Connections[Idx], buf, len);
1951 Conn_UsesSSL(CONN_ID Idx)
1953 return Conn_OPTION_ISSET(&My_Connections[Idx], CONN_SSL);