]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
8f2bd0de1c134a52cc94b5be285c4fb05a8c1f32
[user/henk/code/inspircd.git] / src / inspircd.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  Inspire is copyright (C) 2002-2005 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 /* Now with added unF! ;) */
18
19 using namespace std;
20
21 #include "inspircd_config.h"
22 #include "inspircd.h"
23 #include "inspircd_io.h"
24 #include <unistd.h>
25 #include <fcntl.h>
26 #include <sys/errno.h>
27 #include <sys/ioctl.h>
28 #include <sys/utsname.h>
29 #include <time.h>
30 #include <string>
31 #ifdef GCC3
32 #include <ext/hash_map>
33 #else
34 #include <hash_map>
35 #endif
36 #include <map>
37 #include <sstream>
38 #include <vector>
39 #include <deque>
40 #include <sched.h>
41 #ifdef THREADED_DNS
42 #include <pthread.h>
43 #endif
44 #include "users.h"
45 #include "ctables.h"
46 #include "globals.h"
47 #include "modules.h"
48 #include "dynamic.h"
49 #include "wildcard.h"
50 #include "message.h"
51 #include "mode.h"
52 #include "commands.h"
53 #include "xline.h"
54 #include "inspstring.h"
55 #include "dnsqueue.h"
56 #include "helperfuncs.h"
57 #include "hashcomp.h"
58 #include "socketengine.h"
59 #include "userprocess.h"
60 #include "socket.h"
61 #include "dns.h"
62 #include "typedefs.h"
63
64 InspIRCd* ServerInstance;
65
66 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
67 int WHOWAS_MAX = 100;  // default 100 people maximum in the WHOWAS list
68
69 extern std::vector<Module*> modules;
70 extern std::vector<ircd_module*> factory;
71 std::vector<InspSocket*> module_sockets;
72
73 extern int MODCOUNT;
74 int openSockfd[MAXSOCKS];
75 sockaddr_in client,server;
76 socklen_t length;
77
78 extern InspSocket* socket_ref[65535];
79
80 time_t TIME = time(NULL), OLDTIME = time(NULL);
81
82 SocketEngine* SE = NULL;
83
84 // This table references users by file descriptor.
85 // its an array to make it VERY fast, as all lookups are referenced
86 // by an integer, meaning there is no need for a scan/search operation.
87 userrec* fd_ref_table[65536];
88
89 serverstats* stats = new serverstats;
90 Server* MyServer = new Server;
91 ServerConfig *Config = new ServerConfig;
92
93 user_hash clientlist;
94 chan_hash chanlist;
95 whowas_hash whowas;
96 command_table cmdlist;
97 servernamelist servernames;
98 int BoundPortCount = 0;
99 char lowermap[255];
100
101 void AddServerName(std::string servername)
102 {
103         log(DEBUG,"Adding server name: %s",servername.c_str());
104         for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
105         {
106                 if (*a == servername)
107                         return;
108         }
109         servernames.push_back(servername);
110 }
111
112 const char* FindServerNamePtr(std::string servername)
113 {
114         for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
115         {
116                 if (*a == servername)
117                         return a->c_str();
118         }
119         AddServerName(servername);
120         return FindServerNamePtr(servername);
121 }
122
123 std::string InspIRCd::GetRevision()
124 {
125         /* w00t got me to replace a bunch of strtok_r
126          * with something nicer, so i did this. Its the
127          * same thing really, only in C++. It places the
128          * text into a std::stringstream which is a readable
129          * and writeable buffer stream, and then pops two
130          * words off it, space delimited. Because it reads
131          * into the same variable twice, the first word
132          * is discarded, and the second one returned.
133          */
134         std::stringstream Revision("$Revision$");
135         std::string single;
136         Revision >> single >> single;
137         return single;
138 }
139
140
141 /* This function pokes and hacks at a parameter list like the following:
142  *
143  * PART #winbot,#darkgalaxy :m00!
144  *
145  * to turn it into a series of individual calls like this:
146  *
147  * PART #winbot :m00!
148  * PART #darkgalaxy :m00!
149  *
150  * The seperate calls are sent to a callback function provided by the caller
151  * (the caller will usually call itself recursively). The callback function
152  * must be a command handler. Calling this function on a line with no list causes
153  * no action to be taken. You must provide a starting and ending parameter number
154  * where the range of the list can be found, useful if you have a terminating
155  * parameter as above which is actually not part of the list, or parameters
156  * before the actual list as well. This code is used by many functions which
157  * can function as "one to list" (see the RFC) */
158
159 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
160 {
161         char plist[MAXBUF];
162         char *param;
163         char *pars[32];
164         char blog[32][MAXBUF];
165         char blog2[32][MAXBUF];
166         int j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
167         char keystr[MAXBUF];
168         char moo[MAXBUF];
169
170         for (int i = 0; i <32; i++)
171                 strcpy(blog[i],"");
172
173         for (int i = 0; i <32; i++)
174                 strcpy(blog2[i],"");
175
176         strcpy(moo,"");
177         for (int i = 0; i <10; i++)
178         {
179                 if (!parameters[i])
180                 {
181                         parameters[i] = moo;
182                 }
183         }
184         if (joins)
185         {
186                 if (pcnt > 1) /* we have a key to copy */
187                 {
188                         strlcpy(keystr,parameters[1],MAXBUF);
189                 }
190         }
191
192         if (!parameters[start])
193         {
194                 return 0;
195         }
196         if (!strchr(parameters[start],','))
197         {
198                 return 0;
199         }
200         strcpy(plist,"");
201         for (int i = start; i <= end; i++)
202         {
203                 if (parameters[i])
204                 {
205                         strlcat(plist,parameters[i],MAXBUF);
206                 }
207         }
208         
209         j = 0;
210         param = plist;
211
212         t = strlen(plist);
213         for (int i = 0; i < t; i++)
214         {
215                 if (plist[i] == ',')
216                 {
217                         plist[i] = '\0';
218                         strlcpy(blog[j++],param,MAXBUF);
219                         param = plist+i+1;
220                         if (j>20)
221                         {
222                                 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
223                                 return 1;
224                         }
225                 }
226         }
227         strlcpy(blog[j++],param,MAXBUF);
228         total = j;
229
230         if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
231         {
232                 strcat(keystr,",");
233         }
234         
235         if ((joins) && (keystr))
236         {
237                 if (strchr(keystr,','))
238                 {
239                         j = 0;
240                         param = keystr;
241                         t2 = strlen(keystr);
242                         for (int i = 0; i < t2; i++)
243                         {
244                                 if (keystr[i] == ',')
245                                 {
246                                         keystr[i] = '\0';
247                                         strlcpy(blog2[j++],param,MAXBUF);
248                                         param = keystr+i+1;
249                                 }
250                         }
251                         strlcpy(blog2[j++],param,MAXBUF);
252                         total2 = j;
253                 }
254         }
255
256         for (j = 0; j < total; j++)
257         {
258                 if (blog[j])
259                 {
260                         pars[0] = blog[j];
261                 }
262                 for (q = end; q < pcnt-1; q++)
263                 {
264                         if (parameters[q+1])
265                         {
266                                 pars[q-end+1] = parameters[q+1];
267                         }
268                 }
269                 if ((joins) && (parameters[1]))
270                 {
271                         if (pcnt > 1)
272                         {
273                                 pars[1] = blog2[j];
274                         }
275                         else
276                         {
277                                 pars[1] = NULL;
278                         }
279                 }
280                 /* repeatedly call the function with the hacked parameter list */
281                 if ((joins) && (pcnt > 1))
282                 {
283                         if (pars[1])
284                         {
285                                 // pars[1] already set up and containing key from blog2[j]
286                                 fn(pars,2,u);
287                         }
288                         else
289                         {
290                                 pars[1] = parameters[1];
291                                 fn(pars,2,u);
292                         }
293                 }
294                 else
295                 {
296                         fn(pars,pcnt-(end-start),u);
297                 }
298         }
299
300         return 1;
301 }
302
303
304
305 InspIRCd::InspIRCd(int argc, char** argv)
306 {
307         Start();
308         module_sockets.clear();
309         this->startup_time = time(NULL);
310         srand(time(NULL));
311         log(DEBUG,"*** InspIRCd starting up!");
312         if (!FileExists(CONFIG_FILE))
313         {
314                 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
315                 log(DEFAULT,"main: no config");
316                 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
317                 Exit(ERROR);
318         }
319         if (argc > 1) {
320                 for (int i = 1; i < argc; i++)
321                 {
322                         if (!strcmp(argv[i],"-nofork")) {
323                                 Config->nofork = true;
324                         }
325                         if (!strcmp(argv[i],"-wait")) {
326                                 sleep(6);
327                         }
328                         if (!strcmp(argv[i],"-nolimit")) {
329                                 Config->unlimitcore = true;
330                         }
331                 }
332         }
333
334         strlcpy(Config->MyExecutable,argv[0],MAXBUF);
335         
336         // initialize the lowercase mapping table
337         for (unsigned int cn = 0; cn < 256; cn++)
338                 lowermap[cn] = cn;
339         // lowercase the uppercase chars
340         for (unsigned int cn = 65; cn < 91; cn++)
341                 lowermap[cn] = tolower(cn);
342         // now replace the specific chars for scandanavian comparison
343         lowermap[(unsigned)'['] = '{';
344         lowermap[(unsigned)']'] = '}';
345         lowermap[(unsigned)'\\'] = '|';
346
347
348         OpenLog(argv, argc);
349         Config->ClearStack();
350         Config->Read(true,NULL);
351         CheckRoot();
352         SetupCommandTable();
353         AddServerName(Config->ServerName);
354         CheckDie();
355         BoundPortCount = BindPorts();
356
357         printf("\n");
358         if (!Config->nofork)
359         {
360                 if (DaemonSeed() == ERROR)
361                 {
362                         printf("ERROR: could not go into daemon mode. Shutting down.\n");
363                         Exit(ERROR);
364                 }
365         }
366
367         /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
368          * initialize the socket engine.
369          */
370         SE = new SocketEngine();
371
372         /* We must load the modules AFTER initializing the socket engine, now */
373         LoadAllModules();
374
375         printf("\nInspIRCd is now running!\n");
376
377         return;
378 }
379
380 #ifdef THREADED_DNS
381 void* dns_task(void* arg)
382 {
383         userrec* u = (userrec*)arg;
384         log(DEBUG,"DNS thread for user %s",u->nick);
385         DNS dns1;
386         DNS dns2;
387         std::string host;
388         std::string ip;
389         if (dns1.ReverseLookup(u->ip))
390         {
391                 log(DEBUG,"DNS Step 1");
392                 while (!dns1.HasResult())
393                 {
394                         usleep(100);
395                 }
396                 host = dns1.GetResult();
397                 if (host != "")
398                 {
399                         log(DEBUG,"DNS Step 2: '%s'",host.c_str());
400                         if (dns2.ForwardLookup(host))
401                         {
402                                 while (!dns2.HasResult())
403                                 {
404                                         usleep(100);
405                                 }
406                                 ip = dns2.GetResultIP();
407                                 log(DEBUG,"DNS Step 3 '%s'(%d) '%s'(%d)",ip.c_str(),ip.length(),u->ip,strlen(u->ip));
408                                 if (ip == std::string(u->ip))
409                                 {
410                                         log(DEBUG,"DNS Step 4");
411                                         if (host.length() < 160)
412                                         {
413                                                 log(DEBUG,"DNS Step 5");
414                                                 strcpy(u->host,host.c_str());
415                                                 strcpy(u->dhost,host.c_str());
416                                         }
417                                 }
418                         }
419                 }
420         }
421         u->dns_done = true;
422         return NULL;
423 }
424 #endif
425
426 std::string InspIRCd::GetVersionString()
427 {
428         char versiondata[MAXBUF];
429 #ifdef THREADED_DNS
430         char dnsengine[] = "multithread";
431 #else
432         char dnsengine[] = "singlethread";
433 #endif
434         snprintf(versiondata,MAXBUF,"%s Rev. %s %s :%s [FLAGS=%lu,%s,%s]",VERSION,GetRevision().c_str(),Config->ServerName,SYSTEM,(unsigned long)OPTIMISATION,SE->GetName().c_str(),dnsengine);
435         return versiondata;
436 }
437
438
439 bool is_valid_cmd(std::string &commandname, int pcnt, userrec * user)
440 {
441         for (unsigned int i = 0; i < cmdlist.size(); i++)
442         {
443                 if (!strcasecmp(cmdlist[i].command,commandname.c_str()))
444                 {
445                         if (cmdlist[i].handler_function)
446                         {
447                                 if ((pcnt>=cmdlist[i].min_params) && (strcasecmp(cmdlist[i].source,"<core>")))
448                                 {
449                                         if ((strchr(user->modes,cmdlist[i].flags_needed)) || (!cmdlist[i].flags_needed))
450                                         {
451                                                 if (cmdlist[i].flags_needed)
452                                                 {
453                                                         if ((user->HasPermission(commandname)) || (is_uline(user->server)))
454                                                         {
455                                                                 return true;
456                                                         }
457                                                         else
458                                                         {
459                                                                 return false;
460                                                         }
461                                                 }
462                                                 return true;
463                                         }
464                                 }
465                         }
466                 }
467         }
468         return false;
469 }
470
471 // calls a handler function for a command
472
473 void call_handler(std::string &commandname,char **parameters, int pcnt, userrec *user)
474 {
475         for (unsigned int i = 0; i < cmdlist.size(); i++)
476         {
477                 if (!strcasecmp(cmdlist[i].command,commandname.c_str()))
478                 {
479                         if (cmdlist[i].handler_function)
480                         {
481                                 if (pcnt>=cmdlist[i].min_params)
482                                 {
483                                         if ((strchr(user->modes,cmdlist[i].flags_needed)) || (!cmdlist[i].flags_needed))
484                                         {
485                                                 if (cmdlist[i].flags_needed)
486                                                 {
487                                                         if ((user->HasPermission(commandname)) || (is_uline(user->server)))
488                                                         {
489                                                                 cmdlist[i].handler_function(parameters,pcnt,user);
490                                                         }
491                                                 }
492                                                 else
493                                                 {
494                                                         cmdlist[i].handler_function(parameters,pcnt,user);
495                                                 }
496                                         }
497                                 }
498                         }
499                 }
500         }
501 }
502
503 int process_parameters(char **command_p,char *parameters)
504 {
505         int j = 0;
506         int q = strlen(parameters);
507         if (!q)
508         {
509                 /* no parameters, command_p invalid! */
510                 return 0;
511         }
512         if (parameters[0] == ':')
513         {
514                 command_p[0] = parameters+1;
515                 return 1;
516         }
517         if (q)
518         {
519                 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
520                 {
521                         /* only one parameter */
522                         command_p[0] = parameters;
523                         if (parameters[0] == ':')
524                         {
525                                 if (strchr(parameters,' ') != NULL)
526                                 {
527                                         command_p[0]++;
528                                 }
529                         }
530                         return 1;
531                 }
532         }
533         command_p[j++] = parameters;
534         for (int i = 0; i <= q; i++)
535         {
536                 if (parameters[i] == ' ')
537                 {
538                         command_p[j++] = parameters+i+1;
539                         parameters[i] = '\0';
540                         if (command_p[j-1][0] == ':')
541                         {
542                                 *command_p[j-1]++; /* remove dodgy ":" */
543                                 break;
544                                 /* parameter like this marks end of the sequence */
545                         }
546                 }
547         }
548         return j; /* returns total number of items in the list */
549 }
550
551 void process_command(userrec *user, char* cmd)
552 {
553         char *parameters;
554         char *command;
555         char *command_p[127];
556         char p[MAXBUF], temp[MAXBUF];
557         int j, items, cmd_found;
558
559         for (int i = 0; i < 127; i++)
560                 command_p[i] = NULL;
561
562         if (!user)
563         {
564                 return;
565         }
566         if (!cmd)
567         {
568                 return;
569         }
570         if (!cmd[0])
571         {
572                 return;
573         }
574         
575         int total_params = 0;
576         if (strlen(cmd)>2)
577         {
578                 for (unsigned int q = 0; q < strlen(cmd)-1; q++)
579                 {
580                         if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
581                         {
582                                 total_params++;
583                                 // found a 'trailing', we dont count them after this.
584                                 break;
585                         }
586                         if (cmd[q] == ' ')
587                                 total_params++;
588                 }
589         }
590
591         // another phidjit bug...
592         if (total_params > 126)
593         {
594                 *(strchr(cmd,' ')) = '\0';
595                 WriteServ(user->fd,"421 %s %s :Too many parameters given",user->nick,cmd);
596                 return;
597         }
598
599         strlcpy(temp,cmd,MAXBUF);
600         
601         std::string tmp = cmd;
602         for (int i = 0; i <= MODCOUNT; i++)
603         {
604                 std::string oldtmp = tmp;
605                 modules[i]->OnServerRaw(tmp,true,user);
606                 if (oldtmp != tmp)
607                 {
608                         log(DEBUG,"A Module changed the input string!");
609                         log(DEBUG,"New string: %s",tmp.c_str());
610                         log(DEBUG,"Old string: %s",oldtmp.c_str());
611                         break;
612                 }
613         }
614         strlcpy(cmd,tmp.c_str(),MAXBUF);
615         strlcpy(temp,cmd,MAXBUF);
616
617         if (!strchr(cmd,' '))
618         {
619                 /* no parameters, lets skip the formalities and not chop up
620                  * the string */
621                 log(DEBUG,"About to preprocess command with no params");
622                 items = 0;
623                 command_p[0] = NULL;
624                 parameters = NULL;
625                 for (unsigned int i = 0; i <= strlen(cmd); i++)
626                 {
627                         cmd[i] = toupper(cmd[i]);
628                 }
629                 command = cmd;
630         }
631         else
632         {
633                 strcpy(cmd,"");
634                 j = 0;
635                 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
636                 for (unsigned int i = 0; i < strlen(temp); i++)
637                 {
638                         if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
639                         {
640                                 cmd[j++] = temp[i];
641                                 cmd[j] = 0;
642                         }
643                 }
644                 /* split the full string into a command plus parameters */
645                 parameters = p;
646                 strcpy(p," ");
647                 command = cmd;
648                 if (strchr(cmd,' '))
649                 {
650                         for (unsigned int i = 0; i <= strlen(cmd); i++)
651                         {
652                                 /* capitalise the command ONLY, leave params intact */
653                                 cmd[i] = toupper(cmd[i]);
654                                 /* are we nearly there yet?! :P */
655                                 if (cmd[i] == ' ')
656                                 {
657                                         command = cmd;
658                                         parameters = cmd+i+1;
659                                         cmd[i] = '\0';
660                                         break;
661                                 }
662                         }
663                 }
664                 else
665                 {
666                         for (unsigned int i = 0; i <= strlen(cmd); i++)
667                         {
668                                 cmd[i] = toupper(cmd[i]);
669                         }
670                 }
671
672         }
673         cmd_found = 0;
674         
675         if (strlen(command)>MAXCOMMAND)
676         {
677                 WriteServ(user->fd,"421 %s %s :Command too long",user->nick,command);
678                 return;
679         }
680         
681         for (unsigned int x = 0; x < strlen(command); x++)
682         {
683                 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
684                 {
685                         if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
686                         {
687                                 if (strchr("@!\"$%^&*(){}[]_=+;:'#~,<>/?\\|`",command[x]))
688                                 {
689                                         stats->statsUnknown++;
690                                         WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
691                                         return;
692                                 }
693                         }
694                 }
695         }
696
697         std::string xcommand = command;
698         for (unsigned int i = 0; i != cmdlist.size(); i++)
699         {
700                 if (cmdlist[i].command[0])
701                 {
702                         if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
703                         {
704                                 if (parameters)
705                                 {
706                                         if (parameters[0])
707                                         {
708                                                 items = process_parameters(command_p,parameters);
709                                         }
710                                         else
711                                         {
712                                                 items = 0;
713                                                 command_p[0] = NULL;
714                                         }
715                                 }
716                                 else
717                                 {
718                                         items = 0;
719                                         command_p[0] = NULL;
720                                 }
721                                 
722                                 if (user)
723                                 {
724                                         /* activity resets the ping pending timer */
725                                         user->nping = TIME + user->pingmax;
726                                         if ((items) < cmdlist[i].min_params)
727                                         {
728                                                 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
729                                                 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
730                                                 return;
731                                         }
732                                         if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
733                                         {
734                                                 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
735                                                 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
736                                                 cmd_found = 1;
737                                                 return;
738                                         }
739                                         if ((cmdlist[i].flags_needed) && (!user->HasPermission(xcommand)))
740                                         {
741                                                 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
742                                                 WriteServ(user->fd,"481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command);
743                                                 cmd_found = 1;
744                                                 return;
745                                         }
746                                         /* if the command isnt USER, PASS, or NICK, and nick is empty,
747                                          * deny command! */
748                                         if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
749                                         {
750                                                 if ((!isnick(user->nick)) || (user->registered != 7))
751                                                 {
752                                                         log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
753                                                         WriteServ(user->fd,"451 %s :You have not registered",command);
754                                                         return;
755                                                 }
756                                         }
757                                         if ((user->registered == 7) && (!strchr(user->modes,'o')))
758                                         {
759                                                 std::stringstream dcmds(Config->DisabledCommands);
760                                                 while (!dcmds.eof())
761                                                 {
762                                                         std::string thiscmd;
763                                                         dcmds >> thiscmd;
764                                                         if (!strcasecmp(thiscmd.c_str(),command))
765                                                         {
766                                                                 // command is disabled!
767                                                                 WriteServ(user->fd,"421 %s %s :This command has been disabled.",user->nick,command);
768                                                                 return;
769                                                         }
770                                                 }
771                                         }
772                                         if ((user->registered == 7) || (!strncmp(command,"USER",4)) || (!strncmp(command,"NICK",4)) || (!strncmp(command,"PASS",4)))
773                                         {
774                                                 if (cmdlist[i].handler_function)
775                                                 {
776                                                         
777                                                         /* ikky /stats counters */
778                                                         if (temp)
779                                                         {
780                                                                 cmdlist[i].use_count++;
781                                                                 cmdlist[i].total_bytes+=strlen(temp);
782                                                         }
783
784                                                         int MOD_RESULT = 0;
785                                                         FOREACH_RESULT(OnPreCommand(command,command_p,items,user));
786                                                         if (MOD_RESULT == 1) {
787                                                                 return;
788                                                         }
789
790                                                         /* WARNING: nothing may come after the
791                                                          * command handler call, as the handler
792                                                          * may free the user structure! */
793
794                                                         cmdlist[i].handler_function(command_p,items,user);
795                                                 }
796                                                 return;
797                                         }
798                                         else
799                                         {
800                                                 WriteServ(user->fd,"451 %s :You have not registered",command);
801                                                 return;
802                                         }
803                                 }
804                                 cmd_found = 1;
805                         }
806                 }
807         }
808         if ((!cmd_found) && (user))
809         {
810                 stats->statsUnknown++;
811                 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
812         }
813 }
814
815 bool removecommands(const char* source)
816 {
817         bool go_again = true;
818         while (go_again)
819         {
820                 go_again = false;
821                 for (std::deque<command_t>::iterator i = cmdlist.begin(); i != cmdlist.end(); i++)
822                 {
823                         if (!strcmp(i->source,source))
824                         {
825                                 log(DEBUG,"removecommands(%s) Removing dependent command: %s",i->source,i->command);
826                                 cmdlist.erase(i);
827                                 go_again = true;
828                                 break;
829                         }
830                 }
831         }
832         return true;
833 }
834
835
836 void process_buffer(const char* cmdbuf,userrec *user)
837 {
838         if (!user)
839         {
840                 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
841                 return;
842         }
843         char cmd[MAXBUF];
844         if (!cmdbuf)
845         {
846                 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
847                 return;
848         }
849         if (!cmdbuf[0])
850         {
851                 return;
852         }
853         while (*cmdbuf == ' ') cmdbuf++; // strip leading spaces
854
855         strlcpy(cmd,cmdbuf,MAXBUF);
856         if (!cmd[0])
857         {
858                 return;
859         }
860         int sl = strlen(cmd)-1;
861         if ((cmd[sl] == 13) || (cmd[sl] == 10))
862         {
863                 cmd[sl] = '\0';
864         }
865         sl = strlen(cmd)-1;
866         if ((cmd[sl] == 13) || (cmd[sl] == 10))
867         {
868                 cmd[sl] = '\0';
869         }
870         sl = strlen(cmd)-1;
871         while (cmd[sl] == ' ') // strip trailing spaces
872         {
873                 cmd[sl] = '\0';
874                 sl = strlen(cmd)-1;
875         }
876
877         if (!cmd[0])
878         {
879                 return;
880         }
881         log(DEBUG,"CMDIN: %s %s",user->nick,cmd);
882         tidystring(cmd);
883         if ((user) && (cmd))
884         {
885                 process_command(user,cmd);
886         }
887 }
888
889 char* InspIRCd::ModuleError()
890 {
891         return MODERR;
892 }
893
894 void InspIRCd::erase_factory(int j)
895 {
896         int v = 0;
897         for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
898         {
899                 if (v == j)
900                 {
901                         factory.erase(t);
902                         factory.push_back(NULL);
903                         return;
904                 }
905                 v++;
906         }
907 }
908
909 void InspIRCd::erase_module(int j)
910 {
911         int v1 = 0;
912         for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
913         {
914                 if (v1 == j)
915                 {
916                         delete *m;
917                         modules.erase(m);
918                         modules.push_back(NULL);
919                         break;
920                 }
921                 v1++;
922         }
923         int v2 = 0;
924         for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
925         {
926                 if (v2 == j)
927                 {
928                        Config->module_names.erase(v);
929                        break;
930                 }
931                 v2++;
932         }
933
934 }
935
936 bool InspIRCd::UnloadModule(const char* filename)
937 {
938         std::string filename_str = filename;
939         for (unsigned int j = 0; j != Config->module_names.size(); j++)
940         {
941                 if (Config->module_names[j] == filename_str)
942                 {
943                         if (modules[j]->GetVersion().Flags & VF_STATIC)
944                         {
945                                 log(DEFAULT,"Failed to unload STATIC module %s",filename);
946                                 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
947                                 return false;
948                         }
949                         /* Give the module a chance to tidy out all its metadata */
950                         for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
951                         {
952                                 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
953                         }
954                         for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
955                         {
956                                 modules[j]->OnCleanup(TYPE_USER,u->second);
957                         }
958                         FOREACH_MOD OnUnloadModule(modules[j],Config->module_names[j]);
959                         // found the module
960                         log(DEBUG,"Deleting module...");
961                         erase_module(j);
962                         log(DEBUG,"Erasing module entry...");
963                         erase_factory(j);
964                         log(DEBUG,"Removing dependent commands...");
965                         removecommands(filename);
966                         log(DEFAULT,"Module %s unloaded",filename);
967                         MODCOUNT--;
968                         return true;
969                 }
970         }
971         log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
972         snprintf(MODERR,MAXBUF,"Module not loaded");
973         return false;
974 }
975
976 bool InspIRCd::LoadModule(const char* filename)
977 {
978         char modfile[MAXBUF];
979 #ifdef STATIC_LINK
980         snprintf(modfile,MAXBUF,"%s",filename);
981 #else
982         snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
983 #endif
984         std::string filename_str = filename;
985 #ifndef STATIC_LINK
986         if (!DirValid(modfile))
987         {
988                 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
989                 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
990                 return false;
991         }
992 #endif
993         log(DEBUG,"Loading module: %s",modfile);
994 #ifndef STATIC_LINK
995         if (FileExists(modfile))
996         {
997 #endif
998                 for (unsigned int j = 0; j < Config->module_names.size(); j++)
999                 {
1000                         if (Config->module_names[j] == filename_str)
1001                         {
1002                                 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
1003                                 snprintf(MODERR,MAXBUF,"Module already loaded");
1004                                 return false;
1005                         }
1006                 }
1007                 ircd_module* a = new ircd_module(modfile);
1008                 factory[MODCOUNT+1] = a;
1009                 if (factory[MODCOUNT+1]->LastError())
1010                 {
1011                         log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
1012                         snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
1013                         MODCOUNT--;
1014                         return false;
1015                 }
1016                 if (factory[MODCOUNT+1]->factory)
1017                 {
1018                         Module* m = factory[MODCOUNT+1]->factory->CreateModule(MyServer);
1019                         modules[MODCOUNT+1] = m;
1020                         /* save the module and the module's classfactory, if
1021                          * this isnt done, random crashes can occur :/ */
1022                         Config->module_names.push_back(filename);
1023                 }
1024                 else
1025                 {
1026                         log(DEFAULT,"Unable to load %s",modfile);
1027                         snprintf(MODERR,MAXBUF,"Factory function failed!");
1028                         return false;
1029                 }
1030 #ifndef STATIC_LINK
1031         }
1032         else
1033         {
1034                 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
1035                 snprintf(MODERR,MAXBUF,"Module file could not be found");
1036                 return false;
1037         }
1038 #endif
1039         MODCOUNT++;
1040         FOREACH_MOD OnLoadModule(modules[MODCOUNT],filename_str);
1041         return true;
1042 }
1043
1044 int InspIRCd::Run()
1045 {
1046         bool expire_run = false;
1047         std::vector<int> activefds;
1048         int incomingSockfd;
1049         int in_port;
1050         userrec* cu = NULL;
1051         InspSocket* s = NULL;
1052         InspSocket* s_del = NULL;
1053         char* target;
1054         unsigned int numberactive;
1055         sockaddr_in sock_us;     // our port number
1056         socklen_t uslen;         // length of our port number
1057
1058         if (!Config->nofork)
1059         {
1060                 freopen("/dev/null","w",stdout);
1061                 freopen("/dev/null","w",stderr);
1062         }
1063
1064         /* Add the listening sockets used for client inbound connections
1065          * to the socket engine
1066          */
1067         for (int count = 0; count < BoundPortCount; count++)
1068                 SE->AddFd(openSockfd[count],true,X_LISTEN);
1069
1070         WritePID(Config->PID);
1071
1072         /* main loop, this never returns */
1073         for (;;)
1074         {
1075                 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
1076                  * Once per loop iteration is pleanty.
1077                  */
1078                 OLDTIME = TIME;
1079                 TIME = time(NULL);
1080
1081                 /* Run background module timers every few seconds
1082                  * (the docs say modules shouldnt rely on accurate
1083                  * timing using this event, so we dont have to
1084                  * time this exactly).
1085                  */
1086                 if (((TIME % 8) == 0) && (!expire_run))
1087                 {
1088                         expire_lines();
1089                         FOREACH_MOD OnBackgroundTimer(TIME);
1090                         expire_run = true;
1091                         continue;
1092                 }
1093                 if ((TIME % 8) == 1)
1094                         expire_run = false;
1095                 
1096                 /* Once a second, do the background processing */
1097                 if (TIME != OLDTIME)
1098                         while (DoBackgroundUserStuff(TIME));
1099
1100                 /* Call the socket engine to wait on the active
1101                  * file descriptors. The socket engine has everything's
1102                  * descriptors in its list... dns, modules, users,
1103                  * servers... so its nice and easy, just one call.
1104                  */
1105                 SE->Wait(activefds);
1106
1107                 /**
1108                  * Now process each of the fd's. For users, we have a fast
1109                  * lookup table which can find a user by file descriptor, so
1110                  * processing them by fd isnt expensive. If we have a lot of
1111                  * listening ports or module sockets though, things could get
1112                  * ugly.
1113                  */
1114                 numberactive = activefds.size();
1115                 for (unsigned int activefd = 0; activefd < numberactive; activefd++)
1116                 {
1117                         int socket_type = SE->GetType(activefds[activefd]);
1118                         switch (socket_type)
1119                         {
1120                                 case X_ESTAB_CLIENT:
1121
1122                                         cu = fd_ref_table[activefds[activefd]];
1123                                         if (cu)
1124                                                 ProcessUser(cu);
1125
1126                                 break;
1127
1128                                 case X_ESTAB_MODULE:
1129
1130                                         /* Process module-owned sockets.
1131                                          * Modules are encouraged to inherit their sockets from
1132                                          * InspSocket so we can process them neatly like this.
1133                                          */
1134                                         s = socket_ref[activefds[activefd]];
1135
1136                                         if ((s) && (!s->Poll()))
1137                                         {
1138                                                 log(DEBUG,"Socket poll returned false, close and bail");
1139                                                 SE->DelFd(s->GetFd());
1140                                                 for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
1141                                                 {
1142                                                         s_del = (InspSocket*)*a;
1143                                                         if ((s_del) && (s_del->GetFd() == activefds[activefd]))
1144                                                         {
1145                                                                 module_sockets.erase(a);
1146                                                                 break;
1147                                                         }
1148                                                 }
1149                                                 s->Close();
1150                                                 delete s;
1151                                         }
1152
1153                                 break;
1154
1155                                 case X_ESTAB_DNS:
1156
1157                                         /* When we are using single-threaded dns,
1158                                          * the sockets for dns end up in our mainloop.
1159                                          * When we are using multi-threaded dns,
1160                                          * each thread has its own basic poll() loop
1161                                          * within it, making them 'fire and forget'
1162                                          * and independent of the mainloop.
1163                                          */
1164 #ifndef THREADED_DNS
1165                                         dns_poll(activefds[activefd]);
1166 #endif
1167                                 break;
1168                                 
1169                                 case X_LISTEN:
1170
1171                                         /* It's a listener */
1172                                         uslen = sizeof(sock_us);
1173                                         length = sizeof(client);
1174                                         incomingSockfd = accept (activefds[activefd],(struct sockaddr*)&client,&length);
1175                                         if (!getsockname(incomingSockfd,(sockaddr*)&sock_us,&uslen))
1176                                         {
1177                                                 in_port = ntohs(sock_us.sin_port);
1178                                                 log(DEBUG,"Accepted socket %d",incomingSockfd);
1179                                                 target = (char*)inet_ntoa(client.sin_addr);
1180                                                 /* Years and years ago, we used to resolve here
1181                                                  * using gethostbyaddr(). That is sucky and we
1182                                                  * don't do that any more...
1183                                                  */
1184                                                 if (incomingSockfd >= 0)
1185                                                 {
1186                                                         FOREACH_MOD OnRawSocketAccept(incomingSockfd, target, in_port);
1187                                                         stats->statsAccept++;
1188                                                         AddClient(incomingSockfd, target, in_port, false, target);
1189                                                         log(DEBUG,"Adding client on port %lu fd=%lu",(unsigned long)in_port,(unsigned long)incomingSockfd);
1190                                                 }
1191                                                 else
1192                                                 {
1193                                                         WriteOpers("*** WARNING: accept() failed on port %lu (%s)",(unsigned long)in_port,target);
1194                                                         log(DEBUG,"accept failed: %lu",(unsigned long)in_port);
1195                                                         stats->statsRefused++;
1196                                                 }
1197                                         }
1198                                         else
1199                                         {
1200                                                 log(DEBUG,"Couldnt look up the port number for fd %lu (OS BROKEN?!)",incomingSockfd);
1201                                                 shutdown(incomingSockfd,2);
1202                                                 close(incomingSockfd);
1203                                         }
1204                                 break;
1205
1206                                 default:
1207                                         /* Something went wrong if we're in here.
1208                                          * In fact, so wrong, im not quite sure
1209                                          * what we would do, so for now, its going
1210                                          * to safely do bugger all.
1211                                          */
1212                                 break;
1213                         }
1214                 }
1215
1216         }
1217         /* This is never reached -- we hope! */
1218         return 0;
1219 }
1220
1221 /**********************************************************************************/
1222
1223 /**
1224  * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
1225  */
1226
1227 int main(int argc, char** argv)
1228 {
1229         ServerInstance = new InspIRCd(argc, argv);
1230         ServerInstance->Run();
1231         delete ServerInstance;
1232         return 0;
1233 }
1234