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