2 * ngIRCd -- The Next Generation IRC Daemon
3 * Copyright (c)2001-2007 Alexander Barton (alex@barton.de)
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 * Please read the file COPYING, README and AUTHORS for more information.
11 * Connection management
20 static char UNUSED id[] = "$Id: conn.c,v 1.215 2007/11/23 16:26:04 fw Exp $";
34 #include <sys/socket.h>
36 #include <sys/types.h>
38 #include <netinet/in.h>
40 #ifdef HAVE_NETINET_IP_H
41 # include <netinet/ip.h>
44 #ifdef HAVE_ARPA_INET_H
45 # include <arpa/inet.h>
47 # define PF_INET AF_INET
51 # include <stdint.h> /* e.g. for Mac OS X */
55 # include <tcpd.h> /* for TCP Wrappers */
70 #include "conn-func.h"
76 # include "rendezvous.h"
82 #define SERVER_WAIT (NONE - 1)
85 static bool Handle_Write PARAMS(( CONN_ID Idx ));
86 static bool Conn_Write PARAMS(( CONN_ID Idx, char *Data, size_t Len ));
87 static int New_Connection PARAMS(( int Sock ));
88 static CONN_ID Socket2Index PARAMS(( int Sock ));
89 static void Read_Request PARAMS(( CONN_ID Idx ));
90 static bool Handle_Buffer PARAMS(( CONN_ID Idx ));
91 static void Check_Connections PARAMS(( void ));
92 static void Check_Servers PARAMS(( void ));
93 static void Init_Conn_Struct PARAMS(( CONN_ID Idx ));
94 static bool Init_Socket PARAMS(( int Sock ));
95 static void New_Server PARAMS(( int Server ));
96 static void Simple_Message PARAMS(( int Sock, const char *Msg ));
97 static int Count_Connections PARAMS(( struct sockaddr_in addr ));
98 static int NewListener PARAMS(( const UINT16 Port ));
100 static array My_Listeners;
101 static array My_ConnArray;
104 int allow_severity = LOG_INFO;
105 int deny_severity = LOG_ERR;
108 static void server_login PARAMS((CONN_ID idx));
110 static void cb_Read_Resolver_Result PARAMS(( int sock, UNUSED short what));
111 static void cb_Connect_to_Server PARAMS(( int sock, UNUSED short what));
112 static void cb_clientserver PARAMS((int sock, short what));
115 cb_listen(int sock, short irrelevant)
118 New_Connection( sock );
123 cb_connserver(int sock, UNUSED short what)
127 CONN_ID idx = Socket2Index( sock );
129 LogDebug("cb_connserver wants to write on unknown socket?!");
134 assert( what & IO_WANTWRITE);
136 /* connect() finished, get result. */
137 sock_len = sizeof( err );
138 res = getsockopt( My_Connections[idx].sock, SOL_SOCKET, SO_ERROR, &err, &sock_len );
139 assert( sock_len == sizeof( err ));
141 /* Error while connecting? */
142 if ((res != 0) || (err != 0)) {
144 Log(LOG_CRIT, "getsockopt (connection %d): %s!",
145 idx, strerror(errno));
148 "Can't connect socket to \"%s:%d\" (connection %d): %s!",
149 My_Connections[idx].host,
150 Conf_Server[Conf_GetServer(idx)].port,
153 Conn_Close(idx, "Can't connect!", NULL, false);
157 Conn_OPTION_DEL( &My_Connections[idx], CONN_ISCONNECTING );
163 server_login(CONN_ID idx)
165 Log( LOG_INFO, "Connection %d with \"%s:%d\" established. Now logging in ...", idx,
166 My_Connections[idx].host, Conf_Server[Conf_GetServer( idx )].port );
168 io_event_setcb( My_Connections[idx].sock, cb_clientserver);
169 io_event_add( My_Connections[idx].sock, IO_WANTREAD|IO_WANTWRITE);
171 /* Send PASS and SERVER command to peer */
172 Conn_WriteStr( idx, "PASS %s %s", Conf_Server[Conf_GetServer( idx )].pwd_out, NGIRCd_ProtoID );
173 Conn_WriteStr( idx, "SERVER %s :%s", Conf_ServerName, Conf_ServerInfo );
178 cb_clientserver(int sock, short what)
180 CONN_ID idx = Socket2Index( sock );
183 Log(LOG_WARNING, "WTF: cb_clientserver wants to write on unknown socket?!");
189 if (what & IO_WANTREAD)
192 if (what & IO_WANTWRITE)
200 /* Modul initialisieren: statische Strukturen "ausnullen". */
204 /* Speicher fuer Verbindungs-Pool anfordern */
205 Pool_Size = CONNECTION_POOL;
206 if( Conf_MaxConnections > 0 )
208 /* konfiguriertes Limit beachten */
209 if( Pool_Size > Conf_MaxConnections ) Pool_Size = Conf_MaxConnections;
212 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)Pool_Size)) {
213 Log( LOG_EMERG, "Can't allocate memory! [Conn_Init]" );
217 /* FIXME: My_Connetions/Pool_Size is needed by other parts of the
218 * code; remove them! */
219 My_Connections = (CONNECTION*) array_start(&My_ConnArray);
221 LogDebug("Allocated connection pool for %d items (%ld bytes).",
222 array_length(&My_ConnArray, sizeof( CONNECTION )), array_bytes(&My_ConnArray));
224 assert( array_length(&My_ConnArray, sizeof( CONNECTION )) >= (size_t) Pool_Size);
226 array_free( &My_Listeners );
228 /* Connection-Struktur initialisieren */
229 for( i = 0; i < Pool_Size; i++ ) Init_Conn_Struct( i );
231 /* Global write counter */
239 /* Modul abmelden: alle noch offenen Connections
240 * schliessen und freigeben. */
244 LogDebug("Shutting down all connections ..." );
246 Conn_ExitListeners();
248 /* Sockets schliessen */
249 for( idx = 0; idx < Pool_Size; idx++ ) {
250 if( My_Connections[idx].sock > NONE ) {
251 Conn_Close( idx, NULL, NGIRCd_SignalRestart ?
252 "Server going down (restarting)":"Server going down", true );
256 array_free(&My_ConnArray);
257 My_Connections = NULL;
259 io_library_shutdown();
264 ports_initlisteners(array *a, void (*func)(int,short))
266 unsigned int created = 0;
271 len = array_length(a, sizeof (UINT16));
272 port = array_start(a);
274 fd = NewListener( *port );
279 if (!io_event_create( fd, IO_WANTREAD, func )) {
280 Log( LOG_ERR, "io_event_create(): Could not add listening fd %d (port %u): %s!",
281 fd, (unsigned int) *port, strerror(errno));
295 Conn_InitListeners( void )
297 /* Initialize ports on which the server should accept connections */
299 unsigned int created;
301 if (!io_library_init(CONNECTION_POOL)) {
302 Log(LOG_EMERG, "Cannot initialize IO routines: %s", strerror(errno));
306 created = ports_initlisteners(&Conf_ListenPorts, cb_listen);
309 } /* Conn_InitListeners */
313 Conn_ExitListeners( void )
315 /* Close down all listening sockets */
319 Rendezvous_UnregisterListeners( );
322 arraylen = array_length(&My_Listeners, sizeof (int));
323 Log( LOG_INFO, "Shutting down all listening sockets (%d total)...", arraylen );
324 fd = array_start(&My_Listeners);
329 LogDebug("Listening socket %d closed.", *fd );
332 array_free(&My_Listeners);
333 } /* Conn_ExitListeners */
337 InitSinaddr(struct sockaddr_in *addr, UINT16 Port)
339 struct in_addr inaddr;
341 memset(addr, 0, sizeof(*addr));
342 memset( &inaddr, 0, sizeof(inaddr));
344 addr->sin_family = AF_INET;
345 addr->sin_port = htons(Port);
346 inaddr.s_addr = htonl(INADDR_ANY);
347 addr->sin_addr = inaddr;
352 InitSinaddrListenAddr(struct sockaddr_in *addr, UINT16 Port)
354 struct in_addr inaddr;
356 InitSinaddr(addr, Port);
358 if (!Conf_ListenAddress[0])
361 if (!ngt_IPStrToBin(Conf_ListenAddress, &inaddr)) {
362 Log( LOG_CRIT, "Can't bind to %s:%u: can't convert ip address \"%s\"",
363 Conf_ListenAddress, Port, Conf_ListenAddress);
367 addr->sin_addr = inaddr;
372 /* return new listening port file descriptor or -1 on failure */
374 NewListener( const UINT16 Port )
376 /* Create new listening socket on specified port */
378 struct sockaddr_in addr;
381 char name[CLIENT_ID_LEN], *info;
384 InitSinaddrListenAddr(&addr, Port);
386 addr.sin_family = AF_INET;
387 addr.sin_port = htons( Port );
389 sock = socket( PF_INET, SOCK_STREAM, 0);
391 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
395 if( ! Init_Socket( sock )) return -1;
397 if (bind(sock, (struct sockaddr *)&addr, (socklen_t)sizeof(addr)) != 0) {
398 Log( LOG_CRIT, "Can't bind socket (port %d) : %s!", Port, strerror( errno ));
403 if( listen( sock, 10 ) != 0 ) {
404 Log( LOG_CRIT, "Can't listen on socket: %s!", strerror( errno ));
409 /* keep fd in list so we can close it when ngircd restarts/shuts down */
410 if (!array_catb( &My_Listeners,(char*) &sock, sizeof(int) )) {
411 Log( LOG_CRIT, "Can't add socket to My_Listeners array: %s!", strerror( errno ));
416 if( Conf_ListenAddress[0]) Log( LOG_INFO, "Now listening on %s:%d (socket %d).", Conf_ListenAddress, Port, sock );
417 else Log( LOG_INFO, "Now listening on 0.0.0.0:%d (socket %d).", Port, sock );
420 /* Get best server description text */
421 if( ! Conf_ServerInfo[0] ) info = Conf_ServerName;
424 /* Use server info string */
426 if( Conf_ServerInfo[0] == '[' )
428 /* Cut off leading hostname part in "[]" */
429 info = strchr( Conf_ServerInfo, ']' );
433 while( *info == ' ' ) info++;
436 if( ! info ) info = Conf_ServerInfo;
439 /* Add port number to description if non-standard */
441 snprintf(name, sizeof name, "%s (port %u)", info,
444 strlcpy(name, info, sizeof name);
446 /* Register service */
447 Rendezvous_Register( name, MDNS_TYPE, Port );
456 /* "Main Loop.": Loop until a signal (for shutdown or restart) arrives.
457 * Call io_dispatch() to check for read/writeable sockets every second
458 * Wait for status change on pending connections (e.g: when the hostname has been resolved)
459 * check for penalty/timeouts
460 * handle input buffers
463 unsigned int wdatalen;
468 while(( ! NGIRCd_SignalQuit ) && ( ! NGIRCd_SignalRestart )) {
472 Rendezvous_Handler( );
475 /* Should the configuration be reloaded? */
476 if (NGIRCd_SignalRehash) {
480 /* Check configured servers and established links */
482 Check_Connections( );
486 /* noch volle Lese-Buffer suchen */
487 for( i = 0; i < Pool_Size; i++ ) {
488 if(( My_Connections[i].sock > NONE ) && ( array_bytes(&My_Connections[i].rbuf) > 0 ) &&
489 ( My_Connections[i].delaytime < t ))
491 /* Kann aus dem Buffer noch ein Befehl extrahiert werden? */
492 if (Handle_Buffer( i )) timeout = false;
496 /* noch volle Schreib-Puffer suchen */
497 for( i = 0; i < Pool_Size; i++ ) {
498 if ( My_Connections[i].sock <= NONE )
501 wdatalen = (unsigned int)array_bytes(&My_Connections[i].wbuf);
504 if (( wdatalen > 0 ) || ( array_bytes(&My_Connections[i].zip.wbuf)> 0 ))
509 /* Socket der Verbindung in Set aufnehmen */
510 io_event_add( My_Connections[i].sock, IO_WANTWRITE );
514 /* von welchen Sockets koennte gelesen werden? */
515 for (i = 0; i < Pool_Size; i++ ) {
516 if ( My_Connections[i].sock <= NONE )
519 if (Resolve_INPROGRESS(&My_Connections[i].res_stat)) {
520 /* wait for completion of Resolver Sub-Process */
521 io_event_del( My_Connections[i].sock, IO_WANTREAD );
525 if ( Conn_OPTION_ISSET( &My_Connections[i], CONN_ISCONNECTING ))
526 continue; /* wait for completion of connect() */
528 if( My_Connections[i].delaytime > t ) {
529 /* Fuer die Verbindung ist eine "Penalty-Zeit" gesetzt */
530 io_event_del( My_Connections[i].sock, IO_WANTREAD );
533 io_event_add( My_Connections[i].sock, IO_WANTREAD );
536 /* (re-)set timeout - tv_sec/usec are undefined after io_dispatch() returns */
538 tv.tv_sec = timeout ? 1 : 0;
540 /* wait for activity */
541 i = io_dispatch( &tv );
542 if (i == -1 && errno != EINTR ) {
543 Log(LOG_EMERG, "Conn_Handler(): io_dispatch(): %s!", strerror(errno));
544 Log(LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE_NAME);
549 if( NGIRCd_SignalQuit ) Log( LOG_NOTICE|LOG_snotice, "Server going down NOW!" );
550 else if( NGIRCd_SignalRestart ) Log( LOG_NOTICE|LOG_snotice, "Server restarting NOW!" );
555 * Write a text string into the socket of a connection.
556 * This function automatically appends CR+LF to the string and validates that
557 * the result is a valid IRC message (oversized messages are shortened, for
558 * example). Then it calls the Conn_Write() function to do the actual sending.
559 * @param Idx Index fo the connection.
560 * @param Format Format string, see printf().
561 * @return true on success, false otherwise.
565 Conn_WriteStr( CONN_ID Idx, char *Format, ... )
568 Conn_WriteStr( Idx, Format, va_alist )
574 char buffer[COMMAND_LEN];
579 assert( Idx > NONE );
580 assert( Format != NULL );
583 va_start( ap, Format );
587 if (vsnprintf( buffer, COMMAND_LEN - 2, Format, ap ) >= COMMAND_LEN - 2 ) {
589 * The string that should be written to the socket is longer
590 * than the allowed size of COMMAND_LEN bytes (including both
591 * the CR and LF characters). This can be caused by the
592 * IRC_WriteXXX() functions when the prefix of this server had
593 * to be added to an already "quite long" command line which
594 * has been received from a regular IRC client, for example.
596 * We are not allowed to send such "oversized" messages to
597 * other servers and clients, see RFC 2812 2.3 and 2813 3.3
598 * ("these messages SHALL NOT exceed 512 characters in length,
599 * counting all characters including the trailing CR-LF").
601 * So we have a big problem here: we should send more bytes
602 * to the network than we are allowed to and we don't know
603 * the originator (any more). The "old" behaviour of blaming
604 * the receiver ("next hop") is a bad idea (it could be just
605 * an other server only routing the message!), so the only
606 * option left is to shorten the string and to hope that the
607 * result is still somewhat useful ...
611 strcpy (buffer + sizeof(buffer) - strlen(CUT_TXTSUFFIX) - 2 - 1,
617 Log(LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer);
620 len = strlcat( buffer, "\r\n", sizeof( buffer ));
621 ok = Conn_Write(Idx, buffer, len);
622 My_Connections[Idx].msg_out++;
626 } /* Conn_WriteStr */
630 * Append Data to the outbound write buffer of a connection.
631 * @param Idx Index of the connection.
632 * @param Data pointer to the data.
633 * @param Len length of Data.
634 * @return true on success, false otherwise.
637 Conn_Write( CONN_ID Idx, char *Data, size_t Len )
640 size_t writebuf_limit = WRITEBUFFER_LEN;
641 assert( Idx > NONE );
642 assert( Data != NULL );
645 c = Conn_GetClient(Idx);
648 /* Servers do get special write buffer limits, so they can generate
649 * all the messages that are required while peering. */
650 if (Client_Type(c) == CLIENT_SERVER)
651 writebuf_limit = WRITEBUFFER_SLINK_LEN;
653 /* Is the socket still open? A previous call to Conn_Write()
654 * may have closed the connection due to a fatal error.
655 * In this case it is sufficient to return an error, as well. */
656 if( My_Connections[Idx].sock <= NONE ) {
657 LogDebug("Skipped write on closed socket (connection %d).", Idx);
662 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
664 * Zip_Buffer() does all the dirty work for us: it flushes
665 * the (pre-)compression buffers if required and handles
666 * all error conditions. */
667 if (!Zip_Buffer(Idx, Data, Len))
673 /* Uncompressed link:
674 * Check if outbound buffer has enough space for the data. */
675 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
677 /* Buffer is full, flush it. Handle_Write deals with
678 * low-level errors, if any. */
679 if (!Handle_Write(Idx))
683 /* When the write buffer is still too big after flushing it,
684 * the connection will be killed. */
685 if (array_bytes(&My_Connections[Idx].wbuf) + Len >=
688 "Write buffer overflow (connection %d, size %lu byte)!",
690 (unsigned long)array_bytes(&My_Connections[Idx].wbuf));
691 Conn_Close(Idx, "Write buffer overflow!", NULL, false);
695 /* Copy data to write buffer */
696 if (!array_catb(&My_Connections[Idx].wbuf, Data, Len))
699 My_Connections[Idx].bytes_out += Len;
702 /* Adjust global write counter */
710 Conn_Close( CONN_ID Idx, char *LogMsg, char *FwdMsg, bool InformClient )
712 /* Close connection. Open pipes of asyncronous resolver
713 * sub-processes are closed down. */
719 double in_z_k, out_z_k;
723 assert( Idx > NONE );
725 /* Is this link already shutting down? */
726 if( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ISCLOSING )) {
727 /* Conn_Close() has been called recursively for this link;
728 * probabe reason: Handle_Write() failed -- see below. */
729 LogDebug("Recursive request to close connection: %d", Idx );
733 assert( My_Connections[Idx].sock > NONE );
735 /* Mark link as "closing" */
736 Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCLOSING );
743 txt = "Reason unknown";
745 Log(LOG_INFO, "Shutting down connection %d (%s) with %s:%d ...", Idx,
746 LogMsg ? LogMsg : FwdMsg, My_Connections[Idx].host,
747 ntohs(My_Connections[Idx].addr.sin_port));
749 /* Search client, if any */
750 c = Conn_GetClient( Idx );
752 /* Should the client be informed? */
755 /* Send statistics to client if registered as user: */
756 if ((c != NULL) && (Client_Type(c) == CLIENT_USER)) {
758 ":%s NOTICE %s :%sConnection statistics: client %.1f kb, server %.1f kb.",
759 Client_ID(Client_ThisServer()), Client_ID(c),
761 (double)My_Connections[Idx].bytes_in / 1024,
762 (double)My_Connections[Idx].bytes_out / 1024);
765 /* Send ERROR to client (see RFC!) */
767 Conn_WriteStr(Idx, "ERROR :%s", FwdMsg);
769 Conn_WriteStr(Idx, "ERROR :Closing connection.");
772 /* Try to write out the write buffer. Note: Handle_Write() eventually
773 * removes the CLIENT structure associated with this connection if an
774 * error occurs! So we have to re-check if there is still an valid
775 * CLIENT structure after calling Handle_Write() ...*/
776 (void)Handle_Write( Idx );
778 /* Search client, if any (re-check!) */
779 c = Conn_GetClient( Idx );
781 /* Shut down socket */
782 if (! io_close(My_Connections[Idx].sock)) {
783 /* Oops, we can't close the socket!? This is ... ugly! */
785 "Error closing connection %d (socket %d) with %s:%d - %s! (ignored)",
786 Idx, My_Connections[Idx].sock, My_Connections[Idx].host,
787 ntohs(My_Connections[Idx].addr.sin_port), strerror(errno));
790 /* Mark socket as invalid: */
791 My_Connections[Idx].sock = NONE;
793 /* If there is still a client, unregister it now */
795 Client_Destroy(c, LogMsg, FwdMsg, true);
797 /* Calculate statistics and log information */
798 in_k = (double)My_Connections[Idx].bytes_in / 1024;
799 out_k = (double)My_Connections[Idx].bytes_out / 1024;
801 if (Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP)) {
802 in_z_k = (double)My_Connections[Idx].zip.bytes_in / 1024;
803 out_z_k = (double)My_Connections[Idx].zip.bytes_out / 1024;
804 /* Make sure that no division by zero can occur during
805 * the calculation of in_p and out_p: in_z_k and out_z_k
806 * are non-zero, that's guaranteed by the protocol until
807 * compression can be enabled. */
812 in_p = (int)(( in_k * 100 ) / in_z_k );
813 out_p = (int)(( out_k * 100 ) / out_z_k );
815 "Connection %d with %s:%d closed (in: %.1fk/%.1fk/%d%%, out: %.1fk/%.1fk/%d%%).",
816 Idx, My_Connections[Idx].host,
817 ntohs(My_Connections[Idx].addr.sin_port),
818 in_k, in_z_k, in_p, out_k, out_z_k, out_p);
824 "Connection %d with %s:%d closed (in: %.1fk, out: %.1fk).",
825 Idx, My_Connections[Idx].host,
826 ntohs(My_Connections[Idx].addr.sin_port),
830 /* cancel running resolver */
831 if (Resolve_INPROGRESS(&My_Connections[Idx].res_stat))
832 Resolve_Shutdown(&My_Connections[Idx].res_stat);
834 /* Servers: Modify time of next connect attempt? */
835 Conf_UnsetServer( Idx );
838 /* Clean up zlib, if link was compressed */
839 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
840 inflateEnd( &My_Connections[Idx].zip.in );
841 deflateEnd( &My_Connections[Idx].zip.out );
842 array_free(&My_Connections[Idx].zip.rbuf);
843 array_free(&My_Connections[Idx].zip.wbuf);
847 array_free(&My_Connections[Idx].rbuf);
848 array_free(&My_Connections[Idx].wbuf);
850 /* Clean up connection structure (=free it) */
851 Init_Conn_Struct( Idx );
853 LogDebug("Shutdown of connection %d completed.", Idx );
858 Conn_SyncServerStruct( void )
860 /* Synchronize server structures (connection IDs):
861 * connections <-> configuration */
867 for( i = 0; i < Pool_Size; i++ ) {
868 /* Established connection? */
869 if (My_Connections[i].sock < 0)
872 /* Server connection? */
873 client = Conn_GetClient( i );
874 if(( ! client ) || ( Client_Type( client ) != CLIENT_SERVER )) continue;
876 for( c = 0; c < MAX_SERVERS; c++ )
878 /* Configured server? */
879 if( ! Conf_Server[c].host[0] ) continue;
882 if( strcmp( Conf_Server[c].name, Client_ID( client )) == 0 )
883 Conf_Server[c].conn_id = i;
886 } /* SyncServerStruct */
890 * Send out data of write buffer; connect new sockets.
893 Handle_Write( CONN_ID Idx )
898 assert( Idx > NONE );
899 if ( My_Connections[Idx].sock < 0 ) {
900 LogDebug("Handle_Write() on closed socket, connection %d", Idx);
903 assert( My_Connections[Idx].sock > NONE );
905 wdatalen = array_bytes(&My_Connections[Idx].wbuf );
909 /* Write buffer is empty, so we try to flush the compression
910 * buffer and get some data to work with from there :-) */
914 /* Now the write buffer most probably has changed: */
915 wdatalen = array_bytes(&My_Connections[Idx].wbuf);
920 /* Still no data, fine. */
921 io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
926 ("Handle_Write() called for connection %d, %ld bytes pending ...",
929 len = write(My_Connections[Idx].sock,
930 array_start(&My_Connections[Idx].wbuf), wdatalen );
933 if (errno == EAGAIN || errno == EINTR)
936 Log(LOG_ERR, "Write error on connection %d (socket %d): %s!",
937 Idx, My_Connections[Idx].sock, strerror(errno));
938 Conn_Close(Idx, "Write error!", NULL, false);
942 /* move any data not yet written to beginning */
943 array_moveleft(&My_Connections[Idx].wbuf, 1, (size_t)len);
950 New_Connection( int Sock )
952 /* Neue Client-Verbindung von Listen-Socket annehmen und
953 * CLIENT-Struktur anlegen. */
956 struct request_info req;
958 struct sockaddr_in new_addr;
959 int new_sock, new_sock_len, new_Pool_Size;
963 assert( Sock > NONE );
964 /* Connection auf Listen-Socket annehmen */
965 new_sock_len = (int)sizeof new_addr;
966 new_sock = accept(Sock, (struct sockaddr *)&new_addr,
967 (socklen_t *)&new_sock_len);
969 Log(LOG_CRIT, "Can't accept connection: %s!", strerror(errno));
974 /* Validate socket using TCP Wrappers */
975 request_init( &req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock, RQ_CLIENT_SIN, &new_addr, NULL );
977 if( ! hosts_access( &req ))
980 Log( deny_severity, "Refused connection from %s (by TCP Wrappers)!", inet_ntoa( new_addr.sin_addr ));
981 Simple_Message( new_sock, "ERROR :Connection refused" );
987 /* Socket initialisieren */
988 if (!Init_Socket( new_sock ))
991 /* Check IP-based connection limit */
992 cnt = Count_Connections( new_addr );
993 if(( Conf_MaxConnectionsIP > 0 ) && ( cnt >= Conf_MaxConnectionsIP ))
995 /* Access denied, too many connections from this IP address! */
996 Log( LOG_ERR, "Refused connection from %s: too may connections (%ld) from this IP address!", inet_ntoa( new_addr.sin_addr ), cnt);
997 Simple_Message( new_sock, "ERROR :Connection refused, too many connections from your IP address!" );
1002 if( new_sock >= Pool_Size ) {
1003 new_Pool_Size = new_sock + 1;
1004 /* No free Connection Structures, check if we may accept further connections */
1005 if ((( Conf_MaxConnections > 0) && Pool_Size >= Conf_MaxConnections) ||
1006 (new_Pool_Size < Pool_Size))
1008 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached!", Pool_Size );
1009 Simple_Message( new_sock, "ERROR :Connection limit reached" );
1014 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION),
1015 (size_t)new_sock)) {
1016 Log( LOG_EMERG, "Can't allocate memory! [New_Connection]" );
1017 Simple_Message( new_sock, "ERROR: Internal error" );
1021 LogDebug("Bumped connection pool to %ld items (internal: %ld items, %ld bytes)",
1022 new_sock, array_length(&My_ConnArray, sizeof(CONNECTION)), array_bytes(&My_ConnArray));
1024 /* Adjust pointer to new block */
1025 My_Connections = array_start(&My_ConnArray);
1026 while (Pool_Size < new_Pool_Size)
1027 Init_Conn_Struct(Pool_Size++);
1030 /* register callback */
1031 if (!io_event_create( new_sock, IO_WANTREAD, cb_clientserver)) {
1032 Log(LOG_ALERT, "Can't accept connection: io_event_create failed!");
1033 Simple_Message(new_sock, "ERROR :Internal error");
1038 c = Client_NewLocal( new_sock, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWN, false );
1040 Log(LOG_ALERT, "Can't accept connection: can't create client structure!");
1041 Simple_Message(new_sock, "ERROR :Internal error");
1046 Init_Conn_Struct( new_sock );
1047 My_Connections[new_sock].sock = new_sock;
1048 My_Connections[new_sock].addr = new_addr;
1049 My_Connections[new_sock].client = c;
1051 Log( LOG_INFO, "Accepted connection %d from %s:%d on socket %d.", new_sock,
1052 inet_ntoa( new_addr.sin_addr ), ntohs( new_addr.sin_port), Sock );
1054 /* Hostnamen ermitteln */
1055 strlcpy( My_Connections[new_sock].host, inet_ntoa( new_addr.sin_addr ),
1056 sizeof( My_Connections[new_sock].host ));
1058 Client_SetHostname( c, My_Connections[new_sock].host );
1061 Resolve_Addr(&My_Connections[new_sock].res_stat, &new_addr,
1062 My_Connections[new_sock].sock, cb_Read_Resolver_Result);
1064 Conn_SetPenalty(new_sock, 4);
1066 } /* New_Connection */
1070 Socket2Index( int Sock )
1072 /* zum Socket passende Connection suchen */
1074 assert( Sock >= 0 );
1076 if( Sock >= Pool_Size || My_Connections[Sock].sock != Sock ) {
1077 /* die Connection wurde vermutlich (wegen eines
1078 * Fehlers) bereits wieder abgebaut ... */
1079 LogDebug("Socket2Index: can't get connection for socket %d!", Sock);
1083 } /* Socket2Index */
1087 * Read data from the network to the read buffer. If an error occures,
1088 * the socket of this connection will be shut down.
1091 Read_Request( CONN_ID Idx )
1094 char readbuf[READBUFFER_LEN];
1096 assert( Idx > NONE );
1097 assert( My_Connections[Idx].sock > NONE );
1100 if ((array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN) ||
1101 (array_bytes(&My_Connections[Idx].zip.rbuf) >= READBUFFER_LEN))
1103 if (array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN)
1106 /* Read buffer is full */
1108 "Receive buffer overflow (connection %d): %d bytes!",
1109 Idx, array_bytes(&My_Connections[Idx].rbuf));
1110 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1114 len = read(My_Connections[Idx].sock, readbuf, sizeof(readbuf));
1116 Log(LOG_INFO, "%s:%d (%s) is closing the connection ...",
1117 My_Connections[Idx].host,
1118 ntohs(My_Connections[Idx].addr.sin_port),
1119 inet_ntoa( My_Connections[Idx].addr.sin_addr));
1121 "Socket closed!", "Client closed connection",
1127 if( errno == EAGAIN ) return;
1128 Log(LOG_ERR, "Read error on connection %d (socket %d): %s!",
1129 Idx, My_Connections[Idx].sock, strerror(errno));
1130 Conn_Close(Idx, "Read error!", "Client closed connection",
1135 if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
1136 if (!array_catb(&My_Connections[Idx].zip.rbuf, readbuf,
1139 "Could not append recieved data to zip input buffer (connn %d): %d bytes!",
1141 Conn_Close(Idx, "Receive buffer overflow!", NULL,
1148 if (!array_catb( &My_Connections[Idx].rbuf, readbuf, len)) {
1149 Log( LOG_ERR, "Could not append recieved data to input buffer (connn %d): %d bytes!", Idx, len );
1150 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1154 /* Update connection statistics */
1155 My_Connections[Idx].bytes_in += len;
1157 /* Update timestamp of last data received if this connection is
1158 * registered as a user, server or service connection. Don't update
1159 * otherwise, so users have at least Conf_PongTimeout seconds time to
1160 * register with the IRC server -- see Check_Connections().
1161 * Set "lastping", too, so we can handle time shifts backwards ... */
1162 c = Conn_GetClient(Idx);
1163 if (c && (Client_Type(c) == CLIENT_USER
1164 || Client_Type(c) == CLIENT_SERVER
1165 || Client_Type(c) == CLIENT_SERVICE)) {
1166 My_Connections[Idx].lastdata = time(NULL);
1167 My_Connections[Idx].lastping = My_Connections[Idx].lastdata;
1170 /* Look at the data in the (read-) buffer of this connection */
1172 } /* Read_Request */
1176 Handle_Buffer( CONN_ID Idx )
1178 /* Handle Data in Connections Read-Buffer.
1179 * Return true if a reuqest was handled, false otherwise (also returned on errors). */
1191 starttime = time(NULL);
1195 if( My_Connections[Idx].delaytime > starttime) return result;
1197 /* unpack compressed data */
1198 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP ))
1199 if( ! Unzip_Buffer( Idx )) return false;
1202 if (0 == array_bytes(&My_Connections[Idx].rbuf))
1205 if (!array_cat0_temporary(&My_Connections[Idx].rbuf)) /* make sure buf is NULL terminated */
1208 /* A Complete Request end with CR+LF, see RFC 2812. */
1209 ptr = strstr( array_start(&My_Connections[Idx].rbuf), "\r\n" );
1211 if( ptr ) delta = 2; /* complete request */
1214 /* Check for non-RFC-compliant request (only CR or LF)? Unfortunately,
1215 * there are quite a few clients that do this (incl. "mIRC" :-( */
1216 ptr1 = strchr( array_start(&My_Connections[Idx].rbuf), '\r' );
1217 ptr2 = strchr( array_start(&My_Connections[Idx].rbuf), '\n' );
1219 if( ptr1 && ptr2 ) ptr = ptr1 > ptr2 ? ptr2 : ptr1;
1220 else if( ptr1 ) ptr = ptr1;
1221 else if( ptr2 ) ptr = ptr2;
1228 /* End of request found */
1231 len = ( ptr - (char*) array_start(&My_Connections[Idx].rbuf)) + delta;
1233 if( len > ( COMMAND_LEN - 1 )) {
1234 /* Request must not exceed 512 chars (incl. CR+LF!), see
1235 * RFC 2812. Disconnect Client if this happens. */
1236 Log( LOG_ERR, "Request too long (connection %d): %d bytes (max. %d expected)!",
1237 Idx, array_bytes(&My_Connections[Idx].rbuf), COMMAND_LEN - 1 );
1238 Conn_Close( Idx, NULL, "Request too long", true );
1242 if (len <= 2) { /* request was empty (only '\r\n') */
1243 array_moveleft(&My_Connections[Idx].rbuf, 1, delta); /* delta is either 1 or 2 */
1247 /* remember if stream is already compressed */
1248 old_z = My_Connections[Idx].options & CONN_ZIP;
1251 My_Connections[Idx].msg_in++;
1252 if (!Parse_Request(Idx, (char*)array_start(&My_Connections[Idx].rbuf) ))
1257 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1258 LogDebug("Connection %d: %d bytes left in read buffer.",
1259 Idx, array_bytes(&My_Connections[Idx].rbuf));
1261 if(( ! old_z ) && ( My_Connections[Idx].options & CONN_ZIP ) &&
1262 ( array_bytes(&My_Connections[Idx].rbuf) > 0 ))
1264 /* The last Command activated Socket-Compression.
1265 * Data that was read after that needs to be copied to Unzip-buf
1266 * for decompression */
1267 if (!array_copy( &My_Connections[Idx].zip.rbuf, &My_Connections[Idx].rbuf ))
1270 array_trunc(&My_Connections[Idx].rbuf);
1271 LogDebug("Moved already received data (%u bytes) to uncompression buffer.",
1272 array_bytes(&My_Connections[Idx].zip.rbuf));
1277 } /* Handle_Buffer */
1281 Check_Connections(void)
1283 /* check if connections are alive. if not, play PING-PONG first.
1284 * if this doesn't help either, disconnect client. */
1288 for (i = 0; i < Pool_Size; i++) {
1289 if (My_Connections[i].sock < 0)
1292 c = Conn_GetClient(i);
1293 if (c && ((Client_Type(c) == CLIENT_USER)
1294 || (Client_Type(c) == CLIENT_SERVER)
1295 || (Client_Type(c) == CLIENT_SERVICE))) {
1296 /* connected User, Server or Service */
1297 if (My_Connections[i].lastping >
1298 My_Connections[i].lastdata) {
1299 /* We already sent a ping */
1300 if (My_Connections[i].lastping <
1301 time(NULL) - Conf_PongTimeout) {
1304 ("Connection %d: Ping timeout: %d seconds.",
1305 i, Conf_PongTimeout);
1306 Conn_Close(i, NULL, "Ping timeout",
1309 } else if (My_Connections[i].lastdata <
1310 time(NULL) - Conf_PingTimeout) {
1311 /* We need to send a PING ... */
1312 LogDebug("Connection %d: sending PING ...", i);
1313 My_Connections[i].lastping = time(NULL);
1314 Conn_WriteStr(i, "PING :%s",
1315 Client_ID(Client_ThisServer()));
1318 /* The connection is not fully established yet, so
1319 * we don't do the PING-PONG game here but instead
1320 * disconnect the client after "a short time" if it's
1321 * still not registered. */
1323 if (My_Connections[i].lastdata <
1324 time(NULL) - Conf_PongTimeout) {
1326 ("Unregistered connection %d timed out ...",
1328 Conn_Close(i, NULL, "Timeout", false);
1332 } /* Check_Connections */
1336 Check_Servers( void )
1338 /* Check if we can establish further server links */
1343 /* Check all configured servers */
1344 for( i = 0; i < MAX_SERVERS; i++ ) {
1345 /* Valid outgoing server which isn't already connected or disabled? */
1346 if(( ! Conf_Server[i].host[0] ) || ( ! Conf_Server[i].port > 0 ) ||
1347 ( Conf_Server[i].conn_id > NONE ) || ( Conf_Server[i].flags & CONF_SFLAG_DISABLED ))
1350 /* Is there already a connection in this group? */
1351 if( Conf_Server[i].group > NONE ) {
1352 for (n = 0; n < MAX_SERVERS; n++) {
1353 if (n == i) continue;
1354 if ((Conf_Server[n].conn_id != NONE) &&
1355 (Conf_Server[n].group == Conf_Server[i].group))
1358 if (n < MAX_SERVERS) continue;
1361 /* Check last connect attempt? */
1362 time_now = time(NULL);
1363 if( Conf_Server[i].lasttry > (time_now - Conf_ConnectRetry))
1366 /* Okay, try to connect now */
1367 Conf_Server[i].lasttry = time_now;
1368 Conf_Server[i].conn_id = SERVER_WAIT;
1369 assert(Resolve_Getfd(&Conf_Server[i].res_stat) < 0);
1370 Resolve_Name(&Conf_Server[i].res_stat, Conf_Server[i].host, cb_Connect_to_Server);
1372 } /* Check_Servers */
1376 New_Server( int Server )
1378 /* Establish new server link */
1379 struct sockaddr_in local_addr;
1380 struct sockaddr_in new_addr;
1381 struct in_addr inaddr;
1385 assert( Server > NONE );
1387 Log( LOG_INFO, "Establishing connection to \"%s\", %s, port %d ... ", Conf_Server[Server].host,
1388 Conf_Server[Server].ip, Conf_Server[Server].port );
1390 #ifdef HAVE_INET_ATON
1391 if( inet_aton( Conf_Server[Server].ip, &inaddr ) == 0 )
1393 memset( &inaddr, 0, sizeof( inaddr ));
1394 inaddr.s_addr = inet_addr( Conf_Server[Server].ip );
1395 if( inaddr.s_addr == (unsigned)-1 )
1398 Log( LOG_ERR, "Can't connect to \"%s\": can't convert ip address %s!",
1399 Conf_Server[Server].host, Conf_Server[Server].ip );
1403 memset(&new_addr, 0, sizeof( new_addr ));
1404 new_addr.sin_family = AF_INET;
1405 new_addr.sin_addr = inaddr;
1406 new_addr.sin_port = htons( Conf_Server[Server].port );
1409 new_sock = socket( PF_INET, SOCK_STREAM, 0 );
1410 if ( new_sock < 0 ) {
1411 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
1415 if( ! Init_Socket( new_sock )) return;
1417 /* if we fail to bind, just continue and let connect() pick a source address */
1418 InitSinaddr(&local_addr, 0);
1419 local_addr.sin_addr = Conf_Server[Server].bind_addr;
1420 if (bind(new_sock, (struct sockaddr *)&local_addr, (socklen_t)sizeof(local_addr)))
1421 Log(LOG_WARNING, "Can't bind socket to %s!", Conf_ListenAddress, strerror( errno ));
1423 res = connect(new_sock, (struct sockaddr *)&new_addr,
1424 (socklen_t)sizeof(new_addr));
1425 if(( res != 0 ) && ( errno != EINPROGRESS )) {
1426 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1431 if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)new_sock)) {
1433 "Cannot allocate memory for server connection (socket %d)",
1439 My_Connections = array_start(&My_ConnArray);
1441 assert(My_Connections[new_sock].sock <= 0);
1443 Init_Conn_Struct(new_sock);
1445 c = Client_NewLocal( new_sock, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWNSERVER, false );
1447 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1452 Client_SetIntroducer( c, c );
1453 Client_SetToken( c, TOKEN_OUTBOUND );
1455 /* Register connection */
1456 Conf_Server[Server].conn_id = new_sock;
1457 My_Connections[new_sock].sock = new_sock;
1458 My_Connections[new_sock].addr = new_addr;
1459 My_Connections[new_sock].client = c;
1460 strlcpy( My_Connections[new_sock].host, Conf_Server[Server].host,
1461 sizeof(My_Connections[new_sock].host ));
1463 /* Register new socket */
1464 if (!io_event_create( new_sock, IO_WANTWRITE, cb_connserver)) {
1465 Log( LOG_ALERT, "io_event_create(): could not add fd %d", strerror(errno));
1466 Conn_Close( new_sock, "io_event_create() failed", NULL, false );
1467 Init_Conn_Struct( new_sock );
1468 Conf_Server[Server].conn_id = NONE;
1471 LogDebug("Registered new connection %d on socket %d.",
1472 new_sock, My_Connections[new_sock].sock );
1473 Conn_OPTION_ADD( &My_Connections[new_sock], CONN_ISCONNECTING );
1478 * Initialize connection structure.
1481 Init_Conn_Struct(CONN_ID Idx)
1483 time_t now = time(NULL);
1485 memset(&My_Connections[Idx], 0, sizeof(CONNECTION));
1486 My_Connections[Idx].sock = -1;
1487 My_Connections[Idx].signon = now;
1488 My_Connections[Idx].lastdata = now;
1489 My_Connections[Idx].lastprivmsg = now;
1490 Resolve_Init(&My_Connections[Idx].res_stat);
1491 } /* Init_Conn_Struct */
1495 Init_Socket( int Sock )
1497 /* Initialize socket (set options) */
1501 if (!io_setnonblock(Sock)) {
1502 Log( LOG_CRIT, "Can't enable non-blocking mode for socket: %s!", strerror( errno ));
1507 /* Don't block this port after socket shutdown */
1509 if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &value, (socklen_t)sizeof( value )) != 0 )
1511 Log( LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!", strerror( errno ));
1512 /* ignore this error */
1515 /* Set type of service (TOS) */
1516 #if defined(IP_TOS) && defined(IPTOS_LOWDELAY)
1517 value = IPTOS_LOWDELAY;
1518 LogDebug("Setting option IP_TOS on socket %d to IPTOS_LOWDELAY (%d).", Sock, value );
1519 if( setsockopt( Sock, SOL_IP, IP_TOS, &value, (socklen_t)sizeof( value )) != 0 )
1521 Log( LOG_ERR, "Can't set socket option IP_TOS: %s!", strerror( errno ));
1522 /* ignore this error */
1532 cb_Connect_to_Server(int fd, UNUSED short events)
1534 /* Read result of resolver sub-process from pipe and start connection */
1537 char readbuf[HOST_LEN + 1];
1539 LogDebug("Resolver: Got forward lookup callback on fd %d, events %d", fd, events);
1541 for (i=0; i < MAX_SERVERS; i++) {
1542 if (Resolve_Getfd(&Conf_Server[i].res_stat) == fd )
1546 if( i >= MAX_SERVERS) {
1547 /* Ops, no matching server found?! */
1549 LogDebug("Resolver: Got Forward Lookup callback for unknown server!?");
1553 /* Read result from pipe */
1554 len = Resolve_Read(&Conf_Server[i].res_stat, readbuf, sizeof readbuf -1);
1558 readbuf[len] = '\0';
1559 LogDebug("Got result from resolver: \"%s\" (%u bytes read).", readbuf, len);
1560 strlcpy( Conf_Server[i].ip, readbuf, sizeof( Conf_Server[i].ip ));
1564 } /* cb_Read_Forward_Lookup */
1568 cb_Read_Resolver_Result( int r_fd, UNUSED short events )
1570 /* Read result of resolver sub-process from pipe and update the
1571 * apropriate connection/client structure(s): hostname and/or
1572 * IDENT user name.*/
1579 char readbuf[HOST_LEN + 2 + CLIENT_USER_LEN];
1581 char readbuf[HOST_LEN + 1];
1584 LogDebug("Resolver: Got callback on fd %d, events %d", r_fd, events );
1586 /* Search associated connection ... */
1587 for( i = 0; i < Pool_Size; i++ ) {
1588 if(( My_Connections[i].sock != NONE )
1589 && ( Resolve_Getfd(&My_Connections[i].res_stat) == r_fd ))
1592 if( i >= Pool_Size ) {
1593 /* Ops, none found? Probably the connection has already
1594 * been closed!? We'll ignore that ... */
1596 LogDebug("Resolver: Got callback for unknown connection!?");
1600 /* Read result from pipe */
1601 len = Resolve_Read(&My_Connections[i].res_stat, readbuf, sizeof readbuf -1);
1605 readbuf[len] = '\0';
1606 identptr = strchr(readbuf, '\n');
1607 assert(identptr != NULL);
1609 Log( LOG_CRIT, "Resolver: Got malformed result!");
1614 LogDebug("Got result from resolver: \"%s\" (%u bytes read).", readbuf, len);
1615 /* Okay, we got a complete result: this is a host name for outgoing
1616 * connections and a host name and IDENT user name (if enabled) for
1617 * incoming connections.*/
1618 assert ( My_Connections[i].sock >= 0 );
1619 /* Incoming connection. Search client ... */
1620 c = Conn_GetClient( i );
1621 assert( c != NULL );
1623 /* Only update client information of unregistered clients */
1624 if( Client_Type( c ) == CLIENT_UNKNOWN ) {
1625 strlcpy(My_Connections[i].host, readbuf, sizeof( My_Connections[i].host));
1626 Client_SetHostname( c, readbuf);
1630 Log( LOG_INFO, "IDENT lookup for connection %ld: \"%s\".", i, identptr);
1631 Client_SetUser( c, identptr, true );
1633 Log( LOG_INFO, "IDENT lookup for connection %ld: no result.", i );
1638 else Log( LOG_DEBUG, "Resolver: discarding result for already registered connection %d.", i );
1640 /* Reset penalty time */
1641 Conn_ResetPenalty( i );
1642 } /* cb_Read_Resolver_Result */
1646 Simple_Message( int Sock, const char *Msg )
1648 char buf[COMMAND_LEN];
1650 /* Write "simple" message to socket, without using compression
1651 * or even the connection write buffers. Used e.g. for error
1652 * messages by New_Connection(). */
1653 assert( Sock > NONE );
1654 assert( Msg != NULL );
1656 strlcpy( buf, Msg, sizeof buf - 2);
1657 len = strlcat( buf, "\r\n", sizeof buf);
1658 (void)write(Sock, buf, len);
1659 } /* Simple_Error */
1663 Count_Connections( struct sockaddr_in addr_in )
1668 for( i = 0; i < Pool_Size; i++ ) {
1669 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].addr.sin_addr.s_addr == addr_in.sin_addr.s_addr )) cnt++;
1672 } /* Count_Connections */
1676 Conn_GetClient( CONN_ID Idx )
1678 /* return Client-Structure that belongs to the local Connection Idx.
1679 * If none is found, return NULL.
1684 c = array_get(&My_ConnArray, sizeof (CONNECTION), (size_t)Idx);
1688 return c ? c->client : NULL;