]> arthur.barton.de Git - ngircd-alex.git/blob - src/ngircd/conf.c
Fix spelling
[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 succes, 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("  AllowRemoteOper = %s\n", yesno_to_str(Conf_AllowRemoteOper));
395         printf("  ChrootDir = %s\n", Conf_Chroot);
396         printf("  CloakHost = %s\n", Conf_CloakHost);
397         printf("  CloakHostModeX = %s\n", Conf_CloakHostModeX);
398         printf("  CloakHostSalt = %s\n", Conf_CloakHostSalt);
399         printf("  CloakUserToNick = %s\n", yesno_to_str(Conf_CloakUserToNick));
400 #ifdef WANT_IPV6
401         printf("  ConnectIPv4 = %s\n", yesno_to_str(Conf_ConnectIPv6));
402         printf("  ConnectIPv6 = %s\n", yesno_to_str(Conf_ConnectIPv4));
403 #endif
404         printf("  DNS = %s\n", yesno_to_str(Conf_DNS));
405 #ifdef IDENT
406         printf("  Ident = %s\n", yesno_to_str(Conf_Ident));
407 #endif
408         printf("  IncludeDir = %s\n", Conf_IncludeDir);
409         printf("  MorePrivacy = %s\n", yesno_to_str(Conf_MorePrivacy));
410         printf("  NoticeAuth = %s\n", yesno_to_str(Conf_NoticeAuth));
411         printf("  OperCanUseMode = %s\n", yesno_to_str(Conf_OperCanMode));
412         printf("  OperChanPAutoOp = %s\n", yesno_to_str(Conf_OperChanPAutoOp));
413         printf("  OperServerMode = %s\n", yesno_to_str(Conf_OperServerMode));
414 #ifdef PAM
415         printf("  PAM = %s\n", yesno_to_str(Conf_PAM));
416         printf("  PAMIsOptional = %s\n", yesno_to_str(Conf_PAMIsOptional));
417 #endif
418         printf("  PredefChannelsOnly = %s\n", yesno_to_str(Conf_PredefChannelsOnly));
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         Conf_AllowRemoteOper = false;
762 #ifndef STRICT_RFC
763         Conf_AuthPing = false;
764 #endif
765         strlcpy(Conf_Chroot, CHROOT_DIR, sizeof(Conf_Chroot));
766         strcpy(Conf_CloakHost, "");
767         strcpy(Conf_CloakHostModeX, "");
768         strlcpy(Conf_CloakHostSalt, ngt_RandomStr(random, RANDOM_SALT_LEN),
769                 sizeof(Conf_CloakHostSalt));
770         Conf_CloakUserToNick = false;
771         Conf_ConnectIPv4 = true;
772 #ifdef WANT_IPV6
773         Conf_ConnectIPv6 = true;
774 #else
775         Conf_ConnectIPv6 = false;
776 #endif
777         Conf_DNS = true;
778 #ifdef IDENTAUTH
779         Conf_Ident = true;
780 #else
781         Conf_Ident = false;
782 #endif
783         strcpy(Conf_IncludeDir, "");
784         Conf_MorePrivacy = false;
785         Conf_NoticeAuth = false;
786         Conf_OperCanMode = false;
787         Conf_OperChanPAutoOp = true;
788         Conf_OperServerMode = false;
789 #ifdef PAM
790         Conf_PAM = true;
791 #else
792         Conf_PAM = false;
793 #endif
794         Conf_PAMIsOptional = false;
795         Conf_PredefChannelsOnly = false;
796 #ifdef SYSLOG
797         Conf_ScrubCTCP = false;
798 #ifdef LOG_LOCAL5
799         Conf_SyslogFacility = LOG_LOCAL5;
800 #else
801         Conf_SyslogFacility = 0;
802 #endif
803 #endif
804
805         /* Initialize server configuration structures */
806         if (InitServers) {
807                 for (i = 0; i < MAX_SERVERS;
808                      Init_Server_Struct(&Conf_Server[i++]));
809         }
810 }
811
812 /**
813  * Get number of configured listening ports.
814  *
815  * @returns The number of ports (IPv4+IPv6) on which the server should listen.
816  */
817 static bool
818 no_listenports(void)
819 {
820         size_t cnt = array_bytes(&Conf_ListenPorts);
821 #ifdef SSL_SUPPORT
822         cnt += array_bytes(&Conf_SSLOptions.ListenPorts);
823 #endif
824         return cnt == 0;
825 }
826
827 /**
828  * Read contents of a text file into an array.
829  *
830  * This function is used to read the MOTD and help text file, for example.
831  *
832  * @param filename      Name of the file to read.
833  * @return              true, when the file has been read in.
834  */
835 static bool
836 Read_TextFile(const char *Filename, const char *Name, array *Destination)
837 {
838         char line[127];
839         FILE *fp;
840         int line_no = 1;
841
842         if (*Filename == '\0')
843                 return false;
844
845         fp = fopen(Filename, "r");
846         if (!fp) {
847                 Config_Error(LOG_ERR, "Can't read %s file \"%s\": %s",
848                              Name, Filename, strerror(errno));
849                 return false;
850         }
851
852         array_free(Destination);
853         while (fgets(line, (int)sizeof line, fp)) {
854                 ngt_TrimLastChr(line, '\n');
855
856                 /* add text including \0 */
857                 if (!array_catb(Destination, line, strlen(line) + 1)) {
858                         Log(LOG_ERR, "Cannot read/add \"%s\", line %d: %s",
859                             Filename, line_no, strerror(errno));
860                         break;
861                 }
862                 line_no++;
863         }
864         fclose(fp);
865         return true;
866 }
867
868 /**
869  * Read ngIRCd configuration file.
870  *
871  * Please note that this function uses exit(1) on fatal errors and therefore
872  * can result in ngIRCd terminating!
873  *
874  * @param ngircd_starting       Flag indicating if ngIRCd is starting or not.
875  * @returns                     true when the configuration file has been read
876  *                              successfully; false otherwise.
877  */
878 static bool
879 Read_Config(bool TestOnly, bool IsStarting)
880 {
881         const UINT16 defaultport = 6667;
882         char *ptr, file[FNAME_LEN];
883         struct dirent *entry;
884         int i, n;
885         FILE *fd;
886         DIR *dh;
887
888         /* Open configuration file */
889         fd = fopen( NGIRCd_ConfFile, "r" );
890         if( ! fd ) {
891                 /* No configuration file found! */
892                 Config_Error( LOG_ALERT, "Can't read configuration \"%s\": %s",
893                                         NGIRCd_ConfFile, strerror( errno ));
894                 if (!IsStarting)
895                         return false;
896                 Config_Error( LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE_NAME );
897                 exit( 1 );
898         }
899
900         opers_free();
901         Set_Defaults(IsStarting);
902
903         if (TestOnly)
904                 Config_Error(LOG_INFO,
905                              "Reading configuration from \"%s\" ...",
906                              NGIRCd_ConfFile );
907
908         /* Clean up server configuration structure: mark all already
909          * configured servers as "once" so that they are deleted
910          * after the next disconnect and delete all unused servers.
911          * And delete all servers which are "duplicates" of servers
912          * that are already marked as "once" (such servers have been
913          * created by the last rehash but are now useless). */
914         for( i = 0; i < MAX_SERVERS; i++ ) {
915                 if( Conf_Server[i].conn_id == NONE ) Init_Server_Struct( &Conf_Server[i] );
916                 else {
917                         /* This structure is in use ... */
918                         if( Conf_Server[i].flags & CONF_SFLAG_ONCE ) {
919                                 /* Check for duplicates */
920                                 for( n = 0; n < MAX_SERVERS; n++ ) {
921                                         if( n == i ) continue;
922
923                                         if( Conf_Server[i].conn_id == Conf_Server[n].conn_id ) {
924                                                 Init_Server_Struct( &Conf_Server[n] );
925 #ifdef DEBUG
926                                                 Log(LOG_DEBUG,"Deleted unused duplicate server %d (kept %d).",
927                                                                                                 n, i );
928 #endif
929                                         }
930                                 }
931                         } else {
932                                 /* Mark server as "once" */
933                                 Conf_Server[i].flags |= CONF_SFLAG_ONCE;
934                                 Log( LOG_DEBUG, "Marked server %d as \"once\"", i );
935                         }
936                 }
937         }
938
939         /* Initialize variables */
940         Init_Server_Struct( &New_Server );
941         New_Server_Idx = NONE;
942 #ifdef SSL_SUPPORT
943         ConfSSL_Init();
944 #endif
945
946         Read_Config_File(NGIRCd_ConfFile, fd);
947         fclose(fd);
948
949         if (Conf_IncludeDir[0]) {
950                 dh = opendir(Conf_IncludeDir);
951                 if (!dh)
952                         Config_Error(LOG_ALERT,
953                                      "Can't open include directory \"%s\": %s",
954                                      Conf_IncludeDir, strerror(errno));
955         } else {
956                 strlcpy(Conf_IncludeDir, SYSCONFDIR, sizeof(Conf_IncludeDir));
957                 strlcat(Conf_IncludeDir, CONFIG_DIR, sizeof(Conf_IncludeDir));
958                 dh = opendir(Conf_IncludeDir);
959         }
960
961         /* Include further configuration files, if IncludeDir is available */
962         if (dh) {
963                 while ((entry = readdir(dh)) != NULL) {
964                         ptr = strrchr(entry->d_name, '.');
965                         if (!ptr || strcasecmp(ptr, ".conf") != 0)
966                                 continue;
967                         snprintf(file, sizeof(file), "%s/%s",
968                                  Conf_IncludeDir, entry->d_name);
969                         if (TestOnly)
970                                 Config_Error(LOG_INFO,
971                                              "Reading configuration from \"%s\" ...",
972                                              file);
973                         fd = fopen(file, "r");
974                         if (fd) {
975                                 Read_Config_File(file, fd);
976                                 fclose(fd);
977                         } else
978                                 Config_Error(LOG_ALERT,
979                                              "Can't read configuration \"%s\": %s",
980                                              file, strerror(errno));
981                 }
982                 closedir(dh);
983         }
984
985         /* Check if there is still a server to add */
986         if( New_Server.name[0] ) {
987                 /* Copy data to "real" server structure */
988                 assert( New_Server_Idx > NONE );
989                 Conf_Server[New_Server_Idx] = New_Server;
990         }
991
992         /* not a single listening port? Add default. */
993         if (no_listenports() &&
994                 !array_copyb(&Conf_ListenPorts, (char*) &defaultport, sizeof defaultport))
995         {
996                 Config_Error(LOG_ALERT, "Could not add default listening Port %u: %s",
997                                         (unsigned int) defaultport, strerror(errno));
998
999                 exit(1);
1000         }
1001
1002         if (!Conf_ListenAddress)
1003                 Conf_ListenAddress = strdup_warn(DEFAULT_LISTEN_ADDRSTR);
1004
1005         if (!Conf_ListenAddress) {
1006                 Config_Error(LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE_NAME);
1007                 exit(1);
1008         }
1009
1010         /* No MOTD phrase configured? (re)try motd file. */
1011         if (array_bytes(&Conf_Motd) == 0) {
1012                 if (Read_TextFile(Conf_MotdFile, "MOTD", &Conf_Motd))
1013                         Using_MotdFile = true;
1014         }
1015
1016         /* Try to read ngIRCd help text file. */
1017         (void)Read_TextFile(Conf_HelpFile, "help text", &Conf_Helptext);
1018         if (!array_bytes(&Conf_Helptext))
1019                 Config_Error(LOG_WARNING,
1020                     "No help text available, HELP command will be of limited use.");
1021
1022 #ifdef SSL_SUPPORT
1023         /* Make sure that all SSL-related files are readable */
1024         CheckFileReadable("CertFile", Conf_SSLOptions.CertFile);
1025         CheckFileReadable("DHFile", Conf_SSLOptions.DHFile);
1026         CheckFileReadable("KeyFile", Conf_SSLOptions.KeyFile);
1027 #endif
1028
1029         return true;
1030 }
1031
1032 /**
1033  * ...
1034  */
1035 static void Read_Config_File(const char *File, FILE *fd)
1036 {
1037         char section[LINE_LEN], str[LINE_LEN], *var, *arg, *ptr;
1038         int i, line = 0;
1039         size_t count;
1040
1041         /* Read configuration file */
1042         section[0] = '\0';
1043         while (true) {
1044                 if (!fgets(str, LINE_LEN, fd))
1045                         break;
1046                 ngt_TrimStr(str);
1047                 line++;
1048
1049                 /* Skip comments and empty lines */
1050                 if (str[0] == ';' || str[0] == '#' || str[0] == '\0')
1051                         continue;
1052
1053                 /* Is this the beginning of a new section? */
1054                 if ((str[0] == '[') && (str[strlen(str) - 1] == ']')) {
1055                         strlcpy(section, str, sizeof(section));
1056                         if (strcasecmp(section, "[GLOBAL]") == 0
1057                             || strcasecmp(section, "[LIMITS]") == 0
1058                             || strcasecmp(section, "[OPTIONS]") == 0
1059 #ifdef SSL_SUPPORT
1060                             || strcasecmp(section, "[SSL]") == 0
1061 #endif
1062                             )
1063                                 continue;
1064
1065                         if (strcasecmp(section, "[SERVER]") == 0) {
1066                                 /* Check if there is already a server to add */
1067                                 if (New_Server.name[0]) {
1068                                         /* Copy data to "real" server structure */
1069                                         assert(New_Server_Idx > NONE);
1070                                         Conf_Server[New_Server_Idx] =
1071                                         New_Server;
1072                                 }
1073
1074                                 /* Re-init structure for new server */
1075                                 Init_Server_Struct(&New_Server);
1076
1077                                 /* Search unused item in server configuration structure */
1078                                 for (i = 0; i < MAX_SERVERS; i++) {
1079                                         /* Is this item used? */
1080                                         if (!Conf_Server[i].name[0])
1081                                                 break;
1082                                 }
1083                                 if (i >= MAX_SERVERS) {
1084                                         /* Oops, no free item found! */
1085                                         Config_Error(LOG_ERR,
1086                                                      "Too many servers configured.");
1087                                         New_Server_Idx = NONE;
1088                                 } else
1089                                         New_Server_Idx = i;
1090                                 continue;
1091                         }
1092
1093                         if (strcasecmp(section, "[CHANNEL]") == 0) {
1094                                 count = array_length(&Conf_Channels,
1095                                                      sizeof(struct
1096                                                             Conf_Channel));
1097                                 if (!array_alloc
1098                                     (&Conf_Channels,
1099                                      sizeof(struct Conf_Channel), count)) {
1100                                             Config_Error(LOG_ERR,
1101                                                          "Could not allocate memory for new operator (line %d)",
1102                                                          line);
1103                                     }
1104                                 continue;
1105                         }
1106
1107                         if (strcasecmp(section, "[OPERATOR]") == 0) {
1108                                 count = array_length(&Conf_Opers,
1109                                                      sizeof(struct Conf_Oper));
1110                                 if (!array_alloc(&Conf_Opers,
1111                                                  sizeof(struct Conf_Oper),
1112                                                  count)) {
1113                                         Config_Error(LOG_ERR,
1114                                                      "Could not allocate memory for new channel (line &d)",
1115                                                      line);
1116                                 }
1117                                 continue;
1118                         }
1119
1120                         Config_Error(LOG_ERR,
1121                                      "%s, line %d: Unknown section \"%s\"!",
1122                                      NGIRCd_ConfFile, line, section);
1123                         section[0] = 0x1;
1124                 }
1125                 if (section[0] == 0x1)
1126                         continue;
1127
1128                 /* Split line into variable name and parameters */
1129                 ptr = strchr(str, '=');
1130                 if (!ptr) {
1131                         Config_Error(LOG_ERR, "%s, line %d: Syntax error!",
1132                                      NGIRCd_ConfFile, line);
1133                         continue;
1134                 }
1135                 *ptr = '\0';
1136                 var = str;
1137                 ngt_TrimStr(var);
1138                 arg = ptr + 1;
1139                 ngt_TrimStr(arg);
1140
1141                 if (strcasecmp(section, "[GLOBAL]") == 0)
1142                         Handle_GLOBAL(File, line, var, arg);
1143                 else if (strcasecmp(section, "[LIMITS]") == 0)
1144                         Handle_LIMITS(File, line, var, arg);
1145                 else if (strcasecmp(section, "[OPTIONS]") == 0)
1146                         Handle_OPTIONS(File, line, var, arg);
1147 #ifdef SSL_SUPPORT
1148                 else if (strcasecmp(section, "[SSL]") == 0)
1149                         Handle_SSL(File, line, var, arg);
1150 #endif
1151                 else if (strcasecmp(section, "[OPERATOR]") == 0)
1152                         Handle_OPERATOR(File, line, var, arg);
1153                 else if (strcasecmp(section, "[SERVER]") == 0)
1154                         Handle_SERVER(File, line, var, arg);
1155                 else if (strcasecmp(section, "[CHANNEL]") == 0)
1156                         Handle_CHANNEL(File, line, var, arg);
1157                 else
1158                         Config_Error(LOG_ERR,
1159                                      "%s, line %d: Variable \"%s\" outside section!",
1160                                      NGIRCd_ConfFile, line, var);
1161         }
1162 }
1163
1164 /**
1165  * Check whether a string argument is "true" or "false".
1166  *
1167  * @param Arg   Input string.
1168  * @returns     true if the input string has been parsed as "yes", "true"
1169  *              (case insensitive) or a non-zero integer value.
1170  */
1171 static bool
1172 Check_ArgIsTrue(const char *Arg)
1173 {
1174         if (strcasecmp(Arg, "yes") == 0)
1175                 return true;
1176         if (strcasecmp(Arg, "true") == 0)
1177                 return true;
1178         if (atoi(Arg) != 0)
1179                 return true;
1180
1181         return false;
1182 }
1183
1184 /**
1185  * Handle setting of "MaxNickLength".
1186  *
1187  * @param Line  Line number in configuration file.
1188  * @raram Arg   Input string.
1189  * @returns     New configured maximum nickname length.
1190  */
1191 static unsigned int
1192 Handle_MaxNickLength(int Line, const char *Arg)
1193 {
1194         unsigned new;
1195
1196         new = (unsigned) atoi(Arg) + 1;
1197         if (new > CLIENT_NICK_LEN) {
1198                 Config_Error(LOG_WARNING,
1199                              "%s, line %d: Value of \"MaxNickLength\" exceeds %u!",
1200                              NGIRCd_ConfFile, Line, CLIENT_NICK_LEN - 1);
1201                 return CLIENT_NICK_LEN;
1202         }
1203         if (new < 2) {
1204                 Config_Error(LOG_WARNING,
1205                              "%s, line %d: Value of \"MaxNickLength\" must be at least 1!",
1206                              NGIRCd_ConfFile, Line);
1207                 return 2;
1208         }
1209         return new;
1210 }
1211
1212 /**
1213  * Output a warning messages if IDENT is configured but not compiled in.
1214  */
1215 static void
1216 WarnIdent(int UNUSED Line)
1217 {
1218 #ifndef IDENTAUTH
1219         if (Conf_Ident) {
1220                 /* user has enabled ident lookups explicitly, but ... */
1221                 Config_Error(LOG_WARNING,
1222                         "%s: line %d: \"Ident = yes\", but ngircd was built without IDENT support!",
1223                         NGIRCd_ConfFile, Line);
1224         }
1225 #endif
1226 }
1227
1228 /**
1229  * Output a warning messages if IPv6 is configured but not compiled in.
1230  */
1231 static void
1232 WarnIPv6(int UNUSED Line)
1233 {
1234 #ifndef WANT_IPV6
1235         if (Conf_ConnectIPv6) {
1236                 /* user has enabled IPv6 explicitly, but ... */
1237                 Config_Error(LOG_WARNING,
1238                         "%s: line %d: \"ConnectIPv6 = yes\", but ngircd was built without IPv6 support!",
1239                         NGIRCd_ConfFile, Line);
1240         }
1241 #endif
1242 }
1243
1244 /**
1245  * Output a warning messages if PAM is configured but not compiled in.
1246  */
1247 static void
1248 WarnPAM(int UNUSED Line)
1249 {
1250 #ifndef PAM
1251         if (Conf_PAM) {
1252                 Config_Error(LOG_WARNING,
1253                         "%s: line %d: \"PAM = yes\", but ngircd was built without PAM support!",
1254                         NGIRCd_ConfFile, Line);
1255         }
1256 #endif
1257 }
1258
1259 /**
1260  * Handle legacy "NoXXX" options in [GLOBAL] section.
1261  *
1262  * TODO: This function and support for "NoXXX" could be removed starting
1263  * with ngIRCd release 19 (one release after marking it "deprecated").
1264  *
1265  * @param Var   Variable name.
1266  * @param Arg   Argument string.
1267  * @returns     true if a NoXXX option has been processed; false otherwise.
1268  */
1269 static bool
1270 CheckLegacyNoOption(const char *Var, const char *Arg)
1271 {
1272         if(strcasecmp(Var, "NoDNS") == 0) {
1273                 Conf_DNS = !Check_ArgIsTrue( Arg );
1274                 return true;
1275         }
1276         if (strcasecmp(Var, "NoIdent") == 0) {
1277                 Conf_Ident = !Check_ArgIsTrue(Arg);
1278                 return true;
1279         }
1280         if(strcasecmp(Var, "NoPAM") == 0) {
1281                 Conf_PAM = !Check_ArgIsTrue(Arg);
1282                 return true;
1283         }
1284         return false;
1285 }
1286
1287 /**
1288  * Handle deprecated legacy options in [GLOBAL] section.
1289  *
1290  * TODO: This function and support for these options in the [Global] section
1291  * could be removed starting with ngIRCd release 19 (one release after
1292  * marking it "deprecated").
1293  *
1294  * @param Var   Variable name.
1295  * @param Arg   Argument string.
1296  * @returns     true if a legacy option has been processed; false otherwise.
1297  */
1298 static const char*
1299 CheckLegacyGlobalOption(const char *File, int Line, char *Var, char *Arg)
1300 {
1301         if (strcasecmp(Var, "AllowRemoteOper") == 0
1302             || strcasecmp(Var, "ChrootDir") == 0
1303             || strcasecmp(Var, "ConnectIPv4") == 0
1304             || strcasecmp(Var, "ConnectIPv6") == 0
1305             || strcasecmp(Var, "OperCanUseMode") == 0
1306             || strcasecmp(Var, "OperChanPAutoOp") == 0
1307             || strcasecmp(Var, "OperServerMode") == 0
1308             || strcasecmp(Var, "PredefChannelsOnly") == 0
1309             || strcasecmp(Var, "SyslogFacility") == 0
1310             || strcasecmp(Var, "WebircPassword") == 0) {
1311                 Handle_OPTIONS(File, Line, Var, Arg);
1312                 return "[Options]";
1313         }
1314         if (strcasecmp(Var, "ConnectRetry") == 0
1315             || strcasecmp(Var, "IdleTimeout") == 0
1316             || strcasecmp(Var, "MaxConnections") == 0
1317             || strcasecmp(Var, "MaxConnectionsIP") == 0
1318             || strcasecmp(Var, "MaxJoins") == 0
1319             || strcasecmp(Var, "MaxNickLength") == 0
1320             || strcasecmp(Var, "PingTimeout") == 0
1321             || strcasecmp(Var, "PongTimeout") == 0) {
1322                 Handle_LIMITS(File, Line, Var, Arg);
1323                 return "[Limits]";
1324         }
1325 #ifdef SSL_SUPPORT
1326         if (strcasecmp(Var, "SSLCertFile") == 0
1327             || strcasecmp(Var, "SSLDHFile") == 0
1328             || strcasecmp(Var, "SSLKeyFile") == 0
1329             || strcasecmp(Var, "SSLKeyFilePassword") == 0
1330             || strcasecmp(Var, "SSLPorts") == 0) {
1331                 Handle_SSL(File, Line, Var + 3, Arg);
1332                 return "[SSL]";
1333         }
1334 #endif
1335
1336         return NULL;
1337 }
1338
1339 /**
1340  * Strip "no" prefix of a string.
1341  *
1342  * TODO: This function and support for "NoXXX" should be removed starting
1343  * with ngIRCd release 19! (One release after marking it "deprecated").
1344  *
1345  * @param str   Pointer to input string starting with "no".
1346  * @returns     New pointer to string without "no" prefix.
1347  */
1348 static const char *
1349 NoNo(const char *str)
1350 {
1351         assert(strncasecmp("no", str, 2) == 0 && str[2]);
1352         return str + 2;
1353 }
1354
1355 /**
1356  * Invert "boolean" string.
1357  *
1358  * TODO: This function and support for "NoXXX" should be removed starting
1359  * with ngIRCd release 19! (One release after marking it "deprecated").
1360  *
1361  * @param arg   "Boolean" input string.
1362  * @returns     Pointer to inverted "boolean string".
1363  */
1364 static const char *
1365 InvertArg(const char *arg)
1366 {
1367         return yesno_to_str(!Check_ArgIsTrue(arg));
1368 }
1369
1370 /**
1371  * Handle variable in [Global] configuration section.
1372  *
1373  * @param Line  Line numer in configuration file.
1374  * @param Var   Variable name.
1375  * @param Arg   Variable argument.
1376  */
1377 static void
1378 Handle_GLOBAL(const char *File, int Line, char *Var, char *Arg )
1379 {
1380         struct passwd *pwd;
1381         struct group *grp;
1382         size_t len;
1383         const char *section;
1384
1385         assert(File != NULL);
1386         assert(Line > 0);
1387         assert(Var != NULL);
1388         assert(Arg != NULL);
1389
1390         if (strcasecmp(Var, "Name") == 0) {
1391                 len = strlcpy(Conf_ServerName, Arg, sizeof(Conf_ServerName));
1392                 if (len >= sizeof(Conf_ServerName))
1393                         Config_Error_TooLong(File, Line, Var);
1394                 return;
1395         }
1396         if (strcasecmp(Var, "AdminInfo1") == 0) {
1397                 len = strlcpy(Conf_ServerAdmin1, Arg, sizeof(Conf_ServerAdmin1));
1398                 if (len >= sizeof(Conf_ServerAdmin1))
1399                         Config_Error_TooLong(File, Line, Var);
1400                 return;
1401         }
1402         if (strcasecmp(Var, "AdminInfo2") == 0) {
1403                 len = strlcpy(Conf_ServerAdmin2, Arg, sizeof(Conf_ServerAdmin2));
1404                 if (len >= sizeof(Conf_ServerAdmin2))
1405                         Config_Error_TooLong(File, Line, Var);
1406                 return;
1407         }
1408         if (strcasecmp(Var, "AdminEMail") == 0) {
1409                 len = strlcpy(Conf_ServerAdminMail, Arg,
1410                         sizeof(Conf_ServerAdminMail));
1411                 if (len >= sizeof(Conf_ServerAdminMail))
1412                         Config_Error_TooLong(File, Line, Var);
1413                 return;
1414         }
1415         if (strcasecmp(Var, "Info") == 0) {
1416                 len = strlcpy(Conf_ServerInfo, Arg, sizeof(Conf_ServerInfo));
1417                 if (len >= sizeof(Conf_ServerInfo))
1418                         Config_Error_TooLong(File, Line, Var);
1419                 return;
1420         }
1421         if (strcasecmp(Var, "HelpFile") == 0) {
1422                 len = strlcpy(Conf_HelpFile, Arg, sizeof(Conf_HelpFile));
1423                 if (len >= sizeof(Conf_HelpFile))
1424                         Config_Error_TooLong(File, Line, Var);
1425                 return;
1426         }
1427         if (strcasecmp(Var, "Listen") == 0) {
1428                 if (Conf_ListenAddress) {
1429                         Config_Error(LOG_ERR,
1430                                      "Multiple Listen= options, ignoring: %s",
1431                                      Arg);
1432                         return;
1433                 }
1434                 Conf_ListenAddress = strdup_warn(Arg);
1435                 /* If allocation fails, we're in trouble: we cannot ignore the
1436                  * error -- otherwise ngircd would listen on all interfaces. */
1437                 if (!Conf_ListenAddress) {
1438                         Config_Error(LOG_ALERT,
1439                                      "%s exiting due to fatal errors!",
1440                                      PACKAGE_NAME);
1441                         exit(1);
1442                 }
1443                 return;
1444         }
1445         if (strcasecmp(Var, "MotdFile") == 0) {
1446                 len = strlcpy(Conf_MotdFile, Arg, sizeof(Conf_MotdFile));
1447                 if (len >= sizeof(Conf_MotdFile))
1448                         Config_Error_TooLong(File, Line, Var);
1449                 return;
1450         }
1451         if (strcasecmp(Var, "MotdPhrase") == 0) {
1452                 len = strlen(Arg);
1453                 if (len == 0)
1454                         return;
1455                 if (len >= LINE_LEN) {
1456                         Config_Error_TooLong(File, Line, Var);
1457                         return;
1458                 }
1459                 if (!array_copyb(&Conf_Motd, Arg, len + 1))
1460                         Config_Error(LOG_WARNING,
1461                                      "%s, line %d: Could not append MotdPhrase: %s",
1462                                      NGIRCd_ConfFile, Line, strerror(errno));
1463                 Using_MotdFile = false;
1464                 return;
1465         }
1466         if(strcasecmp(Var, "Password") == 0) {
1467                 len = strlcpy(Conf_ServerPwd, Arg, sizeof(Conf_ServerPwd));
1468                 if (len >= sizeof(Conf_ServerPwd))
1469                         Config_Error_TooLong(File, Line, Var);
1470                 return;
1471         }
1472         if (strcasecmp(Var, "PidFile") == 0) {
1473                 len = strlcpy(Conf_PidFile, Arg, sizeof(Conf_PidFile));
1474                 if (len >= sizeof(Conf_PidFile))
1475                         Config_Error_TooLong(File, Line, Var);
1476                 return;
1477         }
1478         if (strcasecmp(Var, "Ports") == 0) {
1479                 ports_parse(&Conf_ListenPorts, Line, Arg);
1480                 return;
1481         }
1482         if (strcasecmp(Var, "ServerGID") == 0) {
1483                 grp = getgrnam(Arg);
1484                 if (grp)
1485                         Conf_GID = grp->gr_gid;
1486                 else {
1487                         Conf_GID = (unsigned int)atoi(Arg);
1488                         if (!Conf_GID && strcmp(Arg, "0"))
1489                                 Config_Error(LOG_WARNING,
1490                                              "%s, line %d: Value of \"%s\" is not a valid group name or ID!",
1491                                              NGIRCd_ConfFile, Line, Var);
1492                 }
1493                 return;
1494         }
1495         if (strcasecmp(Var, "ServerUID") == 0) {
1496                 pwd = getpwnam(Arg);
1497                 if (pwd)
1498                         Conf_UID = pwd->pw_uid;
1499                 else {
1500                         Conf_UID = (unsigned int)atoi(Arg);
1501                         if (!Conf_UID && strcmp(Arg, "0"))
1502                                 Config_Error(LOG_WARNING,
1503                                              "%s, line %d: Value of \"%s\" is not a valid user name or ID!",
1504                                              NGIRCd_ConfFile, Line, Var);
1505                 }
1506                 return;
1507         }
1508
1509         if (CheckLegacyNoOption(Var, Arg)) {
1510                 /* TODO: This function and support for "NoXXX" could be
1511                  * be removed starting with ngIRCd release 19 (one release
1512                  * after marking it "deprecated"). */
1513                 Config_Error(LOG_WARNING,
1514                              "%s, line %d (section \"Global\"): \"No\"-Prefix is deprecated, use \"%s = %s\" in [Options] section!",
1515                              NGIRCd_ConfFile, Line, NoNo(Var), InvertArg(Arg));
1516                 if (strcasecmp(Var, "NoIdent") == 0)
1517                         WarnIdent(Line);
1518                 else if (strcasecmp(Var, "NoPam") == 0)
1519                         WarnPAM(Line);
1520                 return;
1521         }
1522         if ((section = CheckLegacyGlobalOption(File, Line, Var, Arg))) {
1523                 /** TODO: This function and support for these options in the
1524                  * [Global] section could be removed starting with ngIRCd
1525                  * release 19 (one release after marking it "deprecated"). */
1526                 if (strncasecmp(Var, "SSL", 3) == 0) {
1527                         Config_Error(LOG_WARNING,
1528                                      "%s, line %d (section \"Global\"): \"%s\" is deprecated here, move it to %s and rename to \"%s\"!",
1529                                      NGIRCd_ConfFile, Line, Var, section,
1530                                      Var + 3);
1531                 } else {
1532                         Config_Error(LOG_WARNING,
1533                                      "%s, line %d (section \"Global\"): \"%s\" is deprecated here, move it to %s!",
1534                                      NGIRCd_ConfFile, Line, Var, section);
1535                 }
1536                 return;
1537         }
1538
1539         Config_Error_Section(File, Line, Var, "Global");
1540 }
1541
1542 /**
1543  * Handle variable in [Limits] configuration section.
1544  *
1545  * @param Line  Line numer in configuration file.
1546  * @param Var   Variable name.
1547  * @param Arg   Variable argument.
1548  */
1549 static void
1550 Handle_LIMITS(const char *File, int Line, char *Var, char *Arg)
1551 {
1552         assert(File != NULL);
1553         assert(Line > 0);
1554         assert(Var != NULL);
1555         assert(Arg != NULL);
1556
1557         if (strcasecmp(Var, "ConnectRetry") == 0) {
1558                 Conf_ConnectRetry = atoi(Arg);
1559                 if (Conf_ConnectRetry < 5) {
1560                         Config_Error(LOG_WARNING,
1561                                      "%s, line %d: Value of \"ConnectRetry\" too low!",
1562                                      NGIRCd_ConfFile, Line);
1563                         Conf_ConnectRetry = 5;
1564                 }
1565                 return;
1566         }
1567         if (strcasecmp(Var, "IdleTimeout") == 0) {
1568                 Conf_IdleTimeout = atoi(Arg);
1569                 if (!Conf_IdleTimeout && strcmp(Arg, "0"))
1570                         Config_Error_NaN(File, Line, Var);
1571                 return;
1572         }
1573         if (strcasecmp(Var, "MaxConnections") == 0) {
1574                 Conf_MaxConnections = atoi(Arg);
1575                 if (!Conf_MaxConnections && strcmp(Arg, "0"))
1576                         Config_Error_NaN(File, Line, Var);
1577                 return;
1578         }
1579         if (strcasecmp(Var, "MaxConnectionsIP") == 0) {
1580                 Conf_MaxConnectionsIP = atoi(Arg);
1581                 if (!Conf_MaxConnectionsIP && strcmp(Arg, "0"))
1582                         Config_Error_NaN(File, Line, Var);
1583                 return;
1584         }
1585         if (strcasecmp(Var, "MaxJoins") == 0) {
1586                 Conf_MaxJoins = atoi(Arg);
1587                 if (!Conf_MaxJoins && strcmp(Arg, "0"))
1588                         Config_Error_NaN(File, Line, Var);
1589                 return;
1590         }
1591         if (strcasecmp(Var, "MaxNickLength") == 0) {
1592                 Conf_MaxNickLength = Handle_MaxNickLength(Line, Arg);
1593                 return;
1594         }
1595         if (strcasecmp(Var, "MaxListSize") == 0) {
1596                 Conf_MaxListSize = atoi(Arg);
1597                 if (!Conf_MaxListSize && strcmp(Arg, "0"))
1598                         Config_Error_NaN(File, Line, Var);
1599                 return;
1600         }
1601         if (strcasecmp(Var, "PingTimeout") == 0) {
1602                 Conf_PingTimeout = atoi(Arg);
1603                 if (Conf_PingTimeout < 5) {
1604                         Config_Error(LOG_WARNING,
1605                                      "%s, line %d: Value of \"PingTimeout\" too low!",
1606                                      NGIRCd_ConfFile, Line);
1607                         Conf_PingTimeout = 5;
1608                 }
1609                 return;
1610         }
1611         if (strcasecmp(Var, "PongTimeout") == 0) {
1612                 Conf_PongTimeout = atoi(Arg);
1613                 if (Conf_PongTimeout < 5) {
1614                         Config_Error(LOG_WARNING,
1615                                      "%s, line %d: Value of \"PongTimeout\" too low!",
1616                                      NGIRCd_ConfFile, Line);
1617                         Conf_PongTimeout = 5;
1618                 }
1619                 return;
1620         }
1621
1622         Config_Error_Section(File, Line, Var, "Limits");
1623 }
1624
1625 /**
1626  * Handle variable in [Options] configuration section.
1627  *
1628  * @param Line  Line numer in configuration file.
1629  * @param Var   Variable name.
1630  * @param Arg   Variable argument.
1631  */
1632 static void
1633 Handle_OPTIONS(const char *File, int Line, char *Var, char *Arg)
1634 {
1635         size_t len;
1636
1637         assert(File != NULL);
1638         assert(Line > 0);
1639         assert(Var != NULL);
1640         assert(Arg != NULL);
1641
1642         if (strcasecmp(Var, "AllowRemoteOper") == 0) {
1643                 Conf_AllowRemoteOper = Check_ArgIsTrue(Arg);
1644                 return;
1645         }
1646         if (strcasecmp(Var, "ChrootDir") == 0) {
1647                 len = strlcpy(Conf_Chroot, Arg, sizeof(Conf_Chroot));
1648                 if (len >= sizeof(Conf_Chroot))
1649                         Config_Error_TooLong(File, Line, Var);
1650                 return;
1651         }
1652         if (strcasecmp(Var, "CloakHost") == 0) {
1653                 len = strlcpy(Conf_CloakHost, Arg, sizeof(Conf_CloakHost));
1654                 if (len >= sizeof(Conf_CloakHost))
1655                         Config_Error_TooLong(File, Line, Var);
1656                 return;
1657         }
1658         if (strcasecmp(Var, "CloakHostModeX") == 0) {
1659                 len = strlcpy(Conf_CloakHostModeX, Arg, sizeof(Conf_CloakHostModeX));
1660                 if (len >= sizeof(Conf_CloakHostModeX))
1661                         Config_Error_TooLong(File, Line, Var);
1662                 return;
1663         }
1664         if (strcasecmp(Var, "CloakHostSalt") == 0) {
1665                 len = strlcpy(Conf_CloakHostSalt, Arg, sizeof(Conf_CloakHostSalt));
1666                 if (len >= sizeof(Conf_CloakHostSalt))
1667                         Config_Error_TooLong(File, Line, Var);
1668                 return;
1669         }
1670         if (strcasecmp(Var, "CloakUserToNick") == 0) {
1671                 Conf_CloakUserToNick = Check_ArgIsTrue(Arg);
1672                 return;
1673         }
1674         if (strcasecmp(Var, "ConnectIPv6") == 0) {
1675                 Conf_ConnectIPv6 = Check_ArgIsTrue(Arg);
1676                 WarnIPv6(Line);
1677                 return;
1678         }
1679         if (strcasecmp(Var, "ConnectIPv4") == 0) {
1680                 Conf_ConnectIPv4 = Check_ArgIsTrue(Arg);
1681                 return;
1682         }
1683         if (strcasecmp(Var, "DNS") == 0) {
1684                 Conf_DNS = Check_ArgIsTrue(Arg);
1685                 return;
1686         }
1687         if (strcasecmp(Var, "Ident") == 0) {
1688                 Conf_Ident = Check_ArgIsTrue(Arg);
1689                 WarnIdent(Line);
1690                 return;
1691         }
1692         if (strcasecmp(Var, "IncludeDir") == 0) {
1693                 if (Conf_IncludeDir[0]) {
1694                         Config_Error(LOG_ERR,
1695                                      "%s, line %d: Can't overwrite value of \"IncludeDir\" variable!",
1696                                      File, Line);
1697                         return;
1698                 }
1699                 len = strlcpy(Conf_IncludeDir, Arg, sizeof(Conf_IncludeDir));
1700                 if (len >= sizeof(Conf_IncludeDir))
1701                         Config_Error_TooLong(File, Line, Var);
1702                 return;
1703         }
1704         if (strcasecmp(Var, "MorePrivacy") == 0) {
1705                 Conf_MorePrivacy = Check_ArgIsTrue(Arg);
1706                 return;
1707         }
1708         if (strcasecmp(Var, "NoticeAuth") == 0) {
1709                 Conf_NoticeAuth = Check_ArgIsTrue(Arg);
1710                 return;
1711         }
1712         if (strcasecmp(Var, "OperCanUseMode") == 0) {
1713                 Conf_OperCanMode = Check_ArgIsTrue(Arg);
1714                 return;
1715         }
1716         if (strcasecmp(Var, "OperChanPAutoOp") == 0) {
1717                 Conf_OperChanPAutoOp = Check_ArgIsTrue(Arg);
1718                 return;
1719         }
1720         if (strcasecmp(Var, "OperServerMode") == 0) {
1721                 Conf_OperServerMode = Check_ArgIsTrue(Arg);
1722                 return;
1723         }
1724         if (strcasecmp(Var, "PAM") == 0) {
1725                 Conf_PAM = Check_ArgIsTrue(Arg);
1726                 WarnPAM(Line);
1727                 return;
1728         }
1729         if (strcasecmp(Var, "PAMIsOptional") == 0 ) {
1730                 Conf_PAMIsOptional = Check_ArgIsTrue(Arg);
1731                 return;
1732         }
1733         if (strcasecmp(Var, "PredefChannelsOnly") == 0) {
1734                 Conf_PredefChannelsOnly = Check_ArgIsTrue(Arg);
1735                 return;
1736         }
1737 #ifndef STRICT_RFC
1738         if (strcasecmp(Var, "RequireAuthPing") == 0) {
1739                 Conf_AuthPing = Check_ArgIsTrue(Arg);
1740                 return;
1741         }
1742 #endif
1743         if (strcasecmp(Var, "ScrubCTCP") == 0) {
1744                 Conf_ScrubCTCP = Check_ArgIsTrue(Arg);
1745                 return;
1746         }
1747 #ifdef SYSLOG
1748         if (strcasecmp(Var, "SyslogFacility") == 0) {
1749                 Conf_SyslogFacility = ngt_SyslogFacilityID(Arg,
1750                                                            Conf_SyslogFacility);
1751                 return;
1752         }
1753 #endif
1754         if (strcasecmp(Var, "WebircPassword") == 0) {
1755                 len = strlcpy(Conf_WebircPwd, Arg, sizeof(Conf_WebircPwd));
1756                 if (len >= sizeof(Conf_WebircPwd))
1757                         Config_Error_TooLong(File, Line, Var);
1758                 return;
1759         }
1760
1761         Config_Error_Section(File, Line, Var, "Options");
1762 }
1763
1764 #ifdef SSL_SUPPORT
1765
1766 /**
1767  * Handle variable in [SSL] configuration section.
1768  *
1769  * @param Line  Line numer in configuration file.
1770  * @param Var   Variable name.
1771  * @param Arg   Variable argument.
1772  */
1773 static void
1774 Handle_SSL(const char *File, int Line, char *Var, char *Arg)
1775 {
1776         assert(File != NULL);
1777         assert(Line > 0);
1778         assert(Var != NULL);
1779         assert(Arg != NULL);
1780
1781         if (strcasecmp(Var, "CertFile") == 0) {
1782                 assert(Conf_SSLOptions.CertFile == NULL);
1783                 Conf_SSLOptions.CertFile = strdup_warn(Arg);
1784                 return;
1785         }
1786         if (strcasecmp(Var, "DHFile") == 0) {
1787                 assert(Conf_SSLOptions.DHFile == NULL);
1788                 Conf_SSLOptions.DHFile = strdup_warn(Arg);
1789                 return;
1790         }
1791         if (strcasecmp(Var, "KeyFile") == 0) {
1792                 assert(Conf_SSLOptions.KeyFile == NULL);
1793                 Conf_SSLOptions.KeyFile = strdup_warn(Arg);
1794                 return;
1795         }
1796         if (strcasecmp(Var, "KeyFilePassword") == 0) {
1797                 assert(array_bytes(&Conf_SSLOptions.KeyFilePassword) == 0);
1798                 if (!array_copys(&Conf_SSLOptions.KeyFilePassword, Arg))
1799                         Config_Error(LOG_ERR,
1800                                      "%s, line %d (section \"SSL\"): Could not copy %s: %s!",
1801                                      File, Line, Var, strerror(errno));
1802                 return;
1803         }
1804         if (strcasecmp(Var, "Ports") == 0) {
1805                 ports_parse(&Conf_SSLOptions.ListenPorts, Line, Arg);
1806                 return;
1807         }
1808
1809         Config_Error_Section(File, Line, Var, "SSL");
1810 }
1811
1812 #endif
1813
1814 /**
1815  * Handle variable in [Operator] configuration section.
1816  *
1817  * @param Line  Line numer in configuration file.
1818  * @param Var   Variable name.
1819  * @param Arg   Variable argument.
1820  */
1821 static void
1822 Handle_OPERATOR(const char *File, int Line, char *Var, char *Arg )
1823 {
1824         size_t len;
1825         struct Conf_Oper *op;
1826
1827         assert( File != NULL );
1828         assert( Line > 0 );
1829         assert( Var != NULL );
1830         assert( Arg != NULL );
1831
1832         op = array_get(&Conf_Opers, sizeof(*op),
1833                          array_length(&Conf_Opers, sizeof(*op)) - 1);
1834         if (!op)
1835                 return;
1836
1837         if (strcasecmp(Var, "Name") == 0) {
1838                 /* Name of IRC operator */
1839                 len = strlcpy(op->name, Arg, sizeof(op->name));
1840                 if (len >= sizeof(op->name))
1841                                 Config_Error_TooLong(File, Line, Var);
1842                 return;
1843         }
1844         if (strcasecmp(Var, "Password") == 0) {
1845                 /* Password of IRC operator */
1846                 len = strlcpy(op->pwd, Arg, sizeof(op->pwd));
1847                 if (len >= sizeof(op->pwd))
1848                                 Config_Error_TooLong(File, Line, Var);
1849                 return;
1850         }
1851         if (strcasecmp(Var, "Mask") == 0) {
1852                 if (op->mask)
1853                         return; /* Hostname already configured */
1854                 op->mask = strdup_warn( Arg );
1855                 return;
1856         }
1857
1858         Config_Error_Section(File, Line, Var, "Operator");
1859 }
1860
1861 /**
1862  * Handle variable in [Server] configuration section.
1863  *
1864  * @param Line  Line numer in configuration file.
1865  * @param Var   Variable name.
1866  * @param Arg   Variable argument.
1867  */
1868 static void
1869 Handle_SERVER(const char *File, int Line, char *Var, char *Arg )
1870 {
1871         long port;
1872         size_t len;
1873
1874         assert( File != NULL );
1875         assert( Line > 0 );
1876         assert( Var != NULL );
1877         assert( Arg != NULL );
1878
1879         /* Ignore server block if no space is left in server configuration structure */
1880         if( New_Server_Idx <= NONE ) return;
1881
1882         if( strcasecmp( Var, "Host" ) == 0 ) {
1883                 /* Hostname of the server */
1884                 len = strlcpy( New_Server.host, Arg, sizeof( New_Server.host ));
1885                 if (len >= sizeof( New_Server.host ))
1886                         Config_Error_TooLong(File, Line, Var);
1887                 return;
1888         }
1889         if( strcasecmp( Var, "Name" ) == 0 ) {
1890                 /* Name of the server ("Nick"/"ID") */
1891                 len = strlcpy( New_Server.name, Arg, sizeof( New_Server.name ));
1892                 if (len >= sizeof( New_Server.name ))
1893                         Config_Error_TooLong(File, Line, Var);
1894                 return;
1895         }
1896         if (strcasecmp(Var, "Bind") == 0) {
1897                 if (ng_ipaddr_init(&New_Server.bind_addr, Arg, 0))
1898                         return;
1899
1900                 Config_Error(LOG_ERR, "%s, line %d (section \"Server\"): Can't parse IP address \"%s\"",
1901                                 NGIRCd_ConfFile, Line, Arg);
1902                 return;
1903         }
1904         if( strcasecmp( Var, "MyPassword" ) == 0 ) {
1905                 /* Password of this server which is sent to the peer */
1906                 if (*Arg == ':') {
1907                         Config_Error(LOG_ERR,
1908                                 "%s, line %d (section \"Server\"): MyPassword must not start with ':'!",
1909                                                                                 NGIRCd_ConfFile, Line);
1910                 }
1911                 len = strlcpy( New_Server.pwd_in, Arg, sizeof( New_Server.pwd_in ));
1912                 if (len >= sizeof( New_Server.pwd_in ))
1913                         Config_Error_TooLong(File, Line, Var);
1914                 return;
1915         }
1916         if( strcasecmp( Var, "PeerPassword" ) == 0 ) {
1917                 /* Passwort of the peer which must be received */
1918                 len = strlcpy( New_Server.pwd_out, Arg, sizeof( New_Server.pwd_out ));
1919                 if (len >= sizeof( New_Server.pwd_out ))
1920                         Config_Error_TooLong(File, Line, Var);
1921                 return;
1922         }
1923         if( strcasecmp( Var, "Port" ) == 0 ) {
1924                 /* Port to which this server should connect */
1925                 port = atol( Arg );
1926                 if (port >= 0 && port < 0xFFFF)
1927                         New_Server.port = (UINT16)port;
1928                 else
1929                         Config_Error(LOG_ERR,
1930                                 "%s, line %d (section \"Server\"): Illegal port number %ld!",
1931                                 NGIRCd_ConfFile, Line, port );
1932                 return;
1933         }
1934 #ifdef SSL_SUPPORT
1935         if( strcasecmp( Var, "SSLConnect" ) == 0 ) {
1936                 New_Server.SSLConnect = Check_ArgIsTrue(Arg);
1937                 return;
1938         }
1939 #endif
1940         if( strcasecmp( Var, "Group" ) == 0 ) {
1941                 /* Server group */
1942                 New_Server.group = atoi( Arg );
1943                 if (!New_Server.group && strcmp(Arg, "0"))
1944                         Config_Error_NaN(File, Line, Var);
1945                 return;
1946         }
1947         if( strcasecmp( Var, "Passive" ) == 0 ) {
1948                 if (Check_ArgIsTrue(Arg))
1949                         New_Server.flags |= CONF_SFLAG_DISABLED;
1950                 return;
1951         }
1952         if (strcasecmp(Var, "ServiceMask") == 0) {
1953                 len = strlcpy(New_Server.svs_mask, ngt_LowerStr(Arg),
1954                               sizeof(New_Server.svs_mask));
1955                 if (len >= sizeof(New_Server.svs_mask))
1956                         Config_Error_TooLong(File, Line, Var);
1957                 return;
1958         }
1959
1960         Config_Error_Section(File, Line, Var, "Server");
1961 }
1962
1963 /**
1964  * Copy channel name into channel structure.
1965  *
1966  * If the channel name is not valid because of a missing prefix ('#', '&'),
1967  * a default prefix of '#' will be added.
1968  *
1969  * @param new_chan      New already allocated channel structure.
1970  * @param name          Name of the new channel.
1971  * @returns             true on success, false otherwise.
1972  */
1973 static bool
1974 Handle_Channelname(struct Conf_Channel *new_chan, const char *name)
1975 {
1976         size_t size = sizeof(new_chan->name);
1977         char *dest = new_chan->name;
1978
1979         if (!Channel_IsValidName(name)) {
1980                 /*
1981                  * maybe user forgot to add a '#'.
1982                  * This is only here for user convenience.
1983                  */
1984                 *dest = '#';
1985                 --size;
1986                 ++dest;
1987         }
1988         return size > strlcpy(dest, name, size);
1989 }
1990
1991 /**
1992  * Handle variable in [Channel] configuration section.
1993  *
1994  * @param Line  Line numer in configuration file.
1995  * @param Var   Variable name.
1996  * @param Arg   Variable argument.
1997  */
1998 static void
1999 Handle_CHANNEL(const char *File, int Line, char *Var, char *Arg)
2000 {
2001         size_t len;
2002         struct Conf_Channel *chan;
2003
2004         assert( File != NULL );
2005         assert( Line > 0 );
2006         assert( Var != NULL );
2007         assert( Arg != NULL );
2008
2009         chan = array_get(&Conf_Channels, sizeof(*chan),
2010                          array_length(&Conf_Channels, sizeof(*chan)) - 1);
2011         if (!chan)
2012                 return;
2013
2014         if (strcasecmp(Var, "Name") == 0) {
2015                 if (!Handle_Channelname(chan, Arg))
2016                         Config_Error_TooLong(File, Line, Var);
2017                 return;
2018         }
2019         if (strcasecmp(Var, "Modes") == 0) {
2020                 /* Initial modes */
2021                 len = strlcpy(chan->modes, Arg, sizeof(chan->modes));
2022                 if (len >= sizeof(chan->modes))
2023                         Config_Error_TooLong(File, Line, Var);
2024                 return;
2025         }
2026         if( strcasecmp( Var, "Topic" ) == 0 ) {
2027                 /* Initial topic */
2028                 len = strlcpy(chan->topic, Arg, sizeof(chan->topic));
2029                 if (len >= sizeof(chan->topic))
2030                         Config_Error_TooLong(File, Line, Var);
2031                 return;
2032         }
2033         if( strcasecmp( Var, "Key" ) == 0 ) {
2034                 /* Initial Channel Key (mode k) */
2035                 len = strlcpy(chan->key, Arg, sizeof(chan->key));
2036                 if (len >= sizeof(chan->key))
2037                         Config_Error_TooLong(File, Line, Var);
2038                 return;
2039         }
2040         if( strcasecmp( Var, "MaxUsers" ) == 0 ) {
2041                 /* maximum user limit, mode l */
2042                 chan->maxusers = (unsigned long) atol(Arg);
2043                 if (!chan->maxusers && strcmp(Arg, "0"))
2044                         Config_Error_NaN(File, Line, Var);
2045                 return;
2046         }
2047         if (strcasecmp(Var, "KeyFile") == 0) {
2048                 /* channel keys */
2049                 len = strlcpy(chan->keyfile, Arg, sizeof(chan->keyfile));
2050                 if (len >= sizeof(chan->keyfile))
2051                         Config_Error_TooLong(File, Line, Var);
2052                 return;
2053         }
2054
2055         Config_Error_Section(File, Line, Var, "Channel");
2056 }
2057
2058 /**
2059  * Validate server configuration.
2060  *
2061  * Please note that this function uses exit(1) on fatal errors and therefore
2062  * can result in ngIRCd terminating!
2063  *
2064  * @param Configtest    true if the daemon has been called with "--configtest".
2065  * @param Rehash        true if re-reading configuration on runtime.
2066  * @returns             true if configuration is valid.
2067  */
2068 static bool
2069 Validate_Config(bool Configtest, bool Rehash)
2070 {
2071         /* Validate configuration settings. */
2072
2073 #ifdef DEBUG
2074         int i, servers, servers_once;
2075 #endif
2076         bool config_valid = true;
2077         char *ptr;
2078
2079         /* Emit a warning when the config file is not a full path name */
2080         if (NGIRCd_ConfFile[0] && NGIRCd_ConfFile[0] != '/') {
2081                 Config_Error(LOG_WARNING,
2082                         "Not specifying a full path name to \"%s\" can cause problems when rehashing the server!",
2083                         NGIRCd_ConfFile);
2084         }
2085
2086         /* Validate configured server name, see RFC 2812 section 2.3.1 */
2087         ptr = Conf_ServerName;
2088         do {
2089                 if (*ptr >= 'a' && *ptr <= 'z') continue;
2090                 if (*ptr >= 'A' && *ptr <= 'Z') continue;
2091                 if (*ptr >= '0' && *ptr <= '9') continue;
2092                 if (ptr > Conf_ServerName) {
2093                         if (*ptr == '.' || *ptr == '-')
2094                                 continue;
2095                 }
2096                 Conf_ServerName[0] = '\0';
2097                 break;
2098         } while (*(++ptr));
2099
2100         if (!Conf_ServerName[0]) {
2101                 /* No server name configured! */
2102                 config_valid = false;
2103                 Config_Error(LOG_ALERT,
2104                              "No (valid) server name configured in \"%s\" (section 'Global': 'Name')!",
2105                              NGIRCd_ConfFile);
2106                 if (!Configtest && !Rehash) {
2107                         Config_Error(LOG_ALERT,
2108                                      "%s exiting due to fatal errors!",
2109                                      PACKAGE_NAME);
2110                         exit(1);
2111                 }
2112         }
2113
2114         if (Conf_ServerName[0] && !strchr(Conf_ServerName, '.')) {
2115                 /* No dot in server name! */
2116                 config_valid = false;
2117                 Config_Error(LOG_ALERT,
2118                              "Invalid server name configured in \"%s\" (section 'Global': 'Name'): Dot missing!",
2119                              NGIRCd_ConfFile);
2120                 if (!Configtest) {
2121                         Config_Error(LOG_ALERT,
2122                                      "%s exiting due to fatal errors!",
2123                                      PACKAGE_NAME);
2124                         exit(1);
2125                 }
2126         }
2127
2128 #ifdef STRICT_RFC
2129         if (!Conf_ServerAdminMail[0]) {
2130                 /* No administrative contact configured! */
2131                 config_valid = false;
2132                 Config_Error(LOG_ALERT,
2133                              "No administrator email address configured in \"%s\" ('AdminEMail')!",
2134                              NGIRCd_ConfFile);
2135                 if (!Configtest) {
2136                         Config_Error(LOG_ALERT,
2137                                      "%s exiting due to fatal errors!",
2138                                      PACKAGE_NAME);
2139                         exit(1);
2140                 }
2141         }
2142 #endif
2143
2144         if (!Conf_ServerAdmin1[0] && !Conf_ServerAdmin2[0]
2145             && !Conf_ServerAdminMail[0]) {
2146                 /* No administrative information configured! */
2147                 Config_Error(LOG_WARNING,
2148                              "No administrative information configured but required by RFC!");
2149         }
2150
2151 #ifdef PAM
2152         if (Conf_ServerPwd[0])
2153                 Config_Error(LOG_ERR,
2154                              "This server uses PAM, \"Password\" in [Global] section will be ignored!");
2155 #endif
2156
2157 #ifdef DEBUG
2158         servers = servers_once = 0;
2159         for (i = 0; i < MAX_SERVERS; i++) {
2160                 if (Conf_Server[i].name[0]) {
2161                         servers++;
2162                         if (Conf_Server[i].flags & CONF_SFLAG_ONCE)
2163                                 servers_once++;
2164                 }
2165         }
2166         Log(LOG_DEBUG,
2167             "Configuration: Operators=%ld, Servers=%d[%d], Channels=%ld",
2168             array_length(&Conf_Opers, sizeof(struct Conf_Oper)),
2169             servers, servers_once,
2170             array_length(&Conf_Channels, sizeof(struct Conf_Channel)));
2171 #endif
2172
2173         return config_valid;
2174 }
2175
2176 /**
2177  * Output "line too long" warning.
2178  *
2179  * @param Line  Line number in configuration file.
2180  * @param Item  Affected variable name.
2181  */
2182 static void
2183 Config_Error_TooLong(const char *File, const int Line, const char *Item)
2184 {
2185         Config_Error(LOG_WARNING, "%s, line %d: Value of \"%s\" too long!",
2186                      File, Line, Item );
2187 }
2188
2189 /**
2190  * Output "unknown variable" warning.
2191  *
2192  * @param Line          Line number in configuration file.
2193  * @param Item          Affected variable name.
2194  * @param Section       Section name.
2195  */
2196 static void
2197 Config_Error_Section(const char *File, const int Line, const char *Item,
2198                      const char *Section)
2199 {
2200         Config_Error(LOG_ERR, "%s, line %d (section \"%s\"): Unknown variable \"%s\"!",
2201                      File, Line, Section, Item);
2202 }
2203
2204 /**
2205  * Output "not a number" warning.
2206  *
2207  * @param Line  Line number in configuration file.
2208  * @param Item  Affected variable name.
2209  */
2210 static void
2211 Config_Error_NaN(const char *File, const int Line, const char *Item )
2212 {
2213         Config_Error(LOG_WARNING, "%s, line %d: Value of \"%s\" is not a number!",
2214                      File, Line, Item );
2215 }
2216
2217 /**
2218  * Output configuration error to console and/or logfile.
2219  *
2220  * On runtime, the normal log functions of the daemon are used. But when
2221  * testing the configuration ("--configtest"), all messages go directly
2222  * to the console.
2223  *
2224  * @param Level         Severity level of the message.
2225  * @param Format        Format string; see printf() function.
2226  */
2227 #ifdef PROTOTYPES
2228 static void Config_Error( const int Level, const char *Format, ... )
2229 #else
2230 static void Config_Error( Level, Format, va_alist )
2231 const int Level;
2232 const char *Format;
2233 va_dcl
2234 #endif
2235 {
2236         char msg[MAX_LOG_MSG_LEN];
2237         va_list ap;
2238
2239         assert( Format != NULL );
2240
2241 #ifdef PROTOTYPES
2242         va_start( ap, Format );
2243 #else
2244         va_start( ap );
2245 #endif
2246         vsnprintf( msg, MAX_LOG_MSG_LEN, Format, ap );
2247         va_end( ap );
2248
2249         if (!Use_Log) {
2250                 if (Level <= LOG_WARNING)
2251                         printf(" - %s\n", msg);
2252                 else
2253                         puts(msg);
2254         } else
2255                 Log(Level, "%s", msg);
2256 }
2257
2258 #ifdef DEBUG
2259
2260 /**
2261  * Dump internal state of the "configuration module".
2262  */
2263 GLOBAL void
2264 Conf_DebugDump(void)
2265 {
2266         int i;
2267
2268         Log(LOG_DEBUG, "Configured servers:");
2269         for (i = 0; i < MAX_SERVERS; i++) {
2270                 if (! Conf_Server[i].name[0])
2271                         continue;
2272                 Log(LOG_DEBUG,
2273                     " - %s: %s:%d, last=%ld, group=%d, flags=%d, conn=%d",
2274                     Conf_Server[i].name, Conf_Server[i].host,
2275                     Conf_Server[i].port, Conf_Server[i].lasttry,
2276                     Conf_Server[i].group, Conf_Server[i].flags,
2277                     Conf_Server[i].conn_id);
2278         }
2279 }
2280
2281 #endif
2282
2283 /**
2284  * Initialize server configuration structur to default values.
2285  *
2286  * @param Server        Pointer to server structure to initialize.
2287  */
2288 static void
2289 Init_Server_Struct( CONF_SERVER *Server )
2290 {
2291         assert( Server != NULL );
2292
2293         memset( Server, 0, sizeof (CONF_SERVER) );
2294
2295         Server->group = NONE;
2296         Server->lasttry = time( NULL ) - Conf_ConnectRetry + STARTUP_DELAY;
2297
2298         if( NGIRCd_Passive ) Server->flags = CONF_SFLAG_DISABLED;
2299
2300         Proc_InitStruct(&Server->res_stat);
2301         Server->conn_id = NONE;
2302         memset(&Server->bind_addr, 0, sizeof(Server->bind_addr));
2303 }
2304
2305 /* -eof- */