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