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