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