RFC 3542
Advanced Sockets Application Program Interface (API) for IPv6
RFC 3542: Advanced Sockets Application Program Interface (API) for IPv6 β¨
Okay bestie, let's get into RFC 3542 π¦ It's an Informational RFC from the Network Working Group, published in May 2003. The authors are W. Stevens, M. Thomas (a consultant), E. Nordmark (from Sun), and T. Jinmei (from Toshiba). It obsoletes RFC 2292, and its title block doesn't list anything it updates π
Status of this Memo πΈ
Quick vibe check: this memo is just information for the Internet community. It is not an Internet standard of any kind π And distribution of this memo is unlimited, so share it with everyone π«Ά
Copyright Notice π
Copyright (C) The Internet Society (2003). All Rights Reserved.
Abstract π₯
Okay so this doc gives you a sockets API for "advanced" IPv6 apps, as a supplement to a separate spec, RFC 3493 β¨ The main apps it's thinking about are Ping, Traceroute, and routing daemons, the ones that usually use raw sockets to poke at IPv6 or ICMPv6 header fields. It proposes some portable interfaces for apps that use raw sockets under IPv6 π
There are other IPv6 features some apps need to access too, like interface identification (choosing the outgoing interface and figuring out the incoming one), IPv6 extension headers, and path Maximum Transmission Unit (MTU) information. This doc gives API access to all of those π
Also, some extended interfaces to libraries for the "r" commands are defined. That gives better backward compatibility to existing implementations that aren't IPv6-capable, which is iconic behaviour from a spec π
Table of Contents π§
1. Introduction .............................................. 3
2. Common Structures and Definitions ......................... 5
2.1 The ip6_hdr Structure ................................ 6
2.1.1 IPv6 Next Header Values ....................... 6
2.1.2 IPv6 Extension Headers ........................ 7
2.1.3 IPv6 Options .................................. 8
2.2 The icmp6_hdr Structure .............................. 10
2.2.1 ICMPv6 Type and Code Values ................... 10
2.2.2 ICMPv6 Neighbor Discovery Definitions ......... 11
2.2.3 Multicast Listener Discovery Definitions ...... 14
2.2.4 ICMPv6 Router Renumbering Definitions ......... 14
2.3 Address Testing Macros ............................... 16
2.4 Protocols File ....................................... 16
3. IPv6 Raw Sockets .......................................... 17
3.1 Checksums ............................................ 18
3.2 ICMPv6 Type Filtering ................................ 19
3.3 ICMPv6 Verification of Received Packets .............. 22
4. Access to IPv6 and Extension Headers ...................... 22
4.1 TCP Implications ..................................... 24
4.2 UDP and Raw Socket Implications ...................... 25
5. Extensions to Socket Ancillary Data ....................... 26
5.1 CMSG_NXTHDR .......................................... 26
5.2 CMSG_SPACE ........................................... 26
5.3 CMSG_LEN ............................................. 27
6. Packet Information ........................................ 27
6.1 Specifying/Receiving the Interface ................... 28
6.2 Specifying/Receiving Source/Destination Address ...... 29
6.3 Specifying/Receiving the Hop Limit ................... 29
6.4 Specifying the Next Hop Address ...................... 30
6.5 Specifying/Receiving the Traffic Class value ......... 31
6.6 Additional Errors with sendmsg() and setsockopt() .... 32
6.7 Summary of Outgoing Interface Selection .............. 32
7. Routing Header Option ..................................... 33
7.1 inet6_rth_space ...................................... 35
7.2 inet6_rth_init ....................................... 35
7.3 inet6_rth_add ........................................ 36
7.4 inet6_rth_reverse .................................... 36
7.5 inet6_rth_segments ................................... 36
7.6 inet6_rth_getaddr .................................... 36
8. Hop-By-Hop Options ........................................ 37
8.1 Receiving Hop-by-Hop Options ......................... 38
8.2 Sending Hop-by-Hop Options ........................... 38
9. Destination Options ....................................... 39
9.1 Receiving Destination Options ........................ 39
9.2 Sending Destination Options .......................... 39
10. Hop-by-Hop and Destination Options Processing ............. 40
10.1 inet6_opt_init ...................................... 41
10.2 inet6_opt_append .................................... 41
10.3 inet6_opt_finish .................................... 42
10.4 inet6_opt_set_val ................................... 42
10.5 inet6_opt_next ...................................... 42
10.6 inet6_opt_find ...................................... 43
10.7 inet6_opt_get_val ................................... 43
11. Additional Advanced API Functions ......................... 44
11.1 Sending with the Minimum MTU ........................ 44
11.2 Sending without Fragmentation ....................... 45
11.3 Path MTU Discovery and UDP .......................... 46
11.4 Determining the Current Path MTU .................... 47
12. Ordering of Ancillary Data and IPv6 Extension Headers ..... 48
13. IPv6-Specific Options with IPv4-Mapped IPv6 Addresses ..... 50
14. Extended interfaces for rresvport, rcmd and rexec ......... 51
14.1 rresvport_af ........................................ 51
14.2 rcmd_af ............................................. 51
14.3 rexec_af ............................................ 52
15. Summary of New Definitions ................................ 52
16. Security Considerations ................................... 56
17. Changes from RFC 2292 ..................................... 57
18. References ................................................ 59
19. Acknowledgments ........................................... 59
20. Appendix A: Ancillary Data Overview ....................... 60
20.1 The msghdr Structure ................................ 60
20.2 The cmsghdr Structure ............................... 61
20.3 Ancillary Data Object Macros ........................ 62
20.3.1 CMSG_FIRSTHDR ............................... 63
20.3.2 CMSG_NXTHDR ................................. 64
20.3.3 CMSG_DATA ................................... 65
20.3.4 CMSG_SPACE .................................. 65
20.3.5 CMSG_LEN .................................... 65
21. Appendix B: Examples Using the inet6_rth_XXX() Functions .. 65
21.1 Sending a Routing Header ............................ 65
21.2 Receiving Routing Headers ........................... 70
22. Appendix C: Examples Using the inet6_opt_XXX() Functions .. 72
22.1 Building Options .................................... 72
22.2 Parsing Received Options ............................ 74
23. Authors' Addresses ........................................ 76
24. Full Copyright Statement .................................. 77
Part 1 of 16 π More coming, so stay tuned π
1. Introduction β¨
okay so bestie, RFC 3493 is the separate spec that changes the sockets API so it can handle IP version 6. π¦ Those changes are for TCP and UDP based apps. This doc is all about the "advanced" sockets features that apps need if they want the extra IPv6 goodies. π
Now here's the tea. Right now, IPv4 raw sockets are super portable, and that's mostly because nearly every IPv4 stack started from the same Berkeley source code (or at least the same Berkeley header files). π That's how programs like Ping and Traceroute can compile with barely any effort on tons of hosts that support the sockets API. With IPv6 though, there's no shared source code base that implementors are starting from, so the chance of things drifting apart between implementations is high. π To stop raw IPv6 socket apps from being a total portability disaster, some standardization is necessary. Literally a must.
There are also features from the basic IPv6 spec that RFC 3493 doesn't cover. Those are sending and receiving Routing headers, Hop-by-Hop options, and Destination options, plus specifying the outgoing interface, being told the receiving interface, and controlling path MTU information. π§
This document updates and replaces RFC 2292. This revision is based on implementation experience with RFC 2292, plus some extra extensions that turned out to be useful during IPv6 deployment. β¨ Heads up though: further work on this document may still be needed. Once the API spec gets mature and is deployed among implementations, it may be formally standardized by a more appropriate body, the same way the Basic API got standardized in [RFC-3493]. π
This document can be divided into the following main sections. π
- Definitions of the basic constants and structures required for applications to use raw IPv6 sockets. This includes structure definitions for the IPv6 and ICMPv6 headers and all associated constants (e.g., values for the Next Header field).
- Some basic semantic definitions for IPv6 raw sockets. For example, a raw ICMPv4 socket requires the application to calculate and store the ICMPv4 header checksum. But with IPv6 this would require the application to choose the source IPv6 address, because the source address is part of the pseudo header that ICMPv6 now uses for its checksum computation. It should be defined that with a raw ICMPv6 socket the kernel always calculates and stores the ICMPv6 header checksum. π₯
- Packet information: how applications can obtain the received interface, destination address, and received hop limit, along with specifying these values on a per-packet basis. There are a class of applications that need this capability, and the technique should be portable. π
- Access to the optional Routing header, Hop-by-Hop options, and Destination options extension headers. π«Ά
- Additional features required for improved IPv6 application portability. π
The packet information, along with access to the extension headers (Routing header, Hop-by-Hop options, and Destination options), is specified using the "ancillary data" fields that were added to the 4.3BSD Reno sockets API in 1990. π The reason is that these ancillary data fields are part of the Posix standard [POSIX], so most vendors should adopt them.
This document does not address application access to either the authentication header or the encapsulating security payload header. π₯Ί
Many examples in this document omit error checking in favor of brevity and clarity. π
We note that some of the functions and socket options defined in this document may have error returns that are not defined in this document. Some of these possible error returns will be recognized only as implementations proceed. π
Datatypes in this document follow the Posix format: intN_t means a signed integer of exactly N bits (e.g., int16_t), and uintN_t means an unsigned integer of exactly N bits (e.g., uint32_t). π€
Note that we use the (unofficial) terminology ICMPv4, IGMPv4, and ARPv4 to avoid any confusion with the newer ICMPv6 protocol. πΈ
2. Common Structures and Definitions β¨
Many advanced apps examine fields in the IPv6 header, and set and examine fields in the various ICMPv6 headers. π So common structure definitions for these protocol headers are required, along with common constant definitions for the structure members. π
This API assumes that the fields in the protocol headers are left in the network byte order, which is big-endian for the Internet protocols. If not, then either these constants or the fields being tested must be converted at run-time, using something like htons() or htonl(). π₯
Two new header files are defined: <netinet/ip6.h> and <netinet/icmp6.h>. π¦
When an include file is specified, that include file is allowed to include other files that do the actual declaration or definition. π§
2.1. The ip6_hdr Structure π
The following structure is defined as a result of including <netinet/ip6.h>. Note that this is a new header. π
struct ip6_hdr {
union {
struct ip6_hdrctl {
uint32_t ip6_un1_flow; /* 4 bits version, 8 bits TC, 20 bits
flow-ID */
uint16_t ip6_un1_plen; /* payload length */
uint8_t ip6_un1_nxt; /* next header */
uint8_t ip6_un1_hlim; /* hop limit */
} ip6_un1;
uint8_t ip6_un2_vfc; /* 4 bits version, top 4 bits
tclass */
} ip6_ctlun;
struct in6_addr ip6_src; /* source address */
struct in6_addr ip6_dst; /* destination address */
};
#define ip6_vfc ip6_ctlun.ip6_un2_vfc
#define ip6_flow ip6_ctlun.ip6_un1.ip6_un1_flow
#define ip6_plen ip6_ctlun.ip6_un1.ip6_un1_plen
#define ip6_nxt ip6_ctlun.ip6_un1.ip6_un1_nxt
#define ip6_hlim ip6_ctlun.ip6_un1.ip6_un1_hlim
#define ip6_hops ip6_ctlun.ip6_un1.ip6_un1_hlim
2.1.1. IPv6 Next Header Values π§
IPv6 defines many new values for the Next Header field. π
The following constants are defined as a result of including <netinet/in.h>.
#define IPPROTO_HOPOPTS 0 /* IPv6 Hop-by-Hop options */
#define IPPROTO_IPV6 41 /* IPv6 header */
#define IPPROTO_ROUTING 43 /* IPv6 Routing header */
#define IPPROTO_FRAGMENT 44 /* IPv6 fragment header */
#define IPPROTO_ESP 50 /* encapsulating security payload */
#define IPPROTO_AH 51 /* authentication header */
#define IPPROTO_ICMPV6 58 /* ICMPv6 */
#define IPPROTO_NONE 59 /* IPv6 no next header */
#define IPPROTO_DSTOPTS 60 /* IPv6 Destination options */
Berkeley-derived IPv4 implementations also define IPPROTO_IP to be 0. This should not be a problem, since IPPROTO_IP is used only with IPv4 sockets and IPPROTO_HOPOPTS only with IPv6 sockets. πΈ
2.1.2. IPv6 Extension Headers π
Six extension headers are defined for IPv6. We define structures for all except the Authentication header and Encapsulating Security Payload header, both of which are beyond the scope of this document. π¦ The following structures are defined as a result of including <netinet/ip6.h>.
/* Hop-by-Hop options header */
struct ip6_hbh {
uint8_t ip6h_nxt; /* next header */
uint8_t ip6h_len; /* length in units of 8 octets */
/* followed by options */
};
/* Destination options header */
struct ip6_dest {
uint8_t ip6d_nxt; /* next header */
uint8_t ip6d_len; /* length in units of 8 octets */
/* followed by options */
};
/* Routing header */
struct ip6_rthdr {
uint8_t ip6r_nxt; /* next header */
uint8_t ip6r_len; /* length in units of 8 octets */
uint8_t ip6r_type; /* routing type */
uint8_t ip6r_segleft; /* segments left */
/* followed by routing type specific data */
};
/* Type 0 Routing header */
struct ip6_rthdr0 {
uint8_t ip6r0_nxt; /* next header */
uint8_t ip6r0_len; /* length in units of 8 octets */
uint8_t ip6r0_type; /* always zero */
uint8_t ip6r0_segleft; /* segments left */
uint32_t ip6r0_reserved; /* reserved field */
/* followed by up to 127 struct in6_addr */
};
/* Fragment header */
struct ip6_frag {
uint8_t ip6f_nxt; /* next header */
uint8_t ip6f_reserved; /* reserved field */
uint16_t ip6f_offlg; /* offset, reserved, and flag */
uint32_t ip6f_ident; /* identification */
};
#if BYTE_ORDER == BIG_ENDIAN
#define IP6F_OFF_MASK 0xfff8 /* mask out offset from
ip6f_offlg */
#define IP6F_RESERVED_MASK 0x0006 /* reserved bits in
ip6f_offlg */
#define IP6F_MORE_FRAG 0x0001 /* more-fragments flag */
#else /* BYTE_ORDER == LITTLE_ENDIAN */
#define IP6F_OFF_MASK 0xf8ff /* mask out offset from
ip6f_offlg */
#define IP6F_RESERVED_MASK 0x0600 /* reserved bits in
ip6f_offlg */
#define IP6F_MORE_FRAG 0x0100 /* more-fragments flag */
#endif
2.1.3. IPv6 Options β¨
okay so IPv6 has a whole buffet of options π and we're gonna define structs and macros for some of the main ones. All of these come from including <netinet/ip6.h>, so no extra headers needed, bestie π«Ά
/* IPv6 options */
struct ip6_opt {
uint8_t ip6o_type;
uint8_t ip6o_len;
};
/*
* The high-order 3 bits of the option type define the behavior
* when processing an unknown option and whether or not the option
* content changes in flight.
*/
#define IP6OPT_TYPE(o) ((o) & 0xc0)
#define IP6OPT_TYPE_SKIP 0x00
#define IP6OPT_TYPE_DISCARD 0x40
#define IP6OPT_TYPE_FORCEICMP 0x80
#define IP6OPT_TYPE_ICMP 0xc0
#define IP6OPT_MUTABLE 0x20
#define IP6OPT_PAD1 0x00 /* 00 0 00000 */
#define IP6OPT_PADN 0x01 /* 00 0 00001 */
#define IP6OPT_JUMBO 0xc2 /* 11 0 00010 */
#define IP6OPT_NSAP_ADDR 0xc3 /* 11 0 00011 */
#define IP6OPT_TUNNEL_LIMIT 0x04 /* 00 0 00100 */
#define IP6OPT_ROUTER_ALERT 0x05 /* 00 0 00101 */
/* Jumbo Payload Option */
struct ip6_opt_jumbo {
uint8_t ip6oj_type;
uint8_t ip6oj_len;
uint8_t ip6oj_jumbo_len[4];
};
#define IP6OPT_JUMBO_LEN 6
/* NSAP Address Option */
struct ip6_opt_nsap {
uint8_t ip6on_type;
uint8_t ip6on_len;
uint8_t ip6on_src_nsap_len;
uint8_t ip6on_dst_nsap_len;
/* followed by source NSAP */
/* followed by destination NSAP */
};
/* Tunnel Limit Option */
struct ip6_opt_tunnel {
uint8_t ip6ot_type;
uint8_t ip6ot_len;
uint8_t ip6ot_encap_limit;
};
/* Router Alert Option */
struct ip6_opt_router {
uint8_t ip6or_type;
uint8_t ip6or_len;
uint8_t ip6or_value[2];
};
/* Router alert values (in network byte order) */
#ifdef _BIG_ENDIAN
#define IP6_ALERT_MLD 0x0000
#define IP6_ALERT_RSVP 0x0001
#define IP6_ALERT_AN 0x0002
#else
#define IP6_ALERT_MLD 0x0000
#define IP6_ALERT_RSVP 0x0100
#define IP6_ALERT_AN 0x0200
#endif
2.2. The icmp6_hdr Structure π
the ICMPv6 header is a big deal π basically everything uses it, like Ping, Traceroute, router discovery daemons, and neighbor discovery daemons. heads up, this one is brand new π¦ and it lives in <netinet/icmp6.h>.
struct icmp6_hdr {
uint8_t icmp6_type; /* type field */
uint8_t icmp6_code; /* code field */
uint16_t icmp6_cksum; /* checksum field */
union {
uint32_t icmp6_un_data32[1]; /* type-specific field */
uint16_t icmp6_un_data16[2]; /* type-specific field */
uint8_t icmp6_un_data8[4]; /* type-specific field */
} icmp6_dataun;
};
#define icmp6_data32 icmp6_dataun.icmp6_un_data32
#define icmp6_data16 icmp6_dataun.icmp6_un_data16
#define icmp6_data8 icmp6_dataun.icmp6_un_data8
#define icmp6_pptr icmp6_data32[0] /* parameter prob */
#define icmp6_mtu icmp6_data32[0] /* packet too big */
#define icmp6_id icmp6_data16[0] /* echo request/reply */
#define icmp6_seq icmp6_data16[1] /* echo request/reply */
#define icmp6_maxdelay icmp6_data16[0] /* mcast group
membership */
2.2.1. ICMPv6 Type and Code Values πΈ
so the ICMPv6 type and code fields need shared definitions too, otherwise everyone would be guessing π the constants below also come from <netinet/icmp6.h>.
#define ICMP6_DST_UNREACH 1
#define ICMP6_PACKET_TOO_BIG 2
#define ICMP6_TIME_EXCEEDED 3
#define ICMP6_PARAM_PROB 4
#define ICMP6_INFOMSG_MASK 0x80 /* all informational
messages */
#define ICMP6_ECHO_REQUEST 128
#define ICMP6_ECHO_REPLY 129
#define ICMP6_DST_UNREACH_NOROUTE 0 /* no route to
destination */
#define ICMP6_DST_UNREACH_ADMIN 1 /* communication with
destination */
/* admin. prohibited */
#define ICMP6_DST_UNREACH_BEYONDSCOPE 2 /* beyond scope of source
address */
#define ICMP6_DST_UNREACH_ADDR 3 /* address unreachable */
#define ICMP6_DST_UNREACH_NOPORT 4 /* bad port */
#define ICMP6_TIME_EXCEED_TRANSIT 0 /* Hop Limit == 0 in
transit */
#define ICMP6_TIME_EXCEED_REASSEMBLY 1 /* Reassembly time out */
#define ICMP6_PARAMPROB_HEADER 0 /* erroneous header
field */
#define ICMP6_PARAMPROB_NEXTHEADER 1 /* unrecognized
Next Header */
#define ICMP6_PARAMPROB_OPTION 2 /* unrecognized
IPv6 option */
the five ICMP message types from IPv6 neighbor discovery (133-137) get their own section next, so hold that thought π§
2.2.2. ICMPv6 Neighbor Discovery Definitions π¦
these structs and defines all come from including <netinet/icmp6.h>, and they're the neighbor discovery toolkit π§°β¨
#define ND_ROUTER_SOLICIT 133
#define ND_ROUTER_ADVERT 134
#define ND_NEIGHBOR_SOLICIT 135
#define ND_NEIGHBOR_ADVERT 136
#define ND_REDIRECT 137
struct nd_router_solicit { /* router solicitation */
struct icmp6_hdr nd_rs_hdr;
/* could be followed by options */
};
#define nd_rs_type nd_rs_hdr.icmp6_type
#define nd_rs_code nd_rs_hdr.icmp6_code
#define nd_rs_cksum nd_rs_hdr.icmp6_cksum
#define nd_rs_reserved nd_rs_hdr.icmp6_data32[0]
struct nd_router_advert { /* router advertisement */
struct icmp6_hdr nd_ra_hdr;
uint32_t nd_ra_reachable; /* reachable time */
uint32_t nd_ra_retransmit; /* retransmit timer */
/* could be followed by options */
};
#define nd_ra_type nd_ra_hdr.icmp6_type
#define nd_ra_code nd_ra_hdr.icmp6_code
#define nd_ra_cksum nd_ra_hdr.icmp6_cksum
#define nd_ra_curhoplimit nd_ra_hdr.icmp6_data8[0]
#define nd_ra_flags_reserved nd_ra_hdr.icmp6_data8[1]
#define ND_RA_FLAG_MANAGED 0x80
#define ND_RA_FLAG_OTHER 0x40
#define nd_ra_router_lifetime nd_ra_hdr.icmp6_data16[1]
struct nd_neighbor_solicit { /* neighbor solicitation */
struct icmp6_hdr nd_ns_hdr;
struct in6_addr nd_ns_target; /* target address */
/* could be followed by options */
};
#define nd_ns_type nd_ns_hdr.icmp6_type
#define nd_ns_code nd_ns_hdr.icmp6_code
#define nd_ns_cksum nd_ns_hdr.icmp6_cksum
#define nd_ns_reserved nd_ns_hdr.icmp6_data32[0]
struct nd_neighbor_advert { /* neighbor advertisement */
struct icmp6_hdr nd_na_hdr;
struct in6_addr nd_na_target; /* target address */
/* could be followed by options */
};
#define nd_na_type nd_na_hdr.icmp6_type
#define nd_na_code nd_na_hdr.icmp6_code
#define nd_na_cksum nd_na_hdr.icmp6_cksum
#define nd_na_flags_reserved nd_na_hdr.icmp6_data32[0]
#if BYTE_ORDER == BIG_ENDIAN
#define ND_NA_FLAG_ROUTER 0x80000000
#define ND_NA_FLAG_SOLICITED 0x40000000
#define ND_NA_FLAG_OVERRIDE 0x20000000
#else /* BYTE_ORDER == LITTLE_ENDIAN */
#define ND_NA_FLAG_ROUTER 0x00000080
#define ND_NA_FLAG_SOLICITED 0x00000040
#define ND_NA_FLAG_OVERRIDE 0x00000020
#endif
struct nd_redirect { /* redirect */
struct icmp6_hdr nd_rd_hdr;
struct in6_addr nd_rd_target; /* target address */
struct in6_addr nd_rd_dst; /* destination address */
/* could be followed by options */
};
#define nd_rd_type nd_rd_hdr.icmp6_type
#define nd_rd_code nd_rd_hdr.icmp6_code
#define nd_rd_cksum nd_rd_hdr.icmp6_cksum
#define nd_rd_reserved nd_rd_hdr.icmp6_data32[0]
struct nd_opt_hdr { /* Neighbor discovery option header */
uint8_t nd_opt_type;
uint8_t nd_opt_len; /* in units of 8 octets */
/* followed by option specific data */
};
#define ND_OPT_SOURCE_LINKADDR 1
#define ND_OPT_TARGET_LINKADDR 2
#define ND_OPT_PREFIX_INFORMATION 3
#define ND_OPT_REDIRECTED_HEADER 4
#define ND_OPT_MTU 5
struct nd_opt_prefix_info { /* prefix information */
uint8_t nd_opt_pi_type;
uint8_t nd_opt_pi_len;
uint8_t nd_opt_pi_prefix_len;
uint8_t nd_opt_pi_flags_reserved;
uint32_t nd_opt_pi_valid_time;
uint32_t nd_opt_pi_preferred_time;
uint32_t nd_opt_pi_reserved2;
struct in6_addr nd_opt_pi_prefix;
};
#define ND_OPT_PI_FLAG_ONLINK 0x80
#define ND_OPT_PI_FLAG_AUTO 0x40
struct nd_opt_rd_hdr { /* redirected header */
uint8_t nd_opt_rh_type;
uint8_t nd_opt_rh_len;
uint16_t nd_opt_rh_reserved1;
uint32_t nd_opt_rh_reserved2;
/* followed by IP header and data */
};
struct nd_opt_mtu { /* MTU option */
uint8_t nd_opt_mtu_type;
uint8_t nd_opt_mtu_len;
uint16_t nd_opt_mtu_reserved;
uint32_t nd_opt_mtu_mtu;
};
heads up, the nd_na_flags_reserved flags have the same byte ordering mess we already saw with ip6f_offlg π so keep an eye on that one, bestie π
2.2.3. Multicast Listener Discovery Definitions π
last stop for this part! these structs and defines are also from <netinet/icmp6.h>, and they're all about multicast listener discovery π‘π
#define MLD_LISTENER_QUERY 130
#define MLD_LISTENER_REPORT 131
#define MLD_LISTENER_REDUCTION 132
struct mld_hdr {
struct icmp6_hdr mld_icmp6_hdr;
struct in6_addr mld_addr; /* multicast address */
};
#define mld_type mld_icmp6_hdr.icmp6_type
#define mld_code mld_icmp6_hdr.icmp6_code
#define mld_cksum mld_icmp6_hdr.icmp6_cksum
#define mld_maxdelay mld_icmp6_hdr.icmp6_data16[0]
#define mld_reserved mld_icmp6_hdr.icmp6_data16[1]
2.2.4. ICMPv6 Router Renumbering Definitions β¨
okay so this bit is all the stuff you get from including <netinet/icmp6.h> π Here's the router renumbering setup: the message type, the header struct, and all the flag bits you can poke at π
#define ICMP6_ROUTER_RENUMBERING 138 /* router renumbering */
struct icmp6_router_renum { /* router renumbering header */
struct icmp6_hdr rr_hdr;
uint8_t rr_segnum;
uint8_t rr_flags;
uint16_t rr_maxdelay;
uint32_t rr_reserved;
};
#define rr_type rr_hdr.icmp6_type
#define rr_code rr_hdr.icmp6_code
#define rr_cksum rr_hdr.icmp6_cksum
#define rr_seqnum rr_hdr.icmp6_data32[0]
/* Router renumbering flags */
#define ICMP6_RR_FLAGS_TEST 0x80
#define ICMP6_RR_FLAGS_REQRESULT 0x40
#define ICMP6_RR_FLAGS_FORCEAPPLY 0x20
#define ICMP6_RR_FLAGS_SPECSITE 0x10
#define ICMP6_RR_FLAGS_PREVDONE 0x08
struct rr_pco_match { /* match prefix part */
uint8_t rpm_code;
uint8_t rpm_len;
uint8_t rpm_ordinal;
uint8_t rpm_matchlen;
uint8_t rpm_minlen;
uint8_t rpm_maxlen;
uint16_t rpm_reserved;
struct in6_addr rpm_prefix;
};
/* PCO code values */
#define RPM_PCO_ADD 1
#define RPM_PCO_CHANGE 2
#define RPM_PCO_SETGLOBAL 3
struct rr_pco_use { /* use prefix part */
uint8_t rpu_uselen;
uint8_t rpu_keeplen;
uint8_t rpu_ramask;
uint8_t rpu_raflags;
uint32_t rpu_vltime;
uint32_t rpu_pltime;
uint32_t rpu_flags;
struct in6_addr rpu_prefix;
};
#define ICMP6_RR_PCOUSE_RAFLAGS_ONLINK 0x20
#define ICMP6_RR_PCOUSE_RAFLAGS_AUTO 0x10
#if BYTE_ORDER == BIG_ENDIAN
#define ICMP6_RR_PCOUSE_FLAGS_DECRVLTIME 0x80000000
#define ICMP6_RR_PCOUSE_FLAGS_DECRPLTIME 0x40000000
#elif BYTE_ORDER == LITTLE_ENDIAN
#define ICMP6_RR_PCOUSE_FLAGS_DECRVLTIME 0x80
#define ICMP6_RR_PCOUSE_FLAGS_DECRPLTIME 0x40
#endif
struct rr_result { /* router renumbering result message */
uint16_t rrr_flags;
uint8_t rrr_ordinal;
uint8_t rrr_matchedlen;
uint32_t rrr_ifid;
struct in6_addr rrr_prefix;
};
#if BYTE_ORDER == BIG_ENDIAN
#define ICMP6_RR_RESULT_FLAGS_OOB 0x0002
#define ICMP6_RR_RESULT_FLAGS_FORBIDDEN 0x0001
#elif BYTE_ORDER == LITTLE_ENDIAN
#define ICMP6_RR_RESULT_FLAGS_OOB 0x0200
#define ICMP6_RR_RESULT_FLAGS_FORBIDDEN 0x0100
#endif
2.3. Address Testing Macros π§
bestie, the basic API ([RFC-3493]) already gives you some macros for checking whether an IPv6 address has certain properties. This API adds a few more of its own, and you get them by including <netinet/in.h> π
int IN6_ARE_ADDR_EQUAL(const struct in6_addr *,
const struct in6_addr *);
This macro returns non-zero if the addresses are equal, and returns zero if they aren't. Simple and iconic πΈ
2.4. Protocols File π
Lowkey, a lot of hosts have a file called /etc/protocols that lists the names of the IP protocols along with their protocol numbers (like the value in the IPv4 header's protocol field, so 1 for ICMP). Some programs call getprotobyname() to grab that number and then pass it as the third argument to socket(). For example, the Ping program does something like this:
struct protoent *proto;
proto = getprotobyname("icmp");
s = socket(AF_INET, SOCK_RAW, proto->p_proto);
The new IPv6 protocols need common names in this file too, so that applications calling the getprotoXXX() functions stay portable π¦
These are the protocol names we define, with the values shown. They were taken from http://www.iana.org/numbers.html π₯
hopopt 0 # hop-by-hop options for ipv6
ipv6 41 # ipv6
ipv6-route 43 # routing header for ipv6
ipv6-frag 44 # fragment header for ipv6
esp 50 # encapsulating security payload for ipv6
ah 51 # authentication header for ipv6
ipv6-icmp 58 # icmp for ipv6
ipv6-nonxt 59 # no next header for ipv6
ipv6-opts 60 # destination options for ipv6
3. IPv6 Raw Sockets π
okay this section is about raw sockets, and they are literally so iconic π Raw sockets skip the transport layer (TCP or UDP) entirely π¦ In IPv4, raw sockets were how you got to ICMPv4 and IGMPv4, and how you read and wrote IPv4 datagrams with a protocol field the kernel doesn't process. A routing daemon for OSPF is the classic example, since it uses IPv4 protocol field 89. In IPv6, raw sockets are used for ICMPv6, and for reading and writing IPv6 datagrams with a Next Header field the kernel doesn't process. Examples are a routing daemon for OSPF for IPv6, and RSVP (protocol field 46) π
All data sent via raw sockets must be in network byte order, and all data received via raw sockets will be in network byte order. This is different from IPv4 raw sockets, which didn't specify a byte ordering and used the host's byte order for certain IP header fields π
Another difference from IPv4 raw sockets: you can't send or receive complete packets (that's IPv6 packets with their extension headers) using the IPv6 raw sockets API π Instead, ancillary data objects carry the extension headers and hop limit information, as described in Section 6. If an application needs the entire IPv6 packet, some other technique has to be used, like the datalink interfaces BPF or DLPI π«Ά
Every field in the IPv6 header that an application might want to change, except the flow label, can be modified for output using ancillary data and/or socket options. Everything other than the version number can be changed, so basically you have full control π On input, every field except the flow label (other than the version number and Next Header fields) and all the extension headers an application might care about are also handed over as ancillary data. That's why there's no need for a socket option like the IPv4 IP_HDRINCL socket option, and on receipt the application only gets the payload, meaning the data after the IPv6 header and all the extension headers β¨
This API doesn't define access to the flow label field, because there's currently no standard usage for it π§
When you write to a raw socket, the kernel automatically fragments the packet if its size goes over the path MTU, and it inserts the required fragment headers. On input, the kernel reassembles received fragments, so the reader of a raw socket never sees any fragment headers π¦
When we say "an ICMPv6 raw socket," we mean a socket created by calling the socket function with the three arguments AF_INET6, SOCK_RAW, and IPPROTO_ICMPV6 π
Most IPv4 implementations give special treatment to a raw socket created with IPPROTO_RAW as the third argument to socket(). That value is normally 255, and it means the application will send down complete packets, including the IPv4 header. (Note: This feature was added to IPv4 in 1988 by Van Jacobson to support traceroute, allowing a complete IP header to be passed by the application, before the IP_HDRINCL socket option was added.) We note that IPPROTO_RAW has no special meaning to an IPv6 raw socket, and the IANA currently reserves the value of 255 when used as a next-header field πΈ
3.1. Checksums π₯
The kernel will calculate and insert the ICMPv6 checksum for ICMPv6 raw sockets, since this checksum is mandatory π
For other raw IPv6 sockets (that is, raw IPv6 sockets created with a third argument other than IPPROTO_ICMPV6), the application must set the new IPV6_CHECKSUM socket option, so the kernel can (1) compute and store a checksum for output, and (2) verify the received checksum on input, discarding the packet if the checksum is in error. This option means applications don't have to do source address selection on the packets they send, which is a whole relief π The checksum incorporates the IPv6 pseudo-header, defined in Section 8.1 of [RFC-2460]. This new socket option also specifies an integer offset into the user data where the checksum is located π
int offset = 2;
setsockopt(fd, IPPROTO_IPV6, IPV6_CHECKSUM, &offset,
sizeof(offset));
By default, this socket option is disabled. Setting the offset to -1 also disables the option. When we say disabled, we mean (1) the kernel will not calculate and store a checksum for outgoing packets, and (2) the kernel will not verify a checksum for received packets π
This option assumes the use of the 16-bit one's complement of the one's complement sum as the checksum algorithm, and that the checksum field is aligned on a 16-bit boundary. So specifying a positive odd value as the offset is invalid, and setsockopt() will fail for such offset values π
An attempt to set IPV6_CHECKSUM for an ICMPv6 socket will fail. Also, an attempt to set or get IPV6_CHECKSUM for a non-raw IPv6 socket will fail π
(Note: Since the checksum is always calculated by the kernel for an ICMPv6 socket, applications are not able to generate ICMPv6 packets with incorrect checksums (presumably for testing purposes) using this API.) π«Ά
3.2. ICMPv6 Type Filtering π
okay so ICMPv4 raw sockets get most of the ICMPv4 messages the kernel receives π¦ (we say "most" and not "all" bc Berkeley-derived kernels never pass echo requests, timestamp requests, or address mask requests to a raw socket. those three get handled entirely by the kernel, no cap). but ICMPv6 is a superset of ICMPv4, and it also covers the jobs of IGMPv4 and ARPv4 πΈ. so an ICMPv6 raw socket can potentially receive WAY more messages than an ICMPv4 one: the ICMP-ish stuff, plus neighbor solicitations, neighbor advertisements, and the three multicast listener discovery messages. main character energy π
most apps using an ICMPv6 raw socket only care about a tiny handful of message types, and shipping every extra ICMPv6 message from the kernel up to userspace can cost a lot of overhead π. so this API lets you filter ICMPv6 messages by the ICMPv6 type field π«Ά.
each ICMPv6 raw socket has an associated filter, and its datatype is
struct icmp6_filter;
this structure, plus the macros and constants defined later in this section, all come from including <netinet/icmp6.h> β¨.
you fetch and store the current filter with getsockopt() and setsockopt(), using a level of IPPROTO_ICMPV6 and an option name of ICMP6_FILTER π.
there are six macros that operate on an icmp6_filter structure:
void ICMP6_FILTER_SETPASSALL (struct icmp6_filter *);
void ICMP6_FILTER_SETBLOCKALL(struct icmp6_filter *);
void ICMP6_FILTER_SETPASS ( int, struct icmp6_filter *);
void ICMP6_FILTER_SETBLOCK( int, struct icmp6_filter *);
int ICMP6_FILTER_WILLPASS (int,
const struct icmp6_filter *);
int ICMP6_FILTER_WILLBLOCK(int,
const struct icmp6_filter *);
the first argument to the last four macros is an integer, an ICMPv6 message type between 0 and 255 π₯. the pointer argument to all six macros points at a filter. the first four macros modify that filter, and the last two just examine it π§.
SETPASSALL and SETBLOCKALL are the first two. they say either "pass every ICMPv6 message up to the app" or "block every ICMPv6 message from reaching the app" π.
SETPASS and SETBLOCK are next. they let you say whether messages of one specific ICMPv6 type should get passed to the app, or not passed (blocked) π.
the last two, WILLPASS and WILLBLOCK, just tell you true or false: will that message type get through to the app, or get blocked by the filter pointed to by the second argument? π
when an ICMPv6 raw socket gets created, it passes all ICMPv6 message types to the app by default β.
here's an example. say a program only wants router advertisements. it could do this:
struct icmp6_filter myfilt;
fd = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6);
ICMP6_FILTER_SETBLOCKALL(&myfilt);
ICMP6_FILTER_SETPASS(ND_ROUTER_ADVERT, &myfilt);
setsockopt(fd, IPPROTO_ICMPV6, ICMP6_FILTER, &myfilt,
sizeof(myfilt));
so the filter gets declared and then set to block all message types. then it changes so router advertisement messages can reach the app, and the filter gets installed with setsockopt() π β¨.
to clear an installed filter, the app can call setsockopt for ICMP6_FILTER with a zero length π. if no filter has been installed, getsockopt() returns the kernel default filter π¦.
the icmp6_filter structure is kind of like the fd_set datatype used with the select() function in the sockets API πΈ. it's an opaque datatype, so the app should not care how it's implemented π. all the app does with it is allocate a variable of this type, pass a pointer to one to getsockopt() and setsockopt(), and work on it with the six macros we just went over π«Ά.
that said, it's still worth seeing a simple implementation of the datatype and the six macros π:
struct icmp6_filter {
uint32_t icmp6_filt[8]; /* 8*32 = 256 bits */
};
#define ICMP6_FILTER_WILLPASS(type, filterp) \
((((filterp)->icmp6_filt[(type) >> 5]) & \
(1 << ((type) & 31))) != 0)
#define ICMP6_FILTER_WILLBLOCK(type, filterp) \
((((filterp)->icmp6_filt[(type) >> 5]) & \
(1 << ((type) & 31))) == 0)
#define ICMP6_FILTER_SETPASS(type, filterp) \
((((filterp)->icmp6_filt[(type) >> 5]) |= \
(1 << ((type) & 31))))
#define ICMP6_FILTER_SETBLOCK(type, filterp) \
((((filterp)->icmp6_filt[(type) >> 5]) &= \
~(1 << ((type) & 31))))
#define ICMP6_FILTER_SETPASSALL(filterp) \
memset((filterp), 0xFF, sizeof(struct icmp6_filter))
#define ICMP6_FILTER_SETBLOCKALL(filterp) \
memset((filterp), 0, sizeof(struct icmp6_filter))
(heads up: these sample definitions have two limitations that an implementation might want to fix π. the first four macros evaluate their first argument two times, and the last two macros need <string.h> included for the memset() function.)
3.3. ICMPv6 Verification of Received Packets π
the protocol stack verifies the ICMPv6 checksum and throws away any packets with invalid checksums ποΈ.
an implementation might also run extra validity checks on the ICMPv6 message content and discard malformed packets π . but a portable app MUST NOT assume those checks happened π.
the protocol stack SHOULD NOT automatically discard packets just because the ICMP type is unknown to the stack. for extensibility reasons, received ICMP packets of any type, informational or error, MUST be passed to the applications (subject to ICMP6_FILTER filtering on the type value and the checksum verification) π. the future-proofing is so iconic π.
4. Access to IPv6 and Extension Headers π
apps need to be able to control IPv6 header and extension header content when sending, and also to receive the content of these headers π§. this happens through socket option types that work with both setsockopt and ancillary data (ancillary data is covered in Appendix A) π. the following optional information can be swapped between the app and the kernel:
- The send/receive interface and source/destination address,
- The hop limit,
- Next hop address,
- The traffic class,
- Routing header,
- Hop-by-Hop options header, and
- Destination options header.
first up, to receive any of this info (except the next hop address, which can only be set) on a UDP or raw socket, the app MUST call setsockopt() to turn on the matching flag π₯:
int on = 1;
setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, &on, sizeof(on));
setsockopt(fd, IPPROTO_IPV6, IPV6_RECVHOPLIMIT, &on, sizeof(on));
setsockopt(fd, IPPROTO_IPV6, IPV6_RECVRTHDR, &on, sizeof(on));
setsockopt(fd, IPPROTO_IPV6, IPV6_RECVHOPOPTS, &on, sizeof(on));
setsockopt(fd, IPPROTO_IPV6, IPV6_RECVDSTOPTS, &on, sizeof(on));
setsockopt(fd, IPPROTO_IPV6, IPV6_RECVTCLASS, &on, sizeof(on));
when any of these are enabled, the matching data comes back as control information from recvmsg(), as one or more ancillary data objects β¨.
this document doesn't define how to receive the optional information on a TCP socket. see Section 4.1 for more π¦.
there are two ways to send this optional info π :
- Using setsockopt to specify the option content for a socket. these are called "sticky" options, since they affect every transmitted packet on the socket until either a new setsockopt is done or the options get overridden with ancillary data π«Ά.
- Using ancillary data to specify the option content for a single datagram. this only applies to datagram and raw sockets, not TCP sockets πΈ.
here's the summary of the three socket option parameters and the three cmsghdr fields that describe the options/ancillary data objects π:
opt level/ optname/ optval/
cmsg_level cmsg_type cmsg_data[]
------------ ------------ ------------------------
IPPROTO_IPV6 IPV6_PKTINFO in6_pktinfo structure
IPPROTO_IPV6 IPV6_HOPLIMIT int
IPPROTO_IPV6 IPV6_NEXTHOP socket address structure
IPPROTO_IPV6 IPV6_RTHDR ip6_rthdr structure
IPPROTO_IPV6 IPV6_HOPOPTS ip6_hbh structure
IPPROTO_IPV6 IPV6_DSTOPTS ip6_dest structure
IPPROTO_IPV6 IPV6_RTHDRDSTOPTS ip6_dest structure
IPPROTO_IPV6 IPV6_TCLASS int
(note: IPV6_HOPLIMIT can only be used as an ancillary data item π)
all of these options get described in detail in Section 6, 7, 8 and 9 π. all the constants starting with IPV6_ are defined by including <netinet/in.h> π§.
note: we're deliberately using the same constant for the cmsg_level member that's used as the second argument to getsockopt() and setsockopt() (the "level"), and the same constant for the cmsg_type member that's used as the third argument to those calls (the "option name") π«Ά.
if you call getsockopt() for any of the options above, you get back the sticky option value (the value set with setsockopt()). if no sticky option value has been set, getsockopt() returns these:
- For the IPV6_PKTINFO option, it returns an in6_pktinfo structure with ipi6_addr set to in6addr_any and ipi6_ifindex set to zero.
- For the IPV6_TCLASS option, it returns the kernel default value.
- For other options, it indicates the lack of the option value with optlen being zero.
the app doesn't have to explicitly touch the data structures for the Routing header, Hop-by-Hop options header, and Destination options header π. the API for those features goes through a set of inet6_rth_XXX() and inet6_opt_XXX() functions, which we define in Section 7 and Section 10. those functions simplify the interface so the app doesn't need to know the intimate details of the extension header formats π.
when specifying extension headers, this API assumes the header ordering and the number of occurrences of each header as described in [RFC-2460]. more details about the ordering issue get discussed in Section 12 π.
4.1. TCP Implications
bestie, TCP is lowkey the drama queen of this whole story π π You can't send the above options as ancillary data because there's no one-to-one mapping between send operations and the TCP segments actually going out π So instead, the app sets them as sticky options with setsockopt. Once it does, TCP is expected to start using the new info when it sends segments β¨ BUT, and this is the tea, TCP may or may not use the new info when it retransmits segments that were first sent under the old sticky options π
Receiving is messy too π It's unclear how a TCP app can use received info (like extension headers), because there's no clean mapping between received TCP segments and receive operations. Especially, the received info couldn't be used for access control the way it can on UDP and raw sockets π₯
So this spec does not define how to get received info on TCP sockets π¦ And what the IPV6_RECVxxx options do on a TCP socket? Undefined, bestie. Not my problem, not your problem, it's just vibes π
4.2. UDP and Raw Socket Implications
Okay, receiving on UDP and raw sockets is honestly so simple it's giving clean girl energy π§ Once the app turns on an IPV6_RECVxxx socket option, it gets an ancillary data item for every recvmsg() call that has the requested info β¨ But if that info isn't in the packet, the item just won't show up. For example, if the app enables IPV6_RECVRTHDR and the datagram has no Routing header, there will be no IPV6_RTHDR ancillary data item πΈ Also, fair warning, because of buffering in the socket implementation, some packets might already be queued when you enable an IPV6_RECVxxx option, and those might not carry the ancillary data info π
For sending, the app gets to choose between sticky options and ancillary data π It can even use both: the sticky options set the "default," and ancillary data overrides the default π«Ά
When an ancillary data item is given in a sendmsg() call, it overrides an existing sticky option of the same name (if one was set before) π For example, say the app set IPV6_RTHDR as a sticky option and later passes IPV6_RTHDR as ancillary data. That overrides the IPV6_RTHDR sticky option, and the routing header of the outgoing packet comes from the ancillary data item, not the sticky option π₯ But here's the catch: other sticky options aren't affected by the IPV6_RTHDR ancillary data item. The overriding only works between the same type of sticky option and ancillary data item π
(Note: this overriding rule is different from the one in RFC 2292 π In RFC 2292, an ancillary data item overrode ALL previously defined sticky options. That made sense back then, since sticky options could only be set as a group with one socket option. In this API, each option is separate, so each one can be set as its own sticky option. Plus there are way more ancillary data items and sticky options than in RFC 2292, including ancillary-only ones. So it should feel natural for app programmers to have the overriding rule be separate too β¨)
An app can also temporarily turn off a particular sticky option by passing a matching ancillary data item that disables it when used as an argument for a socket option π¦ For example, say the app set IPV6_HOPOPTS as a sticky option and later passes IPV6_HOPOPTS with a zero length as an ancillary data item. Then the packet won't have a Hop-by-Hop options header ππ
5. Extensions to Socket Ancillary Data
This spec uses ancillary data as defined in Posix, plus some compatible extensions π Those extensions are described in the subsections below. Section 20 gives a detailed overview of ancillary data and its related structures and macros, extensions included π§
5.1. CMSG_NXTHDR
struct cmsghdr *CMSG_NXTHDR(const struct msghdr *mhdr,
const struct cmsghdr *cmsg);
CMSG_NXTHDR() returns a pointer to the cmsghdr structure describing the next ancillary data object π mhdr is a pointer to a msghdr structure and cmsg is a pointer to a cmsghdr structure. If there isn't another ancillary data object, the return value is NULL π
Here's the new bit that's unique to this API β¨ If the cmsg pointer's value is NULL, you get a pointer to the cmsghdr structure describing the first ancillary data object. So CMSG_NXTHDR(mhdr, NULL) is equivalent to CMSG_FIRSTHDR(mhdr) π And if there are no ancillary data objects at all, the return value is NULL πΈ
5.2. CMSG_SPACE
socklen_t CMSG_SPACE(socklen_t length);
This macro is new with this API π Given the length of an ancillary data object, CMSG_SPACE() returns an upper bound on the space the object and its cmsghdr structure need, padding for alignment included β¨ It's handy when you're allocating space dynamically for the ancillary data π«Ά But this macro should not be used to initialize the cmsg_len member of a cmsghdr structure. Use the CMSG_LEN() macro for that instead π
5.3. CMSG_LEN
socklen_t CMSG_LEN(socklen_t length);
This macro is new with this API too π¦ Given the length of an ancillary data object, CMSG_LEN() returns the value to store in the cmsg_len member of the cmsghdr structure, taking into account any padding needed for alignment π
Here's the key difference between CMSG_SPACE() and CMSG_LEN(), also shown in the figure in Section 20.2 π CMSG_SPACE() counts any required padding at the end of the ancillary data object, while CMSG_LEN() is the actual length you store in the cmsg_len member of that object π₯
6. Packet Information
There are five pieces of info an app can set for an outgoing packet using ancillary data π
- the source IPv6 address,
- the outgoing interface index,
- the outgoing hop limit,
- the next hop address, and
- the outgoing traffic class value.
Four similar pieces of info can come back for a received packet as ancillary data π
- the destination IPv6 address,
- the arriving interface index,
- the arriving hop limit, and
- the arriving traffic class value.
The first two pieces of info live in an in6_pktinfo structure. You set it with setsockopt() or send it as ancillary data with sendmsg(), and you get it back as ancillary data with recvmsg() β¨ This structure is defined when you include <netinet/in.h> π§
struct in6_pktinfo {
struct in6_addr ipi6_addr; /* src/dst IPv6 address */
unsigned int ipi6_ifindex; /* send/recv interface index */
};
For the socket option, the cmsghdr level is IPPROTO_IPV6 and the type is IPV6_PKTINFO π The first byte of the option value and of cmsg_data[] is the first byte of the in6_pktinfo structure π To clear any sticky IPV6_PKTINFO option, do a "regular" setsockopt with ipi6_addr set to in6addr_any and ipi6_ifindex set to zero π«Ά
recvmsg() only returns this info as ancillary data if the app has enabled the IPV6_RECVPKTINFO socket option πΈ
int on = 1;
setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, &on, sizeof(on));
(Note: the hop limit isn't in the in6_pktinfo structure, and here's why π¦ Some UDP servers want to answer client requests by sending the reply out the same interface the request came in on, with the reply's source IPv6 address equal to the request's destination IPv6 address. To do that, the app can enable just the IPV6_RECVPKTINFO socket option and then use the control info received from recvmsg() as the outgoing control info for sendmsg(). The app doesn't need to look at or change the in6_pktinfo structure at all. But if the hop limit lived in this structure, the app would have to parse the received control info and change the hop limit member, because the received hop limit isn't the one you want for an outgoing packet π)
6.1. Specifying/Receiving the Interface
Interfaces on an IPv6 node are identified by a small positive integer, as described in Section 4 of [RFC-3493] π That document also describes a function that maps an interface name to its interface index, a function that maps an interface index to its interface name, and a function that returns all the interface names and indexes π§ Notice from this document that no interface is ever assigned an index of 0 β¨
When you're specifying the outgoing interface, if the ipi6_ifindex value is 0, the kernel picks the outgoing interface for you π
The ordering among the various options that can specify the outgoing interface, IPV6_PKTINFO included, is defined in Section 6.7 π
When the IPV6_RECVPKTINFO socket option is enabled, the received interface index is always returned as the ipi6_ifindex member of the in6_pktinfo structure π₯
6.2. Specifying/Receiving Source/Destination Address
The source IPv6 address can be set by calling bind() before each output operation π But supplying the source address together with the data needs less overhead (fewer system calls), and it needs less state stored and protected in a multithreaded app π«Ά
When you specify the source IPv6 address as ancillary data, if the ipi6_addr member of the in6_pktinfo structure is the unspecified address (IN6ADDR_ANY_INIT or in6addr_any), then: (a) if an address is currently bound to the socket, that address is used as the source address, or (b) if no address is currently bound to the socket, the kernel chooses the source address π¦ If the ipi6_addr member is not the unspecified address, but the socket has already bound a source address, then the ipi6_addr value overrides the already-bound source address for this output operation only π
The kernel has to verify that the requested source address is actually a unicast address assigned to the node π When the address is a scoped one, its scope zone can be ambiguous, and that's especially true for link-local addresses π In that case, the kernel first has to figure out the right scope zone, based on the zone of the destination address or the outgoing interface (if known), and then qualify the address π This also means you can't really specify the source address for a non-binding socket with the IPV6_PKTINFO sticky option unless the outgoing interface is specified too π For that stuff, the app should just use bind() πΈ
IPV6_PKTINFO can also be used as a sticky option to set the socket's default source address β¨ But for TCP sockets, the ipi6_addr member must be the unspecified address, because you can't dynamically change the source address of a TCP connection π ββοΈ If the IPV6_PKTINFO option is set on a TCP socket with a non-unspecified address, the call fails π This restriction applies even before the socket binds to a specific address π«Ά
When recvmsg() returns the in6_pktinfo structure as ancillary data, the ipi6_addr member holds the destination IPv6 address from the received packet π§
6.3. Specifying/Receiving the Hop Limit π¦
okay so the outgoing hop limit is normally set with either the IPV6_UNICAST_HOPS socket option or the IPV6_MULTICAST_HOPS socket option, and both of those get explained in [RFC-3493] π
. Ancillary data is the glow-up here, bestie β¨ because it lets your app override either the kernel's default or a previously set value, for a unicast or a multicast destination, for just one single output operation π₯
Returning the received hop limit is also super useful for IPv6 apps that need to check that the received hop limit is 255 (e.g., that the packet has not been forwarded) π
The received hop limit only comes back as ancillary data from recvmsg() if the app has turned on the IPV6_RECVHOPLIMIT socket option:
int on = 1;
setsockopt(fd, IPPROTO_IPV6, IPV6_RECVHOPLIMIT, &on, sizeof(on));
In the cmsghdr structure holding this ancillary data, the cmsg_level member will be IPPROTO_IPV6, the cmsg_type member will be IPV6_HOPLIMIT, and the first byte of cmsg_data[] will be the first byte of the integer hop limit π§
Nothing special is needed to set the outgoing hop limit: just put the control info in as ancillary data for sendmsg(). As specified in [RFC-3493], the integer hop limit value is interpreted like this π
x < -1: return an error of EINVAL
x == -1: use kernel default
0 <= x <= 255: use x
x >= 256: return an error of EINVAL
This API defines IPV6_HOPLIMIT as an ancillary-only option, which means the option name can't be used as a socket option π ββοΈ The reason is that [RFC-3493] already has more fine-grained socket options: IPV6_UNICAST_HOPS and IPV6_MULTICAST_HOPS.
6.4. Specifying the Next Hop Address πΈ
The IPV6_NEXTHOP ancillary data object specifies the next hop for the datagram as a socket address structure π In the cmsghdr structure holding this ancillary data, the cmsg_level member will be IPPROTO_IPV6, the cmsg_type member will be IPV6_NEXTHOP, and the first byte of cmsg_data[] will be the first byte of the socket address structure π
This is a privileged option. (Note: it's implementation defined, and it's beyond the scope of this document to define what "privileged" means. Unix systems use the term to mean the process must have an effective user ID of 0.) π This API only defines the case where the socket address holds an IPv6 address (i.e., the sa_family member is AF_INET6). And in that case, the node identified by that address must be a neighbor of the sending host. If that address equals the destination IPv6 address of the datagram, then it's equivalent to the existing SO_DONTROUTE socket option β¨
This option has no meaning for multicast destinations. In that case the specified next hop gets ignored π¦
When the outgoing interface is also specified by IPV6_PKTINFO, the next hop given by this option must be reachable via that specified interface π«Ά
To clear a sticky IPV6_NEXTHOP option, the app has to issue a setsockopt for IPV6_NEXTHOP with a zero length π§Ή
6.5. Specifying/Receiving the Traffic Class value π
The outgoing traffic class is normally set to 0 π Specifying it as ancillary data lets the app override either the kernel's default or a previously specified value, for a unicast or multicast destination, for a single output operation. Returning the received traffic class is handy for things like a diffserv debugging tool and for user level ECN (explicit congestion notification) implementation π₯
The received traffic class only comes back as ancillary data from recvmsg() if the app has enabled the IPV6_RECVTCLASS socket option:
int on = 1;
setsockopt(fd, IPPROTO_IPV6, IPV6_RECVTCLASS, &on, sizeof(on));
In the cmsghdr structure holding this ancillary data, the cmsg_level member will be IPPROTO_IPV6, the cmsg_type member will be IPV6_TCLASS, and the first byte of cmsg_data[] will be the first byte of the integer traffic class π§
To set the outgoing traffic class value, just put the control info in as ancillary data for sendmsg() or use setsockopt(). Just like the hop limit, the integer traffic class value is interpreted like this:
x < -1: return an error of EINVAL
x == -1: use kernel default
0 <= x <= 255: use x
x >= 256: return an error of EINVAL
To clear a sticky IPV6_TCLASS option, the app can specify -1 as the value π
Sometimes the kernel needs to control the traffic class value, and that clashes with the user-specified value on the outgoing traffic. An example is an ECN implementation in the kernel, which sets 2 bits of the traffic class value. In cases like that, the kernel should override the user-specified value π On incoming traffic, the kernel may mask some of the bits in the traffic class field π«§
6.6. Additional Errors with sendmsg() and setsockopt() π
With the IPV6_PKTINFO socket option there are no additional errors possible with the call to recvmsg(). But when you specify the outgoing interface or the source address, extra errors can come back from sendmsg() or setsockopt(). Some implementations might only be able to return this type of error for setsockopt(), so heads up π The following are examples, but some of them may not be provided by some implementations, and some implementations may define extra errors too:
ENXIO The interface specified by ipi6_ifindex does not exist.
ENETDOWN The interface specified by ipi6_ifindex is not enabled
for IPv6 use.
EADDRNOTAVAIL ipi6_ifindex specifies an interface but the address
ipi6_addr is not available for use on that interface.
EHOSTUNREACH No route to the destination exists over the interface
specified by ipi6_ifindex.
6.7. Summary of Outgoing Interface Selection πΊοΈ
This document and [RFC-3493] specify a bunch of ways that can affect which outgoing interface a packet takes. This subsection sums up the ordering between them so everything stays deterministic π₯
For a given outgoing packet on a given socket, the outgoing interface is decided in this order:
- if an interface is specified in an IPV6_PKTINFO ancillary data item, that interface is used.
- otherwise, if an interface is specified in an IPV6_PKTINFO sticky option, that interface is used.
- otherwise, if the destination address is a multicast address and the IPV6_MULTICAST_IF socket option is specified for the socket, that interface is used.
- otherwise, if an IPV6_NEXTHOP ancillary data item is specified, the interface to the next hop is used.
- otherwise, if an IPV6_NEXTHOP sticky option is specified, the interface to the next hop is used.
- otherwise, the outgoing interface should be determined in an implementation dependent manner.
This ordering especially means that if the app specifies an interface with the IPV6_MULTICAST_IF socket option (described in [RFC-3493]) and also specifies a different interface with the IPV6_PKTINFO sticky option, the latter overrides the former for every multicast packet on that socket π The reason for the ordering comes from the expectation that the source address is specified too, and that the pair of the address and the outgoing interface should be preferred π
In any case, the kernel must also verify that the source and destination addresses don't break their scope zones with regard to the outgoing interface π‘οΈ
7. Routing Header Option π§β¨
Source routing in IPv6 is done by specifying a Routing header as an extension header π¦ There can be different types of Routing headers, but IPv6 currently only defines the Type 0 Routing header [RFC-2460]. This type supports up to 127 intermediate nodes (limited by the length field in the extension header). With that maximum number of intermediate nodes, plus a source and a destination, you get 128 hops π€―
Source routing with the IPv4 sockets API (the IP_OPTIONS socket option) makes the app build the source route in the format that shows up as the IPv4 header option, which needs intimate knowledge of the IPv4 options format π΅βπ« This IPv6 API is way nicer π«Ά It defines six functions the app calls to build and examine a Routing header, and it lets you use sticky options or ancillary data (through the IPV6_RTHDR option) to pass this info between the app and the kernel.
Three functions build a Routing header:
inet6_rth_space() - return #bytes required for Routing header
inet6_rth_init() - initialize buffer data for Routing header
inet6_rth_add() - add one IPv6 address to the Routing header
Three functions deal with a returned Routing header:
inet6_rth_reverse() - reverse a Routing header
inet6_rth_segments() - return #segments in a Routing header
inet6_rth_getaddr() - fetch one address from a Routing header
The function prototypes for these functions are defined when you include <netinet/in.h> π
To receive a Routing header, the app has to enable the IPV6_RECVRTHDR socket option:
int on = 1;
setsockopt(fd, IPPROTO_IPV6, IPV6_RECVRTHDR, &on, sizeof(on));
Each received Routing header comes back as one ancillary data object described by a cmsghdr structure with cmsg_type set to IPV6_RTHDR. When multiple Routing headers are received, multiple ancillary data objects (with cmsg_type set to IPV6_RTHDR) get returned to the app π
To send a Routing header, the app specifies it either as ancillary data in a call to sendmsg() or using setsockopt(). On the sending side, this API assumes the number of occurrences of the Routing header described in [RFC-2460]. That means apps can only specify at most one outgoing Routing header π ββοΈ
The app can remove any sticky Routing header by calling setsockopt() for IPV6_RTHDR with a zero option length π§Ό
When using ancillary data, a Routing header is passed between the app and the kernel like this: the cmsg_level member has a value of IPPROTO_IPV6, and the cmsg_type member has a value of IPV6_RTHDR. The contents of the cmsg_data[] member are implementation dependent and should not be accessed directly by the app. Instead, use the six functions we're about to describe π§
The following constant is defined when you include <netinet/in.h>:
#define IPV6_RTHDR_TYPE_0 0 /* IPv6 Routing header type 0 */
When a Routing header is specified, the destination address given to connect(), sendto(), or sendmsg() is the final destination address of the datagram. The Routing header then contains the addresses of all the intermediate nodes π
7.1. inet6_rth_space β¨
socklen_t inet6_rth_space(int type, int segments);
okay so this one is giving measuring tape π It tells you how many bytes you need for a Routing header of a given type holding a given number of segments (addresses). For an IPv6 Type 0 Routing header, the number of segments must be between 0 and 127, inclusive πΈ The number it returns is only the space for the Routing header itself. If you're using ancillary data, you then pass that length to CMSG_SPACE() to figure out how much memory the ancillary data object needs, including the cmsghdr structure π
If it returns 0, then either the Routing header type isn't supported by this implementation, or the number of segments is invalid for that type π
Note: this function gives you the size but does NOT allocate anything. That's on purpose! All the ancillary data objects have to go into onemsg_controlbuffer passed tosendmsg(), so you can allocate a bigger buffer if you want other ancillary data in there too π«Ά
7.2. inet6_rth_init
void *inet6_rth_init(void *bp, socklen_t bp_len, int type,
int segments);
this one sets up the buffer at bp so it holds a Routing header of the given type, and it sets ip6r_len based on the segments value π¦ The bp_len argument is only there to check that the buffer is big enough. ip6r_segleft gets set to zero, and inet6_rth_add() is what increments it later β¨
When you're using ancillary data, the application has to initialize any cmsghdr fields itself π
The caller is responsible for allocating the buffer, and you can figure out its size by calling inet6_rth_space() π
If everything goes well, the return value is the pointer to the buffer (bp), and you feed that into inet6_rth_add() as the first argument. If something goes wrong, you get NULL back π
7.3. inet6_rth_add
int inet6_rth_add(void *bp, const struct in6_addr *addr);
this tacks the IPv6 address at addr onto the end of the Routing header you're building π§
On success, the segleft member of the Routing Header gets updated to count the new address, and the function returns 0. On an error it returns -1 π
7.4. inet6_rth_reverse
int inet6_rth_reverse(const void *in, void *out);
this one takes an existing Routing header extension header (the first argument) and writes out a brand new Routing header that sends datagrams back along the reverse of that route π It flips the order of the addresses and sets segleft in the new header to the number of segments. Both arguments are allowed to point at the same buffer, so the reversal can happen in place. That's giving efficiency π
It returns 0 on success, or -1 if something goes wrong π
7.5. inet6_rth_segments
int inet6_rth_segments(const void *bp);
this tells you how many segments (addresses) are in the Routing header described by bp π’ On success it returns zero or greater. On an error it returns -1 π«Ά
7.6. inet6_rth_getaddr
struct in6_addr *inet6_rth_getaddr(const void *bp, int index);
this gives you a pointer to the IPv6 address at index, which has to be between 0 and one less than whatever inet6_rth_segments() returned, inside the Routing header described by bp π The application should call inet6_rth_segments() first to find out how many segments there are, so you know what range is valid.
On an error, the return value is NULL π
8. Hop-By-Hop Options β¨
okay bestie, so a single Hop-by-Hop options header can hold a whole bunch of options, and every one of them is TLV-encoded, which means it has a type, a length, and a value π This IPv6 API gives you seven functions to build and read a Hop-by-Hop options header. You can also use sticky options or ancillary data to pass this info back and forth between the app and the kernel π
The header is set using IPV6_HOPOPTS.
Right now there are a few Hop-by-Hop options defined for IPv6. Two of them are pad options, Pad1 and PadN. They're just for alignment, and the inet6_opt_XXX() routines insert them automatically and ignore them on the receive side πΈ So this part of the API is really meant for other (and future) Hop-by-Hop options that an application might need to send and receive π¦
Four functions build the options header:
inet6_opt_init() - initialize buffer data for options header
inet6_opt_append() - add one TLV option to the options header
inet6_opt_finish() - finish adding TLV options to the options
header
inet6_opt_set_val() - add one component of the option content to
the option
Three functions deal with a returned options header:
inet6_opt_next() - extract the next option from the options
header
inet6_opt_find() - extract an option of a specified type from
the header
inet6_opt_get_val() - retrieve one component of the option
content
Individual Hop-by-Hop options (and Destination options, which are covered in Section 9 and are very similar to Hop-by-Hop options) can have specific alignment requirements π For example, the 4-byte Jumbo Payload length should sit on a 4-byte boundary, and IPv6 addresses usually line up on an 8-byte boundary. You'll find these requirements and the terminology explained in Section 4.2 and Appendix B of [RFC-2460]. The alignment of the first byte of each option is described by two values, x and y, written as "xn + y". That means the option has to start at an integer multiple of x bytes from the beginning of the options header (x can be 1, 2, 4, or 8), plus y bytes (y can be anywhere from 0 to 7, inclusive) π Pad1 and PadN options get slotted in as needed to keep that alignment.
The functions also need to know the alignment of the end of the option, which is always in the form "xn," where x can be 1, 2, 4, or 8, plus the total size of the option's data portion. These get passed as the "align" and "len" arguments to inet6_opt_append() π§
Multiple Hop-by-Hop options have to be specified by the application by placing them all in a single extension header π«Ά
Last but not least, using some Hop-by-Hop options or some Destination options might need special privilege π So normal applications (without that privilege) might be blocked from setting certain options in outgoing packets, and they might never see certain options in received packets. Lowkey important! π
8.1. Receiving Hop-by-Hop Options
to receive a Hop-by-Hop options header, the application has to turn on the IPV6_RECVHOPOPTS socket option:
int on = 1;
setsockopt(fd, IPPROTO_IPV6, IPV6_RECVHOPOPTS, &on, sizeof(on));
When you're using ancillary data, a Hop-by-hop options header gets passed between the application and the kernel like this: the cmsg_level member will be IPPROTO_IPV6, and the cmsg_type member will be IPV6_HOPOPTS β¨ After that, you process the options by calling inet6_opt_next(), inet6_opt_find(), and inet6_opt_get_val(), which are described in Section 10 π
8.2. Sending Hop-by-Hop Options
to send a Hop-by-Hop options header, the application specifies the header either as ancillary data in a call to sendmsg(), or by using setsockopt() π¦
If you want to remove a sticky Hop-by-Hop options header, call setsockopt() for IPV6_HOPOPTS with a zero option length π§Ή
All the Hop-by-Hop options have to be specified by a single ancillary data object. The cmsg_level member gets set to IPPROTO_IPV6, and the cmsg_type member gets set to IPV6_HOPOPTS π The option is usually built using inet6_opt_init(), inet6_opt_append(), inet6_opt_finish(), and inet6_opt_set_val(), which are described in Section 10.
Extra errors might be possible from sendmsg() and setsockopt() if the specified option is wrong π
9. Destination Options πΈ
a variable number of Destination options can show up in one or more Destination options headers π As defined in [RFC-2460], a Destination options header that appears before a Routing header gets processed by the first destination plus any later destinations listed in the Routing header. A Destination options header that isn't followed by a Routing header only gets processed by the final destination π Just like Hop-by-Hop options, every option in a Destination options header is TLV-encoded with a type, length, and value.
9.1. Receiving Destination Options
to receive a Destination options header, the application has to turn on the IPV6_RECVDSTOPTS socket option:
int on = 1;
setsockopt(fd, IPPROTO_IPV6, IPV6_RECVDSTOPTS, &on, sizeof(on));
Each Destination options header comes back as one ancillary data object, described by a cmsghdr structure with cmsg_level set to IPPROTO_IPV6 and cmsg_type set to IPV6_DSTOPTS π¦
Then you process these options by calling inet6_opt_next(), inet6_opt_find(), and inet6_opt_get_value() π
9.2. Sending Destination Options
to send a Destination options header, the application specifies it either as ancillary data in a call to sendmsg(), or by using setsockopt() π§
To remove any sticky Destination options header, call setsockopt() for IPV6_RTHDRDSTOPTS/IPV6_DSTOPTS with a zero option length π§Ή
This API assumes the ordering of extension headers described in [RFC-2460]. So one set of Destination options can only appear before a Routing header, and one set can only appear after a Routing header (or in a packet with no Routing header). Each set can have one or more options, but each set is a single extension header π
Today, all the destination options an application might want to specify can go after (or without) a Routing header. So applications should usually only need IPV6_DSTOPTS, and should avoid using IPV6_RTHDRDSTOPTS whenever possible π
When you're using ancillary data, a Destination options header gets passed between the application and the kernel like this: the set that goes before a Routing header is specified with cmsg_level set to IPPROTO_IPV6 and cmsg_type set to IPV6_RTHDRDSTOPTS. Any setsockopt or ancillary data for IPV6_RTHDRDSTOPTS gets silently ignored when sending packets, unless a Routing header is also specified π Note that the "Routing header" here means the one specified by this API. Even when the kernel inserts a routing header in its own internal routine (for example, in a mobile IPv6 stack), the Destination options header specified by IPV6_RTHDRDSTOPTS will still be ignored unless the application explicitly specifies its own Routing header π
The set of Destination options that comes after a Routing header (and gets used when there's no Routing header at all) is specified with cmsg_level set to IPPROTO_IPV6 and cmsg_type set to IPV6_DSTOPTS π
The Destination options are usually built with inet6_opt_init(), inet6_opt_append(), inet6_opt_finish(), and inet6_opt_set_val(), which are described in Section 10 β¨
Extra errors might be possible from sendmsg() and setsockopt() if the specified option is wrong π
10. Hop-by-Hop and Destination Options Processing β¨
Okay so building and parsing Hop-by-Hop and Destination options is genuinely messy, for the reasons we already covered π. So we define a set of helper functions to make life easier for the application π«Ά. These helpers assume the formatting rules in Appendix B in [RFC-2460], which means the largest field goes last in the option π .
The function prototypes come from including <netinet/in.h> π.
The first 3 functions (init, append, and finish) do double duty. They calculate how big the buffer needs to be, and they also encode the options once the application has allocated a buffer for the header π§. If you only want the size, pass a NULL extbuf and a zero extlen to those functions π.
10.1. inet6_opt_init
int inet6_opt_init(void *extbuf, socklen_t extlen);
This function returns the number of bytes needed for the empty extension header, meaning one with no options in it πΈ. If extbuf is not NULL, it also sets up the extension header with the correct length field. In that case, if extlen is not a positive (i.e., non-zero) multiple of 8, the function fails and returns -1 π.
(Note: since the return value on success is based on a "constant" parameter, i.e., the empty extension header, an implementation may return a constant value. However, this specification does not require the value be constant, and leaves it as implementation dependent. The application should not assume a particular constant value as a successful return value of this function.) π
10.2. inet6_opt_append
int inet6_opt_append(void *extbuf, socklen_t extlen, int offset,
uint8_t type, socklen_t len, uint_t align,
void **databufp);
Offset should be the length you got back from inet6_opt_init() or a previous inet6_opt_append() π¦. The function gives you back the updated total length, counting the new option with length len and alignment align π. If extbuf is not NULL, then on top of returning the length, it slides in any pad option that's needed, sets up the option (type and length fields), and hands you a pointer to where the option content goes in databufp β¨. If the option won't fit in the extension header buffer, the function returns -1 π.
Type is the 8-bit option type. Len is the length of the option data (i.e., excluding the option type and option length fields) π.
Once inet6_opt_append() has run, you can write straight into databuf, or use inet6_opt_set_val() to fill in the option content π .
The option type has to be a value from 2 to 255, inclusive. (0 and 1 are reserved for the Pad1 and PadN options, respectively, so they're off limits π ββοΈ.)
The option data length has to be between 0 and 255, inclusive, and it's the length of the option data that follows π.
The align parameter has to be 1, 2, 4, or 8 π. The align value can not exceed the value of len π« .
10.3. inet6_opt_finish
int inet6_opt_finish(void *extbuf, socklen_t extlen, int offset);
Offset should be the length you got back from inet6_opt_init() or inet6_opt_append() π§. The function returns the updated total length, including the final padding that makes the extension header a multiple of 8 bytes π. If extbuf is not NULL, the function also sets up the option by slipping in a Pad1 or PadN option of the right size β¨.
If the necessary pad doesn't fit in the extension header buffer, the function returns -1 π.
10.4. inet6_opt_set_val
int inet6_opt_set_val(void *databuf, int offset, void *val,
socklen_t vallen);
Databuf should be a pointer returned by inet6_opt_append() π¦. This function drops data items of different sizes into the data portion of the option π. Val should point to the data you want to insert π. Offset tells it where in the data portion the value goes. The first byte after the option type and length is at offset zero πΈ.
The caller should make sure each field lines up on its natural boundaries, as described in Appendix B of [RFC-2460], but the function must not rely on the caller doing that π«Ά. Even when the alignment isn't satisfied, inet6_opt_set_val should just copy the data as required π.
The function returns the offset for the next field (i.e., offset + vallen), which you can use when building option content with multiple fields π .
10.5. inet6_opt_next
int inet6_opt_next(void *extbuf, socklen_t extlen, int offset,
uint8_t *typep, socklen_t *lenp,
void **databufp);
This function parses received option extension headers and gives you back the next option π. Extbuf and extlen describe the extension header π. Offset should be zero for the first option, or the length returned by a previous call to inet6_opt_next() or inet6_opt_find() π. It marks the spot where scanning picks back up in the extension buffer β¨. The next option comes back through updated typep, lenp, and databufp. Typep holds the option type, lenp holds the length of the option data (i.e., excluding the option type and option length fields), and databufp points at the data field of the option π.
This function returns the updated "previous" length, computed by advancing past the option it just returned. You can pass that "previous" length into the next inet6_opt_next() call π₯. It does not return any PAD1 or PADN options, so those are invisible to you π«₯. When there are no more options, or the option extension header is malformed, the return value is -1 π.
10.6. inet6_opt_find
int inet6_opt_find(void *extbuf, socklen_t extlen, int offset,
uint8_t type, socklen_t *lenp,
void **databufp);
This one is basically inet6_opt_next() but with a twist: you pick the option type you're hunting for, instead of getting whatever comes next in the extension header π΅οΈββοΈ.
If it finds an option of the type you asked for, it returns the updated "previous" total length. That's computed by advancing past the option it returned, and past any options that didn't match the type π. You can pass that "previous" length into later inet6_opt_find() calls to hunt for the next occurrence of the same type π¦.
If no option of that type is found, the return value is -1. If the option extension header is malformed, the return value is also -1 π.
10.7. inet6_opt_get_val
int inet6_opt_get_val(void *databuf, int offset, void *val,
socklen_t vallen);
Databuf should be a pointer returned by inet6_opt_next() or inet6_opt_find() π§. This function pulls data items of various sizes out of the data portion of the option π. Val should point to where the extracted data should land π. Offset tells it where in the data portion to start extracting, and again the first byte after the option type and length is offset zero β¨.
Each field is expected to line up on its natural boundaries, as described in Appendix B of [RFC-2460], but the function must not rely on that alignment π«Ά.
The function returns the offset for the next field (i.e., offset + vallen), which you can use when pulling out option content with multiple fields πΈ.
11. Additional Advanced API Functions β¨
11.1. Sending with the Minimum MTU
Unicast apps should usually let the kernel handle path MTU discovery [RFC-1981], as long as the kernel supports it, and they shouldn't have to care about the path MTU π . Some apps, though, don't want to deal with the extra overhead of path MTU discovery, especially if they only ever send a single datagram to a destination π. A DNS server is a potential example π.
[RFC-1981] explains how path MTU discovery works for multicast destinations π₯. But from real-world experience with IPv4 multicast, lots of careless apps send big multicast packets on the wire, and that has caused implosions of ICMPv4 error messages π. It gets worse when there's a filtering node blocking those ICMPv4 messages π. Filtering is a problem for unicast too, but the impact is way bigger with multicast π« .
So, applications sending multicast traffic should explicitly turn on path MTU discovery only when they understand that the benefit of possibly larger MTU usage outweighs the possible impact of MTU discovery on active sources across the delivery tree(s) π. This default behavior is based on today's practice with IPv4 multicast and path MTU discovery. It may change in the future once path MTU discovery is found to effectively work with actual multicast applications and network configurations π¦.
This specification defines a mechanism to avoid path MTU discovery by sending at the minimum IPv6 MTU [RFC-2460] π. If the packet is larger than the minimum MTU and this feature is enabled, the IP layer will fragment down to the minimum MTU β¨. To control the path MTU discovery policy, applications can use the IPV6_USE_MIN_MTU socket option π.
As described above, the default policy should depend on whether the destination is unicast or multicast. For unicast destinations, path MTU discovery should be performed by default. For multicast destinations, path MTU discovery should be disabled by default π. So this option takes the following three integer arguments π:
-1: perform path MTU discovery for unicast destinations but do not perform it for multicast destinations. Packets to multicast destinations are therefore sent with the minimum MTU πΈ.0: always perform path MTU discovery π₯.1: always disable path MTU discovery and send packets at the minimum MTU π ββοΈ.
The default value of this option is -1. Values other than -1, 0, and 1 are invalid, and those will return the error EINVAL π.
As an example, if a unicast application wants to disable path MTU discovery on purpose, it adds these lines π§:
int on = 1;
setsockopt(fd, IPPROTO_IPV6, IPV6_USE_MIN_MTU, &on, sizeof(on));
Heads up, though: this API intentionally leaves out the case where an application wants path MTU discovery for multicast but disabled for unicast π. That's because the performance issues around deciding whether to do path MTU discovery make that usage not really feasible π΅βπ«. When path MTU discovery makes sense for one destination but not another, whether unicast or multicast, applications either need to toggle the option between sends on the same socket, or use different sockets for the two classes of destinations π«Ά.
This option can also be sent as ancillary data. In the cmsghdr structure holding this ancillary data, the cmsg_level member will be IPPROTO_IPV6, the cmsg_type member will be IPV6_USE_MIN_MTU, and the first byte of cmsg_data[] will be the first byte of the integer π¦.
11.2. Sending without Fragmentation β¨
Okay so, to make life easy for existing UDP and raw socket apps, IPv6 implementations will, when they originate packets, automatically insert a fragment header into any packet that's too big for the path MTU π§ Super helpful, but not every app wants that. Traceroute is the classic example, since it wants to discover the actual path MTU π
This spec gives you a way to turn off that automatic fragment header insertion for UDP and raw sockets, using the IPV6_DONTFRAG socket option π
int on = 1;
setsockopt(fd, IPPROTO_IPV6, IPV6_DONTFRAG, &on, sizeof(on));
It's disabled by default. Setting the value to 0 also disables it, which puts you right back on automatic inserting π You can also send this option as ancillary data. In that cmsghdr, cmsg_level is IPPROTO_IPV6, cmsg_type is IPV6_DONTFRAG, and the first byte of cmsg_data[] is the first byte of the integer π¦ This API only covers this option for UDP and raw sockets. It doesn't define how TCP sockets use it, so hands off TCP π ββοΈ
Now the catch. If the data is bigger than the MTU of the outgoing interface, the packet gets discarded π You can find out what happened by enabling IPV6_RECVPATHMTU (more on that below) and receiving the matching ancillary data items. Some implementations may also return an extra error, EMSGSIZE, but ngl, others might not be able to return that error when sending a message π
11.3. Path MTU Discovery and UDP πΈ
UDP and raw socket apps need a way to find the "maximum send transport-message size" (Section 5.1 of [RFC-1981]) for a given destination, so they can join in on path MTU discovery. That lets them send smaller datagrams and dodge fragmentation π«Ά
This happens through a new ancillary data item, IPV6_PATHMTU, which gets delivered to recvmsg() with no actual data attached. To receive it, the app turns on the IPV6_RECVPATHMTU socket option π₯
int on = 1;
setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPATHMTU, &on, sizeof(on));
It's disabled by default, and setting it to 0 turns it off again. This API only covers this option for UDP and raw sockets, not TCP π
When the app sends packets that are too big for the path MTU, recvmsg() returns zero (no data), but there's a cmsghdr with cmsg_type set to IPV6_PATHMTU, and cmsg_len says cmsg_data is sizeof(struct ip6_mtuinfo) bytes long β¨ This can happen when the sending node gets a matching ICMPv6 packet too big error, or when the packet is sent from a socket with IPV6_DONTFRAG on and the packet is larger than the MTU of the outgoing interface. The indication counts as an ancillary data item for a separate (empty) message. So if there are buffered messages (ones the app hasn't received yet) on the socket, the app gets those first, and then the indication π§
The first byte of cmsg_data[] points to a struct ip6_mtuinfo, which carries the path MTU to use with the IPv6 destination address π
struct ip6_mtuinfo {
struct sockaddr_in6 ip6m_addr; /* dst address including
zone ID */
uint32_t ip6m_mtu; /* path MTU in host byte order */
};
This cmsghdr gets passed to every socket that sets IPV6_RECVPATHMTU, even non-connected ones π Also, an app that sets the option may get an IPV6_MTU ancillary data item for every ICMP too big error the node receives, including ICMP errors caused by other apps on the same node π So if your app wants to do path MTU discovery by itself, you need to keep a history of the destinations you've actually sent to, and compare the address in the ip6_mtuinfo structure against that history π΅οΈββοΈ An implementation may choose not to deliver data to a connected socket whose foreign address differs from the address in the ip6m_addr structure.
Heads up: when an app sends a packet with a routing header, the final destination stored in the ip6m_addr member doesn't necessarily have the complete information for the entire path π¨
11.4. Determining the Current Path MTU π¦
Sometimes apps need to figure out the current path MTU. For example, apps using IPV6_RECVPATHMTU might want a good starting value π
This spec defines a get-only socket option that retrieves the current path MTU for the destination of a given connected socket. If the IP layer doesn't have a cached path MTU value, it returns the interface MTU for the interface that would be used to send to that destination address π
You get this info through the IPV6_PATHMTU socket option. It takes a pointer to an ip6_mtuinfo structure as the fourth argument, and the size of that structure goes in as a value-result parameter in the fifth argument π
struct ip6_mtuinfo mtuinfo;
socklen_t infolen = sizeof(mtuinfo);
getsockopt(fd, IPPROTO_IPV6, IPV6_PATHMTU, &mtuinfo, &infolen);
When the call succeeds, the path MTU value is stored in the ip6m_mtu member. Since the socket is connected, ip6m_addr is meaningless, so the app should not refer to it π ββοΈ
This option only works on a connected socket. A non-connected socket doesn't have the destination info, and there's no way to pass the destination via getsockopt(), so the call fails on non-connected sockets π Despite that limit, it's still super useful, because apps that care about path MTU tend to send lots of packets to one destination, and they connect the socket to that destination for performance reasons β If an app needs the MTU in a more generic way, it should use a more generic interface, such as routing sockets [TCPIPILLUST] π§
12. Ordering of Ancillary Data and IPv6 Extension Headers π
Three IPv6 extension headers can be set by the app and returned to it through ancillary data with sendmsg() and recvmsg(): the Routing header, the Hop-by-Hop options header, and the Destination options header π When multiple ancillary data objects come through recvmsg() and represent any of these three headers, where they sit in the control buffer is directly tied to where they sit in the IPv6 datagram π§© For example, say the app has enabled IPV6_RECVRTHDR and IPV6_RECVDSTOPTS, and later gets an IPv6 packet with extension headers in this order:
The IPv6 header
A Hop-by-Hop options header
A Destination options header (1)
A Routing header
An Authentication header
A Destination options header (2)
A UDP header and UDP data
Then the app gets three ancillary data objects, in this order:
- an object with cmsg_type set to IPV6_DSTOPTS, which represents the destination options header (1)
- an object with cmsg_type set to IPV6_RTHDR, which represents the Routing header
- an object with cmsg_type set to IPV6_DSTOPTS, which represents the destination options header (2)
This example follows the header ordering in [RFC-2460], but the receiving side of this spec doesn't assume any ordering. Apps may get any number of objects in any order, matching the order of the received IPv6 datagram πΈ
The sending side is different, though. This API imposes some ordering constraints based on [RFC-2460]. Apps using this API can't build a packet with extension headers that don't follow that ordering. But that doesn't mean apps must always follow the restriction. It's just a limitation of this API, meant to give programmers a guideline for building headers in a practical way π If an app needs to build an outgoing packet with extension headers in an arbitrary order, some other technique, like the datalink interfaces BPF or DLPI, has to be used π οΈ
Here are the details of the constraints:
- Each IPV6_xxx ancillary data object for a particular type of extension header can be specified at most once in a single control buffer.
- IPV6_xxx ancillary data objects can appear in any order in a control buffer, because there's no ambiguity about the ordering.
- Each set of IPV6_xxx ancillary data objects and sticky options will be put in the outgoing packet following the header ordering described in [RFC-2460].
- An ancillary data object or a sticky option of IPV6_RTHDRDSTOPTS affects the outgoing packet only when a Routing header is specified as an ancillary data object or a sticky option. Otherwise, the specified value for IPV6_RTHDRDSTOPTS is ignored.
For example, say an app sends a UDP datagram with a control data buffer holding these ancillary data objects, in this order:
- an object with cmsg_type set to IPV6_DSTOPTS
- an object with cmsg_type set to IPV6_RTHDRDSTOPTS
- an object with cmsg_type set to IPV6_HOPOPTS
If the sending socket has no sticky options, the outgoing packet gets built like this:
The IPv6 header
A Hop-by-Hop options header
A Destination options header
A UDP header and UDP data
where the destination options header corresponds to the ancillary data object with the type IPV6_DSTOPTS π¦
Heads up though: the constraints above don't necessarily mean the packet on the wire always follows the header ordering in this API document. The kernel may insert extra headers that break the ordering as a result. For example, if the kernel supports Mobile IPv6, an extra destination options header may get inserted before an authentication header, even without a routing header π
This API doesn't give access to any extension headers beyond those three types. In particular, it provides no info about the IP security headers on an incoming packet, and they can't be specified for an outgoing packet either. This API is for apps that don't care whether IP security headers exist ππ«Ά
13. IPv6-Specific Options with IPv4-Mapped IPv6 Addresses β¨
okay so all the socket options and ancillary data stuff we've been talking about in this doc is only for true IPv6 sockets π§ it IS possible to make an IPv6 socket that actually sends and receives IPv4 packets using IPv4-mapped IPv6 addresses, but how the options in this doc map onto an IPv4 datagram is totally out of scope for this doc π
ngl, if you try to set an IPv6-only option like Hop-by-Hop options, Destination options, or a Routing header on an IPv6 socket that's using IPv4-mapped IPv6 addresses, it will probably throw an error π some implementations might still let you get at the packet information (source/destination address, send/receive interface, and hop limit) on that kind of socket though, so it's not a guarantee either way π«Ά
14. Extended interfaces for rresvport, rcmd and rexec π
the "r" commands are kind of the OG remote tools, and the library functions behind them hide the socket creation and name resolution from the application π the issue is that when those libraries hand back an AF_INET6 socket to an app that doesn't support that address family, things can get weird, like the app getting something unexpected when it calls getpeername() on the socket π so to support AF_INET6 sockets for the "r" commands and still keep backward compatibility, this section adds a few extensions to the libraries. iconic behavior tbh π
14.1. rresvport_af π¦
rresvport() is used by rcmd(), and rcmd() is called by a bunch of the "r" commands, like rlogin πΈ nobody's writing new apps with rcmd() anymore, but legacy apps like rlogin will keep using it, and those are the ones that'll get ported to IPv6.
rresvport() makes an IPv4/TCP socket and binds a "reserved port" to it. Instead of making an IPv6 version of that function, we're adding a brand new function that takes an address family as an argument, which is way more chic π
#include <unistd.h>
int rresvport_af(int *port, int family);
This function acts exactly like the existing rresvport() function, except instead of only creating an AF_INET TCP socket, it can also create an AF_INET6 TCP socket β¨ the family argument is either AF_INET or AF_INET6, and if the address family isn't supported you get a new error return, EAFNOSUPPORT π«
(Note: There is little consensus on which header defines the rresvport() and rcmd() function prototypes. 4.4BSD defines it in <unistd.h>, others in <netdb.h>, and others don't define the function prototypes at all. π€·ββοΈ)
14.2. rcmd_af π
the existing rcmd() can't just quietly use AF_INET6 sockets, because an app wouldn't be ready to handle AF_INET6 addresses coming back from things like getpeername() on the file descriptor that rcmd() made π¬ so we need a new function for this.
int rcmd_af(char **ahost, unsigned short rport,
const char *locuser, const char *remuser,
const char *cmd, int *fd2p, int af)
this one behaves the same as the existing rcmd(), but instead of only making an AF_INET TCP socket, it can make an AF_INET6 TCP socket too π the family argument is AF_INET, AF_INET6, or AF_UNSPEC. if you pass AF_INET or AF_INET6, it creates a socket of that family. if you pass AF_UNSPEC, it'll keep trying every possible address family until a connection goes through, and then it returns the socket for that connection π§ if the address family isn't supported, you get the new error EAFNOSUPPORT.
14.3. rexec_af π
same story with rexec(): the existing one can't transparently use AF_INET6 sockets, since an app wouldn't be prepared for AF_INET6 addresses from things like getpeername() on the file descriptor rexec() creates π so yep, a new function is needed.
int rexec_af(char **ahost, unsigned short rport, const char *name,
const char *pass, const char *cmd, int *fd2p, int af)
this acts the same as the existing rexec(), but instead of only creating an AF_INET TCP socket, it can create an AF_INET6 TCP socket as well β the family argument is AF_INET, AF_INET6, or AF_UNSPEC, and it works just like rcmd_af: a specific family gets you a socket of that family, while AF_UNSPEC tries every possible family until a connection is established and returns that socket. if the address family isn't supported, you get EAFNOSUPPORT π₯
15. Summary of New Definitions β¨
Okay bestie, here's the whole cheat sheet of everything we introduced, sorted by header file so you can find stuff fast π§
Constants and structures first π
The following list summarizes the constants and structure,
definitions discussed in this memo, sorted by header.
<netinet/icmp6.h> ICMP6_DST_UNREACH
<netinet/icmp6.h> ICMP6_DST_UNREACH_ADDR
<netinet/icmp6.h> ICMP6_DST_UNREACH_ADMIN
<netinet/icmp6.h> ICMP6_DST_UNREACH_BEYONDSCOPE
<netinet/icmp6.h> ICMP6_DST_UNREACH_NOPORT
<netinet/icmp6.h> ICMP6_DST_UNREACH_NOROUTE
<netinet/icmp6.h> ICMP6_ECHO_REPLY
<netinet/icmp6.h> ICMP6_ECHO_REQUEST
<netinet/icmp6.h> ICMP6_INFOMSG_MASK
<netinet/icmp6.h> ICMP6_PACKET_TOO_BIG
<netinet/icmp6.h> ICMP6_PARAMPROB_HEADER
<netinet/icmp6.h> ICMP6_PARAMPROB_NEXTHEADER
<netinet/icmp6.h> ICMP6_PARAMPROB_OPTION
<netinet/icmp6.h> ICMP6_PARAM_PROB
<netinet/icmp6.h> ICMP6_ROUTER_RENUMBERING
<netinet/icmp6.h> ICMP6_RR_FLAGS_FORCEAPPLY
<netinet/icmp6.h> ICMP6_RR_FLAGS_PREVDONE
<netinet/icmp6.h> ICMP6_RR_FLAGS_REQRESULT
<netinet/icmp6.h> ICMP6_RR_FLAGS_SPECSITE
<netinet/icmp6.h> ICMP6_RR_FLAGS_TEST
<netinet/icmp6.h> ICMP6_RR_PCOUSE_FLAGS_DECRPLTIME
<netinet/icmp6.h> ICMP6_RR_PCOUSE_FLAGS_DECRVLTIME
<netinet/icmp6.h> ICMP6_RR_PCOUSE_RAFLAGS_AUTO
<netinet/icmp6.h> ICMP6_RR_PCOUSE_RAFLAGS_ONLINK
<netinet/icmp6.h> ICMP6_RR_RESULT_FLAGS_FORBIDDEN
<netinet/icmp6.h> ICMP6_RR_RESULT_FLAGS_OOB
<netinet/icmp6.h> ICMP6_TIME_EXCEEDED
<netinet/icmp6.h> ICMP6_TIME_EXCEED_REASSEMBLY
<netinet/icmp6.h> ICMP6_TIME_EXCEED_TRANSIT
<netinet/icmp6.h> MLD_LISTENER_QUERY
<netinet/icmp6.h> MLD_LISTENER_REDUCTION
<netinet/icmp6.h> MLD_LISTENER_REPORT
<netinet/icmp6.h> ND_NA_FLAG_OVERRIDE
<netinet/icmp6.h> ND_NA_FLAG_ROUTER
<netinet/icmp6.h> ND_NA_FLAG_SOLICITED
<netinet/icmp6.h> ND_NEIGHBOR_ADVERT
<netinet/icmp6.h> ND_NEIGHBOR_SOLICIT
<netinet/icmp6.h> ND_OPT_MTU
<netinet/icmp6.h> ND_OPT_PI_FLAG_AUTO
<netinet/icmp6.h> ND_OPT_PI_FLAG_ONLINK
<netinet/icmp6.h> ND_OPT_PREFIX_INFORMATION
<netinet/icmp6.h> ND_OPT_REDIRECTED_HEADER
<netinet/icmp6.h> ND_OPT_SOURCE_LINKADDR
<netinet/icmp6.h> ND_OPT_TARGET_LINKADDR
<netinet/icmp6.h> ND_RA_FLAG_MANAGED
<netinet/icmp6.h> ND_RA_FLAG_OTHER
<netinet/icmp6.h> ND_REDIRECT
<netinet/icmp6.h> ND_ROUTER_ADVERT
<netinet/icmp6.h> ND_ROUTER_SOLICIT
<netinet/icmp6.h> struct icmp6_filter{};
<netinet/icmp6.h> struct icmp6_hdr{};
<netinet/icmp6.h> struct icmp6_router_renum{};
<netinet/icmp6.h> struct mld_hdr{};
<netinet/icmp6.h> struct nd_neighbor_advert{};
<netinet/icmp6.h> struct nd_neighbor_solicit{};
<netinet/icmp6.h> struct nd_opt_hdr{};
<netinet/icmp6.h> struct nd_opt_mtu{};
<netinet/icmp6.h> struct nd_opt_prefix_info{};
<netinet/icmp6.h> struct nd_opt_rd_hdr{};
<netinet/icmp6.h> struct nd_redirect{};
<netinet/icmp6.h> struct nd_router_advert{};
<netinet/icmp6.h> struct nd_router_solicit{};
<netinet/icmp6.h> struct rr_pco_match{};
<netinet/icmp6.h> struct rr_pco_use{};
<netinet/icmp6.h> struct rr_result{};
<netinet/in.h> IPPROTO_AH
<netinet/in.h> IPPROTO_DSTOPTS
<netinet/in.h> IPPROTO_ESP
<netinet/in.h> IPPROTO_FRAGMENT
<netinet/in.h> IPPROTO_HOPOPTS
<netinet/in.h> IPPROTO_ICMPV6
<netinet/in.h> IPPROTO_IPV6
<netinet/in.h> IPPROTO_NONE
<netinet/in.h> IPPROTO_ROUTING
<netinet/in.h> IPV6_CHECKSUM
<netinet/in.h> IPV6_DONTFRAG
<netinet/in.h> IPV6_DSTOPTS
<netinet/in.h> IPV6_HOPLIMIT
<netinet/in.h> IPV6_HOPOPTS
<netinet/in.h> IPV6_NEXTHOP
<netinet/in.h> IPV6_PATHMTU
<netinet/in.h> IPV6_PKTINFO
<netinet/in.h> IPV6_RECVDSTOPTS
<netinet/in.h> IPV6_RECVHOPLIMIT
<netinet/in.h> IPV6_RECVHOPOPTS
<netinet/in.h> IPV6_RECVPKTINFO
<netinet/in.h> IPV6_RECVRTHDR
<netinet/in.h> IPV6_RECVTCLASS
<netinet/in.h> IPV6_RTHDR
<netinet/in.h> IPV6_RTHDRDSTOPTS
<netinet/in.h> IPV6_RTHDR_TYPE_0
<netinet/in.h> IPV6_RECVPATHMTU
<netinet/in.h> IPV6_TCLASS
<netinet/in.h> IPV6_USE_MIN_MTU
<netinet/in.h> struct in6_pktinfo{};
<netinet/in.h> struct ip6_mtuinfo{};
<netinet/ip6.h> IP6F_MORE_FRAG
<netinet/ip6.h> IP6F_OFF_MASK
<netinet/ip6.h> IP6F_RESERVED_MASK
<netinet/ip6.h> IP6OPT_JUMBO
<netinet/ip6.h> IP6OPT_JUMBO_LEN
<netinet/ip6.h> IP6OPT_MUTABLE
<netinet/ip6.h> IP6OPT_NSAP_ADDR
<netinet/ip6.h> IP6OPT_PAD1
<netinet/ip6.h> IP6OPT_PADN
<netinet/ip6.h> IP6OPT_ROUTER_ALERT
<netinet/ip6.h> IP6OPT_TUNNEL_LIMIT
<netinet/ip6.h> IP6OPT_TYPE_DISCARD
<netinet/ip6.h> IP6OPT_TYPE_FORCEICMP
<netinet/ip6.h> IP6OPT_TYPE_ICMP
<netinet/ip6.h> IP6OPT_TYPE_SKIP
<netinet/ip6.h> IP6_ALERT_AN
<netinet/ip6.h> IP6_ALERT_MLD
<netinet/ip6.h> IP6_ALERT_RSVP
<netinet/ip6.h> struct ip6_dest{};
<netinet/ip6.h> struct ip6_frag{};
<netinet/ip6.h> struct ip6_hbh{};
<netinet/ip6.h> struct ip6_hdr{};
<netinet/ip6.h> struct ip6_opt{};
<netinet/ip6.h> struct ip6_opt_jumbo{};
<netinet/ip6.h> struct ip6_opt_nsap{};
<netinet/ip6.h> struct ip6_opt_router{};
<netinet/ip6.h> struct ip6_opt_tunnel{};
<netinet/ip6.h> struct ip6_rthdr{};
<netinet/ip6.h> struct ip6_rthdr0{};
Now the function and macro prototypes π¦
The following list summarizes the function and macro prototypes
discussed in this memo, sorted by header.
<netinet/icmp6.h> void ICMP6_FILTER_SETBLOCK(int, struct
icmp6_filter *);
<netinet/icmp6.h> void
ICMP6_FILTER_SETBLOCKALL(struct icmp6_filter *);
<netinet/icmp6.h> void
ICMP6_FILTER_SETPASS(int,
struct icmp6_filter *);
<netinet/icmp6.h> void
ICMP6_FILTER_SETPASSALL(struct icmp6_filter *);
<netinet/icmp6.h> int ICMP6_FILTER_WILLBLOCK(int,
const struct icmp6_filter *);
<netinet/icmp6.h> int ICMP6_FILTER_WILLPASS(int,
const struct icmp6_filter *);
<netinet/in.h> int IN6_ARE_ADDR_EQUAL(const struct in6_addr *,
const struct in6_addr *);
<netinet/in.h> int inet6_opt_append(void *, socklen_t, int,
uint8_t, socklen_t, uint_t,
void **);
<netinet/in.h> int inet6_opt_get_val(void *, int, void *,
socklen_t);
<netinet/in.h> int inet6_opt_find(void *, socklen_t,
int, uint8_t ,
socklen_t *, void **);
<netinet/in.h> int inet6_opt_finish(void *, socklen_t, int);
<netinet/in.h> int inet6_opt_init(void *, socklen_t);
<netinet/in.h> int inet6_opt_next(void *, socklen_t,
int, uint8_t *,
socklen_t *, void **);
<netinet/in.h> int inet6_opt_set_val(void *, int,
void *, socklen_t);
<netinet/in.h> int inet6_rth_add(void *,
const struct in6_addr *);
<netinet/in.h> struct in6_addr inet6_rth_getaddr(const void *,
int);
<netinet/in.h> void *inet6_rth_init(void *, socklen_t,
int, int);
<netinet/in.h> int inet6_rth_reverse(const void *, void *);
<netinet/in.h> int inet6_rth_segments(const void *);
<netinet/in.h> soccklen_t inet6_rth_space(int, int);
<netinet/ip6.h> int IP6OPT_TYPE(uint8_t);
<sys/socket.h> socklen_t CMSG_LEN(socklen_t);
<sys/socket.h> socklen_t CMSG_SPACE(socklen_t);
<unistd.h> int rresvport_af(int *, int);
<unistd.h> int rcmd_af(char **, unsigned short,
const char *, const char *,
const char *, int *, int);
<unistd.h> int rexec_af(char **, unsigned short,
const char *, const char *,
const char *, int *, int);
16. Security Considerations π
Okay, this bit is seriously important, so pay attention π₯ Certain Hop-by-Hop options and Destination options may be restricted to privileged processes, so a regular app might not be allowed to set them. Similarly, some Hop-by-Hop options and Destination options may not be handed back to non-privileged applications.
Also, the ability to specify an arbitrary source address using IPV6_PKTINFO has to be prevented, at least for non-privileged processes. Do NOT let that slip π
ββοΈ
17. Changes from RFC 2292 π
okay bestie, this is the part where we talk about what changed since RFC 2292 π¦ these are the changes that actually affect compatibility, so read carefully π
Significant changes that affect compatibility with RFC 2292:
- Dropped the
IPV6_PKTOPTIONSsocket option. Sticky options can now be set with individualsetsockopt()calls instead π - You can't specify Hop-by-Hop and Destination options with multiple ancillary data items anymore. The application is responsible for formatting the whole extension header using the
inet6_opt_xxx()routines (more on those below) π§ - Support for the loose/strict Routing header is gone, since that was removed from the IPv6 specification π
- Loosened the constraints for the jumbo payload option, which was always hidden from applications π
- The
IPV6_HOPLIMITsticky option is disabled π - The
ip6r0_addrfield was removed from theip6_rthdrstructure π - Intentionally left unspecified how to get a received packet's information on TCP sockets π«Ά
New features:
- Added
IPV6_RTHDRDSTOPTSto specify a Destination Options header before the Routing header π¦ - Added separate
IPV6_RECVxxxoptions to enable receipt of each corresponding ancillary data item β¨ - Added
inet6_rth_xxx()andinet6_opt_xxx()functions to deal with routing or IPv6 options headers π₯ - Added extensions of libraries for the "r" commands πΈ
- Introduced more IPv6 option definitions, like
IP6OPT_PAD1π - Added MLD and router renumbering definitions π
- Added MTU-related socket options and ancillary data items π
- Added options and ancillary data items to manipulate the traffic class field π§
- Changed the name of ICMPv6 unreachable code 2 to "beyond scope of source address."
ICMP6_DST_UNREACH_NOTNEIGHBORwas removed with this change π
Clarifications:
- Extension header ordering: on the sending side, assume the recommended ordering described in RFC 2460. On the receiving side, don't assume any ordering, and pass all headers to the application in the received order π¦
- Added a summary about the interface selection rule πΊοΈ
- Clarified the ordering between
IPV6_MULTICAST_IFand theIPV6_PKTINFOsticky option for multicast packets π― - Clarified how sticky options and the ICMPv6 filter are turned off, and that
getsockopt()of a sticky option returns what was set withsetsockopt()π - Clarified that
IPV6_NEXTHOPshould be ignored for a multicast destination, that it should not contradict the specified outgoing interface, and that the next hop should be asockaddr_in6structure π§ - Clarified corner cases of
IPV6_CHECKSUMπ - Aligned with the POSIX standard π€
Editorial changes:
- Replaced
MUSTwithmust, since this is an informational document π - Revised the abstract to be more clear and concise, focusing especially on differences from RFC 2292 βοΈ
- Made the URL of assigned numbers less specific so it would be more robust to future changes π
- Updated the reference to the basic API π
- Added a reference to the latest POSIX standard π
- Moved the general specifications of ancillary data and CMSG macros to the appendix ποΈ
18. References π
[RFC-1981] McCann, J., Deering, S. and J. Mogul, "Path MTU
Discovery for IP version 6", RFC 1981, August 1996.
[RFC-2460] Deering, S. and R. Hinden, "Internet Protocol, Version
6 (IPv6) Specification", RFC 2460, December 1998.
[RFC-3493] Gilligan, R., Thomson, S., Bound, J., McCann, J. and
W. Stevens, "Basic Socket Interface Extensions for
IPv6", RFC 3493, March 2003.
[POSIX] IEEE Std. 1003.1-2001 Standard for Information
Technology -- Portable Operating System Interface
(POSIX). Open group Technical Standard: Base
Specifications, Issue 6, December 2001. ISO/IEC
9945:2002. http://www.opengroup.org/austin
[TCPIPILLUST] Wright, G., Stevens, W., "TCP/IP Illustrated, Volume 2:
The Implementation", Addison Wesley, 1994.
19. Acknowledgments π«Ά
Matt Thomas and Jim Bound have been working on the technical details in this document for over a year π Keith Sklower is the original implementor of ancillary data in the BSD networking code π Craig Metz gave lots of feedback, suggestions, and comments based on implementing many of these features while the document was being written π οΈ Mark Andrews first proposed the idea of the IPV6_USE_MIN_MTU option π‘ and Jun-ichiro Hagino contributed text for the traffic class API from a document of his own π§
The following people provided comments on earlier drafts π: Pascal Anelli, Hamid Asayesh, Ran Atkinson, Karl Auerbach, Hamid Asayesh, Don Coolidge, Matt Crawford, Sam T. Denton, Richard Draves, Francis Dupont, Toerless Eckert, Lilian Fernandes, Bob Gilligan, Gerri Harter, Tim Hartrick, Bob Halley, Masaki Hirabaru, Michael Hunter, Yoshinobu Inoue, Mukesh Kacker, A. N. Kuznetsov, Sam Manthorpe, Pedro Marques, Jack McCann, der Mouse, John Moy, Lori Napoli, Thomas Narten, Atsushi Onoe, Steve Parker, Charles Perkins, Ken Powell, Tom Pusateri, Pedro Roque, Sameer Shah, Peter Sjodin, Stephen P. Spackman, Jinmei Tatuya, Karen Tracey, Sowmini Varadhan, Quaizar Vohra, Carl Williams, Steve Wise, Eric Wong, Farrell Woods, Kazu Yamamoto, Vladislav Yasevich, and Yoshifuji Hideaki πΈβ¨
20. Appendix A: Ancillary Data Overview π
okay so back in 4.2BSD, file descriptors could be passed between separate processes across a UNIX domain socket using sendmsg() and recvmsg() π¨ Two members of the msghdr structure, msg_accrights and msg_accrightslen, were used to send and receive the descriptors. When the OSI protocols were added to 4.3BSD Reno in 1990, those two fields got renamed to msg_control and msg_controllen, because the OSI protocols used them for "control information." The comments in the source code still call it "ancillary data," though π€
Other than the OSI protocols, ancillary data was pretty rare π₯² In 4.4BSD, for example, the only use of ancillary data with IPv4 was returning the destination address of a received UDP datagram if the IP_RECVDSTADDR socket option was set. With Unix domain sockets, ancillary data is still used to send and receive descriptors π₯
Still, the ancillary data fields of the msghdr structure give us a clean way to pass information alongside the data being read or written π
Including the msg_control and msg_controllen members of msghdr, along with the cmsghdr structure that msg_control points to, is required by the Posix sockets API standard π
20.1. The msghdr Structure
The msghdr structure is used by the recvmsg() and sendmsg() functions. Its Posix definition is:
struct msghdr {
void *msg_name; /* ptr to socket address
structure */
socklen_t msg_namelen; /* size of socket address
structure */
struct iovec *msg_iov; /* scatter/gather array */
int msg_iovlen; /* # elements in msg_iov */
void *msg_control; /* ancillary data */
socklen_t msg_controllen; /* ancillary data buffer length */
int msg_flags; /* flags on received message */
};
The structure is declared as a result of including <sys/socket.h>.
(Note: Before Posix, the two void * pointers were typically char *, and the two socklen_t members were typically integers. Earlier drafts of Posix had the two socklen_t members as size_t, but then changed them to socklen_t to simplify binary portability for 64-bit implementations and to align Posix with X/Open's Networking Services, Issue 5. The change in msg_control to a void * pointer affects any code that increments this pointer.)
Most Berkeley-derived implementations limit the amount of ancillary data in a call to sendmsg() to no more than 108 bytes (an mbuf). This API requires a minimum of 10240 bytes of ancillary data, but it is recommended that the amount be limited only by the buffer space reserved by the socket (which can be modified by the SO_SNDBUF socket option). (Note: This magic number 10240 was picked as a value that should always be large enough. 108 bytes is clearly too small, as the maximum size of a Routing header is 2048 bytes.) β¨
20.2. The cmsghdr Structure
The cmsghdr structure describes ancillary data objects transferred by recvmsg() and sendmsg(). Its Posix definition is:
struct cmsghdr {
socklen_t cmsg_len; /* #bytes, including this header */
int cmsg_level; /* originating protocol */
int cmsg_type; /* protocol-specific type */
/* followed by unsigned char cmsg_data[]; */
};
This structure is declared as a result of including <sys/socket.h>.
(Note: Before Posix, the cmsg_len member was an integer, not a socklen_t. See the Note in the previous section for why socklen_t is used here.)
As shown in this definition, normally there is no member with the name cmsg_data[]. Instead, the data portion is accessed using the CMSG_xxx() macros, as described in Section 20.3. Nevertheless, it is common to refer to the cmsg_data[] member πββοΈ
When ancillary data is sent or received, any number of ancillary data objects can be specified by the msg_control and msg_controllen members of the msghdr structure, because each object is preceded by a cmsghdr structure defining the object's length (the cmsg_len member). Historically, Berkeley-derived implementations have passed only one object at a time, but this API allows multiple objects to be passed in a single call to sendmsg() or recvmsg(). The following example shows two ancillary data objects in a control buffer π§©
|<--------------------------- msg_controllen ------------------------->|
| OR |
|<--------------------------- msg_controllen ---------------------->|
| |
|<----- ancillary data object ----->|<---- ancillary data object ----->|
|<------ min CMSG_SPACE() --------->|<----- min CMSG_SPACE() --------->|
| | |
|<---------- cmsg_len ---------->| |<-------- cmsg_len ----------->| |
|<--------- CMSG_LEN() --------->| |<------- CMSG_LEN() ---------->| |
| | | | |
+-----+-----+-----+--+-----------+--+-----+-----+-----+--+----------+--+
|cmsg_|cmsg_|cmsg_|XX| cmsg_ |XX|cmsg_|cmsg_|cmsg_|XX| cmsg_ |XX|
|len |level|type |XX| data[] |XX|len |level|type |XX| data[] |XX|
+-----+-----+-----+--+-----------+--+-----+-----+-----+--+----------+--+
^
|
msg_control
...and that's exactly where it points here πβ¨
The fields marked "XX" are possible padding π«Ά They can show up between the cmsghdr structure and its data, and between the data and the next cmsghdr structure, but only if the implementation needs them π§ When sending, an application may or may not include padding at the end of the last ancillary data in msg_controllen, and implementations must accept both as valid π When receiving, a portable application must leave room for padding at the end of the last ancillary data, because implementations may copy out the padding at the end of the control message buffer and include it in the received msg_controllen π And if msg_controllen is too small when recvmsg() is called, for all the ancillary data items including any trailing padding after the last item, an implementation may set MSG_CTRUNC π
20.3. Ancillary Data Object Macros π
To make ancillary data objects easier to handle, Posix defines three macros borrowed from 4.4BSD: CMSG_DATA(), CMSG_NXTHDR(), and CMSG_FIRSTHDR() π Before we get into them, here's a little example of how they might be used with a call to recvmsg() π
struct msghdr msg;
struct cmsghdr *cmsgptr;
/* fill in msg */
/* call recvmsg() */
for (cmsgptr = CMSG_FIRSTHDR(&msg); cmsgptr != NULL;
cmsgptr = CMSG_NXTHDR(&msg, cmsgptr)) {
if (cmsgptr->cmsg_len == 0) {
/* Error handling */
break;
}
if (cmsgptr->cmsg_level == ... &&
cmsgptr->cmsg_type == ... ) {
u_char *ptr;
ptr = CMSG_DATA(cmsgptr);
/* process data pointed to by ptr */
}
}
So we'll go through the three Posix macros first, then two newer ones added for this API: CMSG_SPACE() and CMSG_LEN() β¨ All of these are defined just by including <sys/socket.h> πΈ
20.3.1. CMSG_FIRSTHDR π¦
struct cmsghdr *CMSG_FIRSTHDR(const struct msghdr *mhdr);
CMSG_FIRSTHDR() gives you a pointer to the first cmsghdr structure in the msghdr structure that mhdr points to π It returns NULL if there's no ancillary data in that msghdr, meaning either msg_control is NULL or msg_controllen is smaller than the size of a cmsghdr structure π
One possible implementation could be:
#define CMSG_FIRSTHDR(mhdr) \
( (mhdr)->msg_controllen >= sizeof(struct cmsghdr) ? \
(struct cmsghdr *)(mhdr)->msg_control : \
(struct cmsghdr *)NULL )
(Okay, side note π«£ Most existing implementations don't check msg_controllen at all. They just return msg_control. But msg_controllen really must be checked! If the application asks recvmsg() to return ancillary data by pointing msg_control at its buffer and setting msg_controllen to that buffer's length, the kernel says "nothing here" by setting msg_controllen to 0 on return. It's also just easier to put this check inside the macro than to make every application do it π )
20.3.2. CMSG_NXTHDR π§
As described in Section 5.1, CMSG_NXTHDR has been extended so that a NULL second argument means "get the first header" π That gives you another way to write the processing loop from earlier:
struct msghdr msg;
struct cmsghdr *cmsgptr = NULL;
/* fill in msg */
/* call recvmsg() */
while ((cmsgptr = CMSG_NXTHDR(&msg, cmsgptr)) != NULL) {
if (cmsgptr->cmsg_len == 0) {
/* Error handling */
break;
}
if (cmsgptr->cmsg_level == ... &&
cmsgptr->cmsg_type == ... ) {
u_char *ptr;
ptr = CMSG_DATA(cmsgptr);
/* process data pointed to by ptr */
}
}
One possible implementation could be:
#define CMSG_NXTHDR(mhdr, cmsg) \
(((cmsg) == NULL) ? CMSG_FIRSTHDR(mhdr) : \
(((u_char *)(cmsg) + ALIGN_H((cmsg)->cmsg_len) \
+ ALIGN_D(sizeof(struct cmsghdr)) > \
(u_char *)((mhdr)->msg_control) + (mhdr)->msg_controllen) ? \
(struct cmsghdr *)NULL : \
(struct cmsghdr *)((u_char *)(cmsg) + \
ALIGN_H((cmsg)->cmsg_len))))
ALIGN_H() and ALIGN_D() are implementation dependent π They round their argument up to the next even multiple of whatever alignment is needed for the start of the cmsghdr structure and for the data, respectively (this is probably a multiple of 4 or 8 bytes). On platforms where the header and data alignment requirements happen to be the same, they often turn out to be the same macro π«Ά
20.3.3. CMSG_DATA π
unsigned char *CMSG_DATA(const struct cmsghdr *cmsg);
CMSG_DATA() returns a pointer to the data that follows a cmsghdr structure π¦ This is what's called the cmsg_data[] member, even though no such member is actually defined in the structure π
One possible implementation could be:
#define CMSG_DATA(cmsg) ( (u_char *)(cmsg) + \
ALIGN_D(sizeof(struct cmsghdr)) )
20.3.4. CMSG_SPACE πΈ
CMSG_SPACE is new with this API (see Section 5.2) β¨ You use it to figure out how much space needs to be allocated for an ancillary data item π
One possible implementation could be:
#define CMSG_SPACE(length) ( ALIGN_D(sizeof(struct cmsghdr)) + \
ALIGN_H(length) )
20.3.5. CMSG_LEN π₯
CMSG_LEN is new with this API (see Section 5.3) π It returns the value to store in the cmsg_len member of the cmsghdr structure, including any padding needed to meet alignment requirements π
One possible implementation could be:
#define CMSG_LEN(length) ( ALIGN_D(sizeof(struct cmsghdr)) + \
length )
21. Appendix B: Examples Using the inet6_rth_XXX() Functions π
Here we show an example of both sending Routing headers and processing and reversing a received Routing header π«Άπ¦
21.1. Sending a Routing Header β¨
okay bestie, this is the example I was most excited to show you π¦ it's the Routing header functions doing their whole thing, and we're following the exact same walkthrough as the example on p. 17 of [RFC-2460]. π§ We've got a source S, a destination D, and three intermediate nodes: I1, I2, and I3. Picture the journey like a group chat with a main character route π
S -----> I1 -----> I2 -----> I3 -----> D
src: * S S S S S
dst: D I1 I2 I3 D D
A[1]: I1 I2 I1 I1 I1 I1
A[2]: I2 I3 I3 I2 I2 I2
A[3]: I3 D D D I3 I3
#seg: 3 3 2 1 0 3
so the src and dst rows are the source and destination IPv6 addresses in the IPv6 header π and A[1], A[2], and A[3] are the three addresses sitting in the Routing header. Then #seg is the Segments Left field in that Routing header. πΈ
The six values in the column under node S are the Routing header values the sending app sets up through sendmsg() of setsockopt(). The sender's function calls look like this:
void *extptr;
socklen_t extlen;
struct msghdr msg;
struct cmsghdr *cmsgptr;
int cmsglen;
struct sockaddr_in6 I1, I2, I3, D;
extlen = inet6_rth_space(IPV6_RTHDR_TYPE_0, 3);
cmsglen = CMSG_SPACE(extlen);
cmsgptr = malloc(cmsglen);
cmsgptr->cmsg_len = CMSG_LEN(extlen);
cmsgptr->cmsg_level = IPPROTO_IPV6;
cmsgptr->cmsg_type = IPV6_RTHDR;
extptr = CMSG_DATA(cmsgptr);
extptr = inet6_rth_init(extptr, extlen, IPV6_RTHDR_TYPE_0, 3);
inet6_rth_add(extptr, &I1.sin6_addr);
inet6_rth_add(extptr, &I2.sin6_addr);
inet6_rth_add(extptr, &I3.sin6_addr);
msg.msg_control = cmsgptr;
msg.msg_controllen = cmsglen;
/* finish filling in msg{}, msg_name = D */
/* call sendmsg() */
π«Ά We're also assuming the socket's source address isn't specified, which is what that little asterisk in the figure is showing. π
Now the four columns of six values sitting between the five nodes are the packet's field values while it's in transit between each pair of nodes. Lowkey the big moment: before S actually sends the packet, the source address gets chosen (replacing the asterisk), I1 becomes the datagram's destination address, the two addresses A[2] and A[3] get "shifted up," and D gets moved into A[3]. It's giving full glow-up π
The columns under the destination node are what recvmsg() hands back, assuming the app has turned on both the IPV6_RECVPKTINFO and IPV6_RECVRTHDR socket options π The source address is S, which lives in the sockaddr_in6 structure pointed to by the msg_name member. The destination address is D, returned as an ancillary data object in an in6_pktinfo structure. And the ancillary data object for the Routing header holds three addresses (I1, I2, and I3). The number of segments is read from the Hdr Ext Len field in the Routing header, where a value of 6 means 3 addresses. π§
The return value from inet6_rth_segments() is 3, inet6_rth_getaddr(0) gives back I1, inet6_rth_getaddr(1) gives back I2, and inet6_rth_getaddr(2) gives back I3,
If the receiving app then calls inet6_rth_reverse(), the order of the three addresses flips to I3, I2, and I1. Reversed era ππ
We can also peek at what an implementation might store in the ancillary data object while the sending process is building the Routing header. Say we're on a 32-bit architecture where sizeof(struct cmsghdr) equals 12, with a desired alignment of 4-byte boundaries. Then the call to inet6_rth_space(3) returns 68: 12 bytes for the cmsghdr structure and 56 bytes for the Routing header (8 + 3*16). π
The call to inet6_rth_init() sets up the ancillary data object so it holds a Type 0 Routing header π¦
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| cmsg_len = 20 |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| cmsg_level = IPPROTO_IPV6 |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| cmsg_type = IPV6_RTHDR |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Next Header | Hdr Ext Len=6 | Routing Type=0| Seg Left=0 |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
The first call to inet6_rth_add() adds I1 to the list. β¨
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| cmsg_len = 36 |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| cmsg_level = IPPROTO_IPV6 |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| cmsg_type = IPV6_RTHDR |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Next Header | Hdr Ext Len=6 | Routing Type=0| Seg Left=1 |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ Address[1] = I1 +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
cmsg_len goes up by 16, and the Segments Left field goes up by 1. π
The next call to inet6_rth_add() adds I2 to the list. π
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| cmsg_len = 52 |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| cmsg_level = IPPROTO_IPV6 |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| cmsg_type = IPV6_RTHDR |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Next Header | Hdr Ext Len=6 | Routing Type=0| Seg Left=2 |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ Address[1] = I1 +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ Address[2] = I2 +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
cmsg_len goes up by 16, and the Segments Left field goes up by 1. π·
The last call to inet6_rth_add() adds I3 to the list. π
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| cmsg_len = 68 |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| cmsg_level = IPPROTO_IPV6 |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| cmsg_type = IPV6_RTHDR |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Next Header | Hdr Ext Len=6 | Routing Type=0| Seg Left=3 |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ Address[1] = I1 +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ Address[2] = I2 +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ Address[3] = I3 +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
cmsg_len goes up by 16 one more time, and the Segments Left field goes up by 1, ending at 3. That's the whole routing header built, periodt π π
21.2. Receiving Routing Headers β¨
okay so this one assumes the app already turned on the IPV6_RECVRTHDR socket option π the app prints out a source route, reverses it, and then echoes the received data back to sender π¦
struct sockaddr_in6 addr;
struct msghdr msg;
struct iovec iov;
struct cmsghdr *cmsgptr;
socklen_t cmsgspace;
void *extptr;
int extlen;
int segments;
int i;
char databuf[8192];
segments = 100; /* Enough */
extlen = inet6_rth_space(IPV6_RTHDR_TYPE_0, segments);
cmsgspace = CMSG_SPACE(extlen);
cmsgptr = malloc(cmsgspace);
if (cmsgptr == NULL) {
perror("malloc");
exit(1);
}
extptr = CMSG_DATA(cmsgptr);
msg.msg_control = cmsgptr;
msg.msg_controllen = cmsgspace;
msg.msg_name = (struct sockaddr *)&addr;
msg.msg_namelen = sizeof (addr);
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
iov.iov_base = databuf;
iov.iov_len = sizeof (databuf);
msg.msg_flags = 0;
if (recvmsg(s, &msg, 0) == -1) {
perror("recvmsg");
return;
}
if (msg.msg_controllen != 0 &&
cmsgptr->cmsg_level == IPPROTO_IPV6 &&
cmsgptr->cmsg_type == IPV6_RTHDR) {
struct in6_addr *in6;
char asciiname[INET6_ADDRSTRLEN];
struct ip6_rthdr *rthdr;
rthdr = (struct ip6_rthdr *)extptr;
segments = inet6_rth_segments(extptr);
printf("route (%d segments, %d left): ",
segments, rthdr->ip6r_segleft);
for (i = 0; i < segments; i++) {
in6 = inet6_rth_getaddr(extptr, i);
if (in6 == NULL)
printf("<NULL> ");
else
printf("%s ", inet_ntop(AF_INET6,
(void *)in6->s6_addr,
asciiname, INET6_ADDRSTRLEN));
}
if (inet6_rth_reverse(extptr, extptr) == -1) {
printf("reverse failed");
return;
}
}
iov.iov_base = databuf;
iov.iov_len = strlen(databuf);
if (sendmsg(s, &msg, 0) == -1)
perror("sendmsg");
if (cmsgptr != NULL)
free(cmsgptr);
Note: The above example is a simple illustration. It skips some error checks, including those involving the MSG_TRUNC and MSG_CTRUNC flags. It also leaves some type mismatches in favor of brevity. π so this is the cute version, not the production-ready one π
22. Appendix C: Examples Using the inet6_opt_XXX() Functions π§
this shows how Hop-by-Hop and Destination options can be both built and parsed using the inet6_opt_XXX() functions π these examples assume that OPT_X and OPT_Y already have defined values.
Note: The example is a simple illustration. It skips some error checks and leaves some type mismatches in favor of brevity. π
22.1. Building Options
we're building two Hop-by-Hop options here, using the example in Appendix B of [RFC-2460] π
void *extbuf;
socklen_t extlen;
int currentlen;
void *databuf;
int offset;
uint8_t value1;
uint16_t value2;
uint32_t value4;
uint64_t value8;
/* Estimate the length */
currentlen = inet6_opt_init(NULL, 0);
if (currentlen == -1)
return (-1);
currentlen = inet6_opt_append(NULL, 0, currentlen, OPT_X,
12, 8, NULL);
if (currentlen == -1)
return (-1);
currentlen = inet6_opt_append(NULL, 0, currentlen, OPT_Y,
7, 4, NULL);
if (currentlen == -1)
return (-1);
currentlen = inet6_opt_finish(NULL, 0, currentlen);
if (currentlen == -1)
return (-1);
extlen = currentlen;
extbuf = malloc(extlen);
if (extbuf == NULL) {
perror("malloc");
return (-1);
}
currentlen = inet6_opt_init(extbuf, extlen);
if (currentlen == -1)
return (-1);
currentlen = inet6_opt_append(extbuf, extlen, currentlen,
OPT_X, 12, 8, &databuf);
if (currentlen == -1)
return (-1);
/* Insert value 0x12345678 for 4-octet field */
offset = 0;
value4 = 0x12345678;
offset = inet6_opt_set_val(databuf, offset,
&value4, sizeof (value4));
/* Insert value 0x0102030405060708 for 8-octet field */
value8 = 0x0102030405060708;
offset = inet6_opt_set_val(databuf, offset,
&value8, sizeof (value8));
currentlen = inet6_opt_append(extbuf, extlen, currentlen,
OPT_Y, 7, 4, &databuf);
if (currentlen == -1)
return (-1);
/* Insert value 0x01 for 1-octet field */
offset = 0;
value1 = 0x01;
offset = inet6_opt_set_val(databuf, offset,
&value1, sizeof (value1));
/* Insert value 0x1331 for 2-octet field */
value2 = 0x1331;
offset = inet6_opt_set_val(databuf, offset,
&value2, sizeof (value2));
/* Insert value 0x01020304 for 4-octet field */
value4 = 0x01020304;
offset = inet6_opt_set_val(databuf, offset,
&value4, sizeof (value4));
currentlen = inet6_opt_finish(extbuf, extlen, currentlen);
if (currentlen == -1)
return (-1);
/* extbuf and extlen are now completely formatted */
22.2. Parsing Received Options
this one parses and prints the content of the two options from the previous example, so you can see the round trip work π
int
print_opt(void *extbuf, socklen_t extlen)
{
struct ip6_dest *ext;
int currentlen;
uint8_t type;
socklen_t len;
void *databuf;
int offset;
uint8_t value1;
uint16_t value2;
uint32_t value4;
uint64_t value8;
ext = (struct ip6_dest *)extbuf;
printf("nxt %u, len %u (bytes %d)\n", ext->ip6d_nxt,
ext->ip6d_len, (ext->ip6d_len + 1) * 8);
currentlen = 0;
while (1) {
currentlen = inet6_opt_next(extbuf, extlen,
currentlen, &type,
&len, &databuf);
if (currentlen == -1)
break;
printf("Received opt %u len %u\n",
type, len);
switch (type) {
case OPT_X:
offset = 0;
offset =
inet6_opt_get_val(databuf, offset,
&value4,
sizeof (value4));
printf("X 4-byte field %x\n", value4);
offset =
inet6_opt_get_val(databuf, offset,
&value8,
sizeof (value8));
printf("X 8-byte field %llx\n", value8);
break;
case OPT_Y:
offset = 0;
offset =
inet6_opt_get_val(databuf, offset,
&value1,
sizeof (value1));
printf("Y 1-byte field %x\n", value1);
offset =
inet6_opt_get_val(databuf, offset,
&value2,
sizeof (value2));
printf("Y 2-byte field %x\n", value2);
offset =
inet6_opt_get_val(databuf, offset,
&value4,
sizeof (value4));
printf("Y 4-byte field %x\n", value4);
break;
default:
printf("Unknown option %u\n", type);
break;
}
}
return (0);
}
23. Authors' Addresses π«Ά
the crew who made this happen π
W. Richard Stevens (deceased)
Matt Thomas
3am Software Foundry
8053 Park Villa Circle
Cupertino, CA 95014
EMail: matt@3am-software.com
Erik Nordmark
Sun Microsystems Laboratories, Europe
180, avenue de l'Europe
38334 SAINT ISMIER Cedex, France
Phone: +33 (0)4 74 18 88 03
Fax: +33 (0)4 76 18 88 88
EMail: Erik.Nordmark@sun.com
Tatuya JINMEI
Corporate Research & Development Center, Toshiba Corporation
1 Komukai Toshiba-cho, Kawasaki-shi
Kanagawa 212-8582, Japan
EMail: jinmei@isl.rdc.toshiba.co.jp
24. Full Copyright Statement π
this part is the legal stuff, so I'm keeping the wording exactly as written π
Copyright (C) The Internet Society (2003). All Rights Reserved.
This document and translations of it may be copied and furnished to others, and derivative works that comment on or otherwise explain it or assist in its implementation may be prepared, copied, published and distributed, in whole or in part, without restriction of any kind, provided that the above copyright notice and this paragraph are included on all such copies and derivative works. However, this document itself may not be modified in any way, such as by removing the copyright notice or references to the Internet Society or other Internet organizations, except as needed for the purpose of developing Internet standards in which case the procedures for copyrights defined in the Internet Standards process must be followed, or as required to translate it into languages other than English.
The limited permissions granted above are perpetual and will not be revoked by the Internet Society or its successors or assigns.
This document and the information contained herein is provided on an "AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
Acknowledgement πΈ
Funding for the RFC Editor function is currently provided by the Internet Society.
π¦ where this page comes from
- ietf: rfc3542 2003-06
- π girlified by claude-haiku-5-5 on : a language model's rewrite of the original, under its terms