]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
Fixed command parser to tidy up malformed commands (xchat inserts extra spaces)
[user/henk/code/inspircd.git] / src / inspircd.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  Inspire is copyright (C) 2002-2003 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 #include "inspircd.h"
20 #include "inspircd_io.h"
21 #include "inspircd_util.h"
22 #include "inspircd_config.h"
23 #include <unistd.h>
24 #include <fcntl.h>
25 #include <sys/errno.h>
26 #include <sys/ioctl.h>
27 #include <sys/utsname.h>
28 #include <cstdio>
29 #include <time.h>
30 #include <string>
31 #ifdef GCC3
32 #include <ext/hash_map>
33 #else
34 #include <hash_map>
35 #endif
36 #include <map>
37 #include <sstream>
38 #include <vector>
39 #include <errno.h>
40 #include <deque>
41 #include "connection.h"
42 #include "users.h"
43 #include "servers.h"
44 #include "ctables.h"
45 #include "globals.h"
46 #include "modules.h"
47 #include "dynamic.h"
48 #include "wildcard.h"
49
50 using namespace std;
51
52 #ifdef GCC3
53 #define nspace __gnu_cxx
54 #else
55 #define nspace std
56 #endif
57
58 int LogLevel = DEFAULT;
59 char ServerName[MAXBUF];
60 char Network[MAXBUF];
61 char ServerDesc[MAXBUF];
62 char AdminName[MAXBUF];
63 char AdminEmail[MAXBUF];
64 char AdminNick[MAXBUF];
65 char diepass[MAXBUF];
66 char restartpass[MAXBUF];
67 char motd[MAXBUF];
68 char rules[MAXBUF];
69 char list[MAXBUF];
70 char PrefixQuit[MAXBUF];
71 char DieValue[MAXBUF];
72 int debugging =  0;
73 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
74 int WHOWAS_MAX = 100;  // default 100 people maximum in the WHOWAS list
75 int DieDelay  =  5;
76 time_t startup_time = time(NULL);
77
78 extern vector<Module*> modules;
79 extern vector<ircd_module*> factory;
80 vector<int> fd_reap;
81
82 extern int MODCOUNT;
83
84 bool nofork = false;
85
86 namespace nspace
87 {
88         template<> struct nspace::hash<in_addr>
89         {
90                 size_t operator()(const struct in_addr &a) const
91                 {
92                         size_t q;
93                         memcpy(&q,&a,sizeof(size_t));
94                         return q;
95                 }
96         };
97
98         template<> struct nspace::hash<string>
99         {
100                 size_t operator()(const string &s) const
101                 {
102                         char a[MAXBUF];
103                         static struct hash<const char *> strhash;
104                         strcpy(a,s.c_str());
105                         strlower(a);
106                         return strhash(a);
107                 }
108         };
109 }       
110
111
112 struct StrHashComp
113 {
114
115         bool operator()(const string& s1, const string& s2) const
116         {
117                 char a[MAXBUF],b[MAXBUF];
118                 strcpy(a,s1.c_str());
119                 strcpy(b,s2.c_str());
120                 return (strcasecmp(a,b) == 0);
121         }
122
123 };
124
125 struct InAddr_HashComp
126 {
127
128         bool operator()(const in_addr &s1, const in_addr &s2) const
129         {
130                 size_t q;
131                 size_t p;
132                 
133                 memcpy(&q,&s1,sizeof(size_t));
134                 memcpy(&p,&s2,sizeof(size_t));
135                 
136                 return (q == p);
137         }
138
139 };
140
141
142 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, StrHashComp> user_hash;
143 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, StrHashComp> chan_hash;
144 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, InAddr_HashComp> address_cache;
145 typedef std::deque<command_t> command_table;
146
147 serverrec* me[32];
148 serverrec* servers[255];
149
150 user_hash clientlist;
151 chan_hash chanlist;
152 user_hash whowas;
153 command_table cmdlist;
154 file_cache MOTD;
155 file_cache RULES;
156 address_cache IP;
157
158 ClassVector Classes;
159
160 struct linger linger = { 0 };
161 char bannerBuffer[MAXBUF];
162 int boundPortCount = 0;
163 int portCount = 0, UDPportCount = 0, ports[MAXSOCKS];
164 int defaultRoute = 0;
165
166 connection C;
167
168 long MyKey = C.GenKey();
169
170 /* prototypes */
171
172 int has_channel(userrec *u, chanrec *c);
173 int usercount(chanrec *c);
174 int usercount_i(chanrec *c);
175 void update_stats_l(int fd,int data_out);
176 char* Passwd(userrec *user);
177 bool IsDenied(userrec *user);
178 void AddWhoWas(userrec* u);
179
180
181 void safedelete(userrec *p)
182 {
183         if (p)
184         {
185                 log(DEBUG,"deleting %s %s %s %s",p->nick,p->ident,p->dhost,p->fullname);
186                 log(DEBUG,"safedelete(userrec*): pointer is safe to delete");
187                 delete p;
188         }
189         else
190         {
191                 log(DEBUG,"safedelete(userrec*): unsafe pointer operation squished");
192         }
193 }
194
195 void safedelete(chanrec *p)
196 {
197         if (p)
198         {
199                 delete p;
200                 log(DEBUG,"safedelete(chanrec*): pointer is safe to delete");
201         }
202         else
203         {
204                 log(DEBUG,"safedelete(chanrec*): unsafe pointer operation squished");
205         }
206 }
207
208
209 void tidystring(char* str)
210 {
211         // strips out double spaces before a : parameter
212         char temp[MAXBUF];
213         bool go_again = true;
214         
215         while (go_again)
216         {
217                 bool noparse = false;
218                 int t = 0, a = 0;
219                 go_again = false;
220                 while (a < strlen(str))
221                 {
222                         if ((a<strlen(str)-1) && (noparse==false))
223                         {
224                                 if ((str[a] == ' ') && (str[a+1] == ' '))
225                                 {
226                                         log(DEBUG,"Tidied extra space out of string: %s",str);
227                                         go_again = true;
228                                         a++;
229                                 }
230                         }
231                         
232                         if (a<strlen(str)-1)
233                         {
234                                 if ((str[a] == ' ') && (str[a+1] == ':'))
235                                 {
236                                         noparse = true;
237                                 }
238                         }
239                         
240                         temp[t++] = str[a++];
241                 }
242                 temp[t] = '\0';
243                 strncpy(str,temp,MAXBUF);
244         }
245 }
246
247 /* chop a string down to 512 characters and preserve linefeed (irc max
248  * line length) */
249
250 void chop(char* str)
251 {
252
253   string temp = str;
254   FOREACH_MOD OnServerRaw(temp,false);
255   const char* str2 = temp.c_str();
256   sprintf(str,"%s",str2);
257   
258
259   if (strlen(str) > 512)
260   {
261         str[510] = '\r';
262         str[511] = '\n';
263         str[512] = '\0';
264   }
265 }
266
267
268 std::string getservername()
269 {
270         return ServerName;
271 }
272
273 std::string getserverdesc()
274 {
275         return ServerDesc;
276 }
277
278 std::string getnetworkname()
279 {
280         return Network;
281 }
282
283 std::string getadminname()
284 {
285         return AdminName;
286 }
287
288 std::string getadminemail()
289 {
290         return AdminEmail;
291 }
292
293 std::string getadminnick()
294 {
295         return AdminNick;
296 }
297
298 void log(int level,char *text, ...)
299 {
300         char textbuffer[MAXBUF];
301         va_list argsPtr;
302         FILE *f;
303         time_t rawtime;
304         struct tm * timeinfo;
305         if (level < LogLevel)
306                 return;
307
308         time(&rawtime);
309         timeinfo = localtime (&rawtime);
310
311         f = fopen("ircd.log","a+");
312         if (f)
313         {
314                 char b[MAXBUF];
315                 va_start (argsPtr, text);
316                 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
317                 va_end(argsPtr);
318                 strcpy(b,asctime(timeinfo));
319                 b[strlen(b)-1] = ':';
320                 fprintf(f,"%s %s\n",b,textbuffer);
321                 fclose(f);
322                 if (nofork)
323                 {
324                         // nofork enabled? display it on terminal too
325                         printf("%s %s\n",b,textbuffer);
326                 }
327         }
328         else
329         {
330                 printf("Can't write log file, bailing!!!");
331                 Exit(ERROR);
332         }
333 }
334
335 void readfile(file_cache &F, const char* fname)
336 {
337   FILE* file;
338   char linebuf[MAXBUF];
339
340   log(DEBUG,"readfile: loading %s",fname);
341   F.clear();
342   file =  fopen(fname,"r");
343   if (file)
344   {
345         while (!feof(file))
346         {
347                 fgets(linebuf,sizeof(linebuf),file);
348                 linebuf[strlen(linebuf)-1]='\0';
349                 if (!strcmp(linebuf,""))
350                 {
351                         strcpy(linebuf,"  ");
352                 }
353                 if (!feof(file))
354                 {
355                         F.push_back(linebuf);
356                 }
357         }
358         fclose(file);
359   }
360   else
361   {
362           log(DEBUG,"readfile: failed to load file: %s",fname);
363   }
364   log(DEBUG,"readfile: loaded %s, %d lines",fname,F.size());
365 }
366
367 void ReadConfig(void)
368 {
369   char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF];
370   ConnectClass c;
371
372   ConfValue("server","name",0,ServerName);
373   ConfValue("server","description",0,ServerDesc);
374   ConfValue("server","network",0,Network);
375   ConfValue("admin","name",0,AdminName);
376   ConfValue("admin","email",0,AdminEmail);
377   ConfValue("admin","nick",0,AdminNick);
378   ConfValue("files","motd",0,motd);
379   ConfValue("files","rules",0,rules);
380   ConfValue("power","diepass",0,diepass);
381   ConfValue("power","pause",0,pauseval);
382   ConfValue("power","restartpass",0,restartpass);
383   ConfValue("options","prefixquit",0,PrefixQuit);
384   ConfValue("die","value",0,DieValue);
385   ConfValue("options","loglevel",0,dbg);
386   if (!strcmp(dbg,"debug"))
387         LogLevel = DEBUG;
388   if (!strcmp(dbg,"verbose"))
389         LogLevel = VERBOSE;
390   if (!strcmp(dbg,"default"))
391         LogLevel = DEFAULT;
392   if (!strcmp(dbg,"sparse"))
393         LogLevel = SPARSE;
394   if (!strcmp(dbg,"none"))
395         LogLevel = NONE;
396   readfile(RULES,rules);
397   log(DEBUG,"Reading connect classes");
398   Classes.clear();
399   for (int i = 0; i < ConfValueEnum("connect"); i++)
400   {
401         strcpy(Value,"");
402         ConfValue("connect","allow",i,Value);
403         if (strcmp(Value,""))
404         {
405                 strcpy(c.host,Value);
406                 c.type = CC_ALLOW;
407                 strcpy(Value,"");
408                 ConfValue("connect","password",i,Value);
409                 strcpy(c.pass,Value);
410                 Classes.push_back(c);
411                 log(DEBUG,"Read connect class type ALLOW, host=%s password=%s",c.host,c.pass);
412         }
413         else
414         {
415                 ConfValue("connect","deny",i,Value);
416                 strcpy(c.host,Value);
417                 c.type = CC_DENY;
418                 Classes.push_back(c);
419                 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
420         }
421         
422   }
423 }
424
425 void Blocking(int s)
426 {
427   int flags;
428   log(DEBUG,"Blocking: %d",s);
429   flags = fcntl(s, F_GETFL, 0);
430   fcntl(s, F_SETFL, flags ^ O_NONBLOCK);
431 }
432
433 void NonBlocking(int s)
434 {
435   int flags;
436   log(DEBUG,"NonBlocking: %d",s);
437   flags = fcntl(s, F_GETFL, 0);
438   fcntl(s, F_SETFL, flags | O_NONBLOCK);
439 }
440
441
442 int CleanAndResolve (char *resolvedHost, const char *unresolvedHost)
443 {
444   struct hostent *hostPtr = NULL;
445   struct in_addr addr;
446
447   memset (resolvedHost, '\0',MAXBUF);
448   if(unresolvedHost == NULL)
449         return(ERROR);
450   if ((inet_aton(unresolvedHost,&addr)) == 0)
451         return(ERROR);
452   hostPtr = gethostbyaddr ((char *)&addr.s_addr,sizeof(addr.s_addr),AF_INET);
453   if (hostPtr != NULL)
454         snprintf(resolvedHost,MAXBUF,"%s",hostPtr->h_name);
455   else
456         snprintf(resolvedHost,MAXBUF,"%s",unresolvedHost);
457   return (TRUE);
458 }
459
460 /* write formatted text to a socket, in same format as printf */
461
462 void Write(int sock,char *text, ...)
463 {
464   char textbuffer[MAXBUF];
465   va_list argsPtr;
466   char tb[MAXBUF];
467
468   va_start (argsPtr, text);
469   vsnprintf(textbuffer, MAXBUF, text, argsPtr);
470   va_end(argsPtr);
471   sprintf(tb,"%s\r\n",textbuffer);
472   chop(tb);
473   write(sock,tb,strlen(tb));
474   update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
475 }
476
477 /* write a server formatted numeric response to a single socket */
478
479 void WriteServ(int sock, char* text, ...)
480 {
481   char textbuffer[MAXBUF],tb[MAXBUF];
482   va_list argsPtr;
483   va_start (argsPtr, text);
484
485   vsnprintf(textbuffer, MAXBUF, text, argsPtr);
486   va_end(argsPtr);
487   sprintf(tb,":%s %s\r\n",ServerName,textbuffer);
488   chop(tb);
489   write(sock,tb,strlen(tb));
490   update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
491 }
492
493 /* write text from an originating user to originating user */
494
495 void WriteFrom(int sock, userrec *user,char* text, ...)
496 {
497   char textbuffer[MAXBUF],tb[MAXBUF];
498   va_list argsPtr;
499   va_start (argsPtr, text);
500
501   vsnprintf(textbuffer, MAXBUF, text, argsPtr);
502   va_end(argsPtr);
503   sprintf(tb,":%s!%s@%s %s\r\n",user->nick,user->ident,user->dhost,textbuffer);
504   chop(tb);
505   write(sock,tb,strlen(tb));
506   update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
507 }
508
509 /* write text to an destination user from a source user (e.g. user privmsg) */
510
511 void WriteTo(userrec *source, userrec *dest,char *data, ...)
512 {
513         char textbuffer[MAXBUF],tb[MAXBUF];
514         va_list argsPtr;
515         va_start (argsPtr, data);
516         if ((!dest) || (!source))
517         {
518                 return;
519         }
520         vsnprintf(textbuffer, MAXBUF, data, argsPtr);
521         va_end(argsPtr);
522         chop(tb);
523         WriteFrom(dest->fd,source,"%s",textbuffer);
524 }
525
526 /* write formatted text from a source user to all users on a channel
527  * including the sender (NOT for privmsg, notice etc!) */
528
529 void WriteChannel(chanrec* Ptr, userrec* user, char* text, ...)
530 {
531         char textbuffer[MAXBUF];
532         va_list argsPtr;
533         va_start (argsPtr, text);
534         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
535         va_end(argsPtr);
536         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
537         {
538                 if (has_channel(i->second,Ptr))
539                 {
540                         WriteTo(user,i->second,"%s",textbuffer);
541                 }
542         }
543 }
544
545 void WriteChannelWithServ(char* ServerName, chanrec* Ptr, userrec* user, char* text, ...)
546 {
547         char textbuffer[MAXBUF];
548         va_list argsPtr;
549         va_start (argsPtr, text);
550         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
551         va_end(argsPtr);
552         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
553         {
554                 if (has_channel(i->second,Ptr))
555                 {
556                         WriteServ(i->second->fd,"%s",textbuffer);
557                 }
558         }
559 }
560
561
562 /* write formatted text from a source user to all users on a channel except
563  * for the sender (for privmsg etc) */
564
565 void ChanExceptSender(chanrec* Ptr, userrec* user, char* text, ...)
566 {
567         char textbuffer[MAXBUF];
568         va_list argsPtr;
569         va_start (argsPtr, text);
570         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
571         va_end(argsPtr);
572
573         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
574         {
575                 if (has_channel(i->second,Ptr) && (user != i->second))
576                 {
577                         WriteTo(user,i->second,"%s",textbuffer);
578                 }
579         }
580 }
581
582 int c_count(userrec* u)
583 {
584         int z = 0;
585         for (int i =0; i != MAXCHANS; i++)
586                 if (u->chans[i].channel)
587                         z++;
588         return z;
589
590 }
591
592 /* return 0 or 1 depending if users u and u2 share one or more common channels
593  * (used by QUIT, NICK etc which arent channel specific notices) */
594
595 int common_channels(userrec *u, userrec *u2)
596 {
597         int i = 0;
598         int z = 0;
599
600         if ((!u) || (!u2))
601         {
602                 return 0;
603         }
604         for (i = 0; i != MAXCHANS; i++)
605         {
606                 for (z = 0; z != MAXCHANS; z++)
607                 {
608                         if ((u->chans[i].channel == u2->chans[z].channel) && (u->chans[i].channel) && (u2->chans[z].channel) && (u->registered == 7) && (u2->registered == 7))
609                         {
610                                 if ((c_count(u)) && (c_count(u2)))
611                                 {
612                                         return 1;
613                                 }
614                         }
615                 }
616         }
617         return 0;
618 }
619
620 /* write a formatted string to all users who share at least one common
621  * channel, including the source user e.g. for use in NICK */
622
623 void WriteCommon(userrec *u, char* text, ...)
624 {
625         char textbuffer[MAXBUF];
626         va_list argsPtr;
627         va_start (argsPtr, text);
628         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
629         va_end(argsPtr);
630
631         WriteFrom(u->fd,u,"%s",textbuffer);
632
633         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
634         {
635                 if (common_channels(u,i->second) && (i->second != u))
636                 {
637                         WriteFrom(i->second->fd,u,"%s",textbuffer);
638                 }
639         }
640 }
641
642 /* write a formatted string to all users who share at least one common
643  * channel, NOT including the source user e.g. for use in QUIT */
644
645 void WriteCommonExcept(userrec *u, char* text, ...)
646 {
647         char textbuffer[MAXBUF];
648         va_list argsPtr;
649         va_start (argsPtr, text);
650         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
651         va_end(argsPtr);
652
653         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
654         {
655                 if ((common_channels(u,i->second)) && (u != i->second))
656                 {
657                         WriteFrom(i->second->fd,u,"%s",textbuffer);
658                 }
659         }
660 }
661
662 void WriteOpers(char* text, ...)
663 {
664         char textbuffer[MAXBUF];
665         va_list argsPtr;
666         va_start (argsPtr, text);
667         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
668         va_end(argsPtr);
669
670         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
671         {
672                 if (strchr(i->second->modes,'o'))
673                 {
674                         if (strchr(i->second->modes,'s'))
675                         {
676                                 // send server notices to all with +s
677                                 // (TODO: needs SNOMASKs)
678                                 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
679                         }
680                 }
681         }
682 }
683
684 void WriteWallOps(userrec *source, char* text, ...)  
685 {  
686         int i = 0;  
687         char textbuffer[MAXBUF];  
688         va_list argsPtr;  
689         va_start (argsPtr, text);  
690         vsnprintf(textbuffer, MAXBUF, text, argsPtr);  
691         va_end(argsPtr);  
692   
693         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
694         {  
695                 if (strchr(i->second->modes,'w'))
696                 {  
697                         WriteTo(source,i->second,"WALLOPS %s",textbuffer);
698                 }
699         }
700 }  
701
702 /* convert a string to lowercase. Note following special circumstances
703  * taken from RFC 1459. Many "official" server branches still hold to this
704  * rule so i will too;
705  *
706  *  Because of IRC's scandanavian origin, the characters {}| are
707  *  considered to be the lower case equivalents of the characters []\,
708  *  respectively. This is a critical issue when determining the
709  *  equivalence of two nicknames.
710  */
711
712 void strlower(char *n)
713 {
714         if (!n)
715         {
716                 return;
717         }
718         for (int i = 0; i != strlen(n); i++)
719         {
720                 n[i] = tolower(n[i]);
721                 if (n[i] == '[')
722                         n[i] = '{';
723                 if (n[i] == ']')
724                         n[i] = '}';
725                 if (n[i] == '\\')
726                         n[i] = '|';
727         }
728 }
729
730 /* verify that a user's ident and nickname is valid */
731
732 int isident(const char* n)
733 {
734         int i = 0;
735         char v[MAXBUF];
736         if (!n)
737
738         {
739                 return 0;
740         }
741         if (!strcmp(n,""))
742         {
743                 return 0;
744         }
745         for (i = 0; i != strlen(n); i++)
746         {
747                 if ((n[i] < 33) || (n[i] > 125))
748                 {
749                         return 0;
750                 }
751                 /* can't occur ANYWHERE in an Ident! */
752                 if (strchr("<>,./?:;@'~#=+()*&%$£ \"!",n[i]))
753                 {
754                         return 0;
755                 }
756         }
757         return 1;
758 }
759
760
761 int isnick(const char* n)
762 {
763         int i = 0;
764         char v[MAXBUF];
765         if (!n)
766         {
767                 return 0;
768         }
769         if (!strcmp(n,""))
770         {
771                 return 0;
772         }
773         if (strlen(n) > NICKMAX-1)
774         {
775                 return 0;
776         }
777         for (i = 0; i != strlen(n); i++)
778         {
779                 if ((n[i] < 33) || (n[i] > 125))
780                 {
781                         return 0;
782                 }
783                 /* can't occur ANYWHERE in a nickname! */
784                 if (strchr("<>,./?:;@'~#=+()*&%$£ \"!",n[i]))
785                 {
786                         return 0;
787                 }
788                 /* can't occur as the first char of a nickname... */
789                 if ((strchr("0123456789",n[i])) && (!i))
790                 {
791                         return 0;
792                 }
793         }
794         return 1;
795 }
796
797 /* Find a user record by nickname and return a pointer to it */
798
799 userrec* Find(string nick)
800 {
801         user_hash::iterator iter = clientlist.find(nick);
802
803         if (iter == clientlist.end())
804                 /* Couldn't find it */
805                 return NULL;
806
807         return iter->second;
808 }
809
810 void update_stats_l(int fd,int data_out) /* add one line-out to stats L for this fd */
811 {
812         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
813         {
814                 if (i->second->fd == fd)
815                 {
816                         i->second->bytes_out+=data_out;
817                         i->second->cmds_out++;
818                 }
819         }
820 }
821
822
823 /* find a channel record by channel name and return a pointer to it */
824
825 chanrec* FindChan(const char* chan)
826 {
827         chan_hash::iterator iter = chanlist.find(chan);
828
829         if (iter == chanlist.end())
830                 /* Couldn't find it */
831                 return NULL;
832
833         return iter->second;
834 }
835
836
837 void purge_empty_chans(void)
838 {
839         int go_again = 1, purge = 0;
840         
841         while (go_again)
842         {
843                 go_again = 0;
844                 for (chan_hash::iterator i = chanlist.begin(); i != chanlist.end(); i++)
845                 {
846                         if (i->second) {
847                                 if (!usercount(i->second))
848                                 {
849                                         /* kill the record */
850                                         if (i != chanlist.end())
851                                         {
852                                                 log(DEBUG,"del_channel: destroyed: %s",i->second->name);
853                                                 delete i->second;
854                                                 chanlist.erase(i);
855                                                 go_again = 1;
856                                                 purge++;
857                                                 break;
858                                         }
859                                 }
860                         }
861                 }
862         }
863         log(DEBUG,"completed channel purge, killed %d",purge);
864 }
865
866 /* returns the status character for a given user on a channel, e.g. @ for op,
867  * % for halfop etc. If the user has several modes set, the highest mode
868  * the user has must be returned. */
869
870 char* cmode(userrec *user, chanrec *chan)
871 {
872         int i;
873         for (i = 0; i != MAXCHANS; i++)
874         {
875                 if ((user->chans[i].channel == chan) && (chan != NULL))
876                 {
877                         if ((user->chans[i].uc_modes & UCMODE_OP) > 0)
878                         {
879                                 return "@";
880                         }
881                         if ((user->chans[i].uc_modes & UCMODE_HOP) > 0)
882                         {
883                                 return "%";
884                         }
885                         if ((user->chans[i].uc_modes & UCMODE_VOICE) > 0)
886                         {
887                                 return "+";
888                         }
889                         return "";
890                 }
891         }
892 }
893
894 char scratch[MAXMODES];
895 char sparam[MAXMODES];
896
897 char* chanmodes(chanrec *chan)
898 {
899         strcpy(scratch,"");
900         strcpy(sparam,"");
901         if (chan->noexternal)
902         {
903                 strcat(scratch,"n");
904         }
905         if (chan->topiclock)
906         {
907                 strcat(scratch,"t");
908         }
909         if (strcmp(chan->key,""))
910         {
911                 strcat(scratch,"k");
912         }
913         if (chan->limit)
914         {
915                 strcat(scratch,"l");
916         }
917         if (chan->inviteonly)
918         {
919                 strcat(scratch,"i");
920         }
921         if (chan->moderated)
922         {
923                 strcat(scratch,"m");
924         }
925         if (chan->secret)
926         {
927                 strcat(scratch,"s");
928         }
929         if (chan->c_private)
930         {
931                 strcat(scratch,"p");
932         }
933         if (strcmp(chan->key,""))
934         {
935                 strcat(sparam,chan->key);
936         }
937         if (chan->limit)
938         {
939                 char foo[24];
940                 sprintf(foo," %d",chan->limit);
941                 strcat(sparam,foo);
942         }
943         if (strlen(chan->custom_modes))
944         {
945                 // TODO: Tack on mode parameters here -
946                 // IN ORDER OF CUSTOM_MODES!
947                 strncat(scratch,chan->custom_modes,MAXMODES);
948         }
949         log(DEBUG,"chanmodes: %s %s%s",chan->name,scratch,sparam);
950         strncat(scratch,sparam,MAXMODES);
951         return scratch;
952 }
953
954 /* returns the status value for a given user on a channel, e.g. STATUS_OP for
955  * op, STATUS_VOICE for voice etc. If the user has several modes set, the
956  * highest mode the user has must be returned. */
957
958 int cstatus(userrec *user, chanrec *chan)
959 {
960         int i;
961         for (i = 0; i != MAXCHANS; i++)
962         {
963                 if ((user->chans[i].channel == chan) && (chan != NULL))
964                 {
965                         if ((user->chans[i].uc_modes & UCMODE_OP) > 0)
966                         {
967                                 return STATUS_OP;
968                         }
969                         if ((user->chans[i].uc_modes & UCMODE_HOP) > 0)
970                         {
971                                 return STATUS_HOP;
972                         }
973                         if ((user->chans[i].uc_modes & UCMODE_VOICE) > 0)
974                         {
975                                 return STATUS_VOICE;
976                         }
977                         return STATUS_NORMAL;
978                 }
979         }
980 }
981
982
983 /* compile a userlist of a channel into a string, each nick seperated by
984  * spaces and op, voice etc status shown as @ and + */
985
986 void userlist(userrec *user,chanrec *c)
987 {
988         sprintf(list,"353 %s = %s :", user->nick, c->name);
989         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
990         {
991                 if (has_channel(i->second,c))
992                 {
993                         if (isnick(i->second->nick))
994                         {
995                                 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
996                                 {
997                                         /* user is +i, and source not on the channel, does not show
998                                          * nick in NAMES list */
999                                         continue;
1000                                 }
1001                                 strcat(list,cmode(i->second,c));
1002                                 strcat(list,i->second->nick);
1003                                 strcat(list," ");
1004                                 if (strlen(list)>(480-NICKMAX))
1005                                 {
1006                                         /* list overflowed into
1007                                          * multiple numerics */
1008                                         WriteServ(user->fd,list);
1009                                         sprintf(list,"353 %s = %s :", user->nick, c->name);
1010                                 }
1011                         }
1012                 }
1013         }
1014         /* if whats left in the list isnt empty, send it */
1015         if (list[strlen(list)-1] != ':')
1016         {
1017                 WriteServ(user->fd,list);
1018         }
1019 }
1020
1021 /* return a count of the users on a specific channel accounting for
1022  * invisible users who won't increase the count. e.g. for /LIST */
1023
1024 int usercount_i(chanrec *c)
1025 {
1026         int i = 0;
1027         int count = 0;
1028
1029         strcpy(list,"");
1030         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1031         {
1032                 if (i->second)
1033                 {
1034                         if (has_channel(i->second,c))
1035                         {
1036                                 if (isnick(i->second->nick))
1037                                 {
1038                                         if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1039                                         {
1040                                                 /* user is +i, and source not on the channel, does not show
1041                                                  * nick in NAMES list */
1042                                                 continue;
1043                                         }
1044                                         count++;
1045                                 }
1046                         }
1047                 }
1048         }
1049         log(DEBUG,"usercount_i: %s %d",c->name,count);
1050         return count;
1051 }
1052
1053
1054 int usercount(chanrec *c)
1055 {
1056         int i = 0;
1057         int count = 0;
1058
1059         strcpy(list,"");
1060         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1061         {
1062                 if (i->second)
1063                 {
1064                         if (has_channel(i->second,c))
1065                         {
1066                                 if ((isnick(i->second->nick)) && (i->second->registered == 7))
1067                                 {
1068                                         count++;
1069                                 }
1070                         }
1071                 }
1072         }
1073         log(DEBUG,"usercount: %s %d",c->name,count);
1074         return count;
1075 }
1076
1077
1078 /* add a channel to a user, creating the record for it if needed and linking
1079  * it to the user record */
1080
1081 chanrec* add_channel(userrec *user, char* cname, char* key)
1082 {
1083         int i = 0;
1084         chanrec* Ptr;
1085         int created = 0;
1086         
1087         // we MUST declare this wherever we use FOREACH_RESULT
1088         int MOD_RESULT = 0;
1089
1090         if ((!cname) || (!user))
1091         {
1092                 return NULL;
1093         }
1094         if (strlen(cname) > CHANMAX-1)
1095         {
1096                 cname[CHANMAX-1] = '\0';
1097         }
1098
1099         log(DEBUG,"add_channel: %s %s",user->nick,cname);
1100         
1101         if ((has_channel(user,FindChan(cname))) && (FindChan(cname)))
1102         {
1103                 return NULL; // already on the channel!
1104         }
1105
1106
1107         if (!FindChan(cname))
1108         {
1109                 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
1110                 if (MOD_RESULT) {
1111                         return NULL;
1112                 }
1113
1114                 /* create a new one */
1115                 log(DEBUG,"add_channel: creating: %s",cname);
1116                 {
1117                         chanlist[cname] = new chanrec();
1118
1119                         strcpy(chanlist[cname]->name, cname);
1120                         chanlist[cname]->topiclock = 1;
1121                         chanlist[cname]->noexternal = 1;
1122                         chanlist[cname]->created = time(NULL);
1123                         strcpy(chanlist[cname]->topic, "");
1124                         strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
1125                         chanlist[cname]->topicset = 0;
1126                         Ptr = chanlist[cname];
1127                         log(DEBUG,"add_channel: created: %s",cname);
1128                         /* set created to 2 to indicate user
1129                          * is the first in the channel
1130                          * and should be given ops */
1131                         created = 2;
1132                 }
1133         }
1134         else
1135         {
1136                 /* channel exists, just fish out a pointer to its struct */
1137                 Ptr = FindChan(cname);
1138                 if (Ptr)
1139                 {
1140                         FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
1141                         if (MOD_RESULT) {
1142                                 return NULL;
1143                         }
1144                         
1145                         log(DEBUG,"add_channel: joining to: %s",Ptr->name);
1146                         if (strcmp(Ptr->key,""))
1147                         {
1148                                 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
1149                                 if (!key)
1150                                 {
1151                                         log(DEBUG,"add_channel: no key given in JOIN");
1152                                         WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
1153                                         return NULL;
1154                                 }
1155                                 else
1156                                 {
1157                                         log(DEBUG,"key at %p is %s",key,key);
1158                                         if (strcasecmp(key,Ptr->key))
1159                                         {
1160                                                 log(DEBUG,"add_channel: bad key given in JOIN");
1161                                                 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
1162                                                 return NULL;
1163                                         }
1164                                 }
1165                         }
1166                         log(DEBUG,"add_channel: no key");
1167
1168                         if (Ptr->inviteonly)
1169                         {
1170                                 log(DEBUG,"add_channel: channel is +i");
1171                                 if (user->IsInvited(Ptr->name))
1172                                 {
1173                                         /* user was invited to channel */
1174                                         /* there may be an optional channel NOTICE here */
1175                                 }
1176                                 else
1177                                 {
1178                                         WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
1179                                         return NULL;
1180                                 }
1181                         }
1182                         log(DEBUG,"add_channel: channel is not +i");
1183
1184                         if (Ptr->limit)
1185                         {
1186                                 if (usercount(Ptr) == Ptr->limit)
1187                                 {
1188                                         WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
1189                                         return NULL;
1190                                 }
1191                         }
1192                         
1193                         log(DEBUG,"add_channel: about to walk banlist");
1194
1195                         /* check user against the channel banlist */
1196                         for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
1197                         {
1198                                 if (match(user->GetFullHost(),i->data))
1199                                 {
1200                                         WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
1201                                         return NULL;
1202                                 }
1203                         }
1204
1205                         log(DEBUG,"add_channel: bans checked");
1206
1207                         user->RemoveInvite(Ptr->name);
1208
1209                         log(DEBUG,"add_channel: invites removed");
1210                         
1211                 }
1212                 created = 1;
1213         }
1214
1215         log(DEBUG,"Passed channel checks");
1216         
1217         for (i =0; i != MAXCHANS; i++)
1218         {
1219                 if (user->chans[i].channel == NULL)
1220                 {
1221                         log(DEBUG,"Adding into their channel list");
1222
1223                         if (created == 2) 
1224                         {
1225                                 /* first user in is given ops */
1226                                 user->chans[i].uc_modes = UCMODE_OP;
1227                         }
1228                         else
1229                         {
1230                                 user->chans[i].uc_modes = 0;
1231                         }
1232                         user->chans[i].channel = Ptr;
1233                         WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
1234
1235                         log(DEBUG,"Sent JOIN to client");
1236
1237                         if (Ptr->topicset)
1238                         {
1239                                 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
1240                                 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
1241                         }
1242                         userlist(user,Ptr);
1243                         WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
1244                         WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
1245                         WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
1246                         FOREACH_MOD OnUserJoin(user,Ptr);
1247                         return Ptr;
1248                 }
1249         }
1250         log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
1251         WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
1252         return NULL;
1253 }
1254
1255 /* remove a channel from a users record, and remove the record from memory
1256  * if the channel has become empty */
1257
1258 chanrec* del_channel(userrec *user, char* cname, char* reason)
1259 {
1260         int i = 0;
1261         chanrec* Ptr;
1262         int created = 0;
1263
1264         if ((!cname) || (!user))
1265         {
1266                 return NULL;
1267         }
1268
1269         Ptr = FindChan(cname);
1270         
1271         if (!Ptr)
1272         {
1273                 return NULL;
1274         }
1275
1276         FOREACH_MOD OnUserPart(user,Ptr);
1277         log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
1278         
1279         for (i =0; i != MAXCHANS; i++)
1280         {
1281                 /* zap it from the channel list of the user */
1282                 if (user->chans[i].channel == Ptr)
1283                 {
1284                         if (reason)
1285                         {
1286                                 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
1287                         }
1288                         else
1289                         {
1290                                 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
1291                         }
1292                         user->chans[i].uc_modes = 0;
1293                         user->chans[i].channel = NULL;
1294                         log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1295                         break;
1296                 }
1297         }
1298         
1299         /* if there are no users left on the channel */
1300         if (!usercount(Ptr))
1301         {
1302                 chan_hash::iterator iter = chanlist.find(Ptr->name);
1303
1304                 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1305
1306                 /* kill the record */
1307                 if (iter != chanlist.end())
1308                 {
1309                         log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1310                         delete iter->second;
1311                         chanlist.erase(iter);
1312                 }
1313         }
1314 }
1315
1316
1317 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
1318 {
1319         int i = 0;
1320         int created = 0;
1321
1322         if ((!Ptr) || (!user) || (!src))
1323         {
1324                 return;
1325         }
1326
1327         log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
1328
1329         if (!has_channel(user,Ptr))
1330         {
1331                 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
1332                 return;
1333         }
1334         if ((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr)))
1335         {
1336                 if (cstatus(src,Ptr) == STATUS_HOP)
1337                 {
1338                         WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
1339                 }
1340                 else
1341                 {
1342                         WriteServ(src->fd,"482 %s %s :You must be at least a half-operator",src->nick, Ptr->name);
1343                 }
1344                 
1345                 return;
1346         }
1347         
1348         for (i =0; i != MAXCHANS; i++)
1349         {
1350                 /* zap it from the channel list of the user */
1351                 if (user->chans[i].channel == Ptr)
1352                 {
1353                         WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
1354                         user->chans[i].uc_modes = 0;
1355                         user->chans[i].channel = NULL;
1356                         log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1357                         break;
1358                 }
1359         }
1360         
1361         /* if there are no users left on the channel */
1362         if (!usercount(Ptr))
1363         {
1364                 chan_hash::iterator iter = chanlist.find(Ptr->name);
1365
1366                 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1367
1368                 /* kill the record */
1369                 if (iter != chanlist.end())
1370                 {
1371                         log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1372                         delete iter->second;
1373                         chanlist.erase(iter);
1374                 }
1375         }
1376 }
1377
1378
1379 /* returns 1 if user u has channel c in their record, 0 if not */
1380
1381 int has_channel(userrec *u, chanrec *c)
1382 {
1383         int i = 0;
1384
1385         if (!u)
1386         {
1387                 return 0;
1388         }
1389         for (i =0; i != MAXCHANS; i++)
1390         {
1391                 if (u->chans[i].channel == c)
1392                 {
1393                         return 1;
1394                 }
1395         }
1396         return 0;
1397 }
1398
1399 int give_ops(userrec *user,char *dest,chanrec *chan,int status)
1400 {
1401         userrec *d;
1402         int i;
1403         
1404         if ((!user) || (!dest) || (!chan))
1405         {
1406                 return 0;
1407         }
1408         if (status != STATUS_OP)
1409         {
1410                 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1411                 return 0;
1412         }
1413         else
1414         {
1415                 if (!isnick(dest))
1416                 {
1417                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1418                         return 0;
1419                 }
1420                 d = Find(dest);
1421                 if (!d)
1422                 {
1423                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1424                         return 0;
1425                 }
1426                 else
1427                 {
1428                         for (i = 0; i != MAXCHANS; i++)
1429                         {
1430                                 if ((d->chans[i].channel == chan) && (chan != NULL))
1431                                 {
1432                                         if (d->chans[i].uc_modes & UCMODE_OP)
1433                                         {
1434                                                 /* mode already set on user, dont allow multiple */
1435                                                 return 0;
1436                                         }
1437                                         d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_OP;
1438                                         log(DEBUG,"gave ops: %s %s",d->chans[i].channel->name,d->nick);
1439                                 }
1440                         }
1441                 }
1442         }
1443         return 1;
1444 }
1445
1446 int give_hops(userrec *user,char *dest,chanrec *chan,int status)
1447 {
1448         userrec *d;
1449         int i;
1450         
1451         if ((!user) || (!dest) || (!chan))
1452         {
1453                 return 0;
1454         }
1455         if (status != STATUS_OP)
1456         {
1457                 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1458                 return 0;
1459         }
1460         else
1461         {
1462                 d = Find(dest);
1463                 if (!isnick(dest))
1464                 {
1465                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1466                         return 0;
1467                 }
1468                 if (!d)
1469                 {
1470                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1471                         return 0;
1472                 }
1473                 else
1474                 {
1475                         for (i = 0; i != MAXCHANS; i++)
1476                         {
1477                                 if ((d->chans[i].channel == chan) && (chan != NULL))
1478                                 {
1479                                         if (d->chans[i].uc_modes & UCMODE_HOP)
1480                                         {
1481                                                 /* mode already set on user, dont allow multiple */
1482                                                 return 0;
1483                                         }
1484                                         d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_HOP;
1485                                         log(DEBUG,"gave h-ops: %s %s",d->chans[i].channel->name,d->nick);
1486                                 }
1487                         }
1488                 }
1489         }
1490         return 1;
1491 }
1492
1493 int give_voice(userrec *user,char *dest,chanrec *chan,int status)
1494 {
1495         userrec *d;
1496         int i;
1497         
1498         if ((!user) || (!dest) || (!chan))
1499         {
1500                 return 0;
1501         }
1502         if (status < STATUS_HOP)
1503         {
1504                 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator",user->nick, chan->name);
1505                 return 0;
1506         }
1507         else
1508         {
1509                 d = Find(dest);
1510                 if (!isnick(dest))
1511                 {
1512                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1513                         return 0;
1514                 }
1515                 if (!d)
1516                 {
1517                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1518                         return 0;
1519                 }
1520                 else
1521                 {
1522                         for (i = 0; i != MAXCHANS; i++)
1523                         {
1524                                 if ((d->chans[i].channel == chan) && (chan != NULL))
1525                                 {
1526                                         if (d->chans[i].uc_modes & UCMODE_VOICE)
1527                                         {
1528                                                 /* mode already set on user, dont allow multiple */
1529                                                 return 0;
1530                                         }
1531                                         d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_VOICE;
1532                                         log(DEBUG,"gave voice: %s %s",d->chans[i].channel->name,d->nick);
1533                                 }
1534                         }
1535                 }
1536         }
1537         return 1;
1538 }
1539
1540 int take_ops(userrec *user,char *dest,chanrec *chan,int status)
1541 {
1542         userrec *d;
1543         int i;
1544         
1545         if ((!user) || (!dest) || (!chan))
1546         {
1547                 return 0;
1548         }
1549         if (status != STATUS_OP)
1550         {
1551                 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1552                 return 0;
1553         }
1554         else
1555         {
1556                 d = Find(dest);
1557                 if (!isnick(dest))
1558                 {
1559                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1560                         return 0;
1561                 }
1562                 if (!d)
1563                 {
1564                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1565                         return 0;
1566                 }
1567                 else
1568                 {
1569                         for (i = 0; i != MAXCHANS; i++)
1570                         {
1571                                 if ((d->chans[i].channel == chan) && (chan != NULL))
1572                                 {
1573                                         if ((d->chans[i].uc_modes & UCMODE_OP) == 0)
1574                                         {
1575                                                 /* mode already set on user, dont allow multiple */
1576                                                 return 0;
1577                                         }
1578                                         d->chans[i].uc_modes ^= UCMODE_OP;
1579                                         log(DEBUG,"took ops: %s %s",d->chans[i].channel->name,d->nick);
1580                                 }
1581                         }
1582                 }
1583         }
1584         return 1;
1585 }
1586
1587 int take_hops(userrec *user,char *dest,chanrec *chan,int status)
1588 {
1589         userrec *d;
1590         int i;
1591         
1592         if ((!user) || (!dest) || (!chan))
1593         {
1594                 return 0;
1595         }
1596         if (status != STATUS_OP)
1597         {
1598                 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1599                 return 0;
1600         }
1601         else
1602         {
1603                 d = Find(dest);
1604                 if (!isnick(dest))
1605                 {
1606                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1607                         return 0;
1608                 }
1609                 if (!d)
1610                 {
1611                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1612                         return 0;
1613                 }
1614                 else
1615                 {
1616                         for (i = 0; i != MAXCHANS; i++)
1617                         {
1618                                 if ((d->chans[i].channel == chan) && (chan != NULL))
1619                                 {
1620                                         if ((d->chans[i].uc_modes & UCMODE_HOP) == 0)
1621                                         {
1622                                                 /* mode already set on user, dont allow multiple */
1623                                                 return 0;
1624                                         }
1625                                         d->chans[i].uc_modes ^= UCMODE_HOP;
1626                                         log(DEBUG,"took h-ops: %s %s",d->chans[i].channel->name,d->nick);
1627                                 }
1628                         }
1629                 }
1630         }
1631         return 1;
1632 }
1633
1634 int take_voice(userrec *user,char *dest,chanrec *chan,int status)
1635 {
1636         userrec *d;
1637         int i;
1638         
1639         if ((!user) || (!dest) || (!chan))
1640         {
1641                 return 0;
1642         }
1643         if (status < STATUS_HOP)
1644         {
1645                 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator",user->nick, chan->name);
1646                 return 0;
1647         }
1648         else
1649         {
1650                 d = Find(dest);
1651                 if (!isnick(dest))
1652                 {
1653                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1654                         return 0;
1655                 }
1656                 if (!d)
1657                 {
1658                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1659                         return 0;
1660                 }
1661                 else
1662                 {
1663                         for (i = 0; i != MAXCHANS; i++)
1664                         {
1665                                 if ((d->chans[i].channel == chan) && (chan != NULL))
1666                                 {
1667                                         if ((d->chans[i].uc_modes & UCMODE_VOICE) == 0)
1668                                         {
1669                                                 /* mode already set on user, dont allow multiple */
1670                                                 return 0;
1671                                         }
1672                                         d->chans[i].uc_modes ^= UCMODE_VOICE;
1673                                         log(DEBUG,"took voice: %s %s",d->chans[i].channel->name,d->nick);
1674                                 }
1675                         }
1676                 }
1677         }
1678         return 1;
1679 }
1680
1681 void TidyBan(char *ban)
1682 {
1683         char temp[MAXBUF],NICK[MAXBUF],IDENT[MAXBUF],HOST[MAXBUF];
1684
1685         strcpy(temp,ban);
1686
1687         char* pos_of_pling = strchr(temp,'!');
1688         char* pos_of_at = strchr(temp,'@');
1689
1690         pos_of_pling[0] = '\0';
1691         pos_of_at[0] = '\0';
1692         pos_of_pling++;
1693         pos_of_at++;
1694
1695         strncpy(NICK,temp,NICKMAX);
1696         strncpy(IDENT,pos_of_pling,IDENTMAX+1);
1697         strncpy(HOST,pos_of_at,160);
1698
1699         sprintf(ban,"%s!%s@%s",NICK,IDENT,HOST);
1700 }
1701
1702 int add_ban(userrec *user,char *dest,chanrec *chan,int status)
1703 {
1704         BanItem b;
1705         if ((!user) || (!dest) || (!chan))
1706                 return 0;
1707         if (strchr(dest,'!')==0)
1708                 return 0;
1709         if (strchr(dest,'@')==0)
1710                 return 0;
1711         for (int i = 0; i < strlen(dest); i++)
1712                 if (dest[i] < 32)
1713                         return 0;
1714         for (int i = 0; i < strlen(dest); i++)
1715                 if (dest[i] > 126)
1716                         return 0;
1717         int c = 0;
1718         for (int i = 0; i < strlen(dest); i++)
1719                 if (dest[i] == '!')
1720                         c++;
1721         if (c>1)
1722                 return 0;
1723         c = 0;
1724         for (int i = 0; i < strlen(dest); i++)
1725                 if (dest[i] == '@')
1726                         c++;
1727         if (c>1)
1728                 return 0;
1729         log(DEBUG,"add_ban: %s %s",chan->name,user->nick);
1730
1731         TidyBan(dest);
1732         for (BanList::iterator i = chan->bans.begin(); i != chan->bans.end(); i++)
1733         {
1734                 if (!strcasecmp(i->data,dest))
1735                 {
1736                         // dont allow a user to set the same ban twice
1737                         return 0;
1738                 }
1739         }
1740
1741         b.set_time = time(NULL);
1742         strncpy(b.data,dest,MAXBUF);
1743         strncpy(b.set_by,user->nick,NICKMAX);
1744         chan->bans.push_back(b);
1745         return 1;
1746 }
1747
1748 int take_ban(userrec *user,char *dest,chanrec *chan,int status)
1749 {
1750         if ((!user) || (!dest) || (!chan))
1751         {
1752                 return 0;
1753         }
1754
1755         log(DEBUG,"del_ban: %s %s",chan->name,user->nick);
1756         for (BanList::iterator i = chan->bans.begin(); i != chan->bans.end(); i++)
1757         {
1758                 if (!strcasecmp(i->data,dest))
1759                 {
1760                         chan->bans.erase(i);
1761                         return 1;
1762                 }
1763         }
1764         return 0;
1765 }
1766
1767 void process_modes(char **parameters,userrec* user,chanrec *chan,int status, int pcnt, bool servermode)
1768 {
1769         char modelist[MAXBUF];
1770         char outlist[MAXBUF];
1771         char outstr[MAXBUF];
1772         char outpars[32][MAXBUF];
1773         int param = 2;
1774         int pc = 0;
1775         int ptr = 0;
1776         int mdir = 1;
1777         int r = 0;
1778         bool k_set = false, l_set = false;
1779
1780         if (pcnt < 2)
1781         {
1782                 return;
1783         }
1784
1785         log(DEBUG,"process_modes: start");
1786
1787         strcpy(modelist,parameters[1]); /* mode list, e.g. +oo-o */
1788                                         /* parameters[2] onwards are parameters for
1789                                          * modes that require them :) */
1790         strcpy(outlist,"+");
1791         mdir = 1;
1792
1793         log(DEBUG,"process_modes: modelist: %s",modelist);
1794
1795         for (ptr = 0; ptr < strlen(modelist); ptr++)
1796         {
1797                 r = 0;
1798
1799                 {
1800                         log(DEBUG,"process_modes: modechar: %c",modelist[ptr]);
1801                         char modechar = modelist[ptr];
1802                         switch (modelist[ptr])
1803                         {
1804                                 case '-':
1805                                         if (mdir != 0)
1806                                         {
1807                                                 if ((outlist[strlen(outlist)-1] == '+') || (outlist[strlen(outlist)-1] == '-'))
1808                                                 {
1809                                                         outlist[strlen(outlist)-1] = '-';
1810                                                 }
1811                                                 else
1812                                                 {
1813                                                         strcat(outlist,"-");
1814                                                 }
1815                                         }
1816                                         mdir = 0;
1817                                         
1818                                 break;                  
1819
1820                                 case '+':
1821                                         if (mdir != 1)
1822                                         {
1823                                                 if ((outlist[strlen(outlist)-1] == '+') || (outlist[strlen(outlist)-1] == '-'))
1824                                                 {
1825                                                         outlist[strlen(outlist)-1] = '+';
1826                                                 }
1827                                                 else
1828                                                 {
1829                                                         strcat(outlist,"+");
1830                                                 }
1831                                         }
1832                                         mdir = 1;
1833                                 break;
1834
1835                                 case 'o':
1836                                         if ((param >= pcnt)) break;
1837                                         if (mdir == 1)
1838                                         {
1839                                                 r = give_ops(user,parameters[param++],chan,status);
1840                                         }
1841                                         else
1842                                         {
1843                                                 r = take_ops(user,parameters[param++],chan,status);
1844                                         }
1845                                         if (r)
1846                                         {
1847                                                 strcat(outlist,"o");
1848                                                 strcpy(outpars[pc++],parameters[param-1]);
1849                                         }
1850                                 break;
1851                         
1852                                 case 'h':
1853                                         if ((param >= pcnt)) break;
1854                                         if (mdir == 1)
1855                                         {
1856                                                 r = give_hops(user,parameters[param++],chan,status);
1857                                         }
1858                                         else
1859                                         {
1860                                                 r = take_hops(user,parameters[param++],chan,status);
1861                                         }
1862                                         if (r)
1863                                         {
1864                                                 strcat(outlist,"h");
1865                                                 strcpy(outpars[pc++],parameters[param-1]);
1866                                         }
1867                                 break;
1868                         
1869                                 
1870                                 case 'v':
1871                                         if ((param >= pcnt)) break;
1872                                         if (mdir == 1)
1873                                         {
1874                                                 r = give_voice(user,parameters[param++],chan,status);
1875                                         }
1876                                         else
1877                                         {
1878                                                 r = take_voice(user,parameters[param++],chan,status);
1879                                         }
1880                                         if (r)
1881                                         {
1882                                                 strcat(outlist,"v");
1883                                                 strcpy(outpars[pc++],parameters[param-1]);
1884                                         }
1885                                 break;
1886                                 
1887                                 case 'b':
1888                                         if ((param >= pcnt)) break;
1889                                         if (mdir == 1)
1890                                         {
1891                                                 r = add_ban(user,parameters[param++],chan,status);
1892                                         }
1893                                         else
1894                                         {
1895                                                 r = take_ban(user,parameters[param++],chan,status);
1896                                         }
1897                                         if (r)
1898                                         {
1899                                                 strcat(outlist,"b");
1900                                                 strcpy(outpars[pc++],parameters[param-1]);
1901                                         }
1902                                 break;
1903
1904                                 case 'k':
1905                                         if ((param >= pcnt))
1906                                                 break;
1907
1908                                         if (mdir == 1)
1909                                         {
1910                                                 if (k_set)
1911                                                         break;
1912                                                 
1913                                                 if (!strcmp(chan->key,""))
1914                                                 {
1915                                                         strcat(outlist,"k");
1916                                                         strcpy(outpars[pc++],parameters[param++]);
1917                                                         strcpy(chan->key,parameters[param-1]);
1918                                                         k_set = true;
1919                                                 }
1920                                         }
1921                                         else
1922                                         {
1923                                                 /* only allow -k if correct key given */
1924                                                 if (strcmp(chan->key,""))
1925                                                 {
1926                                                         strcat(outlist,"k");
1927                                                         strcpy(chan->key,"");
1928                                                 }
1929                                         }
1930                                 break;
1931                                 
1932                                 case 'l':
1933                                         if (mdir == 0)
1934                                         {
1935                                                 if (chan->limit)
1936                                                 {
1937                                                         strcat(outlist,"l");
1938                                                         chan->limit = 0;
1939                                                 }
1940                                         }
1941                                         
1942                                         if ((param >= pcnt)) break;
1943                                         if (mdir == 1)
1944                                         {
1945                                                 if (l_set)
1946                                                         break;
1947                                                 
1948                                                 bool invalid = false;
1949                                                 for (int i = 0; i < strlen(parameters[param]); i++)
1950                                                 {
1951                                                         if ((parameters[param][i] < '0') || (parameters[param][i] > '9'))
1952                                                         {
1953                                                                 invalid = true;
1954                                                         }
1955                                                 }
1956                                                 if (atoi(parameters[param]) < 1)
1957                                                 {
1958                                                         invalid = true;
1959                                                 }
1960
1961                                                 if (invalid)
1962                                                         break;
1963                                                 
1964                                                 chan->limit = atoi(parameters[param]);
1965                                                 if (chan->limit)
1966                                                 {
1967                                                         strcat(outlist,"l");
1968                                                         strcpy(outpars[pc++],parameters[param++]);
1969                                                         l_set = true;
1970                                                 }
1971                                         }
1972                                 break;
1973                                 
1974                                 case 'i':
1975                                         if (chan->inviteonly != mdir)
1976                                         {
1977                                                 strcat(outlist,"i");
1978                                         }
1979                                         chan->inviteonly = mdir;
1980                                 break;
1981                                 
1982                                 case 't':
1983                                         if (chan->topiclock != mdir)
1984                                         {
1985                                                 strcat(outlist,"t");
1986                                         }
1987                                         chan->topiclock = mdir;
1988                                 break;
1989                                 
1990                                 case 'n':
1991                                         if (chan->noexternal != mdir)
1992                                         {
1993                                                 strcat(outlist,"n");
1994                                         }
1995                                         chan->noexternal = mdir;
1996                                 break;
1997                                 
1998                                 case 'm':
1999                                         if (chan->moderated != mdir)
2000                                         {
2001                                                 strcat(outlist,"m");
2002                                         }
2003                                         chan->moderated = mdir;
2004                                 break;
2005                                 
2006                                 case 's':
2007                                         if (chan->secret != mdir)
2008                                         {
2009                                                 strcat(outlist,"s");
2010                                                 if (chan->c_private)
2011                                                 {
2012                                                         chan->c_private = 0;
2013                                                         if (mdir)
2014                                                         {
2015                                                                 strcat(outlist,"-p+");
2016                                                         }
2017                                                         else
2018                                                         {
2019                                                                 strcat(outlist,"+p-");
2020                                                         }
2021                                                 }
2022                                         }
2023                                         chan->secret = mdir;
2024                                 break;
2025                                 
2026                                 case 'p':
2027                                         if (chan->c_private != mdir)
2028                                         {
2029                                                 strcat(outlist,"p");
2030                                                 if (chan->secret)
2031                                                 {
2032                                                         chan->secret = 0;
2033                                                         if (mdir)
2034                                                         {
2035                                                                 strcat(outlist,"-s+");
2036                                                         }
2037                                                         else
2038                                                         {
2039                                                                 strcat(outlist,"+s-");
2040                                                         }
2041                                                 }
2042                                         }
2043                                         chan->c_private = mdir;
2044                                 break;
2045                                 
2046                                 default:
2047                                         log(DEBUG,"Preprocessing custom mode %c",modechar);
2048                                         string_list p;
2049                                         p.clear();
2050                                         if (((!strchr(chan->custom_modes,modechar)) && (!mdir)) || ((strchr(chan->custom_modes,modechar)) && (mdir)))
2051                                         {
2052                                                 log(DEBUG,"Mode %c isnt set on %s but trying to remove!",modechar,chan->name);
2053                                                 break;
2054                                         }
2055                                         if (ModeDefined(modechar,MT_CHANNEL))
2056                                         {
2057                                                 log(DEBUG,"A module has claimed this mode");
2058                                                 if ((ModeDefinedOn(modechar,MT_CHANNEL)>0) && (mdir))
2059                                                 {
2060                                                         p.push_back(parameters[param]);
2061                                                 }
2062                                                 if ((ModeDefinedOff(modechar,MT_CHANNEL)>0) && (!mdir))
2063                                                 {
2064                                                         p.push_back(parameters[param]);
2065                                                 }
2066                                                 bool handled = false;
2067                                                 for (int i = 0; i <= MODCOUNT; i++)
2068                                                 {
2069                                                         if (!handled)
2070                                                         {
2071                                                                 if (modules[i]->OnExtendedMode(user,chan,modechar,MT_CHANNEL,mdir,p))
2072                                                                 {
2073                                                                         log(DEBUG,"OnExtendedMode returned nonzero for a module");
2074                                                                         char app[] = {modechar, 0};
2075                                                                         if (ptr>0)
2076                                                                         {
2077                                                                                 if ((modelist[ptr-1] == '+') || (modelist[ptr-1] == '-'))
2078                                                                                 {
2079                                                                                         strcat(outlist, app);
2080                                                                                 }
2081                                                                                 else if (!strchr(outlist,modechar))
2082                                                                                 {
2083                                                                                         strcat(outlist, app);
2084                                                                                 }
2085                                                                         }
2086                                                                         chan->SetCustomMode(modechar,mdir);
2087                                                                         // include parameters in output if mode has them
2088                                                                         if ((ModeDefinedOn(modechar,MT_CHANNEL)>0) || (ModeDefinedOff(modechar,MT_CHANNEL)>0))
2089                                                                         {
2090                                                                                 chan->SetCustomModeParam(modelist[ptr],parameters[param],mdir);
2091                                                                                 strcpy(outpars[pc++],parameters[param++]);
2092                                                                         }
2093                                                                         // break, because only one module can handle the mode.
2094                                                                         handled = true;
2095                                                                 }
2096                                                         }
2097                                                 }
2098                                         }
2099                                 break;
2100                                 
2101                         }
2102                 }
2103         }
2104
2105         /* this ensures only the *valid* modes are sent out onto the network */
2106         while ((outlist[strlen(outlist)-1] == '-') || (outlist[strlen(outlist)-1] == '+'))
2107         {
2108                 outlist[strlen(outlist)-1] = '\0';
2109         }
2110         if (strcmp(outlist,""))
2111         {
2112                 strcpy(outstr,outlist);
2113                 for (ptr = 0; ptr < pc; ptr++)
2114                 {
2115                         strcat(outstr," ");
2116                         strcat(outstr,outpars[ptr]);
2117                 }
2118                 if (servermode)
2119                 {
2120                         WriteChannelWithServ(ServerName,chan,user,"MODE %s %s",chan->name,outstr);
2121                 }
2122                 else
2123                 {
2124                         WriteChannel(chan,user,"MODE %s %s",chan->name,outstr);
2125                 }
2126         }
2127 }
2128
2129 void handle_mode(char **parameters, int pcnt, userrec *user)
2130 {
2131         chanrec* Ptr;
2132         userrec* dest;
2133         int can_change,i;
2134         int direction = 1;
2135         char outpars[MAXBUF];
2136
2137         dest = Find(parameters[0]);
2138
2139         if ((dest) && (pcnt == 1))
2140         {
2141                 WriteServ(user->fd,"221 %s :+%s",user->nick,user->modes);
2142                 return;
2143         }
2144         if ((dest) && (pcnt > 1))
2145         {
2146                 can_change = 0;
2147                 if (user != dest)
2148                 {
2149                         if (strchr(user->modes,'o'))
2150                         {
2151                                 can_change = 1;
2152                         }
2153                 }
2154                 else
2155                 {
2156                         can_change = 1;
2157                 }
2158                 if (!can_change)
2159                 {
2160                         WriteServ(user->fd,"482 %s :Can't change mode for other users",user->nick);
2161                         return;
2162                 }
2163                 
2164                 strcpy(outpars,"+");
2165                 direction = 1;
2166
2167                 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
2168                         return;
2169
2170                 for (i = 0; i < strlen(parameters[1]); i++)
2171                 {
2172                         if (parameters[1][i] == '+')
2173                         {
2174                                 if (direction != 1)
2175                                 {
2176                                         if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2177                                         {
2178                                                 outpars[strlen(outpars)-1] = '+';
2179                                         }
2180                                         else
2181                                         {
2182                                                 strcat(outpars,"+");
2183                                         }
2184                                 }
2185                                 direction = 1;
2186                         }
2187                         else
2188                         if (parameters[1][i] == '-')
2189                         {
2190                                 if (direction != 0)
2191                                 {
2192                                         if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2193                                         {
2194                                                 outpars[strlen(outpars)-1] = '-';
2195                                         }
2196                                         else
2197                                         {
2198                                                 strcat(outpars,"-");
2199                                         }
2200                                 }
2201                                 direction = 0;
2202                         }
2203                         else
2204                         {
2205                                 can_change = 0;
2206                                 if (strchr(user->modes,'o'))
2207                                 {
2208                                         can_change = 1;
2209                                 }
2210                                 else
2211                                 {
2212                                         if ((parameters[1][i] == 'i') || (parameters[1][i] == 'w') || (parameters[1][i] == 's'))
2213                                         {
2214                                                 can_change = 1;
2215                                         }
2216                                 }
2217                                 if (can_change)
2218                                 {
2219                                         if (direction == 1)
2220                                         {
2221                                                 if (!strchr(dest->modes,parameters[1][i]))
2222                                                 {
2223                                                         dest->modes[strlen(dest->modes)+1]='\0';
2224                                                         dest->modes[strlen(dest->modes)] = parameters[1][i];
2225                                                         outpars[strlen(outpars)+1]='\0';
2226                                                         outpars[strlen(outpars)] = parameters[1][i];
2227                                                 }
2228                                         }
2229                                         else
2230                                         {
2231                                                 int q = 0;
2232                                                 char temp[MAXBUF];
2233                                                 char moo[MAXBUF];
2234
2235                                                 outpars[strlen(outpars)+1]='\0';
2236                                                 outpars[strlen(outpars)] = parameters[1][i];
2237                                                 
2238                                                 strcpy(temp,"");
2239                                                 for (q = 0; q < strlen(user->modes); q++)
2240                                                 {
2241                                                         if (user->modes[q] != parameters[1][i])
2242                                                         {
2243                                                                 moo[0] = user->modes[q];
2244                                                                 moo[1] = '\0';
2245                                                                 strcat(temp,moo);
2246                                                         }
2247                                                 }
2248                                                 strcpy(user->modes,temp);
2249                                         }
2250                                 }
2251                         }
2252                 }
2253                 if (strlen(outpars))
2254                 {
2255                         char b[MAXBUF];
2256                         strcpy(b,"");
2257                         int z = 0;
2258                         int i = 0;
2259                         while (i < strlen (outpars))
2260                         {
2261                                 b[z++] = outpars[i++];
2262                                 b[z] = '\0';
2263                                 if (i<strlen(outpars)-1)
2264                                 {
2265                                         if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
2266                                         {
2267                                                 // someones playing silly buggers and trying
2268                                                 // to put a +- or -+ into the line...
2269                                                 i++;
2270                                         }
2271                                 }
2272                                 if (i == strlen(outpars)-1)
2273                                 {
2274                                         if ((outpars[i] == '-') || (outpars[i] == '+'))
2275                                         {
2276                                                 i++;
2277                                         }
2278                                 }
2279                         }
2280
2281                         z = strlen(b)-1;
2282                         if ((b[z] == '-') || (b[z] == '+'))
2283                                 b[z] == '\0';
2284
2285                         if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
2286                                 return;
2287
2288                         WriteTo(user, dest, "MODE %s :%s", dest->nick, b);
2289                 }
2290                 return;
2291         }
2292         
2293         Ptr = FindChan(parameters[0]);
2294         if (Ptr)
2295         {
2296                 if (pcnt == 1)
2297                 {
2298                         /* just /modes #channel */
2299                         WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name, chanmodes(Ptr));
2300                         WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
2301                         return;
2302                 }
2303                 else
2304                 if (pcnt == 2)
2305                 {
2306                         if ((!strcmp(parameters[1],"+b")) || (!strcmp(parameters[1],"b")))
2307                         {
2308
2309                                 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
2310                                 {
2311                                         WriteServ(user->fd,"367 %s %s %s %s %d",user->nick, Ptr->name, i->data, i->set_by, i->set_time);
2312                                 }
2313                                 WriteServ(user->fd,"368 %s %s :End of channel ban list",user->nick, Ptr->name);
2314                         }
2315                 }
2316
2317                 if ((cstatus(user,Ptr) < STATUS_HOP) && (Ptr))
2318                 {
2319                         WriteServ(user->fd,"482 %s %s :You must be at least a half-operator",user->nick, Ptr->name);
2320                         return;
2321                 }
2322
2323                 process_modes(parameters,user,Ptr,cstatus(user,Ptr),pcnt,false);
2324         }
2325         else
2326         {
2327                 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2328         }
2329 }
2330
2331
2332
2333
2334 void server_mode(char **parameters, int pcnt, userrec *user)
2335 {
2336         chanrec* Ptr;
2337         userrec* dest;
2338         int can_change,i;
2339         int direction = 1;
2340         char outpars[MAXBUF];
2341
2342         dest = Find(parameters[0]);
2343
2344         if ((dest) && (pcnt > 1))
2345         {
2346                 strcpy(outpars,"+");
2347                 direction = 1;
2348
2349                 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
2350                         return;
2351
2352                 for (i = 0; i < strlen(parameters[1]); i++)
2353                 {
2354                         if (parameters[1][i] == '+')
2355                         {
2356                                 if (direction != 1)
2357                                 {
2358                                         if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2359                                         {
2360                                                 outpars[strlen(outpars)-1] = '+';
2361                                         }
2362                                         else
2363                                         {
2364                                                 strcat(outpars,"+");
2365                                         }
2366                                 }
2367                                 direction = 1;
2368                         }
2369                         else
2370                         if (parameters[1][i] == '-')
2371                         {
2372                                 if (direction != 0)
2373                                 {
2374                                         if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2375                                         {
2376                                                 outpars[strlen(outpars)-1] = '-';
2377                                         }
2378                                         else
2379                                         {
2380                                                 strcat(outpars,"-");
2381                                         }
2382                                 }
2383                                 direction = 0;
2384                         }
2385                         else
2386                         {
2387                                 can_change = 0;
2388                                 if (strchr(user->modes,'o'))
2389                                 {
2390                                         can_change = 1;
2391                                 }
2392                                 else
2393                                 {
2394                                         if ((parameters[1][i] == 'i') || (parameters[1][i] == 'w') || (parameters[1][i] == 's'))
2395                                         {
2396                                                 can_change = 1;
2397                                         }
2398                                 }
2399                                 if (can_change)
2400                                 {
2401                                         if (direction == 1)
2402                                         {
2403                                                 if (!strchr(dest->modes,parameters[1][i]))
2404                                                 {
2405                                                         dest->modes[strlen(dest->modes)+1]='\0';
2406                                                         dest->modes[strlen(dest->modes)] = parameters[1][i];
2407                                                         outpars[strlen(outpars)+1]='\0';
2408                                                         outpars[strlen(outpars)] = parameters[1][i];
2409                                                 }
2410                                         }
2411                                         else
2412                                         {
2413                                                 int q = 0;
2414                                                 char temp[MAXBUF];
2415                                                 char moo[MAXBUF];
2416
2417                                                 outpars[strlen(outpars)+1]='\0';
2418                                                 outpars[strlen(outpars)] = parameters[1][i];
2419                                                 
2420                                                 strcpy(temp,"");
2421                                                 for (q = 0; q < strlen(user->modes); q++)
2422                                                 {
2423                                                         if (user->modes[q] != parameters[1][i])
2424                                                         {
2425                                                                 moo[0] = user->modes[q];
2426                                                                 moo[1] = '\0';
2427                                                                 strcat(temp,moo);
2428                                                         }
2429                                                 }
2430                                                 strcpy(user->modes,temp);
2431                                         }
2432                                 }
2433                         }
2434                 }
2435                 if (strlen(outpars))
2436                 {
2437                         char b[MAXBUF];
2438                         strcpy(b,"");
2439                         int z = 0;
2440                         int i = 0;
2441                         while (i < strlen (outpars))
2442                         {
2443                                 b[z++] = outpars[i++];
2444                                 b[z] = '\0';
2445                                 if (i<strlen(outpars)-1)
2446                                 {
2447                                         if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
2448                                         {
2449                                                 // someones playing silly buggers and trying
2450                                                 // to put a +- or -+ into the line...
2451                                                 i++;
2452                                         }
2453                                 }
2454                                 if (i == strlen(outpars)-1)
2455                                 {
2456                                         if ((outpars[i] == '-') || (outpars[i] == '+'))
2457                                         {
2458                                                 i++;
2459                                         }
2460                                 }
2461                         }
2462
2463                         z = strlen(b)-1;
2464                         if ((b[z] == '-') || (b[z] == '+'))
2465                                 b[z] == '\0';
2466
2467                         if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
2468                                 return;
2469
2470                         WriteTo(user, dest, "MODE %s :%s", dest->nick, b);
2471                 }
2472                 return;
2473         }
2474         
2475         Ptr = FindChan(parameters[0]);
2476         if (Ptr)
2477         {
2478                 process_modes(parameters,user,Ptr,STATUS_OP,pcnt,true);
2479         }
2480         else
2481         {
2482                 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2483         }
2484 }
2485
2486
2487 /* This function pokes and hacks at a parameter list like the following:
2488  *
2489  * PART #winbot, #darkgalaxy :m00!
2490  *
2491  * to turn it into a series of individual calls like this:
2492  *
2493  * PART #winbot :m00!
2494  * PART #darkgalaxy :m00!
2495  *
2496  * The seperate calls are sent to a callback function provided by the caller
2497  * (the caller will usually call itself recursively). The callback function
2498  * must be a command handler. Calling this function on a line with no list causes
2499  * no action to be taken. You must provide a starting and ending parameter number
2500  * where the range of the list can be found, useful if you have a terminating
2501  * parameter as above which is actually not part of the list, or parameters
2502  * before the actual list as well. This code is used by many functions which
2503  * can function as "one to list" (see the RFC) */
2504
2505 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
2506 {
2507         char plist[MAXBUF];
2508         char *param;
2509         char *pars[32];
2510         char blog[32][MAXBUF];
2511         char blog2[32][MAXBUF];
2512         int i = 0, j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
2513         char keystr[MAXBUF];
2514         char moo[MAXBUF];
2515
2516         for (i = 0; i <32; i++)
2517                 strcpy(blog[i],"");
2518
2519         for (i = 0; i <32; i++)
2520                 strcpy(blog2[i],"");
2521
2522         strcpy(moo,"");
2523         for (i = 0; i <10; i++)
2524         {
2525                 if (!parameters[i])
2526                 {
2527                         parameters[i] = moo;
2528                 }
2529         }
2530         if (joins)
2531         {
2532                 if (pcnt > 1) /* we have a key to copy */
2533                 {
2534                         strcpy(keystr,parameters[1]);
2535                 }
2536         }
2537
2538         if (!parameters[start])
2539         {
2540                 return 0;
2541         }
2542         if (!strchr(parameters[start],','))
2543         {
2544                 return 0;
2545         }
2546         strcpy(plist,"");
2547         for (i = start; i <= end; i++)
2548         {
2549                 if (parameters[i])
2550                 {
2551                         strcat(plist,parameters[i]);
2552                 }
2553         }
2554         
2555         j = 0;
2556         param = plist;
2557
2558         t = strlen(plist);
2559         for (i = 0; i < t; i++)
2560         {
2561                 if (plist[i] == ',')
2562                 {
2563                         plist[i] = '\0';
2564                         strcpy(blog[j++],param);
2565                         param = plist+i+1;
2566                 }
2567         }
2568         strcpy(blog[j++],param);
2569         total = j;
2570
2571         if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
2572         {
2573                 strcat(keystr,",");
2574         }
2575         
2576         if ((joins) && (keystr))
2577         {
2578                 if (strchr(keystr,','))
2579                 {
2580                         j = 0;
2581                         param = keystr;
2582                         t2 = strlen(keystr);
2583                         for (i = 0; i < t2; i++)
2584                         {
2585                                 if (keystr[i] == ',')
2586                                 {
2587                                         keystr[i] = '\0';
2588                                         strcpy(blog2[j++],param);
2589                                         param = keystr+i+1;
2590                                 }
2591                         }
2592                         strcpy(blog2[j++],param);
2593                         total2 = j;
2594                 }
2595         }
2596
2597         for (j = 0; j < total; j++)
2598         {
2599                 if (blog[j])
2600                 {
2601                         pars[0] = blog[j];
2602                 }
2603                 for (q = end; q < pcnt-1; q++)
2604                 {
2605                         if (parameters[q+1])
2606                         {
2607                                 pars[q-end+1] = parameters[q+1];
2608                         }
2609                 }
2610                 if ((joins) && (parameters[1]))
2611                 {
2612                         if (pcnt > 1)
2613                         {
2614                                 pars[1] = blog2[j];
2615                         }
2616                         else
2617                         {
2618                                 pars[1] = NULL;
2619                         }
2620                 }
2621                 /* repeatedly call the function with the hacked parameter list */
2622                 if ((joins) && (pcnt > 1))
2623                 {
2624                         if (pars[1])
2625                         {
2626                                 // pars[1] already set up and containing key from blog2[j]
2627                                 fn(pars,2,u);
2628                         }
2629                         else
2630                         {
2631                                 pars[1] = parameters[1];
2632                                 fn(pars,2,u);
2633                         }
2634                 }
2635                 else
2636                 {
2637                         fn(pars,pcnt-(end-start),u);
2638                 }
2639         }
2640
2641         return 1;
2642 }
2643
2644 void handle_join(char **parameters, int pcnt, userrec *user)
2645 {
2646         chanrec* Ptr;
2647         int i = 0;
2648         
2649         if (loop_call(handle_join,parameters,pcnt,user,0,0,1))
2650                 return;
2651         if (parameters[0][0] == '#')
2652         {
2653                 Ptr = add_channel(user,parameters[0],parameters[1]);
2654         }
2655 }
2656
2657
2658 void handle_part(char **parameters, int pcnt, userrec *user)
2659 {
2660         chanrec* Ptr;
2661
2662         if (pcnt > 1)
2663         {
2664                 if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-2,0))
2665                         return;
2666                 del_channel(user,parameters[0],parameters[1]);
2667         }
2668         else
2669         {
2670                 if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-1,0))
2671                         return;
2672                 del_channel(user,parameters[0],NULL);
2673         }
2674 }
2675
2676 void handle_kick(char **parameters, int pcnt, userrec *user)
2677 {
2678         chanrec* Ptr = FindChan(parameters[0]);
2679         userrec* u   = Find(parameters[1]);
2680
2681         if ((!u) || (!Ptr))
2682         {
2683                 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2684                 return;
2685         }
2686         
2687         if (!has_channel(u,Ptr))
2688         {
2689                 WriteServ(user->fd,"442 %s %s :You're not on that channel!",user->nick, parameters[0]);
2690                 return;
2691         }
2692         
2693         if (pcnt > 2)
2694         {
2695                 kick_channel(user,u,Ptr,parameters[2]);
2696         }
2697         else
2698         {
2699                 kick_channel(user,u,Ptr,user->nick);
2700         }
2701 }
2702
2703
2704 void handle_die(char **parameters, int pcnt, userrec *user)
2705 {
2706         log(DEBUG,"die: %s",user->nick);
2707         if (!strcmp(parameters[0],diepass))
2708         {
2709                 WriteOpers("*** DIE command from %s!%s@%s, terminating...",user->nick,user->ident,user->host);
2710                 sleep(DieDelay);
2711                 Exit(ERROR);
2712         }
2713         else
2714         {
2715                 WriteOpers("*** Failed DIE Command from %s!%s@%s.",user->nick,user->ident,user->host);
2716         }
2717 }
2718
2719 void handle_restart(char **parameters, int pcnt, userrec *user)
2720 {
2721         log(DEBUG,"restart: %s",user->nick);
2722         if (!strcmp(parameters[0],restartpass))
2723         {
2724                 WriteOpers("*** RESTART command from %s!%s@%s, Pretending to restart till this is finished :D",user->nick,user->ident,user->host);
2725                 sleep(DieDelay);
2726                 Exit(ERROR);
2727                 /* Will finish this later when i can be arsed :) */
2728         }
2729         else
2730         {
2731                 WriteOpers("*** Failed RESTART Command from %s!%s@%s.",user->nick,user->ident,user->host);
2732         }
2733 }
2734
2735
2736 void kill_link(userrec *user,char* reason)
2737 {
2738         user_hash::iterator iter = clientlist.find(user->nick);
2739
2740         log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
2741         Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
2742         fdatasync(user->fd);
2743         log(DEBUG,"closing fd %d",user->fd);
2744
2745         /* bugfix, cant close() a nonblocking socket (sux!) */
2746         if (user->registered == 7) {
2747                 FOREACH_MOD OnUserQuit(user);
2748                 WriteCommonExcept(user,"QUIT :%s",reason);
2749         }
2750
2751         /* push the socket on a stack of sockets due to be closed at the next opportunity */
2752         fd_reap.push_back(user->fd);
2753         
2754         bool do_purge = false;
2755         
2756         if (user->registered == 7) {
2757                 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
2758                 AddWhoWas(user);
2759         }
2760
2761         if (iter != clientlist.end())
2762         {
2763                 log(DEBUG,"deleting user hash value %d",iter->second);
2764                 if ((iter->second) && (user->registered == 7)) {
2765                         delete iter->second;
2766                 }
2767                 clientlist.erase(iter);
2768         }
2769
2770         purge_empty_chans();
2771 }
2772
2773
2774 void handle_kill(char **parameters, int pcnt, userrec *user)
2775 {
2776         userrec *u = Find(parameters[0]);
2777         char killreason[MAXBUF];
2778         
2779         log(DEBUG,"kill: %s %s",parameters[0],parameters[1]);
2780         if (u)
2781         {
2782                 WriteTo(user, u, "KILL %s :%s!%s!%s (%s)", u->nick, ServerName,user->dhost,user->nick,parameters[1]);
2783                 // :Brain!brain@NetAdmin.chatspike.net KILL [Brain] :homer!NetAdmin.chatspike.net!Brain (test kill)
2784                 WriteOpers("*** Local Kill by %s: %s!%s@%s (%s)",user->nick,u->nick,u->ident,u->host,parameters[1]);
2785                 sprintf(killreason,"Killed (%s (%s))",user->nick,parameters[1]);
2786                 kill_link(u,killreason);
2787         }
2788         else
2789         {
2790                 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2791         }
2792 }
2793
2794 void handle_summon(char **parameters, int pcnt, userrec *user)
2795 {
2796         WriteServ(user->fd,"445 %s :SUMMON has been disabled (depreciated command)",user->nick);
2797 }
2798
2799 void handle_users(char **parameters, int pcnt, userrec *user)
2800 {
2801         WriteServ(user->fd,"445 %s :USERS has been disabled (depreciated command)",user->nick);
2802 }
2803
2804
2805 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
2806
2807 char* Passwd(userrec *user)
2808 {
2809         for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2810         {
2811                 if (match(user->host,i->host) && (i->type == CC_ALLOW))
2812                 {
2813                         return i->pass;
2814                 }
2815         }
2816         return "";
2817 }
2818
2819 bool IsDenied(userrec *user)
2820 {
2821         for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
2822         {
2823                 if (match(user->host,i->host) && (i->type == CC_DENY))
2824                 {
2825                         return true;
2826                 }
2827         }
2828         return false;
2829 }
2830
2831
2832 void handle_pass(char **parameters, int pcnt, userrec *user)
2833 {
2834         if (!strcasecmp(parameters[0],Passwd(user)))
2835         {
2836                 user->haspassed = true;
2837         }
2838 }
2839
2840 void handle_invite(char **parameters, int pcnt, userrec *user)
2841 {
2842         userrec* u = Find(parameters[0]);
2843         chanrec* c = FindChan(parameters[1]);
2844
2845         if ((!c) || (!u))
2846         {
2847                 if (!c)
2848                 {
2849                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[1]);
2850                 }
2851                 else
2852                 {
2853                         if (c->inviteonly)
2854                         {
2855                                 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[0]);
2856                         }
2857                 }
2858
2859                 return;
2860         }
2861
2862         if (c->inviteonly)
2863         {
2864                 if (cstatus(user,c) < STATUS_HOP)
2865                 {
2866                         WriteServ(user->fd,"482 %s %s :You must be at least a half-operator",user->nick, c->name);
2867                         return;
2868                 }
2869
2870                 u->InviteTo(c->name);
2871                 WriteFrom(u->fd,user,"INVITE %s :%s",u->nick,c->name);
2872                 WriteServ(user->fd,"341 %s %s %s",user->nick,u->nick,c->name);
2873         }
2874 }
2875
2876 void handle_topic(char **parameters, int pcnt, userrec *user)
2877 {
2878         chanrec* Ptr;
2879
2880         if (pcnt == 1)
2881         {
2882                 if (strlen(parameters[0]) <= CHANMAX)
2883                 {
2884                         Ptr = FindChan(parameters[0]);
2885                         if (Ptr)
2886                         {
2887                                 if (Ptr->topicset)
2888                                 {
2889                                         WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
2890                                         WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
2891                                 }
2892                                 else
2893                                 {
2894                                         WriteServ(user->fd,"331 %s %s :No topic is set.", user->nick, Ptr->name);
2895                                 }
2896                         }
2897                         else
2898                         {
2899                                 WriteServ(user->fd,"331 %s %s :No topic is set.", user->nick, Ptr->name);
2900                         }
2901                 }
2902         }
2903         else if (pcnt>1)
2904         {
2905                 if (loop_call(handle_topic,parameters,pcnt,user,0,pcnt-2,0))
2906                         return;
2907                 if (strlen(parameters[0]) <= CHANMAX)
2908                 {
2909                         Ptr = FindChan(parameters[0]);
2910                         if (Ptr)
2911                         {
2912                                 if ((Ptr->topiclock) && (cstatus(user,Ptr)<STATUS_HOP))
2913                                 {
2914                                         WriteServ(user->fd,"482 %s %s :You must be at least a half-operator", user->nick, Ptr->name);
2915                                         return;
2916                                 }
2917                                 strcpy(Ptr->topic,parameters[1]);
2918                                 strcpy(Ptr->setby,user->nick);
2919                                 Ptr->topicset = time(NULL);
2920                                 WriteChannel(Ptr,user,"TOPIC %s :%s",Ptr->name, Ptr->topic);
2921                         }
2922                         else
2923                         {
2924                                 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2925                         }
2926                 }
2927         }
2928 }
2929
2930 /* sends out an error notice to all connected clients (not to be used
2931  * lightly!) */
2932
2933 void send_error(char *s)
2934 {
2935         log(DEBUG,"send_error: %s",s);
2936         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
2937         {
2938                 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
2939         }
2940 }
2941
2942 void Error(int status)
2943 {
2944         signal (SIGALRM, SIG_IGN);
2945         signal (SIGPIPE, SIG_IGN);
2946         signal (SIGTERM, SIG_IGN);
2947         signal (SIGABRT, SIG_IGN);
2948         signal (SIGSEGV, SIG_IGN);
2949         signal (SIGURG, SIG_IGN);
2950         signal (SIGKILL, SIG_IGN);
2951         log(DEBUG,"*** fell down a pothole in the road to perfection ***");
2952         send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
2953         exit(status);
2954 }
2955
2956 int main (int argc, char *argv[])
2957 {
2958         Start();
2959         log(DEBUG,"*** InspIRCd starting up!");
2960         if (!FileExists(CONFIG_FILE))
2961         {
2962                 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
2963                 log(DEBUG,"main: no config");
2964                 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
2965                 Exit(ERROR);
2966         }
2967         if (argc > 1) {
2968                 if (!strcmp(argv[1],"-nofork")) {
2969                         nofork = true;
2970                 }
2971         }
2972         if (InspIRCd() == ERROR)
2973         {
2974                 log(DEBUG,"main: daemon function bailed");
2975                 printf("ERROR: could not initialise. Shutting down.\n");
2976                 Exit(ERROR);
2977         }
2978         Exit(TRUE);
2979         return 0;
2980 }
2981
2982 template<typename T> inline string ConvToStr(const T &in)
2983 {
2984         stringstream tmp;
2985         if (!(tmp << in)) return string();
2986         return tmp.str();
2987 }
2988
2989 /* re-allocates a nick in the user_hash after they change nicknames,
2990  * returns a pointer to the new user as it may have moved */
2991
2992 userrec* ReHashNick(char* Old, char* New)
2993 {
2994         user_hash::iterator newnick;
2995         user_hash::iterator oldnick = clientlist.find(Old);
2996
2997         log(DEBUG,"ReHashNick: %s %s",Old,New);
2998         
2999         if (!strcasecmp(Old,New))
3000         {
3001                 log(DEBUG,"old nick is new nick, skipping");
3002                 return oldnick->second;
3003         }
3004         
3005         if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
3006
3007         log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
3008
3009         clientlist[New] = new userrec();
3010         clientlist[New] = oldnick->second;
3011         /*delete oldnick->second; */
3012         clientlist.erase(oldnick);
3013
3014         log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
3015         
3016         return clientlist[New];
3017 }
3018
3019 /* adds or updates an entry in the whowas list */
3020 void AddWhoWas(userrec* u)
3021 {
3022         user_hash::iterator iter = whowas.find(u->nick);
3023         userrec *a = new userrec();
3024         strcpy(a->nick,u->nick);
3025         strcpy(a->ident,u->ident);
3026         strcpy(a->dhost,u->dhost);
3027         strcpy(a->host,u->host);
3028         strcpy(a->fullname,u->fullname);
3029         strcpy(a->server,u->server);
3030         a->signon = u->signon;
3031
3032         /* MAX_WHOWAS:   max number of /WHOWAS items
3033          * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
3034          *               can be replaced by a newer one
3035          */
3036         
3037         if (iter == whowas.end())
3038         {
3039                 if (whowas.size() == WHOWAS_MAX)
3040                 {
3041                         for (user_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
3042                         {
3043                                 // 3600 seconds in an hour ;)
3044                                 if ((i->second->signon)<(time(NULL)-(WHOWAS_STALE*3600)))
3045                                 {
3046                                         delete i->second;
3047                                         i->second = a;
3048                                         log(DEBUG,"added WHOWAS entry, purged an old record");
3049                                         return;
3050                                 }
3051                         }
3052                 }
3053                 else
3054                 {
3055                         log(DEBUG,"added fresh WHOWAS entry");
3056                         whowas[a->nick] = a;
3057                 }
3058         }
3059         else
3060         {
3061                 log(DEBUG,"updated WHOWAS entry");
3062                 delete iter->second;
3063                 iter->second = a;
3064         }
3065 }
3066
3067
3068 /* add a client connection to the sockets list */
3069 void AddClient(int socket, char* host, int port, bool iscached)
3070 {
3071         int i;
3072         int blocking = 1;
3073         char resolved[MAXBUF];
3074         string tempnick;
3075         char tn2[MAXBUF];
3076         user_hash::iterator iter;
3077
3078         tempnick = ConvToStr(socket) + "-unknown";
3079         sprintf(tn2,"%d-unknown",socket);
3080
3081         iter = clientlist.find(tempnick);
3082
3083         if (iter != clientlist.end()) return;
3084
3085         /*
3086          * It is OK to access the value here this way since we know
3087          * it exists, we just created it above.
3088          *
3089          * At NO other time should you access a value in a map or a
3090          * hash_map this way.
3091          */
3092         clientlist[tempnick] = new userrec();
3093
3094         NonBlocking(socket);
3095         log(DEBUG,"AddClient: %d %s %d",socket,host,port);
3096
3097
3098         clientlist[tempnick]->fd = socket;
3099         strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
3100         strncpy(clientlist[tempnick]->host, host,160);
3101         strncpy(clientlist[tempnick]->dhost, host,160);
3102         strncpy(clientlist[tempnick]->server, ServerName,256);
3103         clientlist[tempnick]->registered = 0;
3104         clientlist[tempnick]->signon = time(NULL);
3105         clientlist[tempnick]->nping = time(NULL)+240;
3106         clientlist[tempnick]->lastping = 1;
3107         clientlist[tempnick]->port = port;
3108
3109         if (iscached)
3110         {
3111                 WriteServ(socket,"NOTICE Auth :Found your hostname (cached)...");
3112         }
3113         else
3114         {
3115                 WriteServ(socket,"NOTICE Auth :Looking up your hostname...");
3116         }
3117
3118         if (clientlist.size() == MAXCLIENTS)
3119                 kill_link(clientlist[tempnick],"No more connections allowed in this class");
3120 }
3121
3122 void handle_names(char **parameters, int pcnt, userrec *user)
3123 {
3124         chanrec* c;
3125
3126         if (loop_call(handle_names,parameters,pcnt,user,0,pcnt-1,0))
3127                 return;
3128         c = FindChan(parameters[0]);
3129         if (c)
3130         {
3131                 /*WriteServ(user->fd,"353 %s = %s :%s", user->nick, c->name,*/
3132                 userlist(user,c);
3133                 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, c->name);
3134         }
3135         else
3136         {
3137                 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3138         }
3139 }
3140
3141
3142 void handle_privmsg(char **parameters, int pcnt, userrec *user)
3143 {
3144         userrec *dest;
3145         chanrec *chan;
3146         
3147         if (loop_call(handle_privmsg,parameters,pcnt,user,0,pcnt-2,0))
3148                 return;
3149         if (parameters[0][0] == '#')
3150         {
3151                 chan = FindChan(parameters[0]);
3152                 if (chan)
3153                 {
3154                         if ((chan->noexternal) && (!has_channel(user,chan)))
3155                         {
3156                                 WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
3157                                 return;
3158                         }
3159                         if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
3160                         {
3161                                 WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
3162                                 return;
3163                         }
3164                         ChanExceptSender(chan, user, "PRIVMSG %s :%s", chan->name, parameters[1]);
3165                 }
3166                 else
3167                 {
3168                         /* no such nick/channel */
3169                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3170                 }
3171                 return;
3172         }
3173         
3174         dest = Find(parameters[0]);
3175         if (dest)
3176         {
3177                 if (strcmp(dest->awaymsg,""))
3178                 {
3179                         /* auto respond with aweh msg */
3180                         WriteServ(user->fd,"301 %s %s :%s",user->nick,dest->nick,dest->awaymsg);
3181                 }
3182                 WriteTo(user, dest, "PRIVMSG %s :%s", dest->nick, parameters[1]);
3183         }
3184         else
3185         {
3186                 /* no such nick/channel */
3187                 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3188         }
3189 }
3190
3191 void handle_notice(char **parameters, int pcnt, userrec *user)
3192 {
3193         userrec *dest;
3194         chanrec *chan;
3195
3196         if (loop_call(handle_notice,parameters,pcnt,user,0,pcnt-2,0))
3197                 return;
3198         if (parameters[0][0] == '#')
3199         {
3200                 chan = FindChan(parameters[0]);
3201                 if (chan)
3202                 {
3203                         if ((chan->noexternal) && (!has_channel(user,chan)))
3204                         {
3205                                 WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
3206                                 return;
3207                         }
3208                         if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
3209                         {
3210                                 WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
3211                                 return;
3212                         }
3213                         WriteChannel(chan, user, "NOTICE %s :%s", chan->name, parameters[1]);
3214                 }
3215                 else
3216                 {
3217                         /* no such nick/channel */
3218                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3219                 }
3220                 return;
3221         }
3222         
3223         dest = Find(parameters[0]);
3224         if (dest)
3225         {
3226                 WriteTo(user, dest, "NOTICE %s :%s", dest->nick, parameters[1]);
3227         }
3228         else
3229         {
3230                 /* no such nick/channel */
3231                 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3232         }
3233 }
3234
3235 char lst[MAXBUF];
3236
3237 char* chlist(userrec *user)
3238 {
3239         int i = 0;
3240         char cmp[MAXBUF];
3241
3242         log(DEBUG,"chlist: %s",user->nick);
3243         strcpy(lst,"");
3244         if (!user)
3245         {
3246                 return lst;
3247         }
3248         for (i = 0; i != MAXCHANS; i++)
3249         {
3250                 if (user->chans[i].channel != NULL)
3251                 {
3252                         if (user->chans[i].channel->name)
3253                         {
3254                                 strcpy(cmp,user->chans[i].channel->name);
3255                                 strcat(cmp," ");
3256                                 if (!strstr(lst,cmp))
3257                                 {
3258                                         if ((!user->chans[i].channel->c_private) && (!user->chans[i].channel->secret))
3259                                         {
3260                                                 strcat(lst,cmode(user,user->chans[i].channel));
3261                                                 strcat(lst,user->chans[i].channel->name);
3262                                                 strcat(lst," ");
3263                                         }
3264                                 }
3265                         }
3266                 }
3267         }
3268         return lst;
3269 }
3270
3271 void handle_info(char **parameters, int pcnt, userrec *user)
3272 {
3273         WriteServ(user->fd,"371 %s :The Inspire IRCd Project Has been brought to you by the following people..",user->nick);
3274         WriteServ(user->fd,"371 %s :Craig Edwards, Craig McLure, and Others..",user->nick);
3275         WriteServ(user->fd,"371 %s :Will finish this later when i can be arsed :p",user->nick);
3276         WriteServ(user->fd,"374 %s :End of /INFO list",user->nick);
3277 }
3278
3279 void handle_time(char **parameters, int pcnt, userrec *user)
3280 {
3281         time_t rawtime;
3282         struct tm * timeinfo;
3283
3284         time ( &rawtime );
3285         timeinfo = localtime ( &rawtime );
3286         WriteServ(user->fd,"391 %s %s :%s",user->nick,ServerName, asctime (timeinfo) );
3287   
3288 }
3289
3290 void handle_whois(char **parameters, int pcnt, userrec *user)
3291 {
3292         userrec *dest;
3293         char *t;
3294
3295         if (loop_call(handle_whois,parameters,pcnt,user,0,pcnt-1,0))
3296                 return;
3297         dest = Find(parameters[0]);
3298         if (dest)
3299         {
3300                 WriteServ(user->fd,"311 %s %s %s %s * :%s",user->nick, dest->nick, dest->ident, dest->dhost, dest->fullname);
3301                 if ((user == dest) || (strchr(user->modes,'o')))
3302                 {
3303                         WriteServ(user->fd,"378 %s %s :is connecting from *@%s",user->nick, dest->nick, dest->host);
3304                 }
3305                 if (strcmp(chlist(dest),""))
3306                 {
3307                         WriteServ(user->fd,"319 %s %s :%s",user->nick, dest->nick, chlist(dest));
3308                 }
3309                 WriteServ(user->fd,"312 %s %s %s :%s",user->nick, dest->nick, dest->server, ServerDesc);
3310                 if (strcmp(dest->awaymsg,""))
3311                 {
3312                         WriteServ(user->fd,"301 %s %s :%s",user->nick, dest->nick, dest->awaymsg);
3313                 }
3314                 if (strchr(dest->modes,'o'))
3315                 {
3316                         WriteServ(user->fd,"313 %s %s :is an IRC operator",user->nick, dest->nick);
3317                 }
3318                 //WriteServ(user->fd,"310 %s %s :is available for help.",user->nick, dest->nick);
3319                 WriteServ(user->fd,"317 %s %s %d %d :seconds idle, signon time",user->nick, dest->nick, abs((dest->idle_lastmsg)-time(NULL)), dest->signon);
3320                 
3321                 WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, dest->nick);
3322         }
3323         else
3324         {
3325                 /* no such nick/channel */
3326                 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3327         }
3328 }
3329
3330 void handle_quit(char **parameters, int pcnt, userrec *user)
3331 {
3332         user_hash::iterator iter = clientlist.find(user->nick);
3333
3334         if (user->registered == 7)
3335         {
3336                 /* theres more to do here, but for now just close the socket */
3337                 if (pcnt == 1)
3338                 {
3339                         if (parameters[0][0] == ':')
3340                         {
3341                                 *parameters[0]++;
3342                         }
3343                         Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,parameters[0]);
3344                         WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,parameters[0]);
3345                         WriteCommonExcept(user,"QUIT :%s%s",PrefixQuit,parameters[0]);
3346                 }
3347                 else
3348                 {
3349                         Write(user->fd,"ERROR :Closing link (%s@%s) [QUIT]",user->ident,user->host);
3350                         WriteOpers("*** Client exiting: %s!%s@%s [Client exited]",user->nick,user->ident,user->host);
3351                         WriteCommonExcept(user,"QUIT :Client exited");
3352                 }
3353                 FOREACH_MOD OnUserQuit(user);
3354                 AddWhoWas(user);
3355         }
3356
3357         /* push the socket on a stack of sockets due to be closed at the next opportunity */
3358         fd_reap.push_back(user->fd);
3359         
3360         if (iter != clientlist.end())
3361         {
3362                 log(DEBUG,"deleting user hash value %d",iter->second);
3363                 if ((iter->second) && (user->registered == 7)) {
3364                         delete iter->second;
3365                 }
3366                 clientlist.erase(iter);
3367         }
3368
3369         if (user->registered == 7) {
3370                 purge_empty_chans();
3371         }
3372 }
3373
3374 void handle_who(char **parameters, int pcnt, userrec *user)
3375 {
3376         chanrec* Ptr = NULL;
3377         
3378         /* theres more to do here, but for now just close the socket */
3379         if (pcnt == 1)
3380         {
3381                 if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")))
3382                 {
3383                         if (user->chans[0].channel)
3384                         {
3385                                 Ptr = user->chans[0].channel;
3386                                 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3387                                 {
3388                                         if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
3389                                         {
3390                                                 WriteServ(user->fd,"352 %s %s %s %s %s %s Hr@ :0 %s",user->nick, Ptr->name, i->second->ident, i->second->dhost, ServerName, i->second->nick, i->second->fullname);
3391                                         }
3392                                 }
3393                         }
3394                         if (Ptr)
3395                         {
3396                                 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
3397                         }
3398                         else
3399                         {
3400                                 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, user->nick);
3401                         }
3402                         return;
3403                 }
3404                 if (parameters[0][0] = '#')
3405                 {
3406                         Ptr = FindChan(parameters[0]);
3407                         if (Ptr)
3408                         {
3409                                 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3410                                 {
3411                                         if ((has_channel(i->second,Ptr)) && (isnick(i->second->nick)))
3412                                         {
3413                                                 WriteServ(user->fd,"352 %s %s %s %s %s %s Hr@ :0 %s",user->nick, Ptr->name, i->second->ident, i->second->dhost, ServerName, i->second->nick, i->second->fullname);
3414                                         }
3415                                 }
3416                                 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
3417                         }
3418                         else
3419                         {
3420                                 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3421                         }
3422                 }
3423         }
3424         if (pcnt == 2)
3425         {
3426                 if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")) && (!strcmp(parameters[1],"o")))
3427                 {
3428                         Ptr = user->chans[0].channel;
3429                         printf(user->chans[0].channel->name);
3430                         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3431                         {
3432                                 if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
3433                                 {
3434                                         if (strchr(i->second->modes,'o'))
3435                                         {
3436                                                 WriteServ(user->fd,"352 %s %s %s %s %s %s Hr@ :0 %s",user->nick, Ptr->name, i->second->ident, i->second->dhost, ServerName, i->second->nick, i->second->fullname);
3437                                         }
3438                                 }
3439                         }
3440                         WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
3441                         return;
3442                 }
3443         }
3444 }
3445
3446 void handle_wallops(char **parameters, int pcnt, userrec *user)
3447 {
3448         WriteWallOps(user,"%s",parameters[0]);
3449 }
3450
3451 void handle_list(char **parameters, int pcnt, userrec *user)
3452 {
3453         chanrec* Ptr;
3454         
3455         WriteServ(user->fd,"321 %s Channel :Users Name",user->nick);
3456         for (chan_hash::const_iterator i = chanlist.begin(); i != chanlist.end(); i++)
3457         {
3458                 if ((!i->second->c_private) && (!i->second->secret))
3459                 {
3460                         WriteServ(user->fd,"322 %s %s %d :[+%s] %s",user->nick,i->second->name,usercount_i(i->second),chanmodes(i->second),i->second->topic);
3461                 }
3462         }
3463         WriteServ(user->fd,"323 %s :End of channel list.",user->nick);
3464 }
3465
3466
3467 void handle_rehash(char **parameters, int pcnt, userrec *user)
3468 {
3469         WriteServ(user->fd,"382 %s %s :Rehashing",user->nick,CONFIG_FILE);
3470         ReadConfig();
3471         FOREACH_MOD OnRehash();
3472         WriteOpers("%s is rehashing config file %s",user->nick,CONFIG_FILE);
3473 }
3474
3475
3476 int usercnt(void)
3477 {
3478         return clientlist.size();
3479 }
3480
3481 int usercount_invisible(void)
3482 {
3483         int c = 0;
3484
3485         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3486         {
3487                 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
3488         }
3489         return c;
3490 }
3491
3492 int usercount_opers(void)
3493 {
3494         int c = 0;
3495
3496         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3497         {
3498                 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
3499         }
3500         return c;
3501 }
3502
3503 int usercount_unknown(void)
3504 {
3505         int c = 0;
3506
3507         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3508         {
3509                 if ((i->second->fd) && (i->second->registered != 7))
3510                         c++;
3511         }
3512         return c;
3513 }
3514
3515 int chancount(void)
3516 {
3517         return chanlist.size();
3518 }
3519
3520 int servercount(void)
3521 {
3522         return 1;
3523 }
3524
3525 void handle_lusers(char **parameters, int pcnt, userrec *user)
3526 {
3527         WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),servercount());
3528         WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
3529         WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
3530         WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
3531         WriteServ(user->fd,"254 %s :I have %d clients and 0 servers",user->nick,usercnt());
3532 }
3533
3534 void handle_admin(char **parameters, int pcnt, userrec *user)
3535 {
3536         WriteServ(user->fd,"256 %s :Administrative info for %s",user->nick,ServerName);
3537         WriteServ(user->fd,"257 %s :Name     - %s",user->nick,AdminName);
3538         WriteServ(user->fd,"258 %s :Nickname - %s",user->nick,AdminNick);
3539         WriteServ(user->fd,"258 %s :E-Mail   - %s",user->nick,AdminEmail);
3540 }
3541
3542 void ShowMOTD(userrec *user)
3543 {
3544         if (!MOTD.size())
3545         {
3546                 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
3547                 return;
3548         }
3549         WriteServ(user->fd,"375 %s :- %s message of the day",user->nick,ServerName);
3550         for (int i = 0; i != MOTD.size(); i++)
3551         {
3552                                 WriteServ(user->fd,"372 %s :- %s",user->nick,MOTD[i].c_str());
3553         }
3554         WriteServ(user->fd,"376 %s :End of %s message of the day.",user->nick,ServerName);
3555 }
3556
3557 void ShowRULES(userrec *user)
3558 {
3559         if (!RULES.size())
3560         {
3561                 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
3562                 return;
3563         }
3564         WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
3565         for (int i = 0; i != RULES.size(); i++)
3566         {
3567                                 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
3568         }
3569         WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
3570 }
3571
3572 /* shows the message of the day, and any other on-logon stuff */
3573 void ConnectUser(userrec *user)
3574 {
3575         user->registered = 7;
3576         user->idle_lastmsg = time(NULL);
3577         log(DEBUG,"ConnectUser: %s",user->nick);
3578
3579         if (strcmp(Passwd(user),"") && (!user->haspassed))
3580         {
3581                 Write(user->fd,"ERROR :Closing link: Invalid password");
3582                 fdatasync(user->fd);
3583                 kill_link(user,"Invalid password");
3584                 return;
3585         }
3586         if (IsDenied(user))
3587         {
3588                 Write(user->fd,"ERROR :Closing link: Unauthorized connection");
3589                 fdatasync(user->fd);
3590                 kill_link(user,"Unauthorised connection");
3591         }
3592
3593         WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
3594         WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
3595         WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
3596         WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
3597         WriteServ(user->fd,"004 %s :%s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
3598         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);
3599         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);
3600         ShowMOTD(user);
3601         FOREACH_MOD OnUserConnect(user);
3602         WriteOpers("*** Client connecting on port %d: %s!%s@%s",user->port,user->nick,user->ident,user->host);
3603 }
3604
3605 void handle_version(char **parameters, int pcnt, userrec *user)
3606 {
3607         WriteServ(user->fd,"351 %s :%s %s %s :%s",user->nick,VERSION,"$Id$",ServerName,SYSTEM);
3608 }
3609
3610 void handle_ping(char **parameters, int pcnt, userrec *user)
3611 {
3612         WriteServ(user->fd,"PONG %s :%s",ServerName,parameters[0]);
3613 }
3614
3615 void handle_pong(char **parameters, int pcnt, userrec *user)
3616 {
3617         // set the user as alive so they survive to next ping
3618         user->lastping = 1;
3619 }
3620
3621 void handle_motd(char **parameters, int pcnt, userrec *user)
3622 {
3623         ShowMOTD(user);
3624 }
3625
3626 void handle_rules(char **parameters, int pcnt, userrec *user)
3627 {
3628         ShowRULES(user);
3629 }
3630
3631 void handle_user(char **parameters, int pcnt, userrec *user)
3632 {
3633         if (user->registered < 3)
3634         {
3635                 if (isident(parameters[0]) == 0) {
3636                         // This kinda Sucks, According to the RFC thou, its either this,
3637                         // or "You have already registered" :p -- Craig
3638                         WriteServ(user->fd,"461 %s USER :Not enough parameters",user->nick);
3639                 }
3640                 else {
3641                         WriteServ(user->fd,"NOTICE Auth :No ident response, ident prefixed with ~");
3642                         strcpy(user->ident,"~"); /* we arent checking ident... but these days why bother anyway? */
3643                         strncat(user->ident,parameters[0],IDENTMAX);
3644                         strncpy(user->fullname,parameters[3],128);
3645                         user->registered = (user->registered | 1);
3646                 }
3647         }
3648         else
3649         {
3650                 WriteServ(user->fd,"462 %s :You may not reregister",user->nick);
3651                 return;
3652         }
3653         /* parameters 2 and 3 are local and remote hosts, ignored when sent by client connection */
3654         if (user->registered == 3)
3655         {
3656                 /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
3657                 ConnectUser(user);
3658         }
3659 }
3660
3661 void handle_userhost(char **parameters, int pcnt, userrec *user)
3662 {
3663         char Return[MAXBUF],junk[MAXBUF];
3664         sprintf(Return,"302 %s :",user->nick);
3665         for (int i = 0; i < pcnt; i++)
3666         {
3667                 userrec *u = Find(parameters[i]);
3668                 if (u)
3669                 {
3670                         if (strchr(u->modes,'o'))
3671                         {
3672                                 sprintf(junk,"%s*=+%s@%s ",u->nick,u->ident,u->host);
3673                                 strcat(Return,junk);
3674                         }
3675                         else
3676                         {
3677                                 sprintf(junk,"%s=+%s@%s ",u->nick,u->ident,u->host);
3678                                 strcat(Return,junk);
3679                         }
3680                 }
3681         }
3682         WriteServ(user->fd,Return);
3683 }
3684
3685
3686 void handle_ison(char **parameters, int pcnt, userrec *user)
3687 {
3688         char Return[MAXBUF];
3689         sprintf(Return,"303 %s :",user->nick);
3690         for (int i = 0; i < pcnt; i++)
3691         {
3692                 userrec *u = Find(parameters[i]);
3693                 if (u)
3694                 {
3695                         strcat(Return,u->nick);
3696                         strcat(Return," ");
3697                 }
3698         }
3699         WriteServ(user->fd,Return);
3700 }
3701
3702
3703 void handle_away(char **parameters, int pcnt, userrec *user)
3704 {
3705         if (pcnt)
3706         {
3707                 strcpy(user->awaymsg,parameters[0]);
3708                 WriteServ(user->fd,"306 %s :You have been marked as being away",user->nick);
3709         }
3710         else
3711         {
3712                 strcpy(user->awaymsg,"");
3713                 WriteServ(user->fd,"305 %s :You are no longer marked as being away",user->nick);
3714         }
3715 }
3716
3717 void handle_whowas(char **parameters, int pcnt, userrec* user)
3718 {
3719         user_hash::iterator i = whowas.find(parameters[0]);
3720
3721         if (i == whowas.end())
3722         {
3723                 WriteServ(user->fd,"406 %s %s :There was no such nickname",user->nick,parameters[0]);
3724                 WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
3725         }
3726         else
3727         {
3728                 time_t rawtime = i->second->signon;
3729                 tm *timeinfo;
3730                 char b[MAXBUF];
3731                 
3732                 timeinfo = localtime(&rawtime);
3733                 strcpy(b,asctime(timeinfo));
3734                 b[strlen(b)-1] = '\0';
3735                 
3736                 WriteServ(user->fd,"314 %s %s %s %s * :%s",user->nick,i->second->nick,i->second->ident,i->second->dhost,i->second->fullname);
3737                 WriteServ(user->fd,"312 %s %s %s :%s",user->nick,i->second->nick,i->second->server,b);
3738                 WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
3739         }
3740
3741 }
3742
3743 void handle_trace(char **parameters, int pcnt, userrec *user)
3744 {
3745         for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
3746         {
3747                 if (i->second)
3748                 {
3749                         if (isnick(i->second->nick))
3750                         {
3751                                 if (strchr(i->second->modes,'o'))
3752                                 {
3753                                         WriteServ(user->fd,"205 %s :Oper 0 %s",user->nick,i->second->nick);
3754                                 }
3755                                 else
3756                                 {
3757                                         WriteServ(user->fd,"204 %s :User 0 %s",user->nick,i->second->nick);
3758                                 }
3759                         }
3760                         else
3761                         {
3762                                 WriteServ(user->fd,"203 %s :???? 0 [%s]",user->nick,i->second->host);
3763                         }
3764                 }
3765         }
3766 }
3767
3768 void handle_stats(char **parameters, int pcnt, userrec *user)
3769 {
3770         if (pcnt != 1)
3771         {
3772                 return;
3773         }
3774         if (strlen(parameters[0])>1)
3775         {
3776                 /* make the stats query 1 character long */
3777                 parameters[0][1] = '\0';
3778         }
3779
3780         /* stats m (list number of times each command has been used, plus bytecount) */
3781         if (!strcasecmp(parameters[0],"m"))
3782         {
3783                 for (int i = 0; i < cmdlist.size(); i++)
3784                 {
3785                         if (cmdlist[i].handler_function)
3786                         {
3787                                 if (cmdlist[i].use_count)
3788                                 {
3789                                         /* RPL_STATSCOMMANDS */
3790                                         WriteServ(user->fd,"212 %s %s %d %d",user->nick,cmdlist[i].command,cmdlist[i].use_count,cmdlist[i].total_bytes);
3791                                 }
3792                         }
3793                 }
3794                         
3795         }
3796
3797         /* stats z (debug and memory info) */
3798         if (!strcasecmp(parameters[0],"z"))
3799         {
3800                 WriteServ(user->fd,"249 %s :Users(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,clientlist.size(),clientlist.size()*sizeof(userrec),clientlist.bucket_count());
3801                 WriteServ(user->fd,"249 %s :Channels(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,chanlist.size(),chanlist.size()*sizeof(chanrec),chanlist.bucket_count());
3802                 WriteServ(user->fd,"249 %s :Commands(VECTOR) %d (%d bytes)",user->nick,cmdlist.size(),cmdlist.size()*sizeof(command_t));
3803                 WriteServ(user->fd,"249 %s :MOTD(VECTOR) %d, RULES(VECTOR) %d",user->nick,MOTD.size(),RULES.size());
3804                 WriteServ(user->fd,"249 %s :address_cache(HASH_MAP) %d (%d buckets)",user->nick,IP.size(),IP.bucket_count());
3805                 WriteServ(user->fd,"249 %s :Modules(VECTOR) %d (%d)",user->nick,modules.size(),modules.size()*sizeof(Module));
3806                 WriteServ(user->fd,"249 %s :ClassFactories(VECTOR) %d (%d)",user->nick,factory.size(),factory.size()*sizeof(ircd_module));
3807                 WriteServ(user->fd,"249 %s :Ports(STATIC_ARRAY) %d",user->nick,boundPortCount);
3808         }
3809         
3810         /* stats o */
3811         if (!strcasecmp(parameters[0],"o"))
3812         {
3813                 for (int i = 0; i < ConfValueEnum("oper"); i++)
3814                 {
3815                         char LoginName[MAXBUF];
3816                         char HostName[MAXBUF];
3817                         char OperType[MAXBUF];
3818                         ConfValue("oper","name",i,LoginName);
3819                         ConfValue("oper","host",i,HostName);
3820                         ConfValue("oper","type",i,OperType);
3821                         WriteServ(user->fd,"243 %s O %s * %s %s 0",user->nick,HostName,LoginName,OperType);
3822                 }
3823         }
3824         
3825         /* stats l (show user I/O stats) */
3826         if (!strcasecmp(parameters[0],"l"))
3827         {
3828                 WriteServ(user->fd,"211 %s :server:port nick bytes_in cmds_in bytes_out cmds_out",user->nick);
3829                 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
3830                 {
3831                         if (isnick(i->second->nick))
3832                         {
3833                                 WriteServ(user->fd,"211 %s :%s:%d %s %d %d %d %d",user->nick,ServerName,i->second->port,i->second->nick,i->second->bytes_in,i->second->cmds_in,i->second->bytes_out,i->second->cmds_out);
3834                         }
3835                         else
3836                         {
3837                                 WriteServ(user->fd,"211 %s :%s:%d (unknown@%d) %d %d %d %d",user->nick,ServerName,i->second->port,i->second->fd,i->second->bytes_in,i->second->cmds_in,i->second->bytes_out,i->second->cmds_out);
3838                         }
3839                         
3840                 }
3841         }
3842         
3843         /* stats u (show server uptime) */
3844         if (!strcasecmp(parameters[0],"u"))
3845         {
3846                 time_t current_time = 0;
3847                 current_time = time(NULL);
3848                 time_t server_uptime = current_time - startup_time;
3849                 struct tm* stime;
3850                 stime = gmtime(&server_uptime);
3851                 /* i dont know who the hell would have an ircd running for over a year nonstop, but
3852                  * Craig suggested this, and it seemed a good idea so in it went */
3853                 if (stime->tm_year > 70)
3854                 {
3855                         WriteServ(user->fd,"242 %s :Server up %d years, %d days, %.2d:%.2d:%.2d",user->nick,(stime->tm_year-70),stime->tm_yday,stime->tm_hour,stime->tm_min,stime->tm_sec);
3856                 }
3857                 else
3858                 {
3859                         WriteServ(user->fd,"242 %s :Server up %d days, %.2d:%.2d:%.2d",user->nick,stime->tm_yday,stime->tm_hour,stime->tm_min,stime->tm_sec);
3860                 }
3861         }
3862
3863         WriteServ(user->fd,"219 %s %s :End of /STATS report",user->nick,parameters[0]);
3864         WriteOpers("*** Notice: Stats '%s' requested by %s (%s@%s)",parameters[0],user->nick,user->ident,user->host);
3865         
3866 }
3867
3868 void handle_connect(char **parameters, int pcnt, userrec *user)
3869 {
3870         char Link_ServerName[1024];
3871         char Link_IPAddr[1024];
3872         char Link_Port[1024];
3873         char Link_Pass[1024];
3874         int LinkPort;
3875         bool found = false;
3876         
3877         for (int i = 0; i < ConfValueEnum("link"); i++)
3878         {
3879                 ConfValue("link","name",i,Link_ServerName);
3880                 ConfValue("link","ipaddr",i,Link_IPAddr);
3881                 ConfValue("link","port",i,Link_Port);
3882                 ConfValue("link","sendpass",i,Link_Pass);
3883                 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
3884                 LinkPort = atoi(Link_Port);
3885                 if (match(Link_ServerName,parameters[0])) {
3886                         found = true;
3887                 }
3888         }
3889         
3890         if (!found) {
3891                 WriteServ(user->fd,"NOTICE %s :*** Failed to connect to %s: No servers matching this pattern are configured for linking.",user->nick,parameters[0]);
3892                 return;
3893         }
3894         
3895         // TODO: Perform a check here to stop a server being linked twice!
3896
3897         WriteServ(user->fd,"NOTICE %s :*** Connecting to %s (%s) port %s...",user->nick,Link_ServerName,Link_IPAddr,Link_Port);
3898
3899         if (me[defaultRoute])
3900         {
3901
3902                 // at this point parameters[0] is an ip in a string.
3903                 // TODO: Look this up from the <link> blocks instead!
3904                 for (int j = 0; j < 255; j++) {
3905                         if (servers[j] == NULL) {
3906                                 servers[j] = new serverrec;
3907                                 strcpy(servers[j]->internal_addr,Link_IPAddr);
3908                                 strcpy(servers[j]->name,Link_ServerName);
3909                                 log(DEBUG,"Allocated new serverrec");
3910                                 if (!me[defaultRoute]->BeginLink(Link_IPAddr,LinkPort,Link_Pass))
3911                                 {
3912                                         WriteServ(user->fd,"NOTICE %s :*** Failed to send auth packet to %s!",user->nick,Link_IPAddr);
3913                                 }
3914                                 return;
3915                         }
3916                 }
3917                 WriteServ(user->fd,"NOTICE %s :*** Failed to create server record for address %s!",user->nick,Link_IPAddr);
3918         }
3919         else
3920         {
3921                 WriteServ(user->fd,"NOTICE %s :No default route is defined for server connections on this server. You must define a server connection to be default route so that sockets can be bound to it.",user->nick);
3922         }
3923 }
3924
3925 void handle_squit(char **parameters, int pcnt, userrec *user)
3926 {
3927         // send out an squit across the mesh and then clear the server list (for local squit)
3928 }
3929
3930 void handle_oper(char **parameters, int pcnt, userrec *user)
3931 {
3932         char LoginName[MAXBUF];
3933         char Password[MAXBUF];
3934         char OperType[MAXBUF];
3935         char TypeName[MAXBUF];
3936         char Hostname[MAXBUF];
3937         int i,j;
3938
3939         for (i = 0; i < ConfValueEnum("oper"); i++)
3940         {
3941                 ConfValue("oper","name",i,LoginName);
3942                 ConfValue("oper","password",i,Password);
3943                 if ((!strcmp(LoginName,parameters[0])) && (!strcmp(Password,parameters[1])))
3944                 {
3945                         /* correct oper credentials */
3946                         ConfValue("oper","type",i,OperType);
3947                         WriteOpers("*** %s (%s@%s) is now an IRC operator of type %s",user->nick,user->ident,user->host,OperType);
3948                         WriteServ(user->fd,"381 %s :You are now an IRC operator of type %s",user->nick,OperType);
3949                         WriteServ(user->fd,"MODE %s :+o",user->nick);
3950                         for (j =0; j < ConfValueEnum("type"); j++)
3951                         {
3952                                 ConfValue("type","name",j,TypeName);
3953                                 if (!strcmp(TypeName,OperType))
3954                                 {
3955                                         /* found this oper's opertype */
3956                                         ConfValue("type","host",j,Hostname);
3957                                         strncpy(user->dhost,Hostname,256);
3958                                 }
3959                         }
3960                         if (!strchr(user->modes,'o'))
3961                         {
3962                                 strcat(user->modes,"o");
3963                         }
3964                         return;
3965                 }
3966         }
3967         /* no such oper */
3968         WriteServ(user->fd,"491 %s :Invalid oper credentials",user->nick);
3969         WriteOpers("*** WARNING! Failed oper attempt by %s!%s@%s!",user->nick,user->ident,user->host);
3970 }
3971                                 
3972 void handle_nick(char **parameters, int pcnt, userrec *user)
3973 {
3974         if (pcnt < 1) 
3975         {
3976                 log(DEBUG,"not enough params for handle_nick");
3977                 return;
3978         }
3979         if (!parameters[0])
3980         {
3981                 log(DEBUG,"invalid parameter passed to handle_nick");
3982                 return;
3983         }
3984         if (!strlen(parameters[0]))
3985         {
3986                 log(DEBUG,"zero length new nick passed to handle_nick");
3987                 return;
3988         }
3989         if (!user)
3990         {
3991                 log(DEBUG,"invalid user passed to handle_nick");
3992                 return;
3993         }
3994         if (!user->nick)
3995         {
3996                 log(DEBUG,"invalid old nick passed to handle_nick");
3997                 return;
3998         }
3999         if (!strcasecmp(user->nick,parameters[0]))
4000         {
4001                 log(DEBUG,"old nick is new nick, skipping");
4002                 return;
4003         }
4004         else
4005         {
4006                 if (strlen(parameters[0]) > 1)
4007                 {
4008                         if (parameters[0][0] == ':')
4009                         {
4010                                 *parameters[0]++;
4011                         }
4012                 }
4013                 if ((Find(parameters[0])) && (Find(parameters[0]) != user))
4014                 {
4015                         WriteServ(user->fd,"433 %s %s :Nickname is already in use.",user->nick,parameters[0]);
4016                         return;
4017                 }
4018         }
4019         if (isnick(parameters[0]) == 0)
4020         {
4021                 WriteServ(user->fd,"432 %s %s :Erroneous Nickname",user->nick,parameters[0]);
4022                 return;
4023         }
4024
4025         if (user->registered == 7)
4026         {
4027                 WriteCommon(user,"NICK %s",parameters[0]);
4028         }
4029         
4030         /* change the nick of the user in the users_hash */
4031         user = ReHashNick(user->nick, parameters[0]);
4032         /* actually change the nick within the record */
4033         if (!user) return;
4034         if (!user->nick) return;
4035
4036         strncpy(user->nick, parameters[0],NICKMAX);
4037
4038         log(DEBUG,"new nick set: %s",user->nick);
4039         
4040         if (user->registered < 3)
4041                 user->registered = (user->registered | 2);
4042         if (user->registered == 3)
4043         {
4044                 /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
4045                 ConnectUser(user);
4046         }
4047         log(DEBUG,"exit nickchange: %s",user->nick);
4048 }
4049
4050 int process_parameters(char **command_p,char *parameters)
4051 {
4052         int i = 0;
4053         int j = 0;
4054         int q = 0;
4055         q = strlen(parameters);
4056         if (!q)
4057         {
4058                 /* no parameters, command_p invalid! */
4059                 return 0;
4060         }
4061         if (parameters[0] == ':')
4062         {
4063                 command_p[0] = parameters+1;
4064                 return 1;
4065         }
4066         if (q)
4067         {
4068                 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
4069                 {
4070                         /* only one parameter */
4071                         command_p[0] = parameters;
4072                         if (parameters[0] == ':')
4073                         {
4074                                 if (strchr(parameters,' ') != NULL)
4075                                 {
4076                                         command_p[0]++;
4077                                 }
4078                         }
4079                         return 1;
4080                 }
4081         }
4082         command_p[j++] = parameters;
4083         for (i = 0; i <= q; i++)
4084         {
4085                 if (parameters[i] == ' ')
4086                 {
4087                         command_p[j++] = parameters+i+1;
4088                         parameters[i] = '\0';
4089                         if (command_p[j-1][0] == ':')
4090                         {
4091                                 *command_p[j-1]++; /* remove dodgy ":" */
4092                                 break;
4093                                 /* parameter like this marks end of the sequence */
4094                         }
4095                 }
4096         }
4097         return j; /* returns total number of items in the list */
4098 }
4099
4100 void process_command(userrec *user, char* cmd)
4101 {
4102         char *parameters;
4103         char *command;
4104         char *command_p[127];
4105         char p[MAXBUF], temp[MAXBUF];
4106         int i, j, items, cmd_found;
4107
4108         for (int i = 0; i < 127; i++)
4109                 command_p[i] = NULL;
4110
4111         if (!user)
4112         {
4113                 return;
4114         }
4115         if (!cmd)
4116         {
4117                 return;
4118         }
4119         if (!strcmp(cmd,""))
4120         {
4121                 return;
4122         }
4123         strcpy(temp,cmd);
4124
4125         string tmp = cmd;
4126         FOREACH_MOD OnServerRaw(tmp,true);
4127         const char* cmd2 = tmp.c_str();
4128         snprintf(cmd,512,"%s",cmd2);
4129
4130         if (!strchr(cmd,' '))
4131         {
4132                 /* no parameters, lets skip the formalities and not chop up
4133                  * the string */
4134                 items = 0;
4135                 command_p[0] = NULL;
4136                 parameters = NULL;
4137                 for (int i = 0; i <= strlen(cmd); i++)
4138                 {
4139                         cmd[i] = toupper(cmd[i]);
4140                 }
4141         }
4142         else
4143         {
4144                 strcpy(cmd,"");
4145                 j = 0;
4146                 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
4147                 for (i = 0; i < strlen(temp); i++)
4148                 {
4149                         if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
4150                         {
4151                                 cmd[j++] = temp[i];
4152                                 cmd[j] = 0;
4153                         }
4154                 }
4155                 /* split the full string into a command plus parameters */
4156                 parameters = p;
4157                 strcpy(p," ");
4158                 command = cmd;
4159                 if (strchr(cmd,' '))
4160                 {
4161                         for (i = 0; i <= strlen(cmd); i++)
4162                         {
4163                                 /* capitalise the command ONLY, leave params intact */
4164                                 cmd[i] = toupper(cmd[i]);
4165                                 /* are we nearly there yet?! :P */
4166                                 if (cmd[i] == ' ')
4167                                 {
4168                                         command = cmd;
4169                                         parameters = cmd+i+1;
4170                                         cmd[i] = '\0';
4171                                         break;
4172                                 }
4173                         }
4174                 }
4175                 else
4176                 {
4177                         for (i = 0; i <= strlen(cmd); i++)
4178                         {
4179                                 cmd[i] = toupper(cmd[i]);
4180                         }
4181                 }
4182
4183         }
4184         
4185         cmd_found = 0;
4186
4187         for (i = 0; i != cmdlist.size(); i++)
4188         {
4189                 if (strcmp(cmdlist[i].command,""))
4190                 {
4191                         if (!strcmp(command, cmdlist[i].command))
4192                         {
4193                                 if (parameters)
4194                                 {
4195                                         if (strcmp(parameters,""))
4196                                         {
4197                                                 items = process_parameters(command_p,parameters);
4198                                         }
4199                                         else
4200                                         {
4201                                                 items = 0;
4202                                                 command_p[0] = NULL;
4203                                         }
4204                                 }
4205                                 else
4206                                 {
4207                                         items = 0;
4208                                         command_p[0] = NULL;
4209                                 }
4210                                 
4211                                 if (user)
4212                                 {
4213                                         user->idle_lastmsg = time(NULL);
4214                                         /* activity resets the ping pending timer */
4215                                         user->nping = time(NULL) + 120;
4216                                         if ((items) < cmdlist[i].min_params)
4217                                         {
4218                                                 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
4219                                                 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
4220                                                 return;
4221                                         }
4222                                         if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
4223                                         {
4224                                                 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
4225                                                 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
4226                                                 cmd_found = 1;
4227                                                 return;
4228                                         }
4229                 /* if the command isnt USER, PASS, or NICK, and nick is empty,
4230                  * deny command! */
4231                                         if ((strcmp(command,"USER")) && (strcmp(command,"NICK")) && (strcmp(command,"PASS")))
4232                                         {
4233                                                 if ((!isnick(user->nick)) || (user->registered != 7))
4234                                                 {
4235                                                         log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
4236                                                         WriteServ(user->fd,"451 %s :You have not registered",command);
4237                                                         return;
4238                                                 }
4239                                         }
4240                                         if ((user->registered == 7) || (!strcmp(command,"USER")) || (!strcmp(command,"NICK")) || (!strcmp(command,"PASS")))
4241                                         {
4242                                                 log(DEBUG,"process_command: handler: %s %s %d",user->nick,command,items);
4243                                                 if (cmdlist[i].handler_function)
4244                                                 {
4245                                                         /* ikky /stats counters */
4246                                                         if (temp)
4247                                                         {
4248                                                                 if (user)
4249                                                                 {
4250                                                                         user->bytes_in += strlen(temp);
4251                                                                         user->cmds_in++;
4252                                                                 }
4253                                                                 cmdlist[i].use_count++;
4254                                                                 cmdlist[i].total_bytes+=strlen(temp);
4255                                                         }
4256
4257                                                         /* WARNING: nothing may come after the
4258                                                          * command handler call, as the handler
4259                                                          * may free the user structure! */
4260
4261                                                         cmdlist[i].handler_function(command_p,items,user);
4262                                                 }
4263                                                 return;
4264                                         }
4265                                         else
4266                                         {
4267                                                 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
4268                                                 WriteServ(user->fd,"451 %s :You have not registered",command);
4269                                                 return;
4270                                         }
4271                                 }
4272                                 cmd_found = 1;
4273                         }
4274                 }
4275         }
4276         if ((!cmd_found) && (user))
4277         {
4278                 log(DEBUG,"process_command: not in table: %s %s",user->nick,command);
4279                 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
4280         }
4281 }
4282
4283
4284 void createcommand(char* cmd, handlerfunc f, char flags, int minparams)
4285 {
4286         command_t comm;
4287         /* create the command and push it onto the table */     
4288         strcpy(comm.command,cmd);
4289         comm.handler_function = f;
4290         comm.flags_needed = flags;
4291         comm.min_params = minparams;
4292         comm.use_count = 0;
4293         comm.total_bytes = 0;
4294         cmdlist.push_back(comm);
4295         log(DEBUG,"Added command %s (%d parameters)",cmd,minparams);
4296 }
4297
4298 void SetupCommandTable(void)
4299 {
4300   createcommand("USER",handle_user,0,4);
4301   createcommand("NICK",handle_nick,0,1);
4302   createcommand("QUIT",handle_quit,0,0);
4303   createcommand("VERSION",handle_version,0,0);
4304   createcommand("PING",handle_ping,0,1);
4305   createcommand("PONG",handle_pong,0,1);
4306   createcommand("ADMIN",handle_admin,0,0);
4307   createcommand("PRIVMSG",handle_privmsg,0,2);
4308   createcommand("INFO",handle_info,0,0);
4309   createcommand("TIME",handle_time,0,0);
4310   createcommand("WHOIS",handle_whois,0,1);
4311   createcommand("WALLOPS",handle_wallops,'o',1);
4312   createcommand("NOTICE",handle_notice,0,2);
4313   createcommand("JOIN",handle_join,0,1);
4314   createcommand("NAMES",handle_names,0,1);
4315   createcommand("PART",handle_part,0,1);
4316   createcommand("KICK",handle_kick,0,2);
4317   createcommand("MODE",handle_mode,0,1);
4318   createcommand("TOPIC",handle_topic,0,1);
4319   createcommand("WHO",handle_who,0,1);
4320   createcommand("MOTD",handle_motd,0,0);
4321   createcommand("RULES",handle_join,0,0);
4322   createcommand("OPER",handle_oper,0,2);
4323   createcommand("LIST",handle_list,0,0);
4324   createcommand("DIE",handle_die,'o',1);
4325   createcommand("RESTART",handle_restart,'o',1);
4326   createcommand("KILL",handle_kill,'o',2);
4327   createcommand("REHASH",handle_rehash,'o',0);
4328   createcommand("LUSERS",handle_lusers,0,0);
4329   createcommand("STATS",handle_stats,0,1);
4330   createcommand("USERHOST",handle_userhost,0,1);
4331   createcommand("AWAY",handle_away,0,0);
4332   createcommand("ISON",handle_ison,0,0);
4333   createcommand("SUMMON",handle_summon,0,0);
4334   createcommand("USERS",handle_users,0,0);
4335   createcommand("INVITE",handle_invite,0,2);
4336   createcommand("PASS",handle_pass,0,1);
4337   createcommand("TRACE",handle_trace,'o',0);
4338   createcommand("WHOWAS",handle_whowas,0,1);
4339   createcommand("CONNECT",handle_connect,'o',1);
4340   createcommand("SQUIT",handle_squit,'o',1);
4341 }
4342
4343 void process_buffer(userrec *user)
4344 {
4345         char cmd[MAXBUF];
4346         int i;
4347         if (!user->inbuf)
4348         {
4349                 return;
4350         }
4351         if (!strcmp(user->inbuf,""))
4352         {
4353                 return;
4354         }
4355         strncpy(cmd,user->inbuf,MAXBUF);
4356         if (!strcmp(cmd,""))
4357         {
4358                 return;
4359         }
4360         if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
4361         {
4362                 cmd[strlen(cmd)-1] = '\0';
4363         }
4364         if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
4365         {
4366                 cmd[strlen(cmd)-1] = '\0';
4367         }
4368         strcpy(user->inbuf,"");
4369         if (!strcmp(cmd,""))
4370         {
4371                 return;
4372         }
4373         log(DEBUG,"InspIRCd: processing: %s %s",user->nick,cmd);
4374         tidystring(cmd);
4375         process_command(user,cmd);
4376 }
4377
4378 void process_restricted_commands(char token,char* params,serverrec* source,serverrec* reply, char* udp_host,int udp_port)
4379 {
4380         WriteOpers("Secure-UDP-Channel: Token='%c', Params='%s'",token,params);
4381 }
4382
4383
4384 void handle_link_packet(long theirkey, char* udp_msg, char* udp_host, int udp_port, serverrec *serv)
4385 {
4386         char response[10240];
4387         char token = udp_msg[0];
4388         char* params = udp_msg + 2;
4389         char finalparam[1024];
4390         strcpy(finalparam," :xxxx");
4391         if (strstr(params," :")) {
4392                 strncpy(finalparam,strstr(params," :"),1024);
4393         }
4394         if (token == 'S') {
4395                 // S test.chatspike.net password :ChatSpike InspIRCd test server
4396                 char* servername = strtok(params," ");
4397                 char* password = strtok(NULL," ");
4398                 char* serverdesc = finalparam+2;
4399                 WriteOpers("CONNECT from %s (%s)",servername,udp_host,password,serverdesc);
4400                 
4401                 
4402                 char Link_ServerName[1024];
4403                 char Link_IPAddr[1024];
4404                 char Link_Port[1024];
4405                 char Link_Pass[1024];
4406                 char Link_SendPass[1024];
4407                 int LinkPort = 0;
4408                 
4409                 // search for a corresponding <link> block in the config files
4410                 for (int i = 0; i < ConfValueEnum("link"); i++)
4411                 {
4412                         ConfValue("link","name",i,Link_ServerName);
4413                         ConfValue("link","ipaddr",i,Link_IPAddr);
4414                         ConfValue("link","port",i,Link_Port);
4415                         ConfValue("link","recvpass",i,Link_Pass);
4416                         ConfValue("link","sendpass",i,Link_SendPass);
4417                         log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
4418                         LinkPort = atoi(Link_Port);
4419                         if (!strcasecmp(Link_ServerName,servername)) {
4420                                 if (!strcasecmp(Link_IPAddr,udp_host)) {
4421                                         if (LinkPort == udp_port) {
4422                                                 // we have a matching link line -
4423                                                 // send a 'diminutive' server message back...
4424                                                 snprintf(response,10240,"s %s %s :%s",ServerName,Link_SendPass,ServerDesc);
4425                                                 serv->SendPacket(response,udp_host,udp_port,0);
4426                                                 WriteOpers("CONNECT from %s accepted, authenticating",servername);
4427                                                 for (int j = 0; j < 255; j++) {
4428                                                         if (servers[j] == NULL) {
4429                                                                 servers[j] = new serverrec;
4430                                                                 strcpy(servers[j]->internal_addr,udp_host);
4431                                                                 strcpy(servers[j]->name,servername);
4432                                                                 // create a server record for this server
4433                                                                 snprintf(response,10240,"O %d",MyKey);
4434                                                                 serv->SendPacket(response,udp_host,udp_port,0);
4435                                                                 return;
4436                                                         }
4437                                                 }
4438                                                 WriteOpers("Internal error connecting to %s, failed to create server record!",servername);
4439                                                 return;
4440                                         }
4441                                         else {
4442                                                 log(DEBUG,"Port numbers '%d' and '%d' don't match",LinkPort,udp_port);
4443                                         }
4444                                 }
4445                                 else {
4446                                         log(DEBUG,"IP Addresses '%s' and '%s' don't match",Link_IPAddr,udp_host);
4447                                 }
4448                         }
4449                         else {
4450                                 log(DEBUG,"Server names '%s' and '%s' don't match",Link_ServerName,servername);
4451                         }
4452                 }
4453                 serv->SendPacket("E :Access is denied (no matching link block)",udp_host,udp_port,0);
4454                 WriteOpers("CONNECT from %s denied, no matching link block",servername);
4455                 return;
4456         }
4457         else
4458         if (token == 'O') {
4459                 // if this is received, this means the server-ip that sent it said "OK" to credentials.
4460                 // only when a server says this do we exchange keys. The server MUST have an entry in the servers
4461                 // array, which is only added by an 'S' packet or BeginLink().
4462                 for (int i = 0; i < 255; i++) {
4463                         if (servers[i] != NULL) {
4464                                 if (!strcasecmp(servers[i]->internal_addr,udp_host)) {
4465                                         servers[i]->key = atoi(params);
4466                                         log(DEBUG,"Key for this server is now %d",servers[i]->key);
4467                                         serv->SendPacket("Z blah blah",udp_host,udp_port,MyKey);
4468                                         return;
4469                                 }
4470                         }
4471                 }
4472                 WriteOpers("\2WARNING!\2 Server ip %s attempted a key exchange, but is not in the authentication state! Possible intrusion attempt!",udp_host);
4473         }
4474         else
4475         if (token == 's') {
4476                 // S test.chatspike.net password :ChatSpike InspIRCd test server
4477                 char* servername = strtok(params," ");
4478                 char* password = strtok(NULL," ");
4479                 char* serverdesc = finalparam+2;
4480                 
4481                 // TODO: we should do a check here to ensure that this server is one we recently initiated a
4482                 // link with, and didnt hear an 's' or 'E' back from yet (these are the only two valid responses
4483                 // to an 'S' command. If we didn't recently send an 'S' to this server, theyre trying to spoof
4484                 // a connect, so put out an oper alert!
4485                 
4486                 
4487                 
4488                 
4489                 // for now, just accept all, we'll fix that later.
4490                 WriteOpers("%s accepted our link credentials ",servername);
4491                 
4492                 char Link_ServerName[1024];
4493                 char Link_IPAddr[1024];
4494                 char Link_Port[1024];
4495                 char Link_Pass[1024];
4496                 char Link_SendPass[1024];
4497                 int LinkPort = 0;
4498                 
4499                 // search for a corresponding <link> block in the config files
4500                 for (int i = 0; i < ConfValueEnum("link"); i++)
4501                 {
4502                         ConfValue("link","name",i,Link_ServerName);
4503                         ConfValue("link","ipaddr",i,Link_IPAddr);
4504                         ConfValue("link","port",i,Link_Port);
4505                         ConfValue("link","recvpass",i,Link_Pass);
4506                         ConfValue("link","sendpass",i,Link_SendPass);
4507                         log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
4508                         LinkPort = atoi(Link_Port);
4509                         if (!strcasecmp(Link_ServerName,servername)) {
4510                                 if (!strcasecmp(Link_IPAddr,udp_host)) {
4511                                         if (LinkPort == udp_port) {
4512                                                 // matching link at this end too, we're all done!
4513                                                 // at this point we must begin key exchange and insert this
4514                                                 // server into our 'active' table.
4515                                                 for (int j = 0; j < 255; j++) {
4516                                                         if (servers[j] != NULL) {
4517                                                                 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
4518                                                                         WriteOpers("Server %s authenticated, exchanging server keys...",servername);
4519                                                                         snprintf(response,10240,"O %d",MyKey);
4520                                                                         serv->SendPacket(response,udp_host,udp_port,0);
4521                                                                         return;
4522                                                                 }
4523                                                         }
4524                                                 }
4525                                                 WriteOpers("\2WARNING!\2 %s sent us an authentication packet but we are not authenticating with this server right noe! Possible intrusion attempt!",udp_host);
4526                                                 return;
4527
4528                                         }
4529                                         else {
4530                                                 log(DEBUG,"Port numbers '%d' and '%d' don't match",LinkPort,udp_port);
4531                                         }
4532                                 }
4533                                 else {
4534                                         log(DEBUG,"IP Addresses '%s' and '%s' don't match",Link_IPAddr,udp_host);
4535                                 }
4536                         }
4537                         else {
4538                                 log(DEBUG,"Server names '%s' and '%s' don't match",Link_ServerName,servername);
4539                         }
4540                 }
4541                 serv->SendPacket("E :Access is denied (no matching link block)",udp_host,udp_port,0);
4542                 WriteOpers("CONNECT from %s denied, no matching link block",servername);
4543                 return;
4544         }
4545         else
4546         if (token == 'E') {
4547                 char* error_message = finalparam+2;
4548                 WriteOpers("ERROR from %s: %s",udp_host,error_message);
4549                 // remove this server from any lists
4550                 for (int j = 0; j < 255; j++) {
4551                         if (servers[j] != NULL) {
4552                                 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
4553                                         delete servers[j];
4554                                         return;
4555                                 }
4556                         }
4557                 }
4558                 return;
4559         }
4560         else {
4561
4562                 serverrec* source_server = NULL;
4563
4564                 for (int j = 0; j < 255; j++) {
4565                         if (servers[j] != NULL) {
4566                                 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
4567                                         if (servers[j]->key == theirkey) {
4568                                                 // found a valid key for this server, can process restricted stuff here
4569                                                 process_restricted_commands(token,params,servers[j],serv,udp_host,udp_port);
4570                                                 
4571                                                 return;
4572                                         }
4573                                 }
4574                         }
4575                 }
4576
4577                 log(DEBUG,"Unrecognised token or unauthenticated host in datagram from %s:%d: %c",udp_host,udp_port,token);
4578         }
4579 }
4580
4581 int reap_counter = 0;
4582
4583 int InspIRCd(void)
4584 {
4585   struct sockaddr_in client, server;
4586   char addrs[MAXBUF][255];
4587   int openSockfd[MAXSOCKS], incomingSockfd, result = TRUE;
4588   socklen_t length;
4589   int count = 0, scanDetectTrigger = TRUE, showBanner = FALSE;
4590   int selectResult = 0;
4591   char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
4592   char resolvedHost[MAXBUF];
4593   fd_set selectFds;
4594   struct timeval tv;
4595
4596   log(DEBUG,"InspIRCd: startup: begin");
4597   log(DEBUG,"$Id$");
4598   if (geteuid() == 0)
4599   {
4600         printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
4601         Exit(ERROR);
4602         log(DEBUG,"InspIRCd: startup: not starting with UID 0!");
4603   }
4604   SetupCommandTable();
4605   log(DEBUG,"InspIRCd: startup: default command table set up");
4606
4607   ReadConfig();
4608   if (strcmp(DieValue,"")) 
4609   { 
4610         printf("WARNING: %s\n\n",DieValue);
4611         exit(0); 
4612   }  
4613   log(DEBUG,"InspIRCd: startup: read config");
4614   
4615   int count2 = 0, count3 = 0;
4616   for (count = 0; count < ConfValueEnum("bind"); count++)
4617   {
4618         ConfValue("bind","port",count,configToken);
4619         ConfValue("bind","address",count,Addr);
4620         ConfValue("bind","type",count,Type);
4621         if (!strcmp(Type,"servers"))
4622         {
4623                 char Default[MAXBUF];
4624                 strcpy(Default,"no");
4625                 ConfValue("bind","default",count,Default);
4626                 if (strchr(Default,'y'))
4627                 {
4628                                 defaultRoute = count3;
4629                                 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
4630                 }
4631                 me[count3] = new serverrec(ServerName,100L,false);
4632                 me[count3]->CreateListener(Addr,atoi(configToken));
4633                 count3++;
4634         }
4635         else
4636         {
4637                 ports[count2] = atoi(configToken);
4638                 strcpy(addrs[count2],Addr);
4639                 count2++;
4640         }
4641         log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
4642   }
4643   portCount = count2;
4644   UDPportCount = count3;
4645   
4646   log(DEBUG,"InspIRCd: startup: read %d total client ports and %d total server ports",portCount,UDPportCount);
4647
4648   log(DEBUG,"InspIRCd: startup: InspIRCd is now running!");
4649
4650   printf("\n");
4651
4652   /* BugFix By Craig! :p */
4653   count2 = 0;
4654   for (count = 0; count2 < ConfValueEnum("module"); count2++)
4655   {
4656         char modfile[MAXBUF];
4657         ConfValue("module","name",count,configToken);
4658         sprintf(modfile,"%s/%s",MOD_PATH,configToken);
4659         printf("Loading module... \033[1;37m%s\033[0;37m\n",modfile);
4660         log(DEBUG,"InspIRCd: startup: Loading module: %s",modfile);
4661         /* If The File Doesnt exist, Trying to load it
4662          * Will Segfault the IRCd.. So, check to see if
4663          * it Exists, Before Proceeding. */
4664         if (FileExists(modfile))
4665         {
4666                 factory[count] = new ircd_module(modfile);
4667                 if (factory[count]->LastError())
4668                 {
4669                         log(DEBUG,"Unable to load %s: %s",modfile,factory[count]->LastError());
4670                         sprintf("Unable to load %s: %s\nExiting...\n",modfile,factory[count]->LastError());
4671                         Exit(ERROR);
4672                 }
4673                 if (factory[count]->factory)
4674                 {
4675                         modules[count] = factory[count]->factory->CreateModule();
4676                         /* save the module and the module's classfactory, if
4677                          * this isnt done, random crashes can occur :/ */
4678                 }
4679                 else
4680                 {
4681                         log(DEBUG,"Unable to load %s",modfile);
4682                         sprintf("Unable to load %s\nExiting...\n",modfile);
4683                         Exit(ERROR);
4684                 }
4685                 /* Increase the Count */
4686                 count++;
4687         }
4688         else
4689         {
4690                 log(DEBUG,"InspIRCd: startup: Module Not Found %s",modfile);
4691                 printf("Module Not Found: \033[1;37m%s\033[0;37m, Skipping\n",modfile);
4692         }
4693   }
4694   MODCOUNT = count - 1;
4695   log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
4696
4697   printf("\nInspIRCd is now running!\n");
4698
4699   startup_time = time(NULL);
4700   
4701   if (nofork)
4702   {
4703         log(VERBOSE,"Not forking as -nofork was specified");
4704   }
4705   else
4706   {
4707         if (DaemonSeed() == ERROR)
4708         {
4709                 log(DEBUG,"InspIRCd: startup: can't daemonise");
4710                 printf("ERROR: could not go into daemon mode. Shutting down.\n");
4711                 Exit(ERROR);
4712         }
4713   }
4714   
4715   
4716   /* setup select call */
4717   FD_ZERO(&selectFds);
4718   log(DEBUG,"InspIRCd: startup: zero selects");
4719   log(VERBOSE,"InspIRCd: startup: portCount = %d", portCount);
4720
4721   for (count = 0; count < portCount; count++)
4722   {
4723           if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
4724       {
4725                 log(DEBUG,"InspIRCd: startup: bad fd %d",openSockfd[boundPortCount]);
4726                 return(ERROR);
4727       }
4728       if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
4729       {
4730                 log(DEBUG,"InspIRCd: startup: failed to bind port %d",ports[count]);
4731       }
4732       else                      /* well we at least bound to one socket so we'll continue */
4733       {
4734                 boundPortCount++;
4735       }
4736   }
4737
4738   log(DEBUG,"InspIRCd: startup: total bound ports %d",boundPortCount);
4739   
4740   /* if we didn't bind to anything then abort */
4741   if (boundPortCount == 0)
4742   {
4743      log(DEBUG,"InspIRCd: startup: no ports bound, bailing!");
4744      return (ERROR);
4745   }
4746
4747   length = sizeof (client);
4748   int flip_flop = 0, udp_port = 0;
4749   char udp_msg[MAXBUF], udp_host[MAXBUF];
4750   
4751   /* main loop for multiplexing/resetting */
4752   for (;;)
4753   {
4754       /* set up select call */
4755       for (count = 0; count < boundPortCount; count++)
4756       {
4757                 FD_SET (openSockfd[count], &selectFds);
4758       }
4759         
4760       /* added timeout! select was waiting forever... wank... :/ */
4761       tv.tv_usec = 0;
4762
4763       flip_flop++;
4764       reap_counter++;
4765       if (flip_flop > 20)
4766       {
4767               tv.tv_usec = 1;
4768               flip_flop = 0;
4769       }
4770       
4771         vector<int>::iterator niterator;
4772                 
4773
4774         // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
4775         // them in a list, then reap the list every second or so.
4776         if (reap_counter>5000) {
4777                 if (fd_reap.size() > 0) {
4778                         for( int n = 0; n < fd_reap.size(); n++)
4779                         {
4780                                 Blocking(fd_reap[n]);
4781                                 close(fd_reap[n]);
4782                                 NonBlocking(fd_reap[n]);
4783                         }
4784                 }
4785                 fd_reap.clear();
4786                 reap_counter=0;
4787         }
4788
4789       
4790       tv.tv_sec = 0;
4791       selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
4792
4793       for (int x = 0; x != UDPportCount; x++)
4794       {
4795            long theirkey = 0;
4796            if (me[x]->RecvPacket(udp_msg, udp_host, udp_port, theirkey))
4797            {
4798                         if (strlen(udp_msg)<1) {
4799                                 log(DEBUG,"Invalid datagram from %s:%d:%d [route%d]",udp_host,udp_port,me[x]->port,x);
4800                         }
4801                         else {
4802                                 FOREACH_MOD OnPacketReceive(udp_msg);
4803                                 // Packets must go back via the route they arrived on :)
4804                                 handle_link_packet(theirkey, udp_msg, udp_host, udp_port, me[x]);
4805                         }
4806            }
4807       }
4808
4809         for (user_hash::iterator count2 = clientlist.begin(); count2 != clientlist.end(); count2++)
4810         {
4811                 char data[MAXBUF];
4812
4813                 if (!count2->second) break;
4814                 
4815                 if (count2->second)
4816                 if (count2->second->fd)
4817                 {
4818                         if (((time(NULL)) > count2->second->nping) && (isnick(count2->second->nick)) && (count2->second->registered == 7))
4819                         {
4820                                 if (!count2->second->lastping) 
4821                                 {
4822                                         log(DEBUG,"InspIRCd: ping timeout: %s",count2->second->nick);
4823                                         kill_link(count2->second,"Ping timeout");
4824                                         break;
4825                                 }
4826                                 Write(count2->second->fd,"PING :%s",ServerName);
4827                                 log(DEBUG,"InspIRCd: pinging: %s",count2->second->nick);
4828                                 count2->second->lastping = 0;
4829                                 count2->second->nping = time(NULL)+120;
4830                         }
4831                         
4832                         result = read(count2->second->fd, data, 1);
4833                         // result EAGAIN means nothing read
4834                         if (result == EAGAIN)
4835                         {
4836                         }
4837                         else
4838                         if (result == 0)
4839                         {
4840                                 log(DEBUG,"InspIRCd: Exited: %s",count2->second->nick);
4841                                 kill_link(count2->second,"Client exited");
4842                         }
4843                         else if (result > 0)
4844                         {
4845                                 strncat(count2->second->inbuf, data, result);
4846                                 if (strchr(count2->second->inbuf, '\n') || strchr(count2->second->inbuf, '\r'))
4847                                 {
4848                                         /* at least one complete line is waiting to be processed */
4849                                         if (!count2->second->fd)
4850                                                 break;
4851                                         else
4852                                         {
4853                                                 process_buffer(count2->second);
4854                                                 break;
4855                                         }
4856                                 }
4857                         }
4858                 }
4859         }
4860
4861       /* select is reporting a waiting socket. Poll them all to find out which */
4862       if (selectResult > 0)
4863       {
4864         char target[MAXBUF], resolved[MAXBUF];
4865         for (count = 0; count < boundPortCount; count++)                
4866         {
4867             if (FD_ISSET (openSockfd[count], &selectFds))
4868             {
4869               incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
4870               
4871               address_cache::iterator iter = IP.find(client.sin_addr);
4872               bool iscached = false;
4873               if (iter == IP.end())
4874               {
4875                         /* ip isn't in cache, add it */
4876                         strncpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
4877                         if(CleanAndResolve(resolved, target) != TRUE)
4878                         {
4879                                 strncpy(resolved,target,MAXBUF);
4880                         }
4881                         /* hostname now in 'target' */
4882                         IP[client.sin_addr] = new string(resolved);
4883               /* hostname in cache */
4884               }
4885               else
4886               {
4887               /* found ip (cached) */
4888               strncpy(resolved, iter->second->c_str(), MAXBUF);
4889               iscached = true;
4890            }
4891
4892               if (incomingSockfd < 0)
4893               {
4894                         WriteOpers("*** WARNING: Accept failed on port %d (%s)", ports[count],target);
4895                         log(DEBUG,"InspIRCd: accept failed: %d",ports[count]);
4896                         break;
4897               }
4898
4899               AddClient(incomingSockfd, resolved, ports[count], iscached);
4900               log(DEBUG,"InspIRCd: adding client on port %d fd=%d",ports[count],incomingSockfd);
4901               break;
4902             }
4903
4904            }
4905       }
4906   }
4907
4908   /* not reached */
4909   close (incomingSockfd);
4910 }
4911