1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2008 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
15 #include "commands/cmd_whois.h"
16 #include "commands/cmd_stats.h"
20 #include "transport.h"
22 #include "socketengine.h"
24 #include "m_spanningtree/main.h"
25 #include "m_spanningtree/utils.h"
26 #include "m_spanningtree/treeserver.h"
27 #include "m_spanningtree/link.h"
28 #include "m_spanningtree/treesocket.h"
29 #include "m_spanningtree/resolvers.h"
30 #include "m_spanningtree/handshaketimer.h"
32 /* $ModDep: m_spanningtree/timesynctimer.h m_spanningtree/resolvers.h m_spanningtree/main.h m_spanningtree/utils.h m_spanningtree/treeserver.h m_spanningtree/link.h m_spanningtree/treesocket.h m_hash.h */
35 /** Because most of the I/O gubbins are encapsulated within
36 * BufferedSocket, we just call the superclass constructor for
37 * most of the action, and append a few of our own values
40 TreeSocket::TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, std::string host, int port, bool listening, unsigned long maxtime, Module* HookMod)
41 : BufferedSocket(SI, host, port, listening, maxtime), Utils(Util), Hook(HookMod)
44 this->LinkState = LISTENER;
45 theirchallenge.clear();
47 if (listening && Hook)
48 BufferedSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
51 TreeSocket::TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, std::string host, int port, bool listening, unsigned long maxtime, const std::string &ServerName, const std::string &bindto, Module* HookMod)
52 : BufferedSocket(SI, host, port, listening, maxtime, bindto), Utils(Util), Hook(HookMod)
55 theirchallenge.clear();
57 this->LinkState = CONNECTING;
59 BufferedSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
62 /** When a listening socket gives us a new file descriptor,
63 * we must associate it with a socket without creating a new
64 * connection. This constructor is used for this purpose.
66 TreeSocket::TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, int newfd, char* ip, Module* HookMod)
67 : BufferedSocket(SI, newfd, ip), Utils(Util), Hook(HookMod)
69 this->LinkState = WAIT_AUTH_1;
70 theirchallenge.clear();
73 /* If we have a transport module hooked to the parent, hook the same module to this
74 * socket, and set a timer waiting for handshake before we send CAPAB etc.
77 BufferedSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
79 Instance->Timers->AddTimer(new HandshakeTimer(Instance, this, &(Utils->LinkBlocks[0]), this->Utils, 1));
82 ServerState TreeSocket::GetLinkState()
84 return this->LinkState;
87 Module* TreeSocket::GetHook()
92 TreeSocket::~TreeSocket()
95 BufferedSocketUnhookRequest(this, (Module*)Utils->Creator, Hook).Send();
98 const std::string& TreeSocket::GetOurChallenge()
100 return this->ourchallenge;
103 void TreeSocket::SetOurChallenge(const std::string &c)
105 this->ourchallenge = c;
108 const std::string& TreeSocket::GetTheirChallenge()
110 return this->theirchallenge;
113 void TreeSocket::SetTheirChallenge(const std::string &c)
115 this->theirchallenge = c;
118 std::string TreeSocket::MakePass(const std::string &password, const std::string &challenge)
120 /* This is a simple (maybe a bit hacky?) HMAC algorithm, thanks to jilles for
121 * suggesting the use of HMAC to secure the password against various attacks.
123 * Note: If m_sha256.so is not loaded, we MUST fall back to plaintext with no
124 * HMAC challenge/response.
126 Module* sha256 = Instance->Modules->Find("m_sha256.so");
127 if (Utils->ChallengeResponse && sha256 && !challenge.empty())
129 /* XXX: This is how HMAC is supposed to be done:
131 * sha256( (pass xor 0x5c) + sha256((pass xor 0x36) + m) )
133 * Note that we are encoding the hex hash, not the binary
134 * output of the hash which is slightly different to standard.
136 * Don't ask me why its always 0x5c and 0x36... it just is.
138 std::string hmac1, hmac2;
140 for (size_t n = 0; n < password.length(); n++)
142 hmac1 += static_cast<char>(password[n] ^ 0x5C);
143 hmac2 += static_cast<char>(password[n] ^ 0x36);
147 HashResetRequest(Utils->Creator, sha256).Send();
148 hmac2 = HashSumRequest(Utils->Creator, sha256, hmac2).Send();
150 HashResetRequest(Utils->Creator, sha256).Send();
151 std::string hmac = hmac1 + hmac2;
152 hmac = HashSumRequest(Utils->Creator, sha256, hmac).Send();
154 return "HMAC-SHA256:"+ hmac;
156 else if (!challenge.empty() && !sha256)
157 Instance->Log(DEFAULT,"Not authenticating to server using SHA256/HMAC because we don't have m_sha256 loaded!");
162 /** When an outbound connection finishes connecting, we receive
163 * this event, and must send our SERVER string to the other
164 * side. If the other side is happy, as outlined in the server
165 * to server docs on the inspircd.org site, the other side
166 * will then send back its own server string.
168 bool TreeSocket::OnConnected()
170 if (this->LinkState == CONNECTING)
172 /* we do not need to change state here. */
173 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
175 if (x->Name == this->myhost)
177 Utils->Creator->RemoteMessage(NULL,"Connection to \2%s\2[%s] started.", myhost.c_str(), (x->HiddenFromStats ? "<hidden>" : this->GetIP().c_str()));
180 BufferedSocketHookRequest(this, (Module*)Utils->Creator, Hook).Send();
181 Utils->Creator->RemoteMessage(NULL,"Connection to \2%s\2[%s] using transport \2%s\2", myhost.c_str(), (x->HiddenFromStats ? "<hidden>" : this->GetIP().c_str()),
184 this->OutboundPass = x->SendPass;
187 /* found who we're supposed to be connecting to, send the neccessary gubbins. */
189 Instance->Timers->AddTimer(new HandshakeTimer(Instance, this, &(*x), this->Utils, 1));
191 this->SendCapabilities();
197 /* There is a (remote) chance that between the /CONNECT and the connection
198 * being accepted, some muppet has removed the <link> block and rehashed.
199 * If that happens the connection hangs here until it's closed. Unlikely
200 * and rather harmless.
202 this->Utils->Creator->RemoteMessage(NULL,"Connection to \2%s\2 lost link tag(!)", myhost.c_str());
206 void TreeSocket::OnError(BufferedSocketError e)
210 if (this->LinkState == LISTENER)
216 Utils->Creator->RemoteMessage(NULL,"Connection failed: Connection to \002%s\002 refused", myhost.c_str());
217 MyLink = Utils->FindLink(myhost);
219 Utils->DoFailOver(MyLink);
222 Utils->Creator->RemoteMessage(NULL,"Connection failed: Could not create socket");
225 Utils->Creator->RemoteMessage(NULL,"Connection failed: Error binding socket to address or port");
228 Utils->Creator->RemoteMessage(NULL,"Connection failed: I/O error on connection");
230 case I_ERR_NOMOREFDS:
231 Utils->Creator->RemoteMessage(NULL,"Connection failed: Operating system is out of file descriptors!");
234 if ((errno) && (errno != EINPROGRESS) && (errno != EAGAIN))
235 Utils->Creator->RemoteMessage(NULL,"Connection to \002%s\002 failed with OS error: %s", myhost.c_str(), strerror(errno));
240 int TreeSocket::OnDisconnect()
242 /* For the same reason as above, we don't
243 * handle OnDisconnect()
248 /** Recursively send the server tree with distances as hops.
249 * This is used during network burst to inform the other server
250 * (and any of ITS servers too) of what servers we know about.
251 * If at any point any of these servers already exist on the other
252 * end, our connection may be terminated. The hopcounts given
253 * by this function are relative, this doesn't matter so long as
254 * they are all >1, as all the remote servers re-calculate them
255 * to be relative too, with themselves as hop 0.
257 void TreeSocket::SendServers(TreeServer* Current, TreeServer* s, int hops)
260 for (unsigned int q = 0; q < Current->ChildCount(); q++)
262 TreeServer* recursive_server = Current->GetChild(q);
263 if (recursive_server != s)
265 snprintf(command,1024,":%s SERVER %s * %d %s :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,
266 recursive_server->GetID().c_str(),
267 recursive_server->GetDesc().c_str());
268 this->WriteLine(command);
269 this->WriteLine(":"+recursive_server->GetName()+" VERSION :"+recursive_server->GetVersion());
270 /* down to next level */
271 this->SendServers(recursive_server, s, hops+1);
276 std::string TreeSocket::RandString(unsigned int length)
278 char* randombuf = new char[length+1];
283 int fd = open("/dev/urandom", O_RDONLY, 0);
289 read(fd, randombuf, length);
295 for (unsigned int i = 0; i < length; i++)
296 randombuf[i] = rand();
299 for (unsigned int i = 0; i < length; i++)
301 char randchar = static_cast<char>((randombuf[i] & 0x7F) | 0x21);
302 out += (randchar == '=' ? '_' : randchar);
309 void TreeSocket::SendError(const std::string &errormessage)
311 /* Display the error locally as well as sending it remotely */
312 Utils->Creator->RemoteMessage(NULL, "Sent \2ERROR\2 to %s: %s", (this->InboundServerName.empty() ? "<unknown>" : this->InboundServerName.c_str()), errormessage.c_str());
313 this->WriteLine("ERROR :"+errormessage);
314 /* One last attempt to make sure the error reaches its target */
315 this->FlushWriteBuffer();
318 /** This function forces this server to quit, removing this server
319 * and any users on it (and servers and users below that, etc etc).
320 * It's very slow and pretty clunky, but luckily unless your network
321 * is having a REAL bad hair day, this function shouldnt be called
322 * too many times a month ;-)
324 void TreeSocket::SquitServer(std::string &from, TreeServer* Current)
326 /* recursively squit the servers attached to 'Current'.
327 * We're going backwards so we don't remove users
328 * while we still need them ;)
330 for (unsigned int q = 0; q < Current->ChildCount(); q++)
332 TreeServer* recursive_server = Current->GetChild(q);
333 this->SquitServer(from,recursive_server);
335 /* Now we've whacked the kids, whack self */
337 num_lost_users += Current->QuitUsers(from);
340 /** This is a wrapper function for SquitServer above, which
341 * does some validation first and passes on the SQUIT to all
342 * other remaining servers.
344 void TreeSocket::Squit(TreeServer* Current, const std::string &reason)
346 if ((Current) && (Current != Utils->TreeRoot))
348 Event rmode((char*)Current->GetName().c_str(), (Module*)Utils->Creator, "lost_server");
349 rmode.Send(Instance);
351 std::deque<std::string> params;
352 params.push_back(Current->GetName());
353 params.push_back(":"+reason);
354 Utils->DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
355 if (Current->GetParent() == Utils->TreeRoot)
357 this->Instance->SNO->WriteToSnoMask('l',"Server \002"+Current->GetName()+"\002 split: "+reason);
361 this->Instance->SNO->WriteToSnoMask('l',"Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
363 num_lost_servers = 0;
365 std::string from = Current->GetParent()->GetName()+" "+Current->GetName();
366 SquitServer(from, Current);
368 Current->GetParent()->DelChild(Current);
370 this->Instance->SNO->WriteToSnoMask('l',"Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
373 Instance->Log(DEFAULT,"Squit from unknown server");
376 /** Send one or more FJOINs for a channel of users.
377 * If the length of a single line is more than 480-NICKMAX
378 * in length, it is split over multiple lines.
380 void TreeSocket::SendFJoins(TreeServer* Current, Channel* c)
384 std::string individual_halfops = std::string(":")+this->Instance->Config->GetSID()+" FMODE "+c->name+" "+ConvToStr(c->age);
387 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",this->Instance->Config->GetSID().c_str(),c->name,(unsigned long)c->age);
389 char* ptr = list + dlen;
391 CUList *ulist = c->GetUsers();
395 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
397 // The first parameter gets a : before it
398 size_t ptrlen = snprintf(ptr, MAXBUF, " %s%s,%s", !numusers ? ":" : "", c->GetAllPrefixChars(i->first), i->first->uuid);
405 if (curlen > (480-NICKMAX))
407 buffer.append(list).append("\r\n");
408 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",this->Instance->Config->GetSID().c_str(),c->name,(unsigned long)c->age);
416 buffer.append(list).append("\r\n");
418 buffer.append(":").append(this->Instance->Config->GetSID()).append(" FMODE ").append(c->name).append(" ").append(ConvToStr(c->age)).append(" +").append(c->ChanModes(true)).append("\r\n");
421 for (BanList::iterator b = c->bans.begin(); b != c->bans.end(); b++)
423 int size = strlen(b->data) + 2;
424 int currsize = linesize + size;
428 params.append(" ").append(b->data);
431 if ((params.length() >= MAXMODES) || (currsize > 350))
433 /* Wrap at MAXMODES */
434 buffer.append(":").append(this->Instance->Config->GetSID()).append(" FMODE ").append(c->name).append(" ").append(ConvToStr(c->age)).append(" +").append(modes).append(params).append("\r\n");
441 /* Only send these if there are any */
443 buffer.append(":").append(this->Instance->Config->GetSID()).append(" FMODE ").append(c->name).append(" ").append(ConvToStr(c->age)).append(" +").append(modes).append(params);
445 this->WriteLine(buffer);
448 /** Send G, Q, Z and E lines */
449 void TreeSocket::SendXLines(TreeServer* Current)
453 std::string n = this->Instance->Config->GetSID();
454 const char* sn = n.c_str();
456 std::vector<std::string> types = Instance->XLines->GetAllTypes();
458 for (std::vector<std::string>::iterator it = types.begin(); it != types.end(); ++it)
460 XLineLookup* lookup = Instance->XLines->GetAll(*it);
464 for (LookupIter i = lookup->begin(); i != lookup->end(); ++i)
466 snprintf(data,MAXBUF,":%s ADDLINE %s %s %s %lu %lu :%s\r\n",sn, it->c_str(), i->second->Displayable(),
468 (unsigned long)i->second->set_time,
469 (unsigned long)i->second->duration,
477 this->WriteLine(buffer);
480 /** Send channel modes and topics */
481 void TreeSocket::SendChannelModes(TreeServer* Current)
484 std::deque<std::string> list;
485 std::string n = this->Instance->Config->GetSID();
486 const char* sn = n.c_str();
487 Instance->Log(DEBUG,"Sending channels and modes, %d to send", this->Instance->chanlist->size());
488 for (chan_hash::iterator c = this->Instance->chanlist->begin(); c != this->Instance->chanlist->end(); c++)
490 SendFJoins(Current, c->second);
491 if (*c->second->topic)
493 snprintf(data,MAXBUF,":%s FTOPIC %s %lu %s :%s",sn,c->second->name,(unsigned long)c->second->topicset,c->second->setby,c->second->topic);
494 this->WriteLine(data);
496 FOREACH_MOD_I(this->Instance,I_OnSyncChannel,OnSyncChannel(c->second,(Module*)Utils->Creator,(void*)this));
498 c->second->GetExtList(list);
499 for (unsigned int j = 0; j < list.size(); j++)
501 FOREACH_MOD_I(this->Instance,I_OnSyncChannelMetaData,OnSyncChannelMetaData(c->second,(Module*)Utils->Creator,(void*)this,list[j]));
506 /** send all users and their oper state/modes */
507 void TreeSocket::SendUsers(TreeServer* Current)
510 std::deque<std::string> list;
511 std::string dataline;
512 for (user_hash::iterator u = this->Instance->Users->clientlist->begin(); u != this->Instance->Users->clientlist->end(); u++)
514 if (u->second->registered == REG_ALL)
516 TreeServer* theirserver = Utils->FindServer(u->second->server);
519 snprintf(data,MAXBUF,":%s UID %s %lu %s %s %s %s +%s %s %lu :%s", theirserver->GetID().c_str(), u->second->uuid,
520 (unsigned long)u->second->age, u->second->nick, u->second->host, u->second->dhost,
521 u->second->ident, u->second->FormatModes(), u->second->GetIPString(),
522 (unsigned long)u->second->signon, u->second->fullname);
523 this->WriteLine(data);
524 if (*u->second->oper)
526 snprintf(data,MAXBUF,":%s OPERTYPE %s", u->second->uuid, u->second->oper);
527 this->WriteLine(data);
529 if (*u->second->awaymsg)
531 snprintf(data,MAXBUF,":%s AWAY :%s", u->second->uuid, u->second->awaymsg);
532 this->WriteLine(data);
536 FOREACH_MOD_I(this->Instance,I_OnSyncUser,OnSyncUser(u->second,(Module*)Utils->Creator,(void*)this));
538 u->second->GetExtList(list);
539 for (unsigned int j = 0; j < list.size(); j++)
541 FOREACH_MOD_I(this->Instance,I_OnSyncUserMetaData,OnSyncUserMetaData(u->second,(Module*)Utils->Creator,(void*)this,list[j]));
547 /** This function is called when we want to send a netburst to a local
548 * server. There is a set order we must do this, because for example
549 * users require their servers to exist, and channels require their
550 * users to exist. You get the idea.
552 void TreeSocket::DoBurst(TreeServer* s)
554 std::string name = s->GetName();
555 std::string burst = ":" + this->Instance->Config->GetSID() + " BURST " +ConvToStr(Instance->Time(true));
556 std::string endburst = ":" + this->Instance->Config->GetSID() + " ENDBURST";
557 this->Instance->SNO->WriteToSnoMask('l',"Bursting to \2%s\2 (Authentication: %s).", name.c_str(), this->GetTheirChallenge().empty() ? "plaintext password" : "SHA256-HMAC challenge-response");
558 this->WriteLine(burst);
559 /* send our version string */
560 this->WriteLine(std::string(":")+this->Instance->Config->GetSID()+" VERSION :"+this->Instance->GetVersionString());
561 /* Send server tree */
562 this->SendServers(Utils->TreeRoot,s,1);
563 /* Send users and their oper status */
565 /* Send everything else (channel modes, xlines etc) */
566 this->SendChannelModes(s);
568 FOREACH_MOD_I(this->Instance,I_OnSyncOtherMetaData,OnSyncOtherMetaData((Module*)Utils->Creator,(void*)this));
569 this->WriteLine(endburst);
570 this->Instance->SNO->WriteToSnoMask('l',"Finished bursting to \2"+name+"\2.");
573 /** This function is called when we receive data from a remote
574 * server. We buffer the data in a std::string (it doesnt stay
575 * there for long), reading using BufferedSocket::Read() which can
576 * read up to 16 kilobytes in one operation.
578 * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
579 * THE SOCKET OBJECT FOR US.
581 bool TreeSocket::OnDataReady()
583 char* data = this->Read();
584 /* Check that the data read is a valid pointer and it has some content */
587 this->in_buffer.append(data);
588 /* While there is at least one new line in the buffer,
589 * do something useful (we hope!) with it.
591 while (in_buffer.find("\n") != std::string::npos)
593 std::string ret = in_buffer.substr(0,in_buffer.find("\n")-1);
594 in_buffer = in_buffer.substr(in_buffer.find("\n")+1,in_buffer.length()-in_buffer.find("\n"));
595 /* Use rfind here not find, as theres more
596 * chance of the \r being near the end of the
597 * string, not the start.
599 if (ret.find("\r") != std::string::npos)
600 ret = in_buffer.substr(0,in_buffer.find("\r")-1);
601 /* Process this one, abort if it
604 if (!this->ProcessLine(ret))
611 /* EAGAIN returns an empty but non-NULL string, so this
612 * evaluates to TRUE for EAGAIN but to FALSE for EOF.
614 return (data && !*data);