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