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