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