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