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