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