]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
Added customizable pingfreq
[user/henk/code/inspircd.git] / src / inspircd.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  Inspire is copyright (C) 2002-2004 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.h"
22 #include "inspircd_io.h"
23 #include "inspircd_util.h"
24 #include "inspircd_config.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 <cstdio>
31 #include <time.h>
32 #include <string>
33 #ifdef GCC3
34 #include <ext/hash_map>
35 #else
36 #include <hash_map>
37 #endif
38 #include <map>
39 #include <sstream>
40 #include <vector>
41 #include <errno.h>
42 #include <deque>
43 #include <errno.h>
44 #include <unistd.h>
45 #include <sched.h>
46 #include "connection.h"
47 #include "users.h"
48 #include "servers.h"
49 #include "ctables.h"
50 #include "globals.h"
51 #include "modules.h"
52 #include "dynamic.h"
53 #include "wildcard.h"
54 #include "message.h"
55 #include "mode.h"
56 #include "commands.h"
57 #include "xline.h"
58 #include "inspstring.h"
59 #include "dnsqueue.h"
60
61 #ifdef GCC3
62 #define nspace __gnu_cxx
63 #else
64 #define nspace std
65 #endif
66
67 int LogLevel = DEFAULT;
68 char ServerName[MAXBUF];
69 char Network[MAXBUF];
70 char ServerDesc[MAXBUF];
71 char AdminName[MAXBUF];
72 char AdminEmail[MAXBUF];
73 char AdminNick[MAXBUF];
74 char diepass[MAXBUF];
75 char restartpass[MAXBUF];
76 char motd[MAXBUF];
77 char rules[MAXBUF];
78 char list[MAXBUF];
79 char PrefixQuit[MAXBUF];
80 char DieValue[MAXBUF];
81 char DNSServer[MAXBUF];
82 int debugging =  0;
83 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
84 int WHOWAS_MAX = 100;  // default 100 people maximum in the WHOWAS list
85 int DieDelay  =  5;
86 time_t startup_time = time(NULL);
87 int NetBufferSize = 10240; // NetBufferSize used as the buffer size for all read() ops
88 extern int MaxWhoResults;
89 time_t nb_start = 0;
90 int dns_timeout = 5;
91
92 bool AllowHalfop = true;
93 bool AllowProtect = true;
94 bool AllowFounder = true;
95
96 extern std::vector<Module*> modules;
97 std::vector<std::string> module_names;
98 extern std::vector<ircd_module*> factory;
99 std::vector<int> fd_reap;
100
101 extern int MODCOUNT;
102 int openSockfd[MAXSOCKS];
103 bool nofork = false;
104
105 time_t TIME = time(NULL);
106
107 namespace nspace
108 {
109 #ifdef GCC34
110         template<> struct hash<in_addr>
111 #else
112         template<> struct nspace::hash<in_addr>
113 #endif
114         {
115                 size_t operator()(const struct in_addr &a) const
116                 {
117                         size_t q;
118                         memcpy(&q,&a,sizeof(size_t));
119                         return q;
120                 }
121         };
122 #ifdef GCC34
123         template<> struct hash<string>
124 #else
125         template<> struct nspace::hash<string>
126 #endif
127         {
128                 size_t operator()(const string &s) const
129                 {
130                         char a[MAXBUF];
131                         static struct hash<const char *> strhash;
132                         strlcpy(a,s.c_str(),MAXBUF);
133                         strlower(a);
134                         return strhash(a);
135                 }
136         };
137 }
138
139
140 struct StrHashComp
141 {
142
143         bool operator()(const string& s1, const string& s2) const
144         {
145                 char a[MAXBUF],b[MAXBUF];
146                 strlcpy(a,s1.c_str(),MAXBUF);
147                 strlcpy(b,s2.c_str(),MAXBUF);
148                 return (strcasecmp(a,b) == 0);
149         }
150
151 };
152
153 struct InAddr_HashComp
154 {
155
156         bool operator()(const in_addr &s1, const in_addr &s2) const
157         {
158                 size_t q;
159                 size_t p;
160                 
161                 memcpy(&q,&s1,sizeof(size_t));
162                 memcpy(&p,&s2,sizeof(size_t));
163                 
164                 return (q == p);
165         }
166
167 };
168
169
170 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, StrHashComp> user_hash;
171 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, StrHashComp> chan_hash;
172 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, InAddr_HashComp> address_cache;
173 typedef std::deque<command_t> command_table;
174
175 serverrec* me[32];
176
177 FILE *log_file;
178
179 user_hash clientlist;
180 chan_hash chanlist;
181 user_hash whowas;
182 command_table cmdlist;
183 file_cache MOTD;
184 file_cache RULES;
185 address_cache IP;
186
187 ClassVector Classes;
188
189 struct linger linger = { 0 };
190 char MyExecutable[1024];
191 int boundPortCount = 0;
192 int portCount = 0, UDPportCount = 0, ports[MAXSOCKS];
193 int defaultRoute = 0;
194 char ModPath[MAXBUF];
195
196 connection C;
197
198 long MyKey = C.GenKey();
199
200 /* prototypes */
201
202 int has_channel(userrec *u, chanrec *c);
203 int usercount(chanrec *c);
204 int usercount_i(chanrec *c);
205 char* Passwd(userrec *user);
206 bool IsDenied(userrec *user);
207 void AddWhoWas(userrec* u);
208
209 std::vector<long> auth_cookies;
210 std::stringstream config_f(stringstream::in | stringstream::out);
211
212
213
214 long GetRevision()
215 {
216         char Revision[] = "$Revision$";
217         char *s1 = Revision;
218         char *savept;
219         char *v1 = strtok_r(s1," ",&savept);
220         s1 = savept;
221         char *v2 = strtok_r(s1," ",&savept);
222         s1 = savept;
223         return (long)(atof(v2)*10000);
224 }
225
226
227 std::string getservername()
228 {
229         return ServerName;
230 }
231
232 std::string getserverdesc()
233 {
234         return ServerDesc;
235 }
236
237 std::string getnetworkname()
238 {
239         return Network;
240 }
241
242 std::string getadminname()
243 {
244         return AdminName;
245 }
246
247 std::string getadminemail()
248 {
249         return AdminEmail;
250 }
251
252 std::string getadminnick()
253 {
254         return AdminNick;
255 }
256
257 void log(int level,char *text, ...)
258 {
259         char textbuffer[MAXBUF];
260         va_list argsPtr;
261         time_t rawtime;
262         struct tm * timeinfo;
263         if (level < LogLevel)
264                 return;
265
266         time(&rawtime);
267         timeinfo = localtime (&rawtime);
268
269         if (log_file)
270         {
271                 char b[MAXBUF];
272                 va_start (argsPtr, text);
273                 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
274                 va_end(argsPtr);
275                 strlcpy(b,asctime(timeinfo),MAXBUF);
276                 b[strlen(b)-1] = ':';
277                 fprintf(log_file,"%s %s\n",b,textbuffer);
278                 if (nofork)
279                 {
280                         // nofork enabled? display it on terminal too
281                         printf("%s %s\n",b,textbuffer);
282                 }
283         }
284 }
285
286 void readfile(file_cache &F, const char* fname)
287 {
288         FILE* file;
289         char linebuf[MAXBUF];
290         
291         log(DEBUG,"readfile: loading %s",fname);
292         F.clear();
293         file =  fopen(fname,"r");
294         if (file)
295         {
296                 while (!feof(file))
297                 {
298                         fgets(linebuf,sizeof(linebuf),file);
299                         linebuf[strlen(linebuf)-1]='\0';
300                         if (!strcmp(linebuf,""))
301                         {
302                                 strcpy(linebuf,"  ");
303                         }
304                         if (!feof(file))
305                         {
306                                 F.push_back(linebuf);
307                         }
308                 }
309                 fclose(file);
310         }
311         else
312         {
313                 log(DEBUG,"readfile: failed to load file: %s",fname);
314         }
315         log(DEBUG,"readfile: loaded %s, %d lines",fname,F.size());
316 }
317
318 void ReadConfig(bool bail, userrec* user)
319 {
320         char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF],MW[MAXBUF];
321         char AH[MAXBUF],AP[MAXBUF],AF[MAXBUF],DNT[MAXBUF],pfreq[MAXBUF];
322         ConnectClass c;
323         std::stringstream errstr;
324         
325         if (!LoadConf(CONFIG_FILE,&config_f,&errstr))
326         {
327                 errstr.seekg(0);
328                 if (bail)
329                 {
330                         printf("There were errors in your configuration:\n%s",errstr.str().c_str());
331                         Exit(0);
332                 }
333                 else
334                 {
335                         char dataline[1024];
336                         if (user)
337                         {
338                                 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
339                                 while (!errstr.eof())
340                                 {
341                                         errstr.getline(dataline,1024);
342                                         WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
343                                 }
344                         }
345                         else
346                         {
347                                 WriteOpers("There were errors in the configuration file:",user->nick);
348                                 while (!errstr.eof())
349                                 {
350                                         errstr.getline(dataline,1024);
351                                         WriteOpers(dataline);
352                                 }
353                         }
354                         return;
355                 }
356         }
357           
358         ConfValue("server","name",0,ServerName,&config_f);
359         ConfValue("server","description",0,ServerDesc,&config_f);
360         ConfValue("server","network",0,Network,&config_f);
361         ConfValue("admin","name",0,AdminName,&config_f);
362         ConfValue("admin","email",0,AdminEmail,&config_f);
363         ConfValue("admin","nick",0,AdminNick,&config_f);
364         ConfValue("files","motd",0,motd,&config_f);
365         ConfValue("files","rules",0,rules,&config_f);
366         ConfValue("power","diepass",0,diepass,&config_f);
367         ConfValue("power","pause",0,pauseval,&config_f);
368         ConfValue("power","restartpass",0,restartpass,&config_f);
369         ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
370         ConfValue("die","value",0,DieValue,&config_f);
371         ConfValue("options","loglevel",0,dbg,&config_f);
372         ConfValue("options","netbuffersize",0,NB,&config_f);
373         ConfValue("options","maxwho",0,MW,&config_f);
374         ConfValue("options","allowhalfop",0,AH,&config_f);
375         ConfValue("options","allowprotect",0,AP,&config_f);
376         ConfValue("options","allowfounder",0,AF,&config_f);
377         ConfValue("dns","server",0,DNSServer,&config_f);
378         ConfValue("dns","timeout",0,DNT,&config_f);
379         ConfValue("options","moduledir",0,ModPath,&config_f);
380         NetBufferSize = atoi(NB);
381         MaxWhoResults = atoi(MW);
382         dns_timeout = atoi(DNT);
383         if (!dns_timeout)
384                 dns_timeout = 5;
385         if (!strcmp(DNSServer,""))
386                 strlcpy(DNSServer,"127.0.0.1",MAXBUF);
387         if (!strcmp(ModPath,""))
388                 strlcpy(ModPath,MOD_PATH,MAXBUF);
389         AllowHalfop = ((!strcasecmp(AH,"true")) || (!strcasecmp(AH,"1")) || (!strcasecmp(AH,"yes")));
390         AllowProtect = ((!strcasecmp(AP,"true")) || (!strcasecmp(AP,"1")) || (!strcasecmp(AP,"yes")));
391         AllowFounder = ((!strcasecmp(AF,"true")) || (!strcasecmp(AF,"1")) || (!strcasecmp(AF,"yes")));
392         if ((!NetBufferSize) || (NetBufferSize > 65535) || (NetBufferSize < 1024))
393         {
394                 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
395                 NetBufferSize = 10240;
396         }
397         if ((!MaxWhoResults) || (MaxWhoResults > 65535) || (MaxWhoResults < 1))
398         {
399                 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
400                 MaxWhoResults = 128;
401         }
402         if (!strcmp(dbg,"debug"))
403                 LogLevel = DEBUG;
404         if (!strcmp(dbg,"verbose"))
405                 LogLevel = VERBOSE;
406         if (!strcmp(dbg,"default"))
407                 LogLevel = DEFAULT;
408         if (!strcmp(dbg,"sparse"))
409                 LogLevel = SPARSE;
410         if (!strcmp(dbg,"none"))
411                 LogLevel = NONE;
412         readfile(MOTD,motd);
413         log(DEFAULT,"Reading message of the day...");
414         readfile(RULES,rules);
415         log(DEFAULT,"Reading connect classes...");
416         Classes.clear();
417         for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
418         {
419                 strcpy(Value,"");
420                 ConfValue("connect","allow",i,Value,&config_f);
421                 ConfValue("connect","timeout",i,timeout,&config_f);
422                 ConfValue("connect","flood",i,flood,&config_f);
423                 ConfValue("connect","pingfreq",i,pfreq,&config_f);
424                 if (strcmp(Value,""))
425                 {
426                         strlcpy(c.host,Value,MAXBUF);
427                         c.type = CC_ALLOW;
428                         strlcpy(Value,"",MAXBUF);
429                         ConfValue("connect","password",i,Value,&config_f);
430                         strlcpy(c.pass,Value,MAXBUF);
431                         c.registration_timeout = 90; // default is 2 minutes
432                         c.pingtime = 120;
433                         c.flood = atoi(flood);
434                         if (atoi(timeout)>0)
435                         {
436                                 c.registration_timeout = atoi(timeout);
437                         }
438                         if (atoi(pfreq)>0)
439                         {
440                                 c.pingtime = atoi(pfreq);
441                         }
442                         Classes.push_back(c);
443                         log(DEBUG,"Read connect class type ALLOW, host=%s password=%s timeout=%d flood=%d",c.host,c.pass,c.registration_timeout,c.flood);
444                 }
445                 else
446                 {
447                         ConfValue("connect","deny",i,Value,&config_f);
448                         strlcpy(c.host,Value,MAXBUF);
449                         c.type = CC_DENY;
450                         Classes.push_back(c);
451                         log(DEBUG,"Read connect class type DENY, host=%s",c.host);
452                 }
453         
454         }
455         log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
456         read_xline_defaults();
457         log(DEFAULT,"Applying K lines, Q lines and Z lines...");
458         apply_lines();
459         log(DEFAULT,"Done reading configuration file, InspIRCd is now running.");
460         if (!bail)
461         {
462                 log(DEFAULT,"Adding and removing modules due to rehash...");
463
464                 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
465
466                 // store the old module names
467                 for (std::vector<std::string>::iterator t = module_names.begin(); t != module_names.end(); t++)
468                 {
469                         old_module_names.push_back(*t);
470                 }
471
472                 // get the new module names
473                 for (int count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
474                 {
475                         ConfValue("module","name",count2,Value,&config_f);
476                         new_module_names.push_back(Value);
477                 }
478
479                 // now create a list of new modules that are due to be loaded
480                 // and a seperate list of modules which are due to be unloaded
481                 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
482                 {
483                         bool added = true;
484                         for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
485                         {
486                                 if (*old == *_new)
487                                         added = false;
488                         }
489                         if (added)
490                                 added_modules.push_back(*_new);
491                 }
492                 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
493                 {
494                         bool removed = true;
495                         for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
496                         {
497                                 if (*newm == *oldm)
498                                         removed = false;
499                         }
500                         if (removed)
501                                 removed_modules.push_back(*oldm);
502                 }
503                 // now we have added_modules, a vector of modules to be loaded, and removed_modules, a vector of modules
504                 // to be removed.
505                 int rem = 0, add = 0;
506                 if (!removed_modules.empty())
507                 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
508                 {
509                         if (UnloadModule(removing->c_str()))
510                         {
511                                 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
512                                 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
513                                 rem++;
514                         }
515                         else
516                         {
517                                 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ModuleError());
518                         }
519                 }
520                 if (!added_modules.empty())
521                 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
522                 {
523                         if (LoadModule(adding->c_str()))
524                         {
525                                 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
526                                 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
527                                 add++;
528                         }
529                         else
530                         {
531                                 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ModuleError());
532                         }
533                 }
534                 log(DEFAULT,"Successfully unloaded %d of %d modules and loaded %d of %d modules.",rem,removed_modules.size(),add,added_modules.size());
535         }
536 }
537
538 /* write formatted text to a socket, in same format as printf */
539
540 void Write(int sock,char *text, ...)
541 {
542         if (!text)
543         {
544                 log(DEFAULT,"*** BUG *** Write was given an invalid parameter");
545                 return;
546         }
547         char textbuffer[MAXBUF];
548         va_list argsPtr;
549         char tb[MAXBUF];
550         
551         va_start (argsPtr, text);
552         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
553         va_end(argsPtr);
554         snprintf(tb,MAXBUF,"%s\r\n",textbuffer);
555         chop(tb);
556         if (sock != -1)
557         {
558                 write(sock,tb,strlen(tb));
559         }
560 }
561
562 /* write a server formatted numeric response to a single socket */
563
564 void WriteServ(int sock, char* text, ...)
565 {
566         if (!text)
567         {
568                 log(DEFAULT,"*** BUG *** WriteServ was given an invalid parameter");
569                 return;
570         }
571         char textbuffer[MAXBUF],tb[MAXBUF];
572         va_list argsPtr;
573         va_start (argsPtr, text);
574         
575         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
576         va_end(argsPtr);
577         snprintf(tb,MAXBUF,":%s %s\r\n",ServerName,textbuffer);
578         chop(tb);
579         if (sock != -1)
580         {
581                 write(sock,tb,strlen(tb));
582         }
583 }
584
585 /* write text from an originating user to originating user */
586
587 void WriteFrom(int sock, userrec *user,char* text, ...)
588 {
589         if ((!text) || (!user))
590         {
591                 log(DEFAULT,"*** BUG *** WriteFrom was given an invalid parameter");
592                 return;
593         }
594         char textbuffer[MAXBUF],tb[MAXBUF];
595         va_list argsPtr;
596         va_start (argsPtr, text);
597         
598         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
599         va_end(argsPtr);
600         snprintf(tb,MAXBUF,":%s!%s@%s %s\r\n",user->nick,user->ident,user->dhost,textbuffer);
601         chop(tb);
602         if (sock != -1)
603         {
604                 write(sock,tb,strlen(tb));
605         }
606 }
607
608 /* write text to an destination user from a source user (e.g. user privmsg) */
609
610 void WriteTo(userrec *source, userrec *dest,char *data, ...)
611 {
612         if ((!dest) || (!data))
613         {
614                 log(DEFAULT,"*** BUG *** WriteTo was given an invalid parameter");
615                 return;
616         }
617         char textbuffer[MAXBUF],tb[MAXBUF];
618         va_list argsPtr;
619         va_start (argsPtr, data);
620         vsnprintf(textbuffer, MAXBUF, data, argsPtr);
621         va_end(argsPtr);
622         chop(tb);
623
624         // if no source given send it from the server.
625         if (!source)
626         {
627                 WriteServ(dest->fd,":%s %s",ServerName,textbuffer);
628         }
629         else
630         {
631                 WriteFrom(dest->fd,source,"%s",textbuffer);
632         }
633 }
634
635 /* write formatted text from a source user to all users on a channel
636  * including the sender (NOT for privmsg, notice etc!) */
637
638 void WriteChannel(chanrec* Ptr, userrec* user, char* text, ...)
639 {
640         if ((!Ptr) || (!user) || (!text))
641         {
642                 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
643                 return;
644         }
645         char textbuffer[MAXBUF];
646         va_list argsPtr;
647         va_start (argsPtr, text);
648         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
649         va_end(argsPtr);
650         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
651         {
652                 if (has_channel(i->second,Ptr))
653                 {
654                         WriteTo(user,i->second,"%s",textbuffer);
655                 }
656         }
657 }
658
659 /* write formatted text from a source user to all users on a channel
660  * including the sender (NOT for privmsg, notice etc!) doesnt send to
661  * users on remote servers */
662
663 void WriteChannelLocal(chanrec* Ptr, userrec* user, char* text, ...)
664 {
665         if ((!Ptr) || (!text))
666         {
667                 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
668                 return;
669         }
670         char textbuffer[MAXBUF];
671         va_list argsPtr;
672         va_start (argsPtr, text);
673         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
674         va_end(argsPtr);
675         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
676         {
677                 if (has_channel(i->second,Ptr))
678                 {
679                         if (i->second->fd != -1)
680                         {
681                                 if (!user)
682                                 {
683                                         WriteServ(i->second->fd,"%s",textbuffer);
684                                 }
685                                 else
686                                 {
687                                         WriteTo(user,i->second,"%s",textbuffer);
688                                 }
689                         }       
690                 }
691         }
692 }
693
694
695 void WriteChannelWithServ(char* ServerName, chanrec* Ptr, userrec* user, char* text, ...)
696 {
697         if ((!Ptr) || (!user) || (!text))
698         {
699                 log(DEFAULT,"*** BUG *** WriteChannelWithServ was given an invalid parameter");
700                 return;
701         }
702         char textbuffer[MAXBUF];
703         va_list argsPtr;
704         va_start (argsPtr, text);
705         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
706         va_end(argsPtr);
707         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
708         {
709                 if (i->second)
710                 {
711                         if (has_channel(i->second,Ptr))
712                         {
713                                 WriteServ(i->second->fd,"%s",textbuffer);
714                         }
715                 }
716         }
717 }
718
719
720 /* write formatted text from a source user to all users on a channel except
721  * for the sender (for privmsg etc) */
722
723 void ChanExceptSender(chanrec* Ptr, userrec* user, char* text, ...)
724 {
725         if ((!Ptr) || (!user) || (!text))
726         {
727                 log(DEFAULT,"*** BUG *** ChanExceptSender was given an invalid parameter");
728                 return;
729         }
730         char textbuffer[MAXBUF];
731         va_list argsPtr;
732         va_start (argsPtr, text);
733         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
734         va_end(argsPtr);
735
736         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
737         {
738                 if (i->second)
739                 {
740                         if (has_channel(i->second,Ptr) && (user != i->second))
741                         {
742                                 WriteTo(user,i->second,"%s",textbuffer);
743                         }
744                 }
745         }
746 }
747
748
749 std::string GetServerDescription(char* servername)
750 {
751         for (int j = 0; j < 32; j++)
752         {
753                 if (me[j] != NULL)
754                 {
755                         for (int k = 0; k < me[j]->connectors.size(); k++)
756                         {
757                                 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),servername))
758                                 {
759                                         return me[j]->connectors[k].GetDescription();
760                                 }
761                         }
762                 }
763                 return ServerDesc; // not a remote server that can be found, it must be me.
764         }
765 }
766
767
768 /* write a formatted string to all users who share at least one common
769  * channel, including the source user e.g. for use in NICK */
770
771 void WriteCommon(userrec *u, char* text, ...)
772 {
773         if (!u)
774         {
775                 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
776                 return;
777         }
778
779         if (u->registered != 7) {
780                 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
781                 return;
782         }
783         
784         char textbuffer[MAXBUF];
785         va_list argsPtr;
786         va_start (argsPtr, text);
787         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
788         va_end(argsPtr);
789
790         WriteFrom(u->fd,u,"%s",textbuffer);
791
792         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
793         {
794                 if (i->second)
795                 {
796                         if (common_channels(u,i->second) && (i->second != u))
797                         {
798                                 WriteFrom(i->second->fd,u,"%s",textbuffer);
799                         }
800                 }
801         }
802 }
803
804 /* write a formatted string to all users who share at least one common
805  * channel, NOT including the source user e.g. for use in QUIT */
806
807 void WriteCommonExcept(userrec *u, char* text, ...)
808 {
809         if (!u)
810         {
811                 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
812                 return;
813         }
814
815         if (u->registered != 7) {
816                 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
817                 return;
818         }
819
820         char textbuffer[MAXBUF];
821         va_list argsPtr;
822         va_start (argsPtr, text);
823         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
824         va_end(argsPtr);
825
826         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
827         {
828                 if (i->second)
829                 {
830                         if ((common_channels(u,i->second)) && (u != i->second))
831                         {
832                                 WriteFrom(i->second->fd,u,"%s",textbuffer);
833                         }
834                 }
835         }
836 }
837
838 void WriteOpers(char* text, ...)
839 {
840         if (!text)
841         {
842                 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
843                 return;
844         }
845
846         char textbuffer[MAXBUF];
847         va_list argsPtr;
848         va_start (argsPtr, text);
849         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
850         va_end(argsPtr);
851
852         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
853         {
854                 if (i->second)
855                 {
856                         if (strchr(i->second->modes,'o'))
857                         {
858                                 if (strchr(i->second->modes,'s'))
859                                 {
860                                         // send server notices to all with +s
861                                         // (TODO: needs SNOMASKs)
862                                         WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
863                                 }
864                         }
865                 }
866         }
867 }
868
869 // returns TRUE of any users on channel C occupy server 'servername'.
870
871 bool ChanAnyOnThisServer(chanrec *c,char* servername)
872 {
873         log(DEBUG,"ChanAnyOnThisServer");
874         for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
875         {
876                 if (has_channel(i->second,c))
877                 {
878                         if (!strcasecmp(i->second->server,servername))
879                         {
880                                 return true;
881                         }
882                 }
883         }
884         return false;
885 }
886
887 // returns true if user 'u' shares any common channels with any users on server 'servername'
888
889 bool CommonOnThisServer(userrec* u,const char* servername)
890 {
891         log(DEBUG,"ChanAnyOnThisServer");
892         for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
893         {
894                 if ((common_channels(u,i->second)) && (u != i->second))
895                 {
896                         if (!strcasecmp(i->second->server,servername))
897                         {
898                                 log(DEBUG,"%s is common to %s sharing with %s",i->second->nick,servername,u->nick);
899                                 return true;
900                         }
901                 }
902         }
903         return false;
904 }
905
906
907 void NetSendToCommon(userrec* u, char* s)
908 {
909         char buffer[MAXBUF];
910         snprintf(buffer,MAXBUF,"%s",s);
911         
912         log(DEBUG,"NetSendToCommon: '%s' '%s'",u->nick,s);
913
914         for (int j = 0; j < 32; j++)
915         {
916                 if (me[j] != NULL)
917                 {
918                         for (int k = 0; k < me[j]->connectors.size(); k++)
919                         {
920                                 if (CommonOnThisServer(u,me[j]->connectors[k].GetServerName().c_str()))
921                                 {
922                                         me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
923                                 }
924                         }
925                 }
926         }
927 }
928
929
930 void NetSendToAll(char* s)
931 {
932         char buffer[MAXBUF];
933         snprintf(buffer,MAXBUF,"%s",s);
934         
935         log(DEBUG,"NetSendToAll: '%s'",s);
936
937         for (int j = 0; j < 32; j++)
938         {
939                 if (me[j] != NULL)
940                 {
941                         for (int k = 0; k < me[j]->connectors.size(); k++)
942                         {
943                                 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
944                         }
945                 }
946         }
947 }
948
949 void NetSendToAllAlive(char* s)
950 {
951         char buffer[MAXBUF];
952         snprintf(buffer,MAXBUF,"%s",s);
953         
954         log(DEBUG,"NetSendToAllAlive: '%s'",s);
955
956         for (int j = 0; j < 32; j++)
957         {
958                 if (me[j] != NULL)
959                 {
960                         for (int k = 0; k < me[j]->connectors.size(); k++)
961                         {
962                                 if (me[j]->connectors[k].GetState() != STATE_DISCONNECTED)
963                                 {
964                                         me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
965                                 }
966                                 else
967                                 {
968                                         log(DEBUG,"%s is dead, not sending to it.",me[j]->connectors[k].GetServerName().c_str());
969                                 }
970                         }
971                 }
972         }
973 }
974
975
976 void NetSendToOne(char* target,char* s)
977 {
978         char buffer[MAXBUF];
979         snprintf(buffer,MAXBUF,"%s",s);
980         
981         log(DEBUG,"NetSendToOne: '%s' '%s'",target,s);
982
983         for (int j = 0; j < 32; j++)
984         {
985                 if (me[j] != NULL)
986                 {
987                         for (int k = 0; k < me[j]->connectors.size(); k++)
988                         {
989                                 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),target))
990                                 {
991                                         me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
992                                 }
993                         }
994                 }
995         }
996 }
997
998 void NetSendToAllExcept(const char* target,char* s)
999 {
1000         char buffer[MAXBUF];
1001         snprintf(buffer,MAXBUF,"%s",s);
1002         
1003         log(DEBUG,"NetSendToAllExcept: '%s' '%s'",target,s);
1004         
1005         for (int j = 0; j < 32; j++)
1006         {
1007                 if (me[j] != NULL)
1008                 {
1009                         for (int k = 0; k < me[j]->connectors.size(); k++)
1010                         {
1011                                 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),target))
1012                                 {
1013                                         me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
1014                                 }
1015                         }
1016                 }
1017         }
1018 }
1019
1020
1021 void WriteMode(const char* modes, int flags, const char* text, ...)
1022 {
1023         if ((!text) || (!modes) || (!flags))
1024         {
1025                 log(DEFAULT,"*** BUG *** WriteMode was given an invalid parameter");
1026                 return;
1027         }
1028
1029         char textbuffer[MAXBUF];
1030         va_list argsPtr;
1031         va_start (argsPtr, text);
1032         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1033         va_end(argsPtr);
1034
1035         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1036         {
1037                 if (i->second)
1038                 {
1039                         bool send_to_user = false;
1040                         
1041                         if (flags == WM_AND)
1042                         {
1043                                 send_to_user = true;
1044                                 for (int n = 0; n < strlen(modes); n++)
1045                                 {
1046                                         if (!hasumode(i->second,modes[n]))
1047                                         {
1048                                                 send_to_user = false;
1049                                                 break;
1050                                         }
1051                                 }
1052                         }
1053                         else if (flags == WM_OR)
1054                         {
1055                                 send_to_user = false;
1056                                 for (int n = 0; n < strlen(modes); n++)
1057                                 {
1058                                         if (hasumode(i->second,modes[n]))
1059                                         {
1060                                                 send_to_user = true;
1061                                                 break;
1062                                         }
1063                                 }
1064                         }
1065
1066                         if (send_to_user)
1067                         {
1068                                 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
1069                         }
1070                 }
1071         }
1072 }
1073
1074
1075 void WriteWallOps(userrec *source, bool local_only, char* text, ...)  
1076 {  
1077         if ((!text) || (!source))
1078         {
1079                 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
1080                 return;
1081         }
1082
1083         int i = 0;  
1084         char textbuffer[MAXBUF];  
1085         va_list argsPtr;  
1086         va_start (argsPtr, text);  
1087         vsnprintf(textbuffer, MAXBUF, text, argsPtr);  
1088         va_end(argsPtr);  
1089   
1090         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1091         {
1092                 if (i->second)
1093                 {
1094                         if (strchr(i->second->modes,'w'))
1095                         {
1096                                 WriteTo(source,i->second,"WALLOPS :%s",textbuffer);
1097                         }
1098                 }
1099         }
1100
1101         if (!local_only)
1102         {
1103                 char buffer[MAXBUF];
1104                 snprintf(buffer,MAXBUF,"@ %s :%s",source->nick,textbuffer);
1105                 NetSendToAll(buffer);
1106         }
1107 }  
1108
1109 /* convert a string to lowercase. Note following special circumstances
1110  * taken from RFC 1459. Many "official" server branches still hold to this
1111  * rule so i will too;
1112  *
1113  *  Because of IRC's scandanavian origin, the characters {}| are
1114  *  considered to be the lower case equivalents of the characters []\,
1115  *  respectively. This is a critical issue when determining the
1116  *  equivalence of two nicknames.
1117  */
1118
1119 void strlower(char *n)
1120 {
1121         if (!n)
1122         {
1123                 return;
1124         }
1125         for (int i = 0; i != strlen(n); i++)
1126         {
1127                 n[i] = tolower(n[i]);
1128                 if (n[i] == '[')
1129                         n[i] = '{';
1130                 if (n[i] == ']')
1131                         n[i] = '}';
1132                 if (n[i] == '\\')
1133                         n[i] = '|';
1134         }
1135 }
1136
1137
1138
1139 /* Find a user record by nickname and return a pointer to it */
1140
1141 userrec* Find(std::string nick)
1142 {
1143         user_hash::iterator iter = clientlist.find(nick);
1144
1145         if (iter == clientlist.end())
1146                 /* Couldn't find it */
1147                 return NULL;
1148
1149         return iter->second;
1150 }
1151
1152 /* find a channel record by channel name and return a pointer to it */
1153
1154 chanrec* FindChan(const char* chan)
1155 {
1156         if (!chan)
1157         {
1158                 log(DEFAULT,"*** BUG *** Findchan was given an invalid parameter");
1159                 return NULL;
1160         }
1161
1162         chan_hash::iterator iter = chanlist.find(chan);
1163
1164         if (iter == chanlist.end())
1165                 /* Couldn't find it */
1166                 return NULL;
1167
1168         return iter->second;
1169 }
1170
1171
1172 long GetMaxBans(char* name)
1173 {
1174         char CM[MAXBUF];
1175         for (int count = 0; count < ConfValueEnum("banlist",&config_f); count++)
1176         {
1177                 ConfValue("banlist","chan",count,CM,&config_f);
1178                 if (match(name,CM))
1179                 {
1180                         ConfValue("banlist","limit",count,CM,&config_f);
1181                         return atoi(CM);
1182                 }
1183         }
1184         return 64;
1185 }
1186
1187
1188 void purge_empty_chans(void)
1189 {
1190         int go_again = 1, purge = 0;
1191         
1192         while (go_again)
1193         {
1194                 go_again = 0;
1195                 for (chan_hash::iterator i = chanlist.begin(); i != chanlist.end(); i++)
1196                 {
1197                         if (i->second) {
1198                                 if (!usercount(i->second))
1199                                 {
1200                                         /* kill the record */
1201                                         if (i != chanlist.end())
1202                                         {
1203                                                 log(DEBUG,"del_channel: destroyed: %s",i->second->name);
1204                                                 if (i->second) delete i->second;
1205                                                 chanlist.erase(i);
1206                                                 go_again = 1;
1207                                                 purge++;
1208                                                 break;
1209                                         }
1210                                 }
1211                                 else
1212                                 {
1213                                         log(DEBUG,"skipped purge for %s",i->second->name);
1214                                 }
1215                         }
1216                 }
1217         }
1218         log(DEBUG,"completed channel purge, killed %d",purge);
1219 }
1220
1221
1222 char scratch[MAXBUF];
1223 char sparam[MAXBUF];
1224
1225 char* chanmodes(chanrec *chan)
1226 {
1227         if (!chan)
1228         {
1229                 log(DEFAULT,"*** BUG *** chanmodes was given an invalid parameter");
1230                 strcpy(scratch,"");
1231                 return scratch;
1232         }
1233
1234         strcpy(scratch,"");
1235         strcpy(sparam,"");
1236         if (chan->noexternal)
1237         {
1238                 strlcat(scratch,"n",MAXMODES);
1239         }
1240         if (chan->topiclock)
1241         {
1242                 strlcat(scratch,"t",MAXMODES);
1243         }
1244         if (strcmp(chan->key,""))
1245         {
1246                 strlcat(scratch,"k",MAXMODES);
1247         }
1248         if (chan->limit)
1249         {
1250                 strlcat(scratch,"l",MAXMODES);
1251         }
1252         if (chan->inviteonly)
1253         {
1254                 strlcat(scratch,"i",MAXMODES);
1255         }
1256         if (chan->moderated)
1257         {
1258                 strlcat(scratch,"m",MAXMODES);
1259         }
1260         if (chan->secret)
1261         {
1262                 strlcat(scratch,"s",MAXMODES);
1263         }
1264         if (chan->c_private)
1265         {
1266                 strlcat(scratch,"p",MAXMODES);
1267         }
1268         if (strcmp(chan->key,""))
1269         {
1270                 strlcat(sparam," ",MAXBUF);
1271                 strlcat(sparam,chan->key,MAXBUF);
1272         }
1273         if (chan->limit)
1274         {
1275                 char foo[24];
1276                 sprintf(foo," %d",chan->limit);
1277                 strlcat(sparam,foo,MAXBUF);
1278         }
1279         if (strlen(chan->custom_modes))
1280         {
1281                 strlcat(scratch,chan->custom_modes,MAXMODES);
1282                 for (int z = 0; z < strlen(chan->custom_modes); z++)
1283                 {
1284                         std::string extparam = chan->GetModeParameter(chan->custom_modes[z]);
1285                         if (extparam != "")
1286                         {
1287                                 strlcat(sparam," ",MAXBUF);
1288                                 strlcat(sparam,extparam.c_str(),MAXBUF);
1289                         }
1290                 }
1291         }
1292         log(DEBUG,"chanmodes: %s %s%s",chan->name,scratch,sparam);
1293         strlcat(scratch,sparam,MAXMODES);
1294         return scratch;
1295 }
1296
1297
1298 /* compile a userlist of a channel into a string, each nick seperated by
1299  * spaces and op, voice etc status shown as @ and + */
1300
1301 void userlist(userrec *user,chanrec *c)
1302 {
1303         if ((!c) || (!user))
1304         {
1305                 log(DEFAULT,"*** BUG *** userlist was given an invalid parameter");
1306                 return;
1307         }
1308
1309         snprintf(list,MAXBUF,"353 %s = %s :", user->nick, c->name);
1310         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1311         {
1312                 if (has_channel(i->second,c))
1313                 {
1314                         if (isnick(i->second->nick))
1315                         {
1316                                 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1317                                 {
1318                                         /* user is +i, and source not on the channel, does not show
1319                                          * nick in NAMES list */
1320                                         continue;
1321                                 }
1322                                 strlcat(list,cmode(i->second,c),MAXBUF);
1323                                 strlcat(list,i->second->nick,MAXBUF);
1324                                 strlcat(list," ",MAXBUF);
1325                                 if (strlen(list)>(480-NICKMAX))
1326                                 {
1327                                         /* list overflowed into
1328                                          * multiple numerics */
1329                                         WriteServ(user->fd,"%s",list);
1330                                         snprintf(list,MAXBUF,"353 %s = %s :", user->nick, c->name);
1331                                 }
1332                         }
1333                 }
1334         }
1335         /* if whats left in the list isnt empty, send it */     if (list[strlen(list)-1] != ':')
1336         {
1337                 WriteServ(user->fd,"%s",list);
1338         }
1339 }
1340
1341 /* return a count of the users on a specific channel accounting for
1342  * invisible users who won't increase the count. e.g. for /LIST */
1343
1344 int usercount_i(chanrec *c)
1345 {
1346         int i = 0;
1347         int count = 0;
1348         
1349         if (!c)
1350         {
1351                 log(DEFAULT,"*** BUG *** usercount_i was given an invalid parameter");
1352                 return 0;
1353         }
1354
1355         strcpy(list,"");
1356         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1357         {
1358                 if (i->second)
1359                 {
1360                         if (has_channel(i->second,c))
1361                         {
1362                                 if (isnick(i->second->nick))
1363                                 {
1364                                         if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1365                                         {
1366                                                 /* user is +i, and source not on the channel, does not show
1367                                                  * nick in NAMES list */
1368                                                 continue;
1369                                         }
1370                                         count++;
1371                                 }
1372                         }
1373                 }
1374         }
1375         log(DEBUG,"usercount_i: %s %d",c->name,count);
1376         return count;
1377 }
1378
1379
1380 int usercount(chanrec *c)
1381 {
1382         int i = 0;
1383         int count = 0;
1384         
1385         if (!c)
1386         {
1387                 log(DEFAULT,"*** BUG *** usercount was given an invalid parameter");
1388                 return 0;
1389         }
1390
1391         strcpy(list,"");
1392         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1393         {
1394                 if (i->second)
1395                 {
1396                         if (has_channel(i->second,c))
1397                         {
1398                                 if ((isnick(i->second->nick)) && (i->second->registered == 7))
1399                                 {
1400                                         count++;
1401                                 }
1402                         }
1403                 }
1404         }
1405         log(DEBUG,"usercount: %s %d",c->name,count);
1406         return count;
1407 }
1408
1409
1410 /* add a channel to a user, creating the record for it if needed and linking
1411  * it to the user record */
1412
1413 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
1414 {
1415         if ((!user) || (!cn))
1416         {
1417                 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
1418                 return 0;
1419         }
1420
1421         int i = 0;
1422         chanrec* Ptr;
1423         int created = 0;
1424         char cname[MAXBUF];
1425
1426         strncpy(cname,cn,MAXBUF);
1427         
1428         // we MUST declare this wherever we use FOREACH_RESULT
1429         int MOD_RESULT = 0;
1430
1431         if (strlen(cname) > CHANMAX-1)
1432         {
1433                 cname[CHANMAX-1] = '\0';
1434         }
1435
1436         log(DEBUG,"add_channel: %s %s",user->nick,cname);
1437         
1438         if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
1439         {
1440                 return NULL; // already on the channel!
1441         }
1442
1443
1444         if (!FindChan(cname))
1445         {
1446                 int MOD_RESULT = 0;
1447                 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
1448                 if (MOD_RESULT == 1) {
1449                         return NULL;
1450                 }
1451
1452                 /* create a new one */
1453                 log(DEBUG,"add_channel: creating: %s",cname);
1454                 {
1455                         chanlist[cname] = new chanrec();
1456
1457                         strlcpy(chanlist[cname]->name, cname,CHANMAX);
1458                         chanlist[cname]->topiclock = 1;
1459                         chanlist[cname]->noexternal = 1;
1460                         chanlist[cname]->created = TIME;
1461                         strcpy(chanlist[cname]->topic, "");
1462                         strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
1463                         chanlist[cname]->topicset = 0;
1464                         Ptr = chanlist[cname];
1465                         log(DEBUG,"add_channel: created: %s",cname);
1466                         /* set created to 2 to indicate user
1467                          * is the first in the channel
1468                          * and should be given ops */
1469                         created = 2;
1470                 }
1471         }
1472         else
1473         {
1474                 /* channel exists, just fish out a pointer to its struct */
1475                 Ptr = FindChan(cname);
1476                 if (Ptr)
1477                 {
1478                         log(DEBUG,"add_channel: joining to: %s",Ptr->name);
1479                         
1480                         // the override flag allows us to bypass channel modes
1481                         // and bans (used by servers)
1482                         if ((!override) || (!strcasecmp(user->server,ServerName)))
1483                         {
1484                                 log(DEBUG,"Not overriding...");
1485                                 int MOD_RESULT = 0;
1486                                 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
1487                                 if (MOD_RESULT == 1) {
1488                                         return NULL;
1489                                 }
1490                                 log(DEBUG,"MOD_RESULT=%d",MOD_RESULT);
1491                                 
1492                                 if (!MOD_RESULT) 
1493                                 {
1494                                         log(DEBUG,"add_channel: checking key, invite, etc");
1495                                         if (strcmp(Ptr->key,""))
1496                                         {
1497                                                 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
1498                                                 if (!key)
1499                                                 {
1500                                                         log(DEBUG,"add_channel: no key given in JOIN");
1501                                                         WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
1502                                                         return NULL;
1503                                                 }
1504                                                 else
1505                                                 {
1506                                                         log(DEBUG,"key at %p is %s",key,key);
1507                                                         if (strcasecmp(key,Ptr->key))
1508                                                         {
1509                                                                 log(DEBUG,"add_channel: bad key given in JOIN");
1510                                                                 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
1511                                                                 return NULL;
1512                                                         }
1513                                                 }
1514                                         }
1515                                         log(DEBUG,"add_channel: no key");
1516                 
1517                                         if (Ptr->inviteonly)
1518                                         {
1519                                                 log(DEBUG,"add_channel: channel is +i");
1520                                                 if (user->IsInvited(Ptr->name))
1521                                                 {
1522                                                         /* user was invited to channel */
1523                                                         /* there may be an optional channel NOTICE here */
1524                                                 }
1525                                                 else
1526                                                 {
1527                                                         WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
1528                                                         return NULL;
1529                                                 }
1530                                         }
1531                                         log(DEBUG,"add_channel: channel is not +i");
1532                 
1533                                         if (Ptr->limit)
1534                                         {
1535                                                 if (usercount(Ptr) == Ptr->limit)
1536                                                 {
1537                                                         WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
1538                                                         return NULL;
1539                                                 }
1540                                         }
1541                                         
1542                                         log(DEBUG,"add_channel: about to walk banlist");
1543                 
1544                                         /* check user against the channel banlist */
1545                                         if (Ptr)
1546                                         {
1547                                                 if (Ptr->bans.size())
1548                                                 {
1549                                                         for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
1550                                                         {
1551                                                                 if (match(user->GetFullHost(),i->data))
1552                                                                 {
1553                                                                         WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
1554                                                                         return NULL;
1555                                                                 }
1556                                                         }
1557                                                 }
1558                                         }
1559                                         
1560                                         log(DEBUG,"add_channel: bans checked");
1561                                 
1562                                 }
1563                                 
1564
1565                                 if ((Ptr) && (user))
1566                                 {
1567                                         user->RemoveInvite(Ptr->name);
1568                                 }
1569         
1570                                 log(DEBUG,"add_channel: invites removed");
1571
1572                         }
1573                         else
1574                         {
1575                                 log(DEBUG,"Overridden checks");
1576                         }
1577
1578                         
1579                 }
1580                 created = 1;
1581         }
1582
1583         log(DEBUG,"Passed channel checks");
1584         
1585         for (int i =0; i != MAXCHANS; i++)
1586         {
1587                 log(DEBUG,"Check location %d",i);
1588                 if (user->chans[i].channel == NULL)
1589                 {
1590                         log(DEBUG,"Adding into their channel list at location %d",i);
1591
1592                         if (created == 2) 
1593                         {
1594                                 /* first user in is given ops */
1595                                 user->chans[i].uc_modes = UCMODE_OP;
1596                         }
1597                         else
1598                         {
1599                                 user->chans[i].uc_modes = 0;
1600                         }
1601                         user->chans[i].channel = Ptr;
1602                         WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
1603                         
1604                         if (!override) // we're not overriding... so this isnt part of a netburst, broadcast it.
1605                         {
1606                                 // use the stamdard J token with no privilages.
1607                                 char buffer[MAXBUF];
1608                                 if (created == 2)
1609                                 {
1610                                         snprintf(buffer,MAXBUF,"J %s @%s",user->nick,Ptr->name);
1611                                 }
1612                                 else
1613                                 {
1614                                         snprintf(buffer,MAXBUF,"J %s %s",user->nick,Ptr->name);
1615                                 }
1616                                 NetSendToAll(buffer);
1617                         }
1618
1619                         log(DEBUG,"Sent JOIN to client");
1620
1621                         if (Ptr->topicset)
1622                         {
1623                                 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
1624                                 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
1625                         }
1626                         userlist(user,Ptr);
1627                         WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
1628                         WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
1629                         WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
1630                         FOREACH_MOD OnUserJoin(user,Ptr);
1631                         return Ptr;
1632                 }
1633         }
1634         log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
1635         WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
1636         return NULL;
1637 }
1638
1639 /* remove a channel from a users record, and remove the record from memory
1640  * if the channel has become empty */
1641
1642 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
1643 {
1644         if ((!user) || (!cname))
1645         {
1646                 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
1647                 return NULL;
1648         }
1649
1650         chanrec* Ptr;
1651         int created = 0;
1652
1653         if ((!cname) || (!user))
1654         {
1655                 return NULL;
1656         }
1657
1658         Ptr = FindChan(cname);
1659         
1660         if (!Ptr)
1661         {
1662                 return NULL;
1663         }
1664
1665         FOREACH_MOD OnUserPart(user,Ptr);
1666         log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
1667         
1668         for (int i =0; i != MAXCHANS; i++)
1669         {
1670                 /* zap it from the channel list of the user */
1671                 if (user->chans[i].channel == Ptr)
1672                 {
1673                         if (reason)
1674                         {
1675                                 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
1676
1677                                 if (!local)
1678                                 {
1679                                         char buffer[MAXBUF];
1680                                         snprintf(buffer,MAXBUF,"L %s %s :%s",user->nick,Ptr->name,reason);
1681                                         NetSendToAll(buffer);
1682                                 }
1683
1684                                 
1685                         }
1686                         else
1687                         {
1688                                 if (!local)
1689                                 {
1690                                         char buffer[MAXBUF];
1691                                         snprintf(buffer,MAXBUF,"L %s %s :",user->nick,Ptr->name);
1692                                         NetSendToAll(buffer);
1693                                 }
1694                         
1695                                 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
1696                         }
1697                         user->chans[i].uc_modes = 0;
1698                         user->chans[i].channel = NULL;
1699                         log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1700                         break;
1701                 }
1702         }
1703         
1704         /* if there are no users left on the channel */
1705         if (!usercount(Ptr))
1706         {
1707                 chan_hash::iterator iter = chanlist.find(Ptr->name);
1708
1709                 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1710
1711                 /* kill the record */
1712                 if (iter != chanlist.end())
1713                 {
1714                         log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1715                         if (iter->second) delete iter->second;
1716                         chanlist.erase(iter);
1717                 }
1718         }
1719 }
1720
1721
1722 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
1723 {
1724         if ((!src) || (!user) || (!Ptr) || (!reason))
1725         {
1726                 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
1727                 return;
1728         }
1729
1730         int i = 0;
1731         int created = 0;
1732
1733         if ((!Ptr) || (!user) || (!src))
1734         {
1735                 return;
1736         }
1737
1738         log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
1739
1740         if (!has_channel(user,Ptr))
1741         {
1742                 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
1743                 return;
1744         }
1745
1746         int MOD_RESULT = 0;
1747         FOREACH_RESULT(OnAccessCheck(src,user,Ptr,AC_KICK));
1748         
1749         if (MOD_RESULT == ACR_DENY)
1750                 return;
1751
1752         if (MOD_RESULT == ACR_DEFAULT)
1753         {
1754                 if (((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr))) && (!is_uline(src->server)))
1755                 {
1756                         if (cstatus(src,Ptr) == STATUS_HOP)
1757                         {
1758                                 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
1759                         }
1760                         else
1761                         {
1762                                 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
1763                         }
1764                         
1765                         return;
1766                 }
1767         }
1768         
1769         for (int i =0; i != MAXCHANS; i++)
1770         {
1771                 /* zap it from the channel list of the user */
1772                 if (user->chans[i].channel)
1773                 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
1774                 {
1775                         WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
1776                         user->chans[i].uc_modes = 0;
1777                         user->chans[i].channel = NULL;
1778                         log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1779                         break;
1780                 }
1781         }
1782         
1783         /* if there are no users left on the channel */
1784         if (!usercount(Ptr))
1785         {
1786                 chan_hash::iterator iter = chanlist.find(Ptr->name);
1787
1788                 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1789
1790                 /* kill the record */
1791                 if (iter != chanlist.end())
1792                 {
1793                         log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1794                         if (iter->second) delete iter->second;
1795                         chanlist.erase(iter);
1796                 }
1797         }
1798 }
1799
1800
1801
1802
1803 /* This function pokes and hacks at a parameter list like the following:
1804  *
1805  * PART #winbot,#darkgalaxy :m00!
1806  *
1807  * to turn it into a series of individual calls like this:
1808  *
1809  * PART #winbot :m00!
1810  * PART #darkgalaxy :m00!
1811  *
1812  * The seperate calls are sent to a callback function provided by the caller
1813  * (the caller will usually call itself recursively). The callback function
1814  * must be a command handler. Calling this function on a line with no list causes
1815  * no action to be taken. You must provide a starting and ending parameter number
1816  * where the range of the list can be found, useful if you have a terminating
1817  * parameter as above which is actually not part of the list, or parameters
1818  * before the actual list as well. This code is used by many functions which
1819  * can function as "one to list" (see the RFC) */
1820
1821 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
1822 {
1823         char plist[MAXBUF];
1824         char *param;
1825         char *pars[32];
1826         char blog[32][MAXBUF];
1827         char blog2[32][MAXBUF];
1828         int i = 0, j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
1829         char keystr[MAXBUF];
1830         char moo[MAXBUF];
1831
1832         for (int i = 0; i <32; i++)
1833                 strcpy(blog[i],"");
1834
1835         for (int i = 0; i <32; i++)
1836                 strcpy(blog2[i],"");
1837
1838         strcpy(moo,"");
1839         for (int i = 0; i <10; i++)
1840         {
1841                 if (!parameters[i])
1842                 {
1843                         parameters[i] = moo;
1844                 }
1845         }
1846         if (joins)
1847         {
1848                 if (pcnt > 1) /* we have a key to copy */
1849                 {
1850                         strlcpy(keystr,parameters[1],MAXBUF);
1851                 }
1852         }
1853
1854         if (!parameters[start])
1855         {
1856                 return 0;
1857         }
1858         if (!strchr(parameters[start],','))
1859         {
1860                 return 0;
1861         }
1862         strcpy(plist,"");
1863         for (int i = start; i <= end; i++)
1864         {
1865                 if (parameters[i])
1866                 {
1867                         strlcat(plist,parameters[i],MAXBUF);
1868                 }
1869         }
1870         
1871         j = 0;
1872         param = plist;
1873
1874         t = strlen(plist);
1875         for (int i = 0; i < t; i++)
1876         {
1877                 if (plist[i] == ',')
1878                 {
1879                         plist[i] = '\0';
1880                         strlcpy(blog[j++],param,MAXBUF);
1881                         param = plist+i+1;
1882                         if (j>20)
1883                         {
1884                                 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
1885                                 return 1;
1886                         }
1887                 }
1888         }
1889         strlcpy(blog[j++],param,MAXBUF);
1890         total = j;
1891
1892         if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
1893         {
1894                 strcat(keystr,",");
1895         }
1896         
1897         if ((joins) && (keystr))
1898         {
1899                 if (strchr(keystr,','))
1900                 {
1901                         j = 0;
1902                         param = keystr;
1903                         t2 = strlen(keystr);
1904                         for (int i = 0; i < t2; i++)
1905                         {
1906                                 if (keystr[i] == ',')
1907                                 {
1908                                         keystr[i] = '\0';
1909                                         strlcpy(blog2[j++],param,MAXBUF);
1910                                         param = keystr+i+1;
1911                                 }
1912                         }
1913                         strlcpy(blog2[j++],param,MAXBUF);
1914                         total2 = j;
1915                 }
1916         }
1917
1918         for (j = 0; j < total; j++)
1919         {
1920                 if (blog[j])
1921                 {
1922                         pars[0] = blog[j];
1923                 }
1924                 for (q = end; q < pcnt-1; q++)
1925                 {
1926                         if (parameters[q+1])
1927                         {
1928                                 pars[q-end+1] = parameters[q+1];
1929                         }
1930                 }
1931                 if ((joins) && (parameters[1]))
1932                 {
1933                         if (pcnt > 1)
1934                         {
1935                                 pars[1] = blog2[j];
1936                         }
1937                         else
1938                         {
1939                                 pars[1] = NULL;
1940                         }
1941                 }
1942                 /* repeatedly call the function with the hacked parameter list */
1943                 if ((joins) && (pcnt > 1))
1944                 {
1945                         if (pars[1])
1946                         {
1947                                 // pars[1] already set up and containing key from blog2[j]
1948                                 fn(pars,2,u);
1949                         }
1950                         else
1951                         {
1952                                 pars[1] = parameters[1];
1953                                 fn(pars,2,u);
1954                         }
1955                 }
1956                 else
1957                 {
1958                         fn(pars,pcnt-(end-start),u);
1959                 }
1960         }
1961
1962         return 1;
1963 }
1964
1965
1966
1967 void kill_link(userrec *user,const char* r)
1968 {
1969         user_hash::iterator iter = clientlist.find(user->nick);
1970         
1971         char reason[MAXBUF];
1972         
1973         strncpy(reason,r,MAXBUF);
1974
1975         if (strlen(reason)>MAXQUIT)
1976         {
1977                 reason[MAXQUIT-1] = '\0';
1978         }
1979
1980         log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1981         Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1982         log(DEBUG,"closing fd %d",user->fd);
1983
1984         /* bugfix, cant close() a nonblocking socket (sux!) */
1985         if (user->registered == 7) {
1986                 FOREACH_MOD OnUserQuit(user);
1987                 WriteCommonExcept(user,"QUIT :%s",reason);
1988
1989                 // Q token must go to ALL servers!!!
1990                 char buffer[MAXBUF];
1991                 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1992                 NetSendToAll(buffer);
1993         }
1994
1995         /* push the socket on a stack of sockets due to be closed at the next opportunity
1996          * 'Client exited' is an exception to this as it means the client side has already
1997          * closed the socket, we don't need to do it.
1998          */
1999         fd_reap.push_back(user->fd);
2000         
2001         bool do_purge = false;
2002         
2003         if (user->registered == 7) {
2004                 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
2005                 AddWhoWas(user);
2006         }
2007
2008         if (iter != clientlist.end())
2009         {
2010                 log(DEBUG,"deleting user hash value %d",iter->second);
2011                 if ((iter->second) && (user->registered == 7)) {
2012                         if (iter->second) delete iter->second;
2013                 }
2014                 clientlist.erase(iter);
2015         }
2016
2017         if (user->registered == 7) {
2018                 purge_empty_chans();
2019         }
2020         user = NULL;
2021 }
2022
2023 void kill_link_silent(userrec *user,const char* r)
2024 {
2025         user_hash::iterator iter = clientlist.find(user->nick);
2026         
2027         char reason[MAXBUF];
2028         
2029         strncpy(reason,r,MAXBUF);
2030
2031         if (strlen(reason)>MAXQUIT)
2032         {
2033                 reason[MAXQUIT-1] = '\0';
2034         }
2035
2036         log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
2037         Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
2038         log(DEBUG,"closing fd %d",user->fd);
2039
2040         /* bugfix, cant close() a nonblocking socket (sux!) */
2041         if (user->registered == 7) {
2042                 FOREACH_MOD OnUserQuit(user);
2043                 WriteCommonExcept(user,"QUIT :%s",reason);
2044
2045                 // Q token must go to ALL servers!!!
2046                 char buffer[MAXBUF];
2047                 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
2048                 NetSendToAll(buffer);
2049         }
2050
2051         /* push the socket on a stack of sockets due to be closed at the next opportunity
2052          * 'Client exited' is an exception to this as it means the client side has already
2053          * closed the socket, we don't need to do it.
2054          */
2055         fd_reap.push_back(user->fd);
2056         
2057         bool do_purge = false;
2058         
2059         if (iter != clientlist.end())
2060         {
2061                 log(DEBUG,"deleting user hash value %d",iter->second);
2062                 if ((iter->second) && (user->registered == 7)) {
2063                         if (iter->second) delete iter->second;
2064                 }
2065                 clientlist.erase(iter);
2066         }
2067
2068         if (user->registered == 7) {
2069                 purge_empty_chans();
2070         }
2071 }
2072
2073
2074
2075 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
2076
2077 char* Passwd(userrec *user)
2078 {
2079         for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2080         {
2081                 if (match(user->host,i->host) && (i->type == CC_ALLOW))
2082                 {
2083                         return i->pass;
2084                 }
2085         }
2086         return "";
2087 }
2088
2089 bool IsDenied(userrec *user)
2090 {
2091         for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2092         {
2093                 if (match(user->host,i->host) && (i->type == CC_DENY))
2094                 {
2095                         return true;
2096                 }
2097         }
2098         return false;
2099 }
2100
2101
2102
2103
2104 /* sends out an error notice to all connected clients (not to be used
2105  * lightly!) */
2106
2107 void send_error(char *s)
2108 {
2109         log(DEBUG,"send_error: %s",s);
2110         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2111         {
2112                 if (isnick(i->second->nick))
2113                 {
2114                         WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
2115                 }
2116                 else
2117                 {
2118                         // fix - unregistered connections receive ERROR, not NOTICE
2119                         Write(i->second->fd,"ERROR :%s",s);
2120                 }
2121         }
2122 }
2123
2124 void Error(int status)
2125 {
2126         signal (SIGALRM, SIG_IGN);
2127         signal (SIGPIPE, SIG_IGN);
2128         signal (SIGTERM, SIG_IGN);
2129         signal (SIGABRT, SIG_IGN);
2130         signal (SIGSEGV, SIG_IGN);
2131         signal (SIGURG, SIG_IGN);
2132         signal (SIGKILL, SIG_IGN);
2133         log(DEFAULT,"*** fell down a pothole in the road to perfection ***");
2134         send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
2135         Exit(status);
2136 }
2137
2138
2139 int main(int argc, char **argv)
2140 {
2141         Start();
2142         srand(time(NULL));
2143         log(DEBUG,"*** InspIRCd starting up!");
2144         if (!FileExists(CONFIG_FILE))
2145         {
2146                 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
2147                 log(DEFAULT,"main: no config");
2148                 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
2149                 Exit(ERROR);
2150         }
2151         if (argc > 1) {
2152                 for (int i = 1; i < argc; i++)
2153                 {
2154                         if (!strcmp(argv[i],"-nofork")) {
2155                                 nofork = true;
2156                         }
2157                         if (!strcmp(argv[i],"-wait")) {
2158                                 sleep(6);
2159                         }
2160                 }
2161         }
2162         strlcpy(MyExecutable,argv[0],MAXBUF);
2163         
2164         if (InspIRCd() == ERROR)
2165         {
2166                 log(DEFAULT,"main: daemon function bailed");
2167                 printf("ERROR: could not initialise. Shutting down.\n");
2168                 Exit(ERROR);
2169         }
2170         Exit(TRUE);
2171         return 0;
2172 }
2173
2174 template<typename T> inline string ConvToStr(const T &in)
2175 {
2176         stringstream tmp;
2177         if (!(tmp << in)) return string();
2178         return tmp.str();
2179 }
2180
2181 /* re-allocates a nick in the user_hash after they change nicknames,
2182  * returns a pointer to the new user as it may have moved */
2183
2184 userrec* ReHashNick(char* Old, char* New)
2185 {
2186         user_hash::iterator newnick;
2187         user_hash::iterator oldnick = clientlist.find(Old);
2188
2189         log(DEBUG,"ReHashNick: %s %s",Old,New);
2190         
2191         if (!strcasecmp(Old,New))
2192         {
2193                 log(DEBUG,"old nick is new nick, skipping");
2194                 return oldnick->second;
2195         }
2196         
2197         if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
2198
2199         log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
2200
2201         clientlist[New] = new userrec();
2202         clientlist[New] = oldnick->second;
2203         clientlist.erase(oldnick);
2204
2205         log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
2206         
2207         return clientlist[New];
2208 }
2209
2210 /* adds or updates an entry in the whowas list */
2211 void AddWhoWas(userrec* u)
2212 {
2213         user_hash::iterator iter = whowas.find(u->nick);
2214         userrec *a = new userrec();
2215         strlcpy(a->nick,u->nick,NICKMAX);
2216         strlcpy(a->ident,u->ident,64);
2217         strlcpy(a->dhost,u->dhost,256);
2218         strlcpy(a->host,u->host,256);
2219         strlcpy(a->fullname,u->fullname,128);
2220         strlcpy(a->server,u->server,256);
2221         a->signon = u->signon;
2222
2223         /* MAX_WHOWAS:   max number of /WHOWAS items
2224          * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
2225          *               can be replaced by a newer one
2226          */
2227         
2228         if (iter == whowas.end())
2229         {
2230                 if (whowas.size() == WHOWAS_MAX)
2231                 {
2232                         for (user_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
2233                         {
2234                                 // 3600 seconds in an hour ;)
2235                                 if ((i->second->signon)<(TIME-(WHOWAS_STALE*3600)))
2236                                 {
2237                                         if (i->second) delete i->second;
2238                                         i->second = a;
2239                                         log(DEBUG,"added WHOWAS entry, purged an old record");
2240                                         return;
2241                                 }
2242                         }
2243                 }
2244                 else
2245                 {
2246                         log(DEBUG,"added fresh WHOWAS entry");
2247                         whowas[a->nick] = a;
2248                 }
2249         }
2250         else
2251         {
2252                 log(DEBUG,"updated WHOWAS entry");
2253                 if (iter->second) delete iter->second;
2254                 iter->second = a;
2255         }
2256 }
2257
2258
2259 /* add a client connection to the sockets list */
2260 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
2261 {
2262         int i;
2263         int blocking = 1;
2264         char resolved[MAXBUF];
2265         string tempnick;
2266         char tn2[MAXBUF];
2267         user_hash::iterator iter;
2268
2269         tempnick = ConvToStr(socket) + "-unknown";
2270         sprintf(tn2,"%d-unknown",socket);
2271
2272         iter = clientlist.find(tempnick);
2273
2274         if (iter != clientlist.end()) return;
2275
2276         /*
2277          * It is OK to access the value here this way since we know
2278          * it exists, we just created it above.
2279          *
2280          * At NO other time should you access a value in a map or a
2281          * hash_map this way.
2282          */
2283         clientlist[tempnick] = new userrec();
2284
2285         NonBlocking(socket);
2286         log(DEBUG,"AddClient: %d %s %d %s",socket,host,port,ip);
2287
2288         clientlist[tempnick]->fd = socket;
2289         strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
2290         strncpy(clientlist[tempnick]->host, host,160);
2291         strncpy(clientlist[tempnick]->dhost, host,160);
2292         strncpy(clientlist[tempnick]->server, ServerName,256);
2293         strncpy(clientlist[tempnick]->ident, "unknown",9);
2294         clientlist[tempnick]->registered = 0;
2295         clientlist[tempnick]->signon = TIME+dns_timeout;
2296         clientlist[tempnick]->lastping = 1;
2297         clientlist[tempnick]->port = port;
2298         strncpy(clientlist[tempnick]->ip,ip,32);
2299
2300         // set the registration timeout for this user
2301         unsigned long class_regtimeout = 90;
2302         int class_flood = 0;
2303
2304         for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2305         {
2306                 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
2307                 {
2308                         class_regtimeout = (unsigned long)i->registration_timeout;
2309                         class_flood = i->flood;
2310                         clientlist[tempnick]->pingmax = i->pingtime;
2311                         break;
2312                 }
2313         }
2314
2315         clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax+dns_timeout;
2316         clientlist[tempnick]->timeout = TIME+class_regtimeout;
2317         clientlist[tempnick]->flood = class_flood;
2318
2319         for (int i = 0; i < MAXCHANS; i++)
2320         {
2321                 clientlist[tempnick]->chans[i].channel = NULL;
2322                 clientlist[tempnick]->chans[i].uc_modes = 0;
2323         }
2324
2325         if (clientlist.size() == MAXCLIENTS)
2326                 kill_link(clientlist[tempnick],"No more connections allowed in this class");
2327                 
2328
2329         char* e = matches_exception(ip);
2330         if (!e)
2331         {
2332                 char* r = matches_zline(ip);
2333                 if (r)
2334                 {
2335                         char reason[MAXBUF];
2336                         snprintf(reason,MAXBUF,"Z-Lined: %s",r);
2337                         kill_link(clientlist[tempnick],reason);
2338                 }
2339         }
2340 }
2341
2342 // this function counts all users connected, wether they are registered or NOT.
2343 int usercnt(void)
2344 {
2345         return clientlist.size();
2346 }
2347
2348 // this counts only registered users, so that the percentages in /MAP don't mess up when users are sitting in an unregistered state
2349 int registered_usercount(void)
2350 {
2351         int c = 0;
2352         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2353         {
2354                 if ((i->second->fd) && (isnick(i->second->nick))) c++;
2355         }
2356         return c;
2357 }
2358
2359 int usercount_invisible(void)
2360 {
2361         int c = 0;
2362
2363         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2364         {
2365                 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
2366         }
2367         return c;
2368 }
2369
2370 int usercount_opers(void)
2371 {
2372         int c = 0;
2373
2374         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2375         {
2376                 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
2377         }
2378         return c;
2379 }
2380
2381 int usercount_unknown(void)
2382 {
2383         int c = 0;
2384
2385         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2386         {
2387                 if ((i->second->fd) && (i->second->registered != 7))
2388                         c++;
2389         }
2390         return c;
2391 }
2392
2393 long chancount(void)
2394 {
2395         return chanlist.size();
2396 }
2397
2398 long count_servs(void)
2399 {
2400         int c = 0;
2401         //for (int j = 0; j < 255; j++)
2402         //{
2403         //      if (servers[j] != NULL)
2404         //              c++;
2405         //}
2406         return c;
2407 }
2408
2409 long servercount(void)
2410 {
2411         return count_servs()+1;
2412 }
2413
2414 long local_count()
2415 {
2416         int c = 0;
2417         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2418         {
2419                 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,ServerName))) c++;
2420         }
2421         return c;
2422 }
2423
2424
2425 void ShowMOTD(userrec *user)
2426 {
2427         std::string WholeMOTD = "";
2428         if (!MOTD.size())
2429         {
2430                 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
2431                 return;
2432         }
2433         WholeMOTD = std::string(":") + std::string(ServerName) + std::string(" 375 ") + std::string(user->nick) + std::string(" :- ") + std::string(ServerName) + " message of the day\r\n";
2434         for (int i = 0; i != MOTD.size(); i++)
2435         {
2436                 WholeMOTD = WholeMOTD + std::string(":") + std::string(ServerName) + std::string(" 372 ") + std::string(user->nick) + std::string(" :- ") + MOTD[i] + std::string("\r\n");
2437         }
2438         WholeMOTD = WholeMOTD + std::string(":") + std::string(ServerName) + std::string(" 376 ") + std::string(user->nick) + std::string(" :End of message of the day.\r\n");
2439         // only one write operation
2440         send(user->fd,WholeMOTD.c_str(),WholeMOTD.length(),0);
2441
2442 }
2443
2444 void ShowRULES(userrec *user)
2445 {
2446         if (!RULES.size())
2447         {
2448                 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
2449                 return;
2450         }
2451         WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
2452         for (int i = 0; i != RULES.size(); i++)
2453         {
2454                                 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
2455         }
2456         WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
2457 }
2458
2459 /* shows the message of the day, and any other on-logon stuff */
2460 void FullConnectUser(userrec* user)
2461 {
2462         user->registered = 7;
2463         user->idle_lastmsg = TIME;
2464         log(DEBUG,"ConnectUser: %s",user->nick);
2465
2466         if (strcmp(Passwd(user),"") && (!user->haspassed))
2467         {
2468                 kill_link(user,"Invalid password");
2469                 return;
2470         }
2471         if (IsDenied(user))
2472         {
2473                 kill_link(user,"Unauthorised connection");
2474                 return;
2475         }
2476
2477         char match_against[MAXBUF];
2478         snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
2479         char* e = matches_exception(match_against);
2480         if (!e)
2481         {
2482                 char* r = matches_gline(match_against);
2483                 if (r)
2484                 {
2485                         char reason[MAXBUF];
2486                         snprintf(reason,MAXBUF,"G-Lined: %s",r);
2487                         kill_link_silent(user,reason);
2488                         return;
2489                 }
2490                 r = matches_kline(user->host);
2491                 if (r)
2492                 {
2493                         char reason[MAXBUF];
2494                         snprintf(reason,MAXBUF,"K-Lined: %s",r);
2495                         kill_link_silent(user,reason);
2496                         return;
2497                 }
2498         }
2499
2500         WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
2501         WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
2502         WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
2503         WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
2504         WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
2505         // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
2506         std::stringstream v;
2507         v << "MESHED WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
2508         v << " MAXBANS=60 NICKLEN=" << NICKMAX;
2509         v << " TOPICLEN=307 KICKLEN=307 MAXTARGETS=20 AWAYLEN=307 CHANMODES=ohvb,k,l,psmnti NETWORK=";
2510         v << std::string(Network);
2511         std::string data005 = v.str();
2512         FOREACH_MOD On005Numeric(data005);
2513         // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
2514         // so i'd better split it :)
2515         std::stringstream out(data005);
2516         std::string token = "";
2517         std::string line5 = "";
2518         int token_counter = 0;
2519         while (!out.eof())
2520         {
2521                 out >> token;
2522                 line5 = line5 + token + " ";
2523                 token_counter++;
2524                 if ((token_counter >= 13) || (out.eof() == true))
2525                 {
2526                         WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
2527                         line5 = "";
2528                         token_counter = 0;
2529                 }
2530         }
2531         ShowMOTD(user);
2532         FOREACH_MOD OnUserConnect(user);
2533         WriteOpers("*** Client connecting on port %d: %s!%s@%s [%s]",user->port,user->nick,user->ident,user->host,user->ip);
2534
2535         char buffer[MAXBUF];
2536         snprintf(buffer,MAXBUF,"N %d %s %s %s %s +%s %s %s :%s",user->age,user->nick,user->host,user->dhost,user->ident,user->modes,user->ip,ServerName,user->fullname);
2537         NetSendToAll(buffer);
2538 }
2539
2540 /* shows the message of the day, and any other on-logon stuff */
2541 void ConnectUser(userrec *user)
2542 {
2543         // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
2544         if ((user->dns_done) && (user->registered >= 3))
2545         {
2546                 FullConnectUser(user);
2547         }
2548 }
2549
2550 void handle_version(char **parameters, int pcnt, userrec *user)
2551 {
2552         char Revision[] = "$Revision$";
2553
2554         char *s1 = Revision;
2555         char *savept;
2556         char *v1 = strtok_r(s1," ",&savept);
2557         s1 = savept;
2558         char *v2 = strtok_r(s1," ",&savept);
2559         s1 = savept;
2560         
2561         WriteServ(user->fd,"351 %s :%s Rev. %s %s :%s (O=%d)",user->nick,VERSION,v2,ServerName,SYSTEM,OPTIMISATION);
2562 }
2563
2564
2565 // calls a handler function for a command
2566
2567 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
2568 {
2569                 for (int i = 0; i < cmdlist.size(); i++)
2570                 {
2571                         if (!strcasecmp(cmdlist[i].command,commandname))
2572                         {
2573                                 if (cmdlist[i].handler_function)
2574                                 {
2575                                         if (pcnt>=cmdlist[i].min_params)
2576                                         {
2577                                                 if (strchr(user->modes,cmdlist[i].flags_needed))
2578                                                 {
2579                                                         cmdlist[i].handler_function(parameters,pcnt,user);
2580                                                 }
2581                                         }
2582                                 }
2583                         }
2584                 }
2585 }
2586
2587 void DoSplitEveryone()
2588 {
2589         bool go_again = true;
2590         while (go_again)
2591         {
2592                 go_again = false;
2593                 for (int i = 0; i < 32; i++)
2594                 {
2595                         if (me[i] != NULL)
2596                         {
2597                                 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2598                                 {
2599                                         if (strcasecmp(j->GetServerName().c_str(),ServerName))
2600                                         {
2601                                                 j->routes.clear();
2602                                                 j->CloseConnection();
2603                                                 me[i]->connectors.erase(j);
2604                                                 go_again = true;
2605                                                 break;
2606                                         }
2607                                 }
2608                         }
2609                 }
2610         }
2611         log(DEBUG,"Removed server. Will remove clients...");
2612         // iterate through the userlist and remove all users on this server.
2613         // because we're dealing with a mesh, we dont have to deal with anything
2614         // "down-route" from this server (nice huh)
2615         go_again = true;
2616         char reason[MAXBUF];
2617         while (go_again)
2618         {
2619                 go_again = false;
2620                 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
2621                 {
2622                         if (strcasecmp(u->second->server,ServerName))
2623                         {
2624                                 snprintf(reason,MAXBUF,"%s %s",ServerName,u->second->server);
2625                                 kill_link(u->second,reason);
2626                                 go_again = true;
2627                                 break;
2628                         }
2629                 }
2630         }
2631 }
2632
2633
2634
2635 char islast(const char* s)
2636 {
2637         char c = '`';
2638         for (int j = 0; j < 32; j++)
2639         {
2640                 if (me[j] != NULL)
2641                 {
2642                         for (int k = 0; k < me[j]->connectors.size(); k++)
2643                         {
2644                                 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2645                                 {
2646                                         c = '|';
2647                                 }
2648                                 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
2649                                 {
2650                                         c = '`';
2651                                 }
2652                         }
2653                 }
2654         }
2655         return c;
2656 }
2657
2658 long map_count(const char* s)
2659 {
2660         int c = 0;
2661         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2662         {
2663                 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,s))) c++;
2664         }
2665         return c;
2666 }
2667
2668
2669 void force_nickchange(userrec* user,const char* newnick)
2670 {
2671         char nick[MAXBUF];
2672         int MOD_RESULT = 0;
2673         
2674         strcpy(nick,"");
2675
2676         FOREACH_RESULT(OnUserPreNick(user,newnick));
2677         if (MOD_RESULT) {
2678                 kill_link(user,"Nickname collision");
2679                 return;
2680         }
2681         if (matches_qline(newnick))
2682         {
2683                 kill_link(user,"Nickname collision");
2684                 return;
2685         }
2686         
2687         if (user)
2688         {
2689                 if (newnick)
2690                 {
2691                         strncpy(nick,newnick,MAXBUF);
2692                 }
2693                 if (user->registered == 7)
2694                 {
2695                         char* pars[1];
2696                         pars[0] = nick;
2697                         handle_nick(pars,1,user);
2698                 }
2699         }
2700 }
2701                                 
2702
2703 int process_parameters(char **command_p,char *parameters)
2704 {
2705         int i = 0;
2706         int j = 0;
2707         int q = 0;
2708         q = strlen(parameters);
2709         if (!q)
2710         {
2711                 /* no parameters, command_p invalid! */
2712                 return 0;
2713         }
2714         if (parameters[0] == ':')
2715         {
2716                 command_p[0] = parameters+1;
2717                 return 1;
2718         }
2719         if (q)
2720         {
2721                 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
2722                 {
2723                         /* only one parameter */
2724                         command_p[0] = parameters;
2725                         if (parameters[0] == ':')
2726                         {
2727                                 if (strchr(parameters,' ') != NULL)
2728                                 {
2729                                         command_p[0]++;
2730                                 }
2731                         }
2732                         return 1;
2733                 }
2734         }
2735         command_p[j++] = parameters;
2736         for (int i = 0; i <= q; i++)
2737         {
2738                 if (parameters[i] == ' ')
2739                 {
2740                         command_p[j++] = parameters+i+1;
2741                         parameters[i] = '\0';
2742                         if (command_p[j-1][0] == ':')
2743                         {
2744                                 *command_p[j-1]++; /* remove dodgy ":" */
2745                                 break;
2746                                 /* parameter like this marks end of the sequence */
2747                         }
2748                 }
2749         }
2750         return j; /* returns total number of items in the list */
2751 }
2752
2753 void process_command(userrec *user, char* cmd)
2754 {
2755         char *parameters;
2756         char *command;
2757         char *command_p[127];
2758         char p[MAXBUF], temp[MAXBUF];
2759         int i, j, items, cmd_found;
2760
2761         for (int i = 0; i < 127; i++)
2762                 command_p[i] = NULL;
2763
2764         if (!user)
2765         {
2766                 return;
2767         }
2768         if (!cmd)
2769         {
2770                 return;
2771         }
2772         if (!strcmp(cmd,""))
2773         {
2774                 return;
2775         }
2776         
2777         int total_params = 0;
2778         if (strlen(cmd)>2)
2779         {
2780                 for (int q = 0; q < strlen(cmd)-1; q++)
2781                 {
2782                         if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
2783                         {
2784                                 total_params++;
2785                                 // found a 'trailing', we dont count them after this.
2786                                 break;
2787                         }
2788                         if (cmd[q] == ' ')
2789                                 total_params++;
2790                 }
2791         }
2792         
2793         // another phidjit bug...
2794         if (total_params > 126)
2795         {
2796                 //kill_link(user,"Protocol violation (1)");
2797                 WriteServ(user->fd,"421 %s * :Unknown command",user->nick);
2798                 return;
2799         }
2800         
2801         strlcpy(temp,cmd,MAXBUF);
2802
2803         std::string tmp = cmd;
2804         for (int i = 0; i <= MODCOUNT; i++)
2805         {
2806                 std::string oldtmp = tmp;
2807                 modules[i]->OnServerRaw(tmp,true,user);
2808                 if (oldtmp != tmp)
2809                 {
2810                         log(DEBUG,"A Module changed the input string!");
2811                         log(DEBUG,"New string: %s",tmp.c_str());
2812                         log(DEBUG,"Old string: %s",oldtmp.c_str());
2813                         break;
2814                 }
2815         }
2816         strlcpy(cmd,tmp.c_str(),MAXBUF);
2817         strlcpy(temp,cmd,MAXBUF);
2818
2819         if (!strchr(cmd,' '))
2820         {
2821                 /* no parameters, lets skip the formalities and not chop up
2822                  * the string */
2823                 log(DEBUG,"About to preprocess command with no params");
2824                 items = 0;
2825                 command_p[0] = NULL;
2826                 parameters = NULL;
2827                 for (int i = 0; i <= strlen(cmd); i++)
2828                 {
2829                         cmd[i] = toupper(cmd[i]);
2830                 }
2831                 log(DEBUG,"Preprocess done length=%d",strlen(cmd));
2832                 command = cmd;
2833         }
2834         else
2835         {
2836                 strcpy(cmd,"");
2837                 j = 0;
2838                 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
2839                 for (int i = 0; i < strlen(temp); i++)
2840                 {
2841                         if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
2842                         {
2843                                 cmd[j++] = temp[i];
2844                                 cmd[j] = 0;
2845                         }
2846                 }
2847                 /* split the full string into a command plus parameters */
2848                 parameters = p;
2849                 strcpy(p," ");
2850                 command = cmd;
2851                 if (strchr(cmd,' '))
2852                 {
2853                         for (int i = 0; i <= strlen(cmd); i++)
2854                         {
2855                                 /* capitalise the command ONLY, leave params intact */
2856                                 cmd[i] = toupper(cmd[i]);
2857                                 /* are we nearly there yet?! :P */
2858                                 if (cmd[i] == ' ')
2859                                 {
2860                                         command = cmd;
2861                                         parameters = cmd+i+1;
2862                                         cmd[i] = '\0';
2863                                         break;
2864                                 }
2865                         }
2866                 }
2867                 else
2868                 {
2869                         for (int i = 0; i <= strlen(cmd); i++)
2870                         {
2871                                 cmd[i] = toupper(cmd[i]);
2872                         }
2873                 }
2874
2875         }
2876         cmd_found = 0;
2877         
2878         if (strlen(command)>MAXCOMMAND)
2879         {
2880                 //kill_link(user,"Protocol violation (2)");
2881                 WriteServ(user->fd,"421 %s * :Unknown command",user->nick);
2882                 return;
2883         }
2884         
2885         for (int x = 0; x < strlen(command); x++)
2886         {
2887                 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
2888                 {
2889                         if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
2890                         {
2891                                 if (strchr("@!\"$%^&*(){}[]_=+;:'#~,<>/?\\|`",command[x]))
2892                                 {
2893                                         //kill_link(user,"Protocol violation (3)");
2894                                         WriteServ(user->fd,"421 %s * :Unknown command",user->nick);
2895                                         return;
2896                                 }
2897                         }
2898                 }
2899         }
2900
2901         for (int i = 0; i != cmdlist.size(); i++)
2902         {
2903                 if (strcmp(cmdlist[i].command,""))
2904                 {
2905                         if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
2906                         {
2907                                 log(DEBUG,"Found matching command");
2908
2909                                 if (parameters)
2910                                 {
2911                                         if (strcmp(parameters,""))
2912                                         {
2913                                                 items = process_parameters(command_p,parameters);
2914                                         }
2915                                         else
2916                                         {
2917                                                 items = 0;
2918                                                 command_p[0] = NULL;
2919                                         }
2920                                 }
2921                                 else
2922                                 {
2923                                         items = 0;
2924                                         command_p[0] = NULL;
2925                                 }
2926                                 
2927                                 if (user)
2928                                 {
2929                                         log(DEBUG,"Processing command");
2930                                         
2931                                         /* activity resets the ping pending timer */
2932                                         user->nping = TIME + user->pingmax;
2933                                         if ((items) < cmdlist[i].min_params)
2934                                         {
2935                                                 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
2936                                                 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
2937                                                 return;
2938                                         }
2939                                         if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
2940                                         {
2941                                                 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2942                                                 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
2943                                                 cmd_found = 1;
2944                                                 return;
2945                                         }
2946                                         if ((cmdlist[i].flags_needed) && (!user->HasPermission(command)))
2947                                         {
2948                                                 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2949                                                 WriteServ(user->fd,"481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command);
2950                                                 cmd_found = 1;
2951                                                 return;
2952                                         }
2953                                         /* if the command isnt USER, PASS, or NICK, and nick is empty,
2954                                          * deny command! */
2955                                         if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
2956                                         {
2957                                                 if ((!isnick(user->nick)) || (user->registered != 7))
2958                                                 {
2959                                                         log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2960                                                         WriteServ(user->fd,"451 %s :You have not registered",command);
2961                                                         return;
2962                                                 }
2963                                         }
2964                                         if ((user->registered == 7) || (!strcmp(command,"USER")) || (!strcmp(command,"NICK")) || (!strcmp(command,"PASS")))
2965                                         {
2966                                                 log(DEBUG,"process_command: handler: %s %s %d",user->nick,command,items);
2967                                                 if (cmdlist[i].handler_function)
2968                                                 {
2969                                                         /* ikky /stats counters */
2970                                                         if (temp)
2971                                                         {
2972                                                                 if (user)
2973                                                                 {
2974                                                                         user->bytes_in += strlen(temp);
2975                                                                         user->cmds_in++;
2976                                                                         user->bytes_out+=strlen(temp);
2977                                                                         user->cmds_out++;
2978                                                                 }
2979                                                                 cmdlist[i].use_count++;
2980                                                                 cmdlist[i].total_bytes+=strlen(temp);
2981                                                         }
2982
2983                                                         /* WARNING: nothing may come after the
2984                                                          * command handler call, as the handler
2985                                                          * may free the user structure! */
2986
2987                                                         cmdlist[i].handler_function(command_p,items,user);
2988                                                 }
2989                                                 return;
2990                                         }
2991                                         else
2992                                         {
2993                                                 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2994                                                 WriteServ(user->fd,"451 %s :You have not registered",command);
2995                                                 return;
2996                                         }
2997                                 }
2998                                 cmd_found = 1;
2999                         }
3000                 }
3001         }
3002         if ((!cmd_found) && (user))
3003         {
3004                 log(DEBUG,"process_command: not in table: %s %s",user->nick,command);
3005                 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
3006         }
3007 }
3008
3009
3010 void createcommand(char* cmd, handlerfunc f, char flags, int minparams,char* source)
3011 {
3012         command_t comm;
3013         /* create the command and push it onto the table */     
3014         strlcpy(comm.command,cmd,MAXBUF);
3015         strlcpy(comm.source,source,MAXBUF);
3016         comm.handler_function = f;
3017         comm.flags_needed = flags;
3018         comm.min_params = minparams;
3019         comm.use_count = 0;
3020         comm.total_bytes = 0;
3021         cmdlist.push_back(comm);
3022         log(DEBUG,"Added command %s (%d parameters)",cmd,minparams);
3023 }
3024
3025 bool removecommands(const char* source)
3026 {
3027         bool go_again = true;
3028         while (go_again)
3029         {
3030                 go_again = false;
3031                 for (std::deque<command_t>::iterator i = cmdlist.begin(); i != cmdlist.end(); i++)
3032                 {
3033                         if (!strcmp(i->source,source))
3034                         {
3035                                 log(DEBUG,"removecommands(%s) Removing dependent command: %s",i->source,i->command);
3036                                 cmdlist.erase(i);
3037                                 go_again = true;
3038                                 break;
3039                         }
3040                 }
3041         }
3042         return true;
3043 }
3044
3045 void SetupCommandTable(void)
3046 {
3047         createcommand("USER",handle_user,0,4,"<core>");
3048         createcommand("NICK",handle_nick,0,1,"<core>");
3049         createcommand("QUIT",handle_quit,0,0,"<core>");
3050         createcommand("VERSION",handle_version,0,0,"<core>");
3051         createcommand("PING",handle_ping,0,1,"<core>");
3052         createcommand("PONG",handle_pong,0,1,"<core>");
3053         createcommand("ADMIN",handle_admin,0,0,"<core>");
3054         createcommand("PRIVMSG",handle_privmsg,0,2,"<core>");
3055         createcommand("INFO",handle_info,0,0,"<core>");
3056         createcommand("TIME",handle_time,0,0,"<core>");
3057         createcommand("WHOIS",handle_whois,0,1,"<core>");
3058         createcommand("WALLOPS",handle_wallops,'o',1,"<core>");
3059         createcommand("NOTICE",handle_notice,0,2,"<core>");
3060         createcommand("JOIN",handle_join,0,1,"<core>");
3061         createcommand("NAMES",handle_names,0,1,"<core>");
3062         createcommand("PART",handle_part,0,1,"<core>");
3063         createcommand("KICK",handle_kick,0,2,"<core>");
3064         createcommand("MODE",handle_mode,0,1,"<core>");
3065         createcommand("TOPIC",handle_topic,0,1,"<core>");
3066         createcommand("WHO",handle_who,0,1,"<core>");
3067         createcommand("MOTD",handle_motd,0,0,"<core>");
3068         createcommand("RULES",handle_rules,0,0,"<core>");
3069         createcommand("OPER",handle_oper,0,2,"<core>");
3070         createcommand("LIST",handle_list,0,0,"<core>");
3071         createcommand("DIE",handle_die,'o',1,"<core>");
3072         createcommand("RESTART",handle_restart,'o',1,"<core>");
3073         createcommand("KILL",handle_kill,'o',2,"<core>");
3074         createcommand("REHASH",handle_rehash,'o',0,"<core>");
3075         createcommand("LUSERS",handle_lusers,0,0,"<core>");
3076         createcommand("STATS",handle_stats,0,1,"<core>");
3077         createcommand("USERHOST",handle_userhost,0,1,"<core>");
3078         createcommand("AWAY",handle_away,0,0,"<core>");
3079         createcommand("ISON",handle_ison,0,0,"<core>");
3080         createcommand("SUMMON",handle_summon,0,0,"<core>");
3081         createcommand("USERS",handle_users,0,0,"<core>");
3082         createcommand("INVITE",handle_invite,0,2,"<core>");
3083         createcommand("PASS",handle_pass,0,1,"<core>");
3084         createcommand("TRACE",handle_trace,'o',0,"<core>");
3085         createcommand("WHOWAS",handle_whowas,0,1,"<core>");
3086         createcommand("CONNECT",handle_connect,'o',1,"<core>");
3087         createcommand("SQUIT",handle_squit,'o',0,"<core>");
3088         createcommand("MODULES",handle_modules,0,0,"<core>");
3089         createcommand("LINKS",handle_links,0,0,"<core>");
3090         createcommand("MAP",handle_map,0,0,"<core>");
3091         createcommand("KLINE",handle_kline,'o',1,"<core>");
3092         createcommand("GLINE",handle_gline,'o',1,"<core>");
3093         createcommand("ZLINE",handle_zline,'o',1,"<core>");
3094         createcommand("QLINE",handle_qline,'o',1,"<core>");
3095         createcommand("ELINE",handle_eline,'o',1,"<core>");
3096         createcommand("LOADMODULE",handle_loadmodule,'o',1,"<core>");
3097         createcommand("UNLOADMODULE",handle_unloadmodule,'o',1,"<core>");
3098         createcommand("SERVER",handle_server,0,0,"<core>");
3099 }
3100
3101 void process_buffer(const char* cmdbuf,userrec *user)
3102 {
3103         if (!user)
3104         {
3105                 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
3106                 return;
3107         }
3108         char cmd[MAXBUF];
3109         int i;
3110         if (!cmdbuf)
3111         {
3112                 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
3113                 return;
3114         }
3115         if (!strcmp(cmdbuf,""))
3116         {
3117                 return;
3118         }
3119         while ((cmdbuf[0] == ' ') && (strlen(cmdbuf)>0)) cmdbuf++; // strip leading spaces
3120
3121         strlcpy(cmd,cmdbuf,MAXBUF);
3122         if (!strcmp(cmd,""))
3123         {
3124                 return;
3125         }
3126         if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
3127         {
3128                 cmd[strlen(cmd)-1] = '\0';
3129         }
3130         if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
3131         {
3132                 cmd[strlen(cmd)-1] = '\0';
3133         }
3134
3135         while ((cmd[strlen(cmd)-1] == ' ') && (strlen(cmd)>0)) // strip trailing spaces
3136         {
3137                 cmd[strlen(cmd)-1] = '\0';
3138         }
3139
3140         if (!strcmp(cmd,""))
3141         {
3142                 return;
3143         }
3144         log(DEBUG,"InspIRCd: processing: %s %s",user->nick,cmd);
3145         tidystring(cmd);
3146         if ((user) && (cmd))
3147         {
3148                 process_command(user,cmd);
3149         }
3150 }
3151
3152 void DoSync(serverrec* serv, char* tcp_host)
3153 {
3154         char data[MAXBUF];
3155         log(DEBUG,"Sending sync");
3156         // send start of sync marker: Y <timestamp>
3157         // at this point the ircd receiving it starts broadcasting this netburst to all ircds
3158         // except the ones its receiving it from.
3159         snprintf(data,MAXBUF,"Y %d",TIME);
3160         serv->SendPacket(data,tcp_host);
3161         // send users and channels
3162         for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
3163         {
3164                 snprintf(data,MAXBUF,"N %d %s %s %s %s +%s %s %s :%s",u->second->age,u->second->nick,u->second->host,u->second->dhost,u->second->ident,u->second->modes,u->second->ip,u->second->server,u->second->fullname);
3165                 serv->SendPacket(data,tcp_host);
3166                 if (strchr(u->second->modes,'o'))
3167                 {
3168                         snprintf(data,MAXBUF,"| %s %s",u->second->nick,u->second->oper);
3169                         serv->SendPacket(data,tcp_host);
3170                 }
3171                 for (int i = 0; i <= MODCOUNT; i++)
3172                 {
3173                         string_list l = modules[i]->OnUserSync(u->second);
3174                         for (int j = 0; j < l.size(); j++)
3175                         {
3176                                 strlcpy(data,l[j].c_str(),MAXBUF);
3177                                 serv->SendPacket(data,tcp_host);
3178                         }
3179                 }
3180                 if (strcmp(chlist(u->second),""))
3181                 {
3182                         snprintf(data,MAXBUF,"J %s %s",u->second->nick,chlist(u->second));
3183                         serv->SendPacket(data,tcp_host);
3184                 }
3185         }
3186         // send channel modes, topics etc...
3187         for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
3188         {
3189                 snprintf(data,MAXBUF,"M %s +%s",c->second->name,chanmodes(c->second));
3190                 serv->SendPacket(data,tcp_host);
3191                 for (int i = 0; i <= MODCOUNT; i++)
3192                 {
3193                         string_list l = modules[i]->OnChannelSync(c->second);
3194                         for (int j = 0; j < l.size(); j++)
3195                         {
3196                                 strlcpy(data,l[j].c_str(),MAXBUF);
3197                                 serv->SendPacket(data,tcp_host);
3198                         }
3199                 }
3200                 if (strcmp(c->second->topic,""))
3201                 {
3202                         snprintf(data,MAXBUF,"T %d %s %s :%s",c->second->topicset,c->second->setby,c->second->name,c->second->topic);
3203                         serv->SendPacket(data,tcp_host);
3204                 }
3205                 // send current banlist
3206                 
3207                 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
3208                 {
3209                         snprintf(data,MAXBUF,"M %s +b %s",b->set_time,c->second->name,b->data);
3210                         serv->SendPacket(data,tcp_host);
3211                 }
3212         }
3213         // sync global zlines, glines, etc
3214         sync_xlines(serv,tcp_host);
3215
3216         for (int j = 0; j < 32; j++)
3217         {
3218                 if (me[j] != NULL)
3219                 {
3220                         for (int k = 0; k < me[j]->connectors.size(); k++)
3221                         {
3222                                 if (is_uline(me[j]->connectors[k].GetServerName().c_str()))
3223                                 {
3224                                         snprintf(data,MAXBUF,"H %s",me[j]->connectors[k].GetServerName().c_str());
3225                                         serv->SendPacket(data,tcp_host);
3226                                         NetSendMyRoutingTable();
3227                                 }
3228                         }
3229                 }
3230         }
3231
3232         snprintf(data,MAXBUF,"F %d",TIME);
3233         serv->SendPacket(data,tcp_host);
3234         log(DEBUG,"Sent sync");
3235         // ircd sends its serverlist after the end of sync here
3236 }
3237
3238
3239 void NetSendMyRoutingTable()
3240 {
3241         // send out a line saying what is reachable to us.
3242         // E.g. if A is linked to B C and D, send out:
3243         // $ A B C D
3244         // if its only linked to B and D send out:
3245         // $ A B D
3246         // if it has no links, dont even send out the line at all.
3247         char buffer[MAXBUF];
3248         snprintf(buffer,MAXBUF,"$ %s",ServerName);
3249         bool sendit = false;
3250         for (int i = 0; i < 32; i++)
3251         {
3252                 if (me[i] != NULL)
3253                 {
3254                         for (int j = 0; j < me[i]->connectors.size(); j++)
3255                         {
3256                                 if ((me[i]->connectors[j].GetState() != STATE_DISCONNECTED) || (is_uline(me[i]->connectors[j].GetServerName().c_str())))
3257                                 {
3258                                         strlcat(buffer," ",MAXBUF);
3259                                         strlcat(buffer,me[i]->connectors[j].GetServerName().c_str(),MAXBUF);
3260                                         sendit = true;
3261                                 }
3262                         }
3263                 }
3264         }
3265         if (sendit)
3266                 NetSendToAll(buffer);
3267 }
3268
3269
3270 void DoSplit(const char* params)
3271 {
3272         bool go_again = true;
3273         while (go_again)
3274         {
3275                 go_again = false;
3276                 for (int i = 0; i < 32; i++)
3277                 {
3278                         if (me[i] != NULL)
3279                         {
3280                                 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
3281                                 {
3282                                         if (!strcasecmp(j->GetServerName().c_str(),params))
3283                                         {
3284                                                 j->routes.clear();
3285                                                 j->CloseConnection();
3286                                                 me[i]->connectors.erase(j);
3287                                                 go_again = true;
3288                                                 break;
3289                                         }
3290                                 }
3291                         }
3292                 }
3293         }
3294         log(DEBUG,"Removed server. Will remove clients...");
3295         // iterate through the userlist and remove all users on this server.
3296         // because we're dealing with a mesh, we dont have to deal with anything
3297         // "down-route" from this server (nice huh)
3298         go_again = true;
3299         char reason[MAXBUF];
3300         snprintf(reason,MAXBUF,"%s %s",ServerName,params);
3301         while (go_again)
3302         {
3303                 go_again = false;
3304                 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
3305                 {
3306                         if (!strcasecmp(u->second->server,params))
3307                         {
3308                                 kill_link(u->second,reason);
3309                                 go_again = true;
3310                                 break;
3311                         }
3312                 }
3313         }
3314 }
3315
3316 // removes a server. Will NOT remove its users!
3317
3318 void RemoveServer(const char* name)
3319 {
3320         bool go_again = true;
3321         while (go_again)
3322         {
3323                 go_again = false;
3324                 for (int i = 0; i < 32; i++)
3325                 {
3326                         if (me[i] != NULL)
3327                         {
3328                                 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
3329                                 {
3330                                         if (!strcasecmp(j->GetServerName().c_str(),name))
3331                                         {
3332                                                 j->routes.clear();
3333                                                 j->CloseConnection();
3334                                                 me[i]->connectors.erase(j);
3335                                                 go_again = true;
3336                                                 break;
3337                                         }
3338                                 }
3339                         }
3340                 }
3341         }
3342 }
3343
3344
3345 int reap_counter = 0;
3346 char MODERR[MAXBUF];
3347
3348 char* ModuleError()
3349 {
3350         return MODERR;
3351 }
3352
3353 bool UnloadModule(const char* filename)
3354 {
3355         for (int j = 0; j != module_names.size(); j++)
3356         {
3357                 if (module_names[j] == std::string(filename))
3358                 {
3359                         if (modules[j]->GetVersion().Flags & VF_STATIC)
3360                         {
3361                                 log(DEFAULT,"Failed to unload STATIC module %s",filename);
3362                                 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
3363                                 return false;
3364                         }
3365                         // found the module
3366                         log(DEBUG,"Deleting module...");
3367                         delete modules[j];
3368                         modules[j] = NULL;
3369                         log(DEBUG,"Deleting module factory pointer...");
3370                         delete factory[j]->factory;
3371                         log(DEBUG,"Deleting module factory...");
3372                         delete factory[j];
3373                         log(DEBUG,"Erasing module entry...");
3374                         factory[j] = NULL;
3375                         // here we should locate ALL resources claimed by this module... and release them
3376                         // for example commands
3377                         log(DEBUG,"Erasing module vector...");
3378                         for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
3379                         {
3380                                 if (*t == NULL)
3381                                 {
3382                                         factory.erase(t);
3383                                         break;
3384                                 }
3385                         }
3386                         log(DEBUG,"Erasing module name vector...");
3387                         for (std::vector<std::string>::iterator v = module_names.begin(); v != module_names.end(); v++)
3388                         {
3389                                 if (*v == std::string(filename))
3390                                 {
3391                                         module_names.erase(v);
3392                                         break;
3393                                 }
3394                         }
3395                         log(DEBUG,"Erasing module pointer...");
3396                         for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
3397                         {
3398                                 if (*m == NULL)
3399                                 {
3400                                         modules.erase(m);
3401                                         break;
3402                                 }
3403                         }
3404                         log(DEBUG,"Removing dependent commands...");
3405                         removecommands(filename);
3406                         log(DEFAULT,"Module %s unloaded",filename);
3407                         MODCOUNT--;
3408                         return true;
3409                 }
3410         }
3411         log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
3412         snprintf(MODERR,MAXBUF,"Module not loaded");
3413         return false;
3414 }
3415
3416 bool DirValid(char* dirandfile)
3417 {
3418         char work[MAXBUF];
3419         strlcpy(work,dirandfile,MAXBUF);
3420         int p = strlen(work);
3421         // we just want the dir
3422         while (strlen(work))
3423         {
3424                 if (work[p] == '/')
3425                 {
3426                         work[p] = '\0';
3427                         break;
3428                 }
3429                 work[p--] = '\0';
3430         }
3431         log(DEBUG,"Dir valid: %s",work);
3432         char buffer[MAXBUF], otherdir[MAXBUF];
3433         // Get the current working directory
3434         if( getcwd( buffer, MAXBUF ) == NULL )
3435                 return false;
3436         chdir(work);
3437         if( getcwd( otherdir, MAXBUF ) == NULL )
3438                 return false;
3439         chdir(buffer);
3440         log(DEBUG,"Dir is really: %s",otherdir);
3441         if (strlen(otherdir) >= strlen(work))
3442         {
3443                 otherdir[strlen(work)] = '\0';
3444                 log(DEBUG,"Compare: '%s' -> '%s'",otherdir,work);
3445                 if (!strcmp(otherdir,work))
3446                 {
3447                         log(DEBUG,"Match ok");
3448                         return true;
3449                 }
3450                 log(DEBUG,"No match");
3451                 return false;
3452         }
3453         else return false;
3454 }
3455
3456 bool LoadModule(const char* filename)
3457 {
3458         char modfile[MAXBUF];
3459         snprintf(modfile,MAXBUF,"%s/%s",ModPath,filename);
3460         if (!DirValid(modfile))
3461         {
3462                 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
3463                 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
3464                 return false;
3465         }
3466         log(DEBUG,"Loading module: %s",modfile);
3467         if (FileExists(modfile))
3468         {
3469                 for (int j = 0; j < module_names.size(); j++)
3470                 {
3471                         if (module_names[j] == std::string(filename))
3472                         {
3473                                 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
3474                                 snprintf(MODERR,MAXBUF,"Module already loaded");
3475                                 return false;
3476                         }
3477                 }
3478                 factory[MODCOUNT+1] = new ircd_module(modfile);
3479                 if (factory[MODCOUNT+1]->LastError())
3480                 {
3481                         log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
3482                         snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
3483                         MODCOUNT--;
3484                         return false;
3485                 }
3486                 if (factory[MODCOUNT+1]->factory)
3487                 {
3488                         modules[MODCOUNT+1] = factory[MODCOUNT+1]->factory->CreateModule();
3489                         /* save the module and the module's classfactory, if
3490                          * this isnt done, random crashes can occur :/ */
3491                         module_names.push_back(filename);
3492                 }
3493                 else
3494                 {
3495                         log(DEFAULT,"Unable to load %s",modfile);
3496                         snprintf(MODERR,MAXBUF,"Factory function failed!");
3497                         return false;
3498                 }
3499         }
3500         else
3501         {
3502                 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
3503                 snprintf(MODERR,MAXBUF,"Module file could not be found");
3504                 return false;
3505         }
3506         MODCOUNT++;
3507         return true;
3508 }
3509
3510 int InspIRCd(void)
3511 {
3512         struct sockaddr_in client,server;
3513         char addrs[MAXBUF][255];
3514         int incomingSockfd, result = TRUE;
3515         socklen_t length;
3516         int count = 0;
3517         int selectResult = 0, selectResult2 = 0;
3518         char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
3519         char resolvedHost[MAXBUF];
3520         fd_set selectFds;
3521         timeval tv;
3522
3523         log_file = fopen("ircd.log","a+");
3524         if (!log_file)
3525         {
3526                 printf("ERROR: Could not write to logfile ircd.log, bailing!\n\n");
3527                 Exit(ERROR);
3528         }
3529
3530         log(DEBUG,"InspIRCd: startup: begin");
3531         log(DEBUG,"$Id$");
3532         if (geteuid() == 0)
3533         {
3534                 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
3535                 Exit(ERROR);
3536                 log(DEFAULT,"InspIRCd: startup: not starting with UID 0!");
3537         }
3538         SetupCommandTable();
3539         log(DEBUG,"InspIRCd: startup: default command table set up");
3540         
3541         ReadConfig(true,NULL);
3542         if (strcmp(DieValue,"")) 
3543         { 
3544                 printf("WARNING: %s\n\n",DieValue);
3545                 log(DEFAULT,"Ut-Oh, somebody didn't read their config file: '%s'",DieValue);
3546                 exit(0); 
3547         }  
3548         log(DEBUG,"InspIRCd: startup: read config");
3549           
3550         int count2 = 0, count3 = 0;
3551
3552         for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
3553         {
3554                 ConfValue("bind","port",count,configToken,&config_f);
3555                 ConfValue("bind","address",count,Addr,&config_f);
3556                 ConfValue("bind","type",count,Type,&config_f);
3557                 if (!strcmp(Type,"servers"))
3558                 {
3559                         char Default[MAXBUF];
3560                         strcpy(Default,"no");
3561                         ConfValue("bind","default",count,Default,&config_f);
3562                         if (strchr(Default,'y'))
3563                         {
3564                                 defaultRoute = count3;
3565                                 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
3566                         }
3567                         me[count3] = new serverrec(ServerName,100L,false);
3568                         if (!me[count3]->CreateListener(Addr,atoi(configToken)))
3569                         {
3570                                 log(DEFAULT,"Error! Failed to bind port %d",atoi(configToken));
3571                         }
3572                         else
3573                         {
3574                                 count3++;
3575                         }
3576                 }
3577                 else
3578                 {
3579                         ports[count2] = atoi(configToken);
3580                         strlcpy(addrs[count2],Addr,256);
3581                         count2++;
3582                 }
3583                 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
3584         }
3585         portCount = count2;
3586         UDPportCount = count3;
3587           
3588         log(DEBUG,"InspIRCd: startup: read %d total client ports and %d total server ports",portCount,UDPportCount);
3589         
3590         log(DEBUG,"InspIRCd: startup: InspIRCd is now running!");
3591         
3592         printf("\n");
3593         
3594         /* BugFix By Craig! :p */
3595         MODCOUNT = -1;
3596         for (count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
3597         {
3598                 ConfValue("module","name",count2,configToken,&config_f);
3599                 printf("Loading module... \033[1;37m%s\033[0;37m\n",configToken);
3600                 if (!LoadModule(configToken))
3601                 {
3602                         log(DEBUG,"Exiting due to a module loader error.");
3603                         printf("There was an error loading a module: %s\n",ModuleError());
3604                         Exit(0);
3605                 }
3606         }
3607         log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
3608         
3609         printf("\nInspIRCd is now running!\n");
3610         
3611         startup_time = time(NULL);
3612           
3613         if (nofork)
3614         {
3615                 log(VERBOSE,"Not forking as -nofork was specified");
3616         }
3617         else
3618         {
3619                 if (DaemonSeed() == ERROR)
3620                 {
3621                         log(DEFAULT,"InspIRCd: startup: can't daemonise");
3622                         printf("ERROR: could not go into daemon mode. Shutting down.\n");
3623                         Exit(ERROR);
3624                 }
3625         }
3626
3627         char PID[MAXBUF];
3628         ConfValue("pid","file",0,PID,&config_f);
3629         WritePID(PID);
3630           
3631           
3632         /* setup select call */
3633         FD_ZERO(&selectFds);
3634         log(DEBUG,"InspIRCd: startup: zero selects");
3635         log(VERBOSE,"InspIRCd: startup: portCount = %d", portCount);
3636         
3637         for (count = 0; count < portCount; count++)
3638         {
3639                 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
3640                 {
3641                         log(DEBUG,"InspIRCd: startup: bad fd %d",openSockfd[boundPortCount]);
3642                         return(ERROR);
3643                 }
3644                 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
3645                 {
3646                         log(DEFAULT,"InspIRCd: startup: failed to bind port %d",ports[count]);
3647                 }
3648                 else    /* well we at least bound to one socket so we'll continue */
3649                 {
3650                         boundPortCount++;
3651                 }
3652         }
3653         
3654         log(DEBUG,"InspIRCd: startup: total bound ports %d",boundPortCount);
3655           
3656         /* if we didn't bind to anything then abort */
3657         if (boundPortCount == 0)
3658         {
3659                 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
3660                 return (ERROR);
3661         }
3662         
3663
3664         length = sizeof (client);
3665         char udp_msg[MAXBUF], tcp_host[MAXBUF];
3666
3667         fd_set serverfds;
3668         timeval tvs;
3669         tvs.tv_usec = 7000L;
3670         tvs.tv_sec = 0;
3671         tv.tv_sec = 0;
3672         tv.tv_usec = 7000L;
3673         char data[10240];
3674         timeval tval;
3675         fd_set sfd;
3676         tval.tv_usec = 7000L;
3677         tval.tv_sec = 0;
3678         int total_in_this_set = 0;
3679         int v = 0;
3680         bool expire_run = false;
3681           
3682         /* main loop, this never returns */
3683         for (;;)
3684         {
3685 #ifdef _POSIX_PRIORITY_SCHEDULING
3686                 sched_yield();
3687 #endif
3688                 // poll dns queue
3689                 dns_poll();
3690                 FD_ZERO(&sfd);
3691
3692                 // we only read time() once per iteration rather than tons of times!
3693                 TIME = time(NULL);
3694
3695                 user_hash::iterator count2 = clientlist.begin();
3696
3697                 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
3698                 // them in a list, then reap the list every second or so.
3699                 if (((TIME % 5) == 0) && (!expire_run))
3700                 {
3701                         expire_lines();
3702                         expire_run = true;
3703                 }
3704                 if ((TIME % 5) == 1)
3705                         expire_run = false;
3706                 if (reap_counter>300)
3707                 {
3708                         if (fd_reap.size() > 0)
3709                         {
3710                                 for( int n = 0; n < fd_reap.size(); n++)
3711                                 {
3712                                         //Blocking(fd_reap[n]);
3713                                         close(fd_reap[n]);
3714                                         shutdown (fd_reap[n],2);
3715                                         //NonBlocking(fd_reap[n]);
3716                                 }
3717                         }
3718                         fd_reap.clear();
3719                         reap_counter=0;
3720                 }
3721                 reap_counter++;
3722
3723                 FD_ZERO(&serverfds);
3724                 
3725                 for (int x = 0; x != UDPportCount; x++)
3726                 {
3727                         if (me[x])
3728                                 FD_SET(me[x]->fd, &serverfds);
3729                 }
3730                 
3731                 // serverFds timevals went here
3732                 
3733                 tvs.tv_usec = 7000L;
3734                 int servresult = select(32767, &serverfds, NULL, NULL, &tvs);
3735                 if (servresult > 0)
3736                 {
3737                         for (int x = 0; x != UDPportCount; x++)
3738                         {
3739                                 if ((me[x]) && (FD_ISSET (me[x]->fd, &serverfds)))
3740                                 {
3741                                         char remotehost[MAXBUF],resolved[MAXBUF];
3742                                         length = sizeof (client);
3743                                         incomingSockfd = accept (me[x]->fd, (sockaddr *) &client, &length);
3744                                         if (incomingSockfd != -1)
3745                                         {
3746                                                 strlcpy(remotehost,(char *)inet_ntoa(client.sin_addr),MAXBUF);
3747                                                 if(CleanAndResolve(resolved, remotehost) != TRUE)
3748                                                 {
3749                                                         strlcpy(resolved,remotehost,MAXBUF);
3750                                                 }
3751                                                 // add to this connections ircd_connector vector
3752                                                 // *FIX* - we need the LOCAL port not the remote port in &client!
3753                                                 me[x]->AddIncoming(incomingSockfd,resolved,me[x]->port);
3754                                         }
3755                                 }
3756                         }
3757                 }
3758      
3759                 for (int x = 0; x < UDPportCount; x++)
3760                 {
3761                         std::deque<std::string> msgs;
3762                         msgs.clear();
3763                         if ((me[x]) && (me[x]->RecvPacket(msgs, tcp_host)))
3764                         {
3765                                 for (int ctr = 0; ctr < msgs.size(); ctr++)
3766                                 {
3767                                         char udp_msg[MAXBUF];
3768                                         strlcpy(udp_msg,msgs[ctr].c_str(),MAXBUF);
3769                                         if (strlen(udp_msg)<1)
3770                                         {
3771                                                 log(DEBUG,"Invalid string from %s [route%d]",tcp_host,x);
3772                                                 break;
3773                                         }
3774                                         // during a netburst, send all data to all other linked servers
3775                                         if ((((nb_start>0) && (udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))) || (is_uline(tcp_host)))
3776                                         {
3777                                                 if (is_uline(tcp_host))
3778                                                 {
3779                                                         if ((udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))
3780                                                         {
3781                                                                 NetSendToAllExcept(tcp_host,udp_msg);
3782                                                         }
3783                                                 }
3784                                                 else
3785                                                         NetSendToAllExcept(tcp_host,udp_msg);
3786                                         }
3787                                         FOREACH_MOD OnPacketReceive(udp_msg);
3788                                         handle_link_packet(udp_msg, tcp_host, me[x]);
3789                                 }
3790                                 goto label;
3791                         }
3792                 }
3793         
3794
3795         while (count2 != clientlist.end())
3796         {
3797                 FD_ZERO(&sfd);
3798                 total_in_this_set = 0;
3799
3800                 user_hash::iterator xcount = count2;
3801                 user_hash::iterator endingiter = count2;
3802
3803                 if (count2 == clientlist.end()) break;
3804                 
3805                 if (count2->second)
3806                 if (count2->second->fd != 0)
3807                 {
3808                         // assemble up to 64 sockets into an fd_set
3809                         // to implement a pooling mechanism.
3810                         //
3811                         // This should be up to 64x faster than the
3812                         // old implementation.
3813                         while (total_in_this_set < 64)
3814                         {
3815                                 if (count2 != clientlist.end())
3816                                 {
3817                                         // we don't check the state of remote users.
3818                                         if (count2->second->fd > 0)
3819                                         {
3820                                                 FD_SET (count2->second->fd, &sfd);
3821
3822                                                 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
3823                                                 // their connection class.
3824                                                 if ((TIME > count2->second->timeout) && (count2->second->registered != 7)) 
3825                                                 {
3826                                                         log(DEBUG,"InspIRCd: registration timeout: %s",count2->second->nick);
3827                                                         kill_link(count2->second,"Registration timeout");
3828                                                         goto label;
3829                                                 }
3830                                                 if ((TIME > count2->second->signon) && (count2->second->registered == 3))
3831                                                 {
3832                                                                 count2->second->dns_done = true;
3833                                                                 FullConnectUser(count2->second);
3834                                                                 goto label;
3835                                                 }
3836                                                 if ((count2->second->dns_done) && (count2->second->registered == 3)) // both NICK and USER... and DNS
3837                                                 {
3838                                                         FullConnectUser(count2->second);
3839                                                         goto label;
3840                                                 }
3841                                                 if ((TIME > count2->second->nping) && (isnick(count2->second->nick)) && (count2->second->registered == 7))
3842                                                 {
3843                                                         if ((!count2->second->lastping) && (count2->second->registered == 7))
3844                                                         {
3845                                                                 log(DEBUG,"InspIRCd: ping timeout: %s",count2->second->nick);
3846                                                                 kill_link(count2->second,"Ping timeout");
3847                                                                 goto label;
3848                                                         }
3849                                                         Write(count2->second->fd,"PING :%s",ServerName);
3850                                                         log(DEBUG,"InspIRCd: pinging: %s",count2->second->nick);
3851                                                         count2->second->lastping = 0;
3852                                                         count2->second->nping = TIME+count2->second->pingmax;   // was hard coded to 120
3853                                                 }
3854                                         }
3855                                         count2++;
3856                                         total_in_this_set++;
3857                                 }
3858                                 else break;
3859                         }
3860    
3861                         endingiter = count2;
3862                         count2 = xcount; // roll back to where we were
3863         
3864                         v = 0;
3865
3866                         // tvals defined here
3867
3868                         tval.tv_usec = 7000L;
3869                         selectResult2 = select(65535, &sfd, NULL, NULL, &tval);
3870                         
3871                         // now loop through all of the items in this pool if any are waiting
3872                         //if (selectResult2 > 0)
3873                         for (user_hash::iterator count2a = xcount; count2a != endingiter; count2a++)
3874                         {
3875
3876 #ifdef _POSIX_PRIORITY_SCHEDULING
3877                                 sched_yield();
3878 #endif
3879
3880                                 result = EAGAIN;
3881                                 if ((count2a->second->fd != -1) && (FD_ISSET (count2a->second->fd, &sfd)))
3882                                 {
3883                                         memset(data, 0, 10240);
3884                                         result = read(count2a->second->fd, data, 10240);
3885                                         
3886                                         if (result)
3887                                         {
3888                                                 userrec* current = count2a->second;
3889                                                 int currfd = current->fd;
3890                                                 char* l = strtok(data,"\n");
3891                                                 int floodlines = 0;
3892                                                 while (l)
3893                                                 {
3894                                                         floodlines++;
3895                                                         if ((floodlines > current->flood) && (current->flood != 0))
3896                                                         {
3897                                                                 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3898                                                                 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3899                                                                 kill_link(current,"Excess flood");
3900                                                                 goto label;
3901                                                         }
3902                                                         char sanitized[NetBufferSize];
3903                                                         memset(sanitized, 0, NetBufferSize);
3904                                                         int ptt = 0;
3905                                                         for (int pt = 0; pt < strlen(l); pt++)
3906                                                         {
3907                                                                 if (l[pt] != '\r')
3908                                                                 {
3909                                                                         sanitized[ptt++] = l[pt];
3910                                                                 }
3911                                                         }
3912                                                         sanitized[ptt] = '\0';
3913                                                         if (strlen(sanitized))
3914                                                         {
3915
3916
3917                                                                 // we're gonna re-scan to check if the nick is gone, after every
3918                                                                 // command - if it has, we're gonna bail
3919                                                                 bool find_again = false;
3920                                                                 process_buffer(sanitized,current);
3921         
3922                                                                 // look for the user's record in case it's changed
3923                                                                 for (user_hash::iterator c2 = clientlist.begin(); c2 != clientlist.end(); c2++)
3924                                                                 {
3925                                                                         if (c2->second->fd == currfd)
3926                                                                         {
3927                                                                                 // found again, update pointer
3928                                                                                 current == c2->second;
3929                                                                                 find_again = true;
3930                                                                                 break;
3931                                                                         }
3932                                                                 }
3933                                                                 if (!find_again)
3934                                                                         goto label;
3935
3936                                                         }
3937                                                         l = strtok(NULL,"\n");
3938                                                 }
3939                                                 goto label;
3940                                         }
3941
3942                                         if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
3943                                         {
3944                                                 log(DEBUG,"killing: %s",count2a->second->nick);
3945                                                 kill_link(count2a->second,strerror(errno));
3946                                                 goto label;
3947                                         }
3948                                 }
3949                                 // result EAGAIN means nothing read
3950                                 if (result == EAGAIN)
3951                                 {
3952                                 }
3953                                 else
3954                                 if (result == 0)
3955                                 {
3956                                         if (count2->second)
3957                                         {
3958                                                 log(DEBUG,"InspIRCd: Exited: %s",count2a->second->nick);
3959                                                 kill_link(count2a->second,"Client exited");
3960                                                 // must bail here? kill_link removes the hash, corrupting the iterator
3961                                                 log(DEBUG,"Bailing from client exit");
3962                                                 goto label;
3963                                         }
3964                                 }
3965                                 else if (result > 0)
3966                                 {
3967                                 }
3968                         }
3969                 }
3970                 for (int q = 0; q < total_in_this_set; q++)
3971                 {
3972                         // there is no iterator += operator :(
3973                         //if (count2 != clientlist.end())
3974                         //{
3975                                 count2++;
3976                         //}
3977                 }
3978         }
3979         
3980         // set up select call
3981         for (count = 0; count < boundPortCount; count++)
3982         {
3983                 FD_SET (openSockfd[count], &selectFds);
3984         }
3985
3986         tv.tv_usec = 7000L;
3987         selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
3988
3989         /* select is reporting a waiting socket. Poll them all to find out which */
3990         if (selectResult > 0)
3991         {
3992                 char target[MAXBUF], resolved[MAXBUF];
3993                 for (count = 0; count < boundPortCount; count++)                
3994                 {
3995                         if (FD_ISSET (openSockfd[count], &selectFds))
3996                         {
3997                                 length = sizeof (client);
3998                                 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
3999                               
4000                                 strlcpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
4001                                 strlcpy (resolved, target, MAXBUF);
4002                         
4003                                 if (incomingSockfd < 0)
4004                                 {
4005                                         WriteOpers("*** WARNING: Accept failed on port %d (%s)", ports[count],target);
4006                                         log(DEBUG,"InspIRCd: accept failed: %d",ports[count]);
4007                                 }
4008                                 else
4009                                 {
4010                                         AddClient(incomingSockfd, resolved, ports[count], false, inet_ntoa (client.sin_addr));
4011                                         log(DEBUG,"InspIRCd: adding client on port %d fd=%d",ports[count],incomingSockfd);
4012                                 }
4013                                 goto label;
4014                         }
4015                 }
4016         }
4017         label:
4018         if(0) {}; // "Label must be followed by a statement"... so i gave it one.
4019 }
4020 /* not reached */
4021 close (incomingSockfd);
4022 }
4023