2 * ngIRCd -- The Next Generation IRC Daemon
3 * Copyright (c)2001 by Alexander Barton (alex@barton.de)
5 * Dieses Programm ist freie Software. Sie koennen es unter den Bedingungen
6 * der GNU General Public License (GPL), wie von der Free Software Foundation
7 * herausgegeben, weitergeben und/oder modifizieren, entweder unter Version 2
8 * der Lizenz oder (wenn Sie es wuenschen) jeder spaeteren Version.
9 * Naehere Informationen entnehmen Sie bitter der Datei COPYING. Eine Liste
10 * der an comBase beteiligten Autoren finden Sie in der Datei AUTHORS.
12 * $Id: conn.c,v 1.6 2001/12/15 00:11:55 alex Exp $
14 * connect.h: Verwaltung aller Netz-Verbindungen ("connections")
17 * Revision 1.6 2001/12/15 00:11:55 alex
18 * - Lese- und Schreib-Puffer implementiert.
19 * - einige neue (Unter-)Funktionen eingefuehrt.
20 * - diverse weitere kleinere Aenderungen.
22 * Revision 1.5 2001/12/14 08:16:47 alex
23 * - Begonnen, Client-spezifische Lesepuffer zu implementieren.
24 * - Umstellung auf Datentyp "CONN_ID".
26 * Revision 1.4 2001/12/13 02:04:16 alex
27 * - boesen "Speicherschiesser" in Log() gefixt.
29 * Revision 1.3 2001/12/13 01:33:09 alex
30 * - Conn_Handler() unterstuetzt nun einen Timeout.
31 * - fuer Verbindungen werden keine FILE-Handles mehr benutzt.
32 * - kleinere "Code Cleanups" ;-)
34 * Revision 1.2 2001/12/12 23:32:02 alex
35 * - diverse Erweiterungen und Verbesserungen (u.a. sind nun mehrere
36 * Verbindungen und Listen-Sockets moeglich).
38 * Revision 1.1 2001/12/12 17:18:38 alex
39 * - Modul zur Verwaltung aller Netzwerk-Verbindungen begonnen.
53 #include <sys/socket.h>
55 #include <sys/types.h>
56 #include <netinet/in.h>
57 #include <arpa/inet.h>
60 #include <stdint.h> /* u.a. fuer Mac OS X */
71 #define MAX_CONNECTIONS 100 /* max. Anzahl von Verbindungen an diesem Server */
73 #define MAX_CMDLEN 512 /* max. Laenge eines Befehls, vgl. RFC 2812, 3.2 */
75 #define READBUFFER_LEN 2 * MAX_CMDLEN /* Laenge des Lesepuffers je Verbindung (Bytes) */
76 #define WRITEBUFFER_LEN 4096 /* Laenge des Schreibpuffers je Verbindung (Bytes) */
79 typedef struct _Connection
81 INT sock; /* Socket Handle */
82 struct sockaddr_in addr; /* Adresse des Client */
83 CHAR rbuf[READBUFFER_LEN + 1]; /* Lesepuffer */
84 INT rdatalen; /* Laenge der Daten im Lesepuffer */
85 CHAR wbuf[WRITEBUFFER_LEN + 1]; /* Schreibpuffer */
86 INT wdatalen; /* Laenge der Daten im Schreibpuffer */
90 LOCAL VOID Handle_Read( INT sock );
91 LOCAL BOOLEAN Handle_Write( CONN_ID Idx );
92 LOCAL VOID New_Connection( INT Sock );
93 LOCAL CONN_ID Socket2Index( INT Sock );
94 LOCAL VOID Close_Connection( CONN_ID Idx, CHAR *Msg );
95 LOCAL VOID Read_Request( CONN_ID Idx );
96 LOCAL BOOLEAN Try_Write( CONN_ID Idx );
99 LOCAL fd_set My_Listener;
100 LOCAL fd_set My_Sockets;
104 LOCAL CONNECTION My_Connections[MAX_CONNECTIONS];
107 GLOBAL VOID Conn_Init( VOID )
111 /* zu Beginn haben wir keine Verbindungen */
112 FD_ZERO( &My_Listener );
113 FD_ZERO( &My_Sockets );
117 /* Connection-Struktur initialisieren */
118 for( i = 0; i < MAX_CONNECTIONS; i++ ) My_Connections[i].sock = NONE;
122 GLOBAL VOID Conn_Exit( VOID )
127 /* Sockets schliessen */
128 for( i = 0; i < My_Max_Fd + 1; i++ )
130 if( FD_ISSET( i, &My_Sockets ))
132 for( idx = 0; idx < MAX_CONNECTIONS; idx++ )
134 if( My_Connections[idx].sock == i ) break;
136 if( idx < MAX_CONNECTIONS ) Close_Connection( idx, "Server going down ..." );
137 else if( FD_ISSET( i, &My_Listener ))
140 Log( LOG_INFO, "Closed listening socket %d.", i );
145 Log( LOG_WARNING, "Unknown connection %d closed.", i );
152 GLOBAL BOOLEAN Conn_New_Listener( CONST INT Port )
154 /* Neuen Listen-Socket erzeugen: der Server wartet dann
155 * auf dem angegebenen Port auf Verbindungen. */
157 struct sockaddr_in addr;
160 /* Server-"Listen"-Socket initialisieren */
161 memset( &addr, 0, sizeof( addr ));
162 addr.sin_family = AF_INET;
163 addr.sin_port = htons( Port );
164 addr.sin_addr.s_addr = htonl( INADDR_ANY );
166 /* Socket erzeugen */
167 sock = socket( PF_INET, SOCK_STREAM, 0);
170 Log( LOG_ALERT, "Can't create socket: %s", strerror( errno ));
174 /* Socket-Optionen setzen */
175 if( fcntl( sock, F_SETFL, O_NONBLOCK ) != 0 )
177 Log( LOG_ALERT, "Can't enable non-blocking mode: %s", strerror( errno ));
181 if( setsockopt( sock, SOL_SOCKET, SO_REUSEADDR, &on, (socklen_t)sizeof( on )) != 0)
183 Log( LOG_CRIT, "Can't set socket options: %s", strerror( errno ));
184 /* dieser Fehler kann ignoriert werden. */
188 if( bind( sock, (struct sockaddr *)&addr, (socklen_t)sizeof( addr )) != 0 )
190 Log( LOG_ALERT, "Can't bind socket: %s", strerror( errno ));
195 /* in "listen mode" gehen :-) */
196 if( listen( sock, 10 ) != 0 )
198 Log( LOG_ALERT, "Can't listen on soecket: %s", strerror( errno ));
203 /* Neuen Listener in Strukturen einfuegen */
204 FD_SET( sock, &My_Listener );
205 FD_SET( sock, &My_Sockets );
207 if( sock > My_Max_Fd ) My_Max_Fd = sock;
209 Log( LOG_INFO, "Now listening on port %d, socket %d.", Port, sock );
212 } /* Conn_New_Listener */
215 GLOBAL VOID Conn_Handler( INT Timeout )
217 fd_set read_sockets, write_sockets;
221 /* Timeout initialisieren */
225 /* noch volle Schreib-Puffer suchen */
226 FD_ZERO( &write_sockets );
227 for( i = 0; i < MAX_CONNECTIONS; i++ )
229 if(( My_Connections[i].sock >= 0 ) && ( My_Connections[i].wdatalen > 0 ))
231 /* Socket der Verbindung in Set aufnehmen */
232 FD_SET( My_Connections[i].sock, &write_sockets );
236 read_sockets = My_Sockets;
237 if( select( My_Max_Fd + 1, &read_sockets, &write_sockets, NULL, &tv ) == -1 )
239 if( errno != EINTR ) Log( LOG_ALERT, "select(): %s", strerror( errno ));
243 /* Koennen Daten geschrieben werden? */
244 for( i = 0; i < My_Max_Fd + 1; i++ )
246 if( FD_ISSET( i, &write_sockets )) Handle_Write( Socket2Index( i ));
249 /* Daten zum Lesen vorhanden? */
250 for( i = 0; i < My_Max_Fd + 1; i++ )
252 if( FD_ISSET( i, &read_sockets )) Handle_Read( i );
257 GLOBAL BOOLEAN Conn_WriteStr( CONN_ID Idx, CHAR *Data )
259 /* String in Socket schreiben. CR+LF wird von dieser Funktion
260 * automatisch angehaengt. */
262 CHAR buffer[MAX_CMDLEN];
264 if( strlen( Data ) > MAX_CMDLEN - 2 )
266 Log( LOG_ALERT, "String too long to send (connection %d)!", Idx );
267 Close_Connection( Idx, "Server error: String too long to send!" );
271 sprintf( buffer, "%s\r\n", Data );
272 return Conn_Write( Idx, buffer, strlen( buffer ));
273 } /* Conn_WriteStr */
276 GLOBAL BOOLEAN Conn_Write( CONN_ID Idx, CHAR *Data, INT Len )
278 /* Daten in Socket schreiben. Bei "fatalen" Fehlern wird
279 * der Client disconnectiert und FALSE geliefert. */
282 assert( My_Connections[Idx].sock >= 0 );
283 assert( Data != NULL );
286 /* pruefen, ob Daten im Schreibpuffer sind. Wenn ja, zunaechst
287 * pruefen, ob diese gesendet werden koennen */
288 if( My_Connections[Idx].wdatalen > 0 )
290 if( ! Try_Write( Idx )) return FALSE;
293 /* pruefen, ob im Schreibpuffer genuegend Platz ist */
294 if( WRITEBUFFER_LEN - My_Connections[Idx].wdatalen - Len <= 0 )
296 /* der Puffer ist dummerweise voll ... */
297 Log( LOG_NOTICE, "Write buffer overflow (connection %d)!", Idx );
298 Close_Connection( Idx, NULL );
302 /* Daten in Puffer kopieren */
303 memcpy( My_Connections[Idx].wbuf + My_Connections[Idx].wdatalen, Data, Len );
304 My_Connections[Idx].wdatalen += Len;
306 /* pruefen, on Daten vorhanden sind und geschrieben werden koennen */
307 if( My_Connections[Idx].wdatalen > 0 )
309 if( ! Try_Write( Idx )) return FALSE;
316 LOCAL BOOLEAN Try_Write( CONN_ID Idx )
318 /* Versuchen, Daten aus dem Schreib-Puffer in den
319 * Socket zu schreiben. */
324 assert( My_Connections[Idx].sock >= 0 );
325 assert( My_Connections[Idx].wdatalen > 0 );
327 FD_ZERO( &write_socket );
328 FD_SET( My_Connections[Idx].sock, &write_socket );
329 if( select( My_Connections[Idx].sock + 1, NULL, &write_socket, NULL, 0 ) == -1 )
334 Log( LOG_ALERT, "select(): %s", strerror( errno ));
335 Close_Connection( Idx, NULL );
340 if( FD_ISSET( My_Connections[Idx].sock, &write_socket )) return Handle_Write( Idx );
345 LOCAL VOID Handle_Read( INT Sock )
347 /* Aktivitaet auf einem Socket verarbeiten */
353 if( FD_ISSET( Sock, &My_Listener ))
355 /* es ist einer unserer Listener-Sockets: es soll
356 * also eine neue Verbindung aufgebaut werden. */
358 New_Connection( Sock );
362 /* Ein Client Socket: entweder ein User oder Server */
364 idx = Socket2Index( Sock );
370 LOCAL BOOLEAN Handle_Write( CONN_ID Idx )
372 /* Daten aus Schreibpuffer versenden */
377 assert( My_Connections[Idx].sock >= 0 );
378 assert( My_Connections[Idx].wdatalen > 0 );
380 /* Daten schreiben */
381 len = send( My_Connections[Idx].sock, My_Connections[Idx].wbuf, My_Connections[Idx].wdatalen, 0 );
384 /* Oops, ein Fehler! */
385 Log( LOG_ALERT, "Write error (buffer) on connection %d: %s", Idx, strerror( errno ));
386 Close_Connection( Idx, NULL );
390 /* Puffer anpassen */
391 My_Connections[Idx].wdatalen -= len;
392 memmove( My_Connections[Idx].wbuf, My_Connections[Idx].wbuf + len, My_Connections[Idx].wdatalen );
398 LOCAL VOID New_Connection( INT Sock )
400 /* Neue Client-Verbindung von Listen-Socket annehmen */
402 struct sockaddr_in new_addr;
403 INT new_sock, new_sock_len;
408 new_sock_len = sizeof( new_addr );
409 new_sock = accept( Sock, (struct sockaddr *)&new_addr, (socklen_t *)&new_sock_len );
412 Log( LOG_CRIT, "Can't accept connection: %s", strerror( errno ));
416 /* Freie Connection-Struktur suschen */
417 for( idx = 0; idx < MAX_CONNECTIONS; idx++ ) if( My_Connections[idx].sock < 0 ) break;
418 if( idx >= MAX_CONNECTIONS )
420 Log( LOG_ALERT, "Can't accept connection: limit reached (%d)!", MAX_CONNECTIONS );
425 /* Verbindung registrieren */
426 My_Connections[idx].sock = new_sock;
427 My_Connections[idx].addr = new_addr;
428 My_Connections[idx].rdatalen = 0;
429 My_Connections[idx].wdatalen = 0;
431 /* Neuen Socket registrieren */
432 FD_SET( new_sock, &My_Sockets );
434 if( new_sock > My_Max_Fd ) My_Max_Fd = new_sock;
436 Log( LOG_NOTICE, "Accepted connection %d from %s:%d on socket %d.", idx, inet_ntoa( new_addr.sin_addr ), ntohs( new_addr.sin_port), Sock );
437 } /* New_Connection */
440 LOCAL CONN_ID Socket2Index( INT Sock )
442 /* zum Socket passende Connection suchen */
448 for( idx = 0; idx < MAX_CONNECTIONS; idx++ ) if( My_Connections[idx].sock == Sock ) break;
450 assert( idx < MAX_CONNECTIONS );
455 LOCAL VOID Close_Connection( CONN_ID Idx, CHAR *Msg )
457 /* Verbindung schlie§en */
459 CHAR bye_str[MAX_CMDLEN];
462 assert( My_Connections[Idx].sock >= 0 );
466 sprintf( bye_str, "ERROR :%s", Msg );
467 Conn_WriteStr( Idx, bye_str );
470 if( close( My_Connections[Idx].sock ) != 0 )
472 Log( LOG_ERR, "Error closing connection %d with %s:%d - %s", Idx, inet_ntoa( My_Connections[Idx].addr.sin_addr ), ntohs( My_Connections[Idx].addr.sin_port), strerror( errno ));
476 Log( LOG_NOTICE, "Closed connection %d with %s:%d.", Idx, inet_ntoa( My_Connections[Idx].addr.sin_addr ), ntohs( My_Connections[Idx].addr.sin_port ));
479 FD_CLR( My_Connections[Idx].sock, &My_Sockets );
480 My_Connections[Idx].sock = NONE;
481 } /* Close_Connection */
484 LOCAL VOID Read_Request( CONN_ID Idx )
486 /* Daten von Socket einlesen und entsprechend behandeln.
487 * Tritt ein Fehler auf, so wird der Socket geschlossen. */
493 assert( My_Connections[Idx].sock >= 0 );
495 len = recv( My_Connections[Idx].sock, My_Connections[Idx].rbuf + My_Connections[Idx].rdatalen, READBUFFER_LEN - My_Connections[Idx].rdatalen, 0 );
496 My_Connections[Idx].rbuf[READBUFFER_LEN] = '\0';
500 /* Socket wurde geschlossen */
501 Close_Connection( Idx, NULL );
507 /* Fehler beim Lesen */
508 Log( LOG_ALERT, "Read error on connection %d!", Idx );
509 Close_Connection( Idx, "Read error!" );
513 My_Connections[Idx].rdatalen += len;
514 assert( My_Connections[Idx].rdatalen <= READBUFFER_LEN );
515 My_Connections[Idx].rbuf[My_Connections[Idx].rdatalen] = '\0';
517 if( My_Connections[Idx].rdatalen > MAX_CMDLEN )
519 /* Eine Anfrage darf(!) nicht laenger als 512 Zeichen
520 * (incl. CR+LF!) werden; vgl. RFC 2812. Wenn soetwas
521 * empfangen wird, wird der Client disconnectiert. */
522 Log( LOG_ALERT, "Request too long (connection %d)!", Idx );
523 Close_Connection( Idx, "Request too long!" );
527 /* Eine komplette Anfrage muss mit CR+LF enden, vgl.
528 * RFC 2812. Haben wir eine? */
529 ptr = strstr( My_Connections[Idx].rbuf, "\r\n" );
532 /* Ende der Anfrage (CR+LF) wurde gefunden */
534 len = ( ptr - My_Connections[Idx].rbuf ) + 2;
537 printf( " in: '%s'\n", My_Connections[Idx].rbuf );
539 else Log( LOG_DEBUG, "Got null-request (connection %d).", Idx );
541 /* Puffer anpassen */
542 My_Connections[Idx].rdatalen -= len;
543 memmove( My_Connections[Idx].rbuf, My_Connections[Idx].rbuf + len, My_Connections[Idx].rdatalen );