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