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