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