conf: move 'run-time-feature-disable' options to new FEATURE section
[ngircd-alex.git] / src / ngircd / conf.c
1 /*
2  * ngIRCd -- The Next Generation IRC Daemon
3  * Copyright (c)2001-2010 Alexander Barton (alex@barton.de)
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  * Please read the file COPYING, README and AUTHORS for more information.
10  *
11  * Configuration management (reading, parsing & validation)
12  */
13
14
15 #include "portab.h"
16
17 #include "imp.h"
18 #include <assert.h>
19 #include <errno.h>
20 #ifdef PROTOTYPES
21 #       include <stdarg.h>
22 #else
23 #       include <varargs.h>
24 #endif
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <strings.h>
29 #include <unistd.h>
30 #include <pwd.h>
31 #include <grp.h>
32 #include <sys/types.h>
33 #include <unistd.h>
34
35 #ifdef HAVE_CTYPE_H
36 # include <ctype.h>
37 #endif
38
39 #include "array.h"
40 #include "ngircd.h"
41 #include "conn.h"
42 #include "channel.h"
43 #include "defines.h"
44 #include "log.h"
45 #include "match.h"
46 #include "tool.h"
47
48 #include "exp.h"
49 #include "conf.h"
50
51
52 static bool Use_Log = true, Using_MotdFile = true;
53 static CONF_SERVER New_Server;
54 static int New_Server_Idx;
55
56 static size_t Conf_Oper_Count;
57 static size_t Conf_Channel_Count;
58 static char Conf_MotdFile[FNAME_LEN];
59
60 static void Set_Defaults PARAMS(( bool InitServers ));
61 static bool Read_Config PARAMS(( bool ngircd_starting ));
62 static bool Validate_Config PARAMS(( bool TestOnly, bool Rehash ));
63
64 static void Handle_GLOBAL PARAMS(( int Line, char *Var, char *Arg ));
65 static void Handle_FEATURES PARAMS(( int Line, char *Var, char *Arg ));
66 static void Handle_OPERATOR PARAMS(( int Line, char *Var, char *Arg ));
67 static void Handle_SERVER PARAMS(( int Line, char *Var, char *Arg ));
68 static void Handle_CHANNEL PARAMS(( int Line, char *Var, char *Arg ));
69
70 static void Config_Error PARAMS(( const int Level, const char *Format, ... ));
71
72 static void Config_Error_NaN PARAMS(( const int LINE, const char *Value ));
73 static void Config_Error_TooLong PARAMS(( const int LINE, const char *Value ));
74
75 static void Init_Server_Struct PARAMS(( CONF_SERVER *Server ));
76
77 #ifdef WANT_IPV6
78 #define DEFAULT_LISTEN_ADDRSTR "::,0.0.0.0"
79 #else
80 #define DEFAULT_LISTEN_ADDRSTR "0.0.0.0"
81 #endif
82
83 #ifdef SSL_SUPPORT
84 struct SSLOptions Conf_SSLOptions;
85
86 static void
87 ConfSSL_Init(void)
88 {
89         free(Conf_SSLOptions.KeyFile);
90         Conf_SSLOptions.KeyFile = NULL;
91
92         free(Conf_SSLOptions.CertFile);
93         Conf_SSLOptions.CertFile = NULL;
94
95         free(Conf_SSLOptions.DHFile);
96         Conf_SSLOptions.DHFile = NULL;
97         array_free_wipe(&Conf_SSLOptions.KeyFilePassword);
98 }
99
100 static bool
101 ssl_print_configvar(const char *name, const char *file)
102 {
103         FILE *fp;
104
105         if (!file) {
106                 printf("  %s =\n", name);
107                 return true;
108         }
109
110         fp = fopen(file, "r");
111         if (fp)
112                 fclose(fp);
113         else
114                 fprintf(stderr, "ERROR: %s \"%s\": %s\n",
115                         name, file, strerror(errno));
116
117         printf("  %s = %s\n", name, file);
118         return fp != NULL;
119 }
120
121 static bool
122 ConfSSL_Puts(void)
123 {
124         bool ret;
125
126         ret = ssl_print_configvar("SSLKeyFile", Conf_SSLOptions.KeyFile);
127
128         if (!ssl_print_configvar("SSLCertFile", Conf_SSLOptions.CertFile))
129                 ret = false;
130
131         if (!ssl_print_configvar("SSLDHFile", Conf_SSLOptions.DHFile))
132                 ret = false;
133
134         if (array_bytes(&Conf_SSLOptions.KeyFilePassword))
135                 puts("  SSLKeyFilePassword = <secret>");
136
137         array_free_wipe(&Conf_SSLOptions.KeyFilePassword);
138
139         return ret;
140 }
141 #endif
142
143 static char *
144 strdup_warn(const char *str)
145 {
146         char *ptr = strdup(str);
147         if (!ptr)
148                 Config_Error(LOG_ERR, "Could not allocate mem for string: %s", str);
149         return ptr;
150 }
151
152
153 static void
154 ports_puts(array *a)
155 {
156         size_t len;
157         UINT16 *ports;
158         len = array_length(a, sizeof(UINT16));
159         if (len--) {
160                 ports = (UINT16*) array_start(a);
161                 printf("%u", (unsigned int) *ports);
162                 while (len--) {
163                         ports++;
164                         printf(", %u", (unsigned int) *ports);
165                 }
166         }
167         putc('\n', stdout);
168 }
169
170
171 static void
172 ports_parse(array *a, int Line, char *Arg)
173 {
174         char *ptr;
175         int port;
176         UINT16 port16;
177
178         array_trunc(a);
179
180         /* Ports on that the server should listen. More port numbers
181          * must be separated by "," */
182         ptr = strtok( Arg, "," );
183         while (ptr) {
184                 ngt_TrimStr(ptr);
185                 port = atoi(ptr);
186                 if (port > 0 && port < 0xFFFF) {
187                         port16 = (UINT16) port;
188                         if (!array_catb(a, (char*)&port16, sizeof port16))
189                                 Config_Error(LOG_ERR, "%s, line %d Could not add port number %ld: %s",
190                                                         NGIRCd_ConfFile, Line, port, strerror(errno));
191                 } else {
192                         Config_Error( LOG_ERR, "%s, line %d (section \"Global\"): Illegal port number %ld!",
193                                                                         NGIRCd_ConfFile, Line, port );
194                 }
195
196                 ptr = strtok( NULL, "," );
197         }
198 }
199
200
201 GLOBAL void
202 Conf_Init( void )
203 {
204         Read_Config( true );
205         Validate_Config(false, false);
206 } /* Config_Init */
207
208
209 GLOBAL bool
210 Conf_Rehash( void )
211 {
212         if (!Read_Config(false))
213                 return false;
214         Validate_Config(false, true);
215
216         /* Update CLIENT structure of local server */
217         Client_SetInfo(Client_ThisServer(), Conf_ServerInfo);
218         return true;
219 } /* Config_Rehash */
220
221
222 static const char*
223 yesno_to_str(int boolean_value)
224 {
225         if (boolean_value)
226                 return "yes";
227         return "no";
228 }
229
230
231 static void
232 opers_free(void)
233 {
234         struct Conf_Oper *op;
235         size_t len;
236
237         len = array_length(&Conf_Opers, sizeof(*op));
238         op = array_start(&Conf_Opers);
239         while (len--) {
240                 free(op->mask);
241                 op++;
242         }
243         array_free(&Conf_Opers);
244 }
245
246 static void
247 opers_puts(void)
248 {
249         struct Conf_Oper *op;
250         size_t len;
251
252         len = array_length(&Conf_Opers, sizeof(*op));
253         op = array_start(&Conf_Opers);
254         while (len--) {
255                 assert(op->name[0]);
256
257                 puts("[OPERATOR]");
258                 printf("  Name = %s\n", op->name);
259                 printf("  Password = %s\n", op->pwd);
260                 printf("  Mask = %s\n\n", op->mask ? op->mask : "");
261                 op++;
262         }
263 }
264
265
266 GLOBAL int
267 Conf_Test( void )
268 {
269         /* Read configuration, validate and output it. */
270
271         struct passwd *pwd;
272         struct group *grp;
273         unsigned int i;
274         bool config_valid;
275         size_t predef_channel_count;
276         struct Conf_Channel *predef_chan;
277
278         Use_Log = false;
279
280         if (! Read_Config(true))
281                 return 1;
282
283         config_valid = Validate_Config(true, false);
284
285         /* If stdin and stdout ("you can read our nice message and we can
286          * read in your keypress") are valid tty's, wait for a key: */
287         if( isatty( fileno( stdin )) && isatty( fileno( stdout ))) {
288                 puts( "OK, press enter to see a dump of your service configuration ..." );
289                 getchar( );
290         } else {
291                 puts( "Ok, dump of your server configuration follows:\n" );
292         }
293
294         puts( "[GLOBAL]" );
295         printf("  Name = %s\n", Conf_ServerName);
296         printf("  Info = %s\n", Conf_ServerInfo);
297 #ifndef PAM
298         printf("  Password = %s\n", Conf_ServerPwd);
299 #endif
300         printf("  WebircPassword = %s\n", Conf_WebircPwd);
301         printf("  AdminInfo1 = %s\n", Conf_ServerAdmin1);
302         printf("  AdminInfo2 = %s\n", Conf_ServerAdmin2);
303         printf("  AdminEMail = %s\n", Conf_ServerAdminMail);
304         if (Using_MotdFile) {
305                 printf("  MotdFile = %s\n", Conf_MotdFile);
306                 printf("  MotdPhrase =\n");
307         } else {
308                 printf("  MotdFile = \n");
309                 printf("  MotdPhrase = %s\n", array_bytes(&Conf_Motd)
310                        ? (const char*) array_start(&Conf_Motd) : "");
311         }
312         printf("  ChrootDir = %s\n", Conf_Chroot);
313         printf("  PidFile = %s\n", Conf_PidFile);
314         printf("  Listen = %s\n", Conf_ListenAddress);
315         fputs("  Ports = ", stdout);
316         ports_puts(&Conf_ListenPorts);
317 #ifdef SSL_SUPPORT
318         fputs("  SSLPorts = ", stdout);
319         ports_puts(&Conf_SSLOptions.ListenPorts);
320         if (!ConfSSL_Puts())
321                 config_valid = false;
322 #endif
323
324         pwd = getpwuid(Conf_UID);
325         if (pwd)
326                 printf("  ServerUID = %s\n", pwd->pw_name);
327         else
328                 printf("  ServerUID = %ld\n", (long)Conf_UID);
329         grp = getgrgid(Conf_GID);
330         if (grp)
331                 printf("  ServerGID = %s\n", grp->gr_name);
332         else
333                 printf("  ServerGID = %ld\n", (long)Conf_GID);
334 #ifdef SYSLOG
335         printf("  SyslogFacility = %s\n",
336                ngt_SyslogFacilityName(Conf_SyslogFacility));
337 #endif
338         printf("  PingTimeout = %d\n", Conf_PingTimeout);
339         printf("  PongTimeout = %d\n", Conf_PongTimeout);
340         printf("  ConnectRetry = %d\n", Conf_ConnectRetry);
341         printf("  OperCanUseMode = %s\n", yesno_to_str(Conf_OperCanMode));
342         printf("  OperServerMode = %s\n", yesno_to_str(Conf_OperServerMode));
343         printf("  AllowRemoteOper = %s\n", yesno_to_str(Conf_AllowRemoteOper));
344         printf("  PredefChannelsOnly = %s\n", yesno_to_str(Conf_PredefChannelsOnly));
345 #ifdef WANT_IPV6
346         printf("  ConnectIPv4 = %s\n", yesno_to_str(Conf_ConnectIPv6));
347         printf("  ConnectIPv6 = %s\n", yesno_to_str(Conf_ConnectIPv4));
348 #endif
349         printf("  MaxConnections = %ld\n", Conf_MaxConnections);
350         printf("  MaxConnectionsIP = %d\n", Conf_MaxConnectionsIP);
351         printf("  MaxJoins = %d\n", Conf_MaxJoins > 0 ? Conf_MaxJoins : -1);
352         printf("  MaxNickLength = %u\n\n", Conf_MaxNickLength - 1);
353
354         puts("[FEATURES]");
355         printf("  DNS = %s\n", yesno_to_str(Conf_DNS));
356         printf("  Ident = %s\n", yesno_to_str(Conf_Ident));
357         printf("  PAM = %s\n", yesno_to_str(Conf_PAM));
358         printf("  ZeroConf = %s\n", yesno_to_str(Conf_ZeroConf));
359         puts("");
360
361         opers_puts();
362
363         for( i = 0; i < MAX_SERVERS; i++ ) {
364                 if( ! Conf_Server[i].name[0] ) continue;
365
366                 /* Valid "Server" section */
367                 puts( "[SERVER]" );
368                 printf( "  Name = %s\n", Conf_Server[i].name );
369                 printf( "  Host = %s\n", Conf_Server[i].host );
370                 printf( "  Port = %u\n", (unsigned int)Conf_Server[i].port );
371 #ifdef SSL_SUPPORT
372                 printf( "  SSLConnect = %s\n", Conf_Server[i].SSLConnect?"yes":"no");
373 #endif
374                 printf( "  MyPassword = %s\n", Conf_Server[i].pwd_in );
375                 printf( "  PeerPassword = %s\n", Conf_Server[i].pwd_out );
376                 printf( "  ServiceMask = %s\n", Conf_Server[i].svs_mask);
377                 printf( "  Group = %d\n", Conf_Server[i].group );
378                 printf( "  Passive = %s\n\n", Conf_Server[i].flags & CONF_SFLAG_DISABLED ? "yes" : "no");
379         }
380
381         predef_channel_count = array_length(&Conf_Channels, sizeof(*predef_chan));
382         predef_chan = array_start(&Conf_Channels);
383
384         for (i = 0; i < predef_channel_count; i++, predef_chan++) {
385                 if (!predef_chan->name[0])
386                         continue;
387
388                 /* Valid "Channel" section */
389                 puts( "[CHANNEL]" );
390                 printf("  Name = %s\n", predef_chan->name);
391                 printf("  Modes = %s\n", predef_chan->modes);
392                 printf("  Key = %s\n", predef_chan->key);
393                 printf("  MaxUsers = %lu\n", predef_chan->maxusers);
394                 printf("  Topic = %s\n", predef_chan->topic);
395                 printf("  KeyFile = %s\n\n", predef_chan->keyfile);
396         }
397
398         return (config_valid ? 0 : 1);
399 } /* Conf_Test */
400
401
402 GLOBAL void
403 Conf_UnsetServer( CONN_ID Idx )
404 {
405         /* Set next time for next connection attempt, if this is a server
406          * link that is (still) configured here. If the server is set as
407          * "once", delete it from our configuration.
408          * Non-Server-Connections will be silently ignored. */
409
410         int i;
411         time_t t;
412
413         /* Check all our configured servers */
414         for( i = 0; i < MAX_SERVERS; i++ ) {
415                 if( Conf_Server[i].conn_id != Idx ) continue;
416
417                 /* Gotcha! Mark server configuration as "unused": */
418                 Conf_Server[i].conn_id = NONE;
419
420                 if( Conf_Server[i].flags & CONF_SFLAG_ONCE ) {
421                         /* Delete configuration here */
422                         Init_Server_Struct( &Conf_Server[i] );
423                 } else {
424                         /* Set time for next connect attempt */
425                         t = time(NULL);
426                         if (Conf_Server[i].lasttry < t - Conf_ConnectRetry) {
427                                 /* The connection has been "long", so we don't
428                                  * require the next attempt to be delayed. */
429                                 Conf_Server[i].lasttry =
430                                         t - Conf_ConnectRetry + RECONNECT_DELAY;
431                         } else
432                                 Conf_Server[i].lasttry = t;
433                 }
434         }
435 } /* Conf_UnsetServer */
436
437
438 GLOBAL void
439 Conf_SetServer( int ConfServer, CONN_ID Idx )
440 {
441         /* Set connection for specified configured server */
442
443         assert( ConfServer > NONE );
444         assert( Idx > NONE );
445
446         Conf_Server[ConfServer].conn_id = Idx;
447 } /* Conf_SetServer */
448
449
450 GLOBAL int
451 Conf_GetServer( CONN_ID Idx )
452 {
453         /* Get index of server in configuration structure */
454
455         int i = 0;
456
457         assert( Idx > NONE );
458
459         for( i = 0; i < MAX_SERVERS; i++ ) {
460                 if( Conf_Server[i].conn_id == Idx ) return i;
461         }
462         return NONE;
463 } /* Conf_GetServer */
464
465
466 GLOBAL bool
467 Conf_EnableServer( const char *Name, UINT16 Port )
468 {
469         /* Enable specified server and adjust port */
470
471         int i;
472
473         assert( Name != NULL );
474
475         for( i = 0; i < MAX_SERVERS; i++ ) {
476                 if( strcasecmp( Conf_Server[i].name, Name ) == 0 ) {
477                         /* Gotcha! Set port and enable server: */
478                         Conf_Server[i].port = Port;
479                         Conf_Server[i].flags &= ~CONF_SFLAG_DISABLED;
480                         return (Conf_Server[i].port && Conf_Server[i].host[0]);
481                 }
482         }
483         return false;
484 } /* Conf_EnableServer */
485
486
487 GLOBAL bool
488 Conf_EnablePassiveServer(const char *Name)
489 {
490         /* Enable specified server */
491         int i;
492
493         assert( Name != NULL );
494         for (i = 0; i < MAX_SERVERS; i++) {
495                 if ((strcasecmp( Conf_Server[i].name, Name ) == 0) && (Conf_Server[i].port > 0)) {
496                         /* BINGO! Enable server */
497                         Conf_Server[i].flags &= ~CONF_SFLAG_DISABLED;
498                         return true;
499                 }
500         }
501         return false;
502 } /* Conf_EnablePassiveServer */
503
504
505 GLOBAL bool
506 Conf_DisableServer( const char *Name )
507 {
508         /* Enable specified server and adjust port */
509
510         int i;
511
512         assert( Name != NULL );
513
514         for( i = 0; i < MAX_SERVERS; i++ ) {
515                 if( strcasecmp( Conf_Server[i].name, Name ) == 0 ) {
516                         /* Gotcha! Disable and disconnect server: */
517                         Conf_Server[i].flags |= CONF_SFLAG_DISABLED;
518                         if( Conf_Server[i].conn_id > NONE ) Conn_Close( Conf_Server[i].conn_id, NULL, "Server link terminated on operator request", true);
519                         return true;
520                 }
521         }
522         return false;
523 } /* Conf_DisableServer */
524
525
526 GLOBAL bool
527 Conf_AddServer( const char *Name, UINT16 Port, const char *Host, const char *MyPwd, const char *PeerPwd )
528 {
529         /* Add new server to configuration */
530
531         int i;
532
533         assert( Name != NULL );
534         assert( Host != NULL );
535         assert( MyPwd != NULL );
536         assert( PeerPwd != NULL );
537
538         /* Search unused item in server configuration structure */
539         for( i = 0; i < MAX_SERVERS; i++ ) {
540                 /* Is this item used? */
541                 if( ! Conf_Server[i].name[0] ) break;
542         }
543         if( i >= MAX_SERVERS ) return false;
544
545         Init_Server_Struct( &Conf_Server[i] );
546         strlcpy( Conf_Server[i].name, Name, sizeof( Conf_Server[i].name ));
547         strlcpy( Conf_Server[i].host, Host, sizeof( Conf_Server[i].host ));
548         strlcpy( Conf_Server[i].pwd_out, MyPwd, sizeof( Conf_Server[i].pwd_out ));
549         strlcpy( Conf_Server[i].pwd_in, PeerPwd, sizeof( Conf_Server[i].pwd_in ));
550         Conf_Server[i].port = Port;
551         Conf_Server[i].flags = CONF_SFLAG_ONCE;
552
553         return true;
554 } /* Conf_AddServer */
555
556
557 /**
558  * Check if the given nick name is an service
559  */
560 GLOBAL bool
561 Conf_IsService(int ConfServer, const char *Nick)
562 {
563         return MatchCaseInsensitive(Conf_Server[ConfServer].svs_mask, Nick);
564 } /* Conf_IsService */
565
566
567 static void
568 Set_Defaults_Optional(void)
569 {
570 #ifdef IDENTAUTH
571         Conf_Ident = true;
572 #else
573         Conf_Ident = false;
574 #endif
575 #ifdef PAM
576         Conf_PAM = true;
577 #else
578         Conf_PAM = false;
579 #endif
580 #ifdef ZEROCONF
581         Conf_ZeroConf = true;
582 #else
583         Conf_ZeroConf = false;
584 #endif
585 }
586
587
588 /**
589  * Initialize configuration settings with their default values.
590  */
591 static void
592 Set_Defaults(bool InitServers)
593 {
594         int i;
595
596         strcpy(Conf_ServerName, "");
597         snprintf(Conf_ServerInfo, sizeof Conf_ServerInfo, "%s %s",
598                  PACKAGE_NAME, PACKAGE_VERSION);
599         strcpy(Conf_ServerPwd, "");
600
601         strcpy(Conf_ServerAdmin1, "");
602         strcpy(Conf_ServerAdmin2, "");
603         strcpy(Conf_ServerAdminMail, "");
604
605         strlcpy(Conf_MotdFile, SYSCONFDIR, sizeof(Conf_MotdFile));
606         strlcat(Conf_MotdFile, MOTD_FILE, sizeof(Conf_MotdFile));
607
608         Conf_UID = Conf_GID = 0;
609         strlcpy(Conf_Chroot, CHROOT_DIR, sizeof(Conf_Chroot));
610         strlcpy(Conf_PidFile, PID_FILE, sizeof(Conf_PidFile));
611
612         free(Conf_ListenAddress);
613         Conf_ListenAddress = NULL;
614
615         Conf_PingTimeout = 120;
616         Conf_PongTimeout = 20;
617         Conf_ConnectRetry = 60;
618         Conf_DNS = true;
619
620         Conf_Oper_Count = 0;
621         Conf_Channel_Count = 0;
622
623         Conf_OperCanMode = false;
624         Conf_OperServerMode = false;
625         Conf_AllowRemoteOper = false;
626         Conf_PredefChannelsOnly = false;
627
628         Conf_ConnectIPv4 = true;
629         Conf_ConnectIPv6 = true;
630
631         Conf_MaxConnections = 0;
632         Conf_MaxConnectionsIP = 5;
633         Conf_MaxJoins = 10;
634         Conf_MaxNickLength = CLIENT_NICK_LEN_DEFAULT;
635
636 #ifdef SYSLOG
637 #ifdef LOG_LOCAL5
638         Conf_SyslogFacility = LOG_LOCAL5;
639 #else
640         Conf_SyslogFacility = 0;
641 #endif
642 #endif
643         Set_Defaults_Optional();
644
645         /* Initialize server configuration structures */
646         if (InitServers) {
647                 for (i = 0; i < MAX_SERVERS;
648                      Init_Server_Struct(&Conf_Server[i++]));
649         }
650 } /* Set_Defaults */
651
652
653 static bool
654 no_listenports(void)
655 {
656         size_t cnt = array_bytes(&Conf_ListenPorts);
657 #ifdef SSL_SUPPORT
658         cnt += array_bytes(&Conf_SSLOptions.ListenPorts);
659 #endif
660         return cnt == 0;
661 }
662
663 static void
664 Read_Motd(const char *filename)
665 {
666         char line[127];
667         FILE *fp;
668
669         if (*filename == '\0')
670                 return;
671
672         fp = fopen(filename, "r");
673         if (!fp) {
674                 Log(LOG_WARNING, "Can't read MOTD file \"%s\": %s",
675                                         filename, strerror(errno));
676                 return;
677         }
678
679         array_free(&Conf_Motd);
680         Using_MotdFile = true;
681
682         while (fgets(line, (int)sizeof line, fp)) {
683                 ngt_TrimLastChr( line, '\n');
684
685                 /* add text including \0 */
686                 if (!array_catb(&Conf_Motd, line, strlen(line) + 1)) {
687                         Log(LOG_WARNING, "Cannot add MOTD text: %s", strerror(errno));
688                         break;
689                 }
690         }
691         fclose(fp);
692 }
693
694 static bool
695 Read_Config( bool ngircd_starting )
696 {
697         /* Read configuration file. */
698
699         char section[LINE_LEN], str[LINE_LEN], *var, *arg, *ptr;
700         const UINT16 defaultport = 6667;
701         int line, i, n;
702         FILE *fd;
703
704         /* Open configuration file */
705         fd = fopen( NGIRCd_ConfFile, "r" );
706         if( ! fd ) {
707                 /* No configuration file found! */
708                 Config_Error( LOG_ALERT, "Can't read configuration \"%s\": %s",
709                                         NGIRCd_ConfFile, strerror( errno ));
710                 if (!ngircd_starting)
711                         return false;
712                 Config_Error( LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE_NAME );
713                 exit( 1 );
714         }
715
716         opers_free();
717         Set_Defaults( ngircd_starting );
718
719         Config_Error( LOG_INFO, "Reading configuration from \"%s\" ...", NGIRCd_ConfFile );
720
721         /* Clean up server configuration structure: mark all already
722          * configured servers as "once" so that they are deleted
723          * after the next disconnect and delete all unused servers.
724          * And delete all servers which are "duplicates" of servers
725          * that are already marked as "once" (such servers have been
726          * created by the last rehash but are now useless). */
727         for( i = 0; i < MAX_SERVERS; i++ ) {
728                 if( Conf_Server[i].conn_id == NONE ) Init_Server_Struct( &Conf_Server[i] );
729                 else {
730                         /* This structure is in use ... */
731                         if( Conf_Server[i].flags & CONF_SFLAG_ONCE ) {
732                                 /* Check for duplicates */
733                                 for( n = 0; n < MAX_SERVERS; n++ ) {
734                                         if( n == i ) continue;
735
736                                         if( Conf_Server[i].conn_id == Conf_Server[n].conn_id ) {
737                                                 Init_Server_Struct( &Conf_Server[n] );
738 #ifdef DEBUG
739                                                 Log(LOG_DEBUG,"Deleted unused duplicate server %d (kept %d).",
740                                                                                                 n, i );
741 #endif
742                                         }
743                                 }
744                         } else {
745                                 /* Mark server as "once" */
746                                 Conf_Server[i].flags |= CONF_SFLAG_ONCE;
747                                 Log( LOG_DEBUG, "Marked server %d as \"once\"", i );
748                         }
749                 }
750         }
751
752         /* Initialize variables */
753         line = 0;
754         strcpy( section, "" );
755         Init_Server_Struct( &New_Server );
756         New_Server_Idx = NONE;
757 #ifdef SSL_SUPPORT
758         ConfSSL_Init();
759 #endif
760         /* Read configuration file */
761         while( true ) {
762                 if( ! fgets( str, LINE_LEN, fd )) break;
763                 ngt_TrimStr( str );
764                 line++;
765
766                 /* Skip comments and empty lines */
767                 if( str[0] == ';' || str[0] == '#' || str[0] == '\0' ) continue;
768
769                 /* Is this the beginning of a new section? */
770                 if(( str[0] == '[' ) && ( str[strlen( str ) - 1] == ']' )) {
771                         strlcpy( section, str, sizeof( section ));
772                         if( strcasecmp( section, "[GLOBAL]" ) == 0 )
773                                 continue;
774
775                         if( strcasecmp( section, "[SERVER]" ) == 0 ) {
776                                 /* Check if there is already a server to add */
777                                 if( New_Server.name[0] ) {
778                                         /* Copy data to "real" server structure */
779                                         assert( New_Server_Idx > NONE );
780                                         Conf_Server[New_Server_Idx] = New_Server;
781                                 }
782
783                                 /* Re-init structure for new server */
784                                 Init_Server_Struct( &New_Server );
785
786                                 /* Search unused item in server configuration structure */
787                                 for( i = 0; i < MAX_SERVERS; i++ ) {
788                                         /* Is this item used? */
789                                         if( ! Conf_Server[i].name[0] ) break;
790                                 }
791                                 if( i >= MAX_SERVERS ) {
792                                         /* Oops, no free item found! */
793                                         Config_Error( LOG_ERR, "Too many servers configured." );
794                                         New_Server_Idx = NONE;
795                                 }
796                                 else New_Server_Idx = i;
797                                 continue;
798                         }
799                         if (strcasecmp(section, "[CHANNEL]") == 0) {
800                                 Conf_Channel_Count++;
801                                 continue;
802                         }
803                         if (strcasecmp(section, "[OPERATOR]") == 0) {
804                                 Conf_Oper_Count++;
805                                 continue;
806                         }
807
808                         Config_Error( LOG_ERR, "%s, line %d: Unknown section \"%s\"!", NGIRCd_ConfFile, line, section );
809                         section[0] = 0x1;
810                 }
811                 if( section[0] == 0x1 ) continue;
812
813                 /* Split line into variable name and parameters */
814                 ptr = strchr( str, '=' );
815                 if( ! ptr ) {
816                         Config_Error( LOG_ERR, "%s, line %d: Syntax error!", NGIRCd_ConfFile, line );
817                         continue;
818                 }
819                 *ptr = '\0';
820                 var = str; ngt_TrimStr( var );
821                 arg = ptr + 1; ngt_TrimStr( arg );
822
823                 if( strcasecmp( section, "[GLOBAL]" ) == 0 ) Handle_GLOBAL( line, var, arg );
824                 else if( strcasecmp( section, "[FEATURES]" ) == 0 ) Handle_FEATURES( line, var, arg );
825                 else if( strcasecmp( section, "[OPERATOR]" ) == 0 ) Handle_OPERATOR( line, var, arg );
826                 else if( strcasecmp( section, "[SERVER]" ) == 0 ) Handle_SERVER( line, var, arg );
827                 else if( strcasecmp( section, "[CHANNEL]" ) == 0 ) Handle_CHANNEL( line, var, arg );
828                 else Config_Error( LOG_ERR, "%s, line %d: Variable \"%s\" outside section!", NGIRCd_ConfFile, line, var );
829         }
830
831         /* Close configuration file */
832         fclose( fd );
833
834         /* Check if there is still a server to add */
835         if( New_Server.name[0] ) {
836                 /* Copy data to "real" server structure */
837                 assert( New_Server_Idx > NONE );
838                 Conf_Server[New_Server_Idx] = New_Server;
839         }
840
841         /* not a single listening port? Add default. */
842         if (no_listenports() &&
843                 !array_copyb(&Conf_ListenPorts, (char*) &defaultport, sizeof defaultport))
844         {
845                 Config_Error(LOG_ALERT, "Could not add default listening Port %u: %s",
846                                         (unsigned int) defaultport, strerror(errno));
847
848                 exit(1);
849         }
850
851         if (!Conf_ListenAddress)
852                 Conf_ListenAddress = strdup_warn(DEFAULT_LISTEN_ADDRSTR);
853
854         if (!Conf_ListenAddress) {
855                 Config_Error(LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE_NAME);
856                 exit(1);
857         }
858
859         /* No MOTD phrase configured? (re)try motd file. */
860         if (array_bytes(&Conf_Motd) == 0)
861                 Read_Motd(Conf_MotdFile);
862         return true;
863 } /* Read_Config */
864
865
866 static bool
867 Check_ArgIsTrue( const char *Arg )
868 {
869         if( strcasecmp( Arg, "yes" ) == 0 ) return true;
870         if( strcasecmp( Arg, "true" ) == 0 ) return true;
871         if( atoi( Arg ) != 0 ) return true;
872
873         return false;
874 } /* Check_ArgIsTrue */
875
876
877 static unsigned int
878 Handle_MaxNickLength(int Line, const char *Arg)
879 {
880         unsigned new;
881
882         new = (unsigned) atoi(Arg) + 1;
883         if (new > CLIENT_NICK_LEN) {
884                 Config_Error(LOG_WARNING,
885                              "%s, line %d: Value of \"MaxNickLength\" exceeds %u!",
886                              NGIRCd_ConfFile, Line, CLIENT_NICK_LEN - 1);
887                 return CLIENT_NICK_LEN;
888         }
889         if (new < 2) {
890                 Config_Error(LOG_WARNING,
891                              "%s, line %d: Value of \"MaxNickLength\" must be at least 1!",
892                              NGIRCd_ConfFile, Line);
893                 return 2;
894         }
895         return new;
896 } /* Handle_MaxNickLength */
897
898
899 static void
900 WarnIdent(int UNUSED Line)
901 {
902 #ifndef IDENTAUTH
903         if (Conf_Ident) {
904                 /* user has enabled ident lookups explicitly, but ... */
905                 Config_Error(LOG_WARNING,
906                         "%s: line %d: %s=True, but ngircd was built without support",
907                         NGIRCd_ConfFile, Line, "Ident");
908         }
909 #endif
910 }
911
912 static void
913 WarnPAM(int UNUSED Line)
914 {
915 #ifndef PAM
916         if (Conf_PAM) {
917                 Config_Error(LOG_WARNING,
918                         "%s: line %d: %s=True, but ngircd was built without support",
919                         NGIRCd_ConfFile, Line, "PAM");
920         }
921 #endif
922 }
923
924 static bool
925 CheckLegacyNoOption(const char *Var, const char *Arg)
926 {
927         if( strcasecmp( Var, "NoDNS" ) == 0 ) {
928                 Conf_DNS = !Check_ArgIsTrue( Arg );
929                 return true;
930         }
931         if (strcasecmp(Var, "NoIdent") == 0) {
932                 Conf_Ident = !Check_ArgIsTrue(Arg);
933                 return true;
934         }
935         if(strcasecmp(Var, "NoPAM") == 0) {
936                 Conf_PAM = !Check_ArgIsTrue(Arg);
937                 return true;
938         }
939         if(strcasecmp(Var, "NoZeroConf") == 0) {
940                 Conf_ZeroConf = !Check_ArgIsTrue(Arg);
941                 return true;
942         }
943         return false;
944 }
945
946 static const char *
947 NoNo(const char *str)
948 {
949         assert(strncasecmp("no", str, 2) == 0 && str[2]);
950         return str + 2;
951 }
952
953 static const char *
954 InvertArg(const char *arg)
955 {
956         return yesno_to_str(!Check_ArgIsTrue(arg));
957 }
958
959 static void
960 Handle_GLOBAL( int Line, char *Var, char *Arg )
961 {
962         struct passwd *pwd;
963         struct group *grp;
964         size_t len;
965         
966         assert( Line > 0 );
967         assert( Var != NULL );
968         assert( Arg != NULL );
969         
970         if( strcasecmp( Var, "Name" ) == 0 ) {
971                 /* Server name */
972                 len = strlcpy( Conf_ServerName, Arg, sizeof( Conf_ServerName ));
973                 if (len >= sizeof( Conf_ServerName ))
974                         Config_Error_TooLong( Line, Var );
975                 return;
976         }
977         if( strcasecmp( Var, "Info" ) == 0 ) {
978                 /* Info text of server */
979                 len = strlcpy( Conf_ServerInfo, Arg, sizeof( Conf_ServerInfo ));
980                 if (len >= sizeof( Conf_ServerInfo ))
981                         Config_Error_TooLong ( Line, Var );
982                 return;
983         }
984         if( strcasecmp( Var, "Password" ) == 0 ) {
985                 /* Global server password */
986                 len = strlcpy( Conf_ServerPwd, Arg, sizeof( Conf_ServerPwd ));
987                 if (len >= sizeof( Conf_ServerPwd ))
988                         Config_Error_TooLong( Line, Var );
989                 return;
990         }
991         if (strcasecmp(Var, "WebircPassword") == 0) {
992                 /* Password required for WEBIRC command */
993                 len = strlcpy(Conf_WebircPwd, Arg, sizeof(Conf_WebircPwd));
994                 if (len >= sizeof(Conf_WebircPwd))
995                         Config_Error_TooLong(Line, Var);
996                 return;
997         }
998         if( strcasecmp( Var, "AdminInfo1" ) == 0 ) {
999                 /* Administrative info #1 */
1000                 len = strlcpy( Conf_ServerAdmin1, Arg, sizeof( Conf_ServerAdmin1 ));
1001                 if (len >= sizeof( Conf_ServerAdmin1 ))
1002                         Config_Error_TooLong ( Line, Var );
1003                 return;
1004         }
1005         if( strcasecmp( Var, "AdminInfo2" ) == 0 ) {
1006                 /* Administrative info #2 */
1007                 len = strlcpy( Conf_ServerAdmin2, Arg, sizeof( Conf_ServerAdmin2 ));
1008                 if (len >= sizeof( Conf_ServerAdmin2 ))
1009                         Config_Error_TooLong ( Line, Var );
1010                 return;
1011         }
1012         if( strcasecmp( Var, "AdminEMail" ) == 0 ) {
1013                 /* Administrative email contact */
1014                 len = strlcpy( Conf_ServerAdminMail, Arg, sizeof( Conf_ServerAdminMail ));
1015                 if (len >= sizeof( Conf_ServerAdminMail ))
1016                         Config_Error_TooLong( Line, Var );
1017                 return;
1018         }
1019
1020         if( strcasecmp( Var, "Ports" ) == 0 ) {
1021                 ports_parse(&Conf_ListenPorts, Line, Arg);
1022                 return;
1023         }
1024         if( strcasecmp( Var, "MotdFile" ) == 0 ) {
1025                 len = strlcpy( Conf_MotdFile, Arg, sizeof( Conf_MotdFile ));
1026                 if (len >= sizeof( Conf_MotdFile ))
1027                         Config_Error_TooLong( Line, Var );
1028                 Read_Motd(Arg);
1029                 return;
1030         }
1031         if( strcasecmp( Var, "MotdPhrase" ) == 0 ) {
1032                 /* "Message of the day" phrase (instead of file) */
1033                 len = strlen(Arg);
1034                 if (len == 0)
1035                         return;
1036                 if (len >= LINE_LEN) {
1037                         Config_Error_TooLong( Line, Var );
1038                         return;
1039                 }
1040                 if (!array_copyb(&Conf_Motd, Arg, len + 1))
1041                         Config_Error(LOG_WARNING, "%s, line %d: Could not append MotdPhrase: %s",
1042                                                         NGIRCd_ConfFile, Line, strerror(errno));
1043                 Using_MotdFile = false;
1044                 return;
1045         }
1046         if( strcasecmp( Var, "ChrootDir" ) == 0 ) {
1047                 /* directory for chroot() */
1048                 len = strlcpy( Conf_Chroot, Arg, sizeof( Conf_Chroot ));
1049                 if (len >= sizeof( Conf_Chroot ))
1050                         Config_Error_TooLong( Line, Var );
1051                 return;
1052         }
1053         if ( strcasecmp( Var, "PidFile" ) == 0 ) {
1054                 /* name of pidfile */
1055                 len = strlcpy( Conf_PidFile, Arg, sizeof( Conf_PidFile ));
1056                 if (len >= sizeof( Conf_PidFile ))
1057                         Config_Error_TooLong( Line, Var );
1058                 return;
1059         }
1060         if( strcasecmp( Var, "ServerUID" ) == 0 ) {
1061                 /* UID the daemon should switch to */
1062                 pwd = getpwnam( Arg );
1063                 if( pwd ) Conf_UID = pwd->pw_uid;
1064                 else {
1065 #ifdef HAVE_ISDIGIT
1066                         if( ! isdigit( (int)*Arg )) Config_Error_NaN( Line, Var );
1067                         else
1068 #endif
1069                         Conf_UID = (unsigned int)atoi( Arg );
1070                 }
1071                 return;
1072         }
1073         if( strcasecmp( Var, "ServerGID" ) == 0 ) {
1074                 /* GID the daemon should use */
1075                 grp = getgrnam( Arg );
1076                 if( grp ) Conf_GID = grp->gr_gid;
1077                 else {
1078 #ifdef HAVE_ISDIGIT
1079                         if( ! isdigit( (int)*Arg )) Config_Error_NaN( Line, Var );
1080                         else
1081 #endif
1082                         Conf_GID = (unsigned int)atoi( Arg );
1083                 }
1084                 return;
1085         }
1086         if( strcasecmp( Var, "PingTimeout" ) == 0 ) {
1087                 /* PING timeout */
1088                 Conf_PingTimeout = atoi( Arg );
1089                 if( Conf_PingTimeout < 5 ) {
1090                         Config_Error( LOG_WARNING, "%s, line %d: Value of \"PingTimeout\" too low!",
1091                                                                         NGIRCd_ConfFile, Line );
1092                         Conf_PingTimeout = 5;
1093                 }
1094                 return;
1095         }
1096         if( strcasecmp( Var, "PongTimeout" ) == 0 ) {
1097                 /* PONG timeout */
1098                 Conf_PongTimeout = atoi( Arg );
1099                 if( Conf_PongTimeout < 5 ) {
1100                         Config_Error( LOG_WARNING, "%s, line %d: Value of \"PongTimeout\" too low!",
1101                                                                         NGIRCd_ConfFile, Line );
1102                         Conf_PongTimeout = 5;
1103                 }
1104                 return;
1105         }
1106         if( strcasecmp( Var, "ConnectRetry" ) == 0 ) {
1107                 /* Seconds between connection attempts to other servers */
1108                 Conf_ConnectRetry = atoi( Arg );
1109                 if( Conf_ConnectRetry < 5 ) {
1110                         Config_Error( LOG_WARNING, "%s, line %d: Value of \"ConnectRetry\" too low!",
1111                                                                         NGIRCd_ConfFile, Line );
1112                         Conf_ConnectRetry = 5;
1113                 }
1114                 return;
1115         }
1116         if( strcasecmp( Var, "PredefChannelsOnly" ) == 0 ) {
1117                 /* Should we only allow pre-defined-channels? (i.e. users cannot create their own channels) */
1118                 Conf_PredefChannelsOnly = Check_ArgIsTrue( Arg );
1119                 return;
1120         }
1121
1122         if (CheckLegacyNoOption(Var, Arg)) {
1123                 Config_Error(LOG_WARNING, "%s, line %d: \"No\"-Prefix has been removed, use "
1124                                 "\"%s = %s\" in [FEATURES] section instead",
1125                                         NGIRCd_ConfFile, Line, NoNo(Var), InvertArg(Arg));
1126                 if (strcasecmp(Var, "NoIdent") == 0)
1127                         WarnIdent(Line);
1128                 else if (strcasecmp(Var, "NoPam") == 0)
1129                         WarnPAM(Line);
1130                 return;
1131         }
1132 #ifdef WANT_IPV6
1133         /* the default setting for all the WANT_IPV6 special options is 'true' */
1134         if( strcasecmp( Var, "ConnectIPv6" ) == 0 ) {
1135                 /* connect to other hosts using ipv6, if they have an AAAA record? */
1136                 Conf_ConnectIPv6 = Check_ArgIsTrue( Arg );
1137                 return;
1138         }
1139         if( strcasecmp( Var, "ConnectIPv4" ) == 0 ) {
1140                 /* connect to other hosts using ipv4.
1141                  * again, this can be used for ipv6-only setups */
1142                 Conf_ConnectIPv4 = Check_ArgIsTrue( Arg );
1143                 return;
1144         }
1145 #endif
1146         if( strcasecmp( Var, "OperCanUseMode" ) == 0 ) {
1147                 /* Are IRC operators allowed to use MODE in channels they aren't Op in? */
1148                 Conf_OperCanMode = Check_ArgIsTrue( Arg );
1149                 return;
1150         }
1151         if( strcasecmp( Var, "OperServerMode" ) == 0 ) {
1152                 /* Mask IRC operator as if coming from the server? (ircd-irc2 compat hack) */
1153                 Conf_OperServerMode = Check_ArgIsTrue( Arg );
1154                 return;
1155         }
1156         if(strcasecmp(Var, "AllowRemoteOper") == 0) {
1157                 /* Are remote IRC operators allowed to control this server? */
1158                 Conf_AllowRemoteOper = Check_ArgIsTrue(Arg);
1159                 return;
1160         }
1161         if( strcasecmp( Var, "MaxConnections" ) == 0 ) {
1162                 /* Maximum number of connections. 0 -> "no limit". */
1163 #ifdef HAVE_ISDIGIT
1164                 if( ! isdigit( (int)*Arg )) Config_Error_NaN( Line, Var);
1165                 else
1166 #endif
1167                 Conf_MaxConnections = atol( Arg );
1168                 return;
1169         }
1170         if( strcasecmp( Var, "MaxConnectionsIP" ) == 0 ) {
1171                 /* Maximum number of simultaneous connections from one IP. 0 -> "no limit" */
1172 #ifdef HAVE_ISDIGIT
1173                 if( ! isdigit( (int)*Arg )) Config_Error_NaN( Line, Var );
1174                 else
1175 #endif
1176                 Conf_MaxConnectionsIP = atoi( Arg );
1177                 return;
1178         }
1179         if( strcasecmp( Var, "MaxJoins" ) == 0 ) {
1180                 /* Maximum number of channels a user can join. 0 -> "no limit". */
1181 #ifdef HAVE_ISDIGIT
1182                 if( ! isdigit( (int)*Arg )) Config_Error_NaN( Line, Var );
1183                 else
1184 #endif
1185                 Conf_MaxJoins = atoi( Arg );
1186                 return;
1187         }
1188         if( strcasecmp( Var, "MaxNickLength" ) == 0 ) {
1189                 /* Maximum length of a nick name; must be same on all servers
1190                  * within the IRC network! */
1191                 Conf_MaxNickLength = Handle_MaxNickLength(Line, Arg);
1192                 return;
1193         }
1194
1195         if( strcasecmp( Var, "Listen" ) == 0 ) {
1196                 /* IP-Address to bind sockets */
1197                 if (Conf_ListenAddress) {
1198                         Config_Error(LOG_ERR, "Multiple Listen= options, ignoring: %s", Arg);
1199                         return;
1200                 }
1201                 Conf_ListenAddress = strdup_warn(Arg);
1202                 /*
1203                  * if allocation fails, we're in trouble:
1204                  * we cannot ignore the error -- otherwise ngircd
1205                  * would listen on all interfaces.
1206                  */
1207                 if (!Conf_ListenAddress) {
1208                         Config_Error(LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE_NAME);
1209                         exit(1);
1210                 }
1211                 return;
1212         }
1213
1214 #ifdef SSL_SUPPORT
1215         if( strcasecmp( Var, "SSLPorts" ) == 0 ) {
1216                 ports_parse(&Conf_SSLOptions.ListenPorts, Line, Arg);
1217                 return;
1218         }
1219
1220         if( strcasecmp( Var, "SSLKeyFile" ) == 0 ) {
1221                 assert(Conf_SSLOptions.KeyFile == NULL );
1222                 Conf_SSLOptions.KeyFile = strdup_warn(Arg);
1223                 return;
1224         }
1225         if( strcasecmp( Var, "SSLCertFile" ) == 0 ) {
1226                 assert(Conf_SSLOptions.CertFile == NULL );
1227                 Conf_SSLOptions.CertFile = strdup_warn(Arg);
1228                 return;
1229         }
1230
1231         if( strcasecmp( Var, "SSLKeyFilePassword" ) == 0 ) {
1232                 assert(array_bytes(&Conf_SSLOptions.KeyFilePassword) == 0);
1233                 if (!array_copys(&Conf_SSLOptions.KeyFilePassword, Arg))
1234                         Config_Error( LOG_ERR, "%s, line %d (section \"Global\"): Could not copy %s: %s!",
1235                                                                 NGIRCd_ConfFile, Line, Var, strerror(errno));
1236                 return;
1237         }
1238         if( strcasecmp( Var, "SSLDHFile" ) == 0 ) {
1239                 assert(Conf_SSLOptions.DHFile == NULL);
1240                 Conf_SSLOptions.DHFile = strdup_warn( Arg );
1241                 return;
1242         }
1243 #endif
1244 #ifdef SYSLOG
1245         if (strcasecmp(Var, "SyslogFacility") == 0) {
1246                 Conf_SyslogFacility = ngt_SyslogFacilityID(Arg,
1247                                                            Conf_SyslogFacility);
1248                 return;
1249         }
1250 #endif
1251         Config_Error(LOG_ERR, "%s, line %d (section \"Global\"): Unknown variable \"%s\"!",
1252                                                                 NGIRCd_ConfFile, Line, Var);
1253 } /* Handle_GLOBAL */
1254
1255
1256 static void
1257 Handle_FEATURES(int Line, char *Var, char *Arg)
1258 {
1259         assert( Line > 0 );
1260         assert( Var != NULL );
1261         assert( Arg != NULL );
1262
1263         if( strcasecmp( Var, "DNS" ) == 0 ) {
1264                 /* do reverse dns lookups when clients connect? */
1265                 Conf_DNS = Check_ArgIsTrue( Arg );
1266                 return;
1267         }
1268         if (strcasecmp(Var, "Ident") == 0) {
1269                 /* do IDENT lookups when clients connect? */
1270                 Conf_Ident = Check_ArgIsTrue(Arg);
1271                 WarnIdent(Line);
1272                 return;
1273         }
1274         if(strcasecmp(Var, "PAM") == 0) {
1275                 /* use PAM library to authenticate users */
1276                 Conf_PAM = Check_ArgIsTrue(Arg);
1277                 WarnPAM(Line);
1278                 return;
1279         }
1280         if(strcasecmp(Var, "ZeroConf") == 0) {
1281                 /* register services using ZeroConf */
1282                 Conf_ZeroConf = Check_ArgIsTrue(Arg);
1283                 return;
1284         }
1285 }
1286
1287 static void
1288 Handle_OPERATOR( int Line, char *Var, char *Arg )
1289 {
1290         size_t len;
1291         struct Conf_Oper *op;
1292
1293         assert( Line > 0 );
1294         assert( Var != NULL );
1295         assert( Arg != NULL );
1296         assert( Conf_Oper_Count > 0 );
1297
1298         op = array_alloc(&Conf_Opers, sizeof(*op), Conf_Oper_Count - 1);
1299         if (!op) {
1300                 Config_Error(LOG_ERR, "Could not allocate memory for operator (%d:%s = %s)", Line, Var, Arg);
1301                 return;
1302         }
1303
1304         if (strcasecmp(Var, "Name") == 0) {
1305                 /* Name of IRC operator */
1306                 len = strlcpy(op->name, Arg, sizeof(op->name));
1307                 if (len >= sizeof(op->name))
1308                                 Config_Error_TooLong(Line, Var);
1309                 return;
1310         }
1311         if (strcasecmp(Var, "Password") == 0) {
1312                 /* Password of IRC operator */
1313                 len = strlcpy(op->pwd, Arg, sizeof(op->pwd));
1314                 if (len >= sizeof(op->pwd))
1315                                 Config_Error_TooLong(Line, Var);
1316                 return;
1317         }
1318         if (strcasecmp(Var, "Mask") == 0) {
1319                 if (op->mask)
1320                         return; /* Hostname already configured */
1321                 op->mask = strdup_warn( Arg );
1322                 return;
1323         }
1324         Config_Error( LOG_ERR, "%s, line %d (section \"Operator\"): Unknown variable \"%s\"!",
1325                                                                 NGIRCd_ConfFile, Line, Var );
1326 } /* Handle_OPERATOR */
1327
1328
1329 static void
1330 Handle_SERVER( int Line, char *Var, char *Arg )
1331 {
1332         long port;
1333         size_t len;
1334         
1335         assert( Line > 0 );
1336         assert( Var != NULL );
1337         assert( Arg != NULL );
1338
1339         /* Ignore server block if no space is left in server configuration structure */
1340         if( New_Server_Idx <= NONE ) return;
1341
1342         if( strcasecmp( Var, "Host" ) == 0 ) {
1343                 /* Hostname of the server */
1344                 len = strlcpy( New_Server.host, Arg, sizeof( New_Server.host ));
1345                 if (len >= sizeof( New_Server.host ))
1346                         Config_Error_TooLong ( Line, Var );
1347                 return;
1348         }
1349         if( strcasecmp( Var, "Name" ) == 0 ) {
1350                 /* Name of the server ("Nick"/"ID") */
1351                 len = strlcpy( New_Server.name, Arg, sizeof( New_Server.name ));
1352                 if (len >= sizeof( New_Server.name ))
1353                         Config_Error_TooLong( Line, Var );
1354                 return;
1355         }
1356         if (strcasecmp(Var, "Bind") == 0) {
1357                 if (ng_ipaddr_init(&New_Server.bind_addr, Arg, 0))
1358                         return;
1359
1360                 Config_Error(LOG_ERR, "%s, line %d (section \"Server\"): Can't parse IP address \"%s\"",
1361                                 NGIRCd_ConfFile, Line, Arg);
1362                 return;
1363         }
1364         if( strcasecmp( Var, "MyPassword" ) == 0 ) {
1365                 /* Password of this server which is sent to the peer */
1366                 if (*Arg == ':') {
1367                         Config_Error(LOG_ERR,
1368                                 "%s, line %d (section \"Server\"): MyPassword must not start with ':'!",
1369                                                                                 NGIRCd_ConfFile, Line);
1370                 }
1371                 len = strlcpy( New_Server.pwd_in, Arg, sizeof( New_Server.pwd_in ));
1372                 if (len >= sizeof( New_Server.pwd_in ))
1373                         Config_Error_TooLong( Line, Var );
1374                 return;
1375         }
1376         if( strcasecmp( Var, "PeerPassword" ) == 0 ) {
1377                 /* Passwort of the peer which must be received */
1378                 len = strlcpy( New_Server.pwd_out, Arg, sizeof( New_Server.pwd_out ));
1379                 if (len >= sizeof( New_Server.pwd_out ))
1380                         Config_Error_TooLong( Line, Var );
1381                 return;
1382         }
1383         if( strcasecmp( Var, "Port" ) == 0 ) {
1384                 /* Port to which this server should connect */
1385                 port = atol( Arg );
1386                 if( port > 0 && port < 0xFFFF )
1387                         New_Server.port = (UINT16)port;
1388                 else
1389                         Config_Error( LOG_ERR, "%s, line %d (section \"Server\"): Illegal port number %ld!",
1390                                                                                 NGIRCd_ConfFile, Line, port );
1391                 return;
1392         }
1393 #ifdef SSL_SUPPORT
1394         if( strcasecmp( Var, "SSLConnect" ) == 0 ) {
1395                 New_Server.SSLConnect = Check_ArgIsTrue(Arg);
1396                 return;
1397         }
1398 #endif
1399         if( strcasecmp( Var, "Group" ) == 0 ) {
1400                 /* Server group */
1401 #ifdef HAVE_ISDIGIT
1402                 if( ! isdigit( (int)*Arg ))
1403                         Config_Error_NaN( Line, Var );
1404                 else
1405 #endif
1406                 New_Server.group = atoi( Arg );
1407                 return;
1408         }
1409         if( strcasecmp( Var, "Passive" ) == 0 ) {
1410                 if (Check_ArgIsTrue(Arg))
1411                         New_Server.flags |= CONF_SFLAG_DISABLED;
1412                 return;
1413         }
1414         if (strcasecmp(Var, "ServiceMask") == 0) {
1415                 len = strlcpy(New_Server.svs_mask, ngt_LowerStr(Arg),
1416                               sizeof(New_Server.svs_mask));
1417                 if (len >= sizeof(New_Server.svs_mask))
1418                         Config_Error_TooLong(Line, Var);
1419                 return;
1420         }
1421
1422         Config_Error( LOG_ERR, "%s, line %d (section \"Server\"): Unknown variable \"%s\"!",
1423                                                                 NGIRCd_ConfFile, Line, Var );
1424 } /* Handle_SERVER */
1425
1426
1427 static bool
1428 Handle_Channelname(struct Conf_Channel *new_chan, const char *name)
1429 {
1430         size_t size = sizeof(new_chan->name);
1431         char *dest = new_chan->name;
1432
1433         if (!Channel_IsValidName(name)) {
1434                 /*
1435                  * maybe user forgot to add a '#'.
1436                  * This is only here for user convenience.
1437                  */
1438                 *dest = '#';
1439                 --size;
1440                 ++dest;
1441         }
1442         return size > strlcpy(dest, name, size);
1443 }
1444
1445
1446 static void
1447 Handle_CHANNEL(int Line, char *Var, char *Arg)
1448 {
1449         size_t len;
1450         size_t chancount;
1451         struct Conf_Channel *chan;
1452
1453         assert( Line > 0 );
1454         assert( Var != NULL );
1455         assert( Arg != NULL );
1456         assert(Conf_Channel_Count > 0);
1457
1458         chancount = Conf_Channel_Count - 1;
1459
1460         chan = array_alloc(&Conf_Channels, sizeof(*chan), chancount);
1461         if (!chan) {
1462                 Config_Error(LOG_ERR, "Could not allocate memory for predefined channel (%d:%s = %s)", Line, Var, Arg);
1463                 return;
1464         }
1465         if (strcasecmp(Var, "Name") == 0) {
1466                 if (!Handle_Channelname(chan, Arg))
1467                         Config_Error_TooLong(Line, Var);
1468                 return;
1469         }
1470         if (strcasecmp(Var, "Modes") == 0) {
1471                 /* Initial modes */
1472                 len = strlcpy(chan->modes, Arg, sizeof(chan->modes));
1473                 if (len >= sizeof(chan->modes))
1474                         Config_Error_TooLong( Line, Var );
1475                 return;
1476         }
1477         if( strcasecmp( Var, "Topic" ) == 0 ) {
1478                 /* Initial topic */
1479                 len = strlcpy(chan->topic, Arg, sizeof(chan->topic));
1480                 if (len >= sizeof(chan->topic))
1481                         Config_Error_TooLong( Line, Var );
1482                 return;
1483         }
1484         if( strcasecmp( Var, "Key" ) == 0 ) {
1485                 /* Initial Channel Key (mode k) */
1486                 len = strlcpy(chan->key, Arg, sizeof(chan->key));
1487                 if (len >= sizeof(chan->key))
1488                         Config_Error_TooLong(Line, Var);
1489                 return;
1490         }
1491         if( strcasecmp( Var, "MaxUsers" ) == 0 ) {
1492                 /* maximum user limit, mode l */
1493                 chan->maxusers = (unsigned long) atol(Arg);
1494                 if (chan->maxusers == 0)
1495                         Config_Error_NaN(Line, Var);
1496                 return;
1497         }
1498         if (strcasecmp(Var, "KeyFile") == 0) {
1499                 /* channel keys */
1500                 len = strlcpy(chan->keyfile, Arg, sizeof(chan->keyfile));
1501                 if (len >= sizeof(chan->keyfile))
1502                         Config_Error_TooLong(Line, Var);
1503                 return;
1504         }
1505
1506         Config_Error( LOG_ERR, "%s, line %d (section \"Channel\"): Unknown variable \"%s\"!",
1507                                                                 NGIRCd_ConfFile, Line, Var );
1508 } /* Handle_CHANNEL */
1509
1510
1511 static bool
1512 Validate_Config(bool Configtest, bool Rehash)
1513 {
1514         /* Validate configuration settings. */
1515
1516 #ifdef DEBUG
1517         int i, servers, servers_once;
1518 #endif
1519         bool config_valid = true;
1520         char *ptr;
1521
1522         /* Validate configured server name, see RFC 2812 section 2.3.1 */
1523         ptr = Conf_ServerName;
1524         do {
1525                 if (*ptr >= 'a' && *ptr <= 'z') continue;
1526                 if (*ptr >= 'A' && *ptr <= 'Z') continue;
1527                 if (*ptr >= '0' && *ptr <= '9') continue;
1528                 if (ptr > Conf_ServerName) {
1529                         if (*ptr == '.' || *ptr == '-')
1530                                 continue;
1531                 }
1532                 Conf_ServerName[0] = '\0';
1533                 break;
1534         } while (*(++ptr));
1535
1536         if (!Conf_ServerName[0]) {
1537                 /* No server name configured! */
1538                 config_valid = false;
1539                 Config_Error(LOG_ALERT,
1540                              "No (valid) server name configured in \"%s\" (section 'Global': 'Name')!",
1541                              NGIRCd_ConfFile);
1542                 if (!Configtest && !Rehash) {
1543                         Config_Error(LOG_ALERT,
1544                                      "%s exiting due to fatal errors!",
1545                                      PACKAGE_NAME);
1546                         exit(1);
1547                 }
1548         }
1549
1550         if (Conf_ServerName[0] && !strchr(Conf_ServerName, '.')) {
1551                 /* No dot in server name! */
1552                 config_valid = false;
1553                 Config_Error(LOG_ALERT,
1554                              "Invalid server name configured in \"%s\" (section 'Global': 'Name'): Dot missing!",
1555                              NGIRCd_ConfFile);
1556                 if (!Configtest) {
1557                         Config_Error(LOG_ALERT,
1558                                      "%s exiting due to fatal errors!",
1559                                      PACKAGE_NAME);
1560                         exit(1);
1561                 }
1562         }
1563
1564 #ifdef STRICT_RFC
1565         if (!Conf_ServerAdminMail[0]) {
1566                 /* No administrative contact configured! */
1567                 config_valid = false;
1568                 Config_Error(LOG_ALERT,
1569                              "No administrator email address configured in \"%s\" ('AdminEMail')!",
1570                              NGIRCd_ConfFile);
1571                 if (!Configtest) {
1572                         Config_Error(LOG_ALERT,
1573                                      "%s exiting due to fatal errors!",
1574                                      PACKAGE_NAME);
1575                         exit(1);
1576                 }
1577         }
1578 #endif
1579
1580         if (!Conf_ServerAdmin1[0] && !Conf_ServerAdmin2[0]
1581             && !Conf_ServerAdminMail[0]) {
1582                 /* No administrative information configured! */
1583                 Config_Error(LOG_WARNING,
1584                              "No administrative information configured but required by RFC!");
1585         }
1586
1587 #ifdef PAM
1588         if (Conf_ServerPwd[0])
1589                 Config_Error(LOG_ERR,
1590                              "This server uses PAM, \"Password\" will be ignored!");
1591 #endif
1592
1593 #ifdef DEBUG
1594         servers = servers_once = 0;
1595         for (i = 0; i < MAX_SERVERS; i++) {
1596                 if (Conf_Server[i].name[0]) {
1597                         servers++;
1598                         if (Conf_Server[i].flags & CONF_SFLAG_ONCE)
1599                                 servers_once++;
1600                 }
1601         }
1602         Log(LOG_DEBUG,
1603             "Configuration: Operators=%d, Servers=%d[%d], Channels=%d",
1604             Conf_Oper_Count, servers, servers_once, Conf_Channel_Count);
1605 #endif
1606
1607         return config_valid;
1608 } /* Validate_Config */
1609
1610
1611 static void
1612 Config_Error_TooLong ( const int Line, const char *Item )
1613 {
1614         Config_Error( LOG_WARNING, "%s, line %d: Value of \"%s\" too long!", NGIRCd_ConfFile, Line, Item );
1615 }
1616
1617
1618 static void
1619 Config_Error_NaN( const int Line, const char *Item )
1620 {
1621         Config_Error( LOG_WARNING, "%s, line %d: Value of \"%s\" is not a number!",
1622                                                 NGIRCd_ConfFile, Line, Item );
1623 }
1624
1625
1626 #ifdef PROTOTYPES
1627 static void Config_Error( const int Level, const char *Format, ... )
1628 #else
1629 static void Config_Error( Level, Format, va_alist )
1630 const int Level;
1631 const char *Format;
1632 va_dcl
1633 #endif
1634 {
1635         /* Error! Write to console and/or logfile. */
1636
1637         char msg[MAX_LOG_MSG_LEN];
1638         va_list ap;
1639
1640         assert( Format != NULL );
1641
1642 #ifdef PROTOTYPES
1643         va_start( ap, Format );
1644 #else
1645         va_start( ap );
1646 #endif
1647         vsnprintf( msg, MAX_LOG_MSG_LEN, Format, ap );
1648         va_end( ap );
1649         
1650         /* During "normal operations" the log functions of the daemon should
1651          * be used, but during testing of the configuration file, all messages
1652          * should go directly to the console: */
1653         if (Use_Log) Log( Level, "%s", msg );
1654         else puts( msg );
1655 } /* Config_Error */
1656
1657
1658 #ifdef DEBUG
1659
1660 GLOBAL void
1661 Conf_DebugDump(void)
1662 {
1663         int i;
1664
1665         Log(LOG_DEBUG, "Configured servers:");
1666         for (i = 0; i < MAX_SERVERS; i++) {
1667                 if (! Conf_Server[i].name[0])
1668                         continue;
1669                 Log(LOG_DEBUG,
1670                     " - %s: %s:%d, last=%ld, group=%d, flags=%d, conn=%d",
1671                     Conf_Server[i].name, Conf_Server[i].host,
1672                     Conf_Server[i].port, Conf_Server[i].lasttry,
1673                     Conf_Server[i].group, Conf_Server[i].flags,
1674                     Conf_Server[i].conn_id);
1675         }
1676 } /* Conf_DebugDump */
1677
1678 #endif
1679
1680
1681 static void
1682 Init_Server_Struct( CONF_SERVER *Server )
1683 {
1684         /* Initialize server configuration structur to default values */
1685
1686         assert( Server != NULL );
1687
1688         memset( Server, 0, sizeof (CONF_SERVER) );
1689
1690         Server->group = NONE;
1691         Server->lasttry = time( NULL ) - Conf_ConnectRetry + STARTUP_DELAY;
1692
1693         if( NGIRCd_Passive ) Server->flags = CONF_SFLAG_DISABLED;
1694
1695         Proc_InitStruct(&Server->res_stat);
1696         Server->conn_id = NONE;
1697         memset(&Server->bind_addr, 0, sizeof(&Server->bind_addr));
1698 } /* Init_Server_Struct */
1699
1700
1701 /* -eof- */