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