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