]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
Moved a bunch of stuff into class InspIRCd
[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 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
66 int WHOWAS_MAX = 100;  // default 100 people maximum in the WHOWAS list
67 int DieDelay  =  5;
68 time_t startup_time = time(NULL);
69
70 extern std::vector<Module*> modules;
71 extern std::vector<ircd_module*> factory;
72
73 std::vector<InspSocket*> module_sockets;
74
75 extern int MODCOUNT;
76 int openSockfd[MAXSOCKS];
77 sockaddr_in client,server;
78 socklen_t length;
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 address_cache IP;
100 servernamelist servernames;
101 int BoundPortCount = 0;
102 std::vector<userrec*> all_opers;
103 char lowermap[255];
104
105
106 void AddOper(userrec* user)
107 {
108         log(DEBUG,"Oper added to optimization list");
109         all_opers.push_back(user);
110 }
111
112 void AddServerName(std::string servername)
113 {
114         log(DEBUG,"Adding server name: %s",servername.c_str());
115         for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
116         {
117                 if (*a == servername)
118                         return;
119         }
120         servernames.push_back(servername);
121 }
122
123 const char* FindServerNamePtr(std::string servername)
124 {
125         for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
126         {
127                 if (*a == servername)
128                         return a->c_str();
129         }
130         AddServerName(servername);
131         return FindServerNamePtr(servername);
132 }
133
134 void DeleteOper(userrec* user)
135 {
136         for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
137         {
138                 if (*a == user)
139                 {
140                         log(DEBUG,"Oper removed from optimization list");
141                         all_opers.erase(a);
142                         return;
143                 }
144         }
145 }
146
147 std::string GetRevision()
148 {
149         /* w00t got me to replace a bunch of strtok_r
150          * with something nicer, so i did this. Its the
151          * same thing really, only in C++. It places the
152          * text into a std::stringstream which is a readable
153          * and writeable buffer stream, and then pops two
154          * words off it, space delimited. Because it reads
155          * into the same variable twice, the first word
156          * is discarded, and the second one returned.
157          */
158         std::stringstream Revision("$Revision$");
159         std::string single;
160         Revision >> single >> single;
161         return single;
162 }
163
164
165 /* This function pokes and hacks at a parameter list like the following:
166  *
167  * PART #winbot,#darkgalaxy :m00!
168  *
169  * to turn it into a series of individual calls like this:
170  *
171  * PART #winbot :m00!
172  * PART #darkgalaxy :m00!
173  *
174  * The seperate calls are sent to a callback function provided by the caller
175  * (the caller will usually call itself recursively). The callback function
176  * must be a command handler. Calling this function on a line with no list causes
177  * no action to be taken. You must provide a starting and ending parameter number
178  * where the range of the list can be found, useful if you have a terminating
179  * parameter as above which is actually not part of the list, or parameters
180  * before the actual list as well. This code is used by many functions which
181  * can function as "one to list" (see the RFC) */
182
183 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
184 {
185         char plist[MAXBUF];
186         char *param;
187         char *pars[32];
188         char blog[32][MAXBUF];
189         char blog2[32][MAXBUF];
190         int j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
191         char keystr[MAXBUF];
192         char moo[MAXBUF];
193
194         for (int i = 0; i <32; i++)
195                 strcpy(blog[i],"");
196
197         for (int i = 0; i <32; i++)
198                 strcpy(blog2[i],"");
199
200         strcpy(moo,"");
201         for (int i = 0; i <10; i++)
202         {
203                 if (!parameters[i])
204                 {
205                         parameters[i] = moo;
206                 }
207         }
208         if (joins)
209         {
210                 if (pcnt > 1) /* we have a key to copy */
211                 {
212                         strlcpy(keystr,parameters[1],MAXBUF);
213                 }
214         }
215
216         if (!parameters[start])
217         {
218                 return 0;
219         }
220         if (!strchr(parameters[start],','))
221         {
222                 return 0;
223         }
224         strcpy(plist,"");
225         for (int i = start; i <= end; i++)
226         {
227                 if (parameters[i])
228                 {
229                         strlcat(plist,parameters[i],MAXBUF);
230                 }
231         }
232         
233         j = 0;
234         param = plist;
235
236         t = strlen(plist);
237         for (int i = 0; i < t; i++)
238         {
239                 if (plist[i] == ',')
240                 {
241                         plist[i] = '\0';
242                         strlcpy(blog[j++],param,MAXBUF);
243                         param = plist+i+1;
244                         if (j>20)
245                         {
246                                 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
247                                 return 1;
248                         }
249                 }
250         }
251         strlcpy(blog[j++],param,MAXBUF);
252         total = j;
253
254         if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
255         {
256                 strcat(keystr,",");
257         }
258         
259         if ((joins) && (keystr))
260         {
261                 if (strchr(keystr,','))
262                 {
263                         j = 0;
264                         param = keystr;
265                         t2 = strlen(keystr);
266                         for (int i = 0; i < t2; i++)
267                         {
268                                 if (keystr[i] == ',')
269                                 {
270                                         keystr[i] = '\0';
271                                         strlcpy(blog2[j++],param,MAXBUF);
272                                         param = keystr+i+1;
273                                 }
274                         }
275                         strlcpy(blog2[j++],param,MAXBUF);
276                         total2 = j;
277                 }
278         }
279
280         for (j = 0; j < total; j++)
281         {
282                 if (blog[j])
283                 {
284                         pars[0] = blog[j];
285                 }
286                 for (q = end; q < pcnt-1; q++)
287                 {
288                         if (parameters[q+1])
289                         {
290                                 pars[q-end+1] = parameters[q+1];
291                         }
292                 }
293                 if ((joins) && (parameters[1]))
294                 {
295                         if (pcnt > 1)
296                         {
297                                 pars[1] = blog2[j];
298                         }
299                         else
300                         {
301                                 pars[1] = NULL;
302                         }
303                 }
304                 /* repeatedly call the function with the hacked parameter list */
305                 if ((joins) && (pcnt > 1))
306                 {
307                         if (pars[1])
308                         {
309                                 // pars[1] already set up and containing key from blog2[j]
310                                 fn(pars,2,u);
311                         }
312                         else
313                         {
314                                 pars[1] = parameters[1];
315                                 fn(pars,2,u);
316                         }
317                 }
318                 else
319                 {
320                         fn(pars,pcnt-(end-start),u);
321                 }
322         }
323
324         return 1;
325 }
326
327
328
329 void kill_link(userrec *user,const char* r)
330 {
331         user_hash::iterator iter = clientlist.find(user->nick);
332         
333         char reason[MAXBUF];
334         
335         strncpy(reason,r,MAXBUF);
336
337         if (strlen(reason)>MAXQUIT)
338         {
339                 reason[MAXQUIT-1] = '\0';
340         }
341
342         log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
343         Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
344         log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
345
346         if (user->registered == 7) {
347                 FOREACH_MOD OnUserQuit(user,reason);
348                 WriteCommonExcept(user,"QUIT :%s",reason);
349         }
350
351         user->FlushWriteBuf();
352
353         FOREACH_MOD OnUserDisconnect(user);
354
355         if (user->fd > -1)
356         {
357                 FOREACH_MOD OnRawSocketClose(user->fd);
358                 SE->DelFd(user->fd);
359                 user->CloseSocket();
360         }
361
362         // this must come before the WriteOpers so that it doesnt try to fill their buffer with anything
363         // if they were an oper with +s.
364         if (user->registered == 7) {
365                 purge_empty_chans(user);
366                 // fix by brain: only show local quits because we only show local connects (it just makes SENSE)
367                 if (user->fd > -1)
368                         WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
369                 AddWhoWas(user);
370         }
371
372         if (iter != clientlist.end())
373         {
374                 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
375                 if (user->fd > -1)
376                         fd_ref_table[user->fd] = NULL;
377                 clientlist.erase(iter);
378         }
379         delete user;
380 }
381
382 void kill_link_silent(userrec *user,const char* r)
383 {
384         user_hash::iterator iter = clientlist.find(user->nick);
385         
386         char reason[MAXBUF];
387         
388         strncpy(reason,r,MAXBUF);
389
390         if (strlen(reason)>MAXQUIT)
391         {
392                 reason[MAXQUIT-1] = '\0';
393         }
394
395         log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
396         Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
397         log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
398
399         user->FlushWriteBuf();
400
401         if (user->registered == 7) {
402                 FOREACH_MOD OnUserQuit(user,reason);
403                 WriteCommonExcept(user,"QUIT :%s",reason);
404         }
405
406         FOREACH_MOD OnUserDisconnect(user);
407
408         if (user->fd > -1)
409         {
410                 FOREACH_MOD OnRawSocketClose(user->fd);
411                 SE->DelFd(user->fd);
412                 user->CloseSocket();
413         }
414
415         if (user->registered == 7) {
416                 purge_empty_chans(user);
417         }
418         
419         if (iter != clientlist.end())
420         {
421                 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
422                 if (user->fd > -1)
423                         fd_ref_table[user->fd] = NULL;
424                 clientlist.erase(iter);
425         }
426         delete user;
427 }
428
429
430 InspIRCd::InspIRCd(int argc, char** argv)
431 {
432         Start();
433         srand(time(NULL));
434         log(DEBUG,"*** InspIRCd starting up!");
435         if (!FileExists(CONFIG_FILE))
436         {
437                 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
438                 log(DEFAULT,"main: no config");
439                 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
440                 Exit(ERROR);
441         }
442         if (argc > 1) {
443                 for (int i = 1; i < argc; i++)
444                 {
445                         if (!strcmp(argv[i],"-nofork")) {
446                                 Config->nofork = true;
447                         }
448                         if (!strcmp(argv[i],"-wait")) {
449                                 sleep(6);
450                         }
451                         if (!strcmp(argv[i],"-nolimit")) {
452                                 Config->unlimitcore = true;
453                         }
454                 }
455         }
456
457         strlcpy(Config->MyExecutable,argv[0],MAXBUF);
458         
459         // initialize the lowercase mapping table
460         for (unsigned int cn = 0; cn < 256; cn++)
461                 lowermap[cn] = cn;
462         // lowercase the uppercase chars
463         for (unsigned int cn = 65; cn < 91; cn++)
464                 lowermap[cn] = tolower(cn);
465         // now replace the specific chars for scandanavian comparison
466         lowermap[(unsigned)'['] = '{';
467         lowermap[(unsigned)']'] = '}';
468         lowermap[(unsigned)'\\'] = '|';
469
470
471         OpenLog(argv, argc);
472         Config->ClearStack();
473         Config->Read(true,NULL);
474         CheckRoot();
475         SetupCommandTable();
476         AddServerName(Config->ServerName);
477         CheckDie();
478         BoundPortCount = BindPorts();
479
480         printf("\n");
481         startup_time = time(NULL);
482
483         if (!Config->nofork)
484         {
485                 if (DaemonSeed() == ERROR)
486                 {
487                         printf("ERROR: could not go into daemon mode. Shutting down.\n");
488                         Exit(ERROR);
489                 }
490         }
491
492         /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
493          * initialize the socket engine.
494          */
495         SE = new SocketEngine();
496
497         /* We must load the modules AFTER initializing the socket engine, now */
498         LoadAllModules();
499
500         printf("\nInspIRCd is now running!\n");
501
502         return;
503 }
504
505 template<typename T> inline string ConvToStr(const T &in)
506 {
507         stringstream tmp;
508         if (!(tmp << in)) return string();
509         return tmp.str();
510 }
511
512 /* re-allocates a nick in the user_hash after they change nicknames,
513  * returns a pointer to the new user as it may have moved */
514
515 userrec* ReHashNick(char* Old, char* New)
516 {
517         //user_hash::iterator newnick;
518         user_hash::iterator oldnick = clientlist.find(Old);
519
520         log(DEBUG,"ReHashNick: %s %s",Old,New);
521         
522         if (!strcasecmp(Old,New))
523         {
524                 log(DEBUG,"old nick is new nick, skipping");
525                 return oldnick->second;
526         }
527         
528         if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
529
530         log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
531
532         userrec* olduser = oldnick->second;
533         clientlist[New] = olduser;
534         clientlist.erase(oldnick);
535
536         log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
537         
538         return clientlist[New];
539 }
540
541 /* adds or updates an entry in the whowas list */
542 void AddWhoWas(userrec* u)
543 {
544         whowas_hash::iterator iter = whowas.find(u->nick);
545         WhoWasUser *a = new WhoWasUser();
546         strlcpy(a->nick,u->nick,NICKMAX);
547         strlcpy(a->ident,u->ident,IDENTMAX);
548         strlcpy(a->dhost,u->dhost,160);
549         strlcpy(a->host,u->host,160);
550         strlcpy(a->fullname,u->fullname,MAXGECOS);
551         strlcpy(a->server,u->server,256);
552         a->signon = u->signon;
553
554         /* MAX_WHOWAS:   max number of /WHOWAS items
555          * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
556          *               can be replaced by a newer one
557          */
558         
559         if (iter == whowas.end())
560         {
561                 if (whowas.size() >= (unsigned)WHOWAS_MAX)
562                 {
563                         for (whowas_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
564                         {
565                                 // 3600 seconds in an hour ;)
566                                 if ((i->second->signon)<(TIME-(WHOWAS_STALE*3600)))
567                                 {
568                                         // delete the old one
569                                         if (i->second) delete i->second;
570                                         // replace with new one
571                                         i->second = a;
572                                         log(DEBUG,"added WHOWAS entry, purged an old record");
573                                         return;
574                                 }
575                         }
576                         // no space left and user doesnt exist. Don't leave ram in use!
577                         log(DEBUG,"Not able to update whowas (list at WHOWAS_MAX entries and trying to add new?), freeing excess ram");
578                         delete a;
579                 }
580                 else
581                 {
582                         log(DEBUG,"added fresh WHOWAS entry");
583                         whowas[a->nick] = a;
584                 }
585         }
586         else
587         {
588                 log(DEBUG,"updated WHOWAS entry");
589                 if (iter->second) delete iter->second;
590                 iter->second = a;
591         }
592 }
593
594 #ifdef THREADED_DNS
595 void* dns_task(void* arg)
596 {
597         userrec* u = (userrec*)arg;
598         log(DEBUG,"DNS thread for user %s",u->nick);
599         DNS dns1;
600         DNS dns2;
601         std::string host;
602         std::string ip;
603         if (dns1.ReverseLookup(u->ip))
604         {
605                 log(DEBUG,"DNS Step 1");
606                 while (!dns1.HasResult())
607                 {
608                         usleep(100);
609                 }
610                 host = dns1.GetResult();
611                 if (host != "")
612                 {
613                         log(DEBUG,"DNS Step 2: '%s'",host.c_str());
614                         if (dns2.ForwardLookup(host))
615                         {
616                                 while (!dns2.HasResult())
617                                 {
618                                         usleep(100);
619                                 }
620                                 ip = dns2.GetResultIP();
621                                 log(DEBUG,"DNS Step 3 '%s'(%d) '%s'(%d)",ip.c_str(),ip.length(),u->ip,strlen(u->ip));
622                                 if (ip == std::string(u->ip))
623                                 {
624                                         log(DEBUG,"DNS Step 4");
625                                         if (host.length() < 160)
626                                         {
627                                                 log(DEBUG,"DNS Step 5");
628                                                 strcpy(u->host,host.c_str());
629                                                 strcpy(u->dhost,host.c_str());
630                                         }
631                                 }
632                         }
633                 }
634         }
635         u->dns_done = true;
636         return NULL;
637 }
638 #endif
639
640 /* add a client connection to the sockets list */
641 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
642 {
643         string tempnick;
644         char tn2[MAXBUF];
645         user_hash::iterator iter;
646
647         tempnick = ConvToStr(socket) + "-unknown";
648         sprintf(tn2,"%lu-unknown",(unsigned long)socket);
649
650         iter = clientlist.find(tempnick);
651
652         // fix by brain.
653         // as these nicknames are 'RFC impossible', we can be sure nobody is going to be
654         // using one as a registered connection. As theyre per fd, we can also safely assume
655         // that we wont have collisions. Therefore, if the nick exists in the list, its only
656         // used by a dead socket, erase the iterator so that the new client may reclaim it.
657         // this was probably the cause of 'server ignores me when i hammer it with reconnects'
658         // issue in earlier alphas/betas
659         if (iter != clientlist.end())
660         {
661                 userrec* goner = iter->second;
662                 delete goner;
663                 clientlist.erase(iter);
664         }
665
666         /*
667          * It is OK to access the value here this way since we know
668          * it exists, we just created it above.
669          *
670          * At NO other time should you access a value in a map or a
671          * hash_map this way.
672          */
673         clientlist[tempnick] = new userrec();
674
675         NonBlocking(socket);
676         log(DEBUG,"AddClient: %lu %s %d %s",(unsigned long)socket,host,port,ip);
677
678         clientlist[tempnick]->fd = socket;
679         strlcpy(clientlist[tempnick]->nick, tn2,NICKMAX);
680         strlcpy(clientlist[tempnick]->host, host,160);
681         strlcpy(clientlist[tempnick]->dhost, host,160);
682         clientlist[tempnick]->server = (char*)FindServerNamePtr(Config->ServerName);
683         strlcpy(clientlist[tempnick]->ident, "unknown",IDENTMAX);
684         clientlist[tempnick]->registered = 0;
685         clientlist[tempnick]->signon = TIME + Config->dns_timeout;
686         clientlist[tempnick]->lastping = 1;
687         clientlist[tempnick]->port = port;
688         strlcpy(clientlist[tempnick]->ip,ip,16);
689
690         // set the registration timeout for this user
691         unsigned long class_regtimeout = 90;
692         int class_flood = 0;
693         long class_threshold = 5;
694         long class_sqmax = 262144;      // 256kb
695         long class_rqmax = 4096;        // 4k
696
697         for (ClassVector::iterator i = Config->Classes.begin(); i != Config->Classes.end(); i++)
698         {
699                 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
700                 {
701                         class_regtimeout = (unsigned long)i->registration_timeout;
702                         class_flood = i->flood;
703                         clientlist[tempnick]->pingmax = i->pingtime;
704                         class_threshold = i->threshold;
705                         class_sqmax = i->sendqmax;
706                         class_rqmax = i->recvqmax;
707                         break;
708                 }
709         }
710
711         clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax + Config->dns_timeout;
712         clientlist[tempnick]->timeout = TIME+class_regtimeout;
713         clientlist[tempnick]->flood = class_flood;
714         clientlist[tempnick]->threshold = class_threshold;
715         clientlist[tempnick]->sendqmax = class_sqmax;
716         clientlist[tempnick]->recvqmax = class_rqmax;
717
718         ucrec a;
719         a.channel = NULL;
720         a.uc_modes = 0;
721         for (int i = 0; i < MAXCHANS; i++)
722                 clientlist[tempnick]->chans.push_back(a);
723
724         if (clientlist.size() > Config->SoftLimit)
725         {
726                 kill_link(clientlist[tempnick],"No more connections allowed");
727                 return;
728         }
729
730         if (clientlist.size() >= MAXCLIENTS)
731         {
732                 kill_link(clientlist[tempnick],"No more connections allowed");
733                 return;
734         }
735
736         // this is done as a safety check to keep the file descriptors within range of fd_ref_table.
737         // its a pretty big but for the moment valid assumption:
738         // file descriptors are handed out starting at 0, and are recycled as theyre freed.
739         // therefore if there is ever an fd over 65535, 65536 clients must be connected to the
740         // irc server at once (or the irc server otherwise initiating this many connections, files etc)
741         // which for the time being is a physical impossibility (even the largest networks dont have more
742         // than about 10,000 users on ONE server!)
743         if ((unsigned)socket > 65534)
744         {
745                 kill_link(clientlist[tempnick],"Server is full");
746                 return;
747         }
748                 
749
750         char* e = matches_exception(ip);
751         if (!e)
752         {
753                 char* r = matches_zline(ip);
754                 if (r)
755                 {
756                         char reason[MAXBUF];
757                         snprintf(reason,MAXBUF,"Z-Lined: %s",r);
758                         kill_link(clientlist[tempnick],reason);
759                         return;
760                 }
761         }
762         fd_ref_table[socket] = clientlist[tempnick];
763         SE->AddFd(socket,true,X_ESTAB_CLIENT);
764 }
765
766 /* shows the message of the day, and any other on-logon stuff */
767 void FullConnectUser(userrec* user)
768 {
769         stats->statsConnects++;
770         user->idle_lastmsg = TIME;
771         log(DEBUG,"ConnectUser: %s",user->nick);
772
773         if ((strcmp(Passwd(user),"")) && (!user->haspassed))
774         {
775                 kill_link(user,"Invalid password");
776                 return;
777         }
778         if (IsDenied(user))
779         {
780                 kill_link(user,"Unauthorised connection");
781                 return;
782         }
783
784         char match_against[MAXBUF];
785         snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
786         char* e = matches_exception(match_against);
787         if (!e)
788         {
789                 char* r = matches_gline(match_against);
790                 if (r)
791                 {
792                         char reason[MAXBUF];
793                         snprintf(reason,MAXBUF,"G-Lined: %s",r);
794                         kill_link_silent(user,reason);
795                         return;
796                 }
797                 r = matches_kline(user->host);
798                 if (r)
799                 {
800                         char reason[MAXBUF];
801                         snprintf(reason,MAXBUF,"K-Lined: %s",r);
802                         kill_link_silent(user,reason);
803                         return;
804                 }
805         }
806
807
808         WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Config->Network);
809         WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Config->Network,user->nick,user->ident,user->host);
810         WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,Config->ServerName,VERSION);
811         WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
812         WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,Config->ServerName,VERSION);
813         // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
814         std::stringstream v;
815         v << "WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
816         v << " MAXBANS=60 NICKLEN=" << NICKMAX;
817         v << " TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=20 AWAYLEN=" << MAXAWAY << " CHANMODES=ohvb,k,l,psmnti NETWORK=";
818         v << Config->Network;
819         std::string data005 = v.str();
820         FOREACH_MOD On005Numeric(data005);
821         // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
822         // so i'd better split it :)
823         std::stringstream out(data005);
824         std::string token = "";
825         std::string line5 = "";
826         int token_counter = 0;
827         while (!out.eof())
828         {
829                 out >> token;
830                 line5 = line5 + token + " ";
831                 token_counter++;
832                 if ((token_counter >= 13) || (out.eof() == true))
833                 {
834                         WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
835                         line5 = "";
836                         token_counter = 0;
837                 }
838         }
839         ShowMOTD(user);
840
841         // fix 3 by brain, move registered = 7 below these so that spurious modes and host changes dont go out
842         // onto the network and produce 'fake direction'
843         FOREACH_MOD OnUserConnect(user);
844         FOREACH_MOD OnGlobalConnect(user);
845         user->registered = 7;
846         WriteOpers("*** Client connecting on port %lu: %s!%s@%s [%s]",(unsigned long)user->port,user->nick,user->ident,user->host,user->ip);
847 }
848
849
850 /* shows the message of the day, and any other on-logon stuff */
851 void ConnectUser(userrec *user)
852 {
853         // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
854         if ((user->dns_done) && (user->registered >= 3) && (AllModulesReportReady(user)))
855         {
856                 FullConnectUser(user);
857         }
858 }
859
860 std::string GetVersionString()
861 {
862         char versiondata[MAXBUF];
863 #ifdef THREADED_DNS
864         char dnsengine[] = "multithread";
865 #else
866         char dnsengine[] = "singlethread";
867 #endif
868         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);
869         return versiondata;
870 }
871
872 void handle_version(char **parameters, int pcnt, userrec *user)
873 {
874         WriteServ(user->fd,"351 %s :%s",user->nick,GetVersionString().c_str());
875 }
876
877
878 bool is_valid_cmd(const char* commandname, int pcnt, userrec * user)
879 {
880         for (unsigned int i = 0; i < cmdlist.size(); i++)
881         {
882                 if (!strcasecmp(cmdlist[i].command,commandname))
883                 {
884                         if (cmdlist[i].handler_function)
885                         {
886                                 if ((pcnt>=cmdlist[i].min_params) && (strcasecmp(cmdlist[i].source,"<core>")))
887                                 {
888                                         if ((strchr(user->modes,cmdlist[i].flags_needed)) || (!cmdlist[i].flags_needed))
889                                         {
890                                                 if (cmdlist[i].flags_needed)
891                                                 {
892                                                         if ((user->HasPermission((char*)commandname)) || (is_uline(user->server)))
893                                                         {
894                                                                 return true;
895                                                         }
896                                                         else
897                                                         {
898                                                                 return false;
899                                                         }
900                                                 }
901                                                 return true;
902                                         }
903                                 }
904                         }
905                 }
906         }
907         return false;
908 }
909
910 // calls a handler function for a command
911
912 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
913 {
914         for (unsigned int i = 0; i < cmdlist.size(); i++)
915         {
916                 if (!strcasecmp(cmdlist[i].command,commandname))
917                 {
918                         if (cmdlist[i].handler_function)
919                         {
920                                 if (pcnt>=cmdlist[i].min_params)
921                                 {
922                                         if ((strchr(user->modes,cmdlist[i].flags_needed)) || (!cmdlist[i].flags_needed))
923                                         {
924                                                 if (cmdlist[i].flags_needed)
925                                                 {
926                                                         if ((user->HasPermission((char*)commandname)) || (is_uline(user->server)))
927                                                         {
928                                                                 cmdlist[i].handler_function(parameters,pcnt,user);
929                                                         }
930                                                 }
931                                                 else
932                                                 {
933                                                         cmdlist[i].handler_function(parameters,pcnt,user);
934                                                 }
935                                         }
936                                 }
937                         }
938                 }
939         }
940 }
941
942
943 void force_nickchange(userrec* user,const char* newnick)
944 {
945         char nick[MAXBUF];
946         int MOD_RESULT = 0;
947         
948         strcpy(nick,"");
949
950         FOREACH_RESULT(OnUserPreNick(user,newnick));
951         if (MOD_RESULT) {
952                 stats->statsCollisions++;
953                 kill_link(user,"Nickname collision");
954                 return;
955         }
956         if (matches_qline(newnick))
957         {
958                 stats->statsCollisions++;
959                 kill_link(user,"Nickname collision");
960                 return;
961         }
962         
963         if (user)
964         {
965                 if (newnick)
966                 {
967                         strncpy(nick,newnick,MAXBUF);
968                 }
969                 if (user->registered == 7)
970                 {
971                         char* pars[1];
972                         pars[0] = nick;
973                         handle_nick(pars,1,user);
974                 }
975         }
976 }
977                                 
978
979 int process_parameters(char **command_p,char *parameters)
980 {
981         int j = 0;
982         int q = strlen(parameters);
983         if (!q)
984         {
985                 /* no parameters, command_p invalid! */
986                 return 0;
987         }
988         if (parameters[0] == ':')
989         {
990                 command_p[0] = parameters+1;
991                 return 1;
992         }
993         if (q)
994         {
995                 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
996                 {
997                         /* only one parameter */
998                         command_p[0] = parameters;
999                         if (parameters[0] == ':')
1000                         {
1001                                 if (strchr(parameters,' ') != NULL)
1002                                 {
1003                                         command_p[0]++;
1004                                 }
1005                         }
1006                         return 1;
1007                 }
1008         }
1009         command_p[j++] = parameters;
1010         for (int i = 0; i <= q; i++)
1011         {
1012                 if (parameters[i] == ' ')
1013                 {
1014                         command_p[j++] = parameters+i+1;
1015                         parameters[i] = '\0';
1016                         if (command_p[j-1][0] == ':')
1017                         {
1018                                 *command_p[j-1]++; /* remove dodgy ":" */
1019                                 break;
1020                                 /* parameter like this marks end of the sequence */
1021                         }
1022                 }
1023         }
1024         return j; /* returns total number of items in the list */
1025 }
1026
1027 void process_command(userrec *user, char* cmd)
1028 {
1029         char *parameters;
1030         char *command;
1031         char *command_p[127];
1032         char p[MAXBUF], temp[MAXBUF];
1033         int j, items, cmd_found;
1034
1035         for (int i = 0; i < 127; i++)
1036                 command_p[i] = NULL;
1037
1038         if (!user)
1039         {
1040                 return;
1041         }
1042         if (!cmd)
1043         {
1044                 return;
1045         }
1046         if (!cmd[0])
1047         {
1048                 return;
1049         }
1050         
1051         int total_params = 0;
1052         if (strlen(cmd)>2)
1053         {
1054                 for (unsigned int q = 0; q < strlen(cmd)-1; q++)
1055                 {
1056                         if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
1057                         {
1058                                 total_params++;
1059                                 // found a 'trailing', we dont count them after this.
1060                                 break;
1061                         }
1062                         if (cmd[q] == ' ')
1063                                 total_params++;
1064                 }
1065         }
1066
1067         // another phidjit bug...
1068         if (total_params > 126)
1069         {
1070                 *(strchr(cmd,' ')) = '\0';
1071                 WriteServ(user->fd,"421 %s %s :Too many parameters given",user->nick,cmd);
1072                 return;
1073         }
1074
1075         strlcpy(temp,cmd,MAXBUF);
1076         
1077         std::string tmp = cmd;
1078         for (int i = 0; i <= MODCOUNT; i++)
1079         {
1080                 std::string oldtmp = tmp;
1081                 modules[i]->OnServerRaw(tmp,true,user);
1082                 if (oldtmp != tmp)
1083                 {
1084                         log(DEBUG,"A Module changed the input string!");
1085                         log(DEBUG,"New string: %s",tmp.c_str());
1086                         log(DEBUG,"Old string: %s",oldtmp.c_str());
1087                         break;
1088                 }
1089         }
1090         strlcpy(cmd,tmp.c_str(),MAXBUF);
1091         strlcpy(temp,cmd,MAXBUF);
1092
1093         if (!strchr(cmd,' '))
1094         {
1095                 /* no parameters, lets skip the formalities and not chop up
1096                  * the string */
1097                 log(DEBUG,"About to preprocess command with no params");
1098                 items = 0;
1099                 command_p[0] = NULL;
1100                 parameters = NULL;
1101                 for (unsigned int i = 0; i <= strlen(cmd); i++)
1102                 {
1103                         cmd[i] = toupper(cmd[i]);
1104                 }
1105                 command = cmd;
1106         }
1107         else
1108         {
1109                 strcpy(cmd,"");
1110                 j = 0;
1111                 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
1112                 for (unsigned int i = 0; i < strlen(temp); i++)
1113                 {
1114                         if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
1115                         {
1116                                 cmd[j++] = temp[i];
1117                                 cmd[j] = 0;
1118                         }
1119                 }
1120                 /* split the full string into a command plus parameters */
1121                 parameters = p;
1122                 strcpy(p," ");
1123                 command = cmd;
1124                 if (strchr(cmd,' '))
1125                 {
1126                         for (unsigned int i = 0; i <= strlen(cmd); i++)
1127                         {
1128                                 /* capitalise the command ONLY, leave params intact */
1129                                 cmd[i] = toupper(cmd[i]);
1130                                 /* are we nearly there yet?! :P */
1131                                 if (cmd[i] == ' ')
1132                                 {
1133                                         command = cmd;
1134                                         parameters = cmd+i+1;
1135                                         cmd[i] = '\0';
1136                                         break;
1137                                 }
1138                         }
1139                 }
1140                 else
1141                 {
1142                         for (unsigned int i = 0; i <= strlen(cmd); i++)
1143                         {
1144                                 cmd[i] = toupper(cmd[i]);
1145                         }
1146                 }
1147
1148         }
1149         cmd_found = 0;
1150         
1151         if (strlen(command)>MAXCOMMAND)
1152         {
1153                 WriteServ(user->fd,"421 %s %s :Command too long",user->nick,command);
1154                 return;
1155         }
1156         
1157         for (unsigned int x = 0; x < strlen(command); x++)
1158         {
1159                 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
1160                 {
1161                         if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
1162                         {
1163                                 if (strchr("@!\"$%^&*(){}[]_=+;:'#~,<>/?\\|`",command[x]))
1164                                 {
1165                                         stats->statsUnknown++;
1166                                         WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
1167                                         return;
1168                                 }
1169                         }
1170                 }
1171         }
1172
1173         for (unsigned int i = 0; i != cmdlist.size(); i++)
1174         {
1175                 if (cmdlist[i].command[0])
1176                 {
1177                         if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
1178                         {
1179                                 if (parameters)
1180                                 {
1181                                         if (parameters[0])
1182                                         {
1183                                                 items = process_parameters(command_p,parameters);
1184                                         }
1185                                         else
1186                                         {
1187                                                 items = 0;
1188                                                 command_p[0] = NULL;
1189                                         }
1190                                 }
1191                                 else
1192                                 {
1193                                         items = 0;
1194                                         command_p[0] = NULL;
1195                                 }
1196                                 
1197                                 if (user)
1198                                 {
1199                                         /* activity resets the ping pending timer */
1200                                         user->nping = TIME + user->pingmax;
1201                                         if ((items) < cmdlist[i].min_params)
1202                                         {
1203                                                 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
1204                                                 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
1205                                                 return;
1206                                         }
1207                                         if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
1208                                         {
1209                                                 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
1210                                                 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
1211                                                 cmd_found = 1;
1212                                                 return;
1213                                         }
1214                                         if ((cmdlist[i].flags_needed) && (!user->HasPermission(command)))
1215                                         {
1216                                                 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
1217                                                 WriteServ(user->fd,"481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command);
1218                                                 cmd_found = 1;
1219                                                 return;
1220                                         }
1221                                         /* if the command isnt USER, PASS, or NICK, and nick is empty,
1222                                          * deny command! */
1223                                         if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
1224                                         {
1225                                                 if ((!isnick(user->nick)) || (user->registered != 7))
1226                                                 {
1227                                                         log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
1228                                                         WriteServ(user->fd,"451 %s :You have not registered",command);
1229                                                         return;
1230                                                 }
1231                                         }
1232                                         if ((user->registered == 7) && (!strchr(user->modes,'o')))
1233                                         {
1234                                                 std::stringstream dcmds(Config->DisabledCommands);
1235                                                 while (!dcmds.eof())
1236                                                 {
1237                                                         std::string thiscmd;
1238                                                         dcmds >> thiscmd;
1239                                                         if (!strcasecmp(thiscmd.c_str(),command))
1240                                                         {
1241                                                                 // command is disabled!
1242                                                                 WriteServ(user->fd,"421 %s %s :This command has been disabled.",user->nick,command);
1243                                                                 return;
1244                                                         }
1245                                                 }
1246                                         }
1247                                         if ((user->registered == 7) || (!strncmp(command,"USER",4)) || (!strncmp(command,"NICK",4)) || (!strncmp(command,"PASS",4)))
1248                                         {
1249                                                 if (cmdlist[i].handler_function)
1250                                                 {
1251                                                         
1252                                                         /* ikky /stats counters */
1253                                                         if (temp)
1254                                                         {
1255                                                                 cmdlist[i].use_count++;
1256                                                                 cmdlist[i].total_bytes+=strlen(temp);
1257                                                         }
1258
1259                                                         int MOD_RESULT = 0;
1260                                                         FOREACH_RESULT(OnPreCommand(command,command_p,items,user));
1261                                                         if (MOD_RESULT == 1) {
1262                                                                 return;
1263                                                         }
1264
1265                                                         /* WARNING: nothing may come after the
1266                                                          * command handler call, as the handler
1267                                                          * may free the user structure! */
1268
1269                                                         cmdlist[i].handler_function(command_p,items,user);
1270                                                 }
1271                                                 return;
1272                                         }
1273                                         else
1274                                         {
1275                                                 WriteServ(user->fd,"451 %s :You have not registered",command);
1276                                                 return;
1277                                         }
1278                                 }
1279                                 cmd_found = 1;
1280                         }
1281                 }
1282         }
1283         if ((!cmd_found) && (user))
1284         {
1285                 stats->statsUnknown++;
1286                 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
1287         }
1288 }
1289
1290 bool removecommands(const char* source)
1291 {
1292         bool go_again = true;
1293         while (go_again)
1294         {
1295                 go_again = false;
1296                 for (std::deque<command_t>::iterator i = cmdlist.begin(); i != cmdlist.end(); i++)
1297                 {
1298                         if (!strcmp(i->source,source))
1299                         {
1300                                 log(DEBUG,"removecommands(%s) Removing dependent command: %s",i->source,i->command);
1301                                 cmdlist.erase(i);
1302                                 go_again = true;
1303                                 break;
1304                         }
1305                 }
1306         }
1307         return true;
1308 }
1309
1310
1311 void process_buffer(const char* cmdbuf,userrec *user)
1312 {
1313         if (!user)
1314         {
1315                 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
1316                 return;
1317         }
1318         char cmd[MAXBUF];
1319         if (!cmdbuf)
1320         {
1321                 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
1322                 return;
1323         }
1324         if (!cmdbuf[0])
1325         {
1326                 return;
1327         }
1328         while (*cmdbuf == ' ') cmdbuf++; // strip leading spaces
1329
1330         strlcpy(cmd,cmdbuf,MAXBUF);
1331         if (!cmd[0])
1332         {
1333                 return;
1334         }
1335         int sl = strlen(cmd)-1;
1336         if ((cmd[sl] == 13) || (cmd[sl] == 10))
1337         {
1338                 cmd[sl] = '\0';
1339         }
1340         sl = strlen(cmd)-1;
1341         if ((cmd[sl] == 13) || (cmd[sl] == 10))
1342         {
1343                 cmd[sl] = '\0';
1344         }
1345         sl = strlen(cmd)-1;
1346         while (cmd[sl] == ' ') // strip trailing spaces
1347         {
1348                 cmd[sl] = '\0';
1349                 sl = strlen(cmd)-1;
1350         }
1351
1352         if (!cmd[0])
1353         {
1354                 return;
1355         }
1356         log(DEBUG,"CMDIN: %s %s",user->nick,cmd);
1357         tidystring(cmd);
1358         if ((user) && (cmd))
1359         {
1360                 process_command(user,cmd);
1361         }
1362 }
1363
1364 char MODERR[MAXBUF];
1365
1366 char* ModuleError()
1367 {
1368         return MODERR;
1369 }
1370
1371 void InspIRCd::erase_factory(int j)
1372 {
1373         int v = 0;
1374         for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
1375         {
1376                 if (v == j)
1377                 {
1378                         factory.erase(t);
1379                         factory.push_back(NULL);
1380                         return;
1381                 }
1382                 v++;
1383         }
1384 }
1385
1386 void InspIRCd::erase_module(int j)
1387 {
1388         int v1 = 0;
1389         for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
1390         {
1391                 if (v1 == j)
1392                 {
1393                         delete *m;
1394                         modules.erase(m);
1395                         modules.push_back(NULL);
1396                         break;
1397                 }
1398                 v1++;
1399         }
1400         int v2 = 0;
1401         for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
1402         {
1403                 if (v2 == j)
1404                 {
1405                        Config->module_names.erase(v);
1406                        break;
1407                 }
1408                 v2++;
1409         }
1410
1411 }
1412
1413 bool InspIRCd::UnloadModule(const char* filename)
1414 {
1415         std::string filename_str = filename;
1416         for (unsigned int j = 0; j != Config->module_names.size(); j++)
1417         {
1418                 if (Config->module_names[j] == filename_str)
1419                 {
1420                         if (modules[j]->GetVersion().Flags & VF_STATIC)
1421                         {
1422                                 log(DEFAULT,"Failed to unload STATIC module %s",filename);
1423                                 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
1424                                 return false;
1425                         }
1426                         /* Give the module a chance to tidy out all its metadata */
1427                         for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
1428                         {
1429                                 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
1430                         }
1431                         for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
1432                         {
1433                                 modules[j]->OnCleanup(TYPE_USER,u->second);
1434                         }
1435                         FOREACH_MOD OnUnloadModule(modules[j],Config->module_names[j]);
1436                         // found the module
1437                         log(DEBUG,"Deleting module...");
1438                         erase_module(j);
1439                         log(DEBUG,"Erasing module entry...");
1440                         erase_factory(j);
1441                         log(DEBUG,"Removing dependent commands...");
1442                         removecommands(filename);
1443                         log(DEFAULT,"Module %s unloaded",filename);
1444                         MODCOUNT--;
1445                         return true;
1446                 }
1447         }
1448         log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
1449         snprintf(MODERR,MAXBUF,"Module not loaded");
1450         return false;
1451 }
1452
1453 bool InspIRCd::LoadModule(const char* filename)
1454 {
1455         char modfile[MAXBUF];
1456 #ifdef STATIC_LINK
1457         snprintf(modfile,MAXBUF,"%s",filename);
1458 #else
1459         snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
1460 #endif
1461         std::string filename_str = filename;
1462 #ifndef STATIC_LINK
1463         if (!DirValid(modfile))
1464         {
1465                 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
1466                 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
1467                 return false;
1468         }
1469 #endif
1470         log(DEBUG,"Loading module: %s",modfile);
1471 #ifndef STATIC_LINK
1472         if (FileExists(modfile))
1473         {
1474 #endif
1475                 for (unsigned int j = 0; j < Config->module_names.size(); j++)
1476                 {
1477                         if (Config->module_names[j] == filename_str)
1478                         {
1479                                 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
1480                                 snprintf(MODERR,MAXBUF,"Module already loaded");
1481                                 return false;
1482                         }
1483                 }
1484                 ircd_module* a = new ircd_module(modfile);
1485                 factory[MODCOUNT+1] = a;
1486                 if (factory[MODCOUNT+1]->LastError())
1487                 {
1488                         log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
1489                         snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
1490                         MODCOUNT--;
1491                         return false;
1492                 }
1493                 if (factory[MODCOUNT+1]->factory)
1494                 {
1495                         Module* m = factory[MODCOUNT+1]->factory->CreateModule(MyServer);
1496                         modules[MODCOUNT+1] = m;
1497                         /* save the module and the module's classfactory, if
1498                          * this isnt done, random crashes can occur :/ */
1499                         Config->module_names.push_back(filename);
1500                 }
1501                 else
1502                 {
1503                         log(DEFAULT,"Unable to load %s",modfile);
1504                         snprintf(MODERR,MAXBUF,"Factory function failed!");
1505                         return false;
1506                 }
1507 #ifndef STATIC_LINK
1508         }
1509         else
1510         {
1511                 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
1512                 snprintf(MODERR,MAXBUF,"Module file could not be found");
1513                 return false;
1514         }
1515 #endif
1516         MODCOUNT++;
1517         FOREACH_MOD OnLoadModule(modules[MODCOUNT],filename_str);
1518         return true;
1519 }
1520
1521 int InspIRCd::Run()
1522 {
1523         bool expire_run = false;
1524         std::vector<int> activefds;
1525         int incomingSockfd;
1526         int in_port;
1527         userrec* cu = NULL;
1528         InspSocket* s = NULL;
1529         InspSocket* s_del = NULL;
1530         char* target;
1531         unsigned int numberactive;
1532         sockaddr_in sock_us;     // our port number
1533         socklen_t uslen;         // length of our port number
1534
1535         if (!Config->nofork)
1536         {
1537                 freopen("/dev/null","w",stdout);
1538                 freopen("/dev/null","w",stderr);
1539         }
1540
1541         /* Add the listening sockets used for client inbound connections
1542          * to the socket engine
1543          */
1544         for (int count = 0; count < BoundPortCount; count++)
1545                 SE->AddFd(openSockfd[count],true,X_LISTEN);
1546
1547         WritePID(Config->PID);
1548
1549         /* main loop, this never returns */
1550         for (;;)
1551         {
1552                 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
1553                  * Once per loop iteration is pleanty.
1554                  */
1555                 OLDTIME = TIME;
1556                 TIME = time(NULL);
1557
1558                 /* Run background module timers every few seconds
1559                  * (the docs say modules shouldnt rely on accurate
1560                  * timing using this event, so we dont have to
1561                  * time this exactly).
1562                  */
1563                 if (((TIME % 8) == 0) && (!expire_run))
1564                 {
1565                         expire_lines();
1566                         FOREACH_MOD OnBackgroundTimer(TIME);
1567                         expire_run = true;
1568                         continue;
1569                 }
1570                 if ((TIME % 8) == 1)
1571                         expire_run = false;
1572                 
1573                 /* Once a second, do the background processing */
1574                 if (TIME != OLDTIME)
1575                         while (DoBackgroundUserStuff(TIME));
1576
1577                 /* Call the socket engine to wait on the active
1578                  * file descriptors. The socket engine has everything's
1579                  * descriptors in its list... dns, modules, users,
1580                  * servers... so its nice and easy, just one call.
1581                  */
1582                 SE->Wait(activefds);
1583
1584                 /**
1585                  * Now process each of the fd's. For users, we have a fast
1586                  * lookup table which can find a user by file descriptor, so
1587                  * processing them by fd isnt expensive. If we have a lot of
1588                  * listening ports or module sockets though, things could get
1589                  * ugly.
1590                  */
1591                 numberactive = activefds.size();
1592                 for (unsigned int activefd = 0; activefd < numberactive; activefd++)
1593                 {
1594                         int socket_type = SE->GetType(activefds[activefd]);
1595                         switch (socket_type)
1596                         {
1597                                 case X_ESTAB_CLIENT:
1598
1599                                         cu = fd_ref_table[activefds[activefd]];
1600                                         if (cu)
1601                                                 ProcessUser(cu);
1602
1603                                 break;
1604
1605                                 case X_ESTAB_MODULE:
1606
1607                                         /* Process module-owned sockets.
1608                                          * Modules are encouraged to inherit their sockets from
1609                                          * InspSocket so we can process them neatly like this.
1610                                          */
1611                                         s = socket_ref[activefds[activefd]];
1612
1613                                         if ((s) && (!s->Poll()))
1614                                         {
1615                                                 log(DEBUG,"Socket poll returned false, close and bail");
1616                                                 SE->DelFd(s->GetFd());
1617                                                 for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
1618                                                 {
1619                                                         s_del = (InspSocket*)*a;
1620                                                         if ((s_del) && (s_del->GetFd() == activefds[activefd]))
1621                                                         {
1622                                                                 module_sockets.erase(a);
1623                                                                 break;
1624                                                         }
1625                                                 }
1626                                                 s->Close();
1627                                                 delete s;
1628                                         }
1629
1630                                 break;
1631
1632                                 case X_ESTAB_DNS:
1633
1634                                         /* When we are using single-threaded dns,
1635                                          * the sockets for dns end up in our mainloop.
1636                                          * When we are using multi-threaded dns,
1637                                          * each thread has its own basic poll() loop
1638                                          * within it, making them 'fire and forget'
1639                                          * and independent of the mainloop.
1640                                          */
1641 #ifndef THREADED_DNS
1642                                         dns_poll(activefds[activefd]);
1643 #endif
1644                                 break;
1645                                 
1646                                 case X_LISTEN:
1647
1648                                         /* It's a listener */
1649                                         uslen = sizeof(sock_us);
1650                                         length = sizeof(client);
1651                                         incomingSockfd = accept (activefds[activefd],(struct sockaddr*)&client,&length);
1652                                         if (!getsockname(incomingSockfd,(sockaddr*)&sock_us,&uslen))
1653                                         {
1654                                                 in_port = ntohs(sock_us.sin_port);
1655                                                 log(DEBUG,"Accepted socket %d",incomingSockfd);
1656                                                 target = (char*)inet_ntoa(client.sin_addr);
1657                                                 /* Years and years ago, we used to resolve here
1658                                                  * using gethostbyaddr(). That is sucky and we
1659                                                  * don't do that any more...
1660                                                  */
1661                                                 if (incomingSockfd >= 0)
1662                                                 {
1663                                                         FOREACH_MOD OnRawSocketAccept(incomingSockfd, target, in_port);
1664                                                         stats->statsAccept++;
1665                                                         AddClient(incomingSockfd, target, in_port, false, target);
1666                                                         log(DEBUG,"Adding client on port %lu fd=%lu",(unsigned long)in_port,(unsigned long)incomingSockfd);
1667                                                 }
1668                                                 else
1669                                                 {
1670                                                         WriteOpers("*** WARNING: accept() failed on port %lu (%s)",(unsigned long)in_port,target);
1671                                                         log(DEBUG,"accept failed: %lu",(unsigned long)in_port);
1672                                                         stats->statsRefused++;
1673                                                 }
1674                                         }
1675                                         else
1676                                         {
1677                                                 log(DEBUG,"Couldnt look up the port number for fd %lu (OS BROKEN?!)",incomingSockfd);
1678                                                 shutdown(incomingSockfd,2);
1679                                                 close(incomingSockfd);
1680                                         }
1681                                 break;
1682
1683                                 default:
1684                                         /* Something went wrong if we're in here.
1685                                          * In fact, so wrong, im not quite sure
1686                                          * what we would do, so for now, its going
1687                                          * to safely do bugger all.
1688                                          */
1689                                 break;
1690                         }
1691                 }
1692
1693         }
1694         /* This is never reached -- we hope! */
1695         return 0;
1696 }
1697
1698 /**********************************************************************************/
1699
1700 /**
1701  * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
1702  */
1703
1704 int main(int argc, char** argv)
1705 {
1706         InspIRCd* TittyBiscuits = new InspIRCd(argc, argv);
1707         TittyBiscuits->Run();
1708         delete TittyBiscuits;
1709         return 0;
1710 }
1711