]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/command_parse.cpp
f013e0cd5a052f35d9c12be6b0384416fcccdf45
[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         while (tokens.GetToken(para[items]) && (items < 127))
293         {
294                 command_p[items] = para[items].c_str();
295                 items++;
296         }
297
298         std::transform(command.begin(), command.end(), command.begin(), ::toupper);
299                 
300         int MOD_RESULT = 0;
301         FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command,command_p,items,user,false,cmd));
302         if (MOD_RESULT == 1) {
303                 return;
304         }
305
306         nspace::hash_map<std::string,command_t*>::iterator cm = cmdlist.find(command);
307         
308         if (cm != cmdlist.end())
309         {
310                 if (user)
311                 {
312                         /* activity resets the ping pending timer */
313                         user->nping = ServerInstance->Time() + user->pingmax;
314                         if (cm->second->flags_needed)
315                         {
316                                 if (!user->IsModeSet(cm->second->flags_needed))
317                                 {
318                                         user->WriteServ("481 %s :Permission Denied- You do not have the required operator privileges",user->nick);
319                                         return;
320                                 }
321                                 if (!user->HasPermission(command))
322                                 {
323                                         user->WriteServ("481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command.c_str());
324                                         return;
325                                 }
326                         }
327                         if ((user->registered == REG_ALL) && (!*user->oper) && (cm->second->IsDisabled()))
328                         {
329                                 /* command is disabled! */
330                                 user->WriteServ("421 %s %s :This command has been disabled.",user->nick,command.c_str());
331                                 return;
332                         }
333                         if (items < cm->second->min_params)
334                         {
335                                 user->WriteServ("461 %s %s :Not enough parameters.", user->nick, command.c_str());
336                                 /* If syntax is given, display this as the 461 reply */
337                                 if ((ServerInstance->Config->SyntaxHints) && (user->registered == REG_ALL) && (cm->second->syntax.length()))
338                                         user->WriteServ("304 %s :SYNTAX %s %s", user->nick, cm->second->command.c_str(), cm->second->syntax.c_str());
339                                 return;
340                         }
341                         if ((user->registered == REG_ALL) || (cm->second->WorksBeforeReg()))
342                         {
343                                 /* ikky /stats counters */
344                                 cm->second->use_count++;
345                                 cm->second->total_bytes += cmd.length();
346
347                                 int MOD_RESULT = 0;
348                                 FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command,command_p,items,user,true,cmd));
349                                 if (MOD_RESULT == 1)
350                                         return;
351
352                                 /*
353                                  * WARNING: nothing may come after the
354                                  * command handler call, as the handler
355                                  * may free the user structure!
356                                  */
357                                 CmdResult result = cm->second->Handle(command_p,items,user);
358
359                                 FOREACH_MOD(I_OnPostCommand,OnPostCommand(command, command_p, items, user, result,cmd));
360                                 return;
361                         }
362                         else
363                         {
364                                 user->WriteServ("451 %s :You have not registered",command.c_str());
365                                 return;
366                         }
367                 }
368         }
369         else if (user)
370         {
371                 ServerInstance->stats->statsUnknown++;
372                 user->WriteServ("421 %s %s :Unknown command",user->nick,command.c_str());
373         }
374 }
375
376 bool CommandParser::RemoveCommands(const char* source)
377 {
378         nspace::hash_map<std::string,command_t*>::iterator i,safei;
379         for (i = cmdlist.begin(); i != cmdlist.end(); i++)
380         {
381                 safei = i;
382                 safei++;
383                 if (safei != cmdlist.end())
384                 {
385                         RemoveCommand(safei, source);
386                 }
387         }
388         safei = cmdlist.begin();
389         if (safei != cmdlist.end())
390         {
391                 RemoveCommand(safei, source);
392         }
393         return true;
394 }
395
396 void CommandParser::RemoveCommand(nspace::hash_map<std::string,command_t*>::iterator safei, const char* source)
397 {
398         command_t* x = safei->second;
399         if (x->source == std::string(source))
400         {
401                 cmdlist.erase(safei);
402         }
403 }
404
405 void CommandParser::ProcessBuffer(std::string &buffer,userrec *user)
406 {
407         std::string::size_type a;
408
409         if (!user)
410                 return;
411
412         while ((a = buffer.rfind("\n")) != std::string::npos)
413                 buffer.erase(a);
414         while ((a = buffer.rfind("\r")) != std::string::npos)
415                 buffer.erase(a);
416
417         if (buffer.length())
418         {
419                 if (!user->muted)
420                 {
421                         ServerInstance->Log(DEBUG,"-> :%s %s",user->nick,buffer.c_str());
422                         this->ProcessCommand(user,buffer);
423                 }
424         }
425 }
426
427 bool CommandParser::CreateCommand(command_t *f, void* so_handle)
428 {
429         if (so_handle)
430         {
431                 if (RFCCommands.find(f->command) == RFCCommands.end())
432                         RFCCommands[f->command] = so_handle;
433                 else
434                 {
435                         ServerInstance->Log(DEFAULT,"ERK! Somehow, we loaded a cmd_*.so file twice! Only the first instance is being recorded.");
436                         return false;
437                 }
438         }
439
440         /* create the command and push it onto the table */
441         if (cmdlist.find(f->command) == cmdlist.end())
442         {
443                 cmdlist[f->command] = f;
444                 return true;
445         }
446         else return false;
447 }
448
449 CommandParser::CommandParser(InspIRCd* Instance) : ServerInstance(Instance)
450 {
451         para.resize(128);
452         this->SetupCommandTable();
453 }
454
455 bool CommandParser::FindSym(void** v, void* h)
456 {
457         *v = dlsym(h, "init_command");
458         const char* err = dlerror();
459         if (err)
460         {
461                 ServerInstance->Log(SPARSE, "Error loading core command: %s\n", err);
462                 return false;
463         }
464         return true;
465 }
466
467 bool CommandParser::ReloadCommand(const char* cmd)
468 {
469         char filename[MAXBUF];
470         char commandname[MAXBUF];
471         int y = 0;
472
473         for (const char* x = cmd; *x; x++, y++)
474                 commandname[y] = toupper(*x);
475
476         commandname[y] = 0;
477
478         SharedObjectList::iterator command = RFCCommands.find(commandname);
479
480         if (command != RFCCommands.end())
481         {
482                 command_t* cmdptr = cmdlist.find(commandname)->second;
483                 cmdlist.erase(cmdlist.find(commandname));
484
485                 for (char* x = commandname; *x; x++)
486                         *x = tolower(*x);
487
488
489                 delete cmdptr;
490                 dlclose(command->second);
491                 RFCCommands.erase(command);
492
493                 snprintf(filename, MAXBUF, "cmd_%s.so", commandname);
494                 this->LoadCommand(filename);
495
496                 return true;
497         }
498
499         return false;
500 }
501
502 CmdResult cmd_reload::Handle(const char** parameters, int pcnt, userrec *user)
503 {
504         user->WriteServ("NOTICE %s :*** Reloading command '%s'",user->nick, parameters[0]);
505         if (ServerInstance->Parser->ReloadCommand(parameters[0]))
506         {
507                 user->WriteServ("NOTICE %s :*** Successfully reloaded command '%s'", user->nick, parameters[0]);
508                 ServerInstance->WriteOpers("*** RELOAD: %s reloaded the '%s' command.", user->nick, parameters[0]);
509                 return CMD_SUCCESS;
510         }
511         else
512         {
513                 user->WriteServ("NOTICE %s :*** Could not reload command '%s'", user->nick, parameters[0]);
514                 return CMD_FAILURE;
515         }
516 }
517
518 void CommandParser::LoadCommand(const char* name)
519 {
520         char filename[MAXBUF];
521         void* h;
522         command_t* (*cmd_factory_func)(InspIRCd*);
523
524         snprintf(filename, MAXBUF, "%s/%s", LIBRARYDIR, name);
525         h = dlopen(filename, RTLD_NOW | RTLD_GLOBAL);
526
527         if (!h)
528         {
529                 ServerInstance->Log(SPARSE, "Error loading core command: %s", dlerror());
530                 return;
531         }
532
533         if (this->FindSym((void **)&cmd_factory_func, h))
534         {
535                 command_t* newcommand = cmd_factory_func(ServerInstance);
536                 this->CreateCommand(newcommand, h);
537         }
538 }
539
540 void CommandParser::SetupCommandTable()
541 {
542         RFCCommands.clear();
543
544         DIR* library = opendir(LIBRARYDIR);
545         if (library)
546         {
547                 dirent* entry = NULL;
548                 while ((entry = readdir(library)))
549                 {
550                         if (match(entry->d_name, "cmd_*.so"))
551                         {
552                                 this->LoadCommand(entry->d_name);
553                         }
554                 }
555                 closedir(library);
556         }
557
558         this->CreateCommand(new cmd_reload(ServerInstance));
559 }
560