2 * ngIRCd -- The Next Generation IRC Daemon
3 * Copyright (c)2001-2011 Alexander Barton (alex@barton.de) and Contributors.
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.
22 * Connection management
37 #include <sys/socket.h>
39 #include <sys/types.h>
41 #include <netinet/in.h>
43 #ifdef HAVE_NETINET_IP_H
44 # ifdef HAVE_NETINET_IN_SYSTM_H
45 # include <netinet/in_systm.h>
47 # include <netinet/ip.h>
51 # include <stdint.h> /* e.g. for Mac OS X */
55 # include <tcpd.h> /* for TCP Wrappers */
71 #include "conn-func.h"
73 #include "ng_ipaddr.h"
81 #define SERVER_WAIT (NONE - 1)
83 #define MAX_COMMANDS 3
84 #define MAX_COMMANDS_SERVER 10
85 #define MAX_COMMANDS_SERVICE MAX_COMMANDS_SERVER
88 static bool Handle_Write PARAMS(( CONN_ID Idx ));
89 static bool Conn_Write PARAMS(( CONN_ID Idx, char *Data, size_t Len ));
90 static int New_Connection PARAMS(( int Sock ));
91 static CONN_ID Socket2Index PARAMS(( int Sock ));
92 static void Read_Request PARAMS(( CONN_ID Idx ));
93 static unsigned int Handle_Buffer PARAMS(( CONN_ID Idx ));
94 static void Check_Connections PARAMS(( void ));
95 static void Check_Servers PARAMS(( void ));
96 static void Init_Conn_Struct PARAMS(( CONN_ID Idx ));
97 static bool Init_Socket PARAMS(( int Sock ));
98 static void New_Server PARAMS(( int Server, ng_ipaddr_t *dest ));
99 static void Simple_Message PARAMS(( int Sock, const char *Msg ));
100 static int NewListener PARAMS(( const char *listen_addr, UINT16 Port ));
101 static void Account_Connection PARAMS((void));
104 static array My_Listeners;
105 static array My_ConnArray;
106 static size_t NumConnections, NumConnectionsMax, NumConnectionsAccepted;
109 int allow_severity = LOG_INFO;
110 int deny_severity = LOG_ERR;
113 static void server_login PARAMS((CONN_ID idx));
116 extern struct SSLOptions Conf_SSLOptions;
117 static void cb_connserver_login_ssl PARAMS((int sock, short what));
118 static void cb_clientserver_ssl PARAMS((int sock, short what));
120 static void cb_Read_Resolver_Result PARAMS((int sock, UNUSED short what));
121 static void cb_Connect_to_Server PARAMS((int sock, UNUSED short what));
122 static void cb_clientserver PARAMS((int sock, short what));
126 * IO callback for listening sockets: handle new connections. This callback
127 * gets called when a new non-SSL connection should be accepted.
129 * @param sock Socket descriptor.
130 * @param irrelevant (ignored IO specification)
133 cb_listen(int sock, short irrelevant)
136 (void) New_Connection(sock);
142 * IO callback for listening SSL sockets: handle new connections. This callback
143 * gets called when a new SSL-enabled connection should be accepted.
145 * @param sock Socket descriptor.
146 * @param irrelevant (ignored IO specification)
149 cb_listen_ssl(int sock, short irrelevant)
154 fd = New_Connection(sock);
157 io_event_setcb(My_Connections[fd].sock, cb_clientserver_ssl);
163 * IO callback for new outgoing non-SSL server connections.
165 * @param sock Socket descriptor.
166 * @param what IO specification (IO_WANTREAD/IO_WANTWRITE/...).
169 cb_connserver(int sock, UNUSED short what)
171 int res, err, server;
173 CONN_ID idx = Socket2Index( sock );
176 LogDebug("cb_connserver wants to write on unknown socket?!");
181 assert(what & IO_WANTWRITE);
183 /* Make sure that the server is still configured; it could have been
184 * removed in the meantime! */
185 server = Conf_GetServer(idx);
187 Log(LOG_ERR, "Connection on socket %d to \"%s\" aborted!",
188 sock, My_Connections[idx].host);
189 Conn_Close(idx, "Connection aborted!", NULL, false);
193 /* connect() finished, get result. */
194 sock_len = (socklen_t)sizeof(err);
195 res = getsockopt(My_Connections[idx].sock, SOL_SOCKET, SO_ERROR,
197 assert(sock_len == sizeof(err));
199 /* Error while connecting? */
200 if ((res != 0) || (err != 0)) {
202 Log(LOG_CRIT, "getsockopt (connection %d): %s!",
203 idx, strerror(errno));
206 "Can't connect socket to \"%s:%d\" (connection %d): %s!",
207 My_Connections[idx].host, Conf_Server[server].port,
210 Conn_Close(idx, "Can't connect!", NULL, false);
212 if (ng_ipaddr_af(&Conf_Server[server].dst_addr[0])) {
213 /* more addresses to try... */
214 New_Server(server, &Conf_Server[server].dst_addr[0]);
215 /* connection to dst_addr[0] is now in progress, so
216 * remove this address... */
217 Conf_Server[server].dst_addr[0] =
218 Conf_Server[server].dst_addr[1];
219 memset(&Conf_Server[server].dst_addr[1], 0,
220 sizeof(Conf_Server[server].dst_addr[1]));
225 /* connect() succeeded, remove all additional addresses */
226 memset(&Conf_Server[server].dst_addr, 0,
227 sizeof(Conf_Server[server].dst_addr));
229 Conn_OPTION_DEL( &My_Connections[idx], CONN_ISCONNECTING );
231 if ( Conn_OPTION_ISSET( &My_Connections[idx], CONN_SSL_CONNECT )) {
232 io_event_setcb( sock, cb_connserver_login_ssl );
233 io_event_add( sock, IO_WANTWRITE|IO_WANTREAD );
242 * Login to a remote server.
244 * @param idx Connection index.
247 server_login(CONN_ID idx)
250 "Connection %d (socket %d) with \"%s:%d\" established. Now logging in ...",
251 idx, My_Connections[idx].sock, My_Connections[idx].host,
252 Conf_Server[Conf_GetServer(idx)].port);
254 io_event_setcb( My_Connections[idx].sock, cb_clientserver);
255 io_event_add( My_Connections[idx].sock, IO_WANTREAD|IO_WANTWRITE);
257 /* Send PASS and SERVER command to peer */
258 Conn_WriteStr( idx, "PASS %s %s", Conf_Server[Conf_GetServer( idx )].pwd_out, NGIRCd_ProtoID );
259 Conn_WriteStr( idx, "SERVER %s :%s", Conf_ServerName, Conf_ServerInfo );
265 * IO callback for new outgoing SSL-enabled server connections.
267 * @param sock Socket descriptor.
268 * @param unused (ignored IO specification)
271 cb_connserver_login_ssl(int sock, short unused)
273 CONN_ID idx = Socket2Index(sock);
281 switch (ConnSSL_Connect( &My_Connections[idx])) {
283 case 0: LogDebug("ConnSSL_Connect: not ready");
286 Log(LOG_ERR, "SSL connection on socket %d failed!", sock);
287 Conn_Close(idx, "Can't connect!", NULL, false);
291 Log( LOG_INFO, "SSL connection %d with \"%s:%d\" established.", idx,
292 My_Connections[idx].host, Conf_Server[Conf_GetServer( idx )].port );
300 * IO callback for established non-SSL client and server connections.
302 * @param sock Socket descriptor.
303 * @param what IO specification (IO_WANTREAD/IO_WANTWRITE/...).
306 cb_clientserver(int sock, short what)
308 CONN_ID idx = Socket2Index(sock);
317 if (what & IO_WANTREAD
318 || (Conn_OPTION_ISSET(&My_Connections[idx], CONN_SSL_WANT_WRITE))) {
319 /* if TLS layer needs to write additional data, call
320 * Read_Request() instead so that SSL/TLS can continue */
324 if (what & IO_WANTREAD)
327 if (what & IO_WANTWRITE)
334 * IO callback for established SSL-enabled client and server connections.
336 * @param sock Socket descriptor.
337 * @param what IO specification (IO_WANTREAD/IO_WANTWRITE/...).
340 cb_clientserver_ssl(int sock, short what)
342 CONN_ID idx = Socket2Index(sock);
351 switch (ConnSSL_Accept(&My_Connections[idx])) {
355 return; /* EAGAIN: callback will be invoked again by IO layer */
357 Conn_Close(idx, "SSL accept error, closing socket", "SSL accept error", false);
360 if (what & IO_WANTREAD)
363 if (what & IO_WANTWRITE)
366 io_event_setcb(sock, cb_clientserver); /* SSL handshake completed */
372 * Initialite connecion module.
379 /* Speicher fuer Verbindungs-Pool anfordern */
380 Pool_Size = CONNECTION_POOL;
381 if ((Conf_MaxConnections > 0) &&
382 (Pool_Size > Conf_MaxConnections))
383 Pool_Size = Conf_MaxConnections;
385 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)Pool_Size)) {
386 Log(LOG_EMERG, "Can't allocate memory! [Conn_Init]");
390 /* FIXME: My_Connetions/Pool_Size is needed by other parts of the
391 * code; remove them! */
392 My_Connections = (CONNECTION*) array_start(&My_ConnArray);
394 LogDebug("Allocated connection pool for %d items (%ld bytes).",
395 array_length(&My_ConnArray, sizeof(CONNECTION)),
396 array_bytes(&My_ConnArray));
398 assert(array_length(&My_ConnArray, sizeof(CONNECTION)) >= (size_t)Pool_Size);
400 array_free( &My_Listeners );
402 for (i = 0; i < Pool_Size; i++)
408 * Clean up connection module.
415 Conn_ExitListeners();
417 LogDebug("Shutting down all connections ..." );
418 for( idx = 0; idx < Pool_Size; idx++ ) {
419 if( My_Connections[idx].sock > NONE ) {
420 Conn_Close( idx, NULL, NGIRCd_SignalRestart ?
421 "Server going down (restarting)":"Server going down", true );
425 array_free(&My_ConnArray);
426 My_Connections = NULL;
428 io_library_shutdown();
433 * Close all sockets (file descriptors) of open connections.
434 * This is useful in forked child processes, for example, to make sure that
435 * they don't hold connections open that the main process wants to close.
438 Conn_CloseAllSockets(int ExceptOf)
442 for(idx = 0; idx < Pool_Size; idx++) {
443 if(My_Connections[idx].sock > NONE &&
444 My_Connections[idx].sock != ExceptOf)
445 close(My_Connections[idx].sock);
451 * Initialize listening ports.
453 * @param a Array containing the ports the daemon should listen on.
454 * @param listen_addr Address the socket should listen on (can be "0.0.0.0").
455 * @param func IO callback function to register.
456 * @returns Number of listening sockets created.
459 ports_initlisteners(array *a, const char *listen_addr, void (*func)(int,short))
461 unsigned int created = 0;
466 len = array_length(a, sizeof (UINT16));
467 port = array_start(a);
469 fd = NewListener(listen_addr, *port);
474 if (!io_event_create( fd, IO_WANTREAD, func )) {
475 Log( LOG_ERR, "io_event_create(): Could not add listening fd %d (port %u): %s!",
476 fd, (unsigned int) *port, strerror(errno));
489 * Initialize all listening sockets.
491 * @returns Number of created listening sockets
494 Conn_InitListeners( void )
496 /* Initialize ports on which the server should accept connections */
497 unsigned int created = 0;
498 char *copy, *listen_addr;
500 assert(Conf_ListenAddress);
502 /* can't use Conf_ListenAddress directly, see below */
503 copy = strdup(Conf_ListenAddress);
505 Log(LOG_CRIT, "Cannot copy %s: %s", Conf_ListenAddress, strerror(errno));
508 listen_addr = strtok(copy, ",");
510 while (listen_addr) {
511 ngt_TrimStr(listen_addr);
513 created += ports_initlisteners(&Conf_ListenPorts, listen_addr, cb_listen);
515 created += ports_initlisteners(&Conf_SSLOptions.ListenPorts, listen_addr, cb_listen_ssl);
519 listen_addr = strtok(NULL, ",");
522 /* Can't free() Conf_ListenAddress here: on REHASH, if the config file
523 * cannot be re-loaded, we'd end up with a NULL Conf_ListenAddress.
524 * Instead, free() takes place in conf.c, before the config file
525 * is being parsed. */
529 } /* Conn_InitListeners */
533 * Shut down all listening sockets.
536 Conn_ExitListeners( void )
538 /* Close down all listening sockets */
542 arraylen = array_length(&My_Listeners, sizeof (int));
544 "Shutting down all listening sockets (%d total) ...", arraylen);
545 fd = array_start(&My_Listeners);
550 LogDebug("Listening socket %d closed.", *fd );
553 array_free(&My_Listeners);
554 } /* Conn_ExitListeners */
558 * Bind a socket to a specific (source) address.
560 * @param addr Address structure.
561 * @param listen_addrstr Source address as string.
562 * @param Port Port number.
563 * @returns true on success, false otherwise.
566 InitSinaddrListenAddr(ng_ipaddr_t *addr, const char *listen_addrstr, UINT16 Port)
570 ret = ng_ipaddr_init(addr, listen_addrstr, Port);
572 assert(listen_addrstr);
573 Log(LOG_CRIT, "Can't bind to [%s]:%u: can't convert ip address \"%s\"",
574 listen_addrstr, Port, listen_addrstr);
581 * Set a socket to "IPv6 only". If the given socket doesn't belong to the
582 * AF_INET6 family, or the operating system doesn't support this functionality,
583 * this function retruns silently.
585 * @param af Address family of the socket.
586 * @param sock Socket handle.
589 set_v6_only(int af, int sock)
591 #if defined(IPV6_V6ONLY) && defined(WANT_IPV6)
597 if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, (socklen_t)sizeof(on)))
598 Log(LOG_ERR, "Could not set IPV6_V6ONLY: %s", strerror(errno));
607 * Initialize new listening port.
609 * @param listen_addr Local address to bind the socet to (can be 0.0.0.0).
610 * @param Port Port number on which the new socket should be listening.
611 * @returns file descriptor of the socket or -1 on failure.
614 NewListener(const char *listen_addr, UINT16 Port)
616 /* Create new listening socket on specified port */
620 if (!InitSinaddrListenAddr(&addr, listen_addr, Port))
623 af = ng_ipaddr_af(&addr);
624 sock = socket(af, SOCK_STREAM, 0);
626 Log(LOG_CRIT, "Can't create socket (af %d) : %s!", af, strerror(errno));
630 set_v6_only(af, sock);
632 if (!Init_Socket(sock))
635 if (bind(sock, (struct sockaddr *)&addr, ng_ipaddr_salen(&addr)) != 0) {
636 Log(LOG_CRIT, "Can't bind socket to address %s:%d - %s",
637 ng_ipaddr_tostr(&addr), Port, strerror(errno));
642 if( listen( sock, 10 ) != 0 ) {
643 Log( LOG_CRIT, "Can't listen on socket: %s!", strerror( errno ));
648 /* keep fd in list so we can close it when ngircd restarts/shuts down */
649 if (!array_catb( &My_Listeners,(char*) &sock, sizeof(int) )) {
650 Log( LOG_CRIT, "Can't add socket to My_Listeners array: %s!", strerror( errno ));
655 Log(LOG_INFO, "Now listening on [%s]:%d (socket %d).",
656 ng_ipaddr_tostr(&addr), Port, sock);
664 * Check if SSL library needs to read SSL-protocol related data.
666 * SSL/TLS connections require extra treatment:
667 * When either CONN_SSL_WANT_WRITE or CONN_SSL_WANT_READ is set, we
668 * need to take care of that first, before checking read/write buffers.
669 * For instance, while we might have data in our write buffer, the
670 * TLS/SSL protocol might need to read internal data first for TLS/SSL
673 * If this function returns true, such a condition is met and we have
674 * to reverse the condition (check for read even if we've data to write,
675 * do not check for read but writeability even if write-buffer is empty).
677 * @param c Connection to check.
678 * @returns true if SSL-library has to read protocol data.
681 SSL_WantRead(const CONNECTION *c)
683 if (Conn_OPTION_ISSET(c, CONN_SSL_WANT_READ)) {
684 io_event_add(c->sock, IO_WANTREAD);
691 * Check if SSL library needs to write SSL-protocol related data.
693 * Please see description of SSL_WantRead() for full description!
695 * @param c Connection to check.
696 * @returns true if SSL-library has to write protocol data.
699 SSL_WantWrite(const CONNECTION *c)
701 if (Conn_OPTION_ISSET(c, CONN_SSL_WANT_WRITE)) {
702 io_event_add(c->sock, IO_WANTWRITE);
711 SSL_WantRead(UNUSED const CONNECTION *c)
715 SSL_WantWrite(UNUSED const CONNECTION *c)
722 * "Main Loop": Loop until shutdown or restart is signalled.
724 * This function loops until a shutdown or restart of ngIRCd is signalled and
725 * calls io_dispatch() to check for readable and writable sockets every second.
726 * It checks for status changes on pending connections (e. g. when a hostname
727 * has been resolved), checks for "penalties" and timeouts, and handles the
734 unsigned int wdatalen, bytes_processed;
738 while (!NGIRCd_SignalQuit && !NGIRCd_SignalRestart) {
741 /* Check configured servers and established links */
745 /* Look for non-empty read buffers ... */
746 for (i = 0; i < Pool_Size; i++) {
747 if ((My_Connections[i].sock > NONE)
748 && (array_bytes(&My_Connections[i].rbuf) > 0)
749 && (My_Connections[i].delaytime <= t)) {
750 /* ... and try to handle the received data */
751 bytes_processed = Handle_Buffer(i);
752 /* if we processed data, and there might be
753 * more commands in the input buffer, do not
754 * try to read any more data now */
755 if (bytes_processed &&
756 array_bytes(&My_Connections[i].rbuf) > 2) {
758 ("Throttling connection %d: command limit reached!",
760 Conn_SetPenalty(i, 1);
765 /* Look for non-empty write buffers ... */
766 for (i = 0; i < Pool_Size; i++) {
767 if (My_Connections[i].sock <= NONE)
770 wdatalen = (unsigned int)array_bytes(&My_Connections[i].wbuf);
773 array_bytes(&My_Connections[i].zip.wbuf) > 0)
778 if (SSL_WantRead(&My_Connections[i]))
780 io_event_add(My_Connections[i].sock,
785 /* Check from which sockets we possibly could read ... */
786 for (i = 0; i < Pool_Size; i++) {
787 if (My_Connections[i].sock <= NONE)
790 if (SSL_WantWrite(&My_Connections[i]))
791 continue; /* TLS/SSL layer needs to write data; deal with this first */
793 if (Proc_InProgress(&My_Connections[i].proc_stat)) {
794 /* Wait for completion of forked subprocess
795 * and ignore the socket in the meantime ... */
796 io_event_del(My_Connections[i].sock,
801 if (Conn_OPTION_ISSET(&My_Connections[i], CONN_ISCONNECTING))
802 /* Wait for completion of connect() ... */
805 if (My_Connections[i].delaytime > t) {
806 /* There is a "penalty time" set: ignore socket! */
807 io_event_del(My_Connections[i].sock,
812 io_event_add(My_Connections[i].sock, IO_WANTREAD);
815 /* Set the timeout for reading from the network to 1 second,
816 * which is the granularity with witch we handle "penalty
817 * times" for example.
818 * Note: tv_sec/usec are undefined(!) after io_dispatch()
819 * returns, so we have to set it beforce each call to it! */
823 /* Wait for activity ... */
824 i = io_dispatch(&tv);
825 if (i == -1 && errno != EINTR) {
826 Log(LOG_EMERG, "Conn_Handler(): io_dispatch(): %s!",
828 Log(LOG_ALERT, "%s exiting due to fatal errors!",
834 if (NGIRCd_SignalQuit)
835 Log(LOG_NOTICE | LOG_snotice, "Server going down NOW!");
836 else if (NGIRCd_SignalRestart)
837 Log(LOG_NOTICE | LOG_snotice, "Server restarting NOW!");
842 * Write a text string into the socket of a connection.
844 * This function automatically appends CR+LF to the string and validates that
845 * the result is a valid IRC message (oversized messages are shortened, for
846 * example). Then it calls the Conn_Write() function to do the actual sending.
848 * @param Idx Index fo the connection.
849 * @param Format Format string, see printf().
850 * @returns true on success, false otherwise.
854 Conn_WriteStr(CONN_ID Idx, const char *Format, ...)
857 Conn_WriteStr(Idx, Format, va_alist)
863 char buffer[COMMAND_LEN];
868 assert( Idx > NONE );
869 assert( Format != NULL );
872 va_start( ap, Format );
876 if (vsnprintf( buffer, COMMAND_LEN - 2, Format, ap ) >= COMMAND_LEN - 2 ) {
878 * The string that should be written to the socket is longer
879 * than the allowed size of COMMAND_LEN bytes (including both
880 * the CR and LF characters). This can be caused by the
881 * IRC_WriteXXX() functions when the prefix of this server had
882 * to be added to an already "quite long" command line which
883 * has been received from a regular IRC client, for example.
885 * We are not allowed to send such "oversized" messages to
886 * other servers and clients, see RFC 2812 2.3 and 2813 3.3
887 * ("these messages SHALL NOT exceed 512 characters in length,
888 * counting all characters including the trailing CR-LF").
890 * So we have a big problem here: we should send more bytes
891 * to the network than we are allowed to and we don't know
892 * the originator (any more). The "old" behaviour of blaming
893 * the receiver ("next hop") is a bad idea (it could be just
894 * an other server only routing the message!), so the only
895 * option left is to shorten the string and to hope that the
896 * result is still somewhat useful ...
900 strcpy (buffer + sizeof(buffer) - strlen(CUT_TXTSUFFIX) - 2 - 1,
906 Log(LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer);
909 len = strlcat( buffer, "\r\n", sizeof( buffer ));
910 ok = Conn_Write(Idx, buffer, len);
911 My_Connections[Idx].msg_out++;
915 } /* Conn_WriteStr */
919 * Append Data to the outbound write buffer of a connection.
921 * @param Idx Index of the connection.
922 * @param Data pointer to the data.
923 * @param Len length of Data.
924 * @returns true on success, false otherwise.
927 Conn_Write( CONN_ID Idx, char *Data, size_t Len )
930 size_t writebuf_limit = WRITEBUFFER_MAX_LEN;
931 assert( Idx > NONE );
932 assert( Data != NULL );
935 c = Conn_GetClient(Idx);
938 /* Servers do get special write buffer limits, so they can generate
939 * all the messages that are required while peering. */
940 if (Client_Type(c) == CLIENT_SERVER)
941 writebuf_limit = WRITEBUFFER_SLINK_LEN;
943 /* Is the socket still open? A previous call to Conn_Write()
944 * may have closed the connection due to a fatal error.
945 * In this case it is sufficient to return an error, as well. */
946 if( My_Connections[Idx].sock <= NONE ) {
947 LogDebug("Skipped write on closed socket (connection %d).", Idx);
952 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
954 * Zip_Buffer() does all the dirty work for us: it flushes
955 * the (pre-)compression buffers if required and handles
956 * all error conditions. */
957 if (!Zip_Buffer(Idx, Data, Len))
963 /* Uncompressed link:
964 * Check if outbound buffer has enough space for the data. */
965 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
966 WRITEBUFFER_FLUSH_LEN) {
967 /* Buffer is full, flush it. Handle_Write deals with
968 * low-level errors, if any. */
969 if (!Handle_Write(Idx))
973 /* When the write buffer is still too big after flushing it,
974 * the connection will be killed. */
975 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
978 "Write buffer space exhausted (connection %d, limit is %lu bytes, %lu bytes new, %lu bytes pending)",
979 Idx, writebuf_limit, Len,
980 (unsigned long)array_bytes(&My_Connections[Idx].wbuf));
981 Conn_Close(Idx, "Write buffer space exhausted", NULL, false);
985 /* Copy data to write buffer */
986 if (!array_catb(&My_Connections[Idx].wbuf, Data, Len))
989 My_Connections[Idx].bytes_out += Len;
992 /* Adjust global write counter */
1000 * Shut down a connection.
1002 * @param Idx Connection index.
1003 * @param LogMsg Message to write to the log or NULL. If no LogMsg
1004 * is given, the FwdMsg is logged.
1005 * @param FwdMsg Message to forward to remote servers.
1006 * @param InformClient If true, inform the client on the connection which is
1007 * to be shut down of the reason (FwdMsg) and send
1008 * connection statistics before disconnecting it.
1011 Conn_Close( CONN_ID Idx, const char *LogMsg, const char *FwdMsg, bool InformClient )
1013 /* Close connection. Open pipes of asyncronous resolver
1014 * sub-processes are closed down. */
1020 double in_z_k, out_z_k;
1024 assert( Idx > NONE );
1026 /* Is this link already shutting down? */
1027 if( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ISCLOSING )) {
1028 /* Conn_Close() has been called recursively for this link;
1029 * probabe reason: Handle_Write() failed -- see below. */
1030 LogDebug("Recursive request to close connection: %d", Idx );
1034 assert( My_Connections[Idx].sock > NONE );
1036 /* Mark link as "closing" */
1037 Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCLOSING );
1039 port = ng_ipaddr_getport(&My_Connections[Idx].addr);
1040 Log(LOG_INFO, "Shutting down connection %d (%s) with %s:%d ...", Idx,
1041 LogMsg ? LogMsg : FwdMsg, My_Connections[Idx].host, port);
1043 /* Search client, if any */
1044 c = Conn_GetClient( Idx );
1046 /* Should the client be informed? */
1049 /* Send statistics to client if registered as user: */
1050 if ((c != NULL) && (Client_Type(c) == CLIENT_USER)) {
1052 ":%s NOTICE %s :%sConnection statistics: client %.1f kb, server %.1f kb.",
1053 Client_ID(Client_ThisServer()), Client_ID(c),
1055 (double)My_Connections[Idx].bytes_in / 1024,
1056 (double)My_Connections[Idx].bytes_out / 1024);
1059 /* Send ERROR to client (see RFC 2812, section 3.1.7) */
1061 Conn_WriteStr(Idx, "ERROR :%s", FwdMsg);
1063 Conn_WriteStr(Idx, "ERROR :Closing connection");
1066 /* Try to write out the write buffer. Note: Handle_Write() eventually
1067 * removes the CLIENT structure associated with this connection if an
1068 * error occurs! So we have to re-check if there is still an valid
1069 * CLIENT structure after calling Handle_Write() ...*/
1070 (void)Handle_Write( Idx );
1072 /* Search client, if any (re-check!) */
1073 c = Conn_GetClient( Idx );
1075 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_SSL )) {
1076 Log(LOG_INFO, "SSL connection %d shutting down ...", Idx);
1077 ConnSSL_Free(&My_Connections[Idx]);
1080 /* Shut down socket */
1081 if (! io_close(My_Connections[Idx].sock)) {
1082 /* Oops, we can't close the socket!? This is ... ugly! */
1084 "Error closing connection %d (socket %d) with %s:%d - %s! (ignored)",
1085 Idx, My_Connections[Idx].sock, My_Connections[Idx].host,
1086 port, strerror(errno));
1089 /* Mark socket as invalid: */
1090 My_Connections[Idx].sock = NONE;
1092 /* If there is still a client, unregister it now */
1094 Client_Destroy(c, LogMsg, FwdMsg, true);
1096 /* Calculate statistics and log information */
1097 in_k = (double)My_Connections[Idx].bytes_in / 1024;
1098 out_k = (double)My_Connections[Idx].bytes_out / 1024;
1100 if (Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP)) {
1101 in_z_k = (double)My_Connections[Idx].zip.bytes_in / 1024;
1102 out_z_k = (double)My_Connections[Idx].zip.bytes_out / 1024;
1103 /* Make sure that no division by zero can occur during
1104 * the calculation of in_p and out_p: in_z_k and out_z_k
1105 * are non-zero, that's guaranteed by the protocol until
1106 * compression can be enabled. */
1111 in_p = (int)(( in_k * 100 ) / in_z_k );
1112 out_p = (int)(( out_k * 100 ) / out_z_k );
1114 "Connection %d with %s:%d closed (in: %.1fk/%.1fk/%d%%, out: %.1fk/%.1fk/%d%%).",
1115 Idx, My_Connections[Idx].host, port,
1116 in_k, in_z_k, in_p, out_k, out_z_k, out_p);
1122 "Connection %d with %s:%d closed (in: %.1fk, out: %.1fk).",
1123 Idx, My_Connections[Idx].host, port,
1127 /* Servers: Modify time of next connect attempt? */
1128 Conf_UnsetServer( Idx );
1131 /* Clean up zlib, if link was compressed */
1132 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
1133 inflateEnd( &My_Connections[Idx].zip.in );
1134 deflateEnd( &My_Connections[Idx].zip.out );
1135 array_free(&My_Connections[Idx].zip.rbuf);
1136 array_free(&My_Connections[Idx].zip.wbuf);
1140 array_free(&My_Connections[Idx].rbuf);
1141 array_free(&My_Connections[Idx].wbuf);
1143 /* Clean up connection structure (=free it) */
1144 Init_Conn_Struct( Idx );
1146 assert(NumConnections > 0);
1149 LogDebug("Shutdown of connection %d completed, %ld connection%s left.",
1150 Idx, NumConnections, NumConnections != 1 ? "s" : "");
1155 * Get current number of connections.
1157 * @returns Number of current connections.
1162 return NumConnections;
1167 * Get number of maximum simultaneous connections.
1169 * @returns Number of maximum simultaneous connections.
1174 return NumConnectionsMax;
1175 } /* Conn_CountMax */
1179 * Get number of connections accepted since the daemon startet.
1181 * @returns Number of connections accepted.
1184 Conn_CountAccepted(void)
1186 return NumConnectionsAccepted;
1187 } /* Conn_CountAccepted */
1191 * Synchronize established connections and configured server structures
1192 * after a configuration update and store the correct connection IDs, if any.
1195 Conn_SyncServerStruct(void)
1201 for (i = 0; i < Pool_Size; i++) {
1202 if (My_Connections[i].sock == NONE)
1206 client = Conn_GetClient(i);
1207 if (!client || Client_Type(client) != CLIENT_SERVER)
1210 for (c = 0; c < MAX_SERVERS; c++) {
1211 /* Configured server? */
1212 if (!Conf_Server[c].host[0])
1215 if (strcasecmp(Conf_Server[c].name, Client_ID(client)) == 0)
1216 Conf_Server[c].conn_id = i;
1219 } /* SyncServerStruct */
1223 * Send out data of write buffer; connect new sockets.
1225 * @param Idx Connection index.
1226 * @returns true on success, false otherwise.
1229 Handle_Write( CONN_ID Idx )
1234 assert( Idx > NONE );
1235 if ( My_Connections[Idx].sock < 0 ) {
1236 LogDebug("Handle_Write() on closed socket, connection %d", Idx);
1239 assert( My_Connections[Idx].sock > NONE );
1241 wdatalen = array_bytes(&My_Connections[Idx].wbuf );
1244 if (wdatalen == 0) {
1245 /* Write buffer is empty, so we try to flush the compression
1246 * buffer and get some data to work with from there :-) */
1247 if (!Zip_Flush(Idx))
1250 /* Now the write buffer most probably has changed: */
1251 wdatalen = array_bytes(&My_Connections[Idx].wbuf);
1255 if (wdatalen == 0) {
1256 /* Still no data, fine. */
1257 io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
1263 ("Handle_Write() called for connection %d, %ld bytes pending ...",
1268 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_SSL )) {
1269 len = ConnSSL_Write(&My_Connections[Idx], array_start(&My_Connections[Idx].wbuf), wdatalen);
1273 len = write(My_Connections[Idx].sock,
1274 array_start(&My_Connections[Idx].wbuf), wdatalen );
1277 if (errno == EAGAIN || errno == EINTR)
1280 Log(LOG_ERR, "Write error on connection %d (socket %d): %s!",
1281 Idx, My_Connections[Idx].sock, strerror(errno));
1282 Conn_Close(Idx, "Write error!", NULL, false);
1286 /* move any data not yet written to beginning */
1287 array_moveleft(&My_Connections[Idx].wbuf, 1, (size_t)len);
1290 } /* Handle_Write */
1294 * Count established connections to a specific IP address.
1296 * @returns Number of established connections.
1299 Count_Connections(ng_ipaddr_t *a)
1304 for (i = 0; i < Pool_Size; i++) {
1305 if (My_Connections[i].sock <= NONE)
1307 if (ng_ipaddr_ipequal(&My_Connections[i].addr, a))
1311 } /* Count_Connections */
1315 * Initialize new client connection on a listening socket.
1317 * @param Sock Listening socket descriptor.
1318 * @returns Accepted socket descriptor or -1 on error.
1321 New_Connection(int Sock)
1324 struct request_info req;
1326 ng_ipaddr_t new_addr;
1327 char ip_str[NG_INET_ADDRSTRLEN];
1328 int new_sock, new_sock_len, identsock;
1332 assert(Sock > NONE);
1334 LogDebug("Accepting new connection on socket %d ...", Sock);
1336 new_sock_len = (int)sizeof(new_addr);
1337 new_sock = accept(Sock, (struct sockaddr *)&new_addr,
1338 (socklen_t *)&new_sock_len);
1340 Log(LOG_CRIT, "Can't accept connection: %s!", strerror(errno));
1343 NumConnectionsAccepted++;
1345 if (!ng_ipaddr_tostr_r(&new_addr, ip_str)) {
1346 Log(LOG_CRIT, "fd %d: Can't convert IP address!", new_sock);
1347 Simple_Message(new_sock, "ERROR :Internal Server Error");
1353 /* Validate socket using TCP Wrappers */
1354 request_init(&req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock,
1355 RQ_CLIENT_SIN, &new_addr, NULL);
1357 if (!hosts_access(&req)) {
1359 "Refused connection from %s (by TCP Wrappers)!", ip_str);
1360 Simple_Message(new_sock, "ERROR :Connection refused");
1366 if (!Init_Socket(new_sock))
1369 /* Check global connection limit */
1370 if ((Conf_MaxConnections > 0) &&
1371 (NumConnections >= (size_t) Conf_MaxConnections)) {
1372 Log(LOG_ALERT, "Can't accept connection: limit (%d) reached!",
1373 Conf_MaxConnections);
1374 Simple_Message(new_sock, "ERROR :Connection limit reached");
1379 /* Check IP-based connection limit */
1380 cnt = Count_Connections(&new_addr);
1381 if ((Conf_MaxConnectionsIP > 0) && (cnt >= Conf_MaxConnectionsIP)) {
1382 /* Access denied, too many connections from this IP address! */
1384 "Refused connection from %s: too may connections (%ld) from this IP address!",
1386 Simple_Message(new_sock,
1387 "ERROR :Connection refused, too many connections from your IP address");
1392 if (new_sock >= Pool_Size) {
1393 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION),
1394 (size_t) new_sock)) {
1396 "Can't allocate memory! [New_Connection]");
1397 Simple_Message(new_sock, "ERROR: Internal error");
1401 LogDebug("Bumped connection pool to %ld items (internal: %ld items, %ld bytes)",
1402 new_sock, array_length(&My_ConnArray,
1403 sizeof(CONNECTION)), array_bytes(&My_ConnArray));
1405 /* Adjust pointer to new block */
1406 My_Connections = array_start(&My_ConnArray);
1407 while (Pool_Size <= new_sock)
1408 Init_Conn_Struct(Pool_Size++);
1411 /* register callback */
1412 if (!io_event_create(new_sock, IO_WANTREAD, cb_clientserver)) {
1414 "Can't accept connection: io_event_create failed!");
1415 Simple_Message(new_sock, "ERROR :Internal error");
1420 c = Client_NewLocal(new_sock, ip_str, CLIENT_UNKNOWN, false);
1423 "Can't accept connection: can't create client structure!");
1424 Simple_Message(new_sock, "ERROR :Internal error");
1429 Init_Conn_Struct(new_sock);
1430 My_Connections[new_sock].sock = new_sock;
1431 My_Connections[new_sock].addr = new_addr;
1432 My_Connections[new_sock].client = c;
1434 /* Set initial hostname to IP address. This becomes overwritten when
1435 * the DNS lookup is enabled and succeeds, but is used otherwise. */
1436 if (ng_ipaddr_af(&new_addr) != AF_INET)
1437 snprintf(My_Connections[new_sock].host,
1438 sizeof(My_Connections[new_sock].host), "[%s]", ip_str);
1440 strlcpy(My_Connections[new_sock].host, ip_str,
1441 sizeof(My_Connections[new_sock].host));
1443 Client_SetHostname(c, My_Connections[new_sock].host);
1445 Log(LOG_INFO, "Accepted connection %d from %s:%d on socket %d.",
1446 new_sock, My_Connections[new_sock].host,
1447 ng_ipaddr_getport(&new_addr), Sock);
1449 identsock = new_sock;
1455 if (Conf_NoticeAuth) {
1458 (void)Conn_WriteStr(new_sock,
1459 "NOTICE AUTH :*** Looking up your hostname and checking ident");
1462 (void)Conn_WriteStr(new_sock,
1463 "NOTICE AUTH :*** Looking up your hostname");
1465 Resolve_Addr(&My_Connections[new_sock].proc_stat, &new_addr,
1466 identsock, cb_Read_Resolver_Result);
1469 Account_Connection();
1471 } /* New_Connection */
1475 * Update global connection counters.
1478 Account_Connection(void)
1481 if (NumConnections > NumConnectionsMax)
1482 NumConnectionsMax = NumConnections;
1483 LogDebug("Total number of connections now %lu (max %lu).",
1484 NumConnections, NumConnectionsMax);
1485 } /* Account_Connection */
1489 * Translate socket handle into connection index.
1491 * @param Sock Socket handle.
1492 * @returns Connecion index or NONE, if no connection could be found.
1495 Socket2Index( int Sock )
1497 assert( Sock >= 0 );
1499 if( Sock >= Pool_Size || My_Connections[Sock].sock != Sock ) {
1500 /* the Connection was already closed again, likely due to
1502 LogDebug("Socket2Index: can't get connection for socket %d!", Sock);
1506 } /* Socket2Index */
1510 * Read data from the network to the read buffer. If an error occures,
1511 * the socket of this connection will be shut down.
1513 * @param Idx Connection index.
1516 Read_Request( CONN_ID Idx )
1519 static const unsigned int maxbps = COMMAND_LEN / 2;
1520 char readbuf[READBUFFER_LEN];
1523 assert( Idx > NONE );
1524 assert( My_Connections[Idx].sock > NONE );
1527 if ((array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN) ||
1528 (array_bytes(&My_Connections[Idx].zip.rbuf) >= READBUFFER_LEN))
1530 if (array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN)
1533 /* Read buffer is full */
1535 "Receive buffer space exhausted (connection %d): %d bytes",
1536 Idx, array_bytes(&My_Connections[Idx].rbuf));
1537 Conn_Close(Idx, "Receive buffer space exhausted", NULL, false);
1542 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_SSL))
1543 len = ConnSSL_Read( &My_Connections[Idx], readbuf, sizeof(readbuf));
1546 len = read(My_Connections[Idx].sock, readbuf, sizeof(readbuf));
1548 Log(LOG_INFO, "%s:%u (%s) is closing the connection ...",
1549 My_Connections[Idx].host,
1550 (unsigned int) ng_ipaddr_getport(&My_Connections[Idx].addr),
1551 ng_ipaddr_tostr(&My_Connections[Idx].addr));
1553 "Socket closed!", "Client closed connection",
1559 if( errno == EAGAIN ) return;
1560 Log(LOG_ERR, "Read error on connection %d (socket %d): %s!",
1561 Idx, My_Connections[Idx].sock, strerror(errno));
1562 Conn_Close(Idx, "Read error!", "Client closed connection",
1567 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1568 if (!array_catb(&My_Connections[Idx].zip.rbuf, readbuf,
1571 "Could not append recieved data to zip input buffer (connn %d): %d bytes!",
1573 Conn_Close(Idx, "Receive buffer space exhausted", NULL,
1580 if (!array_catb( &My_Connections[Idx].rbuf, readbuf, len)) {
1581 Log( LOG_ERR, "Could not append recieved data to input buffer (connn %d): %d bytes!", Idx, len );
1582 Conn_Close(Idx, "Receive buffer space exhausted", NULL, false );
1586 /* Update connection statistics */
1587 My_Connections[Idx].bytes_in += len;
1588 My_Connections[Idx].bps += Handle_Buffer(Idx);
1590 /* Make sure that there is still a valid client registered */
1591 c = Conn_GetClient(Idx);
1595 /* Update timestamp of last data received if this connection is
1596 * registered as a user, server or service connection. Don't update
1597 * otherwise, so users have at least Conf_PongTimeout seconds time to
1598 * register with the IRC server -- see Check_Connections().
1599 * Update "lastping", too, if time shifted backwards ... */
1600 if (Client_Type(c) == CLIENT_USER
1601 || Client_Type(c) == CLIENT_SERVER
1602 || Client_Type(c) == CLIENT_SERVICE) {
1604 if (My_Connections[Idx].lastdata != t)
1605 My_Connections[Idx].bps = 0;
1607 My_Connections[Idx].lastdata = t;
1608 if (My_Connections[Idx].lastping > t)
1609 My_Connections[Idx].lastping = t;
1612 /* Look at the data in the (read-) buffer of this connection */
1613 if (Client_Type(c) != CLIENT_SERVER
1614 && Client_Type(c) != CLIENT_UNKNOWNSERVER
1615 && Client_Type(c) != CLIENT_SERVICE
1616 && My_Connections[Idx].bps >= maxbps) {
1617 LogDebug("Throttling connection %d: BPS exceeded! (%u >= %u)",
1618 Idx, My_Connections[Idx].bps, maxbps);
1619 Conn_SetPenalty(Idx, 1);
1621 } /* Read_Request */
1625 * Handle all data in the connection read-buffer.
1627 * Data is processed until no complete command is left in the read buffer,
1628 * or MAX_COMMANDS[_SERVER|_SERVICE] commands were processed.
1629 * When a fatal error occurs, the connection is shut down.
1631 * @param Idx Index of the connection.
1632 * @returns Number of bytes processed.
1635 Handle_Buffer(CONN_ID Idx)
1638 char *ptr1, *ptr2, *first_eol;
1646 unsigned int i, maxcmd = MAX_COMMANDS, len_processed = 0;
1649 c = Conn_GetClient(Idx);
1650 starttime = time(NULL);
1654 /* Servers do get special command limits, so they can process
1655 * all the messages that are required while peering. */
1656 switch (Client_Type(c)) {
1658 /* Allow servers to send more commands in the first 10 secods
1659 * to speed up server login and network synchronisation. */
1660 if (starttime - Client_StartTime(c) < 10)
1661 maxcmd = MAX_COMMANDS_SERVER * 5;
1663 maxcmd = MAX_COMMANDS_SERVER;
1665 case CLIENT_SERVICE:
1666 maxcmd = MAX_COMMANDS_SERVICE; break;
1669 for (i=0; i < maxcmd; i++) {
1671 if (My_Connections[Idx].delaytime > starttime)
1674 /* Unpack compressed data, if compression is in use */
1675 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1676 /* When unzipping fails, Unzip_Buffer() shuts
1677 * down the connection itself */
1678 if (!Unzip_Buffer(Idx))
1683 if (0 == array_bytes(&My_Connections[Idx].rbuf))
1686 /* Make sure that the buffer is NULL terminated */
1687 if (!array_cat0_temporary(&My_Connections[Idx].rbuf)) {
1688 Conn_Close(Idx, NULL,
1689 "Can't allocate memory [Handle_Buffer]",
1694 /* RFC 2812, section "2.3 Messages", 5th paragraph:
1695 * "IRC messages are always lines of characters terminated
1696 * with a CR-LF (Carriage Return - Line Feed) pair [...]". */
1698 ptr = strstr(array_start(&My_Connections[Idx].rbuf), "\r\n");
1701 /* Check for non-RFC-compliant request (only CR or LF)?
1702 * Unfortunately, there are quite a few clients out there
1703 * that do this -- e. g. mIRC, BitchX, and Trillian :-( */
1704 ptr1 = strchr(array_start(&My_Connections[Idx].rbuf), '\r');
1705 ptr2 = strchr(array_start(&My_Connections[Idx].rbuf), '\n');
1707 /* Check if there is a single CR or LF _before_ the
1708 * corerct CR+LF line terminator: */
1709 first_eol = ptr1 < ptr2 ? ptr1 : ptr2;
1710 if (first_eol < ptr) {
1711 /* Single CR or LF before CR+LF found */
1715 } else if (ptr1 || ptr2) {
1716 /* No CR+LF terminated command found, but single
1717 * CR or LF found ... */
1719 ptr = ptr1 < ptr2 ? ptr1 : ptr2;
1721 ptr = ptr1 ? ptr1 : ptr2;
1729 /* Complete (=line terminated) request found, handle it! */
1732 len = ptr - (char *)array_start(&My_Connections[Idx].rbuf) + delta;
1734 if (len > (COMMAND_LEN - 1)) {
1735 /* Request must not exceed 512 chars (incl. CR+LF!),
1736 * see RFC 2812. Disconnect Client if this happens. */
1738 "Request too long (connection %d): %d bytes (max. %d expected)!",
1739 Idx, array_bytes(&My_Connections[Idx].rbuf),
1741 Conn_Close(Idx, NULL, "Request too long", true);
1745 len_processed += (unsigned int)len;
1747 /* Request is empty (only '\r\n', '\r' or '\n');
1748 * delta is 2 ('\r\n') or 1 ('\r' or '\n'), see above */
1749 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1753 /* remember if stream is already compressed */
1754 old_z = My_Connections[Idx].options & CONN_ZIP;
1757 My_Connections[Idx].msg_in++;
1759 (Idx, (char *)array_start(&My_Connections[Idx].rbuf)))
1760 return 0; /* error -> connection has been closed */
1762 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1764 LogDebug("Connection %d: %d bytes left in read buffer.",
1765 Idx, array_bytes(&My_Connections[Idx].rbuf));
1768 if ((!old_z) && (My_Connections[Idx].options & CONN_ZIP) &&
1769 (array_bytes(&My_Connections[Idx].rbuf) > 0)) {
1770 /* The last command activated socket compression.
1771 * Data that was read after that needs to be copied
1772 * to the unzip buffer for decompression: */
1774 (&My_Connections[Idx].zip.rbuf,
1775 &My_Connections[Idx].rbuf)) {
1776 Conn_Close(Idx, NULL,
1777 "Can't allocate memory [Handle_Buffer]",
1782 array_trunc(&My_Connections[Idx].rbuf);
1784 ("Moved already received data (%u bytes) to uncompression buffer.",
1785 array_bytes(&My_Connections[Idx].zip.rbuf));
1789 return len_processed;
1790 } /* Handle_Buffer */
1794 * Check whether established connections are still alive or not.
1795 * If not, play PING-PONG first; and if that doesn't help either,
1796 * disconnect the respective peer.
1799 Check_Connections(void)
1805 for (i = 0; i < Pool_Size; i++) {
1806 if (My_Connections[i].sock < 0)
1809 c = Conn_GetClient(i);
1810 if (c && ((Client_Type(c) == CLIENT_USER)
1811 || (Client_Type(c) == CLIENT_SERVER)
1812 || (Client_Type(c) == CLIENT_SERVICE))) {
1813 /* connected User, Server or Service */
1814 if (My_Connections[i].lastping >
1815 My_Connections[i].lastdata) {
1816 /* We already sent a ping */
1817 if (My_Connections[i].lastping <
1818 time(NULL) - Conf_PongTimeout) {
1821 ("Connection %d: Ping timeout: %d seconds.",
1822 i, Conf_PongTimeout);
1823 snprintf(msg, sizeof(msg), "Ping timeout: %d seconds", Conf_PongTimeout);
1824 Conn_Close(i, NULL, msg, true);
1826 } else if (My_Connections[i].lastdata <
1827 time(NULL) - Conf_PingTimeout) {
1828 /* We need to send a PING ... */
1829 LogDebug("Connection %d: sending PING ...", i);
1830 My_Connections[i].lastping = time(NULL);
1831 Conn_WriteStr(i, "PING :%s",
1832 Client_ID(Client_ThisServer()));
1835 /* The connection is not fully established yet, so
1836 * we don't do the PING-PONG game here but instead
1837 * disconnect the client after "a short time" if it's
1838 * still not registered. */
1840 if (My_Connections[i].lastdata <
1841 time(NULL) - Conf_PongTimeout) {
1843 ("Unregistered connection %d timed out ...",
1845 Conn_Close(i, NULL, "Timeout", false);
1849 } /* Check_Connections */
1853 * Check if further server links should be established.
1861 time_now = time(NULL);
1863 /* Check all configured servers */
1864 for (i = 0; i < MAX_SERVERS; i++) {
1865 if (Conf_Server[i].conn_id != NONE)
1866 continue; /* Already establishing or connected */
1867 if (!Conf_Server[i].host[0] || !Conf_Server[i].port > 0)
1868 continue; /* No host and/or port configured */
1869 if (Conf_Server[i].flags & CONF_SFLAG_DISABLED)
1870 continue; /* Disabled configuration entry */
1871 if (Conf_Server[i].lasttry > (time_now - Conf_ConnectRetry))
1872 continue; /* We have to wait a little bit ... */
1874 /* Is there already a connection in this group? */
1875 if (Conf_Server[i].group > NONE) {
1876 for (n = 0; n < MAX_SERVERS; n++) {
1879 if ((Conf_Server[n].conn_id != NONE) &&
1880 (Conf_Server[n].group == Conf_Server[i].group))
1883 if (n < MAX_SERVERS)
1887 /* Okay, try to connect now */
1889 "Preparing to establish a new server link for \"%s\" ...",
1890 Conf_Server[i].name);
1891 Conf_Server[i].lasttry = time_now;
1892 Conf_Server[i].conn_id = SERVER_WAIT;
1893 assert(Proc_GetPipeFd(&Conf_Server[i].res_stat) < 0);
1894 Resolve_Name(&Conf_Server[i].res_stat, Conf_Server[i].host,
1895 cb_Connect_to_Server);
1897 } /* Check_Servers */
1901 * Establish a new outgoing server connection.
1903 * @param Server Configuration index of the server.
1904 * @param dest Destination IP address to connect to.
1907 New_Server( int Server , ng_ipaddr_t *dest)
1909 /* Establish new server link */
1910 char ip_str[NG_INET_ADDRSTRLEN];
1911 int af_dest, res, new_sock;
1914 assert( Server > NONE );
1916 if (!ng_ipaddr_tostr_r(dest, ip_str)) {
1917 Log(LOG_WARNING, "New_Server: Could not convert IP to string");
1921 af_dest = ng_ipaddr_af(dest);
1922 new_sock = socket(af_dest, SOCK_STREAM, 0);
1925 "Establishing connection for \"%s\" to \"%s:%d\" (%s), socket %d ...",
1926 Conf_Server[Server].name, Conf_Server[Server].host,
1927 Conf_Server[Server].port, ip_str, new_sock);
1930 Log(LOG_CRIT, "Can't create socket (af %d): %s!",
1931 af_dest, strerror(errno));
1935 if (!Init_Socket(new_sock))
1938 /* is a bind address configured? */
1939 res = ng_ipaddr_af(&Conf_Server[Server].bind_addr);
1940 /* if yes, bind now. If it fails, warn and let connect() pick a source address */
1941 if (res && bind(new_sock, (struct sockaddr *) &Conf_Server[Server].bind_addr,
1942 ng_ipaddr_salen(&Conf_Server[Server].bind_addr)))
1944 ng_ipaddr_tostr_r(&Conf_Server[Server].bind_addr, ip_str);
1945 Log(LOG_WARNING, "Can't bind socket to %s: %s!", ip_str, strerror(errno));
1947 ng_ipaddr_setport(dest, Conf_Server[Server].port);
1948 res = connect(new_sock, (struct sockaddr *) dest, ng_ipaddr_salen(dest));
1949 if(( res != 0 ) && ( errno != EINPROGRESS )) {
1950 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1955 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)new_sock)) {
1957 "Cannot allocate memory for server connection (socket %d)",
1963 if (!io_event_create( new_sock, IO_WANTWRITE, cb_connserver)) {
1964 Log(LOG_ALERT, "io_event_create(): could not add fd %d", strerror(errno));
1969 My_Connections = array_start(&My_ConnArray);
1971 assert(My_Connections[new_sock].sock <= 0);
1973 Init_Conn_Struct(new_sock);
1975 ng_ipaddr_tostr_r(dest, ip_str);
1976 c = Client_NewLocal(new_sock, ip_str, CLIENT_UNKNOWNSERVER, false);
1978 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1983 /* Conn_Close() decrements this counter again */
1984 Account_Connection();
1985 Client_SetIntroducer( c, c );
1986 Client_SetToken( c, TOKEN_OUTBOUND );
1988 /* Register connection */
1989 Conf_Server[Server].conn_id = new_sock;
1990 My_Connections[new_sock].sock = new_sock;
1991 My_Connections[new_sock].addr = *dest;
1992 My_Connections[new_sock].client = c;
1993 strlcpy( My_Connections[new_sock].host, Conf_Server[Server].host,
1994 sizeof(My_Connections[new_sock].host ));
1997 if (Conf_Server[Server].SSLConnect && !ConnSSL_PrepareConnect( &My_Connections[new_sock],
1998 &Conf_Server[Server] ))
2000 Log(LOG_ALERT, "Could not initialize SSL for outgoing connection");
2001 Conn_Close( new_sock, "Could not initialize SSL for outgoing connection", NULL, false );
2002 Init_Conn_Struct( new_sock );
2003 Conf_Server[Server].conn_id = NONE;
2007 LogDebug("Registered new connection %d on socket %d (%ld in total).",
2008 new_sock, My_Connections[new_sock].sock, NumConnections);
2009 Conn_OPTION_ADD( &My_Connections[new_sock], CONN_ISCONNECTING );
2014 * Initialize connection structure.
2016 * @param Idx Connection index.
2019 Init_Conn_Struct(CONN_ID Idx)
2021 time_t now = time(NULL);
2023 memset(&My_Connections[Idx], 0, sizeof(CONNECTION));
2024 My_Connections[Idx].sock = -1;
2025 My_Connections[Idx].signon = now;
2026 My_Connections[Idx].lastdata = now;
2027 My_Connections[Idx].lastprivmsg = now;
2028 Proc_InitStruct(&My_Connections[Idx].proc_stat);
2029 } /* Init_Conn_Struct */
2033 * Initialize options of a new socket.
2035 * For example, we try to set socket options SO_REUSEADDR and IPTOS_LOWDELAY.
2036 * The socket is automatically closed if a fatal error is encountered.
2038 * @param Sock Socket handle.
2039 * @returns false if socket was closed due to fatal error.
2042 Init_Socket( int Sock )
2046 if (!io_setnonblock(Sock)) {
2047 Log( LOG_CRIT, "Can't enable non-blocking mode for socket: %s!", strerror( errno ));
2052 /* Don't block this port after socket shutdown */
2054 if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &value, (socklen_t)sizeof( value )) != 0 )
2056 Log( LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!", strerror( errno ));
2057 /* ignore this error */
2060 /* Set type of service (TOS) */
2061 #if defined(IPPROTO_IP) && defined(IPTOS_LOWDELAY)
2062 value = IPTOS_LOWDELAY;
2063 if (setsockopt(Sock, IPPROTO_IP, IP_TOS, &value,
2064 (socklen_t) sizeof(value))) {
2065 LogDebug("Can't set socket option IP_TOS: %s!",
2067 /* ignore this error */
2069 LogDebug("IP_TOS on socket %d has been set to IPTOS_LOWDELAY.",
2078 * Read results of a resolver sub-process and try to initiate a new server
2081 * @param fd File descriptor of the pipe to the sub-process.
2082 * @param events (ignored IO specification)
2085 cb_Connect_to_Server(int fd, UNUSED short events)
2087 /* Read result of resolver sub-process from pipe and start connection */
2090 ng_ipaddr_t dest_addrs[4]; /* we can handle at most 3; but we read up to
2091 four so we can log the 'more than we can handle'
2092 condition. First result is tried immediately, rest
2093 is saved for later if needed. */
2095 LogDebug("Resolver: Got forward lookup callback on fd %d, events %d", fd, events);
2097 for (i=0; i < MAX_SERVERS; i++) {
2098 if (Proc_GetPipeFd(&Conf_Server[i].res_stat) == fd )
2102 if( i >= MAX_SERVERS) {
2103 /* Ops, no matching server found?! */
2105 LogDebug("Resolver: Got Forward Lookup callback for unknown server!?");
2109 /* Read result from pipe */
2110 len = Proc_Read(&Conf_Server[i].res_stat, dest_addrs, sizeof(dest_addrs));
2111 Proc_Close(&Conf_Server[i].res_stat);
2113 /* Error resolving hostname: reset server structure */
2114 Conf_Server[i].conn_id = NONE;
2118 assert((len % sizeof(ng_ipaddr_t)) == 0);
2120 LogDebug("Got result from resolver: %u structs (%u bytes).", len/sizeof(ng_ipaddr_t), len);
2122 memset(&Conf_Server[i].dst_addr, 0, sizeof(Conf_Server[i].dst_addr));
2123 if (len > sizeof(ng_ipaddr_t)) {
2124 /* more than one address for this hostname, remember them
2125 * in case first address is unreachable/not available */
2126 len -= sizeof(ng_ipaddr_t);
2127 if (len > sizeof(Conf_Server[i].dst_addr)) {
2128 len = sizeof(Conf_Server[i].dst_addr);
2130 "Notice: Resolver returned more IP Addresses for host than we can handle, additional addresses dropped.");
2132 memcpy(&Conf_Server[i].dst_addr, &dest_addrs[1], len);
2135 New_Server(i, dest_addrs);
2136 } /* cb_Read_Forward_Lookup */
2140 * Read results of a resolver sub-process from the pipe and update the
2141 * apropriate connection/client structure(s): hostname and/or IDENT user name.
2143 * @param r_fd File descriptor of the pipe to the sub-process.
2144 * @param events (ignored IO specification)
2147 cb_Read_Resolver_Result( int r_fd, UNUSED short events )
2154 char readbuf[HOST_LEN + 2 + CLIENT_USER_LEN];
2156 char readbuf[HOST_LEN + 1];
2159 LogDebug("Resolver: Got callback on fd %d, events %d", r_fd, events );
2160 i = Conn_GetFromProc(r_fd);
2162 /* Ops, none found? Probably the connection has already
2163 * been closed!? We'll ignore that ... */
2165 LogDebug("Resolver: Got callback for unknown connection!?");
2169 /* Read result from pipe */
2170 len = Proc_Read(&My_Connections[i].proc_stat, readbuf, sizeof readbuf -1);
2171 Proc_Close(&My_Connections[i].proc_stat);
2175 readbuf[len] = '\0';
2176 identptr = strchr(readbuf, '\n');
2177 assert(identptr != NULL);
2179 Log( LOG_CRIT, "Resolver: Got malformed result!");
2184 LogDebug("Got result from resolver: \"%s\" (%u bytes read).", readbuf, len);
2185 /* Okay, we got a complete result: this is a host name for outgoing
2186 * connections and a host name and IDENT user name (if enabled) for
2187 * incoming connections.*/
2188 assert ( My_Connections[i].sock >= 0 );
2189 /* Incoming connection. Search client ... */
2190 c = Conn_GetClient( i );
2191 assert( c != NULL );
2193 /* Only update client information of unregistered clients.
2194 * Note: user commands (e. g. WEBIRC) are always read _after_ reading
2195 * the resolver results, so we don't have to worry to override settings
2196 * from these commands here. */
2197 if(Client_Type(c) == CLIENT_UNKNOWN) {
2198 strlcpy(My_Connections[i].host, readbuf,
2199 sizeof(My_Connections[i].host));
2200 Client_SetHostname(c, readbuf);
2201 if (Conf_NoticeAuth)
2202 (void)Conn_WriteStr(i,
2203 "NOTICE AUTH :*** Found your hostname");
2207 Log(LOG_INFO, "IDENT lookup for connection %d: \"%s\".", i, identptr);
2208 Client_SetUser(c, identptr, true);
2209 if (Conf_NoticeAuth)
2210 (void)Conn_WriteStr(i,
2211 "NOTICE AUTH :*** Got ident response");
2213 Log(LOG_INFO, "IDENT lookup for connection %d: no result.", i);
2214 if (Conf_NoticeAuth && Conf_Ident)
2215 (void)Conn_WriteStr(i,
2216 "NOTICE AUTH :*** No ident response");
2221 else Log( LOG_DEBUG, "Resolver: discarding result for already registered connection %d.", i );
2223 } /* cb_Read_Resolver_Result */
2227 * Write a "simple" (error) message to a socket.
2229 * The message is sent without using the connection write buffers, without
2230 * compression/encryption, and even without any error reporting. It is
2231 * designed for error messages of e.g. New_Connection().
2233 * @param Sock Socket handle.
2234 * @param Msg Message string to send.
2237 Simple_Message(int Sock, const char *Msg)
2239 char buf[COMMAND_LEN];
2242 assert(Sock > NONE);
2243 assert(Msg != NULL);
2245 strlcpy(buf, Msg, sizeof buf - 2);
2246 len = strlcat(buf, "\r\n", sizeof buf);
2247 if (write(Sock, buf, len) < 0) {
2248 /* Because this function most probably got called to log
2249 * an error message, any write error is ignored here to
2250 * avoid an endless loop. But casting the result of write()
2251 * to "void" doesn't satisfy the GNU C code attribute
2252 * "warn_unused_result" which is used by some versions of
2253 * glibc (e.g. 2.11.1), therefore this silly error
2254 * "handling" code here :-( */
2257 } /* Simple_Error */
2261 * Get CLIENT structure that belongs to a local connection identified by its
2262 * index number. Each connection belongs to a client by definition, so it is
2263 * not required that the caller checks for NULL return values.
2265 * @param Idx Connection index number.
2266 * @returns Pointer to CLIENT structure.
2269 Conn_GetClient( CONN_ID Idx )
2274 c = array_get(&My_ConnArray, sizeof (CONNECTION), (size_t)Idx);
2276 return c ? c->client : NULL;
2280 * Get PROC_STAT sub-process structure of a connection.
2282 * @param Idx Connection index number.
2283 * @returns PROC_STAT structure.
2286 Conn_GetProcStat(CONN_ID Idx)
2291 c = array_get(&My_ConnArray, sizeof (CONNECTION), (size_t)Idx);
2293 return &c->proc_stat;
2294 } /* Conn_GetProcStat */
2298 * Get CONN_ID from file descriptor associated to a subprocess structure.
2300 * @param fd File descriptor.
2301 * @returns CONN_ID or NONE (-1).
2304 Conn_GetFromProc(int fd)
2309 for (i = 0; i < Pool_Size; i++) {
2310 if ((My_Connections[i].sock != NONE)
2311 && (Proc_GetPipeFd(&My_Connections[i].proc_stat) == fd))
2315 } /* Conn_GetFromProc */
2321 Conn_GetAuthPing(CONN_ID Idx)
2323 assert (Idx != NONE);
2324 return My_Connections[Idx].auth_ping;
2325 } /* Conn_GetAuthPing */
2328 Conn_SetAuthPing(CONN_ID Idx, long ID)
2330 assert (Idx != NONE);
2331 My_Connections[Idx].auth_ping = ID;
2332 } /* Conn_SetAuthPing */
2340 * Get information about used SSL chiper.
2342 * @param Idx Connection index number.
2343 * @param buf Buffer for returned information text.
2344 * @param len Size of return buffer "buf".
2345 * @returns true on success, false otherwise.
2348 Conn_GetCipherInfo(CONN_ID Idx, char *buf, size_t len)
2352 assert(Idx < (int) array_length(&My_ConnArray, sizeof(CONNECTION)));
2353 return ConnSSL_GetCipherInfo(&My_Connections[Idx], buf, len);
2358 * Check if a connection is SSL-enabled or not.
2360 * @param Idx Connection index number.
2361 * @return true if connection is SSL-enabled, false otherwise.
2364 Conn_UsesSSL(CONN_ID Idx)
2368 assert(Idx < (int) array_length(&My_ConnArray, sizeof(CONNECTION)));
2369 return Conn_OPTION_ISSET(&My_Connections[Idx], CONN_SSL);
2378 * Dump internal state of the "connection module".
2381 Conn_DebugDump(void)
2385 Log(LOG_DEBUG, "Connection status:");
2386 for (i = 0; i < Pool_Size; i++) {
2387 if (My_Connections[i].sock == NONE)
2390 " - %d: host=%s, lastdata=%ld, lastping=%ld, delaytime=%ld, flag=%d, options=%d, bps=%d, client=%s",
2391 My_Connections[i].sock, My_Connections[i].host,
2392 My_Connections[i].lastdata, My_Connections[i].lastping,
2393 My_Connections[i].delaytime, My_Connections[i].flag,
2394 My_Connections[i].options, My_Connections[i].bps,
2395 My_Connections[i].client ? Client_ID(My_Connections[i].client) : "-");
2397 } /* Conn_DumpClients */