get TCP/UDP ports from skb

From: Thorsten Glaser <hidden>
Date: 2022-06-04 22:41:31

Hi,

is there some kind of helper function to obtain the port numbers
from an skb if it’s TCP or UDP?

I know I can do…

switch (skb->protocol) {
case cpu_to_be16(ETH_P_IP):
	/* IPv4 */
	if (skb_network_header(skb) + sizeof(struct iphdr) >
	    skb_tail_pointer(skb))
		goto noaddress;

	// copy IP address from ip_hdr(skb)->saddr and daddr

	switch (ip_hdr(skb)->protocol) {
	case /* TCP */ 6:
		if (skb_transport_header(skb) + sizeof(struct tcphdr) >
		    skb_tail_pointer(skb))
			goto no_nexthdr;
		sport = ntohs(tcp_hdr(skb)->source);
		dport = ntohs(tcp_hdr(skb)->dest);
		break;
	case /* UDP */ 17:
		if (skb_transport_header(skb) + sizeof(struct udphdr) >
		    skb_tail_pointer(skb))
			goto no_nexthdr;
		sport = ntohs(udp_hdr(skb)->source);
		dport = ntohs(udp_hdr(skb)->dest);
		break;
	// default, no_nexthdr here
	}

	//…
	break;

case cpu_to_be16(ETH_P_IPV6):
	/* IPv6 */
	if (skb_network_header(skb) + sizeof(struct ipv6hdr) >
	    skb_tail_pointer(skb))
		goto noaddress;

	// copy IP address from ipv6_hdr(skb)->saddr.s6_addr and daddr

	nexthdr = ipv6_hdr(skb)->nexthdr;

	↑↑↑↑↑↑↑

But I’m lost-ish at this point: nexthdr can be an extension header,
and it’s seemingly not documented whether skb_transport_header(skb)
is the address of the extension header or the address of the OSI L4
protocol that follows, either.

Do I need to do manual packet parsing here?

Can I somehow use the “flow dissector” thing, which is already used
to hash the skb into an (fq_codel) flow, to obtain IP/port? (If it’s
not IPv4/IPv6, I just need to know that; if it’s IPv4/IPv6 but not
TCP or UDP, same.)

The code is run in dequeue and drop context of a patched fq_codel
qdisc, for monitoring purposes, using relayfs/debugfs, in case that
matters.

Thanks in advance,
//mirabilos
-- 
Infrastrukturexperte • tarent solutions GmbH
Am Dickobskreuz 10, D-53121 Bonn • http://www.tarent.de/
Telephon +49 228 54881-393 • Fax: +49 228 54881-235
HRB AG Bonn 5168 • USt-ID (VAT): DE122264941
Geschäftsführer: Dr. Stefan Barth, Kai Ebenrett, Boris Esser, Alexander Steeg

                        ****************************************************
/⁀\ The UTF-8 Ribbon
╲ ╱ Campaign against      Mit dem tarent-Newsletter nichts mehr verpassen:
 ╳  HTML eMail! Also,     https://www.tarent.de/newsletter
╱ ╲ header encryption!
                        ****************************************************
Keyboard shortcuts
hback out one level
jnext message in thread
kprevious message in thread
ldrill in
Escclose help / fold thread tree
?toggle this help