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