]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/command_parse.cpp
Remove some debug here, cuts down boot output
[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                         if (CommandObj->Handle(new_parameters,pcnt,user) == CMD_USER_DELETED)
157                                 return 1;
158
159                         dupes[item.c_str()] = true;
160                 }
161         }
162         return 1;
163 }
164
165 int CommandParser::LoopCall(userrec* user, command_t* CommandObj, const char** parameters, int pcnt, unsigned int splithere)
166 {
167         /* First check if we have more than one item in the list, if we don't we return zero here and the handler
168          * which called us just carries on as it was.
169          */
170         if (!strchr(parameters[splithere],','))
171                 return 0;
172
173         std::map<irc::string, bool> dupes;
174
175         /* Only one commasepstream here */
176         irc::commasepstream items1(parameters[splithere]);
177         std::string item = "*";
178         unsigned int max = 0;
179
180         /* Parse the commasepstream until there are no tokens remaining.
181          * Each token we parse out, call the command handler that called us
182          * with it
183          */
184         while (((item = items1.GetToken()) != "") && (max++ < ServerInstance->Config->MaxTargets))
185         {
186                 if (dupes.find(item.c_str()) == dupes.end())
187                 {
188                         const char* new_parameters[127];
189
190                         for (int t = 0; (t < pcnt) && (t < 127); t++)
191                                 new_parameters[t] = parameters[t];
192
193                         new_parameters[splithere] = item.c_str();
194
195                         parameters[splithere] = item.c_str();
196
197                         /* Execute the command handler over and over. If someone pulls our user
198                          * record out from under us (e.g. if we /kill a comma sep list, and we're
199                          * in that list ourselves) abort if we're gone.
200                          */
201                         if (CommandObj->Handle(new_parameters,pcnt,user) == CMD_USER_DELETED)
202                                 return 1;
203
204                         dupes[item.c_str()] = true;
205                 }
206         }
207         /* By returning 1 we tell our caller that nothing is to be done,
208          * as all the previous calls handled the data. This makes the parent
209          * return without doing any processing.
210          */
211         return 1;
212 }
213
214 bool CommandParser::IsValidCommand(const std::string &commandname, int pcnt, userrec * user)
215 {
216         nspace::hash_map<std::string,command_t*>::iterator n = cmdlist.find(commandname);
217
218         if (n != cmdlist.end())
219         {
220                 if ((pcnt>=n->second->min_params) && (n->second->source != "<core>"))
221                 {
222                         if ((!n->second->flags_needed) || (user->modes[n->second->flags_needed-65]))
223                         {
224                                 if (n->second->flags_needed)
225                                 {
226                                         return ((user->HasPermission(commandname)) || (ServerInstance->ULine(user->server)));
227                                 }
228                                 return true;
229                         }
230                 }
231         }
232         return false;
233 }
234
235 command_t* CommandParser::GetHandler(const std::string &commandname)
236 {
237         nspace::hash_map<std::string,command_t*>::iterator n = cmdlist.find(commandname);
238         if (n != cmdlist.end())
239                 return n->second;
240
241         return NULL;
242 }
243
244 // calls a handler function for a command
245
246 CmdResult CommandParser::CallHandler(const std::string &commandname,const char** parameters, int pcnt, userrec *user)
247 {
248         nspace::hash_map<std::string,command_t*>::iterator n = cmdlist.find(commandname);
249
250         if (n != cmdlist.end())
251         {
252                 if (pcnt >= n->second->min_params)
253                 {
254                         if ((!n->second->flags_needed) || (user->modes[n->second->flags_needed-65]))
255                         {
256                                 if (n->second->flags_needed)
257                                 {
258                                         if ((user->HasPermission(commandname)) || (!IS_LOCAL(user)))
259                                         {
260                                                 return n->second->Handle(parameters,pcnt,user);
261                                         }
262                                 }
263                                 else
264                                 {
265                                         return n->second->Handle(parameters,pcnt,user);
266                                 }
267                         }
268                 }
269         }
270         return CMD_INVALID;
271 }
272
273 void CommandParser::ProcessCommand(userrec *user, std::string &cmd)
274 {
275         const char *command_p[127];
276         int items = 0;
277         irc::tokenstream tokens(cmd);
278         std::string command = tokens.GetToken();
279
280         while (((para[items] = tokens.GetToken()) != "") && (items < 127))
281         {
282                 command_p[items] = para[items].c_str();
283                 items++;
284         }
285
286         std::transform(command.begin(), command.end(), command.begin(), ::toupper);
287                 
288         int MOD_RESULT = 0;
289         FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command,command_p,items,user,false,cmd));
290         if (MOD_RESULT == 1) {
291                 return;
292         }
293
294         nspace::hash_map<std::string,command_t*>::iterator cm = cmdlist.find(command);
295         
296         if (cm != cmdlist.end())
297         {
298                 if (user)
299                 {
300                         /* activity resets the ping pending timer */
301                         user->nping = ServerInstance->Time() + user->pingmax;
302                         if (cm->second->flags_needed)
303                         {
304                                 if (!user->IsModeSet(cm->second->flags_needed))
305                                 {
306                                         user->WriteServ("481 %s :Permission Denied- You do not have the required operator privileges",user->nick);
307                                         return;
308                                 }
309                                 if (!user->HasPermission(command))
310                                 {
311                                         user->WriteServ("481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command.c_str());
312                                         return;
313                                 }
314                         }
315                         if ((user->registered == REG_ALL) && (!*user->oper) && (cm->second->IsDisabled()))
316                         {
317                                 /* command is disabled! */
318                                 user->WriteServ("421 %s %s :This command has been disabled.",user->nick,command.c_str());
319                                 return;
320                         }
321                         if (items < cm->second->min_params)
322                         {
323                                 user->WriteServ("461 %s %s :Not enough parameters.", user->nick, command.c_str());
324                                 /* If syntax is given, display this as the 461 reply */
325                                 if ((ServerInstance->Config->SyntaxHints) && (cm->second->syntax.length()))
326                                         user->WriteServ("304 %s :SYNTAX %s %s", user->nick, cm->second->command.c_str(), cm->second->syntax.c_str());
327                                 return;
328                         }
329                         if ((user->registered == REG_ALL) || (cm->second->WorksBeforeReg()))
330                         {
331                                 /* ikky /stats counters */
332                                 cm->second->use_count++;
333                                 cm->second->total_bytes += cmd.length();
334
335                                 int MOD_RESULT = 0;
336                                 FOREACH_RESULT(I_OnPreCommand,OnPreCommand(command,command_p,items,user,true,cmd));
337                                 if (MOD_RESULT == 1)
338                                         return;
339
340                                 /*
341                                  * WARNING: nothing may come after the
342                                  * command handler call, as the handler
343                                  * may free the user structure!
344                                  */
345                                 CmdResult result = cm->second->Handle(command_p,items,user);
346
347                                 if (result != CMD_USER_DELETED)
348                                 {
349                                         FOREACH_MOD(I_OnPostCommand,OnPostCommand(command, command_p, items, user, result,cmd));
350                                 }
351                                 return;
352                         }
353                         else
354                         {
355                                 user->WriteServ("451 %s :You have not registered",command.c_str());
356                                 return;
357                         }
358                 }
359         }
360         else if (user)
361         {
362                 ServerInstance->stats->statsUnknown++;
363                 user->WriteServ("421 %s %s :Unknown command",user->nick,command.c_str());
364         }
365 }
366
367 bool CommandParser::RemoveCommands(const char* source)
368 {
369         nspace::hash_map<std::string,command_t*>::iterator i,safei;
370         for (i = cmdlist.begin(); i != cmdlist.end(); i++)
371         {
372                 safei = i;
373                 safei++;
374                 if (safei != cmdlist.end())
375                 {
376                         RemoveCommand(safei, source);
377                 }
378         }
379         safei = cmdlist.begin();
380         if (safei != cmdlist.end())
381         {
382                 RemoveCommand(safei, source);
383         }
384         return true;
385 }
386
387 void CommandParser::RemoveCommand(nspace::hash_map<std::string,command_t*>::iterator safei, const char* source)
388 {
389         command_t* x = safei->second;
390         if (x->source == std::string(source))
391         {
392                 cmdlist.erase(safei);
393         }
394 }
395
396 void CommandParser::ProcessBuffer(std::string &buffer,userrec *user)
397 {
398         std::string::size_type a;
399
400         if (!user)
401                 return;
402
403         while ((a = buffer.rfind("\n")) != std::string::npos)
404                 buffer.erase(a);
405         while ((a = buffer.rfind("\r")) != std::string::npos)
406                 buffer.erase(a);
407
408         if (buffer.length())
409         {
410                 ServerInstance->Log(DEBUG,"-> :%s %s",user->nick,buffer.c_str());
411                 this->ProcessCommand(user,buffer);
412         }
413 }
414
415 bool CommandParser::CreateCommand(command_t *f, void* so_handle)
416 {
417         if (so_handle)
418         {
419                 if (RFCCommands.find(f->command) == RFCCommands.end())
420                         RFCCommands[f->command] = so_handle;
421                 else
422                 {
423                         ServerInstance->Log(DEFAULT,"ERK! Somehow, we loaded a cmd_*.so file twice! Only the first instance is being recorded.");
424                         return false;
425                 }
426         }
427
428         /* create the command and push it onto the table */
429         if (cmdlist.find(f->command) == cmdlist.end())
430         {
431                 cmdlist[f->command] = f;
432                 return true;
433         }
434         else return false;
435 }
436
437 CommandParser::CommandParser(InspIRCd* Instance) : ServerInstance(Instance)
438 {
439         para.resize(128);
440         this->SetupCommandTable();
441 }
442
443 bool CommandParser::FindSym(void** v, void* h)
444 {
445         *v = dlsym(h, "init_command");
446         const char* err = dlerror();
447         if (err)
448         {
449                 ServerInstance->Log(SPARSE, "Error loading core command: %s\n", err);
450                 return false;
451         }
452         return true;
453 }
454
455 bool CommandParser::ReloadCommand(const char* cmd)
456 {
457         char filename[MAXBUF];
458         char commandname[MAXBUF];
459         int y = 0;
460
461         for (const char* x = cmd; *x; x++, y++)
462                 commandname[y] = toupper(*x);
463
464         commandname[y] = 0;
465
466         SharedObjectList::iterator command = RFCCommands.find(commandname);
467
468         if (command != RFCCommands.end())
469         {
470                 command_t* cmdptr = cmdlist.find(commandname)->second;
471                 cmdlist.erase(cmdlist.find(commandname));
472
473                 for (char* x = commandname; *x; x++)
474                         *x = tolower(*x);
475
476
477                 delete cmdptr;
478                 dlclose(command->second);
479                 RFCCommands.erase(command);
480
481                 snprintf(filename, MAXBUF, "cmd_%s.so", commandname);
482                 this->LoadCommand(filename);
483
484                 return true;
485         }
486
487         return false;
488 }
489
490 CmdResult cmd_reload::Handle(const char** parameters, int pcnt, userrec *user)
491 {
492         user->WriteServ("NOTICE %s :*** Reloading command '%s'",user->nick, parameters[0]);
493         if (ServerInstance->Parser->ReloadCommand(parameters[0]))
494         {
495                 user->WriteServ("NOTICE %s :*** Successfully reloaded command '%s'", user->nick, parameters[0]);
496                 ServerInstance->WriteOpers("*** RELOAD: %s reloaded the '%s' command.", user->nick, parameters[0]);
497                 return CMD_SUCCESS;
498         }
499         else
500         {
501                 user->WriteServ("NOTICE %s :*** Could not reload command '%s'", user->nick, parameters[0]);
502                 return CMD_FAILURE;
503         }
504 }
505
506 void CommandParser::LoadCommand(const char* name)
507 {
508         char filename[MAXBUF];
509         void* h;
510         command_t* (*cmd_factory_func)(InspIRCd*);
511
512         snprintf(filename, MAXBUF, "%s/%s", LIBRARYDIR, name);
513         h = dlopen(filename, RTLD_NOW | RTLD_GLOBAL);
514
515         if (!h)
516         {
517                 ServerInstance->Log(SPARSE, "Error loading core command: %s", dlerror());
518                 return;
519         }
520
521         if (this->FindSym((void **)&cmd_factory_func, h))
522         {
523                 command_t* newcommand = cmd_factory_func(ServerInstance);
524                 this->CreateCommand(newcommand, h);
525         }
526 }
527
528 void CommandParser::SetupCommandTable()
529 {
530         RFCCommands.clear();
531
532         DIR* library = opendir(LIBRARYDIR);
533         if (library)
534         {
535                 dirent* entry = NULL;
536                 while ((entry = readdir(library)))
537                 {
538                         if (match(entry->d_name, "cmd_*.so"))
539                         {
540                                 this->LoadCommand(entry->d_name);
541                         }
542                 }
543                 closedir(library);
544         }
545
546         this->CreateCommand(new cmd_reload(ServerInstance));
547 }
548