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