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