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