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