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