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