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