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