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