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