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