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