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