2 * ngIRCd -- The Next Generation IRC Daemon
3 * Copyright (c)2001-2005 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.186 2005/12/09 09:26:55 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 int New_Connection PARAMS(( int Sock ));
87 static CONN_ID Socket2Index PARAMS(( int Sock ));
88 static void Read_Request PARAMS(( CONN_ID Idx ));
89 static bool Handle_Buffer PARAMS(( CONN_ID Idx ));
90 static void Check_Connections PARAMS(( void ));
91 static void Check_Servers PARAMS(( void ));
92 static void Init_Conn_Struct PARAMS(( CONN_ID Idx ));
93 static bool Init_Socket PARAMS(( int Sock ));
94 static void New_Server PARAMS(( int Server, CONN_ID Idx ));
95 static void Simple_Message PARAMS(( int Sock, char *Msg ));
96 static int Count_Connections PARAMS(( struct sockaddr_in addr ));
97 static int NewListener PARAMS(( const UINT16 Port ));
99 static array My_Listeners;
102 int allow_severity = LOG_INFO;
103 int deny_severity = LOG_ERR;
106 static void server_login PARAMS((CONN_ID idx));
108 static void cb_Read_Resolver_Result PARAMS(( int sock, UNUSED short what));
109 static void cb_clientserver PARAMS((int sock, short what));
112 cb_listen(int sock, short irrelevant)
115 New_Connection( sock );
120 cb_connserver(int sock, UNUSED short what)
125 CONN_ID idx = Socket2Index( sock );
128 Log(LOG_DEBUG, "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 /* Clean up the CLIENT structure (to avoid silly log
154 * messages) and call Conn_Close() to do the rest. */
155 c = Client_GetFromConn(idx);
157 Client_DestroyNow(c);
159 Conn_Close(idx, "Can't connect!", NULL, false);
164 Conn_OPTION_DEL( &My_Connections[idx], CONN_ISCONNECTING );
170 server_login(CONN_ID idx)
172 Log( LOG_INFO, "Connection %d with \"%s:%d\" established. Now logging in ...", idx,
173 My_Connections[idx].host, Conf_Server[Conf_GetServer( idx )].port );
175 io_event_setcb( My_Connections[idx].sock, cb_clientserver);
176 io_event_add( My_Connections[idx].sock, IO_WANTREAD|IO_WANTWRITE);
178 /* Send PASS and SERVER command to peer */
179 Conn_WriteStr( idx, "PASS %s %s", Conf_Server[Conf_GetServer( idx )].pwd_out, NGIRCd_ProtoID );
180 Conn_WriteStr( idx, "SERVER %s :%s", Conf_ServerName, Conf_ServerInfo );
185 cb_clientserver(int sock, short what)
187 CONN_ID idx = Socket2Index( sock );
190 Log(LOG_WARNING, "WTF: cb_clientserver wants to write on unknown socket?!");
196 if (what & IO_WANTREAD)
199 if (what & IO_WANTWRITE)
207 /* Modul initialisieren: statische Strukturen "ausnullen". */
211 /* Speicher fuer Verbindungs-Pool anfordern */
212 Pool_Size = CONNECTION_POOL;
213 if( Conf_MaxConnections > 0 )
215 /* konfiguriertes Limit beachten */
216 if( Pool_Size > Conf_MaxConnections ) Pool_Size = Conf_MaxConnections;
218 My_Connections = (CONNECTION *) calloc( Pool_Size, sizeof( CONNECTION ) );
219 if( ! My_Connections )
221 /* Speicher konnte nicht alloziert werden! */
222 Log( LOG_EMERG, "Can't allocate memory! [Conn_Init]" );
226 Log( LOG_DEBUG, "Allocated connection pool for %d items (%ld bytes).", Pool_Size, sizeof( CONNECTION ) * Pool_Size );
229 array_free( &My_Listeners );
231 /* Groesster File-Descriptor fuer select() */
234 /* Connection-Struktur initialisieren */
235 for( i = 0; i < Pool_Size; i++ ) Init_Conn_Struct( i );
237 /* Global write counter */
245 /* Modul abmelden: alle noch offenen Connections
246 * schliessen und freigeben. */
251 Log( LOG_DEBUG, "Shutting down all connections ..." );
254 Conn_ExitListeners();
256 /* Sockets schliessen */
257 for( idx = 0; idx < Pool_Size; idx++ ) {
258 if( My_Connections[idx].sock > NONE ) {
259 Conn_Close( idx, NULL, NGIRCd_SignalRestart ?
260 "Server going down (restarting)":"Server going down", true );
265 free( My_Connections );
266 My_Connections = NULL;
268 io_library_shutdown();
273 ports_initlisteners(array *a, void (*func)(int,short))
275 unsigned int created = 0, len;
279 len = array_length(a, sizeof (UINT16));
280 port = array_start(a);
282 fd = NewListener( *port );
287 if (!io_event_create( fd, IO_WANTREAD, func )) {
288 Log( LOG_ERR, "io_event_create(): Could not add listening fd %d (port %u): %s!",
289 fd, (unsigned int) *port, strerror(errno));
303 Conn_InitListeners( void )
305 /* Initialize ports on which the server should accept connections */
307 unsigned int created;
309 if (!io_library_init(CONNECTION_POOL)) {
310 Log(LOG_EMERG, "Cannot initialize IO routines: %s", strerror(errno));
314 created = ports_initlisteners(&Conf_ListenPorts, cb_listen);
317 } /* Conn_InitListeners */
321 Conn_ExitListeners( void )
323 /* Close down all listening sockets */
327 Rendezvous_UnregisterListeners( );
330 arraylen = array_length(&My_Listeners, sizeof (int));
331 Log( LOG_INFO, "Shutting down all listening sockets (%d total)...", arraylen );
332 fd = array_start(&My_Listeners);
338 Log( LOG_DEBUG, "Listening socket %d closed.", *fd );
342 array_free(&My_Listeners);
343 } /* Conn_ExitListeners */
346 /* return new listening port file descriptor or -1 on failure */
348 NewListener( const UINT16 Port )
350 /* Create new listening socket on specified port */
352 struct sockaddr_in addr;
353 struct in_addr inaddr;
356 char name[CLIENT_ID_LEN], *info;
359 /* Server-"Listen"-Socket initialisieren */
360 memset( &addr, 0, sizeof( addr ));
361 memset( &inaddr, 0, sizeof( inaddr ));
362 addr.sin_family = AF_INET;
363 addr.sin_port = htons( Port );
364 if( Conf_ListenAddress[0] )
366 #ifdef HAVE_INET_ATON
367 if( inet_aton( Conf_ListenAddress, &inaddr ) == 0 )
369 inaddr.s_addr = inet_addr( Conf_ListenAddress );
370 if( inaddr.s_addr == (unsigned)-1 )
373 Log( LOG_CRIT, "Can't listen on %s:%u: can't convert ip address %s!",
374 Conf_ListenAddress, Port, Conf_ListenAddress );
378 else inaddr.s_addr = htonl( INADDR_ANY );
379 addr.sin_addr = inaddr;
381 sock = socket( PF_INET, SOCK_STREAM, 0);
383 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
387 if( ! Init_Socket( sock )) return -1;
389 if( bind( sock, (struct sockaddr *)&addr, (socklen_t)sizeof( addr )) != 0 ) {
390 Log( LOG_CRIT, "Can't bind socket: %s!", strerror( errno ));
395 if( listen( sock, 10 ) != 0 ) {
396 Log( LOG_CRIT, "Can't listen on socket: %s!", strerror( errno ));
401 /* keep fd in list so we can close it when ngircd restarts/shuts down */
402 if (!array_catb( &My_Listeners,(char*) &sock, sizeof(int) )) {
403 Log( LOG_CRIT, "Can't add socket to My_Listeners array: %s!", strerror( errno ));
408 if( Conf_ListenAddress[0]) Log( LOG_INFO, "Now listening on %s:%d (socket %d).", Conf_ListenAddress, Port, sock );
409 else Log( LOG_INFO, "Now listening on 0.0.0.0:%d (socket %d).", Port, sock );
412 /* Get best server description text */
413 if( ! Conf_ServerInfo[0] ) info = Conf_ServerName;
416 /* Use server info string */
418 if( Conf_ServerInfo[0] == '[' )
420 /* Cut off leading hostname part in "[]" */
421 info = strchr( Conf_ServerInfo, ']' );
425 while( *info == ' ' ) info++;
428 if( ! info ) info = Conf_ServerInfo;
431 /* Add port number to description if non-standard */
432 if( Port != 6667 ) snprintf( name, sizeof( name ), "%s (port %u)", info, Port );
433 else strlcpy( name, info, sizeof( name ));
435 /* Register service */
436 Rendezvous_Register( name, MDNS_TYPE, Port );
445 /* "Main Loop.": Loop until a signal (for shutdown or restart) arrives.
446 * Call io_dispatch() to check for read/writeable sockets every second
447 * Wait for status change on pending connections (e.g: when the hostname has been resolved)
448 * check for penalty/timeouts
449 * handle input buffers
452 unsigned int wdatalen;
457 while(( ! NGIRCd_SignalQuit ) && ( ! NGIRCd_SignalRestart )) {
461 Rendezvous_Handler( );
464 /* Should the configuration be reloaded? */
465 if( NGIRCd_SignalRehash ) NGIRCd_Rehash( );
467 /* Check configured servers and established links */
469 Check_Connections( );
473 /* noch volle Lese-Buffer suchen */
474 for( i = 0; i < Pool_Size; i++ ) {
475 if(( My_Connections[i].sock > NONE ) && ( array_bytes(&My_Connections[i].rbuf) > 0 ) &&
476 ( My_Connections[i].delaytime < t ))
478 /* Kann aus dem Buffer noch ein Befehl extrahiert werden? */
479 if (Handle_Buffer( i )) timeout = false;
483 /* noch volle Schreib-Puffer suchen */
484 for( i = 0; i < Pool_Size; i++ ) {
485 if ( My_Connections[i].sock <= NONE )
488 wdatalen = array_bytes(&My_Connections[i].wbuf);
491 if (( wdatalen > 0 ) || ( array_bytes(&My_Connections[i].zip.wbuf)> 0 ))
496 /* Socket der Verbindung in Set aufnehmen */
497 io_event_add( My_Connections[i].sock, IO_WANTWRITE );
501 /* von welchen Sockets koennte gelesen werden? */
502 for (i = 0; i < Pool_Size; i++ ) {
503 if ( My_Connections[i].sock <= NONE )
506 if (Resolve_INPROGRESS(&My_Connections[i].res_stat)) {
507 /* wait for completion of Resolver Sub-Process */
508 io_event_del( My_Connections[i].sock, IO_WANTREAD );
512 if ( Conn_OPTION_ISSET( &My_Connections[i], CONN_ISCONNECTING ))
513 continue; /* wait for completion of connect() */
515 if( My_Connections[i].delaytime > t ) {
516 /* Fuer die Verbindung ist eine "Penalty-Zeit" gesetzt */
517 io_event_del( My_Connections[i].sock, IO_WANTREAD );
520 io_event_add( My_Connections[i].sock, IO_WANTREAD );
523 /* (re-)set timeout - tv_sec/usec are undefined after io_dispatch() returns */
525 tv.tv_sec = timeout ? 1 : 0;
527 /* wait for activity */
528 i = io_dispatch( &tv );
529 if (i == -1 && errno != EINTR ) {
530 Log(LOG_EMERG, "Conn_Handler(): io_dispatch(): %s!", strerror(errno));
531 Log(LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE_NAME);
536 if( NGIRCd_SignalQuit ) Log( LOG_NOTICE|LOG_snotice, "Server going down NOW!" );
537 else if( NGIRCd_SignalRestart ) Log( LOG_NOTICE|LOG_snotice, "Server restarting NOW!" );
542 * Write a text string into the socket of a connection.
543 * This function automatically appends CR+LF to the string and validates that
544 * the result is a valid IRC message (oversized messages are shortened, for
545 * example). Then it calls the Conn_Write() function to do the actual sending.
546 * @param Idx Index fo the connection.
547 * @param Format Format string, see printf().
548 * @return true on success, false otherwise.
552 Conn_WriteStr( CONN_ID Idx, char *Format, ... )
555 Conn_WriteStr( Idx, Format, va_alist )
561 char buffer[COMMAND_LEN];
565 assert( Idx > NONE );
566 assert( Format != NULL );
569 va_start( ap, Format );
573 if (vsnprintf( buffer, COMMAND_LEN - 2, Format, ap ) >= COMMAND_LEN - 2 ) {
575 * The string that should be written to the socket is longer
576 * than the allowed size of COMMAND_LEN bytes (including both
577 * the CR and LF characters). This can be caused by the
578 * IRC_WriteXXX() functions when the prefix of this server had
579 * to be added to an already "quite long" command line which
580 * has been received from a regular IRC client, for example.
582 * We are not allowed to send such "oversized" messages to
583 * other servers and clients, see RFC 2812 2.3 and 2813 3.3
584 * ("these messages SHALL NOT exceed 512 characters in length,
585 * counting all characters including the trailing CR-LF").
587 * So we have a big problem here: we should send more bytes
588 * to the network than we are allowed to and we don't know
589 * the originator (any more). The "old" behaviour of blaming
590 * the receiver ("next hop") is a bad idea (it could be just
591 * an other server only routing the message!), so the only
592 * option left is to shorten the string and to hope that the
593 * result is still somewhat useful ...
597 strcpy (buffer + sizeof(buffer) - strlen(CUT_TXTSUFFIX) - 2 - 1,
603 Log(LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer);
606 strlcat( buffer, "\r\n", sizeof( buffer ));
607 ok = Conn_Write( Idx, buffer, strlen( buffer ));
608 My_Connections[Idx].msg_out++;
612 } /* Conn_WriteStr */
616 Conn_Write( CONN_ID Idx, char *Data, unsigned int Len )
618 /* Daten in Socket schreiben. Bei "fatalen" Fehlern wird
619 * der Client disconnectiert und false geliefert. */
621 assert( Idx > NONE );
622 assert( Data != NULL );
625 /* Ist der entsprechende Socket ueberhaupt noch offen? In einem
626 * "Handler-Durchlauf" kann es passieren, dass dem nicht mehr so
627 * ist, wenn einer von mehreren Conn_Write()'s fehlgeschlagen ist.
628 * In diesem Fall wird hier einfach ein Fehler geliefert. */
629 if( My_Connections[Idx].sock <= NONE )
632 Log( LOG_DEBUG, "Skipped write on closed socket (connection %d).", Idx );
637 /* Pruefen, ob im Schreibpuffer genuegend Platz ist. Ziel ist es,
638 * moeglichts viel im Puffer zu haben und _nicht_ gleich alles auf den
639 * Socket zu schreiben (u.a. wg. Komprimierung). */
640 if( array_bytes(&My_Connections[Idx].wbuf) >= WRITEBUFFER_LEN) {
641 /* Der Puffer ist dummerweise voll. Jetzt versuchen, den Puffer
642 * zu schreiben, wenn das nicht klappt, haben wir ein Problem ... */
643 if( ! Handle_Write( Idx )) return false;
645 /* check again: if our writebuf is twice als large as the initial limit: Kill connection */
646 if( array_bytes(&My_Connections[Idx].wbuf) >= (WRITEBUFFER_LEN*2)) {
647 Log( LOG_NOTICE, "Write buffer overflow (connection %d)!", Idx );
648 Conn_Close( Idx, "Write buffer overflow!", NULL, false );
654 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
655 /* Daten komprimieren und in Puffer kopieren */
656 if( ! Zip_Buffer( Idx, Data, Len )) return false;
661 /* Daten in Puffer kopieren */
662 if (!array_catb( &My_Connections[Idx].wbuf, Data, Len ))
665 My_Connections[Idx].bytes_out += Len;
668 /* Adjust global write counter */
676 Conn_Close( CONN_ID Idx, char *LogMsg, char *FwdMsg, bool InformClient )
678 /* Close connection. Open pipes of asyncronous resolver
679 * sub-processes are closed down. */
685 double in_z_k, out_z_k;
689 assert( Idx > NONE );
691 /* Is this link already shutting down? */
692 if( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ISCLOSING )) {
693 /* Conn_Close() has been called recursively for this link;
694 * probabe reason: Handle_Write() failed -- see below. */
696 Log( LOG_DEBUG, "Recursive request to close connection: %d", Idx );
701 assert( My_Connections[Idx].sock > NONE );
703 /* Mark link as "closing" */
704 Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCLOSING );
706 if( LogMsg ) txt = LogMsg;
708 if( ! txt ) txt = "Reason unknown";
710 Log( LOG_INFO, "Shutting down connection %d (%s) with %s:%d ...", Idx, LogMsg ? LogMsg : FwdMsg, My_Connections[Idx].host, ntohs( My_Connections[Idx].addr.sin_port ));
712 /* Search client, if any */
713 c = Client_GetFromConn( Idx );
715 /* Should the client be informed? */
718 /* Send statistics to client if registered as user: */
719 if ((c != NULL) && (Client_Type(c) == CLIENT_USER)) {
721 ":%s NOTICE %s :%sConnection statistics: client %.1f kb, server %.1f kb.",
722 Client_ID(Client_ThisServer()), Client_ID(c),
724 (double)My_Connections[Idx].bytes_in / 1024,
725 (double)My_Connections[Idx].bytes_out / 1024);
729 /* Send ERROR to client (see RFC!) */
731 Conn_WriteStr(Idx, "ERROR :%s", FwdMsg);
733 Conn_WriteStr(Idx, "ERROR :Closing connection.");
736 /* Try to write out the write buffer. Note: Handle_Write() eventually
737 * removes the CLIENT structure associated with this connection if an
738 * error occurs! So we have to re-check if there is still an valid
739 * CLIENT structure after calling Handle_Write() ...*/
740 (void)Handle_Write( Idx );
742 /* Search client, if any (re-check!) */
743 c = Client_GetFromConn( Idx );
745 /* Shut down socket */
746 if( ! io_close( My_Connections[Idx].sock ))
748 /* Oops, we can't close the socket!? This is ... ugly! */
749 Log( LOG_CRIT, "Error closing connection %d (socket %d) with %s:%d - %s! (ignored)", Idx, My_Connections[Idx].sock, My_Connections[Idx].host, ntohs( My_Connections[Idx].addr.sin_port), strerror( errno ));
752 /* Mark socket as invalid: */
753 My_Connections[Idx].sock = NONE;
755 /* If there is still a client, unregister it now */
756 if( c ) Client_Destroy( c, LogMsg, FwdMsg, true );
758 /* Calculate statistics and log information */
759 in_k = (double)My_Connections[Idx].bytes_in / 1024;
760 out_k = (double)My_Connections[Idx].bytes_out / 1024;
762 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
763 in_z_k = (double)My_Connections[Idx].zip.bytes_in / 1024;
764 out_z_k = (double)My_Connections[Idx].zip.bytes_out / 1024;
765 in_p = (int)(( in_k * 100 ) / in_z_k );
766 out_p = (int)(( out_k * 100 ) / out_z_k );
767 Log( LOG_INFO, "Connection %d with %s:%d closed (in: %.1fk/%.1fk/%d%%, out: %.1fk/%.1fk/%d%%).", Idx, My_Connections[Idx].host, ntohs( My_Connections[Idx].addr.sin_port ), in_k, in_z_k, in_p, out_k, out_z_k, out_p );
772 Log( LOG_INFO, "Connection %d with %s:%d closed (in: %.1fk, out: %.1fk).", Idx, My_Connections[Idx].host, ntohs( My_Connections[Idx].addr.sin_port ), in_k, out_k );
775 /* cancel running resolver */
776 if (Resolve_INPROGRESS(&My_Connections[Idx].res_stat)) {
777 Resolve_Shutdown(&My_Connections[Idx].res_stat);
780 /* Servers: Modify time of next connect attempt? */
781 Conf_UnsetServer( Idx );
784 /* Clean up zlib, if link was compressed */
785 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
786 inflateEnd( &My_Connections[Idx].zip.in );
787 deflateEnd( &My_Connections[Idx].zip.out );
788 array_free(&My_Connections[Idx].zip.rbuf);
789 array_free(&My_Connections[Idx].zip.wbuf);
793 array_free(&My_Connections[Idx].rbuf);
794 array_free(&My_Connections[Idx].wbuf);
795 /* Clean up connection structure (=free it) */
796 Init_Conn_Struct( Idx );
799 Log( LOG_DEBUG, "Shutdown of connection %d completed.", Idx );
805 Conn_SyncServerStruct( void )
807 /* Synchronize server structures (connection IDs):
808 * connections <-> configuration */
814 for( i = 0; i < Pool_Size; i++ )
816 /* Established connection? */
817 if( My_Connections[i].sock <= NONE ) continue;
819 /* Server connection? */
820 client = Client_GetFromConn( i );
821 if(( ! client ) || ( Client_Type( client ) != CLIENT_SERVER )) continue;
823 for( c = 0; c < MAX_SERVERS; c++ )
825 /* Configured server? */
826 if( ! Conf_Server[c].host[0] ) continue;
829 if( strcmp( Conf_Server[c].name, Client_ID( client )) == 0 ) Conf_Server[c].conn_id = i;
832 } /* SyncServerStruct */
836 Handle_Write( CONN_ID Idx )
838 /* Daten aus Schreibpuffer versenden bzw. Connection aufbauen */
841 unsigned int wdatalen;
843 assert( Idx > NONE );
844 if ( My_Connections[Idx].sock < 0 ) {
847 "Handle_Write() on closed socket, connection %d", Idx);
851 assert( My_Connections[Idx].sock > NONE );
854 Log(LOG_DEBUG, "Handle_Write() called for connection %d ...", Idx);
857 wdatalen = array_bytes(&My_Connections[Idx].wbuf );
859 if (wdatalen == 0 && !array_bytes(&My_Connections[Idx].zip.wbuf)) {
860 io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
864 /* write buffer empty, but not compression buffer?
865 * -> flush compression buffer! */
870 io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
875 /* Zip_Flush() may have changed the write buffer ... */
876 wdatalen = array_bytes(&My_Connections[Idx].wbuf);
878 len = write(My_Connections[Idx].sock,
879 array_start(&My_Connections[Idx].wbuf), wdatalen );
882 if (errno == EAGAIN || errno == EINTR)
885 Log(LOG_ERR, "Write error on connection %d (socket %d): %s!",
886 Idx, My_Connections[Idx].sock, strerror(errno));
887 Conn_Close(Idx, "Write error!", NULL, false);
891 /* move any data not yet written to beginning */
892 array_moveleft(&My_Connections[Idx].wbuf, 1, len);
899 New_Connection( int Sock )
901 /* Neue Client-Verbindung von Listen-Socket annehmen und
902 * CLIENT-Struktur anlegen. */
905 struct request_info req;
907 struct sockaddr_in new_addr;
908 int new_sock, new_sock_len;
914 assert( Sock > NONE );
915 /* Connection auf Listen-Socket annehmen */
916 new_sock_len = sizeof( new_addr );
917 new_sock = accept( Sock, (struct sockaddr *)&new_addr, (socklen_t *)&new_sock_len );
920 Log( LOG_CRIT, "Can't accept connection: %s!", strerror( errno ));
925 /* Validate socket using TCP Wrappers */
926 request_init( &req, RQ_DAEMON, PACKAGE_NAME, RQ_FILE, new_sock, RQ_CLIENT_SIN, &new_addr, NULL );
928 if( ! hosts_access( &req ))
931 Log( deny_severity, "Refused connection from %s (by TCP Wrappers)!", inet_ntoa( new_addr.sin_addr ));
932 Simple_Message( new_sock, "ERROR :Connection refused" );
938 /* Socket initialisieren */
939 Init_Socket( new_sock );
941 /* Check IP-based connection limit */
942 cnt = Count_Connections( new_addr );
943 if(( Conf_MaxConnectionsIP > 0 ) && ( cnt >= Conf_MaxConnectionsIP ))
945 /* Access denied, too many connections from this IP address! */
946 Log( LOG_ERR, "Refused connection from %s: too may connections (%ld) from this IP address!", inet_ntoa( new_addr.sin_addr ), cnt);
947 Simple_Message( new_sock, "ERROR :Connection refused, too many connections from your IP address!" );
952 /* Freie Connection-Struktur suchen */
953 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
954 if( idx >= Pool_Size )
956 new_size = Pool_Size + CONNECTION_POOL;
958 /* Im bisherigen Pool wurde keine freie Connection-Struktur mehr gefunden.
959 * Wenn erlaubt und moeglich muss nun der Pool vergroessert werden: */
961 if( Conf_MaxConnections > 0 )
963 /* Es ist ein Limit konfiguriert */
964 if( Pool_Size >= Conf_MaxConnections )
966 /* Mehr Verbindungen duerfen wir leider nicht mehr annehmen ... */
967 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached!", Pool_Size );
968 Simple_Message( new_sock, "ERROR :Connection limit reached" );
972 if( new_size > Conf_MaxConnections ) new_size = Conf_MaxConnections;
974 if( new_size < Pool_Size )
976 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached -- overflow!", Pool_Size );
977 Simple_Message( new_sock, "ERROR :Connection limit reached" );
982 ptr = (POINTER *)realloc( My_Connections, sizeof( CONNECTION ) * new_size );
984 Log( LOG_EMERG, "Can't allocate memory! [New_Connection]" );
985 Simple_Message( new_sock, "ERROR: Internal error" );
991 Log( LOG_DEBUG, "Allocated new connection pool for %ld items (%ld bytes). [realloc()]", new_size, sizeof( CONNECTION ) * new_size );
994 /* Adjust pointer to new block */
995 My_Connections = (CONNECTION *)ptr;
997 /* Initialize new items */
998 for( idx = Pool_Size; idx < new_size; idx++ ) Init_Conn_Struct( idx );
1001 /* Adjust new pool size */
1002 Pool_Size = new_size;
1005 /* Client-Struktur initialisieren */
1006 c = Client_NewLocal( idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWN, false );
1008 Log( LOG_ALERT, "Can't accept connection: can't create client structure!" );
1009 Simple_Message( new_sock, "ERROR :Internal error" );
1014 /* Verbindung registrieren */
1015 Init_Conn_Struct( idx );
1016 My_Connections[idx].sock = new_sock;
1017 My_Connections[idx].addr = new_addr;
1019 /* Neuen Socket registrieren */
1020 if (!io_event_create( new_sock, IO_WANTREAD, cb_clientserver)) {
1021 Simple_Message( new_sock, "ERROR :Internal error" );
1022 Conn_Close( idx, "io_event_create() failed", NULL, false );
1026 Log( LOG_INFO, "Accepted connection %d from %s:%d on socket %d.", idx, inet_ntoa( new_addr.sin_addr ), ntohs( new_addr.sin_port), Sock );
1028 /* Hostnamen ermitteln */
1029 strlcpy( My_Connections[idx].host, inet_ntoa( new_addr.sin_addr ), sizeof( My_Connections[idx].host ));
1030 Client_SetHostname( c, My_Connections[idx].host );
1032 Resolve_Addr(&My_Connections[idx].res_stat, &new_addr,
1033 My_Connections[idx].sock, cb_Read_Resolver_Result);
1035 /* Penalty-Zeit setzen */
1036 Conn_SetPenalty( idx, 4 );
1038 } /* New_Connection */
1042 Socket2Index( int Sock )
1044 /* zum Socket passende Connection suchen */
1048 assert( Sock > NONE );
1050 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == Sock ) break;
1052 if( idx >= Pool_Size )
1054 /* die Connection wurde vermutlich (wegen eines
1055 * Fehlers) bereits wieder abgebaut ... */
1057 Log( LOG_DEBUG, "Socket2Index: can't get connection for socket %d!", Sock );
1062 } /* Socket2Index */
1066 Read_Request( CONN_ID Idx )
1068 /* Daten von Socket einlesen und entsprechend behandeln.
1069 * Tritt ein Fehler auf, so wird der Socket geschlossen. */
1075 assert( Idx > NONE );
1076 assert( My_Connections[Idx].sock > NONE );
1079 if (( array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN ) ||
1080 ( array_bytes(&My_Connections[Idx].zip.rbuf) >= ZREADBUFFER_LEN ))
1082 if ( array_bytes(&My_Connections[Idx].rbuf) >= READBUFFER_LEN )
1085 /* Der Lesepuffer ist voll */
1086 Log( LOG_ERR, "Receive buffer overflow (connection %d): %d bytes!", Idx,
1087 array_bytes(&My_Connections[Idx].rbuf));
1088 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1092 len = read( My_Connections[Idx].sock, readbuf, sizeof readbuf -1 );
1094 Log( LOG_INFO, "%s:%d (%s) is closing the connection ...",
1095 My_Connections[Idx].host, ntohs( My_Connections[Idx].addr.sin_port),
1096 inet_ntoa( My_Connections[Idx].addr.sin_addr ));
1097 Conn_Close( Idx, "Socket closed!", "Client closed connection", false );
1102 if( errno == EAGAIN ) return;
1103 Log( LOG_ERR, "Read error on connection %d (socket %d): %s!", Idx,
1104 My_Connections[Idx].sock, strerror( errno ));
1105 Conn_Close( Idx, "Read error!", "Client closed connection", false );
1109 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
1110 if (!array_catb( &My_Connections[Idx].zip.rbuf, readbuf, len)) {
1111 Log( LOG_ERR, "Could not append recieved data to zip input buffer (connn %d): %d bytes!", Idx, len );
1112 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1119 if (!array_cats( &My_Connections[Idx].rbuf, readbuf )) {
1120 Log( LOG_ERR, "Could not append recieved data to input buffer (connn %d): %d bytes!", Idx, len );
1121 Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
1125 /* Update connection statistics */
1126 My_Connections[Idx].bytes_in += len;
1128 /* Update timestamp of last data received if this connection is
1129 * registered as a user, server or service connection. Don't update
1130 * otherwise, so users have at least Conf_PongTimeout seconds time to
1131 * register with the IRC server -- see Check_Connections(). */
1132 c = Client_GetFromConn(Idx);
1133 if (c && (Client_Type(c) == CLIENT_USER
1134 || Client_Type(c) == CLIENT_SERVER
1135 || Client_Type(c) == CLIENT_SERVICE))
1136 My_Connections[Idx].lastdata = time(NULL);
1138 /* Look at the data in the (read-) buffer of this connection */
1140 } /* Read_Request */
1144 Handle_Buffer( CONN_ID Idx )
1146 /* Handle Data in Connections Read-Buffer.
1147 * Return true if a reuqest was handled, false otherwise (also returned on errors). */
1161 if( My_Connections[Idx].delaytime > time( NULL )) return result;
1163 /* unpack compressed data */
1164 if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP ))
1165 if( ! Unzip_Buffer( Idx )) return false;
1168 if (0 == array_bytes(&My_Connections[Idx].rbuf))
1171 if (!array_cat0_temporary(&My_Connections[Idx].rbuf)) /* make sure buf is NULL terminated */
1174 /* A Complete Request end with CR+LF, see RFC 2812. */
1175 ptr = strstr( array_start(&My_Connections[Idx].rbuf), "\r\n" );
1177 if( ptr ) delta = 2; /* complete request */
1180 /* Check for non-RFC-compliant request (only CR or LF)? Unfortunately,
1181 * there are quite a few clients that do this (incl. "mIRC" :-( */
1182 ptr1 = strchr( array_start(&My_Connections[Idx].rbuf), '\r' );
1183 ptr2 = strchr( array_start(&My_Connections[Idx].rbuf), '\n' );
1185 if( ptr1 && ptr2 ) ptr = ptr1 > ptr2 ? ptr2 : ptr1;
1186 else if( ptr1 ) ptr = ptr1;
1187 else if( ptr2 ) ptr = ptr2;
1194 /* End of request found */
1197 len = ( ptr - (char*) array_start(&My_Connections[Idx].rbuf)) + delta;
1199 if( len < 0 || len > ( COMMAND_LEN - 1 )) {
1200 /* Request must not exceed 512 chars (incl. CR+LF!), see
1201 * RFC 2812. Disconnect Client if this happens. */
1202 Log( LOG_ERR, "Request too long (connection %d): %d bytes (max. %d expected)!",
1203 Idx, array_bytes(&My_Connections[Idx].rbuf), COMMAND_LEN - 1 );
1204 Conn_Close( Idx, NULL, "Request too long", true );
1208 if (len <= 2) { /* request was empty (only '\r\n') */
1209 array_moveleft(&My_Connections[Idx].rbuf, 1, delta); /* delta is either 1 or 2 */
1213 /* remember if stream is already compressed */
1214 old_z = My_Connections[Idx].options & CONN_ZIP;
1217 My_Connections[Idx].msg_in++;
1218 if (!Parse_Request(Idx, (char*)array_start(&My_Connections[Idx].rbuf) ))
1223 array_moveleft(&My_Connections[Idx].rbuf, 1, len);
1226 "Connection %d: %d bytes left in read buffer.",
1227 Idx, array_bytes(&My_Connections[Idx].rbuf));
1230 if(( ! old_z ) && ( My_Connections[Idx].options & CONN_ZIP ) &&
1231 ( array_bytes(&My_Connections[Idx].rbuf) > 0 ))
1233 /* The last Command activated Socket-Compression.
1234 * Data that was read after that needs to be copied to Unzip-buf
1235 * for decompression */
1236 if( array_bytes(&My_Connections[Idx].rbuf)> ZREADBUFFER_LEN ) {
1237 Log( LOG_ALERT, "Connection %d: No space left in unzip buf (need %u bytes)!",
1238 Idx, array_bytes(&My_Connections[Idx].rbuf ));
1241 if (!array_copy( &My_Connections[Idx].zip.rbuf, &My_Connections[Idx].rbuf ))
1244 array_trunc(&My_Connections[Idx].rbuf);
1246 Log( LOG_DEBUG, "Moved already received data (%u bytes) to uncompression buffer.",
1247 array_bytes(&My_Connections[Idx].zip.rbuf));
1254 } /* Handle_Buffer */
1258 Check_Connections( void )
1260 /* check if connections are alive. if not, play PING-PONG first.
1261 * if this doesn't help either, disconnect client. */
1265 for( i = 0; i < Pool_Size; i++ ) {
1266 if (My_Connections[i].sock < 0)
1269 c = Client_GetFromConn( i );
1270 if( c && (( Client_Type( c ) == CLIENT_USER ) || ( Client_Type( c ) == CLIENT_SERVER ) || ( Client_Type( c ) == CLIENT_SERVICE )))
1272 /* connected User, Server or Service */
1273 if( My_Connections[i].lastping > My_Connections[i].lastdata ) {
1274 /* we already sent a ping */
1275 if( My_Connections[i].lastping < time( NULL ) - Conf_PongTimeout ) {
1278 Log( LOG_DEBUG, "Connection %d: Ping timeout: %d seconds.", i, Conf_PongTimeout );
1280 Conn_Close( i, NULL, "Ping timeout", true );
1283 else if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout ) {
1284 /* we need to sent a PING */
1286 Log( LOG_DEBUG, "Connection %d: sending PING ...", i );
1288 My_Connections[i].lastping = time( NULL );
1289 Conn_WriteStr( i, "PING :%s", Client_ID( Client_ThisServer( )));
1294 /* The connection is not fully established yet, so
1295 * we don't do the PING-PONG game here but instead
1296 * disconnect the client after "a short time" if it's
1297 * still not registered. */
1299 if (My_Connections[i].lastdata <
1300 time(NULL) - Conf_PongTimeout) {
1303 "Unregistered connection %d timed out ...",
1306 Conn_Close(i, NULL, "Timeout", false);
1310 } /* Check_Connections */
1314 Check_Servers( void )
1316 /* Check if we can establish further server links */
1322 /* Search all connections, are there results from the resolver? */
1323 for( idx = 0; idx < Pool_Size; idx++ ) {
1324 if( My_Connections[idx].sock != SERVER_WAIT ) continue;
1327 if (Resolve_SUCCESS(&My_Connections[idx].res_stat))
1328 New_Server(Conf_GetServer( idx ), idx);
1331 /* Check all configured servers */
1332 for( i = 0; i < MAX_SERVERS; i++ ) {
1333 /* Valid outgoing server which isn't already connected or disabled? */
1334 if(( ! Conf_Server[i].host[0] ) || ( ! Conf_Server[i].port > 0 ) ||
1335 ( Conf_Server[i].conn_id > NONE ) || ( Conf_Server[i].flags & CONF_SFLAG_DISABLED ))
1338 /* Is there already a connection in this group? */
1339 if( Conf_Server[i].group > NONE ) {
1340 for (n = 0; n < MAX_SERVERS; n++) {
1341 if (n == i) continue;
1342 if ((Conf_Server[n].conn_id > NONE) &&
1343 (Conf_Server[n].group == Conf_Server[i].group))
1346 if (n < MAX_SERVERS) continue;
1349 /* Check last connect attempt? */
1350 time_now = time(NULL);
1351 if( Conf_Server[i].lasttry > (time_now - Conf_ConnectRetry))
1354 /* Okay, try to connect now */
1355 Conf_Server[i].lasttry = time_now;
1357 /* Search free connection structure */
1358 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
1359 if (idx >= Pool_Size) {
1360 Log( LOG_ALERT, "Can't establist server connection: connection limit reached (%d)!",
1365 Log( LOG_DEBUG, "Preparing connection %d for \"%s\" ...", idx, Conf_Server[i].host );
1368 Init_Conn_Struct( idx );
1369 My_Connections[idx].sock = SERVER_WAIT;
1370 Conf_Server[i].conn_id = idx;
1372 /* Resolve Hostname. If this fails, try to use it as an IP address */
1373 strlcpy( Conf_Server[i].ip, Conf_Server[i].host, sizeof( Conf_Server[i].ip ));
1374 strlcpy( My_Connections[idx].host, Conf_Server[i].host, sizeof( My_Connections[idx].host ));
1376 assert(Resolve_Getfd(&My_Connections[idx].res_stat) < 0);
1378 Resolve_Name(&My_Connections[idx].res_stat, Conf_Server[i].host, cb_Read_Resolver_Result);
1380 } /* Check_Servers */
1384 New_Server( int Server, CONN_ID Idx )
1386 /* Establish new server link */
1388 struct sockaddr_in new_addr;
1389 struct in_addr inaddr;
1393 assert( Server > NONE );
1394 assert( Idx > NONE );
1396 Log( LOG_INFO, "Establishing connection to \"%s\", %s, port %d ... ", Conf_Server[Server].host,
1397 Conf_Server[Server].ip, Conf_Server[Server].port );
1399 #ifdef HAVE_INET_ATON
1400 if( inet_aton( Conf_Server[Server].ip, &inaddr ) == 0 )
1402 memset( &inaddr, 0, sizeof( inaddr ));
1403 inaddr.s_addr = inet_addr( Conf_Server[Server].ip );
1404 if( inaddr.s_addr == (unsigned)-1 )
1407 /* Can't convert IP address */
1408 Log( LOG_ERR, "Can't connect to \"%s\" (connection %d): can't convert ip address %s!", Conf_Server[Server].host, Idx, Conf_Server[Server].ip );
1412 memset( &new_addr, 0, sizeof( new_addr ));
1413 new_addr.sin_family = AF_INET;
1414 new_addr.sin_addr = inaddr;
1415 new_addr.sin_port = htons( Conf_Server[Server].port );
1417 new_sock = socket( PF_INET, SOCK_STREAM, 0 );
1418 if ( new_sock < 0 ) {
1419 /* Can't create socket */
1420 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
1424 if( ! Init_Socket( new_sock )) return;
1426 res = connect( new_sock, (struct sockaddr *)&new_addr, sizeof( new_addr ));
1427 if(( res != 0 ) && ( errno != EINPROGRESS )) {
1428 /* Can't connect socket */
1429 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1434 /* Client-Struktur initialisieren */
1435 c = Client_NewLocal( Idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWNSERVER, false );
1437 /* Can't create new client structure */
1438 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1443 Client_SetIntroducer( c, c );
1444 Client_SetToken( c, TOKEN_OUTBOUND );
1446 /* Register connection */
1447 My_Connections[Idx].sock = new_sock;
1448 My_Connections[Idx].addr = new_addr;
1449 strlcpy( My_Connections[Idx].host, Conf_Server[Server].host, sizeof( My_Connections[Idx].host ));
1451 /* Register new socket */
1452 if (!io_event_create( new_sock, IO_WANTWRITE, cb_connserver)) {
1453 Log( LOG_ALERT, "io_event_create(): could not add fd %d", strerror(errno));
1454 Conn_Close( Idx, "io_event_create() failed", NULL, false );
1459 Log( LOG_DEBUG, "Registered new connection %d on socket %d.", Idx, My_Connections[Idx].sock );
1461 Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCONNECTING );
1464 Init_Conn_Struct( Idx );
1465 Conf_Server[Server].conn_id = NONE;
1470 Init_Conn_Struct( CONN_ID Idx )
1472 time_t now = time( NULL );
1473 /* Connection-Struktur initialisieren */
1475 memset( &My_Connections[Idx], 0, sizeof ( CONNECTION ));
1476 My_Connections[Idx].sock = NONE;
1477 My_Connections[Idx].lastdata = now;
1478 My_Connections[Idx].lastprivmsg = now;
1479 Resolve_Init(&My_Connections[Idx].res_stat);
1480 } /* Init_Conn_Struct */
1484 Init_Socket( int Sock )
1486 /* Initialize socket (set options) */
1490 if (!io_setnonblock(Sock)) {
1491 Log( LOG_CRIT, "Can't enable non-blocking mode for socket: %s!", strerror( errno ));
1496 /* Don't block this port after socket shutdown */
1498 if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &value, (socklen_t)sizeof( value )) != 0 )
1500 Log( LOG_ERR, "Can't set socket option SO_REUSEADDR: %s!", strerror( errno ));
1501 /* ignore this error */
1504 /* Set type of service (TOS) */
1505 #if defined(IP_TOS) && defined(IPTOS_LOWDELAY)
1506 value = IPTOS_LOWDELAY;
1508 Log( LOG_DEBUG, "Setting option IP_TOS on socket %d to IPTOS_LOWDELAY (%d).", Sock, value );
1510 if( setsockopt( Sock, SOL_IP, IP_TOS, &value, (socklen_t)sizeof( value )) != 0 )
1512 Log( LOG_ERR, "Can't set socket option IP_TOS: %s!", strerror( errno ));
1513 /* ignore this error */
1522 cb_Read_Resolver_Result( int r_fd, UNUSED short events )
1524 /* Read result of resolver sub-process from pipe and update the
1525 * apropriate connection/client structure(s): hostname and/or
1526 * IDENT user name.*/
1533 char readbuf[HOST_LEN + 2 + CLIENT_USER_LEN];
1535 char readbuf[HOST_LEN + 1];
1539 Log( LOG_DEBUG, "Resolver: Got callback on fd %d, events %d", r_fd, events );
1542 /* Search associated connection ... */
1543 for( i = 0; i < Pool_Size; i++ ) {
1544 if(( My_Connections[i].sock != NONE )
1545 && ( Resolve_Getfd(&My_Connections[i].res_stat) == r_fd ))
1548 if( i >= Pool_Size ) {
1549 /* Ops, none found? Probably the connection has already
1550 * been closed!? We'll ignore that ... */
1553 Log( LOG_DEBUG, "Resolver: Got callback for unknown connection!?" );
1558 /* Read result from pipe */
1559 len = Resolve_Read(&My_Connections[i].res_stat, readbuf, sizeof readbuf -1);
1563 readbuf[len] = '\0';
1564 identptr = strchr(readbuf, '\n');
1565 assert(identptr != NULL);
1567 Log( LOG_CRIT, "Resolver: Got malformed result!");
1573 Log( LOG_DEBUG, "Got result from resolver: \"%s\" (%u bytes read).", readbuf, len);
1575 /* Okay, we got a complete result: this is a host name for outgoing
1576 * connections and a host name and IDENT user name (if enabled) for
1577 * incoming connections.*/
1578 if( My_Connections[i].sock > NONE ) {
1579 /* Incoming connection. Search client ... */
1580 c = Client_GetFromConn( i );
1581 assert( c != NULL );
1583 /* Only update client information of unregistered clients */
1584 if( Client_Type( c ) == CLIENT_UNKNOWN ) {
1585 strlcpy(My_Connections[i].host, readbuf, sizeof( My_Connections[i].host));
1586 Client_SetHostname( c, readbuf);
1590 Log( LOG_INFO, "IDENT lookup for connection %ld: \"%s\".", i, identptr);
1591 Client_SetUser( c, identptr, true );
1593 Log( LOG_INFO, "IDENT lookup for connection %ld: no result.", i );
1598 else Log( LOG_DEBUG, "Resolver: discarding result for already registered connection %d.", i );
1601 /* Outgoing connection (server link): set the IP address
1602 * so that we can connect to it in the main loop. */
1604 /* Search server ... */
1605 n = Conf_GetServer( i );
1608 strlcpy( Conf_Server[n].ip, readbuf, sizeof( Conf_Server[n].ip ));
1611 /* Reset penalty time */
1612 Conn_ResetPenalty( i );
1615 if (My_Connections[i].sock == SERVER_WAIT) {
1616 n = Conf_GetServer( i );
1619 Conf_Server[n].conn_id = NONE;
1620 Init_Conn_Struct(i);
1623 } /* cb_Read_Resolver_Result */
1627 Simple_Message( int Sock, char *Msg )
1629 char buf[COMMAND_LEN];
1630 /* Write "simple" message to socket, without using compression
1631 * or even the connection write buffers. Used e.g. for error
1632 * messages by New_Connection(). */
1633 assert( Sock > NONE );
1634 assert( Msg != NULL );
1636 strlcpy( buf, Msg, sizeof buf - 2);
1637 strlcat( buf, "\r\n", sizeof buf);
1638 (void)write( Sock, buf, strlen( buf ) );
1639 } /* Simple_Error */
1643 Count_Connections( struct sockaddr_in addr_in )
1648 for( i = 0; i < Pool_Size; i++ ) {
1649 if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].addr.sin_addr.s_addr == addr_in.sin_addr.s_addr )) cnt++;
1652 } /* Count_Connections */