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