public inbox for passt-dev@passt.top
 help / color / mirror / code / Atom feed
21e852af211c58c0cd6960c50e7c29d1a4a31704 blob 28913 bytes (raw)

   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
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
 
// SPDX-License-Identifier: GPL-2.0-or-later

/* PASST - Plug A Simple Socket Transport
 *  for qemu/UNIX domain socket mode
 *
 * PASTA - Pack A Subtle Tap Abstraction
 *  for network namespace/tap device mode
 *
 * fwd.c - Port forwarding helpers
 *
 * Copyright Red Hat
 * Author: Stefano Brivio <sbrivio@redhat.com>
 * Author: David Gibson <david@gibson.dropbear.id.au>
 */

#include <assert.h>
#include <stdint.h>
#include <errno.h>
#include <fcntl.h>
#include <sched.h>
#include <unistd.h>
#include <stdio.h>

#include "util.h"
#include "epoll_ctl.h"
#include "ip.h"
#include "siphash.h"
#include "inany.h"
#include "fwd.h"
#include "passt.h"
#include "lineread.h"
#include "flow_table.h"
#include "netlink.h"
#include "arp.h"
#include "ndp.h"

/* Ephemeral port range: values from RFC 6335 */
static in_port_t fwd_ephemeral_min = (1 << 15) + (1 << 14);
static in_port_t fwd_ephemeral_max = NUM_PORTS - 1;

#define PORT_RANGE_SYSCTL	"/proc/sys/net/ipv4/ip_local_port_range"

#define NEIGH_TABLE_SLOTS    1024
#define NEIGH_TABLE_SIZE     (NEIGH_TABLE_SLOTS / 2)
static_assert((NEIGH_TABLE_SLOTS & (NEIGH_TABLE_SLOTS - 1)) == 0,
	      "NEIGH_TABLE_SLOTS must be a power of two");

/**
 * struct neigh_table_entry - Entry in the ARP/NDP table
 * @next:	Next entry in slot or free list
 * @addr:	IP address of represented host
 * @mac:	MAC address of represented host
 * @permanent:	Entry cannot be altered or freed by notification
 */
struct neigh_table_entry {
	struct neigh_table_entry *next;
	union inany_addr addr;
	uint8_t mac[ETH_ALEN];
	bool permanent;
};

/**
 * struct neigh_table - Cache of ARP/NDP table contents
 * @entries:	Entries to be plugged into the hash slots when allocated
 * @slots:	Hash table slots
 * @free:	Linked list of unused entries
 */
struct neigh_table {
	struct neigh_table_entry entries[NEIGH_TABLE_SIZE];
	struct neigh_table_entry *slots[NEIGH_TABLE_SLOTS];
	struct neigh_table_entry *free;
};

static struct neigh_table neigh_table;

/**
 * neigh_table_slot() - Hash key to a number within the table range
 * @c:		Execution context
 * @key:	The key to be used for the hash
 *
 * Return: the resulting hash value
 */
static size_t neigh_table_slot(const struct ctx *c,
			       const union inany_addr *key)
{
	struct siphash_state st = SIPHASH_INIT(c->hash_secret);
	uint32_t i;

	inany_siphash_feed(&st, key);
	i = siphash_final(&st, sizeof(*key), 0);

	return ((size_t)i) & (NEIGH_TABLE_SIZE - 1);
}

/**
 * fwd_neigh_table_find() - Find a MAC table entry
 * @c:		Execution context
 * @addr:	Neighbour address to be used as key for the lookup
 *
 * Return: the matching entry, if found. Otherwise NULL
 */
static struct neigh_table_entry *fwd_neigh_table_find(const struct ctx *c,
						      const union inany_addr *addr)
{
	size_t slot = neigh_table_slot(c, addr);
	struct neigh_table_entry *e = neigh_table.slots[slot];

	while (e && !inany_equals(&e->addr, addr))
		e = e->next;

	return e;
}

/**
 * fwd_neigh_table_update() - Allocate or update neighbour table entry
 * @c:		Execution context
 * @addr:	IP address used to determine insertion slot and store in entry
 * @mac:	The MAC address associated with the neighbour address
 * @permanent:	Created entry cannot be altered or freed
 */
void fwd_neigh_table_update(const struct ctx *c, const union inany_addr *addr,
			    const uint8_t *mac, bool permanent)
{
	struct neigh_table *t = &neigh_table;
	struct neigh_table_entry *e;
	ssize_t slot;

	/* MAC address might change sometimes */
	e = fwd_neigh_table_find(c, addr);
	if (e) {
		if (!e->permanent)
			memcpy(e->mac, mac, ETH_ALEN);
		return;
	}

	e = t->free;
	if (!e) {
		debug("Failed to allocate neighbour table entry");
		return;
	}
	t->free = e->next;
	slot = neigh_table_slot(c, addr);
	e->next = t->slots[slot];
	t->slots[slot] = e;

	memcpy(&e->addr, addr, sizeof(*addr));
	memcpy(e->mac, mac, ETH_ALEN);
	e->permanent = permanent;

	if (!memcmp(mac, c->our_tap_mac, ETH_ALEN))
		return;

	if (inany_v4(addr))
		arp_announce(c, inany_v4(addr), e->mac);
	else
		ndp_unsolicited_na(c, &addr->a6);
}

