]> arthur.barton.de Git - ngircd.git/blob - src/ngircd/conf.c
Deduce a server name when not set in the configuration
[ngircd.git] / src / ngircd / conf.c
1 /*
2  * ngIRCd -- The Next Generation IRC Daemon
3  * Copyright (c)2001-2024 Alexander Barton (alex@barton.de) and Contributors.
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  * Please read the file COPYING, README and AUTHORS for more information.
10  */
11
12 #include "portab.h"
13
14 /**
15  * @file
16  * Configuration management (reading, parsing & validation)
17  */
18
19 #include <assert.h>
20 #include <errno.h>
21 #ifdef PROTOTYPES
22 #       include <stdarg.h>
23 #else
24 #       include <varargs.h>
25 #endif
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <strings.h>
30 #include <time.h>
31 #include <unistd.h>
32 #include <pwd.h>
33 #include <grp.h>
34 #include <sys/types.h>
35 #include <dirent.h>
36 #include <netdb.h>
37
38 #include "ngircd.h"
39 #include "conn.h"
40 #include "channel.h"
41 #include "log.h"
42 #include "match.h"
43
44 #include "conf.h"
45
46
47 static bool Use_Log = true, Using_MotdFile = true;
48 static CONF_SERVER New_Server;
49 static int New_Server_Idx;
50
51 static char Conf_MotdFile[FNAME_LEN];
52 static char Conf_HelpFile[FNAME_LEN];
53 static char Conf_IncludeDir[FNAME_LEN];
54
55 static void Set_Defaults PARAMS(( bool InitServers ));
56 static bool Read_Config PARAMS(( bool TestOnly, bool IsStarting ));
57 static void Read_Config_File PARAMS(( const char *File, FILE *fd ));
58 static bool Validate_Config PARAMS(( bool TestOnly, bool Rehash ));
59
60 static void Handle_GLOBAL PARAMS((const char *File, int Line,
61                                   char *Var, char *Arg ));
62 static void Handle_LIMITS PARAMS((const char *File, int Line,
63                                   char *Var, char *Arg ));
64 static void Handle_OPTIONS PARAMS((const char *File, int Line,
65                                    char *Var, char *Arg ));
66 static void Handle_OPERATOR PARAMS((const char *File, int Line,
67                                     char *Var, char *Arg ));
68 static void Handle_SERVER PARAMS((const char *File, int Line,
69                                   char *Var, char *Arg ));
70 static void Handle_CHANNEL PARAMS((const char *File, int Line,
71                                    char *Var, char *Arg ));
72
73 static void Config_Error PARAMS((const int Level, const char *Format, ...));
74
75 static void Config_Error_NaN PARAMS((const char *File, const int LINE,
76                                      const char *Value));
77 static void Config_Error_Section PARAMS((const char *File, const int Line,
78                                          const char *Item, const char *Section));
79 static void Config_Error_TooLong PARAMS((const char *File, const int LINE,
80                                          const char *Value));
81
82 static void Init_Server_Struct PARAMS(( CONF_SERVER *Server ));
83
84
85 #ifdef WANT_IPV6
86 #define DEFAULT_LISTEN_ADDRSTR "::,0.0.0.0"
87 #else
88 #define DEFAULT_LISTEN_ADDRSTR "0.0.0.0"
89 #endif
90
91 #ifdef HAVE_LIBSSL
92 #define DEFAULT_CIPHERS         "HIGH:!aNULL:@STRENGTH:!SSLv3"
93 #endif
94 #ifdef HAVE_LIBGNUTLS
95 #define DEFAULT_CIPHERS         "SECURE128:-VERS-SSL3.0"
96 #endif
97
98 #ifdef SSL_SUPPORT
99
100 static void Handle_SSL PARAMS((const char *File, int Line, char *Var, char *Ark));
101
102 struct SSLOptions Conf_SSLOptions;
103
104 /**
105  * Initialize SSL configuration.
106  */
107 static void
108 ConfSSL_Init(void)
109 {
110         free(Conf_SSLOptions.KeyFile);
111         Conf_SSLOptions.KeyFile = NULL;
112
113         free(Conf_SSLOptions.CertFile);
114         Conf_SSLOptions.CertFile = NULL;
115
116         free(Conf_SSLOptions.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;
907
908         Config_Error(LOG_INFO, "Using configuration file \"%s\" ...", NGIRCd_ConfFile);
909
910         /* Open configuration file */
911         fd = fopen( NGIRCd_ConfFile, "r" );
912         if( ! fd ) {
913                 /* No configuration file found! */
914                 Config_Error( LOG_ALERT, "Can't read configuration \"%s\": %s",
915                                         NGIRCd_ConfFile, strerror( errno ));
916                 if (!IsStarting)
917                         return false;
918                 Config_Error( LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE_NAME );
919                 exit( 1 );
920         }
921
922         opers_free();
923         Set_Defaults(IsStarting);
924
925         if (TestOnly)
926                 Config_Error(LOG_INFO,
927                              "Reading configuration from \"%s\" ...",
928                              NGIRCd_ConfFile );
929
930         /* Clean up server configuration structure: mark all already
931          * configured servers as "once" so that they are deleted
932          * after the next disconnect and delete all unused servers.
933          * And delete all servers which are "duplicates" of servers
934          * that are already marked as "once" (such servers have been
935          * created by the last rehash but are now useless). */
936         for( i = 0; i < MAX_SERVERS; i++ ) {
937                 if( Conf_Server[i].conn_id == NONE ) Init_Server_Struct( &Conf_Server[i] );
938                 else {
939                         /* This structure is in use ... */
940                         if( Conf_Server[i].flags & CONF_SFLAG_ONCE ) {
941                                 /* Check for duplicates */
942                                 for( n = 0; n < MAX_SERVERS; n++ ) {
943                                         if( n == i ) continue;
944
945                                         if( Conf_Server[i].conn_id == Conf_Server[n].conn_id ) {
946                                                 Init_Server_Struct( &Conf_Server[n] );
947                                                 LogDebug("Deleted unused duplicate server %d (kept %d).", n, i);
948                                         }
949                                 }
950                         } else {
951                                 /* Mark server as "once" */
952                                 Conf_Server[i].flags |= CONF_SFLAG_ONCE;
953                                 LogDebug("Marked server %d as \"once\"", i);
954                         }
955                 }
956         }
957
958         /* Initialize variables */
959         Init_Server_Struct( &New_Server );
960         New_Server_Idx = NONE;
961 #ifdef SSL_SUPPORT
962         ConfSSL_Init();
963 #endif
964
965         Read_Config_File(NGIRCd_ConfFile, fd);
966         fclose(fd);
967
968         if (Conf_IncludeDir[0]) {
969                 dh = opendir(Conf_IncludeDir);
970                 if (!dh)
971                         Config_Error(LOG_ALERT,
972                                      "Can't open include directory \"%s\": %s",
973                                      Conf_IncludeDir, strerror(errno));
974         } else {
975                 strlcpy(Conf_IncludeDir, SYSCONFDIR, sizeof(Conf_IncludeDir));
976                 strlcat(Conf_IncludeDir, CONFIG_DIR, sizeof(Conf_IncludeDir));
977                 dh = opendir(Conf_IncludeDir);
978         }
979
980         /* Include further configuration files, if IncludeDir is available */
981         if (dh) {
982                 while ((entry = readdir(dh)) != NULL) {
983                         ptr = strrchr(entry->d_name, '.');
984                         if (!ptr || strcasecmp(ptr, ".conf") != 0)
985                                 continue;
986                         snprintf(file, sizeof(file), "%s/%s",
987                                  Conf_IncludeDir, entry->d_name);
988                         if (TestOnly)
989                                 Config_Error(LOG_INFO,
990                                              "Reading configuration from \"%s\" ...",
991                                              file);
992                         fd = fopen(file, "r");
993                         if (fd) {
994                                 Read_Config_File(file, fd);
995                                 fclose(fd);
996                         } else
997                                 Config_Error(LOG_ALERT,
998                                              "Can't read configuration \"%s\": %s",
999                                              file, strerror(errno));
1000                 }
1001                 closedir(dh);
1002         }
1003
1004         /* Check if there is still a server to add */
1005         if( New_Server.name[0] ) {
1006                 /* Copy data to "real" server structure */
1007                 assert( New_Server_Idx > NONE );
1008                 Conf_Server[New_Server_Idx] = New_Server;
1009         }
1010
1011         /* not a single listening port? Add default. */
1012         if (no_listenports() &&
1013                 !array_copyb(&Conf_ListenPorts, (char*) &defaultport, sizeof defaultport))
1014         {
1015                 Config_Error(LOG_ALERT, "Could not add default listening Port %u: %s",
1016                                         (unsigned int) defaultport, strerror(errno));
1017
1018                 exit(1);
1019         }
1020
1021         if (!Conf_ListenAddress)
1022                 Conf_ListenAddress = strdup_warn(DEFAULT_LISTEN_ADDRSTR);
1023
1024         if (!Conf_ListenAddress) {
1025                 Config_Error(LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE_NAME);
1026                 exit(1);
1027         }
1028
1029         /* No MOTD phrase configured? (re)try motd file. */
1030         if (array_bytes(&Conf_Motd) == 0) {
1031                 if (Read_TextFile(Conf_MotdFile, "MOTD", &Conf_Motd))
1032                         Using_MotdFile = true;
1033         }
1034
1035         /* Try to read ngIRCd help text file. */
1036         (void)Read_TextFile(Conf_HelpFile, "help text", &Conf_Helptext);
1037         if (!array_bytes(&Conf_Helptext))
1038                 Config_Error(LOG_WARNING,
1039                     "No help text available, HELP command will be of limited use.");
1040
1041 #ifdef SSL_SUPPORT
1042         /* Make sure that all SSL-related files are readable */
1043         CheckFileReadable("CertFile", Conf_SSLOptions.CertFile);
1044         CheckFileReadable("DHFile", Conf_SSLOptions.DHFile);
1045         CheckFileReadable("KeyFile", Conf_SSLOptions.KeyFile);
1046
1047         /* Set the default ciphers if none were configured */
1048         if (!Conf_SSLOptions.CipherList)
1049                 Conf_SSLOptions.CipherList = strdup_warn(DEFAULT_CIPHERS);
1050 #endif
1051
1052         return true;
1053 }
1054
1055 /**
1056  * Read in and handle a configuration file.
1057  *
1058  * @param File Name of the configuration file.
1059  * @param fd File descriptor already opened for reading.
1060  */
1061 static void
1062 Read_Config_File(const char *File, FILE *fd)
1063 {
1064         char section[LINE_LEN], str[LINE_LEN], *var, *arg, *ptr;
1065         int i, line = 0;
1066         size_t count;
1067
1068         /* Read configuration file */
1069         section[0] = '\0';
1070         while (true) {
1071                 if (!fgets(str, sizeof(str), fd))
1072                         break;
1073                 ngt_TrimStr(str);
1074                 line++;
1075
1076                 /* Skip comments and empty lines */
1077                 if (str[0] == ';' || str[0] == '#' || str[0] == '\0')
1078                         continue;
1079
1080                 if (strlen(str) >= sizeof(str) - 1) {
1081                         Config_Error(LOG_WARNING, "%s, line %d too long!",
1082                                      File, line);
1083                         continue;
1084                 }
1085
1086                 /* Is this the beginning of a new section? */
1087                 if ((str[0] == '[') && (str[strlen(str) - 1] == ']')) {
1088                         strlcpy(section, str, sizeof(section));
1089                         if (strcasecmp(section, "[GLOBAL]") == 0
1090                             || strcasecmp(section, "[LIMITS]") == 0
1091                             || strcasecmp(section, "[OPTIONS]") == 0
1092 #ifdef SSL_SUPPORT
1093                             || strcasecmp(section, "[SSL]") == 0
1094 #endif
1095                             )
1096                                 continue;
1097
1098                         if (strcasecmp(section, "[SERVER]") == 0) {
1099                                 /* Check if there is already a server to add */
1100                                 if (New_Server.name[0]) {
1101                                         /* Copy data to "real" server structure */
1102                                         assert(New_Server_Idx > NONE);
1103                                         Conf_Server[New_Server_Idx] =
1104                                         New_Server;
1105                                 }
1106
1107                                 /* Re-init structure for new server */
1108                                 Init_Server_Struct(&New_Server);
1109
1110                                 /* Search unused item in server configuration structure */
1111                                 for (i = 0; i < MAX_SERVERS; i++) {
1112                                         /* Is this item used? */
1113                                         if (!Conf_Server[i].name[0])
1114                                                 break;
1115                                 }
1116                                 if (i >= MAX_SERVERS) {
1117                                         /* Oops, no free item found! */
1118                                         Config_Error(LOG_ERR,
1119                                                      "Too many servers configured.");
1120                                         New_Server_Idx = NONE;
1121                                 } else
1122                                         New_Server_Idx = i;
1123                                 continue;
1124                         }
1125
1126                         if (strcasecmp(section, "[CHANNEL]") == 0) {
1127                                 count = array_length(&Conf_Channels,
1128                                                      sizeof(struct
1129                                                             Conf_Channel));
1130                                 if (!array_alloc
1131                                     (&Conf_Channels,
1132                                      sizeof(struct Conf_Channel), count)) {
1133                                             Config_Error(LOG_ERR,
1134                                                          "Could not allocate memory for new operator (line %d)",
1135                                                          line);
1136                                     }
1137                                 continue;
1138                         }
1139
1140                         if (strcasecmp(section, "[OPERATOR]") == 0) {
1141                                 count = array_length(&Conf_Opers,
1142                                                      sizeof(struct Conf_Oper));
1143                                 if (!array_alloc(&Conf_Opers,
1144                                                  sizeof(struct Conf_Oper),
1145                                                  count)) {
1146                                         Config_Error(LOG_ERR,
1147                                                      "Could not allocate memory for new channel (line &d)",
1148                                                      line);
1149                                 }
1150                                 continue;
1151                         }
1152
1153                         Config_Error(LOG_ERR,
1154                                      "%s, line %d: Unknown section \"%s\"!",
1155                                      File, line, section);
1156                         section[0] = 0x1;
1157                 }
1158                 if (section[0] == 0x1)
1159                         continue;
1160
1161                 /* Split line into variable name and parameters */
1162                 ptr = strchr(str, '=');
1163                 if (!ptr) {
1164                         Config_Error(LOG_ERR, "%s, line %d: Syntax error!",
1165                                      File, line);
1166                         continue;
1167                 }
1168                 *ptr = '\0';
1169                 var = str;
1170                 ngt_TrimStr(var);
1171                 arg = ptr + 1;
1172                 ngt_TrimStr(arg);
1173
1174                 if (strcasecmp(section, "[GLOBAL]") == 0)
1175                         Handle_GLOBAL(File, line, var, arg);
1176                 else if (strcasecmp(section, "[LIMITS]") == 0)
1177                         Handle_LIMITS(File, line, var, arg);
1178                 else if (strcasecmp(section, "[OPTIONS]") == 0)
1179                         Handle_OPTIONS(File, line, var, arg);
1180 #ifdef SSL_SUPPORT
1181                 else if (strcasecmp(section, "[SSL]") == 0)
1182                         Handle_SSL(File, line, var, arg);
1183 #endif
1184                 else if (strcasecmp(section, "[OPERATOR]") == 0)
1185                         Handle_OPERATOR(File, line, var, arg);
1186                 else if (strcasecmp(section, "[SERVER]") == 0)
1187                         Handle_SERVER(File, line, var, arg);
1188                 else if (strcasecmp(section, "[CHANNEL]") == 0)
1189                         Handle_CHANNEL(File, line, var, arg);
1190                 else
1191                         Config_Error(LOG_ERR,
1192                                      "%s, line %d: Variable \"%s\" outside section!",
1193                                      File, line, var);
1194         }
1195 }
1196
1197 /**
1198  * Check whether a string argument is "true" or "false".
1199  *
1200  * @param Arg   Input string.
1201  * @returns     true if the input string has been parsed as "yes", "true"
1202  *              (case insensitive) or a non-zero integer value.
1203  */
1204 static bool
1205 Check_ArgIsTrue(const char *Arg)
1206 {
1207         if (strcasecmp(Arg, "yes") == 0)
1208                 return true;
1209         if (strcasecmp(Arg, "true") == 0)
1210                 return true;
1211         if (atoi(Arg) != 0)
1212                 return true;
1213
1214         return false;
1215 }
1216
1217 /**
1218  * Handle setting of "MaxNickLength".
1219  *
1220  * @param Line  Line number in configuration file.
1221  * @raram Arg   Input string.
1222  * @returns     New configured maximum nickname length.
1223  */
1224 static unsigned int
1225 Handle_MaxNickLength(const char *File, int Line, const char *Arg)
1226 {
1227         unsigned new;
1228
1229         new = (unsigned) atoi(Arg) + 1;
1230         if (new > CLIENT_NICK_LEN) {
1231                 Config_Error(LOG_WARNING,
1232                              "%s, line %d: Value of \"MaxNickLength\" exceeds %u!",
1233                              File, Line, CLIENT_NICK_LEN - 1);
1234                 return CLIENT_NICK_LEN;
1235         }
1236         if (new < 2) {
1237                 Config_Error(LOG_WARNING,
1238                              "%s, line %d: Value of \"MaxNickLength\" must be at least 1!",
1239                              File, Line);
1240                 return 2;
1241         }
1242         return new;
1243 }
1244
1245 /**
1246  * Output a warning messages if IDENT is configured but not compiled in.
1247  */
1248 static void
1249 WarnIdent(const char UNUSED *File, int UNUSED Line)
1250 {
1251 #ifndef IDENTAUTH
1252         if (Conf_Ident) {
1253                 /* user has enabled ident lookups explicitly, but ... */
1254                 Config_Error(LOG_WARNING,
1255                         "%s: line %d: \"Ident = yes\", but ngircd was built without IDENT support!",
1256                         File, Line);
1257         }
1258 #endif
1259 }
1260
1261 /**
1262  * Output a warning messages if IPv6 is configured but not compiled in.
1263  */
1264 static void
1265 WarnIPv6(const char UNUSED *File, int UNUSED Line)
1266 {
1267 #ifndef WANT_IPV6
1268         if (Conf_ConnectIPv6) {
1269                 /* user has enabled IPv6 explicitly, but ... */
1270                 Config_Error(LOG_WARNING,
1271                         "%s: line %d: \"ConnectIPv6 = yes\", but ngircd was built without IPv6 support!",
1272                         File, Line);
1273         }
1274 #endif
1275 }
1276
1277 /**
1278  * Output a warning messages if PAM is configured but not compiled in.
1279  */
1280 static void
1281 WarnPAM(const char UNUSED *File, int UNUSED Line)
1282 {
1283 #ifndef PAM
1284         if (Conf_PAM) {
1285                 Config_Error(LOG_WARNING,
1286                         "%s: line %d: \"PAM = yes\", but ngircd was built without PAM support!",
1287                         File, Line);
1288         }
1289 #endif
1290 }
1291
1292
1293 /**
1294  * Handle variable in [Global] configuration section.
1295  *
1296  * @param Line  Line number in configuration file.
1297  * @param Var   Variable name.
1298  * @param Arg   Variable argument.
1299  */
1300 static void
1301 Handle_GLOBAL(const char *File, int Line, char *Var, char *Arg )
1302 {
1303         struct passwd *pwd;
1304         struct group *grp;
1305         size_t len;
1306         char *ptr;
1307
1308         assert(File != NULL);
1309         assert(Line > 0);
1310         assert(Var != NULL);
1311         assert(Arg != NULL);
1312
1313         if (strcasecmp(Var, "Name") == 0) {
1314                 len = strlcpy(Conf_ServerName, Arg, sizeof(Conf_ServerName));
1315                 if (len >= sizeof(Conf_ServerName))
1316                         Config_Error_TooLong(File, Line, Var);
1317                 return;
1318         }
1319         if (strcasecmp(Var, "AdminInfo1") == 0) {
1320                 len = strlcpy(Conf_ServerAdmin1, Arg, sizeof(Conf_ServerAdmin1));
1321                 if (len >= sizeof(Conf_ServerAdmin1))
1322                         Config_Error_TooLong(File, Line, Var);
1323                 return;
1324         }
1325         if (strcasecmp(Var, "AdminInfo2") == 0) {
1326                 len = strlcpy(Conf_ServerAdmin2, Arg, sizeof(Conf_ServerAdmin2));
1327                 if (len >= sizeof(Conf_ServerAdmin2))
1328                         Config_Error_TooLong(File, Line, Var);
1329                 return;
1330         }
1331         if (strcasecmp(Var, "AdminEMail") == 0) {
1332                 len = strlcpy(Conf_ServerAdminMail, Arg,
1333                         sizeof(Conf_ServerAdminMail));
1334                 if (len >= sizeof(Conf_ServerAdminMail))
1335                         Config_Error_TooLong(File, Line, Var);
1336                 return;
1337         }
1338         if (strcasecmp(Var, "Info") == 0) {
1339                 len = strlcpy(Conf_ServerInfo, Arg, sizeof(Conf_ServerInfo));
1340                 if (len >= sizeof(Conf_ServerInfo))
1341                         Config_Error_TooLong(File, Line, Var);
1342                 return;
1343         }
1344         if (strcasecmp(Var, "HelpFile") == 0) {
1345                 len = strlcpy(Conf_HelpFile, Arg, sizeof(Conf_HelpFile));
1346                 if (len >= sizeof(Conf_HelpFile))
1347                         Config_Error_TooLong(File, Line, Var);
1348                 return;
1349         }
1350         if (strcasecmp(Var, "Listen") == 0) {
1351                 if (Conf_ListenAddress) {
1352                         Config_Error(LOG_ERR,
1353                                      "Multiple Listen= options, ignoring: %s",
1354                                      Arg);
1355                         return;
1356                 }
1357                 Conf_ListenAddress = strdup_warn(Arg);
1358                 /* If allocation fails, we're in trouble: we cannot ignore the
1359                  * error -- otherwise ngircd would listen on all interfaces. */
1360                 if (!Conf_ListenAddress) {
1361                         Config_Error(LOG_ALERT,
1362                                      "%s exiting due to fatal errors!",
1363                                      PACKAGE_NAME);
1364                         exit(1);
1365                 }
1366                 return;
1367         }
1368         if (strcasecmp(Var, "MotdFile") == 0) {
1369                 len = strlcpy(Conf_MotdFile, Arg, sizeof(Conf_MotdFile));
1370                 if (len >= sizeof(Conf_MotdFile))
1371                         Config_Error_TooLong(File, Line, Var);
1372                 return;
1373         }
1374         if (strcasecmp(Var, "MotdPhrase") == 0) {
1375                 len = strlen(Arg);
1376                 if (len == 0)
1377                         return;
1378                 if (len >= 127) {
1379                         Config_Error_TooLong(File, Line, Var);
1380                         return;
1381                 }
1382                 if (!array_copyb(&Conf_Motd, Arg, len + 1))
1383                         Config_Error(LOG_WARNING,
1384                                      "%s, line %d: Could not append MotdPhrase: %s",
1385                                      File, Line, strerror(errno));
1386                 Using_MotdFile = false;
1387                 return;
1388         }
1389         if (strcasecmp(Var, "Network") == 0) {
1390                 len = strlcpy(Conf_Network, Arg, sizeof(Conf_Network));
1391                 if (len >= sizeof(Conf_Network))
1392                         Config_Error_TooLong(File, Line, Var);
1393                 ptr = strchr(Conf_Network, ' ');
1394                 if (ptr) {
1395                         Config_Error(LOG_WARNING,
1396                                      "%s, line %d: \"Network\" can't contain spaces!",
1397                                      File, Line);
1398                         *ptr = '\0';
1399                 }
1400                 return;
1401         }
1402         if(strcasecmp(Var, "Password") == 0) {
1403                 len = strlcpy(Conf_ServerPwd, Arg, sizeof(Conf_ServerPwd));
1404                 if (len >= sizeof(Conf_ServerPwd))
1405                         Config_Error_TooLong(File, Line, Var);
1406                 return;
1407         }
1408         if (strcasecmp(Var, "PidFile") == 0) {
1409                 len = strlcpy(Conf_PidFile, Arg, sizeof(Conf_PidFile));
1410                 if (len >= sizeof(Conf_PidFile))
1411                         Config_Error_TooLong(File, Line, Var);
1412                 return;
1413         }
1414         if (strcasecmp(Var, "Ports") == 0) {
1415                 ports_parse(&Conf_ListenPorts, File, Line, Arg);
1416                 return;
1417         }
1418         if (strcasecmp(Var, "ServerGID") == 0) {
1419                 grp = getgrnam(Arg);
1420                 if (grp)
1421                         Conf_GID = grp->gr_gid;
1422                 else {
1423                         Conf_GID = (unsigned int)atoi(Arg);
1424                         if (!Conf_GID && strcmp(Arg, "0"))
1425                                 Config_Error(LOG_WARNING,
1426                                              "%s, line %d: Value of \"%s\" is not a valid group name or ID!",
1427                                              File, Line, Var);
1428                 }
1429                 return;
1430         }
1431         if (strcasecmp(Var, "ServerUID") == 0) {
1432                 pwd = getpwnam(Arg);
1433                 if (pwd)
1434                         Conf_UID = pwd->pw_uid;
1435                 else {
1436                         Conf_UID = (unsigned int)atoi(Arg);
1437                         if (!Conf_UID && strcmp(Arg, "0"))
1438                                 Config_Error(LOG_WARNING,
1439                                              "%s, line %d: Value of \"%s\" is not a valid user name or ID!",
1440                                              File, Line, Var);
1441                 }
1442                 return;
1443         }
1444
1445         Config_Error_Section(File, Line, Var, "Global");
1446 }
1447
1448 /**
1449  * Handle variable in [Limits] configuration section.
1450  *
1451  * @param Line  Line number in configuration file.
1452  * @param Var   Variable name.
1453  * @param Arg   Variable argument.
1454  */
1455 static void
1456 Handle_LIMITS(const char *File, int Line, char *Var, char *Arg)
1457 {
1458         assert(File != NULL);
1459         assert(Line > 0);
1460         assert(Var != NULL);
1461         assert(Arg != NULL);
1462
1463         if (strcasecmp(Var, "ConnectRetry") == 0) {
1464                 Conf_ConnectRetry = atoi(Arg);
1465                 if (Conf_ConnectRetry < 5) {
1466                         Config_Error(LOG_WARNING,
1467                                      "%s, line %d: Value of \"ConnectRetry\" too low!",
1468                                      File, Line);
1469                         Conf_ConnectRetry = 5;
1470                 }
1471                 return;
1472         }
1473         if (strcasecmp(Var, "IdleTimeout") == 0) {
1474                 Conf_IdleTimeout = atoi(Arg);
1475                 if (!Conf_IdleTimeout && strcmp(Arg, "0"))
1476                         Config_Error_NaN(File, Line, Var);
1477                 return;
1478         }
1479         if (strcasecmp(Var, "MaxConnections") == 0) {
1480                 Conf_MaxConnections = atoi(Arg);
1481                 if (!Conf_MaxConnections && strcmp(Arg, "0"))
1482                         Config_Error_NaN(File, Line, Var);
1483                 return;
1484         }
1485         if (strcasecmp(Var, "MaxConnectionsIP") == 0) {
1486                 Conf_MaxConnectionsIP = atoi(Arg);
1487                 if (!Conf_MaxConnectionsIP && strcmp(Arg, "0"))
1488                         Config_Error_NaN(File, Line, Var);
1489                 return;
1490         }
1491         if (strcasecmp(Var, "MaxJoins") == 0) {
1492                 Conf_MaxJoins = atoi(Arg);
1493                 if (!Conf_MaxJoins && strcmp(Arg, "0"))
1494                         Config_Error_NaN(File, Line, Var);
1495                 return;
1496         }
1497         if (strcasecmp(Var, "MaxNickLength") == 0) {
1498                 Conf_MaxNickLength = Handle_MaxNickLength(File, Line, Arg);
1499                 return;
1500         }
1501         if (strcasecmp(Var, "MaxListSize") == 0) {
1502                 Conf_MaxListSize = atoi(Arg);
1503                 if (!Conf_MaxListSize && strcmp(Arg, "0"))
1504                         Config_Error_NaN(File, Line, Var);
1505                 return;
1506         }
1507         if (strcasecmp(Var, "MaxPenaltyTime") == 0) {
1508                 Conf_MaxPenaltyTime = atol(Arg);
1509                 if (Conf_MaxPenaltyTime < -1)
1510                         Conf_MaxPenaltyTime = -1;       /* "unlimited" */
1511                 return;
1512         }
1513         if (strcasecmp(Var, "PingTimeout") == 0) {
1514                 Conf_PingTimeout = atoi(Arg);
1515                 if (Conf_PingTimeout < 5) {
1516                         Config_Error(LOG_WARNING,
1517                                      "%s, line %d: Value of \"PingTimeout\" too low!",
1518                                      File, Line);
1519                         Conf_PingTimeout = 5;
1520                 }
1521                 return;
1522         }
1523         if (strcasecmp(Var, "PongTimeout") == 0) {
1524                 Conf_PongTimeout = atoi(Arg);
1525                 if (Conf_PongTimeout < 5) {
1526                         Config_Error(LOG_WARNING,
1527                                      "%s, line %d: Value of \"PongTimeout\" too low!",
1528                                      File, Line);
1529                         Conf_PongTimeout = 5;
1530                 }
1531                 return;
1532         }
1533
1534         Config_Error_Section(File, Line, Var, "Limits");
1535 }
1536
1537 /**
1538  * Handle variable in [Options] configuration section.
1539  *
1540  * @param Line  Line number in configuration file.
1541  * @param Var   Variable name.
1542  * @param Arg   Variable argument.
1543  */
1544 static void
1545 Handle_OPTIONS(const char *File, int Line, char *Var, char *Arg)
1546 {
1547         size_t len;
1548         char *p;
1549
1550         assert(File != NULL);
1551         assert(Line > 0);
1552         assert(Var != NULL);
1553         assert(Arg != NULL);
1554
1555         if (strcasecmp(Var, "AllowedChannelTypes") == 0) {
1556                 p = Arg;
1557                 Conf_AllowedChannelTypes[0] = '\0';
1558                 while (*p) {
1559                         if (strchr(Conf_AllowedChannelTypes, *p)) {
1560                                 /* Prefix is already included; ignore it */
1561                                 p++;
1562                                 continue;
1563                         }
1564
1565                         if (strchr(CHANTYPES, *p)) {
1566                                 len = strlen(Conf_AllowedChannelTypes) + 1;
1567                                 assert(len < sizeof(Conf_AllowedChannelTypes));
1568                                 Conf_AllowedChannelTypes[len - 1] = *p;
1569                                 Conf_AllowedChannelTypes[len] = '\0';
1570                         } else {
1571                                 Config_Error(LOG_WARNING,
1572                                              "%s, line %d: Unknown channel prefix \"%c\" in \"AllowedChannelTypes\"!",
1573                                              File, Line, *p);
1574                         }
1575                         p++;
1576                 }
1577                 return;
1578         }
1579         if (strcasecmp(Var, "AllowRemoteOper") == 0) {
1580                 Conf_AllowRemoteOper = Check_ArgIsTrue(Arg);
1581                 return;
1582         }
1583         if (strcasecmp(Var, "ChrootDir") == 0) {
1584                 len = strlcpy(Conf_Chroot, Arg, sizeof(Conf_Chroot));
1585                 if (len >= sizeof(Conf_Chroot))
1586                         Config_Error_TooLong(File, Line, Var);
1587                 return;
1588         }
1589         if (strcasecmp(Var, "CloakHost") == 0) {
1590                 len = strlcpy(Conf_CloakHost, Arg, sizeof(Conf_CloakHost));
1591                 if (len >= sizeof(Conf_CloakHost))
1592                         Config_Error_TooLong(File, Line, Var);
1593                 return;
1594         }
1595         if (strcasecmp(Var, "CloakHostModeX") == 0) {
1596                 len = strlcpy(Conf_CloakHostModeX, Arg, sizeof(Conf_CloakHostModeX));
1597                 if (len >= sizeof(Conf_CloakHostModeX))
1598                         Config_Error_TooLong(File, Line, Var);
1599                 return;
1600         }
1601         if (strcasecmp(Var, "CloakHostSalt") == 0) {
1602                 len = strlcpy(Conf_CloakHostSalt, Arg, sizeof(Conf_CloakHostSalt));
1603                 if (len >= sizeof(Conf_CloakHostSalt))
1604                         Config_Error_TooLong(File, Line, Var);
1605                 return;
1606         }
1607         if (strcasecmp(Var, "CloakUserToNick") == 0) {
1608                 Conf_CloakUserToNick = Check_ArgIsTrue(Arg);
1609                 return;
1610         }
1611         if (strcasecmp(Var, "ConnectIPv6") == 0) {
1612                 Conf_ConnectIPv6 = Check_ArgIsTrue(Arg);
1613                 WarnIPv6(File, Line);
1614                 return;
1615         }
1616         if (strcasecmp(Var, "ConnectIPv4") == 0) {
1617                 Conf_ConnectIPv4 = Check_ArgIsTrue(Arg);
1618                 return;
1619         }
1620         if (strcasecmp(Var, "DefaultUserModes") == 0) {
1621                 p = Arg;
1622                 Conf_DefaultUserModes[0] = '\0';
1623                 while (*p) {
1624                         if (strchr(Conf_DefaultUserModes, *p)) {
1625                                 /* Mode is already included; ignore it */
1626                                 p++;
1627                                 continue;
1628                         }
1629
1630                         if (strchr(USERMODES, *p)) {
1631                                 len = strlen(Conf_DefaultUserModes) + 1;
1632                                 assert(len < sizeof(Conf_DefaultUserModes));
1633                                 Conf_DefaultUserModes[len - 1] = *p;
1634                                 Conf_DefaultUserModes[len] = '\0';
1635                         } else {
1636                                 Config_Error(LOG_WARNING,
1637                                              "%s, line %d: Unknown user mode \"%c\" in \"DefaultUserModes\"!",
1638                                              File, Line, *p);
1639                         }
1640                         p++;
1641                 }
1642                 return;
1643         }
1644         if (strcasecmp(Var, "DNS") == 0) {
1645                 Conf_DNS = Check_ArgIsTrue(Arg);
1646                 return;
1647         }
1648         if (strcasecmp(Var, "Ident") == 0) {
1649                 Conf_Ident = Check_ArgIsTrue(Arg);
1650                 WarnIdent(File, Line);
1651                 return;
1652         }
1653         if (strcasecmp(Var, "IncludeDir") == 0) {
1654                 if (Conf_IncludeDir[0]) {
1655                         Config_Error(LOG_ERR,
1656                                      "%s, line %d: Can't overwrite value of \"IncludeDir\" variable!",
1657                                      File, Line);
1658                         return;
1659                 }
1660                 len = strlcpy(Conf_IncludeDir, Arg, sizeof(Conf_IncludeDir));
1661                 if (len >= sizeof(Conf_IncludeDir))
1662                         Config_Error_TooLong(File, Line, Var);
1663                 return;
1664         }
1665         if (strcasecmp(Var, "MorePrivacy") == 0) {
1666                 Conf_MorePrivacy = Check_ArgIsTrue(Arg);
1667                 return;
1668         }
1669         if (strcasecmp(Var, "NoticeBeforeRegistration") == 0) {
1670                 Conf_NoticeBeforeRegistration = Check_ArgIsTrue(Arg);
1671                 return;
1672         }
1673         if (strcasecmp(Var, "OperCanUseMode") == 0) {
1674                 Conf_OperCanMode = Check_ArgIsTrue(Arg);
1675                 return;
1676         }
1677         if (strcasecmp(Var, "OperChanPAutoOp") == 0) {
1678                 Conf_OperChanPAutoOp = Check_ArgIsTrue(Arg);
1679                 return;
1680         }
1681         if (strcasecmp(Var, "OperServerMode") == 0) {
1682                 Conf_OperServerMode = Check_ArgIsTrue(Arg);
1683                 return;
1684         }
1685         if (strcasecmp(Var, "PAM") == 0) {
1686                 Conf_PAM = Check_ArgIsTrue(Arg);
1687                 WarnPAM(File, Line);
1688                 return;
1689         }
1690         if (strcasecmp(Var, "PAMIsOptional") == 0 ) {
1691                 Conf_PAMIsOptional = Check_ArgIsTrue(Arg);
1692                 return;
1693         }
1694         if (strcasecmp(Var, "PAMServiceName") == 0) {
1695                 len = strlcpy(Conf_PAMServiceName, Arg, sizeof(Conf_PAMServiceName));
1696                 if (len >= sizeof(Conf_PAMServiceName))
1697                         Config_Error_TooLong(File, Line, Var);
1698                 return;
1699         }
1700 #ifndef STRICT_RFC
1701         if (strcasecmp(Var, "RequireAuthPing") == 0) {
1702                 Conf_AuthPing = Check_ArgIsTrue(Arg);
1703                 return;
1704         }
1705 #endif
1706         if (strcasecmp(Var, "ScrubCTCP") == 0) {
1707                 Conf_ScrubCTCP = Check_ArgIsTrue(Arg);
1708                 return;
1709         }
1710 #ifdef SYSLOG
1711         if (strcasecmp(Var, "SyslogFacility") == 0) {
1712                 Conf_SyslogFacility = ngt_SyslogFacilityID(Arg,
1713                                                            Conf_SyslogFacility);
1714                 return;
1715         }
1716 #endif
1717         if (strcasecmp(Var, "WebircPassword") == 0) {
1718                 len = strlcpy(Conf_WebircPwd, Arg, sizeof(Conf_WebircPwd));
1719                 if (len >= sizeof(Conf_WebircPwd))
1720                         Config_Error_TooLong(File, Line, Var);
1721                 return;
1722         }
1723
1724         Config_Error_Section(File, Line, Var, "Options");
1725 }
1726
1727 #ifdef SSL_SUPPORT
1728
1729 /**
1730  * Handle variable in [SSL] configuration section.
1731  *
1732  * @param Line  Line number in configuration file.
1733  * @param Var   Variable name.
1734  * @param Arg   Variable argument.
1735  */
1736 static void
1737 Handle_SSL(const char *File, int Line, char *Var, char *Arg)
1738 {
1739         assert(File != NULL);
1740         assert(Line > 0);
1741         assert(Var != NULL);
1742         assert(Arg != NULL);
1743
1744         if (strcasecmp(Var, "CertFile") == 0) {
1745                 assert(Conf_SSLOptions.CertFile == NULL);
1746                 Conf_SSLOptions.CertFile = strdup_warn(Arg);
1747                 return;
1748         }
1749         if (strcasecmp(Var, "DHFile") == 0) {
1750                 assert(Conf_SSLOptions.DHFile == NULL);
1751                 Conf_SSLOptions.DHFile = strdup_warn(Arg);
1752                 return;
1753         }
1754         if (strcasecmp(Var, "KeyFile") == 0) {
1755                 assert(Conf_SSLOptions.KeyFile == NULL);
1756                 Conf_SSLOptions.KeyFile = strdup_warn(Arg);
1757                 return;
1758         }
1759         if (strcasecmp(Var, "KeyFilePassword") == 0) {
1760                 assert(array_bytes(&Conf_SSLOptions.KeyFilePassword) == 0);
1761                 if (!array_copys(&Conf_SSLOptions.KeyFilePassword, Arg))
1762                         Config_Error(LOG_ERR,
1763                                      "%s, line %d (section \"SSL\"): Could not copy %s: %s!",
1764                                      File, Line, Var, strerror(errno));
1765                 return;
1766         }
1767         if (strcasecmp(Var, "Ports") == 0) {
1768                 ports_parse(&Conf_SSLOptions.ListenPorts, File, Line, Arg);
1769                 return;
1770         }
1771         if (strcasecmp(Var, "CipherList") == 0) {
1772                 assert(Conf_SSLOptions.CipherList == NULL);
1773                 Conf_SSLOptions.CipherList = strdup_warn(Arg);
1774                 return;
1775         }
1776
1777         Config_Error_Section(File, Line, Var, "SSL");
1778 }
1779
1780 #endif
1781
1782 /**
1783  * Handle variable in [Operator] configuration section.
1784  *
1785  * @param Line  Line number in configuration file.
1786  * @param Var   Variable name.
1787  * @param Arg   Variable argument.
1788  */
1789 static void
1790 Handle_OPERATOR(const char *File, int Line, char *Var, char *Arg )
1791 {
1792         size_t len;
1793         struct Conf_Oper *op;
1794
1795         assert( File != NULL );
1796         assert( Line > 0 );
1797         assert( Var != NULL );
1798         assert( Arg != NULL );
1799
1800         op = array_get(&Conf_Opers, sizeof(*op),
1801                          array_length(&Conf_Opers, sizeof(*op)) - 1);
1802         if (!op)
1803                 return;
1804
1805         if (strcasecmp(Var, "Name") == 0) {
1806                 /* Name of IRC operator */
1807                 len = strlcpy(op->name, Arg, sizeof(op->name));
1808                 if (len >= sizeof(op->name))
1809                                 Config_Error_TooLong(File, Line, Var);
1810                 return;
1811         }
1812         if (strcasecmp(Var, "Password") == 0) {
1813                 /* Password of IRC operator */
1814                 len = strlcpy(op->pwd, Arg, sizeof(op->pwd));
1815                 if (len >= sizeof(op->pwd))
1816                                 Config_Error_TooLong(File, Line, Var);
1817                 return;
1818         }
1819         if (strcasecmp(Var, "Mask") == 0) {
1820                 if (op->mask)
1821                         return; /* Hostname already configured */
1822                 op->mask = strdup_warn( Arg );
1823                 return;
1824         }
1825
1826         Config_Error_Section(File, Line, Var, "Operator");
1827 }
1828
1829 /**
1830  * Handle variable in [Server] configuration section.
1831  *
1832  * @param Line  Line number in configuration file.
1833  * @param Var   Variable name.
1834  * @param Arg   Variable argument.
1835  */
1836 static void
1837 Handle_SERVER(const char *File, int Line, char *Var, char *Arg )
1838 {
1839         long port;
1840         size_t len;
1841
1842         assert( File != NULL );
1843         assert( Line > 0 );
1844         assert( Var != NULL );
1845         assert( Arg != NULL );
1846
1847         /* Ignore server block if no space is left in server configuration structure */
1848         if( New_Server_Idx <= NONE ) return;
1849
1850         if( strcasecmp( Var, "Host" ) == 0 ) {
1851                 /* Hostname of the server */
1852                 len = strlcpy( New_Server.host, Arg, sizeof( New_Server.host ));
1853                 if (len >= sizeof( New_Server.host ))
1854                         Config_Error_TooLong(File, Line, Var);
1855                 return;
1856         }
1857         if( strcasecmp( Var, "Name" ) == 0 ) {
1858                 /* Name of the server ("Nick"/"ID") */
1859                 len = strlcpy( New_Server.name, Arg, sizeof( New_Server.name ));
1860                 if (len >= sizeof( New_Server.name ))
1861                         Config_Error_TooLong(File, Line, Var);
1862                 return;
1863         }
1864         if (strcasecmp(Var, "Bind") == 0) {
1865                 if (ng_ipaddr_init(&New_Server.bind_addr, Arg, 0))
1866                         return;
1867
1868                 Config_Error(LOG_ERR, "%s, line %d (section \"Server\"): Can't parse IP address \"%s\"",
1869                              File, Line, Arg);
1870                 return;
1871         }
1872         if( strcasecmp( Var, "MyPassword" ) == 0 ) {
1873                 /* Password of this server which is sent to the peer */
1874                 if (*Arg == ':') {
1875                         Config_Error(LOG_ERR,
1876                                      "%s, line %d (section \"Server\"): MyPassword must not start with ':'!",
1877                                      File, Line);
1878                 }
1879                 len = strlcpy( New_Server.pwd_in, Arg, sizeof( New_Server.pwd_in ));
1880                 if (len >= sizeof( New_Server.pwd_in ))
1881                         Config_Error_TooLong(File, Line, Var);
1882                 return;
1883         }
1884         if( strcasecmp( Var, "PeerPassword" ) == 0 ) {
1885                 /* Passwort of the peer which must be received */
1886                 len = strlcpy( New_Server.pwd_out, Arg, sizeof( New_Server.pwd_out ));
1887                 if (len >= sizeof( New_Server.pwd_out ))
1888                         Config_Error_TooLong(File, Line, Var);
1889                 return;
1890         }
1891         if( strcasecmp( Var, "Port" ) == 0 ) {
1892                 /* Port to which this server should connect */
1893                 port = atol( Arg );
1894                 if (port >= 0 && port < 0xFFFF)
1895                         New_Server.port = (UINT16)port;
1896                 else
1897                         Config_Error(LOG_ERR,
1898                                      "%s, line %d (section \"Server\"): Illegal port number %ld!",
1899                                      File, Line, port );
1900                 return;
1901         }
1902 #ifdef SSL_SUPPORT
1903         if( strcasecmp( Var, "SSLConnect" ) == 0 ) {
1904                 New_Server.SSLConnect = Check_ArgIsTrue(Arg);
1905                 return;
1906         }
1907 #endif
1908         if( strcasecmp( Var, "Group" ) == 0 ) {
1909                 /* Server group */
1910                 New_Server.group = atoi( Arg );
1911                 if (!New_Server.group && strcmp(Arg, "0"))
1912                         Config_Error_NaN(File, Line, Var);
1913                 return;
1914         }
1915         if( strcasecmp( Var, "Passive" ) == 0 ) {
1916                 if (Check_ArgIsTrue(Arg))
1917                         New_Server.flags |= CONF_SFLAG_DISABLED;
1918                 return;
1919         }
1920         if (strcasecmp(Var, "ServiceMask") == 0) {
1921                 len = strlcpy(New_Server.svs_mask, ngt_LowerStr(Arg),
1922                               sizeof(New_Server.svs_mask));
1923                 if (len >= sizeof(New_Server.svs_mask))
1924                         Config_Error_TooLong(File, Line, Var);
1925                 return;
1926         }
1927
1928         Config_Error_Section(File, Line, Var, "Server");
1929 }
1930
1931 /**
1932  * Copy channel name into channel structure.
1933  *
1934  * If the channel name is not valid because of a missing prefix ('#', '&'),
1935  * a default prefix of '#' will be added.
1936  *
1937  * @param new_chan      New already allocated channel structure.
1938  * @param name          Name of the new channel.
1939  * @returns             true on success, false otherwise.
1940  */
1941 static bool
1942 Handle_Channelname(struct Conf_Channel *new_chan, const char *name)
1943 {
1944         size_t size = sizeof(new_chan->name);
1945         char *dest = new_chan->name;
1946
1947         if (!Channel_IsValidName(name)) {
1948                 /*
1949                  * maybe user forgot to add a '#'.
1950                  * This is only here for user convenience.
1951                  */
1952                 *dest = '#';
1953                 --size;
1954                 ++dest;
1955         }
1956         return size > strlcpy(dest, name, size);
1957 }
1958
1959 /**
1960  * Handle variable in [Channel] configuration section.
1961  *
1962  * @param Line  Line number in configuration file.
1963  * @param Var   Variable name.
1964  * @param Arg   Variable argument.
1965  */
1966 static void
1967 Handle_CHANNEL(const char *File, int Line, char *Var, char *Arg)
1968 {
1969         size_t len;
1970         struct Conf_Channel *chan;
1971
1972         assert( File != NULL );
1973         assert( Line > 0 );
1974         assert( Var != NULL );
1975         assert( Arg != NULL );
1976
1977         chan = array_get(&Conf_Channels, sizeof(*chan),
1978                          array_length(&Conf_Channels, sizeof(*chan)) - 1);
1979         if (!chan)
1980                 return;
1981
1982         if (strcasecmp(Var, "Name") == 0) {
1983                 if (!Handle_Channelname(chan, Arg))
1984                         Config_Error_TooLong(File, Line, Var);
1985                 return;
1986         }
1987         if (strcasecmp(Var, "Modes") == 0) {
1988                 /* Initial modes */
1989                 if(chan->modes_num >= sizeof(chan->modes)) {
1990                         Config_Error(LOG_ERR, "Too many Modes, option ignored.");
1991                         return;
1992                 }
1993                 chan->modes[chan->modes_num++] = strndup(Arg, COMMAND_LEN);
1994                 if(strlen(Arg) >= COMMAND_LEN)
1995                         Config_Error_TooLong(File, Line, Var);
1996                 return;
1997         }
1998         if( strcasecmp( Var, "Topic" ) == 0 ) {
1999                 /* Initial topic */
2000                 len = strlcpy(chan->topic, Arg, sizeof(chan->topic));
2001                 if (len >= sizeof(chan->topic))
2002                         Config_Error_TooLong(File, Line, Var);
2003                 return;
2004         }
2005         if( strcasecmp( Var, "Autojoin" ) == 0 ) {
2006                 /* Check autojoin */
2007                 chan->autojoin = Check_ArgIsTrue(Arg);
2008                 return;
2009         }
2010         if( strcasecmp( Var, "Key" ) == 0 ) {
2011                 /* Initial Channel Key (mode k) */
2012                 len = strlcpy(chan->key, Arg, sizeof(chan->key));
2013                 if (len >= sizeof(chan->key))
2014                         Config_Error_TooLong(File, Line, Var);
2015                 Config_Error(LOG_WARNING,
2016                              "%s, line %d (section \"Channel\"): \"%s\" is deprecated here, use \"Modes = +k <key>\"!",
2017                              File, Line, Var);
2018                 return;
2019         }
2020         if( strcasecmp( Var, "MaxUsers" ) == 0 ) {
2021                 /* maximum user limit, mode l */
2022                 chan->maxusers = (unsigned long) atol(Arg);
2023                 if (!chan->maxusers && strcmp(Arg, "0"))
2024                         Config_Error_NaN(File, Line, Var);
2025                 Config_Error(LOG_WARNING,
2026                              "%s, line %d (section \"Channel\"): \"%s\" is deprecated here, use \"Modes = +l <limit>\"!",
2027                              File, Line, Var);
2028                 return;
2029         }
2030         if (strcasecmp(Var, "KeyFile") == 0) {
2031                 /* channel keys */
2032                 len = strlcpy(chan->keyfile, Arg, sizeof(chan->keyfile));
2033                 if (len >= sizeof(chan->keyfile))
2034                         Config_Error_TooLong(File, Line, Var);
2035                 return;
2036         }
2037
2038         Config_Error_Section(File, Line, Var, "Channel");
2039 }
2040
2041 /**
2042  * Validate server configuration.
2043  *
2044  * Please note that this function uses exit(1) on fatal errors and therefore
2045  * can result in ngIRCd terminating!
2046  *
2047  * @param Configtest    true if the daemon has been called with "--configtest".
2048  * @param Rehash        true if re-reading configuration on runtime.
2049  * @returns             true if configuration is valid.
2050  */
2051 static bool
2052 Validate_Config(bool Configtest, bool Rehash)
2053 {
2054         /* Validate configuration settings. */
2055
2056         int i, servers, servers_once;
2057         struct hostent *h;
2058         bool config_valid = true;
2059         char *ptr;
2060
2061         /* Emit a warning when the config file is not a full path name */
2062         if (NGIRCd_ConfFile[0] && NGIRCd_ConfFile[0] != '/') {
2063                 Config_Error(LOG_WARNING,
2064                         "Not specifying a full path name to \"%s\" can cause problems when rehashing the server!",
2065                         NGIRCd_ConfFile);
2066         }
2067
2068         if (!Conf_ServerName[0]) {
2069                 /* No server name configured, try to get a sane name from the
2070                  * host name. Note: the IRC server name MUST contain
2071                  * at least one dot, so the "node name" is not sufficient! */
2072                 gethostname(Conf_ServerName, sizeof(Conf_ServerName));
2073                 if (Conf_DNS) {
2074                         /* Try to get a proper host name ... */
2075                         h = gethostbyname(Conf_ServerName);
2076                         if (h)
2077                                 strlcpy(Conf_ServerName, h->h_name,
2078                                         sizeof(Conf_ServerName));
2079                 }
2080                 if (!strchr(Conf_ServerName, '.')) {
2081                         /* (Still) No dot in the name! */
2082                         strlcat(Conf_ServerName, ".host",
2083                                 sizeof(Conf_ServerName));
2084                 }
2085                 Config_Error(LOG_WARNING,
2086                              "No server name configured, using host name \"%s\".",
2087                              Conf_ServerName);
2088         }
2089
2090         /* Validate configured server name, see RFC 2812 section 2.3.1 */
2091         ptr = Conf_ServerName;
2092         do {
2093                 if (*ptr >= 'a' && *ptr <= 'z') continue;
2094                 if (*ptr >= 'A' && *ptr <= 'Z') continue;
2095                 if (*ptr >= '0' && *ptr <= '9') continue;
2096                 if (ptr > Conf_ServerName) {
2097                         if (*ptr == '.' || *ptr == '-')
2098                                 continue;
2099                 }
2100                 Conf_ServerName[0] = '\0';
2101                 break;
2102         } while (*(++ptr));
2103
2104         if (!Conf_ServerName[0] || !strchr(Conf_ServerName, '.')) {
2105                 config_valid = false;
2106                 Config_Error(LOG_ALERT,
2107                              "No (valid) server name configured in \"%s\" (section 'Global': 'Name')!",
2108                              NGIRCd_ConfFile);
2109                 if (!Configtest && !Rehash) {
2110                         Config_Error(LOG_ALERT,
2111                                      "%s exiting due to fatal errors!",
2112                                      PACKAGE_NAME);
2113                         exit(1);
2114                 }
2115         }
2116
2117 #ifdef STRICT_RFC
2118         if (!Conf_ServerAdminMail[0]) {
2119                 /* No administrative contact configured! */
2120                 config_valid = false;
2121                 Config_Error(LOG_ALERT,
2122                              "No administrator email address configured in \"%s\" ('AdminEMail')!",
2123                              NGIRCd_ConfFile);
2124                 if (!Configtest) {
2125                         Config_Error(LOG_ALERT,
2126                                      "%s exiting due to fatal errors!",
2127                                      PACKAGE_NAME);
2128                         exit(1);
2129                 }
2130         }
2131 #endif
2132
2133         if (!Conf_ServerAdmin1[0] && !Conf_ServerAdmin2[0]
2134             && !Conf_ServerAdminMail[0]) {
2135                 /* No administrative information configured! */
2136                 Config_Error(LOG_WARNING,
2137                              "No administrative information configured but required by RFC!");
2138         }
2139
2140 #ifdef PAM
2141         if (Conf_PAM && Conf_ServerPwd[0])
2142                 Config_Error(LOG_ERR,
2143                              "This server uses PAM, \"Password\" in [Global] section will be ignored!");
2144 #endif
2145
2146         if (Conf_MaxPenaltyTime != -1)
2147                 Config_Error(LOG_WARNING,
2148                              "Maximum penalty increase ('MaxPenaltyTime') is set to %ld, this is not recommended!",
2149                              Conf_MaxPenaltyTime);
2150
2151         servers = servers_once = 0;
2152         for (i = 0; i < MAX_SERVERS; i++) {
2153                 if (Conf_Server[i].name[0]) {
2154                         servers++;
2155                         if (Conf_Server[i].flags & CONF_SFLAG_ONCE)
2156                                 servers_once++;
2157                 }
2158         }
2159         LogDebug("Configuration: Operators=%ld, Servers=%d[%d], Channels=%ld",
2160             array_length(&Conf_Opers, sizeof(struct Conf_Oper)),
2161             servers, servers_once,
2162             array_length(&Conf_Channels, sizeof(struct Conf_Channel)));
2163
2164         return config_valid;
2165 }
2166
2167 /**
2168  * Output "line too long" warning.
2169  *
2170  * @param Line  Line number in configuration file.
2171  * @param Item  Affected variable name.
2172  */
2173 static void
2174 Config_Error_TooLong(const char *File, const int Line, const char *Item)
2175 {
2176         Config_Error(LOG_WARNING, "%s, line %d: Value of \"%s\" too long!",
2177                      File, Line, Item );
2178 }
2179
2180 /**
2181  * Output "unknown variable" warning.
2182  *
2183  * @param Line          Line number in configuration file.
2184  * @param Item          Affected variable name.
2185  * @param Section       Section name.
2186  */
2187 static void
2188 Config_Error_Section(const char *File, const int Line, const char *Item,
2189                      const char *Section)
2190 {
2191         Config_Error(LOG_ERR, "%s, line %d (section \"%s\"): Unknown variable \"%s\"!",
2192                      File, Line, Section, Item);
2193 }
2194
2195 /**
2196  * Output "not a number" warning.
2197  *
2198  * @param Line  Line number in configuration file.
2199  * @param Item  Affected variable name.
2200  */
2201 static void
2202 Config_Error_NaN(const char *File, const int Line, const char *Item )
2203 {
2204         Config_Error(LOG_WARNING, "%s, line %d: Value of \"%s\" is not a number!",
2205                      File, Line, Item );
2206 }
2207
2208 /**
2209  * Output configuration error to console and/or logfile.
2210  *
2211  * On runtime, the normal log functions of the daemon are used. But when
2212  * testing the configuration ("--configtest"), all messages go directly
2213  * to the console.
2214  *
2215  * @param Level         Severity level of the message.
2216  * @param Format        Format string; see printf() function.
2217  */
2218 #ifdef PROTOTYPES
2219 static void Config_Error( const int Level, const char *Format, ... )
2220 #else
2221 static void Config_Error( Level, Format, va_alist )
2222 const int Level;
2223 const char *Format;
2224 va_dcl
2225 #endif
2226 {
2227         char msg[MAX_LOG_MSG_LEN];
2228         va_list ap;
2229
2230         assert( Format != NULL );
2231
2232 #ifdef PROTOTYPES
2233         va_start( ap, Format );
2234 #else
2235         va_start( ap );
2236 #endif
2237         vsnprintf( msg, MAX_LOG_MSG_LEN, Format, ap );
2238         va_end( ap );
2239
2240         if (!Use_Log) {
2241                 if (Level <= LOG_WARNING)
2242                         printf(" - %s\n", msg);
2243                 else
2244                         puts(msg);
2245         } else
2246                 Log(Level, "%s", msg);
2247 }
2248
2249
2250 /**
2251  * Dump internal state of the "configuration module".
2252  */
2253 GLOBAL void
2254 Conf_DebugDump(void)
2255 {
2256         int i;
2257
2258         LogDebug("Configured servers:");
2259         for (i = 0; i < MAX_SERVERS; i++) {
2260                 if (! Conf_Server[i].name[0])
2261                         continue;
2262                 LogDebug(
2263                     " - %s: %s:%d, last=%ld, group=%d, flags=%d, conn=%d",
2264                     Conf_Server[i].name, Conf_Server[i].host,
2265                     Conf_Server[i].port, Conf_Server[i].lasttry,
2266                     Conf_Server[i].group, Conf_Server[i].flags,
2267                     Conf_Server[i].conn_id);
2268         }
2269 }
2270
2271
2272 /**
2273  * Initialize server configuration structure to default values.
2274  *
2275  * @param Server        Pointer to server structure to initialize.
2276  */
2277 static void
2278 Init_Server_Struct( CONF_SERVER *Server )
2279 {
2280         assert( Server != NULL );
2281
2282         memset( Server, 0, sizeof (CONF_SERVER) );
2283
2284         Server->group = NONE;
2285         Server->lasttry = time( NULL ) - Conf_ConnectRetry + STARTUP_DELAY;
2286
2287         if( NGIRCd_Passive ) Server->flags = CONF_SFLAG_DISABLED;
2288
2289         Proc_InitStruct(&Server->res_stat);
2290         Server->conn_id = NONE;
2291         memset(&Server->bind_addr, 0, sizeof(Server->bind_addr));
2292 }
2293
2294 /* -eof- */