]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/command_parse.cpp
Seperate USERIO into USERINPUT and USEROUTPUT
[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 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         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         const char *command_p[MAXPARAMETERS];
263         int items = 0;
264         irc::tokenstream tokens(cmd);
265         std::string command;
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.c_str() == ':')
274                 tokens.GetToken(command);
275
276         while (tokens.GetToken(para[items]) && (items < MAXPARAMETERS))
277         {
278                 command_p[items] = para[items].c_str();
279                 items++;
280         }
281
282         std::transform(command.begin(), command.end(), command.begin(), ::toupper);
283                 
284         int MOD_RESULT = 0;
285         FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command,command_p,items,user,false,cmd));
286         if (MOD_RESULT == 1) {
287                 return true;
288         }
289
290         /* find the command, check it exists */
291         Commandable::iterator cm = cmdlist.find(command);
292         
293         if (cm == cmdlist.end())
294         {
295                 if (user->registered == REG_ALL)
296                 {
297                         user->WriteServ("421 %s %s :Unknown command",user->nick,command.c_str());
298                 }
299                 ServerInstance->stats->statsUnknown++;
300                 return true;
301         }
302
303         /* Modify the user's penalty */
304         bool do_more = true;
305         if (!user->ExemptFromPenalty)
306         {
307                 user->IncreasePenalty(cm->second->Penalty);
308                 do_more = (user->Penalty < 10);
309                 if (!do_more)
310                         user->OverPenalty = true;
311         }
312
313         /* activity resets the ping pending timer */
314         if (user->MyClass)
315                 user->nping = ServerInstance->Time() + user->MyClass->GetPingTime();
316
317         if (cm->second->flags_needed)
318         {
319                 if (!user->IsModeSet(cm->second->flags_needed))
320                 {
321                         user->WriteServ("481 %s :Permission Denied - You do not have the required operator privileges",user->nick);
322                         return do_more;
323                 }
324                 if (!user->HasPermission(command))
325                 {
326                         user->WriteServ("481 %s :Permission Denied - Oper type %s does not have access to command %s",user->nick,user->oper,command.c_str());
327                         return do_more;
328                 }
329         }
330         if ((user->registered == REG_ALL) && (!IS_OPER(user)) && (cm->second->IsDisabled()))
331         {
332                 /* command is disabled! */
333                 user->WriteServ("421 %s %s :This command has been disabled.",user->nick,command.c_str());
334                 ServerInstance->SNO->WriteToSnoMask('d', "%s denied for %s (%s@%s)",
335                                 command.c_str(), user->nick, user->ident, user->host);
336                 return do_more;
337         }
338         if (items < cm->second->min_params)
339         {
340                 user->WriteServ("461 %s %s :Not enough parameters.", user->nick, command.c_str());
341                 if ((ServerInstance->Config->SyntaxHints) && (user->registered == REG_ALL) && (cm->second->syntax.length()))
342                         user->WriteServ("304 %s :SYNTAX %s %s", user->nick, cm->second->command.c_str(), cm->second->syntax.c_str());
343                 return do_more;
344         }
345         if ((user->registered != REG_ALL) && (!cm->second->WorksBeforeReg()))
346         {
347                 user->WriteServ("451 %s :You have not registered",command.c_str());
348                 return do_more;
349         }
350         else
351         {
352                 /* passed all checks.. first, do the (ugly) stats counters. */
353                 cm->second->use_count++;
354                 cm->second->total_bytes += cmd.length();
355
356                 /* module calls too */
357                 MOD_RESULT = 0;
358                 FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command,command_p,items,user,true,cmd));
359                 if (MOD_RESULT == 1)
360                         return do_more;
361
362                 /*
363                  * WARNING: be careful, the user may be deleted soon
364                  */
365                 CmdResult result = cm->second->Handle(command_p,items,user);
366
367                 FOREACH_MOD(I_OnPostCommand,OnPostCommand(command, command_p, items, user, result,cmd));
368                 return do_more;
369         }
370 }
371
372 bool CommandParser::RemoveCommands(const char* source)
373 {
374         Commandable::iterator i,safei;
375         for (i = cmdlist.begin(); i != cmdlist.end(); i++)
376         {
377                 safei = i;
378                 safei++;
379                 if (safei != cmdlist.end())
380                 {
381                         RemoveCommand(safei, source);
382                 }
383         }
384         safei = cmdlist.begin();
385         if (safei != cmdlist.end())
386         {
387                 RemoveCommand(safei, source);
388         }
389         return true;
390 }
391
392 void CommandParser::RemoveCommand(Commandable::iterator safei, const char* source)
393 {
394         Command* x = safei->second;
395         if (x->source == std::string(source))
396         {
397                 cmdlist.erase(safei);
398                 delete x;
399         }
400 }
401
402 bool CommandParser::ProcessBuffer(std::string &buffer,User *user)
403 {
404         std::string::size_type a;
405
406         if (!user)
407                 return true;
408
409         while ((a = buffer.rfind("\n")) != std::string::npos)
410                 buffer.erase(a);
411         while ((a = buffer.rfind("\r")) != std::string::npos)
412                 buffer.erase(a);
413
414         if (buffer.length())
415         {
416                 ServerInstance->Logs->Log("USERINPUT", DEBUG,"C[%d] I :%s %s",user->GetFd(), user->nick, buffer.c_str());
417                 return this->ProcessCommand(user,buffer);
418         }
419
420         return true;
421 }
422
423 bool CommandParser::CreateCommand(Command *f, void* so_handle)
424 {
425         if (so_handle)
426         {
427                 if (RFCCommands.find(f->command) == RFCCommands.end())
428                         RFCCommands[f->command] = so_handle;
429                 else
430                 {
431                         ServerInstance->Log(DEFAULT,"ERK! Somehow, we loaded a cmd_*.so file twice! Only the first instance is being recorded.");
432                         return false;
433                 }
434         }
435
436         /* create the command and push it onto the table */
437         if (cmdlist.find(f->command) == cmdlist.end())
438         {
439                 cmdlist[f->command] = f;
440                 return true;
441         }
442         else return false;
443 }
444
445 CommandParser::CommandParser(InspIRCd* Instance) : ServerInstance(Instance)
446 {
447         para.resize(128);
448 }
449
450 bool CommandParser::FindSym(void** v, void* h, const std::string &name)
451 {
452         *v = dlsym(h, "init_command");
453         const char* err = dlerror();
454         if (err && !(*v))
455         {
456                 ServerInstance->Log(SPARSE, "Error loading core command %s: %s\n", name.c_str(), err);
457                 return false;
458         }
459         return true;
460 }
461
462 bool CommandParser::ReloadCommand(const char* cmd, User* user)
463 {
464         char filename[MAXBUF];
465         char commandname[MAXBUF];
466         int y = 0;
467
468         for (const char* x = cmd; *x; x++, y++)
469                 commandname[y] = toupper(*x);
470
471         commandname[y] = 0;
472
473         SharedObjectList::iterator command = RFCCommands.find(commandname);
474
475         if (command != RFCCommands.end())
476         {
477                 Command* cmdptr = cmdlist.find(commandname)->second;
478                 cmdlist.erase(cmdlist.find(commandname));
479
480                 for (char* x = commandname; *x; x++)
481                         *x = tolower(*x);
482
483
484                 delete cmdptr;
485                 dlclose(command->second);
486                 RFCCommands.erase(command);
487
488                 snprintf(filename, MAXBUF, "cmd_%s.so", commandname);
489                 const char* err = this->LoadCommand(filename);
490                 if (err)
491                 {
492                         if (user)
493                                 user->WriteServ("NOTICE %s :*** Error loading 'cmd_%s.so': %s", user->nick, cmd, err);
494                         return false;
495                 }
496
497                 return true;
498         }
499
500         return false;
501 }
502
503 CmdResult cmd_reload::Handle(const char** parameters, int /* pcnt */, User *user)
504 {
505         user->WriteServ("NOTICE %s :*** Reloading command '%s'",user->nick, parameters[0]);
506         if (ServerInstance->Parser->ReloadCommand(parameters[0], user))
507         {
508                 user->WriteServ("NOTICE %s :*** Successfully reloaded command '%s'", user->nick, parameters[0]);
509                 ServerInstance->SNO->WriteToSnoMask('A', "RELOAD: %s reloaded the '%s' command.", user->nick, parameters[0]);
510                 return CMD_SUCCESS;
511         }
512         else
513         {
514                 user->WriteServ("NOTICE %s :*** Could not reload command '%s' -- fix this problem, then /REHASH as soon as possible!", user->nick, parameters[0]);
515                 return CMD_FAILURE;
516         }
517 }
518
519 const char* CommandParser::LoadCommand(const char* name)
520 {
521         char filename[MAXBUF];
522         void* h;
523         Command* (*cmd_factory_func)(InspIRCd*);
524
525         /* Command already exists? Succeed silently - this is needed for REHASH */
526         if (RFCCommands.find(name) != RFCCommands.end())
527         {
528                 ServerInstance->Log(DEBUG,"Not reloading command %s/%s, it already exists", LIBRARYDIR, name);
529                 return NULL;
530         }
531
532         snprintf(filename, MAXBUF, "%s/%s", LIBRARYDIR, name);
533         h = dlopen(filename, RTLD_NOW | RTLD_GLOBAL);
534
535         if (!h)
536         {
537                 const char* n = dlerror();
538                 ServerInstance->Log(SPARSE, "Error loading core command %s: %s", name, n);
539                 return n;
540         }
541
542         if (this->FindSym((void **)&cmd_factory_func, h, name))
543         {
544                 Command* newcommand = cmd_factory_func(ServerInstance);
545                 this->CreateCommand(newcommand, h);
546         }
547         return NULL;
548 }
549
550 void CommandParser::SetupCommandTable(User* user)
551 {
552         RFCCommands.clear();
553
554         if (!user)
555         {
556                 printf("\nLoading core commands");
557                 fflush(stdout);
558         }
559
560         DIR* library = opendir(LIBRARYDIR);
561         if (library)
562         {
563                 dirent* entry = NULL;
564                 while ((entry = readdir(library)))
565                 {
566                         if (match(entry->d_name, "cmd_*.so"))
567                         {
568                                 if (!user)
569                                 {
570                                         printf(".");
571                                         fflush(stdout);
572                                 }
573                                 const char* err = this->LoadCommand(entry->d_name);
574                                 if (err)
575                                 {
576                                         if (user)
577                                         {
578                                                 user->WriteServ("NOTICE %s :*** Failed to load core command %s: %s", user->nick, entry->d_name, err);
579                                         }
580                                         else
581                                         {
582                                                 printf("Error loading %s: %s", entry->d_name, err);
583                                                 exit(EXIT_STATUS_BADHANDLER);
584                                         }
585                                 }
586                         }
587                 }
588                 closedir(library);
589                 if (!user)
590                         printf("\n");
591         }
592
593         if (cmdlist.find("RELOAD") == cmdlist.end())
594                 this->CreateCommand(new cmd_reload(ServerInstance));
595 }
596
597 int CommandParser::TranslateUIDs(TranslateType to, const std::string &source, std::string &dest)
598 {
599         User* user = NULL;
600         std::string item;
601         int translations = 0;
602         dest.clear();
603
604         switch (to)
605         {
606                 case TR_NICK:
607                         /* Translate single nickname */
608                         user = ServerInstance->FindNick(source);
609                         if (user)
610                         {
611                                 dest = user->uuid;
612                                 translations++;
613                         }
614                         else
615                                 dest = source;
616                 break;
617                 case TR_NICKLIST:
618                 {
619                         /* Translate comma seperated list of nicknames */
620                         irc::commasepstream items(source);
621                         while (items.GetToken(item))
622                         {
623                                 user = ServerInstance->FindNick(item);
624                                 if (user)
625                                 {
626                                         dest.append(user->uuid);
627                                         translations++;
628                                 }
629                                 else
630                                         dest.append(item);
631                                 dest.append(",");
632                         }
633                         if (!dest.empty())
634                                 dest.erase(dest.end() - 1);
635                 }
636                 break;
637                 case TR_SPACENICKLIST:
638                 {
639                         /* Translate space seperated list of nicknames */
640                         irc::spacesepstream items(source);
641                         while (items.GetToken(item))
642                         {
643                                 user = ServerInstance->FindNick(item);
644                                 if (user)
645                                 {
646                                         dest.append(user->uuid);
647                                         translations++;
648                                 }
649                                 else
650                                         dest.append(item);
651                                 dest.append(" ");
652                         }
653                         if (!dest.empty())
654                                 dest.erase(dest.end() - 1);
655                 }
656                 break;
657                 case TR_END:
658                 case TR_TEXT:
659                 default:
660                         /* Do nothing */
661                         dest = source;
662                 break;
663         }
664
665         return translations;
666 }
667