]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/command_parse.cpp
Fix bug #224 by refreshing the security ip cache every hour. The easier solution...
[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 (Config->ulines.find(server) != Config->ulines.end());
35 }
36
37 bool InspIRCd::SilentULine(const char* server)
38 {
39         std::map<irc::string,bool>::iterator n = Config->ulines.find(server);
40         if (n != Config->ulines.end())
41                 return n->second;
42         else return false;
43 }
44
45 int InspIRCd::OperPassCompare(const char* data,const char* input, int tagnumber)
46 {
47         int MOD_RESULT = 0;
48         FOREACH_RESULT_I(this,I_OnOperCompare,OnOperCompare(data, input, tagnumber))
49         if (MOD_RESULT == 1)
50                 return 0;
51         if (MOD_RESULT == -1)
52                 return 1;
53         return strcmp(data,input);
54 }
55
56 long InspIRCd::Duration(const char* str)
57 {
58         char n_field[MAXBUF];
59         long total = 0;
60         n_field[0] = 0;
61
62         if ((!strchr(str,'s')) && (!strchr(str,'m')) && (!strchr(str,'h')) && (!strchr(str,'d')) && (!strchr(str,'w')) && (!strchr(str,'y')))
63         {
64                 std::string n = str;
65                 n += 's';
66                 return Duration(n.c_str());
67         }
68         
69         for (char* i = (char*)str; *i; i++)
70         {
71                 // if we have digits, build up a string for the value in n_field,
72                 // up to 10 digits in size.
73                 if ((*i >= '0') && (*i <= '9'))
74                 {
75                         strlcat(n_field,i,10);
76                 }
77                 else
78                 {
79                         // we dont have a digit, check for numeric tokens
80                         switch (tolower(*i))
81                         {
82                                 case 's':
83                                         total += atoi(n_field);
84                                 break;
85
86                                 case 'm':
87                                         total += (atoi(n_field)*duration_m);
88                                 break;
89
90                                 case 'h':
91                                         total += (atoi(n_field)*duration_h);
92                                 break;
93
94                                 case 'd':
95                                         total += (atoi(n_field)*duration_d);
96                                 break;
97
98                                 case 'w':
99                                         total += (atoi(n_field)*duration_w);
100                                 break;
101
102                                 case 'y':
103                                         total += (atoi(n_field)*duration_y);
104                                 break;
105                         }
106                         n_field[0] = 0;
107                 }
108         }
109         // add trailing seconds
110         total += atoi(n_field);
111         
112         return total;
113 }
114
115 /* LoopCall is used to call a command classes handler repeatedly based on the contents of a comma seperated list.
116  * There are two overriden versions of this method, one of which takes two potential lists and the other takes one.
117  * We need a version which takes two potential lists for JOIN, because a JOIN may contain two lists of items at once,
118  * the channel names and their keys as follows:
119  * JOIN #chan1,#chan2,#chan3 key1,,key3
120  * Therefore, we need to deal with both lists concurrently. The first instance of this method does that by creating
121  * two instances of irc::commasepstream and reading them both together until the first runs out of tokens.
122  * The second version is much simpler and just has the one stream to read, and is used in NAMES, WHOIS, PRIVMSG etc.
123  * Both will only parse until they reach ServerInstance->Config->MaxTargets number of targets, to stop abuse via spam.
124  */
125 int CommandParser::LoopCall(userrec* user, command_t* CommandObj, const char** parameters, int pcnt, unsigned int splithere, unsigned int extra)
126 {
127         /* First check if we have more than one item in the list, if we don't we return zero here and the handler
128          * which called us just carries on as it was.
129          */
130         if (!strchr(parameters[splithere],','))
131                 return 0;
132
133         /** Some lame ircds will weed out dupes using some shitty O(n^2) algorithm.
134          * By using std::map (thanks for the idea w00t) we can cut this down a ton.
135          * ...VOOODOOOO!
136          */
137         std::map<irc::string, bool> dupes;
138
139         /* Create two lists, one for channel names, one for keys
140          */
141         irc::commasepstream items1(parameters[splithere]);
142         irc::commasepstream items2(parameters[extra]);
143         std::string item = "*";
144         unsigned int max = 0;
145
146         /* Attempt to iterate these lists and call the command objech
147          * which called us, for every parameter pair until there are
148          * no more left to parse.
149          */
150         while (((item = items1.GetToken()) != "") && (max++ < ServerInstance->Config->MaxTargets))
151         {
152                 if (dupes.find(item.c_str()) == dupes.end())
153                 {
154                         const char* new_parameters[127];
155
156                         for (int t = 0; (t < pcnt) && (t < 127); t++)
157                                 new_parameters[t] = parameters[t];
158
159                         std::string extrastuff = items2.GetToken();
160
161                         new_parameters[splithere] = item.c_str();
162                         new_parameters[extra] = extrastuff.c_str();
163
164                         CommandObj->Handle(new_parameters,pcnt,user);
165
166                         dupes[item.c_str()] = true;
167                 }
168         }
169         return 1;
170 }
171
172 int CommandParser::LoopCall(userrec* user, command_t* CommandObj, const char** parameters, int pcnt, unsigned int splithere)
173 {
174         /* First check if we have more than one item in the list, if we don't we return zero here and the handler
175          * which called us just carries on as it was.
176          */
177         if (!strchr(parameters[splithere],','))
178                 return 0;
179
180         std::map<irc::string, bool> dupes;
181
182         /* Only one commasepstream here */
183         irc::commasepstream items1(parameters[splithere]);
184         std::string item = "*";
185         unsigned int max = 0;
186
187         /* Parse the commasepstream until there are no tokens remaining.
188          * Each token we parse out, call the command handler that called us
189          * with it
190          */
191         while (((item = items1.GetToken()) != "") && (max++ < ServerInstance->Config->MaxTargets))
192         {
193                 if (dupes.find(item.c_str()) == dupes.end())
194                 {
195                         const char* new_parameters[127];
196
197                         for (int t = 0; (t < pcnt) && (t < 127); t++)
198                                 new_parameters[t] = parameters[t];
199
200                         new_parameters[splithere] = item.c_str();
201
202                         parameters[splithere] = item.c_str();
203
204                         /* Execute the command handler over and over. If someone pulls our user
205                          * record out from under us (e.g. if we /kill a comma sep list, and we're
206                          * in that list ourselves) abort if we're gone.
207                          */
208                         CommandObj->Handle(new_parameters,pcnt,user);
209
210                         dupes[item.c_str()] = true;
211                 }
212         }
213         /* By returning 1 we tell our caller that nothing is to be done,
214          * as all the previous calls handled the data. This makes the parent
215          * return without doing any processing.
216          */
217         return 1;
218 }
219
220 bool CommandParser::IsValidCommand(const std::string &commandname, int pcnt, userrec * user)
221 {
222         nspace::hash_map<std::string,command_t*>::iterator n = cmdlist.find(commandname);
223
224         if (n != cmdlist.end())
225         {
226                 if ((pcnt>=n->second->min_params) && (n->second->source != "<core>"))
227                 {
228                         if ((!n->second->flags_needed) || (user->modes[n->second->flags_needed-65]))
229                         {
230                                 if (n->second->flags_needed)
231                                 {
232                                         return ((user->HasPermission(commandname)) || (ServerInstance->ULine(user->server)));
233                                 }
234                                 return true;
235                         }
236                 }
237         }
238         return false;
239 }
240
241 command_t* CommandParser::GetHandler(const std::string &commandname)
242 {
243         nspace::hash_map<std::string,command_t*>::iterator n = cmdlist.find(commandname);
244         if (n != cmdlist.end())
245                 return n->second;
246
247         return NULL;
248 }
249
250 // calls a handler function for a command
251
252 CmdResult CommandParser::CallHandler(const std::string &commandname,const char** parameters, int pcnt, userrec *user)
253 {
254         nspace::hash_map<std::string,command_t*>::iterator n = cmdlist.find(commandname);
255
256         if (n != cmdlist.end())
257         {
258                 if (pcnt >= n->second->min_params)
259                 {
260                         if ((!n->second->flags_needed) || (user->modes[n->second->flags_needed-65]))
261                         {
262                                 if (n->second->flags_needed)
263                                 {
264                                         if ((user->HasPermission(commandname)) || (!IS_LOCAL(user)))
265                                         {
266                                                 return n->second->Handle(parameters,pcnt,user);
267                                         }
268                                 }
269                                 else
270                                 {
271                                         return n->second->Handle(parameters,pcnt,user);
272                                 }
273                         }
274                 }
275         }
276         return CMD_INVALID;
277 }
278
279 void CommandParser::ProcessCommand(userrec *user, std::string &cmd)
280 {
281         const char *command_p[127];
282         int items = 0;
283         irc::tokenstream tokens(cmd);
284         std::string command;
285         tokens.GetToken(command);
286
287         while (tokens.GetToken(para[items]) && (items < 127))
288         {
289                 command_p[items] = para[items].c_str();
290                 items++;
291         }
292
293         std::transform(command.begin(), command.end(), command.begin(), ::toupper);
294                 
295         int MOD_RESULT = 0;
296         FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command,command_p,items,user,false,cmd));
297         if (MOD_RESULT == 1) {
298                 return;
299         }
300
301         nspace::hash_map<std::string,command_t*>::iterator cm = cmdlist.find(command);
302         
303         if (cm != cmdlist.end())
304         {
305                 if (user)
306                 {
307                         /* activity resets the ping pending timer */
308                         user->nping = ServerInstance->Time() + user->pingmax;
309                         if (cm->second->flags_needed)
310                         {
311                                 if (!user->IsModeSet(cm->second->flags_needed))
312                                 {
313                                         user->WriteServ("481 %s :Permission Denied- You do not have the required operator privileges",user->nick);
314                                         return;
315                                 }
316                                 if (!user->HasPermission(command))
317                                 {
318                                         user->WriteServ("481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command.c_str());
319                                         return;
320                                 }
321                         }
322                         if ((user->registered == REG_ALL) && (!*user->oper) && (cm->second->IsDisabled()))
323                         {
324                                 /* command is disabled! */
325                                 user->WriteServ("421 %s %s :This command has been disabled.",user->nick,command.c_str());
326                                 return;
327                         }
328                         if (items < cm->second->min_params)
329                         {
330                                 user->WriteServ("461 %s %s :Not enough parameters.", user->nick, command.c_str());
331                                 /* If syntax is given, display this as the 461 reply */
332                                 if ((ServerInstance->Config->SyntaxHints) && (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 may come after the
349                                  * command handler call, as the handler
350                                  * may free the user structure!
351                                  */
352                                 CmdResult result = cm->second->Handle(command_p,items,user);
353
354                                 FOREACH_MOD(I_OnPostCommand,OnPostCommand(command, command_p, items, user, result,cmd));
355                                 return;
356                         }
357                         else
358                         {
359                                 user->WriteServ("451 %s :You have not registered",command.c_str());
360                                 return;
361                         }
362                 }
363         }
364         else if (user)
365         {
366                 ServerInstance->stats->statsUnknown++;
367                 user->WriteServ("421 %s %s :Unknown command",user->nick,command.c_str());
368         }
369 }
370
371 bool CommandParser::RemoveCommands(const char* source)
372 {
373         nspace::hash_map<std::string,command_t*>::iterator i,safei;
374         for (i = cmdlist.begin(); i != cmdlist.end(); i++)
375         {
376                 safei = i;
377                 safei++;
378                 if (safei != cmdlist.end())
379                 {
380                         RemoveCommand(safei, source);
381                 }
382         }
383         safei = cmdlist.begin();
384         if (safei != cmdlist.end())
385         {
386                 RemoveCommand(safei, source);
387         }
388         return true;
389 }
390
391 void CommandParser::RemoveCommand(nspace::hash_map<std::string,command_t*>::iterator safei, const char* source)
392 {
393         command_t* x = safei->second;
394         if (x->source == std::string(source))
395         {
396                 cmdlist.erase(safei);
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,"-> :%s %s",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)
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         DIR* library = opendir(LIBRARYDIR);
540         if (library)
541         {
542                 dirent* entry = NULL;
543                 while ((entry = readdir(library)))
544                 {
545                         if (match(entry->d_name, "cmd_*.so"))
546                         {
547                                 this->LoadCommand(entry->d_name);
548                         }
549                 }
550                 closedir(library);
551         }
552
553         this->CreateCommand(new cmd_reload(ServerInstance));
554 }
555