1 /* Copyright (c) 2016 Google Inc
2 * Barret Rhoden <brho@cs.berkeley.edu>
3 * See LICENSE for details.
5 * Network address translation for VM guests.
7 * There are two styles of addressing: qemu and real-addr. qemu-style is what
8 * you expect from Qemu's user-mode networking. real-addr mode uses the same
9 * addresses for the guest as the host uses.
11 * For qemu-style networking:
12 * guest = 10.0.2.15, mask = 255.255.255.0, router = 10.0.2.2.
13 * For real-addr networking:
14 * guest = host_v4, mask = host_mask, router = host's_route
16 * Real-addr mode is useful for guests that statically config their address from
17 * the nodes hard drive. It might also help for apps that want to advertise
18 * their IP address to external users (though that would require straight-thru
19 * port-fowardarding set up by the VMM).
21 * As far as the guest is concerned, the host is the guest_v4_router. If we
22 * ever get a remote IP addr of 'router', that'll be redirected to the host's
23 * loopback IP. That means the guest can't reach the "real" router (in
24 * real-addr mode). The host can reach the guest via 127.0.0.1. In either
25 * case, use the host's side of a mapping.
28 * - We're working with the IOVs that the guest gave us through virtio. If we
29 * care, that whole thing is susceptible to time-of-check attacks. The guest
30 * could be modifying the IOV that we're working on, so we need to not care
31 * too much about that.
33 * - Consider having the kernel proto bypass outbound path overwrite the src
34 * address and the proto port. We don't care about the proto payload. We
35 * might care about IP and proto headers. o/w, the user could fake traffic
36 * for other ports - basically they can craft whatever packet they want (which
37 * is what they had previously with unrestricted access to devether).
39 * - Consider injecting packets to the guest from #srv/snoop-PID.
44 * - Why are we using FD taps, instead of threads, to watch all the host FD?
45 * Couldn't we block a uthread on each FD? I went back and forth on this.
46 * The final reason for this is to avoid copies and weird joins. The
47 * concurrency with the guest is based on the number of IOVs they give us -
48 * not the number of host conversations open. We could listen on 1000 convs,
49 * each with their own read buffer, but we'd then have to copy the entire
50 * packet into the IOVs the guest gave us. We'd also need to synchronize on
51 * access to virtio and do some structural work (draw out how the packets
52 * would move around). It'd be different if each uthread could just push
53 * packets into virtio-net (push vs the current pull model).
55 * - What's the deal with sending packets to broadcast domain targets? Short
56 * answer: the host responds to every ARP request, regardless of the IP. If
57 * the networking is done QEMU style, there's only one other host: the router,
58 * so that's not interesting. If we are in real-addr mode and the guest is
59 * trying to reach someone in our broadcast, they'll be told that we
60 * (host_eth_addr) is the MAC for that addr. Then the guest sends us an IP
61 * packet for that target. Akaros will see an IP packet and will route it to
62 * its own broadcast (on the real network). The guest's ARP only matters when
63 * it comes to getting the packet to us, not the actual network's broadcast
66 * - Why is the RX path single threaded? So it's possible to rewrite
67 * __poll_inbound() such that readv() is not called while holding the rx_mtx.
68 * To do so, we pop the first item off the inbound_todo list (so we have the
69 * ref), do the read, then put it back on the list if it hasn't been drained
70 * to empty. The main issue, apart from being more complicated, is that since
71 * we're unlocking and relocking, any invariant that we had before calling
72 * __poll_inbound needs to be rechecked. Specifically, we would need to check
73 * __poll_injection *after* returning from __poll_inbound. Otherwise we could
74 * sleep with a packet waiting to be injected. Whoops! That could have been
75 * dealt with, but it's subtle. There also might be races with FD taps
76 * firing, the fdtap_watcher not putting items on the list, and the thread
77 * then not putting it on the list. Specifically:
78 * fdtap_watcher: __poll_inbound:
79 * -------------------------------------------------------
81 * map tracked as "on inbound"
83 * readv, get -1 EAGAIN
84 * decide to drop the item
89 * see map is "on inbound"
94 * unlock + sleep on CV
95 * The FD has data, but we lost the event, and we'll never read it.
97 * - Why is the fdtap_watcher its own thread? You can't kick a CV from vcore
98 * context, since you almost always want to hold the MTX while kicking the CV
99 * (see the lengthy comments in the CV code). It's easier to blockon an event
100 * queue as a uthread. But since the RX thread wants to sleep on two sources,
101 * it's simpler this way. It also decouples the inbound_todo list from the
104 * - Could we model the packet injection with an event queue? Maybe with a UCQ
105 * or BCQ. We'd need some support from the kernel (minor) and maybe
106 * user-level event posting (major) to do it right. If we did that, we
107 * probably could get rid of the fdtap_watcher. The RX checks inbound_todo,
108 * then blocks on two evqs (inbound and inject). This way is simpler, for
111 * - Why do we rewrite IP addresses for the router to loopback, instead of
112 * host_v4_addr? First off, you have to pick one: loopback or host_v4_addr,
113 * not both. If we accept both (say, when the host connects to a static map),
114 * then on the other end (i.e. TX, response to an RX) will need to know which
115 * option we chose for its rewriting rule. We have to be consistent with how
116 * we handle ROUTER_IP and do the same thing in both directions. Given that
117 * we have to pick one of them, I opted for 127.0.0.1. That way, any host
118 * users know how to connect to the guest without worrying about their actual
119 * IP address. This also allows us to announce services on the host that are
120 * only available to loopback (i.e. not the main network) and let the guest
123 * - How can a guest reach the real host IP in qemu mode, but not in real-addr
124 * mode? This comes up when someone uses a static map but connects with the
125 * host_v4_addr as the source (which you do by contacting host_v4_addr as the
126 * *destination* from akaros). We don't rewrite those on the RX path. When
127 * the guest responds, it responds to whatever the src was on the inbound
128 * path. To the guest, our host_v4_addr is just another IP, which the host
129 * knows how to route to. It'd be similar to the guest trying to reach an
130 * address that is in the broadcast domain of the host. This doesn't work for
131 * real-addr mode, since the guest has the same IP as the host. Most guests
132 * won't emit a packet that is sent to their own IP address. If they did, the
133 * NAT code would remap it, but the guest just won't send it out. Hence the
138 #include <parlib/iovec.h>
139 #include <iplib/iplib.h>
140 #include <parlib/ros_debug.h>
141 #include <parlib/uthread.h>
142 #include <ndblib/ndb.h>
143 #include <iplib/iplib.h>
144 #include <parlib/printf-ext.h>
145 #include <parlib/event.h>
146 #include <parlib/spinlock.h>
147 #include <parlib/kref.h>
150 #include <parlib/stdio.h>
154 #include <sys/types.h>
155 #include <sys/stat.h>
157 #include <sys/queue.h>
159 /* Global control variables. The main VMM sets these manually. */
160 bool vnet_snoop = FALSE;
161 bool vnet_real_ip_addrs = FALSE;
162 bool vnet_map_diagnostics = FALSE;
163 unsigned long vnet_nat_timeout = 200;
165 uint8_t host_v4_addr[IPV4_ADDR_LEN];
166 uint8_t host_v4_mask[IPV4_ADDR_LEN];
167 uint8_t host_v4_router[IPV4_ADDR_LEN];
168 uint8_t host_v4_dns[IPV4_ADDR_LEN];
170 uint8_t loopback_v4_addr[IPV4_ADDR_LEN];
171 uint8_t bcast_v4_addr[IPV4_ADDR_LEN];
173 uint8_t guest_v4_addr[IPV4_ADDR_LEN];
174 uint8_t guest_v4_mask[IPV4_ADDR_LEN];
175 uint8_t guest_v4_router[IPV4_ADDR_LEN];
176 uint8_t guest_v4_dns[IPV4_ADDR_LEN];
178 /* We'll use this in all our eth headers with the guest. */
179 uint8_t host_eth_addr[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x0a};
180 uint8_t guest_eth_addr[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x0b};
181 const char dhcp_hostname[] = "host";
182 const char dhcp_guestname[] = "guest";
186 /* We map between host port and guest port for a given protocol. We don't care
187 * about confirming IP addresses or anything - we just swap ports. */
189 TAILQ_ENTRY(ip_nat_map) lookup_tuple;
190 TAILQ_ENTRY(ip_nat_map) lookup_fd;
198 /* These fields are protected by the rx mutex */
199 TAILQ_ENTRY(ip_nat_map) inbound;
203 #define NR_VNET_HASH 128
204 TAILQ_HEAD(ip_nat_map_tailq, ip_nat_map);
205 struct spin_pdr_lock maps_lock = SPINPDR_INITIALIZER;
206 /* Two hash tables: one for tuples (tx) and one for FD (rx). There's one kref
207 * for being in both tables; they are treated as a unit. */
208 struct ip_nat_map_tailq map_hash_tuple[NR_VNET_HASH];
209 struct ip_nat_map_tailq map_hash_fd[NR_VNET_HASH];
211 /* The todo list, used to track FDs that had activity but haven't told us EAGAIN
212 * yet. The list is protected by the rx_mtx */
213 struct ip_nat_map_tailq inbound_todo = TAILQ_HEAD_INITIALIZER(inbound_todo);
215 /* buf_pkt: tracks a packet, used for injecting packets (usually synthetic
216 * responses) into the guest via receive_packet. */
218 STAILQ_ENTRY(buf_pkt) next;
222 STAILQ_HEAD(buf_pkt_stailq, buf_pkt);
224 struct buf_pkt_stailq inject_pkts = STAILQ_HEAD_INITIALIZER(inject_pkts);
226 uth_cond_var_t *rx_cv;
227 struct event_queue *inbound_evq;
229 static void tap_inbound_conv(int fd);
231 #define GOLDEN_RATIO_64 0x61C8864680B583EBull
233 static struct ip_nat_map_tailq *list_hash_tuple(uint8_t protocol,
238 idx = ((protocol << 16 | guest_port) * GOLDEN_RATIO_64) % NR_VNET_HASH;
239 return &map_hash_tuple[idx];
242 static struct ip_nat_map_tailq *list_hash_fd(int host_data_fd)
246 idx = (host_data_fd * GOLDEN_RATIO_64) % NR_VNET_HASH;
247 return &map_hash_fd[idx];
250 /* Returnes a refcnted map. */
251 static struct ip_nat_map *lookup_map_by_tuple(uint8_t protocol,
254 struct ip_nat_map *i;
256 spin_pdr_lock(&maps_lock);
257 TAILQ_FOREACH(i, list_hash_tuple(protocol, guest_port), lookup_tuple) {
258 if ((i->protocol == protocol) &&
259 (i->guest_port == guest_port)) {
260 kref_get(&i->kref, 1);
264 spin_pdr_unlock(&maps_lock);
268 static struct ip_nat_map *lookup_map_by_hostfd(int host_data_fd)
270 struct ip_nat_map *i;
272 spin_pdr_lock(&maps_lock);
273 TAILQ_FOREACH(i, list_hash_fd(host_data_fd), lookup_fd) {
274 if (i->host_data_fd == host_data_fd) {
275 kref_get(&i->kref, 1);
279 spin_pdr_unlock(&maps_lock);
283 /* Stores the ref to the map in the global lookup 'table.' */
284 static void add_map(struct ip_nat_map *map)
286 spin_pdr_lock(&maps_lock);
287 TAILQ_INSERT_HEAD(list_hash_tuple(map->protocol, map->guest_port),
289 TAILQ_INSERT_HEAD(list_hash_fd(map->host_data_fd), map, lookup_fd);
290 spin_pdr_unlock(&maps_lock);
293 static void map_release(struct kref *kref)
295 struct ip_nat_map *map = container_of(kref, struct ip_nat_map, kref);
297 close(map->host_data_fd);
301 /* Creates a reference counted ip_nat_map for protocol between guest_port and
302 * host_port. Static mappings are ones that never expire, such as a port
303 * forwarding. Caller should add it to the lookup structure.
305 * For the host port, pass "*" for any port, like in a dialstring. */
306 static struct ip_nat_map *create_map(uint8_t protocol, uint16_t guest_port,
307 char *host_port, bool is_static)
309 struct ip_nat_map *map;
310 char dialstring[128];
311 char conv_dir[NETPATHLEN];
316 map = malloc(sizeof(struct ip_nat_map));
318 kref_init(&map->kref, map_release, 1);
319 map->protocol = protocol;
320 map->guest_port = guest_port;
321 map->is_static = is_static;
322 map->is_stale = FALSE;
323 map->is_on_inbound = FALSE;
333 panic("get_map for unsupported protocol %d!", protocol);
335 snprintf(dialstring, sizeof(dialstring), "%s!*!%s", proto_str,
338 bypass_fd = bypass9(dialstring, conv_dir, 0);
340 fprintf(stderr, "Failed to clone a conv for %s:%d (%r), won't bypass!\n",
341 proto_str, guest_port);
346 port_check = get_port9(conv_dir, "local", &map->host_port);
347 parlib_assert_perror(port_check);
349 map->host_data_fd = open_data_fd9(conv_dir, O_NONBLOCK);
350 parlib_assert_perror(map->host_data_fd >= 0);
352 tap_inbound_conv(map->host_data_fd);
358 /* Looks up or creates an ip_nat_map for the given proto/port tuple. */
359 static struct ip_nat_map *get_map_by_tuple(uint8_t protocol,
362 struct ip_nat_map *map;
364 map = lookup_map_by_tuple(protocol, guest_port);
367 map = create_map(protocol, guest_port, "*", FALSE);
370 kref_get(&map->kref, 1);
375 static void *map_reaper(void *arg)
377 struct ip_nat_map *i, *temp;
378 struct ip_nat_map_tailq to_release;
381 uthread_sleep(vnet_nat_timeout);
382 TAILQ_INIT(&to_release);
383 spin_pdr_lock(&maps_lock);
384 /* Only need to scan one map_hash, might as well be the tuple */
385 for (int j = 0; j < NR_VNET_HASH; j++) {
386 TAILQ_FOREACH_SAFE(i, &map_hash_tuple[j], lookup_tuple,
394 /* Remove from both lists, hashing for the FD
396 TAILQ_REMOVE(&map_hash_tuple[j], i,
398 TAILQ_REMOVE(list_hash_fd(i->host_data_fd), i,
400 /* Use the lookup_tuple for the temp list */
401 TAILQ_INSERT_HEAD(&to_release, i, lookup_tuple);
404 spin_pdr_unlock(&maps_lock);
405 TAILQ_FOREACH_SAFE(i, &to_release, lookup_tuple, temp)
411 static void map_dumper(void)
413 struct ip_nat_map *i;
415 fprintf(stderr, "\n\nVNET NAT maps:\n---------------\n");
416 spin_pdr_lock(&maps_lock);
417 for (int j = 0; j < NR_VNET_HASH; j++) {
418 TAILQ_FOREACH(i, &map_hash_tuple[j], lookup_tuple) {
419 fprintf(stderr, "\tproto %2d, host %5d, guest %5d, FD %4d, stale %d, static %d, ref %d\n",
420 i->protocol, i->host_port, i->guest_port,
421 i->host_data_fd, i->is_stale, i->is_static,
425 spin_pdr_unlock(&maps_lock);
428 static void init_map_lookup(struct virtual_machine *vm)
430 for (int i = 0; i < NR_VNET_HASH; i++)
431 TAILQ_INIT(&map_hash_tuple[i]);
432 for (int i = 0; i < NR_VNET_HASH; i++)
433 TAILQ_INIT(&map_hash_fd[i]);
434 vmm_run_task(vm, map_reaper, NULL);
437 static struct buf_pkt *zalloc_bpkt(size_t size)
439 struct buf_pkt *bpkt;
441 bpkt = malloc(sizeof(struct buf_pkt));
444 bpkt->buf = malloc(bpkt->sz);
446 memset(bpkt->buf, 0, bpkt->sz);
450 static void free_bpkt(struct buf_pkt *bpkt)
456 /* Queues a buf_pkt, which the rx thread will inject when it wakes. */
457 static void inject_buf_pkt(struct buf_pkt *bpkt)
459 uth_mutex_lock(rx_mtx);
460 STAILQ_INSERT_TAIL(&inject_pkts, bpkt, next);
461 uth_mutex_unlock(rx_mtx);
462 uth_cond_var_broadcast(rx_cv);
465 /* Helper for xsum_update, mostly for paranoia with integer promotion and
466 * cleanly keeping variables as u16. */
467 static uint16_t ones_comp(uint16_t x)
472 /* IP checksum updater. If you change amt bytes in a packet from old to new,
473 * this updates the xsum at xsum_off in the iov.
475 * Assumes a few things:
476 * - there's a 16 byte xsum at xsum_off
477 * - amt is a multiple of two
478 * - the data at *old and *new is network (big) endian
480 * There's no assumption about the alignment of old and new, thanks to Plan 9's
481 * sensible nhgets() (just byte accesses, not assuming u16 alignment).
483 * See RFC 1624 for the math. I opted for Eqn 3, instead of 4, since I didn't
484 * want to deal with subtraction underflow / carry / etc. Also note that we
485 * need to do the intermediate carry before doing the one's comp. That wasn't
486 * clear from the RFC either. RFC 1141 didn't need to do that, since they
487 * didn't complement the intermediate HC (xsum). */
488 static void xsum_update(struct iovec *iov, int iovcnt, size_t xsum_off,
489 uint8_t *old, uint8_t *new, size_t amt)
493 assert(amt % 2 == 0);
494 xsum = iov_get_be16(iov, iovcnt, xsum_off);
495 /* for each short: HC' = ~(~HC + ~m + m') (' == new, ~ == ones-comp) */
496 for (int i = 0; i < amt / 2; i++, old += 2, new += 2) {
497 xsum = ones_comp(xsum) + ones_comp(nhgets(old)) + nhgets(new);
498 /* Need to deal with the carry for any additions, before the
499 * outer ~() operation. (Not mentioned in the RFC, determined
502 xsum = (xsum & 0xffff) + (xsum >> 16);
503 /* Yes, next time around the loop we ones comp right back. Not
504 * worth optimizing. */
505 xsum = ones_comp(xsum);
507 iov_put_be16(iov, iovcnt, xsum_off, xsum);
510 static void snoop_on_virtio(void)
513 int srv_fd, pipe_dir_fd, pipe_ctl_fd, pipe_srv_fd, pipe_snoop_fd;
514 const char cmd[] = "oneblock";
515 char buf[MAX_PATH_LEN];
517 pipe_dir_fd = open("#pipe", O_PATH);
518 parlib_assert_perror(pipe_dir_fd >= 0);
520 pipe_ctl_fd = openat(pipe_dir_fd, "ctl", O_RDWR);
521 parlib_assert_perror(pipe_ctl_fd >= 0);
522 ret = write(pipe_ctl_fd, cmd, sizeof(cmd));
523 parlib_assert_perror(ret == sizeof(cmd));
526 pipe_snoop_fd = openat(pipe_dir_fd, "data", O_RDWR);
527 parlib_assert_perror(pipe_snoop_fd >= 0);
528 ret = fcntl(pipe_snoop_fd, F_SETFL, O_NONBLOCK);
529 parlib_assert_perror(!ret);
530 snoop_fd = pipe_snoop_fd;
532 pipe_srv_fd = openat(pipe_dir_fd, "data1", O_RDWR);
533 parlib_assert_perror(pipe_srv_fd >= 0);
534 ret = snprintf(buf, sizeof(buf), "#srv/%s-%d", "snoop", getpid());
535 /* We don't close srv_fd here. When we exit, it'll close and remove. */
536 srv_fd = open(buf, O_RDWR | O_EXCL | O_CREAT | O_REMCLO, 0444);
537 parlib_assert_perror(srv_fd >= 0);
538 ret = snprintf(buf, sizeof(buf), "%d", pipe_srv_fd);
539 ret = write(srv_fd, buf, ret);
540 parlib_assert_perror(ret > 0);
544 /* Gets the host's IPv4 information from iplib and ndb. */
545 static void get_host_ip_addrs(void)
552 struct ipifc *to_free;
555 uint8_t router_ip[IPaddrlen];
557 register_printf_specifier('i', printf_ipaddr, printf_ipaddr_info);
558 register_printf_specifier('M', printf_ipmask, printf_ipmask_info);
560 lifc = get_first_noloop_iplifc(NULL, &to_free);
563 "IP addr lookup failed (%r), no VM networking\n");
566 snprintf(my_ip_str, sizeof(my_ip_str), "%i", lifc->ip);
567 snprintf(buf, sizeof(buf), "%i%M", lifc->ip, lifc->mask);
568 v4parsecidr(host_v4_addr, host_v4_mask, buf);
571 ret = my_router_addr(router_ip, NULL);
574 "Router lookup failed (%r), no VM networking\n");
577 v6tov4(host_v4_router, router_ip);
579 ndb = ndbopen("/net/ndb");
581 fprintf(stderr, "NDB open failed (%r), no VM networking\n");
584 nt = ndbipinfo(ndb, "ip", my_ip_str, &dns, 1);
587 "DNS server lookup failed (%r), no VM networking\n");
590 v4parseip(host_v4_dns, nt->val);
595 static void set_ip_addrs(void)
599 loopback_v4_addr[0] = 127;
600 loopback_v4_addr[1] = 0;
601 loopback_v4_addr[2] = 0;
602 loopback_v4_addr[3] = 1;
604 bcast_v4_addr[0] = 255;
605 bcast_v4_addr[1] = 255;
606 bcast_v4_addr[2] = 255;
607 bcast_v4_addr[3] = 255;
609 /* even in qemu mode, the guest gets the real DNS IP */
610 memcpy(guest_v4_dns, host_v4_dns, IPV4_ADDR_LEN);
612 if (vnet_real_ip_addrs) {
613 memcpy(guest_v4_addr, host_v4_addr, IPV4_ADDR_LEN);
614 memcpy(guest_v4_mask, host_v4_mask, IPV4_ADDR_LEN);
615 memcpy(guest_v4_router, host_v4_router, IPV4_ADDR_LEN);
617 guest_v4_addr[0] = 10;
618 guest_v4_addr[1] = 0;
619 guest_v4_addr[2] = 2;
620 guest_v4_addr[3] = 15;
622 guest_v4_mask[0] = 255;
623 guest_v4_mask[1] = 255;
624 guest_v4_mask[2] = 255;
625 guest_v4_mask[3] = 0;
627 guest_v4_router[0] = 10;
628 guest_v4_router[1] = 0;
629 guest_v4_router[2] = 2;
630 guest_v4_router[3] = 2;
634 static void tap_inbound_conv(int fd)
636 struct fd_tap_req tap_req = {0};
640 tap_req.cmd = FDTAP_CMD_ADD;
641 tap_req.filter = FDTAP_FILT_READABLE;
642 tap_req.ev_q = inbound_evq;
645 ret = sys_tap_fds(&tap_req, 1);
646 parlib_assert_perror(ret == 1);
649 /* For every FD tap that fires, make sure the map is on the inbound_todo list
650 * and kick the receiver.
652 * A map who's FD fires might already be on the list - it's possible for an FD
653 * to drain to 0 and get another packet (thus triggering a tap) before
654 * __poll_inbound() notices and removes it from the list. */
655 static void *fdtap_watcher(void *arg)
657 struct event_msg msg[1];
658 struct ip_nat_map *map;
661 uth_blockon_evqs(msg, NULL, 1, inbound_evq);
662 map = lookup_map_by_hostfd(msg->ev_type);
663 /* Could get an event for an FD/map that has since been reaped.
667 uth_mutex_lock(rx_mtx);
668 if (!map->is_on_inbound) {
669 map->is_on_inbound = TRUE;
670 TAILQ_INSERT_TAIL(&inbound_todo, map, inbound);
671 uth_cond_var_broadcast(rx_cv);
673 kref_put(&map->kref);
675 uth_mutex_unlock(rx_mtx);
680 static struct event_queue *get_inbound_evq(void)
682 struct event_queue *ceq;
684 ceq = get_eventq_raw();
685 ceq->ev_mbox->type = EV_MBOX_CEQ;
686 ceq_init(&ceq->ev_mbox->ceq, CEQ_OR, NR_FILE_DESC_MAX, 128);
687 /* As far as flags go, we might not want IPI in the future. Depends on
688 * some longer range VMM/2LS changes. Regarding INDIR, if you want to
689 * find out about the event (i.e. not poll) for non-VCPD mboxes (like
690 * this evq's mbox), then you need INDIR. We need that for the
692 ceq->ev_flags = EVENT_INDIR | EVENT_SPAM_INDIR | EVENT_WAKEUP |
694 evq_attach_wakeup_ctlr(ceq);
698 void vnet_port_forward(char *protocol, char *host_port, char *guest_port)
700 struct ip_nat_map *map;
703 if (!strcmp("udp", protocol)) {
704 proto_nr = IP_UDPPROTO;
705 } else if (!strcmp("tcp", protocol)) {
706 proto_nr = IP_TCPPROTO;
708 fprintf(stderr, "Can't port forward protocol %s\n", protocol);
711 map = create_map(proto_nr, atoi(guest_port), host_port, TRUE);
713 fprintf(stderr, "Failed to set up port forward!");
719 static void ev_handle_diag(struct event_msg *ev_msg, unsigned int ev_type,
725 void vnet_init(struct virtual_machine *vm, struct virtio_vq_dev *vqdev)
728 virtio_net_set_mac(vqdev, guest_eth_addr);
729 rx_mtx = uth_mutex_alloc();
730 rx_cv = uth_cond_var_alloc();
734 inbound_evq = get_inbound_evq();
735 vmm_run_task(vm, fdtap_watcher, NULL);
736 if (vnet_map_diagnostics)
737 register_ev_handler(EV_FREE_APPLE_PIE, ev_handle_diag, NULL);
740 /* Good DHCP reference:
741 * http://www.tcpipguide.com/free/t_TCPIPDynamicHostConfigurationProtocolDHCP.htm
743 #define DHCP_MAX_OPT_LEN 200
744 #define DHCP_MAIN_BODY_LEN 236
745 #define DHCP_RSP_LEN (DHCP_MAIN_BODY_LEN + DHCP_MAX_OPT_LEN)
746 #define DHCP_LEASE_TIME 3600
748 #define DHCP_OP_REQ 1
749 #define DHCP_OP_RSP 2
751 #define DHCP_MSG_DISCOVER 1
752 #define DHCP_MSG_OFFER 2
753 #define DHCP_MSG_REQUEST 3
754 #define DHCP_MSG_DECLINE 4
755 #define DHCP_MSG_ACK 5
756 #define DHCP_MSG_NAK 6
757 #define DHCP_MSG_RELEASE 7
758 #define DHCP_MSG_INFORM 8
760 #define DHCP_MAGIC_COOKIE_1 0x63
761 #define DHCP_MAGIC_COOKIE_2 0x82
762 #define DHCP_MAGIC_COOKIE_3 0x53
763 #define DHCP_MAGIC_COOKIE_4 0x63
765 #define DHCP_OPT_PAD 0
766 #define DHCP_OPT_SUBNET 1
767 #define DHCP_OPT_ROUTER 3
768 #define DHCP_OPT_DNS 6
769 #define DHCP_OPT_HOSTNAME 12
770 #define DHCP_OPT_LEASE 51
771 #define DHCP_OPT_MSG_TYPE 53
772 #define DHCP_OPT_SERVER_ID 54
773 #define DHCP_OPT_END_OF_OPT 255
775 static int get_dhcp_req_type(struct iovec *iov, int iovcnt)
777 size_t idx = ETH_HDR_LEN + IPV4_HDR_LEN + UDP_HDR_LEN
778 + DHCP_MAIN_BODY_LEN;
780 if (!iov_has_bytes(iov, iovcnt, idx + 4)) {
781 fprintf(stderr, "DHCP request too short!\n");
785 if ((iov_get_byte(iov, iovcnt, idx + 0) != DHCP_MAGIC_COOKIE_1) ||
786 (iov_get_byte(iov, iovcnt, idx + 1) != DHCP_MAGIC_COOKIE_2) ||
787 (iov_get_byte(iov, iovcnt, idx + 2) != DHCP_MAGIC_COOKIE_3) ||
788 (iov_get_byte(iov, iovcnt, idx + 3) != DHCP_MAGIC_COOKIE_4)) {
789 fprintf(stderr, "DHCP request didn't have magic cookie!\n");
792 /* Some clients might ask us to look in sname or other locations, which
793 * is communicated by an option. So far, the clients I've seen just use
794 * the main options to communicate the message type. */
797 if (!iov_has_bytes(iov, iovcnt, idx + 1)) {
798 fprintf(stderr, "DHCP request too short!\n");
801 switch (iov_get_byte(iov, iovcnt, idx)) {
802 case DHCP_OPT_MSG_TYPE:
803 if (!iov_has_bytes(iov, iovcnt, idx + 3)) {
804 fprintf(stderr, "DHCP request too short!\n");
807 return iov_get_byte(iov, iovcnt, idx + 2);
811 case DHCP_OPT_END_OF_OPT:
812 fprintf(stderr, "DHCP request without a type!\n");
815 if (!iov_has_bytes(iov, iovcnt, idx + 2)) {
816 fprintf(stderr, "DHCP request too short!\n");
819 /* idx + 1 is size of the payload. Skip the opt, size,
821 idx += 2 + iov_get_byte(iov, iovcnt, idx + 1);
827 static size_t build_dhcp_response(struct iovec *iov, int iovcnt, uint8_t *buf)
833 *p++ = ETH_HTYPE_ETH;
835 *p++ = 0x00; /* hops */
836 /* TODO: copies XID; assumes the inbound packet had standard headers */
837 iov_memcpy_from(iov, iovcnt,
838 ETH_HDR_LEN + IPV4_HDR_LEN + UDP_HDR_LEN + 4, p, 4);
840 p += 8; /* secs, flags, CIADDR */
841 memcpy(p, guest_v4_addr, IPV4_ADDR_LEN);
843 memcpy(p, guest_v4_router, IPV4_ADDR_LEN);
845 memcpy(p, guest_v4_router, IPV4_ADDR_LEN);
847 iov_memcpy_from(iov, iovcnt, ETH_ADDR_LEN, p, ETH_ADDR_LEN);
848 p += 16; /* CHaddr has 16 bytes, we only use 6 */
849 memcpy(p, dhcp_hostname, strlen(dhcp_hostname));
853 req_type = get_dhcp_req_type(iov, iovcnt);
855 /* DHCP options: Technically, we should be responding with whatever
856 * fields they asked for in their incoming message. For the most part,
857 * there are a bunch of standard things we can just respond with. */
859 *p++ = DHCP_MAGIC_COOKIE_1;
860 *p++ = DHCP_MAGIC_COOKIE_2;
861 *p++ = DHCP_MAGIC_COOKIE_3;
862 *p++ = DHCP_MAGIC_COOKIE_4;
864 *p++ = DHCP_OPT_MSG_TYPE;
867 case DHCP_MSG_DISCOVER:
868 *p++ = DHCP_MSG_OFFER;
870 case DHCP_MSG_REQUEST:
874 panic("Unexpected DHCP message type %d", req_type);
877 *p++ = DHCP_OPT_SUBNET;
879 memcpy(p, guest_v4_mask, IPV4_ADDR_LEN);
882 *p++ = DHCP_OPT_ROUTER;
884 memcpy(p, guest_v4_router, IPV4_ADDR_LEN);
889 memcpy(p, guest_v4_dns, IPV4_ADDR_LEN);
892 *p++ = DHCP_OPT_HOSTNAME;
893 *p++ = strlen(dhcp_guestname); /* not null-terminated */
894 memcpy(p, dhcp_guestname, strlen(dhcp_guestname));
895 p += strlen(dhcp_guestname);
897 if (req_type == DHCP_MSG_REQUEST) {
898 *p++ = DHCP_OPT_LEASE;
900 hnputl(p, DHCP_LEASE_TIME);
903 *p++ = DHCP_OPT_SERVER_ID;
905 memcpy(p, guest_v4_dns, IPV4_ADDR_LEN);
910 *p++ = DHCP_OPT_END_OF_OPT;
915 /* Builds a UDP packet responding to IOV with buf of payload_sz. Sent from
916 * src_port to dst_port. Returns the new size, including UDP headers. */
917 static size_t build_udp_response(struct iovec *iov, int iovcnt, uint8_t *buf,
919 uint16_t src_port, uint16_t dst_port)
927 hnputs(p, payload_sz + UDP_HDR_LEN);
929 /* For v4, we don't need to do the xsum. It's a minor pain too, since
930 * they xsum parts of the IP header too. */
934 return p - buf + payload_sz;
937 /* Builds an IP packet responding to iov with buf of payload_sz. Sent from->to
938 * with protocol. Returns the new size, including IP headers.
940 * We take parameters for the IP, since some usages won't use the iov's IP (e.g.
942 static size_t build_ip_response(struct iovec *iov, int iovcnt, uint8_t *buf,
943 size_t payload_sz, uint8_t *from, uint8_t *to,
949 *p = 0x45; /* version, etc */
951 hnputs(p, payload_sz + IPV4_HDR_LEN);
960 memcpy(p, from, IPV4_ADDR_LEN);
962 memcpy(p, to, IPV4_ADDR_LEN);
964 hnputs(xsum_addr, ip_calc_xsum(buf, IPV4_HDR_LEN));
966 return p - buf + payload_sz;
969 /* Builds an ethernet response to iov from buf of payload_sz. Returns the new
970 * size, including ethernet headers. */
971 static size_t build_eth_response(struct iovec *iov, int iovcnt, uint8_t *buf,
972 size_t payload_sz, uint16_t ether_type)
976 iov_memcpy_from(iov, iovcnt, ETH_OFF_SRC, p, ETH_ADDR_LEN);
978 memcpy(p, host_eth_addr, ETH_ADDR_LEN);
980 hnputs(p, ether_type);
983 return p - buf + payload_sz;
986 static void fake_dhcp_response(struct iovec *iov, int iovcnt)
988 struct buf_pkt *bpkt;
991 switch (get_dhcp_req_type(iov, iovcnt)) {
993 case DHCP_MSG_DECLINE:
996 case DHCP_MSG_RELEASE:
997 case DHCP_MSG_INFORM:
1000 bpkt = zalloc_bpkt(ETH_HDR_LEN + IPV4_HDR_LEN + UDP_HDR_LEN +
1003 payload_sz = build_dhcp_response(iov, iovcnt, bpkt->buf + ETH_HDR_LEN +
1004 IPV4_HDR_LEN + UDP_HDR_LEN);
1005 payload_sz = build_udp_response(iov, iovcnt,
1006 bpkt->buf + ETH_HDR_LEN + IPV4_HDR_LEN,
1007 payload_sz, 67, 68);
1008 /* For offers and initial requests, we definitely need to send it to
1009 * 255.255.255.255 (bcast). For renewals, it seems like that that also
1010 * suffices, which seems reasonable. */
1011 payload_sz = build_ip_response(iov, iovcnt, bpkt->buf + ETH_HDR_LEN,
1012 payload_sz, guest_v4_router,
1013 bcast_v4_addr, IP_UDPPROTO);
1014 payload_sz = build_eth_response(iov, iovcnt, bpkt->buf, payload_sz,
1017 assert(payload_sz <= bpkt->sz);
1018 bpkt->sz = payload_sz;
1019 inject_buf_pkt(bpkt);
1022 static size_t build_arp_response(struct iovec *iov, int iovcnt, uint8_t *buf)
1026 hnputs(p, ETH_HTYPE_ETH);
1028 hnputs(p, ETH_TYPE_IPV4);
1030 *p++ = ETH_ADDR_LEN;
1031 *p++ = IPV4_ADDR_LEN;
1032 hnputs(p, ARP_OP_RSP);
1034 /* SHA: addr they are looking for, which is always host's eth addr */
1035 memcpy(p, host_eth_addr, ETH_ADDR_LEN);
1037 /* SPA: addr they are looking for, which was the request TPA */
1038 iov_memcpy_from(iov, iovcnt, ETH_HDR_LEN + ARP_OFF_TPA, p,
1041 /* THA was the SHA of the request */
1042 iov_memcpy_from(iov, iovcnt, ETH_HDR_LEN + ARP_OFF_SHA, p,
1045 /* TPA was the SPA of the request */
1046 iov_memcpy_from(iov, iovcnt, ETH_HDR_LEN + ARP_OFF_SPA, p,
1053 static bool should_ignore_arp(struct iovec *iov, int iovcnt)
1055 size_t arp_off = ETH_HDR_LEN;
1057 if (iov_get_be16(iov, iovcnt, arp_off + ARP_OFF_OP) != ARP_OP_REQ)
1059 /* ARP probes set the SPA to 0. Ignore these. */
1060 if (iov_get_be32(iov, iovcnt, arp_off + ARP_OFF_SPA) == 0)
1065 static void handle_arp_tx(struct iovec *iov, int iovcnt)
1067 struct buf_pkt *bpkt;
1070 if (should_ignore_arp(iov, iovcnt))
1072 bpkt = zalloc_bpkt(ETH_HDR_LEN + ARP_PKT_LEN);
1073 payload_sz = build_arp_response(iov, iovcnt, bpkt->buf + ETH_HDR_LEN);
1074 payload_sz = build_eth_response(iov, iovcnt, bpkt->buf, payload_sz,
1076 assert(payload_sz <= bpkt->sz);
1077 bpkt->sz = payload_sz;
1078 inject_buf_pkt(bpkt);
1081 /* Helper for protocols: updates an xsum, given a port number change */
1082 static void xsum_changed_port(struct iovec *iov, int iovcnt, size_t xsum_off,
1083 uint16_t old_port, uint16_t new_port)
1085 uint16_t old_port_be, new_port_be;
1087 /* xsum update expects to work on big endian */
1088 hnputs(&old_port_be, old_port);
1089 hnputs(&new_port_be, new_port);
1090 xsum_update(iov, iovcnt, xsum_off, (uint8_t*)&old_port_be,
1091 (uint8_t*)&new_port_be, 2);
1094 static struct ip_nat_map *handle_udp_tx(struct iovec *iov, int iovcnt,
1097 uint16_t src_port, dst_port;
1098 struct ip_nat_map *map;
1100 if (!iov_has_bytes(iov, iovcnt, udp_off + UDP_HDR_LEN)) {
1101 fprintf(stderr, "Short UDP header, dropping!\n");
1104 src_port = iov_get_be16(iov, iovcnt, udp_off + UDP_OFF_SRC_PORT);
1105 dst_port = iov_get_be16(iov, iovcnt, udp_off + UDP_OFF_DST_PORT);
1106 if (dst_port == 67) {
1107 fake_dhcp_response(iov, iovcnt);
1110 map = get_map_by_tuple(IP_UDPPROTO, src_port);
1113 xsum_changed_port(iov, iovcnt, udp_off + UDP_OFF_XSUM, src_port,
1115 iov_put_be16(iov, iovcnt, udp_off + UDP_OFF_SRC_PORT, map->host_port);
1119 static struct ip_nat_map *handle_tcp_tx(struct iovec *iov, int iovcnt,
1122 uint16_t src_port, dst_port;
1123 struct ip_nat_map *map;
1125 if (!iov_has_bytes(iov, iovcnt, tcp_off + TCP_HDR_LEN)) {
1126 fprintf(stderr, "Short TCP header, dropping!\n");
1129 src_port = iov_get_be16(iov, iovcnt, tcp_off + TCP_OFF_SRC_PORT);
1130 dst_port = iov_get_be16(iov, iovcnt, tcp_off + TCP_OFF_DST_PORT);
1131 map = get_map_by_tuple(IP_TCPPROTO, src_port);
1134 xsum_changed_port(iov, iovcnt, tcp_off + TCP_OFF_XSUM, src_port,
1136 iov_put_be16(iov, iovcnt, tcp_off + TCP_OFF_SRC_PORT, map->host_port);
1140 static struct ip_nat_map *handle_icmp_tx(struct iovec *iov, int iovcnt,
1143 /* TODO: we could respond to pings sent to us (router_ip). For anything
1144 * else, we'll need to work with the bypass (if possible, maybe ID it
1145 * with the Identifier field and map that to the bypassed conv)). */
1149 /* Some protocols (like TCP and UDP) need to adjust their xsums whenever an IPv4
1150 * address changes. */
1151 static void ipv4_proto_changed_addr(struct iovec *iov, int iovcnt,
1152 uint8_t protocol, size_t proto_hdr_off,
1153 uint8_t *old_addr, uint8_t *new_addr)
1157 xsum_update(iov, iovcnt, proto_hdr_off + UDP_OFF_XSUM, old_addr,
1158 new_addr, IPV4_ADDR_LEN);
1161 xsum_update(iov, iovcnt, proto_hdr_off + TCP_OFF_XSUM, old_addr,
1162 new_addr, IPV4_ADDR_LEN);
1167 /* Helper, changes a packet's IP address, updating xsums. 'which' controls
1168 * whether we're changing the src or dst address. */
1169 static void ipv4_change_addr(struct iovec *iov, int iovcnt, size_t ip_off,
1170 uint8_t protocol, uint8_t proto_hdr_off,
1171 uint8_t *old_addr, uint8_t *new_addr, size_t which)
1173 xsum_update(iov, iovcnt, ip_off + IPV4_OFF_XSUM, old_addr, new_addr,
1175 ipv4_proto_changed_addr(iov, iovcnt, protocol, proto_hdr_off, old_addr,
1177 iov_memcpy_to(iov, iovcnt, ip_off + which, new_addr, IPV4_ADDR_LEN);
1180 static size_t ipv4_get_header_len(struct iovec *iov, int iovcnt, size_t ip_off)
1182 /* First byte, lower nibble, times 4. */
1183 return (iov_get_byte(iov, iovcnt, ip_off + 0) & 0x0f) * 4;
1186 static size_t ipv4_get_proto_off(struct iovec *iov, int iovcnt, size_t ip_off)
1188 return ipv4_get_header_len(iov, iovcnt, ip_off) + ip_off;
1191 static uint8_t ipv4_get_version(struct iovec *iov, int iovcnt, size_t ip_off)
1193 /* First byte, upper nibble, but keep in the upper nibble location */
1194 return iov_get_byte(iov, iovcnt, ip_off + 0) & 0xf0;
1197 static void handle_ipv4_tx(struct iovec *iov, int iovcnt)
1199 size_t ip_off = ETH_HDR_LEN;
1201 size_t proto_hdr_off;
1202 struct ip_nat_map *map;
1203 uint8_t src_addr[IPV4_ADDR_LEN];
1204 uint8_t dst_addr[IPV4_ADDR_LEN];
1206 if (!iov_has_bytes(iov, iovcnt, ip_off + IPV4_HDR_LEN)) {
1207 fprintf(stderr, "Short IPv4 header, dropping!\n");
1210 /* It's up to each protocol to give us the ip_nat_map matching the
1211 * packet and to change the packet's src port. */
1212 protocol = iov_get_byte(iov, iovcnt, ip_off + IPV4_OFF_PROTO);
1213 proto_hdr_off = ipv4_get_proto_off(iov, iovcnt, ip_off);
1216 map = handle_udp_tx(iov, iovcnt, proto_hdr_off);
1219 map = handle_tcp_tx(iov, iovcnt, proto_hdr_off);
1222 map = handle_icmp_tx(iov, iovcnt, proto_hdr_off);
1225 /* If the protocol handler already dealt with it (e.g. via emulation),
1226 * we bail out. o/w, they gave us the remapping we should use to
1227 * rewrite and send the packet. */
1230 /* At this point, we have a refcnted map, which will keep the map alive
1231 * and its FD open. */
1232 iov_memcpy_from(iov, iovcnt, ip_off + IPV4_OFF_SRC, src_addr,
1234 iov_memcpy_from(iov, iovcnt, ip_off + IPV4_OFF_DST, dst_addr,
1236 /* If the destination is the ROUTER_IP, then it's really meant to go to
1237 * the host (loopback). In that case, we also need the src to be
1238 * loopback, so that the *host's* IP stack recognizes the connection
1239 * (necessary for host-initiated connections via static maps). */
1240 if (!memcmp(dst_addr, guest_v4_router, IPV4_ADDR_LEN)) {
1241 ipv4_change_addr(iov, iovcnt, ip_off, protocol, proto_hdr_off,
1242 dst_addr, loopback_v4_addr, IPV4_OFF_DST);
1243 ipv4_change_addr(iov, iovcnt, ip_off, protocol, proto_hdr_off,
1244 src_addr, loopback_v4_addr, IPV4_OFF_SRC);
1246 ipv4_change_addr(iov, iovcnt, ip_off, protocol, proto_hdr_off,
1247 src_addr, host_v4_addr, IPV4_OFF_SRC);
1249 /* We didn't change the size of the packet, just a few fields. So we
1250 * shouldn't need to worry about iov[] being too big. This is different
1251 * than the receive case, where the guest should give us an MTU-sized
1252 * iov. Here, they just gave us whatever they wanted to send.
1254 * However, we still need to drop the ethernet header from the front of
1255 * the packet, and just send the IP header + payload. */
1256 iov_strip_bytes(iov, iovcnt, ETH_HDR_LEN);
1257 /* As far as blocking goes, this is like blasting out a raw IP packet.
1258 * It shouldn't block, preferring to drop, though there might be some
1259 * cases where a qlock is grabbed or the medium/NIC blocks. */
1260 writev(map->host_data_fd, iov, iovcnt);
1261 map->is_stale = FALSE;
1262 kref_put(&map->kref);
1265 static void handle_ipv6_tx(struct iovec *iov, int iovcnt)
1269 /* virtio-net calls this when the guest transmits a packet */
1270 int vnet_transmit_packet(struct iovec *iov, int iovcnt)
1272 uint16_t ether_type;
1275 writev(snoop_fd, iov, iovcnt);
1276 if (!iov_has_bytes(iov, iovcnt, ETH_HDR_LEN)) {
1278 "Short ethernet frame from the guest, dropping!\n");
1281 ether_type = iov_get_be16(iov, iovcnt, ETH_OFF_ETYPE);
1282 switch (ether_type) {
1284 handle_arp_tx(iov, iovcnt);
1287 handle_ipv4_tx(iov, iovcnt);
1290 handle_ipv6_tx(iov, iovcnt);
1293 fprintf(stderr, "Unknown ethertype 0x%x, dropping!\n",
1300 /* Polls for injected packets, filling the iov[iovcnt] on success and returning
1301 * the amount. 0 means 'nothing there.' */
1302 static size_t __poll_injection(struct iovec *iov, int iovcnt)
1305 struct buf_pkt *bpkt;
1307 if (STAILQ_EMPTY(&inject_pkts))
1309 bpkt = STAILQ_FIRST(&inject_pkts);
1310 STAILQ_REMOVE_HEAD(&inject_pkts, next);
1311 iov_memcpy_to(iov, iovcnt, 0, bpkt->buf, bpkt->sz);
1317 static void handle_udp_rx(struct iovec *iov, int iovcnt, size_t len,
1318 struct ip_nat_map *map, size_t udp_off)
1320 assert(len >= udp_off + UDP_HDR_LEN);
1321 xsum_changed_port(iov, iovcnt, udp_off + UDP_OFF_XSUM,
1322 iov_get_be16(iov, iovcnt, udp_off + UDP_OFF_DST_PORT),
1324 iov_put_be16(iov, iovcnt, udp_off + UDP_OFF_DST_PORT, map->guest_port);
1327 static void handle_tcp_rx(struct iovec *iov, int iovcnt, size_t len,
1328 struct ip_nat_map *map, size_t tcp_off)
1330 assert(len >= tcp_off + TCP_HDR_LEN);
1331 xsum_changed_port(iov, iovcnt, tcp_off + TCP_OFF_XSUM,
1332 iov_get_be16(iov, iovcnt, tcp_off + TCP_OFF_DST_PORT),
1334 iov_put_be16(iov, iovcnt, tcp_off + TCP_OFF_DST_PORT, map->guest_port);
1337 /* Computes and stores the xsum for the ipv4 header in the iov. */
1338 static void xsum_ipv4_header(struct iovec *iov, int iovcnt, size_t ip_off)
1340 size_t hdr_len = ipv4_get_header_len(iov, iovcnt, ip_off);
1341 uint8_t buf[hdr_len];
1343 iov_memcpy_from(iov, iovcnt, ip_off, buf, hdr_len);
1344 *(uint16_t*)&buf[IPV4_OFF_XSUM] = 0;
1345 iov_put_be16(iov, iovcnt, ip_off + IPV4_OFF_XSUM,
1346 ip_calc_xsum(buf, IPV4_HDR_LEN));
1349 static void handle_ipv4_rx(struct iovec *iov, int iovcnt, size_t len,
1350 struct ip_nat_map *map)
1352 size_t ip_off = ETH_HDR_LEN;
1354 size_t proto_hdr_off;
1355 uint8_t src_addr[IPV4_ADDR_LEN];
1356 uint8_t dst_addr[IPV4_ADDR_LEN];
1358 protocol = iov_get_byte(iov, iovcnt, ip_off + IPV4_OFF_PROTO);
1359 proto_hdr_off = ipv4_get_proto_off(iov, iovcnt, ip_off);
1360 switch (map->protocol) {
1362 handle_udp_rx(iov, iovcnt, len, map, proto_hdr_off);
1365 handle_tcp_rx(iov, iovcnt, len, map, proto_hdr_off);
1368 panic("Bad proto %d on map for conv FD %d\n", map->protocol,
1371 iov_memcpy_from(iov, iovcnt, ip_off + IPV4_OFF_SRC, src_addr,
1373 iov_memcpy_from(iov, iovcnt, ip_off + IPV4_OFF_DST, dst_addr,
1375 /* If the src was the host (loopback), the guest thinks the remote is
1377 if (!memcmp(src_addr, loopback_v4_addr, IPV4_ADDR_LEN)) {
1378 ipv4_change_addr(iov, iovcnt, ip_off, map->protocol,
1379 proto_hdr_off, src_addr, guest_v4_router,
1382 /* Interesting case. If we rewrite it to guest_v4_router, when the
1383 * guest responds, *that* packet will get rewritten to loopback. If we
1384 * ignore it, and it's qemu mode, it'll actually work. If it's real
1385 * addr mode, the guest won't send an IP packet out that it thinks is
1387 if (vnet_real_ip_addrs && !memcmp(src_addr, host_v4_addr,
1389 fprintf(stderr, "VNET received packet from host_v4_addr. Not translating, the guest cannot respond!\n");
1391 /* Regardless, the dst changes from HOST_IP/loopback to GUEST_IP */
1392 ipv4_change_addr(iov, iovcnt, ip_off, map->protocol, proto_hdr_off,
1393 dst_addr, guest_v4_addr, IPV4_OFF_DST);
1394 /* Note we did the incremental xsum for the IP header, but also do a
1395 * final xsum. We need the final xsum in case the kernel's networking
1396 * stack messed up the header. */
1397 xsum_ipv4_header(iov, iovcnt, ip_off);
1400 /* NAT / translate an inbound packet iov[len], using map. If a packet comes in
1401 * on a certain FD, then it's going to the guest at the appropriate port, no
1404 * The iov has ETH_HDR_LEN bytes at the front. The data actually read from the
1405 * conv starts at that offset. len includes this frontal padding - it's the
1406 * full length of the real data in the iov + the ethernet header. len may
1407 * include data beyond the IP packet length; we often get padding from the
1408 * kernel networking stack. Returns the final size of the packet. */
1409 static size_t handle_rx(struct iovec *iov, int iovcnt, size_t len,
1410 struct ip_nat_map *map)
1412 size_t ip_off = ETH_HDR_LEN;
1414 uint16_t ether_type;
1416 /* The conv is reading from a Qmsg queue. We should always receive at
1417 * least an IPv4 header from the kernel. */
1418 assert(len >= IPV4_HDR_LEN + ETH_HDR_LEN);
1419 version = ipv4_get_version(iov, iovcnt, ip_off);
1422 ether_type = ETH_TYPE_IPV4;
1423 handle_ipv4_rx(iov, iovcnt, len, map);
1426 ether_type = ETH_TYPE_IPV6;
1427 /* Technically, this could be a bad actor outside our node */
1428 panic("Got an IPv6 packet on FD %d!\n", map->host_data_fd);
1430 panic("Unexpected IP version 0x%x, probably a bug", version);
1432 iov_memcpy_to(iov, iovcnt, ETH_OFF_DST, guest_eth_addr, ETH_ADDR_LEN);
1433 iov_memcpy_to(iov, iovcnt, ETH_OFF_SRC, host_eth_addr, ETH_ADDR_LEN);
1434 iov_put_be16(iov, iovcnt, ETH_OFF_ETYPE, ether_type);
1438 /* Polls for inbound packets on the host's FD, filling the iov[iovcnt] on
1439 * success and returning the amount. 0 means 'nothing there.'
1441 * Notes on concurrency:
1442 * - The inbound_todo list is protected by the rx_mtx. Since we're readv()ing
1443 * while holding the mtx (because we're in a FOREACH), we're single threaded
1445 * - The inbound_todo list is filled by another thread that puts maps on the
1446 * list whenever their FD tap fires.
1447 * - The maps on the inbound_todo list are refcounted. It's possible for them
1448 * to be reaped and removed from the mapping lookup, but the mapping would
1449 * stay around until we drained all of the packets from the inbound conv. */
1450 static size_t __poll_inbound(struct iovec *iov, int iovcnt)
1452 struct ip_nat_map *i, *temp;
1454 struct iovec iov_copy[iovcnt];
1456 /* We're going to readv ETH_HDR_LEN bytes into the iov. To do so, we'll
1457 * use a separate iov to track this offset. The iov and iov_copy both
1458 * point to the same memory (minus the stripping). */
1459 memcpy(iov_copy, iov, sizeof(struct iovec) * iovcnt);
1460 iov_strip_bytes(iov_copy, iovcnt, ETH_HDR_LEN);
1461 TAILQ_FOREACH_SAFE(i, &inbound_todo, inbound, temp) {
1462 pkt_sz = readv(i->host_data_fd, iov_copy, iovcnt);
1464 i->is_stale = FALSE;
1465 return handle_rx(iov, iovcnt, pkt_sz + ETH_HDR_LEN, i);
1467 parlib_assert_perror(errno == EAGAIN);
1468 TAILQ_REMOVE(&inbound_todo, i, inbound);
1469 i->is_on_inbound = FALSE;
1475 /* virtio-net calls this when it wants us to fill iov with a packet. */
1476 int vnet_receive_packet(struct iovec *iov, int iovcnt)
1480 uth_mutex_lock(rx_mtx);
1482 rx_amt = __poll_injection(iov, iovcnt);
1485 rx_amt = __poll_inbound(iov, iovcnt);
1488 uth_cond_var_wait(rx_cv, rx_mtx);
1490 uth_mutex_unlock(rx_mtx);
1491 iov_trim_len_to(iov, iovcnt, rx_amt);
1493 writev(snoop_fd, iov, iovcnt);