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