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