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