/**
 * fwd_neigh_table_free() - Remove an entry from a slot and add it to free list
 * @c:		Execution context
 * @addr:	IP address used to find the slot for the entry
 */
void fwd_neigh_table_free(const struct ctx *c, const union inany_addr *addr)
{
	ssize_t slot = neigh_table_slot(c, addr);
	struct neigh_table *t = &neigh_table;
	struct neigh_table_entry *e, **prev;

	prev = &t->slots[slot];
	e = t->slots[slot];
	while (e && !inany_equals(&e->addr, addr)) {
		prev = &e->next;
		e = e->next;
	}

	if (!e || e->permanent)
		return;

	*prev = e->next;
	e->next = t->free;
	t->free = e;
	memset(&e->addr, 0, sizeof(*addr));
	memset(e->mac, 0, ETH_ALEN);
}

/**
 * fwd_neigh_mac_get() - Look up MAC address in the ARP/NDP table
 * @c:		Execution context
 * @addr:	Neighbour IP address used as lookup key
 * @mac:	Buffer for returned MAC address
 */
void fwd_neigh_mac_get(const struct ctx *c, const union inany_addr *addr,
		       uint8_t *mac)
{
	const struct neigh_table_entry *e = fwd_neigh_table_find(c, addr);

	if (!e) {
		union inany_addr ggw;

		if (inany_v4(addr))
			ggw = inany_from_v4(c->ip4.guest_gw);
		else
			ggw.a6 = c->ip6.guest_gw;

		e = fwd_neigh_table_find(c, &ggw);
	}

	if (e)
		memcpy(mac, e->mac, ETH_ALEN);
	else
		memcpy(mac, c->our_tap_mac, ETH_ALEN);
}

/**
 * fwd_neigh_table_init() - Initialize the neighbour table
 * @c:		Execution context
 */
void fwd_neigh_table_init(const struct ctx *c)
{
	union inany_addr mhl = inany_from_v4(c->ip4.map_host_loopback);
	union inany_addr mga = inany_from_v4(c->ip4.map_guest_addr);
	struct neigh_table *t = &neigh_table;
	struct neigh_table_entry *e;
	int i;

	memset(t, 0, sizeof(*t));

	for (i = 0; i < NEIGH_TABLE_SIZE; i++) {
		e = &t->entries[i];
		e->next = t->free;
		t->free = e;
	}

	/* Blocker entries to stop events from hosts using these addresses */
	if (!inany_is_unspecified4(&mhl))
		fwd_neigh_table_update(c, &mhl, c->our_tap_mac, true);

	if (!inany_is_unspecified4(&mga))
		fwd_neigh_table_update(c, &mga, c->our_tap_mac, true);

	mhl = *(union inany_addr *)&c->ip6.map_host_loopback;
	mga = *(union inany_addr *)&c->ip6.map_guest_addr;

	if (!inany_is_unspecified6(&mhl))
		fwd_neigh_table_update(c, &mhl, c->our_tap_mac, true);

	if (!inany_is_unspecified6(&mga))
		fwd_neigh_table_update(c, &mga, c->our_tap_mac, true);
}

/** fwd_probe_ephemeral() - Determine what ports this host considers ephemeral
 *
 * Work out what ports the host thinks are emphemeral and record it for later
 * use by fwd_port_is_ephemeral().  If we're unable to probe, assume the range
 * recommended by RFC 6335.
 */
void fwd_probe_ephemeral(void)
{
	char *line, *tab, *end;
	struct lineread lr;
	long min, max;
	ssize_t len;
	int fd;

	fd = open(PORT_RANGE_SYSCTL, O_RDONLY | O_CLOEXEC);
	if (fd < 0) {
		warn_perror("Unable to open %s", PORT_RANGE_SYSCTL);
		return;
	}

	lineread_init(&lr, fd);
	len = lineread_get(&lr, &line);
	close(fd);

	if (len < 0)
		goto parse_err;

	tab = strchr(line, '\t');
	if (!tab)
		goto parse_err;
	*tab = '\0';

	errno = 0;
	min = strtol(line, &end, 10);
	if (*end || errno)
		goto parse_err;

	errno = 0;
	max = strtol(tab + 1, &end, 10);
	if (*end || errno)
		goto parse_err;

	if (min < 0 || min >= (long)NUM_PORTS ||
	    max < 0 || max >= (long)NUM_PORTS)
		goto parse_err;

	fwd_ephemeral_min = min;
	fwd_ephemeral_max = max;

	return;

parse_err:
	warn("Unable to parse %s", PORT_RANGE_SYSCTL);
}

