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