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