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