]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/command_parse.cpp
Added the <cloak:ipalways> and <cloak:lowercase> options. Patch by nenolod
[user/henk/code/inspircd.git] / src / command_parse.cpp
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 #include "inspircd.h"
15 #include "configreader.h"
16 #include <algorithm>
17 #include "users.h"
18 #include "modules.h"
19 #include "wildcard.h"
20 #include "xline.h"
21 #include "socketengine.h"
22 #include "socket.h"
23 #include "command_parse.h"
24 #include "exitcodes.h"
25
26 /* Directory Searching for Unix-Only */
27 #ifndef WIN32
28 #include <dirent.h>
29 #include <dlfcn.h>
30 #endif
31
32 bool InspIRCd::ULine(const char* server)
33 {
34         if (!server)
35                 return false;
36         if (!*server)
37                 return true;
38
39         return (Config->ulines.find(server) != Config->ulines.end());
40 }
41
42 bool InspIRCd::SilentULine(const char* server)
43 {
44         std::map<irc::string,bool>::iterator n = Config->ulines.find(server);
45         if (n != Config->ulines.end())
46                 return n->second;
47         else return false;
48 }
49
50 int InspIRCd::OperPassCompare(const char* data,const char* input, int tagnumber)
51 {
52         int MOD_RESULT = 0;
53         FOREACH_RESULT_I(this,I_OnOperCompare,OnOperCompare(data, input, tagnumber))
54         if (MOD_RESULT == 1)
55                 return 0;
56         if (MOD_RESULT == -1)
57                 return 1;
58         return strcmp(data,input);
59 }
60
61 std::string InspIRCd::TimeString(time_t curtime)
62 {
63         return std::string(ctime(&curtime),24);
64 }
65
66 /** Refactored by Brain, Jun 2007. Much faster with some clever O(1) array
67  * lookups and pointer maths.
68  */
69 long InspIRCd::Duration(const std::string &str)
70 {
71         unsigned char multiplier = 0;
72         long total = 0;
73         long times = 1;
74         long subtotal = 0;
75
76         /* Iterate each item in the string, looking for number or multiplier */
77         for (std::string::const_reverse_iterator i = str.rbegin(); i != str.rend(); ++i)
78         {
79                 /* Found a number, queue it onto the current number */
80                 if ((*i >= '0') && (*i <= '9'))
81                 {
82                         subtotal = subtotal + ((*i - '0') * times);
83                         times = times * 10;
84                 }
85                 else
86                 {
87                         /* Found something thats not a number, find out how much
88                          * it multiplies the built up number by, multiply the total
89                          * and reset the built up number.
90                          */
91                         if (subtotal)
92                                 total += subtotal * duration_multi[multiplier];
93
94                         /* Next subtotal please */
95                         subtotal = 0;
96                         multiplier = *i;
97                         times = 1;
98                 }
99         }
100         if (multiplier)
101         {
102                 total += subtotal * duration_multi[multiplier];
103                 subtotal = 0;
104         }
105         /* Any trailing values built up are treated as raw seconds */
106         return total + subtotal;
107 }
108
109 /* LoopCall is used to call a command classes handler repeatedly based on the contents of a comma seperated list.
110  * There are two overriden versions of this method, one of which takes two potential lists and the other takes one.
111  * We need a version which takes two potential lists for JOIN, because a JOIN may contain two lists of items at once,
112  * the channel names and their keys as follows:
113  * JOIN #chan1,#chan2,#chan3 key1,,key3
114  * Therefore, we need to deal with both lists concurrently. The first instance of this method does that by creating
115  * two instances of irc::commasepstream and reading them both together until the first runs out of tokens.
116  * The second version is much simpler and just has the one stream to read, and is used in NAMES, WHOIS, PRIVMSG etc.
117  * Both will only parse until they reach ServerInstance->Config->MaxTargets number of targets, to stop abuse via spam.
118  */
119 int CommandParser::LoopCall(userrec* user, command_t* CommandObj, const char** parameters, int pcnt, unsigned int splithere, unsigned int extra)
120 {
121         /* First check if we have more than one item in the list, if we don't we return zero here and the handler
122          * which called us just carries on as it was.
123          */
124         if (!strchr(parameters[splithere],','))
125                 return 0;
126
127         /** Some lame ircds will weed out dupes using some shitty O(n^2) algorithm.
128          * By using std::map (thanks for the idea w00t) we can cut this down a ton.
129          * ...VOOODOOOO!
130          */
131         std::map<irc::string, bool> dupes;
132
133         /* Create two lists, one for channel names, one for keys
134          */
135         irc::commasepstream items1(parameters[splithere]);
136         irc::commasepstream items2(parameters[extra]);
137         std::string item("*");
138         unsigned int max = 0;
139
140         /* Attempt to iterate these lists and call the command objech
141          * which called us, for every parameter pair until there are
142          * no more left to parse.
143          */
144         while (((item = items1.GetToken()) != "") && (max++ < ServerInstance->Config->MaxTargets))
145         {
146                 if (dupes.find(item.c_str()) == dupes.end())
147                 {
148                         const char* new_parameters[MAXPARAMETERS];
149
150                         for (int t = 0; (t < pcnt) && (t < MAXPARAMETERS); t++)
151                                 new_parameters[t] = parameters[t];
152
153                         std::string extrastuff = items2.GetToken();
154
155                         new_parameters[splithere] = item.c_str();
156                         new_parameters[extra] = extrastuff.c_str();
157
158                         CommandObj->Handle(new_parameters,pcnt,user);
159
160                         dupes[item.c_str()] = true;
161                 }
162         }
163         return 1;
164 }
165
166 int CommandParser::LoopCall(userrec* user, command_t* CommandObj, const char** parameters, int pcnt, unsigned int splithere)
167 {
168         /* First check if we have more than one item in the list, if we don't we return zero here and the handler
169          * which called us just carries on as it was.
170          */
171         if (!strchr(parameters[splithere],','))
172                 return 0;
173
174         std::map<irc::string, bool> dupes;
175
176         /* Only one commasepstream here */
177         irc::commasepstream items1(parameters[splithere]);
178         std::string item("*");
179         unsigned int max = 0;
180
181         /* Parse the commasepstream until there are no tokens remaining.
182          * Each token we parse out, call the command handler that called us
183          * with it
184          */
185         while (((item = items1.GetToken()) != "") && (max++ < ServerInstance->Config->MaxTargets))
186         {
187                 if (dupes.find(item.c_str()) == dupes.end())
188                 {
189                         const char* new_parameters[MAXPARAMETERS];
190
191                         for (int t = 0; (t < pcnt) && (t < MAXPARAMETERS); t++)
192                                 new_parameters[t] = parameters[t];
193
194                         new_parameters[splithere] = item.c_str();
195
196                         parameters[splithere] = item.c_str();
197
198                         /* Execute the command handler over and over. If someone pulls our user
199                          * record out from under us (e.g. if we /kill a comma sep list, and we're
200                          * in that list ourselves) abort if we're gone.
201                          */
202                         CommandObj->Handle(new_parameters,pcnt,user);
203
204                         dupes[item.c_str()] = true;
205                 }
206         }
207         /* By returning 1 we tell our caller that nothing is to be done,
208          * as all the previous calls handled the data. This makes the parent
209          * return without doing any processing.
210          */
211         return 1;
212 }
213
214 bool CommandParser::IsValidCommand(const std::string &commandname, int pcnt, userrec * user)
215 {
216         command_table::iterator n = cmdlist.find(commandname);
217
218         if (n != cmdlist.end())
219         {
220                 if ((pcnt>=n->second->min_params) && (n->second->source != "<core>"))
221                 {
222                         if ((!n->second->flags_needed) || (user->IsModeSet(n->second->flags_needed)))
223                         {
224                                 if (n->second->flags_needed)
225                                 {
226                                         return ((user->HasPermission(commandname)) || (ServerInstance->ULine(user->server)));
227                                 }
228                                 return true;
229                         }
230                 }
231         }
232         return false;
233 }
234
235 command_t* CommandParser::GetHandler(const std::string &commandname)
236 {
237         command_table::iterator n = cmdlist.find(commandname);
238         if (n != cmdlist.end())
239                 return n->second;
240
241         return NULL;
242 }
243
244 // calls a handler function for a command
245
246 CmdResult CommandParser::CallHandler(const std::string &commandname,const char** parameters, int pcnt, userrec *user)
247 {
248         command_table::iterator n = cmdlist.find(commandname);
249
250         if (n != cmdlist.end())
251         {
252                 if (pcnt >= n->second->min_params)
253                 {
254                         if ((!n->second->flags_needed) || (user->IsModeSet(n->second->flags_needed)))
255                         {
256                                 if (n->second->flags_needed)
257                                 {
258                                         if ((user->HasPermission(commandname)) || (!IS_LOCAL(user)))
259                                         {
260                                                 return n->second->Handle(parameters,pcnt,user);
261                                         }
262                                 }
263                                 else
264                                 {
265                                         return n->second->Handle(parameters,pcnt,user);
266                                 }
267                         }
268                 }
269         }
270         return CMD_INVALID;
271 }
272
273 void CommandParser::ProcessCommand(userrec *user, std::string &cmd)
274 {
275         const char *command_p[MAXPARAMETERS];
276         int items = 0;
277         irc::tokenstream tokens(cmd);
278         std::string command;
279         tokens.GetToken(command);
280
281         /* A client sent a nick prefix on their command (ick)
282          * rhapsody and some braindead bouncers do this --
283          * the rfc says they shouldnt but also says the ircd should
284          * discard it if they do.
285          */
286         if (*command.c_str() == ':')
287                 tokens.GetToken(command);
288
289         while (tokens.GetToken(para[items]) && (items < MAXPARAMETERS))
290         {
291                 command_p[items] = para[items].c_str();
292                 items++;
293         }
294
295         std::transform(command.begin(), command.end(), command.begin(), ::toupper);
296                 
297         int MOD_RESULT = 0;
298         FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command,command_p,items,user,false,cmd));
299         if (MOD_RESULT == 1) {
300                 return;
301         }
302
303         command_table::iterator cm = cmdlist.find(command);
304         
305         if (cm != cmdlist.end())
306         {
307                 if (user)
308                 {
309                         /* activity resets the ping pending timer */
310                         user->nping = ServerInstance->Time() + user->pingmax;
311                         if (cm->second->flags_needed)
312                         {
313                                 if (!user->IsModeSet(cm->second->flags_needed))
314                                 {
315                                         user->WriteServ("481 %s :Permission Denied - You do not have the required operator privileges",user->nick);
316                                         return;
317                                 }
318                                 if (!user->HasPermission(command))
319                                 {
320                                         user->WriteServ("481 %s :Permission Denied - Oper type %s does not have access to command %s",user->nick,user->oper,command.c_str());
321                                         return;
322                                 }
323                         }
324                         if ((user->registered == REG_ALL) && (!IS_OPER(user)) && (cm->second->IsDisabled()))
325                         {
326                                 /* command is disabled! */
327                                 user->WriteServ("421 %s %s :This command has been disabled.",user->nick,command.c_str());
328                                 ServerInstance->SNO->WriteToSnoMask('d', "%s denied for %s (%s@%s)",
329                                                 command.c_str(), user->nick, user->ident, user->host);
330                                 return;
331                         }
332                         if (items < cm->second->min_params)
333                         {
334                                 user->WriteServ("461 %s %s :Not enough parameters.", user->nick, command.c_str());
335                                 if ((ServerInstance->Config->SyntaxHints) && (user->registered == REG_ALL) && (cm->second->syntax.length()))
336                                         user->WriteServ("304 %s :SYNTAX %s %s", user->nick, cm->second->command.c_str(), cm->second->syntax.c_str());
337                                 return;
338                         }
339                         if ((user->registered == REG_ALL) || (cm->second->WorksBeforeReg()))
340                         {
341                                 /* ikky /stats counters */
342                                 cm->second->use_count++;
343                                 cm->second->total_bytes += cmd.length();
344
345                                 int MOD_RESULT = 0;
346                                 FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command,command_p,items,user,true,cmd));
347                                 if (MOD_RESULT == 1)
348                                         return;
349
350                                 /*
351                                  * WARNING: nothing should come after this, as the user may be on a cull list to
352                                  * be nuked next loop iteration. be sensible.
353                                  */
354                                 CmdResult result = cm->second->Handle(command_p,items,user);
355
356                                 FOREACH_MOD(I_OnPostCommand,OnPostCommand(command, command_p, items, user, result,cmd));
357                                 return;
358                         }
359                         else
360                         {
361                                 user->WriteServ("451 %s :You have not registered",command.c_str());
362                                 return;
363                         }
364                 }
365         }
366         else if (user)
367         {
368                 ServerInstance->stats->statsUnknown++;
369                 user->WriteServ("421 %s %s :Unknown command",user->nick,command.c_str());
370         }
371 }
372
373 bool CommandParser::RemoveCommands(const char* source)
374 {
375         command_table::iterator i,safei;
376         for (i = cmdlist.begin(); i != cmdlist.end(); i++)
377         {
378                 safei = i;
379                 safei++;
380                 if (safei != cmdlist.end())
381                 {
382                         RemoveCommand(safei, source);
383                 }
384         }
385         safei = cmdlist.begin();
386         if (safei != cmdlist.end())
387         {
388                 RemoveCommand(safei, source);
389         }
390         return true;
391 }
392
393 void CommandParser::RemoveCommand(command_table::iterator safei, const char* source)
394 {
395         command_t* x = safei->second;
396         if (x->source == std::string(source))
397         {
398                 cmdlist.erase(safei);
399                 delete x;
400         }
401 }
402
403 void CommandParser::ProcessBuffer(std::string &buffer,userrec *user)
404 {
405         std::string::size_type a;
406
407         if (!user)
408                 return;
409
410         while ((a = buffer.rfind("\n")) != std::string::npos)
411                 buffer.erase(a);
412         while ((a = buffer.rfind("\r")) != std::string::npos)
413                 buffer.erase(a);
414
415         if (buffer.length())
416         {
417                 if (!user->muted)
418                 {
419                         ServerInstance->Log(DEBUG,"C[%d] -> :%s %s",user->GetFd(), user->nick, buffer.c_str());
420                         this->ProcessCommand(user,buffer);
421                 }
422         }
423 }
424
425 bool CommandParser::CreateCommand(command_t *f, void* so_handle)
426 {
427         if (so_handle)
428         {
429                 if (RFCCommands.find(f->command) == RFCCommands.end())
430                         RFCCommands[f->command] = so_handle;
431                 else
432                 {
433                         ServerInstance->Log(DEFAULT,"ERK! Somehow, we loaded a cmd_*.so file twice! Only the first instance is being recorded.");
434                         return false;
435                 }
436         }
437
438         /* create the command and push it onto the table */
439         if (cmdlist.find(f->command) == cmdlist.end())
440         {
441                 cmdlist[f->command] = f;
442                 return true;
443         }
444         else return false;
445 }
446
447 CommandParser::CommandParser(InspIRCd* Instance) : ServerInstance(Instance)
448 {
449         para.resize(128);
450 }
451
452 bool CommandParser::FindSym(void** v, void* h)
453 {
454         *v = dlsym(h, "init_command");
455         const char* err = dlerror();
456         if (err && !(*v))
457         {
458                 ServerInstance->Log(SPARSE, "Error loading core command: %s\n", err);
459                 return false;
460         }
461         return true;
462 }
463
464 bool CommandParser::ReloadCommand(const char* cmd, userrec* user)
465 {
466         char filename[MAXBUF];
467         char commandname[MAXBUF];
468         int y = 0;
469
470         for (const char* x = cmd; *x; x++, y++)
471                 commandname[y] = toupper(*x);
472
473         commandname[y] = 0;
474
475         SharedObjectList::iterator command = RFCCommands.find(commandname);
476
477         if (command != RFCCommands.end())
478         {
479                 command_t* cmdptr = cmdlist.find(commandname)->second;
480                 cmdlist.erase(cmdlist.find(commandname));
481
482                 for (char* x = commandname; *x; x++)
483                         *x = tolower(*x);
484
485
486                 delete cmdptr;
487                 dlclose(command->second);
488                 RFCCommands.erase(command);
489
490                 snprintf(filename, MAXBUF, "cmd_%s.so", commandname);
491                 const char* err = this->LoadCommand(filename);
492                 if (err)
493                 {
494                         if (user)
495                                 user->WriteServ("NOTICE %s :*** Error loading 'cmd_%s.so': %s", user->nick, cmd, err);
496                         return false;
497                 }
498
499                 return true;
500         }
501
502         return false;
503 }
504
505 CmdResult cmd_reload::Handle(const char** parameters, int pcnt, userrec *user)
506 {
507         user->WriteServ("NOTICE %s :*** Reloading command '%s'",user->nick, parameters[0]);
508         if (ServerInstance->Parser->ReloadCommand(parameters[0], user))
509         {
510                 user->WriteServ("NOTICE %s :*** Successfully reloaded command '%s'", user->nick, parameters[0]);
511                 ServerInstance->WriteOpers("*** RELOAD: %s reloaded the '%s' command.", user->nick, parameters[0]);
512                 return CMD_SUCCESS;
513         }
514         else
515         {
516                 user->WriteServ("NOTICE %s :*** Could not reload command '%s' -- fix this problem, then /REHASH as soon as possible!", user->nick, parameters[0]);
517                 return CMD_FAILURE;
518         }
519 }
520
521 const char* CommandParser::LoadCommand(const char* name)
522 {
523         char filename[MAXBUF];
524         void* h;
525         command_t* (*cmd_factory_func)(InspIRCd*);
526
527         /* Command already exists? Succeed silently - this is needed for REHASH */
528         if (RFCCommands.find(name) != RFCCommands.end())
529         {
530                 ServerInstance->Log(DEBUG,"Not reloading command %s/%s, it already exists", LIBRARYDIR, name);
531                 return NULL;
532         }
533
534         snprintf(filename, MAXBUF, "%s/%s", LIBRARYDIR, name);
535         h = dlopen(filename, RTLD_NOW | RTLD_GLOBAL);
536
537         if (!h)
538         {
539                 const char* n = dlerror();
540                 ServerInstance->Log(SPARSE, "Error loading core command: %s", n);
541                 return n;
542         }
543
544         if (this->FindSym((void **)&cmd_factory_func, h))
545         {
546                 command_t* newcommand = cmd_factory_func(ServerInstance);
547                 this->CreateCommand(newcommand, h);
548         }
549         return NULL;
550 }
551
552 void CommandParser::SetupCommandTable(userrec* user)
553 {
554         RFCCommands.clear();
555
556         if (!user)
557         {
558                 printf("\nLoading core commands");
559                 fflush(stdout);
560         }
561
562         DIR* library = opendir(LIBRARYDIR);
563         if (library)
564         {
565                 dirent* entry = NULL;
566                 while ((entry = readdir(library)))
567                 {
568                         if (match(entry->d_name, "cmd_*.so"))
569                         {
570                                 if (!user)
571                                 {
572                                         printf(".");
573                                         fflush(stdout);
574                                 }
575                                 const char* err = this->LoadCommand(entry->d_name);
576                                 if (err)
577                                 {
578                                         if (user)
579                                         {
580                                                 user->WriteServ("NOTICE %s :*** Failed to load core command %s: %s", user->nick, entry->d_name, err);
581                                         }
582                                         else
583                                         {
584                                                 printf("Error loading %s: %s", entry->d_name, err);
585                                                 exit(EXIT_STATUS_BADHANDLER);
586                                         }
587                                 }
588                         }
589                 }
590                 closedir(library);
591                 if (!user)
592                         printf("\n");
593         }
594
595         if (cmdlist.find("RELOAD") == cmdlist.end())
596                 this->CreateCommand(new cmd_reload(ServerInstance));
597 }
598