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