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