]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/command_parse.cpp
e56005751d2f791556d20f13c4434da6dc3a8406
[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 /* All other ircds when doing this check usually just look for a string of *@* or *. We're smarter than that, though. */
110
111 bool InspIRCd::HostMatchesEveryone(const std::string &mask, userrec* user)
112 {
113         char buffer[MAXBUF];
114         char itrigger[MAXBUF];
115         long matches = 0;
116         
117         if (!Config->ConfValue(Config->config_data, "insane","trigger", 0, itrigger, MAXBUF))
118                 strlcpy(itrigger,"95.5",MAXBUF);
119         
120         if (Config->ConfValueBool(Config->config_data, "insane","hostmasks", 0))
121                 return false;
122         
123         for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
124         {
125                 strlcpy(buffer,u->second->ident,MAXBUF);
126                 charlcat(buffer,'@',MAXBUF);
127                 strlcat(buffer,u->second->host,MAXBUF);
128                 if (match(buffer,mask.c_str()))
129                         matches++;
130         }
131         float percent = ((float)matches / (float)clientlist.size()) * 100;
132         if (percent > (float)atof(itrigger))
133         {
134                 WriteOpers("*** \2WARNING\2: %s tried to set a G/K/E line mask of %s, which covers %.2f%% of the network!",user->nick,mask.c_str(),percent);
135                 return true;
136         }
137         return false;
138 }
139
140 bool InspIRCd::IPMatchesEveryone(const std::string &ip, userrec* user)
141 {
142         char itrigger[MAXBUF];
143         long matches = 0;
144         
145         if (!Config->ConfValue(Config->config_data, "insane","trigger",0,itrigger,MAXBUF))
146                 strlcpy(itrigger,"95.5",MAXBUF);
147         
148         if (Config->ConfValueBool(Config->config_data, "insane","ipmasks",0))
149                 return false;
150         
151         for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
152         {
153                 if (match(u->second->GetIPString(),ip.c_str(),true))
154                         matches++;
155         }
156         
157         float percent = ((float)matches / (float)clientlist.size()) * 100;
158         if (percent > (float)atof(itrigger))
159         {
160                 WriteOpers("*** \2WARNING\2: %s tried to set a Z line mask of %s, which covers %.2f%% of the network!",user->nick,ip.c_str(),percent);
161                 return true;
162         }
163         return false;
164 }
165
166 bool InspIRCd::NickMatchesEveryone(const std::string &nick, userrec* user)
167 {
168         char itrigger[MAXBUF];
169         long matches = 0;
170         
171         if (!Config->ConfValue(Config->config_data, "insane","trigger",0,itrigger,MAXBUF))
172                 strlcpy(itrigger,"95.5",MAXBUF);
173         
174         if (Config->ConfValueBool(Config->config_data, "insane","nickmasks",0))
175                 return false;
176
177         for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
178         {
179                 if (match(u->second->nick,nick.c_str()))
180                         matches++;
181         }
182         
183         float percent = ((float)matches / (float)clientlist.size()) * 100;
184         if (percent > (float)atof(itrigger))
185         {
186                 WriteOpers("*** \2WARNING\2: %s tried to set a Q line mask of %s, which covers %.2f%% of the network!",user->nick,nick.c_str(),percent);
187                 return true;
188         }
189         return false;
190 }
191
192 /* LoopCall is used to call a command classes handler repeatedly based on the contents of a comma seperated list.
193  * There are two overriden versions of this method, one of which takes two potential lists and the other takes one.
194  * We need a version which takes two potential lists for JOIN, because a JOIN may contain two lists of items at once,
195  * the channel names and their keys as follows:
196  * JOIN #chan1,#chan2,#chan3 key1,,key3
197  * Therefore, we need to deal with both lists concurrently. The first instance of this method does that by creating
198  * two instances of irc::commasepstream and reading them both together until the first runs out of tokens.
199  * The second version is much simpler and just has the one stream to read, and is used in NAMES, WHOIS, PRIVMSG etc.
200  * Both will only parse until they reach ServerInstance->Config->MaxTargets number of targets, to stop abuse via spam.
201  */
202 int CommandParser::LoopCall(userrec* user, command_t* CommandObj, const char** parameters, int pcnt, unsigned int splithere, unsigned int extra)
203 {
204         /* First check if we have more than one item in the list, if we don't we return zero here and the handler
205          * which called us just carries on as it was.
206          */
207         if (!strchr(parameters[splithere],','))
208                 return 0;
209
210         /** Some lame ircds will weed out dupes using some shitty O(n^2) algorithm.
211          * By using std::map (thanks for the idea w00t) we can cut this down a ton.
212          * ...VOOODOOOO!
213          */
214         std::map<irc::string, bool> dupes;
215
216         /* Create two lists, one for channel names, one for keys
217          */
218         irc::commasepstream items1(parameters[splithere]);
219         irc::commasepstream items2(parameters[extra]);
220         std::string item = "*";
221         unsigned int max = 0;
222
223         /* Attempt to iterate these lists and call the command objech
224          * which called us, for every parameter pair until there are
225          * no more left to parse.
226          */
227         while (((item = items1.GetToken()) != "") && (max++ < ServerInstance->Config->MaxTargets))
228         {
229                 if (dupes.find(item.c_str()) == dupes.end())
230                 {
231                         const char* new_parameters[127];
232
233                         for (int t = 0; (t < pcnt) && (t < 127); t++)
234                                 new_parameters[t] = parameters[t];
235
236                         std::string extrastuff = items2.GetToken();
237
238                         new_parameters[splithere] = item.c_str();
239                         new_parameters[extra] = extrastuff.c_str();
240
241                         if (CommandObj->Handle(new_parameters,pcnt,user) == CMD_USER_DELETED)
242                                 return 1;
243
244                         dupes[item.c_str()] = true;
245                 }
246         }
247         return 1;
248 }
249
250 int CommandParser::LoopCall(userrec* user, command_t* CommandObj, const char** parameters, int pcnt, unsigned int splithere)
251 {
252         /* First check if we have more than one item in the list, if we don't we return zero here and the handler
253          * which called us just carries on as it was.
254          */
255         if (!strchr(parameters[splithere],','))
256                 return 0;
257
258         std::map<irc::string, bool> dupes;
259
260         /* Only one commasepstream here */
261         ServerInstance->Log(DEBUG,"Splitting '%s'",parameters[splithere]);
262         irc::commasepstream items1(parameters[splithere]);
263         std::string item = "*";
264         unsigned int max = 0;
265
266         /* Parse the commasepstream until there are no tokens remaining.
267          * Each token we parse out, call the command handler that called us
268          * with it
269          */
270         while (((item = items1.GetToken()) != "") && (max++ < ServerInstance->Config->MaxTargets))
271         {
272                 if (dupes.find(item.c_str()) == dupes.end())
273                 {
274                         const char* new_parameters[127];
275
276                         for (int t = 0; (t < pcnt) && (t < 127); t++)
277                                 new_parameters[t] = parameters[t];
278
279                         new_parameters[splithere] = item.c_str();
280
281                         parameters[splithere] = item.c_str();
282
283                         /* Execute the command handler over and over. If someone pulls our user
284                          * record out from under us (e.g. if we /kill a comma sep list, and we're
285                          * in that list ourselves) abort if we're gone.
286                          */
287                         if (CommandObj->Handle(new_parameters,pcnt,user) == CMD_USER_DELETED)
288                                 return 1;
289
290                         dupes[item.c_str()] = true;
291                 }
292         }
293         /* By returning 1 we tell our caller that nothing is to be done,
294          * as all the previous calls handled the data. This makes the parent
295          * return without doing any processing.
296          */
297         return 1;
298 }
299
300 bool CommandParser::IsValidCommand(const std::string &commandname, int pcnt, userrec * user)
301 {
302         nspace::hash_map<std::string,command_t*>::iterator n = cmdlist.find(commandname);
303
304         if (n != cmdlist.end())
305         {
306                 if ((pcnt>=n->second->min_params) && (n->second->source != "<core>"))
307                 {
308                         if ((!n->second->flags_needed) || (user->modes[n->second->flags_needed-65]))
309                         {
310                                 if (n->second->flags_needed)
311                                 {
312                                         return ((user->HasPermission(commandname)) || (ServerInstance->ULine(user->server)));
313                                 }
314                                 return true;
315                         }
316                 }
317         }
318         return false;
319 }
320
321 command_t* CommandParser::GetHandler(const std::string &commandname)
322 {
323         nspace::hash_map<std::string,command_t*>::iterator n = cmdlist.find(commandname);
324         if (n != cmdlist.end())
325                 return n->second;
326
327         return NULL;
328 }
329
330 // calls a handler function for a command
331
332 CmdResult CommandParser::CallHandler(const std::string &commandname,const char** parameters, int pcnt, userrec *user)
333 {
334         nspace::hash_map<std::string,command_t*>::iterator n = cmdlist.find(commandname);
335
336         if (n != cmdlist.end())
337         {
338                 if (pcnt >= n->second->min_params)
339                 {
340                         if ((!n->second->flags_needed) || (user->modes[n->second->flags_needed-65]))
341                         {
342                                 if (n->second->flags_needed)
343                                 {
344                                         if ((user->HasPermission(commandname)) || (!IS_LOCAL(user)))
345                                         {
346                                                 return n->second->Handle(parameters,pcnt,user);
347                                         }
348                                 }
349                                 else
350                                 {
351                                         return n->second->Handle(parameters,pcnt,user);
352                                 }
353                         }
354                 }
355         }
356         return CMD_INVALID;
357 }
358
359 void CommandParser::ProcessCommand(userrec *user, std::string &cmd)
360 {
361         const char *command_p[127];
362         int items = 0;
363         irc::tokenstream tokens(cmd);
364         std::string command = tokens.GetToken();
365
366         while (((para[items] = tokens.GetToken()) != "") && (items < 127))
367         {
368                 command_p[items] = para[items].c_str();
369                 items++;
370         }
371
372         std::transform(command.begin(), command.end(), command.begin(), ::toupper);
373                 
374         int MOD_RESULT = 0;
375         FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command,command_p,items,user,false,cmd));
376         if (MOD_RESULT == 1) {
377                 return;
378         }
379
380         nspace::hash_map<std::string,command_t*>::iterator cm = cmdlist.find(command);
381         
382         if (cm != cmdlist.end())
383         {
384                 if (user)
385                 {
386                         /* activity resets the ping pending timer */
387                         user->nping = ServerInstance->Time() + user->pingmax;
388                         if (cm->second->flags_needed)
389                         {
390                                 if (!user->IsModeSet(cm->second->flags_needed))
391                                 {
392                                         user->WriteServ("481 %s :Permission Denied- You do not have the required operator privileges",user->nick);
393                                         return;
394                                 }
395                                 if (!user->HasPermission(command))
396                                 {
397                                         user->WriteServ("481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command.c_str());
398                                         return;
399                                 }
400                         }
401                         if ((user->registered == REG_ALL) && (!*user->oper) && (cm->second->IsDisabled()))
402                         {
403                                 /* command is disabled! */
404                                 user->WriteServ("421 %s %s :This command has been disabled.",user->nick,command.c_str());
405                                 return;
406                         }
407                         if (items < cm->second->min_params)
408                         {
409                                 user->WriteServ("461 %s %s :Not enough parameters.", user->nick, command.c_str());
410                                 /* If syntax is given, display this as the 461 reply */
411                                 if ((ServerInstance->Config->SyntaxHints) && (cm->second->syntax.length()))
412                                         user->WriteServ("304 %s :SYNTAX %s %s", user->nick, cm->second->command.c_str(), cm->second->syntax.c_str());
413                                 return;
414                         }
415                         if ((user->registered == REG_ALL) || (cm->second->WorksBeforeReg()))
416                         {
417                                 /* ikky /stats counters */
418                                 cm->second->use_count++;
419                                 cm->second->total_bytes += cmd.length();
420
421                                 int MOD_RESULT = 0;
422                                 FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command,command_p,items,user,true,cmd));
423                                 if (MOD_RESULT == 1)
424                                         return;
425
426                                 /*
427                                  * WARNING: nothing may come after the
428                                  * command handler call, as the handler
429                                  * may free the user structure!
430                                  */
431                                 CmdResult result = cm->second->Handle(command_p,items,user);
432
433                                 if (result != CMD_USER_DELETED)
434                                 {
435                                         FOREACH_MOD(I_OnPostCommand,OnPostCommand(command, command_p, items, user, result,cmd));
436                                 }
437                                 return;
438                         }
439                         else
440                         {
441                                 user->WriteServ("451 %s :You have not registered",command.c_str());
442                                 return;
443                         }
444                 }
445         }
446         else if (user)
447         {
448                 ServerInstance->stats->statsUnknown++;
449                 user->WriteServ("421 %s %s :Unknown command",user->nick,command.c_str());
450         }
451 }
452
453 bool CommandParser::RemoveCommands(const char* source)
454 {
455         nspace::hash_map<std::string,command_t*>::iterator i, safeiter, last_iter;
456         last_iter = cmdlist.begin();
457
458         for (i = cmdlist.begin(); i != cmdlist.end(); i++)
459         {
460                 if (i->second->source == std::string(source))
461                 {
462                         ServerInstance->Log(DEBUG, "removecommands(%s) Removing dependent command: %s", i->second->source.c_str(), i->second->command.c_str());
463                         safeiter = i;
464                         i = last_iter;
465                         cmdlist.erase(safeiter);
466                         continue;
467                 }
468                 last_iter = i;
469         }
470         return true;
471 }
472
473 void CommandParser::ProcessBuffer(std::string &buffer,userrec *user)
474 {
475         std::string::size_type a;
476
477         if (!user)
478                 return;
479
480         while ((a = buffer.rfind("\n")) != std::string::npos)
481                 buffer.erase(a);
482         while ((a = buffer.rfind("\r")) != std::string::npos)
483                 buffer.erase(a);
484
485         if (buffer.length())
486         {
487                 ServerInstance->Log(DEBUG,"CMDIN: %s %s",user->nick,buffer.c_str());
488                 this->ProcessCommand(user,buffer);
489         }
490 }
491
492 bool CommandParser::CreateCommand(command_t *f, void* so_handle)
493 {
494         if (so_handle)
495         {
496                 if (RFCCommands.find(f->command) == RFCCommands.end())
497                 {
498                         RFCCommands[f->command] = so_handle;
499                         ServerInstance->Log(DEFAULT,"Monitoring RFC-specified reloadable command at %8x",so_handle);
500                 }
501                 else
502                 {
503                         ServerInstance->Log(DEFAULT,"ERK! Somehow, we loaded a cmd_*.so file twice! Only the first instance is being recorded.");
504                         return false;
505                 }
506         }
507
508         /* create the command and push it onto the table */
509         if (cmdlist.find(f->command) == cmdlist.end())
510         {
511                 cmdlist[f->command] = f;
512                 ServerInstance->Log(DEBUG,"Added command %s (%lu parameters)",f->command.c_str(),(unsigned long)f->min_params);
513                 return true;
514         }
515         else return false;
516 }
517
518 CommandParser::CommandParser(InspIRCd* Instance) : ServerInstance(Instance)
519 {
520         para.resize(128);
521         this->SetupCommandTable();
522 }
523
524 bool CommandParser::FindSym(void** v, void* h)
525 {
526         *v = dlsym(h, "init_command");
527         const char* err = dlerror();
528         if (err)
529         {
530                 ServerInstance->Log(SPARSE, "Error loading core command: %s\n", err);
531                 return false;
532         }
533         return true;
534 }
535
536 bool CommandParser::ReloadCommand(const char* cmd)
537 {
538         char filename[MAXBUF];
539         char commandname[MAXBUF];
540         int y = 0;
541
542         for (const char* x = cmd; *x; x++, y++)
543                 commandname[y] = toupper(*x);
544
545         commandname[y] = 0;
546
547         SharedObjectList::iterator command = RFCCommands.find(commandname);
548
549         if (command != RFCCommands.end())
550         {
551                 command_t* cmdptr = cmdlist.find(commandname)->second;
552                 cmdlist.erase(cmdlist.find(commandname));
553
554                 for (char* x = commandname; *x; x++)
555                         *x = tolower(*x);
556
557
558                 delete cmdptr;
559                 dlclose(command->second);
560                 RFCCommands.erase(command);
561
562                 snprintf(filename, MAXBUF, "cmd_%s.so", commandname);
563                 this->LoadCommand(filename);
564
565                 return true;
566         }
567
568         return false;
569 }
570
571 CmdResult cmd_reload::Handle(const char** parameters, int pcnt, userrec *user)
572 {
573         user->WriteServ("NOTICE %s :*** Reloading command '%s'",user->nick, parameters[0]);
574         if (ServerInstance->Parser->ReloadCommand(parameters[0]))
575         {
576                 user->WriteServ("NOTICE %s :*** Successfully reloaded command '%s'", user->nick, parameters[0]);
577                 ServerInstance->WriteOpers("*** RELOAD: %s reloaded the '%s' command.", user->nick, parameters[0]);
578                 return CMD_SUCCESS;
579         }
580         else
581         {
582                 user->WriteServ("NOTICE %s :*** Could not reload command '%s'", user->nick, parameters[0]);
583                 return CMD_FAILURE;
584         }
585 }
586
587 void CommandParser::LoadCommand(const char* name)
588 {
589         char filename[MAXBUF];
590         void* h;
591         command_t* (*cmd_factory_func)(InspIRCd*);
592
593         snprintf(filename, MAXBUF, "%s/%s", LIBRARYDIR, name);
594         ServerInstance->Log(DEBUG,"Load command: %s", filename);
595
596         h = dlopen(filename, RTLD_NOW | RTLD_GLOBAL);
597
598         if (!h)
599         {
600                 ServerInstance->Log(SPARSE, "Error loading core command: %s", dlerror());
601                 return;
602         }
603
604         if (this->FindSym((void **)&cmd_factory_func, h))
605         {
606                 command_t* newcommand = cmd_factory_func(ServerInstance);
607                 this->CreateCommand(newcommand, h);
608         }
609 }
610
611 void CommandParser::SetupCommandTable()
612 {
613         RFCCommands.clear();
614
615         DIR* library = opendir(LIBRARYDIR);
616         if (library)
617         {
618                 dirent* entry = NULL;
619                 while ((entry = readdir(library)))
620                 {
621                         if (match(entry->d_name, "cmd_*.so"))
622                         {
623                                 this->LoadCommand(entry->d_name);
624                         }
625                 }
626                 closedir(library);
627         }
628
629         this->CreateCommand(new cmd_reload(ServerInstance));
630 }
631