]> arthur.barton.de Git - ngircd-alex.git/blob - src/ngircd/conf.c
"IncludeDir" can't be overwritten by included files
[ngircd-alex.git] / src / ngircd / conf.c
1 /*
2  * ngIRCd -- The Next Generation IRC Daemon
3  * Copyright (c)2001-2013 Alexander Barton (alex@barton.de) and Contributors.
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
12 #include "portab.h"
13
14 /**
15  * @file
16  * Configuration management (reading, parsing & validation)
17  */
18
19 #include "imp.h"
20 #include <assert.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #ifdef PROTOTYPES
24 #       include <stdarg.h>
25 #else
26 #       include <varargs.h>
27 #endif
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <strings.h>
32 #include <unistd.h>
33 #include <pwd.h>
34 #include <grp.h>
35 #include <sys/types.h>
36 #include <unistd.h>
37 #include <dirent.h>
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 char Conf_MotdFile[FNAME_LEN];
57 static char Conf_HelpFile[FNAME_LEN];
58 static char Conf_IncludeDir[FNAME_LEN];
59
60 static void Set_Defaults PARAMS(( bool InitServers ));
61 static bool Read_Config PARAMS(( bool TestOnly, bool IsStarting ));
62 static void Read_Config_File PARAMS(( const char *File, FILE *fd ));
63 static bool Validate_Config PARAMS(( bool TestOnly, bool Rehash ));
64
65 static void Handle_GLOBAL PARAMS((const char *File, int Line,
66                                   char *Var, char *Arg ));
67 static void Handle_LIMITS PARAMS((const char *File, int Line,
68                                   char *Var, char *Arg ));
69 static void Handle_OPTIONS PARAMS((const char *File, int Line,
70                                    char *Var, char *Arg ));
71 static void Handle_OPERATOR PARAMS((const char *File, int Line,
72                                     char *Var, char *Arg ));
73 static void Handle_SERVER PARAMS((const char *File, int Line,
74                                   char *Var, char *Arg ));
75 static void Handle_CHANNEL PARAMS((const char *File, int Line,
76                                    char *Var, char *Arg ));
77
78 static void Config_Error PARAMS((const int Level, const char *Format, ...));
79
80 static void Config_Error_NaN PARAMS((const char *File, const int LINE,
81                                      const char *Value));
82 static void Config_Error_Section PARAMS((const char *File, const int Line,
83                                          const char *Item, const char *Section));
84 static void Config_Error_TooLong PARAMS((const char *File, const int LINE,
85                                          const char *Value));
86
87 static void Init_Server_Struct PARAMS(( CONF_SERVER *Server ));
88
89
90 #ifdef WANT_IPV6
91 #define DEFAULT_LISTEN_ADDRSTR "::,0.0.0.0"
92 #else
93 #define DEFAULT_LISTEN_ADDRSTR "0.0.0.0"
94 #endif
95
96
97 #ifdef SSL_SUPPORT
98
99 static void Handle_SSL PARAMS((const char *File, int Line, char *Var, char *Ark));
100
101 struct SSLOptions Conf_SSLOptions;
102
103 /**
104  * Initialize SSL configuration.
105  */
106 static void
107 ConfSSL_Init(void)
108 {
109         free(Conf_SSLOptions.KeyFile);
110         Conf_SSLOptions.KeyFile = NULL;
111
112         free(Conf_SSLOptions.CertFile);
113         Conf_SSLOptions.CertFile = NULL;
114
115         free(Conf_SSLOptions.DHFile);
116         Conf_SSLOptions.DHFile = NULL;
117         array_free_wipe(&Conf_SSLOptions.KeyFilePassword);
118
119         array_free(&Conf_SSLOptions.ListenPorts);
120 }
121
122 /**
123  * Check if the current configuration uses/requires SSL.
124  *
125  * @returns true if SSL is used and should be initialized.
126  */
127 GLOBAL bool
128 Conf_SSLInUse(void)
129 {
130         int i;
131
132         /* SSL listen ports configured? */
133         if (array_bytes(&Conf_SSLOptions.ListenPorts))
134                 return true;
135
136         for (i = 0; i < MAX_SERVERS; i++) {
137                 if (Conf_Server[i].port > 0
138                     && Conf_Server[i].SSLConnect)
139                         return true;
140         }
141         return false;
142 }
143
144 /**
145  * Make sure that a configured file is readable.
146  *
147  * Currently, this function is only used for SSL-related options ...
148  *
149  * @param Var Configuration variable
150  * @param Filename Configured filename
151  */
152 static void
153 CheckFileReadable(const char *Var, const char *Filename)
154 {
155         FILE *fp;
156
157         if (!Filename)
158                 return;
159
160         fp = fopen(Filename, "r");
161         if (fp)
162                 fclose(fp);
163         else
164                 Config_Error(LOG_ERR, "Can't read \"%s\" (\"%s\"): %s",
165                              Filename, Var, strerror(errno));
166 }
167
168 #endif
169
170
171 /**
172  * Duplicate string and warn on errors.
173  *
174  * @returns Pointer to string on success, NULL otherwise.
175  */
176 static char *
177 strdup_warn(const char *str)
178 {
179         char *ptr = strdup(str);
180         if (!ptr)
181                 Config_Error(LOG_ERR,
182                              "Could not allocate memory for string: %s", str);
183         return ptr;
184 }
185
186 /**
187  * Output a comma separated list of ports (integer values).
188  */
189 static void
190 ports_puts(array *a)
191 {
192         size_t len;
193         UINT16 *ports;
194         len = array_length(a, sizeof(UINT16));
195         if (len--) {
196                 ports = (UINT16*) array_start(a);
197                 printf("%u", (unsigned int) *ports);
198                 while (len--) {
199                         ports++;
200                         printf(", %u", (unsigned int) *ports);
201                 }
202         }
203         putc('\n', stdout);
204 }
205
206 /**
207  * Parse a comma separated string into an array of port numbers (integers).
208  */
209 static void
210 ports_parse(array *a, int Line, char *Arg)
211 {
212         char *ptr;
213         int port;
214         UINT16 port16;
215
216         array_trunc(a);
217
218         ptr = strtok( Arg, "," );
219         while (ptr) {
220                 ngt_TrimStr(ptr);
221                 port = atoi(ptr);
222                 if (port > 0 && port < 0xFFFF) {
223                         port16 = (UINT16) port;
224                         if (!array_catb(a, (char*)&port16, sizeof port16))
225                                 Config_Error(LOG_ERR, "%s, line %d Could not add port number %ld: %s",
226                                                         NGIRCd_ConfFile, Line, port, strerror(errno));
227                 } else {
228                         Config_Error( LOG_ERR, "%s, line %d (section \"Global\"): Illegal port number %ld!",
229                                                                         NGIRCd_ConfFile, Line, port );
230                 }
231
232                 ptr = strtok( NULL, "," );
233         }
234 }
235
236 /**
237  * Initialize configuration module.
238  */
239 GLOBAL void
240 Conf_Init( void )
241 {
242         Read_Config(false, true);
243         Validate_Config(false, false);
244 }
245
246 /**
247  * "Rehash" (reload) server configuration.
248  *
249  * @returns true if configuration has been re-read, false on errors.
250  */
251 GLOBAL bool
252 Conf_Rehash( void )
253 {
254         if (!Read_Config(false, false))
255                 return false;
256         Validate_Config(false, true);
257
258         /* Update CLIENT structure of local server */
259         Client_SetInfo(Client_ThisServer(), Conf_ServerInfo);
260         return true;
261 }
262
263 /**
264  * Output a boolean value as "yes/no" string.
265  */
266 static const char*
267 yesno_to_str(int boolean_value)
268 {
269         if (boolean_value)
270                 return "yes";
271         return "no";
272 }
273
274 /**
275  * Free all IRC operator configuration structures.
276  */
277 static void
278 opers_free(void)
279 {
280         struct Conf_Oper *op;
281         size_t len;
282
283         len = array_length(&Conf_Opers, sizeof(*op));
284         op = array_start(&Conf_Opers);
285         while (len--) {
286                 free(op->mask);
287                 op++;
288         }
289         array_free(&Conf_Opers);
290 }
291
292 /**
293  * Output all IRC operator configuration structures.
294  */
295 static void
296 opers_puts(void)
297 {
298         struct Conf_Oper *op;
299         size_t count, i;
300
301         count = array_length(&Conf_Opers, sizeof(*op));
302         op = array_start(&Conf_Opers);
303         for (i = 0; i < count; i++, op++) {
304                 if (!op->name[0])
305                         continue;
306
307                 puts("[OPERATOR]");
308                 printf("  Name = %s\n", op->name);
309                 printf("  Password = %s\n", op->pwd);
310                 printf("  Mask = %s\n\n", op->mask ? op->mask : "");
311         }
312 }
313
314 /**
315  * Read configuration, validate and output it.
316  *
317  * This function waits for a keypress of the user when stdin/stdout are valid
318  * tty's ("you can read our nice message and we can read in your keypress").
319  *
320  * @return      0 on succes, 1 on failure(s); therefore the result code can
321  *              directly be used by exit() when running "ngircd --configtest".
322  */
323 GLOBAL int
324 Conf_Test( void )
325 {
326         struct passwd *pwd;
327         struct group *grp;
328         unsigned int i;
329         bool config_valid;
330         size_t predef_channel_count;
331         struct Conf_Channel *predef_chan;
332
333         Use_Log = false;
334
335         if (!Read_Config(true, true))
336                 return 1;
337
338         config_valid = Validate_Config(true, false);
339
340         /* Valid tty? */
341         if(isatty(fileno(stdin)) && isatty(fileno(stdout))) {
342                 puts("OK, press enter to see a dump of your server configuration ...");
343                 getchar();
344         } else
345                 puts("Ok, dump of your server configuration follows:\n");
346
347         puts("[GLOBAL]");
348         printf("  Name = %s\n", Conf_ServerName);
349         printf("  AdminInfo1 = %s\n", Conf_ServerAdmin1);
350         printf("  AdminInfo2 = %s\n", Conf_ServerAdmin2);
351         printf("  AdminEMail = %s\n", Conf_ServerAdminMail);
352         printf("  HelpFile = %s\n", Conf_HelpFile);
353         printf("  Info = %s\n", Conf_ServerInfo);
354         printf("  Listen = %s\n", Conf_ListenAddress);
355         if (Using_MotdFile) {
356                 printf("  MotdFile = %s\n", Conf_MotdFile);
357                 printf("  MotdPhrase =\n");
358         } else {
359                 printf("  MotdFile = \n");
360                 printf("  MotdPhrase = %s\n", array_bytes(&Conf_Motd)
361                        ? (const char*) array_start(&Conf_Motd) : "");
362         }
363 #ifndef PAM
364         printf("  Password = %s\n", Conf_ServerPwd);
365 #endif
366         printf("  PidFile = %s\n", Conf_PidFile);
367         printf("  Ports = ");
368         ports_puts(&Conf_ListenPorts);
369         grp = getgrgid(Conf_GID);
370         if (grp)
371                 printf("  ServerGID = %s\n", grp->gr_name);
372         else
373                 printf("  ServerGID = %ld\n", (long)Conf_GID);
374         pwd = getpwuid(Conf_UID);
375         if (pwd)
376                 printf("  ServerUID = %s\n", pwd->pw_name);
377         else
378                 printf("  ServerUID = %ld\n", (long)Conf_UID);
379         puts("");
380
381         puts("[LIMITS]");
382         printf("  ConnectRetry = %d\n", Conf_ConnectRetry);
383         printf("  IdleTimeout = %d\n", Conf_IdleTimeout);
384         printf("  MaxConnections = %d\n", Conf_MaxConnections);
385         printf("  MaxConnectionsIP = %d\n", Conf_MaxConnectionsIP);
386         printf("  MaxJoins = %d\n", Conf_MaxJoins > 0 ? Conf_MaxJoins : -1);
387         printf("  MaxNickLength = %u\n", Conf_MaxNickLength - 1);
388         printf("  MaxListSize = %d\n", Conf_MaxListSize);
389         printf("  PingTimeout = %d\n", Conf_PingTimeout);
390         printf("  PongTimeout = %d\n", Conf_PongTimeout);
391         puts("");
392
393         puts("[OPTIONS]");
394         printf("  AllowRemoteOper = %s\n", yesno_to_str(Conf_AllowRemoteOper));
395         printf("  ChrootDir = %s\n", Conf_Chroot);
396         printf("  CloakHost = %s\n", Conf_CloakHost);
397         printf("  CloakHostModeX = %s\n", Conf_CloakHostModeX);
398         printf("  CloakHostSalt = %s\n", Conf_CloakHostSalt);
399         printf("  CloakUserToNick = %s\n", yesno_to_str(Conf_CloakUserToNick));
400 #ifdef WANT_IPV6
401         printf("  ConnectIPv4 = %s\n", yesno_to_str(Conf_ConnectIPv6));
402         printf("  ConnectIPv6 = %s\n", yesno_to_str(Conf_ConnectIPv4));
403 #endif
404         printf("  DNS = %s\n", yesno_to_str(Conf_DNS));
405 #ifdef IDENT
406         printf("  Ident = %s\n", yesno_to_str(Conf_Ident));
407 #endif
408         printf("  IncludeDir = %s\n", Conf_IncludeDir);
409         printf("  MorePrivacy = %s\n", yesno_to_str(Conf_MorePrivacy));
410         printf("  NoticeAuth = %s\n", yesno_to_str(Conf_NoticeAuth));
411         printf("  OperCanUseMode = %s\n", yesno_to_str(Conf_OperCanMode));
412         printf("  OperChanPAutoOp = %s\n", yesno_to_str(Conf_OperChanPAutoOp));
413         printf("  OperServerMode = %s\n", yesno_to_str(Conf_OperServerMode));
414 #ifdef PAM
415         printf("  PAM = %s\n", yesno_to_str(Conf_PAM));
416         printf("  PAMIsOptional = %s\n", yesno_to_str(Conf_PAMIsOptional));
417 #endif
418         printf("  PredefChannelsOnly = %s\n", yesno_to_str(Conf_PredefChannelsOnly));
419 #ifndef STRICT_RFC
420         printf("  RequireAuthPing = %s\n", yesno_to_str(Conf_AuthPing));
421 #endif
422         printf("  ScrubCTCP = %s\n", yesno_to_str(Conf_ScrubCTCP));
423 #ifdef SYSLOG
424         printf("  SyslogFacility = %s\n",
425                ngt_SyslogFacilityName(Conf_SyslogFacility));
426 #endif
427         printf("  WebircPassword = %s\n", Conf_WebircPwd);
428         puts("");
429
430 #ifdef SSL_SUPPORT
431         puts("[SSL]");
432         printf("  CertFile = %s\n", Conf_SSLOptions.CertFile
433                                         ? Conf_SSLOptions.CertFile : "");
434         printf("  DHFile = %s\n", Conf_SSLOptions.DHFile
435                                         ? Conf_SSLOptions.DHFile : "");
436         printf("  KeyFile = %s\n", Conf_SSLOptions.KeyFile
437                                         ? Conf_SSLOptions.KeyFile : "");
438         if (array_bytes(&Conf_SSLOptions.KeyFilePassword))
439                 puts("  KeyFilePassword = <secret>");
440         else
441                 puts("  KeyFilePassword = ");
442         array_free_wipe(&Conf_SSLOptions.KeyFilePassword);
443         printf("  Ports = ");
444         ports_puts(&Conf_SSLOptions.ListenPorts);
445         puts("");
446 #endif
447
448         opers_puts();
449
450         for( i = 0; i < MAX_SERVERS; i++ ) {
451                 if( ! Conf_Server[i].name[0] ) continue;
452
453                 /* Valid "Server" section */
454                 puts( "[SERVER]" );
455                 printf( "  Name = %s\n", Conf_Server[i].name );
456                 printf( "  Host = %s\n", Conf_Server[i].host );
457                 printf( "  Port = %u\n", (unsigned int)Conf_Server[i].port );
458 #ifdef SSL_SUPPORT
459                 printf( "  SSLConnect = %s\n", Conf_Server[i].SSLConnect?"yes":"no");
460 #endif
461                 printf( "  MyPassword = %s\n", Conf_Server[i].pwd_in );
462                 printf( "  PeerPassword = %s\n", Conf_Server[i].pwd_out );
463                 printf( "  ServiceMask = %s\n", Conf_Server[i].svs_mask);
464                 printf( "  Group = %d\n", Conf_Server[i].group );
465                 printf( "  Passive = %s\n\n", Conf_Server[i].flags & CONF_SFLAG_DISABLED ? "yes" : "no");
466         }
467
468         predef_channel_count = array_length(&Conf_Channels, sizeof(*predef_chan));
469         predef_chan = array_start(&Conf_Channels);
470
471         for (i = 0; i < predef_channel_count; i++, predef_chan++) {
472                 if (!predef_chan->name[0])
473                         continue;
474
475                 /* Valid "Channel" section */
476                 puts( "[CHANNEL]" );
477                 printf("  Name = %s\n", predef_chan->name);
478                 printf("  Modes = %s\n", predef_chan->modes);
479                 printf("  Key = %s\n", predef_chan->key);
480                 printf("  MaxUsers = %lu\n", predef_chan->maxusers);
481                 printf("  Topic = %s\n", predef_chan->topic);
482                 printf("  KeyFile = %s\n\n", predef_chan->keyfile);
483         }
484
485         return (config_valid ? 0 : 1);
486 }
487
488 /**
489  * Remove connection information from configured server.
490  *
491  * If the server is set as "once", delete it from our configuration;
492  * otherwise set the time for the next connection attempt.
493  *
494  * Non-server connections will be silently ignored.
495  */
496 GLOBAL void
497 Conf_UnsetServer( CONN_ID Idx )
498 {
499         int i;
500         time_t t;
501
502         /* Check all our configured servers */
503         for( i = 0; i < MAX_SERVERS; i++ ) {
504                 if( Conf_Server[i].conn_id != Idx ) continue;
505
506                 /* Gotcha! Mark server configuration as "unused": */
507                 Conf_Server[i].conn_id = NONE;
508
509                 if( Conf_Server[i].flags & CONF_SFLAG_ONCE ) {
510                         /* Delete configuration here */
511                         Init_Server_Struct( &Conf_Server[i] );
512                 } else {
513                         /* Set time for next connect attempt */
514                         t = time(NULL);
515                         if (Conf_Server[i].lasttry < t - Conf_ConnectRetry) {
516                                 /* The connection has been "long", so we don't
517                                  * require the next attempt to be delayed. */
518                                 Conf_Server[i].lasttry =
519                                         t - Conf_ConnectRetry + RECONNECT_DELAY;
520                         } else {
521                                 /* "Short" connection, enforce "ConnectRetry"
522                                  * but randomize it a little bit: 15 seconds. */
523                                 Conf_Server[i].lasttry =
524                                         t + rand() / (RAND_MAX / 15);
525                         }
526                 }
527         }
528 }
529
530 /**
531  * Set connection information for specified configured server.
532  */
533 GLOBAL bool
534 Conf_SetServer( int ConfServer, CONN_ID Idx )
535 {
536         assert( ConfServer > NONE );
537         assert( Idx > NONE );
538
539         if (Conf_Server[ConfServer].conn_id > NONE &&
540             Conf_Server[ConfServer].conn_id != Idx) {
541                 Log(LOG_ERR,
542                     "Connection %d: Server configuration of \"%s\" already in use by connection %d!",
543                     Idx, Conf_Server[ConfServer].name,
544                     Conf_Server[ConfServer].conn_id);
545                 Conn_Close(Idx, NULL, "Server configuration already in use", true);
546                 return false;
547         }
548         Conf_Server[ConfServer].conn_id = Idx;
549         return true;
550 }
551
552 /**
553  * Get index of server in configuration structure.
554  */
555 GLOBAL int
556 Conf_GetServer( CONN_ID Idx )
557 {
558         int i = 0;
559
560         assert( Idx > NONE );
561
562         for( i = 0; i < MAX_SERVERS; i++ ) {
563                 if( Conf_Server[i].conn_id == Idx ) return i;
564         }
565         return NONE;
566 }
567
568 /**
569  * Enable a server by name and adjust its port number.
570  *
571  * @returns     true if a server has been enabled and now has a valid port
572  *              number and host name for outgoing connections.
573  */
574 GLOBAL bool
575 Conf_EnableServer( const char *Name, UINT16 Port )
576 {
577         int i;
578
579         assert( Name != NULL );
580         for( i = 0; i < MAX_SERVERS; i++ ) {
581                 if( strcasecmp( Conf_Server[i].name, Name ) == 0 ) {
582                         /* Gotcha! Set port and enable server: */
583                         Conf_Server[i].port = Port;
584                         Conf_Server[i].flags &= ~CONF_SFLAG_DISABLED;
585                         return (Conf_Server[i].port && Conf_Server[i].host[0]);
586                 }
587         }
588         return false;
589 }
590
591 /**
592  * Enable a server by name.
593  *
594  * The server is only usable as outgoing server, if it has set a valid port
595  * number for outgoing connections!
596  * If not, you have to use Conf_EnableServer() function to make it available.
597  *
598  * @returns     true if a server has been enabled; false otherwise.
599  */
600 GLOBAL bool
601 Conf_EnablePassiveServer(const char *Name)
602 {
603         int i;
604
605         assert( Name != NULL );
606         for (i = 0; i < MAX_SERVERS; i++) {
607                 if ((strcasecmp( Conf_Server[i].name, Name ) == 0)
608                     && (Conf_Server[i].port > 0)) {
609                         /* BINGO! Enable server */
610                         Conf_Server[i].flags &= ~CONF_SFLAG_DISABLED;
611                         return true;
612                 }
613         }
614         return false;
615 }
616
617 /**
618  * Disable a server by name.
619  * An already established connection will be disconnected.
620  *
621  * @returns     true if a server was found and has been disabled.
622  */
623 GLOBAL bool
624 Conf_DisableServer( const char *Name )
625 {
626         int i;
627
628         assert( Name != NULL );
629         for( i = 0; i < MAX_SERVERS; i++ ) {
630                 if( strcasecmp( Conf_Server[i].name, Name ) == 0 ) {
631                         /* Gotcha! Disable and disconnect server: */
632                         Conf_Server[i].flags |= CONF_SFLAG_DISABLED;
633                         if( Conf_Server[i].conn_id > NONE )
634                                 Conn_Close(Conf_Server[i].conn_id, NULL,
635                                            "Server link terminated on operator request",
636                                            true);
637                         return true;
638                 }
639         }
640         return false;
641 }
642
643 /**
644  * Add a new remote server to our configuration.
645  *
646  * @param Name          Name of the new server.
647  * @param Port          Port number to connect to or 0 for incoming connections.
648  * @param Host          Host name to connect to.
649  * @param MyPwd         Password that will be sent to the peer.
650  * @param PeerPwd       Password that must be received from the peer.
651  * @returns             true if the new server has been added; false otherwise.
652  */
653 GLOBAL bool
654 Conf_AddServer(const char *Name, UINT16 Port, const char *Host,
655                const char *MyPwd, const char *PeerPwd)
656 {
657         int i;
658
659         assert( Name != NULL );
660         assert( Host != NULL );
661         assert( MyPwd != NULL );
662         assert( PeerPwd != NULL );
663
664         /* Search unused item in server configuration structure */
665         for( i = 0; i < MAX_SERVERS; i++ ) {
666                 /* Is this item used? */
667                 if( ! Conf_Server[i].name[0] ) break;
668         }
669         if( i >= MAX_SERVERS ) return false;
670
671         Init_Server_Struct( &Conf_Server[i] );
672         strlcpy( Conf_Server[i].name, Name, sizeof( Conf_Server[i].name ));
673         strlcpy( Conf_Server[i].host, Host, sizeof( Conf_Server[i].host ));
674         strlcpy( Conf_Server[i].pwd_out, MyPwd, sizeof( Conf_Server[i].pwd_out ));
675         strlcpy( Conf_Server[i].pwd_in, PeerPwd, sizeof( Conf_Server[i].pwd_in ));
676         Conf_Server[i].port = Port;
677         Conf_Server[i].flags = CONF_SFLAG_ONCE;
678
679         return true;
680 }
681
682 /**
683  * Check if the given nickname is reserved for services on a particular server.
684  *
685  * @param ConfServer The server index to check.
686  * @param Nick The nickname to check.
687  * @returns true if the given nickname belongs to an "IRC service".
688  */
689 GLOBAL bool
690 Conf_NickIsService(int ConfServer, const char *Nick)
691 {
692         assert (ConfServer >= 0);
693         assert (ConfServer < MAX_SERVERS);
694
695         return MatchCaseInsensitiveList(Conf_Server[ConfServer].svs_mask,
696                                         Nick, ",");
697 }
698
699 /**
700  * Check if the given nickname is blocked for "normal client" use.
701  *
702  * @param ConfServer The server index or NONE to check all configured servers.
703  * @param Nick The nickname to check.
704  * @returns true if the given nickname belongs to an "IRC service".
705  */
706 GLOBAL bool
707 Conf_NickIsBlocked(const char *Nick)
708 {
709         int i;
710
711         for(i = 0; i < MAX_SERVERS; i++) {
712                 if (!Conf_Server[i].name[0])
713                         continue;
714                 if (Conf_NickIsService(i, Nick))
715                         return true;
716         }
717         return false;
718 }
719
720 /**
721  * Initialize configuration settings with their default values.
722  */
723 static void
724 Set_Defaults(bool InitServers)
725 {
726         int i;
727         char random[RANDOM_SALT_LEN + 1];
728
729         /* Global */
730         strcpy(Conf_ServerName, "");
731         strcpy(Conf_ServerAdmin1, "");
732         strcpy(Conf_ServerAdmin2, "");
733         strcpy(Conf_ServerAdminMail, "");
734         snprintf(Conf_ServerInfo, sizeof Conf_ServerInfo, "%s %s",
735                  PACKAGE_NAME, PACKAGE_VERSION);
736         free(Conf_ListenAddress);
737         Conf_ListenAddress = NULL;
738         array_free(&Conf_ListenPorts);
739         array_free(&Conf_Motd);
740         array_free(&Conf_Helptext);
741         strlcpy(Conf_MotdFile, SYSCONFDIR, sizeof(Conf_MotdFile));
742         strlcat(Conf_MotdFile, MOTD_FILE, sizeof(Conf_MotdFile));
743         strlcpy(Conf_HelpFile, DOCDIR, sizeof(Conf_HelpFile));
744         strlcat(Conf_HelpFile, HELP_FILE, sizeof(Conf_HelpFile));
745         strcpy(Conf_ServerPwd, "");
746         strlcpy(Conf_PidFile, PID_FILE, sizeof(Conf_PidFile));
747         Conf_UID = Conf_GID = 0;
748
749         /* Limits */
750         Conf_ConnectRetry = 60;
751         Conf_IdleTimeout = 0;
752         Conf_MaxConnections = 0;
753         Conf_MaxConnectionsIP = 5;
754         Conf_MaxJoins = 10;
755         Conf_MaxNickLength = CLIENT_NICK_LEN_DEFAULT;
756         Conf_MaxListSize = 100;
757         Conf_PingTimeout = 120;
758         Conf_PongTimeout = 20;
759
760         /* Options */
761         Conf_AllowRemoteOper = false;
762 #ifndef STRICT_RFC
763         Conf_AuthPing = false;
764 #endif
765         strlcpy(Conf_Chroot, CHROOT_DIR, sizeof(Conf_Chroot));
766         strcpy(Conf_CloakHost, "");
767         strcpy(Conf_CloakHostModeX, "");
768         strlcpy(Conf_CloakHostSalt, ngt_RandomStr(random, RANDOM_SALT_LEN),
769                 sizeof(Conf_CloakHostSalt));
770         Conf_CloakUserToNick = false;
771         Conf_ConnectIPv4 = true;
772 #ifdef WANT_IPV6
773         Conf_ConnectIPv6 = true;
774 #else
775         Conf_ConnectIPv6 = false;
776 #endif
777         Conf_DNS = true;
778 #ifdef IDENTAUTH
779         Conf_Ident = true;
780 #else
781         Conf_Ident = false;
782 #endif
783         strcpy(Conf_IncludeDir, "");
784         Conf_MorePrivacy = false;
785         Conf_NoticeAuth = false;
786         Conf_OperCanMode = false;
787         Conf_OperChanPAutoOp = true;
788         Conf_OperServerMode = false;
789 #ifdef PAM
790         Conf_PAM = true;
791 #else
792         Conf_PAM = false;
793 #endif
794         Conf_PAMIsOptional = false;
795         Conf_PredefChannelsOnly = false;
796 #ifdef SYSLOG
797         Conf_ScrubCTCP = false;
798 #ifdef LOG_LOCAL5
799         Conf_SyslogFacility = LOG_LOCAL5;
800 #else
801         Conf_SyslogFacility = 0;
802 #endif
803 #endif
804
805         /* Initialize server configuration structures */
806         if (InitServers) {
807                 for (i = 0; i < MAX_SERVERS;
808                      Init_Server_Struct(&Conf_Server[i++]));
809         }
810 }
811
812 /**
813  * Get number of configured listening ports.
814  *
815  * @returns The number of ports (IPv4+IPv6) on which the server should listen.
816  */
817 static bool
818 no_listenports(void)
819 {
820         size_t cnt = array_bytes(&Conf_ListenPorts);
821 #ifdef SSL_SUPPORT
822         cnt += array_bytes(&Conf_SSLOptions.ListenPorts);
823 #endif
824         return cnt == 0;
825 }
826
827 /**
828  * Read contents of a text file into an array.
829  *
830  * This function is used to read the MOTD and help text file, for exampe.
831  *
832  * @param filename      Name of the file to read.
833  * @return              true, when the file has been read in.
834  */
835 static bool
836 Read_TextFile(const char *Filename, const char *Name, array *Destination)
837 {
838         char line[127];
839         FILE *fp;
840         int line_no = 1;
841
842         if (*Filename == '\0')
843                 return false;
844
845         fp = fopen(Filename, "r");
846         if (!fp) {
847                 Config_Error(LOG_ERR, "Can't read %s file \"%s\": %s",
848                              Name, Filename, strerror(errno));
849                 return false;
850         }
851
852         array_free(Destination);
853         while (fgets(line, (int)sizeof line, fp)) {
854                 ngt_TrimLastChr(line, '\n');
855
856                 /* add text including \0 */
857                 if (!array_catb(Destination, line, strlen(line) + 1)) {
858                         Log(LOG_ERR, "Cannot read/add \"%s\", line %d: %s",
859                             Filename, line_no, strerror(errno));
860                         break;
861                 }
862                 line_no++;
863         }
864         fclose(fp);
865         return true;
866 }
867
868 /**
869  * Read ngIRCd configuration file.
870  *
871  * Please note that this function uses exit(1) on fatal errors and therefore
872  * can result in ngIRCd terminating!
873  *
874  * @param ngircd_starting       Flag indicating if ngIRCd is starting or not.
875  * @returns                     true when the configuration file has been read
876  *                              successfully; false otherwise.
877  */
878 static bool
879 Read_Config(bool TestOnly, bool IsStarting)
880 {
881         const UINT16 defaultport = 6667;
882         char *ptr, file[FNAME_LEN];
883         struct dirent *entry;
884         int i, n;
885         FILE *fd;
886         DIR *dh;
887
888         /* Open configuration file */
889         fd = fopen( NGIRCd_ConfFile, "r" );
890         if( ! fd ) {
891                 /* No configuration file found! */
892                 Config_Error( LOG_ALERT, "Can't read configuration \"%s\": %s",
893                                         NGIRCd_ConfFile, strerror( errno ));
894                 if (!IsStarting)
895                         return false;
896                 Config_Error( LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE_NAME );
897                 exit( 1 );
898         }
899
900         opers_free();
901         Set_Defaults(IsStarting);
902
903         if (TestOnly)
904                 Config_Error(LOG_INFO,
905                              "Reading configuration from \"%s\" ...",
906                              NGIRCd_ConfFile );
907
908         /* Clean up server configuration structure: mark all already
909          * configured servers as "once" so that they are deleted
910          * after the next disconnect and delete all unused servers.
911          * And delete all servers which are "duplicates" of servers
912          * that are already marked as "once" (such servers have been
913          * created by the last rehash but are now useless). */
914         for( i = 0; i < MAX_SERVERS; i++ ) {
915                 if( Conf_Server[i].conn_id == NONE ) Init_Server_Struct( &Conf_Server[i] );
916                 else {
917                         /* This structure is in use ... */
918                         if( Conf_Server[i].flags & CONF_SFLAG_ONCE ) {
919                                 /* Check for duplicates */
920                                 for( n = 0; n < MAX_SERVERS; n++ ) {
921                                         if( n == i ) continue;
922
923                                         if( Conf_Server[i].conn_id == Conf_Server[n].conn_id ) {
924                                                 Init_Server_Struct( &Conf_Server[n] );
925 #ifdef DEBUG
926                                                 Log(LOG_DEBUG,"Deleted unused duplicate server %d (kept %d).",
927                                                                                                 n, i );
928 #endif
929                                         }
930                                 }
931                         } else {
932                                 /* Mark server as "once" */
933                                 Conf_Server[i].flags |= CONF_SFLAG_ONCE;
934                                 Log( LOG_DEBUG, "Marked server %d as \"once\"", i );
935                         }
936                 }
937         }
938
939         /* Initialize variables */
940         Init_Server_Struct( &New_Server );
941         New_Server_Idx = NONE;
942 #ifdef SSL_SUPPORT
943         ConfSSL_Init();
944 #endif
945
946         Read_Config_File(NGIRCd_ConfFile, fd);
947         fclose(fd);
948
949         if (Conf_IncludeDir[0]) {
950                 /* Include further configuration files, if any */
951                 dh = opendir(Conf_IncludeDir);
952                 if (dh) {
953                         while ((entry = readdir(dh)) != NULL) {
954                                 ptr = strrchr(entry->d_name, '.');
955                                 if (!ptr || strcasecmp(ptr, ".conf") != 0)
956                                         continue;
957                                 snprintf(file, sizeof(file), "%s/%s",
958                                          Conf_IncludeDir, entry->d_name);
959                                 if (TestOnly)
960                                         Config_Error(LOG_INFO,
961                                                      "Reading configuration from \"%s\" ...",
962                                                      file);
963                                 fd = fopen(file, "r");
964                                 if (fd) {
965                                         Read_Config_File(file, fd);
966                                         fclose(fd);
967                                 } else
968                                         Config_Error(LOG_ALERT,
969                                                      "Can't read configuration \"%s\": %s",
970                                                      file, strerror(errno));
971                         }
972                         closedir(dh);
973                 } else
974                         Config_Error(LOG_ALERT,
975                                      "Can't open include directory \"%s\": %s",
976                                      Conf_IncludeDir, strerror(errno));
977         }
978
979         /* Check if there is still a server to add */
980         if( New_Server.name[0] ) {
981                 /* Copy data to "real" server structure */
982                 assert( New_Server_Idx > NONE );
983                 Conf_Server[New_Server_Idx] = New_Server;
984         }
985
986         /* not a single listening port? Add default. */
987         if (no_listenports() &&
988                 !array_copyb(&Conf_ListenPorts, (char*) &defaultport, sizeof defaultport))
989         {
990                 Config_Error(LOG_ALERT, "Could not add default listening Port %u: %s",
991                                         (unsigned int) defaultport, strerror(errno));
992
993                 exit(1);
994         }
995
996         if (!Conf_ListenAddress)
997                 Conf_ListenAddress = strdup_warn(DEFAULT_LISTEN_ADDRSTR);
998
999         if (!Conf_ListenAddress) {
1000                 Config_Error(LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE_NAME);
1001                 exit(1);
1002         }
1003
1004         /* No MOTD phrase configured? (re)try motd file. */
1005         if (array_bytes(&Conf_Motd) == 0) {
1006                 if (Read_TextFile(Conf_MotdFile, "MOTD", &Conf_Motd))
1007                         Using_MotdFile = true;
1008         }
1009
1010         /* Try to read ngIRCd help text file. */
1011         (void)Read_TextFile(Conf_HelpFile, "help text", &Conf_Helptext);
1012         if (!array_bytes(&Conf_Helptext))
1013                 Config_Error(LOG_WARNING,
1014                     "No help text available, HELP command will be of limited use.");
1015
1016 #ifdef SSL_SUPPORT
1017         /* Make sure that all SSL-related files are readable */
1018         CheckFileReadable("CertFile", Conf_SSLOptions.CertFile);
1019         CheckFileReadable("DHFile", Conf_SSLOptions.DHFile);
1020         CheckFileReadable("KeyFile", Conf_SSLOptions.KeyFile);
1021 #endif
1022
1023         return true;
1024 }
1025
1026 /**
1027  * ...
1028  */
1029 static void Read_Config_File(const char *File, FILE *fd)
1030 {
1031         char section[LINE_LEN], str[LINE_LEN], *var, *arg, *ptr;
1032         int i, line = 0;
1033         size_t count;
1034
1035         /* Read configuration file */
1036         section[0] = '\0';
1037         while (true) {
1038                 if (!fgets(str, LINE_LEN, fd))
1039                         break;
1040                 ngt_TrimStr(str);
1041                 line++;
1042
1043                 /* Skip comments and empty lines */
1044                 if (str[0] == ';' || str[0] == '#' || str[0] == '\0')
1045                         continue;
1046
1047                 /* Is this the beginning of a new section? */
1048                 if ((str[0] == '[') && (str[strlen(str) - 1] == ']')) {
1049                         strlcpy(section, str, sizeof(section));
1050                         if (strcasecmp(section, "[GLOBAL]") == 0
1051                             || strcasecmp(section, "[LIMITS]") == 0
1052                             || strcasecmp(section, "[OPTIONS]") == 0
1053 #ifdef SSL_SUPPORT
1054                             || strcasecmp(section, "[SSL]") == 0
1055 #endif
1056                             )
1057                                 continue;
1058
1059                         if (strcasecmp(section, "[SERVER]") == 0) {
1060                                 /* Check if there is already a server to add */
1061                                 if (New_Server.name[0]) {
1062                                         /* Copy data to "real" server structure */
1063                                         assert(New_Server_Idx > NONE);
1064                                         Conf_Server[New_Server_Idx] =
1065                                         New_Server;
1066                                 }
1067
1068                                 /* Re-init structure for new server */
1069                                 Init_Server_Struct(&New_Server);
1070
1071                                 /* Search unused item in server configuration structure */
1072                                 for (i = 0; i < MAX_SERVERS; i++) {
1073                                         /* Is this item used? */
1074                                         if (!Conf_Server[i].name[0])
1075                                                 break;
1076                                 }
1077                                 if (i >= MAX_SERVERS) {
1078                                         /* Oops, no free item found! */
1079                                         Config_Error(LOG_ERR,
1080                                                      "Too many servers configured.");
1081                                         New_Server_Idx = NONE;
1082                                 } else
1083                                         New_Server_Idx = i;
1084                                 continue;
1085                         }
1086
1087                         if (strcasecmp(section, "[CHANNEL]") == 0) {
1088                                 count = array_length(&Conf_Channels,
1089                                                      sizeof(struct
1090                                                             Conf_Channel));
1091                                 if (!array_alloc
1092                                     (&Conf_Channels,
1093                                      sizeof(struct Conf_Channel), count)) {
1094                                             Config_Error(LOG_ERR,
1095                                                          "Could not allocate memory for new operator (line %d)",
1096                                                          line);
1097                                     }
1098                                 continue;
1099                         }
1100
1101                         if (strcasecmp(section, "[OPERATOR]") == 0) {
1102                                 count = array_length(&Conf_Opers,
1103                                                      sizeof(struct Conf_Oper));
1104                                 if (!array_alloc(&Conf_Opers,
1105                                                  sizeof(struct Conf_Oper),
1106                                                  count)) {
1107                                         Config_Error(LOG_ERR,
1108                                                      "Could not allocate memory for new channel (line &d)",
1109                                                      line);
1110                                 }
1111                                 continue;
1112                         }
1113
1114                         Config_Error(LOG_ERR,
1115                                      "%s, line %d: Unknown section \"%s\"!",
1116                                      NGIRCd_ConfFile, line, section);
1117                         section[0] = 0x1;
1118                 }
1119                 if (section[0] == 0x1)
1120                         continue;
1121
1122                 /* Split line into variable name and parameters */
1123                 ptr = strchr(str, '=');
1124                 if (!ptr) {
1125                         Config_Error(LOG_ERR, "%s, line %d: Syntax error!",
1126                                      NGIRCd_ConfFile, line);
1127                         continue;
1128                 }
1129                 *ptr = '\0';
1130                 var = str;
1131                 ngt_TrimStr(var);
1132                 arg = ptr + 1;
1133                 ngt_TrimStr(arg);
1134
1135                 if (strcasecmp(section, "[GLOBAL]") == 0)
1136                         Handle_GLOBAL(File, line, var, arg);
1137                 else if (strcasecmp(section, "[LIMITS]") == 0)
1138                         Handle_LIMITS(File, line, var, arg);
1139                 else if (strcasecmp(section, "[OPTIONS]") == 0)
1140                         Handle_OPTIONS(File, line, var, arg);
1141 #ifdef SSL_SUPPORT
1142                 else if (strcasecmp(section, "[SSL]") == 0)
1143                         Handle_SSL(File, line, var, arg);
1144 #endif
1145                 else if (strcasecmp(section, "[OPERATOR]") == 0)
1146                         Handle_OPERATOR(File, line, var, arg);
1147                 else if (strcasecmp(section, "[SERVER]") == 0)
1148                         Handle_SERVER(File, line, var, arg);
1149                 else if (strcasecmp(section, "[CHANNEL]") == 0)
1150                         Handle_CHANNEL(File, line, var, arg);
1151                 else
1152                         Config_Error(LOG_ERR,
1153                                      "%s, line %d: Variable \"%s\" outside section!",
1154                                      NGIRCd_ConfFile, line, var);
1155         }
1156 }
1157
1158 /**
1159  * Check whether a string argument is "true" or "false".
1160  *
1161  * @param Arg   Input string.
1162  * @returns     true if the input string has been parsed as "yes", "true"
1163  *              (case insensitive) or a non-zero integer value.
1164  */
1165 static bool
1166 Check_ArgIsTrue(const char *Arg)
1167 {
1168         if (strcasecmp(Arg, "yes") == 0)
1169                 return true;
1170         if (strcasecmp(Arg, "true") == 0)
1171                 return true;
1172         if (atoi(Arg) != 0)
1173                 return true;
1174
1175         return false;
1176 }
1177
1178 /**
1179  * Handle setting of "MaxNickLength".
1180  *
1181  * @param Line  Line number in configuration file.
1182  * @raram Arg   Input string.
1183  * @returns     New configured maximum nickname length.
1184  */
1185 static unsigned int
1186 Handle_MaxNickLength(int Line, const char *Arg)
1187 {
1188         unsigned new;
1189
1190         new = (unsigned) atoi(Arg) + 1;
1191         if (new > CLIENT_NICK_LEN) {
1192                 Config_Error(LOG_WARNING,
1193                              "%s, line %d: Value of \"MaxNickLength\" exceeds %u!",
1194                              NGIRCd_ConfFile, Line, CLIENT_NICK_LEN - 1);
1195                 return CLIENT_NICK_LEN;
1196         }
1197         if (new < 2) {
1198                 Config_Error(LOG_WARNING,
1199                              "%s, line %d: Value of \"MaxNickLength\" must be at least 1!",
1200                              NGIRCd_ConfFile, Line);
1201                 return 2;
1202         }
1203         return new;
1204 }
1205
1206 /**
1207  * Output a warning messages if IDENT is configured but not compiled in.
1208  */
1209 static void
1210 WarnIdent(int UNUSED Line)
1211 {
1212 #ifndef IDENTAUTH
1213         if (Conf_Ident) {
1214                 /* user has enabled ident lookups explicitly, but ... */
1215                 Config_Error(LOG_WARNING,
1216                         "%s: line %d: \"Ident = yes\", but ngircd was built without IDENT support!",
1217                         NGIRCd_ConfFile, Line);
1218         }
1219 #endif
1220 }
1221
1222 /**
1223  * Output a warning messages if IPv6 is configured but not compiled in.
1224  */
1225 static void
1226 WarnIPv6(int UNUSED Line)
1227 {
1228 #ifndef WANT_IPV6
1229         if (Conf_ConnectIPv6) {
1230                 /* user has enabled IPv6 explicitly, but ... */
1231                 Config_Error(LOG_WARNING,
1232                         "%s: line %d: \"ConnectIPv6 = yes\", but ngircd was built without IPv6 support!",
1233                         NGIRCd_ConfFile, Line);
1234         }
1235 #endif
1236 }
1237
1238 /**
1239  * Output a warning messages if PAM is configured but not compiled in.
1240  */
1241 static void
1242 WarnPAM(int UNUSED Line)
1243 {
1244 #ifndef PAM
1245         if (Conf_PAM) {
1246                 Config_Error(LOG_WARNING,
1247                         "%s: line %d: \"PAM = yes\", but ngircd was built without PAM support!",
1248                         NGIRCd_ConfFile, Line);
1249         }
1250 #endif
1251 }
1252
1253 /**
1254  * Handle legacy "NoXXX" options in [GLOBAL] section.
1255  *
1256  * TODO: This function and support for "NoXXX" could be removed starting
1257  * with ngIRCd release 19 (one release after marking it "deprecated").
1258  *
1259  * @param Var   Variable name.
1260  * @param Arg   Argument string.
1261  * @returns     true if a NoXXX option has been processed; false otherwise.
1262  */
1263 static bool
1264 CheckLegacyNoOption(const char *Var, const char *Arg)
1265 {
1266         if(strcasecmp(Var, "NoDNS") == 0) {
1267                 Conf_DNS = !Check_ArgIsTrue( Arg );
1268                 return true;
1269         }
1270         if (strcasecmp(Var, "NoIdent") == 0) {
1271                 Conf_Ident = !Check_ArgIsTrue(Arg);
1272                 return true;
1273         }
1274         if(strcasecmp(Var, "NoPAM") == 0) {
1275                 Conf_PAM = !Check_ArgIsTrue(Arg);
1276                 return true;
1277         }
1278         return false;
1279 }
1280
1281 /**
1282  * Handle deprecated legacy options in [GLOBAL] section.
1283  *
1284  * TODO: This function and support for these options in the [Global] section
1285  * could be removed starting with ngIRCd release 19 (one release after
1286  * marking it "deprecated").
1287  *
1288  * @param Var   Variable name.
1289  * @param Arg   Argument string.
1290  * @returns     true if a legacy option has been processed; false otherwise.
1291  */
1292 static const char*
1293 CheckLegacyGlobalOption(const char *File, int Line, char *Var, char *Arg)
1294 {
1295         if (strcasecmp(Var, "AllowRemoteOper") == 0
1296             || strcasecmp(Var, "ChrootDir") == 0
1297             || strcasecmp(Var, "ConnectIPv4") == 0
1298             || strcasecmp(Var, "ConnectIPv6") == 0
1299             || strcasecmp(Var, "OperCanUseMode") == 0
1300             || strcasecmp(Var, "OperChanPAutoOp") == 0
1301             || strcasecmp(Var, "OperServerMode") == 0
1302             || strcasecmp(Var, "PredefChannelsOnly") == 0
1303             || strcasecmp(Var, "SyslogFacility") == 0
1304             || strcasecmp(Var, "WebircPassword") == 0) {
1305                 Handle_OPTIONS(File, Line, Var, Arg);
1306                 return "[Options]";
1307         }
1308         if (strcasecmp(Var, "ConnectRetry") == 0
1309             || strcasecmp(Var, "IdleTimeout") == 0
1310             || strcasecmp(Var, "MaxConnections") == 0
1311             || strcasecmp(Var, "MaxConnectionsIP") == 0
1312             || strcasecmp(Var, "MaxJoins") == 0
1313             || strcasecmp(Var, "MaxNickLength") == 0
1314             || strcasecmp(Var, "PingTimeout") == 0
1315             || strcasecmp(Var, "PongTimeout") == 0) {
1316                 Handle_LIMITS(File, Line, Var, Arg);
1317                 return "[Limits]";
1318         }
1319 #ifdef SSL_SUPPORT
1320         if (strcasecmp(Var, "SSLCertFile") == 0
1321             || strcasecmp(Var, "SSLDHFile") == 0
1322             || strcasecmp(Var, "SSLKeyFile") == 0
1323             || strcasecmp(Var, "SSLKeyFilePassword") == 0
1324             || strcasecmp(Var, "SSLPorts") == 0) {
1325                 Handle_SSL(File, Line, Var + 3, Arg);
1326                 return "[SSL]";
1327         }
1328 #endif
1329
1330         return NULL;
1331 }
1332
1333 /**
1334  * Strip "no" prefix of a string.
1335  *
1336  * TODO: This function and support for "NoXXX" should be removed starting
1337  * with ngIRCd release 19! (One release after marking it "deprecated").
1338  *
1339  * @param str   Pointer to input string starting with "no".
1340  * @returns     New pointer to string without "no" prefix.
1341  */
1342 static const char *
1343 NoNo(const char *str)
1344 {
1345         assert(strncasecmp("no", str, 2) == 0 && str[2]);
1346         return str + 2;
1347 }
1348
1349 /**
1350  * Invert "boolean" string.
1351  *
1352  * TODO: This function and support for "NoXXX" should be removed starting
1353  * with ngIRCd release 19! (One release after marking it "deprecated").
1354  *
1355  * @param arg   "Boolean" input string.
1356  * @returns     Pointer to inverted "boolean string".
1357  */
1358 static const char *
1359 InvertArg(const char *arg)
1360 {
1361         return yesno_to_str(!Check_ArgIsTrue(arg));
1362 }
1363
1364 /**
1365  * Handle variable in [Global] configuration section.
1366  *
1367  * @param Line  Line numer in configuration file.
1368  * @param Var   Variable name.
1369  * @param Arg   Variable argument.
1370  */
1371 static void
1372 Handle_GLOBAL(const char *File, int Line, char *Var, char *Arg )
1373 {
1374         struct passwd *pwd;
1375         struct group *grp;
1376         size_t len;
1377         const char *section;
1378
1379         assert(File != NULL);
1380         assert(Line > 0);
1381         assert(Var != NULL);
1382         assert(Arg != NULL);
1383
1384         if (strcasecmp(Var, "Name") == 0) {
1385                 len = strlcpy(Conf_ServerName, Arg, sizeof(Conf_ServerName));
1386                 if (len >= sizeof(Conf_ServerName))
1387                         Config_Error_TooLong(File, Line, Var);
1388                 return;
1389         }
1390         if (strcasecmp(Var, "AdminInfo1") == 0) {
1391                 len = strlcpy(Conf_ServerAdmin1, Arg, sizeof(Conf_ServerAdmin1));
1392                 if (len >= sizeof(Conf_ServerAdmin1))
1393                         Config_Error_TooLong(File, Line, Var);
1394                 return;
1395         }
1396         if (strcasecmp(Var, "AdminInfo2") == 0) {
1397                 len = strlcpy(Conf_ServerAdmin2, Arg, sizeof(Conf_ServerAdmin2));
1398                 if (len >= sizeof(Conf_ServerAdmin2))
1399                         Config_Error_TooLong(File, Line, Var);
1400                 return;
1401         }
1402         if (strcasecmp(Var, "AdminEMail") == 0) {
1403                 len = strlcpy(Conf_ServerAdminMail, Arg,
1404                         sizeof(Conf_ServerAdminMail));
1405                 if (len >= sizeof(Conf_ServerAdminMail))
1406                         Config_Error_TooLong(File, Line, Var);
1407                 return;
1408         }
1409         if (strcasecmp(Var, "Info") == 0) {
1410                 len = strlcpy(Conf_ServerInfo, Arg, sizeof(Conf_ServerInfo));
1411                 if (len >= sizeof(Conf_ServerInfo))
1412                         Config_Error_TooLong(File, Line, Var);
1413                 return;
1414         }
1415         if (strcasecmp(Var, "HelpFile") == 0) {
1416                 len = strlcpy(Conf_HelpFile, Arg, sizeof(Conf_HelpFile));
1417                 if (len >= sizeof(Conf_HelpFile))
1418                         Config_Error_TooLong(File, Line, Var);
1419                 return;
1420         }
1421         if (strcasecmp(Var, "Listen") == 0) {
1422                 if (Conf_ListenAddress) {
1423                         Config_Error(LOG_ERR,
1424                                      "Multiple Listen= options, ignoring: %s",
1425                                      Arg);
1426                         return;
1427                 }
1428                 Conf_ListenAddress = strdup_warn(Arg);
1429                 /* If allocation fails, we're in trouble: we cannot ignore the
1430                  * error -- otherwise ngircd would listen on all interfaces. */
1431                 if (!Conf_ListenAddress) {
1432                         Config_Error(LOG_ALERT,
1433                                      "%s exiting due to fatal errors!",
1434                                      PACKAGE_NAME);
1435                         exit(1);
1436                 }
1437                 return;
1438         }
1439         if (strcasecmp(Var, "MotdFile") == 0) {
1440                 len = strlcpy(Conf_MotdFile, Arg, sizeof(Conf_MotdFile));
1441                 if (len >= sizeof(Conf_MotdFile))
1442                         Config_Error_TooLong(File, Line, Var);
1443                 return;
1444         }
1445         if (strcasecmp(Var, "MotdPhrase") == 0) {
1446                 len = strlen(Arg);
1447                 if (len == 0)
1448                         return;
1449                 if (len >= LINE_LEN) {
1450                         Config_Error_TooLong(File, Line, Var);
1451                         return;
1452                 }
1453                 if (!array_copyb(&Conf_Motd, Arg, len + 1))
1454                         Config_Error(LOG_WARNING,
1455                                      "%s, line %d: Could not append MotdPhrase: %s",
1456                                      NGIRCd_ConfFile, Line, strerror(errno));
1457                 Using_MotdFile = false;
1458                 return;
1459         }
1460         if(strcasecmp(Var, "Password") == 0) {
1461                 len = strlcpy(Conf_ServerPwd, Arg, sizeof(Conf_ServerPwd));
1462                 if (len >= sizeof(Conf_ServerPwd))
1463                         Config_Error_TooLong(File, Line, Var);
1464                 return;
1465         }
1466         if (strcasecmp(Var, "PidFile") == 0) {
1467                 len = strlcpy(Conf_PidFile, Arg, sizeof(Conf_PidFile));
1468                 if (len >= sizeof(Conf_PidFile))
1469                         Config_Error_TooLong(File, Line, Var);
1470                 return;
1471         }
1472         if (strcasecmp(Var, "Ports") == 0) {
1473                 ports_parse(&Conf_ListenPorts, Line, Arg);
1474                 return;
1475         }
1476         if (strcasecmp(Var, "ServerGID") == 0) {
1477                 grp = getgrnam(Arg);
1478                 if (grp)
1479                         Conf_GID = grp->gr_gid;
1480                 else {
1481                         Conf_GID = (unsigned int)atoi(Arg);
1482                         if (!Conf_GID && strcmp(Arg, "0"))
1483                                 Config_Error(LOG_WARNING,
1484                                              "%s, line %d: Value of \"%s\" is not a valid group name or ID!",
1485                                              NGIRCd_ConfFile, Line, Var);
1486                 }
1487                 return;
1488         }
1489         if (strcasecmp(Var, "ServerUID") == 0) {
1490                 pwd = getpwnam(Arg);
1491                 if (pwd)
1492                         Conf_UID = pwd->pw_uid;
1493                 else {
1494                         Conf_UID = (unsigned int)atoi(Arg);
1495                         if (!Conf_UID && strcmp(Arg, "0"))
1496                                 Config_Error(LOG_WARNING,
1497                                              "%s, line %d: Value of \"%s\" is not a valid user name or ID!",
1498                                              NGIRCd_ConfFile, Line, Var);
1499                 }
1500                 return;
1501         }
1502
1503         if (CheckLegacyNoOption(Var, Arg)) {
1504                 /* TODO: This function and support for "NoXXX" could be
1505                  * be removed starting with ngIRCd release 19 (one release
1506                  * after marking it "deprecated"). */
1507                 Config_Error(LOG_WARNING,
1508                              "%s, line %d (section \"Global\"): \"No\"-Prefix is deprecated, use \"%s = %s\" in [Options] section!",
1509                              NGIRCd_ConfFile, Line, NoNo(Var), InvertArg(Arg));
1510                 if (strcasecmp(Var, "NoIdent") == 0)
1511                         WarnIdent(Line);
1512                 else if (strcasecmp(Var, "NoPam") == 0)
1513                         WarnPAM(Line);
1514                 return;
1515         }
1516         if ((section = CheckLegacyGlobalOption(File, Line, Var, Arg))) {
1517                 /** TODO: This function and support for these options in the
1518                  * [Global] section could be removed starting with ngIRCd
1519                  * release 19 (one release after marking it "deprecated"). */
1520                 if (strncasecmp(Var, "SSL", 3) == 0) {
1521                         Config_Error(LOG_WARNING,
1522                                      "%s, line %d (section \"Global\"): \"%s\" is deprecated here, move it to %s and rename to \"%s\"!",
1523                                      NGIRCd_ConfFile, Line, Var, section,
1524                                      Var + 3);
1525                 } else {
1526                         Config_Error(LOG_WARNING,
1527                                      "%s, line %d (section \"Global\"): \"%s\" is deprecated here, move it to %s!",
1528                                      NGIRCd_ConfFile, Line, Var, section);
1529                 }
1530                 return;
1531         }
1532
1533         Config_Error_Section(File, Line, Var, "Global");
1534 }
1535
1536 /**
1537  * Handle variable in [Limits] configuration section.
1538  *
1539  * @param Line  Line numer in configuration file.
1540  * @param Var   Variable name.
1541  * @param Arg   Variable argument.
1542  */
1543 static void
1544 Handle_LIMITS(const char *File, int Line, char *Var, char *Arg)
1545 {
1546         assert(File != NULL);
1547         assert(Line > 0);
1548         assert(Var != NULL);
1549         assert(Arg != NULL);
1550
1551         if (strcasecmp(Var, "ConnectRetry") == 0) {
1552                 Conf_ConnectRetry = atoi(Arg);
1553                 if (Conf_ConnectRetry < 5) {
1554                         Config_Error(LOG_WARNING,
1555                                      "%s, line %d: Value of \"ConnectRetry\" too low!",
1556                                      NGIRCd_ConfFile, Line);
1557                         Conf_ConnectRetry = 5;
1558                 }
1559                 return;
1560         }
1561         if (strcasecmp(Var, "IdleTimeout") == 0) {
1562                 Conf_IdleTimeout = atoi(Arg);
1563                 if (!Conf_IdleTimeout && strcmp(Arg, "0"))
1564                         Config_Error_NaN(File, Line, Var);
1565                 return;
1566         }
1567         if (strcasecmp(Var, "MaxConnections") == 0) {
1568                 Conf_MaxConnections = atoi(Arg);
1569                 if (!Conf_MaxConnections && strcmp(Arg, "0"))
1570                         Config_Error_NaN(File, Line, Var);
1571                 return;
1572         }
1573         if (strcasecmp(Var, "MaxConnectionsIP") == 0) {
1574                 Conf_MaxConnectionsIP = atoi(Arg);
1575                 if (!Conf_MaxConnectionsIP && strcmp(Arg, "0"))
1576                         Config_Error_NaN(File, Line, Var);
1577                 return;
1578         }
1579         if (strcasecmp(Var, "MaxJoins") == 0) {
1580                 Conf_MaxJoins = atoi(Arg);
1581                 if (!Conf_MaxJoins && strcmp(Arg, "0"))
1582                         Config_Error_NaN(File, Line, Var);
1583                 return;
1584         }
1585         if (strcasecmp(Var, "MaxNickLength") == 0) {
1586                 Conf_MaxNickLength = Handle_MaxNickLength(Line, Arg);
1587                 return;
1588         }
1589         if (strcasecmp(Var, "MaxListSize") == 0) {
1590                 Conf_MaxListSize = atoi(Arg);
1591                 if (!Conf_MaxListSize && strcmp(Arg, "0"))
1592                         Config_Error_NaN(File, Line, Var);
1593                 return;
1594         }
1595         if (strcasecmp(Var, "PingTimeout") == 0) {
1596                 Conf_PingTimeout = atoi(Arg);
1597                 if (Conf_PingTimeout < 5) {
1598                         Config_Error(LOG_WARNING,
1599                                      "%s, line %d: Value of \"PingTimeout\" too low!",
1600                                      NGIRCd_ConfFile, Line);
1601                         Conf_PingTimeout = 5;
1602                 }
1603                 return;
1604         }
1605         if (strcasecmp(Var, "PongTimeout") == 0) {
1606                 Conf_PongTimeout = atoi(Arg);
1607                 if (Conf_PongTimeout < 5) {
1608                         Config_Error(LOG_WARNING,
1609                                      "%s, line %d: Value of \"PongTimeout\" too low!",
1610                                      NGIRCd_ConfFile, Line);
1611                         Conf_PongTimeout = 5;
1612                 }
1613                 return;
1614         }
1615
1616         Config_Error_Section(File, Line, Var, "Limits");
1617 }
1618
1619 /**
1620  * Handle variable in [Options] configuration section.
1621  *
1622  * @param Line  Line numer in configuration file.
1623  * @param Var   Variable name.
1624  * @param Arg   Variable argument.
1625  */
1626 static void
1627 Handle_OPTIONS(const char *File, int Line, char *Var, char *Arg)
1628 {
1629         size_t len;
1630
1631         assert(File != NULL);
1632         assert(Line > 0);
1633         assert(Var != NULL);
1634         assert(Arg != NULL);
1635
1636         if (strcasecmp(Var, "AllowRemoteOper") == 0) {
1637                 Conf_AllowRemoteOper = Check_ArgIsTrue(Arg);
1638                 return;
1639         }
1640         if (strcasecmp(Var, "ChrootDir") == 0) {
1641                 len = strlcpy(Conf_Chroot, Arg, sizeof(Conf_Chroot));
1642                 if (len >= sizeof(Conf_Chroot))
1643                         Config_Error_TooLong(File, Line, Var);
1644                 return;
1645         }
1646         if (strcasecmp(Var, "CloakHost") == 0) {
1647                 len = strlcpy(Conf_CloakHost, Arg, sizeof(Conf_CloakHost));
1648                 if (len >= sizeof(Conf_CloakHost))
1649                         Config_Error_TooLong(File, Line, Var);
1650                 return;
1651         }
1652         if (strcasecmp(Var, "CloakHostModeX") == 0) {
1653                 len = strlcpy(Conf_CloakHostModeX, Arg, sizeof(Conf_CloakHostModeX));
1654                 if (len >= sizeof(Conf_CloakHostModeX))
1655                         Config_Error_TooLong(File, Line, Var);
1656                 return;
1657         }
1658         if (strcasecmp(Var, "CloakHostSalt") == 0) {
1659                 len = strlcpy(Conf_CloakHostSalt, Arg, sizeof(Conf_CloakHostSalt));
1660                 if (len >= sizeof(Conf_CloakHostSalt))
1661                         Config_Error_TooLong(File, Line, Var);
1662                 return;
1663         }
1664         if (strcasecmp(Var, "CloakUserToNick") == 0) {
1665                 Conf_CloakUserToNick = Check_ArgIsTrue(Arg);
1666                 return;
1667         }
1668         if (strcasecmp(Var, "ConnectIPv6") == 0) {
1669                 Conf_ConnectIPv6 = Check_ArgIsTrue(Arg);
1670                 WarnIPv6(Line);
1671                 return;
1672         }
1673         if (strcasecmp(Var, "ConnectIPv4") == 0) {
1674                 Conf_ConnectIPv4 = Check_ArgIsTrue(Arg);
1675                 return;
1676         }
1677         if (strcasecmp(Var, "DNS") == 0) {
1678                 Conf_DNS = Check_ArgIsTrue(Arg);
1679                 return;
1680         }
1681         if (strcasecmp(Var, "Ident") == 0) {
1682                 Conf_Ident = Check_ArgIsTrue(Arg);
1683                 WarnIdent(Line);
1684                 return;
1685         }
1686         if (strcasecmp(Var, "IncludeDir") == 0) {
1687                 if (Conf_IncludeDir[0]) {
1688                         Config_Error(LOG_ERR,
1689                                      "%s, line %d: Can't overwrite value of \"IncludeDir\" variable!",
1690                                      File, Line);
1691                         return;
1692                 }
1693                 len = strlcpy(Conf_IncludeDir, Arg, sizeof(Conf_IncludeDir));
1694                 if (len >= sizeof(Conf_IncludeDir))
1695                         Config_Error_TooLong(File, Line, Var);
1696                 return;
1697         }
1698         if (strcasecmp(Var, "MorePrivacy") == 0) {
1699                 Conf_MorePrivacy = Check_ArgIsTrue(Arg);
1700                 return;
1701         }
1702         if (strcasecmp(Var, "NoticeAuth") == 0) {
1703                 Conf_NoticeAuth = Check_ArgIsTrue(Arg);
1704                 return;
1705         }
1706         if (strcasecmp(Var, "OperCanUseMode") == 0) {
1707                 Conf_OperCanMode = Check_ArgIsTrue(Arg);
1708                 return;
1709         }
1710         if (strcasecmp(Var, "OperChanPAutoOp") == 0) {
1711                 Conf_OperChanPAutoOp = Check_ArgIsTrue(Arg);
1712                 return;
1713         }
1714         if (strcasecmp(Var, "OperServerMode") == 0) {
1715                 Conf_OperServerMode = Check_ArgIsTrue(Arg);
1716                 return;
1717         }
1718         if (strcasecmp(Var, "PAM") == 0) {
1719                 Conf_PAM = Check_ArgIsTrue(Arg);
1720                 WarnPAM(Line);
1721                 return;
1722         }
1723         if (strcasecmp(Var, "PAMIsOptional") == 0 ) {
1724                 Conf_PAMIsOptional = Check_ArgIsTrue(Arg);
1725                 return;
1726         }
1727         if (strcasecmp(Var, "PredefChannelsOnly") == 0) {
1728                 Conf_PredefChannelsOnly = Check_ArgIsTrue(Arg);
1729                 return;
1730         }
1731 #ifndef STRICT_RFC
1732         if (strcasecmp(Var, "RequireAuthPing") == 0) {
1733                 Conf_AuthPing = Check_ArgIsTrue(Arg);
1734                 return;
1735         }
1736 #endif
1737         if (strcasecmp(Var, "ScrubCTCP") == 0) {
1738                 Conf_ScrubCTCP = Check_ArgIsTrue(Arg);
1739                 return;
1740         }
1741 #ifdef SYSLOG
1742         if (strcasecmp(Var, "SyslogFacility") == 0) {
1743                 Conf_SyslogFacility = ngt_SyslogFacilityID(Arg,
1744                                                            Conf_SyslogFacility);
1745                 return;
1746         }
1747 #endif
1748         if (strcasecmp(Var, "WebircPassword") == 0) {
1749                 len = strlcpy(Conf_WebircPwd, Arg, sizeof(Conf_WebircPwd));
1750                 if (len >= sizeof(Conf_WebircPwd))
1751                         Config_Error_TooLong(File, Line, Var);
1752                 return;
1753         }
1754
1755         Config_Error_Section(File, Line, Var, "Options");
1756 }
1757
1758 #ifdef SSL_SUPPORT
1759
1760 /**
1761  * Handle variable in [SSL] configuration section.
1762  *
1763  * @param Line  Line numer in configuration file.
1764  * @param Var   Variable name.
1765  * @param Arg   Variable argument.
1766  */
1767 static void
1768 Handle_SSL(const char *File, int Line, char *Var, char *Arg)
1769 {
1770         assert(File != NULL);
1771         assert(Line > 0);
1772         assert(Var != NULL);
1773         assert(Arg != NULL);
1774
1775         if (strcasecmp(Var, "CertFile") == 0) {
1776                 assert(Conf_SSLOptions.CertFile == NULL);
1777                 Conf_SSLOptions.CertFile = strdup_warn(Arg);
1778                 return;
1779         }
1780         if (strcasecmp(Var, "DHFile") == 0) {
1781                 assert(Conf_SSLOptions.DHFile == NULL);
1782                 Conf_SSLOptions.DHFile = strdup_warn(Arg);
1783                 return;
1784         }
1785         if (strcasecmp(Var, "KeyFile") == 0) {
1786                 assert(Conf_SSLOptions.KeyFile == NULL);
1787                 Conf_SSLOptions.KeyFile = strdup_warn(Arg);
1788                 return;
1789         }
1790         if (strcasecmp(Var, "KeyFilePassword") == 0) {
1791                 assert(array_bytes(&Conf_SSLOptions.KeyFilePassword) == 0);
1792                 if (!array_copys(&Conf_SSLOptions.KeyFilePassword, Arg))
1793                         Config_Error(LOG_ERR,
1794                                      "%s, line %d (section \"SSL\"): Could not copy %s: %s!",
1795                                      File, Line, Var, strerror(errno));
1796                 return;
1797         }
1798         if (strcasecmp(Var, "Ports") == 0) {
1799                 ports_parse(&Conf_SSLOptions.ListenPorts, Line, Arg);
1800                 return;
1801         }
1802
1803         Config_Error_Section(File, Line, Var, "SSL");
1804 }
1805
1806 #endif
1807
1808 /**
1809  * Handle variable in [Operator] configuration section.
1810  *
1811  * @param Line  Line numer in configuration file.
1812  * @param Var   Variable name.
1813  * @param Arg   Variable argument.
1814  */
1815 static void
1816 Handle_OPERATOR(const char *File, int Line, char *Var, char *Arg )
1817 {
1818         size_t len;
1819         struct Conf_Oper *op;
1820
1821         assert( File != NULL );
1822         assert( Line > 0 );
1823         assert( Var != NULL );
1824         assert( Arg != NULL );
1825
1826         op = array_get(&Conf_Opers, sizeof(*op),
1827                          array_length(&Conf_Opers, sizeof(*op)) - 1);
1828         if (!op)
1829                 return;
1830
1831         if (strcasecmp(Var, "Name") == 0) {
1832                 /* Name of IRC operator */
1833                 len = strlcpy(op->name, Arg, sizeof(op->name));
1834                 if (len >= sizeof(op->name))
1835                                 Config_Error_TooLong(File, Line, Var);
1836                 return;
1837         }
1838         if (strcasecmp(Var, "Password") == 0) {
1839                 /* Password of IRC operator */
1840                 len = strlcpy(op->pwd, Arg, sizeof(op->pwd));
1841                 if (len >= sizeof(op->pwd))
1842                                 Config_Error_TooLong(File, Line, Var);
1843                 return;
1844         }
1845         if (strcasecmp(Var, "Mask") == 0) {
1846                 if (op->mask)
1847                         return; /* Hostname already configured */
1848                 op->mask = strdup_warn( Arg );
1849                 return;
1850         }
1851
1852         Config_Error_Section(File, Line, Var, "Operator");
1853 }
1854
1855 /**
1856  * Handle variable in [Server] configuration section.
1857  *
1858  * @param Line  Line numer in configuration file.
1859  * @param Var   Variable name.
1860  * @param Arg   Variable argument.
1861  */
1862 static void
1863 Handle_SERVER(const char *File, int Line, char *Var, char *Arg )
1864 {
1865         long port;
1866         size_t len;
1867
1868         assert( File != NULL );
1869         assert( Line > 0 );
1870         assert( Var != NULL );
1871         assert( Arg != NULL );
1872
1873         /* Ignore server block if no space is left in server configuration structure */
1874         if( New_Server_Idx <= NONE ) return;
1875
1876         if( strcasecmp( Var, "Host" ) == 0 ) {
1877                 /* Hostname of the server */
1878                 len = strlcpy( New_Server.host, Arg, sizeof( New_Server.host ));
1879                 if (len >= sizeof( New_Server.host ))
1880                         Config_Error_TooLong(File, Line, Var);
1881                 return;
1882         }
1883         if( strcasecmp( Var, "Name" ) == 0 ) {
1884                 /* Name of the server ("Nick"/"ID") */
1885                 len = strlcpy( New_Server.name, Arg, sizeof( New_Server.name ));
1886                 if (len >= sizeof( New_Server.name ))
1887                         Config_Error_TooLong(File, Line, Var);
1888                 return;
1889         }
1890         if (strcasecmp(Var, "Bind") == 0) {
1891                 if (ng_ipaddr_init(&New_Server.bind_addr, Arg, 0))
1892                         return;
1893
1894                 Config_Error(LOG_ERR, "%s, line %d (section \"Server\"): Can't parse IP address \"%s\"",
1895                                 NGIRCd_ConfFile, Line, Arg);
1896                 return;
1897         }
1898         if( strcasecmp( Var, "MyPassword" ) == 0 ) {
1899                 /* Password of this server which is sent to the peer */
1900                 if (*Arg == ':') {
1901                         Config_Error(LOG_ERR,
1902                                 "%s, line %d (section \"Server\"): MyPassword must not start with ':'!",
1903                                                                                 NGIRCd_ConfFile, Line);
1904                 }
1905                 len = strlcpy( New_Server.pwd_in, Arg, sizeof( New_Server.pwd_in ));
1906                 if (len >= sizeof( New_Server.pwd_in ))
1907                         Config_Error_TooLong(File, Line, Var);
1908                 return;
1909         }
1910         if( strcasecmp( Var, "PeerPassword" ) == 0 ) {
1911                 /* Passwort of the peer which must be received */
1912                 len = strlcpy( New_Server.pwd_out, Arg, sizeof( New_Server.pwd_out ));
1913                 if (len >= sizeof( New_Server.pwd_out ))
1914                         Config_Error_TooLong(File, Line, Var);
1915                 return;
1916         }
1917         if( strcasecmp( Var, "Port" ) == 0 ) {
1918                 /* Port to which this server should connect */
1919                 port = atol( Arg );
1920                 if (port >= 0 && port < 0xFFFF)
1921                         New_Server.port = (UINT16)port;
1922                 else
1923                         Config_Error(LOG_ERR,
1924                                 "%s, line %d (section \"Server\"): Illegal port number %ld!",
1925                                 NGIRCd_ConfFile, Line, port );
1926                 return;
1927         }
1928 #ifdef SSL_SUPPORT
1929         if( strcasecmp( Var, "SSLConnect" ) == 0 ) {
1930                 New_Server.SSLConnect = Check_ArgIsTrue(Arg);
1931                 return;
1932         }
1933 #endif
1934         if( strcasecmp( Var, "Group" ) == 0 ) {
1935                 /* Server group */
1936                 New_Server.group = atoi( Arg );
1937                 if (!New_Server.group && strcmp(Arg, "0"))
1938                         Config_Error_NaN(File, Line, Var);
1939                 return;
1940         }
1941         if( strcasecmp( Var, "Passive" ) == 0 ) {
1942                 if (Check_ArgIsTrue(Arg))
1943                         New_Server.flags |= CONF_SFLAG_DISABLED;
1944                 return;
1945         }
1946         if (strcasecmp(Var, "ServiceMask") == 0) {
1947                 len = strlcpy(New_Server.svs_mask, ngt_LowerStr(Arg),
1948                               sizeof(New_Server.svs_mask));
1949                 if (len >= sizeof(New_Server.svs_mask))
1950                         Config_Error_TooLong(File, Line, Var);
1951                 return;
1952         }
1953
1954         Config_Error_Section(File, Line, Var, "Server");
1955 }
1956
1957 /**
1958  * Copy channel name into channel structure.
1959  *
1960  * If the channel name is not valid because of a missing prefix ('#', '&'),
1961  * a default prefix of '#' will be added.
1962  *
1963  * @param new_chan      New already allocated channel structure.
1964  * @param name          Name of the new channel.
1965  * @returns             true on success, false otherwise.
1966  */
1967 static bool
1968 Handle_Channelname(struct Conf_Channel *new_chan, const char *name)
1969 {
1970         size_t size = sizeof(new_chan->name);
1971         char *dest = new_chan->name;
1972
1973         if (!Channel_IsValidName(name)) {
1974                 /*
1975                  * maybe user forgot to add a '#'.
1976                  * This is only here for user convenience.
1977                  */
1978                 *dest = '#';
1979                 --size;
1980                 ++dest;
1981         }
1982         return size > strlcpy(dest, name, size);
1983 }
1984
1985 /**
1986  * Handle variable in [Channel] configuration section.
1987  *
1988  * @param Line  Line numer in configuration file.
1989  * @param Var   Variable name.
1990  * @param Arg   Variable argument.
1991  */
1992 static void
1993 Handle_CHANNEL(const char *File, int Line, char *Var, char *Arg)
1994 {
1995         size_t len;
1996         struct Conf_Channel *chan;
1997
1998         assert( File != NULL );
1999         assert( Line > 0 );
2000         assert( Var != NULL );
2001         assert( Arg != NULL );
2002
2003         chan = array_get(&Conf_Channels, sizeof(*chan),
2004                          array_length(&Conf_Channels, sizeof(*chan)) - 1);
2005         if (!chan)
2006                 return;
2007
2008         if (strcasecmp(Var, "Name") == 0) {
2009                 if (!Handle_Channelname(chan, Arg))
2010                         Config_Error_TooLong(File, Line, Var);
2011                 return;
2012         }
2013         if (strcasecmp(Var, "Modes") == 0) {
2014                 /* Initial modes */
2015                 len = strlcpy(chan->modes, Arg, sizeof(chan->modes));
2016                 if (len >= sizeof(chan->modes))
2017                         Config_Error_TooLong(File, Line, Var);
2018                 return;
2019         }
2020         if( strcasecmp( Var, "Topic" ) == 0 ) {
2021                 /* Initial topic */
2022                 len = strlcpy(chan->topic, Arg, sizeof(chan->topic));
2023                 if (len >= sizeof(chan->topic))
2024                         Config_Error_TooLong(File, Line, Var);
2025                 return;
2026         }
2027         if( strcasecmp( Var, "Key" ) == 0 ) {
2028                 /* Initial Channel Key (mode k) */
2029                 len = strlcpy(chan->key, Arg, sizeof(chan->key));
2030                 if (len >= sizeof(chan->key))
2031                         Config_Error_TooLong(File, Line, Var);
2032                 return;
2033         }
2034         if( strcasecmp( Var, "MaxUsers" ) == 0 ) {
2035                 /* maximum user limit, mode l */
2036                 chan->maxusers = (unsigned long) atol(Arg);
2037                 if (!chan->maxusers && strcmp(Arg, "0"))
2038                         Config_Error_NaN(File, Line, Var);
2039                 return;
2040         }
2041         if (strcasecmp(Var, "KeyFile") == 0) {
2042                 /* channel keys */
2043                 len = strlcpy(chan->keyfile, Arg, sizeof(chan->keyfile));
2044                 if (len >= sizeof(chan->keyfile))
2045                         Config_Error_TooLong(File, Line, Var);
2046                 return;
2047         }
2048
2049         Config_Error_Section(File, Line, Var, "Channel");
2050 }
2051
2052 /**
2053  * Validate server configuration.
2054  *
2055  * Please note that this function uses exit(1) on fatal errors and therefore
2056  * can result in ngIRCd terminating!
2057  *
2058  * @param Configtest    true if the daemon has been called with "--configtest".
2059  * @param Rehash        true if re-reading configuration on runtime.
2060  * @returns             true if configuration is valid.
2061  */
2062 static bool
2063 Validate_Config(bool Configtest, bool Rehash)
2064 {
2065         /* Validate configuration settings. */
2066
2067 #ifdef DEBUG
2068         int i, servers, servers_once;
2069 #endif
2070         bool config_valid = true;
2071         char *ptr;
2072
2073         /* Emit a warning when the config file is not a full path name */
2074         if (NGIRCd_ConfFile[0] && NGIRCd_ConfFile[0] != '/') {
2075                 Config_Error(LOG_WARNING,
2076                         "Not specifying a full path name to \"%s\" can cause problems when rehashing the server!",
2077                         NGIRCd_ConfFile);
2078         }
2079
2080         /* Validate configured server name, see RFC 2812 section 2.3.1 */
2081         ptr = Conf_ServerName;
2082         do {
2083                 if (*ptr >= 'a' && *ptr <= 'z') continue;
2084                 if (*ptr >= 'A' && *ptr <= 'Z') continue;
2085                 if (*ptr >= '0' && *ptr <= '9') continue;
2086                 if (ptr > Conf_ServerName) {
2087                         if (*ptr == '.' || *ptr == '-')
2088                                 continue;
2089                 }
2090                 Conf_ServerName[0] = '\0';
2091                 break;
2092         } while (*(++ptr));
2093
2094         if (!Conf_ServerName[0]) {
2095                 /* No server name configured! */
2096                 config_valid = false;
2097                 Config_Error(LOG_ALERT,
2098                              "No (valid) server name configured in \"%s\" (section 'Global': 'Name')!",
2099                              NGIRCd_ConfFile);
2100                 if (!Configtest && !Rehash) {
2101                         Config_Error(LOG_ALERT,
2102                                      "%s exiting due to fatal errors!",
2103                                      PACKAGE_NAME);
2104                         exit(1);
2105                 }
2106         }
2107
2108         if (Conf_ServerName[0] && !strchr(Conf_ServerName, '.')) {
2109                 /* No dot in server name! */
2110                 config_valid = false;
2111                 Config_Error(LOG_ALERT,
2112                              "Invalid server name configured in \"%s\" (section 'Global': 'Name'): Dot missing!",
2113                              NGIRCd_ConfFile);
2114                 if (!Configtest) {
2115                         Config_Error(LOG_ALERT,
2116                                      "%s exiting due to fatal errors!",
2117                                      PACKAGE_NAME);
2118                         exit(1);
2119                 }
2120         }
2121
2122 #ifdef STRICT_RFC
2123         if (!Conf_ServerAdminMail[0]) {
2124                 /* No administrative contact configured! */
2125                 config_valid = false;
2126                 Config_Error(LOG_ALERT,
2127                              "No administrator email address configured in \"%s\" ('AdminEMail')!",
2128                              NGIRCd_ConfFile);
2129                 if (!Configtest) {
2130                         Config_Error(LOG_ALERT,
2131                                      "%s exiting due to fatal errors!",
2132                                      PACKAGE_NAME);
2133                         exit(1);
2134                 }
2135         }
2136 #endif
2137
2138         if (!Conf_ServerAdmin1[0] && !Conf_ServerAdmin2[0]
2139             && !Conf_ServerAdminMail[0]) {
2140                 /* No administrative information configured! */
2141                 Config_Error(LOG_WARNING,
2142                              "No administrative information configured but required by RFC!");
2143         }
2144
2145 #ifdef PAM
2146         if (Conf_ServerPwd[0])
2147                 Config_Error(LOG_ERR,
2148                              "This server uses PAM, \"Password\" in [Global] section will be ignored!");
2149 #endif
2150
2151 #ifdef DEBUG
2152         servers = servers_once = 0;
2153         for (i = 0; i < MAX_SERVERS; i++) {
2154                 if (Conf_Server[i].name[0]) {
2155                         servers++;
2156                         if (Conf_Server[i].flags & CONF_SFLAG_ONCE)
2157                                 servers_once++;
2158                 }
2159         }
2160         Log(LOG_DEBUG,
2161             "Configuration: Operators=%ld, Servers=%d[%d], Channels=%ld",
2162             array_length(&Conf_Opers, sizeof(struct Conf_Oper)),
2163             servers, servers_once,
2164             array_length(&Conf_Channels, sizeof(struct Conf_Channel)));
2165 #endif
2166
2167         return config_valid;
2168 }
2169
2170 /**
2171  * Output "line too long" warning.
2172  *
2173  * @param Line  Line number in configuration file.
2174  * @param Item  Affected variable name.
2175  */
2176 static void
2177 Config_Error_TooLong(const char *File, const int Line, const char *Item)
2178 {
2179         Config_Error(LOG_WARNING, "%s, line %d: Value of \"%s\" too long!",
2180                      File, Line, Item );
2181 }
2182
2183 /**
2184  * Output "unknown variable" warning.
2185  *
2186  * @param Line          Line number in configuration file.
2187  * @param Item          Affected variable name.
2188  * @param Section       Section name.
2189  */
2190 static void
2191 Config_Error_Section(const char *File, const int Line, const char *Item,
2192                      const char *Section)
2193 {
2194         Config_Error(LOG_ERR, "%s, line %d (section \"%s\"): Unknown variable \"%s\"!",
2195                      File, Line, Section, Item);
2196 }
2197
2198 /**
2199  * Output "not a number" warning.
2200  *
2201  * @param Line  Line number in configuration file.
2202  * @param Item  Affected variable name.
2203  */
2204 static void
2205 Config_Error_NaN(const char *File, const int Line, const char *Item )
2206 {
2207         Config_Error(LOG_WARNING, "%s, line %d: Value of \"%s\" is not a number!",
2208                      File, Line, Item );
2209 }
2210
2211 /**
2212  * Output configuration error to console and/or logfile.
2213  *
2214  * On runtime, the normal log functions of the daemon are used. But when
2215  * testing the configuration ("--configtest"), all messages go directly
2216  * to the console.
2217  *
2218  * @param Level         Severity level of the message.
2219  * @param Format        Format string; see printf() function.
2220  */
2221 #ifdef PROTOTYPES
2222 static void Config_Error( const int Level, const char *Format, ... )
2223 #else
2224 static void Config_Error( Level, Format, va_alist )
2225 const int Level;
2226 const char *Format;
2227 va_dcl
2228 #endif
2229 {
2230         char msg[MAX_LOG_MSG_LEN];
2231         va_list ap;
2232
2233         assert( Format != NULL );
2234
2235 #ifdef PROTOTYPES
2236         va_start( ap, Format );
2237 #else
2238         va_start( ap );
2239 #endif
2240         vsnprintf( msg, MAX_LOG_MSG_LEN, Format, ap );
2241         va_end( ap );
2242
2243         if (!Use_Log) {
2244                 if (Level <= LOG_WARNING)
2245                         printf(" - %s\n", msg);
2246                 else
2247                         puts(msg);
2248         } else
2249                 Log(Level, "%s", msg);
2250 }
2251
2252 #ifdef DEBUG
2253
2254 /**
2255  * Dump internal state of the "configuration module".
2256  */
2257 GLOBAL void
2258 Conf_DebugDump(void)
2259 {
2260         int i;
2261
2262         Log(LOG_DEBUG, "Configured servers:");
2263         for (i = 0; i < MAX_SERVERS; i++) {
2264                 if (! Conf_Server[i].name[0])
2265                         continue;
2266                 Log(LOG_DEBUG,
2267                     " - %s: %s:%d, last=%ld, group=%d, flags=%d, conn=%d",
2268                     Conf_Server[i].name, Conf_Server[i].host,
2269                     Conf_Server[i].port, Conf_Server[i].lasttry,
2270                     Conf_Server[i].group, Conf_Server[i].flags,
2271                     Conf_Server[i].conn_id);
2272         }
2273 }
2274
2275 #endif
2276
2277 /**
2278  * Initialize server configuration structur to default values.
2279  *
2280  * @param Server        Pointer to server structure to initialize.
2281  */
2282 static void
2283 Init_Server_Struct( CONF_SERVER *Server )
2284 {
2285         assert( Server != NULL );
2286
2287         memset( Server, 0, sizeof (CONF_SERVER) );
2288
2289         Server->group = NONE;
2290         Server->lasttry = time( NULL ) - Conf_ConnectRetry + STARTUP_DELAY;
2291
2292         if( NGIRCd_Passive ) Server->flags = CONF_SFLAG_DISABLED;
2293
2294         Proc_InitStruct(&Server->res_stat);
2295         Server->conn_id = NONE;
2296         memset(&Server->bind_addr, 0, sizeof(Server->bind_addr));
2297 }
2298
2299 /* -eof- */