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