]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/command_parse.cpp
Change to use std::string::iterator rather than making a copy of the pointer and...
[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 <dirent.h>
18 #include <dlfcn.h>
19 #include "users.h"
20 #include "modules.h"
21 #include "wildcard.h"
22 #include "xline.h"
23 #include "socketengine.h"
24 #include "socket.h"
25 #include "command_parse.h"
26
27 bool InspIRCd::ULine(const char* server)
28 {
29         if (!server)
30                 return false;
31         if (!*server)
32                 return true;
33
34         return (find(Config->ulines.begin(),Config->ulines.end(),server) != Config->ulines.end());
35 }
36
37 int InspIRCd::OperPassCompare(const char* data,const char* input, int tagnumber)
38 {
39         int MOD_RESULT = 0;
40         FOREACH_RESULT_I(this,I_OnOperCompare,OnOperCompare(data, input, tagnumber))
41         Log(DEBUG,"OperPassCompare: %d",MOD_RESULT);
42         if (MOD_RESULT == 1)
43                 return 0;
44         if (MOD_RESULT == -1)
45                 return 1;
46         Log(DEBUG,"strcmp fallback: '%s' '%s' %d",data,input,strcmp(data,input));
47         return strcmp(data,input);
48 }
49
50 long InspIRCd::Duration(const char* str)
51 {
52         char n_field[MAXBUF];
53         long total = 0;
54         n_field[0] = 0;
55
56         if ((!strchr(str,'s')) && (!strchr(str,'m')) && (!strchr(str,'h')) && (!strchr(str,'d')) && (!strchr(str,'w')) && (!strchr(str,'y')))
57         {
58                 std::string n = str;
59                 n += 's';
60                 return Duration(n.c_str());
61         }
62         
63         for (char* i = (char*)str; *i; i++)
64         {
65                 // if we have digits, build up a string for the value in n_field,
66                 // up to 10 digits in size.
67                 if ((*i >= '0') && (*i <= '9'))
68                 {
69                         strlcat(n_field,i,10);
70                 }
71                 else
72                 {
73                         // we dont have a digit, check for numeric tokens
74                         switch (tolower(*i))
75                         {
76                                 case 's':
77                                         total += atoi(n_field);
78                                 break;
79
80                                 case 'm':
81                                         total += (atoi(n_field)*duration_m);
82                                 break;
83
84                                 case 'h':
85                                         total += (atoi(n_field)*duration_h);
86                                 break;
87
88                                 case 'd':
89                                         total += (atoi(n_field)*duration_d);
90                                 break;
91
92                                 case 'w':
93                                         total += (atoi(n_field)*duration_w);
94                                 break;
95
96                                 case 'y':
97                                         total += (atoi(n_field)*duration_y);
98                                 break;
99                         }
100                         n_field[0] = 0;
101                 }
102         }
103         // add trailing seconds
104         total += atoi(n_field);
105         
106         return total;
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 item = "*";
138         unsigned int max = 0;
139
140         /* Attempt to iterate these lists and call the command objech
141          * which called us, for every parameter pair until there are
142          * no more left to parse.
143          */
144         while (((item = items1.GetToken()) != "") && (max++ < ServerInstance->Config->MaxTargets))
145         {
146                 if (dupes.find(item.c_str()) == dupes.end())
147                 {
148                         const char* new_parameters[127];
149
150                         for (int t = 0; (t < pcnt) && (t < 127); t++)
151                                 new_parameters[t] = parameters[t];
152
153                         std::string extrastuff = items2.GetToken();
154
155                         new_parameters[splithere] = item.c_str();
156                         new_parameters[extra] = extrastuff.c_str();
157
158                         if (CommandObj->Handle(new_parameters,pcnt,user) == CMD_USER_DELETED)
159                                 return 1;
160
161                         dupes[item.c_str()] = true;
162                 }
163         }
164         return 1;
165 }
166
167 int CommandParser::LoopCall(userrec* user, command_t* CommandObj, const char** parameters, int pcnt, unsigned int splithere)
168 {
169         /* First check if we have more than one item in the list, if we don't we return zero here and the handler
170          * which called us just carries on as it was.
171          */
172         if (!strchr(parameters[splithere],','))
173                 return 0;
174
175         std::map<irc::string, bool> dupes;
176
177         /* Only one commasepstream here */
178         ServerInstance->Log(DEBUG,"Splitting '%s'",parameters[splithere]);
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 (((item = items1.GetToken()) != "") && (max++ < ServerInstance->Config->MaxTargets))
188         {
189                 if (dupes.find(item.c_str()) == dupes.end())
190                 {
191                         const char* new_parameters[127];
192
193                         for (int t = 0; (t < pcnt) && (t < 127); 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                         if (CommandObj->Handle(new_parameters,pcnt,user) == CMD_USER_DELETED)
205                                 return 1;
206
207                         dupes[item.c_str()] = true;
208                 }
209         }
210         /* By returning 1 we tell our caller that nothing is to be done,
211          * as all the previous calls handled the data. This makes the parent
212          * return without doing any processing.
213          */
214         return 1;
215 }
216
217 bool CommandParser::IsValidCommand(const std::string &commandname, int pcnt, userrec * user)
218 {
219         nspace::hash_map<std::string,command_t*>::iterator n = cmdlist.find(commandname);
220
221         if (n != cmdlist.end())
222         {
223                 if ((pcnt>=n->second->min_params) && (n->second->source != "<core>"))
224                 {
225                         if ((!n->second->flags_needed) || (user->modes[n->second->flags_needed-65]))
226                         {
227                                 if (n->second->flags_needed)
228                                 {
229                                         return ((user->HasPermission(commandname)) || (ServerInstance->ULine(user->server)));
230                                 }
231                                 return true;
232                         }
233                 }
234         }
235         return false;
236 }
237
238 command_t* CommandParser::GetHandler(const std::string &commandname)
239 {
240         nspace::hash_map<std::string,command_t*>::iterator n = cmdlist.find(commandname);
241         if (n != cmdlist.end())
242                 return n->second;
243
244         return NULL;
245 }
246
247 // calls a handler function for a command
248
249 CmdResult CommandParser::CallHandler(const std::string &commandname,const char** parameters, int pcnt, userrec *user)
250 {
251         nspace::hash_map<std::string,command_t*>::iterator n = cmdlist.find(commandname);
252
253         if (n != cmdlist.end())
254         {
255                 if (pcnt >= n->second->min_params)
256                 {
257                         if ((!n->second->flags_needed) || (user->modes[n->second->flags_needed-65]))
258                         {
259                                 if (n->second->flags_needed)
260                                 {
261                                         if ((user->HasPermission(commandname)) || (!IS_LOCAL(user)))
262                                         {
263                                                 return n->second->Handle(parameters,pcnt,user);
264                                         }
265                                 }
266                                 else
267                                 {
268                                         return n->second->Handle(parameters,pcnt,user);
269                                 }
270                         }
271                 }
272         }
273         return CMD_INVALID;
274 }
275
276 void CommandParser::ProcessCommand(userrec *user, std::string &cmd)
277 {
278         const char *command_p[127];
279         int items = 0;
280         irc::tokenstream tokens(cmd);
281         std::string command = tokens.GetToken();
282
283         while (((para[items] = tokens.GetToken()) != "") && (items < 127))
284         {
285                 command_p[items] = para[items].c_str();
286                 items++;
287         }
288
289         std::transform(command.begin(), command.end(), command.begin(), ::toupper);
290                 
291         int MOD_RESULT = 0;
292         FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command,command_p,items,user,false,cmd));
293         if (MOD_RESULT == 1) {
294                 return;
295         }
296
297         nspace::hash_map<std::string,command_t*>::iterator cm = cmdlist.find(command);
298         
299         if (cm != cmdlist.end())
300         {
301                 if (user)
302                 {
303                         /* activity resets the ping pending timer */
304                         user->nping = ServerInstance->Time() + user->pingmax;
305                         if (cm->second->flags_needed)
306                         {
307                                 if (!user->IsModeSet(cm->second->flags_needed))
308                                 {
309                                         user->WriteServ("481 %s :Permission Denied- You do not have the required operator privileges",user->nick);
310                                         return;
311                                 }
312                                 if (!user->HasPermission(command))
313                                 {
314                                         user->WriteServ("481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command.c_str());
315                                         return;
316                                 }
317                         }
318                         if ((user->registered == REG_ALL) && (!*user->oper) && (cm->second->IsDisabled()))
319                         {
320                                 /* command is disabled! */
321                                 user->WriteServ("421 %s %s :This command has been disabled.",user->nick,command.c_str());
322                                 return;
323                         }
324                         if (items < cm->second->min_params)
325                         {
326                                 user->WriteServ("461 %s %s :Not enough parameters.", user->nick, command.c_str());
327                                 /* If syntax is given, display this as the 461 reply */
328                                 if ((ServerInstance->Config->SyntaxHints) && (cm->second->syntax.length()))
329                                         user->WriteServ("304 %s :SYNTAX %s %s", user->nick, cm->second->command.c_str(), cm->second->syntax.c_str());
330                                 return;
331                         }
332                         if ((user->registered == REG_ALL) || (cm->second->WorksBeforeReg()))
333                         {
334                                 /* ikky /stats counters */
335                                 cm->second->use_count++;
336                                 cm->second->total_bytes += cmd.length();
337
338                                 int MOD_RESULT = 0;
339                                 FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command,command_p,items,user,true,cmd));
340                                 if (MOD_RESULT == 1)
341                                         return;
342
343                                 /*
344                                  * WARNING: nothing may come after the
345                                  * command handler call, as the handler
346                                  * may free the user structure!
347                                  */
348                                 CmdResult result = cm->second->Handle(command_p,items,user);
349
350                                 if (result != CMD_USER_DELETED)
351                                 {
352                                         FOREACH_MOD(I_OnPostCommand,OnPostCommand(command, command_p, items, user, result,cmd));
353                                 }
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         nspace::hash_map<std::string,command_t*>::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(nspace::hash_map<std::string,command_t*>::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         }
397 }
398
399 void CommandParser::ProcessBuffer(std::string &buffer,userrec *user)
400 {
401         std::string::size_type a;
402
403         if (!user)
404                 return;
405
406         while ((a = buffer.rfind("\n")) != std::string::npos)
407                 buffer.erase(a);
408         while ((a = buffer.rfind("\r")) != std::string::npos)
409                 buffer.erase(a);
410
411         if (buffer.length())
412         {
413                 ServerInstance->Log(DEBUG,"CMDIN: %s %s",user->nick,buffer.c_str());
414                 this->ProcessCommand(user,buffer);
415         }
416 }
417
418 bool CommandParser::CreateCommand(command_t *f, void* so_handle)
419 {
420         if (so_handle)
421         {
422                 if (RFCCommands.find(f->command) == RFCCommands.end())
423                 {
424                         RFCCommands[f->command] = so_handle;
425                         ServerInstance->Log(DEBUG,"Monitoring RFC-specified reloadable command at %8x",so_handle);
426                 }
427                 else
428                 {
429                         ServerInstance->Log(DEFAULT,"ERK! Somehow, we loaded a cmd_*.so file twice! Only the first instance is being recorded.");
430                         return false;
431                 }
432         }
433
434         /* create the command and push it onto the table */
435         if (cmdlist.find(f->command) == cmdlist.end())
436         {
437                 cmdlist[f->command] = f;
438                 ServerInstance->Log(DEBUG,"Added command %s (%d parameters)", f->command.c_str(), f->min_params);
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)
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         ServerInstance->Log(DEBUG,"Load command: %s", filename);
521
522         h = dlopen(filename, RTLD_NOW | RTLD_GLOBAL);
523
524         if (!h)
525         {
526                 ServerInstance->Log(SPARSE, "Error loading core command: %s", dlerror());
527                 return;
528         }
529
530         if (this->FindSym((void **)&cmd_factory_func, h))
531         {
532                 command_t* newcommand = cmd_factory_func(ServerInstance);
533                 this->CreateCommand(newcommand, h);
534         }
535 }
536
537 void CommandParser::SetupCommandTable()
538 {
539         RFCCommands.clear();
540
541         DIR* library = opendir(LIBRARYDIR);
542         if (library)
543         {
544                 dirent* entry = NULL;
545                 while ((entry = readdir(library)))
546                 {
547                         if (match(entry->d_name, "cmd_*.so"))
548                         {
549                                 this->LoadCommand(entry->d_name);
550                         }
551                 }
552                 closedir(library);
553         }
554
555         this->CreateCommand(new cmd_reload(ServerInstance));
556 }
557