Global replace of Nicira Networks.
[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 /* Given the IP netmask 'netmask', returns the number of bits of the IP address
152  * that it specifies, that is, the number of 1-bits in 'netmask'.  'netmask'
153  * must be a CIDR netmask (see ip_is_cidr()). */
154 int
155 ip_count_cidr_bits(ovs_be32 netmask)
156 {
157     assert(ip_is_cidr(netmask));
158     return 32 - ctz(ntohl(netmask));
159 }
160
161 void
162 ip_format_masked(ovs_be32 ip, ovs_be32 mask, struct ds *s)
163 {
164     ds_put_format(s, IP_FMT, IP_ARGS(&ip));
165     if (mask != htonl(UINT32_MAX)) {
166         if (ip_is_cidr(mask)) {
167             ds_put_format(s, "/%d", ip_count_cidr_bits(mask));
168         } else {
169             ds_put_format(s, "/"IP_FMT, IP_ARGS(&mask));
170         }
171     }
172 }
173
174
175 /* Stores the string representation of the IPv6 address 'addr' into the
176  * character array 'addr_str', which must be at least INET6_ADDRSTRLEN
177  * bytes long. */
178 void
179 format_ipv6_addr(char *addr_str, const struct in6_addr *addr)
180 {
181     inet_ntop(AF_INET6, addr, addr_str, INET6_ADDRSTRLEN);
182 }
183
184 void
185 print_ipv6_addr(struct ds *string, const struct in6_addr *addr)
186 {
187     char *dst;
188
189     ds_reserve(string, string->length + INET6_ADDRSTRLEN);
190
191     dst = string->string + string->length;
192     format_ipv6_addr(dst, addr);
193     string->length += strlen(dst);
194 }
195
196 void
197 print_ipv6_masked(struct ds *s, const struct in6_addr *addr,
198                   const struct in6_addr *mask)
199 {
200     print_ipv6_addr(s, addr);
201     if (mask && !ipv6_mask_is_exact(mask)) {
202         if (ipv6_is_cidr(mask)) {
203             int cidr_bits = ipv6_count_cidr_bits(mask);
204             ds_put_format(s, "/%d", cidr_bits);
205         } else {
206             ds_put_char(s, '/');
207             print_ipv6_addr(s, mask);
208         }
209     }
210 }
211
212 struct in6_addr ipv6_addr_bitand(const struct in6_addr *a,
213                                  const struct in6_addr *b)
214 {
215     int i;
216     struct in6_addr dst;
217
218 #ifdef s6_addr32
219     for (i=0; i<4; i++) {
220         dst.s6_addr32[i] = a->s6_addr32[i] & b->s6_addr32[i];
221     }
222 #else
223     for (i=0; i<16; i++) {
224         dst.s6_addr[i] = a->s6_addr[i] & b->s6_addr[i];
225     }
226 #endif
227
228     return dst;
229 }
230
231 /* Returns an in6_addr consisting of 'mask' high-order 1-bits and 128-N
232  * low-order 0-bits. */
233 struct in6_addr
234 ipv6_create_mask(int mask)
235 {
236     struct in6_addr netmask;
237     uint8_t *netmaskp = &netmask.s6_addr[0];
238
239     memset(&netmask, 0, sizeof netmask);
240     while (mask > 8) {
241         *netmaskp = 0xff;
242         netmaskp++;
243         mask -= 8;
244     }
245
246     if (mask) {
247         *netmaskp = 0xff << (8 - mask);
248     }
249
250     return netmask;
251 }
252
253 /* Given the IPv6 netmask 'netmask', returns the number of bits of the IPv6
254  * address that it specifies, that is, the number of 1-bits in 'netmask'.
255  * 'netmask' must be a CIDR netmask (see ipv6_is_cidr()). */
256 int
257 ipv6_count_cidr_bits(const struct in6_addr *netmask)
258 {
259     int i;
260     int count = 0;
261     const uint8_t *netmaskp = &netmask->s6_addr[0];
262
263     assert(ipv6_is_cidr(netmask));
264
265     for (i=0; i<16; i++) {
266         if (netmaskp[i] == 0xff) {
267             count += 8;
268         } else {
269             uint8_t nm;
270
271             for(nm = netmaskp[i]; nm; nm <<= 1) {
272                 count++;
273             }
274             break;
275         }
276
277     }
278
279     return count;
280 }
281
282 /* Returns true if 'netmask' is a CIDR netmask, that is, if it consists of N
283  * high-order 1-bits and 128-N low-order 0-bits. */
284 bool
285 ipv6_is_cidr(const struct in6_addr *netmask)
286 {
287     const uint8_t *netmaskp = &netmask->s6_addr[0];
288     int i;
289
290     for (i=0; i<16; i++) {
291         if (netmaskp[i] != 0xff) {
292             uint8_t x = ~netmaskp[i];
293             if (x & (x + 1)) {
294                 return false;
295             }
296             while (++i < 16) {
297                 if (netmaskp[i]) {
298                     return false;
299                 }
300             }
301         }
302     }
303
304     return true;
305 }
306
307 /* Populates 'b' with an Ethernet II packet headed with the given 'eth_dst',
308  * 'eth_src' and 'eth_type' parameters.  A payload of 'size' bytes is allocated
309  * in 'b' and returned.  This payload may be populated with appropriate
310  * information by the caller.  Sets 'b''s 'l2' and 'l3' pointers to the
311  * Ethernet header and payload respectively.
312  *
313  * The returned packet has enough headroom to insert an 802.1Q VLAN header if
314  * desired. */
315 void *
316 eth_compose(struct ofpbuf *b, const uint8_t eth_dst[ETH_ADDR_LEN],
317             const uint8_t eth_src[ETH_ADDR_LEN], uint16_t eth_type,
318             size_t size)
319 {
320     void *data;
321     struct eth_header *eth;
322
323     ofpbuf_clear(b);
324
325     ofpbuf_prealloc_tailroom(b, ETH_HEADER_LEN + VLAN_HEADER_LEN + size);
326     ofpbuf_reserve(b, VLAN_HEADER_LEN);
327     eth = ofpbuf_put_uninit(b, ETH_HEADER_LEN);
328     data = ofpbuf_put_uninit(b, size);
329
330     memcpy(eth->eth_dst, eth_dst, ETH_ADDR_LEN);
331     memcpy(eth->eth_src, eth_src, ETH_ADDR_LEN);
332     eth->eth_type = htons(eth_type);
333
334     b->l2 = eth;
335     b->l3 = data;
336
337     return data;
338 }
339
340 /* Populates 'b' with an Ethernet LLC+SNAP packet headed with the given
341  * 'eth_dst', 'eth_src', 'snap_org', and 'snap_type'.  A payload of 'size'
342  * bytes is allocated in 'b' and returned.  This payload may be populated with
343  * appropriate information by the caller.
344  *
345  * The returned packet has enough headroom to insert an 802.1Q VLAN header if
346  * desired. */
347 void *
348 snap_compose(struct ofpbuf *b, const uint8_t eth_dst[ETH_ADDR_LEN],
349              const uint8_t eth_src[ETH_ADDR_LEN],
350              unsigned int oui, uint16_t snap_type, size_t size)
351 {
352     struct eth_header *eth;
353     struct llc_snap_header *llc_snap;
354     void *payload;
355
356     /* Compose basic packet structure.  (We need the payload size to stick into
357      * the 802.2 header.) */
358     ofpbuf_clear(b);
359     ofpbuf_prealloc_tailroom(b, ETH_HEADER_LEN + VLAN_HEADER_LEN
360                              + LLC_SNAP_HEADER_LEN + size);
361     ofpbuf_reserve(b, VLAN_HEADER_LEN);
362     eth = ofpbuf_put_zeros(b, ETH_HEADER_LEN);
363     llc_snap = ofpbuf_put_zeros(b, LLC_SNAP_HEADER_LEN);
364     payload = ofpbuf_put_uninit(b, size);
365
366     /* Compose 802.2 header. */
367     memcpy(eth->eth_dst, eth_dst, ETH_ADDR_LEN);
368     memcpy(eth->eth_src, eth_src, ETH_ADDR_LEN);
369     eth->eth_type = htons(b->size - ETH_HEADER_LEN);
370
371     /* Compose LLC, SNAP headers. */
372     llc_snap->llc.llc_dsap = LLC_DSAP_SNAP;
373     llc_snap->llc.llc_ssap = LLC_SSAP_SNAP;
374     llc_snap->llc.llc_cntl = LLC_CNTL_SNAP;
375     llc_snap->snap.snap_org[0] = oui >> 16;
376     llc_snap->snap.snap_org[1] = oui >> 8;
377     llc_snap->snap.snap_org[2] = oui;
378     llc_snap->snap.snap_type = htons(snap_type);
379
380     return payload;
381 }
382
383 static void
384 packet_set_ipv4_addr(struct ofpbuf *packet, ovs_be32 *addr, ovs_be32 new_addr)
385 {
386     struct ip_header *nh = packet->l3;
387
388     if (nh->ip_proto == IPPROTO_TCP && packet->l7) {
389         struct tcp_header *th = packet->l4;
390
391         th->tcp_csum = recalc_csum32(th->tcp_csum, *addr, new_addr);
392     } else if (nh->ip_proto == IPPROTO_UDP && packet->l7) {
393         struct udp_header *uh = packet->l4;
394
395         if (uh->udp_csum) {
396             uh->udp_csum = recalc_csum32(uh->udp_csum, *addr, new_addr);
397             if (!uh->udp_csum) {
398                 uh->udp_csum = htons(0xffff);
399             }
400         }
401     }
402     nh->ip_csum = recalc_csum32(nh->ip_csum, *addr, new_addr);
403     *addr = new_addr;
404 }
405
406 /* Modifies the IPv4 header fields of 'packet' to be consistent with 'src',
407  * 'dst', 'tos', and 'ttl'.  Updates 'packet''s L4 checksums as appropriate.
408  * 'packet' must contain a valid IPv4 packet with correctly populated l[347]
409  * markers. */
410 void
411 packet_set_ipv4(struct ofpbuf *packet, ovs_be32 src, ovs_be32 dst,
412                 uint8_t tos, uint8_t ttl)
413 {
414     struct ip_header *nh = packet->l3;
415
416     if (nh->ip_src != src) {
417         packet_set_ipv4_addr(packet, &nh->ip_src, src);
418     }
419
420     if (nh->ip_dst != dst) {
421         packet_set_ipv4_addr(packet, &nh->ip_dst, dst);
422     }
423
424     if (nh->ip_tos != tos) {
425         uint8_t *field = &nh->ip_tos;
426
427         nh->ip_csum = recalc_csum16(nh->ip_csum, htons((uint16_t) *field),
428                                     htons((uint16_t) tos));
429         *field = tos;
430     }
431
432     if (nh->ip_ttl != ttl) {
433         uint8_t *field = &nh->ip_ttl;
434
435         nh->ip_csum = recalc_csum16(nh->ip_csum, htons(*field << 8),
436                                     htons(ttl << 8));
437         *field = ttl;
438     }
439 }
440
441 static void
442 packet_set_port(ovs_be16 *port, ovs_be16 new_port, ovs_be16 *csum)
443 {
444     if (*port != new_port) {
445         *csum = recalc_csum16(*csum, *port, new_port);
446         *port = new_port;
447     }
448 }
449
450 /* Sets the TCP source and destination port ('src' and 'dst' respectively) of
451  * the TCP header contained in 'packet'.  'packet' must be a valid TCP packet
452  * with its l4 marker properly populated. */
453 void
454 packet_set_tcp_port(struct ofpbuf *packet, ovs_be16 src, ovs_be16 dst)
455 {
456     struct tcp_header *th = packet->l4;
457
458     packet_set_port(&th->tcp_src, src, &th->tcp_csum);
459     packet_set_port(&th->tcp_dst, dst, &th->tcp_csum);
460 }
461
462 /* Sets the UDP source and destination port ('src' and 'dst' respectively) of
463  * the UDP header contained in 'packet'.  'packet' must be a valid UDP packet
464  * with its l4 marker properly populated. */
465 void
466 packet_set_udp_port(struct ofpbuf *packet, ovs_be16 src, ovs_be16 dst)
467 {
468     struct udp_header *uh = packet->l4;
469
470     if (uh->udp_csum) {
471         packet_set_port(&uh->udp_src, src, &uh->udp_csum);
472         packet_set_port(&uh->udp_dst, dst, &uh->udp_csum);
473
474         if (!uh->udp_csum) {
475             uh->udp_csum = htons(0xffff);
476         }
477     } else {
478         uh->udp_src = src;
479         uh->udp_dst = dst;
480     }
481 }
482
483 /* If 'packet' is a TCP packet, returns the TCP flags.  Otherwise, returns 0.
484  *
485  * 'flow' must be the flow corresponding to 'packet' and 'packet''s header
486  * pointers must be properly initialized (e.g. with flow_extract()). */
487 uint8_t
488 packet_get_tcp_flags(const struct ofpbuf *packet, const struct flow *flow)
489 {
490     if ((flow->dl_type == htons(ETH_TYPE_IP) ||
491          flow->dl_type == htons(ETH_TYPE_IPV6)) &&
492         flow->nw_proto == IPPROTO_TCP && packet->l7) {
493         const struct tcp_header *tcp = packet->l4;
494         return TCP_FLAGS(tcp->tcp_ctl);
495     } else {
496         return 0;
497     }
498 }
499
500 /* Appends a string representation of the TCP flags value 'tcp_flags'
501  * (e.g. obtained via packet_get_tcp_flags() or TCP_FLAGS) to 's', in the
502  * format used by tcpdump. */
503 void
504 packet_format_tcp_flags(struct ds *s, uint8_t tcp_flags)
505 {
506     if (!tcp_flags) {
507         ds_put_cstr(s, "none");
508         return;
509     }
510
511     if (tcp_flags & TCP_SYN) {
512         ds_put_char(s, 'S');
513     }
514     if (tcp_flags & TCP_FIN) {
515         ds_put_char(s, 'F');
516     }
517     if (tcp_flags & TCP_PSH) {
518         ds_put_char(s, 'P');
519     }
520     if (tcp_flags & TCP_RST) {
521         ds_put_char(s, 'R');
522     }
523     if (tcp_flags & TCP_URG) {
524         ds_put_char(s, 'U');
525     }
526     if (tcp_flags & TCP_ACK) {
527         ds_put_char(s, '.');
528     }
529     if (tcp_flags & 0x40) {
530         ds_put_cstr(s, "[40]");
531     }
532     if (tcp_flags & 0x80) {
533         ds_put_cstr(s, "[80]");
534     }
535 }