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