]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/command_parse.cpp
9a525dd5b360148c8a869ba3948799bb01bd7205
[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 bool InspIRCd::ULine(const char* server)
29 {
30         if (!server)
31                 return false;
32         if (!*server)
33                 return true;
34
35         return (Config->ulines.find(server) != Config->ulines.end());
36 }
37
38 bool InspIRCd::SilentULine(const char* server)
39 {
40         std::map<irc::string,bool>::iterator n = Config->ulines.find(server);
41         if (n != Config->ulines.end())
42                 return n->second;
43         else return false;
44 }
45
46 int InspIRCd::OperPassCompare(const char* data,const char* input, int tagnumber)
47 {
48         int MOD_RESULT = 0;
49         FOREACH_RESULT_I(this,I_OnOperCompare,OnOperCompare(data, input, tagnumber))
50         if (MOD_RESULT == 1)
51                 return 0;
52         if (MOD_RESULT == -1)
53                 return 1;
54         return strcmp(data,input);
55 }
56
57 std::string InspIRCd::TimeString(time_t curtime)
58 {
59         return std::string(ctime(&curtime),24);
60 }
61
62 /* LoopCall is used to call a command classes handler repeatedly based on the contents of a comma seperated list.
63  * There are two overriden versions of this method, one of which takes two potential lists and the other takes one.
64  * We need a version which takes two potential lists for JOIN, because a JOIN may contain two lists of items at once,
65  * the channel names and their keys as follows:
66  * JOIN #chan1,#chan2,#chan3 key1,,key3
67  * Therefore, we need to deal with both lists concurrently. The first instance of this method does that by creating
68  * two instances of irc::commasepstream and reading them both together until the first runs out of tokens.
69  * The second version is much simpler and just has the one stream to read, and is used in NAMES, WHOIS, PRIVMSG etc.
70  * Both will only parse until they reach ServerInstance->Config->MaxTargets number of targets, to stop abuse via spam.
71  */
72 int CommandParser::LoopCall(User* user, Command* CommandObj, const char** parameters, int pcnt, unsigned int splithere, unsigned int extra)
73 {
74         /* First check if we have more than one item in the list, if we don't we return zero here and the handler
75          * which called us just carries on as it was.
76          */
77         if (!strchr(parameters[splithere],','))
78                 return 0;
79
80         /** Some lame ircds will weed out dupes using some shitty O(n^2) algorithm.
81          * By using std::map (thanks for the idea w00t) we can cut this down a ton.
82          * ...VOOODOOOO!
83          */
84         std::map<irc::string, bool> dupes;
85
86         /* Create two lists, one for channel names, one for keys
87          */
88         irc::commasepstream items1(parameters[splithere]);
89         irc::commasepstream items2(parameters[extra]);
90         std::string extrastuff;
91         std::string item;
92         unsigned int max = 0;
93
94         /* Attempt to iterate these lists and call the command objech
95          * which called us, for every parameter pair until there are
96          * no more left to parse.
97          */
98         while (items1.GetToken(item) && (max++ < ServerInstance->Config->MaxTargets))
99         {
100                 if (dupes.find(item.c_str()) == dupes.end())
101                 {
102                         const char* new_parameters[MAXPARAMETERS];
103
104                         for (int t = 0; (t < pcnt) && (t < MAXPARAMETERS); t++)
105                                 new_parameters[t] = parameters[t];
106
107                         if (!items2.GetToken(extrastuff))
108                                 extrastuff = "";
109
110                         new_parameters[splithere] = item.c_str();
111                         new_parameters[extra] = extrastuff.c_str();
112
113                         CommandObj->Handle(new_parameters,pcnt,user);
114
115                         dupes[item.c_str()] = true;
116                 }
117         }
118         return 1;
119 }
120
121 int CommandParser::LoopCall(User* user, Command* CommandObj, const char** parameters, int pcnt, unsigned int splithere)
122 {
123         /* First check if we have more than one item in the list, if we don't we return zero here and the handler
124          * which called us just carries on as it was.
125          */
126         if (!strchr(parameters[splithere],','))
127                 return 0;
128
129         std::map<irc::string, bool> dupes;
130
131         /* Only one commasepstream here */
132         irc::commasepstream items1(parameters[splithere]);
133         std::string item;
134         unsigned int max = 0;
135
136         /* Parse the commasepstream until there are no tokens remaining.
137          * Each token we parse out, call the command handler that called us
138          * with it
139          */
140         while (items1.GetToken(item) && (max++ < ServerInstance->Config->MaxTargets))
141         {
142                 if (dupes.find(item.c_str()) == dupes.end())
143                 {
144                         const char* new_parameters[MAXPARAMETERS];
145
146                         for (int t = 0; (t < pcnt) && (t < MAXPARAMETERS); t++)
147                                 new_parameters[t] = parameters[t];
148
149                         new_parameters[splithere] = item.c_str();
150
151                         parameters[splithere] = item.c_str();
152
153                         /* Execute the command handler over and over. If someone pulls our user
154                          * record out from under us (e.g. if we /kill a comma sep list, and we're
155                          * in that list ourselves) abort if we're gone.
156                          */
157                         CommandObj->Handle(new_parameters,pcnt,user);
158
159                         dupes[item.c_str()] = true;
160                 }
161         }
162         /* By returning 1 we tell our caller that nothing is to be done,
163          * as all the previous calls handled the data. This makes the parent
164          * return without doing any processing.
165          */
166         return 1;
167 }
168
169 bool CommandParser::IsValidCommand(const std::string &commandname, int pcnt, User * user)
170 {
171         Commandable::iterator n = cmdlist.find(commandname);
172
173         if (n != cmdlist.end())
174         {
175                 if ((pcnt>=n->second->min_params) && (n->second->source != "<core>"))
176                 {
177                         if (IS_LOCAL(user) && n->second->flags_needed)
178                         {
179                                 if (user->IsModeSet(n->second->flags_needed))
180                                 {
181                                         return (user->HasPermission(commandname));
182                                 }
183                         }
184                         else
185                         {
186                                 return true;
187                         }
188                 }
189         }
190         return false;
191 }
192
193 Command* CommandParser::GetHandler(const std::string &commandname)
194 {
195         Commandable::iterator n = cmdlist.find(commandname);
196         if (n != cmdlist.end())
197                 return n->second;
198
199         return NULL;
200 }
201
202 // calls a handler function for a command
203
204 CmdResult CommandParser::CallHandler(const std::string &commandname,const char** parameters, int pcnt, User *user)
205 {
206         Commandable::iterator n = cmdlist.find(commandname);
207
208         if (n != cmdlist.end())
209         {
210                 if (pcnt >= n->second->min_params)
211                 {
212                         bool bOkay = false;
213
214                         if (IS_LOCAL(user) && n->second->flags_needed)
215                         {
216                                 /* if user is local, and flags are needed .. */
217
218                                 if (user->IsModeSet(n->second->flags_needed))
219                                 {
220                                         /* if user has the flags, and now has the permissions, go ahead */
221                                         if (user->HasPermission(commandname))
222                                                 bOkay = true;
223                                 }
224                         }
225                         else
226                         {
227                                 /* remote or no flags required anyway */
228                                 bOkay = true;
229                         }
230
231                         if (bOkay)
232                         {
233                                 return n->second->Handle(parameters,pcnt,user);
234                         }
235                 }
236         }
237         return CMD_INVALID;
238 }
239
240 void CommandParser::ProcessCommand(User *user, std::string &cmd)
241 {
242         const char *command_p[MAXPARAMETERS];
243         int items = 0;
244         irc::tokenstream tokens(cmd);
245         std::string command;
246         tokens.GetToken(command);
247
248         /* A client sent a nick prefix on their command (ick)
249          * rhapsody and some braindead bouncers do this --
250          * the rfc says they shouldnt but also says the ircd should
251          * discard it if they do.
252          */
253         if (*command.c_str() == ':')
254                 tokens.GetToken(command);
255
256         while (tokens.GetToken(para[items]) && (items < MAXPARAMETERS))
257         {
258                 command_p[items] = para[items].c_str();
259                 items++;
260         }
261
262         std::transform(command.begin(), command.end(), command.begin(), ::toupper);
263                 
264         int MOD_RESULT = 0;
265         FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command,command_p,items,user,false,cmd));
266         if (MOD_RESULT == 1) {
267                 return;
268         }
269
270         Commandable::iterator cm = cmdlist.find(command);
271         
272         if (cm != cmdlist.end())
273         {
274                 if (user)
275                 {
276                         /* activity resets the ping pending timer */
277                         user->nping = ServerInstance->Time() + user->pingmax;
278                         if (cm->second->flags_needed)
279                         {
280                                 if (!user->IsModeSet(cm->second->flags_needed))
281                                 {
282                                         user->WriteServ("481 %s :Permission Denied - You do not have the required operator privileges",user->nick);
283                                         return;
284                                 }
285                                 if (!user->HasPermission(command))
286                                 {
287                                         user->WriteServ("481 %s :Permission Denied - Oper type %s does not have access to command %s",user->nick,user->oper,command.c_str());
288                                         return;
289                                 }
290                         }
291                         if ((user->registered == REG_ALL) && (!IS_OPER(user)) && (cm->second->IsDisabled()))
292                         {
293                                 /* command is disabled! */
294                                 user->WriteServ("421 %s %s :This command has been disabled.",user->nick,command.c_str());
295                                 ServerInstance->SNO->WriteToSnoMask('d', "%s denied for %s (%s@%s)",
296                                                 command.c_str(), user->nick, user->ident, user->host);
297                                 return;
298                         }
299                         if (items < cm->second->min_params)
300                         {
301                                 user->WriteServ("461 %s %s :Not enough parameters.", user->nick, command.c_str());
302                                 if ((ServerInstance->Config->SyntaxHints) && (user->registered == REG_ALL) && (cm->second->syntax.length()))
303                                         user->WriteServ("304 %s :SYNTAX %s %s", user->nick, cm->second->command.c_str(), cm->second->syntax.c_str());
304                                 return;
305                         }
306                         if ((user->registered == REG_ALL) || (cm->second->WorksBeforeReg()))
307                         {
308                                 /* ikky /stats counters */
309                                 cm->second->use_count++;
310                                 cm->second->total_bytes += cmd.length();
311
312                                 int MOD_RESULT = 0;
313                                 FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command,command_p,items,user,true,cmd));
314                                 if (MOD_RESULT == 1)
315                                         return;
316
317                                 /*
318                                  * WARNING: be careful, the user may be deleted soon
319                                  */
320                                 CmdResult result = cm->second->Handle(command_p,items,user);
321
322                                 FOREACH_MOD(I_OnPostCommand,OnPostCommand(command, command_p, items, user, result,cmd));
323                                 return;
324                         }
325                         else
326                         {
327                                 user->WriteServ("451 %s :You have not registered",command.c_str());
328                                 return;
329                         }
330                 }
331         }
332         else if (user)
333         {
334                 ServerInstance->stats->statsUnknown++;
335                 user->WriteServ("421 %s %s :Unknown command",user->nick,command.c_str());
336         }
337 }
338
339 bool CommandParser::RemoveCommands(const char* source)
340 {
341         Commandable::iterator i,safei;
342         for (i = cmdlist.begin(); i != cmdlist.end(); i++)
343         {
344                 safei = i;
345                 safei++;
346                 if (safei != cmdlist.end())
347                 {
348                         RemoveCommand(safei, source);
349                 }
350         }
351         safei = cmdlist.begin();
352         if (safei != cmdlist.end())
353         {
354                 RemoveCommand(safei, source);
355         }
356         return true;
357 }
358
359 void CommandParser::RemoveCommand(Commandable::iterator safei, const char* source)
360 {
361         Command* x = safei->second;
362         if (x->source == std::string(source))
363         {
364                 cmdlist.erase(safei);
365                 delete x;
366         }
367 }
368
369 void CommandParser::ProcessBuffer(std::string &buffer,User *user)
370 {
371         std::string::size_type a;
372
373         if (!user)
374                 return;
375
376         while ((a = buffer.rfind("\n")) != std::string::npos)
377                 buffer.erase(a);
378         while ((a = buffer.rfind("\r")) != std::string::npos)
379                 buffer.erase(a);
380
381         if (buffer.length())
382         {
383                 if (!user->muted)
384                 {
385                         ServerInstance->Log(DEBUG,"C[%d] I :%s %s",user->GetFd(), user->nick, buffer.c_str());
386                         this->ProcessCommand(user,buffer);
387                 }
388         }
389 }
390
391 bool CommandParser::CreateCommand(Command *f, void* so_handle)
392 {
393         if (so_handle)
394         {
395                 if (RFCCommands.find(f->command) == RFCCommands.end())
396                         RFCCommands[f->command] = so_handle;
397                 else
398                 {
399                         ServerInstance->Log(DEFAULT,"ERK! Somehow, we loaded a cmd_*.so file twice! Only the first instance is being recorded.");
400                         return false;
401                 }
402         }
403
404         /* create the command and push it onto the table */
405         if (cmdlist.find(f->command) == cmdlist.end())
406         {
407                 cmdlist[f->command] = f;
408                 return true;
409         }
410         else return false;
411 }
412
413 CommandParser::CommandParser(InspIRCd* Instance) : ServerInstance(Instance)
414 {
415         para.resize(128);
416 }
417
418 bool CommandParser::FindSym(void** v, void* h, const std::string &name)
419 {
420         *v = dlsym(h, "init_command");
421         const char* err = dlerror();
422         if (err && !(*v))
423         {
424                 ServerInstance->Log(SPARSE, "Error loading core command %s: %s\n", name.c_str(), err);
425                 return false;
426         }
427         return true;
428 }
429
430 bool CommandParser::ReloadCommand(const char* cmd, User* user)
431 {
432         char filename[MAXBUF];
433         char commandname[MAXBUF];
434         int y = 0;
435
436         for (const char* x = cmd; *x; x++, y++)
437                 commandname[y] = toupper(*x);
438
439         commandname[y] = 0;
440
441         SharedObjectList::iterator command = RFCCommands.find(commandname);
442
443         if (command != RFCCommands.end())
444         {
445                 Command* cmdptr = cmdlist.find(commandname)->second;
446                 cmdlist.erase(cmdlist.find(commandname));
447
448                 for (char* x = commandname; *x; x++)
449                         *x = tolower(*x);
450
451
452                 delete cmdptr;
453                 dlclose(command->second);
454                 RFCCommands.erase(command);
455
456                 snprintf(filename, MAXBUF, "cmd_%s.so", commandname);
457                 const char* err = this->LoadCommand(filename);
458                 if (err)
459                 {
460                         if (user)
461                                 user->WriteServ("NOTICE %s :*** Error loading 'cmd_%s.so': %s", user->nick, cmd, err);
462                         return false;
463                 }
464
465                 return true;
466         }
467
468         return false;
469 }
470
471 CmdResult cmd_reload::Handle(const char** parameters, int pcnt, User *user)
472 {
473         user->WriteServ("NOTICE %s :*** Reloading command '%s'",user->nick, parameters[0]);
474         if (ServerInstance->Parser->ReloadCommand(parameters[0], user))
475         {
476                 user->WriteServ("NOTICE %s :*** Successfully reloaded command '%s'", user->nick, parameters[0]);
477                 ServerInstance->WriteOpers("*** RELOAD: %s reloaded the '%s' command.", user->nick, parameters[0]);
478                 return CMD_SUCCESS;
479         }
480         else
481         {
482                 user->WriteServ("NOTICE %s :*** Could not reload command '%s' -- fix this problem, then /REHASH as soon as possible!", user->nick, parameters[0]);
483                 return CMD_FAILURE;
484         }
485 }
486
487 const char* CommandParser::LoadCommand(const char* name)
488 {
489         char filename[MAXBUF];
490         void* h;
491         Command* (*cmd_factory_func)(InspIRCd*);
492
493         /* Command already exists? Succeed silently - this is needed for REHASH */
494         if (RFCCommands.find(name) != RFCCommands.end())
495         {
496                 ServerInstance->Log(DEBUG,"Not reloading command %s/%s, it already exists", LIBRARYDIR, name);
497                 return NULL;
498         }
499
500         snprintf(filename, MAXBUF, "%s/%s", LIBRARYDIR, name);
501         h = dlopen(filename, RTLD_NOW | RTLD_GLOBAL);
502
503         if (!h)
504         {
505                 const char* n = dlerror();
506                 ServerInstance->Log(SPARSE, "Error loading core command %s: %s", name, n);
507                 return n;
508         }
509
510         if (this->FindSym((void **)&cmd_factory_func, h, name))
511         {
512                 Command* newcommand = cmd_factory_func(ServerInstance);
513                 this->CreateCommand(newcommand, h);
514         }
515         return NULL;
516 }
517
518 void CommandParser::SetupCommandTable(User* user)
519 {
520         RFCCommands.clear();
521
522         if (!user)
523         {
524                 printf("\nLoading core commands");
525                 fflush(stdout);
526         }
527
528         DIR* library = opendir(LIBRARYDIR);
529         if (library)
530         {
531                 dirent* entry = NULL;
532                 while ((entry = readdir(library)))
533                 {
534                         if (match(entry->d_name, "cmd_*.so"))
535                         {
536                                 if (!user)
537                                 {
538                                         printf(".");
539                                         fflush(stdout);
540                                 }
541                                 const char* err = this->LoadCommand(entry->d_name);
542                                 if (err)
543                                 {
544                                         if (user)
545                                         {
546                                                 user->WriteServ("NOTICE %s :*** Failed to load core command %s: %s", user->nick, entry->d_name, err);
547                                         }
548                                         else
549                                         {
550                                                 printf("Error loading %s: %s", entry->d_name, err);
551                                                 exit(EXIT_STATUS_BADHANDLER);
552                                         }
553                                 }
554                         }
555                 }
556                 closedir(library);
557                 if (!user)
558                         printf("\n");
559         }
560
561         if (cmdlist.find("RELOAD") == cmdlist.end())
562                 this->CreateCommand(new cmd_reload(ServerInstance));
563 }
564
565 int CommandParser::TranslateUIDs(TranslateType to, const std::string &source, std::string &dest)
566 {
567         User* user = NULL;
568         std::string item;
569         int translations = 0;
570
571         switch (to)
572         {
573                 case TR_NICK:
574                         /* Translate single nickname */
575                         ServerInstance->Log(DEBUG,"TR_NICK");
576                         user = ServerInstance->FindNick(source);
577                         if (user)
578                         {
579                                 ServerInstance->Log(DEBUG,"Managed UUID");
580                                 dest = user->uuid;
581                                 translations++;
582                         }
583                         else
584                         {
585                                 ServerInstance->Log(DEBUG,"Had to use source.. (%s)", source.c_str());
586                                 dest = source;
587                         }
588                 break;
589                 case TR_NICKLIST:
590                 {
591                         /* Translate comma seperated list of nicknames */
592                         irc::commasepstream items(source);
593                         while (items.GetToken(item))
594                         {
595                                 user = ServerInstance->FindNick(item);
596                                 if (user)
597                                 {
598                                         dest.append(user->uuid);
599                                         translations++;
600                                 }
601                                 else
602                                         dest.append(source);
603                                 dest.append(",");
604                         }
605                         if (!dest.empty())
606                                 dest.erase(dest.end() - 1);
607                 }
608                 break;
609                 case TR_SPACENICKLIST:
610                 {
611                         /* Translate space seperated list of nicknames */
612                         irc::spacesepstream items(source);
613                         while (items.GetToken(item))
614                         {
615                                 user = ServerInstance->FindNick(item);
616                                 if (user)
617                                 {
618                                         dest.append(user->uuid);
619                                         translations++;
620                                 }
621                                 else
622                                         dest.append(source);
623                                 dest.append(" ");
624                         }
625                         if (!dest.empty())
626                                 dest.erase(dest.end() - 1);
627                 }
628                 break;
629                 case TR_END:
630                 case TR_TEXT:
631                 default:
632                         /* Do nothing */
633                         dest = source;
634                 break;
635         }
636
637         return translations;
638 }
639