]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/command_parse.cpp
Optimizations and code tidyups. QA please check that svsnick and other forced nick...
[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[127];
148
149                         for (int t = 0; (t < pcnt) && (t < 127); 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[127];
189
190                         for (int t = 0; (t < pcnt) && (t < 127); 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->modes[n->second->flags_needed-65]))
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->modes[n->second->flags_needed-65]))
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[127];
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 < 127))
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 syntax is given, display this as the 461 reply */
333                                 if ((ServerInstance->Config->SyntaxHints) && (user->registered == REG_ALL) && (cm->second->syntax.length()))
334                                         user->WriteServ("304 %s :SYNTAX %s %s", user->nick, cm->second->command.c_str(), cm->second->syntax.c_str());
335                                 return;
336                         }
337                         if ((user->registered == REG_ALL) || (cm->second->WorksBeforeReg()))
338                         {
339                                 /* ikky /stats counters */
340                                 cm->second->use_count++;
341                                 cm->second->total_bytes += cmd.length();
342
343                                 int MOD_RESULT = 0;
344                                 FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command,command_p,items,user,true,cmd));
345                                 if (MOD_RESULT == 1)
346                                         return;
347
348                                 /*
349                                  * WARNING: nothing may come after the
350                                  * command handler call, as the handler
351                                  * may free the user structure!
352                                  */
353                                 CmdResult result = cm->second->Handle(command_p,items,user);
354
355                                 FOREACH_MOD(I_OnPostCommand,OnPostCommand(command, command_p, items, user, result,cmd));
356                                 return;
357                         }
358                         else
359                         {
360                                 user->WriteServ("451 %s :You have not registered",command.c_str());
361                                 return;
362                         }
363                 }
364         }
365         else if (user)
366         {
367                 ServerInstance->stats->statsUnknown++;
368                 user->WriteServ("421 %s %s :Unknown command",user->nick,command.c_str());
369         }
370 }
371
372 bool CommandParser::RemoveCommands(const char* source)
373 {
374         command_table::iterator i,safei;
375         for (i = cmdlist.begin(); i != cmdlist.end(); i++)
376         {
377                 safei = i;
378                 safei++;
379                 if (safei != cmdlist.end())
380                 {
381                         RemoveCommand(safei, source);
382                 }
383         }
384         safei = cmdlist.begin();
385         if (safei != cmdlist.end())
386         {
387                 RemoveCommand(safei, source);
388         }
389         return true;
390 }
391
392 void CommandParser::RemoveCommand(command_table::iterator safei, const char* source)
393 {
394         command_t* x = safei->second;
395         if (x->source == std::string(source))
396         {
397                 cmdlist.erase(safei);
398         }
399 }
400
401 void CommandParser::ProcessBuffer(std::string &buffer,userrec *user)
402 {
403         std::string::size_type a;
404
405         if (!user)
406                 return;
407
408         while ((a = buffer.rfind("\n")) != std::string::npos)
409                 buffer.erase(a);
410         while ((a = buffer.rfind("\r")) != std::string::npos)
411                 buffer.erase(a);
412
413         if (buffer.length())
414         {
415                 if (!user->muted)
416                 {
417                         ServerInstance->Log(DEBUG,"C[%d] -> :%s %s",user->GetFd(), user->nick, buffer.c_str());
418                         this->ProcessCommand(user,buffer);
419                 }
420         }
421 }
422
423 bool CommandParser::CreateCommand(command_t *f, void* so_handle)
424 {
425         if (so_handle)
426         {
427                 if (RFCCommands.find(f->command) == RFCCommands.end())
428                         RFCCommands[f->command] = so_handle;
429                 else
430                 {
431                         ServerInstance->Log(DEFAULT,"ERK! Somehow, we loaded a cmd_*.so file twice! Only the first instance is being recorded.");
432                         return false;
433                 }
434         }
435
436         /* create the command and push it onto the table */
437         if (cmdlist.find(f->command) == cmdlist.end())
438         {
439                 cmdlist[f->command] = f;
440                 return true;
441         }
442         else return false;
443 }
444
445 CommandParser::CommandParser(InspIRCd* Instance) : ServerInstance(Instance)
446 {
447         para.resize(128);
448         this->SetupCommandTable();
449 }
450
451 bool CommandParser::FindSym(void** v, void* h)
452 {
453         *v = dlsym(h, "init_command");
454         const char* err = dlerror();
455         if (err && !(*v))
456         {
457                 ServerInstance->Log(SPARSE, "Error loading core command: %s\n", err);
458                 return false;
459         }
460         return true;
461 }
462
463 bool CommandParser::ReloadCommand(const char* cmd)
464 {
465         char filename[MAXBUF];
466         char commandname[MAXBUF];
467         int y = 0;
468
469         for (const char* x = cmd; *x; x++, y++)
470                 commandname[y] = toupper(*x);
471
472         commandname[y] = 0;
473
474         SharedObjectList::iterator command = RFCCommands.find(commandname);
475
476         if (command != RFCCommands.end())
477         {
478                 command_t* cmdptr = cmdlist.find(commandname)->second;
479                 cmdlist.erase(cmdlist.find(commandname));
480
481                 for (char* x = commandname; *x; x++)
482                         *x = tolower(*x);
483
484
485                 delete cmdptr;
486                 dlclose(command->second);
487                 RFCCommands.erase(command);
488
489                 snprintf(filename, MAXBUF, "cmd_%s.so", commandname);
490                 this->LoadCommand(filename);
491
492                 return true;
493         }
494
495         return false;
496 }
497
498 CmdResult cmd_reload::Handle(const char** parameters, int pcnt, userrec *user)
499 {
500         user->WriteServ("NOTICE %s :*** Reloading command '%s'",user->nick, parameters[0]);
501         if (ServerInstance->Parser->ReloadCommand(parameters[0]))
502         {
503                 user->WriteServ("NOTICE %s :*** Successfully reloaded command '%s'", user->nick, parameters[0]);
504                 ServerInstance->WriteOpers("*** RELOAD: %s reloaded the '%s' command.", user->nick, parameters[0]);
505                 return CMD_SUCCESS;
506         }
507         else
508         {
509                 user->WriteServ("NOTICE %s :*** Could not reload command '%s'", user->nick, parameters[0]);
510                 return CMD_FAILURE;
511         }
512 }
513
514 void CommandParser::LoadCommand(const char* name)
515 {
516         char filename[MAXBUF];
517         void* h;
518         command_t* (*cmd_factory_func)(InspIRCd*);
519
520         snprintf(filename, MAXBUF, "%s/%s", LIBRARYDIR, name);
521         h = dlopen(filename, RTLD_NOW | RTLD_GLOBAL);
522
523         if (!h)
524         {
525                 ServerInstance->Log(SPARSE, "Error loading core command: %s", dlerror());
526                 return;
527         }
528
529         if (this->FindSym((void **)&cmd_factory_func, h))
530         {
531                 command_t* newcommand = cmd_factory_func(ServerInstance);
532                 this->CreateCommand(newcommand, h);
533         }
534 }
535
536 void CommandParser::SetupCommandTable()
537 {
538         RFCCommands.clear();
539
540         printf("\nLoading core commands");
541         fflush(stdout);
542
543         DIR* library = opendir(LIBRARYDIR);
544         if (library)
545         {
546                 dirent* entry = NULL;
547                 while ((entry = readdir(library)))
548                 {
549                         if (match(entry->d_name, "cmd_*.so"))
550                         {
551                                 printf(".");
552                                 fflush(stdout);
553                                 this->LoadCommand(entry->d_name);
554                         }
555                 }
556                 closedir(library);
557                 printf("\n");
558         }
559
560         this->CreateCommand(new cmd_reload(ServerInstance));
561 }
562