2 * ngIRCd -- The Next Generation IRC Daemon
3 * Copyright (c)2001-2010 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.
20 * Connection management
35 #include <sys/socket.h>
37 #include <sys/types.h>
39 #include <netinet/in.h>
41 #ifdef HAVE_NETINET_IP_H
42 # ifdef HAVE_NETINET_IN_SYSTM_H
43 # include <netinet/in_systm.h>
45 # include <netinet/ip.h>
49 # include <stdint.h> /* e.g. for Mac OS X */
53 # include <tcpd.h> /* for TCP Wrappers */
69 #include "conn-func.h"
71 #include "ng_ipaddr.h"
79 #define SERVER_WAIT (NONE - 1)
81 #define MAX_COMMANDS 3
82 #define MAX_COMMANDS_SERVER 10
83 #define MAX_COMMANDS_SERVICE MAX_COMMANDS_SERVER
86 static bool Handle_Write PARAMS(( CONN_ID Idx ));
87 static bool Conn_Write PARAMS(( CONN_ID Idx, char *Data, size_t Len ));
88 static int New_Connection PARAMS(( int Sock ));
89 static CONN_ID Socket2Index PARAMS(( int Sock ));
90 static void Read_Request PARAMS(( CONN_ID Idx ));
91 static unsigned int Handle_Buffer PARAMS(( CONN_ID Idx ));
92 static void Check_Connections PARAMS(( void ));
93 static void Check_Servers PARAMS(( void ));
94 static void Init_Conn_Struct PARAMS(( CONN_ID Idx ));
95 static bool Init_Socket PARAMS(( int Sock ));
96 static void New_Server PARAMS(( int Server, ng_ipaddr_t *dest ));
97 static void Simple_Message PARAMS(( int Sock, const char *Msg ));
98 static int NewListener PARAMS(( const char *listen_addr, UINT16 Port ));
99 static void Account_Connection PARAMS((void));
102 static array My_Listeners;
103 static array My_ConnArray;
104 static size_t NumConnections, NumConnectionsMax, NumConnectionsAccepted;
107 int allow_severity = LOG_INFO;
108 int deny_severity = LOG_ERR;
111 static void server_login PARAMS((CONN_ID idx));
114 extern struct SSLOptions Conf_SSLOptions;
115 static void cb_connserver_login_ssl PARAMS((int sock, short what));
116 static void cb_clientserver_ssl PARAMS((int sock, short what));
118 static void cb_Read_Resolver_Result PARAMS((int sock, UNUSED short what));
119 static void cb_Connect_to_Server PARAMS((int sock, UNUSED short what));
120 static void cb_clientserver PARAMS((int sock, short what));
124 * IO callback for listening sockets: handle new connections. This callback
125 * gets called when a new non-SSL connection should be accepted.
127 * @param sock Socket descriptor.
128 * @param irrelevant (ignored IO specification)
131 cb_listen(int sock, short irrelevant)
134 (void) New_Connection(sock);
140 * IO callback for listening SSL sockets: handle new connections. This callback
141 * gets called when a new SSL-enabled connection should be accepted.
143 * @param sock Socket descriptor.
144 * @param irrelevant (ignored IO specification)
147 cb_listen_ssl(int sock, short irrelevant)
152 fd = New_Connection(sock);
155 io_event_setcb(My_Connections[fd].sock, cb_clientserver_ssl);
161 * IO callback for new outgoing non-SSL server connections.
163 * @param sock Socket descriptor.
164 * @param what IO specification (IO_WANTREAD/IO_WANTWRITE/...).
167 cb_connserver(int sock, UNUSED short what)
169 int res, err, server;
171 CONN_ID idx = Socket2Index( sock );
174 LogDebug("cb_connserver wants to write on unknown socket?!");
179 assert(what & IO_WANTWRITE);
181 /* Make sure that the server is still configured; it could have been
182 * removed in the meantime! */
183 server = Conf_GetServer(idx);
185 Log(LOG_ERR, "Connection on socket %d to \"%s\" aborted!",
186 sock, My_Connections[idx].host);
187 Conn_Close(idx, "Connection aborted!", NULL, false);
191 /* connect() finished, get result. */
192 sock_len = (socklen_t)sizeof(err);
193 res = getsockopt(My_Connections[idx].sock, SOL_SOCKET, SO_ERROR,
195 assert(sock_len == sizeof(err));
197 /* Error while connecting? */
198 if ((res != 0) || (err != 0)) {
200 Log(LOG_CRIT, "getsockopt (connection %d): %s!",
201 idx, strerror(errno));
204 "Can't connect socket to \"%s:%d\" (connection %d): %s!",
205 My_Connections[idx].host, Conf_Server[server].port,
208 Conn_Close(idx, "Can't connect!", NULL, false);
210 if (ng_ipaddr_af(&Conf_Server[server].dst_addr[0])) {
211 /* more addresses to try... */
212 New_Server(server, &Conf_Server[server].dst_addr[0]);
213 /* connection to dst_addr[0] is now in progress, so
214 * remove this address... */
215 Conf_Server[server].dst_addr[0] =
216 Conf_Server[server].dst_addr[1];
217 memset(&Conf_Server[server].dst_addr[1], 0,
218 sizeof(Conf_Server[server].dst_addr[1]));
223 /* connect() succeeded, remove all additional addresses */
224 memset(&Conf_Server[server].dst_addr, 0,
225 sizeof(Conf_Server[server].dst_addr));
227 Conn_OPTION_DEL( &My_Connections[idx], CONN_ISCONNECTING );
229 if ( Conn_OPTION_ISSET( &My_Connections[idx], CONN_SSL_CONNECT )) {
230 io_event_setcb( sock, cb_connserver_login_ssl );
231 io_event_add( sock, IO_WANTWRITE|IO_WANTREAD );
240 * Login to a remote server.
242 * @param idx Connection index.
245 server_login(CONN_ID idx)
248 "Connection %d (socket %d) with \"%s:%d\" established. Now logging in ...",
249 idx, My_Connections[idx].sock, My_Connections[idx].host,
250 Conf_Server[Conf_GetServer(idx)].port);
252 io_event_setcb( My_Connections[idx].sock, cb_clientserver);
253 io_event_add( My_Connections[idx].sock, IO_WANTREAD|IO_WANTWRITE);
255 /* Send PASS and SERVER command to peer */
256 Conn_WriteStr( idx, "PASS %s %s", Conf_Server[Conf_GetServer( idx )].pwd_out, NGIRCd_ProtoID );
257 Conn_WriteStr( idx, "SERVER %s :%s", Conf_ServerName, Conf_ServerInfo );
263 * IO callback for new outgoing SSL-enabled server connections.
265 * @param sock Socket descriptor.
266 * @param unused (ignored IO specification)
269 cb_connserver_login_ssl(int sock, short unused)
271 CONN_ID idx = Socket2Index(sock);
279 switch (ConnSSL_Connect( &My_Connections[idx])) {
281 case 0: LogDebug("ConnSSL_Connect: not ready");
284 Log(LOG_ERR, "SSL connection on socket %d failed!", sock);
285 Conn_Close(idx, "Can't connect!", NULL, false);
289 Log( LOG_INFO, "SSL connection %d with \"%s:%d\" established.", idx,
290 My_Connections[idx].host, Conf_Server[Conf_GetServer( idx )].port );
298 * IO callback for established non-SSL client and server connections.
300 * @param sock Socket descriptor.
301 * @param what IO specification (IO_WANTREAD/IO_WANTWRITE/...).
304 cb_clientserver(int sock, short what)
306 CONN_ID idx = Socket2Index(sock);
315 if (what & IO_WANTREAD
316 || (Conn_OPTION_ISSET(&My_Connections[idx], CONN_SSL_WANT_WRITE))) {
317 /* if TLS layer needs to write additional data, call
318 * Read_Request() instead so that SSL/TLS can continue */
322 if (what & IO_WANTREAD)
325 if (what & IO_WANTWRITE)
332 * IO callback for established SSL-enabled client and server connections.
334 * @param sock Socket descriptor.
335 * @param what IO specification (IO_WANTREAD/IO_WANTWRITE/...).
338 cb_clientserver_ssl(int sock, short what)
340 CONN_ID idx = Socket2Index(sock);
349 switch (ConnSSL_Accept(&My_Connections[idx])) {
353 return; /* EAGAIN: callback will be invoked again by IO layer */
355 Conn_Close(idx, "SSL accept error, closing socket", "SSL accept error", false);
358 if (what & IO_WANTREAD)
361 if (what & IO_WANTWRITE)
364 io_event_setcb(sock, cb_clientserver); /* SSL handshake completed */
370 * Initialite connecion module.
377 /* Speicher fuer Verbindungs-Pool anfordern */
378 Pool_Size = CONNECTION_POOL;
379 if ((Conf_MaxConnections > 0) &&
380 (Pool_Size > Conf_MaxConnections))
381 Pool_Size = Conf_MaxConnections;
383 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)Pool_Size)) {
384 Log(LOG_EMERG, "Can't allocate memory! [Conn_Init]");
388 /* FIXME: My_Connetions/Pool_Size is needed by other parts of the
389 * code; remove them! */
390 My_Connections = (CONNECTION*) array_start(&My_ConnArray);
392 LogDebug("Allocated connection pool for %d items (%ld bytes).",
393 array_length(&My_ConnArray, sizeof(CONNECTION)),
394 array_bytes(&My_ConnArray));
396 assert(array_length(&My_ConnArray, sizeof(CONNECTION)) >= (size_t)Pool_Size);
398 array_free( &My_Listeners );
400 for (i = 0; i < Pool_Size; i++)
406 * Clean up connection module.
413 Conn_ExitListeners();
415 LogDebug("Shutting down all connections ..." );
416 for( idx = 0; idx < Pool_Size; idx++ ) {
417 if( My_Connections[idx].sock > NONE ) {
418 Conn_Close( idx, NULL, NGIRCd_SignalRestart ?
419 "Server going down (restarting)":"Server going down", true );
423 array_free(&My_ConnArray);
424 My_Connections = NULL;
426 io_library_shutdown();
431 * Close all sockets (file descriptors) of open connections.
432 * This is useful in forked child processes, for example, to make sure that
433 * they don't hold connections open that the main process wants to close.
436 Conn_CloseAllSockets(void)
440 for(idx = 0; idx < Pool_Size; idx++) {
441 if(My_Connections[idx].sock > NONE)
442 close(My_Connections[idx].sock);
448 * Initialize listening ports.
450 * @param a Array containing the ports the daemon should listen on.
451 * @param listen_addr Address the socket should listen on (can be "0.0.0.0").
452 * @param func IO callback function to register.
453 * @returns Number of listening sockets created.
456 ports_initlisteners(array *a, const char *listen_addr, void (*func)(int,short))
458 unsigned int created = 0;
463 len = array_length(a, sizeof (UINT16));
464 port = array_start(a);
466 fd = NewListener(listen_addr, *port);
471 if (!io_event_create( fd, IO_WANTREAD, func )) {
472 Log( LOG_ERR, "io_event_create(): Could not add listening fd %d (port %u): %s!",
473 fd, (unsigned int) *port, strerror(errno));
486 * Initialize all listening sockets.
488 * @returns Number of created listening sockets
491 Conn_InitListeners( void )
493 /* Initialize ports on which the server should accept connections */
494 unsigned int created = 0;
495 char *copy, *listen_addr;
497 assert(Conf_ListenAddress);
499 /* can't use Conf_ListenAddress directly, see below */
500 copy = strdup(Conf_ListenAddress);
502 Log(LOG_CRIT, "Cannot copy %s: %s", Conf_ListenAddress, strerror(errno));
505 listen_addr = strtok(copy, ",");
507 while (listen_addr) {
508 ngt_TrimStr(listen_addr);
510 created += ports_initlisteners(&Conf_ListenPorts, listen_addr, cb_listen);
512 created += ports_initlisteners(&Conf_SSLOptions.ListenPorts, listen_addr, cb_listen_ssl);
516 listen_addr = strtok(NULL, ",");
519 /* Can't free() Conf_ListenAddress here: on REHASH, if the config file
520 * cannot be re-loaded, we'd end up with a NULL Conf_ListenAddress.
521 * Instead, free() takes place in conf.c, before the config file
522 * is being parsed. */
526 } /* Conn_InitListeners */
530 * Shut down all listening sockets.
533 Conn_ExitListeners( void )
535 /* Close down all listening sockets */
539 arraylen = array_length(&My_Listeners, sizeof (int));
541 "Shutting down all listening sockets (%d total) ...", arraylen);
542 fd = array_start(&My_Listeners);
547 LogDebug("Listening socket %d closed.", *fd );
550 array_free(&My_Listeners);
551 } /* Conn_ExitListeners */
555 * Bind a socket to a specific (source) address.
557 * @param addr Address structure.
558 * @param listen_addrstr Source address as string.
559 * @param Port Port number.
560 * @returns true on success, false otherwise.
563 InitSinaddrListenAddr(ng_ipaddr_t *addr, const char *listen_addrstr, UINT16 Port)
567 ret = ng_ipaddr_init(addr, listen_addrstr, Port);
569 assert(listen_addrstr);
570 Log(LOG_CRIT, "Can't bind to [%s]:%u: can't convert ip address \"%s\"",
571 listen_addrstr, Port, listen_addrstr);
578 * Set a socket to "IPv6 only". If the given socket doesn't belong to the
579 * AF_INET6 family, or the operating system doesn't support this functionality,
580 * this function retruns silently.
582 * @param af Address family of the socket.
583 * @param sock Socket handle.
586 set_v6_only(int af, int sock)
588 #if defined(IPV6_V6ONLY) && defined(WANT_IPV6)
594 if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, (socklen_t)sizeof(on)))
595 Log(LOG_ERR, "Could not set IPV6_V6ONLY: %s", strerror(errno));
604 * Initialize new listening port.
606 * @param listen_addr Local address to bind the socet to (can be 0.0.0.0).
607 * @param Port Port number on which the new socket should be listening.
608 * @returns file descriptor of the socket or -1 on failure.
611 NewListener(const char *listen_addr, UINT16 Port)
613 /* Create new listening socket on specified port */
617 if (!InitSinaddrListenAddr(&addr, listen_addr, Port))
620 af = ng_ipaddr_af(&addr);
621 sock = socket(af, SOCK_STREAM, 0);
623 Log(LOG_CRIT, "Can't create socket (af %d) : %s!", af, strerror(errno));
627 set_v6_only(af, sock);
629 if (!Init_Socket(sock))
632 if (bind(sock, (struct sockaddr *)&addr, ng_ipaddr_salen(&addr)) != 0) {
633 Log(LOG_CRIT, "Can't bind socket to address %s:%d - %s",
634 ng_ipaddr_tostr(&addr), Port, strerror(errno));
639 if( listen( sock, 10 ) != 0 ) {
640 Log( LOG_CRIT, "Can't listen on socket: %s!", strerror( errno ));
645 /* keep fd in list so we can close it when ngircd restarts/shuts down */
646 if (!array_catb( &My_Listeners,(char*) &sock, sizeof(int) )) {
647 Log( LOG_CRIT, "Can't add socket to My_Listeners array: %s!", strerror( errno ));
652 Log(LOG_INFO, "Now listening on [%s]:%d (socket %d).",
653 ng_ipaddr_tostr(&addr), Port, sock);
661 * Check if SSL library needs to read SSL-protocol related data.
663 * SSL/TLS connections require extra treatment:
664 * When either CONN_SSL_WANT_WRITE or CONN_SSL_WANT_READ is set, we
665 * need to take care of that first, before checking read/write buffers.
666 * For instance, while we might have data in our write buffer, the
667 * TLS/SSL protocol might need to read internal data first for TLS/SSL
670 * If this function returns true, such a condition is met and we have
671 * to reverse the condition (check for read even if we've data to write,
672 * do not check for read but writeability even if write-buffer is empty).
674 * @param c Connection to check.
675 * @returns true if SSL-library has to read protocol data.
678 SSL_WantRead(const CONNECTION *c)
680 if (Conn_OPTION_ISSET(c, CONN_SSL_WANT_READ)) {
681 io_event_add(c->sock, IO_WANTREAD);
688 * Check if SSL library needs to write SSL-protocol related data.
690 * Please see description of SSL_WantRead() for full description!
692 * @param c Connection to check.
693 * @returns true if SSL-library has to write protocol data.
696 SSL_WantWrite(const CONNECTION *c)
698 if (Conn_OPTION_ISSET(c, CONN_SSL_WANT_WRITE)) {
699 io_event_add(c->sock, IO_WANTWRITE);
708 SSL_WantRead(UNUSED const CONNECTION *c)
712 SSL_WantWrite(UNUSED const CONNECTION *c)
719 * "Main Loop": Loop until shutdown or restart is signalled.
721 * This function loops until a shutdown or restart of ngIRCd is signalled and
722 * calls io_dispatch() to check for readable and writable sockets every second.
723 * It checks for status changes on pending connections (e. g. when a hostname
724 * has been resolved), checks for "penalties" and timeouts, and handles the
731 unsigned int wdatalen, bytes_processed;
735 while (!NGIRCd_SignalQuit && !NGIRCd_SignalRestart) {
738 /* Check configured servers and established links */
742 /* Look for non-empty read buffers ... */
743 for (i = 0; i < Pool_Size; i++) {
744 if ((My_Connections[i].sock > NONE)
745 && (array_bytes(&My_Connections[i].rbuf) > 0)
746 && (My_Connections[i].delaytime <= t)) {
747 /* ... and try to handle the received data */
748 bytes_processed = Handle_Buffer(i);
749 /* if we processed data, and there might be
750 * more commands in the input buffer, do not
751 * try to read any more data now */
752 if (bytes_processed &&
753 array_bytes(&My_Connections[i].rbuf) > 2) {
755 ("Throttling connection %d: command limit reached!",
757 Conn_SetPenalty(i, 1);
762 /* Look for non-empty write buffers ... */
763 for (i = 0; i < Pool_Size; i++) {
764 if (My_Connections[i].sock <= NONE)
767 wdatalen = (unsigned int)array_bytes(&My_Connections[i].wbuf);
770 array_bytes(&My_Connections[i].zip.wbuf) > 0)
775 if (SSL_WantRead(&My_Connections[i]))
777 io_event_add(My_Connections[i].sock,
782 /* Check from which sockets we possibly could read ... */
783 for (i = 0; i < Pool_Size; i++) {
784 if (My_Connections[i].sock <= NONE)
787 if (SSL_WantWrite(&My_Connections[i]))
788 continue; /* TLS/SSL layer needs to write data; deal with this first */
790 if (Proc_InProgress(&My_Connections[i].proc_stat)) {
791 /* Wait for completion of forked subprocess
792 * and ignore the socket in the meantime ... */
793 io_event_del(My_Connections[i].sock,
798 if (Conn_OPTION_ISSET(&My_Connections[i], CONN_ISCONNECTING))
799 /* Wait for completion of connect() ... */
802 if (My_Connections[i].delaytime > t) {
803 /* There is a "penalty time" set: ignore socket! */
804 io_event_del(My_Connections[i].sock,
809 io_event_add(My_Connections[i].sock, IO_WANTREAD);
812 /* Set the timeout for reading from the network to 1 second,
813 * which is the granularity with witch we handle "penalty
814 * times" for example.
815 * Note: tv_sec/usec are undefined(!) after io_dispatch()
816 * returns, so we have to set it beforce each call to it! */
820 /* Wait for activity ... */
821 i = io_dispatch(&tv);
822 if (i == -1 && errno != EINTR) {
823 Log(LOG_EMERG, "Conn_Handler(): io_dispatch(): %s!",
825 Log(LOG_ALERT, "%s exiting due to fatal errors!",
831 if (NGIRCd_SignalQuit)
832 Log(LOG_NOTICE | LOG_snotice, "Server going down NOW!");
833 else if (NGIRCd_SignalRestart)
834 Log(LOG_NOTICE | LOG_snotice, "Server restarting NOW!");
839 * Write a text string into the socket of a connection.
841 * This function automatically appends CR+LF to the string and validates that
842 * the result is a valid IRC message (oversized messages are shortened, for
843 * example). Then it calls the Conn_Write() function to do the actual sending.
845 * @param Idx Index fo the connection.
846 * @param Format Format string, see printf().
847 * @returns true on success, false otherwise.
851 Conn_WriteStr(CONN_ID Idx, const char *Format, ...)
854 Conn_WriteStr(Idx, Format, va_alist)
860 char buffer[COMMAND_LEN];
865 assert( Idx > NONE );
866 assert( Format != NULL );
869 va_start( ap, Format );
873 if (vsnprintf( buffer, COMMAND_LEN - 2, Format, ap ) >= COMMAND_LEN - 2 ) {
875 * The string that should be written to the socket is longer
876 * than the allowed size of COMMAND_LEN bytes (including both
877 * the CR and LF characters). This can be caused by the
878 * IRC_WriteXXX() functions when the prefix of this server had
879 * to be added to an already "quite long" command line which
880 * has been received from a regular IRC client, for example.
882 * We are not allowed to send such "oversized" messages to
883 * other servers and clients, see RFC 2812 2.3 and 2813 3.3
884 * ("these messages SHALL NOT exceed 512 characters in length,
885 * counting all characters including the trailing CR-LF").
887 * So we have a big problem here: we should send more bytes
888 * to the network than we are allowed to and we don't know
889 * the originator (any more). The "old" behaviour of blaming
890 * the receiver ("next hop") is a bad idea (it could be just
891 * an other server only routing the message!), so the only
892 * option left is to shorten the string and to hope that the
893 * result is still somewhat useful ...
897 strcpy (buffer + sizeof(buffer) - strlen(CUT_TXTSUFFIX) - 2 - 1,
903 Log(LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer);
906 len = strlcat( buffer, "\r\n", sizeof( buffer ));
907 ok = Conn_Write(Idx, buffer, len);
908 My_Connections[Idx].msg_out++;
912 } /* Conn_WriteStr */
916 * Append Data to the outbound write buffer of a connection.
918 * @param Idx Index of the connection.
919 * @param Data pointer to the data.
920 * @param Len length of Data.
921 * @returns true on success, false otherwise.
924 Conn_Write( CONN_ID Idx, char *Data, size_t Len )
927 size_t writebuf_limit = WRITEBUFFER_MAX_LEN;
928 assert( Idx > NONE );
929 assert( Data != NULL );
932 c = Conn_GetClient(Idx);
935 /* Servers do get special write buffer limits, so they can generate
936 * all the messages that are required while peering. */
937 if (Client_Type(c) == CLIENT_SERVER)
938 writebuf_limit = WRITEBUFFER_SLINK_LEN;
940 /* Is the socket still open? A previous call to Conn_Write()
941 * may have closed the connection due to a fatal error.
942 * In this case it is sufficient to return an error, as well. */
943 if( My_Connections[Idx].sock <= NONE ) {
944 LogDebug("Skipped write on closed socket (connection %d).", Idx);
949 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
951 * Zip_Buffer() does all the dirty work for us: it flushes
952 * the (pre-)compression buffers if required and handles
953 * all error conditions. */
954 if (!Zip_Buffer(Idx, Data, Len))
960 /* Uncompressed link:
961 * Check if outbound buffer has enough space for the data. */
962 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
963 WRITEBUFFER_FLUSH_LEN) {
964 /* Buffer is full, flush it. Handle_Write deals with
965 * low-level errors, if any. */
966 if (!Handle_Write(Idx))
970 /* When the write buffer is still too big after flushing it,
971 * the connection will be killed. */
972 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
975 "Write buffer overflow (connection %d, limit is %lu bytes, %lu bytes new, %lu bytes pending)!",
976 Idx, writebuf_limit, Len,
977 (unsigned long)array_bytes(&My_Connections[Idx].wbuf));
978 Conn_Close(Idx, "Write buffer overflow!", NULL, false);
982 /* Copy data to write buffer */
983 if (!array_catb(&My_Connections[Idx].wbuf, Data, Len))
986 My_Connections[Idx].bytes_out += Len;
989 /* Adjust global write counter */
997 * Shut down a connection.
999 * @param Idx Connection index.
1000 * @param LogMsg Message to write to the log or NULL. If no LogMsg
1001 * is given, the FwdMsg is logged.
1002 * @param FwdMsg Message to forward to remote servers.
1003 * @param InformClient If true, inform the client on the connection which is
1004 * to be shut down of the reason (FwdMsg) and send
1005 * connection statistics before disconnecting it.
1008 Conn_Close( CONN_ID Idx, const char *LogMsg, const char *FwdMsg, bool InformClient )
1010 /* Close connection. Open pipes of asyncronous resolver
1011 * sub-processes are closed down. */
1017 double in_z_k, out_z_k;
1021 assert( Idx > NONE );
1023 /* Is this link already shutting down? */
1024 if( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ISCLOSING )) {
1025 /* Conn_Close() has been called recursively for this link;
1026 * probabe reason: Handle_Write() failed -- see below. */
1027 LogDebug("Recursive request to close connection: %d", Idx );
1031 assert( My_Connections[Idx].sock > NONE );
1033 /* Mark link as "closing" */
1034 Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCLOSING );
1036 port = ng_ipaddr_getport(&My_Connections[Idx].addr);
1037 Log(LOG_INFO, "Shutting down connection %d (%s) with %s:%d ...", Idx,
1038 LogMsg ? LogMsg : FwdMsg, My_Connections[Idx].host, port);
1040 /* Search client, if any */
1041 c = Conn_GetClient( Idx );
1043 /* Should the client be informed? */
1046 /* Send statistics to client if registered as user: */
1047 if ((c != NULL) && (Client_Type(c) == CLIENT_USER)) {
1049 ":%s NOTICE %s :%sConnection statistics: client %.1f kb, server %.1f kb.",
1050 Client_ID(Client_ThisServer()), Client_ID(c),
1052 (double)My_Connections[Idx].bytes_in / 1024,
1053 (double)My_Connections[Idx].bytes_out / 1024);
1056 /* Send ERROR to client (see RFC 2812, section 3.1.7) */
1058 Conn_WriteStr(Idx, "ERROR :%s", FwdMsg);
1060 Conn_WriteStr(Idx, "ERROR :Closing connection");
1063 /* Try to write out the write buffer. Note: Handle_Write() eventually
1064 * removes the CLIENT structure associated with this connection if an
1065 * error occurs! So we have to re-check if there is still an valid
1066 * CLIENT structure after calling Handle_Write() ...*/
1067 (void)Handle_Write( Idx );
1069 /* Search client, if any (re-check!) */
1070 c = Conn_GetClient( Idx );
1072 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_SSL )) {
1073 Log(LOG_INFO, "SSL connection %d shutting down ...", Idx);
1074 ConnSSL_Free(&My_Connections[Idx]);
1077 /* Shut down socket */
1078 if (! io_close(My_Connections[Idx].sock)) {
1079 /* Oops, we can't close the socket!? This is ... ugly! */
1081 "Error closing connection %d (socket %d) with %s:%d - %s! (ignored)",
1082 Idx, My_Connections[Idx].sock, My_Connections[Idx].host,
1083 port, strerror(errno));
1086 /* Mark socket as invalid: */
1087 My_Connections[Idx].sock = NONE;
1089 /* If there is still a client, unregister it now */
1091 Client_Destroy(c, LogMsg, FwdMsg, true);
1093 /* Calculate statistics and log information */
1094 in_k = (double)My_Connections[Idx].bytes_in / 1024;
1095 out_k = (double)My_Connections[Idx].bytes_out / 1024;
1097 if (Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP)) {
1098 in_z_k = (double)My_Connections[Idx].zip.bytes_in / 1024;
1099 out_z_k = (double)My_Connections[Idx].zip.bytes_out / 1024;
1100 /* Make sure that no division by zero can occur during
1101 * the calculation of in_p and out_p: in_z_k and out_z_k
1102 * are non-zero, that's guaranteed by the protocol until
1103 * compression can be enabled. */
1108 in_p = (int)(( in_k * 100 ) / in_z_k );
1109 out_p = (int)(( out_k * 100 ) / out_z_k );
1111 "Connection %d with %s:%d closed (in: %.1fk/%.1fk/%d%%, out: %.1fk/%.1fk/%d%%).",
1112 Idx, My_Connections[Idx].host, port,
1113 in_k, in_z_k, in_p, out_k, out_z_k, out_p);
1119 "Connection %d with %s:%d closed (in: %.1fk, out: %.1fk).",
1120 Idx, My_Connections[Idx].host, port,
1124 /* Servers: Modify time of next connect attempt? */
1125 Conf_UnsetServer( Idx );
1128 /* Clean up zlib, if link was compressed */
1129 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
1130 inflateEnd( &My_Connections[Idx].zip.in );
1131 deflateEnd( &My_Connections[Idx].zip.out );
1132 array_free(&My_Connections[Idx].zip.rbuf);
1133 array_free(&My_Connections[Idx].zip.wbuf);
1137 array_free(&My_Connections[Idx].rbuf);
1138 array_free(&My_Connections[Idx].wbuf);
1140 /* Clean up connection structure (=free it) */
1141 Init_Conn_Struct( Idx );
1143 assert(NumConnections > 0);
1146 LogDebug("Shutdown of connection %d completed, %ld connection%s left.",
1147 Idx, NumConnections, NumConnections != 1 ? "s" : "");
1152 * Get current number of connections.
1154 * @returns Number of current connections.
1159 return NumConnections;
1164 * Get number of maximum simultaneous connections.
1166 * @returns Number of maximum simultaneous connections.
1171 return NumConnectionsMax;
1172 } /* Conn_CountMax */
1176 * Get number of connections accepted since the daemon startet.
1178 * @returns Number of connections accepted.
1181 Conn_CountAccepted(void)
1183 return NumConnectionsAccepted;
1184 } /* Conn_CountAccepted */
1188 * Synchronize established connections and configured server structures
1189 * after a configuration update and store the correct connection IDs, if any.
1192 Conn_SyncServerStruct(void)
1198 for (i = 0; i < Pool_Size; i++) {
1199 if (My_Connections[i].sock == NONE)
1203 client = Conn_GetClient(i);
1204 if (!client || Client_Type(client) != CLIENT_SERVER)
1207 for (c = 0; c < MAX_SERVERS; c++) {
1208 /* Configured server? */
1209 if (!Conf_Server[c].host[0])
1212 if (strcasecmp(Conf_Server[c].name, Client_ID(client)) == 0)
1213 Conf_Server[c].conn_id = i;
1216 } /* SyncServerStruct */
1220 * Send out data of write buffer; connect new sockets.
1222 * @param Idx Connection index.
1223 * @returns true on success, false otherwise.
1226 Handle_Write( CONN_ID Idx )
1231 assert( Idx > NONE );
1232 if ( My_Connections[Idx].sock < 0 ) {
1233 LogDebug("Handle_Write() on closed socket, connection %d", Idx);
1236 assert( My_Connections[Idx].sock > NONE );
1238 wdatalen = array_bytes(&My_Connections[Idx].wbuf );
1241 if (wdatalen == 0) {
1242 /* Write buffer is empty, so we try to flush the compression
1243 * buffer and get some data to work with from there :-) */
1244 if (!Zip_Flush(Idx))
1247 /* Now the write buffer most probably has changed: */
1248 wdatalen = array_bytes(&My_Connections[Idx].wbuf);
1252 if (wdatalen == 0) {
1253 /* Still no data, fine. */
1254 io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
1259 ("Handle_Write() called for connection %d, %ld bytes pending ...",
1263 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_SSL )) {
1264 len = ConnSSL_Write(&My_Connections[Idx], array_start(&My_Connections[Idx].wbuf), wdatalen);
1268 len = write(My_Connections[Idx].sock,
1269 array_start(&My_Connections[Idx].wbuf), wdatalen );
1272 if (errno == EAGAIN || errno == EINTR)
1275 Log(LOG_ERR, "Write error on connection %d (socket %d): %s!",
1276 Idx, My_Connections[Idx].sock, strerror(errno));
1277 Conn_Close(Idx, "Write error!", NULL, false);
1281 /* move any data not yet written to beginning */
1282 array_moveleft(&My_Connections[Idx].wbuf, 1, (size_t)len);
1285 } /* Handle_Write */
1289 * Count established connections to a specific IP address.
1291 * @returns Number of established connections.
1294 Count_Connections(ng_ipaddr_t *a)
1299 for (i = 0; i < Pool_Size; i++) {
1300 if (My_Connections[i].sock <= NONE)
1302 if (ng_ipaddr_ipequal(&My_Connections[i].addr, a))
1306 } /* Count_Connections */
1310 * Initialize new client connection on a listening socket.
1312 * @param Sock Listening socket descriptor.
1313 * @returns Accepted socket descriptor or -1 on error.
1316 New_Connection(int Sock)
1319 struct request_info req;
1321 ng_ipaddr_t new_addr;
1322 char ip_str[NG_INET_ADDRSTRLEN];
1323 int new_sock, new_sock_len, identsock;
1327 assert(Sock > NONE);
1329 new_sock_len = (int)sizeof(new_addr);
1330 new_sock = accept(Sock, (struct sockaddr *)&new_addr,
1331 (socklen_t *)&new_sock_len);
1333 Log(LOG_CRIT, "Can't accept connection: %s!", strerror(errno));
1336 NumConnectionsAccepted++;
1338 if (!ng_ipaddr_tostr_r(&new_addr, ip_str)) {
1339 Log(LOG_CRIT, "fd %d: Can't convert IP address!", new_sock);
1340 Simple_Message(new_sock, "ERROR :Internal Server Error");
1346 /* Validate socket using TCP Wrappers */
1347 request_init(&req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock,
1348 RQ_CLIENT_SIN, &new_addr, NULL);
1350 if (!hosts_access(&req)) {
1352 "Refused connection from %s (by TCP Wrappers)!", ip_str);
1353 Simple_Message(new_sock, "ERROR :Connection refused");
1359 if (!Init_Socket(new_sock))
1362 /* Check global connection limit */
1363 if ((Conf_MaxConnections > 0) &&
1364 (NumConnections >= (size_t) Conf_MaxConnections)) {
1365 Log(LOG_ALERT, "Can't accept connection: limit (%d) reached!",
1366 Conf_MaxConnections);
1367 Simple_Message(new_sock, "ERROR :Connection limit reached");
1372 /* Check IP-based connection limit */
1373 cnt = Count_Connections(&new_addr);
1374 if ((Conf_MaxConnectionsIP > 0) && (cnt >= Conf_MaxConnectionsIP)) {
1375 /* Access denied, too many connections from this IP address! */
1377 "Refused connection from %s: too may connections (%ld) from this IP address!",
1379 Simple_Message(new_sock,
1380 "ERROR :Connection refused, too many connections from your IP address");
1385 if (new_sock >= Pool_Size) {
1386 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION),
1387 (size_t) new_sock)) {
1389 "Can't allocate memory! [New_Connection]");
1390 Simple_Message(new_sock, "ERROR: Internal error");
1394 LogDebug("Bumped connection pool to %ld items (internal: %ld items, %ld bytes)",
1395 new_sock, array_length(&My_ConnArray,
1396 sizeof(CONNECTION)), array_bytes(&My_ConnArray));
1398 /* Adjust pointer to new block */
1399 My_Connections = array_start(&My_ConnArray);
1400 while (Pool_Size <= new_sock)
1401 Init_Conn_Struct(Pool_Size++);
1404 /* register callback */
1405 if (!io_event_create(new_sock, IO_WANTREAD, cb_clientserver)) {
1407 "Can't accept connection: io_event_create failed!");
1408 Simple_Message(new_sock, "ERROR :Internal error");
1413 c = Client_NewLocal(new_sock, ip_str, CLIENT_UNKNOWN, false);
1416 "Can't accept connection: can't create client structure!");
1417 Simple_Message(new_sock, "ERROR :Internal error");
1422 Init_Conn_Struct(new_sock);
1423 My_Connections[new_sock].sock = new_sock;
1424 My_Connections[new_sock].addr = new_addr;
1425 My_Connections[new_sock].client = c;
1427 /* Set initial hostname to IP address. This becomes overwritten when
1428 * the DNS lookup is enabled and succeeds, but is used otherwise. */
1429 if (ng_ipaddr_af(&new_addr) != AF_INET)
1430 snprintf(My_Connections[new_sock].host,
1431 sizeof(My_Connections[new_sock].host), "[%s]", ip_str);
1433 strlcpy(My_Connections[new_sock].host, ip_str,
1434 sizeof(My_Connections[new_sock].host));
1436 Client_SetHostname(c, My_Connections[new_sock].host);
1438 Log(LOG_INFO, "Accepted connection %d from %s:%d on socket %d.",
1439 new_sock, My_Connections[new_sock].host,
1440 ng_ipaddr_getport(&new_addr), Sock);
1442 identsock = new_sock;
1448 Resolve_Addr(&My_Connections[new_sock].proc_stat, &new_addr,
1449 identsock, cb_Read_Resolver_Result);
1451 Account_Connection();
1453 } /* New_Connection */
1457 * Update global connection counters.
1460 Account_Connection(void)
1463 if (NumConnections > NumConnectionsMax)
1464 NumConnectionsMax = NumConnections;
1465 LogDebug("Total number of connections now %lu (max %lu).",
1466 NumConnections, NumConnectionsMax);
1467 } /* Account_Connection */
1471 * Translate socket handle into connection index.
1473 * @param Sock Socket handle.
1474 * @returns Connecion index or NONE, if no connection could be found.
1477 Socket2Index( int Sock )
1479 assert( Sock >= 0 );
1481 if( Sock >= Pool_Size || My_Connections[Sock].sock != Sock ) {
1482 /* the Connection was already closed again, likely due to
1484 LogDebug("Socket2Index: can't get connection for socket %d!", Sock);
1488 } /* Socket2Index */
1492 * Read data from the network to the read buffer. If an error occures,
1493 * the socket of this connection will be shut down.
1495 * @param Idx Connection index.
1498 Read_Request( CONN_ID Idx )
1501 static const unsigned int maxbps = COMMAND_LEN / 2;
1502 char readbuf[READBUFFER_LEN];
1505 assert( Idx > NONE );
1506 assert( My_Connections[Idx].sock > NONE );
1509 if ((array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN) ||
1510 (array_bytes(&My_Connections[Idx].zip.rbuf) >= READBUFFER_LEN))
1512 if (array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN)
1515 /* Read buffer is full */
1517 "Receive buffer overflow (connection %d): %d bytes!",
1518 Idx, array_bytes(&My_Connections[Idx].rbuf));
1519 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1524 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_SSL))
1525 len = ConnSSL_Read( &My_Connections[Idx], readbuf, sizeof(readbuf));
1528 len = read(My_Connections[Idx].sock, readbuf, sizeof(readbuf));
1530 Log(LOG_INFO, "%s:%u (%s) is closing the connection ...",
1531 My_Connections[Idx].host,
1532 (unsigned int) ng_ipaddr_getport(&My_Connections[Idx].addr),
1533 ng_ipaddr_tostr(&My_Connections[Idx].addr));
1535 "Socket closed!", "Client closed connection",
1541 if( errno == EAGAIN ) return;
1542 Log(LOG_ERR, "Read error on connection %d (socket %d): %s!",
1543 Idx, My_Connections[Idx].sock, strerror(errno));
1544 Conn_Close(Idx, "Read error!", "Client closed connection",
1549 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1550 if (!array_catb(&My_Connections[Idx].zip.rbuf, readbuf,
1553 "Could not append recieved data to zip input buffer (connn %d): %d bytes!",
1555 Conn_Close(Idx, "Receive buffer overflow!", NULL,
1562 if (!array_catb( &My_Connections[Idx].rbuf, readbuf, len)) {
1563 Log( LOG_ERR, "Could not append recieved data to input buffer (connn %d): %d bytes!", Idx, len );
1564 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1568 /* Update connection statistics */
1569 My_Connections[Idx].bytes_in += len;
1570 My_Connections[Idx].bps += Handle_Buffer(Idx);
1572 /* Make sure that there is still a valid client registered */
1573 c = Conn_GetClient(Idx);
1577 /* Update timestamp of last data received if this connection is
1578 * registered as a user, server or service connection. Don't update
1579 * otherwise, so users have at least Conf_PongTimeout seconds time to
1580 * register with the IRC server -- see Check_Connections().
1581 * Update "lastping", too, if time shifted backwards ... */
1582 if (Client_Type(c) == CLIENT_USER
1583 || Client_Type(c) == CLIENT_SERVER
1584 || Client_Type(c) == CLIENT_SERVICE) {
1586 if (My_Connections[Idx].lastdata != t)
1587 My_Connections[Idx].bps = 0;
1589 My_Connections[Idx].lastdata = t;
1590 if (My_Connections[Idx].lastping > t)
1591 My_Connections[Idx].lastping = t;
1594 /* Look at the data in the (read-) buffer of this connection */
1595 if (Client_Type(c) != CLIENT_SERVER
1596 && Client_Type(c) != CLIENT_UNKNOWNSERVER
1597 && Client_Type(c) != CLIENT_SERVICE
1598 && My_Connections[Idx].bps >= maxbps) {
1599 LogDebug("Throttling connection %d: BPS exceeded! (%u >= %u)",
1600 Idx, My_Connections[Idx].bps, maxbps);
1601 Conn_SetPenalty(Idx, 1);
1603 } /* Read_Request */
1607 * Handle all data in the connection read-buffer.
1609 * Data is processed until no complete command is left in the read buffer,
1610 * or MAX_COMMANDS[_SERVER|_SERVICE] commands were processed.
1611 * When a fatal error occurs, the connection is shut down.
1613 * @param Idx Index of the connection.
1614 * @returns Number of bytes processed.
1617 Handle_Buffer(CONN_ID Idx)
1620 char *ptr1, *ptr2, *first_eol;
1628 unsigned int i, maxcmd = MAX_COMMANDS, len_processed = 0;
1631 c = Conn_GetClient(Idx);
1632 starttime = time(NULL);
1636 /* Servers do get special command limits, so they can process
1637 * all the messages that are required while peering. */
1638 switch (Client_Type(c)) {
1640 /* Allow servers to send more commands in the first 10 secods
1641 * to speed up server login and network synchronisation. */
1642 if (starttime - Client_StartTime(c) < 10)
1643 maxcmd = MAX_COMMANDS_SERVER * 5;
1645 maxcmd = MAX_COMMANDS_SERVER;
1647 case CLIENT_SERVICE:
1648 maxcmd = MAX_COMMANDS_SERVICE; break;
1651 for (i=0; i < maxcmd; i++) {
1653 if (My_Connections[Idx].delaytime > starttime)
1656 /* Unpack compressed data, if compression is in use */
1657 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1658 /* When unzipping fails, Unzip_Buffer() shuts
1659 * down the connection itself */
1660 if (!Unzip_Buffer(Idx))
1665 if (0 == array_bytes(&My_Connections[Idx].rbuf))
1668 /* Make sure that the buffer is NULL terminated */
1669 if (!array_cat0_temporary(&My_Connections[Idx].rbuf)) {
1670 Conn_Close(Idx, NULL,
1671 "Can't allocate memory [Handle_Buffer]",
1676 /* RFC 2812, section "2.3 Messages", 5th paragraph:
1677 * "IRC messages are always lines of characters terminated
1678 * with a CR-LF (Carriage Return - Line Feed) pair [...]". */
1680 ptr = strstr(array_start(&My_Connections[Idx].rbuf), "\r\n");
1683 /* Check for non-RFC-compliant request (only CR or LF)?
1684 * Unfortunately, there are quite a few clients out there
1685 * that do this -- e. g. mIRC, BitchX, and Trillian :-( */
1686 ptr1 = strchr(array_start(&My_Connections[Idx].rbuf), '\r');
1687 ptr2 = strchr(array_start(&My_Connections[Idx].rbuf), '\n');
1689 /* Check if there is a single CR or LF _before_ the
1690 * corerct CR+LF line terminator: */
1691 first_eol = ptr1 < ptr2 ? ptr1 : ptr2;
1692 if (first_eol < ptr) {
1693 /* Single CR or LF before CR+LF found */
1697 } else if (ptr1 || ptr2) {
1698 /* No CR+LF terminated command found, but single
1699 * CR or LF found ... */
1701 ptr = ptr1 < ptr2 ? ptr1 : ptr2;
1703 ptr = ptr1 ? ptr1 : ptr2;
1711 /* Complete (=line terminated) request found, handle it! */
1714 len = ptr - (char *)array_start(&My_Connections[Idx].rbuf) + delta;
1716 if (len > (COMMAND_LEN - 1)) {
1717 /* Request must not exceed 512 chars (incl. CR+LF!),
1718 * see RFC 2812. Disconnect Client if this happens. */
1720 "Request too long (connection %d): %d bytes (max. %d expected)!",
1721 Idx, array_bytes(&My_Connections[Idx].rbuf),
1723 Conn_Close(Idx, NULL, "Request too long", true);
1727 len_processed += (unsigned int)len;
1729 /* Request is empty (only '\r\n', '\r' or '\n');
1730 * delta is 2 ('\r\n') or 1 ('\r' or '\n'), see above */
1731 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1735 /* remember if stream is already compressed */
1736 old_z = My_Connections[Idx].options & CONN_ZIP;
1739 My_Connections[Idx].msg_in++;
1741 (Idx, (char *)array_start(&My_Connections[Idx].rbuf)))
1742 return 0; /* error -> connection has been closed */
1744 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1745 LogDebug("Connection %d: %d bytes left in read buffer.",
1746 Idx, array_bytes(&My_Connections[Idx].rbuf));
1748 if ((!old_z) && (My_Connections[Idx].options & CONN_ZIP) &&
1749 (array_bytes(&My_Connections[Idx].rbuf) > 0)) {
1750 /* The last command activated socket compression.
1751 * Data that was read after that needs to be copied
1752 * to the unzip buffer for decompression: */
1754 (&My_Connections[Idx].zip.rbuf,
1755 &My_Connections[Idx].rbuf)) {
1756 Conn_Close(Idx, NULL,
1757 "Can't allocate memory [Handle_Buffer]",
1762 array_trunc(&My_Connections[Idx].rbuf);
1764 ("Moved already received data (%u bytes) to uncompression buffer.",
1765 array_bytes(&My_Connections[Idx].zip.rbuf));
1769 return len_processed;
1770 } /* Handle_Buffer */
1774 * Check whether established connections are still alive or not.
1775 * If not, play PING-PONG first; and if that doesn't help either,
1776 * disconnect the respective peer.
1779 Check_Connections(void)
1785 for (i = 0; i < Pool_Size; i++) {
1786 if (My_Connections[i].sock < 0)
1789 c = Conn_GetClient(i);
1790 if (c && ((Client_Type(c) == CLIENT_USER)
1791 || (Client_Type(c) == CLIENT_SERVER)
1792 || (Client_Type(c) == CLIENT_SERVICE))) {
1793 /* connected User, Server or Service */
1794 if (My_Connections[i].lastping >
1795 My_Connections[i].lastdata) {
1796 /* We already sent a ping */
1797 if (My_Connections[i].lastping <
1798 time(NULL) - Conf_PongTimeout) {
1801 ("Connection %d: Ping timeout: %d seconds.",
1802 i, Conf_PongTimeout);
1803 snprintf(msg, sizeof(msg), "Ping timeout: %d seconds", Conf_PongTimeout);
1804 Conn_Close(i, NULL, msg, true);
1806 } else if (My_Connections[i].lastdata <
1807 time(NULL) - Conf_PingTimeout) {
1808 /* We need to send a PING ... */
1809 LogDebug("Connection %d: sending PING ...", i);
1810 My_Connections[i].lastping = time(NULL);
1811 Conn_WriteStr(i, "PING :%s",
1812 Client_ID(Client_ThisServer()));
1815 /* The connection is not fully established yet, so
1816 * we don't do the PING-PONG game here but instead
1817 * disconnect the client after "a short time" if it's
1818 * still not registered. */
1820 if (My_Connections[i].lastdata <
1821 time(NULL) - Conf_PongTimeout) {
1823 ("Unregistered connection %d timed out ...",
1825 Conn_Close(i, NULL, "Timeout", false);
1829 } /* Check_Connections */
1833 * Check if further server links should be established.
1841 time_now = time(NULL);
1843 /* Check all configured servers */
1844 for (i = 0; i < MAX_SERVERS; i++) {
1845 if (Conf_Server[i].conn_id != NONE)
1846 continue; /* Already establishing or connected */
1847 if (!Conf_Server[i].host[0] || !Conf_Server[i].port > 0)
1848 continue; /* No host and/or port configured */
1849 if (Conf_Server[i].flags & CONF_SFLAG_DISABLED)
1850 continue; /* Disabled configuration entry */
1851 if (Conf_Server[i].lasttry > (time_now - Conf_ConnectRetry))
1852 continue; /* We have to wait a little bit ... */
1854 /* Is there already a connection in this group? */
1855 if (Conf_Server[i].group > NONE) {
1856 for (n = 0; n < MAX_SERVERS; n++) {
1859 if ((Conf_Server[n].conn_id != NONE) &&
1860 (Conf_Server[n].group == Conf_Server[i].group))
1863 if (n < MAX_SERVERS)
1867 /* Okay, try to connect now */
1869 "Preparing to establish a new server link for \"%s\" ...",
1870 Conf_Server[i].name);
1871 Conf_Server[i].lasttry = time_now;
1872 Conf_Server[i].conn_id = SERVER_WAIT;
1873 assert(Proc_GetPipeFd(&Conf_Server[i].res_stat) < 0);
1874 Resolve_Name(&Conf_Server[i].res_stat, Conf_Server[i].host,
1875 cb_Connect_to_Server);
1877 } /* Check_Servers */
1881 * Establish a new outgoing server connection.
1883 * @param Server Configuration index of the server.
1884 * @param dest Destination IP address to connect to.
1887 New_Server( int Server , ng_ipaddr_t *dest)
1889 /* Establish new server link */
1890 char ip_str[NG_INET_ADDRSTRLEN];
1891 int af_dest, res, new_sock;
1894 assert( Server > NONE );
1896 if (!ng_ipaddr_tostr_r(dest, ip_str)) {
1897 Log(LOG_WARNING, "New_Server: Could not convert IP to string");
1901 af_dest = ng_ipaddr_af(dest);
1902 new_sock = socket(af_dest, SOCK_STREAM, 0);
1905 "Establishing connection for \"%s\" to \"%s:%d\" (%s), socket %d ...",
1906 Conf_Server[Server].name, Conf_Server[Server].host,
1907 Conf_Server[Server].port, ip_str, new_sock);
1910 Log(LOG_CRIT, "Can't create socket (af %d): %s!",
1911 af_dest, strerror(errno));
1915 if (!Init_Socket(new_sock))
1918 /* is a bind address configured? */
1919 res = ng_ipaddr_af(&Conf_Server[Server].bind_addr);
1920 /* if yes, bind now. If it fails, warn and let connect() pick a source address */
1921 if (res && bind(new_sock, (struct sockaddr *) &Conf_Server[Server].bind_addr,
1922 ng_ipaddr_salen(&Conf_Server[Server].bind_addr)))
1924 ng_ipaddr_tostr_r(&Conf_Server[Server].bind_addr, ip_str);
1925 Log(LOG_WARNING, "Can't bind socket to %s: %s!", ip_str, strerror(errno));
1927 ng_ipaddr_setport(dest, Conf_Server[Server].port);
1928 res = connect(new_sock, (struct sockaddr *) dest, ng_ipaddr_salen(dest));
1929 if(( res != 0 ) && ( errno != EINPROGRESS )) {
1930 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1935 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)new_sock)) {
1937 "Cannot allocate memory for server connection (socket %d)",
1943 My_Connections = array_start(&My_ConnArray);
1945 assert(My_Connections[new_sock].sock <= 0);
1947 Init_Conn_Struct(new_sock);
1949 ng_ipaddr_tostr_r(dest, ip_str);
1950 c = Client_NewLocal(new_sock, ip_str, CLIENT_UNKNOWNSERVER, false);
1952 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1957 /* Conn_Close() decrements this counter again */
1958 Account_Connection();
1959 Client_SetIntroducer( c, c );
1960 Client_SetToken( c, TOKEN_OUTBOUND );
1962 /* Register connection */
1963 Conf_Server[Server].conn_id = new_sock;
1964 My_Connections[new_sock].sock = new_sock;
1965 My_Connections[new_sock].addr = *dest;
1966 My_Connections[new_sock].client = c;
1967 strlcpy( My_Connections[new_sock].host, Conf_Server[Server].host,
1968 sizeof(My_Connections[new_sock].host ));
1970 /* Register new socket */
1971 if (!io_event_create( new_sock, IO_WANTWRITE, cb_connserver)) {
1972 Log( LOG_ALERT, "io_event_create(): could not add fd %d", strerror(errno));
1973 Conn_Close( new_sock, "io_event_create() failed", NULL, false );
1974 Init_Conn_Struct( new_sock );
1975 Conf_Server[Server].conn_id = NONE;
1978 if (Conf_Server[Server].SSLConnect && !ConnSSL_PrepareConnect( &My_Connections[new_sock],
1979 &Conf_Server[Server] ))
1981 Log(LOG_ALERT, "Could not initialize SSL for outgoing connection");
1982 Conn_Close( new_sock, "Could not initialize SSL for outgoing connection", NULL, false );
1983 Init_Conn_Struct( new_sock );
1984 Conf_Server[Server].conn_id = NONE;
1988 LogDebug("Registered new connection %d on socket %d (%ld in total).",
1989 new_sock, My_Connections[new_sock].sock, NumConnections);
1990 Conn_OPTION_ADD( &My_Connections[new_sock], CONN_ISCONNECTING );
1995 * Initialize connection structure.
1997 * @param Idx Connection index.
2000 Init_Conn_Struct(CONN_ID Idx)
2002 time_t now = time(NULL);
2004 memset(&My_Connections[Idx], 0, sizeof(CONNECTION));
2005 My_Connections[Idx].sock = -1;
2006 My_Connections[Idx].signon = now;
2007 My_Connections[Idx].lastdata = now;
2008 My_Connections[Idx].lastprivmsg = now;
2009 Proc_InitStruct(&My_Connections[Idx].proc_stat);
2010 } /* Init_Conn_Struct */
2014 * Initialize options of a new socket.
2016 * For example, we try to set socket options SO_REUSEADDR and IPTOS_LOWDELAY.
2017 * Errors shouldn't be fatal and therefore are ignored.
2019 * @param Sock Socket handle.
2022 Init_Socket( int Sock )
2026 if (!io_setnonblock(Sock)) {
2027 Log( LOG_CRIT, "Can't enable non-blocking mode for socket: %s!", strerror( errno ));
2032 /* Don't block this port after socket shutdown */
2034 if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &value, (socklen_t)sizeof( value )) != 0 )
2036 Log( LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!", strerror( errno ));
2037 /* ignore this error */
2040 /* Set type of service (TOS) */
2041 #if defined(IPPROTO_IP) && defined(IPTOS_LOWDELAY)
2042 value = IPTOS_LOWDELAY;
2043 LogDebug("Setting IP_TOS on socket %d to IPTOS_LOWDELAY.", Sock);
2044 if (setsockopt(Sock, IPPROTO_IP, IP_TOS, &value,
2045 (socklen_t) sizeof(value))) {
2046 LogDebug("Can't set socket option IP_TOS: %s!",
2048 /* ignore this error */
2057 * Read results of a resolver sub-process and try to initiate a new server
2060 * @param fd File descriptor of the pipe to the sub-process.
2061 * @param events (ignored IO specification)
2064 cb_Connect_to_Server(int fd, UNUSED short events)
2066 /* Read result of resolver sub-process from pipe and start connection */
2069 ng_ipaddr_t dest_addrs[4]; /* we can handle at most 3; but we read up to
2070 four so we can log the 'more than we can handle'
2071 condition. First result is tried immediately, rest
2072 is saved for later if needed. */
2074 LogDebug("Resolver: Got forward lookup callback on fd %d, events %d", fd, events);
2076 for (i=0; i < MAX_SERVERS; i++) {
2077 if (Proc_GetPipeFd(&Conf_Server[i].res_stat) == fd )
2081 if( i >= MAX_SERVERS) {
2082 /* Ops, no matching server found?! */
2084 LogDebug("Resolver: Got Forward Lookup callback for unknown server!?");
2088 /* Read result from pipe */
2089 len = Proc_Read(&Conf_Server[i].res_stat, dest_addrs, sizeof(dest_addrs));
2091 /* Error resolving hostname: reset server structure */
2092 Conf_Server[i].conn_id = NONE;
2096 assert((len % sizeof(ng_ipaddr_t)) == 0);
2098 LogDebug("Got result from resolver: %u structs (%u bytes).", len/sizeof(ng_ipaddr_t), len);
2100 memset(&Conf_Server[i].dst_addr, 0, sizeof(Conf_Server[i].dst_addr));
2101 if (len > sizeof(ng_ipaddr_t)) {
2102 /* more than one address for this hostname, remember them
2103 * in case first address is unreachable/not available */
2104 len -= sizeof(ng_ipaddr_t);
2105 if (len > sizeof(Conf_Server[i].dst_addr)) {
2106 len = sizeof(Conf_Server[i].dst_addr);
2108 "Notice: Resolver returned more IP Addresses for host than we can handle, additional addresses dropped.");
2110 memcpy(&Conf_Server[i].dst_addr, &dest_addrs[1], len);
2113 New_Server(i, dest_addrs);
2114 } /* cb_Read_Forward_Lookup */
2118 * Read results of a resolver sub-process from the pipe and update the
2119 * apropriate connection/client structure(s): hostname and/or IDENT user name.
2121 * @param r_fd File descriptor of the pipe to the sub-process.
2122 * @param events (ignored IO specification)
2125 cb_Read_Resolver_Result( int r_fd, UNUSED short events )
2132 char readbuf[HOST_LEN + 2 + CLIENT_USER_LEN];
2134 char readbuf[HOST_LEN + 1];
2137 LogDebug("Resolver: Got callback on fd %d, events %d", r_fd, events );
2138 i = Conn_GetFromProc(r_fd);
2140 /* Ops, none found? Probably the connection has already
2141 * been closed!? We'll ignore that ... */
2143 LogDebug("Resolver: Got callback for unknown connection!?");
2147 /* Read result from pipe */
2148 len = Proc_Read(&My_Connections[i].proc_stat, readbuf, sizeof readbuf -1);
2152 readbuf[len] = '\0';
2153 identptr = strchr(readbuf, '\n');
2154 assert(identptr != NULL);
2156 Log( LOG_CRIT, "Resolver: Got malformed result!");
2161 LogDebug("Got result from resolver: \"%s\" (%u bytes read).", readbuf, len);
2162 /* Okay, we got a complete result: this is a host name for outgoing
2163 * connections and a host name and IDENT user name (if enabled) for
2164 * incoming connections.*/
2165 assert ( My_Connections[i].sock >= 0 );
2166 /* Incoming connection. Search client ... */
2167 c = Conn_GetClient( i );
2168 assert( c != NULL );
2170 /* Only update client information of unregistered clients.
2171 * Note: user commands (e. g. WEBIRC) are always read _after_ reading
2172 * the resolver results, so we don't have to worry to override settings
2173 * from these commands here. */
2174 if(Client_Type(c) == CLIENT_UNKNOWN) {
2175 strlcpy(My_Connections[i].host, readbuf,
2176 sizeof(My_Connections[i].host));
2177 Client_SetHostname(c, readbuf);
2181 Log(LOG_INFO, "IDENT lookup for connection %d: \"%s\".", i, identptr);
2182 Client_SetUser(c, identptr, true);
2184 Log(LOG_INFO, "IDENT lookup for connection %d: no result.", i);
2189 else Log( LOG_DEBUG, "Resolver: discarding result for already registered connection %d.", i );
2191 } /* cb_Read_Resolver_Result */
2195 * Write a "simple" (error) message to a socket.
2197 * The message is sent without using the connection write buffers, without
2198 * compression/encryption, and even without any error reporting. It is
2199 * designed for error messages of e.g. New_Connection().
2201 * @param Sock Socket handle.
2202 * @param Msg Message string to send.
2205 Simple_Message(int Sock, const char *Msg)
2207 char buf[COMMAND_LEN];
2210 assert(Sock > NONE);
2211 assert(Msg != NULL);
2213 strlcpy(buf, Msg, sizeof buf - 2);
2214 len = strlcat(buf, "\r\n", sizeof buf);
2215 if (write(Sock, buf, len) < 0) {
2216 /* Because this function most probably got called to log
2217 * an error message, any write error is ignored here to
2218 * avoid an endless loop. But casting the result of write()
2219 * to "void" doesn't satisfy the GNU C code attribute
2220 * "warn_unused_result" which is used by some versions of
2221 * glibc (e.g. 2.11.1), therefore this silly error
2222 * "handling" code here :-( */
2225 } /* Simple_Error */
2229 * Get CLIENT structure that belongs to a local connection identified by its
2230 * index number. Each connection belongs to a client by definition, so it is
2231 * not required that the caller checks for NULL return values.
2233 * @param Idx Connection index number.
2234 * @returns Pointer to CLIENT structure.
2237 Conn_GetClient( CONN_ID Idx )
2242 c = array_get(&My_ConnArray, sizeof (CONNECTION), (size_t)Idx);
2244 return c ? c->client : NULL;
2248 * Get PROC_STAT sub-process structure of a connection.
2250 * @param Idx Connection index number.
2251 * @returns PROC_STAT structure.
2254 Conn_GetProcStat(CONN_ID Idx)
2259 c = array_get(&My_ConnArray, sizeof (CONNECTION), (size_t)Idx);
2261 return &c->proc_stat;
2262 } /* Conn_GetProcStat */
2266 * Get CONN_ID from file descriptor associated to a subprocess structure.
2268 * @param fd File descriptor.
2269 * @returns CONN_ID or NONE (-1).
2272 Conn_GetFromProc(int fd)
2277 for (i = 0; i < Pool_Size; i++) {
2278 if ((My_Connections[i].sock != NONE)
2279 && (Proc_GetPipeFd(&My_Connections[i].proc_stat) == fd))
2283 } /* Conn_GetFromProc */
2289 * Get information about used SSL chiper.
2291 * @param Idx Connection index number.
2292 * @param buf Buffer for returned information text.
2293 * @param len Size of return buffer "buf".
2294 * @returns true on success, false otherwise.
2297 Conn_GetCipherInfo(CONN_ID Idx, char *buf, size_t len)
2301 assert(Idx < (int) array_length(&My_ConnArray, sizeof(CONNECTION)));
2302 return ConnSSL_GetCipherInfo(&My_Connections[Idx], buf, len);
2307 * Check if a connection is SSL-enabled or not.
2309 * @param Idx Connection index number.
2310 * @return true if connection is SSL-enabled, false otherwise.
2313 Conn_UsesSSL(CONN_ID Idx)
2317 assert(Idx < (int) array_length(&My_ConnArray, sizeof(CONNECTION)));
2318 return Conn_OPTION_ISSET(&My_Connections[Idx], CONN_SSL);
2327 * Dump internal state of the "connection module".
2330 Conn_DebugDump(void)
2334 Log(LOG_DEBUG, "Connection status:");
2335 for (i = 0; i < Pool_Size; i++) {
2336 if (My_Connections[i].sock == NONE)
2339 " - %d: host=%s, lastdata=%ld, lastping=%ld, delaytime=%ld, flag=%d, options=%d, bps=%d, client=%s",
2340 My_Connections[i].sock, My_Connections[i].host,
2341 My_Connections[i].lastdata, My_Connections[i].lastping,
2342 My_Connections[i].delaytime, My_Connections[i].flag,
2343 My_Connections[i].options, My_Connections[i].bps,
2344 My_Connections[i].client ? Client_ID(My_Connections[i].client) : "-");
2346 } /* Conn_DumpClients */