/**
 * fwd_port_is_ephemeral() - Is port number ephemeral?
 * @port:	Port number
 *
 * Return: true if @port is ephemeral, that is may be allocated by the kernel as
 *         a local port for outgoing connections or datagrams, but should not be
 *         used for binding services to.
 */
bool fwd_port_is_ephemeral(in_port_t port)
{
	return (port >= fwd_ephemeral_min) && (port <= fwd_ephemeral_max);
}

/**
 * fwd_table_add() - Add an entry to a forwarding table
 * @fwd:	Table to add to
 * @flags:	Flags for this entry
 * @addr:	Our address to forward (NULL for both 0.0.0.0 and ::)
 * @ifname:	Only forward from this interface name, if non-empty
 * @first:	First port number to forward
 * @last:	Last port number to forward
 * @to:		First port of target port range to map to
 */
void fwd_table_add(struct fwd_ports *fwd, uint8_t flags,
		   const union inany_addr *addr, const char *ifname,
		   in_port_t first, in_port_t last, in_port_t to)
{
	/* Flags which can be set from the caller */
	const uint8_t allowed_flags = FWD_WEAK | FWD_SCAN;
	unsigned num = (unsigned)last - first + 1, i;
	struct fwd_entry *new;

	ASSERT(!(flags & ~allowed_flags));

	if (fwd->count >= ARRAY_SIZE(fwd->tab))
		die("Too many port forwarding ranges");
	if ((fwd->listen_sock_count + num) > ARRAY_SIZE(fwd->listen_socks))
		die("Too many listening sockets");

	new = &fwd->tab[fwd->count++];
	new->flags = flags;

	if (addr) {
		new->addr = *addr;
	} else {
		new->addr = inany_any6;
		new->flags |= FWD_DUAL_STACK;
	}

	memset(new->ifname, 0, sizeof(new->ifname));
	if (ifname)
		strncpy(new->ifname, ifname, sizeof(new->ifname));

	ASSERT(first <= last);
	new->first = first;
	new->last = last;

	new->to = to;

	new->socks = &fwd->listen_socks[fwd->listen_sock_count];
	fwd->listen_sock_count += num;
	for (i = 0; i < num; i++)
		new->socks[i] = -1;
}

/**
 * fwd_table_print() - Print forwarding table for debugging
 * @fwd:	Table to print
 */
void fwd_table_print(const struct fwd_ports *fwd)
{
	unsigned i;

	for (i = 0; i < fwd->count; i++) {
		const struct fwd_entry *fe = &fwd->tab[i];
		const char *weak = fe->flags & FWD_WEAK ? " WEAK" : "";
		const char *scan = fe->flags & FWD_SCAN ? " AUTO" : "";
		const char *percent = *fe->ifname ? "%" : "";
		char addr[INANY_ADDRSTRLEN] = "*";

		if (!(fe->flags & FWD_DUAL_STACK))
			inany_ntop(&fe->addr, addr, sizeof(addr));

		if (fe->first == fe->last) {
			info("    [%s]%s%s:%hu  =>  %hu %s%s",
			     addr, percent, fe->ifname,
			     fe->first, fe->to, weak, scan);
		} else {
			info("    [%s]%s%s:%hu-%hu  =>  %hu-%hu %s%s",
			     addr, percent, fe->ifname, fe->first, fe->last,
			     fe->to, fe->last - fe->first + fe->to,
			     weak, scan);
		}
	}
}

/** fwd_sync_one() - Create or remove listening sockets for a forward entry
 * @c:		Execution context
 * @fe:		Forwarding entry
 * @pif:	Interface to create listening sockets for
 * @proto:	Protocol to listen for
 * @scanmap:	Bitmap of ports to listen for on FWD_SCAN entries
 */
static void fwd_sync_one(const struct ctx *c, const struct fwd_entry *fe,
			 uint8_t pif, uint8_t proto, const uint8_t *scanmap)
{
	const union inany_addr *addr = &fe->addr;
	const char *ifname = fe->ifname;
	bool bound_one = false;
	unsigned port;

	ASSERT(pif_is_socket(pif));

	if (fe->flags & FWD_DUAL_STACK)
		addr = NULL;
	if (!*ifname)
		ifname = NULL;

	for (port = fe->first; port <= fe->last; port++) {
		int fd = fe->socks[port - fe->first];

		if ((fe->flags & FWD_SCAN) && !bitmap_isset(scanmap, port)) {
			/* We don't want to listen on this port */
			if (fd >= 0) {
				/* We already are, so stop */
				epoll_del(c->epollfd, fd);
				close(fd);
				fe->socks[port - fe->first] = -1;
			}
			continue;
		}

		if (fd >= 0) /* Already listening, nothing to do */ {
			bound_one = true;
			continue;
		}

		if (proto == IPPROTO_TCP)
			fd = tcp_listen(c, pif, addr, ifname, port);
		else if (proto == IPPROTO_UDP)
			fd = udp_listen(c, pif, addr, ifname, port);
		else
			ASSERT(0);

		if (fd < 0) {
			char astr[INANY_ADDRSTRLEN] = "";

			if (addr)
				inany_ntop(addr, astr, sizeof(astr));

			warn("Listen failed for %s %s port %s%s%s%s%u: %s",
			     pif_name(pif), ipproto_name(proto),
			     astr, ifname ? "%" : "", ifname ? ifname : "",
			     addr || ifname ? "/" : "", port, strerror_(-fd));

			if (!(fe->flags & FWD_WEAK))
				goto die;

			continue;
		}

		fe->socks[port - fe->first] = fd;
		bound_one = true;
	}

	if (!bound_one && !(fe->flags & FWD_SCAN)) {
		char astr[INANY_ADDRSTRLEN] = "";

		if (addr)
			inany_ntop(addr, astr, sizeof(astr));

		err("All listens failed for %s %s %s%s%s%s%u-%u",
		    pif_name(pif), ipproto_name(proto),
		    astr, ifname ? "%" : "", ifname ? ifname : "",
		    addr || ifname ? "/" : "", fe->first, fe->last);
		goto die;
	}

	return;

die:
	die("Couldn't listen on requested %s ports", ipproto_name(proto));
}

