]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
Made inspircd itself a class, and called its instance TittyBiscuits, just because.
[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         return;
472 }
473
474 template<typename T> inline string ConvToStr(const T &in)
475 {
476         stringstream tmp;
477         if (!(tmp << in)) return string();
478         return tmp.str();
479 }
480
481 /* re-allocates a nick in the user_hash after they change nicknames,
482  * returns a pointer to the new user as it may have moved */
483
484 userrec* ReHashNick(char* Old, char* New)
485 {
486         //user_hash::iterator newnick;
487         user_hash::iterator oldnick = clientlist.find(Old);
488
489         log(DEBUG,"ReHashNick: %s %s",Old,New);
490         
491         if (!strcasecmp(Old,New))
492         {
493                 log(DEBUG,"old nick is new nick, skipping");
494                 return oldnick->second;
495         }
496         
497         if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
498
499         log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
500
501         userrec* olduser = oldnick->second;
502         clientlist[New] = olduser;
503         clientlist.erase(oldnick);
504
505         log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
506         
507         return clientlist[New];
508 }
509
510 /* adds or updates an entry in the whowas list */
511 void AddWhoWas(userrec* u)
512 {
513         whowas_hash::iterator iter = whowas.find(u->nick);
514         WhoWasUser *a = new WhoWasUser();
515         strlcpy(a->nick,u->nick,NICKMAX);
516         strlcpy(a->ident,u->ident,IDENTMAX);
517         strlcpy(a->dhost,u->dhost,160);
518         strlcpy(a->host,u->host,160);
519         strlcpy(a->fullname,u->fullname,MAXGECOS);
520         strlcpy(a->server,u->server,256);
521         a->signon = u->signon;
522
523         /* MAX_WHOWAS:   max number of /WHOWAS items
524          * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
525          *               can be replaced by a newer one
526          */
527         
528         if (iter == whowas.end())
529         {
530                 if (whowas.size() >= (unsigned)WHOWAS_MAX)
531                 {
532                         for (whowas_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
533                         {
534                                 // 3600 seconds in an hour ;)
535                                 if ((i->second->signon)<(TIME-(WHOWAS_STALE*3600)))
536                                 {
537                                         // delete the old one
538                                         if (i->second) delete i->second;
539                                         // replace with new one
540                                         i->second = a;
541                                         log(DEBUG,"added WHOWAS entry, purged an old record");
542                                         return;
543                                 }
544                         }
545                         // no space left and user doesnt exist. Don't leave ram in use!
546                         log(DEBUG,"Not able to update whowas (list at WHOWAS_MAX entries and trying to add new?), freeing excess ram");
547                         delete a;
548                 }
549                 else
550                 {
551                         log(DEBUG,"added fresh WHOWAS entry");
552                         whowas[a->nick] = a;
553                 }
554         }
555         else
556         {
557                 log(DEBUG,"updated WHOWAS entry");
558                 if (iter->second) delete iter->second;
559                 iter->second = a;
560         }
561 }
562
563 #ifdef THREADED_DNS
564 void* dns_task(void* arg)
565 {
566         userrec* u = (userrec*)arg;
567         log(DEBUG,"DNS thread for user %s",u->nick);
568         DNS dns1;
569         DNS dns2;
570         std::string host;
571         std::string ip;
572         if (dns1.ReverseLookup(u->ip))
573         {
574                 log(DEBUG,"DNS Step 1");
575                 while (!dns1.HasResult())
576                 {
577                         usleep(100);
578                 }
579                 host = dns1.GetResult();
580                 if (host != "")
581                 {
582                         log(DEBUG,"DNS Step 2: '%s'",host.c_str());
583                         if (dns2.ForwardLookup(host))
584                         {
585                                 while (!dns2.HasResult())
586                                 {
587                                         usleep(100);
588                                 }
589                                 ip = dns2.GetResultIP();
590                                 log(DEBUG,"DNS Step 3 '%s'(%d) '%s'(%d)",ip.c_str(),ip.length(),u->ip,strlen(u->ip));
591                                 if (ip == std::string(u->ip))
592                                 {
593                                         log(DEBUG,"DNS Step 4");
594                                         if (host.length() < 160)
595                                         {
596                                                 log(DEBUG,"DNS Step 5");
597                                                 strcpy(u->host,host.c_str());
598                                                 strcpy(u->dhost,host.c_str());
599                                         }
600                                 }
601                         }
602                 }
603         }
604         u->dns_done = true;
605         return NULL;
606 }
607 #endif
608
609 /* add a client connection to the sockets list */
610 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
611 {
612         string tempnick;
613         char tn2[MAXBUF];
614         user_hash::iterator iter;
615
616         tempnick = ConvToStr(socket) + "-unknown";
617         sprintf(tn2,"%lu-unknown",(unsigned long)socket);
618
619         iter = clientlist.find(tempnick);
620
621         // fix by brain.
622         // as these nicknames are 'RFC impossible', we can be sure nobody is going to be
623         // using one as a registered connection. As theyre per fd, we can also safely assume
624         // that we wont have collisions. Therefore, if the nick exists in the list, its only
625         // used by a dead socket, erase the iterator so that the new client may reclaim it.
626         // this was probably the cause of 'server ignores me when i hammer it with reconnects'
627         // issue in earlier alphas/betas
628         if (iter != clientlist.end())
629         {
630                 userrec* goner = iter->second;
631                 delete goner;
632                 clientlist.erase(iter);
633         }
634
635         /*
636          * It is OK to access the value here this way since we know
637          * it exists, we just created it above.
638          *
639          * At NO other time should you access a value in a map or a
640          * hash_map this way.
641          */
642         clientlist[tempnick] = new userrec();
643
644         NonBlocking(socket);
645         log(DEBUG,"AddClient: %lu %s %d %s",(unsigned long)socket,host,port,ip);
646
647         clientlist[tempnick]->fd = socket;
648         strlcpy(clientlist[tempnick]->nick, tn2,NICKMAX);
649         strlcpy(clientlist[tempnick]->host, host,160);
650         strlcpy(clientlist[tempnick]->dhost, host,160);
651         clientlist[tempnick]->server = (char*)FindServerNamePtr(Config->ServerName);
652         strlcpy(clientlist[tempnick]->ident, "unknown",IDENTMAX);
653         clientlist[tempnick]->registered = 0;
654         clientlist[tempnick]->signon = TIME + Config->dns_timeout;
655         clientlist[tempnick]->lastping = 1;
656         clientlist[tempnick]->port = port;
657         strlcpy(clientlist[tempnick]->ip,ip,16);
658
659         // set the registration timeout for this user
660         unsigned long class_regtimeout = 90;
661         int class_flood = 0;
662         long class_threshold = 5;
663         long class_sqmax = 262144;      // 256kb
664         long class_rqmax = 4096;        // 4k
665
666         for (ClassVector::iterator i = Config->Classes.begin(); i != Config->Classes.end(); i++)
667         {
668                 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
669                 {
670                         class_regtimeout = (unsigned long)i->registration_timeout;
671                         class_flood = i->flood;
672                         clientlist[tempnick]->pingmax = i->pingtime;
673                         class_threshold = i->threshold;
674                         class_sqmax = i->sendqmax;
675                         class_rqmax = i->recvqmax;
676                         break;
677                 }
678         }
679
680         clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax + Config->dns_timeout;
681         clientlist[tempnick]->timeout = TIME+class_regtimeout;
682         clientlist[tempnick]->flood = class_flood;
683         clientlist[tempnick]->threshold = class_threshold;
684         clientlist[tempnick]->sendqmax = class_sqmax;
685         clientlist[tempnick]->recvqmax = class_rqmax;
686
687         ucrec a;
688         a.channel = NULL;
689         a.uc_modes = 0;
690         for (int i = 0; i < MAXCHANS; i++)
691                 clientlist[tempnick]->chans.push_back(a);
692
693         if (clientlist.size() > Config->SoftLimit)
694         {
695                 kill_link(clientlist[tempnick],"No more connections allowed");
696                 return;
697         }
698
699         if (clientlist.size() >= MAXCLIENTS)
700         {
701                 kill_link(clientlist[tempnick],"No more connections allowed");
702                 return;
703         }
704
705         // this is done as a safety check to keep the file descriptors within range of fd_ref_table.
706         // its a pretty big but for the moment valid assumption:
707         // file descriptors are handed out starting at 0, and are recycled as theyre freed.
708         // therefore if there is ever an fd over 65535, 65536 clients must be connected to the
709         // irc server at once (or the irc server otherwise initiating this many connections, files etc)
710         // which for the time being is a physical impossibility (even the largest networks dont have more
711         // than about 10,000 users on ONE server!)
712         if ((unsigned)socket > 65534)
713         {
714                 kill_link(clientlist[tempnick],"Server is full");
715                 return;
716         }
717                 
718
719         char* e = matches_exception(ip);
720         if (!e)
721         {
722                 char* r = matches_zline(ip);
723                 if (r)
724                 {
725                         char reason[MAXBUF];
726                         snprintf(reason,MAXBUF,"Z-Lined: %s",r);
727                         kill_link(clientlist[tempnick],reason);
728                         return;
729                 }
730         }
731         fd_ref_table[socket] = clientlist[tempnick];
732         SE->AddFd(socket,true,X_ESTAB_CLIENT);
733 }
734
735 /* shows the message of the day, and any other on-logon stuff */
736 void FullConnectUser(userrec* user)
737 {
738         stats->statsConnects++;
739         user->idle_lastmsg = TIME;
740         log(DEBUG,"ConnectUser: %s",user->nick);
741
742         if ((strcmp(Passwd(user),"")) && (!user->haspassed))
743         {
744                 kill_link(user,"Invalid password");
745                 return;
746         }
747         if (IsDenied(user))
748         {
749                 kill_link(user,"Unauthorised connection");
750                 return;
751         }
752
753         char match_against[MAXBUF];
754         snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
755         char* e = matches_exception(match_against);
756         if (!e)
757         {
758                 char* r = matches_gline(match_against);
759                 if (r)
760                 {
761                         char reason[MAXBUF];
762                         snprintf(reason,MAXBUF,"G-Lined: %s",r);
763                         kill_link_silent(user,reason);
764                         return;
765                 }
766                 r = matches_kline(user->host);
767                 if (r)
768                 {
769                         char reason[MAXBUF];
770                         snprintf(reason,MAXBUF,"K-Lined: %s",r);
771                         kill_link_silent(user,reason);
772                         return;
773                 }
774         }
775
776
777         WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Config->Network);
778         WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Config->Network,user->nick,user->ident,user->host);
779         WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,Config->ServerName,VERSION);
780         WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
781         WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,Config->ServerName,VERSION);
782         // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
783         std::stringstream v;
784         v << "WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
785         v << " MAXBANS=60 NICKLEN=" << NICKMAX;
786         v << " TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=20 AWAYLEN=" << MAXAWAY << " CHANMODES=ohvb,k,l,psmnti NETWORK=";
787         v << Config->Network;
788         std::string data005 = v.str();
789         FOREACH_MOD On005Numeric(data005);
790         // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
791         // so i'd better split it :)
792         std::stringstream out(data005);
793         std::string token = "";
794         std::string line5 = "";
795         int token_counter = 0;
796         while (!out.eof())
797         {
798                 out >> token;
799                 line5 = line5 + token + " ";
800                 token_counter++;
801                 if ((token_counter >= 13) || (out.eof() == true))
802                 {
803                         WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
804                         line5 = "";
805                         token_counter = 0;
806                 }
807         }
808         ShowMOTD(user);
809
810         // fix 3 by brain, move registered = 7 below these so that spurious modes and host changes dont go out
811         // onto the network and produce 'fake direction'
812         FOREACH_MOD OnUserConnect(user);
813         FOREACH_MOD OnGlobalConnect(user);
814         user->registered = 7;
815         WriteOpers("*** Client connecting on port %lu: %s!%s@%s [%s]",(unsigned long)user->port,user->nick,user->ident,user->host,user->ip);
816 }
817
818
819 /* shows the message of the day, and any other on-logon stuff */
820 void ConnectUser(userrec *user)
821 {
822         // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
823         if ((user->dns_done) && (user->registered >= 3) && (AllModulesReportReady(user)))
824         {
825                 FullConnectUser(user);
826         }
827 }
828
829 std::string GetVersionString()
830 {
831         char versiondata[MAXBUF];
832 #ifdef THREADED_DNS
833         char dnsengine[] = "multithread";
834 #else
835         char dnsengine[] = "singlethread";
836 #endif
837         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);
838         return versiondata;
839 }
840
841 void handle_version(char **parameters, int pcnt, userrec *user)
842 {
843         WriteServ(user->fd,"351 %s :%s",user->nick,GetVersionString().c_str());
844 }
845
846
847 bool is_valid_cmd(const char* commandname, int pcnt, userrec * user)
848 {
849         for (unsigned int i = 0; i < cmdlist.size(); i++)
850         {
851                 if (!strcasecmp(cmdlist[i].command,commandname))
852                 {
853                         if (cmdlist[i].handler_function)
854                         {
855                                 if ((pcnt>=cmdlist[i].min_params) && (strcasecmp(cmdlist[i].source,"<core>")))
856                                 {
857                                         if ((strchr(user->modes,cmdlist[i].flags_needed)) || (!cmdlist[i].flags_needed))
858                                         {
859                                                 if (cmdlist[i].flags_needed)
860                                                 {
861                                                         if ((user->HasPermission((char*)commandname)) || (is_uline(user->server)))
862                                                         {
863                                                                 return true;
864                                                         }
865                                                         else
866                                                         {
867                                                                 return false;
868                                                         }
869                                                 }
870                                                 return true;
871                                         }
872                                 }
873                         }
874                 }
875         }
876         return false;
877 }
878
879 // calls a handler function for a command
880
881 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
882 {
883         for (unsigned int i = 0; i < cmdlist.size(); i++)
884         {
885                 if (!strcasecmp(cmdlist[i].command,commandname))
886                 {
887                         if (cmdlist[i].handler_function)
888                         {
889                                 if (pcnt>=cmdlist[i].min_params)
890                                 {
891                                         if ((strchr(user->modes,cmdlist[i].flags_needed)) || (!cmdlist[i].flags_needed))
892                                         {
893                                                 if (cmdlist[i].flags_needed)
894                                                 {
895                                                         if ((user->HasPermission((char*)commandname)) || (is_uline(user->server)))
896                                                         {
897                                                                 cmdlist[i].handler_function(parameters,pcnt,user);
898                                                         }
899                                                 }
900                                                 else
901                                                 {
902                                                         cmdlist[i].handler_function(parameters,pcnt,user);
903                                                 }
904                                         }
905                                 }
906                         }
907                 }
908         }
909 }
910
911
912 void force_nickchange(userrec* user,const char* newnick)
913 {
914         char nick[MAXBUF];
915         int MOD_RESULT = 0;
916         
917         strcpy(nick,"");
918
919         FOREACH_RESULT(OnUserPreNick(user,newnick));
920         if (MOD_RESULT) {
921                 stats->statsCollisions++;
922                 kill_link(user,"Nickname collision");
923                 return;
924         }
925         if (matches_qline(newnick))
926         {
927                 stats->statsCollisions++;
928                 kill_link(user,"Nickname collision");
929                 return;
930         }
931         
932         if (user)
933         {
934                 if (newnick)
935                 {
936                         strncpy(nick,newnick,MAXBUF);
937                 }
938                 if (user->registered == 7)
939                 {
940                         char* pars[1];
941                         pars[0] = nick;
942                         handle_nick(pars,1,user);
943                 }
944         }
945 }
946                                 
947
948 int process_parameters(char **command_p,char *parameters)
949 {
950         int j = 0;
951         int q = strlen(parameters);
952         if (!q)
953         {
954                 /* no parameters, command_p invalid! */
955                 return 0;
956         }
957         if (parameters[0] == ':')
958         {
959                 command_p[0] = parameters+1;
960                 return 1;
961         }
962         if (q)
963         {
964                 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
965                 {
966                         /* only one parameter */
967                         command_p[0] = parameters;
968                         if (parameters[0] == ':')
969                         {
970                                 if (strchr(parameters,' ') != NULL)
971                                 {
972                                         command_p[0]++;
973                                 }
974                         }
975                         return 1;
976                 }
977         }
978         command_p[j++] = parameters;
979         for (int i = 0; i <= q; i++)
980         {
981                 if (parameters[i] == ' ')
982                 {
983                         command_p[j++] = parameters+i+1;
984                         parameters[i] = '\0';
985                         if (command_p[j-1][0] == ':')
986                         {
987                                 *command_p[j-1]++; /* remove dodgy ":" */
988                                 break;
989                                 /* parameter like this marks end of the sequence */
990                         }
991                 }
992         }
993         return j; /* returns total number of items in the list */
994 }
995
996 void process_command(userrec *user, char* cmd)
997 {
998         char *parameters;
999         char *command;
1000         char *command_p[127];
1001         char p[MAXBUF], temp[MAXBUF];
1002         int j, items, cmd_found;
1003
1004         for (int i = 0; i < 127; i++)
1005                 command_p[i] = NULL;
1006
1007         if (!user)
1008         {
1009                 return;
1010         }
1011         if (!cmd)
1012         {
1013                 return;
1014         }
1015         if (!cmd[0])
1016         {
1017                 return;
1018         }
1019         
1020         int total_params = 0;
1021         if (strlen(cmd)>2)
1022         {
1023                 for (unsigned int q = 0; q < strlen(cmd)-1; q++)
1024                 {
1025                         if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
1026                         {
1027                                 total_params++;
1028                                 // found a 'trailing', we dont count them after this.
1029                                 break;
1030                         }
1031                         if (cmd[q] == ' ')
1032                                 total_params++;
1033                 }
1034         }
1035
1036         // another phidjit bug...
1037         if (total_params > 126)
1038         {
1039                 *(strchr(cmd,' ')) = '\0';
1040                 WriteServ(user->fd,"421 %s %s :Too many parameters given",user->nick,cmd);
1041                 return;
1042         }
1043
1044         strlcpy(temp,cmd,MAXBUF);
1045         
1046         std::string tmp = cmd;
1047         for (int i = 0; i <= MODCOUNT; i++)
1048         {
1049                 std::string oldtmp = tmp;
1050                 modules[i]->OnServerRaw(tmp,true,user);
1051                 if (oldtmp != tmp)
1052                 {
1053                         log(DEBUG,"A Module changed the input string!");
1054                         log(DEBUG,"New string: %s",tmp.c_str());
1055                         log(DEBUG,"Old string: %s",oldtmp.c_str());
1056                         break;
1057                 }
1058         }
1059         strlcpy(cmd,tmp.c_str(),MAXBUF);
1060         strlcpy(temp,cmd,MAXBUF);
1061
1062         if (!strchr(cmd,' '))
1063         {
1064                 /* no parameters, lets skip the formalities and not chop up
1065                  * the string */
1066                 log(DEBUG,"About to preprocess command with no params");
1067                 items = 0;
1068                 command_p[0] = NULL;
1069                 parameters = NULL;
1070                 for (unsigned int i = 0; i <= strlen(cmd); i++)
1071                 {
1072                         cmd[i] = toupper(cmd[i]);
1073                 }
1074                 command = cmd;
1075         }
1076         else
1077         {
1078                 strcpy(cmd,"");
1079                 j = 0;
1080                 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
1081                 for (unsigned int i = 0; i < strlen(temp); i++)
1082                 {
1083                         if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
1084                         {
1085                                 cmd[j++] = temp[i];
1086                                 cmd[j] = 0;
1087                         }
1088                 }
1089                 /* split the full string into a command plus parameters */
1090                 parameters = p;
1091                 strcpy(p," ");
1092                 command = cmd;
1093                 if (strchr(cmd,' '))
1094                 {
1095                         for (unsigned int i = 0; i <= strlen(cmd); i++)
1096                         {
1097                                 /* capitalise the command ONLY, leave params intact */
1098                                 cmd[i] = toupper(cmd[i]);
1099                                 /* are we nearly there yet?! :P */
1100                                 if (cmd[i] == ' ')
1101                                 {
1102                                         command = cmd;
1103                                         parameters = cmd+i+1;
1104                                         cmd[i] = '\0';
1105                                         break;
1106                                 }
1107                         }
1108                 }
1109                 else
1110                 {
1111                         for (unsigned int i = 0; i <= strlen(cmd); i++)
1112                         {
1113                                 cmd[i] = toupper(cmd[i]);
1114                         }
1115                 }
1116
1117         }
1118         cmd_found = 0;
1119         
1120         if (strlen(command)>MAXCOMMAND)
1121         {
1122                 WriteServ(user->fd,"421 %s %s :Command too long",user->nick,command);
1123                 return;
1124         }
1125         
1126         for (unsigned int x = 0; x < strlen(command); x++)
1127         {
1128                 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
1129                 {
1130                         if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
1131                         {
1132                                 if (strchr("@!\"$%^&*(){}[]_=+;:'#~,<>/?\\|`",command[x]))
1133                                 {
1134                                         stats->statsUnknown++;
1135                                         WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
1136                                         return;
1137                                 }
1138                         }
1139                 }
1140         }
1141
1142         for (unsigned int i = 0; i != cmdlist.size(); i++)
1143         {
1144                 if (cmdlist[i].command[0])
1145                 {
1146                         if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
1147                         {
1148                                 if (parameters)
1149                                 {
1150                                         if (parameters[0])
1151                                         {
1152                                                 items = process_parameters(command_p,parameters);
1153                                         }
1154                                         else
1155                                         {
1156                                                 items = 0;
1157                                                 command_p[0] = NULL;
1158                                         }
1159                                 }
1160                                 else
1161                                 {
1162                                         items = 0;
1163                                         command_p[0] = NULL;
1164                                 }
1165                                 
1166                                 if (user)
1167                                 {
1168                                         /* activity resets the ping pending timer */
1169                                         user->nping = TIME + user->pingmax;
1170                                         if ((items) < cmdlist[i].min_params)
1171                                         {
1172                                                 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
1173                                                 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
1174                                                 return;
1175                                         }
1176                                         if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
1177                                         {
1178                                                 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
1179                                                 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
1180                                                 cmd_found = 1;
1181                                                 return;
1182                                         }
1183                                         if ((cmdlist[i].flags_needed) && (!user->HasPermission(command)))
1184                                         {
1185                                                 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
1186                                                 WriteServ(user->fd,"481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command);
1187                                                 cmd_found = 1;
1188                                                 return;
1189                                         }
1190                                         /* if the command isnt USER, PASS, or NICK, and nick is empty,
1191                                          * deny command! */
1192                                         if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
1193                                         {
1194                                                 if ((!isnick(user->nick)) || (user->registered != 7))
1195                                                 {
1196                                                         log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
1197                                                         WriteServ(user->fd,"451 %s :You have not registered",command);
1198                                                         return;
1199                                                 }
1200                                         }
1201                                         if ((user->registered == 7) && (!strchr(user->modes,'o')))
1202                                         {
1203                                                 std::stringstream dcmds(Config->DisabledCommands);
1204                                                 while (!dcmds.eof())
1205                                                 {
1206                                                         std::string thiscmd;
1207                                                         dcmds >> thiscmd;
1208                                                         if (!strcasecmp(thiscmd.c_str(),command))
1209                                                         {
1210                                                                 // command is disabled!
1211                                                                 WriteServ(user->fd,"421 %s %s :This command has been disabled.",user->nick,command);
1212                                                                 return;
1213                                                         }
1214                                                 }
1215                                         }
1216                                         if ((user->registered == 7) || (!strncmp(command,"USER",4)) || (!strncmp(command,"NICK",4)) || (!strncmp(command,"PASS",4)))
1217                                         {
1218                                                 if (cmdlist[i].handler_function)
1219                                                 {
1220                                                         
1221                                                         /* ikky /stats counters */
1222                                                         if (temp)
1223                                                         {
1224                                                                 cmdlist[i].use_count++;
1225                                                                 cmdlist[i].total_bytes+=strlen(temp);
1226                                                         }
1227
1228                                                         int MOD_RESULT = 0;
1229                                                         FOREACH_RESULT(OnPreCommand(command,command_p,items,user));
1230                                                         if (MOD_RESULT == 1) {
1231                                                                 return;
1232                                                         }
1233
1234                                                         /* WARNING: nothing may come after the
1235                                                          * command handler call, as the handler
1236                                                          * may free the user structure! */
1237
1238                                                         cmdlist[i].handler_function(command_p,items,user);
1239                                                 }
1240                                                 return;
1241                                         }
1242                                         else
1243                                         {
1244                                                 WriteServ(user->fd,"451 %s :You have not registered",command);
1245                                                 return;
1246                                         }
1247                                 }
1248                                 cmd_found = 1;
1249                         }
1250                 }
1251         }
1252         if ((!cmd_found) && (user))
1253         {
1254                 stats->statsUnknown++;
1255                 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
1256         }
1257 }
1258
1259 bool removecommands(const char* source)
1260 {
1261         bool go_again = true;
1262         while (go_again)
1263         {
1264                 go_again = false;
1265                 for (std::deque<command_t>::iterator i = cmdlist.begin(); i != cmdlist.end(); i++)
1266                 {
1267                         if (!strcmp(i->source,source))
1268                         {
1269                                 log(DEBUG,"removecommands(%s) Removing dependent command: %s",i->source,i->command);
1270                                 cmdlist.erase(i);
1271                                 go_again = true;
1272                                 break;
1273                         }
1274                 }
1275         }
1276         return true;
1277 }
1278
1279
1280 void process_buffer(const char* cmdbuf,userrec *user)
1281 {
1282         if (!user)
1283         {
1284                 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
1285                 return;
1286         }
1287         char cmd[MAXBUF];
1288         if (!cmdbuf)
1289         {
1290                 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
1291                 return;
1292         }
1293         if (!cmdbuf[0])
1294         {
1295                 return;
1296         }
1297         while (*cmdbuf == ' ') cmdbuf++; // strip leading spaces
1298
1299         strlcpy(cmd,cmdbuf,MAXBUF);
1300         if (!cmd[0])
1301         {
1302                 return;
1303         }
1304         int sl = strlen(cmd)-1;
1305         if ((cmd[sl] == 13) || (cmd[sl] == 10))
1306         {
1307                 cmd[sl] = '\0';
1308         }
1309         sl = strlen(cmd)-1;
1310         if ((cmd[sl] == 13) || (cmd[sl] == 10))
1311         {
1312                 cmd[sl] = '\0';
1313         }
1314         sl = strlen(cmd)-1;
1315         while (cmd[sl] == ' ') // strip trailing spaces
1316         {
1317                 cmd[sl] = '\0';
1318                 sl = strlen(cmd)-1;
1319         }
1320
1321         if (!cmd[0])
1322         {
1323                 return;
1324         }
1325         log(DEBUG,"CMDIN: %s %s",user->nick,cmd);
1326         tidystring(cmd);
1327         if ((user) && (cmd))
1328         {
1329                 process_command(user,cmd);
1330         }
1331 }
1332
1333 char MODERR[MAXBUF];
1334
1335 char* ModuleError()
1336 {
1337         return MODERR;
1338 }
1339
1340 void erase_factory(int j)
1341 {
1342         int v = 0;
1343         for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
1344         {
1345                 if (v == j)
1346                 {
1347                         factory.erase(t);
1348                         factory.push_back(NULL);
1349                         return;
1350                 }
1351                 v++;
1352         }
1353 }
1354
1355 void erase_module(int j)
1356 {
1357         int v1 = 0;
1358         for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
1359         {
1360                 if (v1 == j)
1361                 {
1362                         delete *m;
1363                         modules.erase(m);
1364                         modules.push_back(NULL);
1365                         break;
1366                 }
1367                 v1++;
1368         }
1369         int v2 = 0;
1370         for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
1371         {
1372                 if (v2 == j)
1373                 {
1374                        Config->module_names.erase(v);
1375                        break;
1376                 }
1377                 v2++;
1378         }
1379
1380 }
1381
1382 bool UnloadModule(const char* filename)
1383 {
1384         std::string filename_str = filename;
1385         for (unsigned int j = 0; j != Config->module_names.size(); j++)
1386         {
1387                 if (Config->module_names[j] == filename_str)
1388                 {
1389                         if (modules[j]->GetVersion().Flags & VF_STATIC)
1390                         {
1391                                 log(DEFAULT,"Failed to unload STATIC module %s",filename);
1392                                 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
1393                                 return false;
1394                         }
1395                         /* Give the module a chance to tidy out all its metadata */
1396                         for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
1397                         {
1398                                 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
1399                         }
1400                         for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
1401                         {
1402                                 modules[j]->OnCleanup(TYPE_USER,u->second);
1403                         }
1404                         FOREACH_MOD OnUnloadModule(modules[j],Config->module_names[j]);
1405                         // found the module
1406                         log(DEBUG,"Deleting module...");
1407                         erase_module(j);
1408                         log(DEBUG,"Erasing module entry...");
1409                         erase_factory(j);
1410                         log(DEBUG,"Removing dependent commands...");
1411                         removecommands(filename);
1412                         log(DEFAULT,"Module %s unloaded",filename);
1413                         MODCOUNT--;
1414                         return true;
1415                 }
1416         }
1417         log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
1418         snprintf(MODERR,MAXBUF,"Module not loaded");
1419         return false;
1420 }
1421
1422 bool LoadModule(const char* filename)
1423 {
1424         char modfile[MAXBUF];
1425 #ifdef STATIC_LINK
1426         snprintf(modfile,MAXBUF,"%s",filename);
1427 #else
1428         snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
1429 #endif
1430         std::string filename_str = filename;
1431 #ifndef STATIC_LINK
1432         if (!DirValid(modfile))
1433         {
1434                 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
1435                 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
1436                 return false;
1437         }
1438 #endif
1439         log(DEBUG,"Loading module: %s",modfile);
1440 #ifndef STATIC_LINK
1441         if (FileExists(modfile))
1442         {
1443 #endif
1444                 for (unsigned int j = 0; j < Config->module_names.size(); j++)
1445                 {
1446                         if (Config->module_names[j] == filename_str)
1447                         {
1448                                 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
1449                                 snprintf(MODERR,MAXBUF,"Module already loaded");
1450                                 return false;
1451                         }
1452                 }
1453                 ircd_module* a = new ircd_module(modfile);
1454                 factory[MODCOUNT+1] = a;
1455                 if (factory[MODCOUNT+1]->LastError())
1456                 {
1457                         log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
1458                         snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
1459                         MODCOUNT--;
1460                         return false;
1461                 }
1462                 if (factory[MODCOUNT+1]->factory)
1463                 {
1464                         Module* m = factory[MODCOUNT+1]->factory->CreateModule(MyServer);
1465                         modules[MODCOUNT+1] = m;
1466                         /* save the module and the module's classfactory, if
1467                          * this isnt done, random crashes can occur :/ */
1468                         Config->module_names.push_back(filename);
1469                 }
1470                 else
1471                 {
1472                         log(DEFAULT,"Unable to load %s",modfile);
1473                         snprintf(MODERR,MAXBUF,"Factory function failed!");
1474                         return false;
1475                 }
1476 #ifndef STATIC_LINK
1477         }
1478         else
1479         {
1480                 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
1481                 snprintf(MODERR,MAXBUF,"Module file could not be found");
1482                 return false;
1483         }
1484 #endif
1485         MODCOUNT++;
1486         FOREACH_MOD OnLoadModule(modules[MODCOUNT],filename_str);
1487         return true;
1488 }
1489
1490 int BindPorts()
1491 {
1492         char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
1493         int clientportcount = 0;
1494         for (int count = 0; count < Config->ConfValueEnum("bind",&Config->config_f); count++)
1495         {
1496                 Config->ConfValue("bind","port",count,configToken,&Config->config_f);
1497                 Config->ConfValue("bind","address",count,Addr,&Config->config_f);
1498                 Config->ConfValue("bind","type",count,Type,&Config->config_f);
1499                 if (strcmp(Type,"servers"))
1500                 {
1501                         // modules handle server bind types now,
1502                         // its not a typo in the strcmp.
1503                         ports[clientportcount] = atoi(configToken);
1504                         strlcpy(Config->addrs[clientportcount],Addr,256);
1505                         clientportcount++;
1506                         log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
1507                 }
1508         }
1509         portCount = clientportcount;
1510
1511         for (int count = 0; count < portCount; count++)
1512         {
1513                 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
1514                 {
1515                         log(DEBUG,"InspIRCd: startup: bad fd %lu",(unsigned long)openSockfd[boundPortCount]);
1516                         return(ERROR);
1517                 }
1518                 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],Config->addrs[count]) == ERROR)
1519                 {
1520                         log(DEFAULT,"InspIRCd: startup: failed to bind port %lu",(unsigned long)ports[count]);
1521                 }
1522                 else    /* well we at least bound to one socket so we'll continue */
1523                 {
1524                         boundPortCount++;
1525                 }
1526         }
1527
1528         /* if we didn't bind to anything then abort */
1529         if (!boundPortCount)
1530         {
1531                 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
1532                 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)portCount);
1533                 return (ERROR);
1534         }
1535
1536         return boundPortCount;
1537 }
1538
1539 int InspIRCd::Run()
1540 {
1541         bool expire_run = false;
1542         std::vector<int> activefds;
1543         int incomingSockfd;
1544         int in_port;
1545         userrec* cu = NULL;
1546         InspSocket* s = NULL;
1547         InspSocket* s_del = NULL;
1548         char* target;
1549         unsigned int numberactive;
1550         sockaddr_in sock_us;     // our port number
1551         socklen_t uslen;         // length of our port number
1552
1553         /* Beta 7 moved all this stuff out of the main function
1554          * into smaller sub-functions, much tidier -- Brain
1555          */
1556         OpenLog(argv, argc);
1557         Config->ClearStack();
1558         Config->Read(true,NULL);
1559         CheckRoot();
1560         SetupCommandTable();
1561         AddServerName(Config->ServerName);
1562         CheckDie();
1563         boundPortCount = BindPorts();
1564
1565         printf("\n");
1566         startup_time = time(NULL);
1567         
1568         if (!Config->nofork)
1569         {
1570                 if (DaemonSeed() == ERROR)
1571                 {
1572                         printf("ERROR: could not go into daemon mode. Shutting down.\n");
1573                         Exit(ERROR);
1574                 }
1575         }
1576
1577         /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
1578          * initialize the socket engine.
1579          */
1580         SE = new SocketEngine();
1581
1582         /* We must load the modules AFTER initializing the socket engine, now */
1583         LoadAllModules();
1584
1585         printf("\nInspIRCd is now running!\n");
1586         if (!Config->nofork)
1587         {
1588                 freopen("/dev/null","w",stdout);
1589                 freopen("/dev/null","w",stderr);
1590         }
1591
1592         /* Add the listening sockets used for client inbound connections
1593          * to the socket engine
1594          */
1595         for (int count = 0; count < portCount; count++)
1596                 SE->AddFd(openSockfd[count],true,X_LISTEN);
1597
1598         WritePID(Config->PID);
1599
1600         /* main loop, this never returns */
1601         for (;;)
1602         {
1603                 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
1604                  * Once per loop iteration is pleanty.
1605                  */
1606                 OLDTIME = TIME;
1607                 TIME = time(NULL);
1608
1609                 /* Run background module timers every few seconds
1610                  * (the docs say modules shouldnt rely on accurate
1611                  * timing using this event, so we dont have to
1612                  * time this exactly).
1613                  */
1614                 if (((TIME % 8) == 0) && (!expire_run))
1615                 {
1616                         expire_lines();
1617                         FOREACH_MOD OnBackgroundTimer(TIME);
1618                         expire_run = true;
1619                         continue;
1620                 }
1621                 if ((TIME % 8) == 1)
1622                         expire_run = false;
1623                 
1624                 /* Once a second, do the background processing */
1625                 if (TIME != OLDTIME)
1626                         while (DoBackgroundUserStuff(TIME));
1627
1628                 /* Call the socket engine to wait on the active
1629                  * file descriptors. The socket engine has everything's
1630                  * descriptors in its list... dns, modules, users,
1631                  * servers... so its nice and easy, just one call.
1632                  */
1633                 SE->Wait(activefds);
1634
1635                 /**
1636                  * Now process each of the fd's. For users, we have a fast
1637                  * lookup table which can find a user by file descriptor, so
1638                  * processing them by fd isnt expensive. If we have a lot of
1639                  * listening ports or module sockets though, things could get
1640                  * ugly.
1641                  */
1642                 numberactive = activefds.size();
1643                 for (unsigned int activefd = 0; activefd < numberactive; activefd++)
1644                 {
1645                         int socket_type = SE->GetType(activefds[activefd]);
1646                         switch (socket_type)
1647                         {
1648                                 case X_ESTAB_CLIENT:
1649
1650                                         cu = fd_ref_table[activefds[activefd]];
1651                                         if (cu)
1652                                                 ProcessUser(cu);
1653
1654                                 break;
1655
1656                                 case X_ESTAB_MODULE:
1657
1658                                         /* Process module-owned sockets.
1659                                          * Modules are encouraged to inherit their sockets from
1660                                          * InspSocket so we can process them neatly like this.
1661                                          */
1662                                         s = socket_ref[activefds[activefd]];
1663
1664                                         if ((s) && (!s->Poll()))
1665                                         {
1666                                                 log(DEBUG,"Socket poll returned false, close and bail");
1667                                                 SE->DelFd(s->GetFd());
1668                                                 for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
1669                                                 {
1670                                                         s_del = (InspSocket*)*a;
1671                                                         if ((s_del) && (s_del->GetFd() == activefds[activefd]))
1672                                                         {
1673                                                                 module_sockets.erase(a);
1674                                                                 break;
1675                                                         }
1676                                                 }
1677                                                 s->Close();
1678                                                 delete s;
1679                                         }
1680
1681                                 break;
1682
1683                                 case X_ESTAB_DNS:
1684
1685                                         /* When we are using single-threaded dns,
1686                                          * the sockets for dns end up in our mainloop.
1687                                          * When we are using multi-threaded dns,
1688                                          * each thread has its own basic poll() loop
1689                                          * within it, making them 'fire and forget'
1690                                          * and independent of the mainloop.
1691                                          */
1692 #ifndef THREADED_DNS
1693                                         dns_poll(activefds[activefd]);
1694 #endif
1695                                 break;
1696                                 
1697                                 case X_LISTEN:
1698
1699                                         /* It's a listener */
1700                                         uslen = sizeof(sock_us);
1701                                         length = sizeof(client);
1702                                         incomingSockfd = accept (activefds[activefd],(struct sockaddr*)&client,&length);
1703                                         if (!getsockname(incomingSockfd,(sockaddr*)&sock_us,&uslen))
1704                                         {
1705                                                 in_port = ntohs(sock_us.sin_port);
1706                                                 log(DEBUG,"Accepted socket %d",incomingSockfd);
1707                                                 target = (char*)inet_ntoa(client.sin_addr);
1708                                                 /* Years and years ago, we used to resolve here
1709                                                  * using gethostbyaddr(). That is sucky and we
1710                                                  * don't do that any more...
1711                                                  */
1712                                                 if (incomingSockfd >= 0)
1713                                                 {
1714                                                         FOREACH_MOD OnRawSocketAccept(incomingSockfd, target, in_port);
1715                                                         stats->statsAccept++;
1716                                                         AddClient(incomingSockfd, target, in_port, false, target);
1717                                                         log(DEBUG,"Adding client on port %lu fd=%lu",(unsigned long)in_port,(unsigned long)incomingSockfd);
1718                                                 }
1719                                                 else
1720                                                 {
1721                                                         WriteOpers("*** WARNING: accept() failed on port %lu (%s)",(unsigned long)in_port,target);
1722                                                         log(DEBUG,"accept failed: %lu",(unsigned long)in_port);
1723                                                         stats->statsRefused++;
1724                                                 }
1725                                         }
1726                                         else
1727                                         {
1728                                                 log(DEBUG,"Couldnt look up the port number for fd %lu (OS BROKEN?!)",incomingSockfd);
1729                                                 shutdown(incomingSockfd,2);
1730                                                 close(incomingSockfd);
1731                                         }
1732                                 break;
1733
1734                                 default:
1735                                         /* Something went wrong if we're in here.
1736                                          * In fact, so wrong, im not quite sure
1737                                          * what we would do, so for now, its going
1738                                          * to safely do bugger all.
1739                                          */
1740                                 break;
1741                         }
1742                 }
1743
1744         }
1745         /* This is never reached -- we hope! */
1746         return 0;
1747 }
1748
1749 /**********************************************************************************/
1750
1751 /**
1752  * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
1753  */
1754
1755 int main(int argc, char** argv)
1756 {
1757         InspIRCd TittyBiscuits = new InspIRCd(argc, argv);
1758         TittyBiscuits->Run();
1759         delete TittyBiscuits;
1760         return 0;
1761 }
1762