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