/** struct fwd_listen_args - arguments for fwd_listen_init_()
 * @c:		Execution context
 * @fwd:	Forwarding information
 * @scanmap:	Bitmap of ports to auto-forward
 * @pif:	Interface to create listening sockets for
 * @proto:	Protocol
 */
struct fwd_listen_args {
	const struct ctx *c;
	const struct fwd_ports *fwd;
	const uint8_t *scanmap;
	uint8_t pif;
	uint8_t proto;
};

/** fwd_listen_sync_() - Update listening sockets to match forwards
 * @arg:	struct fwd_listen_args with arguments
 *
 * Returns: zero
 */
static int fwd_listen_sync_(void *arg)
{
	const struct fwd_listen_args *a = arg;
	unsigned i;

	if (a->pif == PIF_SPLICE)
		ns_enter(a->c);

	for (i = 0; i < a->fwd->count; i++)
		fwd_sync_one(a->c, &a->fwd->tab[i], a->pif, a->proto,
			     a->fwd->map);

	return 0;
}

/** fwd_listen_sync() - Update listening sockets to match forwards
 * @c:		Execution context
 * @fwd:	Forwarding information
 * @pif:	Interface to create listening sockets for
 * @proto:	Protocol
 */
void fwd_listen_sync(const struct ctx *c, const struct fwd_ports *fwd,
		     uint8_t pif, uint8_t proto)
{
	struct fwd_listen_args a = {
		.c = c, .fwd = fwd, .pif = pif, .proto = proto,
	};

	if (pif == PIF_SPLICE)
		NS_CALL(fwd_listen_sync_, &a);
	else
		fwd_listen_sync_(&a);
}

/* See enum in kernel's include/net/tcp_states.h */
#define UDP_LISTEN	0x07
#define TCP_LISTEN	0x0a

/**
 * procfs_scan_listen() - Set bits for listening TCP or UDP sockets from procfs
 * @fd:		fd for relevant /proc/net file
 * @lstate:	Code for listening state to scan for
 * @map:	Bitmap where numbers of ports in listening state will be set
 *
 * #syscalls:pasta lseek
 * #syscalls:pasta ppc64le:_llseek ppc64:_llseek arm:_llseek
 */
static void procfs_scan_listen(int fd, unsigned int lstate, uint8_t *map)
{
	struct lineread lr;
	unsigned long port;
	unsigned int state;
	char *line;

	if (fd < 0)
		return;

	if (lseek(fd, 0, SEEK_SET)) {
		warn_perror("lseek() failed on /proc/net file");
		return;
	}

	lineread_init(&lr, fd);
	lineread_get(&lr, &line); /* throw away header */
	while (lineread_get(&lr, &line) > 0) {
		/* NOLINTNEXTLINE(cert-err34-c): != 2 if conversion fails */
		if (sscanf(line, "%*u: %*x:%lx %*x:%*x %x", &port, &state) != 2)
			continue;

		if (state != lstate)
			continue;

		bitmap_set(map, port);
	}
}

/**
 * fwd_scan_ports_tcp() - Scan /proc to update TCP forwarding map
 * @fwd:	Forwarding information to update
 * @exclude:	Ports to _not_ forward
 */
static void fwd_scan_ports_tcp(struct fwd_ports *fwd, const uint8_t *exclude)
{
	if (fwd->mode != FWD_AUTO)
		return;

	memset(fwd->map, 0, PORT_BITMAP_SIZE);
	procfs_scan_listen(fwd->scan4, TCP_LISTEN, fwd->map);
	procfs_scan_listen(fwd->scan6, TCP_LISTEN, fwd->map);
	bitmap_and_not(fwd->map, PORT_BITMAP_SIZE, fwd->map, exclude);
}

/**
 * fwd_scan_ports_udp() - Scan /proc to update UDP forwarding map
 * @fwd:	Forwarding information to update
 * @tcp_fwd:	Corresponding TCP forwarding information
 * @exclude:	Ports to _not_ forward
 */
