]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/command_parse.cpp
Add support for blacklists and whitelists, just http password auth to go (the most...
[user/henk/code/inspircd.git] / src / command_parse.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2008 InspIRCd Development Team
6  * See: http://www.inspircd.org/wiki/index.php/Credits
7  *
8  * This program is free but copyrighted software; see
9  *          the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 /* $Core: libIRCDcommand_parse */
15
16 #include "inspircd.h"
17 #include "wildcard.h"
18 #include "xline.h"
19 #include "socketengine.h"
20 #include "socket.h"
21 #include "command_parse.h"
22 #include "exitcodes.h"
23
24 /* Directory Searching for Unix-Only */
25 #ifndef WIN32
26 #include <dirent.h>
27 #include <dlfcn.h>
28 #endif
29
30 int InspIRCd::PassCompare(Extensible* ex, const char* data,const char* input, const char* hashtype)
31 {
32         int MOD_RESULT = 0;
33         FOREACH_RESULT_I(this,I_OnPassCompare,OnPassCompare(ex, data, input, hashtype))
34         if (MOD_RESULT == 1)
35                 return 0;
36         if (MOD_RESULT == -1)
37                 return 1;
38         return strcmp(data,input);
39 }
40
41 /* LoopCall is used to call a command classes handler repeatedly based on the contents of a comma seperated list.
42  * There are two overriden versions of this method, one of which takes two potential lists and the other takes one.
43  * We need a version which takes two potential lists for JOIN, because a JOIN may contain two lists of items at once,
44  * the channel names and their keys as follows:
45  * JOIN #chan1,#chan2,#chan3 key1,,key3
46  * Therefore, we need to deal with both lists concurrently. The first instance of this method does that by creating
47  * two instances of irc::commasepstream and reading them both together until the first runs out of tokens.
48  * The second version is much simpler and just has the one stream to read, and is used in NAMES, WHOIS, PRIVMSG etc.
49  * Both will only parse until they reach ServerInstance->Config->MaxTargets number of targets, to stop abuse via spam.
50  */
51 int CommandParser::LoopCall(User* user, Command* CommandObj, const std::vector<std::string>& parameters, unsigned int splithere, unsigned int extra)
52 {
53         if (splithere >= parameters.size())
54                 return 0;
55
56         /* First check if we have more than one item in the list, if we don't we return zero here and the handler
57          * which called us just carries on as it was.
58          */
59         if (parameters[splithere].find(',') == std::string::npos)
60                 return 0;
61
62         /** Some lame ircds will weed out dupes using some shitty O(n^2) algorithm.
63          * By using std::map (thanks for the idea w00t) we can cut this down a ton.
64          * ...VOOODOOOO!
65          */
66         std::map<irc::string, bool> dupes;
67
68         /* Create two lists, one for channel names, one for keys
69          */
70         irc::commasepstream items1(parameters[splithere]);
71         irc::commasepstream items2(parameters[extra]);
72         std::string extrastuff;
73         std::string item;
74         unsigned int max = 0;
75
76         /* Attempt to iterate these lists and call the command objech
77          * which called us, for every parameter pair until there are
78          * no more left to parse.
79          */
80         while (items1.GetToken(item) && (max++ < ServerInstance->Config->MaxTargets))
81         {
82                 if (dupes.find(item.c_str()) == dupes.end())
83                 {
84                         std::vector<std::string> new_parameters;
85
86                         for (unsigned int t = 0; (t < parameters.size()) && (t < MAXPARAMETERS); t++)
87                                 new_parameters.push_back(parameters[t]);
88
89                         if (!items2.GetToken(extrastuff))
90                                 extrastuff = "";
91
92                         new_parameters[splithere] = item.c_str();
93                         new_parameters[extra] = extrastuff.c_str();
94
95                         CommandObj->Handle(new_parameters, user);
96
97                         dupes[item.c_str()] = true;
98                 }
99         }
100         return 1;
101 }
102
103 int CommandParser::LoopCall(User* user, Command* CommandObj, const std::vector<std::string>& parameters, unsigned int splithere)
104 {
105         if (splithere >= parameters.size())
106                 return 0;
107
108         /* First check if we have more than one item in the list, if we don't we return zero here and the handler
109          * which called us just carries on as it was.
110          */
111         if (parameters[splithere].find(',') == std::string::npos)
112                 return 0;
113
114         std::map<irc::string, bool> dupes;
115
116         /* Only one commasepstream here */
117         irc::commasepstream items1(parameters[splithere]);
118         std::string item;
119         unsigned int max = 0;
120
121         /* Parse the commasepstream until there are no tokens remaining.
122          * Each token we parse out, call the command handler that called us
123          * with it
124          */
125         while (items1.GetToken(item) && (max++ < ServerInstance->Config->MaxTargets))
126         {
127                 if (dupes.find(item.c_str()) == dupes.end())
128                 {
129                         std::vector<std::string> new_parameters;
130
131                         for (unsigned int t = 0; (t < parameters.size()) && (t < MAXPARAMETERS); t++)
132                                 new_parameters.push_back(parameters[t]);
133
134                         new_parameters[splithere] = item.c_str();
135
136                         /* Execute the command handler over and over. If someone pulls our user
137                          * record out from under us (e.g. if we /kill a comma sep list, and we're
138                          * in that list ourselves) abort if we're gone.
139                          */
140                         CommandObj->Handle(new_parameters, user);
141
142                         dupes[item.c_str()] = true;
143                 }
144         }
145         /* By returning 1 we tell our caller that nothing is to be done,
146          * as all the previous calls handled the data. This makes the parent
147          * return without doing any processing.
148          */
149         return 1;
150 }
151
152 bool CommandParser::IsValidCommand(const std::string &commandname, unsigned int pcnt, User * user)
153 {
154         Commandable::iterator n = cmdlist.find(commandname);
155
156         if (n != cmdlist.end())
157         {
158                 if ((pcnt >= n->second->min_params) && (n->second->source != "<core>"))
159                 {
160                         if (IS_LOCAL(user) && n->second->flags_needed)
161                         {
162                                 if (user->IsModeSet(n->second->flags_needed))
163                                 {
164                                         return (user->HasPermission(commandname));
165                                 }
166                         }
167                         else
168                         {
169                                 return true;
170                         }
171                 }
172         }
173         return false;
174 }
175
176 Command* CommandParser::GetHandler(const std::string &commandname)
177 {
178         Commandable::iterator n = cmdlist.find(commandname);
179         if (n != cmdlist.end())
180                 return n->second;
181
182         return NULL;
183 }
184
185 // calls a handler function for a command
186
187 CmdResult CommandParser::CallHandler(const std::string &commandname, const std::vector<std::string>& parameters, User *user)
188 {
189         Commandable::iterator n = cmdlist.find(commandname);
190
191         if (n != cmdlist.end())
192         {
193                 if (parameters.size() >= n->second->min_params)
194                 {
195                         bool bOkay = false;
196
197                         if (IS_LOCAL(user) && n->second->flags_needed)
198                         {
199                                 /* if user is local, and flags are needed .. */
200
201                                 if (user->IsModeSet(n->second->flags_needed))
202                                 {
203                                         /* if user has the flags, and now has the permissions, go ahead */
204                                         if (user->HasPermission(commandname))
205                                                 bOkay = true;
206                                 }
207                         }
208                         else
209                         {
210                                 /* remote or no flags required anyway */
211                                 bOkay = true;
212                         }
213
214                         if (bOkay)
215                         {
216                                 return n->second->Handle(parameters,user);
217                         }
218                 }
219         }
220         return CMD_INVALID;
221 }
222
223 void CommandParser::DoLines(User* current, bool one_only)
224 {
225         // while there are complete lines to process...
226         unsigned int floodlines = 0;
227
228         while (current->BufferIsReady())
229         {
230                 if (current->MyClass)
231                 {
232                         if (ServerInstance->Time() > current->reset_due)
233                         {
234                                 current->reset_due = ServerInstance->Time() + current->MyClass->GetThreshold();
235                                 current->lines_in = 0;
236                         }
237
238                         if (++current->lines_in > current->MyClass->GetFlood() && current->MyClass->GetFlood())
239                         {
240                                 ServerInstance->FloodQuitUser(current);
241                                 return;
242                         }
243
244                         if ((++floodlines > current->MyClass->GetFlood()) && (current->MyClass->GetFlood() != 0))
245                         {
246                                 ServerInstance->FloodQuitUser(current);
247                                 return;
248                         }
249                 }
250
251                 // use GetBuffer to copy single lines into the sanitized string
252                 std::string single_line = current->GetBuffer();
253                 current->bytes_in += single_line.length();
254                 current->cmds_in++;
255                 if (single_line.length() > MAXBUF - 2)  // MAXBUF is 514 to allow for neccessary line terminators
256                         single_line.resize(MAXBUF - 2); // So to trim to 512 here, we use MAXBUF - 2
257
258                 // ProcessBuffer returns false if the user has gone over penalty
259                 if (!ServerInstance->Parser->ProcessBuffer(single_line, current) || one_only)
260                         break;
261         }
262 }
263
264 bool CommandParser::ProcessCommand(User *user, std::string &cmd)
265 {
266         std::vector<std::string> command_p;
267         irc::tokenstream tokens(cmd);
268         std::string command, token;
269         tokens.GetToken(command);
270
271         /* A client sent a nick prefix on their command (ick)
272          * rhapsody and some braindead bouncers do this --
273          * the rfc says they shouldnt but also says the ircd should
274          * discard it if they do.
275          */
276         if (command[0] == ':')
277                 tokens.GetToken(command);
278
279         while (tokens.GetToken(token) && (command_p.size() <= MAXPARAMETERS))
280                 command_p.push_back(token);
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, 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->WriteNumeric(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->WriteNumeric(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->WriteNumeric(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->WriteNumeric(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 (command_p.size() < cm->second->min_params)
339         {
340                 user->WriteNumeric(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->WriteNumeric(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->WriteNumeric(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, 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, user);
366
367                 FOREACH_MOD(I_OnPostCommand,OnPostCommand(command, command_p, user, result,cmd));
368                 return do_more;
369         }
370 }
371
372 void CommandParser::RemoveCommands(const char* source)
373 {
374         Commandable::iterator i,safei;
375         for (i = cmdlist.begin(); i != cmdlist.end();)
376         {
377                 safei = i;
378                 i++;
379                 RemoveCommand(safei, source);
380         }
381 }
382
383 void CommandParser::RemoveCommand(Commandable::iterator safei, const char* source)
384 {
385         Command* x = safei->second;
386         if (x->source == std::string(source))
387         {
388                 cmdlist.erase(safei);
389                 delete x;
390         }
391 }
392
393 bool CommandParser::ProcessBuffer(std::string &buffer,User *user)
394 {
395         std::string::size_type a;
396
397         if (!user)
398                 return true;
399
400         while ((a = buffer.rfind("\n")) != std::string::npos)
401                 buffer.erase(a);
402         while ((a = buffer.rfind("\r")) != std::string::npos)
403                 buffer.erase(a);
404
405         if (buffer.length())
406         {
407                 ServerInstance->Logs->Log("USERINPUT", DEBUG,"C[%d] I :%s %s",user->GetFd(), user->nick, buffer.c_str());
408                 return this->ProcessCommand(user,buffer);
409         }
410
411         return true;
412 }
413
414 bool CommandParser::CreateCommand(Command *f, void* so_handle)
415 {
416         if (so_handle)
417         {
418                 if (RFCCommands.find(f->command) == RFCCommands.end())
419                         RFCCommands[f->command] = so_handle;
420                 else
421                 {
422                         ServerInstance->Logs->Log("COMMAND",DEFAULT,"ERK! Somehow, we loaded a cmd_*.so file twice! Only the first instance is being recorded.");
423                         return false;
424                 }
425         }
426
427         /* create the command and push it onto the table */
428         if (cmdlist.find(f->command) == cmdlist.end())
429         {
430                 cmdlist[f->command] = f;
431                 return true;
432         }
433         else return false;
434 }
435
436 CommandParser::CommandParser(InspIRCd* Instance) : ServerInstance(Instance)
437 {
438         para.resize(128);
439 }
440
441 bool CommandParser::FindSym(void** v, void* h, const std::string &name)
442 {
443         *v = dlsym(h, "init_command");
444         const char* err = dlerror();
445         if (err && !(*v))
446         {
447                 ServerInstance->Logs->Log("COMMAND",SPARSE, "Error loading core command %s: %s\n", name.c_str(), err);
448                 return false;
449         }
450         return true;
451 }
452
453 bool CommandParser::ReloadCommand(std::string cmd, User* user)
454 {
455         char filename[MAXBUF];
456         std::transform(cmd.begin(), cmd.end(), cmd.begin(), ::toupper);
457
458         SharedObjectList::iterator command = RFCCommands.find(cmd);
459
460         if (command != RFCCommands.end())
461         {
462                 Command* cmdptr = cmdlist.find(cmd)->second;
463                 cmdlist.erase(cmdlist.find(cmd));
464
465                 RFCCommands.erase(cmd);
466                 std::transform(cmd.begin(), cmd.end(), cmd.begin(), ::tolower);
467                 delete cmdptr;
468                 dlclose(command->second);
469
470                 snprintf(filename, MAXBUF, "cmd_%s.so", cmd.c_str());
471                 const char* err = this->LoadCommand(filename);
472                 if (err)
473                 {
474                         if (user)
475                                 user->WriteServ("NOTICE %s :*** Error loading 'cmd_%s.so': %s", user->nick, cmd.c_str(), err);
476                         return false;
477                 }
478
479                 return true;
480         }
481
482         return false;
483 }
484
485 CmdResult cmd_reload::Handle(const std::vector<std::string>& parameters, User *user)
486 {
487         if (parameters.size() < 1)
488                 return CMD_FAILURE;
489
490         user->WriteServ("NOTICE %s :*** Reloading command '%s'",user->nick, parameters[0].c_str());
491         if (ServerInstance->Parser->ReloadCommand(parameters[0], user))
492         {
493                 user->WriteServ("NOTICE %s :*** Successfully reloaded command '%s'", user->nick, parameters[0].c_str());
494                 ServerInstance->SNO->WriteToSnoMask('A', "RELOAD: %s reloaded the '%s' command.", user->nick, parameters[0].c_str());
495                 return CMD_SUCCESS;
496         }
497         else
498         {
499                 user->WriteServ("NOTICE %s :*** Could not reload command '%s' -- fix this problem, then /REHASH as soon as possible!", user->nick, parameters[0].c_str());
500                 return CMD_FAILURE;
501         }
502 }
503
504 const char* CommandParser::LoadCommand(const char* name)
505 {
506         char filename[MAXBUF];
507         void* h;
508         Command* (*cmd_factory_func)(InspIRCd*);
509
510         /* Command already exists? Succeed silently - this is needed for REHASH */
511         if (RFCCommands.find(name) != RFCCommands.end())
512         {
513                 ServerInstance->Logs->Log("COMMAND",DEBUG,"Not reloading command %s/%s, it already exists", LIBRARYDIR, name);
514                 return NULL;
515         }
516
517         snprintf(filename, MAXBUF, "%s/%s", LIBRARYDIR, name);
518         h = dlopen(filename, RTLD_NOW | RTLD_GLOBAL);
519
520         if (!h)
521         {
522                 const char* n = dlerror();
523                 ServerInstance->Logs->Log("COMMAND",SPARSE, "Error loading core command %s: %s", name, n);
524                 return n;
525         }
526
527         if (this->FindSym((void **)&cmd_factory_func, h, name))
528         {
529                 Command* newcommand = cmd_factory_func(ServerInstance);
530                 this->CreateCommand(newcommand, h);
531         }
532         return NULL;
533 }
534
535 void CommandParser::SetupCommandTable(User* user)
536 {
537         RFCCommands.clear();
538
539         if (!user)
540         {
541                 printf("\nLoading core commands");
542                 fflush(stdout);
543         }
544
545         DIR* library = opendir(LIBRARYDIR);
546         if (library)
547         {
548                 dirent* entry = NULL;
549                 while (0 != (entry = readdir(library)))
550                 {
551                         if (match(entry->d_name, "cmd_*.so"))
552                         {
553                                 if (!user)
554                                 {
555                                         printf(".");
556                                         fflush(stdout);
557                                 }
558                                 const char* err = this->LoadCommand(entry->d_name);
559                                 if (err)
560                                 {
561                                         if (user)
562                                         {
563                                                 user->WriteServ("NOTICE %s :*** Failed to load core command %s: %s", user->nick, entry->d_name, err);
564                                         }
565                                         else
566                                         {
567                                                 printf("Error loading %s: %s", entry->d_name, err);
568                                                 exit(EXIT_STATUS_BADHANDLER);
569                                         }
570                                 }
571                         }
572                 }
573                 closedir(library);
574                 if (!user)
575                         printf("\n");
576         }
577
578         if (cmdlist.find("RELOAD") == cmdlist.end())
579                 this->CreateCommand(new cmd_reload(ServerInstance));
580 }
581
582 int CommandParser::TranslateUIDs(TranslateType to, const std::string &source, std::string &dest)
583 {
584         User* user = NULL;
585         std::string item;
586         int translations = 0;
587         dest.clear();
588
589         switch (to)
590         {
591                 case TR_NICK:
592                         /* Translate single nickname */
593                         user = ServerInstance->FindNick(source);
594                         if (user)
595                         {
596                                 dest = user->uuid;
597                                 translations++;
598                         }
599                         else
600                                 dest = source;
601                 break;
602                 case TR_NICKLIST:
603                 {
604                         /* Translate comma seperated list of nicknames */
605                         irc::commasepstream items(source);
606                         while (items.GetToken(item))
607                         {
608                                 user = ServerInstance->FindNick(item);
609                                 if (user)
610                                 {
611                                         dest.append(user->uuid);
612                                         translations++;
613                                 }
614                                 else
615                                         dest.append(item);
616                                 dest.append(",");
617                         }
618                         if (!dest.empty())
619                                 dest.erase(dest.end() - 1);
620                 }
621                 break;
622                 case TR_SPACENICKLIST:
623                 {
624                         /* Translate space seperated list of nicknames */
625                         irc::spacesepstream items(source);
626                         while (items.GetToken(item))
627                         {
628                                 user = ServerInstance->FindNick(item);
629                                 if (user)
630                                 {
631                                         dest.append(user->uuid);
632                                         translations++;
633                                 }
634                                 else
635                                         dest.append(item);
636                                 dest.append(" ");
637                         }
638                         if (!dest.empty())
639                                 dest.erase(dest.end() - 1);
640                 }
641                 break;
642                 case TR_END:
643                 case TR_TEXT:
644                 default:
645                         /* Do nothing */
646                         dest = source;
647                 break;
648         }
649
650         return translations;
651 }
652
653