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