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