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