#include "portab.h"
#include "io.h"
-static char UNUSED id[] = "$Id: conn.c,v 1.190 2006/02/16 19:21:57 fw Exp $";
+static char UNUSED id[] = "$Id: conn.c,v 1.203 2007/02/21 11:06:06 fw Exp $";
#include "imp.h"
#include <assert.h>
static void Init_Conn_Struct PARAMS(( CONN_ID Idx ));
static bool Init_Socket PARAMS(( int Sock ));
static void New_Server PARAMS(( int Server ));
-static void Simple_Message PARAMS(( int Sock, char *Msg ));
+static void Simple_Message PARAMS(( int Sock, const char *Msg ));
static int Count_Connections PARAMS(( struct sockaddr_in addr ));
static int NewListener PARAMS(( const UINT16 Port ));
{
int res, err;
socklen_t sock_len;
- CLIENT *c;
CONN_ID idx = Socket2Index( sock );
if (idx <= NONE) {
LogDebug("cb_connserver wants to write on unknown socket?!");
Conf_Server[Conf_GetServer(idx)].port,
idx, strerror(err));
- /* Clean up the CLIENT structure (to avoid silly log
- * messages) and call Conn_Close() to do the rest. */
- c = Client_GetFromConn(idx);
- if (c)
- Client_DestroyNow(c);
-
- Conn_Close(idx, "Can't connect!", NULL, false);
-
+ Conn_Close(idx, "Can't connect!", NULL, false);
return;
}
if( Pool_Size > Conf_MaxConnections ) Pool_Size = Conf_MaxConnections;
}
- if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), Pool_Size)) {
+ if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)Pool_Size)) {
Log( LOG_EMERG, "Can't allocate memory! [Conn_Init]" );
exit( 1 );
}
- /* XXX: My_Connetions/Pool_Size are needed by other parts of the code; remove them */
+ /* FIXME: My_Connetions/Pool_Size is needed by other parts of the
+ * code; remove them! */
My_Connections = (CONNECTION*) array_start(&My_ConnArray);
LogDebug("Allocated connection pool for %d items (%ld bytes).",
} /* Conn_Exit */
-static unsigned int
+static int
ports_initlisteners(array *a, void (*func)(int,short))
{
- unsigned int created = 0, len;
+ int created = 0;
+ size_t len;
int fd;
UINT16 *port;
{
/* Initialize ports on which the server should accept connections */
- unsigned int created;
+ int created;
if (!io_library_init(CONNECTION_POOL)) {
Log(LOG_EMERG, "Cannot initialize IO routines: %s", strerror(errno));
Log( LOG_INFO, "Shutting down all listening sockets (%d total)...", arraylen );
fd = array_start(&My_Listeners);
while(arraylen--) {
- assert(fd);
+ assert(fd != NULL);
assert(*fd >= 0);
io_close(*fd);
LogDebug("Listening socket %d closed.", *fd );
/* Server-"Listen"-Socket initialisieren */
memset( &addr, 0, sizeof( addr ));
memset( &inaddr, 0, sizeof( inaddr ));
- addr.sin_family = AF_INET;
+ addr.sin_family = (sa_family_t)AF_INET;
addr.sin_port = htons( Port );
if( Conf_ListenAddress[0] )
{
if( ! Init_Socket( sock )) return -1;
- if( bind( sock, (struct sockaddr *)&addr, (socklen_t)sizeof( addr )) != 0 ) {
- Log( LOG_CRIT, "Can't bind socket: %s!", strerror( errno ));
+ if (bind(sock, (struct sockaddr *)&addr, (socklen_t)sizeof(addr)) != 0) {
+ Log( LOG_CRIT, "Can't bind socket (port %d) : %s!", Port, strerror( errno ));
close( sock );
return -1;
}
}
/* Add port number to description if non-standard */
- if( Port != 6667 ) snprintf( name, sizeof( name ), "%s (port %u)", info, Port );
- else strlcpy( name, info, sizeof( name ));
+ if (Port != 6667)
+ snprintf(name, sizeof name, "%s (port %u)", info,
+ (unsigned int)Port);
+ else
+ strlcpy(name, info, sizeof name);
/* Register service */
Rendezvous_Register( name, MDNS_TYPE, Port );
if ( My_Connections[i].sock <= NONE )
continue;
- wdatalen = array_bytes(&My_Connections[i].wbuf);
+ wdatalen = (unsigned int)array_bytes(&My_Connections[i].wbuf);
#ifdef ZLIB
if (( wdatalen > 0 ) || ( array_bytes(&My_Connections[i].zip.wbuf)> 0 ))
#endif
{
char buffer[COMMAND_LEN];
+ size_t len;
bool ok;
va_list ap;
Log(LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer);
#endif
- strlcat( buffer, "\r\n", sizeof( buffer ));
- ok = Conn_Write( Idx, buffer, strlen( buffer ));
+ len = strlcat( buffer, "\r\n", sizeof( buffer ));
+ ok = Conn_Write(Idx, buffer, len);
My_Connections[Idx].msg_out++;
va_end( ap );
GLOBAL bool
-Conn_Write( CONN_ID Idx, char *Data, unsigned int Len )
+Conn_Write( CONN_ID Idx, char *Data, size_t Len )
{
/* Daten in Socket schreiben. Bei "fatalen" Fehlern wird
* der Client disconnectiert und false geliefert. */
/* Mark link as "closing" */
Conn_OPTION_ADD( &My_Connections[Idx], CONN_ISCLOSING );
- if( LogMsg ) txt = LogMsg;
- else txt = FwdMsg;
- if( ! txt ) txt = "Reason unknown";
+ if (LogMsg)
+ txt = LogMsg;
+ else
+ txt = FwdMsg;
+ if (! txt)
+ txt = "Reason unknown";
- 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 ));
+ 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));
/* Search client, if any */
- c = Client_GetFromConn( Idx );
+ c = Conn_GetClient( Idx );
/* Should the client be informed? */
if (InformClient) {
(void)Handle_Write( Idx );
/* Search client, if any (re-check!) */
- c = Client_GetFromConn( Idx );
+ c = Conn_GetClient( Idx );
/* Shut down socket */
- if( ! io_close( My_Connections[Idx].sock ))
- {
+ if (! io_close(My_Connections[Idx].sock)) {
/* Oops, we can't close the socket!? This is ... ugly! */
- 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 ));
+ 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));
}
/* Mark socket as invalid: */
My_Connections[Idx].sock = NONE;
/* If there is still a client, unregister it now */
- if( c ) Client_Destroy( c, LogMsg, FwdMsg, true );
+ if (c)
+ Client_Destroy(c, LogMsg, FwdMsg, true);
/* Calculate statistics and log information */
in_k = (double)My_Connections[Idx].bytes_in / 1024;
out_k = (double)My_Connections[Idx].bytes_out / 1024;
#ifdef ZLIB
- if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
+ if (Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP)) {
in_z_k = (double)My_Connections[Idx].zip.bytes_in / 1024;
out_z_k = (double)My_Connections[Idx].zip.bytes_out / 1024;
+ /* Make sure that no division by zero can occur during
+ * the calculation of in_p and out_p: in_z_k and out_z_k
+ * are non-zero, that's guaranteed by the protocol until
+ * compression can be enabled. */
+ if (! in_z_k)
+ in_z_k = in_k;
+ if (! out_z_k)
+ out_z_k = out_k;
in_p = (int)(( in_k * 100 ) / in_z_k );
out_p = (int)(( out_k * 100 ) / out_z_k );
- 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 );
+ 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);
}
else
#endif
{
- 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 );
+ 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);
}
/* cancel running resolver */
- if (Resolve_INPROGRESS(&My_Connections[Idx].res_stat)) {
+ if (Resolve_INPROGRESS(&My_Connections[Idx].res_stat))
Resolve_Shutdown(&My_Connections[Idx].res_stat);
- }
/* Servers: Modify time of next connect attempt? */
Conf_UnsetServer( Idx );
array_free(&My_Connections[Idx].rbuf);
array_free(&My_Connections[Idx].wbuf);
+
/* Clean up connection structure (=free it) */
Init_Conn_Struct( Idx );
continue;
/* Server connection? */
- client = Client_GetFromConn( i );
+ client = Conn_GetClient( i );
if(( ! client ) || ( Client_Type( client ) != CLIENT_SERVER )) continue;
for( c = 0; c < MAX_SERVERS; c++ )
} /* SyncServerStruct */
+/**
+ * Send out data of write buffer; connect new sockets.
+ */
static bool
Handle_Write( CONN_ID Idx )
{
- /* Daten aus Schreibpuffer versenden bzw. Connection aufbauen */
-
- int len;
- unsigned int wdatalen;
+ ssize_t len;
+ size_t wdatalen;
assert( Idx > NONE );
if ( My_Connections[Idx].sock < 0 ) {
}
assert( My_Connections[Idx].sock > NONE );
- LogDebug("Handle_Write() called for connection %d ...", Idx);
-
wdatalen = array_bytes(&My_Connections[Idx].wbuf );
+
#ifdef ZLIB
if (wdatalen == 0 && !array_bytes(&My_Connections[Idx].zip.wbuf)) {
io_event_del(My_Connections[Idx].sock, IO_WANTWRITE );
}
#endif
- /* Zip_Flush() may have changed the write buffer ... */
+ /* Zip_Flush() may have changed the write buffer ... */
wdatalen = array_bytes(&My_Connections[Idx].wbuf);
+ LogDebug
+ ("Handle_Write() called for connection %d, %ld bytes pending ...",
+ Idx, wdatalen);
len = write(My_Connections[Idx].sock,
array_start(&My_Connections[Idx].wbuf), wdatalen );
}
/* move any data not yet written to beginning */
- array_moveleft(&My_Connections[Idx].wbuf, 1, len);
+ array_moveleft(&My_Connections[Idx].wbuf, 1, (size_t)len);
return true;
} /* Handle_Write */
assert( Sock > NONE );
/* Connection auf Listen-Socket annehmen */
- new_sock_len = sizeof( new_addr );
- new_sock = accept( Sock, (struct sockaddr *)&new_addr, (socklen_t *)&new_sock_len );
- if( new_sock < 0 )
- {
- Log( LOG_CRIT, "Can't accept connection: %s!", strerror( errno ));
+ new_sock_len = (int)sizeof new_addr;
+ new_sock = accept(Sock, (struct sockaddr *)&new_addr,
+ (socklen_t *)&new_sock_len);
+ if (new_sock < 0) {
+ Log(LOG_CRIT, "Can't accept connection: %s!", strerror(errno));
return -1;
}
return -1;
}
- if (!array_alloc(&My_ConnArray, sizeof( CONNECTION ), new_sock)) {
+ if (!array_alloc(&My_ConnArray, sizeof(CONNECTION),
+ (size_t)new_sock)) {
Log( LOG_EMERG, "Can't allocate memory! [New_Connection]" );
Simple_Message( new_sock, "ERROR: Internal error" );
close( new_sock );
/* Adjust pointer to new block */
My_Connections = array_start(&My_ConnArray);
- Pool_Size = new_Pool_Size;
+ while (Pool_Size < new_Pool_Size)
+ Init_Conn_Struct(Pool_Size++);
+ }
+
+ /* register callback */
+ if (!io_event_create( new_sock, IO_WANTREAD, cb_clientserver)) {
+ Log(LOG_ALERT, "Can't accept connection: io_event_create failed!");
+ Simple_Message(new_sock, "ERROR :Internal error");
+ close(new_sock);
+ return -1;
}
c = Client_NewLocal( new_sock, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWN, false );
if( ! c ) {
- Log( LOG_ALERT, "Can't accept connection: can't create client structure!" );
- Simple_Message( new_sock, "ERROR :Internal error" );
- close( new_sock );
+ Log(LOG_ALERT, "Can't accept connection: can't create client structure!");
+ Simple_Message(new_sock, "ERROR :Internal error");
+ io_close(new_sock);
return -1;
}
Init_Conn_Struct( new_sock );
My_Connections[new_sock].sock = new_sock;
My_Connections[new_sock].addr = new_addr;
-
- /* register callback */
- if (!io_event_create( new_sock, IO_WANTREAD, cb_clientserver)) {
- Simple_Message( new_sock, "ERROR :Internal error" );
- Conn_Close( new_sock, "io_event_create() failed", NULL, false );
- return -1;
- }
+ My_Connections[new_sock].client = c;
Log( LOG_INFO, "Accepted connection %d from %s:%d on socket %d.", new_sock,
inet_ntoa( new_addr.sin_addr ), ntohs( new_addr.sin_port), Sock );
/* Daten von Socket einlesen und entsprechend behandeln.
* Tritt ein Fehler auf, so wird der Socket geschlossen. */
- int len;
+ ssize_t len;
char readbuf[1024];
CLIENT *c;
return;
}
#ifdef ZLIB
- if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP )) {
- if (!array_catb( &My_Connections[Idx].zip.rbuf, readbuf, len)) {
- Log( LOG_ERR, "Could not append recieved data to zip input buffer (connn %d): %d bytes!", Idx, len );
- Conn_Close( Idx, "Receive buffer overflow!", NULL, false );
+ if (Conn_OPTION_ISSET(&My_Connections[Idx], CONN_ZIP)) {
+ if (!array_catb(&My_Connections[Idx].zip.rbuf, readbuf,
+ (size_t) len)) {
+ Log(LOG_ERR,
+ "Could not append recieved data to zip input buffer (connn %d): %d bytes!",
+ Idx, len);
+ Conn_Close(Idx, "Receive buffer overflow!", NULL,
+ false);
return;
}
} else
/* Update timestamp of last data received if this connection is
* registered as a user, server or service connection. Don't update
* otherwise, so users have at least Conf_PongTimeout seconds time to
- * register with the IRC server -- see Check_Connections(). */
- c = Client_GetFromConn(Idx);
+ * register with the IRC server -- see Check_Connections().
+ * Set "lastping", too, so we can handle time shifts backwards ... */
+ c = Conn_GetClient(Idx);
if (c && (Client_Type(c) == CLIENT_USER
|| Client_Type(c) == CLIENT_SERVER
- || Client_Type(c) == CLIENT_SERVICE))
+ || Client_Type(c) == CLIENT_SERVICE)) {
My_Connections[Idx].lastdata = time(NULL);
+ My_Connections[Idx].lastping = My_Connections[Idx].lastdata;
+ }
/* Look at the data in the (read-) buffer of this connection */
Handle_Buffer(Idx);
char *ptr1, *ptr2;
#endif
char *ptr;
- int len, delta;
+ size_t len, delta;
bool result;
+ time_t starttime;
#ifdef ZLIB
bool old_z;
#endif
+ starttime = time(NULL);
result = false;
for (;;) {
/* Check penalty */
- if( My_Connections[Idx].delaytime > time( NULL )) return result;
+ if( My_Connections[Idx].delaytime > starttime) return result;
#ifdef ZLIB
/* unpack compressed data */
if ( Conn_OPTION_ISSET( &My_Connections[Idx], CONN_ZIP ))
len = ( ptr - (char*) array_start(&My_Connections[Idx].rbuf)) + delta;
- if( len < 0 || len > ( COMMAND_LEN - 1 )) {
+ if( len > ( COMMAND_LEN - 1 )) {
/* Request must not exceed 512 chars (incl. CR+LF!), see
* RFC 2812. Disconnect Client if this happens. */
Log( LOG_ERR, "Request too long (connection %d): %d bytes (max. %d expected)!",
static void
-Check_Connections( void )
+Check_Connections(void)
{
/* check if connections are alive. if not, play PING-PONG first.
* if this doesn't help either, disconnect client. */
CLIENT *c;
CONN_ID i;
- for( i = 0; i < Pool_Size; i++ ) {
+ for (i = 0; i < Pool_Size; i++) {
if (My_Connections[i].sock < 0)
continue;
- c = Client_GetFromConn( i );
- if( c && (( Client_Type( c ) == CLIENT_USER ) || ( Client_Type( c ) == CLIENT_SERVER ) || ( Client_Type( c ) == CLIENT_SERVICE )))
- {
+ c = Conn_GetClient(i);
+ if (c && ((Client_Type(c) == CLIENT_USER)
+ || (Client_Type(c) == CLIENT_SERVER)
+ || (Client_Type(c) == CLIENT_SERVICE))) {
/* connected User, Server or Service */
- if( My_Connections[i].lastping > My_Connections[i].lastdata ) {
- /* we already sent a ping */
- if( My_Connections[i].lastping < time( NULL ) - Conf_PongTimeout ) {
+ if (My_Connections[i].lastping >
+ My_Connections[i].lastdata) {
+ /* We already sent a ping */
+ if (My_Connections[i].lastping <
+ time(NULL) - Conf_PongTimeout) {
/* Timeout */
- LogDebug("Connection %d: Ping timeout: %d seconds.",
- i, Conf_PongTimeout );
- Conn_Close( i, NULL, "Ping timeout", true );
+ LogDebug
+ ("Connection %d: Ping timeout: %d seconds.",
+ i, Conf_PongTimeout);
+ Conn_Close(i, NULL, "Ping timeout",
+ true);
}
+ } else if (My_Connections[i].lastdata <
+ time(NULL) - Conf_PingTimeout) {
+ /* We need to send a PING ... */
+ LogDebug("Connection %d: sending PING ...", i);
+ My_Connections[i].lastping = time(NULL);
+ Conn_WriteStr(i, "PING :%s",
+ Client_ID(Client_ThisServer()));
}
- else if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout ) {
- /* we need to sent a PING */
- LogDebug("Connection %d: sending PING ...", i );
- My_Connections[i].lastping = time( NULL );
- Conn_WriteStr( i, "PING :%s", Client_ID( Client_ThisServer( )));
- }
- }
- else
- {
+ } else {
/* The connection is not fully established yet, so
* we don't do the PING-PONG game here but instead
* disconnect the client after "a short time" if it's
if (My_Connections[i].lastdata <
time(NULL) - Conf_PongTimeout) {
- LogDebug("Unregistered connection %d timed out ...", i);
+ LogDebug
+ ("Unregistered connection %d timed out ...",
+ i);
Conn_Close(i, NULL, "Timeout", false);
}
}
}
memset( &new_addr, 0, sizeof( new_addr ));
- new_addr.sin_family = AF_INET;
+ new_addr.sin_family = (sa_family_t)AF_INET;
new_addr.sin_addr = inaddr;
new_addr.sin_port = htons( Conf_Server[Server].port );
if( ! Init_Socket( new_sock )) return;
- res = connect( new_sock, (struct sockaddr *)&new_addr, sizeof( new_addr ));
+ res = connect(new_sock, (struct sockaddr *)&new_addr,
+ (socklen_t)sizeof(new_addr));
if(( res != 0 ) && ( errno != EINPROGRESS )) {
Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
close( new_sock );
return;
}
- if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), new_sock)) {
- Log( LOG_ALERT, "Cannot allocate memory for server connection (socket %d)", new_sock);
+ if (!array_alloc(&My_ConnArray, sizeof(CONNECTION), (size_t)new_sock)) {
+ Log(LOG_ALERT,
+ "Cannot allocate memory for server connection (socket %d)",
+ new_sock);
close( new_sock );
return;
}
Conf_Server[Server].conn_id = new_sock;
My_Connections[new_sock].sock = new_sock;
My_Connections[new_sock].addr = new_addr;
+ My_Connections[new_sock].client = c;
strlcpy( My_Connections[new_sock].host, Conf_Server[Server].host,
sizeof(My_Connections[new_sock].host ));
* incoming connections.*/
assert ( My_Connections[i].sock >= 0 );
/* Incoming connection. Search client ... */
- c = Client_GetFromConn( i );
+ c = Conn_GetClient( i );
assert( c != NULL );
/* Only update client information of unregistered clients */
static void
-Simple_Message( int Sock, char *Msg )
+Simple_Message( int Sock, const char *Msg )
{
char buf[COMMAND_LEN];
+ size_t len;
/* Write "simple" message to socket, without using compression
* or even the connection write buffers. Used e.g. for error
* messages by New_Connection(). */
assert( Msg != NULL );
strlcpy( buf, Msg, sizeof buf - 2);
- strlcat( buf, "\r\n", sizeof buf);
- (void)write( Sock, buf, strlen( buf ) );
+ len = strlcat( buf, "\r\n", sizeof buf);
+ (void)write(Sock, buf, len);
} /* Simple_Error */
} /* Count_Connections */
+GLOBAL CLIENT *
+Conn_GetClient( CONN_ID Idx )
+{
+ /* return Client-Structure that belongs to the local Connection Idx.
+ * If none is found, return NULL.
+ */
+ CONNECTION *c;
+ assert( Idx >= 0 );
+
+ c = array_get(&My_ConnArray, sizeof (CONNECTION), (size_t)Idx);
+
+ assert(c != NULL);
+
+ return c ? c->client : NULL;
+}
/* -eof- */