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