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