]> arthur.barton.de Git - ngircd-alex.git/blob - src/ngircd/conn.c
3975a920429dcb7b2bbf911bbd1b3272ffc1b3c9
[ngircd-alex.git] / src / ngircd / conn.c
1 /*
2  * ngIRCd -- The Next Generation IRC Daemon
3  * Copyright (c)2001,2002 by Alexander Barton (alex@barton.de)
4  *
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.
10  *
11  * Connection management
12  */
13
14
15 #define CONN_MODULE
16
17 #include "portab.h"
18
19 static char UNUSED id[] = "$Id: conn.c,v 1.113 2002/12/30 17:14:59 alex Exp $";
20
21 #include "imp.h"
22 #include <assert.h>
23 #include <stdarg.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <unistd.h>
27 #include <errno.h>
28 #include <fcntl.h>
29 #include <string.h>
30 #include <sys/socket.h>
31 #include <sys/time.h>
32 #include <sys/types.h>
33 #include <time.h>
34 #include <netinet/in.h>
35
36 #ifdef HAVE_ARPA_INET_H
37 #include <arpa/inet.h>
38 #else
39 #define PF_INET AF_INET
40 #endif
41
42 #ifdef HAVE_STDINT_H
43 #include <stdint.h>                     /* u.a. fuer Mac OS X */
44 #endif
45
46 #include "defines.h"
47 #include "resolve.h"
48
49 #include "exp.h"
50 #include "conn.h"
51
52 #include "imp.h"
53 #include "ngircd.h"
54 #include "client.h"
55 #include "conf.h"
56 #include "conn-zip.h"
57 #include "conn-func.h"
58 #include "log.h"
59 #include "parse.h"
60 #include "tool.h"
61
62 #include "exp.h"
63
64
65 #define SERVER_WAIT (NONE - 1)
66
67
68 LOCAL VOID Handle_Read PARAMS(( INT sock ));
69 LOCAL BOOLEAN Handle_Write PARAMS(( CONN_ID Idx ));
70 LOCAL VOID New_Connection PARAMS(( INT Sock ));
71 LOCAL CONN_ID Socket2Index PARAMS(( INT Sock ));
72 LOCAL VOID Read_Request PARAMS(( CONN_ID Idx ));
73 LOCAL BOOLEAN Try_Write PARAMS(( CONN_ID Idx ));
74 LOCAL BOOLEAN Handle_Buffer PARAMS(( CONN_ID Idx ));
75 LOCAL VOID Check_Connections PARAMS(( VOID ));
76 LOCAL VOID Check_Servers PARAMS(( VOID ));
77 LOCAL VOID Init_Conn_Struct PARAMS(( CONN_ID Idx ));
78 LOCAL BOOLEAN Init_Socket PARAMS(( INT Sock ));
79 LOCAL VOID New_Server PARAMS(( INT Server, CONN_ID Idx ));
80 LOCAL VOID Read_Resolver_Result PARAMS(( INT r_fd ));
81
82 LOCAL fd_set My_Listeners;
83 LOCAL fd_set My_Sockets;
84 LOCAL fd_set My_Connects;
85
86
87 GLOBAL VOID
88 Conn_Init( VOID )
89 {
90         /* Modul initialisieren: statische Strukturen "ausnullen". */
91
92         CONN_ID i;
93
94         /* Speicher fuer Verbindungs-Pool anfordern */
95         Pool_Size = CONNECTION_POOL;
96         if( Conf_MaxConnections > 0 )
97         {
98                 /* konfiguriertes Limit beachten */
99                 if( Pool_Size > Conf_MaxConnections ) Pool_Size = Conf_MaxConnections;
100         }
101         My_Connections = malloc( sizeof( CONNECTION ) * Pool_Size );
102         if( ! My_Connections )
103         {
104                 /* Speicher konnte nicht alloziert werden! */
105                 Log( LOG_EMERG, "Can't allocate memory! [Conn_Init]" );
106                 exit( 1 );
107         }
108         Log( LOG_DEBUG, "Allocted connection pool for %d items (%ld bytes).", Pool_Size, sizeof( CONNECTION ) * Pool_Size );
109
110         /* zu Beginn haben wir keine Verbindungen */
111         FD_ZERO( &My_Listeners );
112         FD_ZERO( &My_Sockets );
113         FD_ZERO( &My_Connects );
114
115         /* Groesster File-Descriptor fuer select() */
116         Conn_MaxFD = 0;
117
118         /* Connection-Struktur initialisieren */
119         for( i = 0; i < Pool_Size; i++ ) Init_Conn_Struct( i );
120
121         /* Global write counter */
122         WCounter = 0;
123 } /* Conn_Init */
124
125
126 GLOBAL VOID
127 Conn_Exit( VOID )
128 {
129         /* Modul abmelden: alle noch offenen Connections
130          * schliessen und freigeben. */
131
132         CONN_ID idx;
133         INT i;
134
135         /* Sockets schliessen */
136         Log( LOG_DEBUG, "Shutting down all connections ..." );
137         for( i = 0; i < Conn_MaxFD + 1; i++ )
138         {
139                 if( FD_ISSET( i, &My_Sockets ))
140                 {
141                         for( idx = 0; idx < Pool_Size; idx++ )
142                         {
143                                 if( My_Connections[idx].sock == i ) break;
144                         }
145                         if( FD_ISSET( i, &My_Listeners ))
146                         {
147                                 close( i );
148                                 Log( LOG_DEBUG, "Listening socket %d closed.", i );
149                         }
150                         else if( FD_ISSET( i, &My_Connects ))
151                         {
152                                 close( i );
153                                 Log( LOG_DEBUG, "Connection %d closed during creation (socket %d).", idx, i );
154                         }
155                         else if( idx < Pool_Size )
156                         {
157                                 if( NGIRCd_SignalRestart ) Conn_Close( idx, NULL, "Server going down (restarting)", TRUE );
158                                 else Conn_Close( idx, NULL, "Server going down", TRUE );
159                         }
160                         else
161                         {
162                                 Log( LOG_WARNING, "Closing unknown connection %d ...", i );
163                                 close( i );
164                         }
165                 }
166         }
167         
168         free( My_Connections );
169         My_Connections = NULL;
170         Pool_Size = 0;
171 } /* Conn_Exit */
172
173
174 GLOBAL INT
175 Conn_InitListeners( VOID )
176 {
177         /* Initialize ports on which the server should accept connections */
178
179         INT created, i;
180
181         created = 0;
182         for( i = 0; i < Conf_ListenPorts_Count; i++ )
183         {
184                 if( Conn_NewListener( Conf_ListenPorts[i] )) created++;
185                 else Log( LOG_ERR, "Can't listen on port %u!", Conf_ListenPorts[i] );
186         }
187         return created;
188 } /* Conn_InitListeners */
189
190
191 GLOBAL VOID
192 Conn_ExitListeners( VOID )
193 {
194         /* Close down all listening sockets */
195
196         INT i;
197
198         Log( LOG_INFO, "Shutting down all listening sockets ..." );
199         for( i = 0; i < Conn_MaxFD + 1; i++ )
200         {
201                 if( FD_ISSET( i, &My_Sockets ) && FD_ISSET( i, &My_Listeners ))
202                 {
203                         close( i );
204                         Log( LOG_DEBUG, "Listening socket %d closed.", i );
205                 }
206         }
207 } /* Conn_ExitListeners */
208
209
210 GLOBAL BOOLEAN
211 Conn_NewListener( CONST UINT Port )
212 {
213         /* Create new listening socket on specified port */
214
215         struct sockaddr_in addr;
216         INT sock;
217
218         /* Server-"Listen"-Socket initialisieren */
219         memset( &addr, 0, sizeof( addr ));
220         addr.sin_family = AF_INET;
221         addr.sin_port = htons( Port );
222         addr.sin_addr.s_addr = htonl( INADDR_ANY );
223
224         /* Socket erzeugen */
225         sock = socket( PF_INET, SOCK_STREAM, 0);
226         if( sock < 0 )
227         {
228                 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
229                 return FALSE;
230         }
231
232         if( ! Init_Socket( sock )) return FALSE;
233
234         /* an Port binden */
235         if( bind( sock, (struct sockaddr *)&addr, (socklen_t)sizeof( addr )) != 0 )
236         {
237                 Log( LOG_CRIT, "Can't bind socket: %s!", strerror( errno ));
238                 close( sock );
239                 return FALSE;
240         }
241
242         /* in "listen mode" gehen :-) */
243         if( listen( sock, 10 ) != 0 )
244         {
245                 Log( LOG_CRIT, "Can't listen on soecket: %s!", strerror( errno ));
246                 close( sock );
247                 return FALSE;
248         }
249
250         /* Neuen Listener in Strukturen einfuegen */
251         FD_SET( sock, &My_Listeners );
252         FD_SET( sock, &My_Sockets );
253
254         if( sock > Conn_MaxFD ) Conn_MaxFD = sock;
255
256         Log( LOG_INFO, "Now listening on port %d (socket %d).", Port, sock );
257
258         return TRUE;
259 } /* Conn_NewListener */
260
261
262 GLOBAL VOID
263 Conn_Handler( VOID )
264 {
265         /* "Hauptschleife": Aktive Verbindungen ueberwachen. Folgende Aktionen
266          * werden dabei durchgefuehrt, bis der Server terminieren oder neu
267          * starten soll:
268          *
269          *  - neue Verbindungen annehmen,
270          *  - Server-Verbindungen aufbauen,
271          *  - geschlossene Verbindungen loeschen,
272          *  - volle Schreibpuffer versuchen zu schreiben,
273          *  - volle Lesepuffer versuchen zu verarbeiten,
274          *  - Antworten von Resolver Sub-Prozessen annehmen.
275          */
276
277         fd_set read_sockets, write_sockets;
278         struct timeval tv;
279         time_t start, t;
280         CONN_ID i, idx;
281         BOOLEAN timeout;
282
283         start = time( NULL );
284         while(( ! NGIRCd_SignalQuit ) && ( ! NGIRCd_SignalRestart ))
285         {
286                 timeout = TRUE;
287
288                 /* Should the configuration be reloaded? */
289                 if( NGIRCd_SignalRehash ) NGIRCd_Rehash( );
290
291                 /* Check configured servers and established links */
292                 Check_Servers( );
293                 Check_Connections( );
294
295                 /* noch volle Lese-Buffer suchen */
296                 for( i = 0; i < Pool_Size; i++ )
297                 {
298                         if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].rdatalen > 0 ))
299                         {
300                                 /* Kann aus dem Buffer noch ein Befehl extrahiert werden? */
301                                 if( Handle_Buffer( i )) timeout = FALSE;
302                         }
303                 }
304
305                 /* noch volle Schreib-Puffer suchen */
306                 FD_ZERO( &write_sockets );
307                 for( i = 0; i < Pool_Size; i++ )
308                 {
309 #ifdef USE_ZLIB
310                         if(( My_Connections[i].sock > NONE ) && (( My_Connections[i].wdatalen > 0 ) || ( My_Connections[i].zip.wdatalen > 0 )))
311 #else
312                         if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].wdatalen > 0 ))
313 #endif
314                         {
315                                 /* Socket der Verbindung in Set aufnehmen */
316                                 FD_SET( My_Connections[i].sock, &write_sockets );
317                         }
318                 }
319
320                 /* Sockets mit im Aufbau befindlichen ausgehenden Verbindungen suchen */
321                 for( i = 0; i < Pool_Size; i++ )
322                 {
323                         if(( My_Connections[i].sock > NONE ) && ( FD_ISSET( My_Connections[i].sock, &My_Connects ))) FD_SET( My_Connections[i].sock, &write_sockets );
324                 }
325
326                 /* von welchen Sockets koennte gelesen werden? */
327                 t = time( NULL );
328                 read_sockets = My_Sockets;
329                 for( i = 0; i < Pool_Size; i++ )
330                 {
331                         if(( My_Connections[i].sock > NONE ) && ( My_Connections[i].host[0] == '\0' ))
332                         {
333                                 /* Hier muss noch auf den Resolver Sub-Prozess gewartet werden */
334                                 FD_CLR( My_Connections[i].sock, &read_sockets );
335                         }
336                         if(( My_Connections[i].sock > NONE ) && ( FD_ISSET( My_Connections[i].sock, &My_Connects )))
337                         {
338                                 /* Hier laeuft noch ein asyncrones connect() */
339                                 FD_CLR( My_Connections[i].sock, &read_sockets );
340                         }
341                         if( My_Connections[i].delaytime > t )
342                         {
343                                 /* Fuer die Verbindung ist eine "Penalty-Zeit" gesetzt */
344                                 FD_CLR( My_Connections[i].sock, &read_sockets );
345                         }
346                 }
347                 for( i = 0; i < Conn_MaxFD + 1; i++ )
348                 {
349                         /* Pipes von Resolver Sub-Prozessen aufnehmen */
350                         if( FD_ISSET( i, &Resolver_FDs ))
351                         {
352                                 FD_SET( i, &read_sockets );
353                         }
354                 }
355
356                 /* Timeout initialisieren */
357                 tv.tv_usec = 0;
358                 if( timeout ) tv.tv_sec = TIME_RES;
359                 else tv.tv_sec = 0;
360                 
361                 /* Auf Aktivitaet warten */
362                 i = select( Conn_MaxFD + 1, &read_sockets, &write_sockets, NULL, &tv );
363                 if( i == 0 )
364                 {
365                         /* keine Veraenderung an den Sockets */
366                         continue;
367                 }
368                 if( i == -1 )
369                 {
370                         /* Fehler (z.B. Interrupt) */
371                         if( errno != EINTR )
372                         {
373                                 Log( LOG_EMERG, "Conn_Handler(): select(): %s!", strerror( errno ));
374                                 Log( LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE );
375                                 exit( 1 );
376                         }
377                         continue;
378                 }
379
380                 /* Koennen Daten geschrieben werden? */
381                 for( i = 0; i < Conn_MaxFD + 1; i++ )
382                 {
383                         if( ! FD_ISSET( i, &write_sockets )) continue;
384
385                         /* Es kann geschrieben werden ... */
386                         idx = Socket2Index( i );
387                         if( idx == NONE ) continue;
388                         
389                         if( ! Handle_Write( idx ))
390                         {
391                                 /* Fehler beim Schreiben! Diesen Socket nun
392                                  * auch aus dem Read-Set entfernen: */
393                                 FD_CLR( i, &read_sockets );
394                         }
395                 }
396
397                 /* Daten zum Lesen vorhanden? */
398                 for( i = 0; i < Conn_MaxFD + 1; i++ )
399                 {
400                         if( FD_ISSET( i, &read_sockets )) Handle_Read( i );
401                 }
402         }
403
404         if( NGIRCd_SignalQuit ) Log( LOG_NOTICE|LOG_snotice, "Server going down NOW!" );
405         else if( NGIRCd_SignalRestart ) Log( LOG_NOTICE|LOG_snotice, "Server restarting NOW!" );
406 } /* Conn_Handler */
407
408
409 #ifdef PROTOTYPES
410 GLOBAL BOOLEAN
411 Conn_WriteStr( CONN_ID Idx, CHAR *Format, ... )
412 #else
413 GLOBAL BOOLEAN
414 Conn_WriteStr( Idx, Format, va_alist )
415 CONN_ID Idx;
416 CHAR *Format;
417 va_dcl
418 #endif
419 {
420         /* String in Socket schreiben. CR+LF wird von dieser Funktion
421          * automatisch angehaengt. Im Fehlerfall wird dir Verbindung
422          * getrennt und FALSE geliefert. */
423
424         CHAR buffer[COMMAND_LEN];
425         BOOLEAN ok;
426         va_list ap;
427
428         assert( Idx > NONE );
429         assert( Format != NULL );
430
431 #ifdef PROTOTYPES
432         va_start( ap, Format );
433 #else
434         va_start( ap );
435 #endif
436         if( vsnprintf( buffer, COMMAND_LEN - 2, Format, ap ) == COMMAND_LEN - 2 )
437         {
438                 Log( LOG_CRIT, "Text too long to send (connection %d)!", Idx );
439                 Conn_Close( Idx, "Text too long to send!", NULL, FALSE );
440                 return FALSE;
441         }
442
443 #ifdef SNIFFER
444         if( NGIRCd_Sniffer ) Log( LOG_DEBUG, " -> connection %d: '%s'.", Idx, buffer );
445 #endif
446
447         strlcat( buffer, "\r\n", sizeof( buffer ));
448         ok = Conn_Write( Idx, buffer, strlen( buffer ));
449         My_Connections[Idx].msg_out++;
450
451         va_end( ap );
452         return ok;
453 } /* Conn_WriteStr */
454
455
456 GLOBAL BOOLEAN
457 Conn_Write( CONN_ID Idx, CHAR *Data, INT Len )
458 {
459         /* Daten in Socket schreiben. Bei "fatalen" Fehlern wird
460          * der Client disconnectiert und FALSE geliefert. */
461
462         assert( Idx > NONE );
463         assert( Data != NULL );
464         assert( Len > 0 );
465
466         /* Ist der entsprechende Socket ueberhaupt noch offen? In einem
467          * "Handler-Durchlauf" kann es passieren, dass dem nicht mehr so
468          * ist, wenn einer von mehreren Conn_Write()'s fehlgeschlagen ist.
469          * In diesem Fall wird hier einfach ein Fehler geliefert. */
470         if( My_Connections[Idx].sock <= NONE )
471         {
472                 Log( LOG_DEBUG, "Skipped write on closed socket (connection %d).", Idx );
473                 return FALSE;
474         }
475
476         /* Pruefen, ob im Schreibpuffer genuegend Platz ist. Ziel ist es,
477          * moeglichts viel im Puffer zu haben und _nicht_ gleich alles auf den
478          * Socket zu schreiben (u.a. wg. Komprimierung). */
479         if( WRITEBUFFER_LEN - My_Connections[Idx].wdatalen - Len <= 0 )
480         {
481                 /* Der Puffer ist dummerweise voll. Jetzt versuchen, den Puffer
482                  * zu schreiben, wenn das nicht klappt, haben wir ein Problem ... */
483                 if( ! Try_Write( Idx )) return FALSE;
484
485                 /* nun neu pruefen: */
486                 if( WRITEBUFFER_LEN - My_Connections[Idx].wdatalen - Len <= 0 )
487                 {
488                         Log( LOG_NOTICE, "Write buffer overflow (connection %d)!", Idx );
489                         Conn_Close( Idx, "Write buffer overflow!", NULL, FALSE );
490                         return FALSE;
491                 }
492         }
493
494 #ifdef USE_ZLIB
495         if( My_Connections[Idx].options & CONN_ZIP )
496         {
497                 /* Daten komprimieren und in Puffer kopieren */
498                 if( ! Zip_Buffer( Idx, Data, Len )) return FALSE;
499         }
500         else
501 #endif
502         {
503                 /* Daten in Puffer kopieren */
504                 memcpy( My_Connections[Idx].wbuf + My_Connections[Idx].wdatalen, Data, Len );
505                 My_Connections[Idx].wdatalen += Len;
506                 My_Connections[Idx].bytes_out += Len;
507         }
508
509         /* Adjust global write counter */
510         WCounter += Len;
511
512         return TRUE;
513 } /* Conn_Write */
514
515
516 GLOBAL VOID
517 Conn_Close( CONN_ID Idx, CHAR *LogMsg, CHAR *FwdMsg, BOOLEAN InformClient )
518 {
519         /* Close connection. Open pipes of asyncronous resolver
520          * sub-processes are closed down. */
521
522         CLIENT *c;
523         DOUBLE in_k, out_k;
524 #ifdef USE_ZLIB
525         DOUBLE in_z_k, out_z_k;
526         INT in_p, out_p;
527 #endif
528
529         assert( Idx > NONE );
530         assert( My_Connections[Idx].sock > NONE );
531
532         /* Search client, if any */
533         c = Client_GetFromConn( Idx );
534
535         /* Should the client be informed? */
536         if( InformClient )
537         {
538 #ifndef STRICT_RFC
539                 /* Send statistics to client if registered as user: */
540                 if(( c != NULL ) && ( Client_Type( c ) == CLIENT_USER ))
541                 {
542                         Conn_WriteStr( Idx, "NOTICE %s :%sConnection statistics: client %.1f kb, server %.1f kb.", Client_ThisServer( ), NOTICE_TXTPREFIX, (DOUBLE)My_Connections[Idx].bytes_in / 1024,  (DOUBLE)My_Connections[Idx].bytes_out / 1024 );
543                 }
544 #endif
545
546                 /* Send ERROR to client (see RFC!) */
547                 if( FwdMsg ) Conn_WriteStr( Idx, "ERROR :%s", FwdMsg );
548                 else Conn_WriteStr( Idx, "ERROR :Closing connection." );
549                 if( My_Connections[Idx].sock == NONE ) return;
550         }
551
552         /* Try to write out the write buffer */
553         Try_Write( Idx );
554
555         /* Shut down socket */
556         if( close( My_Connections[Idx].sock ) != 0 )
557         {
558                 /* Oops, we can't close the socket!? This is fatal! */
559                 Log( LOG_EMERG, "Error closing connection %d (socket %d) with %s:%d - %s!", Idx, My_Connections[Idx].sock, My_Connections[Idx].host, ntohs( My_Connections[Idx].addr.sin_port), strerror( errno ));
560                 Log( LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE );
561                 exit( 1 );
562         }
563
564         /* Mark socket as invalid: */
565         FD_CLR( My_Connections[Idx].sock, &My_Sockets );
566         FD_CLR( My_Connections[Idx].sock, &My_Connects );
567         My_Connections[Idx].sock = NONE;
568
569         /* If there is still a client, unregister it now */
570         if( c ) Client_Destroy( c, LogMsg, FwdMsg, TRUE );
571
572         /* Calculate statistics and log information */
573         in_k = (DOUBLE)My_Connections[Idx].bytes_in / 1024;
574         out_k = (DOUBLE)My_Connections[Idx].bytes_out / 1024;
575 #ifdef USE_ZLIB
576         if( My_Connections[Idx].options & CONN_ZIP )
577         {
578                 in_z_k = (DOUBLE)My_Connections[Idx].zip.bytes_in / 1024;
579                 out_z_k = (DOUBLE)My_Connections[Idx].zip.bytes_out / 1024;
580                 in_p = (INT)(( in_k * 100 ) / in_z_k );
581                 out_p = (INT)(( out_k * 100 ) / out_z_k );
582                 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 );
583         }
584         else
585 #endif
586         {
587                 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 );
588         }
589
590         /* Is there a resolver sub-process running? */
591         if( My_Connections[Idx].res_stat )
592         {
593                 /* Free resolver structures */
594                 FD_CLR( My_Connections[Idx].res_stat->pipe[0], &Resolver_FDs );
595                 close( My_Connections[Idx].res_stat->pipe[0] );
596                 close( My_Connections[Idx].res_stat->pipe[1] );
597                 free( My_Connections[Idx].res_stat );
598         }
599
600         /* Servers: Modify time of next connect attempt? */
601         Conf_UnsetServer( Idx );
602
603 #ifdef USE_ZLIB
604         /* Clean up zlib, if link was compressed */
605         if( Conn_Options( Idx ) & CONN_ZIP )
606         {
607                 inflateEnd( &My_Connections[Idx].zip.in );
608                 deflateEnd( &My_Connections[Idx].zip.out );
609         }
610 #endif
611
612         /* Clean up connection structure (=free it) */
613         Init_Conn_Struct( Idx );
614 } /* Conn_Close */
615
616
617 LOCAL BOOLEAN
618 Try_Write( CONN_ID Idx )
619 {
620         /* Versuchen, Daten aus dem Schreib-Puffer in den Socket zu
621          * schreiben. TRUE wird geliefert, wenn entweder keine Daten
622          * zum Versenden vorhanden sind oder erfolgreich bearbeitet
623          * werden konnten. Im Fehlerfall wird FALSE geliefert und
624          * die Verbindung geschlossen. */
625
626         fd_set write_socket;
627         struct timeval tv;
628
629         assert( Idx > NONE );
630         assert( My_Connections[Idx].sock > NONE );
631
632         /* sind ueberhaupt Daten vorhanden? */
633 #ifdef USE_ZLIB
634         if(( ! My_Connections[Idx].wdatalen > 0 ) && ( ! My_Connections[Idx].zip.wdatalen )) return TRUE;
635 #else
636         if( ! My_Connections[Idx].wdatalen > 0 ) return TRUE;
637 #endif
638
639         /* Timeout initialisieren: 0 Sekunden, also nicht blockieren */
640         tv.tv_sec = 0; tv.tv_usec = 0;
641
642         FD_ZERO( &write_socket );
643         FD_SET( My_Connections[Idx].sock, &write_socket );
644         if( select( My_Connections[Idx].sock + 1, NULL, &write_socket, NULL, &tv ) == -1 )
645         {
646                 /* Fehler! */
647                 if( errno != EINTR )
648                 {
649                         Log( LOG_ALERT, "Try_Write(): select() failed: %s (con=%d, sock=%d)!", strerror( errno ), Idx, My_Connections[Idx].sock );
650                         Conn_Close( Idx, "Server error!", NULL, FALSE );
651                         return FALSE;
652                 }
653         }
654
655         if( FD_ISSET( My_Connections[Idx].sock, &write_socket )) return Handle_Write( Idx );
656         else return TRUE;
657 } /* Try_Write */
658
659
660 LOCAL VOID
661 Handle_Read( INT Sock )
662 {
663         /* Aktivitaet auf einem Socket verarbeiten:
664          *  - neue Clients annehmen,
665          *  - Daten von Clients verarbeiten,
666          *  - Resolver-Rueckmeldungen annehmen. */
667
668         CONN_ID idx;
669
670         assert( Sock > NONE );
671
672         if( FD_ISSET( Sock, &My_Listeners ))
673         {
674                 /* es ist einer unserer Listener-Sockets: es soll
675                  * also eine neue Verbindung aufgebaut werden. */
676
677                 New_Connection( Sock );
678         }
679         else if( FD_ISSET( Sock, &Resolver_FDs ))
680         {
681                 /* Rueckmeldung von einem Resolver Sub-Prozess */
682
683                 Read_Resolver_Result( Sock );
684         }
685         else
686         {
687                 /* Ein Client Socket: entweder ein User oder Server */
688
689                 idx = Socket2Index( Sock );
690                 if( idx > NONE ) Read_Request( idx );
691         }
692 } /* Handle_Read */
693
694
695 LOCAL BOOLEAN
696 Handle_Write( CONN_ID Idx )
697 {
698         /* Daten aus Schreibpuffer versenden bzw. Connection aufbauen */
699
700         INT len, res, err;
701
702         assert( Idx > NONE );
703         assert( My_Connections[Idx].sock > NONE );
704
705         if( FD_ISSET( My_Connections[Idx].sock, &My_Connects ))
706         {
707                 /* es soll nichts geschrieben werden, sondern ein
708                  * connect() hat ein Ergebnis geliefert */
709
710                 FD_CLR( My_Connections[Idx].sock, &My_Connects );
711
712                 /* Ergebnis des connect() ermitteln */
713                 len = sizeof( err );
714                 res = getsockopt( My_Connections[Idx].sock, SOL_SOCKET, SO_ERROR, &err, &len );
715                 assert( len == sizeof( err ));
716
717                 /* Fehler aufgetreten? */
718                 if(( res != 0 ) || ( err != 0 ))
719                 {
720                         /* Fehler! */
721                         if( res != 0 ) Log( LOG_CRIT, "getsockopt (connection %d): %s!", Idx, strerror( errno ));
722                         else Log( LOG_CRIT, "Can't connect socket to \"%s:%d\" (connection %d): %s!", My_Connections[Idx].host, Conf_Server[Conf_GetServer( Idx )].port, Idx, strerror( err ));
723
724                         /* Socket etc. pp. aufraeumen */
725                         FD_CLR( My_Connections[Idx].sock, &My_Sockets );
726                         close( My_Connections[Idx].sock );
727                         Init_Conn_Struct( Idx );
728
729                         /* Bei Server-Verbindungen lasttry-Zeitpunkt auf "jetzt" setzen */
730                         Conf_Server[Conf_GetServer( Idx )].lasttry = time( NULL );
731                         Conf_UnsetServer( Idx );
732
733                         return FALSE;
734                 }
735                 Log( LOG_DEBUG, "Connection %d with \"%s:%d\" established, now sendig PASS and SERVER ...", Idx, My_Connections[Idx].host, Conf_Server[Conf_GetServer( Idx )].port );
736
737                 /* PASS und SERVER verschicken */
738                 Conn_WriteStr( Idx, "PASS %s %s", Conf_Server[Conf_GetServer( Idx )].pwd_out, NGIRCd_ProtoID );
739                 return Conn_WriteStr( Idx, "SERVER %s :%s", Conf_ServerName, Conf_ServerInfo );
740         }
741
742 #ifdef USE_ZLIB
743         /* Schreibpuffer leer, aber noch Daten im Kompressionsbuffer?
744          * Dann muss dieser nun geflushed werden! */
745         if( My_Connections[Idx].wdatalen == 0 ) Zip_Flush( Idx );
746 #endif
747
748         assert( My_Connections[Idx].wdatalen > 0 );
749
750         /* Daten schreiben */
751         len = send( My_Connections[Idx].sock, My_Connections[Idx].wbuf, My_Connections[Idx].wdatalen, 0 );
752         if( len < 0 )
753         {
754                 /* Operation haette Socket "nur" blockiert ... */
755                 if( errno == EAGAIN ) return TRUE;
756
757                 /* Oops, ein Fehler! */
758                 Log( LOG_ERR, "Write error on connection %d (socket %d): %s!", Idx, My_Connections[Idx].sock, strerror( errno ));
759                 Conn_Close( Idx, "Write error!", NULL, FALSE );
760                 return FALSE;
761         }
762
763         /* Puffer anpassen */
764         My_Connections[Idx].wdatalen -= len;
765         memmove( My_Connections[Idx].wbuf, My_Connections[Idx].wbuf + len, My_Connections[Idx].wdatalen );
766
767         return TRUE;
768 } /* Handle_Write */
769
770
771 LOCAL VOID
772 New_Connection( INT Sock )
773 {
774         /* Neue Client-Verbindung von Listen-Socket annehmen und
775          * CLIENT-Struktur anlegen. */
776
777         struct sockaddr_in new_addr;
778         INT new_sock, new_sock_len;
779         RES_STAT *s;
780         CONN_ID idx;
781         CLIENT *c;
782         POINTER *ptr;
783         LONG new_size;
784
785         assert( Sock > NONE );
786
787         /* Connection auf Listen-Socket annehmen */
788         new_sock_len = sizeof( new_addr );
789         new_sock = accept( Sock, (struct sockaddr *)&new_addr, (socklen_t *)&new_sock_len );
790         if( new_sock < 0 )
791         {
792                 Log( LOG_CRIT, "Can't accept connection: %s!", strerror( errno ));
793                 return;
794         }
795
796         /* Socket initialisieren */
797         Init_Socket( new_sock );
798
799         /* Freie Connection-Struktur suchen */
800         for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
801         if( idx >= Pool_Size )
802         {
803                 new_size = Pool_Size + CONNECTION_POOL;
804                 
805                 /* Im bisherigen Pool wurde keine freie Connection-Struktur mehr gefunden.
806                  * Wenn erlaubt und moeglich muss nun der Pool vergroessert werden: */
807                 
808                 if( Conf_MaxConnections > 0 )
809                 {
810                         /* Es ist ein Limit konfiguriert */
811                         if( Pool_Size >= Conf_MaxConnections )
812                         {
813                                 /* Mehr Verbindungen duerfen wir leider nicht mehr annehmen ... */
814                                 Log( LOG_ALERT, "Can't accept connection: limit (%d) reached!", Pool_Size );
815                                 close( new_sock );
816                                 return;
817                         }
818                         if( new_size > Conf_MaxConnections ) new_size = Conf_MaxConnections;
819                 }
820                 if( new_size < Pool_Size )
821                 {
822                         Log( LOG_ALERT, "Can't accespt connection: limit (%d) reached -- overflow!", Pool_Size );
823                         close( new_sock );
824                         return;
825                 }
826                 
827                 /* zunaechst realloc() versuchen; wenn das scheitert, malloc() versuchen
828                  * und Daten ggf. "haendisch" umkopieren. (Haesslich! Eine wirklich
829                  * dynamische Verwaltung waere wohl _deutlich_ besser ...) */
830                 ptr = realloc( My_Connections, sizeof( CONNECTION ) * new_size );
831                 if( ! ptr )
832                 {
833                         /* realloc() ist fehlgeschlagen. Nun malloc() probieren: */
834                         ptr = malloc( sizeof( CONNECTION ) * new_size );
835                         if( ! ptr )
836                         {
837                                 /* Offenbar steht kein weiterer Sepeicher zur Verfuegung :-( */
838                                 Log( LOG_EMERG, "Can't allocate memory! [New_Connection]" );
839                                 close( new_sock );
840                                 return;
841                         }
842                         
843                         /* Struktur umkopieren ... */
844                         memcpy( ptr, My_Connections, sizeof( CONNECTION ) * Pool_Size );
845                         
846                         Log( LOG_DEBUG, "Allocated new connection pool for %ld items (%ld bytes). [malloc()/memcpy()]", new_size, sizeof( CONNECTION ) * new_size );
847                 }
848                 else Log( LOG_DEBUG, "Allocated new connection pool for %ld items (%ld bytes). [realloc()]", new_size, sizeof( CONNECTION ) * new_size );
849                 
850                 /* Adjust pointer to new block */
851                 My_Connections = ptr;
852                 
853                 /* Initialize new items */
854                 for( idx = Pool_Size; idx < new_size; idx++ ) Init_Conn_Struct( idx );
855                 idx = Pool_Size;
856                 
857                 /* Adjust new pool size */
858                 Pool_Size = new_size;
859         }
860
861         /* Client-Struktur initialisieren */
862         c = Client_NewLocal( idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWN, FALSE );
863         if( ! c )
864         {
865                 Log( LOG_ALERT, "Can't accept connection: can't create client structure!" );
866                 close( new_sock );
867                 return;
868         }
869
870         /* Verbindung registrieren */
871         Init_Conn_Struct( idx );
872         My_Connections[idx].sock = new_sock;
873         My_Connections[idx].addr = new_addr;
874
875         /* Neuen Socket registrieren */
876         FD_SET( new_sock, &My_Sockets );
877         if( new_sock > Conn_MaxFD ) Conn_MaxFD = new_sock;
878
879         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 );
880
881         /* Hostnamen ermitteln */
882         strlcpy( My_Connections[idx].host, inet_ntoa( new_addr.sin_addr ), sizeof( My_Connections[idx].host ));
883         Client_SetHostname( c, My_Connections[idx].host );
884         s = Resolve_Addr( &new_addr );
885         if( s )
886         {
887                 /* Sub-Prozess wurde asyncron gestartet */
888                 My_Connections[idx].res_stat = s;
889         }
890         
891         /* Penalty-Zeit setzen */
892         Conn_SetPenalty( idx, 4 );
893 } /* New_Connection */
894
895
896 LOCAL CONN_ID
897 Socket2Index( INT Sock )
898 {
899         /* zum Socket passende Connection suchen */
900
901         CONN_ID idx;
902
903         assert( Sock > NONE );
904
905         for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == Sock ) break;
906
907         if( idx >= Pool_Size )
908         {
909                 /* die Connection wurde vermutlich (wegen eines
910                  * Fehlers) bereits wieder abgebaut ... */
911                 Log( LOG_DEBUG, "Socket2Index: can't get connection for socket %d!", Sock );
912                 return NONE;
913         }
914         else return idx;
915 } /* Socket2Index */
916
917
918 LOCAL VOID
919 Read_Request( CONN_ID Idx )
920 {
921         /* Daten von Socket einlesen und entsprechend behandeln.
922          * Tritt ein Fehler auf, so wird der Socket geschlossen. */
923
924         INT len, bsize;
925 #ifdef USE_ZLIB
926         CLIENT *c;
927 #endif
928
929         assert( Idx > NONE );
930         assert( My_Connections[Idx].sock > NONE );
931
932         /* wenn noch nicht registriert: maximal mit ZREADBUFFER_LEN arbeiten,
933          * ansonsten koennen Daten ggf. nicht umkopiert werden. */
934         bsize = READBUFFER_LEN;
935 #ifdef USE_ZLIB
936         c = Client_GetFromConn( Idx );
937         if(( Client_Type( c ) != CLIENT_USER ) && ( Client_Type( c ) != CLIENT_SERVER ) && ( Client_Type( c ) != CLIENT_SERVICE ) && ( bsize > ZREADBUFFER_LEN )) bsize = ZREADBUFFER_LEN;
938 #endif
939
940 #ifdef USE_ZLIB
941         if(( bsize - My_Connections[Idx].rdatalen - 1 < 1 ) || ( ZREADBUFFER_LEN - My_Connections[Idx].zip.rdatalen < 1 ))
942 #else
943         if( bsize - My_Connections[Idx].rdatalen - 1 < 1 )
944 #endif
945         {
946                 /* Der Lesepuffer ist voll */
947                 Log( LOG_ERR, "Read buffer overflow (connection %d): %d bytes!", Idx, My_Connections[Idx].rdatalen );
948                 Conn_Close( Idx, "Read buffer overflow!", NULL, FALSE );
949                 return;
950         }
951
952 #ifdef USE_ZLIB
953         if( My_Connections[Idx].options & CONN_ZIP )
954         {
955                 len = recv( My_Connections[Idx].sock, My_Connections[Idx].zip.rbuf + My_Connections[Idx].zip.rdatalen, ( ZREADBUFFER_LEN - My_Connections[Idx].zip.rdatalen ), 0 );
956                 if( len > 0 ) My_Connections[Idx].zip.rdatalen += len;
957         }
958         else
959 #endif
960         {
961                 len = recv( My_Connections[Idx].sock, My_Connections[Idx].rbuf + My_Connections[Idx].rdatalen, bsize - My_Connections[Idx].rdatalen - 1, 0 );
962                 if( len > 0 ) My_Connections[Idx].rdatalen += len;
963         }
964
965         if( len == 0 )
966         {
967                 /* Socket wurde geschlossen */
968                 Log( LOG_INFO, "%s:%d (%s) is closing the connection ...", My_Connections[Idx].host, ntohs( My_Connections[Idx].addr.sin_port), inet_ntoa( My_Connections[Idx].addr.sin_addr ));
969                 Conn_Close( Idx, "Socket closed!", "Client closed connection", FALSE );
970                 return;
971         }
972
973         if( len < 0 )
974         {
975                 /* Operation haette Socket "nur" blockiert ... */
976                 if( errno == EAGAIN ) return;
977
978                 /* Fehler beim Lesen */
979                 Log( LOG_ERR, "Read error on connection %d (socket %d): %s!", Idx, My_Connections[Idx].sock, strerror( errno ));
980                 Conn_Close( Idx, "Read error!", "Client closed connection", FALSE );
981                 return;
982         }
983
984         /* Connection-Statistik aktualisieren */
985         My_Connections[Idx].bytes_in += len;
986
987         /* Timestamp aktualisieren */
988         My_Connections[Idx].lastdata = time( NULL );
989
990         Handle_Buffer( Idx );
991 } /* Read_Request */
992
993
994 LOCAL BOOLEAN
995 Handle_Buffer( CONN_ID Idx )
996 {
997         /* Daten im Lese-Puffer einer Verbindung verarbeiten.
998          * Wurde ein Request verarbeitet, so wird TRUE geliefert,
999          * ansonsten FALSE (auch bei Fehlern). */
1000
1001 #ifndef STRICT_RFC
1002         CHAR *ptr1, *ptr2;
1003 #endif
1004         CHAR *ptr;
1005         INT len, delta;
1006         BOOLEAN action, result;
1007 #ifdef USE_ZLIB
1008         BOOLEAN old_z;
1009 #endif
1010
1011         result = FALSE;
1012         do
1013         {
1014 #ifdef USE_ZLIB
1015                 /* ggf. noch unkomprimiete Daten weiter entpacken */
1016                 if( My_Connections[Idx].options & CONN_ZIP )
1017                 {
1018                         if( ! Unzip_Buffer( Idx )) return FALSE;
1019                 }
1020 #endif
1021         
1022                 if( My_Connections[Idx].rdatalen < 1 ) break;
1023
1024                 /* Eine komplette Anfrage muss mit CR+LF enden, vgl.
1025                  * RFC 2812. Haben wir eine? */
1026                 My_Connections[Idx].rbuf[My_Connections[Idx].rdatalen] = '\0';
1027                 ptr = strstr( My_Connections[Idx].rbuf, "\r\n" );
1028         
1029                 if( ptr ) delta = 2;
1030 #ifndef STRICT_RFC
1031                 else
1032                 {
1033                         /* Nicht RFC-konforme Anfrage mit nur CR oder LF? Leider
1034                          * machen soetwas viele Clients, u.a. "mIRC" :-( */
1035                         ptr1 = strchr( My_Connections[Idx].rbuf, '\r' );
1036                         ptr2 = strchr( My_Connections[Idx].rbuf, '\n' );
1037                         delta = 1;
1038                         if( ptr1 && ptr2 ) ptr = ptr1 > ptr2 ? ptr2 : ptr1;
1039                         else if( ptr1 ) ptr = ptr1;
1040                         else if( ptr2 ) ptr = ptr2;
1041                 }
1042 #endif
1043         
1044                 action = FALSE;
1045                 if( ptr )
1046                 {
1047                         /* Ende der Anfrage wurde gefunden */
1048                         *ptr = '\0';
1049                         len = ( ptr - My_Connections[Idx].rbuf ) + delta;
1050                         if( len > ( COMMAND_LEN - 1 ))
1051                         {
1052                                 /* Eine Anfrage darf(!) nicht laenger als 512 Zeichen
1053                                  * (incl. CR+LF!) werden; vgl. RFC 2812. Wenn soetwas
1054                                  * empfangen wird, wird der Client disconnectiert. */
1055                                 Log( LOG_ERR, "Request too long (connection %d): %d bytes (max. %d expected)!", Idx, My_Connections[Idx].rdatalen, COMMAND_LEN - 1 );
1056                                 Conn_Close( Idx, NULL, "Request too long", TRUE );
1057                                 return FALSE;
1058                         }
1059
1060 #ifdef USE_ZLIB
1061                         /* merken, ob Stream bereits komprimiert wird */
1062                         old_z = My_Connections[Idx].options & CONN_ZIP;
1063 #endif
1064
1065                         if( len > delta )
1066                         {
1067                                 /* Es wurde ein Request gelesen */
1068                                 My_Connections[Idx].msg_in++;
1069                                 if( ! Parse_Request( Idx, My_Connections[Idx].rbuf )) return FALSE;
1070                                 else action = TRUE;
1071                         }
1072
1073                         /* Puffer anpassen */
1074                         My_Connections[Idx].rdatalen -= len;
1075                         memmove( My_Connections[Idx].rbuf, My_Connections[Idx].rbuf + len, My_Connections[Idx].rdatalen );
1076
1077 #ifdef USE_ZLIB
1078                         if(( ! old_z ) && ( My_Connections[Idx].options & CONN_ZIP ) && ( My_Connections[Idx].rdatalen > 0 ))
1079                         {
1080                                 /* Mit dem letzten Befehl wurde Socket-Kompression aktiviert.
1081                                  * Evtl. schon vom Socket gelesene Daten in den Unzip-Puffer
1082                                  * umkopieren, damit diese nun zunaechst entkomprimiert werden */
1083                                 {
1084                                         if( My_Connections[Idx].rdatalen > ZREADBUFFER_LEN )
1085                                         {
1086                                                 /* Hupsa! Soviel Platz haben wir aber gar nicht! */
1087                                                 Log( LOG_ALERT, "Can't move read buffer: No space left in unzip buffer (need %d bytes)!", My_Connections[Idx].rdatalen );
1088                                                 return FALSE;
1089                                         }
1090                                         memcpy( My_Connections[Idx].zip.rbuf, My_Connections[Idx].rbuf, My_Connections[Idx].rdatalen );
1091                                         My_Connections[Idx].zip.rdatalen = My_Connections[Idx].rdatalen;
1092                                         My_Connections[Idx].rdatalen = 0;
1093                                         Log( LOG_DEBUG, "Moved already received data (%d bytes) to uncompression buffer.", My_Connections[Idx].zip.rdatalen );
1094                                 }
1095                         }
1096 #endif
1097                 }
1098                 
1099                 if( action ) result = TRUE;
1100         } while( action );
1101         
1102         return result;
1103 } /* Handle_Buffer */
1104
1105
1106 LOCAL VOID
1107 Check_Connections( VOID )
1108 {
1109         /* Pruefen, ob Verbindungen noch "alive" sind. Ist dies
1110          * nicht der Fall, zunaechst PING-PONG spielen und, wenn
1111          * auch das nicht "hilft", Client disconnectieren. */
1112
1113         CLIENT *c;
1114         CONN_ID i;
1115
1116         for( i = 0; i < Pool_Size; i++ )
1117         {
1118                 if( My_Connections[i].sock == NONE ) continue;
1119
1120                 c = Client_GetFromConn( i );
1121                 if( c && (( Client_Type( c ) == CLIENT_USER ) || ( Client_Type( c ) == CLIENT_SERVER ) || ( Client_Type( c ) == CLIENT_SERVICE )))
1122                 {
1123                         /* verbundener User, Server oder Service */
1124                         if( My_Connections[i].lastping > My_Connections[i].lastdata )
1125                         {
1126                                 /* es wurde bereits ein PING gesendet */
1127                                 if( My_Connections[i].lastping < time( NULL ) - Conf_PongTimeout )
1128                                 {
1129                                         /* Timeout */
1130                                         Log( LOG_DEBUG, "Connection %d: Ping timeout: %d seconds.", i, Conf_PongTimeout );
1131                                         Conn_Close( i, NULL, "Ping timeout", TRUE );
1132                                 }
1133                         }
1134                         else if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout )
1135                         {
1136                                 /* es muss ein PING gesendet werden */
1137                                 Log( LOG_DEBUG, "Connection %d: sending PING ...", i );
1138                                 My_Connections[i].lastping = time( NULL );
1139                                 Conn_WriteStr( i, "PING :%s", Client_ID( Client_ThisServer( )));
1140                         }
1141                 }
1142                 else
1143                 {
1144                         /* noch nicht vollstaendig aufgebaute Verbindung */
1145                         if( My_Connections[i].lastdata < time( NULL ) - Conf_PingTimeout )
1146                         {
1147                                 /* Timeout */
1148                                 Log( LOG_DEBUG, "Connection %d timed out ...", i );
1149                                 Conn_Close( i, NULL, "Timeout", FALSE );
1150                         }
1151                 }
1152         }
1153 } /* Check_Connections */
1154
1155
1156 LOCAL VOID
1157 Check_Servers( VOID )
1158 {
1159         /* Check if we can establish further server links */
1160
1161         RES_STAT *s;
1162         CONN_ID idx;
1163         INT i, n;
1164
1165         /* Don't connect in "passive mode" */
1166         if( NGIRCd_Passive ) return;
1167
1168         /* Serach all connections, are there results from the resolver? */
1169         for( idx = 0; idx < Pool_Size; idx++ )
1170         {
1171                 if( My_Connections[idx].sock != SERVER_WAIT ) continue;
1172
1173                 /* IP resolved? */
1174                 if( My_Connections[idx].res_stat == NULL ) New_Server( Conf_GetServer( idx ), idx );
1175         }
1176
1177         /* Check all configured servers */
1178         for( i = 0; i < MAX_SERVERS; i++ )
1179         {
1180                 /* Valid outgoing server which isn't already connected? */
1181                 if(( ! Conf_Server[i].host[0] ) || ( ! Conf_Server[i].port > 0 ) || ( Conf_Server[i].conn_id > NONE )) continue;
1182
1183                 /* Is there already a connection in this group? */
1184                 if( Conf_Server[i].group > NONE )
1185                 {
1186                         for( n = 0; n < MAX_SERVERS; n++ )
1187                         {
1188                                 if( n == i ) continue;
1189                                 if(( Conf_Server[n].conn_id > NONE ) && ( Conf_Server[n].group == Conf_Server[i].group )) break;
1190                         }
1191                         if( n < MAX_SERVERS ) continue;
1192                 }
1193
1194                 /* Check last connect attempt? */
1195                 if( Conf_Server[i].lasttry > time( NULL ) - Conf_ConnectRetry ) continue;
1196
1197                 /* Okay, try to connect now */
1198                 Conf_Server[i].lasttry = time( NULL );
1199
1200                 /* Search free connection structure */
1201                 for( idx = 0; idx < Pool_Size; idx++ ) if( My_Connections[idx].sock == NONE ) break;
1202                 if( idx >= Pool_Size )
1203                 {
1204                         Log( LOG_ALERT, "Can't establist server connection: connection limit reached (%d)!", Pool_Size );
1205                         return;
1206                 }
1207                 Log( LOG_DEBUG, "Preparing connection %d for \"%s\" ...", idx, Conf_Server[i].host );
1208
1209                 /* Verbindungs-Struktur initialisieren */
1210                 Init_Conn_Struct( idx );
1211                 My_Connections[idx].sock = SERVER_WAIT;
1212                 Conf_Server[i].conn_id = idx;
1213
1214                 /* Resolve Hostname. If this fails, try to use it as an IP address */
1215                 strlcpy( Conf_Server[i].ip, Conf_Server[i].host, sizeof( Conf_Server[i].ip ));
1216                 strlcpy( My_Connections[idx].host, Conf_Server[i].host, sizeof( My_Connections[idx].host ));
1217                 s = Resolve_Name( Conf_Server[i].host );
1218                 if( s )
1219                 {
1220                         /* Sub-Prozess wurde asyncron gestartet */
1221                         My_Connections[idx].res_stat = s;
1222                 }
1223         }
1224 } /* Check_Servers */
1225
1226
1227 LOCAL VOID
1228 New_Server( INT Server, CONN_ID Idx )
1229 {
1230         /* Neue Server-Verbindung aufbauen */
1231
1232         struct sockaddr_in new_addr;
1233         struct in_addr inaddr;
1234         INT res, new_sock;
1235         CLIENT *c;
1236
1237         assert( Server > NONE );
1238         assert( Idx > NONE );
1239
1240         /* Wurde eine gueltige IP-Adresse gefunden? */
1241         if( ! Conf_Server[Server].ip[0] )
1242         {
1243                 /* Nein. Verbindung wieder freigeben: */
1244                 Init_Conn_Struct( Idx );
1245                 Log( LOG_ERR, "Can't connect to \"%s\" (connection %d): ip address unknown!", Conf_Server[Server].host, Idx );
1246                 return;
1247         }
1248
1249         Log( LOG_INFO, "Establishing connection to \"%s\", %s, port %d (connection %d) ... ", Conf_Server[Server].host, Conf_Server[Server].ip, Conf_Server[Server].port, Idx );
1250
1251 #ifdef HAVE_INET_ATON
1252         if( inet_aton( Conf_Server[Server].ip, &inaddr ) == 0 )
1253 #else
1254         memset( &inaddr, 0, sizeof( inaddr ));
1255         inaddr.s_addr = inet_addr( Conf_Server[Server].ip );
1256         if( inaddr.s_addr == (unsigned)-1 )
1257 #endif
1258         {
1259                 /* Konnte Adresse nicht konvertieren */
1260                 Init_Conn_Struct( Idx );
1261                 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 );
1262                 return;
1263         }
1264
1265         memset( &new_addr, 0, sizeof( new_addr ));
1266         new_addr.sin_family = AF_INET;
1267         new_addr.sin_addr = inaddr;
1268         new_addr.sin_port = htons( Conf_Server[Server].port );
1269
1270         new_sock = socket( PF_INET, SOCK_STREAM, 0 );
1271         if ( new_sock < 0 )
1272         {
1273                 Init_Conn_Struct( Idx );
1274                 Log( LOG_CRIT, "Can't create socket: %s!", strerror( errno ));
1275                 return;
1276         }
1277
1278         if( ! Init_Socket( new_sock )) return;
1279
1280         res = connect( new_sock, (struct sockaddr *)&new_addr, sizeof( new_addr ));
1281         if(( res != 0 ) && ( errno != EINPROGRESS ))
1282         {
1283                 Log( LOG_CRIT, "Can't connect socket: %s!", strerror( errno ));
1284                 close( new_sock );
1285                 Init_Conn_Struct( Idx );
1286                 return;
1287         }
1288
1289         /* Client-Struktur initialisieren */
1290         c = Client_NewLocal( Idx, inet_ntoa( new_addr.sin_addr ), CLIENT_UNKNOWNSERVER, FALSE );
1291         if( ! c )
1292         {
1293                 close( new_sock );
1294                 Init_Conn_Struct( Idx );
1295                 Log( LOG_ALERT, "Can't establish connection: can't create client structure!" );
1296                 return;
1297         }
1298         Client_SetIntroducer( c, c );
1299         Client_SetToken( c, TOKEN_OUTBOUND );
1300
1301         /* Verbindung registrieren */
1302         My_Connections[Idx].sock = new_sock;
1303         My_Connections[Idx].addr = new_addr;
1304         strlcpy( My_Connections[Idx].host, Conf_Server[Server].host, sizeof( My_Connections[Idx].host ));
1305
1306         /* Neuen Socket registrieren */
1307         FD_SET( new_sock, &My_Sockets );
1308         FD_SET( new_sock, &My_Connects );
1309         if( new_sock > Conn_MaxFD ) Conn_MaxFD = new_sock;
1310         
1311         Log( LOG_DEBUG, "Registered new connection %d on socket %d.", Idx, My_Connections[Idx].sock );
1312 } /* New_Server */
1313
1314
1315 LOCAL VOID
1316 Init_Conn_Struct( CONN_ID Idx )
1317 {
1318         /* Connection-Struktur initialisieren */
1319
1320         My_Connections[Idx].sock = NONE;
1321         My_Connections[Idx].res_stat = NULL;
1322         My_Connections[Idx].host[0] = '\0';
1323         My_Connections[Idx].rbuf[0] = '\0';
1324         My_Connections[Idx].rdatalen = 0;
1325         My_Connections[Idx].wbuf[0] = '\0';
1326         My_Connections[Idx].wdatalen = 0;
1327         My_Connections[Idx].starttime = time( NULL );
1328         My_Connections[Idx].lastdata = time( NULL );
1329         My_Connections[Idx].lastping = 0;
1330         My_Connections[Idx].lastprivmsg = time( NULL );
1331         My_Connections[Idx].delaytime = 0;
1332         My_Connections[Idx].bytes_in = 0;
1333         My_Connections[Idx].bytes_out = 0;
1334         My_Connections[Idx].msg_in = 0;
1335         My_Connections[Idx].msg_out = 0;
1336         My_Connections[Idx].flag = 0;
1337         My_Connections[Idx].options = 0;
1338
1339 #ifdef USE_ZLIB
1340         My_Connections[Idx].zip.rbuf[0] = '\0';
1341         My_Connections[Idx].zip.rdatalen = 0;
1342         My_Connections[Idx].zip.wbuf[0] = '\0';
1343         My_Connections[Idx].zip.wdatalen = 0;
1344         My_Connections[Idx].zip.bytes_in = 0;
1345         My_Connections[Idx].zip.bytes_out = 0;
1346 #endif
1347 } /* Init_Conn_Struct */
1348
1349
1350 LOCAL BOOLEAN
1351 Init_Socket( INT Sock )
1352 {
1353         /* Socket-Optionen setzen */
1354
1355         INT on = 1;
1356
1357 #ifdef O_NONBLOCK       /* A/UX kennt das nicht? */
1358         if( fcntl( Sock, F_SETFL, O_NONBLOCK ) != 0 )
1359         {
1360                 Log( LOG_CRIT, "Can't enable non-blocking mode: %s!", strerror( errno ));
1361                 close( Sock );
1362                 return FALSE;
1363         }
1364 #endif
1365         if( setsockopt( Sock, SOL_SOCKET, SO_REUSEADDR, &on, (socklen_t)sizeof( on )) != 0)
1366         {
1367                 Log( LOG_ERR, "Can't set socket options: %s!", strerror( errno ));
1368                 /* dieser Fehler kann ignoriert werden. */
1369         }
1370
1371         return TRUE;
1372 } /* Init_Socket */
1373
1374
1375 LOCAL VOID
1376 Read_Resolver_Result( INT r_fd )
1377 {
1378         /* Ergebnis von Resolver Sub-Prozess aus Pipe lesen
1379          * und entsprechende Connection aktualisieren */
1380
1381         CHAR result[HOST_LEN];
1382         CLIENT *c;
1383         INT len, i, n;
1384
1385         FD_CLR( r_fd, &Resolver_FDs );
1386
1387         /* Anfrage vom Parent lesen */
1388         len = read( r_fd, result, HOST_LEN - 1 );
1389         if( len < 0 )
1390         {
1391                 /* Fehler beim Lesen aus der Pipe */
1392                 close( r_fd );
1393                 Log( LOG_CRIT, "Resolver: Can't read result: %s!", strerror( errno ));
1394                 return;
1395         }
1396         result[len] = '\0';
1397
1398         /* zugehoerige Connection suchen */
1399         for( i = 0; i < Pool_Size; i++ )
1400         {
1401                 if(( My_Connections[i].sock != NONE ) && ( My_Connections[i].res_stat ) && ( My_Connections[i].res_stat->pipe[0] == r_fd )) break;
1402         }
1403         if( i >= Pool_Size )
1404         {
1405                 /* Opsa! Keine passende Connection gefunden!? Vermutlich
1406                  * wurde sie schon wieder geschlossen. */
1407                 close( r_fd );
1408                 Log( LOG_DEBUG, "Resolver: Got result for unknown connection!?" );
1409                 return;
1410         }
1411
1412         Log( LOG_DEBUG, "Resolver: %s is \"%s\".", My_Connections[i].host, result );
1413         
1414         /* Aufraeumen */
1415         close( My_Connections[i].res_stat->pipe[0] );
1416         close( My_Connections[i].res_stat->pipe[1] );
1417         free( My_Connections[i].res_stat );
1418         My_Connections[i].res_stat = NULL;
1419
1420         if( My_Connections[i].sock > NONE )
1421         {
1422                 /* Eingehende Verbindung: Hostnamen setzen */
1423                 c = Client_GetFromConn( i );
1424                 assert( c != NULL );
1425                 strlcpy( My_Connections[i].host, result, sizeof( My_Connections[i].host ));
1426                 Client_SetHostname( c, result );
1427         }
1428         else
1429         {
1430                 /* Ausgehende Verbindung (=Server): IP setzen */
1431                 n = Conf_GetServer( i );
1432                 if( n > NONE ) strlcpy( Conf_Server[n].ip, result, sizeof( Conf_Server[n].ip ));
1433                 else Log( LOG_ERR, "Got resolver result for non-configured server!?" );
1434         }
1435
1436         /* Penalty-Zeit zurueck setzen */
1437         Conn_ResetPenalty( i );
1438 } /* Read_Resolver_Result */
1439
1440
1441 /* -eof- */