]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/command_parse.cpp
0c3f29a25151572ed715b904c0e2c2c17c0756d9
[user/henk/code/inspircd.git] / src / command_parse.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2007 InspIRCd Development Team
6  * See: http://www.inspircd.org/wiki/index.php/Credits
7  *
8  * This program is free but copyrighted software; see
9  *          the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 /* $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::OperPassCompare(const char* data,const char* input, int tagnumber)
31 {
32         int MOD_RESULT = 0;
33         FOREACH_RESULT_I(this,I_OnOperCompare,OnOperCompare(data, input, tagnumber))
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 char** parameters, int pcnt, 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 (!strchr(parameters[splithere],','))
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                         const char* new_parameters[MAXPARAMETERS];
82
83                         for (int t = 0; (t < pcnt) && (t < MAXPARAMETERS); t++)
84                                 new_parameters[t] = 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,pcnt,user);
93
94                         dupes[item.c_str()] = true;
95                 }
96         }
97         return 1;
98 }
99
100 int CommandParser::LoopCall(User* user, Command* CommandObj, const char** parameters, int pcnt, 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 (!strchr(parameters[splithere],','))
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                         const char* new_parameters[MAXPARAMETERS];
124
125                         for (int t = 0; (t < pcnt) && (t < MAXPARAMETERS); t++)
126                                 new_parameters[t] = parameters[t];
127
128                         new_parameters[splithere] = item.c_str();
129
130                         parameters[splithere] = item.c_str();
131
132                         /* Execute the command handler over and over. If someone pulls our user
133                          * record out from under us (e.g. if we /kill a comma sep list, and we're
134                          * in that list ourselves) abort if we're gone.
135                          */
136                         CommandObj->Handle(new_parameters,pcnt,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, int pcnt, User * user)
149 {
150         Commandable::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         Commandable::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 char** parameters, int pcnt, User *user)
184 {
185         Commandable::iterator n = cmdlist.find(commandname);
186
187         if (n != cmdlist.end())
188         {
189                 if (pcnt >= 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,pcnt,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         int floodlines = 0;
223
224         while (current->BufferIsReady())
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                 // use GetBuffer to copy single lines into the sanitized string
245                 std::string single_line = current->GetBuffer();
246                 current->bytes_in += single_line.length();
247                 current->cmds_in++;
248                 if (single_line.length() > MAXBUF - 2)  // MAXBUF is 514 to allow for neccessary line terminators
249                         single_line.resize(MAXBUF - 2); // So to trim to 512 here, we use MAXBUF - 2
250
251                 // ProcessBuffer returns false if the user has gone over penalty
252                 if (!ServerInstance->Parser->ProcessBuffer(single_line, current) || one_only)
253                         break;
254         }
255 }
256
257 bool CommandParser::ProcessCommand(User *user, std::string &cmd)
258 {
259         const char *command_p[MAXPARAMETERS];
260         int items = 0;
261         irc::tokenstream tokens(cmd);
262         std::string command;
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(para[items]) && (items < MAXPARAMETERS))
274         {
275                 command_p[items] = para[items].c_str();
276                 items++;
277         }
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,items,user,false,cmd));
283         if (MOD_RESULT == 1) {
284                 return true;
285         }
286
287         if (!user)
288         {
289                 /*
290                  * before, we went and found the command even with no user.. seems nonsensical.
291                  * I'm not entirely sure when we would be passed NULL, but let's handle it
292                  * anyway, by dropping it like a hot potato. -- w00t
293                  */
294                 return true;
295         }
296
297         /* find the command, check it exists */
298         Commandable::iterator cm = cmdlist.find(command);
299         
300         if (cm == cmdlist.end())
301         {
302                 ServerInstance->stats->statsUnknown++;
303                 user->WriteServ("421 %s %s :Unknown command",user->nick,command.c_str());
304                 return true;
305         }
306
307         /* Modify the user's penalty */
308         bool do_more = true;
309         if (!user->ExemptFromPenalty)
310         {
311                 user->IncreasePenalty(cm->second->Penalty);
312                 ServerInstance->Log(DEBUG,"Penalty for %s is now incremented to %d (%d added on)", user->nick, user->Penalty, cm->second->Penalty);
313                 do_more = (user->Penalty < 10);
314                 if (!do_more)
315                 {
316                         user->OverPenalty = true;
317                         ServerInstance->Log(DEBUG,"User %s now OVER penalty of 10", user->nick);
318                 }
319         }
320
321         /* activity resets the ping pending timer */
322         user->nping = ServerInstance->Time() + user->MyClass->GetPingTime();
323         if (cm->second->flags_needed)
324         {
325                 if (!user->IsModeSet(cm->second->flags_needed))
326                 {
327                         user->WriteServ("481 %s :Permission Denied - You do not have the required operator privileges",user->nick);
328                         return do_more;
329                 }
330                 if (!user->HasPermission(command))
331                 {
332                         user->WriteServ("481 %s :Permission Denied - Oper type %s does not have access to command %s",user->nick,user->oper,command.c_str());
333                         return do_more;
334                 }
335         }
336         if ((user->registered == REG_ALL) && (!IS_OPER(user)) && (cm->second->IsDisabled()))
337         {
338                 /* command is disabled! */
339                 user->WriteServ("421 %s %s :This command has been disabled.",user->nick,command.c_str());
340                 ServerInstance->SNO->WriteToSnoMask('d', "%s denied for %s (%s@%s)",
341                                 command.c_str(), user->nick, user->ident, user->host);
342                 return do_more;
343         }
344         if (items < cm->second->min_params)
345         {
346                 user->WriteServ("461 %s %s :Not enough parameters.", user->nick, command.c_str());
347                 if ((ServerInstance->Config->SyntaxHints) && (user->registered == REG_ALL) && (cm->second->syntax.length()))
348                         user->WriteServ("304 %s :SYNTAX %s %s", user->nick, cm->second->command.c_str(), cm->second->syntax.c_str());
349                 return do_more;
350         }
351         if ((user->registered != REG_ALL) && (!cm->second->WorksBeforeReg()))
352         {
353                 user->WriteServ("451 %s :You have not registered",command.c_str());
354                 return do_more;
355         }
356         else
357         {
358                 /* passed all checks.. first, do the (ugly) stats counters. */
359                 cm->second->use_count++;
360                 cm->second->total_bytes += cmd.length();
361
362                 /* module calls too */
363                 int MOD_RESULT = 0;
364                 FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command,command_p,items,user,true,cmd));
365                 if (MOD_RESULT == 1)
366                         return do_more;
367
368                 /*
369                  * WARNING: be careful, the user may be deleted soon
370                  */
371                 CmdResult result = cm->second->Handle(command_p,items,user);
372
373                 FOREACH_MOD(I_OnPostCommand,OnPostCommand(command, command_p, items, user, result,cmd));
374                 return do_more;
375         }
376 }
377
378 bool CommandParser::RemoveCommands(const char* source)
379 {
380         Commandable::iterator i,safei;
381         for (i = cmdlist.begin(); i != cmdlist.end(); i++)
382         {
383                 safei = i;
384                 safei++;
385                 if (safei != cmdlist.end())
386                 {
387                         RemoveCommand(safei, source);
388                 }
389         }
390         safei = cmdlist.begin();
391         if (safei != cmdlist.end())
392         {
393                 RemoveCommand(safei, source);
394         }
395         return true;
396 }
397
398 void CommandParser::RemoveCommand(Commandable::iterator safei, const char* source)
399 {
400         Command* x = safei->second;
401         if (x->source == std::string(source))
402         {
403                 cmdlist.erase(safei);
404                 delete x;
405         }
406 }
407
408 bool CommandParser::ProcessBuffer(std::string &buffer,User *user)
409 {
410         std::string::size_type a;
411
412         if (!user)
413                 return true;
414
415         while ((a = buffer.rfind("\n")) != std::string::npos)
416                 buffer.erase(a);
417         while ((a = buffer.rfind("\r")) != std::string::npos)
418                 buffer.erase(a);
419
420         if (buffer.length())
421         {
422                 if (!user->muted)
423                 {
424                         ServerInstance->Log(DEBUG,"C[%d] I :%s %s",user->GetFd(), user->nick, buffer.c_str());
425                         return this->ProcessCommand(user,buffer);
426                 }
427         }
428         return true;
429 }
430
431 bool CommandParser::CreateCommand(Command *f, void* so_handle)
432 {
433         if (so_handle)
434         {
435                 if (RFCCommands.find(f->command) == RFCCommands.end())
436                         RFCCommands[f->command] = so_handle;
437                 else
438                 {
439                         ServerInstance->Log(DEFAULT,"ERK! Somehow, we loaded a cmd_*.so file twice! Only the first instance is being recorded.");
440                         return false;
441                 }
442         }
443
444         /* create the command and push it onto the table */
445         if (cmdlist.find(f->command) == cmdlist.end())
446         {
447                 cmdlist[f->command] = f;
448                 return true;
449         }
450         else return false;
451 }
452
453 CommandParser::CommandParser(InspIRCd* Instance) : ServerInstance(Instance)
454 {
455         para.resize(128);
456 }
457
458 bool CommandParser::FindSym(void** v, void* h, const std::string &name)
459 {
460         *v = dlsym(h, "init_command");
461         const char* err = dlerror();
462         if (err && !(*v))
463         {
464                 ServerInstance->Log(SPARSE, "Error loading core command %s: %s\n", name.c_str(), err);
465                 return false;
466         }
467         return true;
468 }
469
470 bool CommandParser::ReloadCommand(const char* cmd, User* user)
471 {
472         char filename[MAXBUF];
473         char commandname[MAXBUF];
474         int y = 0;
475
476         for (const char* x = cmd; *x; x++, y++)
477                 commandname[y] = toupper(*x);
478
479         commandname[y] = 0;
480
481         SharedObjectList::iterator command = RFCCommands.find(commandname);
482
483         if (command != RFCCommands.end())
484         {
485                 Command* cmdptr = cmdlist.find(commandname)->second;
486                 cmdlist.erase(cmdlist.find(commandname));
487
488                 for (char* x = commandname; *x; x++)
489                         *x = tolower(*x);
490
491
492                 delete cmdptr;
493                 dlclose(command->second);
494                 RFCCommands.erase(command);
495
496                 snprintf(filename, MAXBUF, "cmd_%s.so", commandname);
497                 const char* err = this->LoadCommand(filename);
498                 if (err)
499                 {
500                         if (user)
501                                 user->WriteServ("NOTICE %s :*** Error loading 'cmd_%s.so': %s", user->nick, cmd, err);
502                         return false;
503                 }
504
505                 return true;
506         }
507
508         return false;
509 }
510
511 CmdResult cmd_reload::Handle(const char** parameters, int /* pcnt */, User *user)
512 {
513         user->WriteServ("NOTICE %s :*** Reloading command '%s'",user->nick, parameters[0]);
514         if (ServerInstance->Parser->ReloadCommand(parameters[0], user))
515         {
516                 user->WriteServ("NOTICE %s :*** Successfully reloaded command '%s'", user->nick, parameters[0]);
517                 ServerInstance->WriteOpers("*** RELOAD: %s reloaded the '%s' command.", user->nick, parameters[0]);
518                 return CMD_SUCCESS;
519         }
520         else
521         {
522                 user->WriteServ("NOTICE %s :*** Could not reload command '%s' -- fix this problem, then /REHASH as soon as possible!", user->nick, parameters[0]);
523                 return CMD_FAILURE;
524         }
525 }
526
527 const char* CommandParser::LoadCommand(const char* name)
528 {
529         char filename[MAXBUF];
530         void* h;
531         Command* (*cmd_factory_func)(InspIRCd*);
532
533         /* Command already exists? Succeed silently - this is needed for REHASH */
534         if (RFCCommands.find(name) != RFCCommands.end())
535         {
536                 ServerInstance->Log(DEBUG,"Not reloading command %s/%s, it already exists", LIBRARYDIR, name);
537                 return NULL;
538         }
539
540         snprintf(filename, MAXBUF, "%s/%s", LIBRARYDIR, name);
541         h = dlopen(filename, RTLD_NOW | RTLD_GLOBAL);
542
543         if (!h)
544         {
545                 const char* n = dlerror();
546                 ServerInstance->Log(SPARSE, "Error loading core command %s: %s", name, n);
547                 return n;
548         }
549
550         if (this->FindSym((void **)&cmd_factory_func, h, name))
551         {
552                 Command* newcommand = cmd_factory_func(ServerInstance);
553                 this->CreateCommand(newcommand, h);
554         }
555         return NULL;
556 }
557
558 void CommandParser::SetupCommandTable(User* user)
559 {
560         RFCCommands.clear();
561
562         if (!user)
563         {
564                 printf("\nLoading core commands");
565                 fflush(stdout);
566         }
567
568         DIR* library = opendir(LIBRARYDIR);
569         if (library)
570         {
571                 dirent* entry = NULL;
572                 while ((entry = readdir(library)))
573                 {
574                         if (match(entry->d_name, "cmd_*.so"))
575                         {
576                                 if (!user)
577                                 {
578                                         printf(".");
579                                         fflush(stdout);
580                                 }
581                                 const char* err = this->LoadCommand(entry->d_name);
582                                 if (err)
583                                 {
584                                         if (user)
585                                         {
586                                                 user->WriteServ("NOTICE %s :*** Failed to load core command %s: %s", user->nick, entry->d_name, err);
587                                         }
588                                         else
589                                         {
590                                                 printf("Error loading %s: %s", entry->d_name, err);
591                                                 exit(EXIT_STATUS_BADHANDLER);
592                                         }
593                                 }
594                         }
595                 }
596                 closedir(library);
597                 if (!user)
598                         printf("\n");
599         }
600
601         if (cmdlist.find("RELOAD") == cmdlist.end())
602                 this->CreateCommand(new cmd_reload(ServerInstance));
603 }
604
605 int CommandParser::TranslateUIDs(TranslateType to, const std::string &source, std::string &dest)
606 {
607         User* user = NULL;
608         std::string item;
609         int translations = 0;
610         dest.clear();
611
612         switch (to)
613         {
614                 case TR_NICK:
615                         /* Translate single nickname */
616                         user = ServerInstance->FindNick(source);
617                         if (user)
618                         {
619                                 dest = user->uuid;
620                                 translations++;
621                         }
622                         else
623                                 dest = source;
624                 break;
625                 case TR_NICKLIST:
626                 {
627                         /* Translate comma seperated list of nicknames */
628                         irc::commasepstream items(source);
629                         while (items.GetToken(item))
630                         {
631                                 user = ServerInstance->FindNick(item);
632                                 if (user)
633                                 {
634                                         dest.append(user->uuid);
635                                         translations++;
636                                 }
637                                 else
638                                         dest.append(item);
639                                 dest.append(",");
640                         }
641                         if (!dest.empty())
642                                 dest.erase(dest.end() - 1);
643                 }
644                 break;
645                 case TR_SPACENICKLIST:
646                 {
647                         /* Translate space seperated list of nicknames */
648                         irc::spacesepstream items(source);
649                         while (items.GetToken(item))
650                         {
651                                 user = ServerInstance->FindNick(item);
652                                 if (user)
653                                 {
654                                         dest.append(user->uuid);
655                                         translations++;
656                                 }
657                                 else
658                                         dest.append(item);
659                                 dest.append(" ");
660                         }
661                         if (!dest.empty())
662                                 dest.erase(dest.end() - 1);
663                 }
664                 break;
665                 case TR_END:
666                 case TR_TEXT:
667                 default:
668                         /* Do nothing */
669                         dest = source;
670                 break;
671         }
672
673         return translations;
674 }
675