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