1 // Copyright 2014 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #include "remoting/test/fake_network_dispatcher.h" 6 7 #include "base/bind.h" 8 #include "base/location.h" 9 #include "base/single_thread_task_runner.h" 10 #include "net/base/io_buffer.h" 11 12 namespace remoting { 13 14 FakeNetworkDispatcher::FakeNetworkDispatcher() 15 : allocated_address_(0) { 16 } 17 18 FakeNetworkDispatcher::~FakeNetworkDispatcher() { 19 CHECK(nodes_.empty()); 20 } 21 22 rtc::IPAddress FakeNetworkDispatcher::AllocateAddress() { 23 in6_addr addr; 24 memset(&addr, 0, sizeof(addr)); 25 26 // fc00::/7 is reserved for unique local addresses. 27 addr.s6_addr[0] = 0xfc; 28 29 // Copy |allocated_address_| to the end of |addr|. 30 ++allocated_address_; 31 for (size_t i = 0; i < sizeof(allocated_address_); ++i) { 32 addr.s6_addr[15 - i] = (allocated_address_ >> (8 * i)) & 0xff; 33 } 34 35 return rtc::IPAddress(addr); 36 } 37 38 void FakeNetworkDispatcher::AddNode(Node* node) { 39 DCHECK(node->GetThread()->BelongsToCurrentThread()); 40 41 base::AutoLock auto_lock(nodes_lock_); 42 DCHECK(nodes_.find(node->GetAddress()) == nodes_.end()); 43 nodes_[node->GetAddress()] = node; 44 } 45 46 void FakeNetworkDispatcher::RemoveNode(Node* node) { 47 DCHECK(node->GetThread()->BelongsToCurrentThread()); 48 49 base::AutoLock auto_lock(nodes_lock_); 50 DCHECK(nodes_[node->GetAddress()] == node); 51 nodes_.erase(node->GetAddress()); 52 } 53 54 void FakeNetworkDispatcher::DeliverPacket( 55 const rtc::SocketAddress& from, 56 const rtc::SocketAddress& to, 57 const scoped_refptr<net::IOBuffer>& data, 58 int data_size) { 59 Node* node; 60 { 61 base::AutoLock auto_lock(nodes_lock_); 62 63 NodesMap::iterator node_it = nodes_.find(to.ipaddr()); 64 if (node_it == nodes_.end()) { 65 LOG(ERROR) << "Tried to deliver packet to unknown target: " 66 << to.ToString(); 67 return; 68 } 69 70 node = node_it->second; 71 72 // Check if |node| belongs to a different thread and post a task in that 73 // case. 74 scoped_refptr<base::SingleThreadTaskRunner> task_runner = node->GetThread(); 75 if (!task_runner->BelongsToCurrentThread()) { 76 task_runner->PostTask(FROM_HERE, 77 base::Bind(&FakeNetworkDispatcher::DeliverPacket, 78 this, from, to, data, data_size)); 79 return; 80 } 81 } 82 83 // Call ReceivePacket() without lock held. It's safe because at this point we 84 // know that |node| belongs to the current thread. 85 node->ReceivePacket(from, to, data, data_size); 86 } 87 88 } // namespace remoting 89