static void fwd_scan_ports_udp(struct fwd_ports *fwd,
			       const struct fwd_ports *tcp_fwd,
			       const uint8_t *exclude)
{
	if (fwd->mode != FWD_AUTO)
		return;

	memset(fwd->map, 0, PORT_BITMAP_SIZE);
	procfs_scan_listen(fwd->scan4, UDP_LISTEN, fwd->map);
	procfs_scan_listen(fwd->scan6, UDP_LISTEN, fwd->map);

	/* Also forward UDP ports with the same numbers as bound TCP ports.
	 * This is useful for a handful of protocols (e.g. iperf3) where a TCP
	 * control port is used to set up transfers on a corresponding UDP
	 * port.
	 */
	procfs_scan_listen(tcp_fwd->scan4, TCP_LISTEN, fwd->map);
	procfs_scan_listen(tcp_fwd->scan6, TCP_LISTEN, fwd->map);

	bitmap_and_not(fwd->map, PORT_BITMAP_SIZE, fwd->map, exclude);
}

/**
 * fwd_scan_ports() - Scan automatic port forwarding information
 * @c:		Execution context
 */
static void fwd_scan_ports(struct ctx *c)
{
	uint8_t excl_tcp_out[PORT_BITMAP_SIZE], excl_udp_out[PORT_BITMAP_SIZE];
	uint8_t excl_tcp_in[PORT_BITMAP_SIZE], excl_udp_in[PORT_BITMAP_SIZE];

	memcpy(excl_tcp_out, c->tcp.fwd_in.map, sizeof(excl_tcp_out));
	memcpy(excl_tcp_in, c->tcp.fwd_out.map, sizeof(excl_tcp_in));
	memcpy(excl_udp_out, c->udp.fwd_in.map, sizeof(excl_udp_out));
	memcpy(excl_udp_in, c->udp.fwd_out.map, sizeof(excl_udp_in));

	fwd_scan_ports_tcp(&c->tcp.fwd_out, excl_tcp_out);
	fwd_scan_ports_tcp(&c->tcp.fwd_in, excl_tcp_in);
	fwd_scan_ports_udp(&c->udp.fwd_out, &c->tcp.fwd_out, excl_udp_out);
	fwd_scan_ports_udp(&c->udp.fwd_in, &c->tcp.fwd_in, excl_udp_in);
}

/**
 * fwd_scan_ports_init() - Initial setup for port forwarding
 * @c:		Execution context
 */
void fwd_scan_ports_init(struct ctx *c)
{
	const int flags = O_RDONLY | O_CLOEXEC;

	c->tcp.fwd_in.scan4 = c->tcp.fwd_in.scan6 = -1;
	c->tcp.fwd_out.scan4 = c->tcp.fwd_out.scan6 = -1;
	c->udp.fwd_in.scan4 = c->udp.fwd_in.scan6 = -1;
	c->udp.fwd_out.scan4 = c->udp.fwd_out.scan6 = -1;

	if (c->tcp.fwd_in.mode == FWD_AUTO) {
		c->tcp.fwd_in.scan4 = open_in_ns(c, "/proc/net/tcp", flags);
		c->tcp.fwd_in.scan6 = open_in_ns(c, "/proc/net/tcp6", flags);
	}
	if (c->udp.fwd_in.mode == FWD_AUTO) {
		c->udp.fwd_in.scan4 = open_in_ns(c, "/proc/net/udp", flags);
		c->udp.fwd_in.scan6 = open_in_ns(c, "/proc/net/udp6", flags);
	}
	if (c->tcp.fwd_out.mode == FWD_AUTO) {
		c->tcp.fwd_out.scan4 = open("/proc/net/tcp", flags);
		c->tcp.fwd_out.scan6 = open("/proc/net/tcp6", flags);
	}
	if (c->udp.fwd_out.mode == FWD_AUTO) {
		c->udp.fwd_out.scan4 = open("/proc/net/udp", flags);
		c->udp.fwd_out.scan6 = open("/proc/net/udp6", flags);
	}
	fwd_scan_ports(c);
}

/* Last time we scanned for open ports */
static struct timespec scan_ports_run;

/**
 * fwd_scan_ports_timer() - Rescan open port information when necessary
 * @c:		Execution context
 * @now:	Current (monotonic) time
 */
void fwd_scan_ports_timer(struct ctx *c, const struct timespec *now)
{
	if (c->mode != MODE_PASTA)
		return;

	if (timespec_diff_ms(now, &scan_ports_run) < FWD_PORT_SCAN_INTERVAL)
		return;

	scan_ports_run = *now;

	fwd_scan_ports(c);

	if (!c->no_tcp) {
		fwd_listen_sync(c, &c->tcp.fwd_in, PIF_HOST, IPPROTO_TCP);
		fwd_listen_sync(c, &c->tcp.fwd_out, PIF_SPLICE, IPPROTO_TCP);
	}
	if (!c->no_udp) {
		fwd_listen_sync(c, &c->udp.fwd_in, PIF_HOST, IPPROTO_UDP);
		fwd_listen_sync(c, &c->udp.fwd_out, PIF_SPLICE, IPPROTO_UDP);
	}
}

