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