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