fe06ac8a68f82a3e29628bce19ff68c9da8a0871
[cascardo/ovs.git] / lib / packets.c
1 /*
2  * Copyright (c) 2009, 2010, 2011, 2012, 2013, 2014, 2015 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include "packets.h"
19 #include <arpa/inet.h>
20 #include <sys/socket.h>
21 #include <netinet/in.h>
22 #include <netinet/ip6.h>
23 #include <netinet/icmp6.h>
24 #include <stdlib.h>
25 #include "byte-order.h"
26 #include "csum.h"
27 #include "crc32c.h"
28 #include "flow.h"
29 #include "hmap.h"
30 #include "dynamic-string.h"
31 #include "ovs-thread.h"
32 #include "odp-util.h"
33 #include "dp-packet.h"
34 #include "unaligned.h"
35
36 const struct in6_addr in6addr_exact = IN6ADDR_EXACT_INIT;
37 const struct in6_addr in6addr_all_hosts = IN6ADDR_ALL_HOSTS_INIT;
38
39 struct in6_addr
40 flow_tnl_dst(const struct flow_tnl *tnl)
41 {
42     struct in6_addr addr;
43     if (tnl->ip_dst) {
44         in6_addr_set_mapped_ipv4(&addr, tnl->ip_dst);
45         return addr;
46     }
47     return tnl->ipv6_dst;
48 }
49
50 struct in6_addr
51 flow_tnl_src(const struct flow_tnl *tnl)
52 {
53     struct in6_addr addr;
54     if (tnl->ip_src) {
55         in6_addr_set_mapped_ipv4(&addr, tnl->ip_src);
56         return addr;
57     }
58     return tnl->ipv6_src;
59 }
60
61 /* Parses 's' as a 16-digit hexadecimal number representing a datapath ID.  On
62  * success stores the dpid into '*dpidp' and returns true, on failure stores 0
63  * into '*dpidp' and returns false.
64  *
65  * Rejects an all-zeros dpid as invalid. */
66 bool
67 dpid_from_string(const char *s, uint64_t *dpidp)
68 {
69     *dpidp = (strlen(s) == 16 && strspn(s, "0123456789abcdefABCDEF") == 16
70               ? strtoull(s, NULL, 16)
71               : 0);
72     return *dpidp != 0;
73 }
74
75 /* Returns true if 'ea' is a reserved address, that a bridge must never
76  * forward, false otherwise.
77  *
78  * If you change this function's behavior, please update corresponding
79  * documentation in vswitch.xml at the same time. */
80 bool
81 eth_addr_is_reserved(const struct eth_addr ea)
82 {
83     struct eth_addr_node {
84         struct hmap_node hmap_node;
85         const uint64_t ea64;
86     };
87
88     static struct eth_addr_node nodes[] = {
89         /* STP, IEEE pause frames, and other reserved protocols. */
90         { HMAP_NODE_NULL_INITIALIZER, 0x0180c2000000ULL },
91         { HMAP_NODE_NULL_INITIALIZER, 0x0180c2000001ULL },
92         { HMAP_NODE_NULL_INITIALIZER, 0x0180c2000002ULL },
93         { HMAP_NODE_NULL_INITIALIZER, 0x0180c2000003ULL },
94         { HMAP_NODE_NULL_INITIALIZER, 0x0180c2000004ULL },
95         { HMAP_NODE_NULL_INITIALIZER, 0x0180c2000005ULL },
96         { HMAP_NODE_NULL_INITIALIZER, 0x0180c2000006ULL },
97         { HMAP_NODE_NULL_INITIALIZER, 0x0180c2000007ULL },
98         { HMAP_NODE_NULL_INITIALIZER, 0x0180c2000008ULL },
99         { HMAP_NODE_NULL_INITIALIZER, 0x0180c2000009ULL },
100         { HMAP_NODE_NULL_INITIALIZER, 0x0180c200000aULL },
101         { HMAP_NODE_NULL_INITIALIZER, 0x0180c200000bULL },
102         { HMAP_NODE_NULL_INITIALIZER, 0x0180c200000cULL },
103         { HMAP_NODE_NULL_INITIALIZER, 0x0180c200000dULL },
104         { HMAP_NODE_NULL_INITIALIZER, 0x0180c200000eULL },
105         { HMAP_NODE_NULL_INITIALIZER, 0x0180c200000fULL },
106
107         /* Extreme protocols. */
108         { HMAP_NODE_NULL_INITIALIZER, 0x00e02b000000ULL }, /* EDP. */
109         { HMAP_NODE_NULL_INITIALIZER, 0x00e02b000004ULL }, /* EAPS. */
110         { HMAP_NODE_NULL_INITIALIZER, 0x00e02b000006ULL }, /* EAPS. */
111
112         /* Cisco protocols. */
113         { HMAP_NODE_NULL_INITIALIZER, 0x01000c000000ULL }, /* ISL. */
114         { HMAP_NODE_NULL_INITIALIZER, 0x01000cccccccULL }, /* PAgP, UDLD, CDP,
115                                                             * DTP, VTP. */
116         { HMAP_NODE_NULL_INITIALIZER, 0x01000ccccccdULL }, /* PVST+. */
117         { HMAP_NODE_NULL_INITIALIZER, 0x01000ccdcdcdULL }, /* STP Uplink Fast,
118                                                             * FlexLink. */
119
120         /* Cisco CFM. */
121         { HMAP_NODE_NULL_INITIALIZER, 0x01000cccccc0ULL },
122         { HMAP_NODE_NULL_INITIALIZER, 0x01000cccccc1ULL },
123         { HMAP_NODE_NULL_INITIALIZER, 0x01000cccccc2ULL },
124         { HMAP_NODE_NULL_INITIALIZER, 0x01000cccccc3ULL },
125         { HMAP_NODE_NULL_INITIALIZER, 0x01000cccccc4ULL },
126         { HMAP_NODE_NULL_INITIALIZER, 0x01000cccccc5ULL },
127         { HMAP_NODE_NULL_INITIALIZER, 0x01000cccccc6ULL },
128         { HMAP_NODE_NULL_INITIALIZER, 0x01000cccccc7ULL },
129     };
130
131     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
132     struct eth_addr_node *node;
133     static struct hmap addrs;
134     uint64_t ea64;
135
136     if (ovsthread_once_start(&once)) {
137         hmap_init(&addrs);
138         for (node = nodes; node < &nodes[ARRAY_SIZE(nodes)]; node++) {
139             hmap_insert(&addrs, &node->hmap_node, hash_uint64(node->ea64));
140         }
141         ovsthread_once_done(&once);
142     }
143
144     ea64 = eth_addr_to_uint64(ea);
145     HMAP_FOR_EACH_IN_BUCKET (node, hmap_node, hash_uint64(ea64), &addrs) {
146         if (node->ea64 == ea64) {
147             return true;
148         }
149     }
150     return false;
151 }
152
153 bool
154 eth_addr_from_string(const char *s, struct eth_addr *ea)
155 {
156     if (ovs_scan(s, ETH_ADDR_SCAN_FMT, ETH_ADDR_SCAN_ARGS(*ea))) {
157         return true;
158     } else {
159         *ea = eth_addr_zero;
160         return false;
161     }
162 }
163
164 /* Fills 'b' with a Reverse ARP packet with Ethernet source address 'eth_src'.
165  * This function is used by Open vSwitch to compose packets in cases where
166  * context is important but content doesn't (or shouldn't) matter.
167  *
168  * The returned packet has enough headroom to insert an 802.1Q VLAN header if
169  * desired. */
170 void
171 compose_rarp(struct dp_packet *b, const struct eth_addr eth_src)
172 {
173     struct eth_header *eth;
174     struct arp_eth_header *arp;
175
176     dp_packet_clear(b);
177     dp_packet_prealloc_tailroom(b, 2 + ETH_HEADER_LEN + VLAN_HEADER_LEN
178                              + ARP_ETH_HEADER_LEN);
179     dp_packet_reserve(b, 2 + VLAN_HEADER_LEN);
180     eth = dp_packet_put_uninit(b, sizeof *eth);
181     eth->eth_dst = eth_addr_broadcast;
182     eth->eth_src = eth_src;
183     eth->eth_type = htons(ETH_TYPE_RARP);
184
185     arp = dp_packet_put_uninit(b, sizeof *arp);
186     arp->ar_hrd = htons(ARP_HRD_ETHERNET);
187     arp->ar_pro = htons(ARP_PRO_IP);
188     arp->ar_hln = sizeof arp->ar_sha;
189     arp->ar_pln = sizeof arp->ar_spa;
190     arp->ar_op = htons(ARP_OP_RARP);
191     arp->ar_sha = eth_src;
192     put_16aligned_be32(&arp->ar_spa, htonl(0));
193     arp->ar_tha = eth_src;
194     put_16aligned_be32(&arp->ar_tpa, htonl(0));
195
196     dp_packet_reset_offsets(b);
197     dp_packet_set_l3(b, arp);
198 }
199
200 /* Insert VLAN header according to given TCI. Packet passed must be Ethernet
201  * packet.  Ignores the CFI bit of 'tci' using 0 instead.
202  *
203  * Also adjusts the layer offsets accordingly. */
204 void
205 eth_push_vlan(struct dp_packet *packet, ovs_be16 tpid, ovs_be16 tci)
206 {
207     struct vlan_eth_header *veh;
208
209     /* Insert new 802.1Q header. */
210     veh = dp_packet_resize_l2(packet, VLAN_HEADER_LEN);
211     memmove(veh, (char *)veh + VLAN_HEADER_LEN, 2 * ETH_ADDR_LEN);
212     veh->veth_type = tpid;
213     veh->veth_tci = tci & htons(~VLAN_CFI);
214 }
215
216 /* Removes outermost VLAN header (if any is present) from 'packet'.
217  *
218  * 'packet->l2_5' should initially point to 'packet''s outer-most VLAN header
219  * or may be NULL if there are no VLAN headers. */
220 void
221 eth_pop_vlan(struct dp_packet *packet)
222 {
223     struct vlan_eth_header *veh = dp_packet_l2(packet);
224
225     if (veh && dp_packet_size(packet) >= sizeof *veh
226         && eth_type_vlan(veh->veth_type)) {
227
228         memmove((char *)veh + VLAN_HEADER_LEN, veh, 2 * ETH_ADDR_LEN);
229         dp_packet_resize_l2(packet, -VLAN_HEADER_LEN);
230     }
231 }
232
233 /* Set ethertype of the packet. */
234 static void
235 set_ethertype(struct dp_packet *packet, ovs_be16 eth_type)
236 {
237     struct eth_header *eh = dp_packet_l2(packet);
238
239     if (!eh) {
240         return;
241     }
242
243     if (eth_type_vlan(eh->eth_type)) {
244         ovs_be16 *p;
245         char *l2_5 = dp_packet_l2_5(packet);
246
247         p = ALIGNED_CAST(ovs_be16 *,
248                          (l2_5 ? l2_5 : (char *)dp_packet_l3(packet)) - 2);
249         *p = eth_type;
250     } else {
251         eh->eth_type = eth_type;
252     }
253 }
254
255 static bool is_mpls(struct dp_packet *packet)
256 {
257     return packet->l2_5_ofs != UINT16_MAX;
258 }
259
260 /* Set time to live (TTL) of an MPLS label stack entry (LSE). */
261 void
262 set_mpls_lse_ttl(ovs_be32 *lse, uint8_t ttl)
263 {
264     *lse &= ~htonl(MPLS_TTL_MASK);
265     *lse |= htonl((ttl << MPLS_TTL_SHIFT) & MPLS_TTL_MASK);
266 }
267
268 /* Set traffic class (TC) of an MPLS label stack entry (LSE). */
269 void
270 set_mpls_lse_tc(ovs_be32 *lse, uint8_t tc)
271 {
272     *lse &= ~htonl(MPLS_TC_MASK);
273     *lse |= htonl((tc << MPLS_TC_SHIFT) & MPLS_TC_MASK);
274 }
275
276 /* Set label of an MPLS label stack entry (LSE). */
277 void
278 set_mpls_lse_label(ovs_be32 *lse, ovs_be32 label)
279 {
280     *lse &= ~htonl(MPLS_LABEL_MASK);
281     *lse |= htonl((ntohl(label) << MPLS_LABEL_SHIFT) & MPLS_LABEL_MASK);
282 }
283
284 /* Set bottom of stack (BoS) bit of an MPLS label stack entry (LSE). */
285 void
286 set_mpls_lse_bos(ovs_be32 *lse, uint8_t bos)
287 {
288     *lse &= ~htonl(MPLS_BOS_MASK);
289     *lse |= htonl((bos << MPLS_BOS_SHIFT) & MPLS_BOS_MASK);
290 }
291
292 /* Compose an MPLS label stack entry (LSE) from its components:
293  * label, traffic class (TC), time to live (TTL) and
294  * bottom of stack (BoS) bit. */
295 ovs_be32
296 set_mpls_lse_values(uint8_t ttl, uint8_t tc, uint8_t bos, ovs_be32 label)
297 {
298     ovs_be32 lse = htonl(0);
299     set_mpls_lse_ttl(&lse, ttl);
300     set_mpls_lse_tc(&lse, tc);
301     set_mpls_lse_bos(&lse, bos);
302     set_mpls_lse_label(&lse, label);
303     return lse;
304 }
305
306 /* Set MPLS label stack entry to outermost MPLS header.*/
307 void
308 set_mpls_lse(struct dp_packet *packet, ovs_be32 mpls_lse)
309 {
310     /* Packet type should be MPLS to set label stack entry. */
311     if (is_mpls(packet)) {
312         struct mpls_hdr *mh = dp_packet_l2_5(packet);
313
314         /* Update mpls label stack entry. */
315         put_16aligned_be32(&mh->mpls_lse, mpls_lse);
316     }
317 }
318
319 /* Push MPLS label stack entry 'lse' onto 'packet' as the outermost MPLS
320  * header.  If 'packet' does not already have any MPLS labels, then its
321  * Ethertype is changed to 'ethtype' (which must be an MPLS Ethertype). */
322 void
323 push_mpls(struct dp_packet *packet, ovs_be16 ethtype, ovs_be32 lse)
324 {
325     char * header;
326     size_t len;
327
328     if (!eth_type_mpls(ethtype)) {
329         return;
330     }
331
332     if (!is_mpls(packet)) {
333         /* Set MPLS label stack offset. */
334         packet->l2_5_ofs = packet->l3_ofs;
335     }
336
337     set_ethertype(packet, ethtype);
338
339     /* Push new MPLS shim header onto packet. */
340     len = packet->l2_5_ofs;
341     header = dp_packet_resize_l2_5(packet, MPLS_HLEN);
342     memmove(header, header + MPLS_HLEN, len);
343     memcpy(header + len, &lse, sizeof lse);
344 }
345
346 /* If 'packet' is an MPLS packet, removes its outermost MPLS label stack entry.
347  * If the label that was removed was the only MPLS label, changes 'packet''s
348  * Ethertype to 'ethtype' (which ordinarily should not be an MPLS
349  * Ethertype). */
350 void
351 pop_mpls(struct dp_packet *packet, ovs_be16 ethtype)
352 {
353     if (is_mpls(packet)) {
354         struct mpls_hdr *mh = dp_packet_l2_5(packet);
355         size_t len = packet->l2_5_ofs;
356
357         set_ethertype(packet, ethtype);
358         if (get_16aligned_be32(&mh->mpls_lse) & htonl(MPLS_BOS_MASK)) {
359             dp_packet_set_l2_5(packet, NULL);
360         }
361         /* Shift the l2 header forward. */
362         memmove((char*)dp_packet_data(packet) + MPLS_HLEN, dp_packet_data(packet), len);
363         dp_packet_resize_l2_5(packet, -MPLS_HLEN);
364     }
365 }
366
367 /* Converts hex digits in 'hex' to an Ethernet packet in '*packetp'.  The
368  * caller must free '*packetp'.  On success, returns NULL.  On failure, returns
369  * an error message and stores NULL in '*packetp'.
370  *
371  * Aligns the L3 header of '*packetp' on a 32-bit boundary. */
372 const char *
373 eth_from_hex(const char *hex, struct dp_packet **packetp)
374 {
375     struct dp_packet *packet;
376
377     /* Use 2 bytes of headroom to 32-bit align the L3 header. */
378     packet = *packetp = dp_packet_new_with_headroom(strlen(hex) / 2, 2);
379
380     if (dp_packet_put_hex(packet, hex, NULL)[0] != '\0') {
381         dp_packet_delete(packet);
382         *packetp = NULL;
383         return "Trailing garbage in packet data";
384     }
385
386     if (dp_packet_size(packet) < ETH_HEADER_LEN) {
387         dp_packet_delete(packet);
388         *packetp = NULL;
389         return "Packet data too short for Ethernet";
390     }
391
392     return NULL;
393 }
394
395 void
396 eth_format_masked(const struct eth_addr eth,
397                   const struct eth_addr *mask, struct ds *s)
398 {
399     ds_put_format(s, ETH_ADDR_FMT, ETH_ADDR_ARGS(eth));
400     if (mask && !eth_mask_is_exact(*mask)) {
401         ds_put_format(s, "/"ETH_ADDR_FMT, ETH_ADDR_ARGS(*mask));
402     }
403 }
404
405 /* Given the IP netmask 'netmask', returns the number of bits of the IP address
406  * that it specifies, that is, the number of 1-bits in 'netmask'.
407  *
408  * If 'netmask' is not a CIDR netmask (see ip_is_cidr()), the return value will
409  * still be in the valid range but isn't otherwise meaningful. */
410 int
411 ip_count_cidr_bits(ovs_be32 netmask)
412 {
413     return 32 - ctz32(ntohl(netmask));
414 }
415
416 void
417 ip_format_masked(ovs_be32 ip, ovs_be32 mask, struct ds *s)
418 {
419     ds_put_format(s, IP_FMT, IP_ARGS(ip));
420     if (mask != OVS_BE32_MAX) {
421         if (ip_is_cidr(mask)) {
422             ds_put_format(s, "/%d", ip_count_cidr_bits(mask));
423         } else {
424             ds_put_format(s, "/"IP_FMT, IP_ARGS(mask));
425         }
426     }
427 }
428
429 /* Parses string 's', which must be an IP address with an optional netmask or
430  * CIDR prefix length.  Stores the IP address into '*ip' and the netmask into
431  * '*mask'.  (If 's' does not contain a netmask, 255.255.255.255 is
432  * assumed.)
433  *
434  * Returns NULL if successful, otherwise an error message that the caller must
435  * free(). */
436 char * OVS_WARN_UNUSED_RESULT
437 ip_parse_masked(const char *s, ovs_be32 *ip, ovs_be32 *mask)
438 {
439     int prefix;
440     int n;
441
442     if (ovs_scan(s, IP_SCAN_FMT"/"IP_SCAN_FMT"%n",
443                  IP_SCAN_ARGS(ip), IP_SCAN_ARGS(mask), &n) && !s[n]) {
444         /* OK. */
445     } else if (ovs_scan(s, IP_SCAN_FMT"/%d%n", IP_SCAN_ARGS(ip), &prefix, &n)
446                && !s[n]) {
447         if (prefix <= 0 || prefix > 32) {
448             return xasprintf("%s: network prefix bits not between 0 and "
449                              "32", s);
450         }
451         *mask = be32_prefix_mask(prefix);
452     } else if (ovs_scan(s, IP_SCAN_FMT"%n", IP_SCAN_ARGS(ip), &n) && !s[n]) {
453         *mask = OVS_BE32_MAX;
454     } else {
455         return xasprintf("%s: invalid IP address", s);
456     }
457     return NULL;
458 }
459
460 void
461 ipv6_format_addr(const struct in6_addr *addr, struct ds *s)
462 {
463     char *dst;
464
465     ds_reserve(s, s->length + INET6_ADDRSTRLEN);
466
467     dst = s->string + s->length;
468     inet_ntop(AF_INET6, addr, dst, INET6_ADDRSTRLEN);
469     s->length += strlen(dst);
470 }
471
472 /* Same as print_ipv6_addr, but optionally encloses the address in square
473  * brackets. */
474 void
475 ipv6_format_addr_bracket(const struct in6_addr *addr, struct ds *s,
476                          bool bracket)
477 {
478     if (bracket) {
479         ds_put_char(s, '[');
480     }
481     ipv6_format_addr(addr, s);
482     if (bracket) {
483         ds_put_char(s, ']');
484     }
485 }
486
487 void
488 ipv6_format_mapped(const struct in6_addr *addr, struct ds *s)
489 {
490     if (IN6_IS_ADDR_V4MAPPED(addr)) {
491         ds_put_format(s, IP_FMT, addr->s6_addr[12], addr->s6_addr[13],
492                                  addr->s6_addr[14], addr->s6_addr[15]);
493     } else {
494         ipv6_format_addr(addr, s);
495     }
496 }
497
498 void
499 ipv6_format_masked(const struct in6_addr *addr, const struct in6_addr *mask,
500                    struct ds *s)
501 {
502     ipv6_format_addr(addr, s);
503     if (mask && !ipv6_mask_is_exact(mask)) {
504         if (ipv6_is_cidr(mask)) {
505             int cidr_bits = ipv6_count_cidr_bits(mask);
506             ds_put_format(s, "/%d", cidr_bits);
507         } else {
508             ds_put_char(s, '/');
509             ipv6_format_addr(mask, s);
510         }
511     }
512 }
513
514 /* Stores the string representation of the IPv6 address 'addr' into the
515  * character array 'addr_str', which must be at least INET6_ADDRSTRLEN
516  * bytes long. If addr is IPv4-mapped, store an IPv4 dotted-decimal string. */
517 const char *
518 ipv6_string_mapped(char *addr_str, const struct in6_addr *addr)
519 {
520     ovs_be32 ip;
521     ip = in6_addr_get_mapped_ipv4(addr);
522     if (ip) {
523         return inet_ntop(AF_INET, &ip, addr_str, INET6_ADDRSTRLEN);
524     } else {
525         return inet_ntop(AF_INET6, addr, addr_str, INET6_ADDRSTRLEN);
526     }
527 }
528
529 struct in6_addr ipv6_addr_bitand(const struct in6_addr *a,
530                                  const struct in6_addr *b)
531 {
532     int i;
533     struct in6_addr dst;
534
535 #ifdef s6_addr32
536     for (i=0; i<4; i++) {
537         dst.s6_addr32[i] = a->s6_addr32[i] & b->s6_addr32[i];
538     }
539 #else
540     for (i=0; i<16; i++) {
541         dst.s6_addr[i] = a->s6_addr[i] & b->s6_addr[i];
542     }
543 #endif
544
545     return dst;
546 }
547
548 /* Returns an in6_addr consisting of 'mask' high-order 1-bits and 128-N
549  * low-order 0-bits. */
550 struct in6_addr
551 ipv6_create_mask(int mask)
552 {
553     struct in6_addr netmask;
554     uint8_t *netmaskp = &netmask.s6_addr[0];
555
556     memset(&netmask, 0, sizeof netmask);
557     while (mask > 8) {
558         *netmaskp = 0xff;
559         netmaskp++;
560         mask -= 8;
561     }
562
563     if (mask) {
564         *netmaskp = 0xff << (8 - mask);
565     }
566
567     return netmask;
568 }
569
570 /* Given the IPv6 netmask 'netmask', returns the number of bits of the IPv6
571  * address that it specifies, that is, the number of 1-bits in 'netmask'.
572  * 'netmask' must be a CIDR netmask (see ipv6_is_cidr()).
573  *
574  * If 'netmask' is not a CIDR netmask (see ipv6_is_cidr()), the return value
575  * will still be in the valid range but isn't otherwise meaningful. */
576 int
577 ipv6_count_cidr_bits(const struct in6_addr *netmask)
578 {
579     int i;
580     int count = 0;
581     const uint8_t *netmaskp = &netmask->s6_addr[0];
582
583     for (i=0; i<16; i++) {
584         if (netmaskp[i] == 0xff) {
585             count += 8;
586         } else {
587             uint8_t nm;
588
589             for(nm = netmaskp[i]; nm; nm <<= 1) {
590                 count++;
591             }
592             break;
593         }
594
595     }
596
597     return count;
598 }
599
600 /* Returns true if 'netmask' is a CIDR netmask, that is, if it consists of N
601  * high-order 1-bits and 128-N low-order 0-bits. */
602 bool
603 ipv6_is_cidr(const struct in6_addr *netmask)
604 {
605     const uint8_t *netmaskp = &netmask->s6_addr[0];
606     int i;
607
608     for (i=0; i<16; i++) {
609         if (netmaskp[i] != 0xff) {
610             uint8_t x = ~netmaskp[i];
611             if (x & (x + 1)) {
612                 return false;
613             }
614             while (++i < 16) {
615                 if (netmaskp[i]) {
616                     return false;
617                 }
618             }
619         }
620     }
621
622     return true;
623 }
624
625 /* Parses string 's', which must be an IPv6 address with an optional
626  * CIDR prefix length.  Stores the IP address into '*ipv6' and the CIDR
627  * prefix in '*prefix'.  (If 's' does not contain a CIDR length, all-ones
628  * is assumed.)
629  *
630  * Returns NULL if successful, otherwise an error message that the caller must
631  * free(). */
632 char * OVS_WARN_UNUSED_RESULT
633 ipv6_parse_masked(const char *s, struct in6_addr *ipv6, struct in6_addr *mask)
634 {
635     char ipv6_s[IPV6_SCAN_LEN + 1];
636     char mask_s[IPV6_SCAN_LEN + 1];
637     int prefix;
638     int n;
639
640     if (ovs_scan(s, IPV6_SCAN_FMT"/"IPV6_SCAN_FMT"%n", ipv6_s, mask_s, &n)
641         && inet_pton(AF_INET6, ipv6_s, ipv6) == 1
642         && inet_pton(AF_INET6, mask_s, mask) == 1
643         && !s[n]) {
644         /* OK. */
645     } else if (ovs_scan(s, IPV6_SCAN_FMT"/%d%n", ipv6_s, &prefix, &n)
646         && inet_pton(AF_INET6, ipv6_s, ipv6) == 1
647         && !s[n]) {
648         if (prefix <= 0 || prefix > 128) {
649             return xasprintf("%s: prefix bits not between 0 and 128", s);
650         }
651         *mask = ipv6_create_mask(prefix);
652     } else if (ovs_scan(s, IPV6_SCAN_FMT"%n", ipv6_s, &n)
653                && inet_pton(AF_INET6, ipv6_s, ipv6) == 1
654                && !s[n]) {
655         *mask = in6addr_exact;
656     } else {
657         return xasprintf("%s: invalid IP address", s);
658     }
659     return NULL;
660 }
661
662 /* Populates 'b' with an Ethernet II packet headed with the given 'eth_dst',
663  * 'eth_src' and 'eth_type' parameters.  A payload of 'size' bytes is allocated
664  * in 'b' and returned.  This payload may be populated with appropriate
665  * information by the caller.  Sets 'b''s 'frame' pointer and 'l3' offset to
666  * the Ethernet header and payload respectively.  Aligns b->l3 on a 32-bit
667  * boundary.
668  *
669  * The returned packet has enough headroom to insert an 802.1Q VLAN header if
670  * desired. */
671 void *
672 eth_compose(struct dp_packet *b, const struct eth_addr eth_dst,
673             const struct eth_addr eth_src, uint16_t eth_type,
674             size_t size)
675 {
676     void *data;
677     struct eth_header *eth;
678
679     dp_packet_clear(b);
680
681     /* The magic 2 here ensures that the L3 header (when it is added later)
682      * will be 32-bit aligned. */
683     dp_packet_prealloc_tailroom(b, 2 + ETH_HEADER_LEN + VLAN_HEADER_LEN + size);
684     dp_packet_reserve(b, 2 + VLAN_HEADER_LEN);
685     eth = dp_packet_put_uninit(b, ETH_HEADER_LEN);
686     data = dp_packet_put_uninit(b, size);
687
688     eth->eth_dst = eth_dst;
689     eth->eth_src = eth_src;
690     eth->eth_type = htons(eth_type);
691
692     dp_packet_reset_offsets(b);
693     dp_packet_set_l3(b, data);
694
695     return data;
696 }
697
698 static void
699 packet_set_ipv4_addr(struct dp_packet *packet,
700                      ovs_16aligned_be32 *addr, ovs_be32 new_addr)
701 {
702     struct ip_header *nh = dp_packet_l3(packet);
703     ovs_be32 old_addr = get_16aligned_be32(addr);
704     size_t l4_size = dp_packet_l4_size(packet);
705
706     if (nh->ip_proto == IPPROTO_TCP && l4_size >= TCP_HEADER_LEN) {
707         struct tcp_header *th = dp_packet_l4(packet);
708
709         th->tcp_csum = recalc_csum32(th->tcp_csum, old_addr, new_addr);
710     } else if (nh->ip_proto == IPPROTO_UDP && l4_size >= UDP_HEADER_LEN ) {
711         struct udp_header *uh = dp_packet_l4(packet);
712
713         if (uh->udp_csum) {
714             uh->udp_csum = recalc_csum32(uh->udp_csum, old_addr, new_addr);
715             if (!uh->udp_csum) {
716                 uh->udp_csum = htons(0xffff);
717             }
718         }
719     }
720     nh->ip_csum = recalc_csum32(nh->ip_csum, old_addr, new_addr);
721     put_16aligned_be32(addr, new_addr);
722 }
723
724 /* Returns true, if packet contains at least one routing header where
725  * segements_left > 0.
726  *
727  * This function assumes that L3 and L4 offsets are set in the packet. */
728 static bool
729 packet_rh_present(struct dp_packet *packet)
730 {
731     const struct ovs_16aligned_ip6_hdr *nh;
732     int nexthdr;
733     size_t len;
734     size_t remaining;
735     uint8_t *data = dp_packet_l3(packet);
736
737     remaining = packet->l4_ofs - packet->l3_ofs;
738
739     if (remaining < sizeof *nh) {
740         return false;
741     }
742     nh = ALIGNED_CAST(struct ovs_16aligned_ip6_hdr *, data);
743     data += sizeof *nh;
744     remaining -= sizeof *nh;
745     nexthdr = nh->ip6_nxt;
746
747     while (1) {
748         if ((nexthdr != IPPROTO_HOPOPTS)
749                 && (nexthdr != IPPROTO_ROUTING)
750                 && (nexthdr != IPPROTO_DSTOPTS)
751                 && (nexthdr != IPPROTO_AH)
752                 && (nexthdr != IPPROTO_FRAGMENT)) {
753             /* It's either a terminal header (e.g., TCP, UDP) or one we
754              * don't understand.  In either case, we're done with the
755              * packet, so use it to fill in 'nw_proto'. */
756             break;
757         }
758
759         /* We only verify that at least 8 bytes of the next header are
760          * available, but many of these headers are longer.  Ensure that
761          * accesses within the extension header are within those first 8
762          * bytes. All extension headers are required to be at least 8
763          * bytes. */
764         if (remaining < 8) {
765             return false;
766         }
767
768         if (nexthdr == IPPROTO_AH) {
769             /* A standard AH definition isn't available, but the fields
770              * we care about are in the same location as the generic
771              * option header--only the header length is calculated
772              * differently. */
773             const struct ip6_ext *ext_hdr = (struct ip6_ext *)data;
774
775             nexthdr = ext_hdr->ip6e_nxt;
776             len = (ext_hdr->ip6e_len + 2) * 4;
777         } else if (nexthdr == IPPROTO_FRAGMENT) {
778             const struct ovs_16aligned_ip6_frag *frag_hdr
779                 = ALIGNED_CAST(struct ovs_16aligned_ip6_frag *, data);
780
781             nexthdr = frag_hdr->ip6f_nxt;
782             len = sizeof *frag_hdr;
783         } else if (nexthdr == IPPROTO_ROUTING) {
784             const struct ip6_rthdr *rh = (struct ip6_rthdr *)data;
785
786             if (rh->ip6r_segleft > 0) {
787                 return true;
788             }
789
790             nexthdr = rh->ip6r_nxt;
791             len = (rh->ip6r_len + 1) * 8;
792         } else {
793             const struct ip6_ext *ext_hdr = (struct ip6_ext *)data;
794
795             nexthdr = ext_hdr->ip6e_nxt;
796             len = (ext_hdr->ip6e_len + 1) * 8;
797         }
798
799         if (remaining < len) {
800             return false;
801         }
802         remaining -= len;
803         data += len;
804     }
805
806     return false;
807 }
808
809 static void
810 packet_update_csum128(struct dp_packet *packet, uint8_t proto,
811                      ovs_16aligned_be32 addr[4], const ovs_be32 new_addr[4])
812 {
813     size_t l4_size = dp_packet_l4_size(packet);
814
815     if (proto == IPPROTO_TCP && l4_size >= TCP_HEADER_LEN) {
816         struct tcp_header *th = dp_packet_l4(packet);
817
818         th->tcp_csum = recalc_csum128(th->tcp_csum, addr, new_addr);
819     } else if (proto == IPPROTO_UDP && l4_size >= UDP_HEADER_LEN) {
820         struct udp_header *uh = dp_packet_l4(packet);
821
822         if (uh->udp_csum) {
823             uh->udp_csum = recalc_csum128(uh->udp_csum, addr, new_addr);
824             if (!uh->udp_csum) {
825                 uh->udp_csum = htons(0xffff);
826             }
827         }
828     } else if (proto == IPPROTO_ICMPV6 &&
829                l4_size >= sizeof(struct icmp6_header)) {
830         struct icmp6_header *icmp = dp_packet_l4(packet);
831
832         icmp->icmp6_cksum = recalc_csum128(icmp->icmp6_cksum, addr, new_addr);
833     }
834 }
835
836 static void
837 packet_set_ipv6_addr(struct dp_packet *packet, uint8_t proto,
838                      ovs_16aligned_be32 addr[4], const ovs_be32 new_addr[4],
839                      bool recalculate_csum)
840 {
841     if (recalculate_csum) {
842         packet_update_csum128(packet, proto, addr, new_addr);
843     }
844     memcpy(addr, new_addr, sizeof(ovs_be32[4]));
845 }
846
847 static void
848 packet_set_ipv6_flow_label(ovs_16aligned_be32 *flow_label, ovs_be32 flow_key)
849 {
850     ovs_be32 old_label = get_16aligned_be32(flow_label);
851     ovs_be32 new_label = (old_label & htonl(~IPV6_LABEL_MASK)) | flow_key;
852     put_16aligned_be32(flow_label, new_label);
853 }
854
855 static void
856 packet_set_ipv6_tc(ovs_16aligned_be32 *flow_label, uint8_t tc)
857 {
858     ovs_be32 old_label = get_16aligned_be32(flow_label);
859     ovs_be32 new_label = (old_label & htonl(0xF00FFFFF)) | htonl(tc << 20);
860     put_16aligned_be32(flow_label, new_label);
861 }
862
863 /* Modifies the IPv4 header fields of 'packet' to be consistent with 'src',
864  * 'dst', 'tos', and 'ttl'.  Updates 'packet''s L4 checksums as appropriate.
865  * 'packet' must contain a valid IPv4 packet with correctly populated l[347]
866  * markers. */
867 void
868 packet_set_ipv4(struct dp_packet *packet, ovs_be32 src, ovs_be32 dst,
869                 uint8_t tos, uint8_t ttl)
870 {
871     struct ip_header *nh = dp_packet_l3(packet);
872
873     if (get_16aligned_be32(&nh->ip_src) != src) {
874         packet_set_ipv4_addr(packet, &nh->ip_src, src);
875     }
876
877     if (get_16aligned_be32(&nh->ip_dst) != dst) {
878         packet_set_ipv4_addr(packet, &nh->ip_dst, dst);
879     }
880
881     if (nh->ip_tos != tos) {
882         uint8_t *field = &nh->ip_tos;
883
884         nh->ip_csum = recalc_csum16(nh->ip_csum, htons((uint16_t) *field),
885                                     htons((uint16_t) tos));
886         *field = tos;
887     }
888
889     if (nh->ip_ttl != ttl) {
890         uint8_t *field = &nh->ip_ttl;
891
892         nh->ip_csum = recalc_csum16(nh->ip_csum, htons(*field << 8),
893                                     htons(ttl << 8));
894         *field = ttl;
895     }
896 }
897
898 /* Modifies the IPv6 header fields of 'packet' to be consistent with 'src',
899  * 'dst', 'traffic class', and 'next hop'.  Updates 'packet''s L4 checksums as
900  * appropriate. 'packet' must contain a valid IPv6 packet with correctly
901  * populated l[34] offsets. */
902 void
903 packet_set_ipv6(struct dp_packet *packet, uint8_t proto, const ovs_be32 src[4],
904                 const ovs_be32 dst[4], uint8_t key_tc, ovs_be32 key_fl,
905                 uint8_t key_hl)
906 {
907     struct ovs_16aligned_ip6_hdr *nh = dp_packet_l3(packet);
908
909     if (memcmp(&nh->ip6_src, src, sizeof(ovs_be32[4]))) {
910         packet_set_ipv6_addr(packet, proto, nh->ip6_src.be32, src, true);
911     }
912
913     if (memcmp(&nh->ip6_dst, dst, sizeof(ovs_be32[4]))) {
914         packet_set_ipv6_addr(packet, proto, nh->ip6_dst.be32, dst,
915                              !packet_rh_present(packet));
916     }
917
918     packet_set_ipv6_tc(&nh->ip6_flow, key_tc);
919
920     packet_set_ipv6_flow_label(&nh->ip6_flow, key_fl);
921
922     nh->ip6_hlim = key_hl;
923 }
924
925 static void
926 packet_set_port(ovs_be16 *port, ovs_be16 new_port, ovs_be16 *csum)
927 {
928     if (*port != new_port) {
929         *csum = recalc_csum16(*csum, *port, new_port);
930         *port = new_port;
931     }
932 }
933
934 /* Sets the TCP source and destination port ('src' and 'dst' respectively) of
935  * the TCP header contained in 'packet'.  'packet' must be a valid TCP packet
936  * with its l4 offset properly populated. */
937 void
938 packet_set_tcp_port(struct dp_packet *packet, ovs_be16 src, ovs_be16 dst)
939 {
940     struct tcp_header *th = dp_packet_l4(packet);
941
942     packet_set_port(&th->tcp_src, src, &th->tcp_csum);
943     packet_set_port(&th->tcp_dst, dst, &th->tcp_csum);
944 }
945
946 /* Sets the UDP source and destination port ('src' and 'dst' respectively) of
947  * the UDP header contained in 'packet'.  'packet' must be a valid UDP packet
948  * with its l4 offset properly populated. */
949 void
950 packet_set_udp_port(struct dp_packet *packet, ovs_be16 src, ovs_be16 dst)
951 {
952     struct udp_header *uh = dp_packet_l4(packet);
953
954     if (uh->udp_csum) {
955         packet_set_port(&uh->udp_src, src, &uh->udp_csum);
956         packet_set_port(&uh->udp_dst, dst, &uh->udp_csum);
957
958         if (!uh->udp_csum) {
959             uh->udp_csum = htons(0xffff);
960         }
961     } else {
962         uh->udp_src = src;
963         uh->udp_dst = dst;
964     }
965 }
966
967 /* Sets the SCTP source and destination port ('src' and 'dst' respectively) of
968  * the SCTP header contained in 'packet'.  'packet' must be a valid SCTP packet
969  * with its l4 offset properly populated. */
970 void
971 packet_set_sctp_port(struct dp_packet *packet, ovs_be16 src, ovs_be16 dst)
972 {
973     struct sctp_header *sh = dp_packet_l4(packet);
974     ovs_be32 old_csum, old_correct_csum, new_csum;
975     uint16_t tp_len = dp_packet_l4_size(packet);
976
977     old_csum = get_16aligned_be32(&sh->sctp_csum);
978     put_16aligned_be32(&sh->sctp_csum, 0);
979     old_correct_csum = crc32c((void *)sh, tp_len);
980
981     sh->sctp_src = src;
982     sh->sctp_dst = dst;
983
984     new_csum = crc32c((void *)sh, tp_len);
985     put_16aligned_be32(&sh->sctp_csum, old_csum ^ old_correct_csum ^ new_csum);
986 }
987
988 /* Sets the ICMP type and code of the ICMP header contained in 'packet'.
989  * 'packet' must be a valid ICMP packet with its l4 offset properly
990  * populated. */
991 void
992 packet_set_icmp(struct dp_packet *packet, uint8_t type, uint8_t code)
993 {
994     struct icmp_header *ih = dp_packet_l4(packet);
995     ovs_be16 orig_tc = htons(ih->icmp_type << 8 | ih->icmp_code);
996     ovs_be16 new_tc = htons(type << 8 | code);
997
998     if (orig_tc != new_tc) {
999         ih->icmp_type = type;
1000         ih->icmp_code = code;
1001
1002         ih->icmp_csum = recalc_csum16(ih->icmp_csum, orig_tc, new_tc);
1003     }
1004 }
1005
1006 void
1007 packet_set_nd(struct dp_packet *packet, const ovs_be32 target[4],
1008               const struct eth_addr sll, const struct eth_addr tll) {
1009     struct ovs_nd_msg *ns;
1010     struct ovs_nd_opt *nd_opt;
1011     int bytes_remain = dp_packet_l4_size(packet);
1012
1013     if (OVS_UNLIKELY(bytes_remain < sizeof(*ns))) {
1014         return;
1015     }
1016
1017     ns = dp_packet_l4(packet);
1018     nd_opt = &ns->options[0];
1019     bytes_remain -= sizeof(*ns);
1020
1021     if (memcmp(&ns->target, target, sizeof(ovs_be32[4]))) {
1022         packet_set_ipv6_addr(packet, IPPROTO_ICMPV6,
1023                              ns->target.be32,
1024                              target, true);
1025     }
1026
1027     while (bytes_remain >= ND_OPT_LEN && nd_opt->nd_opt_len != 0) {
1028         if (nd_opt->nd_opt_type == ND_OPT_SOURCE_LINKADDR
1029             && nd_opt->nd_opt_len == 1) {
1030             if (!eth_addr_equals(nd_opt->nd_opt_mac, sll)) {
1031                 ovs_be16 *csum = &(ns->icmph.icmp6_cksum);
1032
1033                 *csum = recalc_csum48(*csum, nd_opt->nd_opt_mac, sll);
1034                 nd_opt->nd_opt_mac = sll;
1035             }
1036
1037             /* A packet can only contain one SLL or TLL option */
1038             break;
1039         } else if (nd_opt->nd_opt_type == ND_OPT_TARGET_LINKADDR
1040                    && nd_opt->nd_opt_len == 1) {
1041             if (!eth_addr_equals(nd_opt->nd_opt_mac, tll)) {
1042                 ovs_be16 *csum = &(ns->icmph.icmp6_cksum);
1043
1044                 *csum = recalc_csum48(*csum, nd_opt->nd_opt_mac, tll);
1045                 nd_opt->nd_opt_mac = tll;
1046             }
1047
1048             /* A packet can only contain one SLL or TLL option */
1049             break;
1050         }
1051
1052         nd_opt += nd_opt->nd_opt_len;
1053         bytes_remain -= nd_opt->nd_opt_len * ND_OPT_LEN;
1054     }
1055 }
1056
1057 const char *
1058 packet_tcp_flag_to_string(uint32_t flag)
1059 {
1060     switch (flag) {
1061     case TCP_FIN:
1062         return "fin";
1063     case TCP_SYN:
1064         return "syn";
1065     case TCP_RST:
1066         return "rst";
1067     case TCP_PSH:
1068         return "psh";
1069     case TCP_ACK:
1070         return "ack";
1071     case TCP_URG:
1072         return "urg";
1073     case TCP_ECE:
1074         return "ece";
1075     case TCP_CWR:
1076         return "cwr";
1077     case TCP_NS:
1078         return "ns";
1079     case 0x200:
1080         return "[200]";
1081     case 0x400:
1082         return "[400]";
1083     case 0x800:
1084         return "[800]";
1085     default:
1086         return NULL;
1087     }
1088 }
1089
1090 /* Appends a string representation of the TCP flags value 'tcp_flags'
1091  * (e.g. from struct flow.tcp_flags or obtained via TCP_FLAGS) to 's', in the
1092  * format used by tcpdump. */
1093 void
1094 packet_format_tcp_flags(struct ds *s, uint16_t tcp_flags)
1095 {
1096     if (!tcp_flags) {
1097         ds_put_cstr(s, "none");
1098         return;
1099     }
1100
1101     if (tcp_flags & TCP_SYN) {
1102         ds_put_char(s, 'S');
1103     }
1104     if (tcp_flags & TCP_FIN) {
1105         ds_put_char(s, 'F');
1106     }
1107     if (tcp_flags & TCP_PSH) {
1108         ds_put_char(s, 'P');
1109     }
1110     if (tcp_flags & TCP_RST) {
1111         ds_put_char(s, 'R');
1112     }
1113     if (tcp_flags & TCP_URG) {
1114         ds_put_char(s, 'U');
1115     }
1116     if (tcp_flags & TCP_ACK) {
1117         ds_put_char(s, '.');
1118     }
1119     if (tcp_flags & TCP_ECE) {
1120         ds_put_cstr(s, "E");
1121     }
1122     if (tcp_flags & TCP_CWR) {
1123         ds_put_cstr(s, "C");
1124     }
1125     if (tcp_flags & TCP_NS) {
1126         ds_put_cstr(s, "N");
1127     }
1128     if (tcp_flags & 0x200) {
1129         ds_put_cstr(s, "[200]");
1130     }
1131     if (tcp_flags & 0x400) {
1132         ds_put_cstr(s, "[400]");
1133     }
1134     if (tcp_flags & 0x800) {
1135         ds_put_cstr(s, "[800]");
1136     }
1137 }
1138
1139 #define ARP_PACKET_SIZE  (2 + ETH_HEADER_LEN + VLAN_HEADER_LEN + \
1140                           ARP_ETH_HEADER_LEN)
1141
1142 /* Clears 'b' and replaces its contents by an ARP frame with the specified
1143  * 'arp_op', 'arp_sha', 'arp_tha', 'arp_spa', and 'arp_tpa'.  The outer
1144  * Ethernet frame is initialized with Ethernet source 'arp_sha' and destination
1145  * 'arp_tha', except that destination ff:ff:ff:ff:ff:ff is used instead if
1146  * 'broadcast' is true. */
1147 void
1148 compose_arp(struct dp_packet *b, uint16_t arp_op,
1149             const struct eth_addr arp_sha, const struct eth_addr arp_tha,
1150             bool broadcast, ovs_be32 arp_spa, ovs_be32 arp_tpa)
1151 {
1152     struct eth_header *eth;
1153     struct arp_eth_header *arp;
1154
1155     dp_packet_clear(b);
1156     dp_packet_prealloc_tailroom(b, ARP_PACKET_SIZE);
1157     dp_packet_reserve(b, 2 + VLAN_HEADER_LEN);
1158
1159     eth = dp_packet_put_uninit(b, sizeof *eth);
1160     eth->eth_dst = broadcast ? eth_addr_broadcast : arp_tha;
1161     eth->eth_src = arp_sha;
1162     eth->eth_type = htons(ETH_TYPE_ARP);
1163
1164     arp = dp_packet_put_uninit(b, sizeof *arp);
1165     arp->ar_hrd = htons(ARP_HRD_ETHERNET);
1166     arp->ar_pro = htons(ARP_PRO_IP);
1167     arp->ar_hln = sizeof arp->ar_sha;
1168     arp->ar_pln = sizeof arp->ar_spa;
1169     arp->ar_op = htons(arp_op);
1170     arp->ar_sha = arp_sha;
1171     arp->ar_tha = arp_tha;
1172
1173     put_16aligned_be32(&arp->ar_spa, arp_spa);
1174     put_16aligned_be32(&arp->ar_tpa, arp_tpa);
1175
1176     dp_packet_reset_offsets(b);
1177     dp_packet_set_l3(b, arp);
1178 }
1179
1180 uint32_t
1181 packet_csum_pseudoheader(const struct ip_header *ip)
1182 {
1183     uint32_t partial = 0;
1184
1185     partial = csum_add32(partial, get_16aligned_be32(&ip->ip_src));
1186     partial = csum_add32(partial, get_16aligned_be32(&ip->ip_dst));
1187     partial = csum_add16(partial, htons(ip->ip_proto));
1188     partial = csum_add16(partial, htons(ntohs(ip->ip_tot_len) -
1189                                         IP_IHL(ip->ip_ihl_ver) * 4));
1190
1191     return partial;
1192 }
1193