/**
 * is_dns_flow() - Determine if flow appears to be a DNS request
 * @proto:	Protocol (IP L4 protocol number)
 * @ini:	Flow address information of the initiating side
 *
 * Return: true if the flow appears to be directed at a dns server, that is a
 *         TCP or UDP flow to port 53 (domain) or port 853 (domain-s)
 */
static bool is_dns_flow(uint8_t proto, const struct flowside *ini)
{
	return ((proto == IPPROTO_UDP) || (proto == IPPROTO_TCP)) &&
		((ini->oport == 53) || (ini->oport == 853));
}

/**
 * fwd_guest_accessible4() - Is IPv4 address guest-accessible
 * @c:		Execution context
 * @addr:	Host visible IPv4 address
 *
 * Return: true if @addr on the host is accessible to the guest without
 *         translation, false otherwise
 */
static bool fwd_guest_accessible4(const struct ctx *c,
				    const struct in_addr *addr)
{
	if (IN4_IS_ADDR_LOOPBACK(addr))
		return false;

	/* In socket interfaces 0.0.0.0 generally means "any" or unspecified,
	 * however on the wire it can mean "this host on this network".  Since
	 * that has a different meaning for host and guest, we can't let it
	 * through untranslated.
	 */
	if (IN4_IS_ADDR_UNSPECIFIED(addr))
		return false;

	/* For IPv4, addr_seen is initialised to addr, so is always a valid
	 * address
	 */
	if (IN4_ARE_ADDR_EQUAL(addr, &c->ip4.addr) ||
	    IN4_ARE_ADDR_EQUAL(addr, &c->ip4.addr_seen))
		return false;

	return true;
}

/**
 * fwd_guest_accessible6() - Is IPv6 address guest-accessible
 * @c:		Execution context
 * @addr:	Host visible IPv6 address
 *
 * Return: true if @addr on the host is accessible to the guest without
 *         translation, false otherwise
 */
static bool fwd_guest_accessible6(const struct ctx *c,
				  const struct in6_addr *addr)
{
	if (IN6_IS_ADDR_LOOPBACK(addr))
		return false;

	if (IN6_ARE_ADDR_EQUAL(addr, &c->ip6.addr))
		return false;

	/* For IPv6, addr_seen starts unspecified, because we don't know what LL
	 * address the guest will take until we see it.  Only check against it
	 * if it has been set to a real address.
	 */
	if (!IN6_IS_ADDR_UNSPECIFIED(&c->ip6.addr_seen) &&
	    IN6_ARE_ADDR_EQUAL(addr, &c->ip6.addr_seen))
		return false;

	return true;
}

/**
 * fwd_guest_accessible() - Is IPv[46] address guest-accessible
 * @c:		Execution context
 * @addr:	Host visible IPv[46] address
 *
 * Return: true if @addr on the host is accessible to the guest without
 *         translation, false otherwise
 */
static bool fwd_guest_accessible(const struct ctx *c,
				 const union inany_addr *addr)
{
	const struct in_addr *a4 = inany_v4(addr);

	if (a4)
		return fwd_guest_accessible4(c, a4);

	return fwd_guest_accessible6(c, &addr->a6);
}

/**
 * nat_outbound() - Apply address translation for outbound (TAP to HOST)
 * @c:		Execution context
 * @addr:	Input address (as seen on TAP interface)
 * @translated:	Output address (as seen on HOST interface)
 *
 * Only handles translations that depend *only* on the address.  Anything
 * related to specific ports or flows is handled elsewhere.
 */
static void nat_outbound(const struct ctx *c, const union inany_addr *addr,
			 union inany_addr *translated)
{
	if (inany_equals4(addr, &c->ip4.map_host_loopback))
		*translated = inany_loopback4;
	else if (inany_equals6(addr, &c->ip6.map_host_loopback))
		*translated = inany_loopback6;
	else if (inany_equals4(addr, &c->ip4.map_guest_addr))
		*translated = inany_from_v4(c->ip4.addr);
	else if (inany_equals6(addr, &c->ip6.map_guest_addr))
		translated->a6 = c->ip6.addr;
	else
		*translated = *addr;
}

/**
 * fwd_nat_from_tap() - Determine to forward a flow from the tap interface
 * @c:		Execution context
 * @proto:	Protocol (IP L4 protocol number)
 * @ini:	Flow address information of the initiating side
 * @tgt:	Flow address information on the target side (updated)
 *
 * Return: pif of the target interface to forward the flow to, PIF_NONE if the
 *         flow cannot or should not be forwarded at all.
 */
