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