]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/users.cpp
Move all /WHOWAS related out of core and into cmd_whowas.
[user/henk/code/inspircd.git] / src / users.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2007 InspIRCd Development Team
6  * See: http://www.inspircd.org/wiki/index.php/Credits
7  *
8  * This program is free but copyrighted software; see
9  *            the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 #include "configreader.h"
15 #include "channels.h"
16 #include "users.h"
17 #include "inspircd.h"
18 #include <stdarg.h>
19 #include "socketengine.h"
20 #include "wildcard.h"
21 #include "xline.h"
22 #include "cull_list.h"
23 #include "commands/cmd_whowas.h"
24
25 static unsigned long already_sent[MAX_DESCRIPTORS] = {0};
26
27 /* XXX: Used for speeding up WriteCommon operations */
28 unsigned long uniq_id = 0;
29
30 bool InitTypes(ServerConfig* conf, const char* tag)
31 {
32         if (conf->opertypes.size())
33         {
34                 conf->GetInstance()->Log(DEBUG,"Currently %d items to clear",conf->opertypes.size());
35                 for (opertype_t::iterator n = conf->opertypes.begin(); n != conf->opertypes.end(); n++)
36                 {
37                         conf->GetInstance()->Log(DEBUG,"Clear item");
38                         if (n->second)
39                                 delete[] n->second;
40                 }
41         }
42         
43         conf->opertypes.clear();
44         return true;
45 }
46
47 bool InitClasses(ServerConfig* conf, const char* tag)
48 {
49         if (conf->operclass.size())
50         {
51                 for (operclass_t::iterator n = conf->operclass.begin(); n != conf->operclass.end(); n++)
52                 {
53                         if (n->second)
54                                 delete[] n->second;
55                 }
56         }
57         
58         conf->operclass.clear();
59         return true;
60 }
61
62 bool DoType(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
63 {
64         const char* TypeName = values[0].GetString();
65         const char* Classes = values[1].GetString();
66         
67         conf->opertypes[TypeName] = strdup(Classes);
68         conf->GetInstance()->Log(DEBUG,"Read oper TYPE '%s' with classes '%s'",TypeName,Classes);
69         return true;
70 }
71
72 bool DoClass(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
73 {
74         const char* ClassName = values[0].GetString();
75         const char* CommandList = values[1].GetString();
76         
77         conf->operclass[ClassName] = strdup(CommandList);
78         conf->GetInstance()->Log(DEBUG,"Read oper CLASS '%s' with commands '%s'",ClassName,CommandList);
79         return true;
80 }
81
82 bool DoneClassesAndTypes(ServerConfig* conf, const char* tag)
83 {
84         return true;
85 }
86
87 std::string userrec::ProcessNoticeMasks(const char *sm)
88 {
89         bool adding = true, oldadding = false;
90         const char *c = sm;
91         std::string output;
92
93         ServerInstance->Log(DEBUG,"Process notice masks");
94
95         while (c && *c)
96         {
97                 ServerInstance->Log(DEBUG,"Process notice mask %c",*c);
98                 
99                 switch (*c)
100                 {
101                         case '+':
102                                 adding = true;
103                         break;
104                         case '-':
105                                 adding = false;
106                         break;
107                         case '*':
108                                 for (unsigned char d = 'A'; d <= 'z'; d++)
109                                 {
110                                         if (ServerInstance->SNO->IsEnabled(d))
111                                         {
112                                                 if ((!IsNoticeMaskSet(d) && adding) || (IsNoticeMaskSet(d) && !adding))
113                                                 {
114                                                         if ((oldadding != adding) || (!output.length()))
115                                                                 output += (adding ? '+' : '-');
116
117                                                         this->SetNoticeMask(d, adding);
118
119                                                         output += d;
120                                                 }
121                                         }
122                                         oldadding = adding;
123                                 }
124                         break;
125                         default:
126                                 if ((*c >= 'A') && (*c <= 'z') && (ServerInstance->SNO->IsEnabled(*c)))
127                                 {
128                                         if ((!IsNoticeMaskSet(*c) && adding) || (IsNoticeMaskSet(*c) && !adding))
129                                         {
130                                                 if ((oldadding != adding) || (!output.length()))
131                                                         output += (adding ? '+' : '-');
132
133                                                 this->SetNoticeMask(*c, adding);
134
135                                                 output += *c;
136                                         }
137                                 }
138                                 oldadding = adding;
139                         break;
140                 }
141
142                 *c++;
143         }
144
145         return output;
146 }
147
148 void userrec::StartDNSLookup()
149 {
150         ServerInstance->Log(DEBUG,"Commencing reverse lookup");
151         try
152         {
153                 ServerInstance->Log(DEBUG,"Passing instance: %08x",this->ServerInstance);
154                 res_reverse = new UserResolver(this->ServerInstance, this, this->GetIPString(), DNS_QUERY_REVERSE);
155                 this->ServerInstance->AddResolver(res_reverse);
156         }
157         catch (CoreException& e)
158         {
159                 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
160         }
161 }
162
163 UserResolver::UserResolver(InspIRCd* Instance, userrec* user, std::string to_resolve, QueryType qt) :
164         Resolver(Instance, to_resolve, qt), bound_user(user)
165 {
166         this->fwd = (qt == DNS_QUERY_A || qt == DNS_QUERY_AAAA);
167         this->bound_fd = user->GetFd();
168 }
169
170 void UserResolver::OnLookupComplete(const std::string &result, unsigned int ttl)
171 {
172         if ((!this->fwd) && (ServerInstance->SE->GetRef(this->bound_fd) == this->bound_user))
173         {
174                 ServerInstance->Log(DEBUG,"Commencing forward lookup");
175                 this->bound_user->stored_host = result;
176                 try
177                 {
178                         /* Check we didnt time out */
179                         if (this->bound_user->registered != REG_ALL)
180                         {
181 #ifdef IPV6
182                                 const char *ip = this->bound_user->GetIPString();
183                                 bound_user->res_forward = new UserResolver(this->ServerInstance, this->bound_user, result, (strstr(ip,"0::ffff:") == ip ? DNS_QUERY_A : DNS_QUERY_AAAA));
184 #else
185                                 bound_user->res_forward = new UserResolver(this->ServerInstance, this->bound_user, result, DNS_QUERY_A);
186 #endif
187                                 this->ServerInstance->AddResolver(bound_user->res_forward);
188                         }
189                 }
190                 catch (CoreException& e)
191                 {
192                         ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
193                 }
194         }
195         else if ((this->fwd) && (ServerInstance->SE->GetRef(this->bound_fd) == this->bound_user))
196         {
197                 /* Both lookups completed */
198                 std::string result2 = "0::ffff:";
199                 result2.append(result);
200                 if (this->bound_user->GetIPString() == result || this->bound_user->GetIPString() == result2)
201                 {
202                         std::string hostname = this->bound_user->stored_host;
203                         if (hostname.length() < 65)
204                         {
205                                 /* Check we didnt time out */
206                                 if (this->bound_user->registered != REG_ALL)
207                                 {
208                                         /* Hostnames starting with : are not a good thing (tm) */
209                                         if (*(hostname.c_str()) == ':')
210                                                 hostname = "0" + hostname;
211
212                                         this->bound_user->WriteServ("NOTICE Auth :*** Found your hostname (%s)", hostname.c_str());
213                                         this->bound_user->dns_done = true;
214                                         strlcpy(this->bound_user->dhost, hostname.c_str(),64);
215                                         strlcpy(this->bound_user->host, hostname.c_str(),64);
216                                         /* Invalidate cache */
217                                         this->bound_user->InvalidateCache();
218                                 }
219                         }
220                         else
221                         {
222                                 this->bound_user->WriteServ("NOTICE Auth :*** Your hostname is longer than the maximum of 64 characters, using your IP address (%s) instead.", this->bound_user->GetIPString());
223                         }
224                 }
225                 else
226                 {
227                         this->bound_user->WriteServ("NOTICE Auth :*** Your hostname does not match up with your IP address. Sorry, using your IP address (%s) instead.", this->bound_user->GetIPString());
228                 }
229         }
230 }
231
232 void UserResolver::OnError(ResolverError e, const std::string &errormessage)
233 {
234         if (ServerInstance->SE->GetRef(this->bound_fd) == this->bound_user)
235         {
236                 /* Error message here */
237                 this->bound_user->WriteServ("NOTICE Auth :*** Could not resolve your hostname: %s; using your IP address (%s) instead.", errormessage.c_str(), this->bound_user->GetIPString());
238                 this->bound_user->dns_done = true;
239         }
240 }
241
242
243 bool userrec::IsNoticeMaskSet(unsigned char sm)
244 {
245         return (snomasks[sm-65]);
246 }
247
248 void userrec::SetNoticeMask(unsigned char sm, bool value)
249 {
250         snomasks[sm-65] = value;
251 }
252
253 const char* userrec::FormatNoticeMasks()
254 {
255         static char data[MAXBUF];
256         int offset = 0;
257
258         for (int n = 0; n < 64; n++)
259         {
260                 if (snomasks[n])
261                         data[offset++] = n+65;
262         }
263
264         data[offset] = 0;
265         return data;
266 }
267
268
269
270 bool userrec::IsModeSet(unsigned char m)
271 {
272         return (modes[m-65]);
273 }
274
275 void userrec::SetMode(unsigned char m, bool value)
276 {
277         modes[m-65] = value;
278 }
279
280 const char* userrec::FormatModes()
281 {
282         static char data[MAXBUF];
283         int offset = 0;
284         for (int n = 0; n < 64; n++)
285         {
286                 if (modes[n])
287                         data[offset++] = n+65;
288         }
289         data[offset] = 0;
290         return data;
291 }
292
293 void userrec::DecrementModes()
294 {
295         for (int n = 0; n < 64; n++)
296         {
297                 if (modes[n])
298                 {
299                         ModeHandler* mh = ServerInstance->Modes->FindMode(n+65, MODETYPE_USER);
300                         if (mh)
301                                 mh->ChangeCount(-1);
302                 }
303         }
304 }
305
306 userrec::userrec(InspIRCd* Instance) : ServerInstance(Instance)
307 {
308         ServerInstance->Log(DEBUG,"userrec::userrec(): Instance: %08x",ServerInstance);
309         // the PROPER way to do it, AVOID bzero at *ALL* costs
310         *password = *nick = *ident = *host = *dhost = *fullname = *awaymsg = *oper = 0;
311         server = (char*)Instance->FindServerNamePtr(Instance->Config->ServerName);
312         reset_due = ServerInstance->Time();
313         age = ServerInstance->Time(true);
314         lines_in = lastping = signon = idle_lastmsg = nping = registered = 0;
315         ChannelCount = timeout = flood = bytes_in = bytes_out = cmds_in = cmds_out = 0;
316         exempt = haspassed = dns_done = false;
317         fd = -1;
318         recvq = "";
319         sendq = "";
320         WriteError = "";
321         res_forward = res_reverse = NULL;
322         ip = NULL;
323         chans.clear();
324         invites.clear();
325         memset(modes,0,sizeof(modes));
326         memset(snomasks,0,sizeof(snomasks));
327         /* Invalidate cache */
328         cached_fullhost = cached_hostip = cached_makehost = cached_fullrealhost = NULL;
329 }
330
331 userrec::~userrec()
332 {
333         this->InvalidateCache();
334         this->DecrementModes();
335         if (ip)
336         {
337                 clonemap::iterator x = ServerInstance->local_clones.find(this->GetIPString());
338                 if (x != ServerInstance->local_clones.end())
339                 {
340                         x->second--;
341                         if (!x->second)
342                         {
343                                 ServerInstance->local_clones.erase(x);
344                         }
345                 }
346         
347                 clonemap::iterator y = ServerInstance->global_clones.find(this->GetIPString());
348                 if (y != ServerInstance->global_clones.end())
349                 {
350                         y->second--;
351                         if (!y->second)
352                         {
353                                 ServerInstance->global_clones.erase(y);
354                         }
355                 }
356
357                 if (this->GetProtocolFamily() == AF_INET)
358                 {
359                         delete (sockaddr_in*)ip;
360                 }
361 #ifdef SUPPORT_IP6LINKS
362                 else
363                 {
364                         delete (sockaddr_in6*)ip;
365                 }
366 #endif
367         }
368 }
369
370 char* userrec::MakeHost()
371 {
372         if (this->cached_makehost)
373                 return this->cached_makehost;
374
375         char nhost[MAXBUF];
376         /* This is much faster than snprintf */
377         char* t = nhost;
378         for(char* n = ident; *n; n++)
379                 *t++ = *n;
380         *t++ = '@';
381         for(char* n = host; *n; n++)
382                 *t++ = *n;
383         *t = 0;
384
385         this->cached_makehost = strdup(nhost);
386
387         return this->cached_makehost;
388 }
389
390 char* userrec::MakeHostIP()
391 {
392         if (this->cached_hostip)
393                 return this->cached_hostip;
394
395         char ihost[MAXBUF];
396         /* This is much faster than snprintf */
397         char* t = ihost;
398         for(char* n = ident; *n; n++)
399                 *t++ = *n;
400         *t++ = '@';
401         for(const char* n = this->GetIPString(); *n; n++)
402                 *t++ = *n;
403         *t = 0;
404
405         this->cached_hostip = strdup(ihost);
406
407         return this->cached_hostip;
408 }
409
410 void userrec::CloseSocket()
411 {
412         shutdown(this->fd,2);
413         close(this->fd);
414 }
415  
416 char* userrec::GetFullHost()
417 {
418         if (this->cached_fullhost)
419                 return this->cached_fullhost;
420
421         char result[MAXBUF];
422         char* t = result;
423         for(char* n = nick; *n; n++)
424                 *t++ = *n;
425         *t++ = '!';
426         for(char* n = ident; *n; n++)
427                 *t++ = *n;
428         *t++ = '@';
429         for(char* n = dhost; *n; n++)
430                 *t++ = *n;
431         *t = 0;
432
433         this->cached_fullhost = strdup(result);
434
435         return this->cached_fullhost;
436 }
437
438 char* userrec::MakeWildHost()
439 {
440         static char nresult[MAXBUF];
441         char* t = nresult;
442         *t++ = '*';     *t++ = '!';
443         *t++ = '*';     *t++ = '@';
444         for(char* n = dhost; *n; n++)
445                 *t++ = *n;
446         *t = 0;
447         return nresult;
448 }
449
450 int userrec::ReadData(void* buffer, size_t size)
451 {
452         if (IS_LOCAL(this))
453         {
454                 return read(this->fd, buffer, size);
455         }
456         else
457                 return 0;
458 }
459
460
461 char* userrec::GetFullRealHost()
462 {
463         if (this->cached_fullrealhost)
464                 return this->cached_fullrealhost;
465
466         char fresult[MAXBUF];
467         char* t = fresult;
468         for(char* n = nick; *n; n++)
469                 *t++ = *n;
470         *t++ = '!';
471         for(char* n = ident; *n; n++)
472                 *t++ = *n;
473         *t++ = '@';
474         for(char* n = host; *n; n++)
475                 *t++ = *n;
476         *t = 0;
477
478         this->cached_fullrealhost = strdup(fresult);
479
480         return this->cached_fullrealhost;
481 }
482
483 bool userrec::IsInvited(const irc::string &channel)
484 {
485         for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
486         {
487                 if (channel == *i)
488                 {
489                         return true;
490                 }
491         }
492         return false;
493 }
494
495 InvitedList* userrec::GetInviteList()
496 {
497         return &invites;
498 }
499
500 void userrec::InviteTo(const irc::string &channel)
501 {
502         invites.push_back(channel);
503 }
504
505 void userrec::RemoveInvite(const irc::string &channel)
506 {
507         ServerInstance->Log(DEBUG,"Removing invites");
508         for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
509         {
510                 if (channel == *i)
511                 {
512                         invites.erase(i);
513                         return;
514                 }
515         }
516 }
517
518 bool userrec::HasPermission(const std::string &command)
519 {
520         char* mycmd;
521         char* savept;
522         char* savept2;
523         
524         /*
525          * users on remote servers can completely bypass all permissions based checks.
526          * This prevents desyncs when one server has different type/class tags to another.
527          * That having been said, this does open things up to the possibility of source changes
528          * allowing remote kills, etc - but if they have access to the src, they most likely have
529          * access to the conf - so it's an end to a means either way.
530          */
531         if (!IS_LOCAL(this))
532                 return true;
533         
534         // are they even an oper at all?
535         if (*this->oper)
536         {
537                 opertype_t::iterator iter_opertype = ServerInstance->Config->opertypes.find(this->oper);
538                 if (iter_opertype != ServerInstance->Config->opertypes.end())
539                 {
540                         char* Classes = strdup(iter_opertype->second);
541                         char* myclass = strtok_r(Classes," ",&savept);
542                         while (myclass)
543                         {
544                                 operclass_t::iterator iter_operclass = ServerInstance->Config->operclass.find(myclass);
545                                 if (iter_operclass != ServerInstance->Config->operclass.end())
546                                 {
547                                         char* CommandList = strdup(iter_operclass->second);
548                                         mycmd = strtok_r(CommandList," ",&savept2);
549                                         while (mycmd)
550                                         {
551                                                 if ((!strcasecmp(mycmd,command.c_str())) || (*mycmd == '*'))
552                                                 {
553                                                         free(Classes);
554                                                         free(CommandList);
555                                                         return true;
556                                                 }
557                                                 mycmd = strtok_r(NULL," ",&savept2);
558                                         }
559                                         free(CommandList);
560                                 }
561                                 myclass = strtok_r(NULL," ",&savept);
562                         }
563                         free(Classes);
564                 }
565         }
566         return false;
567 }
568
569 /** NOTE: We cannot pass a const reference to this method.
570  * The string is changed by the workings of the method,
571  * so that if we pass const ref, we end up copying it to
572  * something we can change anyway. Makes sense to just let
573  * the compiler do that copy for us.
574  */
575 bool userrec::AddBuffer(std::string a)
576 {
577         try
578         {
579                 std::string::size_type i = a.rfind('\r');
580         
581                 while (i != std::string::npos)
582                 {
583                         a.erase(i, 1);
584                         i = a.rfind('\r');
585                 }
586
587                 if (a.length())
588                         recvq.append(a);
589                 
590                 if (recvq.length() > (unsigned)this->recvqmax)
591                 {
592                         this->SetWriteError("RecvQ exceeded");
593                         ServerInstance->WriteOpers("*** User %s RecvQ of %d exceeds connect class maximum of %d",this->nick,recvq.length(),this->recvqmax);
594                         return false;
595                 }
596         
597                 return true;
598         }
599
600         catch (...)
601         {
602                 ServerInstance->Log(DEBUG,"Exception in userrec::AddBuffer()");
603                 return false;
604         }
605 }
606
607 bool userrec::BufferIsReady()
608 {
609         return (recvq.find('\n') != std::string::npos);
610 }
611
612 void userrec::ClearBuffer()
613 {
614         recvq = "";
615 }
616
617 std::string userrec::GetBuffer()
618 {
619         try
620         {
621                 if (!recvq.length())
622                         return "";
623         
624                 /* Strip any leading \r or \n off the string.
625                  * Usually there are only one or two of these,
626                  * so its is computationally cheap to do.
627                  */
628                 while ((*recvq.begin() == '\r') || (*recvq.begin() == '\n'))
629                         recvq.erase(recvq.begin());
630         
631                 for (std::string::iterator x = recvq.begin(); x != recvq.end(); x++)
632                 {
633                         /* Find the first complete line, return it as the
634                          * result, and leave the recvq as whats left
635                          */
636                         if (*x == '\n')
637                         {
638                                 std::string ret = std::string(recvq.begin(), x);
639                                 recvq.erase(recvq.begin(), x + 1);
640                                 return ret;
641                         }
642                 }
643                 return "";
644         }
645
646         catch (...)
647         {
648                 ServerInstance->Log(DEBUG,"Exception in userrec::GetBuffer()");
649                 return "";
650         }
651 }
652
653 void userrec::AddWriteBuf(const std::string &data)
654 {
655         if (*this->GetWriteError())
656                 return;
657         
658         if (sendq.length() + data.length() > (unsigned)this->sendqmax)
659         {
660                 /*
661                  * Fix by brain - Set the error text BEFORE calling writeopers, because
662                  * if we dont it'll recursively  call here over and over again trying
663                  * to repeatedly add the text to the sendq!
664                  */
665                 this->SetWriteError("SendQ exceeded");
666                 ServerInstance->WriteOpers("*** User %s SendQ of %d exceeds connect class maximum of %d",this->nick,sendq.length() + data.length(),this->sendqmax);
667                 return;
668         }
669
670         try 
671         {
672                 if (data.length() > 512)
673                         sendq.append(data.substr(0,510)).append("\r\n");
674                 else
675                         sendq.append(data);
676         }
677         catch (...)
678         {
679                 this->SetWriteError("SendQ exceeded");
680                 ServerInstance->WriteOpers("*** User %s SendQ got an exception",this->nick);
681         }
682 }
683
684 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
685 void userrec::FlushWriteBuf()
686 {
687         try
688         {
689                 if ((this->fd == FD_MAGIC_NUMBER) || (*this->GetWriteError()))
690                 {
691                         sendq = "";
692                 }
693                 if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
694                 {
695                         int old_sendq_length = sendq.length();
696                         int n_sent = write(this->fd, this->sendq.data(), this->sendq.length());
697                         if (n_sent == -1)
698                         {
699                                 if (errno == EAGAIN)
700                                 {
701                                         /* The socket buffer is full. This isnt fatal,
702                                          * try again later.
703                                          */
704                                         ServerInstance->Log(DEBUG,"EAGAIN, want write");
705                                         this->ServerInstance->SE->WantWrite(this);
706                                 }
707                                 else
708                                 {
709                                         /* Fatal error, set write error and bail
710                                          */
711                                         this->SetWriteError(strerror(errno));
712                                         return;
713                                 }
714                         }
715                         else
716                         {
717                                 /* advance the queue */
718                                 if (n_sent)
719                                         this->sendq = this->sendq.substr(n_sent);
720                                 /* update the user's stats counters */
721                                 this->bytes_out += n_sent;
722                                 this->cmds_out++;
723                                 if (n_sent != old_sendq_length)
724                                 {
725                                         ServerInstance->Log(DEBUG,"Not all written, want write");
726                                         this->ServerInstance->SE->WantWrite(this);
727                                 }
728                         }
729                 }
730         }
731
732         catch (...)
733         {
734                 ServerInstance->Log(DEBUG,"Exception in userrec::FlushWriteBuf()");
735         }
736 }
737
738 void userrec::SetWriteError(const std::string &error)
739 {
740         try
741         {
742                 // don't try to set the error twice, its already set take the first string.
743                 if (this->WriteError.empty())
744                 {
745                         ServerInstance->Log(DEBUG,"Setting error string for %s to '%s'",this->nick,error.c_str());
746                         this->WriteError = error;
747                 }
748         }
749
750         catch (...)
751         {
752                 ServerInstance->Log(DEBUG,"Exception in userrec::SetWriteError()");
753         }
754 }
755
756 const char* userrec::GetWriteError()
757 {
758         return this->WriteError.c_str();
759 }
760
761 void userrec::Oper(const std::string &opertype)
762 {
763         try
764         {
765                 this->modes[UM_OPERATOR] = 1;
766                 this->WriteServ("MODE %s :+o", this->nick);
767                 FOREACH_MOD(I_OnOper, OnOper(this, opertype));
768                 ServerInstance->Log(DEFAULT,"OPER: %s!%s@%s opered as type: %s", this->nick, this->ident, this->host, opertype.c_str());
769                 strlcpy(this->oper, opertype.c_str(), NICKMAX - 1);
770                 ServerInstance->all_opers.push_back(this);
771                 FOREACH_MOD(I_OnPostOper,OnPostOper(this, opertype));
772         }
773
774         catch (...)
775         {
776                 ServerInstance->Log(DEBUG,"Exception in userrec::Oper()");
777         }
778 }
779
780 void userrec::UnOper()
781 {
782         try
783         {
784                 if (*this->oper)
785                 {
786                         *this->oper = 0;
787                         this->modes[UM_OPERATOR] = 0;
788                         for (std::vector<userrec*>::iterator a = ServerInstance->all_opers.begin(); a < ServerInstance->all_opers.end(); a++)
789                         {
790                                 if (*a == this)
791                                 {
792                                         ServerInstance->Log(DEBUG,"Oper removed from optimization list");
793                                         ServerInstance->all_opers.erase(a);
794                                         return;
795                                 }
796                         }
797                 }
798         }
799
800         catch (...)
801         {
802                 ServerInstance->Log(DEBUG,"Exception in userrec::UnOper()");
803         }
804 }
805
806 void userrec::QuitUser(InspIRCd* Instance, userrec *user, const std::string &quitreason)
807 {
808         user_hash::iterator iter = Instance->clientlist->find(user->nick);
809         std::string reason = quitreason;
810
811         if (reason.length() > MAXQUIT - 1)
812                 reason.resize(MAXQUIT - 1);
813
814         if (user->registered != REG_ALL)
815                 if (Instance->unregistered_count)
816                         Instance->unregistered_count--;
817
818         if (IS_LOCAL(user))
819         {
820                 user->Write("ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason.c_str());
821                 if ((!user->sendq.empty()) && (!(*user->GetWriteError())))
822                         user->FlushWriteBuf();
823         }
824
825         if (user->registered == REG_ALL)
826         {
827                 user->PurgeEmptyChannels();
828                 user->WriteCommonExcept("QUIT :%s",reason.c_str());
829                 FOREACH_MOD_I(Instance,I_OnUserQuit,OnUserQuit(user,reason));
830         }
831
832         FOREACH_MOD_I(Instance,I_OnUserDisconnect,OnUserDisconnect(user));
833
834         if (IS_LOCAL(user))
835         {
836                 if (Instance->Config->GetIOHook(user->GetPort()))
837                 {
838                         try
839                         {
840                                 Instance->Config->GetIOHook(user->GetPort())->OnRawSocketClose(user->fd);
841                         }
842                         catch (CoreException& modexcept)
843                         {
844                                 Instance->Log(DEBUG, "%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
845                         }
846                 }
847                 
848                 Instance->SE->DelFd(user);
849                 user->CloseSocket();
850         }
851
852         /*
853          * this must come before the ServerInstance->SNO->WriteToSnoMaskso that it doesnt try to fill their buffer with anything
854          * if they were an oper with +sn +qQ.
855          */
856         if (user->registered == REG_ALL)
857         {
858                 if (IS_LOCAL(user))
859                         Instance->SNO->WriteToSnoMask('q',"Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason.c_str());
860                 else
861                         Instance->SNO->WriteToSnoMask('Q',"Client exiting on server %s: %s!%s@%s [%s]",user->server,user->nick,user->ident,user->host,reason.c_str());
862                 user->AddToWhoWas();
863         }
864
865         if (iter != Instance->clientlist->end())
866         {
867                 Instance->Log(DEBUG,"deleting user hash value %lx",(unsigned long)user);
868                 if (IS_LOCAL(user))
869                 {
870                         std::vector<userrec*>::iterator x = find(Instance->local_users.begin(),Instance->local_users.end(),user);
871                         if (x != Instance->local_users.end())
872                                 Instance->local_users.erase(x);
873                 }
874                 Instance->clientlist->erase(iter);
875                 DELETE(user);
876         }
877 }
878
879
880 /* adds or updates an entry in the whowas list */
881 void userrec::AddToWhoWas()
882 {
883         command_t* whowas_command = ServerInstance->Parser->GetHandler("WHOWAS");
884         if (whowas_command)
885         {
886                 std::deque<classbase*> params;
887                 params.push_back(this);
888                 whowas_command->HandleInternal(WHOWAS_ADD, params);
889         }
890 }
891
892 /* add a client connection to the sockets list */
893 void userrec::AddClient(InspIRCd* Instance, int socket, int port, bool iscached, insp_inaddr ip)
894 {
895         std::string tempnick = ConvToStr(socket) + "-unknown";
896         user_hash::iterator iter = Instance->clientlist->find(tempnick);
897         const char *ipaddr = insp_ntoa(ip);
898         userrec* New;
899         int j = 0;
900
901         Instance->unregistered_count++;
902
903         /*
904          * fix by brain.
905          * as these nicknames are 'RFC impossible', we can be sure nobody is going to be
906          * using one as a registered connection. As they are per fd, we can also safely assume
907          * that we wont have collisions. Therefore, if the nick exists in the list, its only
908          * used by a dead socket, erase the iterator so that the new client may reclaim it.
909          * this was probably the cause of 'server ignores me when i hammer it with reconnects'
910          * issue in earlier alphas/betas
911          */
912         if (iter != Instance->clientlist->end())
913         {
914                 userrec* goner = iter->second;
915                 DELETE(goner);
916                 Instance->clientlist->erase(iter);
917         }
918
919         Instance->Log(DEBUG,"AddClient: %d %d %s",socket,port,ipaddr);
920
921         New = new userrec(Instance);
922         (*(Instance->clientlist))[tempnick] = New;
923         New->fd = socket;
924         strlcpy(New->nick,tempnick.c_str(),NICKMAX-1);
925
926         New->server = Instance->FindServerNamePtr(Instance->Config->ServerName);
927         /* We don't need range checking here, we KNOW 'unknown\0' will fit into the ident field. */
928         strcpy(New->ident, "unknown");
929
930         New->registered = REG_NONE;
931         New->signon = Instance->Time() + Instance->Config->dns_timeout;
932         New->lastping = 1;
933
934         New->SetSockAddr(AF_FAMILY, ipaddr, port);
935
936         /* Smarter than your average bear^H^H^H^Hset of strlcpys. */
937         for (const char* temp = New->GetIPString(); *temp && j < 64; temp++, j++)
938                 New->dhost[j] = New->host[j] = *temp;
939         New->dhost[j] = New->host[j] = 0;
940
941         Instance->AddLocalClone(New);
942         Instance->AddGlobalClone(New);
943
944         ConnectClass* i = New->GetClass();
945
946         if ((!i) || (i->GetType() == CC_DENY))
947         {
948                 userrec::QuitUser(Instance, New,"Unauthorised connection");
949                 return;
950         }
951
952         New->pingmax = i->GetPingTime();
953         New->nping = Instance->Time() + i->GetPingTime() + Instance->Config->dns_timeout;
954         New->timeout = Instance->Time() + i->GetRegTimeout();
955         New->flood = i->GetFlood();
956         New->threshold = i->GetThreshold();
957         New->sendqmax = i->GetSendqMax();
958         New->recvqmax = i->GetRecvqMax();
959
960         Instance->local_users.push_back(New);
961
962         if ((Instance->local_users.size() > Instance->Config->SoftLimit) || (Instance->local_users.size() >= MAXCLIENTS))
963         {
964                 Instance->WriteOpers("*** Warning: softlimit value has been reached: %d clients", Instance->Config->SoftLimit);
965                 userrec::QuitUser(Instance, New,"No more connections allowed");
966                 return;
967         }
968
969         /*
970          * XXX -
971          * this is done as a safety check to keep the file descriptors within range of fd_ref_table.
972          * its a pretty big but for the moment valid assumption:
973          * file descriptors are handed out starting at 0, and are recycled as theyre freed.
974          * therefore if there is ever an fd over 65535, 65536 clients must be connected to the
975          * irc server at once (or the irc server otherwise initiating this many connections, files etc)
976          * which for the time being is a physical impossibility (even the largest networks dont have more
977          * than about 10,000 users on ONE server!)
978          */
979         if ((unsigned int)socket >= MAX_DESCRIPTORS)
980         {
981                 userrec::QuitUser(Instance, New, "Server is full");
982                 return;
983         }
984
985         New->exempt = (Instance->XLines->matches_exception(New) != NULL);
986         if (!New->exempt)
987         {
988                 ZLine* r = Instance->XLines->matches_zline(ipaddr);
989                 if (r)
990                 {
991                         char reason[MAXBUF];
992                         snprintf(reason,MAXBUF,"Z-Lined: %s",r->reason);
993                         userrec::QuitUser(Instance, New, reason);
994                         return;
995                 }
996         }
997
998         if (socket > -1)
999         {
1000                 if (!Instance->SE->AddFd(New))
1001                 {
1002                         userrec::QuitUser(Instance, New, "Internal error handling connection");
1003                         return;
1004                 }
1005         }
1006
1007         /* NOTE: even if dns lookups are *off*, we still need to display this.
1008          * BOPM and other stuff requires it.
1009          */
1010         New->WriteServ("NOTICE Auth :*** Looking up your hostname...");
1011 }
1012
1013 unsigned long userrec::GlobalCloneCount()
1014 {
1015         clonemap::iterator x = ServerInstance->global_clones.find(this->GetIPString());
1016         if (x != ServerInstance->global_clones.end())
1017                 return x->second;
1018         else
1019                 return 0;
1020 }
1021
1022 unsigned long userrec::LocalCloneCount()
1023 {
1024         clonemap::iterator x = ServerInstance->local_clones.find(this->GetIPString());
1025         if (x != ServerInstance->local_clones.end())
1026                 return x->second;
1027         else
1028                 return 0;
1029 }
1030
1031 void userrec::FullConnect(CullList* Goners)
1032 {
1033         ServerInstance->stats->statsConnects++;
1034         this->idle_lastmsg = ServerInstance->Time();
1035
1036         ConnectClass* a = this->GetClass();
1037
1038         if ((!a) || (a->GetType() == CC_DENY))
1039         {
1040                 Goners->AddItem(this,"Unauthorised connection");
1041                 return;
1042         }
1043
1044         if ((!a->GetPass().empty()) && (!this->haspassed))
1045         {
1046                 Goners->AddItem(this,"Invalid password");
1047                 return;
1048         }
1049         
1050         if (this->LocalCloneCount() > a->GetMaxLocal())
1051         {
1052                 Goners->AddItem(this, "No more connections allowed from your host via this connect class (local)");
1053                 ServerInstance->WriteOpers("*** WARNING: maximum LOCAL connections (%ld) exceeded for IP %s", a->GetMaxLocal(), this->GetIPString());
1054                 return;
1055         }
1056         else if (this->GlobalCloneCount() > a->GetMaxGlobal())
1057         {
1058                 Goners->AddItem(this, "No more connections allowed from your host via this connect class (global)");
1059                 ServerInstance->WriteOpers("*** WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s",a->GetMaxGlobal(), this->GetIPString());
1060                 return;
1061         }
1062
1063         if (!this->exempt)
1064         {
1065                 GLine* r = ServerInstance->XLines->matches_gline(this);
1066                 
1067                 if (r)
1068                 {
1069                         char reason[MAXBUF];
1070                         snprintf(reason,MAXBUF,"G-Lined: %s",r->reason);
1071                         Goners->AddItem(this, reason);
1072                         return;
1073                 }
1074                 
1075                 KLine* n = ServerInstance->XLines->matches_kline(this);
1076                 
1077                 if (n)
1078                 {
1079                         char reason[MAXBUF];
1080                         snprintf(reason,MAXBUF,"K-Lined: %s",n->reason);
1081                         Goners->AddItem(this, reason);
1082                         return;
1083                 }
1084
1085         }
1086
1087         this->WriteServ("NOTICE Auth :Welcome to \002%s\002!",ServerInstance->Config->Network);
1088         this->WriteServ("001 %s :Welcome to the %s IRC Network %s!%s@%s",this->nick, ServerInstance->Config->Network, this->nick, this->ident, this->host);
1089         this->WriteServ("002 %s :Your host is %s, running version %s",this->nick,ServerInstance->Config->ServerName,VERSION);
1090         this->WriteServ("003 %s :This server was created %s %s", this->nick, __TIME__, __DATE__);
1091         this->WriteServ("004 %s %s %s %s %s %s", this->nick, ServerInstance->Config->ServerName, VERSION, ServerInstance->Modes->UserModeList().c_str(), ServerInstance->Modes->ChannelModeList().c_str(), ServerInstance->Modes->ParaModeList().c_str());
1092
1093         ServerInstance->Config->Send005(this);
1094
1095         this->ShowMOTD();
1096
1097         /* Now registered */
1098         if (ServerInstance->unregistered_count)
1099                 ServerInstance->unregistered_count--;
1100
1101         /*
1102          * fix 3 by brain, move registered = 7 below these so that spurious modes and host
1103          * changes dont go out onto the network and produce 'fake direction'.
1104          */
1105         FOREACH_MOD(I_OnUserConnect,OnUserConnect(this));
1106
1107         this->registered = REG_ALL;
1108
1109         FOREACH_MOD(I_OnPostConnect,OnPostConnect(this));
1110
1111         ServerInstance->SNO->WriteToSnoMask('c',"Client connecting on port %d: %s!%s@%s [%s]", this->GetPort(), this->nick, this->ident, this->host, this->GetIPString());
1112 }
1113
1114 /** userrec::UpdateNick()
1115  * re-allocates a nick in the user_hash after they change nicknames,
1116  * returns a pointer to the new user as it may have moved
1117  */
1118 userrec* userrec::UpdateNickHash(const char* New)
1119 {
1120         try
1121         {
1122                 //user_hash::iterator newnick;
1123                 user_hash::iterator oldnick = ServerInstance->clientlist->find(this->nick);
1124
1125                 if (!strcasecmp(this->nick,New))
1126                         return oldnick->second;
1127
1128                 if (oldnick == ServerInstance->clientlist->end())
1129                         return NULL; /* doesnt exist */
1130
1131                 userrec* olduser = oldnick->second;
1132                 (*(ServerInstance->clientlist))[New] = olduser;
1133                 ServerInstance->clientlist->erase(oldnick);
1134                 return olduser;
1135         }
1136
1137         catch (...)
1138         {
1139                 ServerInstance->Log(DEBUG,"Exception in userrec::UpdateNickHash()");
1140                 return NULL;
1141         }
1142 }
1143
1144 void userrec::InvalidateCache()
1145 {
1146         /* Invalidate cache */
1147         if (cached_fullhost)
1148                 free(cached_fullhost);
1149         if (cached_hostip)
1150                 free(cached_hostip);
1151         if (cached_makehost)
1152                 free(cached_makehost);
1153         if (cached_fullrealhost)
1154                 free(cached_fullrealhost);
1155         cached_fullhost = cached_hostip = cached_makehost = cached_fullrealhost = NULL;
1156 }
1157
1158 bool userrec::ForceNickChange(const char* newnick)
1159 {
1160         try
1161         {
1162                 int MOD_RESULT = 0;
1163
1164                 this->InvalidateCache();
1165         
1166                 FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(this, newnick));
1167
1168                 if (MOD_RESULT)
1169                 {
1170                         ServerInstance->stats->statsCollisions++;
1171                         return false;
1172                 }
1173         
1174                 if (ServerInstance->XLines->matches_qline(newnick))
1175                 {
1176                         ServerInstance->stats->statsCollisions++;
1177                         return false;
1178                 }
1179
1180                 if (this->registered == REG_ALL)
1181                 {
1182                         const char* pars[1];
1183                         pars[0] = newnick;
1184                         std::string cmd = "NICK";
1185                         return (ServerInstance->Parser->CallHandler(cmd, pars, 1, this) == CMD_SUCCESS);
1186                 }
1187                 return false;
1188         }
1189
1190         catch (...)
1191         {
1192                 ServerInstance->Log(DEBUG,"Exception in userrec::ForceNickChange()");
1193                 return false;
1194         }
1195 }
1196
1197 void userrec::SetSockAddr(int protocol_family, const char* ip, int port)
1198 {
1199         switch (protocol_family)
1200         {
1201 #ifdef SUPPORT_IP6LINKS
1202                 case AF_INET6:
1203                 {
1204                         ServerInstance->Log(DEBUG,"Set inet6 protocol address");
1205                         sockaddr_in6* sin = new sockaddr_in6;
1206                         sin->sin6_family = AF_INET6;
1207                         sin->sin6_port = port;
1208                         inet_pton(AF_INET6, ip, &sin->sin6_addr);
1209                         this->ip = (sockaddr*)sin;
1210                 }
1211                 break;
1212 #endif
1213                 case AF_INET:
1214                 {
1215                         ServerInstance->Log(DEBUG,"Set inet4 protocol address");
1216                         sockaddr_in* sin = new sockaddr_in;
1217                         sin->sin_family = AF_INET;
1218                         sin->sin_port = port;
1219                         inet_pton(AF_INET, ip, &sin->sin_addr);
1220                         this->ip = (sockaddr*)sin;
1221                 }
1222                 break;
1223                 default:
1224                         ServerInstance->Log(DEBUG,"Ut oh, I dont know protocol %d to be set on '%s'!", protocol_family, this->nick);
1225                 break;
1226         }
1227 }
1228
1229 int userrec::GetPort()
1230 {
1231         if (this->ip == NULL)
1232                 return 0;
1233
1234         switch (this->GetProtocolFamily())
1235         {
1236 #ifdef SUPPORT_IP6LINKS
1237                 case AF_INET6:
1238                 {
1239                         sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1240                         return sin->sin6_port;
1241                 }
1242                 break;
1243 #endif
1244                 case AF_INET:
1245                 {
1246                         sockaddr_in* sin = (sockaddr_in*)this->ip;
1247                         return sin->sin_port;
1248                 }
1249                 break;
1250                 default:
1251                 break;
1252         }
1253         return 0;
1254 }
1255
1256 int userrec::GetProtocolFamily()
1257 {
1258         if (this->ip == NULL)
1259                 return 0;
1260
1261         sockaddr_in* sin = (sockaddr_in*)this->ip;
1262         return sin->sin_family;
1263 }
1264
1265 const char* userrec::GetIPString()
1266 {
1267         static char buf[1024];
1268
1269         if (this->ip == NULL)
1270                 return "";
1271
1272         switch (this->GetProtocolFamily())
1273         {
1274 #ifdef SUPPORT_IP6LINKS
1275                 case AF_INET6:
1276                 {
1277                         static char temp[1024];
1278                 
1279                         sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1280                         inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1281                         /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1282                         if (*buf == ':')
1283                         {
1284                                 strlcpy(&temp[1], buf, sizeof(temp) - 1);
1285                                 *temp = '0';
1286                                 return temp;
1287                         }
1288                         return buf;
1289                 }
1290                 break;
1291 #endif
1292                 case AF_INET:
1293                 {
1294                         sockaddr_in* sin = (sockaddr_in*)this->ip;
1295                         inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1296                         return buf;
1297                 }
1298                 break;
1299                 default:
1300                 break;
1301         }
1302         return "";
1303 }
1304
1305 const char* userrec::GetIPString(char* buf)
1306 {
1307         if (this->ip == NULL)
1308         {
1309                 *buf = 0;
1310                 return buf;
1311         }
1312
1313         switch (this->GetProtocolFamily())
1314         {
1315 #ifdef SUPPORT_IP6LINKS
1316                 case AF_INET6:
1317                 {
1318                         static char temp[1024];
1319                 
1320                         sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1321                         inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1322                         /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1323                         if (*buf == ':')
1324                         {
1325                                 strlcpy(&temp[1], buf, sizeof(temp) - 1);
1326                                 *temp = '0';
1327                                 strlcpy(buf, temp, sizeof(temp));
1328                         }
1329                         return buf;
1330                 }
1331                 break;
1332 #endif
1333                 case AF_INET:
1334                 {
1335                         sockaddr_in* sin = (sockaddr_in*)this->ip;
1336                         inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1337                         return buf;
1338                 }
1339                 break;
1340
1341                 default:
1342                 break;
1343         }
1344         return "";
1345 }
1346
1347 /** NOTE: We cannot pass a const reference to this method.
1348  * The string is changed by the workings of the method,
1349  * so that if we pass const ref, we end up copying it to
1350  * something we can change anyway. Makes sense to just let
1351  * the compiler do that copy for us.
1352  */
1353 void userrec::Write(std::string text)
1354 {
1355         if ((this->fd < 0) || (this->fd > MAX_DESCRIPTORS))
1356                 return;
1357
1358         try
1359         {
1360                 text.append("\r\n");
1361         }
1362         catch (...)
1363         {
1364                 ServerInstance->Log(DEBUG,"Exception in userrec::Write() std::string::append");
1365                 return;
1366         }
1367
1368         if (ServerInstance->Config->GetIOHook(this->GetPort()))
1369         {
1370                 try
1371                 {
1372                         ServerInstance->Config->GetIOHook(this->GetPort())->OnRawSocketWrite(this->fd, text.data(), text.length());
1373                 }
1374                 catch (CoreException& modexcept)
1375                 {
1376                         ServerInstance->Log(DEBUG, "%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
1377                 }
1378         }
1379         else
1380         {
1381                 this->AddWriteBuf(text);
1382         }
1383         ServerInstance->stats->statsSent += text.length();
1384         this->ServerInstance->SE->WantWrite(this);
1385 }
1386
1387 /** Write()
1388  */
1389 void userrec::Write(const char *text, ...)
1390 {
1391         va_list argsPtr;
1392         char textbuffer[MAXBUF];
1393
1394         va_start(argsPtr, text);
1395         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1396         va_end(argsPtr);
1397
1398         this->Write(std::string(textbuffer));
1399 }
1400
1401 void userrec::WriteServ(const std::string& text)
1402 {
1403         char textbuffer[MAXBUF];
1404
1405         snprintf(textbuffer,MAXBUF,":%s %s",ServerInstance->Config->ServerName,text.c_str());
1406         this->Write(std::string(textbuffer));
1407 }
1408
1409 /** WriteServ()
1410  *  Same as Write(), except `text' is prefixed with `:server.name '.
1411  */
1412 void userrec::WriteServ(const char* text, ...)
1413 {
1414         va_list argsPtr;
1415         char textbuffer[MAXBUF];
1416
1417         va_start(argsPtr, text);
1418         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1419         va_end(argsPtr);
1420
1421         this->WriteServ(std::string(textbuffer));
1422 }
1423
1424
1425 void userrec::WriteFrom(userrec *user, const std::string &text)
1426 {
1427         char tb[MAXBUF];
1428
1429         snprintf(tb,MAXBUF,":%s %s",user->GetFullHost(),text.c_str());
1430         
1431         this->Write(std::string(tb));
1432 }
1433
1434
1435 /* write text from an originating user to originating user */
1436
1437 void userrec::WriteFrom(userrec *user, const char* text, ...)
1438 {
1439         va_list argsPtr;
1440         char textbuffer[MAXBUF];
1441
1442         va_start(argsPtr, text);
1443         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1444         va_end(argsPtr);
1445
1446         this->WriteFrom(user, std::string(textbuffer));
1447 }
1448
1449
1450 /* write text to an destination user from a source user (e.g. user privmsg) */
1451
1452 void userrec::WriteTo(userrec *dest, const char *data, ...)
1453 {
1454         char textbuffer[MAXBUF];
1455         va_list argsPtr;
1456
1457         va_start(argsPtr, data);
1458         vsnprintf(textbuffer, MAXBUF, data, argsPtr);
1459         va_end(argsPtr);
1460
1461         this->WriteTo(dest, std::string(textbuffer));
1462 }
1463
1464 void userrec::WriteTo(userrec *dest, const std::string &data)
1465 {
1466         dest->WriteFrom(this, data);
1467 }
1468
1469
1470 void userrec::WriteCommon(const char* text, ...)
1471 {
1472         char textbuffer[MAXBUF];
1473         va_list argsPtr;
1474
1475         if (this->registered != REG_ALL)
1476                 return;
1477
1478         va_start(argsPtr, text);
1479         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1480         va_end(argsPtr);
1481
1482         this->WriteCommon(std::string(textbuffer));
1483 }
1484
1485 void userrec::WriteCommon(const std::string &text)
1486 {
1487         try
1488         {
1489                 bool sent_to_at_least_one = false;
1490                 char tb[MAXBUF];
1491         
1492                 if (this->registered != REG_ALL)
1493                         return;
1494         
1495                 uniq_id++;
1496
1497                 /* We dont want to be doing this n times, just once */
1498                 snprintf(tb,MAXBUF,":%s %s",this->GetFullHost(),text.c_str());
1499                 std::string out = tb;
1500         
1501                 for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1502                 {
1503                         CUList* ulist = v->first->GetUsers();
1504                         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1505                         {
1506                                 if ((IS_LOCAL(i->second)) && (already_sent[i->second->fd] != uniq_id))
1507                                 {
1508                                         already_sent[i->second->fd] = uniq_id;
1509                                         i->second->Write(out);
1510                                         sent_to_at_least_one = true;
1511                                 }
1512                         }
1513                 }
1514         
1515                 /*
1516                  * if the user was not in any channels, no users will receive the text. Make sure the user
1517                  * receives their OWN message for WriteCommon
1518                  */
1519                 if (!sent_to_at_least_one)
1520                 {
1521                         this->Write(std::string(tb));
1522                 }
1523         }
1524
1525         catch (...)
1526         {
1527                 ServerInstance->Log(DEBUG,"Exception in userrec::WriteCommon()");
1528         }
1529 }
1530
1531
1532 /* write a formatted string to all users who share at least one common
1533  * channel, NOT including the source user e.g. for use in QUIT
1534  */
1535
1536 void userrec::WriteCommonExcept(const char* text, ...)
1537 {
1538         char textbuffer[MAXBUF];
1539         va_list argsPtr;
1540
1541         va_start(argsPtr, text);
1542         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1543         va_end(argsPtr);
1544
1545         this->WriteCommonExcept(std::string(textbuffer));
1546 }
1547
1548 void userrec::WriteCommonExcept(const std::string &text)
1549 {
1550         bool quit_munge = false;
1551         char oper_quit[MAXBUF];
1552         char textbuffer[MAXBUF];
1553         char tb1[MAXBUF];
1554         char tb2[MAXBUF];
1555         std::string out1;
1556         std::string out2;
1557
1558         strlcpy(textbuffer, text.c_str(), MAXBUF);
1559
1560         if (this->registered != REG_ALL)
1561                 return;
1562
1563         uniq_id++;
1564
1565         snprintf(tb1,MAXBUF,":%s %s",this->GetFullHost(),textbuffer);
1566
1567         /* TODO: We need some form of WriteCommonExcept that will send two lines, one line to
1568          * opers and the other line to non-opers, then all this hidebans and hidesplits gunk
1569          * can go byebye.
1570          */
1571         if (ServerInstance->Config->HideSplits)
1572         {
1573                 char* check = textbuffer + 6;
1574
1575                 if (!strncasecmp(textbuffer, "QUIT :",6))
1576                 {
1577                         std::stringstream split(check);
1578                         std::string server_one;
1579                         std::string server_two;
1580
1581                         split >> server_one;
1582                         split >> server_two;
1583
1584                         if ((ServerInstance->FindServerName(server_one)) && (ServerInstance->FindServerName(server_two)))
1585                         {
1586                                 strlcpy(oper_quit,textbuffer,MAXQUIT);
1587                                 strlcpy(check,"*.net *.split",MAXQUIT);
1588                                 quit_munge = true;
1589                                 snprintf(tb2,MAXBUF,":%s %s",this->GetFullHost(),oper_quit);
1590                                 out2 = tb2;
1591                         }
1592                 }
1593         }
1594
1595         if ((ServerInstance->Config->HideBans) && (!quit_munge))
1596         {
1597                 if ((!strncasecmp(textbuffer, "QUIT :G-Lined:",14)) || (!strncasecmp(textbuffer, "QUIT :K-Lined:",14))
1598                 || (!strncasecmp(textbuffer, "QUIT :Q-Lined:",14)) || (!strncasecmp(textbuffer, "QUIT :Z-Lined:",14)))
1599                 {
1600                         char* check = textbuffer + 13;
1601                         strlcpy(oper_quit,textbuffer,MAXQUIT);
1602                         *check = 0;  // We don't need to strlcpy, we just chop it from the :
1603                         quit_munge = true;
1604                         snprintf(tb2,MAXBUF,":%s %s",this->GetFullHost(),oper_quit);
1605                         out2 = tb2;
1606                 }
1607         }
1608
1609         out1 = tb1;
1610
1611         for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1612         {
1613                 CUList *ulist = v->first->GetUsers();
1614                 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1615                 {
1616                         if (this != i->second)
1617                         {
1618                                 if ((IS_LOCAL(i->second)) && (already_sent[i->second->fd] != uniq_id))
1619                                 {
1620                                         already_sent[i->second->fd] = uniq_id;
1621                                         if (quit_munge)
1622                                                 i->second->Write(*i->second->oper ? out2 : out1);
1623                                         else
1624                                                 i->second->Write(out1);
1625                                 }
1626                         }
1627                 }
1628         }
1629
1630 }
1631
1632 void userrec::WriteWallOps(const std::string &text)
1633 {
1634         /* Does nothing if theyre not opered */
1635         if ((!*this->oper) && (IS_LOCAL(this)))
1636                 return;
1637
1638         std::string wallop = "WALLOPS :";
1639
1640         try
1641         {
1642                 wallop.append(text);
1643         }
1644         catch (...)
1645         {
1646                 ServerInstance->Log(DEBUG,"Exception in userrec::Write() std::string::append");
1647                 return;
1648         }
1649
1650         for (std::vector<userrec*>::const_iterator i = ServerInstance->local_users.begin(); i != ServerInstance->local_users.end(); i++)
1651         {
1652                 userrec* t = *i;
1653                 if ((IS_LOCAL(t)) && (t->modes[UM_WALLOPS]))
1654                         this->WriteTo(t,wallop);
1655         }
1656 }
1657
1658 void userrec::WriteWallOps(const char* text, ...)
1659 {       
1660         char textbuffer[MAXBUF];
1661         va_list argsPtr;
1662
1663         va_start(argsPtr, text);
1664         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1665         va_end(argsPtr);                
1666                                         
1667         this->WriteWallOps(std::string(textbuffer));
1668 }                                      
1669
1670 /* return 0 or 1 depending if users u and u2 share one or more common channels
1671  * (used by QUIT, NICK etc which arent channel specific notices)
1672  *
1673  * The old algorithm in 1.0 for this was relatively inefficient, iterating over
1674  * the first users channels then the second users channels within the outer loop,
1675  * therefore it was a maximum of x*y iterations (upon returning 0 and checking
1676  * all possible iterations). However this new function instead checks against the
1677  * channel's userlist in the inner loop which is a std::map<userrec*,userrec*>
1678  * and saves us time as we already know what pointer value we are after.
1679  * Don't quote me on the maths as i am not a mathematician or computer scientist,
1680  * but i believe this algorithm is now x+(log y) maximum iterations instead.
1681  */
1682 bool userrec::SharesChannelWith(userrec *other)
1683 {
1684         if ((!other) || (this->registered != REG_ALL) || (other->registered != REG_ALL))
1685                 return false;
1686
1687         /* Outer loop */
1688         for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1689         {
1690                 /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
1691                  * by replacing it with a map::find which *should* be more efficient
1692                  */
1693                 if (i->first->HasUser(other))
1694                         return true;
1695         }
1696         return false;
1697 }
1698
1699 bool userrec::ChangeName(const char* gecos)
1700 {
1701         if (!strcmp(gecos, this->fullname))
1702                 return true;
1703
1704         if (IS_LOCAL(this))
1705         {
1706                 int MOD_RESULT = 0;
1707                 FOREACH_RESULT(I_OnChangeLocalUserGECOS,OnChangeLocalUserGECOS(this,gecos));
1708                 if (MOD_RESULT)
1709                         return false;
1710                 FOREACH_MOD(I_OnChangeName,OnChangeName(this,gecos));
1711         }
1712         strlcpy(this->fullname,gecos,MAXGECOS+1);
1713
1714         return true;
1715 }
1716
1717 bool userrec::ChangeDisplayedHost(const char* host)
1718 {
1719         if (!strcmp(host, this->dhost))
1720                 return true;
1721
1722         if (IS_LOCAL(this))
1723         {
1724                 int MOD_RESULT = 0;
1725                 FOREACH_RESULT(I_OnChangeLocalUserHost,OnChangeLocalUserHost(this,host));
1726                 if (MOD_RESULT)
1727                         return false;
1728                 FOREACH_MOD(I_OnChangeHost,OnChangeHost(this,host));
1729         }
1730         if (this->ServerInstance->Config->CycleHosts)
1731                 this->WriteCommonExcept("QUIT :Changing hosts");
1732
1733         /* Fix by Om: userrec::dhost is 65 long, this was truncating some long hosts */
1734         strlcpy(this->dhost,host,64);
1735
1736         this->InvalidateCache();
1737
1738         if (this->ServerInstance->Config->CycleHosts)
1739         {
1740                 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1741                 {
1742                         i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name);
1743                         std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
1744                         if (n.length() > 0)
1745                                 i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name, n.c_str());
1746                 }
1747         }
1748
1749         if (IS_LOCAL(this))
1750                 this->WriteServ("396 %s %s :is now your hidden host",this->nick,this->dhost);
1751
1752         return true;
1753 }
1754
1755 bool userrec::ChangeIdent(const char* newident)
1756 {
1757         if (!strcmp(newident, this->ident))
1758                 return true;
1759
1760         if (this->ServerInstance->Config->CycleHosts)
1761                 this->WriteCommonExcept("%s","QUIT :Changing ident");
1762
1763         strlcpy(this->ident, newident, IDENTMAX+2);
1764
1765         this->InvalidateCache();
1766
1767         if (this->ServerInstance->Config->CycleHosts)
1768         {
1769                 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1770                 {
1771                         i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name);
1772                         std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
1773                         if (n.length() > 0)
1774                                 i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name, n.c_str());
1775                 }
1776         }
1777
1778         return true;
1779 }
1780
1781 void userrec::NoticeAll(char* text, ...)
1782 {
1783         char textbuffer[MAXBUF];
1784         char formatbuffer[MAXBUF];
1785         va_list argsPtr;
1786
1787         va_start(argsPtr, text);
1788         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1789         va_end(argsPtr);
1790
1791         snprintf(formatbuffer,MAXBUF,":%s NOTICE $* :%s", this->GetFullHost(), textbuffer);
1792         std::string fmt = formatbuffer;
1793
1794         for (std::vector<userrec*>::const_iterator i = ServerInstance->local_users.begin(); i != ServerInstance->local_users.end(); i++)
1795         {
1796                 (*i)->Write(fmt);
1797         }
1798 }
1799
1800
1801 std::string userrec::ChannelList(userrec* source)
1802 {
1803         try
1804         {
1805                 std::string list;
1806                 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1807                 {
1808                         /* If the target is the same as the sender, let them see all their channels.
1809                          * If the channel is NOT private/secret OR the user shares a common channel
1810                          * If the user is an oper, and the <options:operspywhois> option is set.
1811                          */
1812                         if ((source == this) || (*source->oper && ServerInstance->Config->OperSpyWhois) || (((!i->first->modes[CM_PRIVATE]) && (!i->first->modes[CM_SECRET])) || (i->first->HasUser(source))))
1813                         {
1814                                 list.append(i->first->GetPrefixChar(this)).append(i->first->name).append(" ");
1815                         }
1816                 }
1817                 return list;
1818         }
1819         catch (...)
1820         {
1821                 ServerInstance->Log(DEBUG,"Exception in userrec::ChannelList()");
1822                 return "";
1823         }
1824 }
1825
1826 void userrec::SplitChanList(userrec* dest, const std::string &cl)
1827 {
1828         std::string line;
1829         std::ostringstream prefix;
1830         std::string::size_type start, pos, length;
1831
1832         try
1833         {
1834                 prefix << this->nick << " " << dest->nick << " :";
1835                 line = prefix.str();
1836                 int namelen = strlen(ServerInstance->Config->ServerName) + 6;
1837         
1838                 for (start = 0; (pos = cl.find(' ', start)) != std::string::npos; start = pos+1)
1839                 {
1840                         length = (pos == std::string::npos) ? cl.length() : pos;
1841         
1842                         if (line.length() + namelen + length - start > 510)
1843                         {
1844                                 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1845                                 line = prefix.str();
1846                         }
1847         
1848                         if(pos == std::string::npos)
1849                         {
1850                                 line.append(cl.substr(start, length - start));
1851                                 break;
1852                         }
1853                         else
1854                         {
1855                                 line.append(cl.substr(start, length - start + 1));
1856                         }
1857                 }
1858         
1859                 if (line.length())
1860                 {
1861                         ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1862                 }
1863         }
1864
1865         catch (...)
1866         {
1867                 ServerInstance->Log(DEBUG,"Exception in userrec::SplitChanList()");
1868         }
1869 }
1870
1871
1872 /* looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1873  * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1874  * then their ip will be taken as 'priority' anyway, so for example,
1875  * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1876  */
1877 ConnectClass* userrec::GetClass()
1878 {
1879         for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1880         {
1881                 if ((match(this->GetIPString(),i->GetHost().c_str(),true)) || (match(this->host,i->GetHost().c_str())))
1882                         return &(*i);
1883         }
1884         return NULL;
1885 }
1886
1887 void userrec::PurgeEmptyChannels()
1888 {
1889         std::vector<chanrec*> to_delete;
1890
1891         // firstly decrement the count on each channel
1892         for (UCListIter f = this->chans.begin(); f != this->chans.end(); f++)
1893         {
1894                 f->first->RemoveAllPrefixes(this);
1895                 if (f->first->DelUser(this) == 0)
1896                 {
1897                         /* No users left in here, mark it for deletion */
1898                         try
1899                         {
1900                                 to_delete.push_back(f->first);
1901                         }
1902                         catch (...)
1903                         {
1904                                 ServerInstance->Log(DEBUG,"Exception in userrec::PurgeEmptyChannels to_delete.push_back()");
1905                         }
1906                 }
1907         }
1908
1909         for (std::vector<chanrec*>::iterator n = to_delete.begin(); n != to_delete.end(); n++)
1910         {
1911                 chanrec* thischan = *n;
1912                 chan_hash::iterator i2 = ServerInstance->chanlist->find(thischan->name);
1913                 if (i2 != ServerInstance->chanlist->end())
1914                 {
1915                         FOREACH_MOD(I_OnChannelDelete,OnChannelDelete(i2->second));
1916                         DELETE(i2->second);
1917                         ServerInstance->chanlist->erase(i2);
1918                         this->chans.erase(*n);
1919                 }
1920         }
1921
1922         this->UnOper();
1923 }
1924
1925 void userrec::ShowMOTD()
1926 {
1927         if (!ServerInstance->Config->MOTD.size())
1928         {
1929                 this->WriteServ("422 %s :Message of the day file is missing.",this->nick);
1930                 return;
1931         }
1932         this->WriteServ("375 %s :%s message of the day", this->nick, ServerInstance->Config->ServerName);
1933
1934         for (file_cache::iterator i = ServerInstance->Config->MOTD.begin(); i != ServerInstance->Config->MOTD.end(); i++)
1935                 this->WriteServ("372 %s :- %s",this->nick,i->c_str());
1936
1937         this->WriteServ("376 %s :End of message of the day.", this->nick);
1938 }
1939
1940 void userrec::ShowRULES()
1941 {
1942         if (!ServerInstance->Config->RULES.size())
1943         {
1944                 this->WriteServ("NOTICE %s :Rules file is missing.",this->nick);
1945                 return;
1946         }
1947         this->WriteServ("NOTICE %s :%s rules",this->nick,ServerInstance->Config->ServerName);
1948
1949         for (file_cache::iterator i = ServerInstance->Config->RULES.begin(); i != ServerInstance->Config->RULES.end(); i++)
1950                 this->WriteServ("NOTICE %s :%s",this->nick,i->c_str());
1951
1952         this->WriteServ("NOTICE %s :End of %s rules.",this->nick,ServerInstance->Config->ServerName);
1953 }
1954
1955 void userrec::HandleEvent(EventType et, int errornum)
1956 {
1957         /* WARNING: May delete this user! */
1958         int thisfd = this->GetFd();
1959
1960         try
1961         {
1962                 switch (et)
1963                 {
1964                         case EVENT_READ:
1965                                 ServerInstance->ProcessUser(this);
1966                         break;
1967                         case EVENT_WRITE:
1968                                 this->FlushWriteBuf();
1969                         break;
1970                         case EVENT_ERROR:
1971                                 /** This should be safe, but dont DARE do anything after it -- Brain */
1972                                 this->SetWriteError(errornum ? strerror(errornum) : "EOF from client");
1973                         break;
1974                 }
1975         }
1976         catch (...)
1977         {
1978                 ServerInstance->Log(DEBUG,"Exception in userrec::HandleEvent intercepted");
1979         }
1980
1981         /* If the user has raised an error whilst being processed, quit them now we're safe to */
1982         if ((ServerInstance->SE->GetRef(thisfd) == this))
1983         {
1984                 if (!WriteError.empty())
1985                 {
1986                         userrec::QuitUser(ServerInstance, this, GetWriteError());
1987                 }
1988         }
1989 }
1990