]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/command_parse.cpp
Replace std::deque with std::vector in spanningtree and related modules
[user/henk/code/inspircd.git] / src / command_parse.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2009 InspIRCd Development Team
6  * See: http://wiki.inspircd.org/Credits
7  *
8  * This program is free but copyrighted software; see
9  *          the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 /* $Core */
15
16 #include "inspircd.h"
17 #include "xline.h"
18 #include "socketengine.h"
19 #include "socket.h"
20 #include "command_parse.h"
21 #include "exitcodes.h"
22
23 /* Directory Searching for Unix-Only */
24 #ifndef WIN32
25 #include <dirent.h>
26 #include <dlfcn.h>
27 #endif
28
29 int InspIRCd::PassCompare(Extensible* ex, const std::string &data, const std::string &input, const std::string &hashtype)
30 {
31         int MOD_RESULT = 0;
32         FOREACH_RESULT_I(this,I_OnPassCompare,OnPassCompare(ex, data, input, hashtype))
33
34         /* Module matched */
35         if (MOD_RESULT == 1)
36                 return 0;
37
38         /* Module explicitly didnt match */
39         if (MOD_RESULT == -1)
40                 return 1;
41
42         /* We dont handle any hash types except for plaintext - Thanks tra26 */
43         if (hashtype != "" && hashtype != "plaintext")
44                 /* See below. 1 because they dont match */
45                 return 1;
46
47         return (data != input); // this seems back to front, but returns 0 if they *match*, 1 else
48 }
49
50 /* LoopCall is used to call a command classes handler repeatedly based on the contents of a comma seperated list.
51  * There are two overriden versions of this method, one of which takes two potential lists and the other takes one.
52  * We need a version which takes two potential lists for JOIN, because a JOIN may contain two lists of items at once,
53  * the channel names and their keys as follows:
54  * JOIN #chan1,#chan2,#chan3 key1,,key3
55  * Therefore, we need to deal with both lists concurrently. The first instance of this method does that by creating
56  * two instances of irc::commasepstream and reading them both together until the first runs out of tokens.
57  * The second version is much simpler and just has the one stream to read, and is used in NAMES, WHOIS, PRIVMSG etc.
58  * Both will only parse until they reach ServerInstance->Config->MaxTargets number of targets, to stop abuse via spam.
59  */
60 int CommandParser::LoopCall(User* user, Command* CommandObj, const std::vector<std::string>& parameters, unsigned int splithere, unsigned int extra)
61 {
62         if (splithere >= parameters.size())
63                 return 0;
64
65         /* First check if we have more than one item in the list, if we don't we return zero here and the handler
66          * which called us just carries on as it was.
67          */
68         if (parameters[splithere].find(',') == std::string::npos)
69                 return 0;
70
71         /** Some lame ircds will weed out dupes using some shitty O(n^2) algorithm.
72          * By using std::set (thanks for the idea w00t) we can cut this down a ton.
73          * ...VOOODOOOO!
74          */
75         std::set<irc::string> dupes;
76
77         /* Create two lists, one for channel names, one for keys
78          */
79         irc::commasepstream items1(parameters[splithere]);
80         irc::commasepstream items2(parameters[extra]);
81         std::string extrastuff;
82         std::string item;
83         unsigned int max = 0;
84
85         /* Attempt to iterate these lists and call the command objech
86          * which called us, for every parameter pair until there are
87          * no more left to parse.
88          */
89         while (items1.GetToken(item) && (max++ < ServerInstance->Config->MaxTargets))
90         {
91                 if (dupes.find(item.c_str()) == dupes.end())
92                 {
93                         std::vector<std::string> new_parameters;
94
95                         for (unsigned int t = 0; (t < parameters.size()) && (t < MAXPARAMETERS); t++)
96                                 new_parameters.push_back(parameters[t]);
97
98                         if (!items2.GetToken(extrastuff))
99                                 extrastuff = "";
100
101                         new_parameters[splithere] = item.c_str();
102                         new_parameters[extra] = extrastuff.c_str();
103
104                         CommandObj->Handle(new_parameters, user);
105
106                         dupes.insert(item.c_str());
107                 }
108         }
109         return 1;
110 }
111
112 int CommandParser::LoopCall(User* user, Command* CommandObj, const std::vector<std::string>& parameters, unsigned int splithere)
113 {
114         if (splithere >= parameters.size())
115                 return 0;
116
117         /* First check if we have more than one item in the list, if we don't we return zero here and the handler
118          * which called us just carries on as it was.
119          */
120         if (parameters[splithere].find(',') == std::string::npos)
121                 return 0;
122
123         std::set<irc::string> dupes;
124
125         /* Only one commasepstream here */
126         irc::commasepstream items1(parameters[splithere]);
127         std::string item;
128         unsigned int max = 0;
129
130         /* Parse the commasepstream until there are no tokens remaining.
131          * Each token we parse out, call the command handler that called us
132          * with it
133          */
134         while (items1.GetToken(item) && (max++ < ServerInstance->Config->MaxTargets))
135         {
136                 if (dupes.find(item.c_str()) == dupes.end())
137                 {
138                         std::vector<std::string> new_parameters;
139
140                         for (unsigned int t = 0; (t < parameters.size()) && (t < MAXPARAMETERS); t++)
141                                 new_parameters.push_back(parameters[t]);
142
143                         new_parameters[splithere] = item.c_str();
144
145                         /* Execute the command handler. */
146                         CommandObj->Handle(new_parameters, user);
147
148                         dupes.insert(item.c_str());
149                 }
150         }
151         /* By returning 1 we tell our caller that nothing is to be done,
152          * as all the previous calls handled the data. This makes the parent
153          * return without doing any processing.
154          */
155         return 1;
156 }
157
158 bool CommandParser::IsValidCommand(const std::string &commandname, unsigned int pcnt, User * user)
159 {
160         Commandtable::iterator n = cmdlist.find(commandname);
161
162         if (n != cmdlist.end())
163         {
164                 if ((pcnt >= n->second->min_params) && (n->second->source != "<core>"))
165                 {
166                         if (IS_LOCAL(user) && n->second->flags_needed)
167                         {
168                                 if (user->IsModeSet(n->second->flags_needed))
169                                 {
170                                         return (user->HasPermission(commandname));
171                                 }
172                         }
173                         else
174                         {
175                                 return true;
176                         }
177                 }
178         }
179         return false;
180 }
181
182 Command* CommandParser::GetHandler(const std::string &commandname)
183 {
184         Commandtable::iterator n = cmdlist.find(commandname);
185         if (n != cmdlist.end())
186                 return n->second;
187
188         return NULL;
189 }
190
191 // calls a handler function for a command
192
193 CmdResult CommandParser::CallHandler(const std::string &commandname, const std::vector<std::string>& parameters, User *user)
194 {
195         Commandtable::iterator n = cmdlist.find(commandname);
196
197         if (n != cmdlist.end())
198         {
199                 if (parameters.size() >= n->second->min_params)
200                 {
201                         bool bOkay = false;
202
203                         if (IS_LOCAL(user) && n->second->flags_needed)
204                         {
205                                 /* if user is local, and flags are needed .. */
206
207                                 if (user->IsModeSet(n->second->flags_needed))
208                                 {
209                                         /* if user has the flags, and now has the permissions, go ahead */
210                                         if (user->HasPermission(commandname))
211                                                 bOkay = true;
212                                 }
213                         }
214                         else
215                         {
216                                 /* remote or no flags required anyway */
217                                 bOkay = true;
218                         }
219
220                         if (bOkay)
221                         {
222                                 return n->second->Handle(parameters,user);
223                         }
224                 }
225         }
226         return CMD_INVALID;
227 }
228
229 void CommandParser::DoLines(User* current, bool one_only)
230 {
231         while (current->BufferIsReady())
232         {
233                 // use GetBuffer to copy single lines into the sanitized string
234                 std::string single_line = current->GetBuffer();
235                 current->bytes_in += single_line.length();
236                 current->cmds_in++;
237                 if (single_line.length() > MAXBUF - 2)  // MAXBUF is 514 to allow for neccessary line terminators
238                         single_line.resize(MAXBUF - 2); // So to trim to 512 here, we use MAXBUF - 2
239
240                 // ProcessBuffer returns false if the user has gone over penalty
241                 if (!ServerInstance->Parser->ProcessBuffer(single_line, current) || one_only)
242                         break;
243         }
244 }
245
246 bool CommandParser::ProcessCommand(User *user, std::string &cmd)
247 {
248         std::vector<std::string> command_p;
249         irc::tokenstream tokens(cmd);
250         std::string command, token;
251         tokens.GetToken(command);
252
253         /* A client sent a nick prefix on their command (ick)
254          * rhapsody and some braindead bouncers do this --
255          * the rfc says they shouldnt but also says the ircd should
256          * discard it if they do.
257          */
258         if (command[0] == ':')
259                 tokens.GetToken(command);
260
261         while (tokens.GetToken(token) && (command_p.size() <= MAXPARAMETERS))
262                 command_p.push_back(token);
263
264         std::transform(command.begin(), command.end(), command.begin(), ::toupper);
265
266         /* find the command, check it exists */
267         Commandtable::iterator cm = cmdlist.find(command);
268
269         /* Modify the user's penalty regardless of whether or not the command exists */
270         bool do_more = true;
271         if (!user->HasPrivPermission("users/flood/no-throttle"))
272         {
273                 // If it *doesn't* exist, give it a slightly heftier penalty than normal to deter flooding us crap
274                 user->IncreasePenalty(cm != cmdlist.end() ? cm->second->Penalty : 2);
275                 do_more = (user->Penalty < 10);
276         }
277
278
279         if (cm == cmdlist.end())
280         {
281                 int MOD_RESULT = 0;
282                 FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command, command_p, user, false, cmd));
283                 if (MOD_RESULT == 1)
284                         return true;
285
286                 /*
287                  * This double lookup is in case a module (abbreviation) wishes to change a command.
288                  * Sure, the double lookup is a bit painful, but bear in mind this only happens for unknowns anyway.
289                  *
290                  * Thanks dz for making me actually understand why this is necessary!
291                  * -- w00t
292                  */
293                 cm = cmdlist.find(command);
294                 if (cm == cmdlist.end())
295                 {
296                         if (user->registered == REG_ALL)
297                                 user->WriteNumeric(ERR_UNKNOWNCOMMAND, "%s %s :Unknown command",user->nick.c_str(),command.c_str());
298                         ServerInstance->stats->statsUnknown++;
299                         return true;
300                 }
301         }
302
303         if (cm->second->max_params && command_p.size() > cm->second->max_params)
304         {
305                 /*
306                  * command_p input (assuming max_params 1):
307                  *      this
308                  *      is
309                  *      a
310                  *      test
311                  */
312                 std::string lparam = "";
313
314                 /*
315                  * The '-1' here is a clever trick, we'll go backwards throwing everything into a temporary param
316                  * and then just toss that into the array.
317                  * -- w00t
318                  */
319                 while (command_p.size() > (cm->second->max_params - 1))
320                 {
321                         // BE CAREFUL: .end() returns past the end of the vector, hence decrement.
322                         std::vector<std::string>::iterator it = --command_p.end();
323
324                         lparam.insert(0, " " + *(it));
325                         command_p.erase(it); // remove last element
326                 }
327
328                 /* we now have (each iteration):
329                  *      ' test'
330                  *      ' a test'
331                  *      ' is a test' <-- final string
332                  * ...now remove the ' ' at the start...
333                  */
334                 lparam.erase(lparam.begin());
335
336                 /* param is now 'is a test', which is exactly what we wanted! */
337                 command_p.push_back(lparam);
338         }
339
340         /*
341          * We call OnPreCommand here seperately if the command exists, so the magic above can
342          * truncate to max_params if necessary. -- w00t
343          */
344         int MOD_RESULT = 0;
345         FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command, command_p, user, false, cmd));
346         if (MOD_RESULT == 1)
347                 return true;
348
349         /* activity resets the ping pending timer */
350         if (user->MyClass)
351                 user->nping = ServerInstance->Time() + user->MyClass->GetPingTime();
352
353         if (cm->second->flags_needed)
354         {
355                 if (!user->IsModeSet(cm->second->flags_needed))
356                 {
357                         user->WriteNumeric(ERR_NOPRIVILEGES, "%s :Permission Denied - You do not have the required operator privileges",user->nick.c_str());
358                         return do_more;
359                 }
360                 if (!user->HasPermission(command))
361                 {
362                         user->WriteNumeric(ERR_NOPRIVILEGES, "%s :Permission Denied - Oper type %s does not have access to command %s",user->nick.c_str(),user->oper.c_str(),command.c_str());
363                         return do_more;
364                 }
365         }
366         if ((user->registered == REG_ALL) && (!IS_OPER(user)) && (cm->second->IsDisabled()))
367         {
368                 /* command is disabled! */
369                 if (ServerInstance->Config->DisabledDontExist)
370                 {
371                         user->WriteNumeric(ERR_UNKNOWNCOMMAND, "%s %s :Unknown command",user->nick.c_str(),command.c_str());
372                 }
373                 else
374                 {
375                         user->WriteNumeric(ERR_UNKNOWNCOMMAND, "%s %s :This command has been disabled.",
376                                                                                 user->nick.c_str(), command.c_str());
377                 }
378
379                 ServerInstance->SNO->WriteToSnoMask('t', "%s denied for %s (%s@%s)",
380                                 command.c_str(), user->nick.c_str(), user->ident.c_str(), user->host.c_str());
381                 return do_more;
382         }
383         if (command_p.size() < cm->second->min_params)
384         {
385                 user->WriteNumeric(ERR_NEEDMOREPARAMS, "%s %s :Not enough parameters.", user->nick.c_str(), command.c_str());
386                 if ((ServerInstance->Config->SyntaxHints) && (user->registered == REG_ALL) && (cm->second->syntax.length()))
387                         user->WriteNumeric(RPL_SYNTAX, "%s :SYNTAX %s %s", user->nick.c_str(), cm->second->command.c_str(), cm->second->syntax.c_str());
388                 return do_more;
389         }
390         if ((user->registered != REG_ALL) && (!cm->second->WorksBeforeReg()))
391         {
392                 user->WriteNumeric(ERR_NOTREGISTERED, "%s :You have not registered",command.c_str());
393                 return do_more;
394         }
395         else
396         {
397                 /* passed all checks.. first, do the (ugly) stats counters. */
398                 cm->second->use_count++;
399                 cm->second->total_bytes += cmd.length();
400
401                 /* module calls too */
402                 MOD_RESULT = 0;
403                 FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command, command_p, user, true, cmd));
404                 if (MOD_RESULT == 1)
405                         return do_more;
406
407                 /*
408                  * WARNING: be careful, the user may be deleted soon
409                  */
410                 CmdResult result = cm->second->Handle(command_p, user);
411
412                 FOREACH_MOD(I_OnPostCommand,OnPostCommand(command, command_p, user, result,cmd));
413                 return do_more;
414         }
415 }
416
417 void CommandParser::RemoveCommands(const char* source)
418 {
419         Commandtable::iterator i,safei;
420         for (i = cmdlist.begin(); i != cmdlist.end();)
421         {
422                 safei = i;
423                 i++;
424                 RemoveCommand(safei, source);
425         }
426 }
427
428 void CommandParser::RemoveCommand(Commandtable::iterator safei, const char* source)
429 {
430         Command* x = safei->second;
431         if (x->source == std::string(source))
432         {
433                 cmdlist.erase(safei);
434         }
435 }
436
437 bool CommandParser::ProcessBuffer(std::string &buffer,User *user)
438 {
439         std::string::size_type a;
440
441         if (!user)
442                 return true;
443
444         while ((a = buffer.rfind("\n")) != std::string::npos)
445                 buffer.erase(a);
446         while ((a = buffer.rfind("\r")) != std::string::npos)
447                 buffer.erase(a);
448
449         if (buffer.length())
450         {
451                 ServerInstance->Logs->Log("USERINPUT", DEBUG,"C[%d] I :%s %s",user->GetFd(), user->nick.c_str(), buffer.c_str());
452                 return this->ProcessCommand(user,buffer);
453         }
454
455         return true;
456 }
457
458 bool CommandParser::CreateCommand(Command *f, void* so_handle)
459 {
460         if (so_handle)
461         {
462                 if (RFCCommands.find(f->command) == RFCCommands.end())
463                         RFCCommands[f->command] = so_handle;
464                 else
465                 {
466                         ServerInstance->Logs->Log("COMMAND",DEFAULT,"ERK! Somehow, we loaded a cmd_*.so file twice! Only the first instance is being recorded.");
467                         return false;
468                 }
469         }
470
471         /* create the command and push it onto the table */
472         if (cmdlist.find(f->command) == cmdlist.end())
473         {
474                 cmdlist[f->command] = f;
475                 return true;
476         }
477         else return false;
478 }
479
480 CommandParser::CommandParser(InspIRCd* Instance) : ServerInstance(Instance)
481 {
482         para.resize(128);
483 }
484
485 bool CommandParser::FindSym(void** v, void* h, const std::string &name)
486 {
487         *v = dlsym(h, "init_command");
488         const char* err = dlerror();
489         if (err && !(*v))
490         {
491                 ServerInstance->Logs->Log("COMMAND",SPARSE, "Error loading core command %s: %s\n", name.c_str(), err);
492                 return false;
493         }
494         return true;
495 }
496
497 bool CommandParser::ReloadCommand(std::string cmd, User* user)
498 {
499         char filename[MAXBUF];
500         std::transform(cmd.begin(), cmd.end(), cmd.begin(), ::toupper);
501
502         SharedObjectList::iterator command = RFCCommands.find(cmd);
503
504         if (command != RFCCommands.end())
505         {
506                 Command* cmdptr = cmdlist.find(cmd)->second;
507                 cmdlist.erase(cmdlist.find(cmd));
508
509                 RFCCommands.erase(cmd);
510                 delete cmdptr;
511                 dlclose(command->second);
512         }
513
514         std::transform(cmd.begin(), cmd.end(), cmd.begin(), ::tolower);
515         snprintf(filename, MAXBUF, "cmd_%s.so", cmd.c_str());
516         const char* err = this->LoadCommand(filename);
517         if (err)
518         {
519                 if (user)
520                         user->WriteServ("NOTICE %s :*** Error loading '%s': %s", user->nick.c_str(), filename, err);
521                 return false;
522         }
523         return true;
524 }
525
526 CmdResult CommandReload::Handle(const std::vector<std::string>& parameters, User *user)
527 {
528         if (parameters.size() < 1)
529                 return CMD_FAILURE;
530
531         user->WriteServ("NOTICE %s :*** Reloading command '%s'",user->nick.c_str(), parameters[0].c_str());
532         if (ServerInstance->Parser->ReloadCommand(parameters[0], user))
533         {
534                 user->WriteServ("NOTICE %s :*** Successfully reloaded command '%s'", user->nick.c_str(), parameters[0].c_str());
535                 ServerInstance->SNO->WriteToSnoMask('a', "RELOAD: %s reloaded the '%s' command.", user->nick.c_str(), parameters[0].c_str());
536                 return CMD_SUCCESS;
537         }
538         else
539         {
540                 user->WriteServ("NOTICE %s :*** Could not reload command '%s'. The command will not work until reloaded successfully.", user->nick.c_str(), parameters[0].c_str());
541                 return CMD_FAILURE;
542         }
543 }
544
545 const char* CommandParser::LoadCommand(const char* name)
546 {
547         char filename[MAXBUF];
548         void* h;
549         Command* (*cmd_factory_func)(InspIRCd*);
550
551         /* Command already exists? Succeed silently - this is needed for REHASH */
552         if (RFCCommands.find(name) != RFCCommands.end())
553         {
554                 ServerInstance->Logs->Log("COMMAND",DEBUG,"Not reloading command %s/%s, it already exists", LIBRARYDIR, name);
555                 return NULL;
556         }
557
558         snprintf(filename, MAXBUF, "%s/%s", LIBRARYDIR, name);
559         h = dlopen(filename, RTLD_NOW | RTLD_GLOBAL);
560
561         if (!h)
562         {
563                 const char* n = dlerror();
564                 ServerInstance->Logs->Log("COMMAND",SPARSE, "Error loading core command %s: %s", name, n);
565                 return n;
566         }
567
568         if (this->FindSym((void **)&cmd_factory_func, h, name))
569         {
570                 Command* newcommand = cmd_factory_func(ServerInstance);
571                 this->CreateCommand(newcommand, h);
572         }
573         return NULL;
574 }
575
576 /** This is only invoked on startup
577  */
578 void CommandParser::SetupCommandTable()
579 {
580         printf("\nLoading core commands");
581         fflush(stdout);
582
583         DIR* library = opendir(LIBRARYDIR);
584         if (library)
585         {
586                 dirent* entry = NULL;
587                 while (0 != (entry = readdir(library)))
588                 {
589                         if (InspIRCd::Match(entry->d_name, "cmd_*.so", ascii_case_insensitive_map))
590                         {
591                                 printf(".");
592                                 fflush(stdout);
593
594                                 const char* err = this->LoadCommand(entry->d_name);
595                                 if (err)
596                                 {
597                                         printf("Error loading %s: %s", entry->d_name, err);
598                                         exit(EXIT_STATUS_BADHANDLER);
599                                 }
600                         }
601                 }
602                 closedir(library);
603                 printf("\n");
604         }
605
606         if (cmdlist.find("RELOAD") == cmdlist.end())
607                 this->CreateCommand(new CommandReload(ServerInstance));
608 }
609
610 int CommandParser::TranslateUIDs(const std::vector<TranslateType> to, const std::vector<std::string> &source, std::string &dest)
611 {
612         std::vector<std::string>::const_iterator items = source.begin();
613         std::vector<TranslateType>::const_iterator types = to.begin();
614         User* user = NULL;
615         int translations = 0;
616         dest.clear();
617
618         while (items != source.end() && types != to.end())
619         {
620                 TranslateType t = *types;
621                 std::string item = *items;
622                 types++;
623                 items++;
624
625                 switch (t)
626                 {
627                         case TR_NICK:
628                                 /* Translate single nickname */
629                                 user = ServerInstance->FindNick(item);
630                                 if (user)
631                                 {
632                                         dest.append(user->uuid);
633                                         translations++;
634                                 }
635                                 else
636                                         dest.append(item);
637                         break;
638                         break;
639                         case TR_END:
640                         case TR_TEXT:
641                         default:
642                                 /* Do nothing */
643                                 dest.append(item);
644                         break;
645                 }
646                 dest.append(" ");
647         }
648
649         if (!dest.empty())
650                 dest.erase(dest.end() - 1);
651         return translations;
652 }
653
654 int CommandParser::TranslateUIDs(TranslateType to, const std::string &source, std::string &dest)
655 {
656         User* user = NULL;
657         std::string item;
658         int translations = 0;
659         dest.clear();
660
661         switch (to)
662         {
663                 case TR_NICK:
664                         /* Translate single nickname */
665                         user = ServerInstance->FindNick(source);
666                         if (user)
667                         {
668                                 dest = user->uuid;
669                                 translations++;
670                         }
671                         else
672                                 dest = source;
673                 break;
674                 case TR_END:
675                 case TR_TEXT:
676                 default:
677                         /* Do nothing */
678                         dest = source;
679                 break;
680         }
681
682         return translations;
683 }