uint8_t fwd_nat_from_tap(const struct ctx *c, uint8_t proto,
			 const struct flowside *ini, struct flowside *tgt)
{
	if (is_dns_flow(proto, ini) &&
	    inany_equals4(&ini->oaddr, &c->ip4.dns_match))
		tgt->eaddr = inany_from_v4(c->ip4.dns_host);
	else if (is_dns_flow(proto, ini) &&
		   inany_equals6(&ini->oaddr, &c->ip6.dns_match))
		tgt->eaddr.a6 = c->ip6.dns_host;
	else
		nat_outbound(c, &ini->oaddr, &tgt->eaddr);

	tgt->eport = ini->oport;

	/* The relevant addr_out controls the host side source address.  This
	 * may be unspecified, which allows the kernel to pick an address.
	 */
	if (inany_v4(&tgt->eaddr))
		tgt->oaddr = inany_from_v4(c->ip4.addr_out);
	else
		tgt->oaddr.a6 = c->ip6.addr_out;

	/* Let the kernel pick a host side source port */
	tgt->oport = 0;
	if (proto == IPPROTO_UDP) {
		/* But for UDP we preserve the source port */
		tgt->oport = ini->eport;
	}

	return PIF_HOST;
}

/**
 * fwd_nat_from_splice() - Determine to forward a flow from the splice interface
 * @c:		Execution context
 * @proto:	Protocol (IP L4 protocol number)
 * @ini:	Flow address information of the initiating side
 * @tgt:	Flow address information on the target side (updated)
 *
 * Return: pif of the target interface to forward the flow to, PIF_NONE if the
 *         flow cannot or should not be forwarded at all.
 */
uint8_t fwd_nat_from_splice(const struct ctx *c, uint8_t proto,
			    const struct flowside *ini, struct flowside *tgt)
{
	if (!inany_is_loopback(&ini->eaddr) ||
	    (!inany_is_loopback(&ini->oaddr) && !inany_is_unspecified(&ini->oaddr))) {
		char estr[INANY_ADDRSTRLEN], fstr[INANY_ADDRSTRLEN];

		debug("Non loopback address on %s: [%s]:%hu -> [%s]:%hu",
		      pif_name(PIF_SPLICE),
		      inany_ntop(&ini->eaddr, estr, sizeof(estr)), ini->eport,
		      inany_ntop(&ini->oaddr, fstr, sizeof(fstr)), ini->oport);
		return PIF_NONE;
	}

	if (!inany_is_unspecified(&ini->oaddr))
		tgt->eaddr = ini->oaddr;
	else if (inany_v4(&ini->oaddr))
		tgt->eaddr = inany_loopback4;
	else
		tgt->eaddr = inany_loopback6;

	/* Preserve the specific loopback address used, but let the kernel pick
	 * a source port on the target side
	 */
	tgt->oaddr = ini->eaddr;
	tgt->oport = 0;

	tgt->eport = ini->oport;
	if (proto == IPPROTO_TCP)
		tgt->eport += c->tcp.fwd_out.delta[tgt->eport];
	else if (proto == IPPROTO_UDP)
		tgt->eport += c->udp.fwd_out.delta[tgt->eport];

	/* Let the kernel pick a host side source port */
	tgt->oport = 0;
	if (proto == IPPROTO_UDP)
		/* But for UDP preserve the source port */
		tgt->oport = ini->eport;

	return PIF_HOST;
}

/**
 * nat_inbound() - Apply address translation for inbound (HOST to TAP)
 * @c:		Execution context
 * @addr:	Input address (as seen on HOST interface)
 * @translated:	Output address (as seen on TAP interface)
 *
 * Return: true on success, false if it couldn't translate the address
 *
 * Only handles translations that depend *only* on the address.  Anything
 * related to specific ports or flows is handled elsewhere.
 */
bool nat_inbound(const struct ctx *c, const union inany_addr *addr,
		 union inany_addr *translated)
{
	if (!IN4_IS_ADDR_UNSPECIFIED(&c->ip4.map_host_loopback) &&
	    inany_equals4(addr, &in4addr_loopback)) {
		/* Specifically 127.0.0.1, not 127.0.0.0/8 */
		*translated = inany_from_v4(c->ip4.map_host_loopback);
	} else if (!IN6_IS_ADDR_UNSPECIFIED(&c->ip6.map_host_loopback) &&
		   inany_equals6(addr, &in6addr_loopback)) {
		translated->a6 = c->ip6.map_host_loopback;
	} else if (!IN4_IS_ADDR_UNSPECIFIED(&c->ip4.map_guest_addr) &&
		   inany_equals4(addr, &c->ip4.addr)) {
		*translated = inany_from_v4(c->ip4.map_guest_addr);
	} else if (!IN6_IS_ADDR_UNSPECIFIED(&c->ip6.map_guest_addr) &&
		   inany_equals6(addr, &c->ip6.addr)) {
		translated->a6 = c->ip6.map_guest_addr;
	} else if (fwd_guest_accessible(c, addr)) {
		*translated = *addr;
	} else {
		return false;
	}

	return true;
}

