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