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