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