]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
65f8af0fad2f5a54884a12d15d607fbca1375112
[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 "inspircd_util.h"
25 #include <unistd.h>
26 #include <fcntl.h>
27 #include <sys/errno.h>
28 #include <sys/ioctl.h>
29 #include <sys/utsname.h>
30 #include <time.h>
31 #include <string>
32 #ifdef GCC3
33 #include <ext/hash_map>
34 #else
35 #include <hash_map>
36 #endif
37 #include <map>
38 #include <sstream>
39 #include <vector>
40 #include <deque>
41 #include <sched.h>
42 #ifdef THREADED_DNS
43 #include <pthread.h>
44 #endif
45 #include "users.h"
46 #include "ctables.h"
47 #include "globals.h"
48 #include "modules.h"
49 #include "dynamic.h"
50 #include "wildcard.h"
51 #include "message.h"
52 #include "mode.h"
53 #include "commands.h"
54 #include "xline.h"
55 #include "inspstring.h"
56 #include "dnsqueue.h"
57 #include "helperfuncs.h"
58 #include "hashcomp.h"
59 #include "socketengine.h"
60 #include "userprocess.h"
61 #include "socket.h"
62 #include "dns.h"
63 #include "typedefs.h"
64
65 InspIRCd* ServerInstance;
66
67 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
68 int WHOWAS_MAX = 100;  // default 100 people maximum in the WHOWAS list
69
70 extern std::vector<Module*> modules;
71 extern std::vector<ircd_module*> factory;
72 std::vector<InspSocket*> module_sockets;
73
74 extern int MODCOUNT;
75 int openSockfd[MAXSOCKS];
76 sockaddr_in client,server;
77 socklen_t length;
78
79 extern InspSocket* socket_ref[65535];
80
81 time_t TIME = time(NULL), OLDTIME = time(NULL);
82
83 SocketEngine* SE = NULL;
84
85 // This table references users by file descriptor.
86 // its an array to make it VERY fast, as all lookups are referenced
87 // by an integer, meaning there is no need for a scan/search operation.
88 userrec* fd_ref_table[65536];
89
90 serverstats* stats = new serverstats;
91 Server* MyServer = new Server;
92 ServerConfig *Config = new ServerConfig;
93
94 user_hash clientlist;
95 chan_hash chanlist;
96 whowas_hash whowas;
97 command_table cmdlist;
98 servernamelist servernames;
99 int BoundPortCount = 0;
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         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 /* re-allocates a nick in the user_hash after they change nicknames,
382  * returns a pointer to the new user as it may have moved */
383
384 userrec* ReHashNick(char* Old, char* New)
385 {
386         //user_hash::iterator newnick;
387         user_hash::iterator oldnick = clientlist.find(Old);
388
389         log(DEBUG,"ReHashNick: %s %s",Old,New);
390         
391         if (!strcasecmp(Old,New))
392         {
393                 log(DEBUG,"old nick is new nick, skipping");
394                 return oldnick->second;
395         }
396         
397         if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
398
399         log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
400
401         userrec* olduser = oldnick->second;
402         clientlist[New] = olduser;
403         clientlist.erase(oldnick);
404
405         log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
406         
407         return clientlist[New];
408 }
409
410 #ifdef THREADED_DNS
411 void* dns_task(void* arg)
412 {
413         userrec* u = (userrec*)arg;
414         log(DEBUG,"DNS thread for user %s",u->nick);
415         DNS dns1;
416         DNS dns2;
417         std::string host;
418         std::string ip;
419         if (dns1.ReverseLookup(u->ip))
420         {
421                 log(DEBUG,"DNS Step 1");
422                 while (!dns1.HasResult())
423                 {
424                         usleep(100);
425                 }
426                 host = dns1.GetResult();
427                 if (host != "")
428                 {
429                         log(DEBUG,"DNS Step 2: '%s'",host.c_str());
430                         if (dns2.ForwardLookup(host))
431                         {
432                                 while (!dns2.HasResult())
433                                 {
434                                         usleep(100);
435                                 }
436                                 ip = dns2.GetResultIP();
437                                 log(DEBUG,"DNS Step 3 '%s'(%d) '%s'(%d)",ip.c_str(),ip.length(),u->ip,strlen(u->ip));
438                                 if (ip == std::string(u->ip))
439                                 {
440                                         log(DEBUG,"DNS Step 4");
441                                         if (host.length() < 160)
442                                         {
443                                                 log(DEBUG,"DNS Step 5");
444                                                 strcpy(u->host,host.c_str());
445                                                 strcpy(u->dhost,host.c_str());
446                                         }
447                                 }
448                         }
449                 }
450         }
451         u->dns_done = true;
452         return NULL;
453 }
454 #endif
455
456 std::string InspIRCd::GetVersionString()
457 {
458         char versiondata[MAXBUF];
459 #ifdef THREADED_DNS
460         char dnsengine[] = "multithread";
461 #else
462         char dnsengine[] = "singlethread";
463 #endif
464         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);
465         return versiondata;
466 }
467
468
469 bool is_valid_cmd(std::string &commandname, int pcnt, userrec * user)
470 {
471         for (unsigned int i = 0; i < cmdlist.size(); i++)
472         {
473                 if (!strcasecmp(cmdlist[i].command,commandname.c_str()))
474                 {
475                         if (cmdlist[i].handler_function)
476                         {
477                                 if ((pcnt>=cmdlist[i].min_params) && (strcasecmp(cmdlist[i].source,"<core>")))
478                                 {
479                                         if ((strchr(user->modes,cmdlist[i].flags_needed)) || (!cmdlist[i].flags_needed))
480                                         {
481                                                 if (cmdlist[i].flags_needed)
482                                                 {
483                                                         if ((user->HasPermission(commandname)) || (is_uline(user->server)))
484                                                         {
485                                                                 return true;
486                                                         }
487                                                         else
488                                                         {
489                                                                 return false;
490                                                         }
491                                                 }
492                                                 return true;
493                                         }
494                                 }
495                         }
496                 }
497         }
498         return false;
499 }
500
501 // calls a handler function for a command
502
503 void call_handler(std::string &commandname,char **parameters, int pcnt, userrec *user)
504 {
505         for (unsigned int i = 0; i < cmdlist.size(); i++)
506         {
507                 if (!strcasecmp(cmdlist[i].command,commandname.c_str()))
508                 {
509                         if (cmdlist[i].handler_function)
510                         {
511                                 if (pcnt>=cmdlist[i].min_params)
512                                 {
513                                         if ((strchr(user->modes,cmdlist[i].flags_needed)) || (!cmdlist[i].flags_needed))
514                                         {
515                                                 if (cmdlist[i].flags_needed)
516                                                 {
517                                                         if ((user->HasPermission(commandname)) || (is_uline(user->server)))
518                                                         {
519                                                                 cmdlist[i].handler_function(parameters,pcnt,user);
520                                                         }
521                                                 }
522                                                 else
523                                                 {
524                                                         cmdlist[i].handler_function(parameters,pcnt,user);
525                                                 }
526                                         }
527                                 }
528                         }
529                 }
530         }
531 }
532
533
534 void force_nickchange(userrec* user,const char* newnick)
535 {
536         char nick[MAXBUF];
537         int MOD_RESULT = 0;
538         
539         strcpy(nick,"");
540
541         FOREACH_RESULT(OnUserPreNick(user,newnick));
542         if (MOD_RESULT) {
543                 stats->statsCollisions++;
544                 kill_link(user,"Nickname collision");
545                 return;
546         }
547         if (matches_qline(newnick))
548         {
549                 stats->statsCollisions++;
550                 kill_link(user,"Nickname collision");
551                 return;
552         }
553         
554         if (user)
555         {
556                 if (newnick)
557                 {
558                         strncpy(nick,newnick,MAXBUF);
559                 }
560                 if (user->registered == 7)
561                 {
562                         char* pars[1];
563                         pars[0] = nick;
564                         handle_nick(pars,1,user);
565                 }
566         }
567 }
568                                 
569
570 int process_parameters(char **command_p,char *parameters)
571 {
572         int j = 0;
573         int q = strlen(parameters);
574         if (!q)
575         {
576                 /* no parameters, command_p invalid! */
577                 return 0;
578         }
579         if (parameters[0] == ':')
580         {
581                 command_p[0] = parameters+1;
582                 return 1;
583         }
584         if (q)
585         {
586                 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
587                 {
588                         /* only one parameter */
589                         command_p[0] = parameters;
590                         if (parameters[0] == ':')
591                         {
592                                 if (strchr(parameters,' ') != NULL)
593                                 {
594                                         command_p[0]++;
595                                 }
596                         }
597                         return 1;
598                 }
599         }
600         command_p[j++] = parameters;
601         for (int i = 0; i <= q; i++)
602         {
603                 if (parameters[i] == ' ')
604                 {
605                         command_p[j++] = parameters+i+1;
606                         parameters[i] = '\0';
607                         if (command_p[j-1][0] == ':')
608                         {
609                                 *command_p[j-1]++; /* remove dodgy ":" */
610                                 break;
611                                 /* parameter like this marks end of the sequence */
612                         }
613                 }
614         }
615         return j; /* returns total number of items in the list */
616 }
617
618 void process_command(userrec *user, char* cmd)
619 {
620         char *parameters;
621         char *command;
622         char *command_p[127];
623         char p[MAXBUF], temp[MAXBUF];
624         int j, items, cmd_found;
625
626         for (int i = 0; i < 127; i++)
627                 command_p[i] = NULL;
628
629         if (!user)
630         {
631                 return;
632         }
633         if (!cmd)
634         {
635                 return;
636         }
637         if (!cmd[0])
638         {
639                 return;
640         }
641         
642         int total_params = 0;
643         if (strlen(cmd)>2)
644         {
645                 for (unsigned int q = 0; q < strlen(cmd)-1; q++)
646                 {
647                         if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
648                         {
649                                 total_params++;
650                                 // found a 'trailing', we dont count them after this.
651                                 break;
652                         }
653                         if (cmd[q] == ' ')
654                                 total_params++;
655                 }
656         }
657
658         // another phidjit bug...
659         if (total_params > 126)
660         {
661                 *(strchr(cmd,' ')) = '\0';
662                 WriteServ(user->fd,"421 %s %s :Too many parameters given",user->nick,cmd);
663                 return;
664         }
665
666         strlcpy(temp,cmd,MAXBUF);
667         
668         std::string tmp = cmd;
669         for (int i = 0; i <= MODCOUNT; i++)
670         {
671                 std::string oldtmp = tmp;
672                 modules[i]->OnServerRaw(tmp,true,user);
673                 if (oldtmp != tmp)
674                 {
675                         log(DEBUG,"A Module changed the input string!");
676                         log(DEBUG,"New string: %s",tmp.c_str());
677                         log(DEBUG,"Old string: %s",oldtmp.c_str());
678                         break;
679                 }
680         }
681         strlcpy(cmd,tmp.c_str(),MAXBUF);
682         strlcpy(temp,cmd,MAXBUF);
683
684         if (!strchr(cmd,' '))
685         {
686                 /* no parameters, lets skip the formalities and not chop up
687                  * the string */
688                 log(DEBUG,"About to preprocess command with no params");
689                 items = 0;
690                 command_p[0] = NULL;
691                 parameters = NULL;
692                 for (unsigned int i = 0; i <= strlen(cmd); i++)
693                 {
694                         cmd[i] = toupper(cmd[i]);
695                 }
696                 command = cmd;
697         }
698         else
699         {
700                 strcpy(cmd,"");
701                 j = 0;
702                 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
703                 for (unsigned int i = 0; i < strlen(temp); i++)
704                 {
705                         if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
706                         {
707                                 cmd[j++] = temp[i];
708                                 cmd[j] = 0;
709                         }
710                 }
711                 /* split the full string into a command plus parameters */
712                 parameters = p;
713                 strcpy(p," ");
714                 command = cmd;
715                 if (strchr(cmd,' '))
716                 {
717                         for (unsigned int i = 0; i <= strlen(cmd); i++)
718                         {
719                                 /* capitalise the command ONLY, leave params intact */
720                                 cmd[i] = toupper(cmd[i]);
721                                 /* are we nearly there yet?! :P */
722                                 if (cmd[i] == ' ')
723                                 {
724                                         command = cmd;
725                                         parameters = cmd+i+1;
726                                         cmd[i] = '\0';
727                                         break;
728                                 }
729                         }
730                 }
731                 else
732                 {
733                         for (unsigned int i = 0; i <= strlen(cmd); i++)
734                         {
735                                 cmd[i] = toupper(cmd[i]);
736                         }
737                 }
738
739         }
740         cmd_found = 0;
741         
742         if (strlen(command)>MAXCOMMAND)
743         {
744                 WriteServ(user->fd,"421 %s %s :Command too long",user->nick,command);
745                 return;
746         }
747         
748         for (unsigned int x = 0; x < strlen(command); x++)
749         {
750                 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
751                 {
752                         if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
753                         {
754                                 if (strchr("@!\"$%^&*(){}[]_=+;:'#~,<>/?\\|`",command[x]))
755                                 {
756                                         stats->statsUnknown++;
757                                         WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
758                                         return;
759                                 }
760                         }
761                 }
762         }
763
764         for (unsigned int i = 0; i != cmdlist.size(); i++)
765         {
766                 if (cmdlist[i].command[0])
767                 {
768                         if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
769                         {
770                                 if (parameters)
771                                 {
772                                         if (parameters[0])
773                                         {
774                                                 items = process_parameters(command_p,parameters);
775                                         }
776                                         else
777                                         {
778                                                 items = 0;
779                                                 command_p[0] = NULL;
780                                         }
781                                 }
782                                 else
783                                 {
784                                         items = 0;
785                                         command_p[0] = NULL;
786                                 }
787                                 
788                                 if (user)
789                                 {
790                                         /* activity resets the ping pending timer */
791                                         user->nping = TIME + user->pingmax;
792                                         if ((items) < cmdlist[i].min_params)
793                                         {
794                                                 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
795                                                 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
796                                                 return;
797                                         }
798                                         if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
799                                         {
800                                                 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
801                                                 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
802                                                 cmd_found = 1;
803                                                 return;
804                                         }
805                                         if ((cmdlist[i].flags_needed) && (!user->HasPermission(command)))
806                                         {
807                                                 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
808                                                 WriteServ(user->fd,"481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command);
809                                                 cmd_found = 1;
810                                                 return;
811                                         }
812                                         /* if the command isnt USER, PASS, or NICK, and nick is empty,
813                                          * deny command! */
814                                         if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
815                                         {
816                                                 if ((!isnick(user->nick)) || (user->registered != 7))
817                                                 {
818                                                         log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
819                                                         WriteServ(user->fd,"451 %s :You have not registered",command);
820                                                         return;
821                                                 }
822                                         }
823                                         if ((user->registered == 7) && (!strchr(user->modes,'o')))
824                                         {
825                                                 std::stringstream dcmds(Config->DisabledCommands);
826                                                 while (!dcmds.eof())
827                                                 {
828                                                         std::string thiscmd;
829                                                         dcmds >> thiscmd;
830                                                         if (!strcasecmp(thiscmd.c_str(),command))
831                                                         {
832                                                                 // command is disabled!
833                                                                 WriteServ(user->fd,"421 %s %s :This command has been disabled.",user->nick,command);
834                                                                 return;
835                                                         }
836                                                 }
837                                         }
838                                         if ((user->registered == 7) || (!strncmp(command,"USER",4)) || (!strncmp(command,"NICK",4)) || (!strncmp(command,"PASS",4)))
839                                         {
840                                                 if (cmdlist[i].handler_function)
841                                                 {
842                                                         
843                                                         /* ikky /stats counters */
844                                                         if (temp)
845                                                         {
846                                                                 cmdlist[i].use_count++;
847                                                                 cmdlist[i].total_bytes+=strlen(temp);
848                                                         }
849
850                                                         int MOD_RESULT = 0;
851                                                         FOREACH_RESULT(OnPreCommand(command,command_p,items,user));
852                                                         if (MOD_RESULT == 1) {
853                                                                 return;
854                                                         }
855
856                                                         /* WARNING: nothing may come after the
857                                                          * command handler call, as the handler
858                                                          * may free the user structure! */
859
860                                                         cmdlist[i].handler_function(command_p,items,user);
861                                                 }
862                                                 return;
863                                         }
864                                         else
865                                         {
866                                                 WriteServ(user->fd,"451 %s :You have not registered",command);
867                                                 return;
868                                         }
869                                 }
870                                 cmd_found = 1;
871                         }
872                 }
873         }
874         if ((!cmd_found) && (user))
875         {
876                 stats->statsUnknown++;
877                 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
878         }
879 }
880
881 bool removecommands(const char* source)
882 {
883         bool go_again = true;
884         while (go_again)
885         {
886                 go_again = false;
887                 for (std::deque<command_t>::iterator i = cmdlist.begin(); i != cmdlist.end(); i++)
888                 {
889                         if (!strcmp(i->source,source))
890                         {
891                                 log(DEBUG,"removecommands(%s) Removing dependent command: %s",i->source,i->command);
892                                 cmdlist.erase(i);
893                                 go_again = true;
894                                 break;
895                         }
896                 }
897         }
898         return true;
899 }
900
901
902 void process_buffer(const char* cmdbuf,userrec *user)
903 {
904         if (!user)
905         {
906                 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
907                 return;
908         }
909         char cmd[MAXBUF];
910         if (!cmdbuf)
911         {
912                 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
913                 return;
914         }
915         if (!cmdbuf[0])
916         {
917                 return;
918         }
919         while (*cmdbuf == ' ') cmdbuf++; // strip leading spaces
920
921         strlcpy(cmd,cmdbuf,MAXBUF);
922         if (!cmd[0])
923         {
924                 return;
925         }
926         int sl = strlen(cmd)-1;
927         if ((cmd[sl] == 13) || (cmd[sl] == 10))
928         {
929                 cmd[sl] = '\0';
930         }
931         sl = strlen(cmd)-1;
932         if ((cmd[sl] == 13) || (cmd[sl] == 10))
933         {
934                 cmd[sl] = '\0';
935         }
936         sl = strlen(cmd)-1;
937         while (cmd[sl] == ' ') // strip trailing spaces
938         {
939                 cmd[sl] = '\0';
940                 sl = strlen(cmd)-1;
941         }
942
943         if (!cmd[0])
944         {
945                 return;
946         }
947         log(DEBUG,"CMDIN: %s %s",user->nick,cmd);
948         tidystring(cmd);
949         if ((user) && (cmd))
950         {
951                 process_command(user,cmd);
952         }
953 }
954
955 char* InspIRCd::ModuleError()
956 {
957         return MODERR;
958 }
959
960 void InspIRCd::erase_factory(int j)
961 {
962         int v = 0;
963         for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
964         {
965                 if (v == j)
966                 {
967                         factory.erase(t);
968                         factory.push_back(NULL);
969                         return;
970                 }
971                 v++;
972         }
973 }
974
975 void InspIRCd::erase_module(int j)
976 {
977         int v1 = 0;
978         for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
979         {
980                 if (v1 == j)
981                 {
982                         delete *m;
983                         modules.erase(m);
984                         modules.push_back(NULL);
985                         break;
986                 }
987                 v1++;
988         }
989         int v2 = 0;
990         for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
991         {
992                 if (v2 == j)
993                 {
994                        Config->module_names.erase(v);
995                        break;
996                 }
997                 v2++;
998         }
999
1000 }
1001
1002 bool InspIRCd::UnloadModule(const char* filename)
1003 {
1004         std::string filename_str = filename;
1005         for (unsigned int j = 0; j != Config->module_names.size(); j++)
1006         {
1007                 if (Config->module_names[j] == filename_str)
1008                 {
1009                         if (modules[j]->GetVersion().Flags & VF_STATIC)
1010                         {
1011                                 log(DEFAULT,"Failed to unload STATIC module %s",filename);
1012                                 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
1013                                 return false;
1014                         }
1015                         /* Give the module a chance to tidy out all its metadata */
1016                         for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
1017                         {
1018                                 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
1019                         }
1020                         for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
1021                         {
1022                                 modules[j]->OnCleanup(TYPE_USER,u->second);
1023                         }
1024                         FOREACH_MOD OnUnloadModule(modules[j],Config->module_names[j]);
1025                         // found the module
1026                         log(DEBUG,"Deleting module...");
1027                         erase_module(j);
1028                         log(DEBUG,"Erasing module entry...");
1029                         erase_factory(j);
1030                         log(DEBUG,"Removing dependent commands...");
1031                         removecommands(filename);
1032                         log(DEFAULT,"Module %s unloaded",filename);
1033                         MODCOUNT--;
1034                         return true;
1035                 }
1036         }
1037         log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
1038         snprintf(MODERR,MAXBUF,"Module not loaded");
1039         return false;
1040 }
1041
1042 bool InspIRCd::LoadModule(const char* filename)
1043 {
1044         char modfile[MAXBUF];
1045 #ifdef STATIC_LINK
1046         snprintf(modfile,MAXBUF,"%s",filename);
1047 #else
1048         snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
1049 #endif
1050         std::string filename_str = filename;
1051 #ifndef STATIC_LINK
1052         if (!DirValid(modfile))
1053         {
1054                 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
1055                 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
1056                 return false;
1057         }
1058 #endif
1059         log(DEBUG,"Loading module: %s",modfile);
1060 #ifndef STATIC_LINK
1061         if (FileExists(modfile))
1062         {
1063 #endif
1064                 for (unsigned int j = 0; j < Config->module_names.size(); j++)
1065                 {
1066                         if (Config->module_names[j] == filename_str)
1067                         {
1068                                 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
1069                                 snprintf(MODERR,MAXBUF,"Module already loaded");
1070                                 return false;
1071                         }
1072                 }
1073                 ircd_module* a = new ircd_module(modfile);
1074                 factory[MODCOUNT+1] = a;
1075                 if (factory[MODCOUNT+1]->LastError())
1076                 {
1077                         log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
1078                         snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
1079                         MODCOUNT--;
1080                         return false;
1081                 }
1082                 if (factory[MODCOUNT+1]->factory)
1083                 {
1084                         Module* m = factory[MODCOUNT+1]->factory->CreateModule(MyServer);
1085                         modules[MODCOUNT+1] = m;
1086                         /* save the module and the module's classfactory, if
1087                          * this isnt done, random crashes can occur :/ */
1088                         Config->module_names.push_back(filename);
1089                 }
1090                 else
1091                 {
1092                         log(DEFAULT,"Unable to load %s",modfile);
1093                         snprintf(MODERR,MAXBUF,"Factory function failed!");
1094                         return false;
1095                 }
1096 #ifndef STATIC_LINK
1097         }
1098         else
1099         {
1100                 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
1101                 snprintf(MODERR,MAXBUF,"Module file could not be found");
1102                 return false;
1103         }
1104 #endif
1105         MODCOUNT++;
1106         FOREACH_MOD OnLoadModule(modules[MODCOUNT],filename_str);
1107         return true;
1108 }
1109
1110 int InspIRCd::Run()
1111 {
1112         bool expire_run = false;
1113         std::vector<int> activefds;
1114         int incomingSockfd;
1115         int in_port;
1116         userrec* cu = NULL;
1117         InspSocket* s = NULL;
1118         InspSocket* s_del = NULL;
1119         char* target;
1120         unsigned int numberactive;
1121         sockaddr_in sock_us;     // our port number
1122         socklen_t uslen;         // length of our port number
1123
1124         if (!Config->nofork)
1125         {
1126                 freopen("/dev/null","w",stdout);
1127                 freopen("/dev/null","w",stderr);
1128         }
1129
1130         /* Add the listening sockets used for client inbound connections
1131          * to the socket engine
1132          */
1133         for (int count = 0; count < BoundPortCount; count++)
1134                 SE->AddFd(openSockfd[count],true,X_LISTEN);
1135
1136         WritePID(Config->PID);
1137
1138         /* main loop, this never returns */
1139         for (;;)
1140         {
1141                 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
1142                  * Once per loop iteration is pleanty.
1143                  */
1144                 OLDTIME = TIME;
1145                 TIME = time(NULL);
1146
1147                 /* Run background module timers every few seconds
1148                  * (the docs say modules shouldnt rely on accurate
1149                  * timing using this event, so we dont have to
1150                  * time this exactly).
1151                  */
1152                 if (((TIME % 8) == 0) && (!expire_run))
1153                 {
1154                         expire_lines();
1155                         FOREACH_MOD OnBackgroundTimer(TIME);
1156                         expire_run = true;
1157                         continue;
1158                 }
1159                 if ((TIME % 8) == 1)
1160                         expire_run = false;
1161                 
1162                 /* Once a second, do the background processing */
1163                 if (TIME != OLDTIME)
1164                         while (DoBackgroundUserStuff(TIME));
1165
1166                 /* Call the socket engine to wait on the active
1167                  * file descriptors. The socket engine has everything's
1168                  * descriptors in its list... dns, modules, users,
1169                  * servers... so its nice and easy, just one call.
1170                  */
1171                 SE->Wait(activefds);
1172
1173                 /**
1174                  * Now process each of the fd's. For users, we have a fast
1175                  * lookup table which can find a user by file descriptor, so
1176                  * processing them by fd isnt expensive. If we have a lot of
1177                  * listening ports or module sockets though, things could get
1178                  * ugly.
1179                  */
1180                 numberactive = activefds.size();
1181                 for (unsigned int activefd = 0; activefd < numberactive; activefd++)
1182                 {
1183                         int socket_type = SE->GetType(activefds[activefd]);
1184                         switch (socket_type)
1185                         {
1186                                 case X_ESTAB_CLIENT:
1187
1188                                         cu = fd_ref_table[activefds[activefd]];
1189                                         if (cu)
1190                                                 ProcessUser(cu);
1191
1192                                 break;
1193
1194                                 case X_ESTAB_MODULE:
1195
1196                                         /* Process module-owned sockets.
1197                                          * Modules are encouraged to inherit their sockets from
1198                                          * InspSocket so we can process them neatly like this.
1199                                          */
1200                                         s = socket_ref[activefds[activefd]];
1201
1202                                         if ((s) && (!s->Poll()))
1203                                         {
1204                                                 log(DEBUG,"Socket poll returned false, close and bail");
1205                                                 SE->DelFd(s->GetFd());
1206                                                 for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
1207                                                 {
1208                                                         s_del = (InspSocket*)*a;
1209                                                         if ((s_del) && (s_del->GetFd() == activefds[activefd]))
1210                                                         {
1211                                                                 module_sockets.erase(a);
1212                                                                 break;
1213                                                         }
1214                                                 }
1215                                                 s->Close();
1216                                                 delete s;
1217                                         }
1218
1219                                 break;
1220
1221                                 case X_ESTAB_DNS:
1222
1223                                         /* When we are using single-threaded dns,
1224                                          * the sockets for dns end up in our mainloop.
1225                                          * When we are using multi-threaded dns,
1226                                          * each thread has its own basic poll() loop
1227                                          * within it, making them 'fire and forget'
1228                                          * and independent of the mainloop.
1229                                          */
1230 #ifndef THREADED_DNS
1231                                         dns_poll(activefds[activefd]);
1232 #endif
1233                                 break;
1234                                 
1235                                 case X_LISTEN:
1236
1237                                         /* It's a listener */
1238                                         uslen = sizeof(sock_us);
1239                                         length = sizeof(client);
1240                                         incomingSockfd = accept (activefds[activefd],(struct sockaddr*)&client,&length);
1241                                         if (!getsockname(incomingSockfd,(sockaddr*)&sock_us,&uslen))
1242                                         {
1243                                                 in_port = ntohs(sock_us.sin_port);
1244                                                 log(DEBUG,"Accepted socket %d",incomingSockfd);
1245                                                 target = (char*)inet_ntoa(client.sin_addr);
1246                                                 /* Years and years ago, we used to resolve here
1247                                                  * using gethostbyaddr(). That is sucky and we
1248                                                  * don't do that any more...
1249                                                  */
1250                                                 if (incomingSockfd >= 0)
1251                                                 {
1252                                                         FOREACH_MOD OnRawSocketAccept(incomingSockfd, target, in_port);
1253                                                         stats->statsAccept++;
1254                                                         AddClient(incomingSockfd, target, in_port, false, target);
1255                                                         log(DEBUG,"Adding client on port %lu fd=%lu",(unsigned long)in_port,(unsigned long)incomingSockfd);
1256                                                 }
1257                                                 else
1258                                                 {
1259                                                         WriteOpers("*** WARNING: accept() failed on port %lu (%s)",(unsigned long)in_port,target);
1260                                                         log(DEBUG,"accept failed: %lu",(unsigned long)in_port);
1261                                                         stats->statsRefused++;
1262                                                 }
1263                                         }
1264                                         else
1265                                         {
1266                                                 log(DEBUG,"Couldnt look up the port number for fd %lu (OS BROKEN?!)",incomingSockfd);
1267                                                 shutdown(incomingSockfd,2);
1268                                                 close(incomingSockfd);
1269                                         }
1270                                 break;
1271
1272                                 default:
1273                                         /* Something went wrong if we're in here.
1274                                          * In fact, so wrong, im not quite sure
1275                                          * what we would do, so for now, its going
1276                                          * to safely do bugger all.
1277                                          */
1278                                 break;
1279                         }
1280                 }
1281
1282         }
1283         /* This is never reached -- we hope! */
1284         return 0;
1285 }
1286
1287 /**********************************************************************************/
1288
1289 /**
1290  * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
1291  */
1292
1293 int main(int argc, char** argv)
1294 {
1295         ServerInstance = new InspIRCd(argc, argv);
1296         ServerInstance->Run();
1297         delete ServerInstance;
1298         return 0;
1299 }
1300