]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - include/configreader.h
Pedantic safe
[user/henk/code/inspircd.git] / include / configreader.h
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2007 InspIRCd Development Team
6  * See: http://www.inspircd.org/wiki/index.php/Credits
7  *
8  * This program is free but copyrighted software; see
9  *            the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 #ifndef INSPIRCD_CONFIGREADER
15 #define INSPIRCD_CONFIGREADER
16
17 /* handy defines */
18
19 /** Determines if a channel op is exempt from given mode m,
20  * in config of server instance s. 
21  */
22 #define CHANOPS_EXEMPT(s, m) (s->Config->ExemptChanOps[(unsigned char)m])
23
24 #include <sstream>
25 #include <string>
26 #include <vector>
27 #include <map>
28 #include "inspircd.h"
29 #include "globals.h"
30 #include "modules.h"
31 #include "socketengine.h"
32 #include "socket.h"
33
34 /* Required forward definitions */
35 class ServerConfig;
36 class InspIRCd;
37 class BufferedSocket;
38
39 /** Types of data in the core config
40  */
41 enum ConfigDataType
42 {
43         DT_NOTHING       = 0,           /* No data */
44         DT_INTEGER       = 1,           /* Integer */
45         DT_CHARPTR       = 2,           /* Char pointer */
46         DT_BOOLEAN       = 3,           /* Boolean */
47         DT_ALLOW_NEWLINE = 128          /* New line characters allowed */
48 };
49
50 /** Holds a config value, either string, integer or boolean.
51  * Callback functions receive one or more of these, either on
52  * their own as a reference, or in a reference to a deque of them.
53  * The callback function can then alter the values of the ValueItem
54  * classes to validate the settings.
55  */
56 class ValueItem
57 {
58         /** Actual data */
59         std::string v;
60  public:
61         /** Initialize with an int */
62         ValueItem(int value);
63         /** Initialize with a bool */
64         ValueItem(bool value);
65         /** Initialize with a char pointer */
66         ValueItem(char* value);
67         /** Change value to a char pointer */
68         void Set(char* value);
69         /** Change value to a const char pointer */
70         void Set(const char* val);
71         /** Change value to an int */
72         void Set(int value);
73         /** Get value as an int */
74         int GetInteger();
75         /** Get value as a string */
76         char* GetString();
77         /** Get value as a bool */
78         bool GetBool();
79 };
80
81 /** The base class of the container 'ValueContainer'
82  * used internally by the core to hold core values.
83  */
84 class ValueContainerBase
85 {
86  public:
87         /** Constructor */
88         ValueContainerBase() { }
89         /** Destructor */
90         virtual ~ValueContainerBase() { }
91 };
92
93 /** ValueContainer is used to contain pointers to different
94  * core values such as the server name, maximum number of
95  * clients etc.
96  * It is specialized to hold a data type, then pointed at
97  * a value in the ServerConfig class. When the value has been
98  * read and validated, the Set method is called to write the
99  * value safely in a type-safe manner.
100  */
101 template<typename T> class ValueContainer : public ValueContainerBase
102 {
103         /** Contained item */
104         T val;
105  public:
106
107         /** Initialize with nothing */
108         ValueContainer()
109         {
110                 val = NULL;
111         }
112
113         /** Initialize with a value of type T */
114         ValueContainer(T Val)
115         {
116                 val = Val;
117         }
118
119         /** Change value to type T of size s */
120         void Set(T newval, size_t s)
121         {
122                 memcpy(val, newval, s);
123         }
124 };
125
126 /** A specialization of ValueContainer to hold a pointer to a bool
127  */
128 typedef ValueContainer<bool*> ValueContainerBool;
129
130 /** A specialization of ValueContainer to hold a pointer to
131  * an unsigned int
132  */
133 typedef ValueContainer<unsigned int*> ValueContainerUInt;
134
135 /** A specialization of ValueContainer to hold a pointer to
136  * a char array.
137  */
138 typedef ValueContainer<char*> ValueContainerChar;
139
140 /** A specialization of ValueContainer to hold a pointer to
141  * an int
142  */
143 typedef ValueContainer<int*> ValueContainerInt;
144
145 /** A set of ValueItems used by multi-value validator functions
146  */
147 typedef std::deque<ValueItem> ValueList;
148
149 /** A callback for validating a single value
150  */
151 typedef bool (*Validator)(ServerConfig* conf, const char*, const char*, ValueItem&);
152 /** A callback for validating multiple value entries
153  */
154 typedef bool (*MultiValidator)(ServerConfig* conf, const char*, char**, ValueList&, int*);
155 /** A callback indicating the end of a group of entries
156  */
157 typedef bool (*MultiNotify)(ServerConfig* conf, const char*);
158
159 /** Holds a core configuration item and its callbacks
160  */
161 struct InitialConfig
162 {
163         /** Tag name */
164         char* tag;
165         /** Value name */
166         char* value;
167         /** Default, if not defined */
168         char* default_value;
169         /** Value containers */
170         ValueContainerBase* val;
171         /** Data types */
172         ConfigDataType datatype;
173         /** Validation function */
174         Validator validation_function;
175 };
176
177 /** Holds a core configuration item and its callbacks
178  * where there may be more than one item
179  */
180 struct MultiConfig
181 {
182         /** Tag name */
183         const char*     tag;
184         /** One or more items within tag */
185         char*           items[17];
186         /** One or more defaults for items within tags */
187         char*           items_default[17];
188         /** One or more data types */
189         int             datatype[17];
190         /** Initialization function */
191         MultiNotify     init_function;
192         /** Validation function */
193         MultiValidator  validation_function;
194         /** Completion function */
195         MultiNotify     finish_function;
196 };
197
198 /** A set of oper types
199  */
200 typedef std::map<irc::string,char*> opertype_t;
201
202 /** A Set of oper classes
203  */
204 typedef std::map<irc::string,char*> operclass_t;
205
206
207 /** This class holds the bulk of the runtime configuration for the ircd.
208  * It allows for reading new config values, accessing configuration files,
209  * and storage of the configuration data needed to run the ircd, such as
210  * the servername, connect classes, /ADMIN data, MOTDs and filenames etc.
211  */
212 class CoreExport ServerConfig : public Extensible
213 {
214   private:
215         /** Creator/owner pointer
216          */
217         InspIRCd* ServerInstance;
218
219         /** This variable holds the names of all
220          * files included from the main one. This
221          * is used to make sure that no files are
222          * recursively included.
223          */
224         std::vector<std::string> include_stack;
225
226         /** This private method processes one line of
227          * configutation, appending errors to errorstream
228          * and setting error if an error has occured.
229          */
230         bool ParseLine(ConfigDataHash &target, std::string &line, long &linenumber, std::ostringstream &errorstream);
231   
232         /** Process an include directive
233          */
234         bool DoInclude(ConfigDataHash &target, const std::string &file, std::ostringstream &errorstream);
235
236         /** Check that there is only one of each configuration item
237          */
238         bool CheckOnce(char* tag) throw (CoreException);
239   
240   public:
241
242         /** Used to indicate who we announce invites to on a channel */
243         enum InviteAnnounceState { INVITE_ANNOUNCE_NONE, INVITE_ANNOUNCE_ALL, INVITE_ANNOUNCE_OPS, INVITE_ANNOUNCE_DYNAMIC };
244
245         /** Pointer to function that validates dns server addresses (can be changed depending on platform) */
246         Validator DNSServerValidator;
247
248         InspIRCd* GetInstance();
249           
250         /** This holds all the information in the config file,
251          * it's indexed by tag name to a vector of key/values.
252          */
253         ConfigDataHash config_data;
254
255         /** Max number of WhoWas entries per user.
256          */
257         int WhoWasGroupSize;
258
259         /** Max number of cumulative user-entries in WhoWas.
260          *  When max reached and added to, push out oldest entry FIFO style.
261          */
262         int WhoWasMaxGroups;
263
264         /** Max seconds a user is kept in WhoWas before being pruned.
265          */
266         int WhoWasMaxKeep;
267
268         /** Holds the server name of the local server
269          * as defined by the administrator.
270          */
271         char ServerName[MAXBUF];
272
273         /** Notice to give to users when they are Xlined
274          */
275         char MoronBanner[MAXBUF];
276         
277         /* Holds the network name the local server
278          * belongs to. This is an arbitary field defined
279          * by the administrator.
280          */
281         char Network[MAXBUF];
282
283         /** Holds the description of the local server
284          * as defined by the administrator.
285          */
286         char ServerDesc[MAXBUF];
287
288         /** Holds the admin's name, for output in
289          * the /ADMIN command.
290          */
291         char AdminName[MAXBUF];
292
293         /** Holds the email address of the admin,
294          * for output in the /ADMIN command.
295          */
296         char AdminEmail[MAXBUF];
297
298         /** Holds the admin's nickname, for output
299          * in the /ADMIN command
300          */
301         char AdminNick[MAXBUF];
302
303         /** The admin-configured /DIE password
304          */
305         char diepass[MAXBUF];
306
307         /** The admin-configured /RESTART password
308          */
309         char restartpass[MAXBUF];
310
311         /** The pathname and filename of the message of the
312          * day file, as defined by the administrator.
313          */
314         char motd[MAXBUF];
315
316         /** The pathname and filename of the rules file,
317          * as defined by the administrator.
318          */
319         char rules[MAXBUF];
320
321         /** The quit prefix in use, or an empty string
322          */
323         char PrefixQuit[MAXBUF];
324
325         /** The quit suffix in use, or an empty string
326          */
327         char SuffixQuit[MAXBUF];
328
329         /** The fixed quit message in use, or an empty string
330          */
331         char FixedQuit[MAXBUF];
332
333         /** The last string found within a <die> tag, or
334          * an empty string.
335          */
336         char DieValue[MAXBUF];
337
338         /** The DNS server to use for DNS queries
339          */
340         char DNSServer[MAXBUF];
341
342         /** This variable contains a space-seperated list
343          * of commands which are disabled by the
344          * administrator of the server for non-opers.
345          */
346         char DisabledCommands[MAXBUF];
347
348         /** The full path to the modules directory.
349          * This is either set at compile time, or
350          * overridden in the configuration file via
351          * the <options> tag.
352          */
353         char ModPath[1024];
354
355         /** The full pathname to the executable, as
356          * given in argv[0] when the program starts.
357          */
358         char MyExecutable[1024];
359
360         /** The file handle of the logfile. If this
361          * value is NULL, the log file is not open,
362          * probably due to a permissions error on
363          * startup (this should not happen in normal
364          * operation!).
365          */
366         FILE *log_file;
367
368         /** If this value is true, the owner of the
369          * server specified -nofork on the command
370          * line, causing the daemon to stay in the
371          * foreground.
372          */
373         bool nofork;
374         
375         /** If this value if true then all log
376          * messages will be output, regardless of
377          * the level given in the config file.
378          * This is set with the -debug commandline
379          * option.
380          */
381         bool forcedebug;
382         
383         /** If this is true then log output will be
384          * written to the logfile. This is the default.
385          * If you put -nolog on the commandline then
386          * the logfile will not be written.
387          * This is meant to be used in conjunction with
388          * -debug for debugging without filling up the
389          * hard disk.
390          */
391         bool writelog;
392
393         /** If this value is true, halfops have been
394          * enabled in the configuration file.
395          */
396         bool AllowHalfop;
397
398         /** If this is set to true, then mode lists (e.g
399          * MODE #chan b) are hidden from unprivileged
400          * users.
401          */
402         bool HideModeLists[256];
403
404         /** If this is set to true, then channel operators
405          * are exempt from this channel mode. Used for +Sc etc.
406          */
407         bool ExemptChanOps[256];
408
409         /** The number of seconds the DNS subsystem
410          * will wait before timing out any request.
411          */
412         int dns_timeout;
413
414         /** The size of the read() buffer in the user
415          * handling code, used to read data into a user's
416          * recvQ.
417          */
418         int NetBufferSize;
419
420         /** The value to be used for listen() backlogs
421          * as default.
422          */
423         int MaxConn;
424
425         /** The soft limit value assigned to the irc server.
426          * The IRC server will not allow more than this
427          * number of local users.
428          */
429         unsigned int SoftLimit;
430
431         /** Maximum number of targets for a multi target command
432          * such as PRIVMSG or KICK
433          */
434         unsigned int MaxTargets;
435
436         /** The maximum number of /WHO results allowed
437          * in any single /WHO command.
438          */
439         int MaxWhoResults;
440
441         /** True if the DEBUG loglevel is selected.
442          */
443         int debugging;
444
445         /** The loglevel in use by the IRC server
446          */
447         int LogLevel;
448
449         /** How many seconds to wait before exiting
450          * the program when /DIE is correctly issued.
451          */
452         int DieDelay;
453
454         /** True if we're going to hide netsplits as *.net *.split for non-opers
455          */
456         bool HideSplits;
457
458         /** True if we're going to hide ban reasons for non-opers (e.g. G-Lines,
459          * K-Lines, Z-Lines)
460          */
461         bool HideBans;
462
463         /** Announce invites to the channel with a server notice
464          */
465         InviteAnnounceState AnnounceInvites;
466
467         /** If this is enabled then operators will
468          * see invisible (+i) channels in /whois.
469          */
470         bool OperSpyWhois;
471
472         /** Set to a non-empty string to obfuscate the server name of users in WHOIS
473          */
474         char HideWhoisServer[MAXBUF];
475
476         /** Set to a non empty string to obfuscate nicknames prepended to a KILL.
477          */
478         char HideKillsServer[MAXBUF];
479
480         /** The MOTD file, cached in a file_cache type.
481          */
482         file_cache MOTD;
483
484         /** The RULES file, cached in a file_cache type.
485          */
486         file_cache RULES;
487
488         /** The full pathname and filename of the PID
489          * file as defined in the configuration.
490          */
491         char PID[1024];
492
493         /** The connect classes in use by the IRC server.
494          */
495         ClassVector Classes;
496
497         /** A list of module names (names only, no paths)
498          * which are currently loaded by the server.
499          */
500         std::vector<std::string> module_names;
501
502         /** A list of the classes for listening client ports
503          */
504         std::vector<ListenSocket*> ports;
505
506         /** Boolean sets of which modules implement which functions
507          */
508         char implement_lists[255][255];
509
510         /** Global implementation list
511          */
512         char global_implementation[255];
513
514         /** A list of ports claimed by IO Modules
515          */
516         std::map<int,Module*> IOHookModule;
517
518         std::map<BufferedSocket*, Module*> SocketIOHookModule;
519
520         /** The 005 tokens of this server (ISUPPORT)
521          * populated/repopulated upon loading or unloading
522          * modules.
523          */
524         std::string data005;
525
526         /** isupport strings
527          */
528         std::vector<std::string> isupport;
529
530         /** STATS characters in this list are available
531          * only to operators.
532          */
533         char UserStats[MAXBUF];
534         
535         /** The path and filename of the ircd.log file
536          */
537         std::string logpath;
538
539         /** Default channel modes
540          */
541         char DefaultModes[MAXBUF];
542
543         /** Custom version string, which if defined can replace the system info in VERSION.
544          */
545         char CustomVersion[MAXBUF];
546
547         /** List of u-lined servers
548          */
549         std::map<irc::string, bool> ulines;
550
551         /** Max banlist sizes for channels (the std::string is a glob)
552          */
553         std::map<std::string, int> maxbans;
554
555         /** Directory where the inspircd binary resides
556          */
557         std::string MyDir;
558
559         /** If set to true, no user DNS lookups are to be performed
560          */
561         bool NoUserDns;
562
563         /** If set to true, provide syntax hints for unknown commands
564          */
565         bool SyntaxHints;
566
567         /** If set to true, users appear to quit then rejoin when their hosts change.
568          * This keeps clients synchronized properly.
569          */
570         bool CycleHosts;
571
572         /** If set to true, prefixed channel NOTICEs and PRIVMSGs will have the prefix
573          *  added to the outgoing text for undernet style msg prefixing.
574          */
575         bool UndernetMsgPrefix;
576
577         /** If set to true, the full nick!user@host will be shown in the TOPIC command
578          * for who set the topic last. If false, only the nick is shown.
579          */
580         bool FullHostInTopic;
581
582         /** All oper type definitions from the config file
583          */
584         opertype_t opertypes;
585
586         /** All oper class definitions from the config file
587          */
588         operclass_t operclass;
589
590         /** Saved argv from startup
591          */
592         char** argv;
593
594         /** Saved argc from startup
595          */
596         int argc;
597
598         /** Max channels per user
599          */
600         unsigned int MaxChans;
601
602         /** Oper max channels per user
603          */
604         unsigned int OperMaxChans;
605
606         /** TS6-like server ID.
607          * NOTE: 000...999 are usable for InspIRCd servers. This
608          * makes code simpler. 0AA, 1BB etc with letters are reserved
609          * for services use.
610          */
611         int sid;
612
613         /** Construct a new ServerConfig
614          */
615         ServerConfig(InspIRCd* Instance);
616
617         /** Clears the include stack in preperation for a Read() call.
618          */
619         void ClearStack();
620
621         /** Get server ID as string with required leading zeroes
622          */
623         std::string GetSID();
624
625         /** Update the 005 vector
626          */
627         void Update005();
628
629         /** Send the 005 numerics (ISUPPORT) to a user
630          */
631         void Send005(User* user);
632
633         /** Read the entire configuration into memory
634          * and initialize this class. All other methods
635          * should be used only by the core.
636          */
637         void Read(bool bail, User* user);
638
639         /** Read a file into a file_cache object
640          */
641         bool ReadFile(file_cache &F, const char* fname);
642
643         /** Report a configuration error given in errormessage.
644          * @param bail If this is set to true, the error is sent to the console, and the program exits
645          * @param user If this is set to a non-null value, and bail is false, the errors are spooled to
646          * this user as SNOTICEs.
647          * If the parameter is NULL, the messages are spooled to all users via WriteOpers as SNOTICEs.
648          */
649         void ReportConfigError(const std::string &errormessage, bool bail, User* user);
650
651         /** Load 'filename' into 'target', with the new config parser everything is parsed into
652          * tag/key/value at load-time rather than at read-value time.
653          */
654         bool LoadConf(ConfigDataHash &target, const char* filename, std::ostringstream &errorstream);
655
656         /** Load 'filename' into 'target', with the new config parser everything is parsed into
657          * tag/key/value at load-time rather than at read-value time.
658          */
659         bool LoadConf(ConfigDataHash &target, const std::string &filename, std::ostringstream &errorstream);
660         
661         /* Both these return true if the value existed or false otherwise */
662         
663         /** Writes 'length' chars into 'result' as a string
664          */
665         bool ConfValue(ConfigDataHash &target, const char* tag, const char* var, int index, char* result, int length, bool allow_linefeeds = false);
666         /** Writes 'length' chars into 'result' as a string
667          */
668         bool ConfValue(ConfigDataHash &target, const char* tag, const char* var, const char* default_value, int index, char* result, int length, bool allow_linefeeds = false);
669
670         /** Writes 'length' chars into 'result' as a string
671          */
672         bool ConfValue(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, std::string &result, bool allow_linefeeds = false);
673         /** Writes 'length' chars into 'result' as a string
674          */
675         bool ConfValue(ConfigDataHash &target, const std::string &tag, const std::string &var, const std::string &default_value, int index, std::string &result, bool allow_linefeeds = false);
676         
677         /** Tries to convert the value to an integer and write it to 'result'
678          */
679         bool ConfValueInteger(ConfigDataHash &target, const char* tag, const char* var, int index, int &result);
680         /** Tries to convert the value to an integer and write it to 'result'
681          */
682         bool ConfValueInteger(ConfigDataHash &target, const char* tag, const char* var, const char* default_value, int index, int &result);
683         /** Tries to convert the value to an integer and write it to 'result'
684          */
685         bool ConfValueInteger(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, int &result);
686         /** Tries to convert the value to an integer and write it to 'result'
687          */
688         bool ConfValueInteger(ConfigDataHash &target, const std::string &tag, const std::string &var, const std::string &default_value, int index, int &result);
689         
690         /** Returns true if the value exists and has a true value, false otherwise
691          */
692         bool ConfValueBool(ConfigDataHash &target, const char* tag, const char* var, int index);
693         /** Returns true if the value exists and has a true value, false otherwise
694          */
695         bool ConfValueBool(ConfigDataHash &target, const char* tag, const char* var, const char* default_value, int index);
696         /** Returns true if the value exists and has a true value, false otherwise
697          */
698         bool ConfValueBool(ConfigDataHash &target, const std::string &tag, const std::string &var, int index);
699         /** Returns true if the value exists and has a true value, false otherwise
700          */
701         bool ConfValueBool(ConfigDataHash &target, const std::string &tag, const std::string &var, const std::string &default_value, int index);
702         
703         /** Returns the number of occurences of tag in the config file
704          */
705         int ConfValueEnum(ConfigDataHash &target, const char* tag);
706         /** Returns the number of occurences of tag in the config file
707          */
708         int ConfValueEnum(ConfigDataHash &target, const std::string &tag);
709         
710         /** Returns the numbers of vars inside the index'th 'tag in the config file
711          */
712         int ConfVarEnum(ConfigDataHash &target, const char* tag, int index);
713         /** Returns the numbers of vars inside the index'th 'tag in the config file
714          */
715         int ConfVarEnum(ConfigDataHash &target, const std::string &tag, int index);
716         
717         /** Get a pointer to the module which has hooked the given port.
718          * @parameter port Port number
719          * @return Returns a pointer to the hooking module, or NULL
720          */
721         Module* GetIOHook(int port);
722
723         /** Hook a module to a client port, so that it can receive notifications
724          * of low-level port activity.
725          * @param port The port number
726          * @param Module the module to hook to the port
727          * @return True if the hook was successful.
728          */
729         bool AddIOHook(int port, Module* iomod);
730
731         /** Delete a module hook from a client port.
732          * @param port The port to detatch from
733          * @return True if successful
734          */
735         bool DelIOHook(int port);
736         
737         /** Get a pointer to the module which has hooked the given BufferedSocket class.
738          * @parameter port Port number
739          * @return Returns a pointer to the hooking module, or NULL
740          */
741         Module* GetIOHook(BufferedSocket* is);
742
743         /** Hook a module to an BufferedSocket class, so that it can receive notifications
744          * of low-level socket activity.
745          * @param iomod The module to hook to the socket
746          * @param is The BufferedSocket to attach to
747          * @return True if the hook was successful.
748          */
749         bool AddIOHook(Module* iomod, BufferedSocket* is);
750
751         /** Delete a module hook from an BufferedSocket.
752          * @param is The BufferedSocket to detatch from.
753          * @return True if the unhook was successful
754          */
755         bool DelIOHook(BufferedSocket* is);
756
757         /** Returns the fully qualified path to the inspircd directory
758          * @return The full program directory
759          */
760         std::string GetFullProgDir();
761
762         /** Returns true if a directory is valid (within the modules directory).
763          * @param dirandfile The directory and filename to check
764          * @return True if the directory is valid
765          */
766         static bool DirValid(const char* dirandfile);
767
768         /** Clean a filename, stripping the directories (and drives) from string.
769          * @param name Directory to tidy
770          * @return The cleaned filename
771          */
772         static char* CleanFilename(char* name);
773
774         /** Check if a file exists.
775          * @param file The full path to a file
776          * @return True if the file exists and is readable.
777          */
778         static bool FileExists(const char* file);
779         
780 };
781
782 /** Initialize the disabled commands list
783  */
784 CoreExport bool InitializeDisabledCommands(const char* data, InspIRCd* ServerInstance);
785
786 /** Initialize the oper types
787  */
788 bool InitTypes(ServerConfig* conf, const char* tag);
789
790 /** Initialize the oper classes
791  */
792 bool InitClasses(ServerConfig* conf, const char* tag);
793
794 /** Initialize an oper type 
795  */
796 bool DoType(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types);
797
798 /** Initialize an oper class
799  */
800 bool DoClass(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types);
801
802 /** Finish initializing the oper types and classes
803  */
804 bool DoneClassesAndTypes(ServerConfig* conf, const char* tag);
805
806 #endif
807