1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
|
/**********
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the
Free Software Foundation; either version 2.1 of the License, or (at your
option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.)
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********/
// Copyright (c) 1996-2012 Live Networks, Inc. All rights reserved.
// 'Group sockets'
// Implementation
#include "Groupsock.hh"
#include "GroupsockHelper.hh"
//##### Eventually fix the following #include; we shouldn't know about tunnels
#include "TunnelEncaps.hh"
#ifndef NO_SSTREAM
#include <sstream>
#endif
#include <stdio.h>
///////// OutputSocket //////////
OutputSocket::OutputSocket(UsageEnvironment& env)
: Socket(env, 0 /* let kernel choose port */),
fSourcePort(0), fLastSentTTL(0) {
}
OutputSocket::OutputSocket(UsageEnvironment& env, Port port)
: Socket(env, port),
fSourcePort(0), fLastSentTTL(0) {
}
OutputSocket::~OutputSocket() {
}
Boolean OutputSocket::write(netAddressBits address, Port port, u_int8_t ttl,
unsigned char* buffer, unsigned bufferSize) {
if (ttl == fLastSentTTL) {
// Optimization: So we don't do a 'set TTL' system call again
ttl = 0;
} else {
fLastSentTTL = ttl;
}
struct in_addr destAddr; destAddr.s_addr = address;
if (!writeSocket(env(), socketNum(), destAddr, port, ttl,
buffer, bufferSize))
return False;
if (sourcePortNum() == 0) {
// Now that we've sent a packet, we can find out what the
// kernel chose as our ephemeral source port number:
if (!getSourcePort(env(), socketNum(), fSourcePort)) {
if (DebugLevel >= 1)
env() << *this
<< ": failed to get source port: "
<< env().getResultMsg() << "\n";
return False;
}
}
return True;
}
// By default, we don't do reads:
Boolean OutputSocket
::handleRead(unsigned char* /*buffer*/, unsigned /*bufferMaxSize*/,
unsigned& /*bytesRead*/, struct sockaddr_in& /*fromAddress*/) {
return True;
}
///////// destRecord //////////
destRecord
::destRecord(struct in_addr const& addr, Port const& port, u_int8_t ttl,
destRecord* next)
: fNext(next), fGroupEId(addr, port.num(), ttl), fPort(port) {
}
destRecord::~destRecord() {
delete fNext;
}
///////// Groupsock //////////
NetInterfaceTrafficStats Groupsock::statsIncoming;
NetInterfaceTrafficStats Groupsock::statsOutgoing;
NetInterfaceTrafficStats Groupsock::statsRelayedIncoming;
NetInterfaceTrafficStats Groupsock::statsRelayedOutgoing;
// Constructor for a source-independent multicast group
Groupsock::Groupsock(UsageEnvironment& env, struct in_addr const& groupAddr,
Port port, u_int8_t ttl)
: OutputSocket(env, port),
deleteIfNoMembers(False), isSlave(False),
fIncomingGroupEId(groupAddr, port.num(), ttl), fDests(NULL), fTTL(ttl) {
addDestination(groupAddr, port);
if (!socketJoinGroup(env, socketNum(), groupAddr.s_addr)) {
if (DebugLevel >= 1) {
env << *this << ": failed to join group: "
<< env.getResultMsg() << "\n";
}
}
// Make sure we can get our source address:
if (ourIPAddress(env) == 0) {
if (DebugLevel >= 0) { // this is a fatal error
env << "Unable to determine our source address: "
<< env.getResultMsg() << "\n";
}
}
if (DebugLevel >= 2) env << *this << ": created\n";
}
// Constructor for a source-specific multicast group
Groupsock::Groupsock(UsageEnvironment& env, struct in_addr const& groupAddr,
struct in_addr const& sourceFilterAddr,
Port port)
: OutputSocket(env, port),
deleteIfNoMembers(False), isSlave(False),
fIncomingGroupEId(groupAddr, sourceFilterAddr, port.num()),
fDests(NULL), fTTL(255) {
addDestination(groupAddr, port);
// First try a SSM join. If that fails, try a regular join:
if (!socketJoinGroupSSM(env, socketNum(), groupAddr.s_addr,
sourceFilterAddr.s_addr)) {
if (DebugLevel >= 3) {
env << *this << ": SSM join failed: "
<< env.getResultMsg();
env << " - trying regular join instead\n";
}
if (!socketJoinGroup(env, socketNum(), groupAddr.s_addr)) {
if (DebugLevel >= 1) {
env << *this << ": failed to join group: "
<< env.getResultMsg() << "\n";
}
}
}
if (DebugLevel >= 2) env << *this << ": created\n";
}
Groupsock::~Groupsock() {
if (isSSM()) {
if (!socketLeaveGroupSSM(env(), socketNum(), groupAddress().s_addr,
sourceFilterAddress().s_addr)) {
socketLeaveGroup(env(), socketNum(), groupAddress().s_addr);
}
} else {
socketLeaveGroup(env(), socketNum(), groupAddress().s_addr);
}
delete fDests;
if (DebugLevel >= 2) env() << *this << ": deleting\n";
}
void
Groupsock::changeDestinationParameters(struct in_addr const& newDestAddr,
Port newDestPort, int newDestTTL) {
if (fDests == NULL) return;
struct in_addr destAddr = fDests->fGroupEId.groupAddress();
if (newDestAddr.s_addr != 0) {
if (newDestAddr.s_addr != destAddr.s_addr
&& IsMulticastAddress(newDestAddr.s_addr)) {
// If the new destination is a multicast address, then we assume that
// we want to join it also. (If this is not in fact the case, then
// call "multicastSendOnly()" afterwards.)
socketLeaveGroup(env(), socketNum(), destAddr.s_addr);
socketJoinGroup(env(), socketNum(), newDestAddr.s_addr);
}
destAddr.s_addr = newDestAddr.s_addr;
}
portNumBits destPortNum = fDests->fGroupEId.portNum();
if (newDestPort.num() != 0) {
if (newDestPort.num() != destPortNum
&& IsMulticastAddress(destAddr.s_addr)) {
// Also bind to the new port number:
changePort(newDestPort);
// And rejoin the multicast group:
socketJoinGroup(env(), socketNum(), destAddr.s_addr);
}
destPortNum = newDestPort.num();
fDests->fPort = newDestPort;
}
u_int8_t destTTL = ttl();
if (newDestTTL != ~0) destTTL = (u_int8_t)newDestTTL;
fDests->fGroupEId = GroupEId(destAddr, destPortNum, destTTL);
}
void Groupsock::addDestination(struct in_addr const& addr, Port const& port) {
// Check whether this destination is already known:
for (destRecord* dests = fDests; dests != NULL; dests = dests->fNext) {
if (addr.s_addr == dests->fGroupEId.groupAddress().s_addr
&& port.num() == dests->fPort.num()) {
return;
}
}
fDests = new destRecord(addr, port, ttl(), fDests);
}
void Groupsock::removeDestination(struct in_addr const& addr, Port const& port) {
for (destRecord** destsPtr = &fDests; *destsPtr != NULL;
destsPtr = &((*destsPtr)->fNext)) {
if (addr.s_addr == (*destsPtr)->fGroupEId.groupAddress().s_addr
&& port.num() == (*destsPtr)->fPort.num()) {
// Remove the record pointed to by *destsPtr :
destRecord* next = (*destsPtr)->fNext;
(*destsPtr)->fNext = NULL;
delete (*destsPtr);
*destsPtr = next;
return;
}
}
}
void Groupsock::removeAllDestinations() {
delete fDests; fDests = NULL;
}
void Groupsock::multicastSendOnly() {
// We disable this code for now, because - on some systems - leaving the multicast group seems to cause sent packets
// to not be received by other applications (at least, on the same host).
#if 0
socketLeaveGroup(env(), socketNum(), fIncomingGroupEId.groupAddress().s_addr);
for (destRecord* dests = fDests; dests != NULL; dests = dests->fNext) {
socketLeaveGroup(env(), socketNum(), dests->fGroupEId.groupAddress().s_addr);
}
#endif
}
Boolean Groupsock::output(UsageEnvironment& env, u_int8_t ttlToSend,
unsigned char* buffer, unsigned bufferSize,
DirectedNetInterface* interfaceNotToFwdBackTo) {
do {
// First, do the datagram send, to each destination:
Boolean writeSuccess = True;
for (destRecord* dests = fDests; dests != NULL; dests = dests->fNext) {
if (!write(dests->fGroupEId.groupAddress().s_addr, dests->fPort, ttlToSend,
buffer, bufferSize)) {
writeSuccess = False;
break;
}
}
if (!writeSuccess) break;
statsOutgoing.countPacket(bufferSize);
statsGroupOutgoing.countPacket(bufferSize);
// Then, forward to our members:
int numMembers = 0;
if (!members().IsEmpty()) {
numMembers =
outputToAllMembersExcept(interfaceNotToFwdBackTo,
ttlToSend, buffer, bufferSize,
ourIPAddress(env));
if (numMembers < 0) break;
}
if (DebugLevel >= 3) {
env << *this << ": wrote " << bufferSize << " bytes, ttl "
<< (unsigned)ttlToSend;
if (numMembers > 0) {
env << "; relayed to " << numMembers << " members";
}
env << "\n";
}
return True;
} while (0);
if (DebugLevel >= 0) { // this is a fatal error
env.setResultMsg("Groupsock write failed: ", env.getResultMsg());
}
return False;
}
Boolean Groupsock::handleRead(unsigned char* buffer, unsigned bufferMaxSize,
unsigned& bytesRead,
struct sockaddr_in& fromAddress) {
// Read data from the socket, and relay it across any attached tunnels
//##### later make this code more general - independent of tunnels
bytesRead = 0;
int maxBytesToRead = bufferMaxSize - TunnelEncapsulationTrailerMaxSize;
int numBytes = readSocket(env(), socketNum(),
buffer, maxBytesToRead, fromAddress);
if (numBytes < 0) {
if (DebugLevel >= 0) { // this is a fatal error
env().setResultMsg("Groupsock read failed: ",
env().getResultMsg());
}
return False;
}
// If we're a SSM group, make sure the source address matches:
if (isSSM()
&& fromAddress.sin_addr.s_addr != sourceFilterAddress().s_addr) {
return True;
}
// We'll handle this data.
// Also write it (with the encapsulation trailer) to each member,
// unless the packet was originally sent by us to begin with.
bytesRead = numBytes;
int numMembers = 0;
if (!wasLoopedBackFromUs(env(), fromAddress)) {
statsIncoming.countPacket(numBytes);
statsGroupIncoming.countPacket(numBytes);
numMembers =
outputToAllMembersExcept(NULL, ttl(),
buffer, bytesRead,
fromAddress.sin_addr.s_addr);
if (numMembers > 0) {
statsRelayedIncoming.countPacket(numBytes);
statsGroupRelayedIncoming.countPacket(numBytes);
}
}
if (DebugLevel >= 3) {
env() << *this << ": read " << bytesRead << " bytes from " << AddressString(fromAddress).val();
if (numMembers > 0) {
env() << "; relayed to " << numMembers << " members";
}
env() << "\n";
}
return True;
}
Boolean Groupsock::wasLoopedBackFromUs(UsageEnvironment& env,
struct sockaddr_in& fromAddress) {
if (fromAddress.sin_addr.s_addr
== ourIPAddress(env)) {
if (fromAddress.sin_port == sourcePortNum()) {
#ifdef DEBUG_LOOPBACK_CHECKING
if (DebugLevel >= 3) {
env() << *this << ": got looped-back packet\n";
}
#endif
return True;
}
}
return False;
}
int Groupsock::outputToAllMembersExcept(DirectedNetInterface* exceptInterface,
u_int8_t ttlToFwd,
unsigned char* data, unsigned size,
netAddressBits sourceAddr) {
// Don't forward TTL-0 packets
if (ttlToFwd == 0) return 0;
DirectedNetInterfaceSet::Iterator iter(members());
unsigned numMembers = 0;
DirectedNetInterface* interf;
while ((interf = iter.next()) != NULL) {
// Check whether we've asked to exclude this interface:
if (interf == exceptInterface)
continue;
// Check that the packet's source address makes it OK to
// be relayed across this interface:
UsageEnvironment& saveEnv = env();
// because the following call may delete "this"
if (!interf->SourceAddrOKForRelaying(saveEnv, sourceAddr)) {
if (strcmp(saveEnv.getResultMsg(), "") != 0) {
// Treat this as a fatal error
return -1;
} else {
continue;
}
}
if (numMembers == 0) {
// We know that we're going to forward to at least one
// member, so fill in the tunnel encapsulation trailer.
// (Note: Allow for it not being 4-byte-aligned.)
TunnelEncapsulationTrailer* trailerInPacket
= (TunnelEncapsulationTrailer*)&data[size];
TunnelEncapsulationTrailer* trailer;
Boolean misaligned = ((uintptr_t)trailerInPacket & 3) != 0;
unsigned trailerOffset;
u_int8_t tunnelCmd;
if (isSSM()) {
// add an 'auxilliary address' before the trailer
trailerOffset = TunnelEncapsulationTrailerAuxSize;
tunnelCmd = TunnelDataAuxCmd;
} else {
trailerOffset = 0;
tunnelCmd = TunnelDataCmd;
}
unsigned trailerSize = TunnelEncapsulationTrailerSize + trailerOffset;
unsigned tmpTr[TunnelEncapsulationTrailerMaxSize];
if (misaligned) {
trailer = (TunnelEncapsulationTrailer*)&tmpTr;
} else {
trailer = trailerInPacket;
}
trailer += trailerOffset;
if (fDests != NULL) {
trailer->address() = fDests->fGroupEId.groupAddress().s_addr;
trailer->port() = fDests->fPort; // structure copy, outputs in network order
}
trailer->ttl() = ttlToFwd;
trailer->command() = tunnelCmd;
if (isSSM()) {
trailer->auxAddress() = sourceFilterAddress().s_addr;
}
if (misaligned) {
memmove(trailerInPacket, trailer-trailerOffset, trailerSize);
}
size += trailerSize;
}
interf->write(data, size);
++numMembers;
}
return numMembers;
}
UsageEnvironment& operator<<(UsageEnvironment& s, const Groupsock& g) {
UsageEnvironment& s1 = s << timestampString() << " Groupsock("
<< g.socketNum() << ": "
<< AddressString(g.groupAddress()).val()
<< ", " << g.port() << ", ";
if (g.isSSM()) {
return s1 << "SSM source: "
<< AddressString(g.sourceFilterAddress()).val() << ")";
} else {
return s1 << (unsigned)(g.ttl()) << ")";
}
}
////////// GroupsockLookupTable //////////
// A hash table used to index Groupsocks by socket number.
static HashTable*& getSocketTable(UsageEnvironment& env) {
_groupsockPriv* priv = groupsockPriv(env);
if (priv->socketTable == NULL) { // We need to create it
priv->socketTable = HashTable::create(ONE_WORD_HASH_KEYS);
}
return priv->socketTable;
}
static Boolean unsetGroupsockBySocket(Groupsock const* groupsock) {
do {
if (groupsock == NULL) break;
int sock = groupsock->socketNum();
// Make sure "sock" is in bounds:
if (sock < 0) break;
HashTable*& sockets = getSocketTable(groupsock->env());
Groupsock* gs = (Groupsock*)sockets->Lookup((char*)(long)sock);
if (gs == NULL || gs != groupsock) break;
sockets->Remove((char*)(long)sock);
if (sockets->IsEmpty()) {
// We can also delete the table (to reclaim space):
delete sockets; sockets = NULL;
reclaimGroupsockPriv(gs->env());
}
return True;
} while (0);
return False;
}
static Boolean setGroupsockBySocket(UsageEnvironment& env, int sock,
Groupsock* groupsock) {
do {
// Make sure the "sock" parameter is in bounds:
if (sock < 0) {
char buf[100];
sprintf(buf, "trying to use bad socket (%d)", sock);
env.setResultMsg(buf);
break;
}
HashTable* sockets = getSocketTable(env);
// Make sure we're not replacing an existing Groupsock (although that shouldn't happen)
Boolean alreadyExists
= (sockets->Lookup((char*)(long)sock) != 0);
if (alreadyExists) {
char buf[100];
sprintf(buf,
"Attempting to replace an existing socket (%d",
sock);
env.setResultMsg(buf);
break;
}
sockets->Add((char*)(long)sock, groupsock);
return True;
} while (0);
return False;
}
static Groupsock* getGroupsockBySocket(UsageEnvironment& env, int sock) {
do {
// Make sure the "sock" parameter is in bounds:
if (sock < 0) break;
HashTable* sockets = getSocketTable(env);
return (Groupsock*)sockets->Lookup((char*)(long)sock);
} while (0);
return NULL;
}
Groupsock*
GroupsockLookupTable::Fetch(UsageEnvironment& env,
netAddressBits groupAddress,
Port port, u_int8_t ttl,
Boolean& isNew) {
isNew = False;
Groupsock* groupsock;
do {
groupsock = (Groupsock*) fTable.Lookup(groupAddress, (~0), port);
if (groupsock == NULL) { // we need to create one:
groupsock = AddNew(env, groupAddress, (~0), port, ttl);
if (groupsock == NULL) break;
isNew = True;
}
} while (0);
return groupsock;
}
Groupsock*
GroupsockLookupTable::Fetch(UsageEnvironment& env,
netAddressBits groupAddress,
netAddressBits sourceFilterAddr, Port port,
Boolean& isNew) {
isNew = False;
Groupsock* groupsock;
do {
groupsock
= (Groupsock*) fTable.Lookup(groupAddress, sourceFilterAddr, port);
if (groupsock == NULL) { // we need to create one:
groupsock = AddNew(env, groupAddress, sourceFilterAddr, port, 0);
if (groupsock == NULL) break;
isNew = True;
}
} while (0);
return groupsock;
}
Groupsock*
GroupsockLookupTable::Lookup(netAddressBits groupAddress, Port port) {
return (Groupsock*) fTable.Lookup(groupAddress, (~0), port);
}
Groupsock*
GroupsockLookupTable::Lookup(netAddressBits groupAddress,
netAddressBits sourceFilterAddr, Port port) {
return (Groupsock*) fTable.Lookup(groupAddress, sourceFilterAddr, port);
}
Groupsock* GroupsockLookupTable::Lookup(UsageEnvironment& env, int sock) {
return getGroupsockBySocket(env, sock);
}
Boolean GroupsockLookupTable::Remove(Groupsock const* groupsock) {
unsetGroupsockBySocket(groupsock);
return fTable.Remove(groupsock->groupAddress().s_addr,
groupsock->sourceFilterAddress().s_addr,
groupsock->port());
}
Groupsock* GroupsockLookupTable::AddNew(UsageEnvironment& env,
netAddressBits groupAddress,
netAddressBits sourceFilterAddress,
Port port, u_int8_t ttl) {
Groupsock* groupsock;
do {
struct in_addr groupAddr; groupAddr.s_addr = groupAddress;
if (sourceFilterAddress == netAddressBits(~0)) {
// regular, ISM groupsock
groupsock = new Groupsock(env, groupAddr, port, ttl);
} else {
// SSM groupsock
struct in_addr sourceFilterAddr;
sourceFilterAddr.s_addr = sourceFilterAddress;
groupsock = new Groupsock(env, groupAddr, sourceFilterAddr, port);
}
if (groupsock == NULL || groupsock->socketNum() < 0) break;
if (!setGroupsockBySocket(env, groupsock->socketNum(), groupsock)) break;
fTable.Add(groupAddress, sourceFilterAddress, port, (void*)groupsock);
} while (0);
return groupsock;
}
GroupsockLookupTable::Iterator::Iterator(GroupsockLookupTable& groupsocks)
: fIter(AddressPortLookupTable::Iterator(groupsocks.fTable)) {
}
Groupsock* GroupsockLookupTable::Iterator::next() {
return (Groupsock*) fIter.next();
};
|