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