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