ethertap.cc (12559:55550caed7f0) ethertap.cc (12632:a00c27d2256b)
1/*
2 * Copyright (c) 2003-2005 The Regents of The University of Michigan
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
7 * met: redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer;
9 * redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution;
12 * neither the name of the copyright holders nor the names of its
13 * contributors may be used to endorse or promote products derived from
14 * this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 *
28 * Authors: Nathan Binkert
29 */
30
31/* @file
32 * Interface to connect a simulated ethernet device to the real world
33 */
34
35#include "dev/net/ethertap.hh"
36
37#if defined(__OpenBSD__) || defined(__APPLE__)
38#include <sys/param.h>
39
40#endif
41
42#if USE_TUNTAP && defined(__linux__)
43#if 1 // Hide from the style checker since these have to be out of order.
44#include <sys/socket.h> // Has to be included before if.h for some reason.
45
46#endif
47
48#include <linux/if.h>
49#include <linux/if_tun.h>
50
51#endif
52
53#include <fcntl.h>
54#include <netinet/in.h>
55#include <sys/ioctl.h>
56#include <unistd.h>
57
58#include <cstring>
59#include <deque>
60#include <string>
61
62#include "base/logging.hh"
63#include "base/pollevent.hh"
64#include "base/socket.hh"
65#include "base/trace.hh"
66#include "debug/Ethernet.hh"
67#include "debug/EthernetData.hh"
68#include "dev/net/etherdump.hh"
69#include "dev/net/etherint.hh"
70#include "dev/net/etherpkt.hh"
71
72using namespace std;
73
74class TapEvent : public PollEvent
75{
76 protected:
77 EtherTapBase *tap;
78
79 public:
80 TapEvent(EtherTapBase *_tap, int fd, int e)
81 : PollEvent(fd, e), tap(_tap) {}
1/*
2 * Copyright (c) 2003-2005 The Regents of The University of Michigan
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
7 * met: redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer;
9 * redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution;
12 * neither the name of the copyright holders nor the names of its
13 * contributors may be used to endorse or promote products derived from
14 * this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 *
28 * Authors: Nathan Binkert
29 */
30
31/* @file
32 * Interface to connect a simulated ethernet device to the real world
33 */
34
35#include "dev/net/ethertap.hh"
36
37#if defined(__OpenBSD__) || defined(__APPLE__)
38#include <sys/param.h>
39
40#endif
41
42#if USE_TUNTAP && defined(__linux__)
43#if 1 // Hide from the style checker since these have to be out of order.
44#include <sys/socket.h> // Has to be included before if.h for some reason.
45
46#endif
47
48#include <linux/if.h>
49#include <linux/if_tun.h>
50
51#endif
52
53#include <fcntl.h>
54#include <netinet/in.h>
55#include <sys/ioctl.h>
56#include <unistd.h>
57
58#include <cstring>
59#include <deque>
60#include <string>
61
62#include "base/logging.hh"
63#include "base/pollevent.hh"
64#include "base/socket.hh"
65#include "base/trace.hh"
66#include "debug/Ethernet.hh"
67#include "debug/EthernetData.hh"
68#include "dev/net/etherdump.hh"
69#include "dev/net/etherint.hh"
70#include "dev/net/etherpkt.hh"
71
72using namespace std;
73
74class TapEvent : public PollEvent
75{
76 protected:
77 EtherTapBase *tap;
78
79 public:
80 TapEvent(EtherTapBase *_tap, int fd, int e)
81 : PollEvent(fd, e), tap(_tap) {}
82 virtual void process(int revent) { tap->recvReal(revent); }
82
83 void
84 process(int revent) override
85 {
86 // Ensure that our event queue is active. It may not be since we get
87 // here from the PollQueue whenever a real packet happens to arrive.
88 EventQueue::ScopedMigration migrate(tap->eventQueue());
89
90 tap->recvReal(revent);
91 }
83};
84
85EtherTapBase::EtherTapBase(const Params *p)
86 : EtherObject(p), buflen(p->bufsz), dump(p->dump), event(NULL),
87 interface(NULL),
88 txEvent([this]{ retransmit(); }, "EtherTapBase retransmit")
89{
90 buffer = new uint8_t[buflen];
91 interface = new EtherTapInt(name() + ".interface", this);
92}
93
94EtherTapBase::~EtherTapBase()
95{
96 delete buffer;
97 delete event;
98 delete interface;
99}
100
101void
102EtherTapBase::serialize(CheckpointOut &cp) const
103{
104 SERIALIZE_SCALAR(buflen);
105 uint8_t *buffer = (uint8_t *)this->buffer;
106 SERIALIZE_ARRAY(buffer, buflen);
107
108 bool tapevent_present = false;
109 if (event) {
110 tapevent_present = true;
111 SERIALIZE_SCALAR(tapevent_present);
112 event->serialize(cp);
113 } else {
114 SERIALIZE_SCALAR(tapevent_present);
115 }
116}
117
118void
119EtherTapBase::unserialize(CheckpointIn &cp)
120{
121 UNSERIALIZE_SCALAR(buflen);
122 uint8_t *buffer = (uint8_t *)this->buffer;
123 UNSERIALIZE_ARRAY(buffer, buflen);
124
125 bool tapevent_present;
126 UNSERIALIZE_SCALAR(tapevent_present);
127 if (tapevent_present) {
128 event = new TapEvent(this, 0, 0);
129 event->unserialize(cp);
130 if (event->queued())
131 pollQueue.schedule(event);
132 }
133}
134
135
136void
137EtherTapBase::pollFd(int fd)
138{
139 assert(!event);
140 event = new TapEvent(this, fd, POLLIN|POLLERR);
141 pollQueue.schedule(event);
142}
143
144void
145EtherTapBase::stopPolling()
146{
147 assert(event);
148 delete event;
149 event = NULL;
150}
151
152
153EtherInt*
154EtherTapBase::getEthPort(const std::string &if_name, int idx)
155{
156 if (if_name == "tap") {
157 if (interface->getPeer())
158 panic("Interface already connected to\n");
159 return interface;
160 }
161 return NULL;
162}
163
164bool
165EtherTapBase::recvSimulated(EthPacketPtr packet)
166{
167 if (dump)
168 dump->dump(packet);
169
170 DPRINTF(Ethernet, "EtherTap sim->real len=%d\n", packet->length);
171 DDUMP(EthernetData, packet->data, packet->length);
172
173 bool success = sendReal(packet->data, packet->length);
174
175 interface->recvDone();
176
177 return success;
178}
179
180void
181EtherTapBase::sendSimulated(void *data, size_t len)
182{
183 EthPacketPtr packet;
184 packet = make_shared<EthPacketData>(len);
185 packet->length = len;
186 packet->simLength = len;
187 memcpy(packet->data, data, len);
188
189 DPRINTF(Ethernet, "EtherTap real->sim len=%d\n", packet->length);
190 DDUMP(EthernetData, packet->data, packet->length);
191 if (!packetBuffer.empty() || !interface->sendPacket(packet)) {
192 DPRINTF(Ethernet, "bus busy...buffer for retransmission\n");
193 packetBuffer.push(packet);
194 if (!txEvent.scheduled())
195 schedule(txEvent, curTick() + retryTime);
196 } else if (dump) {
197 dump->dump(packet);
198 }
199}
200
201void
202EtherTapBase::retransmit()
203{
204 if (packetBuffer.empty())
205 return;
206
207 EthPacketPtr packet = packetBuffer.front();
208 if (interface->sendPacket(packet)) {
209 if (dump)
210 dump->dump(packet);
211 DPRINTF(Ethernet, "EtherTap retransmit\n");
212 packetBuffer.front() = NULL;
213 packetBuffer.pop();
214 }
215
216 if (!packetBuffer.empty() && !txEvent.scheduled())
217 schedule(txEvent, curTick() + retryTime);
218}
219
220
221class TapListener
222{
223 protected:
224 class Event : public PollEvent
225 {
226 protected:
227 TapListener *listener;
228
229 public:
230 Event(TapListener *l, int fd, int e) : PollEvent(fd, e), listener(l) {}
231
232 void process(int revent) override { listener->accept(); }
233 };
234
235 friend class Event;
236 Event *event;
237
238 void accept();
239
240 protected:
241 ListenSocket listener;
242 EtherTapStub *tap;
243 int port;
244
245 public:
246 TapListener(EtherTapStub *t, int p) : event(NULL), tap(t), port(p) {}
247 ~TapListener() { delete event; }
248
249 void listen();
250};
251
252void
253TapListener::listen()
254{
255 while (!listener.listen(port, true)) {
256 DPRINTF(Ethernet, "TapListener(listen): Can't bind port %d\n", port);
257 port++;
258 }
259
260 ccprintf(cerr, "Listening for tap connection on port %d\n", port);
261 event = new Event(this, listener.getfd(), POLLIN|POLLERR);
262 pollQueue.schedule(event);
263}
264
265void
266TapListener::accept()
267{
268 // As a consequence of being called from the PollQueue, we might
269 // have been called from a different thread. Migrate to "our"
270 // thread.
271 EventQueue::ScopedMigration migrate(tap->eventQueue());
272
273 if (!listener.islistening())
274 panic("TapListener(accept): cannot accept if we're not listening!");
275
276 int sfd = listener.accept(true);
277 if (sfd != -1)
278 tap->attach(sfd);
279}
280
281
282EtherTapStub::EtherTapStub(const Params *p) : EtherTapBase(p), socket(-1)
283{
284 if (ListenSocket::allDisabled())
285 fatal("All listeners are disabled! EtherTapStub can't work!");
286
287 listener = new TapListener(this, p->port);
288 listener->listen();
289}
290
291EtherTapStub::~EtherTapStub()
292{
293 delete listener;
294}
295
296void
297EtherTapStub::serialize(CheckpointOut &cp) const
298{
299 EtherTapBase::serialize(cp);
300
301 SERIALIZE_SCALAR(socket);
302 SERIALIZE_SCALAR(buffer_used);
303 SERIALIZE_SCALAR(frame_len);
304}
305
306void
307EtherTapStub::unserialize(CheckpointIn &cp)
308{
309 EtherTapBase::unserialize(cp);
310
311 UNSERIALIZE_SCALAR(socket);
312 UNSERIALIZE_SCALAR(buffer_used);
313 UNSERIALIZE_SCALAR(frame_len);
314}
315
316
317void
318EtherTapStub::attach(int fd)
319{
320 if (socket != -1)
321 close(fd);
322
323 buffer_used = 0;
324 frame_len = 0;
325 socket = fd;
326 DPRINTF(Ethernet, "EtherTapStub attached\n");
327 pollFd(socket);
328}
329
330void
331EtherTapStub::detach()
332{
333 DPRINTF(Ethernet, "EtherTapStub detached\n");
334 stopPolling();
335 close(socket);
336 socket = -1;
337}
338
339void
340EtherTapStub::recvReal(int revent)
341{
342 if (revent & POLLERR) {
343 detach();
344 return;
345 }
346
347 if (!(revent & POLLIN))
348 return;
349
350 // Read in as much of the new data as we can.
351 int len = read(socket, buffer + buffer_used, buflen - buffer_used);
352 if (len == 0) {
353 detach();
354 return;
355 }
356 buffer_used += len;
357
358 // If there's not enough data for the frame length, wait for more.
359 if (buffer_used < sizeof(uint32_t))
360 return;
361
362 if (frame_len == 0)
363 frame_len = ntohl(*(uint32_t *)buffer);
364
365 DPRINTF(Ethernet, "Received data from peer: len=%d buffer_used=%d "
366 "frame_len=%d\n", len, buffer_used, frame_len);
367
368 uint8_t *frame_start = &buffer[sizeof(uint32_t)];
369 while (frame_len != 0 && buffer_used >= frame_len + sizeof(uint32_t)) {
370 sendSimulated(frame_start, frame_len);
371
372 // Bookkeeping.
373 buffer_used -= frame_len + sizeof(uint32_t);
374 if (buffer_used > 0) {
375 // If there's still any data left, move it into position.
376 memmove(buffer, frame_start + frame_len, buffer_used);
377 }
378 frame_len = 0;
379
380 if (buffer_used >= sizeof(uint32_t))
381 frame_len = ntohl(*(uint32_t *)buffer);
382 }
383}
384
385bool
386EtherTapStub::sendReal(const void *data, size_t len)
387{
388 uint32_t frame_len = htonl(len);
389 ssize_t ret = write(socket, &frame_len, sizeof(frame_len));
390 if (ret != sizeof(frame_len))
391 return false;
392 return write(socket, data, len) == len;
393}
394
395
396#if USE_TUNTAP
397
398EtherTap::EtherTap(const Params *p) : EtherTapBase(p)
399{
400 int fd = open(p->tun_clone_device.c_str(), O_RDWR);
401 if (fd < 0)
402 panic("Couldn't open %s.\n", p->tun_clone_device);
403
404 struct ifreq ifr;
405 memset(&ifr, 0, sizeof(ifr));
406 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
407 strncpy(ifr.ifr_name, p->tap_device_name.c_str(), IFNAMSIZ - 1);
408
409 if (ioctl(fd, TUNSETIFF, (void *)&ifr) < 0)
410 panic("Failed to access tap device %s.\n", ifr.ifr_name);
411 // fd now refers to the tap device.
412 tap = fd;
413 pollFd(tap);
414}
415
416EtherTap::~EtherTap()
417{
418 stopPolling();
419 close(tap);
420 tap = -1;
421}
422
423void
424EtherTap::recvReal(int revent)
425{
426 if (revent & POLLERR)
427 panic("Error polling for tap data.\n");
428
429 if (!(revent & POLLIN))
430 return;
431
432 ssize_t ret = read(tap, buffer, buflen);
433 if (ret < 0)
434 panic("Failed to read from tap device.\n");
435
436 sendSimulated(buffer, ret);
437}
438
439bool
440EtherTap::sendReal(const void *data, size_t len)
441{
442 if (write(tap, data, len) != len)
443 panic("Failed to write data to tap device.\n");
444 return true;
445}
446
447EtherTap *
448EtherTapParams::create()
449{
450 return new EtherTap(this);
451}
452
453#endif
454
455EtherTapStub *
456EtherTapStubParams::create()
457{
458 return new EtherTapStub(this);
459}
92};
93
94EtherTapBase::EtherTapBase(const Params *p)
95 : EtherObject(p), buflen(p->bufsz), dump(p->dump), event(NULL),
96 interface(NULL),
97 txEvent([this]{ retransmit(); }, "EtherTapBase retransmit")
98{
99 buffer = new uint8_t[buflen];
100 interface = new EtherTapInt(name() + ".interface", this);
101}
102
103EtherTapBase::~EtherTapBase()
104{
105 delete buffer;
106 delete event;
107 delete interface;
108}
109
110void
111EtherTapBase::serialize(CheckpointOut &cp) const
112{
113 SERIALIZE_SCALAR(buflen);
114 uint8_t *buffer = (uint8_t *)this->buffer;
115 SERIALIZE_ARRAY(buffer, buflen);
116
117 bool tapevent_present = false;
118 if (event) {
119 tapevent_present = true;
120 SERIALIZE_SCALAR(tapevent_present);
121 event->serialize(cp);
122 } else {
123 SERIALIZE_SCALAR(tapevent_present);
124 }
125}
126
127void
128EtherTapBase::unserialize(CheckpointIn &cp)
129{
130 UNSERIALIZE_SCALAR(buflen);
131 uint8_t *buffer = (uint8_t *)this->buffer;
132 UNSERIALIZE_ARRAY(buffer, buflen);
133
134 bool tapevent_present;
135 UNSERIALIZE_SCALAR(tapevent_present);
136 if (tapevent_present) {
137 event = new TapEvent(this, 0, 0);
138 event->unserialize(cp);
139 if (event->queued())
140 pollQueue.schedule(event);
141 }
142}
143
144
145void
146EtherTapBase::pollFd(int fd)
147{
148 assert(!event);
149 event = new TapEvent(this, fd, POLLIN|POLLERR);
150 pollQueue.schedule(event);
151}
152
153void
154EtherTapBase::stopPolling()
155{
156 assert(event);
157 delete event;
158 event = NULL;
159}
160
161
162EtherInt*
163EtherTapBase::getEthPort(const std::string &if_name, int idx)
164{
165 if (if_name == "tap") {
166 if (interface->getPeer())
167 panic("Interface already connected to\n");
168 return interface;
169 }
170 return NULL;
171}
172
173bool
174EtherTapBase::recvSimulated(EthPacketPtr packet)
175{
176 if (dump)
177 dump->dump(packet);
178
179 DPRINTF(Ethernet, "EtherTap sim->real len=%d\n", packet->length);
180 DDUMP(EthernetData, packet->data, packet->length);
181
182 bool success = sendReal(packet->data, packet->length);
183
184 interface->recvDone();
185
186 return success;
187}
188
189void
190EtherTapBase::sendSimulated(void *data, size_t len)
191{
192 EthPacketPtr packet;
193 packet = make_shared<EthPacketData>(len);
194 packet->length = len;
195 packet->simLength = len;
196 memcpy(packet->data, data, len);
197
198 DPRINTF(Ethernet, "EtherTap real->sim len=%d\n", packet->length);
199 DDUMP(EthernetData, packet->data, packet->length);
200 if (!packetBuffer.empty() || !interface->sendPacket(packet)) {
201 DPRINTF(Ethernet, "bus busy...buffer for retransmission\n");
202 packetBuffer.push(packet);
203 if (!txEvent.scheduled())
204 schedule(txEvent, curTick() + retryTime);
205 } else if (dump) {
206 dump->dump(packet);
207 }
208}
209
210void
211EtherTapBase::retransmit()
212{
213 if (packetBuffer.empty())
214 return;
215
216 EthPacketPtr packet = packetBuffer.front();
217 if (interface->sendPacket(packet)) {
218 if (dump)
219 dump->dump(packet);
220 DPRINTF(Ethernet, "EtherTap retransmit\n");
221 packetBuffer.front() = NULL;
222 packetBuffer.pop();
223 }
224
225 if (!packetBuffer.empty() && !txEvent.scheduled())
226 schedule(txEvent, curTick() + retryTime);
227}
228
229
230class TapListener
231{
232 protected:
233 class Event : public PollEvent
234 {
235 protected:
236 TapListener *listener;
237
238 public:
239 Event(TapListener *l, int fd, int e) : PollEvent(fd, e), listener(l) {}
240
241 void process(int revent) override { listener->accept(); }
242 };
243
244 friend class Event;
245 Event *event;
246
247 void accept();
248
249 protected:
250 ListenSocket listener;
251 EtherTapStub *tap;
252 int port;
253
254 public:
255 TapListener(EtherTapStub *t, int p) : event(NULL), tap(t), port(p) {}
256 ~TapListener() { delete event; }
257
258 void listen();
259};
260
261void
262TapListener::listen()
263{
264 while (!listener.listen(port, true)) {
265 DPRINTF(Ethernet, "TapListener(listen): Can't bind port %d\n", port);
266 port++;
267 }
268
269 ccprintf(cerr, "Listening for tap connection on port %d\n", port);
270 event = new Event(this, listener.getfd(), POLLIN|POLLERR);
271 pollQueue.schedule(event);
272}
273
274void
275TapListener::accept()
276{
277 // As a consequence of being called from the PollQueue, we might
278 // have been called from a different thread. Migrate to "our"
279 // thread.
280 EventQueue::ScopedMigration migrate(tap->eventQueue());
281
282 if (!listener.islistening())
283 panic("TapListener(accept): cannot accept if we're not listening!");
284
285 int sfd = listener.accept(true);
286 if (sfd != -1)
287 tap->attach(sfd);
288}
289
290
291EtherTapStub::EtherTapStub(const Params *p) : EtherTapBase(p), socket(-1)
292{
293 if (ListenSocket::allDisabled())
294 fatal("All listeners are disabled! EtherTapStub can't work!");
295
296 listener = new TapListener(this, p->port);
297 listener->listen();
298}
299
300EtherTapStub::~EtherTapStub()
301{
302 delete listener;
303}
304
305void
306EtherTapStub::serialize(CheckpointOut &cp) const
307{
308 EtherTapBase::serialize(cp);
309
310 SERIALIZE_SCALAR(socket);
311 SERIALIZE_SCALAR(buffer_used);
312 SERIALIZE_SCALAR(frame_len);
313}
314
315void
316EtherTapStub::unserialize(CheckpointIn &cp)
317{
318 EtherTapBase::unserialize(cp);
319
320 UNSERIALIZE_SCALAR(socket);
321 UNSERIALIZE_SCALAR(buffer_used);
322 UNSERIALIZE_SCALAR(frame_len);
323}
324
325
326void
327EtherTapStub::attach(int fd)
328{
329 if (socket != -1)
330 close(fd);
331
332 buffer_used = 0;
333 frame_len = 0;
334 socket = fd;
335 DPRINTF(Ethernet, "EtherTapStub attached\n");
336 pollFd(socket);
337}
338
339void
340EtherTapStub::detach()
341{
342 DPRINTF(Ethernet, "EtherTapStub detached\n");
343 stopPolling();
344 close(socket);
345 socket = -1;
346}
347
348void
349EtherTapStub::recvReal(int revent)
350{
351 if (revent & POLLERR) {
352 detach();
353 return;
354 }
355
356 if (!(revent & POLLIN))
357 return;
358
359 // Read in as much of the new data as we can.
360 int len = read(socket, buffer + buffer_used, buflen - buffer_used);
361 if (len == 0) {
362 detach();
363 return;
364 }
365 buffer_used += len;
366
367 // If there's not enough data for the frame length, wait for more.
368 if (buffer_used < sizeof(uint32_t))
369 return;
370
371 if (frame_len == 0)
372 frame_len = ntohl(*(uint32_t *)buffer);
373
374 DPRINTF(Ethernet, "Received data from peer: len=%d buffer_used=%d "
375 "frame_len=%d\n", len, buffer_used, frame_len);
376
377 uint8_t *frame_start = &buffer[sizeof(uint32_t)];
378 while (frame_len != 0 && buffer_used >= frame_len + sizeof(uint32_t)) {
379 sendSimulated(frame_start, frame_len);
380
381 // Bookkeeping.
382 buffer_used -= frame_len + sizeof(uint32_t);
383 if (buffer_used > 0) {
384 // If there's still any data left, move it into position.
385 memmove(buffer, frame_start + frame_len, buffer_used);
386 }
387 frame_len = 0;
388
389 if (buffer_used >= sizeof(uint32_t))
390 frame_len = ntohl(*(uint32_t *)buffer);
391 }
392}
393
394bool
395EtherTapStub::sendReal(const void *data, size_t len)
396{
397 uint32_t frame_len = htonl(len);
398 ssize_t ret = write(socket, &frame_len, sizeof(frame_len));
399 if (ret != sizeof(frame_len))
400 return false;
401 return write(socket, data, len) == len;
402}
403
404
405#if USE_TUNTAP
406
407EtherTap::EtherTap(const Params *p) : EtherTapBase(p)
408{
409 int fd = open(p->tun_clone_device.c_str(), O_RDWR);
410 if (fd < 0)
411 panic("Couldn't open %s.\n", p->tun_clone_device);
412
413 struct ifreq ifr;
414 memset(&ifr, 0, sizeof(ifr));
415 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
416 strncpy(ifr.ifr_name, p->tap_device_name.c_str(), IFNAMSIZ - 1);
417
418 if (ioctl(fd, TUNSETIFF, (void *)&ifr) < 0)
419 panic("Failed to access tap device %s.\n", ifr.ifr_name);
420 // fd now refers to the tap device.
421 tap = fd;
422 pollFd(tap);
423}
424
425EtherTap::~EtherTap()
426{
427 stopPolling();
428 close(tap);
429 tap = -1;
430}
431
432void
433EtherTap::recvReal(int revent)
434{
435 if (revent & POLLERR)
436 panic("Error polling for tap data.\n");
437
438 if (!(revent & POLLIN))
439 return;
440
441 ssize_t ret = read(tap, buffer, buflen);
442 if (ret < 0)
443 panic("Failed to read from tap device.\n");
444
445 sendSimulated(buffer, ret);
446}
447
448bool
449EtherTap::sendReal(const void *data, size_t len)
450{
451 if (write(tap, data, len) != len)
452 panic("Failed to write data to tap device.\n");
453 return true;
454}
455
456EtherTap *
457EtherTapParams::create()
458{
459 return new EtherTap(this);
460}
461
462#endif
463
464EtherTapStub *
465EtherTapStubParams::create()
466{
467 return new EtherTapStub(this);
468}