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