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