datapath: Fix sparse warning on BUILD_BUG_ON_NOT_POWER_OF_2 definition.
[sliver-openvswitch.git] / lib / packets.c
1 /*
2  * Copyright (c) 2009, 2010, 2011, 2012 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 <assert.h>
20 #include <arpa/inet.h>
21 #include <sys/socket.h>
22 #include <netinet/in.h>
23 #include <stdlib.h>
24 #include "byte-order.h"
25 #include "csum.h"
26 #include "flow.h"
27 #include "dynamic-string.h"
28 #include "ofpbuf.h"
29
30 const struct in6_addr in6addr_exact = IN6ADDR_EXACT_INIT;
31
32 /* Parses 's' as a 16-digit hexadecimal number representing a datapath ID.  On
33  * success stores the dpid into '*dpidp' and returns true, on failure stores 0
34  * into '*dpidp' and returns false.
35  *
36  * Rejects an all-zeros dpid as invalid. */
37 bool
38 dpid_from_string(const char *s, uint64_t *dpidp)
39 {
40     *dpidp = (strlen(s) == 16 && strspn(s, "0123456789abcdefABCDEF") == 16
41               ? strtoull(s, NULL, 16)
42               : 0);
43     return *dpidp != 0;
44 }
45
46 /* Returns true if 'ea' is a reserved multicast address, that a bridge must
47  * never forward, false otherwise.  Includes some proprietary vendor protocols
48  * that shouldn't be forwarded as well.
49  *
50  * If you change this function's behavior, please update corresponding
51  * documentation in vswitch.xml at the same time. */
52 bool
53 eth_addr_is_reserved(const uint8_t ea[ETH_ADDR_LEN])
54 {
55     struct masked_eth_addr {
56         uint8_t ea[ETH_ADDR_LEN];
57         uint8_t mask[ETH_ADDR_LEN];
58     };
59
60     static struct masked_eth_addr mea[] = {
61         { /* STP, IEEE pause frames, and other reserved protocols. */
62             {0x01, 0x08, 0xc2, 0x00, 0x00, 0x00},
63             {0xff, 0xff, 0xff, 0xff, 0xff, 0xf0}},
64
65         { /* VRRP IPv4. */
66             {0x00, 0x00, 0x5e, 0x00, 0x01, 0x00},
67             {0xff, 0xff, 0xff, 0xff, 0xff, 0x00}},
68
69         { /* VRRP IPv6. */
70             {0x00, 0x00, 0x5e, 0x00, 0x02, 0x00},
71             {0xff, 0xff, 0xff, 0xff, 0xff, 0x00}},
72
73         { /* HSRPv1. */
74             {0x00, 0x00, 0x0c, 0x07, 0xac, 0x00},
75             {0xff, 0xff, 0xff, 0xff, 0xff, 0x00}},
76
77         { /* HSRPv2. */
78             {0x00, 0x00, 0x0c, 0x9f, 0xf0, 0x00},
79             {0xff, 0xff, 0xff, 0xff, 0xf0, 0x00}},
80
81         { /* GLBP. */
82             {0x00, 0x07, 0xb4, 0x00, 0x00, 0x00},
83             {0xff, 0xff, 0xff, 0x00, 0x00, 0x00}},
84
85         { /* Extreme Discovery Protocol. */
86             {0x00, 0xE0, 0x2B, 0x00, 0x00, 0x00},
87             {0xff, 0xff, 0xff, 0xff, 0xf0, 0x00}},
88
89         { /* Cisco Inter Switch Link. */
90             {0x01, 0x00, 0x0c, 0x00, 0x00, 0x00},
91             {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}},
92
93         { /* Cisco protocols plus others following the same pattern:
94            *
95            * CDP, VTP, DTP, PAgP  (01-00-0c-cc-cc-cc)
96            * Spanning Tree PVSTP+ (01-00-0c-cc-cc-cd)
97            * STP Uplink Fast      (01-00-0c-cd-cd-cd) */
98             {0x01, 0x00, 0x0c, 0xcc, 0xcc, 0xcc},
99             {0xff, 0xff, 0xff, 0xfe, 0xfe, 0xfe}}};
100
101     size_t i;
102
103     for (i = 0; i < ARRAY_SIZE(mea); i++) {
104         if (eth_addr_equal_except(ea, mea[i].ea, mea[i].mask)) {
105             return true;
106         }
107     }
108     return false;
109 }
110
111 bool
112 eth_addr_from_string(const char *s, uint8_t ea[ETH_ADDR_LEN])
113 {
114     if (sscanf(s, ETH_ADDR_SCAN_FMT, ETH_ADDR_SCAN_ARGS(ea))
115         == ETH_ADDR_SCAN_COUNT) {
116         return true;
117     } else {
118         memset(ea, 0, ETH_ADDR_LEN);
119         return false;
120     }
121 }
122
123 /* Fills 'b' with an 802.2 SNAP packet with Ethernet source address 'eth_src',
124  * the Nicira OUI as SNAP organization and 'snap_type' as SNAP type.  The text
125  * string in 'tag' is enclosed as the packet payload.
126  *
127  * This function is used by Open vSwitch to compose packets in cases where
128  * context is important but content doesn't (or shouldn't) matter.  For this
129  * purpose, 'snap_type' should be a random number and 'tag' should be an
130  * English phrase that explains the purpose of the packet.  (The English phrase
131  * gives hapless admins running Wireshark the opportunity to figure out what's
132  * going on.) */
133 void
134 compose_benign_packet(struct ofpbuf *b, const char *tag, uint16_t snap_type,
135                       const uint8_t eth_src[ETH_ADDR_LEN])
136 {
137     size_t tag_size = strlen(tag) + 1;
138     char *payload;
139
140     payload = snap_compose(b, eth_addr_broadcast, eth_src, 0x002320, snap_type,
141                            tag_size + ETH_ADDR_LEN);
142     memcpy(payload, tag, tag_size);
143     memcpy(payload + tag_size, eth_src, ETH_ADDR_LEN);
144 }
145
146 /* Insert VLAN header according to given TCI. Packet passed must be Ethernet
147  * packet.  Ignores the CFI bit of 'tci' using 0 instead.
148  *
149  * Also sets 'packet->l2' to point to the new Ethernet header. */
150 void
151 eth_push_vlan(struct ofpbuf *packet, ovs_be16 tci)
152 {
153     struct eth_header *eh = packet->data;
154     struct vlan_eth_header *veh;
155
156     /* Insert new 802.1Q header. */
157     struct vlan_eth_header tmp;
158     memcpy(tmp.veth_dst, eh->eth_dst, ETH_ADDR_LEN);
159     memcpy(tmp.veth_src, eh->eth_src, ETH_ADDR_LEN);
160     tmp.veth_type = htons(ETH_TYPE_VLAN);
161     tmp.veth_tci = tci & htons(~VLAN_CFI);
162     tmp.veth_next_type = eh->eth_type;
163
164     veh = ofpbuf_push_uninit(packet, VLAN_HEADER_LEN);
165     memcpy(veh, &tmp, sizeof tmp);
166
167     packet->l2 = packet->data;
168 }
169
170 /* Removes outermost VLAN header (if any is present) from 'packet'.
171  *
172  * 'packet->l2' must initially point to 'packet''s Ethernet header. */
173 void
174 eth_pop_vlan(struct ofpbuf *packet)
175 {
176     struct vlan_eth_header *veh = packet->l2;
177     if (packet->size >= sizeof *veh
178         && veh->veth_type == htons(ETH_TYPE_VLAN)) {
179         struct eth_header tmp;
180
181         memcpy(tmp.eth_dst, veh->veth_dst, ETH_ADDR_LEN);
182         memcpy(tmp.eth_src, veh->veth_src, ETH_ADDR_LEN);
183         tmp.eth_type = veh->veth_next_type;
184
185         ofpbuf_pull(packet, VLAN_HEADER_LEN);
186         packet->l2 = (char*)packet->l2 + VLAN_HEADER_LEN;
187         memcpy(packet->data, &tmp, sizeof tmp);
188     }
189 }
190
191 /* Converts hex digits in 'hex' to an Ethernet packet in '*packetp'.  The
192  * caller must free '*packetp'.  On success, returns NULL.  On failure, returns
193  * an error message and stores NULL in '*packetp'. */
194 const char *
195 eth_from_hex(const char *hex, struct ofpbuf **packetp)
196 {
197     struct ofpbuf *packet;
198
199     packet = *packetp = ofpbuf_new(strlen(hex) / 2);
200
201     if (ofpbuf_put_hex(packet, hex, NULL)[0] != '\0') {
202         ofpbuf_delete(packet);
203         *packetp = NULL;
204         return "Trailing garbage in packet data";
205     }
206
207     if (packet->size < ETH_HEADER_LEN) {
208         ofpbuf_delete(packet);
209         *packetp = NULL;
210         return "Packet data too short for Ethernet";
211     }
212
213     return NULL;
214 }
215
216 void
217 eth_format_masked(const uint8_t eth[ETH_ADDR_LEN],
218                   const uint8_t mask[ETH_ADDR_LEN], struct ds *s)
219 {
220     ds_put_format(s, ETH_ADDR_FMT, ETH_ADDR_ARGS(eth));
221     if (mask && !eth_mask_is_exact(mask)) {
222         ds_put_format(s, "/"ETH_ADDR_FMT, ETH_ADDR_ARGS(mask));
223     }
224 }
225
226 void
227 eth_addr_bitand(const uint8_t src[ETH_ADDR_LEN],
228                 const uint8_t mask[ETH_ADDR_LEN],
229                 uint8_t dst[ETH_ADDR_LEN])
230 {
231     int i;
232
233     for (i = 0; i < ETH_ADDR_LEN; i++) {
234         dst[i] = src[i] & mask[i];
235     }
236 }
237
238 /* Given the IP netmask 'netmask', returns the number of bits of the IP address
239  * that it specifies, that is, the number of 1-bits in 'netmask'.  'netmask'
240  * must be a CIDR netmask (see ip_is_cidr()). */
241 int
242 ip_count_cidr_bits(ovs_be32 netmask)
243 {
244     assert(ip_is_cidr(netmask));
245     return 32 - ctz(ntohl(netmask));
246 }
247
248 void
249 ip_format_masked(ovs_be32 ip, ovs_be32 mask, struct ds *s)
250 {
251     ds_put_format(s, IP_FMT, IP_ARGS(&ip));
252     if (mask != htonl(UINT32_MAX)) {
253         if (ip_is_cidr(mask)) {
254             ds_put_format(s, "/%d", ip_count_cidr_bits(mask));
255         } else {
256             ds_put_format(s, "/"IP_FMT, IP_ARGS(&mask));
257         }
258     }
259 }
260
261
262 /* Stores the string representation of the IPv6 address 'addr' into the
263  * character array 'addr_str', which must be at least INET6_ADDRSTRLEN
264  * bytes long. */
265 void
266 format_ipv6_addr(char *addr_str, const struct in6_addr *addr)
267 {
268     inet_ntop(AF_INET6, addr, addr_str, INET6_ADDRSTRLEN);
269 }
270
271 void
272 print_ipv6_addr(struct ds *string, const struct in6_addr *addr)
273 {
274     char *dst;
275
276     ds_reserve(string, string->length + INET6_ADDRSTRLEN);
277
278     dst = string->string + string->length;
279     format_ipv6_addr(dst, addr);
280     string->length += strlen(dst);
281 }
282
283 void
284 print_ipv6_masked(struct ds *s, const struct in6_addr *addr,
285                   const struct in6_addr *mask)
286 {
287     print_ipv6_addr(s, addr);
288     if (mask && !ipv6_mask_is_exact(mask)) {
289         if (ipv6_is_cidr(mask)) {
290             int cidr_bits = ipv6_count_cidr_bits(mask);
291             ds_put_format(s, "/%d", cidr_bits);
292         } else {
293             ds_put_char(s, '/');
294             print_ipv6_addr(s, mask);
295         }
296     }
297 }
298
299 struct in6_addr ipv6_addr_bitand(const struct in6_addr *a,
300                                  const struct in6_addr *b)
301 {
302     int i;
303     struct in6_addr dst;
304
305 #ifdef s6_addr32
306     for (i=0; i<4; i++) {
307         dst.s6_addr32[i] = a->s6_addr32[i] & b->s6_addr32[i];
308     }
309 #else
310     for (i=0; i<16; i++) {
311         dst.s6_addr[i] = a->s6_addr[i] & b->s6_addr[i];
312     }
313 #endif
314
315     return dst;
316 }
317
318 /* Returns an in6_addr consisting of 'mask' high-order 1-bits and 128-N
319  * low-order 0-bits. */
320 struct in6_addr
321 ipv6_create_mask(int mask)
322 {
323     struct in6_addr netmask;
324     uint8_t *netmaskp = &netmask.s6_addr[0];
325
326     memset(&netmask, 0, sizeof netmask);
327     while (mask > 8) {
328         *netmaskp = 0xff;
329         netmaskp++;
330         mask -= 8;
331     }
332
333     if (mask) {
334         *netmaskp = 0xff << (8 - mask);
335     }
336
337     return netmask;
338 }
339
340 /* Given the IPv6 netmask 'netmask', returns the number of bits of the IPv6
341  * address that it specifies, that is, the number of 1-bits in 'netmask'.
342  * 'netmask' must be a CIDR netmask (see ipv6_is_cidr()). */
343 int
344 ipv6_count_cidr_bits(const struct in6_addr *netmask)
345 {
346     int i;
347     int count = 0;
348     const uint8_t *netmaskp = &netmask->s6_addr[0];
349
350     assert(ipv6_is_cidr(netmask));
351
352     for (i=0; i<16; i++) {
353         if (netmaskp[i] == 0xff) {
354             count += 8;
355         } else {
356             uint8_t nm;
357
358             for(nm = netmaskp[i]; nm; nm <<= 1) {
359                 count++;
360             }
361             break;
362         }
363
364     }
365
366     return count;
367 }
368
369 /* Returns true if 'netmask' is a CIDR netmask, that is, if it consists of N
370  * high-order 1-bits and 128-N low-order 0-bits. */
371 bool
372 ipv6_is_cidr(const struct in6_addr *netmask)
373 {
374     const uint8_t *netmaskp = &netmask->s6_addr[0];
375     int i;
376
377     for (i=0; i<16; i++) {
378         if (netmaskp[i] != 0xff) {
379             uint8_t x = ~netmaskp[i];
380             if (x & (x + 1)) {
381                 return false;
382             }
383             while (++i < 16) {
384                 if (netmaskp[i]) {
385                     return false;
386                 }
387             }
388         }
389     }
390
391     return true;
392 }
393
394 /* Populates 'b' with an Ethernet II packet headed with the given 'eth_dst',
395  * 'eth_src' and 'eth_type' parameters.  A payload of 'size' bytes is allocated
396  * in 'b' and returned.  This payload may be populated with appropriate
397  * information by the caller.  Sets 'b''s 'l2' and 'l3' pointers to the
398  * Ethernet header and payload respectively.
399  *
400  * The returned packet has enough headroom to insert an 802.1Q VLAN header if
401  * desired. */
402 void *
403 eth_compose(struct ofpbuf *b, const uint8_t eth_dst[ETH_ADDR_LEN],
404             const uint8_t eth_src[ETH_ADDR_LEN], uint16_t eth_type,
405             size_t size)
406 {
407     void *data;
408     struct eth_header *eth;
409
410     ofpbuf_clear(b);
411
412     ofpbuf_prealloc_tailroom(b, ETH_HEADER_LEN + VLAN_HEADER_LEN + size);
413     ofpbuf_reserve(b, VLAN_HEADER_LEN);
414     eth = ofpbuf_put_uninit(b, ETH_HEADER_LEN);
415     data = ofpbuf_put_uninit(b, size);
416
417     memcpy(eth->eth_dst, eth_dst, ETH_ADDR_LEN);
418     memcpy(eth->eth_src, eth_src, ETH_ADDR_LEN);
419     eth->eth_type = htons(eth_type);
420
421     b->l2 = eth;
422     b->l3 = data;
423
424     return data;
425 }
426
427 /* Populates 'b' with an Ethernet LLC+SNAP packet headed with the given
428  * 'eth_dst', 'eth_src', 'snap_org', and 'snap_type'.  A payload of 'size'
429  * bytes is allocated in 'b' and returned.  This payload may be populated with
430  * appropriate information by the caller.
431  *
432  * The returned packet has enough headroom to insert an 802.1Q VLAN header if
433  * desired. */
434 void *
435 snap_compose(struct ofpbuf *b, const uint8_t eth_dst[ETH_ADDR_LEN],
436              const uint8_t eth_src[ETH_ADDR_LEN],
437              unsigned int oui, uint16_t snap_type, size_t size)
438 {
439     struct eth_header *eth;
440     struct llc_snap_header *llc_snap;
441     void *payload;
442
443     /* Compose basic packet structure.  (We need the payload size to stick into
444      * the 802.2 header.) */
445     ofpbuf_clear(b);
446     ofpbuf_prealloc_tailroom(b, ETH_HEADER_LEN + VLAN_HEADER_LEN
447                              + LLC_SNAP_HEADER_LEN + size);
448     ofpbuf_reserve(b, VLAN_HEADER_LEN);
449     eth = ofpbuf_put_zeros(b, ETH_HEADER_LEN);
450     llc_snap = ofpbuf_put_zeros(b, LLC_SNAP_HEADER_LEN);
451     payload = ofpbuf_put_uninit(b, size);
452
453     /* Compose 802.2 header. */
454     memcpy(eth->eth_dst, eth_dst, ETH_ADDR_LEN);
455     memcpy(eth->eth_src, eth_src, ETH_ADDR_LEN);
456     eth->eth_type = htons(b->size - ETH_HEADER_LEN);
457
458     /* Compose LLC, SNAP headers. */
459     llc_snap->llc.llc_dsap = LLC_DSAP_SNAP;
460     llc_snap->llc.llc_ssap = LLC_SSAP_SNAP;
461     llc_snap->llc.llc_cntl = LLC_CNTL_SNAP;
462     llc_snap->snap.snap_org[0] = oui >> 16;
463     llc_snap->snap.snap_org[1] = oui >> 8;
464     llc_snap->snap.snap_org[2] = oui;
465     llc_snap->snap.snap_type = htons(snap_type);
466
467     return payload;
468 }
469
470 static void
471 packet_set_ipv4_addr(struct ofpbuf *packet, ovs_be32 *addr, ovs_be32 new_addr)
472 {
473     struct ip_header *nh = packet->l3;
474
475     if (nh->ip_proto == IPPROTO_TCP && packet->l7) {
476         struct tcp_header *th = packet->l4;
477
478         th->tcp_csum = recalc_csum32(th->tcp_csum, *addr, new_addr);
479     } else if (nh->ip_proto == IPPROTO_UDP && packet->l7) {
480         struct udp_header *uh = packet->l4;
481
482         if (uh->udp_csum) {
483             uh->udp_csum = recalc_csum32(uh->udp_csum, *addr, new_addr);
484             if (!uh->udp_csum) {
485                 uh->udp_csum = htons(0xffff);
486             }
487         }
488     }
489     nh->ip_csum = recalc_csum32(nh->ip_csum, *addr, new_addr);
490     *addr = new_addr;
491 }
492
493 /* Modifies the IPv4 header fields of 'packet' to be consistent with 'src',
494  * 'dst', 'tos', and 'ttl'.  Updates 'packet''s L4 checksums as appropriate.
495  * 'packet' must contain a valid IPv4 packet with correctly populated l[347]
496  * markers. */
497 void
498 packet_set_ipv4(struct ofpbuf *packet, ovs_be32 src, ovs_be32 dst,
499                 uint8_t tos, uint8_t ttl)
500 {
501     struct ip_header *nh = packet->l3;
502
503     if (nh->ip_src != src) {
504         packet_set_ipv4_addr(packet, &nh->ip_src, src);
505     }
506
507     if (nh->ip_dst != dst) {
508         packet_set_ipv4_addr(packet, &nh->ip_dst, dst);
509     }
510
511     if (nh->ip_tos != tos) {
512         uint8_t *field = &nh->ip_tos;
513
514         nh->ip_csum = recalc_csum16(nh->ip_csum, htons((uint16_t) *field),
515                                     htons((uint16_t) tos));
516         *field = tos;
517     }
518
519     if (nh->ip_ttl != ttl) {
520         uint8_t *field = &nh->ip_ttl;
521
522         nh->ip_csum = recalc_csum16(nh->ip_csum, htons(*field << 8),
523                                     htons(ttl << 8));
524         *field = ttl;
525     }
526 }
527
528 static void
529 packet_set_port(ovs_be16 *port, ovs_be16 new_port, ovs_be16 *csum)
530 {
531     if (*port != new_port) {
532         *csum = recalc_csum16(*csum, *port, new_port);
533         *port = new_port;
534     }
535 }
536
537 /* Sets the TCP source and destination port ('src' and 'dst' respectively) of
538  * the TCP header contained in 'packet'.  'packet' must be a valid TCP packet
539  * with its l4 marker properly populated. */
540 void
541 packet_set_tcp_port(struct ofpbuf *packet, ovs_be16 src, ovs_be16 dst)
542 {
543     struct tcp_header *th = packet->l4;
544
545     packet_set_port(&th->tcp_src, src, &th->tcp_csum);
546     packet_set_port(&th->tcp_dst, dst, &th->tcp_csum);
547 }
548
549 /* Sets the UDP source and destination port ('src' and 'dst' respectively) of
550  * the UDP header contained in 'packet'.  'packet' must be a valid UDP packet
551  * with its l4 marker properly populated. */
552 void
553 packet_set_udp_port(struct ofpbuf *packet, ovs_be16 src, ovs_be16 dst)
554 {
555     struct udp_header *uh = packet->l4;
556
557     if (uh->udp_csum) {
558         packet_set_port(&uh->udp_src, src, &uh->udp_csum);
559         packet_set_port(&uh->udp_dst, dst, &uh->udp_csum);
560
561         if (!uh->udp_csum) {
562             uh->udp_csum = htons(0xffff);
563         }
564     } else {
565         uh->udp_src = src;
566         uh->udp_dst = dst;
567     }
568 }
569
570 /* If 'packet' is a TCP packet, returns the TCP flags.  Otherwise, returns 0.
571  *
572  * 'flow' must be the flow corresponding to 'packet' and 'packet''s header
573  * pointers must be properly initialized (e.g. with flow_extract()). */
574 uint8_t
575 packet_get_tcp_flags(const struct ofpbuf *packet, const struct flow *flow)
576 {
577     if ((flow->dl_type == htons(ETH_TYPE_IP) ||
578          flow->dl_type == htons(ETH_TYPE_IPV6)) &&
579         flow->nw_proto == IPPROTO_TCP && packet->l7) {
580         const struct tcp_header *tcp = packet->l4;
581         return TCP_FLAGS(tcp->tcp_ctl);
582     } else {
583         return 0;
584     }
585 }
586
587 /* Appends a string representation of the TCP flags value 'tcp_flags'
588  * (e.g. obtained via packet_get_tcp_flags() or TCP_FLAGS) to 's', in the
589  * format used by tcpdump. */
590 void
591 packet_format_tcp_flags(struct ds *s, uint8_t tcp_flags)
592 {
593     if (!tcp_flags) {
594         ds_put_cstr(s, "none");
595         return;
596     }
597
598     if (tcp_flags & TCP_SYN) {
599         ds_put_char(s, 'S');
600     }
601     if (tcp_flags & TCP_FIN) {
602         ds_put_char(s, 'F');
603     }
604     if (tcp_flags & TCP_PSH) {
605         ds_put_char(s, 'P');
606     }
607     if (tcp_flags & TCP_RST) {
608         ds_put_char(s, 'R');
609     }
610     if (tcp_flags & TCP_URG) {
611         ds_put_char(s, 'U');
612     }
613     if (tcp_flags & TCP_ACK) {
614         ds_put_char(s, '.');
615     }
616     if (tcp_flags & 0x40) {
617         ds_put_cstr(s, "[40]");
618     }
619     if (tcp_flags & 0x80) {
620         ds_put_cstr(s, "[80]");
621     }
622 }