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