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