/**
 * fwd_nat_from_host() - Determine to forward a flow from the host interface
 * @c:		Execution context
 * @proto:	Protocol (IP L4 protocol number)
 * @ini:	Flow address information of the initiating side
 * @tgt:	Flow address information on the target side (updated)
 *
 * Return: pif of the target interface to forward the flow to, PIF_NONE if the
 *         flow cannot or should not be forwarded at all.
 */
uint8_t fwd_nat_from_host(const struct ctx *c, uint8_t proto,
			  const struct flowside *ini, struct flowside *tgt)
{
	/* Common for spliced and non-spliced cases */
	tgt->eport = ini->oport;
	if (proto == IPPROTO_TCP)
		tgt->eport += c->tcp.fwd_in.delta[tgt->eport];
	else if (proto == IPPROTO_UDP)
		tgt->eport += c->udp.fwd_in.delta[tgt->eport];

	if (!c->no_splice && inany_is_loopback(&ini->eaddr) &&
	    (proto == IPPROTO_TCP || proto == IPPROTO_UDP)) {
		/* spliceable */

		/* The traffic will go over the guest's 'lo' interface, but by
		 * default use its external address, so we don't inadvertently
		 * expose services that listen only on the guest's loopback
		 * address.  That can be overridden by --host-lo-to-ns-lo which
		 * will instead forward to the loopback address in the guest.
		 *
		 * In either case, let the kernel pick the source address to
		 * match.
		 */
		if (inany_v4(&ini->eaddr)) {
			if (c->host_lo_to_ns_lo)
				tgt->eaddr = inany_loopback4;
			else
				tgt->eaddr = inany_from_v4(c->ip4.addr_seen);
			tgt->oaddr = inany_any4;
		} else {
			if (c->host_lo_to_ns_lo)
				tgt->eaddr = inany_loopback6;
			else
				tgt->eaddr.a6 = c->ip6.addr_seen;
			tgt->oaddr = inany_any6;
		}

		/* Let the kernel pick source port */
		tgt->oport = 0;
		if (proto == IPPROTO_UDP)
			/* But for UDP preserve the source port */
			tgt->oport = ini->eport;

		return PIF_SPLICE;
	}

	if (!nat_inbound(c, &ini->eaddr, &tgt->oaddr)) {
		if (inany_v4(&ini->eaddr)) {
			if (IN4_IS_ADDR_UNSPECIFIED(&c->ip4.our_tap_addr))
				/* No source address we can use */
				return PIF_NONE;
			tgt->oaddr = inany_from_v4(c->ip4.our_tap_addr);
		} else {
			tgt->oaddr.a6 = c->ip6.our_tap_ll;
		}
	}
	tgt->oport = ini->eport;

	if (inany_v4(&tgt->oaddr)) {
		tgt->eaddr = inany_from_v4(c->ip4.addr_seen);
	} else {
		if (inany_is_linklocal6(&tgt->oaddr))
			tgt->eaddr.a6 = c->ip6.addr_ll_seen;
		else
			tgt->eaddr.a6 = c->ip6.addr_seen;
	}

	return PIF_TAP;
}
debug log:

solving 21e852af ...
found 21e852af in https://archives.passt.top/passt-dev/20251219141904.1758072-10-david@gibson.dropbear.id.au/
found 5215cee9 in https://archives.passt.top/passt-dev/20251219141904.1758072-8-david@gibson.dropbear.id.au/
found 5e5dc58c in https://archives.passt.top/passt-dev/20251219141904.1758072-6-david@gibson.dropbear.id.au/
found a8477607 in https://archives.passt.top/passt-dev/20251219141904.1758072-4-david@gibson.dropbear.id.au/
found 44a0e109 in https://passt.top/passt
preparing index
index prepared:
100644 44a0e1096971c2d114edb80c58094563a1a044d9	fwd.c

applying [1/4] https://archives.passt.top/passt-dev/20251219141904.1758072-4-david@gibson.dropbear.id.au/
diff --git a/fwd.c b/fwd.c
index 44a0e109..a8477607 100644


applying [2/4] https://archives.passt.top/passt-dev/20251219141904.1758072-6-david@gibson.dropbear.id.au/
diff --git a/fwd.c b/fwd.c
index a8477607..5e5dc58c 100644


applying [3/4] https://archives.passt.top/passt-dev/20251219141904.1758072-8-david@gibson.dropbear.id.au/
diff --git a/fwd.c b/fwd.c
index 5e5dc58c..5215cee9 100644


applying [4/4] https://archives.passt.top/passt-dev/20251219141904.1758072-10-david@gibson.dropbear.id.au/
diff --git a/fwd.c b/fwd.c
index 5215cee9..21e852af 100644

Checking patch fwd.c...
Applied patch fwd.c cleanly.
Checking patch fwd.c...
Applied patch fwd.c cleanly.
Checking patch fwd.c...
Applied patch fwd.c cleanly.
Checking patch fwd.c...
Applied patch fwd.c cleanly.

index at:
100644 21e852af211c58c0cd6960c50e7c29d1a4a31704	fwd.c

Code repositories for project(s) associated with this public inbox

	https://passt.top/passt

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for IMAP folder(s).