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